Exemple #1
0
DBObjRecord *DBGridIF::AddLayer(char *layerName) {
    DBInt index;
    DBObjRecord *firstLayer, *layerRec, *dataRec;
    DBObjTableField *rowNumFLD = LayerTable->Field(DBrNRowNum);
    DBObjTableField *colNumFLD = LayerTable->Field(DBrNColNum);
    DBObjTableField *cellWidthFLD = LayerTable->Field(DBrNCellWidth);
    DBObjTableField *cellHeightFLD = LayerTable->Field(DBrNCellHeight);
    DBObjTableField *valueTypeFLD = LayerTable->Field(DBrNValueType);
    DBObjTableField *valueSizeFLD = LayerTable->Field(DBrNValueSize);

    firstLayer = LayerTable->First(&index);
    LayerTable->Add(layerName);
    if ((layerRec = LayerTable->Item()) == (DBObjRecord *) NULL)
        return ((DBObjRecord *) NULL);
    rowNumFLD->Int(layerRec, rowNumFLD->Int(firstLayer));
    colNumFLD->Int(layerRec, colNumFLD->Int(firstLayer));
    cellWidthFLD->Float(layerRec, cellWidthFLD->Float(firstLayer));
    cellHeightFLD->Float(layerRec, cellHeightFLD->Float(firstLayer));
    valueTypeFLD->Int(layerRec, valueTypeFLD->Int(firstLayer));
    valueSizeFLD->Int(layerRec, valueSizeFLD->Int(firstLayer));
    if ((dataRec = new DBObjRecord(layerName, ((size_t) rowNumFLD->Int(firstLayer)) * colNumFLD->Int(firstLayer) *
                                              valueSizeFLD->Int(firstLayer), valueSizeFLD->Int(firstLayer))) ==
        (DBObjRecord *) NULL) { return ((DBObjRecord *) NULL); }
    LayerFLD->Record(layerRec, dataRec);
    ((Data())->Arrays())->Add(dataRec);
    if (DataPTR->Type() == DBTypeGridContinuous) {
        ItemTable->Add(layerName);
        MissingValueFLD->Float(ItemTable->Item(), MissingValueFLD->Float(ItemTable->First(&index)));
    }
    return (layerRec);
}
Exemple #2
0
DBInt RGlibGenFuncFieldCompare(DBObjTable *table, char *f0Text, char *f1Text, char *rText, DBInt diffMethod) {
    DBInt intVal, ret, i, rowID;
    DBFloat val[2];
    DBObjTableField *field[2];
    DBObjTableField *result;
    DBObjRecord *record;

    field[0] = table->Field(f0Text);
    field[1] = table->Field(f1Text);
    result = table->Field(rText);
    if ((field[0] == (DBObjTableField *) NULL) || (field[1] == (DBObjTableField *) NULL)) {
        CMmsgPrint(CMmsgAppError, "Invalid Compare Fields in: %s %d", __FILE__, __LINE__);
        return (DBFault);
    }
    if (result == (DBObjTableField *) NULL)
        table->AddField(result = new DBObjTableField(rText, DBTableFieldFloat, "%10.3f", sizeof(DBFloat4)));
    if (diffMethod > 0) result->Format("%6.2f");
    for (rowID = 0; rowID < table->ItemNum(); ++rowID) {
        record = table->Item(rowID);
        if ((record->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle)
            result->Float(record, result->FloatNoData());
        else {
            for (i = 0; i < 2; ++i)
                if (field[i]->Type() == DBTableFieldInt) {
                    intVal = field[i]->Int(record);
                    ret = intVal == field[i]->IntNoData();
                    val[i] = (DBFloat) intVal;
                }
                else {
                    val[i] = field[i]->Float(record);
                    ret = CMmathEqualValues(val[i], field[i]->FloatNoData());
                }
            if (ret) result->Float(record, result->FloatNoData());
            else
                switch (diffMethod) {
                    default:
                        result->Float(record, val[0] - val[1]);
                        break;
                    case 1:
                        result->Float(record, (val[0] - val[1]) * 100.0 / val[0]);
                        break;
                    case 2:
                        result->Float(record, (val[0] - val[1]) * 100.0 / (val[0] > val[1] ? val[0] : val[1]));
                        break;
                }
        }
    }
    return (DBSuccess);
}
Exemple #3
0
DBInt RGlibPointSubbasinCenter(DBObjData *pntData, DBObjData *netData) {
    DBCoordinate massCoord;
    DBVPointIF *pntIF = new DBVPointIF(pntData);
    DBObjTable *pointTable = pntData->Table(DBrNItems);
    DBObjTableField *massCoordXFLD = pointTable->Field(RGlibMassCoordX);
    DBObjTableField *massCoordYFLD = pointTable->Field(RGlibMassCoordY);
    DBNetworkIF *netIF = new DBNetworkIF(netData);
    DBObjRecord *pointRec, *cellRec;

    if (massCoordXFLD == NULL) {
        massCoordXFLD = new DBObjTableField(RGlibMassCoordX, DBTableFieldFloat, "%10.3f", sizeof(DBFloat4));
        pointTable->AddField(massCoordXFLD);
    }
    if (massCoordYFLD == NULL) {
        massCoordYFLD = new DBObjTableField(RGlibMassCoordY, DBTableFieldFloat, "%10.3f", sizeof(DBFloat4));
        pointTable->AddField(massCoordYFLD);
    }

    for (pointRec = pntIF->FirstItem(); pointRec != (DBObjRecord *) NULL; pointRec = pntIF->NextItem()) {
        if ((pointRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) {
            massCoordXFLD->Float(pointRec, massCoordXFLD->FloatNoData());
            massCoordYFLD->Float(pointRec, massCoordYFLD->FloatNoData());
            continue;
        }
        if (DBPause(pointRec->RowID() * 100 / pntIF->ItemNum())) goto Stop;
        if ((cellRec = netIF->Cell(pntIF->Coordinate(pointRec))) == (DBObjRecord *) NULL)
            massCoord = pntIF->Coordinate(pointRec);
        else {
            if (netIF->CellBasinCells(cellRec) > 1) {
                massCoord.X = 0.0;
                massCoord.Y = 0.0;
                netIF->UpStreamSearch(cellRec, (DBNetworkACTION) _RGlibSubbasinCenterAction, &massCoord);
                massCoord.X = massCoord.X / (DBFloat) netIF->CellBasinCells(cellRec);
                massCoord.Y = massCoord.Y / (DBFloat) netIF->CellBasinCells(cellRec);
            }
            else massCoord = netIF->Center(cellRec);
        }
        massCoordXFLD->Float(pointRec, massCoord.X);
        massCoordYFLD->Float(pointRec, massCoord.Y);
    }
    Stop:
    if (pointRec != (DBObjRecord *) NULL) {
        pointTable->DeleteField(massCoordXFLD);
        pointTable->DeleteField(massCoordYFLD);
        return (DBFault);
    }
    return (DBSuccess);
}
Exemple #4
0
 void GetVariable(DBObjRecord *record, DBCoordinate coord) {
     switch ((GridIF->Data())->Type()) {
         case DBTypeGridContinuous: {
             DBFloat value;
             if (GridIF->Value(LayerRec, coord, &value))
                 TargetFLD->Float(record, value);
             else TargetFLD->Float(record, TargetFLD->FloatNoData());
         }
             break;
         case DBTypeGridDiscrete: {
             DBObjRecord *grdRec;
             if ((grdRec = GridIF->GridItem(LayerRec, coord)) != (DBObjRecord *) NULL)
                 switch (SourceFLD->Type()) {
                     case DBVariableString:
                         TargetFLD->String(record, SourceFLD->String(grdRec));
                         break;
                     case DBVariableInt:
                         TargetFLD->Int(record, SourceFLD->Int(grdRec));
                         break;
                     case DBVariableFloat:
                         TargetFLD->Float(record, SourceFLD->Float(grdRec));
                         break;
                     default:
                         break;
                 }
             else
                 switch (SourceFLD->Type()) {
                     case DBVariableString:
                         TargetFLD->String(record, "");
                         break;
                     case DBVariableInt:
                         TargetFLD->Int(record, SourceFLD->IntNoData());
                         break;
                     case DBVariableFloat:
                         TargetFLD->Float(record, SourceFLD->FloatNoData());
                         break;
                     default:
                         break;
                 }
         }
             break;
         default:
             CMmsgPrint(CMmsgUsrError, "Invalid grid type in: CMDgrdVariable:GetVariable ()");
             break;
     }
 }
Exemple #5
0
void RGISEditNetAddBasinXYCBK (Widget widget, RGISWorkspace *workspace,XmAnyCallbackStruct *callData)

	{
	DBInt basinID;
	DBDataset *dataset = UIDataset ();
	DBObjData *dbData =dataset->Data ();
	DBNetworkIF *netIF = new DBNetworkIF (dbData);
	DBObjTable *itemTable = dbData->Table (DBrNItems);
	DBObjTableField *xCoordFLD	= itemTable->Field (RGISNetMouthXCoord);
	DBObjTableField *yCoordFLD = itemTable->Field (RGISNetMouthYCoord);
	DBCoordinate coord;
	DBObjRecord *basinRec;
	UITable *tableCLS = (UITable *) dbData->Display (UITableName (dbData,itemTable));

	UIPauseDialogOpen ((char *) "Adding XY Coordinates");
	if (xCoordFLD == NULL)
		{
		xCoordFLD = new DBObjTableField (RGISNetMouthXCoord,DBTableFieldFloat,(char *) "%10.3f",sizeof (DBFloat4));
		itemTable->AddField (xCoordFLD);
		if (tableCLS != (UITable *) NULL) tableCLS->AddField (xCoordFLD);
		UIPause (40);
		}
	if (yCoordFLD == NULL)
		{
		yCoordFLD = new DBObjTableField (RGISNetMouthYCoord,DBTableFieldFloat,(char *) "%10.3f",sizeof (DBFloat4));
		itemTable->AddField (yCoordFLD);
		if (tableCLS != (UITable *) NULL) tableCLS->AddField (yCoordFLD);
		UIPause (80);
		}
	for (basinID = 0;basinID < netIF->BasinNum ();++basinID)
		{
		basinRec = netIF->Basin (basinID);
		if (UIPause (80 + basinID * 20 / netIF->BasinNum ())) goto Stop;
		coord = netIF->Center  (netIF->MouthCell (basinRec));
		xCoordFLD->Float (basinRec,coord.X);
		yCoordFLD->Float (basinRec,coord.Y);
		}
Stop:
	UIPauseDialogClose ();
	if (tableCLS != (UITable *) NULL) tableCLS->Draw ();
	}
Exemple #6
0
void RGISEditPointAddXYCBK (Widget widget, RGISWorkspace *workspace,XmAnyCallbackStruct *callData)

	{
	DBDataset *dataset = UIDataset ();
	DBObjData *dbData =dataset->Data ();
	DBVPointIF *pntIF = new DBVPointIF (dbData);
	DBObjTable *pointTable = dbData->Table (DBrNItems);
	DBObjTableField *xCoordFLD	= pointTable->Field (RGISEditPointXCoord);
	DBObjTableField *yCoordFLD = pointTable->Field (RGISEditPointYCoord);
	DBCoordinate coord;
	DBObjRecord *pointRec;
	UITable *tableCLS = (UITable *) dbData->Display (UITableName (dbData,pointTable));

	widget = widget; workspace = workspace; callData = callData;
	UIPauseDialogOpen ((char *) "Adding XY Coordinates");
	if (xCoordFLD == NULL)
		{
		xCoordFLD = new DBObjTableField (RGISEditPointXCoord,DBTableFieldFloat,"%10.3f",sizeof (DBFloat4));
		pointTable->AddField (xCoordFLD);
		if (tableCLS != (UITable *) NULL) tableCLS->AddField (xCoordFLD);
		UIPause (40);
		}
	if (yCoordFLD == NULL)
		{
		yCoordFLD = new DBObjTableField (RGISEditPointYCoord,DBTableFieldFloat,"%10.3f",sizeof (DBFloat4));
		pointTable->AddField (yCoordFLD);
		if (tableCLS != (UITable *) NULL) tableCLS->AddField (yCoordFLD);
		UIPause (80);
		}
	for (pointRec = pntIF->FirstItem (); pointRec != (DBObjRecord *) NULL; pointRec = pntIF->NextItem ())
		{
		if (UIPause (80 + pointRec->RowID () * 20 / pntIF->ItemNum ())) goto Stop;
		coord = pntIF->Coordinate  (pointRec);
		xCoordFLD->Float (pointRec,coord.X);
		yCoordFLD->Float (pointRec,coord.Y);
		}
Stop:
	UIPauseDialogClose ();
	if (tableCLS != (UITable *) NULL) tableCLS->Draw ();
	}
Exemple #7
0
static int _DBObjTableListSort(const DBObjRecord **obj0, const DBObjRecord **obj1) {
    DBInt ret = 0;
    DBObjTableField *field;
    DBDate date0, date1;

    for (field = _DBObjTableSortFields->First();
         field != (DBObjTableField *) NULL;
         field = _DBObjTableSortFields->Next()) {
        switch (field->Type()) {
            case DBTableFieldString:
                ret = strcmp(field->String(*obj0), field->String(*obj1));
                break;
            case DBTableFieldInt:
                ret = field->Int(*obj0) - field->Int(*obj1);
                break;
            case DBTableFieldFloat:
                if (field->Float(*obj0) - field->Float(*obj1) > 0.0) ret = 1;
                else if (field->Float(*obj0) - field->Float(*obj1) < 0.0) ret = -1;
                else ret = 0;
                break;
            case DBTableFieldDate:
                date0 = field->Date(*obj0);
                date1 = field->Date(*obj1);
                if (date0 > date1) ret = 1;
                else if (date0 < date1) ret = -1;
                else ret = 0;
                break;
            case DBTableFieldTableRec:
                ret = strcmp((*obj0)->Name(), (*obj1)->Name());
                break;
            case DBTableFieldDataRec:
                ret = (*obj0)->RowID() - (*obj1)->RowID();
                break;
        }
        if ((field->Flags() & DBObjectFlagSortReversed) == DBObjectFlagSortReversed) ret *= -1;
        if (ret != 0) return (ret);
    }
    if (ret == 0) ret = (*obj0)->ListPos() - (*obj1)->ListPos();
    return (ret);
}
Exemple #8
0
void DBGridIF::DiscreteStats() {
    DBInt recordID, layerID;
    DBFloat area, sumArea = 0.0;
    DBPosition pos;
    DBObjTableField *areaFLD = ItemTable->Field(DBrNGridArea);
    DBObjTableField *percentFLD = ItemTable->Field(DBrNGridPercent);
    DBObjRecord *layerRec, *record;

    for (recordID = 0; recordID < ItemTable->ItemNum(); ++recordID) {
        record = ItemTable->Item(recordID);
        areaFLD->Float(record, 0.0);
        percentFLD->Float(record, 0.0);
    }
    for (layerID = 0; layerID < LayerNum(); ++layerID) {
        layerRec = Layer(layerID);
        for (pos.Row = 0; pos.Row < RowNum(); ++pos.Row)
            for (pos.Col = 0; pos.Col < ColNum(); ++pos.Col)
                if ((record = GridItem(layerRec, pos)) != (DBObjRecord *) NULL) {
                    area = CellArea(pos);
                    sumArea += area;
                    areaFLD->Float(record, areaFLD->Float(record) + area);
                }
    }
    for (recordID = 0; recordID < ItemTable->ItemNum(); ++recordID) {
        record = ItemTable->Item(recordID);
        percentFLD->Float(record, areaFLD->Float(record) * 100.0 / sumArea);
    }
}
Exemple #9
0
int main(int argc, char *argv[]) {
    int argPos, argNum = argc, ret, verbose = false;
    DBInt recID, mode = DBTimeStepYear;
    char *tableName = (char *) NULL;
    char *srcName = (char *) NULL;
    char *dstName = (char *) NULL;
    DBObjData *data;
    DBObjTable *table;
    DBObjTableField *srcField;
    DBObjTableField *dstField = (DBObjTableField *) NULL;
    DBDate date;
    DBObjRecord *record;

    for (argPos = 1; argPos < argNum;) {
        if (CMargTest (argv[argPos], "-a", "--table")) {
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) {
                CMmsgPrint(CMmsgUsrError, "Missing table name!");
                return (CMfailed);
            }
            tableName = argv[argPos];
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-f", "--field")) {
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) {
                CMmsgPrint(CMmsgUsrError, "Missing field name!");
                return (CMfailed);
            }
            srcName = argv[argPos];
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-o", "--outfield")) {
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) {
                CMmsgPrint(CMmsgUsrError, "Missing output field name!");
                return (CMfailed);
            }
            dstName = argv[argPos];
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-m", "--mode")) {
            int optCodes[] = {DBTimeStepYear, DBTimeStepMonth};
            const char *optStrs[] = {"year", "month", (char *) NULL};

            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) {
                CMmsgPrint(CMmsgUsrError, "Missing mode!");
                return (CMfailed);
            }
            if ((mode = CMoptLookup(optStrs, argv[argPos], true)) == DBFault) {
                CMmsgPrint(CMmsgUsrError, "Invalid decimal date method!");
                return (CMfailed);
            }
            mode = optCodes[mode];
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-V", "--verbose")) {
            verbose = true;
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-h", "--help")) {
            CMmsgPrint(CMmsgInfo, "%s [options] <input file> <output file>", CMfileName(argv[0]));
            CMmsgPrint(CMmsgInfo, "     -a,--table     [table name]");
            CMmsgPrint(CMmsgInfo, "     -f,--field     [field name]");
            CMmsgPrint(CMmsgInfo, "     -o,--outfield  [output field]");
            CMmsgPrint(CMmsgInfo, "     -m,--mode      [year|month]");
            CMmsgPrint(CMmsgInfo, "     -V,--verbose");
            CMmsgPrint(CMmsgInfo, "     -h,--help");
            return (DBSuccess);
        }
        if ((argv[argPos][0] == '-') && ((int) strlen(argv[argPos]) > 1)) {
            CMmsgPrint(CMmsgUsrError, "Unknown option: %s!", argv[argPos]);
            return (CMfailed);
        }
        argPos++;
    }

    if (argNum > 3) {
        CMmsgPrint(CMmsgUsrError, "Extra arguments!");
        return (CMfailed);
    }
    if (verbose) RGlibPauseOpen(argv[0]);

    data = new DBObjData();
    if (((argNum > 1) && (strcmp(argv[1], "-") != 0) ? data->Read(argv[1]) : data->Read(stdin)) == DBFault) {
        delete data;
        return (CMfailed);
    }

    if (tableName == (char *) NULL) tableName = DBrNItems;

    if ((table = data->Table(tableName)) == (DBObjTable *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Invalid table!");
        delete data;
        return (CMfailed);
    }

    if (srcName == (char *) NULL) srcName = (char *) "Date";
    if ((srcField = table->Field(srcName)) == (DBObjTableField *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Missing date field!");
        delete data;
        return (CMfailed);
    }
    if ((srcField->Type() != DBTableFieldString) &&
        (srcField->Type() != DBTableFieldDate)) {
        CMmsgPrint(CMmsgUsrError, "Invalid date field!");
        delete data;
        return (CMfailed);
    }

    if (dstName == (char *) NULL)
        switch (mode) {
            case DBTimeStepYear:
                dstName = (char *) "Decimal Year";
                break;
            case DBTimeStepMonth:
                dstName = (char *) "Decimal Month";
                break;
        }

    if ((dstField = table->Field(dstName)) == (DBObjTableField *) NULL) {
        dstField = new DBObjTableField(dstName, DBTableFieldFloat, (char *) "%8.2f", sizeof(DBFloat4), false);
        table->AddField(dstField);
    }

    for (recID = 0; recID < table->ItemNum(); ++recID) {
        record = table->Item(recID);
        if (srcField->Type() == DBTableFieldString)
            date.Set(srcField->String(record));
        else date = srcField->Date(record);
        switch (mode) {
            case DBTimeStepYear:
                dstField->Float(record, date.DecimalYear());
                break;
            case DBTimeStepMonth:
                dstField->Float(record, date.DecimalMonth());
                break;
        }
    }
    ret = (argNum > 2) && (strcmp(argv[2], "-") != 0) ? data->Write(argv[2]) : data->Write(stdout);

    delete data;
    if (verbose) RGlibPauseClose();
    return (ret);
}
Exemple #10
0
DBInt RGlibGenFuncFieldCalculate (DBObjTable *table,char *f0Text,char *f1Text,char *rText,DBInt oper)

	{
	DBInt intVal, ret = false, i, rowID;
	DBFloat val [2];
	DBObjTableField *field [2];
	DBObjTableField *result;
	DBObjRecord *record;
		
	field [0] = table->Field (f0Text);
	field [1] = table->Field (f1Text);
	result = table->Field (rText);

	if ((field [0] == (DBObjTableField *) NULL) && (sscanf (f0Text,"%lf",val) != 1)) 		return (DBFault);
	if ((field [1] == (DBObjTableField *) NULL) && (sscanf (f1Text,"%lf",val + 1) != 1))	return (DBFault);
	 
	if (result == (DBObjTableField *) NULL)
		table->AddField (result = new DBObjTableField (rText,DBTableFieldFloat,"%10.3f",sizeof (DBFloat4)));
	if (field [0] != (DBObjTableField *) NULL)
		result->Format (field [0]->Format ());
	else if (field [1] != (DBObjTableField *) NULL)
		result->Format (field [1]->Format ());

	for (rowID = 0;rowID < table->ItemNum ();++rowID)
		{
		record = table->Item (rowID);
		if ((record->Flags () & DBObjectFlagIdle) == DBObjectFlagIdle)
			result->Float (record,result->FloatNoData ());
		else
			{
			for (i = 0;i < 2;++i)
				if (field [i] != (DBObjTableField *) NULL)
					{
					ret = false;
					if (field [i]->Type () == DBTableFieldInt) 
						{
						intVal = field [i]->Int (record);
						val [i] = (DBFloat) intVal;
						ret = intVal == field [i]->IntNoData ();
						}
					else
						{
						val [i] = field [i]->Float (record);
						ret = CMmathEqualValues (val [i],field [i]->FloatNoData ());
						}
					if (ret)
						{
						result->Float (record,result->FloatNoData ());
						goto Continue;
						}
					}
			if ((oper == DBMathOperatorDiv) && (val [1] == 0))
				result->Float (record,result->FloatNoData ());
			else
				switch (oper)
					{
					case DBMathOperatorAdd:	result->Float (record, val [0] + val [1]);	break;
					case DBMathOperatorSub:	result->Float (record, val [0] - val [1]);	break;
					case DBMathOperatorMul:	result->Float (record, val [0] * val [1]);	break;
					case DBMathOperatorDiv:	result->Float (record, val [0] / val [1]);	break;
					default:	CMmsgPrint (CMmsgAppError, "Invalid Operand in: %s %d",__FILE__,__LINE__);	break;
					}
Continue:
			continue;
			}
		}
	return (DBSuccess);
	}
Exemple #11
0
int main(int argc, char *argv[]) {
    int argPos, argNum = argc, ret, verbose = false;
    DBInt recID, i, deg, min, sec, strLen;
    DBFloat coord;
    char crdStr[DBStringLength];
    char *minStr, *secStr;
    char *tableName = (char *) NULL;
    char *srcFieldName = (char *) NULL;
    char *dstFieldName = (char *) NULL;
    DBObjData *data;
    DBObjTable *table;
    DBObjTableField *srcField;
    DBObjTableField *dstField;
    DBObjRecord *record;

    for (argPos = 1; argPos < argNum;) {
        if (CMargTest (argv[argPos], "-a", "--table")) {
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) {
                CMmsgPrint(CMmsgUsrError, "Missing table name!");
                return (CMfailed);
            }
            tableName = argv[argPos];
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-f", "--field")) {
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) {
                CMmsgPrint(CMmsgUsrError, "Missing field name!");
                return (CMfailed);
            }
            srcFieldName = argv[argPos];
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-r", "--rename")) {
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) {
                CMmsgPrint(CMmsgUsrError, "Missing second field name!");
                return (CMfailed);
            }
            dstFieldName = argv[argPos];
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-V", "--verbose")) {
            verbose = true;
            if ((argNum = CMargShiftLeft(argPos, argv, argNum)) <= argPos) break;
            continue;
        }
        if (CMargTest (argv[argPos], "-h", "--help")) {
            CMmsgPrint(CMmsgInfo, "%s [options] <input file> <output file>", CMfileName(argv[0]));
            CMmsgPrint(CMmsgInfo, "     -a,--table     [table name]");
            CMmsgPrint(CMmsgInfo, "     -f,--field     [coord field name]");
            CMmsgPrint(CMmsgInfo, "     -r,--rename    [output field]");
            CMmsgPrint(CMmsgInfo, "     -V,--verbose");
            CMmsgPrint(CMmsgInfo, "     -h,--help");
            return (DBSuccess);
        }
        if ((argv[argPos][0] == '-') && ((int) strlen(argv[argPos]) > 1)) {
            CMmsgPrint(CMmsgUsrError, "Unknown option: %s!", argv[argPos]);
            return (CMfailed);
        }
        argPos++;
    }

    if (argNum > 3) {
        CMmsgPrint(CMmsgUsrError, "Extra arguments!");
        return (CMfailed);
    }
    if (verbose) RGlibPauseOpen(argv[0]);

    if (srcFieldName == (char *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Coordinate field is not set!");
        return (CMfailed);
    }

    data = new DBObjData();
    if (((argNum > 1) && (strcmp(argv[1], "-") != 0) ? data->Read(argv[1]) : data->Read(stdin)) == DBFault) {
        delete data;
        return (CMfailed);
    }

    if (tableName == (char *) NULL) tableName = DBrNItems;

    if ((table = data->Table(tableName)) == (DBObjTable *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Invalid table!");
        delete data;
        return (CMfailed);
    }

    if ((srcField = table->Field(srcFieldName)) == (DBObjTableField *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Invalid coordinate field [%s]!", srcFieldName);
        delete data;
        return (CMfailed);
    }


    if (dstFieldName == (char *) NULL) dstFieldName = (char *) "DecimalCoord";
    {
        if ((dstField = table->Field(dstFieldName)) == (DBObjTableField *) NULL) {
            dstField = new DBObjTableField(dstFieldName, DBVariableFloat, "%10.3f", sizeof(DBFloat4), false);
            table->AddField(dstField);
        }
        else {
            if (dstField->Type() != DBVariableFloat) {
                CMmsgPrint(CMmsgUsrError, "Invalid coordinate field type!");
                delete data;
                return (CMfailed);
            }
        }
    }

    for (recID = 0; recID < table->ItemNum(); ++recID) {
        record = table->Item(recID);
        strncpy(crdStr, srcField->String(record), sizeof(crdStr) - 1);
        if ((strLen = strlen(crdStr)) > 0) {
            minStr = secStr = (char *) NULL;
            for (i = 0; i < strLen; ++i)
                if (crdStr[i] == ':') minStr = crdStr + i + 1;
                else if (crdStr[i] == '\'') secStr = crdStr + i + 1;
                else if (crdStr[i] == '\"') crdStr[i] = '\0';
            if (sscanf(crdStr, "%d", &deg) != 1) continue;
            coord = (float) deg;
            if ((minStr != (char *) NULL) && (sscanf(minStr, "%d", &min) == 1)) {
                coord = coord + (deg > 0 ? 1.0 : -1.0) * (DBFloat) min / 60.0;
                if ((secStr != (char *) NULL) && (sscanf(secStr, "%d", &sec) == 1))
                    coord = coord + (deg > 0 ? 1.0 : -1.0) * (DBFloat) sec / 3600.0;
            }
            dstField->Float(record, coord);
        }
    }

    ret = (argNum > 2) && (strcmp(argv[2], "-") != 0) ? data->Write(argv[2]) : data->Write(stdout);

    delete data;
    if (verbose) RGlibPauseClose();
    return (ret);
}
Exemple #12
0
DBInt DBGridCont2Network (DBObjData *gridData,DBObjData *netData, bool downhill)

	{
	DBInt basinID, layerID, zLayerID, zLayerNum, dir, maxDir, projection = gridData->Projection (), *zones;
	DBFloat elev0, elev1, delta, maxDelta, distance;
	DBCoordinate coord0, coord1;
	DBInt row, col;
	DBPosition pos, auxPos;
	char nameSTR [DBStringLength];
	DBObjTable *basinTable = netData->Table (DBrNItems);
	DBObjTable *cellTable  = netData->Table (DBrNCells);
	DBObjTable *layerTable = netData->Table (DBrNLayers);
	DBObjRecord *layerRec, *dataRec, *cellRec, *basinRec;

	DBObjTableField *mouthPosFLD = basinTable->Field (DBrNMouthPos);
	DBObjTableField *colorFLD		= basinTable->Field (DBrNColor);

	DBObjTableField *positionFLD	= cellTable->Field (DBrNPosition);
	DBObjTableField *toCellFLD		= cellTable->Field (DBrNToCell);
	DBObjTableField *fromCellFLD	= cellTable->Field (DBrNFromCell);
	DBObjTableField *orderFLD		= cellTable->Field (DBrNOrder);
	DBObjTableField *basinFLD		= cellTable->Field (DBrNBasin);
	DBObjTableField *basinCellsFLD= cellTable->Field (DBrNBasinCells);
	DBObjTableField *travelFLD		= cellTable->Field (DBrNTravel);
	DBObjTableField *upCellPosFLD	= cellTable->Field (DBrNUpCellPos);
	DBObjTableField *cellAreaFLD	= cellTable->Field (DBrNCellArea);
	DBObjTableField *subbasinLengthFLD = cellTable->Field (DBrNSubbasinLength);
	DBObjTableField *subbasinAreaFLD = cellTable->Field (DBrNSubbasinArea);

	DBObjTableField *rowNumFLD = layerTable->Field (DBrNRowNum);
	DBObjTableField *colNumFLD = layerTable->Field (DBrNColNum);
	DBObjTableField *cellWidthFLD = layerTable->Field (DBrNCellWidth);
	DBObjTableField *cellHeightFLD = layerTable->Field (DBrNCellHeight);
	DBObjTableField *valueTypeFLD = layerTable->Field (DBrNValueType);
	DBObjTableField *valueSizeFLD = layerTable->Field (DBrNValueSize);
	DBObjTableField *layerFLD = layerTable->Field (DBrNLayer);
	DBObjData *zGridData = gridData->LinkedData ();
	DBGridIF *gridIF = new DBGridIF (gridData), *zGridIF;
	DBNetworkIF *netIF;

	if ((zGridData != (DBObjData *) NULL) && ((zGridData->Type () == DBTypeGridDiscrete) || (zGridData->Type () == DBTypeGridContinuous)))
		{
		zGridIF = new DBGridIF (zGridData);
		zLayerNum = zGridIF->LayerNum () + 1;
		}
	else { zGridIF = (DBGridIF *) NULL; zLayerNum = 1; }

	if ((zones = (DBInt *) calloc (9 * zLayerNum,sizeof (DBInt))) == (DBInt *) NULL)
		{
		CMmsgPrint (CMmsgSysError, "Memory Allocation Error in: %s %d",__FILE__,__LINE__);
		if (zGridIF != (DBGridIF *) NULL) delete zGridIF;
		delete gridIF;
		return (DBFault);
		}
	layerTable->Add (DBrNLookupGrid);
	if ((layerRec = layerTable->Item (DBrNLookupGrid)) == (DBObjRecord *) NULL)
		{
		free (zones);
		if (zGridIF != (DBGridIF *) NULL) delete zGridIF;
		delete gridIF;
		return (DBFault);
		}

	netData->Projection (projection);
	netData->Extent (gridData->Extent ());
	cellWidthFLD->Float  (layerRec,gridIF->CellWidth ());
	cellHeightFLD->Float (layerRec,gridIF->CellHeight ());
	valueTypeFLD->Int (layerRec,DBTableFieldInt);
	valueSizeFLD->Int (layerRec,sizeof (DBInt));
	rowNumFLD->Int (layerRec,gridIF->RowNum ());
	colNumFLD->Int (layerRec,gridIF->ColNum ());

	dataRec = new DBObjRecord ("NetLookupGridRecord",((size_t) gridIF->RowNum ()) * gridIF->ColNum () * sizeof (DBInt),sizeof (DBInt));
	if (dataRec == (DBObjRecord *) NULL)
		{
		if (zGridIF != (DBGridIF *) NULL) delete zGridIF;
		return (DBFault);
		}
	layerFLD->Record (layerRec,dataRec);
	(netData->Arrays ())->Add (dataRec);
	for (pos.Row = 0;pos.Row < gridIF->RowNum ();pos.Row++)
		for (pos.Col = 0;pos.Col < gridIF->ColNum ();pos.Col++)
			((DBInt *) dataRec->Data ()) [pos.Row * gridIF->ColNum () + pos.Col] = DBFault;

	for (pos.Row = 0;pos.Row < gridIF->RowNum ();pos.Row++)
		{
		if (DBPause (10 * pos.Row / gridIF->RowNum ())) goto PauseStop;
		for (pos.Col = 0;pos.Col < gridIF->ColNum ();pos.Col++)
			{
			gridIF->Pos2Coord (pos,coord0);
			zLayerID = 0;
			if (zGridIF != (DBGridIF *) NULL)
				for ( ; zLayerID < zGridIF->LayerNum (); zLayerID++)
					{
					layerRec = zGridIF->Layer (zLayerID);
					if ((layerRec->Flags () & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
					for (dir = 0;dir < 8;++dir)
						{
						row = pos.Row;
						col = pos.Col;
						if (((0x01 << dir) == DBNetDirNW) || ((0x01 << dir) == DBNetDirN) || ((0x01 << dir) == DBNetDirNE)) row++;
						if (((0x01 << dir) == DBNetDirSE) || ((0x01 << dir) == DBNetDirS) || ((0x01 << dir) == DBNetDirSW)) row--;
						if (((0x01 << dir) == DBNetDirNE) || ((0x01 << dir) == DBNetDirE) || ((0x01 << dir) == DBNetDirSE)) col++;
						if (((0x01 << dir) == DBNetDirNW) || ((0x01 << dir) == DBNetDirW) || ((0x01 << dir) == DBNetDirSW)) col--;
						if (row < 0) continue;
						if (col < 0) continue;
						if (row >= gridIF->RowNum ()) continue;
						if (col >= gridIF->ColNum ()) continue;
						auxPos.Row = row;
						auxPos.Col = col;
						gridIF->Pos2Coord (auxPos,coord1);
						switch (zGridData->Type ())
							{
							case DBTypeGridDiscrete:	basinID = zGridIF->GridValue (layerRec,coord1);	break;
							case DBTypeGridContinuous:	zGridIF->Value (layerRec,coord1,&basinID);		break;
							}
						zones [zLayerID * 9 + dir] = basinID;
						}
					switch (zGridData->Type ())
						{
						case DBTypeGridDiscrete:	basinID = zGridIF->GridValue (layerRec,coord0);	break;
						case DBTypeGridContinuous: zGridIF->Value (layerRec,coord0,&basinID);		break;
						}
					zones [zLayerID * 9 + 8] = basinID;
					}
			for (dir = 0;dir < 9;++dir) zones [zLayerID * 9 + dir] = 0;

			maxDir = DBFault;
			for (layerID = 0;layerID < gridIF->LayerNum ();++layerID)
				{
				layerRec = gridIF->Layer (layerID);
				if ((layerRec->Flags () & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
				if (gridIF->Value (layerRec,pos,&elev0))
					{
					maxDelta = (DBFloat) 0.0;
					maxDir   = 0;

					for (zLayerID = 0;zLayerID < zLayerNum;++zLayerID)
						{
						for (dir = 0;dir < 8;++dir)
							{
							row = pos.Row;
							col = pos.Col;
							if (((0x01 << dir) == DBNetDirNW) || ((0x01 << dir) == DBNetDirN) || ((0x01 << dir) == DBNetDirNE)) row++;
							if (((0x01 << dir) == DBNetDirSE) || ((0x01 << dir) == DBNetDirS) || ((0x01 << dir) == DBNetDirSW)) row--;
							if (((0x01 << dir) == DBNetDirNE) || ((0x01 << dir) == DBNetDirE) || ((0x01 << dir) == DBNetDirSE)) col++;
							if (((0x01 << dir) == DBNetDirNW) || ((0x01 << dir) == DBNetDirW) || ((0x01 << dir) == DBNetDirSW)) col--;
							if (col < 0) continue;
							if (row < 0) continue;
							if (col >= gridIF->ColNum ()) continue;
							if (row >= gridIF->RowNum ()) continue;
							auxPos.Row = row;
							auxPos.Col = col;
							gridIF->Pos2Coord (auxPos,coord1);
							distance = DBMathCoordinateDistance (projection,coord0,coord1);
							if ((zones [zLayerID * 9 + dir] == zones [zLayerID * 9 + 8]) && (gridIF->Value (layerRec,auxPos,&elev1)))
								{
								delta = (downhill ? (elev1 - elev0) : (elev0 - elev1)) / distance;
								if (maxDelta > delta) { maxDelta = delta; maxDir = (0x01 << dir); }
								}
							}
						if (maxDir != 0) goto SlopeStop;
						}
					}
				}
SlopeStop:
			if (maxDir != DBFault)
				{
				sprintf (nameSTR,"GHAASCell:%d",cellTable->ItemNum ());
				cellRec = cellTable->Add (nameSTR);
				positionFLD->Position(cellRec,pos);
				toCellFLD->Int			(cellRec,(DBInt) maxDir);
				fromCellFLD->Int		(cellRec,(DBInt) 0);
				orderFLD->Int			(cellRec,(DBInt) 0);
				basinFLD->Int			(cellRec,(DBInt) 0);
				basinCellsFLD->Int	(cellRec,(DBInt) 0);
				travelFLD->Int			(cellRec,(DBInt) 0);
				upCellPosFLD->Position	(cellRec,pos);
				cellAreaFLD->Float	(cellRec,(DBFloat) 0.0);
				subbasinLengthFLD->Float(cellRec,(DBFloat) 0.0);
				subbasinAreaFLD->Float	(cellRec,(DBFloat) 0.0);
				((DBInt *) dataRec->Data ()) [pos.Row * gridIF->ColNum () + pos.Col] = cellRec->RowID ();
				}
			}
		}
PauseStop:
	if (pos.Row < gridIF->RowNum ())	return (DBFault);
	sprintf (nameSTR,"GHAASBasin%d",(DBInt) 0);
	basinRec = basinTable->Add (nameSTR);
	mouthPosFLD->Position	(basinRec,positionFLD->Position (cellTable->Item (0)));
	colorFLD->Int				(basinRec,0);

	free (zones);
	delete gridIF;
	if (zGridIF != (DBGridIF *) NULL) delete zGridIF;

	netData->Precision (DBMathMin (gridIF->CellWidth (),gridIF->CellHeight ()) / 25.0);
	netIF = new DBNetworkIF (netData);
	netIF->Build ();
	delete netIF;
	return (DBSuccess);
	}
Exemple #13
0
DBInt RGlibPointInterStationTS(DBObjData *pntData, DBObjData *tsData, char *relateFldName, char *joinFldName) {
    DBInt first = true, tsIndex, tsRowNum = 0;
    DBObjTable *pntTBL = pntData->Table(DBrNItems), *tsTBL;
    DBObjectLIST<DBObjTableField> *fields;
    DBObjTableField *pntNextFLD = pntTBL->Field(RGlibNextStation);
    DBObjTableField *pntAreaFLD = pntTBL->Field(RGlibArea);
    DBObjTableField *pntInterStnFLD = pntTBL->Field(RGlibInterStation);
    DBObjTableField *pntRelateFLD;
    DBObjTableField *pntNewNextFLD;
    DBObjTableField *pntNewInterStnFLD;
    DBObjTableField *tsTimeFLD;
    DBObjTableField *tsJoinFLD;
    DBObjTableField *tsNextStnFLD, *tsInterStnFLD;
    DBObjRecord *pntRec, *nextPntRec, *tsRec, *tsIndexRec;
    DBDate curDate, date;

    if (pntNextFLD == (DBObjTableField *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Missing Next Station Field!");
        return (DBFault);
    }
    if (pntAreaFLD == (DBObjTableField *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Missing STN Area Field!");
        return (DBFault);
    }
    if (pntInterStnFLD == (DBObjTableField *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Missing Interfluvial Area Field!");
        return (DBFault);
    }

    tsTBL = tsData->Table(DBrNItems);
    tsNextStnFLD = new DBObjTableField(RGlibNextStation, DBTableFieldInt, "%8d", sizeof(DBInt));
    tsTBL->AddField(tsNextStnFLD);
    tsInterStnFLD = new DBObjTableField(RGlibInterStation, DBTableFieldFloat, "%9.1f", sizeof(DBFloat4));
    tsTBL->AddField(tsInterStnFLD);
    fields = tsTBL->Fields();
    for (tsTimeFLD = fields->First(); tsTimeFLD != (DBObjTableField *) NULL; tsTimeFLD = fields->Next())
        if (tsTimeFLD->Type() == DBTableFieldDate) break;
    if (tsTimeFLD == (DBObjTableField *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Missing Date Field!");
        return (DBFault);
    }
    if ((tsJoinFLD = tsTBL->Field(joinFldName)) == (DBObjTableField *) NULL) {
        CMmsgPrint(CMmsgUsrError, "Missing Join Field!");
        return (DBFault);
    }
    fields = new DBObjectLIST<DBObjTableField>("Field List");
    fields->Add(new DBObjTableField(*tsTimeFLD));
    fields->Add(new DBObjTableField(*tsJoinFLD));
    tsTBL->ListSort(fields);
    delete fields;

    pntTBL = new DBObjTable(*pntTBL);
    pntNextFLD = pntTBL->Field(RGlibNextStation);
    pntAreaFLD = pntTBL->Field(RGlibArea);
    pntInterStnFLD = pntTBL->Field(RGlibInterStation);
    pntNewNextFLD = new DBObjTableField("NextStnTS", pntNextFLD->Type(), pntNextFLD->Format(), pntNextFLD->Length());
    pntNewInterStnFLD = new DBObjTableField("InterFluTS", pntInterStnFLD->Type(), pntInterStnFLD->Format(),
                                            pntInterStnFLD->Length());
    pntRelateFLD = pntTBL->Field(relateFldName);
    pntTBL->AddField(pntNewNextFLD);
    pntTBL->AddField(pntNewInterStnFLD);
    pntTBL->ListSort(pntRelateFLD);

    tsIndexRec = tsTBL->First(&tsIndex);
    for (tsRec = tsTBL->First(); tsRec != (DBObjRecord *) NULL; tsRec = tsTBL->Next()) {
        DBPause(tsRowNum++ * 100 / tsTBL->ItemNum());
        date = tsTimeFLD->Date(tsRec);
        if (date != curDate) {
            if (first) first = false;
            else {
                for (pntRec = pntTBL->First(); pntRec != (DBObjRecord *) NULL; pntRec = pntTBL->Next()) {
                    if ((pntRec->Flags() & DBObjectFlagLocked) != DBObjectFlagLocked) continue;
                    for (nextPntRec = pntTBL->Item(pntNextFLD->Int(pntRec) - 1);
                         (nextPntRec != (DBObjRecord *) NULL) &&
                         ((nextPntRec->Flags() & DBObjectFlagLocked) != DBObjectFlagLocked);
                         nextPntRec = pntTBL->Item(pntNextFLD->Int(nextPntRec) - 1));
                    if (nextPntRec != (DBObjRecord *) NULL) {
                        pntNewNextFLD->Int(pntRec, nextPntRec->RowID() + 1);
                        pntNewInterStnFLD->Float(nextPntRec,
                                                 pntNewInterStnFLD->Float(nextPntRec) - pntAreaFLD->Float(pntRec));
                    }
                }
                pntRec = pntTBL->First();
                for (; tsIndexRec != (DBObjRecord *) NULL; tsIndexRec = tsTBL->Next(&tsIndex)) {
                    if (tsRec == tsIndexRec) break;
                    for (; pntRec != (DBObjRecord *) NULL; pntRec = pntTBL->Next())
                        if (pntRelateFLD->Int(pntRec) == tsJoinFLD->Int(tsIndexRec)) {
                            tsNextStnFLD->Int(tsIndexRec, pntNewNextFLD->Int(pntRec));
                            tsInterStnFLD->Float(tsIndexRec, pntNewInterStnFLD->Float(pntRec));
                            break;
                        }
                    if (pntRec == (DBObjRecord *) NULL) pntRec = pntTBL->First();
                }
            }
            for (pntRec = pntTBL->First(); pntRec != (DBObjRecord *) NULL; pntRec = pntTBL->Next()) {
                pntNewNextFLD->Int(pntRec, 0);
                pntNewInterStnFLD->Float(pntRec, pntAreaFLD->Float(pntRec));
                pntRec->Flags(DBObjectFlagLocked, DBClear);
            }
            curDate = date;
            pntRec = pntTBL->First();
        }
        for (; pntRec != (DBObjRecord *) NULL; pntRec = pntTBL->Next())
            if (pntRelateFLD->Int(pntRec) == tsJoinFLD->Int(tsRec)) {
                pntRec->Flags(DBObjectFlagLocked, DBSet);
                break;
            }
        if (pntRec == (DBObjRecord *) NULL) pntRec = pntTBL->First();
    }
    if (!first) {
        for (pntRec = pntTBL->First(); pntRec != (DBObjRecord *) NULL; pntRec = pntTBL->Next()) {
            if ((pntRec->Flags() & DBObjectFlagLocked) != DBObjectFlagLocked) continue;
            for (nextPntRec = pntTBL->Item(pntNextFLD->Int(pntRec) - 1);
                 (nextPntRec != (DBObjRecord *) NULL) &&
                 ((nextPntRec->Flags() & DBObjectFlagLocked) != DBObjectFlagLocked);
                 nextPntRec = pntTBL->Item(pntNextFLD->Int(nextPntRec) - 1));
            if (nextPntRec != (DBObjRecord *) NULL) {
                pntNewNextFLD->Int(pntRec, nextPntRec->RowID() + 1);
                pntNewInterStnFLD->Float(nextPntRec, pntNewInterStnFLD->Float(nextPntRec) - pntAreaFLD->Float(pntRec));
            }
        }
        pntRec = pntTBL->First();
        for (; tsIndexRec != (DBObjRecord *) NULL; tsIndexRec = tsTBL->Next(&tsIndex)) {
            if (tsRec == tsIndexRec) break;
            for (; pntRec != (DBObjRecord *) NULL; pntRec = pntTBL->Next())
                if (pntRelateFLD->Int(pntRec) == tsJoinFLD->Int(tsIndexRec)) {
                    tsNextStnFLD->Int(tsIndexRec, pntNewNextFLD->Int(pntRec));
                    tsInterStnFLD->Float(tsIndexRec, pntNewInterStnFLD->Float(pntRec));
                    break;
                }
            if (pntRec == (DBObjRecord *) NULL) pntRec = pntTBL->First();
        }
    }
    delete pntTBL;
    return (DBSuccess);
}
Exemple #14
0
void DBGridIF::Initialize(DBObjData *data, bool flat) {
    DBObjTableField *rowNumFLD;
    DBObjTableField *colNumFLD;
    DBObjTableField *cellWidthFLD;
    DBObjTableField *cellHeightFLD;
    DBObjTableField *valueTypeFLD;
    DBObjTableField *valueSizeFLD;
    DBObjRecord *layerRec;

    DataPTR = data;
    ItemTable = data->Table(DBrNItems);
    switch (data->Type()) {
        case DBTypeGridDiscrete:
            SymbolTable = data->Table(DBrNSymbols);
            AverageFLD = (DBObjTableField *) NULL;
            StdDevFLD = (DBObjTableField *) NULL;
            MinimumFLD = (DBObjTableField *) NULL;
            MaximumFLD = (DBObjTableField *) NULL;
            MissingValueFLD = (DBObjTableField *) NULL;
            GridValueFLD = ItemTable->Field(DBrNGridValue);
            SymbolFLD = ItemTable->Field(DBrNSymbol);
            SymbolIDFLD = SymbolTable->Field(DBrNSymbolID);
            ForegroundFLD = SymbolTable->Field(DBrNForeground);
            BackgroundFLD = SymbolTable->Field(DBrNBackground);
            StyleFLD = SymbolTable->Field(DBrNStyle);
            break;
        case DBTypeGridContinuous:
            SymbolTable = (DBObjTable *) NULL;
            AverageFLD = ItemTable->Field(DBrNAverage);
            StdDevFLD = ItemTable->Field(DBrNStdDev);
            MinimumFLD = ItemTable->Field(DBrNMinimum);
            MaximumFLD = ItemTable->Field(DBrNMaximum);
            MissingValueFLD = ItemTable->Field(DBrNMissingValue);
            SymbolFLD = (DBObjTableField *) NULL;
            SymbolIDFLD = (DBObjTableField *) NULL;
            ForegroundFLD = (DBObjTableField *) NULL;
            BackgroundFLD = (DBObjTableField *) NULL;
            StyleFLD = (DBObjTableField *) NULL;
            break;
        default:
            CMmsgPrint(CMmsgAppError, "Invalid Data Type in: %s %d", __FILE__, __LINE__);
            break;
    }
    LayerTable = data->Table(DBrNLayers);
    LayerFLD = LayerTable->Field(DBrNLayer);
    rowNumFLD = LayerTable->Field(DBrNRowNum);
    colNumFLD = LayerTable->Field(DBrNColNum);
    cellWidthFLD = LayerTable->Field(DBrNCellWidth);
    cellHeightFLD = LayerTable->Field(DBrNCellHeight);
    valueTypeFLD = LayerTable->Field(DBrNValueType);
    valueSizeFLD = LayerTable->Field(DBrNValueSize);

    layerRec = LayerTable->Item();
    DimensionVAR.Row = rowNumFLD->Int(layerRec);
    DimensionVAR.Col = colNumFLD->Int(layerRec);
    CellWidthVAR = cellWidthFLD->Float(layerRec);
    CellHeightVAR = cellHeightFLD->Float(layerRec);
    ValueTypeVAR = valueTypeFLD->Int(layerRec);
    ValueSizeVAR = valueSizeFLD->Int(layerRec);
    Flat = flat;
}
Exemple #15
0
DBInt RGlibRGIS2DataStream(DBObjData *grdData, DBObjData *tmplData, char *fieldName, FILE *outFile) {
    DBInt layerID, ret = DBSuccess, itemSize, itemID;
    DBInt intValue;
    DBFloat floatValue;
    void *data;
    MFVarHeader_t varHeader;
    DBObjRecord *layerRec, *gridRec;
    DBObjTableField *fieldPTR = (DBObjTableField *) NULL;
    DBGridIF *gridIF;
    DBVPointIF *tmplPntIF = (DBVPointIF *) NULL;
    DBGridIF *tmplGrdIF = (DBGridIF *) NULL;
    DBNetworkIF *tmplNetIF = (DBNetworkIF *) NULL;

    gridIF = new DBGridIF(grdData);

    varHeader.Swap = 1;
    if (grdData->Type() == DBTypeGridDiscrete) {
        DBObjTable *itemTable = grdData->Table(DBrNItems);

        if (fieldName == (char *) NULL) fieldName = DBrNGridValue;
        if ((fieldPTR = itemTable->Field(fieldName)) == (DBObjTableField *) NULL) {
            CMmsgPrint(CMmsgAppError, "Error: Invalid field [%s] in: %s %d", fieldName, __FILE__, __LINE__);
            return (DBFault);
        }
        itemSize = fieldPTR->Length();
        switch (fieldPTR->Type()) {
            case DBTableFieldInt:
                switch (itemSize) {
                    default:
                    case sizeof(DBByte):
                        varHeader.DataType = MFByte;
                        break;
                    case sizeof(DBShort):
                        varHeader.DataType = MFShort;
                        break;
                    case sizeof(DBInt):
                        varHeader.DataType = MFInt;
                        break;
                }
                varHeader.Missing.Int = fieldPTR->IntNoData();
                break;
            case DBTableFieldFloat:
                switch (itemSize) {
                    default:
                    case sizeof(DBFloat4):
                        varHeader.DataType = MFFloat;
                        break;
                    case sizeof(DBFloat):
                        varHeader.DataType = MFDouble;
                        break;
                }
                varHeader.Missing.Float = fieldPTR->FloatNoData();
                break;
        }
    }
    else {
        if (fieldName != (char *) NULL) CMmsgPrint(CMmsgUsrError, "Warning: Fieldname ignored for continuous grid!");
        itemSize = gridIF->ValueSize();
        switch (gridIF->ValueType()) {
            case DBVariableInt:
                switch (itemSize) {
                    case 1:
                        varHeader.DataType = MFByte;
                        break;
                    case 2:
                        varHeader.DataType = MFShort;
                        break;
                    case 4:
                        varHeader.DataType = MFInt;
                        break;
                }
                varHeader.Missing.Int = (int) gridIF->MissingValue();
                break;
            case DBVariableFloat:
                switch (itemSize) {
                    case 4:
                        varHeader.DataType = MFFloat;
                        break;
                    case 8:
                        varHeader.DataType = MFDouble;
                        break;
                }
                varHeader.Missing.Float = gridIF->MissingValue();
                break;
        }
    }

    if (tmplData == (DBObjData *) NULL) {
        tmplGrdIF = gridIF;
        varHeader.ItemNum = gridIF->RowNum() * gridIF->ColNum();
    }
    else {
        switch (tmplData->Type()) {
            case DBTypeVectorPoint:
                tmplPntIF = new DBVPointIF(tmplData);
                varHeader.ItemNum = tmplPntIF->ItemNum();
                break;
            case DBTypeGridContinuous:
            case DBTypeGridDiscrete:
                tmplGrdIF = new DBGridIF(tmplData);
                varHeader.ItemNum = gridIF->RowNum() * gridIF->ColNum();
                break;
            case DBTypeNetwork:
                tmplNetIF = new DBNetworkIF(tmplData);
                varHeader.ItemNum = tmplNetIF->CellNum();
                break;
            default:
                delete gridIF;
                return (DBFault);
        }
    }
    if ((data = (void *) calloc(varHeader.ItemNum, itemSize)) == (void *) NULL) {
        CMmsgPrint(CMmsgSysError, "Error! Allocating %d items of %d size in: %s %d", varHeader.ItemNum, itemSize,
                   __FILE__, __LINE__);
        return (DBFault);
    }

/**************************************************************
*                                                             *
* Point template                                              *
*                                                             *
**************************************************************/

    if (tmplPntIF != (DBVPointIF *) NULL) {
        DBObjRecord *pntRec;

        if (fieldPTR == (DBObjTableField *) NULL) {
            for (layerID = 0; layerID < gridIF->LayerNum(); ++layerID) {
                layerRec = gridIF->Layer(layerID);
                strncpy(varHeader.Date, layerRec->Name(), MFDateStringLength - 1);
                for (itemID = 0; itemID < varHeader.ItemNum; ++itemID) {
                    pntRec = tmplPntIF->Item(itemID);
                    if ((varHeader.DataType == MFByte) || (varHeader.DataType == MFShort) ||
                        (varHeader.DataType == MFInt)) {
                        if (gridIF->Value(layerRec, tmplPntIF->Coordinate(pntRec), &intValue) == false)
                            intValue = varHeader.Missing.Int;
                        switch (varHeader.DataType) {
                            case MFByte:
                                ((char *) data)[itemID] = (char) intValue;
                                break;
                            case MFShort:
                                ((short *) data)[itemID] = (short) intValue;
                                break;
                            case MFInt:
                                ((int *) data)[itemID] = (short) intValue;
                                break;
                        }
                    }
                    else {
                        if (gridIF->Value(layerRec, tmplPntIF->Coordinate(pntRec), &floatValue) == false)
                            floatValue = varHeader.Missing.Float;
                        switch (varHeader.DataType) {
                            case MFFloat:
                                ((float *) data)[itemID] = (float) floatValue;
                                break;
                            case MFDouble:
                                ((double *) data)[itemID] = (double) floatValue;
                                break;
                        }
                    }
                }
                if ((DBInt) fwrite(&varHeader, sizeof(MFVarHeader_t), 1, outFile) != 1) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing record header in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
                if ((DBInt) fwrite(data, itemSize, varHeader.ItemNum, outFile) != varHeader.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing data in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
            }
        }
        else {
            for (layerID = 0; layerID < gridIF->LayerNum(); ++layerID) {
                layerRec = gridIF->Layer(layerID);
                strncpy(varHeader.Date, layerRec->Name(), MFDateStringLength - 1);
                for (itemID = 0; itemID < varHeader.ItemNum; ++itemID) {
                    pntRec = tmplPntIF->Item(itemID);
                    gridRec = gridIF->GridItem(layerRec, tmplPntIF->Coordinate(pntRec));
                    switch (varHeader.DataType) {
                        case MFByte:
                            ((char *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->IntNoData();
                            break;
                        case MFShort:
                            ((short *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->IntNoData();
                            break;
                        case MFInt:
                            ((int *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->IntNoData();
                            break;
                        case MFFloat:
                            ((float *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->FloatNoData();
                            break;
                        case MFDouble:
                            ((double *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->FloatNoData();
                            break;
                    }
                }
                if ((DBInt) fwrite(&varHeader, sizeof(MFVarHeader_t), 1, outFile) != 1) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing record header in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
                if ((DBInt) fwrite(data, itemSize, varHeader.ItemNum, outFile) != varHeader.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing data in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
            }
        }
        delete tmplPntIF;
    }

/**************************************************************
*                                                             *
* Grid Template (default when no template coverage is given.  *
*                                                             *
**************************************************************/
    else if (tmplGrdIF != (DBGridIF *) NULL) {
        DBPosition pos;
        DBCoordinate coord;

        if (fieldPTR == (DBObjTableField *) NULL) {
            for (layerID = 0; layerID < gridIF->LayerNum(); ++layerID) {
                layerRec = gridIF->Layer(layerID);
                strncpy(varHeader.Date, layerRec->Name(), MFDateStringLength - 1);
                for (pos.Row = 0; pos.Row < tmplGrdIF->RowNum(); ++pos.Row)
                    for (pos.Col = 0; pos.Col < tmplGrdIF->ColNum(); ++pos.Col) {
                        itemID = pos.Row * tmplGrdIF->ColNum() + pos.Col;
                        if ((varHeader.DataType == MFByte) || (varHeader.DataType == MFShort) ||
                            (varHeader.DataType == MFInt)) {
                            if (tmplGrdIF != gridIF) {
                                tmplGrdIF->Pos2Coord(pos, coord);
                                if (gridIF->Value(layerRec, coord, &intValue) == false)
                                    intValue = varHeader.Missing.Int;
                            }
                            else {
                                if (gridIF->Value(layerRec, pos, &intValue) == false) intValue = varHeader.Missing.Int;
                            }
                            switch (varHeader.DataType) {
                                case MFByte:
                                    ((char *) data)[itemID] = (char) intValue;
                                    break;
                                case MFShort:
                                    ((short *) data)[itemID] = (short) intValue;
                                    break;
                                case MFInt:
                                    ((int *) data)[itemID] = (short) intValue;
                                    break;
                            }
                        }
                        else {
                            if (tmplGrdIF != gridIF) {
                                tmplGrdIF->Pos2Coord(pos, coord);
                                if (gridIF->Value(layerRec, coord, &floatValue) == false)
                                    floatValue = varHeader.Missing.Float;
                            }
                            else {
                                if (gridIF->Value(layerRec, pos, &floatValue) == false)
                                    floatValue = varHeader.Missing.Float;
                            }
                            switch (varHeader.DataType) {
                                case MFFloat:
                                    ((float *) data)[itemID] = (float) floatValue;
                                    break;
                                case MFDouble:
                                    ((double *) data)[itemID] = (double) floatValue;
                                    break;
                            }
                        }
                    }
                if ((DBInt) fwrite(&varHeader, sizeof(MFVarHeader_t), 1, outFile) != 1) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing record header in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
                if ((DBInt) fwrite(data, itemSize, varHeader.ItemNum, outFile) != varHeader.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing data in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
            }
        }
        else {
            for (layerID = 0; layerID < gridIF->LayerNum(); ++layerID) {
                layerRec = gridIF->Layer(layerID);
                strncpy(varHeader.Date, layerRec->Name(), MFDateStringLength - 1);
                for (pos.Row = 0; pos.Row < tmplGrdIF->RowNum(); ++pos.Row)
                    for (pos.Col = 0; pos.Col < tmplGrdIF->ColNum(); ++pos.Col) {
                        itemID = pos.Row * tmplGrdIF->ColNum() + pos.Col;
                        if (tmplGrdIF != gridIF) {
                            tmplGrdIF->Pos2Coord(pos, coord);
                            gridRec = gridIF->GridItem(layerRec, coord);
                        }
                        else gridRec = gridIF->GridItem(layerRec, pos);
                        switch (varHeader.DataType) {
                            case MFByte:
                                ((char *) data)[itemID] = gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec)
                                                                                          : fieldPTR->IntNoData();
                                break;
                            case MFShort:
                                ((short *) data)[itemID] = gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec)
                                                                                           : fieldPTR->IntNoData();
                                break;
                            case MFInt:
                                ((int *) data)[itemID] = gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec)
                                                                                         : fieldPTR->IntNoData();
                                break;
                            case MFFloat:
                                ((float *) data)[itemID] = gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec)
                                                                                           : fieldPTR->FloatNoData();
                                break;
                            case MFDouble:
                                ((double *) data)[itemID] = gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec)
                                                                                            : fieldPTR->FloatNoData();
                                break;
                        }
                    }
                if ((DBInt) fwrite(&varHeader, sizeof(MFVarHeader_t), 1, outFile) != 1) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing record header in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
                if ((DBInt) fwrite(data, itemSize, varHeader.ItemNum, outFile) != varHeader.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing data in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
            }
        }
        if (tmplGrdIF != gridIF) delete tmplGrdIF;
    }

/**************************************************************
*                                                             *
* Network Template                                            *
*                                                             *
**************************************************************/
    else if (tmplNetIF != (DBNetworkIF *) NULL) {
        DBObjRecord *cellRec;

        if (fieldPTR == (DBObjTableField *) NULL) {
            for (layerID = 0; layerID < gridIF->LayerNum(); ++layerID) {
                layerRec = gridIF->Layer(layerID);
                strncpy(varHeader.Date, layerRec->Name(), MFDateStringLength - 1);
                for (itemID = 0; itemID < varHeader.ItemNum; ++itemID) {
                    cellRec = tmplNetIF->Cell(itemID);
                    if ((varHeader.DataType == MFByte) || (varHeader.DataType == MFShort) ||
                        (varHeader.DataType == MFInt)) {
                        if (gridIF->Value(layerRec, tmplNetIF->Center(cellRec), &intValue) == false)
                            intValue = varHeader.Missing.Int;
                        switch (varHeader.DataType) {
                            case MFByte:
                                ((char *) data)[itemID] = (char) intValue;
                                break;
                            case MFShort:
                                ((short *) data)[itemID] = (short) intValue;
                                break;
                            case MFInt:
                                ((int *) data)[itemID] = (short) intValue;
                                break;
                        }
                    }
                    else {
                        if (gridIF->Value(layerRec, tmplNetIF->Center(cellRec), &floatValue) == false)
                            floatValue = varHeader.Missing.Float;
                        switch (varHeader.DataType) {
                            case MFFloat:
                                ((float *) data)[itemID] = (float) floatValue;
                                break;
                            case MFDouble:
                                ((double *) data)[itemID] = (double) floatValue;
                                break;
                        }
                    }
                }
                if ((DBInt) fwrite(&varHeader, sizeof(MFVarHeader_t), 1, outFile) != 1) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing record header in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
                if ((DBInt) fwrite(data, itemSize, varHeader.ItemNum, outFile) != varHeader.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing data in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
            }
        }
        else {
            for (layerID = 0; layerID < gridIF->LayerNum(); ++layerID) {
                layerRec = gridIF->Layer(layerID);
                strncpy(varHeader.Date, layerRec->Name(), MFDateStringLength - 1);
                for (itemID = 0; itemID < varHeader.ItemNum; ++itemID) {
                    cellRec = tmplNetIF->Cell(itemID);
                    gridRec = gridIF->GridItem(layerRec, tmplNetIF->Center(cellRec));
                    switch (varHeader.DataType) {
                        case MFByte:
                            ((char *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->IntNoData();
                            break;
                        case MFShort:
                            ((short *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->IntNoData();
                            break;
                        case MFInt:
                            ((int *) data)[itemID] =
                                    gridRec != (DBObjRecord *) NULL ? fieldPTR->Int(gridRec) : fieldPTR->IntNoData();
                            break;
                        case MFFloat:
                            ((float *) data)[itemID] = gridRec != (DBObjRecord *) NULL ? fieldPTR->Float(gridRec)
                                                                                       : fieldPTR->FloatNoData();
                            break;
                        case MFDouble:
                            ((double *) data)[itemID] = gridRec != (DBObjRecord *) NULL ? fieldPTR->Float(gridRec)
                                                                                        : fieldPTR->FloatNoData();
                            break;
                    }
                }
                if ((DBInt) fwrite(&varHeader, sizeof(MFVarHeader_t), 1, outFile) != 1) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing record header in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
                if ((DBInt) fwrite(data, itemSize, varHeader.ItemNum, outFile) != varHeader.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Writing data in: %s %d", __FILE__, __LINE__);
                    ret = DBFault;
                    break;
                }
            }
        }
        delete tmplNetIF;
    }

    free(data);
    delete gridIF;
    return (ret);
}
Exemple #16
0
DBInt RGlibDataStream2RGIS(DBObjData *outData, DBObjData *tmplData, FILE *inFile) {
    DBInt layerID = 0, itemSize;
    DBPosition pos;
    DBFloat val;
    void *data = (void *) NULL;
    MFVarHeader_t header;
    DBObjRecord *record;


    switch (tmplData->Type()) {
        case DBTypeVectorPoint: {
            DBInt itemID;
            DBDate date;
            DBObjTable *itemTable = outData->Table(DBrNItems);
            DBObjTableField *idField = new DBObjTableField("ItemID", DBTableFieldInt, "%6d", sizeof(DBInt), false);
            DBObjTableField *dateField = new DBObjTableField("Date", DBTableFieldDate, "%s", sizeof(DBDate), false);
            DBObjTableField *valField;
            DBVPointIF *pntIF = new DBVPointIF(tmplData);

            itemTable->AddField(idField);
            itemTable->AddField(dateField);

            while (MFVarReadHeader(&header, inFile)) {
                if (header.ItemNum != pntIF->ItemNum()) {
                    CMmsgPrint(CMmsgUsrError, "Error: Datastream inconsistency %d %d!", header.ItemNum,
                               pntIF->ItemNum());
                    return (DBFault);
                }
                if (data == (void *) NULL) {
                    itemSize = MFVarItemSize(header.DataType);
                    if ((data = (void *) realloc(data, header.ItemNum * itemSize)) == (void *) NULL) {
                        CMmsgPrint(CMmsgSysError, "Memory allocation error in: %s %d", __FILE__, __LINE__);
                        return (DBFault);
                    }
                    switch (header.DataType) {
                        case MFByte:
                            valField = new DBObjTableField("Value", DBTableFieldInt, "%2d", sizeof(char), false);
                        case MFShort:
                            valField = new DBObjTableField("Value", DBTableFieldInt, "%4d", sizeof(DBShort), false);
                        case MFInt:
                            valField = new DBObjTableField("Value", DBTableFieldInt, "%8d", sizeof(DBInt), false);
                        case MFFloat:
                            valField = new DBObjTableField("Value", DBTableFieldFloat, "%8.2f", sizeof(DBFloat4),
                                                           false);
                        case MFDouble:
                            valField = new DBObjTableField("Value", DBTableFieldFloat, "%8.2f", sizeof(DBFloat), false);
                    }
                    itemTable->AddField(valField);
                }
                if ((int) fread(data, itemSize, header.ItemNum, inFile) != header.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Data stream read in: %s %d", __FILE__, __LINE__);
                    return (DBFault);
                }
                for (itemID = 0; itemID < header.ItemNum; ++itemID) {
                    record = itemTable->Add(header.Date);
                    date.Set(header.Date);
                    idField->Int(record, itemID);
                    dateField->Date(record, date);
/*					decDateField->Float (record,date);
*/                    switch (header.DataType) {
                        case MFByte:
                            valField->Int(record, ((char *) data)[itemID]);
                            break;
                        case MFShort:
                            valField->Int(record, ((short *) data)[itemID]);
                            break;
                        case MFInt:
                            valField->Int(record, ((int *) data)[itemID]);
                            break;
                        case MFFloat:
                            valField->Float(record, ((float *) data)[itemID]);
                            break;
                        case MFDouble:
                            valField->Float(record, ((double *) data)[itemID]);
                            break;
                    }
                }
            }
            delete pntIF;
        }
            break;
        case DBTypeGridContinuous:
        case DBTypeGridDiscrete: {
            DBGridIF *gridIF = new DBGridIF(outData);

            while (MFVarReadHeader(&header, inFile)) {
                if (header.ItemNum != gridIF->RowNum() * gridIF->ColNum()) {
                    CMmsgPrint(CMmsgUsrError, "Error: Datastream inconsistency!");
                    return (DBFault);
                }
                if (layerID == 0) {
                    itemSize = MFVarItemSize(header.DataType);
                    if ((data = (void *) realloc(data, header.ItemNum * itemSize)) == (void *) NULL) {
                        CMmsgPrint(CMmsgSysError, "Memory allocation error in: %s %d", __FILE__, __LINE__);
                        return (DBFault);
                    }
                    record = gridIF->Layer(layerID);
                    gridIF->RenameLayer(header.Date);
                }
                else record = gridIF->AddLayer(header.Date);

                switch (header.DataType) {
                    case MFByte:
                    case MFShort:
                    case MFInt:
                        gridIF->MissingValue(record, header.Missing.Int);
                        break;
                    case MFFloat:
                    case MFDouble:
                        gridIF->MissingValue(record, header.Missing.Float);
                        break;
                }
                if ((int) fread(data, itemSize, header.ItemNum, inFile) != header.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Data stream read in: %s %d", __FILE__, __LINE__);
                    return (DBFault);
                }

                for (pos.Row = 0; pos.Row < gridIF->RowNum(); ++pos.Row)
                    for (pos.Col = 0; pos.Col < gridIF->ColNum(); ++pos.Col) {
                        switch (header.DataType) {
                            case MFByte:
                                val = (DBFloat) (((char *) data)[pos.Row * gridIF->ColNum() + pos.Col]);
                                break;
                            case MFShort:
                                val = (DBFloat) (((short *) data)[pos.Row * gridIF->ColNum() + pos.Col]);
                                break;
                            case MFInt:
                                val = (DBFloat) (((int *) data)[pos.Row * gridIF->ColNum() + pos.Col]);
                                break;
                            case MFFloat:
                                val = (DBFloat) (((float *) data)[pos.Row * gridIF->ColNum() + pos.Col]);
                                break;
                            case MFDouble:
                                val = (DBFloat) (((double *) data)[pos.Row * gridIF->ColNum() + pos.Col]);
                                break;
                        }
                        gridIF->Value(record, pos, val);
                    }
                layerID++;
            }
            gridIF->RecalcStats();
        }
            break;
        case DBTypeNetwork: {
            DBInt cellID;
            DBGridIF *gridIF = new DBGridIF(outData);
            DBNetworkIF *netIF = new DBNetworkIF(tmplData);

            while (MFVarReadHeader(&header, inFile)) {
                if (header.ItemNum != netIF->CellNum()) {
                    CMmsgPrint(CMmsgUsrError, "Error: Datastream inconsistency!");
                    return (DBFault);
                }
                if (layerID == 0) {
                    itemSize = MFVarItemSize(header.DataType);
                    if ((data = (void *) realloc(data, header.ItemNum * itemSize)) == (void *) NULL) {
                        CMmsgPrint(CMmsgSysError, "Memory allocation error in: %s %d", __FILE__, __LINE__);
                        return (DBFault);
                    }
                    record = gridIF->Layer(layerID);
                    gridIF->RenameLayer(header.Date);
                }
                else record = gridIF->AddLayer(header.Date);
                if ((int) fread(data, itemSize, header.ItemNum, inFile) != header.ItemNum) {
                    CMmsgPrint(CMmsgSysError, "Error: Data stream read in: %s %d", __FILE__, __LINE__);
                    delete netIF;
                    return (DBFault);
                }

                for (pos.Row = 0; pos.Row < gridIF->RowNum(); ++pos.Row)
                    for (pos.Col = 0; pos.Col < gridIF->ColNum(); ++pos.Col)
                        gridIF->Value(record, pos, gridIF->MissingValue());

                for (cellID = 0; cellID < netIF->CellNum(); ++cellID) {
                    pos = netIF->CellPosition(netIF->Cell(cellID));

                    switch (header.DataType) {
                        case MFByte:
                            val = (DBFloat) (((char *) data)[cellID]);
                            break;
                        case MFShort:
                            val = (DBFloat) (((short *) data)[cellID]);
                            break;
                        case MFInt:
                            val = (DBFloat) (((int *) data)[cellID]);
                            break;
                        case MFFloat:
                            val = (DBFloat) (((float *) data)[cellID]);
                            break;
                        case MFDouble:
                            val = (DBFloat) (((double *) data)[cellID]);
                            break;
                    }
                    gridIF->Value(record, pos, val);
                }
                layerID++;
            }
            gridIF->RecalcStats();
        }
            break;
    }
    return (DBSuccess);
}
Exemple #17
0
void RGISAnalyseLineMSampleGridCBK (Widget widget, RGISWorkspace *workspace,XmAnyCallbackStruct *callData)

	{
	DBInt layerID, layerNum;
	DBCoordinate coord;
	DBFloat realValue;
	DBDataset *dataset  = UIDataset ();
	DBObjData *dbData  = dataset->Data ();
	DBObjData *grdData  = dbData->LinkedData ();
	DBObjData *tblData;
	DBObjTable *table, *itemTable = dbData->Table (DBrNItems);
	DBObjTableField *lineIDFLD;
	DBObjTableField *layerIDFLD;
	DBObjTableField *layerNameFLD;
	DBObjTableField *fromValueFLD = (DBObjTableField *) NULL;
	DBObjTableField *toValueFLD = (DBObjTableField *) NULL;
	DBVLineIF	*lineIF = (DBVLineIF *)	 NULL;
	DBGridIF *gridIF;
	DBObjRecord *record, *layerRec, *tblRec;
	DBObjectLIST<DBObjTableField> *fields;

	widget = widget; callData = callData;

	gridIF = new DBGridIF (grdData);
	for (layerID = 0;layerID < gridIF->LayerNum ();++layerID)
		{
		layerRec = gridIF->Layer (layerID);
		if ((layerRec->Flags () & DBObjectFlagIdle) != DBObjectFlagIdle) ++layerNum;
		}
	if (layerNum < 1)
		{ CMmsgPrint (CMmsgAppError, "No Layer to Process in: %s %d",__FILE__,__LINE__); delete gridIF; return; }


	tblData  = new DBObjData ("",DBTypeTable);
	tblData->Document (DBDocGeoDomain,dbData->Document (DBDocGeoDomain));
	tblData->Document (DBDocSubject,grdData->Document (DBDocSubject));

	if (UIDataHeaderForm (tblData) == false) { delete gridIF; delete tblData; return; }
	table = tblData->Table (DBrNItems);

	lineIF = new DBVLineIF (dbData);

	table->AddField (lineIDFLD =		new DBObjTableField ("GHAASPointID",DBTableFieldInt,	"%8d",sizeof (DBInt)));
	table->AddField (layerIDFLD =		new DBObjTableField ("LayerID",		DBTableFieldInt,	"%4d",sizeof (DBShort)));
	table->AddField (layerNameFLD =	new DBObjTableField ("LayerName",	DBTableFieldString,"%s",DBStringLength));
	table->AddField (fromValueFLD =	new DBObjTableField (RGISLineFromNodeValue,DBTableFieldFloat,gridIF->ValueFormat (),sizeof (DBFloat4)));
	table->AddField (toValueFLD =		new DBObjTableField (RGISLineToNodeValue,DBTableFieldFloat,gridIF->ValueFormat (),sizeof (DBFloat4)));

	grdData->Flags (DBObjectFlagProcessed,DBSet);
	UIPauseDialogOpen ((char *) "Sampling Grid(s)");
	for (layerID = 0;layerID < gridIF->LayerNum ();++layerID)
		{
		layerRec = gridIF->Layer (layerID);
		if ((layerRec->Flags () & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
		for (record = itemTable->First ();record != (DBObjRecord *) NULL;record = itemTable->Next ())
			{
			if (UIPause ((layerRec->RowID () * itemTable->ItemNum () + record->RowID ()) * 100 / (itemTable->ItemNum () * gridIF->LayerNum ()))) goto Stop;
			if ((record->Flags () & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
			tblRec = table->Add (record->Name ());
			lineIDFLD->Int (tblRec,record->RowID () + 1);
			layerIDFLD->Int (tblRec,layerRec->RowID ());
			layerNameFLD->String (tblRec,layerRec->Name ());
			coord = lineIF->FromCoord (record);
			if (gridIF->Value (layerRec,coord,&realValue))
				fromValueFLD->Float (tblRec,realValue);
			coord = lineIF->ToCoord (record);
			if (gridIF->Value (layerRec,coord,&realValue))
				toValueFLD->Float (tblRec,realValue);
			}
		}
Stop:
	UIPauseDialogClose ();
	delete gridIF;
	delete lineIF;

	fields = new DBObjectLIST<DBObjTableField> ("Field List");
	fields->Add (new DBObjTableField (*lineIDFLD));
	fields->Add (new DBObjTableField (*layerIDFLD));
	table->ListSort (fields);
	workspace->CurrentData  (tblData);
	delete fields;
	}
Exemple #18
0
DBInt RGlibPointSubbasinStats(DBObjData *pntData, DBObjData *netData, DBObjData *grdData, DBObjData *tblData) {
    DBInt layerID, layerNum = 0, progress = 0, maxProgress;
    DBObjTable *table;
    DBObjTableField *pointIDFLD;
    DBObjTableField *layerIDFLD;
    DBObjTableField *layerNameFLD;
    DBObjTableField *minimumFLD;
    DBObjTableField *maximumFLD;
    DBObjTableField *averageFLD;
    DBObjTableField *stdDevFLD;
    DBObjTableField *areaFLD;
    DBVPointIF *pntIF;
    DBNetworkIF *netIF;
    DBObjRecord *pntRec, *tblRec;
    DBObjectLIST<DBObjTableField> *fields;

    _RGlibPointGrdIF = new DBGridIF(grdData);
    for (layerID = 0; layerID < _RGlibPointGrdIF->LayerNum(); ++layerID) {
        _RGlibPointGrdLayerRec = _RGlibPointGrdIF->Layer(layerID);
        if ((_RGlibPointGrdLayerRec->Flags() & DBObjectFlagIdle) != DBObjectFlagIdle) ++layerNum;
    }
    if (layerNum < 1) {
        CMmsgPrint(CMmsgUsrError, "No Layer to Process!");
        delete _RGlibPointGrdIF;
        return (DBFault);
    }

    table = tblData->Table(DBrNItems);
    pntIF = new DBVPointIF(pntData);
    netIF = new DBNetworkIF(netData);

    table->AddField(pointIDFLD = new DBObjTableField("GHAASPointID", DBTableFieldInt, "%8d", sizeof(DBInt)));
    table->AddField(layerIDFLD = new DBObjTableField("LayerID", DBTableFieldInt, "%4d", sizeof(DBShort)));
    table->AddField(layerNameFLD = new DBObjTableField("LayerName", DBTableFieldString, "%s", DBStringLength));
    table->AddField(averageFLD = new DBObjTableField(RGlibPointMean, DBTableFieldFloat, _RGlibPointGrdIF->ValueFormat(),
                                                     sizeof(DBFloat4)));
    table->AddField(minimumFLD = new DBObjTableField(RGlibPointMin, DBTableFieldFloat, _RGlibPointGrdIF->ValueFormat(),
                                                     sizeof(DBFloat4)));
    table->AddField(maximumFLD = new DBObjTableField(RGlibPointMax, DBTableFieldFloat, _RGlibPointGrdIF->ValueFormat(),
                                                     sizeof(DBFloat4)));
    table->AddField(
            stdDevFLD = new DBObjTableField(RGlibPointStdDev, DBTableFieldFloat, _RGlibPointGrdIF->ValueFormat(),
                                            sizeof(DBFloat4)));
    table->AddField(areaFLD = new DBObjTableField(RGlibPointArea, DBTableFieldFloat, _RGlibPointGrdIF->ValueFormat(),
                                                  sizeof(DBFloat4)));

    grdData->Flags(DBObjectFlagProcessed, DBSet);
    maxProgress = pntIF->ItemNum() * _RGlibPointGrdIF->LayerNum();
    for (layerID = 0; layerID < _RGlibPointGrdIF->LayerNum(); ++layerID) {
        _RGlibPointGrdLayerRec = _RGlibPointGrdIF->Layer(layerID);
        if ((_RGlibPointGrdLayerRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
        for (pntRec = pntIF->FirstItem(); pntRec != (DBObjRecord *) NULL; pntRec = pntIF->NextItem()) {
            if (DBPause(progress * 100 / maxProgress)) goto Stop;
            progress++;
            if ((pntRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
            tblRec = table->Add(pntRec->Name());
            pointIDFLD->Int(tblRec, pntRec->RowID() + 1);
            layerIDFLD->Int(tblRec, _RGlibPointGrdLayerRec->RowID());
            layerNameFLD->String(tblRec, _RGlibPointGrdLayerRec->Name());
            _RGlibSubbasinArea = 0.0;
            _RGlibSubbasinMin = DBHugeVal;
            _RGlibSubbasinMax = -DBHugeVal;
            _RGlibSubbasinMean = 0.0;
            _RGlibSubbasinStdDev = 0.0;
            netIF->UpStreamSearch(netIF->Cell(pntIF->Coordinate(pntRec)), (DBNetworkACTION) _RGlibSubbasinStatistics);
            _RGlibSubbasinMean = _RGlibSubbasinMean / _RGlibSubbasinArea;
            _RGlibSubbasinStdDev = _RGlibSubbasinStdDev / _RGlibSubbasinArea;
            _RGlibSubbasinStdDev = _RGlibSubbasinStdDev - _RGlibSubbasinMean * _RGlibSubbasinMean;
            _RGlibSubbasinStdDev = sqrt(_RGlibSubbasinStdDev);
            minimumFLD->Float(tblRec, _RGlibSubbasinMin);
            maximumFLD->Float(tblRec, _RGlibSubbasinMax);
            averageFLD->Float(tblRec, _RGlibSubbasinMean);
            stdDevFLD->Float(tblRec, _RGlibSubbasinStdDev);
            areaFLD->Float(tblRec, _RGlibSubbasinArea);
        }
    }
    Stop:
    delete _RGlibPointGrdIF;
    delete netIF;
    delete pntIF;

    if (progress == maxProgress) {
        fields = new DBObjectLIST<DBObjTableField>("Field List");
        fields->Add(new DBObjTableField(*pointIDFLD));
        fields->Add(new DBObjTableField(*layerIDFLD));
        table->ListSort(fields);
        delete fields;
        return (DBSuccess);
    }
    return (DBFault);
}
Exemple #19
0
DBInt DBPointToGrid(DBObjData *pntData, DBObjData *netData, DBObjData *grdData) {
    DBInt i;
    DBPosition pos;
    DBObjTable *pntTable = pntData->Table(DBrNItems);
    DBObjTable *grdTable = grdData->Table(DBrNItems);
    DBObjTable *symTable = grdData->Table(DBrNSymbols);
    DBObjectLIST<DBObjTableField> *pntFields = pntTable->Fields();
    DBObjTableField *pntFLD;
    DBObjTableField *grdAttribFLD;
    DBObjTableField *grdFLD = grdTable->Field(DBrNGridValue);
    DBObjTableField *symFLD = grdTable->Field(DBrNSymbol);
    DBObjRecord *cellRec, *toCell, *pntRec, *itemRec;
    DBObjRecord *symRec = symTable->First();
    DBVPointIF *pntIF;
    DBNetworkIF *netIF;
    DBGridIF *grdIF;

    pntIF = new DBVPointIF(pntData);
    netIF = new DBNetworkIF(netData);
    grdIF = new DBGridIF(grdData);

    grdIF->RenameLayer(grdIF->Layer((DBInt) 0), (char *) "Subbasins");

    for (pos.Row = 0; pos.Row < grdIF->RowNum(); ++pos.Row)
        for (pos.Col = 0; pos.Col < grdIF->ColNum(); ++pos.Col) grdIF->Value(pos, DBFault);

    for (pntFLD = pntFields->First(); pntFLD != (DBObjTableField *) NULL; pntFLD = pntFields->Next())
        if (DBTableFieldIsVisible(pntFLD)) grdTable->AddField(new DBObjTableField(*pntFLD));

    for (i = 0; i < pntIF->ItemNum(); ++i) {
        DBPause(i * 100 / pntIF->ItemNum());
        pntRec = pntIF->Item(i);
        if ((pntRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
        if ((cellRec = netIF->Cell(pntIF->Coordinate(pntRec))) == (DBObjRecord *) NULL) continue;

        itemRec = grdTable->Add(pntRec->Name());
        grdFLD->Int(itemRec, pntRec->RowID() + 1);
        symFLD->Record(itemRec, symRec);

        for (pntFLD = pntFields->First(); pntFLD != (DBObjTableField *) NULL; pntFLD = pntFields->Next())
            if ((grdAttribFLD = grdTable->Field(pntFLD->Name())) != (DBObjTableField *) NULL)
                switch (pntFLD->Type()) {
                    case DBTableFieldString:
                        grdAttribFLD->String(itemRec, pntFLD->String(pntRec));
                        break;
                    case DBTableFieldInt:
                        grdAttribFLD->Int(itemRec, pntFLD->Int(pntRec));
                        break;
                    case DBTableFieldFloat:
                        grdAttribFLD->Float(itemRec, pntFLD->Float(pntRec));
                        break;
                    case DBTableFieldDate:
                        grdAttribFLD->Date(itemRec, pntFLD->Date(pntRec));
                        break;
                }
        grdIF->Value(netIF->CellPosition(cellRec), itemRec->RowID());
    }

    for (i = 0; i < netIF->CellNum(); ++i) {
        if ((cellRec = netIF->Cell(i)) == (DBObjRecord *) NULL) continue;
        if ((itemRec = grdIF->GridItem(netIF->CellPosition(cellRec))) != (DBObjRecord *) NULL) continue;
        if ((toCell = netIF->ToCell(cellRec)) == (DBObjRecord *) NULL) continue;
        if ((itemRec = grdIF->GridItem(netIF->CellPosition(toCell))) != (DBObjRecord *) NULL)
            grdIF->Value(netIF->CellPosition(cellRec), itemRec->RowID());
    }
    grdIF->DiscreteStats();
    delete pntIF;
    delete netIF;
    delete grdIF;
    return (DBSuccess);
}
Exemple #20
0
static void _RGISToolsNetBasinMouthCBK (Widget widget,RGISWorkspace *workspace,XmAnyCallbackStruct *callData)

	{
	DBDataset *dataset = UIDataset ();
	DBObjData *netData = dataset->Data (), *pntData;
	DBNetworkIF *netIF;

	widget = widget; callData = callData;

	if (netData == (DBObjData *) NULL)
		{ CMmsgPrint (CMmsgAppError, "Null Data in: %s %d",__FILE__,__LINE__); return; }
	netIF = new DBNetworkIF (netData);

	if (UIDataHeaderForm (pntData = new DBObjData ("",DBTypeVectorPoint)))
		{
		char symName [DBStringLength];
		DBInt basinID, order;
		DBCoordinate coord;
		DBObjTable *items 	= pntData->Table (DBrNItems);
		DBObjTable *symbols	= pntData->Table (DBrNSymbols);
		DBObjTableField *coordField = items->Field (DBrNCoord);
		DBObjTableField *symbolFLD	 = items->Field (DBrNSymbol);
		DBObjTableField *orderFLD 	= new DBObjTableField (DBrNOrder,DBTableFieldInt,"%3d",sizeof (DBByte));
		DBObjTableField *subbasinLengthFLD = new DBObjTableField (DBrNSubbasinLength,DBTableFieldFloat,"%10.1f",sizeof (float));
		DBObjTableField *subbasinAreaFLD = new DBObjTableField (DBrNSubbasinArea,DBTableFieldFloat,"%10.1f",sizeof (float));
		DBObjTableField *foregroundFLD = symbols->Field (DBrNForeground);
		DBObjTableField *backgroundFLD = symbols->Field (DBrNBackground);
		DBObjTableField *styleFLD = symbols->Field (DBrNStyle);
		DBObjRecord *pntRec, *symRec, *cellRec, *basinRec;
		DBRegion dataExtent;

		items->AddField (orderFLD);
		items->AddField (subbasinLengthFLD);
		items->AddField (subbasinAreaFLD);

		cellRec = netIF->Cell ((DBInt) 0);
		for (order = 0;order <= netIF->CellOrder (cellRec);++order)
			{
			sprintf (symName,"Strahler Order:%2d",order);
			symRec = symbols->Add (symName);
			styleFLD->Int (symRec,0);
			foregroundFLD->Int (symRec,1);
			backgroundFLD->Int (symRec,0);
			}

		UIPauseDialogOpen ((char *) "Creating Basin Mouth");
		for (basinID = 0;basinID < netIF->BasinNum ();++basinID)
			{
			basinRec = netIF->Basin (basinID);
			if (UIPause (basinID * 100 / netIF->BasinNum ())) goto Stop;

			symRec = symbols->Item (netIF->CellOrder (cellRec));
			cellRec = netIF->MouthCell (basinRec);
			pntRec = items->Add (basinRec->Name ());
			coord = netIF->Center (cellRec);
			coordField->Coordinate (pntRec,coord);
			symbolFLD->Record (pntRec,symRec);
			orderFLD->Int (pntRec,netIF->CellOrder (cellRec));
			subbasinLengthFLD->Float (pntRec,netIF->CellBasinLength (cellRec));
			subbasinAreaFLD->Float (pntRec,netIF->CellBasinArea (cellRec));
			dataExtent.Expand (coord);
			}
Stop:
		UIPauseDialogClose ();
		pntData->Extent (dataExtent);
		workspace->CurrentData  (pntData);
		}
	else	delete pntData;
	delete netIF;
	}
Exemple #21
0
		DBInt Read (FILE *file,DBObjData *data)
			{
			DBInt i, layer, swap, valueType, valueSize, docLength;
			DMLayerHeader dmLayerHeader;
			DBObjRecord *layerRec, *dataRec;
			DBObjTable *layerTable = data->Table (DBrNLayers);
			DBObjTable *itemTable	 = data->Table (DBrNItems);
			DBObjTableField *rowNumFLD = layerTable->Field (DBrNRowNum);
			DBObjTableField *colNumFLD = layerTable->Field (DBrNColNum);
			DBObjTableField *cellWidthFLD = layerTable->Field (DBrNCellWidth);
			DBObjTableField *cellHeightFLD = layerTable->Field (DBrNCellHeight);
			DBObjTableField *valueTypeFLD = layerTable->Field (DBrNValueType);
			DBObjTableField *valueSizeFLD = layerTable->Field (DBrNValueSize);
			DBObjTableField *layerFLD = layerTable->Field (DBrNLayer);
			DBGridIF *gridIF;

			if ((swap = DMFileHeader::Read (file)) == DBFault) return (DBFault);
         data->Extent (Extent ());
         data->Projection (DBMathGuessProjection (data->Extent ()));
         data->Precision  (DBMathGuessPrecision  (data->Extent ()));
			if (FileType () != DMMatrix)
				{ CMmsgPrint (CMmsgAppError, "Wrong File Type in: %s %d",__FILE__,__LINE__); return (DBFault); }
			switch (DataType ())
				{
				case DMFloat:	valueType = DBTableFieldFloat;	valueSize = sizeof (DBFloat4);break;
				case DMInt:		valueType = DBTableFieldInt;		valueSize = sizeof (DBInt);	break;
				case DMByte:	valueType = DBTableFieldInt;		valueSize = sizeof (DBByte);	break;
				default: CMmsgPrint (CMmsgAppError, "Wrong Data Value Type in: %s %d",__FILE__,__LINE__); return (DBFault);
				}
			for (layer = 0;layer < LayerNum ();++layer)
				{
				if (dmLayerHeader.Read (file,swap) == DBFault) return (DBFault);
				if (strlen (dmLayerHeader.Description ()) > 0) layerName = dmLayerHeader.Description ();
				else { sprintf (layerNameSTR,"GHAASLayer%4d",layer + 1); layerName = layerNameSTR; }
				layerTable->Add (layerName);
				if ((layerRec = layerTable->Item ()) == (DBObjRecord *) NULL) return (DBFault);
				rowNumFLD->Int (layerRec,RowNum ());
				colNumFLD->Int (layerRec,ColNum ());
				cellWidthFLD->Float (layerRec,CellWidth ());
				cellHeightFLD->Float (layerRec,CellHeight ());
				valueTypeFLD->Int (layerRec,((DBInt) DBTypeGridDiscrete) == data->Type () ? DBTableFieldInt : valueType);
				valueSizeFLD->Int (layerRec,valueSize);
				if ((dataRec = new DBObjRecord (layerName,((size_t) ColNum ()) * RowNum () * valueSize,valueSize)) == (DBObjRecord *) NULL)
					return (DBFault);
				(data->Arrays ())->Add (dataRec);
				layerFLD->Record (layerRec,dataRec);
				}
			if (fread (&docLength,sizeof (int),1,file) != 1)
				{ CMmsgPrint (CMmsgSysError, "File Reading Error in: %s %d",__FILE__,__LINE__); return (DBFault); }
			if (swap) DBByteOrderSwapWord (&docLength);
			if (docLength > 0)
				{
				char *docString;
				if ((docString = (char *) calloc (docLength,sizeof (char))) == (char *) NULL)
					{ CMmsgPrint (CMmsgSysError, "Memory Allocation Error in: %s %d",__FILE__,__LINE__); return (DBFault); }
				if (fread (docString,docLength,1,file) != 1)
					{ CMmsgPrint (CMmsgSysError, "File Reading Error in: %s %d",__FILE__,__LINE__); return (DBFault); }
				data->Document (DBDocComment,docString);
				free (docString);
				}
			for (dataRec = (data->Arrays ())->First ();dataRec != (DBObjRecord *) NULL;dataRec = (data->Arrays ())->Next ())
				if (fread (dataRec->Data (),ColNum () * valueSize * RowNum (),1,file) != 1)
					{ CMmsgPrint (CMmsgSysError, "File Reading Error in: %s %d",__FILE__,__LINE__); return (DBFault); }
			if (swap && valueSize > 1)
				{
				int i;
				void (*swapFunc) (void *);
				switch (valueSize)
					{
					case 2: swapFunc = DBByteOrderSwapHalfWord; break;
					case 4: swapFunc = DBByteOrderSwapWord; break;
					case 8: swapFunc = DBByteOrderSwapLongWord; break;
					default: CMmsgPrint (CMmsgAppError, "Wrong Data Value Size in: %s %d",__FILE__,__LINE__); return (DBFault);
					}
				for (dataRec = (data->Arrays ())->First ();dataRec != (DBObjRecord *) NULL;dataRec = (data->Arrays ())->Next ())
					for (i = 0;i < ColNum () * RowNum ();++i) (*swapFunc) ((char *) dataRec->Data () + i * valueSize);
				}
			switch (data->Type ())
				{
				case DBTypeGridDiscrete:
					{
					DBInt value;
					char nameStr [DBStringLength];
					DBObjRecord *symRec = (data->Table (DBrNSymbols))->Add ("Default Symbol");
					DBObjRecord *itemRec;
					DBObjTableField *gridValueFLD  = itemTable->Field (DBrNGridValue);
					DBObjTableField *gridSymbolFLD = itemTable->Field (DBrNSymbol);
					DBObjTableField *symbolIDFLD	 = (data->Table (DBrNSymbols))->Field (DBrNSymbolID);
					DBObjTableField *foregroundFLD = (data->Table (DBrNSymbols))->Field (DBrNForeground);
					DBObjTableField *backgroundFLD = (data->Table (DBrNSymbols))->Field (DBrNBackground);
					DBObjTableField *styleFLD = (data->Table (DBrNSymbols))->Field (DBrNStyle);

					symbolIDFLD->Int (symRec,0);
					foregroundFLD->Int (symRec,1);
					backgroundFLD->Int (symRec,0);
					styleFLD->Int (symRec,0);
					for (dataRec = (data->Arrays ())->First ();dataRec != (DBObjRecord *) NULL;dataRec = (data->Arrays ())->Next ())
						{
						for (i = 0;i < ColNum () * RowNum ();++i)
							{
							switch (valueType)
								{
								case DBTableFieldFloat: value = (DBInt) rint (*((float *) ((char *) dataRec->Data () + i * valueSize))); break;
								case DBTableFieldInt:
									switch (valueSize)
										{
										case sizeof (DBByte):  value = (DBInt) (*((DBByte *)  ((char *) dataRec->Data () + i * valueSize))); break;
										case sizeof (DBShort): value = (DBInt) (*((DBShort *) ((char *) dataRec->Data () + i * valueSize))); break;
										case sizeof (DBInt):	  value = (DBInt) (*((DBInt *)	((char *) dataRec->Data () + i * valueSize))); break;
										default: CMmsgPrint (CMmsgAppError, "Wrong Data Size in: %s %d",__FILE__,__LINE__); return (DBFault);
										}
									break;
								default: CMmsgPrint (CMmsgAppError, "Wrong Data Type in: %s %d",__FILE__,__LINE__); return (DBFault);
								}
							sprintf (nameStr,"Category%04d",value);
							if ((itemRec = itemTable->Item (nameStr)) == (DBObjRecord *) NULL)
								{
								if ((itemRec = itemTable->Add (nameStr)) == (DBObjRecord *) NULL)
									{ CMmsgPrint (CMmsgAppError, "Item Object Creation Error in: %s %d",__FILE__,__LINE__); return (DBFault); }
								gridValueFLD->Int (itemRec,value);
								gridSymbolFLD->Record (itemRec,symRec);
								}
							value = itemRec->RowID ();
							switch (valueSize)
								{
								case sizeof (DBByte):  *((DBByte *)  ((char *) dataRec->Data () + i * valueSize)) = value; break;
								case sizeof (DBShort): *((DBShort *) ((char *) dataRec->Data () + i * valueSize)) = value; break;
								case sizeof (DBInt):	  *((DBInt *)	 ((char *) dataRec->Data () + i * valueSize)) = value; break;
								default: CMmsgPrint (CMmsgAppError, "Wrong Data Size in: %s %d",__FILE__,__LINE__); return (DBFault);
								}
							}
						}
					itemTable->ListSort (gridValueFLD);
					for (dataRec = (data->Arrays ())->First ();dataRec != (DBObjRecord *) NULL;dataRec = (data->Arrays ())->Next ())
						{
						for (i = 0;i < ColNum () * RowNum ();++i)
							{
							switch (valueSize)
								{
								case sizeof (DBByte):  value = (DBInt) (*((DBByte *)  ((char *) dataRec->Data () + i * valueSize))); break;
								case sizeof (DBShort): value = (DBInt) (*((DBShort *) ((char *) dataRec->Data () + i * valueSize))); break;
								case sizeof (DBInt):	  value = (DBInt) (*((DBInt *)	((char *) dataRec->Data () + i * valueSize))); break;
								default: CMmsgPrint (CMmsgAppError, "Wrong Data Size in: %s %d",__FILE__,__LINE__); return (DBFault);
								}
							itemRec = itemTable->Item (value);
							value = itemRec->ListPos ();
							switch (valueSize)
								{
								case sizeof (DBByte):  *((DBByte *)  ((char *) dataRec->Data () + i * valueSize)) = value; break;
								case sizeof (DBShort): *((DBShort *) ((char *) dataRec->Data () + i * valueSize)) = value; break;
								case sizeof (DBInt):	  *((DBInt *)	 ((char *) dataRec->Data () + i * valueSize)) = value; break;
								default: CMmsgPrint (CMmsgAppError, "Wrong Data Size in: %s %d",__FILE__,__LINE__); return (DBFault);
								}
							}
						}
					itemTable->ItemSort ();
					gridIF = new DBGridIF (data);
					gridIF->DiscreteStats ();
					delete gridIF;
					} break;
				case DBTypeGridContinuous:
					{
					DBObjTableField *missingValueFLD		= itemTable->Field (DBrNMissingValue);

					for (dataRec = (data->Arrays ())->First ();dataRec != (DBObjRecord *) NULL;dataRec = (data->Arrays ())->Next ())
						{
						itemTable->Add (dataRec->Name ());
						missingValueFLD->Float (itemTable->Item (),MissingValue ());
						}
					gridIF = new DBGridIF (data);
					gridIF->RecalcStats ();
					delete gridIF;
					data->Flags (DBDataFlagDispModeContBlueRed,DBSet);
					break;
					}
				default: break;
				}
			return (DBSuccess);
			}
Exemple #22
0
DBInt RGlibPointSTNCharacteristics(DBObjData *dbData) {
    DBInt i, pointID, dPointID, cellID, mouthID, basinID, color, ret = DBFault, dir;
    DBVPointIF *pntIF;
    DBObjTable *pointTable, *cellTable;
    DBObjTableField *cellIDFLD;
    DBObjTableField *basinFLD;
    DBObjTableField *basinNameFLD;
    DBObjTableField *orderFLD;
    DBObjTableField *colorFLD;
    DBObjTableField *basinCellsFLD;
    DBObjTableField *basinLengthFLD;
    DBObjTableField *basinAreaFLD;
    DBObjTableField *interAreaFLD;
    DBObjTableField *nextStationFLD;
    DBObjData *netData;
    DBNetworkIF *netIF;
    DBObjRecord *pointRec, *dPointRec, *cellRec, *fromCell, *basinRec;

    if ((netData = dbData->LinkedData()) == (DBObjData *) NULL) return (DBFault);
    pointTable = dbData->Table(DBrNItems);
    pntIF = new DBVPointIF(dbData);
    netIF = new DBNetworkIF(netData);
    cellTable = netData->Table(DBrNCells);
    if ((cellIDFLD = pointTable->Field(RGlibCellID)) == NULL) {
        cellIDFLD = new DBObjTableField(RGlibCellID, DBTableFieldInt, "%8d", sizeof(DBInt));
        pointTable->AddField(cellIDFLD);
        DBPause(1);
    }
    if ((basinFLD = pointTable->Field(DBrNBasin)) == NULL) {
        basinFLD = new DBObjTableField(DBrNBasin, DBTableFieldInt, "%8d", sizeof(DBInt));
        pointTable->AddField(basinFLD);
        DBPause(2);
    }
    if ((basinNameFLD = pointTable->Field(RGlibBasinName)) == NULL) {
        basinNameFLD = new DBObjTableField(RGlibBasinName, DBTableFieldString, "%32s", DBStringLength);
        pointTable->AddField(basinNameFLD);
        DBPause(3);
    }
    if ((orderFLD = pointTable->Field(DBrNOrder)) == NULL) {
        orderFLD = new DBObjTableField(DBrNOrder, DBTableFieldInt, "%3d", sizeof(DBByte));
        pointTable->AddField(orderFLD);
        DBPause(4);
    }
    if ((colorFLD = pointTable->Field(RGlibColor)) == NULL) {
        colorFLD = new DBObjTableField(RGlibColor, DBTableFieldInt, "%2d", sizeof(DBShort));
        pointTable->AddField(colorFLD);
        DBPause(5);
    }
    if ((basinCellsFLD = pointTable->Field(RGlibCellNum)) == NULL) {
        basinCellsFLD = new DBObjTableField(RGlibCellNum, DBTableFieldInt, "%8d", sizeof(DBInt));
        pointTable->AddField(basinCellsFLD);
        DBPause(6);
    }
    if ((basinLengthFLD = pointTable->Field(RGlibLength)) == NULL) {
        basinLengthFLD = new DBObjTableField(RGlibLength, DBTableFieldFloat, "%10.1f", sizeof(DBFloat4));
        pointTable->AddField(basinLengthFLD);
        DBPause(7);
    }
    if ((basinAreaFLD = pointTable->Field(RGlibArea)) == NULL) {
        basinAreaFLD = new DBObjTableField(RGlibArea, DBTableFieldFloat, "%10.1f", sizeof(DBFloat4));
        pointTable->AddField(basinAreaFLD);
        DBPause(8);
    }
    if ((interAreaFLD = pointTable->Field(RGlibInterStation)) == NULL) {
        interAreaFLD = new DBObjTableField(RGlibInterStation, DBTableFieldFloat, "%10.1f", sizeof(DBFloat4));
        pointTable->AddField(interAreaFLD);
        DBPause(9);
    }
    if ((nextStationFLD = pointTable->Field(RGlibNextStation)) == NULL) {
        nextStationFLD = new DBObjTableField(RGlibNextStation, DBTableFieldInt, "%8d", sizeof(DBInt));
        pointTable->AddField(nextStationFLD);
        DBPause(10);
    }
    if ((_RGlibTEMPPointIDFLD = cellTable->Field(RGlibTEMPPointID)) == NULL) {
        _RGlibTEMPPointIDFLD = new DBObjTableField(RGlibTEMPPointID, DBTableFieldInt, "%8d", sizeof(DBInt));
        cellTable->AddField(_RGlibTEMPPointIDFLD);
    }
    for (pointID = 0; pointID < pointTable->ItemNum(); pointID++) {
        pointRec = pointTable->Item(pointID);
        if (DBPause(10 + pointID * 10 / pointTable->ItemNum())) goto Stop;
        if ((pointRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) {
            cellIDFLD->Int(pointRec, cellIDFLD->IntNoData());
            basinFLD->Int(pointRec, basinFLD->IntNoData());
            basinNameFLD->String(pointRec, "");
            orderFLD->Int(pointRec, orderFLD->IntNoData());
            colorFLD->Int(pointRec, colorFLD->IntNoData());
            basinCellsFLD->Int(pointRec, basinCellsFLD->IntNoData());
            basinAreaFLD->Float(pointRec, basinAreaFLD->FloatNoData());
            interAreaFLD->Float(pointRec, interAreaFLD->FloatNoData());
            continue;
        }
        if ((cellRec = netIF->Cell(pntIF->Coordinate(pointRec))) == (DBObjRecord *) NULL) {
            cellIDFLD->Int(pointRec, 0);
            basinFLD->Int(pointRec, 0);
            basinNameFLD->String(pointRec, "Water");
            orderFLD->Int(pointRec, colorFLD->IntNoData());
            colorFLD->Int(pointRec, colorFLD->IntNoData());
            basinCellsFLD->Int(pointRec, 0);
            basinAreaFLD->Float(pointRec, 0.0);
            interAreaFLD->Float(pointRec, 0.0);
        }
        else {
            cellIDFLD->Int(pointRec, cellRec->RowID() + 1);
            basinRec = netIF->Basin(cellRec);
            basinFLD->Int(pointRec, basinRec->RowID() + 1);
            basinNameFLD->String(pointRec, basinRec->Name());
            orderFLD->Int(pointRec, netIF->CellOrder(cellRec));
            colorFLD->Int(pointRec, 0);
            basinCellsFLD->Int(pointRec, netIF->CellBasinCells(cellRec));
            basinLengthFLD->Float(pointRec, netIF->CellBasinLength(cellRec));
            basinAreaFLD->Float(pointRec, netIF->CellBasinArea(cellRec));
            interAreaFLD->Float(pointRec, netIF->CellBasinArea(cellRec));
        }
        nextStationFLD->Int(pointRec, 0);
    }
    for (cellID = 0; cellID < cellTable->ItemNum(); ++cellID) {
        if (DBPause(20 + cellID * 20 / cellTable->ItemNum())) goto Stop;
        cellRec = cellTable->Item(cellID);
        _RGlibTEMPPointIDFLD->Int(cellRec, DBFault);
    }
    pointTable->ListSort(basinAreaFLD);
    for (pointRec = pointTable->Last(); pointRec != (DBObjRecord *) NULL; pointRec = pointTable->Next(DBBackward)) {
        if ((pointRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
        if (DBPause(40 + pointID * 20 / pointTable->ItemNum())) goto Stop;
        cellRec = netIF->Cell(pntIF->Coordinate(pointRec));
        netIF->UpStreamSearch(cellRec, (DBNetworkACTION) _RGlibSetPointID,
                              (void *) ((char *) NULL + pointRec->RowID()));
    }
    for (pointID = 0; pointID < pointTable->ItemNum(); pointID++) {
        pointRec = pointTable->Item(pointID);
        if ((pointRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
        if (DBPause(60 + pointID * 20 / pointTable->ItemNum())) goto Stop;
        if ((cellRec = netIF->Cell(pntIF->Coordinate(pointRec))) != (DBObjRecord *) NULL) {
            if ((cellRec = netIF->ToCell(cellRec)) == (DBObjRecord *) NULL) continue;
            if ((dPointID = _RGlibTEMPPointIDFLD->Int(cellRec)) != DBFault) {
                dPointRec = pointTable->Item(dPointID);
                nextStationFLD->Int(pointRec, dPointRec->RowID() + 1);
                interAreaFLD->Float(dPointRec, interAreaFLD->Float(dPointRec) - basinAreaFLD->Float(pointRec));
            }
        }
    }
    pointTable->ListSort(interAreaFLD);

    i = 0;
    for (pointRec = pointTable->Last(); pointRec != (DBObjRecord *) NULL; pointRec = pointTable->Next(DBBackward)) {
        if (DBPause(80 + (i++) * 20 / pointTable->ItemNum())) goto Stop;
        pointID = pointRec->RowID();
        if ((pointRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;

        if ((basinID = basinFLD->Int(pointRec)) == 0) continue;
        cellRec = netIF->Cell(pntIF->Coordinate(pointRec));
        mouthID = cellRec->RowID();
        color = 1;
        Start:
        for (cellID = mouthID; cellID < cellTable->ItemNum(); ++cellID) {
            cellRec = cellTable->Item(cellID);
            if (netIF->CellBasinID(cellRec) != basinID) break;
            if (_RGlibTEMPPointIDFLD->Int(cellRec) != pointID) continue;

            for (dir = 0; dir < 8; ++dir) {
                if ((fromCell = netIF->FromCell(cellRec, 0x01 << dir, false)) == (DBObjRecord *) NULL) continue;
                if ((dPointID = _RGlibTEMPPointIDFLD->Int(fromCell)) == pointID) continue;
                if (dPointID == DBFault) continue;

                dPointRec = pointTable->Item(dPointID);
                if (colorFLD->Int(dPointRec) == color) {
                    color++;
                    goto Start;
                }
            }
        }
        colorFLD->Int(pointRec, color);
    }
    ret = DBSuccess;
    Stop:
    pointTable->ListSort();
    cellTable->DeleteField(_RGlibTEMPPointIDFLD);
    delete pntIF;
    delete netIF;
    return (ret);
}
Exemple #23
0
DBInt RGlibPointSubbasinHist(DBObjData *pntData, DBObjData *netData, DBObjData *grdData, DBObjData *tblData) {
    DBInt layerID, layerNum = 0, progress = 0, maxProgress;
    DBObjTable *itemTable = grdData->Table(DBrNItems);
    DBObjTable *table = tblData->Table(DBrNItems);
    DBObjTableField *pointIDFLD;
    DBObjTableField *layerIDFLD;
    DBObjTableField *layerNameFLD;
    DBObjTableField *categoryIDFLD;
    DBObjTableField *categoryFLD;
    DBObjTableField *percentFLD;
    DBObjTableField *areaFLD;
    DBObjTableField *cellNumFLD;
    DBVPointIF *pntIF;
    DBNetworkIF *netIF;
    DBObjRecord *pntRec, *itemRec, *tblRec;
    DBObjectLIST<DBObjTableField> *fields;

    _RGlibPointGrdIF = new DBGridIF(grdData);
    for (layerID = 0; layerID < _RGlibPointGrdIF->LayerNum(); ++layerID) {
        _RGlibPointGrdLayerRec = _RGlibPointGrdIF->Layer(layerID);
        if ((_RGlibPointGrdLayerRec->Flags() & DBObjectFlagIdle) != DBObjectFlagIdle) ++layerNum;
    }
    if (layerNum < 1) {
        CMmsgPrint(CMmsgUsrError, "No Layer to Process!");
        delete _RGlibPointGrdIF;
        return (DBFault);
    }
    pntIF = new DBVPointIF(pntData);
    netIF = new DBNetworkIF(netData);

    table->AddField(pointIDFLD = new DBObjTableField("GHAASPointID", DBTableFieldInt, "%8d", sizeof(DBInt)));
    table->AddField(layerIDFLD = new DBObjTableField("LayerID", DBTableFieldInt, "%4d", sizeof(DBShort)));
    table->AddField(layerNameFLD = new DBObjTableField("LayerName", DBTableFieldString, "%s", DBStringLength));
    table->AddField(categoryIDFLD = new DBObjTableField(DBrNCategoryID, DBTableFieldInt, "%2d", sizeof(DBShort)));
    table->AddField(categoryFLD = new DBObjTableField(DBrNCategory, DBTableFieldString, _RGlibPointGrdIF->ValueFormat(),
                                                      DBStringLength));
    table->AddField(cellNumFLD = new DBObjTableField("CellNum", DBTableFieldInt, "%8d", sizeof(DBInt)));
    table->AddField(areaFLD = new DBObjTableField(DBrNArea, DBTableFieldFloat, "%10.1f", sizeof(DBFloat4)));
    table->AddField(percentFLD = new DBObjTableField(DBrNPercent, DBTableFieldFloat, "%6.2f", sizeof(DBFloat4)));

    _RGlibHistogram = (Histogram *) malloc(itemTable->ItemNum() * sizeof(Histogram));
    if (_RGlibHistogram == (Histogram *) NULL) {
        CMmsgPrint(CMmsgAppError, "Memory Allocation Error in: %s %d", __FILE__, __LINE__);
        return (DBFault);
    }
    maxProgress = pntIF->ItemNum() * _RGlibPointGrdIF->LayerNum();
    for (layerID = 0; layerID < _RGlibPointGrdIF->LayerNum(); ++layerID) {
        _RGlibPointGrdLayerRec = _RGlibPointGrdIF->Layer(layerID);
        if ((_RGlibPointGrdLayerRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
        for (pntRec = pntIF->FirstItem(); pntRec != (DBObjRecord *) NULL; pntRec = pntIF->NextItem()) {
            if (DBPause(progress * 100 / maxProgress)) goto Stop;
            progress++;
            if ((pntRec->Flags() & DBObjectFlagIdle) == DBObjectFlagIdle) continue;
            for (itemRec = itemTable->First(); itemRec != (DBObjRecord *) NULL; itemRec = itemTable->Next())
                _RGlibHistogram[itemRec->RowID()].Initialize();
            netIF->UpStreamSearch(netIF->Cell(pntIF->Coordinate(pntRec)), (DBNetworkACTION) _RGlibSubbasinCategories);
            for (itemRec = itemTable->First(); itemRec != (DBObjRecord *) NULL; itemRec = itemTable->Next())
                if (_RGlibHistogram[itemRec->RowID()].cellNum > 0) {
                    tblRec = table->Add(pntRec->Name());
                    pointIDFLD->Int(tblRec, pntRec->RowID() + 1);
                    layerIDFLD->Int(tblRec, _RGlibPointGrdLayerRec->RowID());
                    layerNameFLD->String(tblRec, _RGlibPointGrdLayerRec->Name());
                    categoryIDFLD->Int(tblRec, itemRec->RowID() + 1);
                    categoryFLD->String(tblRec, itemRec->Name());
                    areaFLD->Float(tblRec, _RGlibHistogram[itemRec->RowID()].area);
                    percentFLD->Float(tblRec, _RGlibHistogram[itemRec->RowID()].area /
                                              netIF->CellBasinArea(netIF->Cell(pntIF->Coordinate(pntRec))) * 100.0);
                    cellNumFLD->Int(tblRec, _RGlibHistogram[itemRec->RowID()].cellNum);
                }
        }
    }
    Stop:
    delete _RGlibPointGrdIF;
    delete netIF;
    delete pntIF;
    free(_RGlibHistogram);

    if (progress == maxProgress) {
        fields = new DBObjectLIST<DBObjTableField>("Field List");
        fields->Add(new DBObjTableField(*pointIDFLD));
        fields->Add(new DBObjTableField(*layerIDFLD));
        fields->Add(areaFLD = new DBObjTableField(*areaFLD));
        areaFLD->Flags(DBObjectFlagSortReversed, DBSet);
        table->ListSort(fields);
        delete fields;
        return (DBSuccess);
    }
    return (DBFault);
}
Exemple #24
0
void RGISAnNetworkStreamLinesCBK (Widget widget,RGISWorkspace *workspace,XmAnyCallbackStruct *callData)

	{
	char *selection;
	DBDataset *dataset = UIDataset ();
	DBObjData *netData = dataset->Data ();
	DBObjTable *cellTable = netData->Table (DBrNCells);
	DBObjData *arcData = new DBObjData ("",DBTypeVectorLine);
	DBNetworkIF *netIF = new DBNetworkIF (netData);
	static Widget fieldSelect = (Widget) NULL;

	widget = widget; callData = callData;

	if (fieldSelect == (Widget) NULL)	fieldSelect = UISelectionCreate ((char *) "Select Field");
	if ((selection = UISelectObject (fieldSelect,(DBObjectLIST<DBObject> *) cellTable->Fields (),DBTableFieldIsInteger)) == (char *) NULL)
		return;
	if ((_RGISAnNetOrderField = cellTable->Field (selection)) == (DBObjTableField *) NULL)
		{ CMmsgPrint (CMmsgAppError, "Field Selection Error in: %s %d",__FILE__,__LINE__); return; }
	arcData->Document (DBDocGeoDomain,netData->Document (DBDocGeoDomain));
	arcData->Document (DBDocSubject,"Stream Lines");
	if (UIDataHeaderForm (arcData))
		{
		DBInt cellID;
		char objName [DBStringLength];
		DBVLineIF *lineIF = new DBVLineIF (arcData);
		DBObjTable *cellTable 	= netData->Table (DBrNCells);
		DBObjTable *lineTable 	= arcData->Table (DBrNItems);
		DBObjTableField *basinFLD  = new DBObjTableField (DBrNBasin,DBTableFieldInt,"%8d",sizeof (DBInt));
		DBObjTableField *fieldFLD  = new DBObjTableField (_RGISAnNetOrderField->Name (),
		                                                  _RGISAnNetOrderField->Type (),
		                                                  _RGISAnNetOrderField->Format (),
		                                                  _RGISAnNetOrderField->Length ());
		DBObjTableField *lengthFLD = new DBObjTableField (RGISNetStreamLength,DBTableFieldFloat,"%10.1f",sizeof (DBFloat4));
		DBObjTableField *areaFLD   = new DBObjTableField (RGISNetStreamArea,DBTableFieldFloat,"%10.1f",sizeof (DBFloat4));
		DBObjTableField *basinAreaFLD = new DBObjTableField (RGISNetBasinArea,DBTableFieldFloat,"%10.1f",sizeof (DBFloat4));
		DBObjTableField *nextFLD  = new DBObjTableField (RGISNetStreamNext,DBTableFieldInt,"%6d",sizeof (DBInt));
		DBObjRecord *cellRec, *toCellRec, *lineRec;

		arcData->Projection (netData->Projection ());
		arcData->Precision  (netData->Precision ());
		arcData->MaxScale   (netData->MaxScale ());
		arcData->MinScale   (netData->MinScale ());

		lineTable->AddField (basinFLD);
		lineTable->AddField (fieldFLD);
		lineTable->AddField (lengthFLD);
		lineTable->AddField (areaFLD);
		lineTable->AddField (basinAreaFLD);
		lineTable->AddField (nextFLD);

		cellTable->AddField (_RGISAnNetStreamIDFLD = new DBObjTableField ("StreamID",DBTableFieldInt,"%8d",sizeof (DBInt)));

		_RGISAnNetStreamID = 0;
		UIPauseDialogOpen ((char *) "Creating Stream Lines");
		cellID = netIF->CellNum () - 1;
		cellRec = netIF->Cell (cellID);
		if (lineIF->NewSymbol ("Default Symbol") == (DBObjRecord *) NULL)
			{ CMmsgPrint (CMmsgAppError, "Symbol Creation Error in: %s %d",__FILE__,__LINE__); return; }

		for (;cellID >= 0;--cellID)
			{
			cellRec = netIF->Cell (cellID);
			if (((toCellRec = netIF->ToCell (cellRec)) == (DBObjRecord *) NULL) ||
			    (_RGISAnNetOrderField->Int (cellRec) != _RGISAnNetOrderField->Int (toCellRec)) ||
	 		    (netIF->CellOrder (cellRec)          != netIF->CellOrder (toCellRec)))
				{
				if (UIPause ((netIF->CellNum () - cellRec->RowID ()) * 100 / netIF->CellNum ())) goto Stop;
				sprintf (objName,"Line: %5d",_RGISAnNetStreamID + 1);
				if ((lineRec = lineIF->NewItem (objName)) == (DBObjRecord *) NULL)
					{ CMmsgPrint (CMmsgAppError, "Line Insertion Error in: %s %d",__FILE__,__LINE__); return; }
				nextFLD->Int (lineRec,toCellRec == (DBObjRecord *) NULL ? 0 : _RGISAnNetStreamIDFLD->Int (toCellRec) + 1);
				basinFLD->Int (lineRec,netIF->CellBasinID (cellRec));
				fieldFLD->Int (lineRec,_RGISAnNetOrderField->Int (cellRec));

				_RGISAnNetVertex = 0;
				netIF->UpStreamSearch (_RGISAnNetworkCellRec = cellRec,(DBNetworkACTION) _RGISAnNetworkUpStreamAction);
				lineIF->FromNode (lineRec,lineIF->Node (netIF->Center (_RGISAnNetworkCellRec),true));
				lineIF->ToNode (lineRec,lineIF->Node (netIF->Center (cellRec) + netIF->Delta (cellRec),true));

				_RGISAnNetArea = netIF->CellArea (_RGISAnNetworkCellRec);
				if (_RGISAnNetVertex > 1)
					{
					if (_RGISAnNetVertexNum < _RGISAnNetVertex - 1)
						{
						_RGISAnNetCoord = (DBCoordinate *) realloc (_RGISAnNetCoord,(_RGISAnNetVertex - 1) * sizeof (DBCoordinate));
						if (_RGISAnNetCoord == (DBCoordinate *) NULL)
							{ CMmsgPrint (CMmsgSysError, "Memory Allocation Error in: %s %d",__FILE__,__LINE__); return; }
						}
					_RGISAnNetVertex = 0;
					netIF->DownStreamSearch (netIF->ToCell (_RGISAnNetworkCellRec),(DBNetworkACTION) _RGISAnNetworkDownStreamAction);
					}
				else	_RGISAnNetVertex = 0;
				lineIF->Vertexes (lineRec,_RGISAnNetCoord,_RGISAnNetVertex);
				lineIF->ItemSymbol (lineRec,lineIF->Symbol (0));
				lengthFLD->Float (lineRec,netIF->CellBasinLength (cellRec));
				areaFLD->Float (lineRec,_RGISAnNetArea);
				basinAreaFLD->Float (lineRec,netIF->CellBasinArea (cellRec));
				_RGISAnNetStreamID += 1;
				}
			}
Stop:	UIPauseDialogClose ();
		if (_RGISAnNetCoord != (DBCoordinate *) NULL) free (_RGISAnNetCoord);

		delete lineIF;
		if (cellID >= 0) delete arcData;
		else	workspace->CurrentData (arcData);
		}
	else delete arcData;
	delete netIF;
	}
Exemple #25
0
DBObjData *DBNetworkToGrid(DBObjData *netData, DBInt type) {
    DBPosition pos;
    DBObjData *grdData = new DBObjData("", type);
    DBObjRecord *layerRec, *dataRec;
    DBObjTable *layerTable = grdData->Table(DBrNLayers);
    DBObjTable *itemTable = grdData->Table(DBrNItems);
    DBObjTableField *rowNumFLD = layerTable->Field(DBrNRowNum);
    DBObjTableField *colNumFLD = layerTable->Field(DBrNColNum);
    DBObjTableField *cellWidthFLD = layerTable->Field(DBrNCellWidth);
    DBObjTableField *cellHeightFLD = layerTable->Field(DBrNCellHeight);
    DBObjTableField *valueTypeFLD = layerTable->Field(DBrNValueType);
    DBObjTableField *valueSizeFLD = layerTable->Field(DBrNValueSize);
    DBObjTableField *layerFLD = layerTable->Field(DBrNLayer);
    DBNetworkIF *netIF;
    DBGridIF *gridIF;

    grdData->Projection(netData->Projection());
    grdData->Precision(netData->Precision());
    grdData->MaxScale(netData->MaxScale());
    grdData->MinScale(netData->MinScale());
    grdData->Extent(netData->Extent());
    grdData->Document(DBDocGeoDomain, netData->Document(DBDocGeoDomain));

    netIF = new DBNetworkIF(netData);

    layerTable->Add("FirstLayer");
    if ((layerRec = layerTable->Item()) == (DBObjRecord *) NULL) {
        delete netIF;
        return ((DBObjData *) NULL);
    }
    rowNumFLD->Int(layerRec, netIF->RowNum());
    colNumFLD->Int(layerRec, netIF->ColNum());
    cellWidthFLD->Float(layerRec, netIF->CellWidth());
    cellHeightFLD->Float(layerRec, netIF->CellHeight());
    switch (type) {
        case DBTypeGridContinuous:
            valueTypeFLD->Int(layerRec, DBTableFieldFloat);
            valueSizeFLD->Int(layerRec, sizeof(DBFloat));
            break;
        case DBTypeGridDiscrete:
            valueTypeFLD->Int(layerRec, DBTableFieldInt);
            valueSizeFLD->Int(layerRec, sizeof(DBInt));
            break;
        default:
            CMmsgPrint(CMmsgAppError, "Invalid Data Type in: %s %d", __FILE__, __LINE__);
            delete grdData;
            delete netIF;
            return ((DBObjData *) NULL);
    }
    if ((dataRec = new DBObjRecord(layerRec->Name(),
                                   ((size_t) netIF->ColNum()) * netIF->RowNum() * valueSizeFLD->Int(layerRec),
                                   valueSizeFLD->Int(layerRec))) == (DBObjRecord *) NULL) {
        delete netIF;
        return ((DBObjData *) NULL);
    }
    (grdData->Arrays())->Add(dataRec);
    layerFLD->Record(layerRec, dataRec);

    gridIF = new DBGridIF(grdData);
    if (type == DBTypeGridContinuous) {
        itemTable->Add(layerRec->Name());
        DBObjTableField *missingValueFLD = itemTable->Field(DBrNMissingValue);
        missingValueFLD->Float(itemTable->Item(layerRec->Name()), DBDefaultMissingFloatVal);
        for (pos.Row = 0; pos.Row < netIF->RowNum(); pos.Row++)
            for (pos.Col = 0; pos.Col < netIF->ColNum(); pos.Col++)
                gridIF->Value(layerRec, pos, DBDefaultMissingFloatVal);
    }
    else {
        DBObjTable *symbolTable = grdData->Table(DBrNSymbols);
        DBObjTableField *foregroundFLD = symbolTable->Field(DBrNForeground);
        DBObjTableField *backgroundFLD = symbolTable->Field(DBrNBackground);
        DBObjTableField *styleFLD = symbolTable->Field(DBrNStyle);
        DBObjRecord *symbolRec = symbolTable->Add("Default Symbol");

        foregroundFLD->Int(symbolRec, 1);
        backgroundFLD->Int(symbolRec, 0);
        styleFLD->Int(symbolRec, 0);
        for (pos.Row = 0; pos.Row < netIF->RowNum(); pos.Row++)
            for (pos.Col = 0; pos.Col < netIF->ColNum(); pos.Col++)
                gridIF->Value(layerRec, pos, 0);
    }
    delete netIF;
    delete gridIF;
    return (grdData);
}
Exemple #26
0
void RGISAnalyseLineSSampleGridCBK (Widget widget, RGISWorkspace *workspace,XmAnyCallbackStruct *callData)

	{
	char *fText;
	int allowOk;
	static int sample;
	DBDataset *dataset = UIDataset ();
	DBObjData *dbData  = dataset->Data (), *grdData = dbData->LinkedData ();
	DBObjTable *itemTable = dbData->Table (DBrNItems);
	static Widget dShell = (Widget) NULL, mainForm;
	static Widget fromNameTextF, toNameTextF;
	XmString string;

	widget = widget;	workspace = workspace; callData = callData;
	_RGISAnLineSampleGridFields = itemTable->Fields ();
	if (dShell == (Widget) NULL)
		{
		Widget button;

		dShell = UIDialogForm ((char *) "Single Layer Grid Sampling",false);
		mainForm = UIDialogFormGetMainForm (dShell);

		string = XmStringCreate ((char *) "Select",UICharSetBold);
		button = XtVaCreateManagedWidget ("RGISAnalyseLineSSampleNameButton",xmPushButtonWidgetClass,mainForm,
								XmNtopAttachment,			XmATTACH_FORM,
								XmNtopOffset,				10,
								XmNrightAttachment,		XmATTACH_FORM,
								XmNrightOffset,			10,
								XmNmarginHeight,			5,
								XmNtraversalOn,			False,
								XmNlabelString,			string,
								XmNuserData,				grdData->Type () == DBTypeGridContinuous ? DBTableFieldIsNumeric : DBTableFieldIsCategory,
								NULL);
		XmStringFree (string);
		fromNameTextF = XtVaCreateManagedWidget ("RGISAnalyseLineSSampleNameTextF",xmTextFieldWidgetClass,mainForm,
								XmNtopAttachment,			XmATTACH_OPPOSITE_WIDGET,
								XmNtopWidget,				button,
								XmNrightAttachment,		XmATTACH_WIDGET,
								XmNrightWidget,			button,
								XmNrightOffset,			10,
								XmNbottomAttachment,		XmATTACH_OPPOSITE_WIDGET,
								XmNbottomWidget,			button,
								XmNmaxLength,				DBStringLength,
								XmNcolumns,					DBStringLength / 2,
								NULL);
		XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _RGIAnalyseLineSSampleGridSSelectCBK,fromNameTextF);
		string = XmStringCreate ((char *) "From Field:",UICharSetBold);
		XtVaCreateManagedWidget ("RGISAnalyseLineSSampleNameLabel",xmLabelWidgetClass,mainForm,
								XmNtopAttachment,			XmATTACH_OPPOSITE_WIDGET,
								XmNtopWidget,				button,
								XmNleftAttachment,		XmATTACH_FORM,
								XmNleftOffset,				10,
								XmNrightAttachment,		XmATTACH_WIDGET,
								XmNrightWidget,			fromNameTextF,
								XmNrightOffset,			10,
								XmNbottomAttachment,		XmATTACH_OPPOSITE_WIDGET,
								XmNbottomWidget,			button,
								XmNlabelString,			string,
								NULL);
		XmStringFree (string);

		string = XmStringCreate ((char *) "Select",UICharSetBold);
		button = XtVaCreateManagedWidget ("RGISAnalyseLineSSampleNameButton",xmPushButtonWidgetClass,mainForm,
								XmNtopAttachment,			XmATTACH_WIDGET,
								XmNtopWidget,				button,
								XmNtopOffset,				10,
								XmNrightAttachment,		XmATTACH_FORM,
								XmNrightOffset,			10,
								XmNbottomAttachment,		XmATTACH_FORM,
								XmNbottomOffset,			10,
								XmNmarginHeight,			5,
								XmNtraversalOn,			False,
								XmNlabelString,			string,
								XmNuserData,				grdData->Type () == DBTypeGridContinuous ? DBTableFieldIsNumeric : DBTableFieldIsCategory,
								NULL);
		XmStringFree (string);
		toNameTextF = XtVaCreateManagedWidget ("RGISAnalyseLineSSampleNameTextF",xmTextFieldWidgetClass,mainForm,
								XmNtopAttachment,			XmATTACH_OPPOSITE_WIDGET,
								XmNtopWidget,				button,
								XmNrightAttachment,		XmATTACH_WIDGET,
								XmNrightWidget,			button,
								XmNrightOffset,			10,
								XmNbottomAttachment,		XmATTACH_OPPOSITE_WIDGET,
								XmNbottomWidget,			button,
								XmNmaxLength,				DBStringLength,
								XmNcolumns,					DBStringLength / 2,
								NULL);
		XtAddCallback (button,XmNactivateCallback,(XtCallbackProc) _RGIAnalyseLineSSampleGridSSelectCBK,toNameTextF);
		string = XmStringCreate ((char *) "To Field:",UICharSetBold);
		XtVaCreateManagedWidget ("RGISAnalyseLineSSampleNameLabel",xmLabelWidgetClass,mainForm,
								XmNtopAttachment,			XmATTACH_OPPOSITE_WIDGET,
								XmNtopWidget,				button,
								XmNleftAttachment,		XmATTACH_FORM,
								XmNleftOffset,				10,
								XmNrightAttachment,		XmATTACH_WIDGET,
								XmNrightWidget,			toNameTextF,
								XmNrightOffset,			10,
								XmNbottomAttachment,		XmATTACH_OPPOSITE_WIDGET,
								XmNbottomWidget,			button,
								XmNlabelString,			string,
								NULL);
		XmStringFree (string);
		XtAddCallback (UIDialogFormGetOkButton (dShell),XmNactivateCallback,(XtCallbackProc) UIAuxSetBooleanTrueCBK,&sample);
		}

	sample = false;
	UIDialogFormPopup (dShell);
	while (UILoop ())
		{
		allowOk = false;
		fText = XmTextFieldGetString (fromNameTextF);
		if (strlen (fText) > 0) allowOk = true;
		XtFree (fText);
		fText = XmTextFieldGetString (toNameTextF);
		if (strlen (fText) > 0) allowOk = true;
		XtFree (fText);
		XtSetSensitive (UIDialogFormGetOkButton (dShell),allowOk);
		}
	UIDialogFormPopdown (dShell);

	if (sample)
		{
		DBInt ret;
		DBFloat value;
		DBCoordinate coord;
		DBGridIF *gridIF = new DBGridIF (grdData);
		DBVLineIF *lineIF = new DBVLineIF (dbData);
		DBObjTableField *fromField;
		DBObjTableField *toField;
		DBObjRecord *record;

		fText = XmTextFieldGetString (fromNameTextF);
		if (strlen (fText) > 0)
			{
			if ((fromField = itemTable->Field (fText)) == (DBObjTableField *) NULL)
				itemTable->AddField (fromField = new DBObjTableField (fText,DBTableFieldFloat,"%10.3f",sizeof (DBFloat4)));
			}
		else	fromField = (DBObjTableField *) NULL;
		XtFree (fText);
		fText = XmTextFieldGetString (toNameTextF);
		if (strlen (fText) > 0)
			{
			if ((toField = itemTable->Field (fText)) == (DBObjTableField *) NULL)
				itemTable->AddField (toField = new DBObjTableField (fText,DBTableFieldFloat,"%10.3f",sizeof (DBFloat4)));
			}
		else	toField = (DBObjTableField *) NULL;
		XtFree (fText);

		UIPauseDialogOpen ((char *) "Sampling Grid");
		for (record = itemTable->First ();record != (DBObjRecord *) NULL;record = itemTable->Next ())
			{
			if (UIPause (record->RowID () * 100 / itemTable->ItemNum ())) goto Stop;
			if (fromField != (DBObjTableField *) NULL)
				{
				coord = lineIF->FromCoord (record);
				ret = gridIF->Value (coord,&value);
				if (fromField->Type () == DBTableFieldFloat)
					{
					if (ret)	fromField->Float (record,value);
					else		fromField->Float (record,fromField->FloatNoData ());
					}
				else
					{
					if (ret)	fromField->Int (record,(DBInt) value);
					else		fromField->Int (record,fromField->IntNoData ());
					}
				}
			if (toField != (DBObjTableField *) NULL)
				{
				coord = lineIF->ToCoord (record);
				ret = gridIF->Value (coord,&value);
				if (toField->Type () == DBTableFieldFloat)
					{
					if (ret)	toField->Float (record,value);
					else		toField->Float (record,toField->FloatNoData ());
					}
				else
					{
					if (ret)	toField->Int (record,(DBInt) value);
					else		toField->Int (record,toField->IntNoData ());
					}
				}
			}
Stop:
		UIPauseDialogClose ();
		delete lineIF;
		delete gridIF;
		}
	}
Exemple #27
0
int main (int argc,char *argv [])
	{
	int argPos, argNum = argc, numGrpNames = 0, i = 0;
	char **groupnames, *rename = (char *) NULL, *tableName = (char *) NULL;
	bool ascii = false;
	FieldOptions *head = (FieldOptions *) NULL, *p = (FieldOptions *) NULL, *temp = (FieldOptions *) NULL;
	Groups **groups = (Groups **) NULL;
	FILE *outFile = (FILE *) NULL;
	DBObjData *inData, *outData;
	DBObjTable *inTable, *outTable;
	DBObjTableField *field;
	DBObjRecord *inRecord, *outRecord;
	DBObjectLIST<DBObjTableField> *fields;

	if(argc <= 2) { doHelp(false,argv[0]); return(DBSuccess); }
	outData = new DBObjData("Untitled", DBTypeTable);
	outTable = outData->Table(DBrNItems);

	head = new FieldOptions(BAD,"","", (FieldOptions *) NULL);
	groupnames = (char **) malloc(sizeof(char *));

	for (argPos = 1;argPos < argNum;)
		{
		if (CMargTest(argv[argPos],"-f","--field"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing operation and field after -f!"); return (CMfailed); }
			if(!strcmp(argv[argPos],"pct"))
				{
				if (argNum <= argPos + 2)
					{ CMmsgPrint (CMmsgUsrError,"Missing field and/or percentage after -f pct!"); return (CMfailed); }
				p = FOHierarchy(argv[argPos],argv[argPos+1],rename,atoi(argv[argPos+2]),head);
				argNum = CMargShiftLeft(argPos,argv,argNum);
				argNum = CMargShiftLeft(argPos,argv,argNum);
				}
			else if(!strcmp(argv[argPos],"num"))
				{
				char *num = new char[4];
				strcpy(num,"Num");
				p = FOHierarchy(argv[argPos],num,rename,-1,head);
				}
			else
				{
				if (argNum < argPos + 1)
					{ CMmsgPrint (CMmsgUsrError,"Missing operation or field after -f %s!",argv[argPos]); return (CMfailed); }
				p = FOHierarchy(argv[argPos],argv[argPos+1],rename,-1,head);
				argNum = CMargShiftLeft(argPos,argv,argNum);
				}
			p->setPrint(true);
			rename = (char *) NULL;
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-g","--group"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing groupname!"); return (CMfailed); }
			if((groupnames = (char **) realloc(groupnames,(numGrpNames + 1) * sizeof(char *))) == (char **) NULL)
				{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(DBFault); }
			groupnames[numGrpNames] = argv[argPos];
			numGrpNames++;
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-h","--help"))
			{
			argNum = CMargShiftLeft (argPos,argv,argNum);
			if(CMargTest(argv[argPos],"e","extend"))
				{
				doHelp(true,argv[0]);
				argNum = CMargShiftLeft (argPos,argv,argNum);
				}
			else doHelp(false,argv[0]);
			}
		if (CMargTest(argv[argPos],"-c","--ascii"))
			{
			ascii = true;
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-a","--table"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing table name!"); return (CMfailed); }
			tableName = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-r","--rename"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing field after -r!"); return (CMfailed); }
			rename = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-o","--output"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing output filename!"); return (CMfailed); }
			if((outFile = fopen(argv[argPos],"w")) == (FILE *) NULL)
				{ CMmsgPrint (CMmsgUsrError,"Cannot open file %s",argv[argPos]); return (CMfailed); }
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-t","--title"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing title!"); return (CMfailed); }
			outData->Name(argv[argPos]);
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-s","--subject"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing subject!"); return (CMfailed); }
			outData->Document(DBDocSubject,argv[argPos]);
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-d","--domain"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing domain!"); return (CMfailed); }
			outData->Document(DBDocGeoDomain,argv[argPos]);
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if (CMargTest(argv[argPos],"-v","--version"))
			{
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing version!"); return (CMfailed); }
			outData->Document(DBDocVersion,argv[argPos]);
			if ((argNum = CMargShiftLeft(argPos,argv,argNum)) <= argPos) break;
			continue;
			}
		if ((argv[argPos][0] == '-') && (strlen (argv[argPos]) > 1))
			{ CMmsgPrint (CMmsgUsrError, "Unknown option: %s!",argv[argPos]); return (CMfailed); }
		argPos++;
		}

	if(outFile == (FILE *) NULL) outFile = stdout;
	if(head->next == (FieldOptions *) NULL) return(DBSuccess);

	inData = new DBObjData();
	if ((argNum > 1) && (strcmp(argv[1],"-") != 0)) inData->Read(argv[1]);
	else inData->Read(stdin);

	if (outData->Name() == (char *) NULL) outData->Name("Untitled");
	if (outData->Document(DBDocSubject) == (char *) NULL) outData->Document(DBDocSubject,inData->Document(DBDocSubject));
	if (outData->Document(DBDocGeoDomain) == (char *) NULL) outData->Document(DBDocGeoDomain,inData->Document(DBDocGeoDomain));
	if (outData->Document(DBDocVersion) == (char *) NULL) outData->Document(DBDocVersion,inData->Document(DBDocVersion));

	if(tableName == (char *) NULL) tableName = DBrNItems;
	if((inTable = inData->Table(tableName)) == (DBObjTable *) NULL)
		{ CMmsgPrint (CMmsgUsrError,"Invalid table!"); delete inData; return (CMfailed); }

	if((groups = (Groups **) malloc(numGrpNames * sizeof(Groups *))) == (Groups **) NULL)
		{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(DBFault); }
	for(i = 0; i < numGrpNames; i++)
		{
		if((field = inTable->Field(groupnames[i])) == (DBObjTableField *) NULL)
			{ CMmsgPrint (CMmsgUsrError, "Invalid group name: %s",groupnames[i]); return (CMfailed); }
		if(DBTableFieldIsCategory(field))
			{
			groups[i] = new Groups();
			groups[i]->srcFLD = field;
			groups[i]->dstFLD = new DBObjTableField(*field);
			outTable->AddField(groups[i]->dstFLD);
//			CMmsgPrint (CMmsgUsrError, "Added Group: %s",groups[i]->dstFLD->Name());
			}
		else CMmsgPrint (CMmsgUsrError, "Group %s is not Category!",groupnames[i]);
		}
	delete groupnames;

	p = head->next;
	temp = head;
	while(p->next)
		{
		FieldOptions *duplicate = (FieldOptions *) NULL, *prev = p;
		if(!p->getPrint() && FLDExists(p,p->getOldName(),p->getFunc(),&duplicate))
			{ temp->next = p->next; delete p; p = temp->next; continue; }
		while(FLDExists(prev,prev->getOldName(),prev->getFunc(),&prev,&duplicate) && !duplicate->getPrint())
			{ prev->next = duplicate->next; delete duplicate; }
		temp = p;
		p = p->next;
		}
//	p = head->next;
//	while(p) { CMmsgPrint (CMmsgUsrError, "Added: o:%s n:%s p:",p->getOldName(),p->getNewName()); if(p->getPrint()) CMmsgPrint (CMmsgUsrError, "true"); else CMmsgPrint (CMmsgUsrError, "false"); p = p->next; }

	fields = inTable->Fields();
	p = head->next;
	while(p)
		{
		field = fields->Item (p->getOldName());
		if (p->getFunc() == MIN || p->getFunc() == MAX)
			p->field = new DBObjTableField(p->getNewName(),field->Type(),field->Format(),field->Length());
		else if(p->getFunc() == NUM || p->getFunc() == NONNULL)
			p->field = new DBObjTableField(p->getNewName(), DBTableFieldInt, DBHiddenField, sizeof (DBInt));
		else p->field = new DBObjTableField(p->getNewName(), DBTableFieldFloat, DBHiddenField, sizeof(DBFloat));
		if(p->getFunc() != NUM && p->getFunc() != NONNULL)
			{
//			if ((field = inTable->Field(p->getOldName())) == (DBObjTableField *) NULL)
			if (field == (DBObjTableField *) NULL)
				{
				CMmsgPrint (CMmsgUsrError, "Invalid field name: %s",p->getOldName());
				return(DBFault);
				}
			if (!DBTableFieldIsNumeric(field))
				{
				CMmsgPrint (CMmsgUsrError, "Field is not Numeric: %s",p->getOldName());
				return(DBFault);
				}
			}
		outTable->AddField(p->field);
		p = p->next;
		}
// MAKE SURE TO TEST FOR SPEED BY DECLARING INTS OUTSIDE OF FOR LOOPS!!!

	for (int inRecID = 0;inRecID < inTable->ItemNum();++inRecID)
		{
		inRecord = inTable->Item(inRecID);
		if ((outRecord = FindMatch(inRecord, outTable,(const Groups**) groups, numGrpNames)) != (DBObjRecord *) NULL)
			{
			p = head->next;
			while(p)
				{
				field = fields->Item (p->getOldName());
				switch(p->getFunc())
					{
					default:
						break;
					case NUM:
						p->field->Int(outRecord,p->field->Int(outRecord) + 1);
						break;
					case NONNULL:
						if (p->isInt())
							{
							if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,p->field->Int(outRecord) + 1);
							}
						else
							{
							if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData()))
								p->field->Int(outRecord,p->field->Int(outRecord) + 1);
							}
						break;
					case MIN:
						if (p->isInt())
							{
							if(field->Int(inRecord) != field->IntNoData())
								{
								if (p->field->Int(outRecord) != p->field->IntNoData())
									{ if (field->Int(inRecord) < p->field->Int(outRecord)) p->field->Int(outRecord,field->Int(inRecord)); }
								else { p->field->Int(outRecord,field->Int(inRecord)); }
								}
							}
						else
							{
							if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData()))
								{
								if (!CMmathEqualValues(p->field->Float(inRecord),p->field->FloatNoData()))
									{ if (field->Float(inRecord) < p->field->Float(outRecord)) p->field->Float(outRecord,field->Float(inRecord)); }
								else { p->field->Float(outRecord,field->Float(inRecord)); }
								}
							}
						break;
					case MAX:
						if (p->isInt())
							{
							if(field->Int(inRecord) != field->IntNoData())
								{
								if (p->field->Int(outRecord) != p->field->IntNoData())
									{ if (field->Int(inRecord) > p->field->Int(outRecord)) p->field->Int(outRecord,field->Int(inRecord)); }
								else { p->field->Int(outRecord,field->Int(inRecord)); }
								}
							}
						else
							{
							if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData()))
								{
								if (!CMmathEqualValues(p->field->Float(inRecord),p->field->FloatNoData()))
									{ if (field->Float(inRecord) > p->field->Float(outRecord)) p->field->Float(outRecord,field->Float(inRecord)); }
								else { p->field->Float(outRecord,field->Float(inRecord)); }
								}
							}
						break;
					case SUM:
						if (p->isInt())
							{
							if(field->Int(inRecord) != field->IntNoData())
								p->field->Int(outRecord,p->field->Int(outRecord) + field->Int(inRecord));
							}
							else
							{
							if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData()))
								p->field->Float(outRecord,p->field->Float(outRecord) + field->Float(inRecord));
							}
						break;
					case DEV:
					case PCT:
					case MED:
						p->tailVal = p->tailVal->next = new Values();
						p->tailVal->val = field->Float(inRecord);
						p->tailVal->next = 0;
						break;
					case MOD:
						Values *cur = p->getHead();
						while(cur->next && !CMmathEqualValues(cur->val,field->Float(inRecord))) cur = cur->next;
						if(cur->next) cur->occur++;
						else
							{
							p->tailVal->val = field->Float(inRecord);
							p->tailVal->occur = 1;
							p->tailVal = p->tailVal->next = new Values();
							}
						break;
					}
				p = p->next;
				}
			}
		else
			{
			outRecord = outTable->Add();

			for(i = 0; i < numGrpNames; i++)
				{
				switch (groups[i]->srcFLD->Type())
					{
					default:
					case DBTableFieldString:
						groups[i]->dstFLD->String(outRecord,groups[i]->srcFLD->String(inRecord));
						break;
					case DBTableFieldInt:
						groups[i]->dstFLD->Int(outRecord,groups[i]->srcFLD->Int(inRecord));
						break;
					}
				}
			p = head->next;
			while(p)
				{
				field = fields->Item (p->getOldName());
				switch(p->getFunc())
					{
					default:
					case BAD:
						break;
					case NUM:
						p->setInt();
						p->field->Int(outRecord,1);
						break;
					case NONNULL:
						if (field->Type() == DBTableFieldInt)
							{
							p->setInt();
							if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,1);
							else p->field->Int(outRecord,0);
							}
						else
							{
							if (!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Int(outRecord,1);
							else p->field->Int(outRecord,0);
							}
						break;
					case MIN:
						if (field->Type() == DBTableFieldInt)
							{ p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); }
						else
							{
							if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData()))
								p->field->Float(outRecord,field->Float(inRecord));
							}
						break;
					case MAX:
						if (field->Type() == DBTableFieldInt)
							{ p->setInt(); if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord)); }
						else
							{
							if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData()))
								p->field->Float(outRecord,field->Float(inRecord));
							}
						break;
					case SUM:
						if (field->Type() == DBTableFieldInt)
							{
							p->setInt();
							if (field->Int(inRecord) != field->IntNoData()) p->field->Int(outRecord,field->Int(inRecord));
							else p->field->Int(outRecord,0);
							}
						else
							{
							if(!CMmathEqualValues(field->Float(inRecord),field->FloatNoData())) p->field->Float(outRecord,field->Float(inRecord));
							else p->field->Float(outRecord,0.0);
							}
						break;
					case DEV:
					case PCT:
					case MED:
						p->tailVal = p->tailVal->next = new Values();
						p->tailVal->val = field->Float(inRecord);
						p->tailVal->next = 0;
						break;
					case MOD:
						p->tailVal->val = field->Float(inRecord);
						p->tailVal->occur = 1;
						p->tailVal = p->tailVal->next = new Values();
						break;
					}
				p = p->next;
				}
			}
		}

	for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID)
		{
		outRecord = outTable->Item(outRecID);
		p = head->next;
		FieldOptions *sum, *num;
		DBFloat mod;
		int occurrance;
		float i;
		bool mult;
		Values *cur;
		while(p)
			{
			field = fields->Item (p->getOldName());
			switch(p->getFunc())
				{
				case AVG:
					if((FLDExists(head,p->getOldName(),SUM,&sum)) && (FLDExists(head,p->getOldName(),NONNULL,&num)))
						p->field->Float(outRecord,sum->field->Float(outRecord) / (DBFloat) (num->field->Int(outRecord)));
					else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find SUM or NONNULL in linked list! Please contact the GHAAS developers group!");
					break;
				case NAVG:
					if((FLDExists(head,p->getOldName(),SUM,&sum)) && (FLDExists(head,"NUM",NUM,&num)))
						p->field->Float(outRecord,sum->field->Float(outRecord) / (DBFloat) (num->field->Int(outRecord)));
					else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find SUM or NUM in linked list! Please contact the GHAAS developers group!");
					break;
				case PCT:
				case MED:
					i = (float) (inTable->ItemNum() * p->getHead()->occur * 0.01) - 1;
					cur = p->getHead()->next;
					while(i > 0) { cur = cur->next; i--; }
					p->field->Float(outRecord,(cur->val + cur->next->val) / 2);
					break;
				case MOD:
					mod = 0.0;
					occurrance = 0;
					mult = false;
					cur = p->getHead();
					while(cur)
						{
						if(cur->occur > occurrance)
							{
							mod = cur->val;
							occurrance = cur->occur;
							mult = false;
							}
						else if(cur->occur == occurrance) mult = true;
						cur = cur->next;
						}
					if(mult) CMmsgPrint (CMmsgUsrError, "** Warning, multiple answers for MOD, listing first found!");
					p->field->Float(outRecord,mod);
					break;
				default:
					break;
				}
			p = p->next;
			}
		}

	p = head->next;
	while(p)
		{
		if(p->getFunc() == DEV)
			{
			FieldOptions *avg, *num;
			field = fields->Item (p->getOldName());
			if((FLDExists(head,p->getOldName(),AVG,&avg)) && (FLDExists(head,"NUM",NUM,&num)))
				{
				for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID)
					{
					outRecord = outTable->Item(outRecID);
					DBFloat sum = 0.0;
					Values *cur = p->getHead()->next;
					while(cur)
						{
//						sum += (DBFloat) (pow((cur->val - avg->field->Float(outRecord)),2));
						DBFloat add = (cur->val - avg->field->Float(outRecord));
						sum += (DBFloat) (add * add);
						cur = cur->next;
						}
					sum = sqrt(sum /(DBFloat) num->field->Int(outRecord));
					p->field->Float(outRecord,sum);
					}
				}
			else CMmsgPrint (CMmsgUsrError, "Program Error! Could not find AVG or NUM in linked list! Please contact the GHAAS developers group!");
			}
		p = p->next;
		}
// DELETE unnecessary fields which were for temp storage
	fields = outTable->Fields();
	p = head->next;
	while(p)
		{
		if(!p->getPrint()) outTable->DeleteField(fields->Item(p->getNewName()));
		p = p->next;
		}

	p = head->next;
	while(p)
		{
		if ((strcmp(p->field->Format(),DBHiddenField) == 0) && p->getPrint())
			{
			if(p->isInt())
				{
				int maxval = 0;
				for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID)
					{
					int val = p->field->Int(outTable->Item(outRecID));
					if (maxval < val) maxval = val; else if (maxval < -val) maxval = -val;
					}
				p->field->Format(DBMathIntAutoFormat(maxval));
				}
			else
				{
				float maxval = 0.0;
				for(int outRecID = 0; outRecID < outTable->ItemNum();++outRecID)
					{
					float val = p->field->Float(outTable->Item(outRecID));
					if (maxval < val) maxval = val; else if (maxval < -val) maxval = -val;
					}
				p->field->Format(DBMathFloatAutoFormat(maxval));
				}
			}
//		CMmsgPrint (CMmsgUsrError, "Format(%s)%d,%d: '%s'",p->getFuncName(),p->isInt(),p->getPrint(),p->field->Format());
		p = p->next;
		}

	DBObjectLIST<DBObjTableField> *list = new DBObjectLIST<DBObjTableField> ("Sorted Field List");
	for(i = 0; i < numGrpNames; i++) list->Add(groups[i]->dstFLD);
	outTable->ListSort(list);

if (ascii) DBExportASCIITable(outTable,outFile); else outData->Write(outFile);

/* CLEANUP ************************************************/
	if(outFile != stdout) fclose(outFile);
	for(i = 0; i < numGrpNames; i++) delete groups[i]->dstFLD;
	delete groups;
	p = head;
	while(p)
		{
		head = head->next;
		delete p;
		p = head;
		}
	return(DBSuccess);

}