Beispiel #1
0
//<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
//<> INPUTS:
//<> 
//<> tide_current_table - pointer to the tides and current table in the At5 that the feature was read from
//<> 
//<> OUTPUTS:
//<> 
//<> tc_header - structure referencing the positions and element size of each major section of the Tides and
//<>    Currents table
//<> return - returns whether file read was performed successfully
//<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
bool TidalCurrentPredictor::getTablePositions(const At5::tTidesCurrentsData& tides_currents, const At5::tUShort majorVersion, TideCurrentFileHeader& tc_header)
{
    try
    {
        tc_header.tide_prediction_num_items = tides_currents.secondaryTideData.size();
        assert(tc_header.tide_prediction_num_items >= 0);
        tc_header.tide_primary_station_num_items = tides_currents.primaryTideData.size();
        assert(tc_header.tide_primary_station_num_items >= 0);
        tc_header.current_prediction_num_items = tides_currents.secondaryCurrentData.size();
        assert(tc_header.current_prediction_num_items >= 0);
        tc_header.current_primary_station_num_items = tides_currents.primaryCurrentData.size();
        assert(tc_header.current_primary_station_num_items >= 0);
        if(majorVersion >= 13)
        {
            tc_header.panel_stream_num_items = tides_currents.panelStreamData.size();
        }
    }
    catch(char *str)
    {
        ErrorPrintf(str);
        ErrorPrintf("Tides and Current Prediction Error :: TC Table could not be read");
        return true;
    }
    return false;
}
Beispiel #2
0
/*------------------------------------------------------------------------
       Parameters:

      Description:

    Return Values:
            0 on success, < 0 otherwise.

------------------------------------------------------------------------*/
int
WinCreate(char *pcName, int button_rows, int image_rows, int image_cols,
          int rows, int cols)
{
  int    iWin ;
  DIAG_WINDOW *pwin ;

  iWin = winNewHandle() ;
  if (iWin < 0)
    return(ErrorPrintf(ERROR_NO_MEMORY,
                       "WinAlloc: could not allocate new window"));

  pwin = HandleToPtr(iWin) ;
  pwin->xvf = XValloc(rows, cols, button_rows, image_rows, image_cols,
                      pcName, winPoll) ;
  XVsetParms(event_handler) ;

  if (!inited)
  {
    ThreadInit(0, MAX_WINDOWS, 10*1024, 1) ;
    inited = 1 ;
  }

  ThreadStart("window", winThread, pwin, MIN_PRIORITY) ;

  ThreadSuspend(TID_SELF, SIG_ANY) ;
  WinFlush(iWin) ;
  return(iWin) ;
}
Beispiel #3
0
double
randomNumber(double low, double hi)
{
  double val, range ;

  if (low > hi)
  {
    val = low ;
    low = hi ;
    hi = val ;
  }

  if (idum == 0L)     /* change seed from run to run */
    idum = -1L * (long)(abs((int)time(NULL))) ;

  range = hi - low ;
  val = OpenRan1(&idum) * range + low ;
  //printf("randomcall %3ld %12.10lf\n",nrgcalls,val);
  nrgcalls++;
  if ((val < low) || (val > hi))
    ErrorPrintf(ERROR_BADPARM, "randomNumber(%2.1f, %2.1f) - %2.1f\n",
                (float)low, (float)hi, (float)val) ;

  return(val) ;
}
/*******************************************************************************
* Name:			Read3DS ()
*******************************************************************************/
int MASTER_SCALE::Read3DS (int iNrOfBytes, byte* bp3DSData)
{
	// Print status
	VerbosePrintf ("Begin reading MASTER_SCALE chunk");

	// Check chunk length
	if (iNrOfBytes < 4)
	{
		// Set error chunk size invalid
		ErrorPrintf ("Chunk size invalid");

		// Return error
		return (-1);
	}

	// Get version from buffer
	MASTER_SCALE::fScale = GetFloat (bp3DSData);
	
	// Print status
	VerbosePrintf ("Scale: %f", MASTER_SCALE::fScale);

	// Print status
	VerbosePrintf ("End reading MASTER_SCALE chunk");

	// Return no error
	return (0);
}
Beispiel #5
0
int LoaderLoad(TCHAR *filename)
{
	wchar_t buffer[BUFFERSIZE], command[BUFFERSIZE];
	FILE *file;
	_wfopen_s(&file, filename, L"r");
	int error = 0, i, ret, line = 0;
	while (fgetws(buffer, BUFFERSIZE, file) != NULL) {
		++line;
		if (buffer[0] == '#') continue;
		if (swscanf(buffer, L"%s", command) != 1) continue;
		ret = 0;
		for (i = 0; i < commandsEnd; ++i)
			if (wcscmp(Commands[i].commandName, command) == 0) {
				ret = Commands[i].commandFunc(buffer);
				break;
			}
		if (ret != 0 || i == commandsEnd) {
			ErrorPrintf(L"LoaderError: Cannot parse command \"%s\" at Line %d in \"%s\". ", command, line + 1, filename);
			error = 1;
		}
	}
	wcscpy(lastFile, filename);
	fclose(file);
	return error;
}
Beispiel #6
0
void tOJDeviceOtherData::OnDataSent()
{
    bool success = false;

    QNetworkReply* pReply = qobject_cast<QNetworkReply*>( sender() );

    if( pReply != 0 )
    {
        QVariant statusCode = pReply->attribute( QNetworkRequest::HttpStatusCodeAttribute );
        if ( statusCode.isValid() )
        {
            int status = statusCode.toInt();

            if ( status != 200 )
            {
                QString reason = pReply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
                ErrorPrintf( QString("%1(): %2 %3").arg(__FUNCTION__).arg(status).arg(reason).toLatin1() );
                QString content = pReply->readAll();
                ErrorPrintf( QString("%1(): %2").arg(__FUNCTION__).arg(content).toLatin1() );
            }
            else
            {
                QString content = pReply->readAll();

                tJson json;
                bool ok;
                QVariantMap result = json.Parse( content, ok ).toMap();
                if ( result["OJ_DeviceOtherDataResult"].isValid() == false )
                {
                    DbgPrintf( QString("  error_status = %1").arg(result["error_status"].toInt()) );
                    DbgPrintf( QString("  language = %1").arg(result["language"].toString()) );
                    DbgPrintf( QString("  error_message = %1").arg(result["error_message"].toString()) );            }
                else
                {
                    QVariantMap nested = result["OJ_DeviceOtherDataResult"].toMap();

                    success = true;
                }
            }
        }
        pReply->deleteLater();
    }

    emit Sent( success );
}
Beispiel #7
0
static void CommandLineKey(int id, WPARAM wParam, int keytype)
{
	TCHAR code = (TCHAR)wParam;
	int len = (int)wcslen(commandLine);
	if (keytype == KEYCHAR) {
		if (!commandLineFocus && code == L':') {
			CreateCaret(g_hWnd, (HBITMAP)NULL, 1, FONTSIZE_CMD);
			commandLineFocus = 1;
			commandLine[commandLinePos++] = L':';
			commandLine[commandLinePos] = L'\0';
			CommandLineSetpos();
			ShowCaret(g_hWnd);
		}
		else if (commandLineFocus) {
			if (code == L'\r' || code == VK_ESCAPE) {
				if(code == L'\r' && LoaderRun(commandLine + 1))
					ErrorPrintf(L"CommandLineError: Cannot parse the command");
				commandLine[0] = L'\0';
				commandLinePos = 0;
				commandLineFocus = 0;
				HideCaret(g_hWnd);
				DestroyCaret();
				memset(KeyboardIsDown, 0, sizeof(KeyboardIsDown));
			}
			if (code < L' ' || len == MAX_COMMANDLINEBUFFER) return;
			MoveMemory(commandLine + commandLinePos + 1, commandLine + commandLinePos, (len - commandLinePos + 1) * sizeof(TCHAR));
			commandLine[commandLinePos++] = code;
			CommandLineSetpos();
		}
	}
	else if (keytype == KEYDOWN && commandLineFocus) {
		switch (code)
		{
		case VK_LEFT:
			if (commandLinePos > 1) --commandLinePos;
			CommandLineSetpos();
			break;
		case VK_RIGHT:
			if (commandLinePos < len) ++commandLinePos;
			CommandLineSetpos();
			break;
		case VK_HOME:
			commandLinePos = 1;
			break;
		case VK_END:
			commandLinePos = len;
			break;
		case VK_BACK:
			if (commandLinePos > 1) {
				MoveMemory(commandLine + commandLinePos - 1, commandLine + commandLinePos, (len - commandLinePos + 1) * sizeof(TCHAR));
				commandLinePos--;
			}
			CommandLineSetpos();
			break;
		}
	}
}
Beispiel #8
0
/*------------------------------------------------------------------------
       Parameters:

      Description:

    Return Values:
            0 on success, < 0 otherwise.

------------------------------------------------------------------------*/
static DIAG_WINDOW *
HandleToPtr(int iWin)
{
  if ((iWin < 0) || (iWin >= MAX_WINDOWS))
  {
    ErrorPrintf(ERROR_NO_MEMORY, "HandleToPtr(%d): bad handle", iWin) ;
    return(NULL) ;
  }
  return(&window_table[iWin]) ;
}
Beispiel #9
0
int GroundAdd(double fromX, double fromY, double toX, double toY, int traits, int invisible)
{
	int i = 0;
	double lower;
	if (groundsEnd == MAX_GROUNDLEN) {
		ErrorPrintf(L"GroundError: Resource used up.");
		return -1;
	}
	grounds[groundsEnd].leftId = grounds[groundsEnd].rightId = -1;
	for (i = 0; i < groundsEnd; ++i) {
		if (grounds[i].fromX < toX && fromX < grounds[i].toX)
			return 1;
		else if (grounds[i].fromX == toX) {
			grounds[i].leftId = groundsEnd;
			grounds[groundsEnd].rightId = i;
		}
		else if (grounds[i].toX == fromX) {
			grounds[i].rightId = groundsEnd;
			grounds[groundsEnd].leftId = i;
		}
	}
	grounds[groundsEnd].fromX = fromX;
	grounds[groundsEnd].fromY = fromY;
	grounds[groundsEnd].toX = toX;
	grounds[groundsEnd].toY = toY;
	grounds[groundsEnd].traits = traits;
	grounds[groundsEnd].invisible = invisible;
	if (groundsMostId[0] == -1 || fromX < grounds[groundsMostId[0]].fromX)
		groundsMostId[0] = groundsEnd;
	if (groundsMostId[1] == -1 || toX > grounds[groundsMostId[1]].toX)
		groundsMostId[1] = groundsEnd;
	if (fromY > toY) lower = fromY;
	else lower = toY;
	if (groundsLowestID == -1 || grounds[groundsLowestID].fromY < lower && grounds[groundsLowestID].toY < lower)
		groundsLowestID = groundsEnd;
	grounds[groundsEnd].color = 0.0;
	grounds[groundsEnd].hasTimer = 0;
	if (!grounds[groundsEnd].invisible && gameState == STARTED) {
		grounds[groundsEnd].hasTimer = 1;
		TimerAdd(GroundVisibleTimer, groundsEnd, 20);
	}
	else if(!grounds[groundsEnd].invisible)
		grounds[groundsEnd].color = 1.0;
	grounds[groundsEnd].points.points[0][0] = fromX;	grounds[groundsEnd].points.points[0][1] = fromY + 0.5;
	grounds[groundsEnd].points.points[1][0] = fromX;	grounds[groundsEnd].points.points[1][1] = fromY;
	grounds[groundsEnd].points.points[2][0] = toX;		grounds[groundsEnd].points.points[2][1] = toY;
	grounds[groundsEnd].points.points[3][0] = toX;		grounds[groundsEnd].points.points[3][1] = toY + 0.5;
	grounds[groundsEnd].points.n = 4;
	grounds[groundsEnd].points.velocity[0] = 0.0;		grounds[groundsEnd].points.velocity[1] = 0.0;
	grounds[groundsEnd].points.usev = 1;
	DrawerAdd(GroundDrawer, groundsEnd, 6);
	CollisionAdd(GroundCollision, groundsEnd, ID_GROUND, &groundCollisionTypes, GroundCollisionNotifier);
	++groundsEnd;
	return groundsEnd;
}
Beispiel #10
0
int
check_finite(char *where, double what)
{
  if (!finite(what))
  {
    ErrorPrintf(ERROR_BADPARM, "%s not finite!\n",where) ;
    DiagBreak() ;
    return(0) ;
  }
  return(1) ;
}
Beispiel #11
0
//<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
//<> INPUTS:
//<> 
//<> tide_current_table - pointer to the tides and current table in the At5 that the feature was read from
//<> table_pos - absolute file location of the table to read from
//<> year_index - index of the year in the table (year - first year)
//<> 
//<> OUTPUTS:
//<> 
//<> year_record - structure containing the year, whether it's a leap year, and all the constants for the year
//<> return - returns whether file read was performed successfully
//<>
//<> POTENTIAL ERROR FIX:
//<>
//<> We can implement a method where it interpolates from the last or first known year...the amplitude value
//<> won't be exact but the phase shift can be estimated using a leap year/non-leap year offset
//<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
bool TidalCurrentPredictor::getYearData(const At5::tTidesCurrentsData& tides_currents, long /*table_pos*/, YearRecord& year_record)
{
    try
    {
        std::map<At5::eNodeFactorModifier, double> phaseTable;
        std::map<At5::eNodeFactorModifier, double> amplitudeTable;

        //read constants
        year_record.constants.resize(tides_currents.constTable.size());
        At5::GenerateNodeTables(QDateTime(QDate(year_record.year,1,1)), &phaseTable, &amplitudeTable);
        for(unsigned short x = 0; x < year_record.constants.size(); ++x)
        {
            year_record.constants[x].amplitude = tides_currents.constTable[x].GetConstAmplitude(amplitudeTable);
            year_record.constants[x].phase_shift = tides_currents.constTable[x].GetConstPhase(phaseTable, QDateTime(QDate(year_record.year,1,1)));
        }
    }
    catch(char *str)
    {
        ErrorPrintf(str);
        ErrorPrintf("Tidal Current Prediction Error :: Could not read year information.");
        return true;
    }
    return false;
}
Beispiel #12
0
/******************************************************************************
 *
 * Function   :  Dispatch_open
 *
 * Description:  Handle open() which allows applications to create a
 *               connection to the driver
 *
 ******************************************************************************/
