void SystemProperties::ReadCallback(const prop_info* pi,
                                    void (*callback)(void* cookie, const char* name,
                                                     const char* value, uint32_t serial),
                                    void* cookie) {
  // Read only properties don't need to copy the value to a temporary buffer, since it can never
  // change.
  if (is_read_only(pi->name)) {
    uint32_t serial = Serial(pi);
    if (pi->is_long()) {
      callback(cookie, pi->name, pi->long_value(), serial);
    } else {
      callback(cookie, pi->name, pi->value, serial);
    }
    return;
  }

  while (true) {
    uint32_t serial = Serial(pi);  // acquire semantics
    size_t len = SERIAL_VALUE_LEN(serial);
    char value_buf[len + 1];

    memcpy(value_buf, pi->value, len);
    value_buf[len] = '\0';

    // TODO: see todo in Read function
    atomic_thread_fence(memory_order_acquire);
    if (serial == load_const_atomic(&(pi->serial), memory_order_relaxed)) {
      callback(cookie, pi->name, value_buf, serial);
      return;
    }
  }
}
Beispiel #2
0
int main(void)
{
  for(int i=0;i<MY_N;i++)
  {
    scanf("%c", &eps[i]) ;
    eps[i] -= '0' ;
    if(eps[i]!=0 && eps[i]!=1) i-- ;
  }
  //for(int i=0;i<MY_N;i++) eps[i] = rand()%2 ;
  
  std::cout << Frequency(MY_N, eps) << std::endl ;
  std::cout << BlockFrequency(MY_N/100, MY_N, eps) << std::endl ;
  std::cout << Runs(MY_N, eps) << std::endl ;
  std::cout << LongestRunOfOnes(MY_N, eps) << std::endl ;
  //std::cout << Rank(MY_N, eps) << std::endl ;
  //std::cout << DiscreteFourierTransform(MY_N, eps) << std::endl ;
  //std::cout << NonOverlappingTemplateMatchings(10, MY_N, eps) << std::endl ;
  //std::cout << OverlappingTemplateMatchings(10, MY_N, eps) << std::endl ;
  std::cout << Universal(MY_N, eps) << std::endl ;
  std::cout << LinearComplexity(1000, MY_N, eps) << std::endl ;
  std::cout << Serial(5, MY_N, eps) << std::endl ;
  //std::cout << ApproximateEntropy(5, MY_N, eps) << std::endl ;
  std::cout << CumulativeSums(MY_N, eps) << std::endl ;
  //std::cout << RandomExcursions(MY_N, eps) << std::endl ;
  //std::cout << RandomExcursionsVariant(MY_N, eps) << std::endl ;

  return 0 ;
}
Beispiel #3
0
bool RNGTester::Test(unsigned char *eps, int n)
{
  double p_value = 1.0 ;

  std::cout << std::fixed << std::setprecision(6) ;

  p_value = std::min(p_value, Frequency(n, eps) ) ;
  p_value = std::min(p_value, BlockFrequency(n/100, n, eps) ) ;
  p_value = std::min(p_value, Runs(n, eps) ) ;
  p_value = std::min(p_value, LongestRunOfOnes(n, eps) ) ;
  //p_value = std::min(p_value, Rank(n, eps) ) ;
  //p_value = std::min(p_value, DiscreteFourierTransform(n, eps) ) ;
  //p_value = std::min(p_value, NonOverlappingTemplateMatchings(10, n, eps) ) ;
  //p_value = std::min(p_value, OverlappingTemplateMatchings(10, n, eps) ) ;
  p_value = std::min(p_value, Universal(n, eps) ) ;
  p_value = std::min(p_value, LinearComplexity(1000, n, eps) ) ;
  p_value = std::min(p_value, Serial(5, n, eps) ) ;
  //p_value = std::min(p_value, ApproximateEntropy(5, n, eps) ) ;
  p_value = std::min(p_value, CumulativeSums(n, eps) ) ;
  //p_value = std::min(p_value, RandomExcursions(n, eps) ) ;
  //p_value = std::min(p_value, RandomExcursionsVariant(n, eps) ) ;

  std::cout << "p_value = " << p_value << std::endl ;

  return (p_value>=0.01) ; 
}
Beispiel #4
0
ParNonlinearForm::ParNonlinearForm(ParFiniteElementSpace *pf)
   : NonlinearForm(pf), pGrad(Operator::Hypre_ParCSR)
{
   X.MakeRef(pf, NULL);
   Y.MakeRef(pf, NULL);
   MFEM_VERIFY(!Serial(), "internal MFEM error");
}
Beispiel #5
0
/**
 * Serial object constructor tests.
 */