int
Dispatch_open(
    struct inode *inode,
    struct file  *filp
    )
{
    U8             i;
    DEVICE_OBJECT *fdo;


    DebugPrintf_Cont(("\n"));
    DebugPrintf(("Received message ==> OPEN_DEVICE\n"));

    if (iminor(inode) == PLX_MNGMT_INTERFACE)
    {
        DebugPrintf(("Open Management interface...\n"));

        // Store the driver object in the private data
        filp->private_data = pGbl_DriverObject;
    }
    else
    {
        // Select desired device from device list
        i   = iminor(inode);
        fdo = pGbl_DriverObject->DeviceObject;

        while (i-- && fdo != NULL)
           fdo = fdo->NextDevice;

        if (fdo == NULL)
        {
            ErrorPrintf(("WARNING - Attempt to open non-existent device\n"));
            return (-ENODEV);
        }

        DebugPrintf((
            "Open device (%s)...\n",
            fdo->DeviceExtension->LinkName
            ));

        // Store device object for future calls
        filp->private_data = fdo;
    }

    DebugPrintf(("...device opened\n"));

    return 0;
}
Beispiel #13
0
static char *get_afni_string(FILE *fp, int count, char *name)
{

  char *buf;
  int i;
  char c;

  buf = (char *)malloc(count+1);

  c = fgetc(fp);

  if (c != '\'')
  {
    free(buf);
    errno = 0;
    ErrorReturn(NULL, (ERROR_BADPARM, "get_afni_string(): afni header string %s does not start with \"'\"", name));
  }

  for (i = 0;i < count;i++)
  {

    if (feof(fp))
    {
      free(buf);
      errno = 0;
      ErrorReturn(NULL, (ERROR_BADPARM, "get_afni_string(): end of file reached at %d of %d bytes of string %s", i+1, count, name));
    }

    c = fgetc(fp);

    if (i == count - 1 && c != '~')
    {
      errno = 0;
      ErrorPrintf(ERROR_BADPARM, "warning: string %s does not end with \"~\"", name);
    }

    buf[i] = (c == '~' ? '\0' : c);

  }

  buf[count] = '\0';

  for (c = fgetc(fp) ; c != '\n' && !feof(fp) ; c = fgetc(fp));

  return(buf);

} /* end get_afni_string() */
Beispiel #14
0
// ////////////////////
// Constructor
// ////////////////////
tRadarClientSettings::tRadarClientSettings(
        int instance,
        tRadarClientType clientType,
        tISettingsWriterFactory& factory,
        const tConfig& config)
    : m_xSettings()
    , m_Instance(instance)
    , m_ClientType(clientType)
    , m_RadarOrientationMode()
    , m_RadarPositionMode()
    , m_RadarPPIOffset()
    , m_RadarColorScheme()
    , m_RadarNightColorScheme()
    , m_TargetTrailsValue()
    , m_EchoAveragingValue()
    , m_RadarMotionMode()
    , m_RadarThresholdPercent()
    , m_RadarChartThresholdPercent()
    , m_TransparencyLevel()
    , m_RadarOverlayPalette()
    , m_PreferredRadar()
    , m_MultiRadar(config.multiRadar)
    , m_NightMode(config.nightMode)
    , m_Defaults(config.defaults)
{
    // set up the settingsWriter with the correct title
    QString settingsString;
    if(clientType == RADAR_CLIENT_TYPE_CHART)
    {
        settingsString = QString( "RadarClientChart2D_%1" ).arg(instance);
    }
    else if(clientType == RADAR_CLIENT_TYPE_RADAR)
    {
        settingsString = QString( "RadarClientRadar_%1" ).arg(instance);
    }
    else
    {
        Assert(false);
        ErrorPrintf("tRadarClientSettings::tRadarClientSettings() - unknown client type");
    }
    m_xSettings.reset(factory.Create( settingsString ));

    InitializeSettings();
}
Beispiel #15
0
bool tGLUtil::VerifyGLState(const QString& debugString)
{
    bool stateIsValid = true;

#ifdef _DEBUG

    GLenum error = glGetError();

    if (error != GL_NO_ERROR)
    {
        // Get list of error(s)
        QVector<GLenum> errorList;

        do
        {
            errorList.push_back(error);
            error = glGetError();
        } while (error != GL_NO_ERROR && errorList.size() < 7);

        // Print error message
        std::stringstream errorMessage;
        errorMessage << "OpenGL error(s) found:  ";

        errorMessage << GetErrorString(errorList);

        errorMessage << " (Debug Message:  " << debugString.toStdString() << ")";

        ErrorPrintf("%s", errorMessage.str().c_str());



        stateIsValid = false;
    }

#else

    Q_UNUSED(debugString);

#endif

    return stateIsValid;
}
Beispiel #16
0
tRadarClientSettings* tRadarClientSettings::Instance(int instance, tRadarClientType clientType)
{
    if (clientType == RADAR_CLIENT_TYPE_CHART)
    {
        Assert(instance < NUM_RADAR_CLIENT_CHART_INSTANCES);
        Assert(m_pChartInstances[instance] != 0);
        return m_pChartInstances[instance];
    }

    if (clientType == RADAR_CLIENT_TYPE_RADAR)
    {
        Assert(instance < NUM_RADAR_CLIENT_RADAR_INSTANCES);
        Assert(m_pRadarInstances[instance] != 0);
        return m_pRadarInstances[instance];
    }

    ErrorPrintf("tRadarClientSettings::Instance() - unknown client type");

    return m_pRadarInstances[0];
}
Beispiel #17
0
/*------------------------------------------------------------------------
       Parameters:

      Description:

    Return Values:
            0 on success, < 0 otherwise.

------------------------------------------------------------------------*/
int
WinAlloc(char *pcName, int iXpos, int iYpos, int iWidth, int iHeight)
{
  int    iWin ;
  DIAG_WINDOW *pwin ;

  iWin = winNewHandle() ;
  if (iWin < 0)
    return(ErrorPrintf(ERROR_NO_MEMORY,
                       "WinAlloc: could not allocate new window"));

  pwin = HandleToPtr(iWin) ;
#if 1
  pwin->xwin = xNewWindow(NULL, iXpos, iYpos, iWidth, iHeight, pcName, 0, 0) ;
#else
  pwin->xwin = xNewWindow(NULL, iXpos, iYpos, iWidth, iHeight, pcName, 0, 0) ;
#endif

  return(iWin) ;
}
Beispiel #18
0
void tRenderer::AddOverlayWidget(const boost::shared_ptr<tOverlayImage>& xOverlay)
{
    boost::shared_ptr<tOverlayUpdater> xNewOverlay;

    try
    {
        xNewOverlay.reset(new tOverlayUpdater(xOverlay));
    }

    catch (std::runtime_error& error)
    {
        ErrorPrintf("Failed to create new tOverlayUpdater in AddOverlay()!  %s", error.what());
    }

    // If tOverlayUpdater creation was successful, add the overlay to the scene
    if (xNewOverlay != 0)
    {
        m_OverlayManagers.insert(xNewOverlay);  // Insert the new tOverlayUpdater into the ordered set
    }
}
Beispiel #19
0
/*------------------------------------------------------------------------
  Parameters:

  Description:

  Return Values:
  nothing.
  ------------------------------------------------------------------------*/
double
latan2(double y, double x)
{
  int oerr ;
  double val ;

  oerr = errno ;
  if (FZERO(x) && FZERO(y))
    val = 0.0 ;
  else
    val = atan2(y, x) ;
  if (val < -PI)
    val += 2.0 * PI ;
  if (val > PI)
    val -= 2.0 * PI ;

  if (oerr != errno)
    ErrorPrintf(ERROR_BADPARM,
                "error %d, y %f, x %f\n", errno, (float)y, (float)x) ;
  return(val) ;
}
Beispiel #20
0
void ConvertImages(int nframes, char **argv) {
  IMAGE *I;
  int i, rows = 0, cols = 0;

  for (i=0;i<nframes;i++) {

    I = ImageRead(argv[i+1]);
    if (!I)
      ErrorExit(ERROR_NOFILE,
                "%s: could not read image file %s\n", Progname,argv[i+1]);
    if (i == 0) {
      rows = I->rows ;
      cols = I->cols ;
    } else if (rows != I->rows || cols != I->cols) {
#if 0
      ErrorExit
      (
        ERROR_BADFILE,
        "%s: image %s dimensions (%d x %d) "
        "don't match first image (%d x %d)",
        Progname, argv[i+1],I->cols, I->rows, cols, rows) ;
#else
      ErrorPrintf
      (ERROR_BADFILE,
       "%s: image %s dimensions (%d x %d) "
       "don't match first image (%d x %d)",
       Progname, argv[i+1],I->cols, I->rows, cols, rows) ;
#endif
      argv++ ;
      nframes-- ;
      i-- ;
      continue ;
    }

    rgb2xcol(I,imgdata,i);
    ImageFree(&I);
  }
}
Beispiel #21
0
/*----------------------------------------------------------------------
            Parameters:
              fname - the name of the file to read from

           Description:
              read a hips image from a file, and allocate an image
              header and data space for it.  Returns the newly
              allocated image.
----------------------------------------------------------------------*/
int
ImageReadInto(const char*fname, IMAGE *I, int image_no)
{
  FILE   *fp ;
  int    ecode ;

  fp = fopen(fname, "rb") ;
  if (!fp)
    ErrorPrintf(ERROR_NO_FILE, "ImageReadInto(%s) failed\n", fname) ;

  ecode = fread_header(fp, I, fname) ;
  if (ecode != HIPS_OK)
    ErrorExit(ERROR_NO_FILE, "ImageReadInto(%s): fread_header failed (%d)\n",
              fname, ecode) ;
  ecode = fread_image(fp, I, image_no, fname) ;
  if (ecode != HIPS_OK)
    ErrorExit(ERROR_NO_FILE, "ImageReadInto(%s): fread_image failed (%d)\n",
              fname, ecode) ;

  fclose(fp) ;

  return(0) ;
}
Beispiel #22
0
void tGPXFileExport::WriteRoutes(tFile& file, QList<tRoute> routeList, tIUDBWpRtDB* pUDBWpRtDB)
{
    QString string;
    for(int i = 0; i < routeList.size(); ++i )
    {
        tRoute route = routeList.at( i );
        
        // Name
        string = QString("    <rte>\n        <name>%1</name>\n").arg(PrepareForXML(route.Name()));
        file.write(string.toAscii());

        const QList<QUuid> waypointList = route.WaypointList();
        for ( int j=0; j < waypointList.size(); ++j )
        {
            tWaypoint waypoint;
            if ( pUDBWpRtDB->FindWaypoint( waypointList.at( j ), &waypoint ) )
            {                  
                string = CreateWaypointString(waypoint, "rtept", "        ");
                file.write(string.toAscii());
            }
            else
            {
                ErrorPrintf( "Failed to find route waypoint" );
                Assert( false );
            }
        }

        string = QString("    </rte>\n");
        file.write(string.toAscii());

        // keep the event loop alive every 100 times round this loop
        if( (i % 100) == 0 )
        {
            QApplication::processEvents();
        }
    }
}
/*******************************************************************************
* Name:			Read3DS (int iNrOfBytes, byte* bp3DSData)
*******************************************************************************/
int FLOAT_PERCENTAGE::Read3DS (int iNrOfBytes, byte* bp3DSData)
{
	// Print status
	VerbosePrintf ("Begin reading FLOAT_PERCENTAGE chunk");

	// Check chunk length
	if (iNrOfBytes < 2)
	{
		// Set error chunk size invalid
		ErrorPrintf ("Chunk size invalid");

		// Return error
		return (-1);
	}

	// Get version from buffer
	FLOAT_PERCENTAGE::fPercentage = GetFloat (bp3DSData);
	
	// Check percentage
	if (FLOAT_PERCENTAGE::fPercentage > 1)
	{
		// Set to default
		FLOAT_PERCENTAGE::fPercentage = 1;
		
		// Print status
		VerbosePrintf ("Invalid percentage, reset to 1.0");
	}

	// Print status
	VerbosePrintf ("Percentage: %f", FLOAT_PERCENTAGE::fPercentage);

	// Print status
	VerbosePrintf ("End reading FLOAT_PERCENTAGE chunk");

	// Return no error
	return (0);
}
static int
remove_vertex_from_cluster(MRI_SURFACE *mris, MRI *mri_profiles, CLUSTER *ct,
                           int c, int vno) {
  int    nsamples;
  static VECTOR *v_vals = NULL ;

  nsamples = mri_profiles->nframes ;

  mris->vertices[vno].curv = c ;
  if (v_vals == NULL)
    v_vals = VectorAlloc(nsamples, MATRIX_REAL) ;

  VectorScalarMul(ct[c].v_mean, ct[c].npoints, ct[c].v_mean) ;
  load_vals(mri_profiles, v_vals, vno) ;
  VectorSubtract(ct[c].v_mean, v_vals, ct[c].v_mean) ;
  ct[c].npoints-- ;
  if (ct[c].npoints == 0)
    ErrorPrintf(ERROR_BADPARM, "%s: empty cluster %d (vertex %d removed)",
                Progname, c, vno) ;
  else
    VectorScalarMul(ct[c].v_mean, 1.0/(double)ct[c].npoints, ct[c].v_mean) ;

  return(NO_ERROR) ;
}
Beispiel #25
0
int afniWrite(MRI *mri,const char *fname)
{

  char header_fname[STRLEN];
  FILE *fp;
  int i, j, k;
  int orient_specific[3];
  int bytes_per_voxel;
  float max, min;
  int dest_type;
  short s;
  float f;
  char *c;

  errno = 0;
  ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "AFNI BRIK write unsupported"));

  /* ----- keep compiler quiet ----- */
  bytes_per_voxel = 0;
  dest_type = -1;

  if (mri->nframes != 1)
  {
    errno = 0;
    ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "afniRead(): writing of anything but 1 frame unsupported (mri->nframes = %d)", mri->nframes));
  }

  orient_specific[0] = -1;
  orient_specific[1] = -1;
  orient_specific[2] = -1;

  for (i = 0;i < 6;i++)
  {
    if (mri->x_r == afni_orientations[i][0] && mri->x_a == afni_orientations[i][1] && mri->x_s == afni_orientations[i][2])
      orient_specific[0] = i;
    if (mri->y_r == afni_orientations[i][0] && mri->y_a == afni_orientations[i][1] && mri->y_s == afni_orientations[i][2])
      orient_specific[1] = i;
    if (mri->z_r == afni_orientations[i][0] && mri->z_a == afni_orientations[i][1] && mri->z_s == afni_orientations[i][2])
      orient_specific[2] = i;
  }

  if (orient_specific[0] == -1 || orient_specific[1] == -1 || orient_specific[2] == -1)
  {
    errno = 0;
    ErrorPrintf(ERROR_UNSUPPORTED, "afniWrite(): oblique volume writing to AFNI unsupported");
    ErrorPrintf(ERROR_UNSUPPORTED, "x_(r, a, s) = (%g, %g, %g)", mri->x_r, mri->x_a, mri->x_s);
    ErrorPrintf(ERROR_UNSUPPORTED, "y_(r, a, s) = (%g, %g, %g)", mri->y_r, mri->y_a, mri->y_s);
    ErrorPrintf(ERROR_UNSUPPORTED, "z_(r, a, s) = (%g, %g, %g)", mri->z_r, mri->z_a, mri->z_s);
    return(ERROR_UNSUPPORTED);
  }

  if (mri->type == MRI_INT || mri->type == MRI_LONG)
  {
    MRIlimits(mri, &min, &max);
    if (min > -32768.0 && min < 32768.0 && max > -32768.0 && max < 32768.0)
      dest_type = MRI_SHORT;
    else
      dest_type = MRI_FLOAT;
  }
  else if (mri->type == MRI_UCHAR)
    bytes_per_voxel = 1;
  else if (mri->type == MRI_SHORT)
    bytes_per_voxel = 2;
  else if (mri->type == MRI_FLOAT)
    bytes_per_voxel = 4;
  else
  {
    errno = 0;
    ErrorReturn(ERROR_UNSUPPORTED, (ERROR_UNSUPPORTED, "afniRead(): unsupported data type %d", mri->type));
  }

  strcpy(header_fname, fname);
  c = strrchr(header_fname, '.');

  if (c == NULL)
  {
    errno = 0;
    ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "afniRead(): bad file name %s", fname));
  }

  if (strcmp(c, ".BRIK") != 0)
  {
    errno = 0;
    ErrorReturn(ERROR_BADPARM, (ERROR_BADPARM, "afniRead(): bad file name %s", fname));
  }

  sprintf(c, ".HEAD");

  if ((fp = fopen(header_fname, "w")) == NULL)
  {
    errno = 0;
    ErrorReturn(ERROR_BADFILE, (ERROR_BADFILE, "afniWrite(): can't open file %s for writing", header_fname));
  }

  fprintf(fp, "\n");

  fprintf(fp, "type = integer-attribute\n");
  fprintf(fp, "name = ORIENT_SPECIFIC\n");
  fprintf(fp, "count = 3\n");
  fprintf(fp, " 1\n");

  fprintf(fp, "\n");

  fprintf(fp, "type = integer-attribute\n");
  fprintf(fp, "name = BRICK_TYPES\n");
  fprintf(fp, "count = 1\n");
  fprintf(fp, " 1\n");

  fprintf(fp, "\n");

  fprintf(fp, "type = integer-attribute\n");
  fprintf(fp, "name = DATASET_DIMENSIONS\n");
  fprintf(fp, "count = 3\n");
  fprintf(fp, " %d %d %d\n", mri->width, mri->height, mri->depth);

  fprintf(fp, "\n");

  fprintf(fp, "type = float-attribute\n");
  fprintf(fp, "name = DELTA\n");
  fprintf(fp, "count = 3\n");
  fprintf(fp, " %g %g %g\n", mri->xsize, mri->ysize, mri->zsize);

  fprintf(fp, "\n");

  fprintf(fp, "type = float-attribute\n");
  fprintf(fp, "name = ORIGIN\n");
  fprintf(fp, "count = 3\n");
  fprintf(fp, " %g %g %g\n", -(mri->width  - 1.0) / 2.0 * mri->xsize,
          -(mri->height - 1.0) / 2.0 * mri->ysize,
          -(mri->depth  - 1.0) / 2.0 * mri->zsize);

  fprintf(fp, "\n");

  fprintf(fp, "type = \n");
  fprintf(fp, "name = BYTEORDER_STRING\n");
  fprintf(fp, "count = 10\n");