void SerialTest::Constructor() {
	// create a Serial object
	CPPUNIT_ASSERT_NO_THROW(Serial("/dev/ttyS0"));

	// create a Serial object from a nonexistent file
	CPPUNIT_ASSERT_THROW(Serial("f00bar"), std::runtime_error);

	// create a Serial object from a file that is not a character device
	CPPUNIT_ASSERT_THROW(Serial("bogus_serial_dev"), std::runtime_error);

	/// @Todo Implement test to create a Serial object from a character device
	/// file that can't be opened (no permission for example).

	/// @Todo Implement test to create a Serial object that can't determine
	/// and save it's mode.
}
Beispiel #6
0
void
TraceManager::ClearTrace()
{
  append_serial = modify_serial = Serial();
  trace_dirty = true;
  trace.clear();
  n_points = 0;
  predicted = TracePoint::Invalid();
}
Beispiel #7
0
Serial::Serial() : Serial("/dev/ttyUSB0", 9600, false, false, 0, 0) {
#else
Serial::Serial() : Serial("\\\\.\\COM1", 9600, false, false, 0, 0) {
#endif

}

#ifndef _WIN32
Serial::Serial(const char *file, int baudRate, bool useParity, bool extraStopBit, unsigned char readMinChars, unsigned char readTimeout) : fd(0),
																																		   tty{0} {
	//Set up serial interface
		//http://linux.die.net/man/3/termios
	fd = open(file, O_RDWR | O_NOCTTY);
	if(fd < 0) {
		Log::logf(Log::ERR, "Serial connection initialization failed!\n");
		throw std::runtime_error("serial initialization failed");
	}

	//Input/output flags
	tty.c_iflag = 0;			//No input processing
	if(useParity) {
		tty.c_iflag |= INPCK;	//Enable input parity checking
	}
	tty.c_oflag = 0;			//No output processing
	//Control flags
	tty.c_cflag = CSIZE;		//Character size mask
	tty.c_cflag |= CS8;			//8 data bits
	if(useParity) {
		tty.c_cflag &= PARENB;	//Enable output parity generation and input parity checking
	} else {
		tty.c_cflag &= ~PARENB;	//Disable parity generation
	}
	if(extraStopBit) {
		tty.c_cflag &= CSTOPB;	//2 stop bits
	} else {
		tty.c_cflag &= ~CSTOPB;	//1 stop bit
	}
	tty.c_cflag |= CREAD;		//Enable read
	tty.c_cflag |= CLOCAL;		//Ignore control lines
	tty.c_cflag &= ~PARODD;		//Even parity, if used
	//Local flags
	tty.c_lflag = 0;			//No local processing: use non-canonical (raw) mode, disable echo, etc.
	//Control characters
	tty.c_cc[VMIN] = readMinChars;	//Block on read until specified number of characters have been read
	tty.c_cc[VTIME] = readTimeout;	//Time-based read, or timeout for blocking read

	//Set intial baud rate
	setBaudRate(baudRate, false);

	//Flush serial port and apply settings
	if(tcsetattr(fd, TCSAFLUSH, &tty) != 0) {
		Log::logf(Log::ERR, "Error applying serial port settings: %s\n", strerror(errno));
		throw std::runtime_error("serial initialization failed");
	}

	Log::logf(Log::INFO, "Serial connection initialized!\n");
}
Beispiel #8
0
const String CTestResource::Image() const
{
  String str;
  str.Format(_T("%10s %20s %8s"),(LPCTSTR)HostPort(),(LPCTSTR)Target(),(LPCTSTR)Serial());
  if(IsLocked()){
    str+=_T(" [RL]");
  }
  return str;
}
Beispiel #9
0
void LowPowerRestore(void) {

// Enable required GPIO clocks - Ports A, B and C
RCC->AHBENR |= (RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN | RCC_AHBENR_GPIOCEN);
Serial(PB_10, PB_11,"pc"); // re-enable USB serial
pc.baud(115200);
pc.printf("..Wake!\r\n");
sensor.pinsOn(); // re-enable sensor pins
Radio.IoReInit(); // re-enable radio pins
Radio.Standby();
Radio.EnableRadioIRQs(); // Re-enable the radio IRQs

}
void
nist_test_suite()
{
	if ( (testVector[0] == 1) || (testVector[TEST_FREQUENCY] == 1) ) 
		Frequency(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_BLOCK_FREQUENCY] == 1) ) 
		BlockFrequency(tp.blockFrequencyBlockLength, tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_CUSUM] == 1) )
		CumulativeSums(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_RUNS] == 1) )
		Runs(tp.n); 
	
	if ( (testVector[0] == 1) || (testVector[TEST_LONGEST_RUN] == 1) )
		LongestRunOfOnes(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_RANK] == 1) )
		Rank(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_FFT] == 1) )
		DiscreteFourierTransform(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_NONPERIODIC] == 1) )
		NonOverlappingTemplateMatchings(tp.nonOverlappingTemplateBlockLength, tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_OVERLAPPING] == 1) )
		OverlappingTemplateMatchings(tp.overlappingTemplateBlockLength, tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_UNIVERSAL] == 1) )
		Universal(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_APEN] == 1) )
		ApproximateEntropy(tp.approximateEntropyBlockLength, tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_RND_EXCURSION] == 1) )
		RandomExcursions(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_RND_EXCURSION_VAR] == 1) )
		RandomExcursionsVariant(tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_SERIAL] == 1) )
		Serial(tp.serialBlockLength,tp.n);
	
	if ( (testVector[0] == 1) || (testVector[TEST_LINEARCOMPLEXITY] == 1) )
		LinearComplexity(tp.linearComplexitySequenceLength, tp.n);

	if ( (testVector[0] == 1) || (testVector[TEST_FFT80] == 1) )
		DiscreteFourierTransform80(tp.n);
}
Beispiel #11
0
int SerialData::Serial(CMonitorList &MonitorList,Groups *pGroups,Subsequent *pSubsequent,TASKMAP &TaskMap,bool out)
{
	if(m_filename.empty())
		return -1;

	FILE *pf=NULL;
	if(out)
		pf=fopen(m_filename.c_str(),"w");
	else
		pf=fopen(m_filename.c_str(),"r");

	if(pf==NULL)
		return -2;

	int nret=Serial(pf,MonitorList,pGroups,pSubsequent,TaskMap,out);

	fclose(pf);

	return nret;
}
int SystemProperties::Read(const prop_info* pi, char* name, char* value) {
  while (true) {
    uint32_t serial = Serial(pi);  // acquire semantics
    size_t len = SERIAL_VALUE_LEN(serial);
    memcpy(value, pi->value, len + 1);
    // TODO: Fix the synchronization scheme here.
    // There is no fully supported way to implement this kind
    // of synchronization in C++11, since the memcpy races with
    // updates to pi, and the data being accessed is not atomic.
    // The following fence is unintuitive, but would be the
    // correct one if memcpy used memory_order_relaxed atomic accesses.
    // In practice it seems unlikely that the generated code would
    // would be any different, so this should be OK.
    atomic_thread_fence(memory_order_acquire);
    if (serial == load_const_atomic(&(pi->serial), memory_order_relaxed)) {
      if (name != nullptr) {
        size_t namelen = strlcpy(name, pi->name, PROP_NAME_MAX);
        if (namelen >= PROP_NAME_MAX) {
          async_safe_format_log(ANDROID_LOG_ERROR, "libc",
                                "The property name length for \"%s\" is >= %d;"
                                " please use __system_property_read_callback"
                                " to read this property. (the name is truncated to \"%s\")",
                                pi->name, PROP_NAME_MAX - 1, name);
        }
      }
      if (is_read_only(pi->name) && pi->is_long()) {
        async_safe_format_log(
            ANDROID_LOG_ERROR, "libc",
            "The property \"%s\" has a value with length %zu that is too large for"
            " __system_property_get()/__system_property_read(); use"
            " __system_property_read_callback() instead.",
            pi->name, strlen(pi->long_value()));
      }
      return len;
    }
  }
}
Beispiel #13
0
int uart_init(uart32_t baudrate)
{
  Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X);
  begin(baudrate);
}
Beispiel #14
0
/**
 * Main is used to:
 * Initialize drivers
 * Create threads
 * Pass drivers structures to threads
 */