#if (BYTE_ORDER==LITTLE_ENDIAN)
  //#ifdef Linux
  fprintf(fp, " LSB_FIRST~\n");
#else
  fprintf(fp, " MSB_FIRST~\n");
#endif

  fclose(fp);

  if ((fp = fopen(fname, "w")) == NULL)
  {
    errno = 0;
    ErrorReturn(ERROR_BADFILE, (ERROR_BADFILE, "afniWrite(): can't open file %s for writing", fname));
  }

  for (k = 0;k < mri->depth;k++)
  {
    for (j = 0;j < mri->height;j++)
    {

      if (mri->type == MRI_INT || mri->type == MRI_LONG)
      {
        for (i = 0;i < mri->width;i++)
        {
          if (dest_type == MRI_SHORT)
          {
            if (mri->type == MRI_INT)
              s = (short)MRIIvox(mri, i, j, k);
            if (mri->type == MRI_LONG)
              s = (short)MRILvox(mri, i, j, k);
            fwrite(&s, sizeof(short), 1, fp);
          }
          if (dest_type == MRI_FLOAT)
          {
            if (mri->type == MRI_INT)
              f = (float)MRIIvox(mri, i, j, k);
            if (mri->type == MRI_LONG)
              f = (float)MRILvox(mri, i, j, k);
            fwrite(&f, sizeof(float), 1, fp);
          }
        }
      }

      else
        fwrite(mri->slices[k][j], bytes_per_voxel, mri->width, fp);

    }
  }

  fclose(fp);

  printf("no afni write\n");
  return(0);

} /* end afniWrite() */
Beispiel #26
0
int
RFtrain(RANDOM_FOREST *rf, double feature_fraction, double training_fraction, int *training_classes, double **training_data, int ntraining)
{
  int    n, ii, nfeatures_per_tree = 0, *feature_permutation, *training_permutation, f, 
    index, start_no, end_no, ntraining_per_tree = 0, total_to_remove = 0 ;
  TREE   *tree = NULL ;

  if (rf->max_class_ratio > 0)
  {
    int class_counts[MAX_CLASSES], max_class, max_class_count, min_class, min_class_count ;
    double **new_training_data ;
    int    *new_training_classes ;

    memset(class_counts, 0, sizeof(class_counts)) ;
    for (n = 0 ; n < ntraining ; n++)
      class_counts[training_classes[n]]++ ;
    for (min_class_count = ntraining+1, min_class = max_class = max_class_count = n = 0 ; 
	 n < rf->nclasses ; n++)
    {
      if (class_counts[n] > max_class_count)
      {
	max_class_count = class_counts[n] ;
	max_class = n ;
      }
      if (class_counts[n] < min_class_count)
      {
	min_class_count = class_counts[n] ;
	min_class = n ;
      }
    }
    total_to_remove = (max_class_count-nint(min_class_count*rf->max_class_ratio)) ;
    if (total_to_remove > 0)
    {
      int *class_indices, class_index,new_index, new_ntraining = ntraining-total_to_remove ;

      printf("class %s (%d) has too many examples (%d) relative to class %s (%d) with %d\n",
	     rf->class_names[max_class], max_class, max_class_count,
	     rf->class_names[min_class], min_class, min_class_count) ;
      new_training_classes = (int *)calloc(new_ntraining, sizeof(int)) ;
      new_training_data = (double **)calloc(new_ntraining, sizeof(double *)) ;
      class_indices = (int *)calloc(max_class_count, sizeof(int)) ;

      // first copy over everything that isn't in class max_class
      for (class_index = new_index = n = 0 ; n < ntraining ; n++)
      {
	if (training_classes[n] == max_class)
	  class_indices[class_index++] = n ;
	else  // copy over other class features and class
	{
	  new_training_classes[new_index] = training_classes[n] ;
	  new_training_data[new_index] = (double *)calloc(rf->nfeatures,sizeof(double));
	  for (ii = 0 ; ii < rf->nfeatures ; ii++)
	    new_training_data[new_index][ii] = training_data[n][ii] ;
	  new_index++ ;
	}
      }

      compute_permutation(max_class_count, class_indices) ;
      for (n = 0 ; n < max_class_count - total_to_remove ; n++)
      {
	new_training_classes[new_index] = max_class ;
	new_training_data[new_index] = (double *)calloc(rf->nfeatures,sizeof(double));
	for (ii = 0 ; ii < rf->nfeatures ; ii++)
	  new_training_data[new_index][ii] = training_data[class_indices[new_index]][ii] ;
	new_index++ ;
      }
      training_data = new_training_data ;
      training_classes = new_training_classes ;
      ntraining -= total_to_remove ;
    }
  }

  if (getenv("RF_WRITE_TRAINING"))
  {
    char *fname = getenv("RF_WRITE_TRAINING") ;
    FILE *fp ;

    printf("writing RF training to %s\n", fname) ;
    fp = fopen(fname, "w") ;

    for (n = 0 ; n < ntraining ; n++)
    {
      fprintf(fp, "%d ", training_classes[n]) ;
      for (ii = 0 ; ii < rf->nfeatures ; ii++)
	fprintf(fp, "%f ", training_data[n][ii]) ;
      fprintf(fp, "\n") ;
    }

    fclose(fp) ;
  }
  rf->ntraining = ntraining ;
  rf->training_data = training_data ;
  rf->training_classes = training_classes ;
  rf->feature_fraction = feature_fraction ;
  rf->training_fraction = training_fraction ;

  for (f = 0 ; f < rf->nfeatures ; f++)
  {
    rf->feature_min[f] = 1e20 ;
    rf->feature_max[f] = -1e20 ;
    for (ii = 0 ; ii < ntraining ; ii++)
    {
      if (training_data[ii][f] < rf->feature_min[f])
        rf->feature_min[f] = training_data[ii][f] ;
      if (training_data[ii][f] > rf->feature_max[f])
        rf->feature_max[f] = training_data[ii][f] ;
    }
  }

  nfeatures_per_tree = nint((double)rf->nfeatures * feature_fraction) ;
  ntraining_per_tree = nint((double)rf->ntraining * training_fraction) ;
  feature_permutation = compute_permutation(rf->nfeatures, NULL) ;
  training_permutation = compute_permutation(ntraining, NULL) ;

#ifdef HAVE_OPENMP
  tree = NULL;
  start_no = 0 ; // only 1 tree
  end_no = 0 ; // only 1 tree
  index = 0 ;
  n = 0 ;
  ii = 0 ;
#pragma omp parallel for firstprivate(tree,start_no,end_no,ii,index) shared(rf, nfeatures_per_tree, Gdiag,training_classes,training_data) schedule(static,1)
#endif
  for (n = 0 ; n < rf->ntrees ; n++)  // train each tree
  {
#ifdef HAVE_OPENMP
  #pragma omp critical 
#endif  
    printf("training tree %d of %d....\n", n, rf->ntrees) ;
    tree = &rf->trees[n] ;

    // randomize what features this tree will use
    tree->feature_list = (int *)calloc(nfeatures_per_tree, sizeof(tree->feature_list[0]));
    if (tree->feature_list == NULL)
      ErrorExit(ERROR_NOMEMORY, "RFtrain: could not allocate feature list %d (%d)",
                n,nfeatures_per_tree) ;
    tree->nfeatures = nfeatures_per_tree ;
    if (rf->ntrees > 1)
      start_no = nint(n*((double)(rf->nfeatures-nfeatures_per_tree))/(rf->ntrees-1.0)) ;
    else
      start_no = 0 ; // only 1 tree
    end_no = MIN(rf->nfeatures-1, start_no+nfeatures_per_tree-1) ;
    for (ii = start_no  ; ii <= end_no  ; ii++)
      tree->feature_list[ii-start_no] = feature_permutation[ii] ;
    

    // randomize what training data this tree will use
    tree->root.training_set = (int *)calloc(ntraining, sizeof(tree->root.training_set[0])) ;
    if (tree->root.training_set == NULL)
      ErrorExit(ERROR_NOMEMORY, "RFtrain: could not allocate root training set") ;
    tree->root.total_counts = 0 ;
    if (rf->ntrees > 1)
      start_no = nint(n*((double)(rf->ntraining-ntraining_per_tree))/(rf->ntrees-1.0)) ;
    else
      start_no = 0 ; // only 1 tree
    end_no = MIN(rf->ntraining-1, start_no+ntraining_per_tree-1) ;
    for (ii = start_no  ; ii <= end_no  ; ii++)
    {
      index = training_permutation[ii] ;
      if (training_classes[index] < 0 || training_classes[index] >= rf->nclasses)
      {
	ErrorPrintf(ERROR_BADPARM, "RFtrain: class at index %d = %d: out of bounds (%d)",
		    index, training_classes[index], rf->nclasses) ;
	training_classes[index] = 0 ;
      }
      tree->root.class_counts[training_classes[index]]++ ;
      tree->root.training_set[tree->root.total_counts] = index ;
      tree->root.total_counts++ ;
    }

    if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
      printf("tree %d: initial entropy = %f\n", n, 
	     entropy(tree->root.class_counts, rf->nclasses, tree->root.class_counts)) ;
    rfTrainTree(rf, tree, training_classes, training_data, rf->ntraining) ;
#ifdef HAVE_OPENMP
  #pragma omp critical 
#endif  
    printf("\ttraining complete, depth %d, nleaves %d.\n", tree->depth, tree->nleaves) ;
  }

  if (total_to_remove > 0)
  {
    for (n = 0 ; n < ntraining ; n++)
      free(training_data[n]) ;
    free(training_data) ; free(training_classes) ;
  }
  free(feature_permutation) ;
  free(training_permutation) ;
  return(NO_ERROR) ;
}
Beispiel #27
0
/*******************************************************************************
* Name:			Read3DS ()
*******************************************************************************/
int M3DMAGIC::Read3DS (int iNrOfBytes, byte* bp3DSData)
{
	int iCurrentByte = 0;	// Pointer to current byte in chunk
	int iChunkID;			// Chunk id
	long lChunkLength;		// Chunk length

	// Print status
	VerbosePrintf ("Begin reading M3DMAGIC chunk");

	// Check for zero length
	if (iNrOfBytes <= CHUNKHEADER_SIZE)
	{
		// Set error file contains no data
		ErrorPrintf ("File contains no data");

		// Return error
		return (-1);
	}

	// Get chunks from M3DMAGIC chunk
	while (iCurrentByte < iNrOfBytes)
	{
		// Get chunk id
		iChunkID = Get3DSChunkID (bp3DSData + iCurrentByte);
		iCurrentByte += CHUNKID_SIZE;
		
		// Get chunk length
		lChunkLength = GetInt (bp3DSData + iCurrentByte);
		iCurrentByte += CHUNKLENGTH_SIZE;
		
		// Check if length is correct
		if (lChunkLength > (iNrOfBytes - iCurrentByte + CHUNKHEADER_SIZE))
		{
			// Set error chunk size invalid
			ErrorPrintf ("Chunk size invalid");

			// Return error
			return (-1);
		}
		
		// Check chunk id
		switch (iChunkID)
		{
			case M3D_VERSION_CHUNK:
				// Print status
				VerbosePrintf ("M3D_VERSION chunk found");

				// Read M3D_VERSION chunk
				if (M3DMAGIC::vVersion.Read3DS (lChunkLength - CHUNKHEADER_SIZE,
					bp3DSData + iCurrentByte) != 0)
				{
					// Return error
					return (-1);
				}				
				break;
			case MDATA_CHUNK:
				// Print status
				VerbosePrintf ("MDATA chunk found");

				// Read MDATA chunk
				if (M3DMAGIC::dData.Read3DS (lChunkLength - CHUNKHEADER_SIZE, bp3DSData + iCurrentByte) != 0) {
					// Return error
					return (-1);
				}
				break;
			default:
				// Print status
				VerbosePrintf ("Unknown chunk found in M3DMAGIC: %x", iChunkID);
				break;
		}
		
		// Set pointer
		iCurrentByte += (lChunkLength - CHUNKHEADER_SIZE);
	}

	// Print status
	VerbosePrintf ("End reading M3DMAGIC chunk");

	// Return no error
	return (0);
}
Beispiel #28
0
int readAFNIHeader(FILE *fp, AF *pAF)
{
  char line[STRLEN], line2[STRLEN];
  int i, j;
  char type[STRLEN], name[STRLEN];
  int count;
  char *s;
  float *f;
  int *ip;
  long gotten = 0;

  int val;

  fseek(fp, 0, SEEK_SET);

  // AFNI header attribute spec http://afni.nimh.nih.gov/afni/docREADME/README.attributes
  while (1) // !feof(fp))
  {

    fgets(line, STRLEN, fp);
    if (feof(fp)) // wow.  we read too many.  get out
      break;

    if (!feof(fp))
    {
      i = -1;
      j = -1;
      do
      {
        i++;
        j++;
        for (;isspace(line[j]) && line[j] != '\0';j++);
        line2[i] = line[j];
      }
      while (line[j] != '\0');

      if (strlen(line2) > 0)
        if (line2[strlen(line2)-1] == '\n')
          line2[strlen(line2)-1] = '\0';

      if (strncmp(line2, "type=", 5) == 0)
        strcpy(type, &line2[5]);
      if (strncmp(line2, "name=", 5) == 0)
        strcpy(name, &line2[5]);
      if (strncmp(line2, "count=", 5) == 0)
      {
        count = atoi(&line2[6]);
        s = 0;
        f = 0;
        ip = 0;
        // depending on the attribute, get the array
        if (strncmp(type, "string-attribute", 16) == 0)
        {
          s = get_afni_string(fp, count, name);
          if (s == 0)
            return(0);
        }
        else if (strncmp(type, "float-attribute", 15) == 0)
        {
          f = get_afni_float(fp, count, name);
          if (f == 0)
            return(0);
        }
        else if (strncmp(type, "integer-attribute", 17) == 0)
        {
          ip = get_afni_int(fp, count, name);
          if (ip == 0)
            return(0);
        }
        else
        {
          errno = 0;
          ErrorReturn(0, (ERROR_BADPARM, "read_afni_header(): unknown type %s", type));
        }
        // now compare name with the attribute
        // mandatory attributes
        if (strcmp(name, "DATASET_RANK") == 0)
        {
          pAF->dataset_rank[0] = ip[0];
          pAF->dataset_rank[1] = ip[1];
        }
        else if (strcmp(name, "DATASET_DIMENSIONS") == 0)
        {
          // check errors for getting non-integer
          if (strncmp(type, "integer-attribute", 17) != 0)
          {
            errno = 0;
            ErrorReturn(0, (ERROR_BADPARM, "read_afni_header(): variable %s listed as %s (expecting integer-attribute)", name, type));
          }
          // check errors for getting less than 3 counts
          if (count < 3)
          {
            errno = 0;
            ErrorReturn(0, (ERROR_BADPARM, "read_afni_header(): not enough variables in %s (need 3, have %d", name, count));
          }
          pAF->dataset_dimensions[0] = ip[0];
          pAF->dataset_dimensions[1] = ip[1];
          pAF->dataset_dimensions[2] = ip[2];
          // mark got the info on dimension
          gotten = gotten | DATASET_DIMENSIONS_FLAG;
        }
        else if (strcmp(name, "TYPESTRING") == 0)
        {
          strcpy(pAF->typestring, s);// s is src
        }
        else if (strcmp(name, "SCENE_DATA") == 0)
        {
          pAF->scene_data[0] = ip[0];
          pAF->scene_data[1] = ip[1];
          pAF->scene_data[2] = ip[2];
        }
        else if (strcmp(name, "ORIENT_SPECIFIC") == 0)
        {
          // error check to make sure 3 integers
          if (strncmp(type, "integer-attribute", 17) != 0)
          {
            errno = 0;
            ErrorReturn(0,
                        (ERROR_BADPARM,
                         "read_afni_header(): variable %s listed as %s (expecting integer-attribute)",
                         name, type));
          }
          if (count < 3)
          {
            errno = 0;
            ErrorReturn(0,
                        (ERROR_BADPARM, "read_afni_header(): not enough variables in %s (need 3, have %d",
                         name, count));
          }
          if (ip[0] < 0 || ip[0] > 5 ||
              ip[1] < 0 || ip[1] > 5 ||
              ip[2] < 0 || ip[2] > 5)
          {
            errno = 0;
            ErrorReturn(0,
                        (ERROR_BADPARM,
                         "read_afni_header(): %s variables should be 0 to 5, inclusive (are %d, %d, %d here)",
                         name, ip[0], ip[1], ip[2]));
          }
          //
          pAF->orient_specific[0] = ip[0];
          pAF->orient_specific[1] = ip[1];
          pAF->orient_specific[2] = ip[2];

          gotten = gotten | ORIENT_SPECIFIC_FLAG;
        }
        else if (strcmp(name, "ORIGIN") == 0)
        {
          if (count < 3)
          {
            errno = 0;
            ErrorReturn(0,
                        (ERROR_BADPARM,
                         "read_afni_header(): not enough variables in %s (need 3, have %d", name, count));
          }
          if (strncmp(type, "float-attribute", 15) != 0)
          {
            errno = 0;
            ErrorReturn(0,
                        (ERROR_BADPARM,
                         "read_afni_header(): variable %s listed as %s (expecting float-attribute)",
                         name, type));
          }
          pAF->origin[0] = f[0];
          pAF->origin[1] = f[1];
          pAF->origin[2] = f[2];

          gotten = gotten | ORIGIN_FLAG;
        }
        else if (strcmp(name, "DELTA") == 0)
        {
          if (strncmp(type, "float-attribute", 15) != 0)
          {
            errno = 0;
            ErrorReturn(0,
                        (ERROR_BADPARM,
                         "read_afni_header(): variable %s listed as %s (expecting float-attribute)",
                         name, type));
          }
          if (count < 3)
          {
            errno = 0;
            ErrorReturn(0, (ERROR_BADPARM, "read_afni_header(): not enough variables in %s (need 3, have %d", name, count));
          }
          pAF->delta[0] = f[0];
          pAF->delta[1] = f[1];
          pAF->delta[2] = f[2];
          gotten = gotten | DELTA_FLAG;
        }
        ////////////////////////////////////////////////////////////////////
        //// Almost Mandatory Attributes
        ////////////////////////////////////////////////////////////////////
        else if (strcmp(name, "IDCODE_STRING") == 0)
        {
          pAF->idcode_string = (char *) malloc(sizeof(char)*count);
          strcpy(pAF->idcode_string, s);
        }
        else if (strcmp(name, "BYTEORDER_STRING") == 0)
        {
          if (strncmp(type, "string-attribute", 16) != 0)
          {
            errno = 0;
            ErrorReturn(0, (ERROR_BADPARM, "read_afni_header(): variable %s listed as %s (expecting string-attribute)", name, type));
          }
          strcpy(pAF->byteorder_string, s);
          gotten = gotten | BYTEORDER_STRING_FLAG;
        }
        else if (strcmp(name, "BRICK_STATS") == 0)
        {
          pAF->numstats = count;
          pAF->brick_stats = (float *) malloc(sizeof(float)*count);
          for (i=0; i < count; ++i)
            pAF->brick_stats[i] = f[i];
        }
        else if (strcmp(name, "BRICK_TYPES") == 0)
        {
          pAF->numtypes = count;
          pAF->brick_types = (int *) malloc(sizeof(int)*count);
          for (i=0; i < count; ++i)
            pAF->brick_types[i] = ip[i];
          // verify all same type
          if (pAF->brick_types)
          {
            val = pAF->brick_types[0];
            // we can support only one type nframs
            for (i = 1; i < count; ++i)
            {
              if (pAF->brick_types[i] != val)
                ErrorReturn(0, (ERROR_BADPARM, "multiple data types are not supported"));
            }
          }
          gotten = gotten | BRICK_TYPES_FLAG;
        }
        // new adddition
        else if (strcmp(name, "BRICK_FLOAT_FACS") == 0)
        {
          pAF->numfacs = count;
          pAF->brick_float_facs = (float *) malloc(sizeof(float)*count);
          for (i=0; i < count; ++i)
            pAF->brick_float_facs[i] = f[i];
        }
        else /* ignore unknown variables */
        {}

        if (s != 0)
          free(s);
        if (f != 0)
          free(f);
        if (ip != 0)
          free(ip);
      }
    }
  }
  fclose(fp);

  if ((gotten & AFNI_ALL_REQUIRED) != AFNI_ALL_REQUIRED)
  {

    errno = 0;
    ErrorPrintf(ERROR_BADFILE, "missing fields in afni header file");

    if (!(gotten & ORIENT_SPECIFIC_FLAG))
      ErrorPrintf(ERROR_BADFILE, "  ORIENT_SPECIFIC missing");
    if (!(gotten & BRICK_TYPES_FLAG))
      ErrorPrintf(ERROR_BADFILE, "  BRICK_TYPES missing");
    if (!(gotten & DATASET_DIMENSIONS_FLAG))
      ErrorPrintf(ERROR_BADFILE, "  DATASET_DIMENSIONS missing");
    if (!(gotten & DELTA_FLAG))
      ErrorPrintf(ERROR_BADFILE, "  DELTA missing");
    if (!(gotten & ORIGIN_FLAG))
      ErrorPrintf(ERROR_BADFILE, "  ORIGIN missing");
    if (!(gotten & BYTEORDER_STRING_FLAG))
      ErrorPrintf(ERROR_BADFILE, "  BYTEORDER_STRING missing");

    return(0);
  }
  return 1;
}
Beispiel #29
0
int dijkstra(
    s_env&          st_env,
    float           af_maxAllowedCost,
    bool            ab_surfaceCostVoid)
{
    int             i, j;
    int             vno_c   = -1;
    int             vno_n   = -1;
    int             vno_i, vno_f;
    VERTEX          *v_c, *v_n;
    float           cost, f_pathCost;
    struct d_node   *dn, *dn_next;
    int             rv;
//    s_iterInfo      st_iterInfo;
    MRIS*           surf                = st_env.pMS_active;
//    bool            b_relNextReference  = true;

  // If we aren't going to preserve cost history in the environment, then we
  // will by default always be able to write path costs
  bool              b_canWriteCostVal   = !st_env.b_costHistoryPreserve;
  static int        calls               = 0;
  int               marked              = 0;
  int               totalLoops          = -1;

  /* --- sanity checks --- */
  vno_i  = st_env.startVertex;
  vno_f  = st_env.endVertex;

  assert(vno_i >= 0);
  assert(vno_i < surf->nvertices);
  assert(vno_f >= 0);
  assert(vno_f < surf->nvertices);

  if (!st_env.b_costHistoryPreserve) {
    assert(!surf->vertices[vno_i].ripflag);
    assert(!surf->vertices[vno_f].ripflag);
  }

  /* --- initialize --- */
  for (i = 0; i < surf->nvertices; i++) {
    bool b_overwrite = true;
    if (mark(surf, i, DIJK_VIRGIN, b_overwrite) != NO_ERROR)
      goto error;
    // Set all vertex values to -1 - only the very first time
    // that this function is called, or if explicitly
    // specified in the calling parameters.
    if (!calls || ab_surfaceCostVoid) surf->vertices[i].val = -1;
  }
  calls++;

  surf->vertices[vno_i].val = 0.0;
  surf->vertices[vno_i].old_undefval = vno_f;
  if (mark(surf, vno_i, DIJK_IN_PLAY) != NO_ERROR)
    goto error;

  // If the start and end vertices are coincident in the problem environment,
  // we should loop through at least once, and ignore the vno_c!=vno_f
  // condition, otherwise the while() will terminate after one loop.
  while ( vno_c!=vno_f || !totalLoops) {
    totalLoops++;
    if(totalLoops >= st_env.pMS_curvature->nvertices-1) {
      // If this condition is true, we have processed all available vertices
      // in the mesh -- typically only occurs if the startVertex == endVertex
      // and is used for 'autodijk' type calculations.
      rv = TRUE;
      goto clean;
    }
    
    /* set vno_c (find min) */
    if (d_list == NULL) {
      ErrorPrintf(ERROR_BADPARM, "dijkstra(): out of vertices");
      colprintf(st_env.lw, st_env.rw, "start:stop", "[ %d:%d ]\n",
                st_env.startVertex,
                st_env.endVertex);
      goto error;
    }

    vno_c  = d_list->vno;
    v_c  = &surf->vertices[vno_c];

    /* mark it */
    if (mark(surf, vno_c, DIJK_DONE) != NO_ERROR)
      goto error;

    /* update neighbors */
    //cout << "neighbors = " << (int) v_c->num << endl;
    for (j = 0; j < (int) v_c->vnum; j++) {
      //cout << "neighbor = " << j << endl;
      vno_n = v_c->v[j];
      v_n  = &surf->vertices[vno_n];

      //if(v_n->ripflag) continue;

      if (v_n->marked == DIJK_DONE) continue; // for "circular" path searches

//      cost = st_env.costFunc_do(st_env, &st_iterInfo, vno_c, j, 
//          			b_relNextReference);
      cost = s_env_edgeCostFind(st_env, vno_c, vno_n);
      f_pathCost = v_c->val + cost;

      // Break out of while if af_maxAllowedCost is violated.
      if (af_maxAllowedCost && (f_pathCost > af_maxAllowedCost)) continue;

      if ( (v_n->marked == DIJK_VIRGIN) || (f_pathCost < v_n->val) ) {
        // The check in the <if> statement preserves pathCost values in the MRIS
        // from previous calls to this function. This history is important
        // in determing ply distances from a given target path. A pathCost
        // is only written to a new vertex iff that vertex has never been
        // visited, or if the cost is less than an older value.
        if (st_env.b_costHistoryPreserve) {
          b_canWriteCostVal = (f_pathCost<v_n->val||v_n->val==-1);
        }
        if (b_canWriteCostVal) {
          marked++;
          v_n->val   = f_pathCost;
          v_n->old_undefval  = vno_c;
          //cout << vno_c << "<---" << vno_n << endl;
        }
      }
//     cout << "v->marked in dijkstra " << v_n->marked << endl;
      if (v_n->marked == DIJK_VIRGIN)
        if (mark(surf, vno_n, DIJK_IN_PLAY) != NO_ERROR) goto error;
    }
  }

  rv = TRUE;
  goto clean;

error:
  rv = FALSE;

clean:
  for (dn = d_list;dn != NULL;dn = dn_next) {
    dn_next = dn->next;
    free(dn);
  }
  d_list = NULL;

  return(rv);

} /* end dijkstra() */
Beispiel #30
0
void tGPXFileExport::WriteTracks(tFile& file, const QList<tTrackXPtr>& trackList)
{
    QString string;
    for(int i = 0; i < trackList.size(); ++i )
    {
        const tTrackXPtr& xTrack = trackList.at(i);

        // Name
        string = QString("    <trk>\n        <name>%1</name>\n").arg(PrepareForXML(xTrack->Name()));
        file.write(string.toAscii());

        // Comment
        if ( !xTrack->Comment().isEmpty() )
        {
            string = QString("        <desc>%1</desc>\n").arg(PrepareForXML(xTrack->Comment()));
            file.write(string.toAscii());
        }

        bool inSegment = false;
        int pointCounter = 0;
        for(int sectionIndex = 0; sectionIndex < xTrack->NumTrackSections(); ++sectionIndex )
        {
            tTrackSection trackSection = xTrack->TrackSection( sectionIndex );

            for(int trackPointIndex = 0; trackPointIndex < trackSection.Size(); ++trackPointIndex)
            {
                tTrackPoint trackPoint;
                if(trackSection.GetPoint(trackPointIndex, trackPoint))
                {
                    quint8 flags = trackPoint.Flags();
                    // Start a new segment if we have an invalid position or start a new section
                    if((flags & tTrackPoint::TRACK_VALID) == 0 || (flags & tTrackPoint::TRACK_START))
                    {
                        if(inSegment)
                        {
                            string = QString("        </trkseg>\n");
                            file.write(string.toAscii());
                            inSegment = false;
                        }
                    }


                    if(flags & tTrackPoint::TRACK_VALID)
                    {
                        if(!inSegment)
                        {
                            string = QString("        <trkseg>\n");
                            file.write(string.toAscii());
                            inSegment = true;
                        }

                        // Position
                        tMCoord mCoord( trackPoint.Position() );
                        double latDegrees;
                        double lonDegrees;
                        tGisConvert::MercatorMetersToLatLonDegs( mCoord.X(), mCoord.Y(), latDegrees, lonDegrees );

                        QString latString;
                        latString.setNum( latDegrees, 'f', 8 );

                        QString lonString;
                        lonString.setNum( lonDegrees, 'f', 8 );

                        string = QString("            <trkpt lon=\"%1\" lat=\"%2\" >\n").arg(lonString).arg(latString);

                        // Time
                        QDateTime dateTime = QDateTime::fromTime_t( trackPoint.TimeStamp() );
                        if(dateTime.isValid())
                        {
                            string += QString("                <time>%1</time>\n").arg( dateTime.toString( "yyyy-MM-dd'T'hh:mm:ss'Z'" ) );
                        }

                        float value;
                        /* NSW-21005
                        if(trackPoint.GetFloatValueCount() >= 1)
                        {
                            if(trackPoint.GetDigitalDataItem(0).GetValue(value))    // Depth [ft]
                            {
                                string += QString("                <depth>%1</depth>\n").arg(value * CF_FT_TO_M);
                            }
                        }
                        */
                        if(trackPoint.GetFloatValueCount() >= 2)
                        {
                            if(trackPoint.GetDigitalDataItem(1).GetValue(value))    // Water temp [C]
                            {
                                string += QString("                <watertemp>%1</watertemp>\n").arg(value);
                            }
                        }
                        if(trackPoint.GetFloatValueCount() >= 3)
                        {
                            if(trackPoint.GetDigitalDataItem(2).GetValue(value))    // SOG [kn]
                            {
                                string += QString("                <sog>%1</sog>\n").arg(value / CF_MPS_TO_KN);
                            }
                        }

                        string += "            </trkpt>\n";
                        file.write(string.toAscii());
                    }
                }
                else
                {
                    ErrorPrintf( "Failed to find track point" );
                    Assert( false );
                }

                // keep the event loop alive every 100 times round this loop
                if((pointCounter++ % 100) == 0)
                {
                    QApplication::processEvents();
                }
            }
        }
        
        if(inSegment)
        {
            string = QString("        </trkseg>\n");
            file.write(string.toAscii());
            inSegment = false;
        }

        string = QString("    </trk>\n");
        file.write(string.toAscii());
    }
}