int main( void ) {
    /*
     * Enable internal 32 MHz ring oscillator and wait until it's
     * stable. Set the 32 MHz ring oscillator as the main clock source.
     */
    CLKSYS_Enable( OSC_RC32MEN_bm );
    CLKSYS_Prescalers_Config( CLK_PSADIV_1_gc, CLK_PSBCDIV_1_1_gc );
    do {} while ( CLKSYS_IsReady( OSC_RC32MRDY_bm ) == 0 );
    CLKSYS_Main_ClockSource_Select( CLK_SCLKSEL_RC32M_gc );

    //Enable watchdog timer, which will be reset by timer
    WDT_EnableAndSetTimeout( WDT_PER_1KCLK_gc );
    /*
     * Do all configuration and create all tasks and queues before scheduler is started.
     * It is possible to put initialization of peripherals like displays into task functions
     * (which will be executed after scheduler has started) if fast startup is needed.
     * Interrupts are not enabled until the call of vTaskStartScheduler();
     */
    // Enable the Round-Robin Scheduling scheme.Round-Robin scheme ensures that no low-level
    // interrupts are “starved”, as the priority changes continuously
    PMIC_EnableRoundRobin();

    //Create and start the timer, which will reset Watch Dog Timer
    xTimerStart(xTimerCreate((signed char*)"WDT",500, pdTRUE, 0, watchdogTimerCallback), 0);
    //---------Use USART on PORTC----------------------------
    Serial usartFTDI = Serial(&USARTE0, BAUD9600, 128, 10);

    // Initialize SPI slave on port D
    SpiSlave spiSlave = SpiSlave(&SPIC,false,SPI_MODE_1_gc,64);
    // Initialize SPI master on port C
    SpiMaster spiMaster = SpiMaster(&SPID, false, SPI_MODE_1_gc, false, SPI_PRESCALER_DIV4_gc);
    SpiDevice spiDevice = SpiDevice(&spiMaster, &PORTD, SPI_SS_bm);

    //---------Start LED task for testing purposes-----------
    ledRGB = LedGroup(3);
    ledRGB.add(&PORTF, 0x04,1 );//R
    ledRGB.add(&PORTF, 0x08,1 );//G
    ledRGB.add(&PORTF, 0x02,1 );//B
    ledRGB.set(BLUE);
    LedProcessorThread ledRGBEThread = LedProcessorThread(&ledRGB, GREEN, 500, "RGB", 64, configLOW_PRIORITY);

    LedGroup ledString = LedGroup(7);
    ledString.add(&PORTA, 0x02, 0);
    ledString.add(&PORTA, 0x04, 0);
    ledString.add(&PORTA, 0x08, 0);
    ledString.add(&PORTA, 0x10, 0);
    ledString.add(&PORTA, 0x20, 0);
    ledString.add(&PORTA, 0x40, 0);
    ledString.add(&PORTA, 0x80, 0);
    LedProcessorThread ledStringThread = LedProcessorThread(&ledString, "STR", 64, configLOW_PRIORITY);

    // ***** Start main Looper
    Looper looper = Looper(10, "LPR", 750, configNORMAL_PRIORITY);
    //XXX why it is not working if on the heap not on the stack?
    //ExampleHandler *exampleHandler = (ExampleHandler*) pvPortMalloc(sizeof(ExampleHandler));
    //*exampleHandler = ExampleHandler(looper, spiDevice, ledStringQueue, usartFTDI);
    ExampleHandler exampleHandler = ExampleHandler(&looper, &spiDevice, &ledStringThread, &usartFTDI);
    // ****** Register commands for the interpreter
    CommandInterpreter interpreter = CommandInterpreter();
    interpreter.registerCommand(Strings_SpiExampleCmd, Strings_SpiExampleCmdDesc, &exampleHandler, EVENT_RUN_SPI_TEST);
    interpreter.registerCommand(Strings_BlinkCmd, Strings_BlinkCmdDesc, &exampleHandler, EVENT_BLINK);
    CommandInterpreterThread cmdIntThreadFTDI = CommandInterpreterThread(&interpreter, 32, &usartFTDI, "I12", 128, configNORMAL_PRIORITY);

    PinChangeController pinChangeController = PinChangeController();
    pinChangeController.registerOnPinChangeListener(&exampleHandler, &PORTD, PIN2_bm, PORT_OPC_TOTEM_gc, PORT_ISC_RISING_gc);

    // ****** Start stand-alone tasks
    SpiSlaveThread spiSlaveThread = SpiSlaveThread(&spiSlave, &usartFTDI, "SLV", 128, configLOW_PRIORITY);

    /* Start scheduler. Creates idle task and returns if failed to create it.
     * vTaskStartScheduler never returns during normal operation. It is unlikely that XMEGA port will need to
     * dynamically create tasks or queues. To ensure stable work, create ALL tasks and ALL queues before
     * vTaskStartScheduler call.
     * Interrupts would be enabled by calling PMIC_EnableLowLevel();*/
    vTaskStartScheduler();

    /* Should never get here, stop execution and report error */
    while(true) ledRGB.set(PINK);
    return 0;
}
Beispiel #15
0
int main(int argc, char *argv[])
{
    int DEBUG_LEVEL = 0;
    if(argc >= 2)
    {
        DEBUG_LEVEL = atoi(argv[1]);
    }

    CLog * Log= new CLog; //inits the log
    CERGO_SERIAL Serial(DEBUG_LEVEL) ; // inits the Serial class
    CERGO_GPS GPS(DEBUG_LEVEL) ; // inits the GPS CLASS
    CERGO_INTERNET * Internet = new CERGO_INTERNET(DEBUG_LEVEL); // inits the INTERNET class

    std::deque <uint8_t> test_list;
    int counter = 0;
    int data_int = 0;
    bool internet_light_set = false;

    //Adds restarted message to log
    Log ->add("\n############################################################ \n\n \t\t ERGO-PIXLE RESTARTED \n\n############################################################ \n ");

    Serial.setval_gpio(1,24);
    Serial.serial_setup(1337);
    std::deque <uint8_t> data_list; // list to store serial data
    std::stringstream test_string;
    std::thread ([&] { Internet->manage_list(); }).detach();

    while(true) // main management loop
    {
        usleep(200);
        counter = Serial.data_read(data_list); // checks for incomming data
        while(!data_list.empty())
        {
            if(DEBUG_LEVEL >= 2)
            {
                test_list = data_list;
            }
            data_int =GPS.Read_data(data_list);
             if(data_int == 5)
            {
                if(DEBUG_LEVEL >=2)
                {
                    printf("fix data\n");
                }
            }
            if(data_int == 4)
            {
                if(DEBUG_LEVEL >=2)
                {
                    printf("POS DATA\n");
                }
            }
            else if( data_int == 3)//sends the serial data to be parsed
            {
                Serial.setval_gpio(1,18);
                GPS.packatize();
                Internet->set_check_archive(true);
                Serial.setval_gpio(0,18);
                if(DEBUG_LEVEL >=3)
                {
                    printf("Good data!");
                    while(!test_list.empty())
                    {
                        printf("0x%X ",test_list.front());
                        test_list.pop_front();
                    }
                    printf("\n\n");
                }
            }
            else if(data_int == 2)
            {
                if(DEBUG_LEVEL >=3)
                {
                    printf("Not enough data!");
                    while(!test_list.empty())
                    {
                        printf("0x%X ",test_list.front());
                        test_list.pop_front();
                    }
                    printf("\n\n");
                }
                break;
            }
            else if (data_int == 0)
            {
                if(DEBUG_LEVEL >=3)
                {
                    printf("Bad checksum!");
                    while(!test_list.empty())
                    {
                        printf("0x%X ",test_list.front());
                        test_list.pop_front();
                    }
                    printf("\n\n");
                }
            }
        }

        if(Internet->get_internet_availiable() )
        {
            if(!internet_light_set)
            {
                internet_light_set =true;
                Serial.setval_gpio(1,23);
            }
        }
        else
        {
            if(internet_light_set)
            {
                internet_light_set= false;
                Serial.setval_gpio(0,23);
            }
        }

    }
}
Beispiel #16
0
CResetAttributes::ResetResult CTestResource::Reset(LogFunc *pfnLog, void *pfnLogparam)
{
  String strReset;
  strReset.Format(_T("port(%s,%d) %s"),Serial(),Baud(),ResetString());
  return CResetAttributes(strReset).Reset(pfnLog,pfnLogparam);
}
Beispiel #17
0
int main(){

    Mecanismo P = Mecanismo(2);

    cube I1__; I1__.zeros(3,3,2);
    I1__.slice(0) << 0 << 0                       << 0          << endr
                  << 0 << 107.307e-6 + 146.869e-6 << 0          << endr
                  << 0 << 0                       << 107.307e-6 + 146.869e-6 << endr;

    I1__.slice(1) << 0 << 0        << 0        << endr
                  << 0 << 438.0e-6 << 0        << endr
                  << 0 << 0        << 438.0e-6 << endr;

    cube I2__; I2__.zeros(3,3,2);
    I2__.slice(0) << 0 << 0                        << 0          << endr
                  << 0 << 107.307e-6 + 188.738e-6  << 0          << endr
                  << 0 << 0                        << 107.307e-6 + 188.738e-6  << endr;

    I2__.slice(1) << 0 << 0          << 0          << endr
                  << 0 << 301.679e-6 << 0          << endr
                  << 0 << 0          << 301.679e-6 << endr;

    Serial RR1 = Serial(2, {0.12, 0.16}, {0.06, 0.078},{0.062, 0.124}, I1__ , {0, 0, 9.8}, &fDH_RR);
    Serial RR2 = Serial(2, {0.12, 0.16}, {0.06, 0.058},{0.062, 0.097}, I2__ , {0, 0, 9.8}, &fDH_RR);
    Serial **RR_ = new Serial* [2];
    RR_[0] = &RR1;
    RR_[1] = &RR2;

    //Matrizes que descrevem a arquitetura do mecanismo
    double l0 = 0.05;
    mat D_ = join_vert((mat)eye(2,2),2);
    mat E_ = join_diag( Roty(0)(span(0,1),span(0,2)), Roty(PI)(span(0,1),span(0,2)) );
    mat F_ = zeros(4,4);
    vec f_ = {l0,0,-l0,0};

    Parallel Robot = Parallel(2, &P, RR_, 2, {2,4}, D_, E_, F_, f_);
    Reference RefObj = Reference(0.12, {0.08, 0.16}, {-0.08, 0.4});

    //Plotar área de trabalho
    uint nx = 96.0;
    uint ny = 56.0;
    double lx = 0.24;
    double ly = 0.28;
    double xi = -lx;
    double xf = lx;
    double yi = 0.0;
    double yf = ly;
    double dx = (xf-xi)/(nx-1);
    double dy = (yf-yi)/(ny-1);
    double dl = 0.5*(dx+dy);
    
    Mat<int> M; M.zeros(nx,ny);
    field<mat> fZ_(nx,ny);
    field<mat> fMh_(nx,ny);
    field<vec> fgh_(nx,ny);
    field<vec> fa1_(nx,ny);
    field<vec> fa2_(nx,ny);
    field<vec> fa12_(nx,ny);
    for(uint i=0; i<nx; i++){
        for(uint j=0; j<ny; j++){
            fZ_(i,j).zeros(2,2);
            fMh_(i,j).zeros(2,2);
            fgh_(i,j).zeros(2);
            fa1_(i,j).zeros(2);
            fa2_(i,j).zeros(2);
            fa12_(i,j).zeros(2);
        }
    }
    vec v1_ = {1,0};
    vec v2_ = {0,1};
    vec v12_ = {1,1};
    double r = 0.07;
    double x0 = 0.0;
    double y0 = 0.17;

    uint rows = nx;
    uint cols = ny;

    vec q0_ = {0.823167, 1.81774, 0.823167, 1.81774};

    GNR2 gnr2 = GNR2("RK6", &Robot, 1e-6, 30);
    //gnr2.Doit(q0_, {0.05,0.08});
    //cout << gnr2.convergiu << endl;
    //cout << gnr2.x_ << endl;
    //cout << gnr2.res_ << endl;
    //cout << gnr2.n << endl;

    double x;
    double y;
    mat A2_;
    for(uint i=0; i<rows; i++){
        for(uint j=0; j<cols; j++){
            x = xi + i*dx;
            y = yi + j*dy;
            gnr2.Doit(q0_, {x, y});
            if(gnr2.convergiu){
                q0_ = gnr2.x_;
                A2_ = join_horiz(Robot.Ah_, join_horiz(Robot.Ao_.col(1), Robot.Ao_.col(3)) );
                if(abs(det(Robot.Ao_)) < 1.6*1e-6 || abs(det(A2_)) < 1e-11 ) M(i,j) = 2;
                else{ 
                	M(i,j) = 1;
                	Robot.Doit(Robot.q0_, join_vert(v1_, -solve(Robot.Ao_, Robot.Ah_*v1_)) );
                	fZ_(i,j) = Robot.Z_;
                    fMh_(i,j) = Robot.dy->Mh_;
                    fgh_(i,j) = Robot.dy->gh_;
                    fa1_(i,j) = Robot.dy->vh_;
                    Robot.Doit(Robot.q0_, Robot.C_*v2_);
                    fa2_(i,j) = Robot.dy->vh_;
                    Robot.Doit(Robot.q0_, Robot.C_*v12_);
                    fa12_(i,j) = Robot.dy->vh_ - fa1_(i,j) - fa2_(i,j);
                }
            }
            gnr2.convergiu = false;
            if( ((x - x0)*(x - x0) + (y - y0)*(y - y0) <= (r+dl)*(r+dl) ) && ((x - x0)*(x - x0) + (y - y0)*(y - y0) >= (r-dl)*(r-dl) ) && (M(i,j) != 2) )
                M(i,j) = 3;
        }
    }

    for(uint i=0; i<rows; i++){
        for(uint j=0; j<cols; j++){
            cout << M(i,j) << ";" ;
            if(j==cols-1) cout << endl;
        }
    }


    fZ_.save("fZ_field");
    fMh_.save("fMh_field");
    fgh_.save("fgh_field");
    fa1_.save("fa1_field");
    fa2_.save("fa2_field");
    fa12_.save("fa12_field");


    return 0;
}
Beispiel #18
0
int main( int argc, char *argv[] )
{
	FILE *output, *input;	// File pointers for the data that will be read in and written out.
	double programRunTime; 	// The amount of time a this program took to complete execution.
	int processCount;		// The total number of processes we have including PI_Main.
	int workerCount;		// The max number of workers this program run can utilize.

	// Setup our program, calculate how many workers we have.
	processCount = PI_Configure( &argc, &argv );
	workerCount = processCount - 1;

	PI_StartTime();

	if(argc != 2){ // If after setting up our program, we don't have a string for a file argument, abort this run.
		return ExitFailure(", Error: No input file specified.", __FILE__, __LINE__);
	}

	// Create the workers based off worker count, and the channels/bundles between the workers and PI_Main.
	SetupWorkers(workerCount);

	//**********//
	PI_StartAll();
	//**********//

	// File opening
	output = fopen("pal.out", "a");
	input = fopen(argv[1], "r");

	// File error checking.
	if(output==NULL){
		return ExitFailure("Could not open output file 'pal.out' for appending in current directory.", __FILE__, __LINE__);
	}
	if(input==NULL){
		return ExitFailure("Could not open input file for reading, from path in argv[1].", __FILE__, __LINE__);
	}
	else{
		printf(">> Input file is: '%s'\n", argv[1]);
	}


	// Run serial or parallel algorithm.
	if(workerCount == 0){
		Serial(input, output);
	}
	else{
		Parallel(input, output, workerCount);
	}

	// Clean up our program run.
	fclose(output);
	fclose(input);

	free(toWorker);
	free(Worker);
	free(result);

	printf(">> Exiting... <<\n");

	programRunTime = PI_EndTime();
	printf("\n\n>>< PROGRAM EXECUTION TIME: (%.2f)s ><<\n\n\n", programRunTime);
	PI_StopMain(0);
	return EXIT_SUCCESS;
}