void write(const std::string& line) { if (SOCKET_ERROR == send(sock, line.c_str(), line.size(), 0)) { std::cerr << "Error: couldn't send a packet to the server.\n"; bomb(0); } }
UnitsEdit *UnitsEditPage::addEdit( const QString &labelKey, const char **varList, const char **unitsList, int row, bool showDecimals ) { // Find the variable EqVar *varPtr = m_dialog->m_bp->m_eqTree->m_varDict->find( varList[0] ); if ( ! varPtr ) // This code block should never be executed! { QString text(""); translate( text, "UnitsEditDialog:UnknownVar", varList[0] ); bomb( text ); } // Create the QLabel QString text(""); translate( text, labelKey ); QLabel *label = new QLabel( text, m_frame, QString( "%1:Label" ).arg( labelKey ) ); Q_CHECK_PTR( label ); m_grid->addMultiCellWidget( label, row, row, 0, 0, AlignLeft ); // Create the combo box QComboBox *combo = new QComboBox( false, m_frame, QString( "%1:ComboBox" ).arg( labelKey ) ); Q_CHECK_PTR( combo ); // Insert items into the combo box while searching for the current item int n = 0; for ( int id = 0; unitsList[id]; id++ ) { combo->insertItem( unitsList[id] ); if ( appSiUnits()->equivalent( unitsList[id], varPtr->m_displayUnits.latin1() ) ) { n = id; } } combo->setCurrentItem( n ); m_grid->addMultiCellWidget( combo, row, row, 1, 1 ); // Create the spin box QSpinBox *spin = NULL; if ( showDecimals ) { spin = new QSpinBox( 0, 6, 1, m_frame, QString( "%1:SpinBox" ).arg( labelKey ) ); Q_CHECK_PTR( spin ); spin->setValue( varPtr->m_displayDecimals ); m_grid->addMultiCellWidget( spin, row, row, 2, 2 ); } // All rows share the available space equally m_grid->setRowStretch( row, 10 ); // Create the new UnitsEdit UnitsEdit *edit = new UnitsEdit( varList, varPtr, combo, spin ); checkmem( __FILE__, __LINE__, edit, "UnitsEdit edit", 1 ); // Add the UnitsEdit to the UnitEditPage's m_editList m_editList->append( edit ); return( edit ); }
long RHBvalue::read_octal_value(const char *p) { long x=0; while (*p) { long d=0; switch (*p) { case '0': d=0; break; case '1': d=1; break; case '2': d=2; break; case '3': d=3; break; case '4': d=4; break; case '5': d=5; break; case '6': d=6; break; case '7': d=7; break; default: bomb("invalid char"); } x<<=3; x+=d; p++; } return x; }
void Shuttle::fire(){ Bomb bomb(*this, sf::Vector2f(0,-5)); bomb.setStage(__stage__); bomb.shoot(); ///sf::Thread thread(&Bomb::shoot, &bomb); //thread.launch(); }
void *array_1d(long size, long lower_index, long upper_index) { char *ptr; if (!(ptr=tmalloc((unsigned)size*(upper_index-lower_index+1)))) bomb("unable to allocate array (array_1d)", NULL); ptr -= lower_index*size; return((void*)ptr); }
int main(int argc, char *argv[]) { WINDOW *p, *s1, *s2, *s3; FILE *f; int ch; initscr(); refresh(); /* create a new pad */ p = newpad(200, WIDE + 1); if( p == NULL ) bomb("Unable to create new pad\n"); /* create three subpads */ s1 = subpad(p, TALL, WIDE + 1, 0, 0); if( s1 == NULL ) bomb("Unable to create subpad 1\n"); s2 = subpad(p, TALL, WIDE + 1, TALL, 0); if( s2 == NULL ) bomb("Unable to create subpad 2\n"); s3 = subpad(p, TALL, WIDE + 1, 2 * TALL, 0); if( s3 == NULL ) bomb("Unable to create subpad 3\n"); /* open the file */ f = fopen(FILENAME, "r"); if( f == NULL ) bomb("Unable to open the file\n"); /* display the file's contents on the pad */ while( (ch = fgetc(f)) != EOF) waddch(p, ch); fclose(f); /* display the pad's contents on the screen */ prefresh(s1, 0, 0, 0, 0, TALL - 1, WIDE); prefresh(s2, 0, 0, 0, WIDE + SPACER, TALL - 1, WIDE * 2 + SPACER); prefresh(s3, 0, 0, 0, WIDE * 2 + SPACER * 2, TALL - 1, WIDE * 3 + SPACER * 2); wgetch(p); endwin(); return 0; }
voidProc GetProc(const char *name) { voidProc p=(voidProc)GetProcAddress(get_dll(),name); if (!p) { bomb(GetLastError()); } return p; }
void ChrsGrid::goCrush() { //注意:最后一个不删除,等待特殊类型判断后处理之 m_bonus = 0; for (int i = 0; i < m_SelectedChrs.size(); i++) { auto chr = m_SelectedChrs.at(i); //汉字元素消除 chr->bomb(); } }
double ipow(double x, long p) { register double hp; register long n; if (!x) { if (p<0) bomb("Floating divide by zero in ipow().", NULL); return(p==0?1.:0.); } if (p<0) return(1./ipow(x, -p)); switch (p) { case 0: return(1.); case 1: return(x); case 2: return(x*x); case 3: hp = x*x; return(hp*x); case 4: hp = x*x; return(hp*hp); case 5: hp = x*x; return(hp*hp*x); case 6: hp = x*x; return(hp*hp*hp); case 7: hp = x*x*x; return(hp*hp*x); case 8: hp = x*x; hp = hp*hp; return(hp*hp); default: n = p/2; hp = ipow(x, n); switch (p-2*n) { case 0: return(hp*hp); case 1: return(hp*hp*x); } break; } return(0.); /* never actually executed--keeps compiler happy */ }
int main(void) { initscr(); /* first test for color ability of the terminal */ if(!has_colors()) bomb(1); /* next attempt to initialize curses colors */ if(start_color() != OK) bomb(2); /* colors are okay; continue */ printw("Colors have been properly initialized.\n"); printw("Congratulations!\n"); printw("Curses reports that you can use %d colors,\n",COLORS); printw("and %d color pairs.",COLOR_PAIRS); refresh(); getch(); endwin(); return 0; }
int placeBomb(int row, int col) { int ret = -1; //Ok row, col #s....nvr bombed area before if((row<10 && row >=0) && (col<10 && col >=0) && board[row][col]<0) { ret = bomb(row, col); board[row][col] = ret; lcd.cls(); numBombs++; lcd.printf("B(%d, %d) = %d\n%d bombs used",row, col, ret, numBombs); print("Bombing: R %d C %d - %d bombs used", row, col, numBombs); } return ret; }
long powellMinStep(double *yReturn, double *xReturn, double **dirVector, double **P, double *xLower, double *xUpper, long dims, double target, long linMinIterations, long limitGoodSteps, double (*func)(double *x, long *invalid)) { long i, invalid, evals; double *yValue, yExtrap, *PExtrap=NULL, dyMax, dy; if (!(yValue=malloc(sizeof(*yValue)*(dims+1))) || !(PExtrap=malloc(sizeof(*PExtrap)*dims))) bomb("memory allocation failure (powellMinStep)", NULL); memcpy(P[0], xReturn, sizeof(*xReturn)*dims); yValue[0] = *yReturn; dyMax = -DBL_MAX; evals = 0; for (i=1; i<=dims; i++) { #if DEBUG fprintf(stderr, ">> Scanning %ld\n", i-1); #endif memcpy(P[i], P[i-1], sizeof(**P)*dims); yValue[i] = yValue[i-1]; evals += powellMoveToMin(yValue+i, P[i], PExtrap, dirVector[i-1], xLower, xUpper, dims, linMinIterations, limitGoodSteps?3:0, func); if ((dy=yValue[i]-yValue[i-1])>dyMax) dyMax = dy; } if (dyMax == -DBL_MAX) return evals; for (i=0; i<dims; i++) PExtrap[i] = 2*P[dims][i]-P[0][i]; yExtrap = (*func)(PExtrap, &invalid); if (invalid) yExtrap = 1e9*yValue[0]; if (!(yExtrap>=yValue[0] || 2*(yValue[0]-2*yValue[dims]+yExtrap)* sqr(yValue[0]-yValue[dims]-dyMax)>=sqr(yValue[0]-yExtrap)*dyMax)) { /* exchange dir vectors */ for (i=0; i<dims-1; i++) memcpy(dirVector[i], dirVector[i+1], sizeof(**dirVector)*dims); for (i=0; i<dims; i++) dirVector[dims-1][i] = P[dims][i]-P[0][i]; } memcpy(xReturn, P[dims], sizeof(*xReturn)*dims); *yReturn = yValue[dims]; free(yValue); free(PExtrap); return evals; }
int main(void){ initscr(); if (!has_colors()) bomb("Terminal cannot do colors\n"); printw("Colors have been properly initialized"); printw("Congratulations!\n"); printw("NCurses reports that you are using %d colors,\n", COLORS); printw("and %d color pairs.", COLOR_PAIRS); refresh(); getch(); endwin(); return 0; }
/*! Функция открывает, то что скрыто под блоком */ void bomb_item::open() { if(type == 'b' && !isFlagged) {//Отрисовываем бомбу там где игрок не отметил ее QPixmap img = block_pressed; QPixmap bomb(":/Saper/bomb.png"); bomb = bomb.scaled(cur_block.size()); QPainter pr; pr.begin(&img); pr.drawPixmap(bomb.rect(),bomb); pr.end(); cur_block = img; } isPressed = true; update(); }
void UnitsEditDialog::store( void ) { UnitsEditPage *page; UnitsEdit *edit; EqVar *varPtr; QString newUnits; int newDecimals; // Loop for each UnitsEditPage in this UnitsEditDialog. for ( page = m_pageList->first(); page != 0; page = m_pageList->next() ) { // Loop for each UnitsEdit item on this UnitsEditPage for ( edit = page->m_editList->first(); edit != 0; edit = page->m_editList->next() ) { // Get the current units and decimals newUnits = edit->m_combo->currentText(); newDecimals = ( edit->m_spin == NULL ) ? -1 : edit->m_spin->value(); varPtr = edit->m_var; // Reset units of each EqVar in the UnitEdit item's m_varList[] varPtr->setDisplayUnits( newUnits, newDecimals ); for ( int id = 1; edit->m_varList[id]; id++ ) { // Find the variable EqVar *varPtr = m_bp->m_eqTree->m_varDict->find( edit->m_varList[id] ); if ( ! varPtr ) // This code block should never be executed! { QString text(""); translate( text, "UnitsEditDialog:UnknownVar", edit->m_varList[id] ); bomb( text ); } varPtr->setDisplayUnits( newUnits, newDecimals ); } } } // Ok, all the edited units have been stored to their variables. // Now save it to a file m_bp->save( "", "Units Set" ); return; }
static PLI_INT32 regfileTestCompileTf() { vpiHandle sys = vpi_handle(vpiSysTfCall, 0); vpiHandle argv = vpi_iterate(vpiArgument, sys); vpiHandle arg = NULL; init(); /* Check for arguments number */ for (int i=0; i < ARGS_NR; i++) { arg = vpi_scan(argv); assert(arg); args[i].handle = arg; char* name = vpi_get_str(vpiName, arg); if (!(args[i].name = copy_string(args[i].name, name))) bomb(); } return 0; }
bool turn(Labyrinth &map) { take_objects_from_cell(map, map.player[map.current_player]); if (DEBUG) print_debug(map); user_message(map.player[map.current_player].name + ", it's your turn"); string message = map.player[map.current_player].name + ", enter what you want (go, bomb, shoot, knife, suicide, stay, leave"; if (SERVER) message += ")"; else message += ", save)"; user_message(message); if (SERVER) server.clear_user_messages(map.current_player); string s = read_user_command(map.current_player); if (s == "leave") return leave_game(map, map.player[map.current_player]); if (s == "suicide") return suicide(map, map.player[map.current_player]); if (s == "knife") return use_knife(map, map.player[map.current_player]); if (s == "bomb") return bomb(map, map.player[map.current_player]); if (s == "go") return go(map, map.player[map.current_player]); if (s == "shoot") return shoot(map, map.player[map.current_player]); if (s == "stay") return stay(map.player[map.current_player]); if (s == "save" && !SERVER) { save_game(map); return false; } if (s == "winthemall") { if (is_developer(map.player[map.current_player])) { user_message("Okay, master"); finish_game(map); return true; } } user_message(map.player[map.current_player].name + ", you entered incorrect command! Try again, if you can!"); return false; }
void ResourceCache::LoadExtraResources(const TiXmlHandle& hndl) { const Size size = mAppConfig.GetCellSize(); ExtraResource speed(ExtraType::Speed, LoadTextures(hndl, "Speed", size)); ExtraResource bomb(ExtraType::Bombs, LoadTextures(hndl, "Bombs", size)); ExtraResource range(ExtraType::Range, LoadTextures(hndl, "Range", size)); ExtraResource range_gold(ExtraType::InfiniteRange, LoadTextures(hndl, "RangeGold", size)); ExtraResource kick(ExtraType::Kick, LoadTextures(hndl, "Kick", size)); ExtraResource remotebombs(ExtraType::RemoteBombs, LoadTextures(hndl, "RemoteBombs", size)); mExtraRes.insert({ speed.GetType(), speed }); mExtraRes.insert({ bomb.GetType(), bomb }); mExtraRes.insert({ range.GetType(), range }); mExtraRes.insert({ range_gold.GetType(), range_gold }); mExtraRes.insert({ kick.GetType(), kick }); mExtraRes.insert({ remotebombs.GetType(), remotebombs }); }
void Player::update(){ if(!active) return; x += xv; y += yv; if(x > gamew) x = gamew; if(y > gameh) y = gameh; if(x < 0) x = 0; if(y < 0) y = 0; if(cooldown > 0) cooldown--; if(cooldown2 > 0) cooldown2--; if(fire1) fire(); if(fire2) bomb(); draw(); }
long RHBvalue::read_hex_value(const char *p) { long x=0; while (*p) { long d=0; switch (*p) { case '0': d=0; break; case '1': d=1; break; case '2': d=2; break; case '3': d=3; break; case '4': d=4; break; case '5': d=5; break; case '6': d=6; break; case '7': d=7; break; case '8': d=8; break; case '9': d=9; break; case 'A': case 'a': d=10; break; case 'B': case 'b': d=11; break; case 'C': case 'c': d=12; break; case 'D': case 'd': d=13; break; case 'E': case 'e': d=14; break; case 'F': case 'f': d=15; break; default: bomb("invalid char"); } x<<=4; x+=d; p++; } return x; }
void renderGame() { renderMap(); // renders the character into the buffer renderCharacter(); // renders the character into the buffer renderMonster(); // renders Ghost renderGuards(); // renders guards projectile(); // projectile function bomb(); // bomb function Ultimate(); // ultimate skills function if (fight == BATTLE){ BossAttack(); if (elapsedTime > bossFightTime){ bossSpeed(); // Seeding bossFightTime = elapsedTime + 30; // map and boss pattern refreshes every 30 seconds for (int i = 0; i < MAP_HEIGHT; i++){ for (int j = 0; j < MAP_WIDTH; j++){ printMap[i][j] = BossMap[i][j]; } } } } }
HMODULE get_dll(void) { HMODULE h=NULL; DWORD dw=0; EnterCriticalSection(&cs); if (!hDll) { hDll=LoadLibrary(name); if (!hDll) dw=GetLastError(); } h=hDll; LeaveCriticalSection(&cs); if (!h) { bomb(dw); } return h; }
void game() { /* 指し手を変更したり,入力させたり,判定をしたり... */ /* 初期化 */ int field[ROW][COL] = {}; // フィールド(何もない = 0; 爆弾位置 = 1;) int open[ROW][COL] = {}; // マスがオープンされているか(フラグを立てた = -1, されてない = 0; されてる = 1;) int number[ROW][COL] = {}; // マスに表示する数値(爆弾 = -1, 何も表示しない = 0; 表示する = 1 以上;) int doukasen; int status = 0; printf("爆弾の数を決めてください\n"); scanf("%d",&doukasen); bomb(field,doukasen); // 爆弾位置を決定 defNumber(field, number); // 爆弾位置に応じて、1, 2, 3 みたいな数値を算出 printf("マインスイーパを開始します。(端末サイズを80x24にしてください)。\n"); while(1) { status = input(field, open, number); // 碁石の置く場所を入力,判定など if(status != 0) break; // もし,勝敗がついたなら,ループから抜ける } scanf("%d",&status); return; }
int main(int argc, char **argv) { SDDS_DATASET inSet, outSet; SCANNED_ARG *s_arg; char *input, *output, *zeroName, **columnName; long i_arg, i, pageReturned, rows, row, zrow; int32_t columnNames; double **indepData, *depenData, **slopeData, slope, offset; unsigned long pipeFlags, flags, majorOrderFlag; char s[SDDS_MAXLINE]; short columnMajorOrder=-1; SDDS_RegisterProgramName(argv[0]); argc = scanargs(&s_arg, argc, argv); if (argc<2 || argc>(2+N_OPTIONS)) bomb(NULL, USAGE); flags = pipeFlags = 0; input = output = NULL; zeroName = NULL; columnName = NULL; columnNames = 0; offset = 0; for (i_arg=1; i_arg<argc; i_arg++) { if (s_arg[i_arg].arg_type==OPTION) { switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) { case CLO_MAJOR_ORDER: majorOrderFlag=0; s_arg[i_arg].n_items--; if (s_arg[i_arg].n_items>0 && (!scanItemList(&majorOrderFlag, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0, "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER, "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER, NULL))) SDDS_Bomb("invalid -majorOrder syntax/values"); if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER) columnMajorOrder=1; else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER) columnMajorOrder=0; break; case CLO_PIPE: if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags)) SDDS_Bomb("invalid -pipe syntax"); break; case CLO_ZEROESOF: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("invalid -zeroesOf syntax"); zeroName = s_arg[i_arg].list[1]; break; case CLO_COLUMNS: if (s_arg[i_arg].n_items<2) SDDS_Bomb("invalid -columns syntax"); columnName = tmalloc(sizeof(*columnName)*(columnNames = s_arg[i_arg].n_items-1)); for (i=0; i<columnNames; i++) columnName[i] = s_arg[i_arg].list[i+1]; break; case CLO_SLOPEOUTPUT: flags |= FL_SLOPEOUTPUT; break; case CLO_OFFSET: if (s_arg[i_arg].n_items!=2 || sscanf(s_arg[i_arg].list[1], "%le", &offset)!=1) SDDS_Bomb("invalid -offset syntax"); break; default: fprintf(stderr, "Error (%s): unknown/ambiguous option: %s\n", argv[0], s_arg[i_arg].list[0]); exit(1); break; } } else { if (input==NULL) input = s_arg[i_arg].list[0]; else if (output==NULL) output = s_arg[i_arg].list[0]; else SDDS_Bomb("too many filenames"); } } processFilenames("sddszerofind", &input, &output, pipeFlags, 0, NULL); if (!zeroName) SDDS_Bomb("-zeroesOf option must be given"); if (!SDDS_InitializeInput(&inSet, input)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (!resolveColumnNames(&inSet, zeroName, &columnName, &columnNames) || !SDDS_InitializeOutput(&outSet, SDDS_BINARY, 0, NULL, "sddszerofind output", output) || !SDDS_TransferColumnDefinition(&outSet, &inSet, zeroName, NULL)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (columnMajorOrder!=-1) outSet.layout.data_mode.column_major = columnMajorOrder; else outSet.layout.data_mode.column_major = inSet.layout.data_mode.column_major; for (i=0; i<columnNames; i++) { sprintf(s, "%sSlope", columnName[i]); if (!SDDS_TransferColumnDefinition(&outSet, &inSet, columnName[i], NULL) || (flags&FL_SLOPEOUTPUT && !SDDS_TransferColumnDefinition(&outSet, &inSet, columnName[i], s))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_WriteLayout(&outSet)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); indepData = tmalloc(sizeof(*indepData)*columnNames); slopeData = tmalloc(sizeof(*slopeData)*columnNames); while ((pageReturned=SDDS_ReadPage(&inSet))>0) { if (!SDDS_StartPage(&outSet, 0)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if ((rows=SDDS_CountRowsOfInterest(&inSet))>1) { if (!(depenData = SDDS_GetColumnInDoubles(&inSet, zeroName))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); for (i=0; i<columnNames; i++) { if (!(indepData[i] = SDDS_GetColumnInDoubles(&inSet, columnName[i]))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (flags&FL_SLOPEOUTPUT) slopeData[i] = tmalloc(sizeof(**slopeData)*rows); } if (offset) for (row=0; row<rows; row++) depenData[row] += offset; for (zrow=row=0; row<rows-1; row++) { if ((depenData[row]<=0 && depenData[row+1]>=0) || (depenData[row]>=0 && depenData[row+1]<=0)) { for (i=0; i<columnNames; i++) { if (indepData[i][row]==indepData[i][row+1]) { if (flags&FL_SLOPEOUTPUT) slopeData[i][zrow] = DBL_MAX; indepData[i][zrow] = indepData[i][row]; } else { slope = (depenData[row+1]-depenData[row])/(indepData[i][row+1]-indepData[i][row]); if (flags&FL_SLOPEOUTPUT) slopeData[i][zrow] = slope; if (slope) indepData[i][zrow] = indepData[i][row] - depenData[row]/slope; else indepData[i][zrow] = (indepData[i][row] + indepData[i][row+1])/2; } } depenData[zrow] = -offset; zrow++; } } if (zrow) { if (!SDDS_LengthenTable(&outSet, zrow) || !SDDS_SetColumnFromDoubles(&outSet, SDDS_SET_BY_NAME, depenData, zrow, zeroName)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); for (i=0; i<columnNames; i++) { sprintf(s, "%sSlope", columnName[i]); if (!SDDS_SetColumnFromDoubles(&outSet, SDDS_SET_BY_NAME, indepData[i], zrow, columnName[i]) || (flags&FL_SLOPEOUTPUT && !SDDS_SetColumnFromDoubles(&outSet, SDDS_SET_BY_NAME, slopeData[i], zrow, s))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } free(depenData); for (i=0; i<columnNames; i++) free(indepData[i]); if (flags&FL_SLOPEOUTPUT) for (i=0; i<columnNames; i++) free(slopeData[i]); } if (!SDDS_WritePage(&outSet)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_Terminate(&inSet) || !SDDS_Terminate(&outSet)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } return(0); }
int main(int argc, char **argv) { FILE *fileID; COLUMN_DATA_STRUCTURES *columnValues; PARAMETER_DATA_STRUCTURES *parameterValues; SDDS_DATASET SDDS_dataset; SCANNED_ARG *s_arg; long i, j, k, n, i_arg; int32_t rows; int32_t maxRows=10000, initRows=10000, row; long par, col, page, size, readline=1, fillin=0; int32_t ptrSize=0; char *input, *output, s[1024], *ptr, *ptr2, data[10240],temp[10240]; unsigned long pipeFlags=0,majorOrderFlag; long noWarnings=0, tmpfile_used=0, columnOrder=0, whitespace=1; short shortValue; int32_t longValue; float floatValue; double doubleValue; char stringValue[SDDS_MAXLINE]; char characterValue; char buffer[124], buffer2[124]; long *parameterIndex, *columnIndex; long binary=0, noRowCount=0, inputBinary=0, count=0; char separator; char commentCharacters[20]; short checkComment=0; short commentFound; long parameters=0, columns=0; long skiplines=0; short abort=0, recover=1, columnMajorOrder=0; input = output = NULL; separator = ' '; columnValues = NULL; parameterValues = NULL; parameterIndex = columnIndex = NULL; SDDS_RegisterProgramName(argv[0]); argc = scanargs(&s_arg, argc, argv); if (argc<3) bomb(NULL, USAGE); for (i_arg=1; i_arg<argc; i_arg++) { if (s_arg[i_arg].arg_type==OPTION) { switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) { case SET_MAJOR_ORDER: majorOrderFlag=0; s_arg[i_arg].n_items -=1; if (s_arg[i_arg].n_items>0 && (!scanItemList(&majorOrderFlag, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0, "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER, "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER, NULL))) SDDS_Bomb("invalid -majorOrder syntax/values"); if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER) columnMajorOrder=1; else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER) columnMajorOrder=0; break; case SET_OUTPUTMODE: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("invalid -outputMode syntax"); switch (match_string(s_arg[i_arg].list[1], mode_name, MODES, 0)) { case ASCII_MODE: binary = 0; break; case BINARY_MODE: binary = 1; break; default: SDDS_Bomb("invalid -outputMode syntax"); break; } break; case SET_INPUTMODE: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("invalid -inputMode syntax"); switch (match_string(s_arg[i_arg].list[1], mode_name, MODES, 0)) { case ASCII_MODE: inputBinary = 0; break; case BINARY_MODE: inputBinary = 1; break; default: SDDS_Bomb("invalid -inputMode syntax"); break; } break; case SET_SEPARATOR: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("invalid -separator syntax"); separator = s_arg[i_arg].list[1][0]; whitespace = 0; break; case SET_COMMENT: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("invalid -commentCharacters syntax"); sprintf(commentCharacters, "%s", s_arg[i_arg].list[1]); checkComment=1; break; case SET_FILLIN: fillin=1; break; case SET_NOROWCOUNT: if (s_arg[i_arg].n_items!=1) SDDS_Bomb("invalid -noRowCount syntax"); noRowCount = 1; break; case SET_ORDER: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("invalid -order syntax"); switch (match_string(s_arg[i_arg].list[1], order_names, ORDERS, 0)) { case ROW_ORDER: columnOrder = 0; break; case COLUMN_ORDER: columnOrder = 1; break; default: SDDS_Bomb("invalid -order syntax"); break; } break; case SET_PARAMETER: if (s_arg[i_arg].n_items<3) SDDS_Bomb("invalid -parameter syntax"); count=1; parameters++; parameterValues = trealloc(parameterValues, sizeof(*parameterValues)*(parameters)); SDDS_CopyString(¶meterValues[parameters-1].name, s_arg[i_arg].list[1]); parameterValues[parameters-1].units = NULL; parameterValues[parameters-1].description = NULL; parameterValues[parameters-1].symbol = NULL; switch (match_string(s_arg[i_arg].list[2], type_name, DATATYPES, 0)) { case TYPE_SHORT: parameterValues[parameters-1].type = SDDS_SHORT; break; case TYPE_LONG: parameterValues[parameters-1].type = SDDS_LONG; break; case TYPE_FLOAT: parameterValues[parameters-1].type = SDDS_FLOAT; break; case TYPE_DOUBLE: parameterValues[parameters-1].type = SDDS_DOUBLE; break; case TYPE_STRING: parameterValues[parameters-1].type = SDDS_STRING; break; case TYPE_CHARACTER: parameterValues[parameters-1].type = SDDS_CHARACTER; break; default: SDDS_Bomb("invalid -parameter type"); break; } for (i=3;i<s_arg[i_arg].n_items;i++) { if (!(ptr=strchr(s_arg[i_arg].list[i], '='))) SDDS_Bomb("invalid -parameter syntax"); *ptr++ = 0; switch (match_string(s_arg[i_arg].list[i], header_elements, HEADERELEMENTS, 0)) { case HEADER_UNITS: SDDS_CopyString(¶meterValues[parameters-1].units, ptr); break; case HEADER_DESCRIPTION: SDDS_CopyString(¶meterValues[parameters-1].description, ptr); break; case HEADER_SYMBOL: SDDS_CopyString(¶meterValues[parameters-1].symbol, ptr); break; case HEADER_COUNT: if (sscanf(ptr, "%ld", &count)!=1 || count<=0) SDDS_Bomb("invalid parameter count value"); sprintf(buffer, "%s", parameterValues[parameters-1].name); sprintf(buffer2, "%s1", buffer); free(parameterValues[parameters-1].name); SDDS_CopyString(¶meterValues[parameters-1].name, buffer2); break; default: SDDS_Bomb("invalid -parameter syntax"); break; } } for (i=2;i<=count;i++) { parameters++; parameterValues = trealloc(parameterValues, sizeof(*parameterValues)*(parameters)); sprintf(buffer2, "%s%ld", buffer, i); SDDS_CopyString(¶meterValues[parameters-1].name, buffer2); parameterValues[parameters-1].units = NULL; parameterValues[parameters-1].description = NULL; parameterValues[parameters-1].symbol = NULL; parameterValues[parameters-1].type = parameterValues[parameters-2].type; if (parameterValues[parameters-2].units) SDDS_CopyString(¶meterValues[parameters-1].units, parameterValues[parameters-2].units); if (parameterValues[parameters-2].description) SDDS_CopyString(¶meterValues[parameters-1].description, parameterValues[parameters-2].description); if (parameterValues[parameters-2].symbol) SDDS_CopyString(¶meterValues[parameters-1].symbol, parameterValues[parameters-2].symbol); } break; case SET_COLUMN: if (s_arg[i_arg].n_items<3) SDDS_Bomb("invalid -column syntax"); count=1; columns++; columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns)); SDDS_CopyString(&columnValues[columns-1].name, s_arg[i_arg].list[1]); columnValues[columns-1].elements = 0; columnValues[columns-1].values = NULL; columnValues[columns-1].stringValues = NULL; columnValues[columns-1].units = NULL; columnValues[columns-1].description = NULL; columnValues[columns-1].symbol = NULL; columnValues[columns-1].skip = 0; switch (match_string(s_arg[i_arg].list[2], type_name, DATATYPES, 0)) { case TYPE_SHORT: columnValues[columns-1].type = SDDS_SHORT; break; case TYPE_LONG: columnValues[columns-1].type = SDDS_LONG; break; case TYPE_FLOAT: columnValues[columns-1].type = SDDS_FLOAT; break; case TYPE_DOUBLE: columnValues[columns-1].type = SDDS_DOUBLE; break; case TYPE_STRING: columnValues[columns-1].type = SDDS_STRING; break; case TYPE_CHARACTER: columnValues[columns-1].type = SDDS_CHARACTER; break; default: SDDS_Bomb("invalid -column type"); break; } for (i=3;i<s_arg[i_arg].n_items;i++) { if (!(ptr=strchr(s_arg[i_arg].list[i], '='))) SDDS_Bomb("invalid -column syntax"); *ptr++ = 0; switch (match_string(s_arg[i_arg].list[i], header_elements, HEADERELEMENTS, 0)) { case HEADER_UNITS: SDDS_CopyString(&columnValues[columns-1].units, ptr); break; case HEADER_DESCRIPTION: SDDS_CopyString(&columnValues[columns-1].description, ptr); break; case HEADER_SYMBOL: SDDS_CopyString(&columnValues[columns-1].symbol, ptr); break; case HEADER_COUNT: if (sscanf(ptr, "%ld", &count)!=1 || count<=0) SDDS_Bomb("invalid column count value"); sprintf(buffer, "%s", columnValues[columns-1].name); sprintf(buffer2, "%s1", buffer); free(columnValues[columns-1].name); SDDS_CopyString(&columnValues[columns-1].name, buffer2); break; default: SDDS_Bomb("invalid -column syntax"); break; } } for (i=2;i<=count;i++) { columns++; columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns)); sprintf(buffer2, "%s%ld", buffer, i); SDDS_CopyString(&columnValues[columns-1].name, buffer2); columnValues[columns-1].elements = 0; columnValues[columns-1].values = NULL; columnValues[columns-1].stringValues = NULL; columnValues[columns-1].units = NULL; columnValues[columns-1].description = NULL; columnValues[columns-1].symbol = NULL; columnValues[columns-1].type = columnValues[columns-2].type; if (columnValues[columns-2].units) SDDS_CopyString(&columnValues[columns-1].units, columnValues[columns-2].units); if (columnValues[columns-2].description) SDDS_CopyString(&columnValues[columns-1].description, columnValues[columns-2].description); if (columnValues[columns-2].symbol) SDDS_CopyString(&columnValues[columns-1].symbol, columnValues[columns-2].symbol); } break; case SET_SKIPCOLUMN: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("invalid -skipcolumn syntax"); count=1; columns++; columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns)); columnValues[columns-1].name = NULL; columnValues[columns-1].elements = 0; columnValues[columns-1].values = NULL; columnValues[columns-1].stringValues = NULL; columnValues[columns-1].units = NULL; columnValues[columns-1].description = NULL; columnValues[columns-1].symbol = NULL; columnValues[columns-1].skip = 1; switch (match_string(s_arg[i_arg].list[1], type_name, DATATYPES, 0)) { case TYPE_SHORT: columnValues[columns-1].type = SDDS_SHORT; break; case TYPE_LONG: columnValues[columns-1].type = SDDS_LONG; break; case TYPE_FLOAT: columnValues[columns-1].type = SDDS_FLOAT; break; case TYPE_DOUBLE: columnValues[columns-1].type = SDDS_DOUBLE; break; case TYPE_STRING: columnValues[columns-1].type = SDDS_STRING; break; case TYPE_CHARACTER: columnValues[columns-1].type = SDDS_CHARACTER; break; default: SDDS_Bomb("invalid -skipcolumn type"); break; } break; case SET_PIPE: if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags)) SDDS_Bomb("invalid -pipe syntax"); break; case SET_NOWARNINGS: if (s_arg[i_arg].n_items!=1) SDDS_Bomb("invalid -nowarnings syntax"); noWarnings = 1; break; case SET_SKIPLINES: if (s_arg[i_arg].n_items!=2 || sscanf(s_arg[i_arg].list[1], "%ld", &skiplines)!=1 || skiplines<=0) SDDS_Bomb("invalid -skiplines syntax"); break; default: fprintf(stderr, "error: unknown switch: %s\n", s_arg[i_arg].list[0]); exit(1); break; } } else { if (input == NULL) { input = s_arg[i_arg].list[0]; } else if (output == NULL) { output = s_arg[i_arg].list[0]; } else { fprintf(stderr, "too many filenames"); exit(1); } } } processFilenames("plaindata2sdds", &input, &output, pipeFlags, noWarnings, &tmpfile_used); if (!columns && !parameters) SDDS_Bomb("you must specify one of the -column or the -parameter options"); if (skiplines && inputBinary) SDDS_Bomb("-skiplines does not work with binary input files"); if (!input) { if (inputBinary) { #if defined(_WIN32) if (_setmode(_fileno(stdin), _O_BINARY) == -1) { fprintf(stderr, "error: unable to set stdin to binary mode\n"); exit(1); } #endif } fileID = stdin; } else { if (!fexists(input)) { fprintf(stderr, "input file not found\n"); exit(1); } if (inputBinary) { fileID = fopen(input, "rb"); } else { fileID = fopen(input, "r"); } } if (fileID == NULL) { fprintf(stderr, "unable to open input file for reading\n"); exit(1); } if (!SDDS_InitializeOutput(&SDDS_dataset, binary?SDDS_BINARY:SDDS_ASCII, 1, NULL, NULL, output)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); SDDS_dataset.layout.data_mode.column_major = columnMajorOrder; if (parameters) { parameterIndex = tmalloc(sizeof(*parameterIndex)*parameters); } if (columns) { columnIndex = tmalloc(sizeof(*columnIndex)*columns); } for (i=0; i<parameters; i++) { if ((parameterIndex[i] = SDDS_DefineParameter(&SDDS_dataset, parameterValues[i].name, parameterValues[i].symbol, parameterValues[i].units, parameterValues[i].description, NULL, parameterValues[i].type, 0))<0) { sprintf(s, "Problem defining parameter %s.", parameterValues[i].name); SDDS_SetError(s); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } for (i=0; i<columns; i++) { if (columnValues[i].skip) continue; if ((columnIndex[i] = SDDS_DefineColumn(&SDDS_dataset, columnValues[i].name, columnValues[i].symbol, \ columnValues[i].units, columnValues[i].description, NULL, columnValues[i].type, 0))<0) { sprintf(s, "Problem defining column %s.", columnValues[i].name); SDDS_SetError(s); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } if (!SDDS_WriteLayout(&SDDS_dataset)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (!SDDS_StartPage(&SDDS_dataset, initRows)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); row = par = col = page = 0; while (inputBinary) { row = par = col = 0; if (fread(&rows,sizeof(rows),1,fileID) != 1) { if (page == 0) { SDDS_SetError("Unable to read number of rows"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } else { if (!SDDS_Terminate(&SDDS_dataset)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); for (k=0;k<columns;k++) { if (columnValues[k].type == SDDS_STRING) { SDDS_FreeStringArray(columnValues[k].stringValues,columnValues[k].elements); } else { free(columnValues[k].values); } } return 0; } } page++; for (par=0;par<parameters;par++) { switch (parameterValues[par].type) { case SDDS_SHORT: if (fread(&shortValue,2,1,fileID) != 1) { SDDS_SetError("Unable to read short parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,shortValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_LONG: if (fread(&longValue,4,1,fileID) != 1) { SDDS_SetError("Unable to read long parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,longValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_FLOAT: if (fread(&floatValue,4,1,fileID) != 1) { SDDS_SetError("Unable to read float parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,floatValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_DOUBLE: if (fread(&doubleValue,8,1,fileID) != 1) { SDDS_SetError("Unable to read double parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,doubleValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_STRING: if (fread(&size,4,1,fileID) != 1) { SDDS_SetError("Unable to read string parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (size>SDDS_MAXLINE-1) SDDS_Bomb("String is too long"); if (size > 0) { if (fread(&stringValue,size,1,fileID) != 1) { SDDS_SetError("Unable to read string parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } stringValue[size] = 0; } else { strcpy(stringValue,""); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,stringValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_CHARACTER: if (fread(&characterValue,1,1,fileID) != 1) { SDDS_SetError("Unable to read character parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,characterValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; } } for (i=0;i<columns;i++) { if (rows > columnValues[i].elements) { if (columnValues[i].type == SDDS_STRING) { columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements); } else { columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows); } columnValues[i].elements = rows; } } if (columnOrder) { for (col=0;col<columns;col++) { switch (columnValues[col].type) { case SDDS_SHORT: for (i=0;i<rows;i++) { if (fread((short*)(columnValues[col].values)+i,2,1,fileID) != 1) { SDDS_SetError("Unable to read short column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_LONG: for (i=0;i<rows;i++) { if (fread((int32_t*)(columnValues[col].values)+i,4,1,fileID) != 1) { SDDS_SetError("Unable to read long column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_FLOAT: for (i=0;i<rows;i++) { if (fread((float*)(columnValues[col].values)+i,4,1,fileID) != 1) { SDDS_SetError("Unable to read float column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_DOUBLE: for (i=0;i<rows;i++) { if (fread((double*)(columnValues[col].values)+i,8,1,fileID) != 1) { SDDS_SetError("Unable to read double double"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_STRING: for (i=0;i<rows;i++) { if (fread(&size,4,1,fileID) != 1) { SDDS_SetError("Unable to read string column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (size>SDDS_MAXLINE-1) SDDS_Bomb("String is too long"); columnValues[col].stringValues[i] = malloc(size + 1); if (size > 0) { if (fread(columnValues[col].stringValues[i],size,1,fileID) != 1) { SDDS_SetError("Unable to read string column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } columnValues[col].stringValues[i][size] = 0; } else { strcpy(columnValues[col].stringValues[i],""); } } break; case SDDS_CHARACTER: for (i=0;i<rows;i++) { if (fread((char*)(columnValues[col].values)+i,1,1,fileID) != 1) { SDDS_SetError("Unable to read character column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; } } } else { for (i=0;i<rows;i++) { for (col=0;col<columns;col++) { switch (columnValues[col].type) { case SDDS_SHORT: if (fread((short*)(columnValues[col].values)+i,2,1,fileID) != 1) { SDDS_SetError("Unable to read short column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } break; case SDDS_LONG: if (fread((int32_t*)(columnValues[col].values)+i,4,1,fileID) != 1) { SDDS_SetError("Unable to read long column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } break; case SDDS_FLOAT: if (fread((float*)(columnValues[col].values)+i,4,1,fileID) != 1) { SDDS_SetError("Unable to read float column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } break; case SDDS_DOUBLE: if (fread(((double*)(columnValues[col].values)+i),8,1,fileID) != 1) { SDDS_SetError("Unable to read double column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } break; case SDDS_STRING: if (fread(&size,4,1,fileID) != 1) { SDDS_SetError("Unable to read string column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (size>SDDS_MAXLINE-1) SDDS_Bomb("String is too long"); columnValues[col].stringValues[i] = malloc(size + 1); if (size > 0) { if (fread(columnValues[col].stringValues[i],size,1,fileID) != 1) { SDDS_SetError("Unable to read string column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } columnValues[col].stringValues[i][size] = 0; } else { strcpy(columnValues[col].stringValues[i],""); } break; case SDDS_CHARACTER: if (fread(((char*)(columnValues[col].values)+i),1,1,fileID) != 1) { SDDS_SetError("Unable to read character column"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } break; } } } } if (rows > maxRows) { if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) { SDDS_SetError("Unable to lengthen table"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = rows; } j=n; for (i=0;i<columns;i++) { if (columnValues[i].skip) continue; if (columnValues[i].type == SDDS_STRING) { SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].stringValues, rows, n); } else { SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].values, rows, n); } n++; } if (!SDDS_WritePage(&SDDS_dataset)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = 10000; if (!SDDS_StartPage(&SDDS_dataset, initRows)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } row = par = col = n = 0; rows = -1; ptr = NULL; ptr = SDDS_Malloc(sizeof(*ptr)*(ptrSize=2048)); /* ptr2 = NULL; ptr2 = SDDS_Malloc(sizeof(*ptr)*(ptrSize=2048));*/ ptr[0] = 0; while (1) { if (readline) { while (skiplines > 0) { fgets(ptr, ptrSize, fileID); skiplines--; } if (!fgetsSkipCommentsResize(&ptr,&ptrSize,fileID, '!')) break; commentFound=0; if (checkComment) { for (i=0; i<strlen(commentCharacters); i++) { if (ptr[0] == commentCharacters[i]) { commentFound=1; } } } if (commentFound == 1) { continue; } if (ptr[strlen(ptr)-1] == '\n') ptr[strlen(ptr)-1] = 0; strcpy(temp,ptr); /*skip empty lines*/ if (getToken(temp,data,10240,separator,whitespace)<0) continue; } else { readline = 1; } if (par < parameters) { switch (parameterValues[par].type) { case SDDS_SHORT: if (sscanf(ptr,"%hd",&shortValue) != 1) { SDDS_SetError("Invalid short parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,shortValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_LONG: if (sscanf(ptr,"%" SCNd32 ,&longValue) != 1) { SDDS_SetError("Invalid long parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,longValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_FLOAT: ConvertDNotationToENotation(ptr); if (sscanf(ptr,"%f",&floatValue) != 1) { SDDS_SetError("Invalid float parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,floatValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_DOUBLE: ConvertDNotationToENotation(ptr); if (sscanf(ptr,"%lf",&doubleValue) != 1) { SDDS_SetError("Invalid double parameter"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,doubleValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_STRING: SDDS_GetToken(ptr,stringValue,SDDS_MAXLINE); SDDS_InterpretEscapes(stringValue); if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,stringValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; case SDDS_CHARACTER: SDDS_InterpretEscapes(ptr); characterValue = ptr[0]; if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,characterValue,-1)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); break; } par++; } else if ((rows == -1) && (!noRowCount)) { if (sscanf(ptr,"%ld",&rows) != 1) { SDDS_SetError("Invalid row count"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } else if ((columns > 0) && ((row < rows) || (noRowCount))) { if (columnOrder) { if (noRowCount) { cp_str(&ptr2,ptr); rows = 0; while (getToken(ptr2,data,10240,separator,whitespace) >= 0) { rows++; } free(ptr2); } if (rows > columnValues[col].elements) { if (columnValues[col].type == SDDS_STRING) { columnValues[col].stringValues = AllocateColumnStringData(columnValues[col].stringValues, rows, columnValues[col].elements); } else { columnValues[col].values = AllocateColumnData(columnValues[col].type, columnValues[col].values, rows); } columnValues[col].elements = rows; } switch (columnValues[col].type) { case SDDS_SHORT: for (row=0;row<rows;row++) { if (getToken(ptr,data,10240,separator,whitespace) < 0) { SDDS_SetError("Invalid short column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (sscanf(data,"%hd",((short*)(columnValues[col].values)+row)) != 1) { SDDS_SetError("Invalid short column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_LONG: for (row=0;row<rows;row++) { if (getToken(ptr,data,10240,separator,whitespace) < 0) { SDDS_SetError("Invalid long column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (sscanf(data,"%" SCNd32,((int32_t*)(columnValues[col].values)+row)) != 1) { SDDS_SetError("Invalid long column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_FLOAT: for (row=0;row<rows;row++) { if (getToken(ptr,data,10240,separator,whitespace) < 0) { SDDS_SetError("Invalid float column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } ConvertDNotationToENotation(data); if (sscanf(data,"%f",((float*)(columnValues[col].values)+row)) != 1) { SDDS_SetError("Invalid float column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_DOUBLE: for (row=0;row<rows;row++) { if (getToken(ptr,data,10240,separator,whitespace) < 0) { SDDS_SetError("Invalid double column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } ConvertDNotationToENotation(data); if (sscanf(data,"%lf",((double*)(columnValues[col].values)+row)) != 1) { SDDS_SetError("Invalid double column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_STRING: for (row=0;row<rows;row++) { if (getToken(ptr,data,10240,separator,whitespace) < 0) { SDDS_SetError("Invalid string column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } SDDS_InterpretEscapes(data); columnValues[col].stringValues[row] = malloc(strlen(data) + 1); strcpy(columnValues[col].stringValues[row],data); } break; case SDDS_CHARACTER: for (row=0;row<rows;row++) { if (getToken(ptr,data,10240,separator,whitespace) < 0) { SDDS_SetError("Invalid character column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } SDDS_InterpretEscapes(data); *((char*)(columnValues[col].values)+row) = data[0]; } break; } if (rows > maxRows) { if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) { SDDS_SetError("Unable to lengthen table"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = rows; } if (columnValues[col].skip == 0) { if (columnValues[col].type == SDDS_STRING) { SetColumnData(columnValues[col].type, &SDDS_dataset, columnValues[col].stringValues, rows, col); } else { SetColumnData(columnValues[col].type, &SDDS_dataset, columnValues[col].values, rows, col); } n++; } col++; row = 0; } else { if (noRowCount) { if (row == 0) { rows = 3; } else if (row == rows - 1) { rows = rows + 3; for (i=0;i<columns;i++) { if (rows > columnValues[i].elements) { if (columnValues[i].type == SDDS_STRING) { columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements); } else { columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows); } } columnValues[i].elements = rows; } } } if (row == 0) for (i=0;i<columns;i++) { if (rows > columnValues[i].elements) { if (columnValues[i].type == SDDS_STRING) { columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements); } else { columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows); } } columnValues[i].elements = rows; } if (noRowCount) { cp_str(&ptr2,ptr); i = 0; while (getToken(ptr2,data,10240,separator,whitespace) >= 0) i++; free(ptr2); if ((i != columns) && (parameters>0 && i==1)) { if (row > 0) { if (row > maxRows) { if (!SDDS_LengthenTable(&SDDS_dataset, row - maxRows)) { SDDS_SetError("Unable to lengthen table"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = row; } n=0; for (j=0;j<columns;j++) { if (columnValues[j].skip) continue; if (columnValues[j].type == SDDS_STRING) { SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].stringValues, row, n); } else { SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].values, row, n); } n++; } if (!SDDS_WritePage(&SDDS_dataset)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); maxRows = 10000; if (!SDDS_StartPage(&SDDS_dataset, initRows)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); row = par = col = 0; rows = -1; } readline = 0; continue; } } for (i=0;i<columns;i++) { if (getToken(ptr,data,10240,separator,whitespace) < 0) { if (!fillin) { SDDS_SetError("Invalid column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } else { switch (columnValues[i].type) { case SDDS_SHORT: case SDDS_LONG: case SDDS_FLOAT: case SDDS_DOUBLE: data[0]='0'; data[1]='\0'; break; case SDDS_STRING: case SDDS_CHARACTER: data[0]='\0'; break; } } } switch (columnValues[i].type) { case SDDS_SHORT: if (sscanf(data,"%hd",((short*)(columnValues[i].values)+row)) != 1) { if (recover) { abort=1; row--; } else { SDDS_SetError("Invalid short column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_LONG: if (sscanf(data,"%" SCNd32,((int32_t*)(columnValues[i].values)+row)) != 1) { if (recover) { abort=1; row--; } else { SDDS_SetError("Invalid long column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_FLOAT: ConvertDNotationToENotation(data); if (sscanf(data,"%f",((float*)(columnValues[i].values)+row)) != 1) { if (recover) { abort=1; row--; } else { SDDS_SetError("Invalid float column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_DOUBLE: ConvertDNotationToENotation(data); if (sscanf(data,"%lf",((double*)(columnValues[i].values)+row)) != 1) { if (recover) { abort=1; row--; } else { SDDS_SetError("Invalid double column element"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } break; case SDDS_STRING: SDDS_InterpretEscapes(data); columnValues[i].stringValues[row] = malloc(strlen(data) + 1); strcpy(columnValues[i].stringValues[row],data); break; case SDDS_CHARACTER: SDDS_InterpretEscapes(data); *((char*)(columnValues[i].values)+row) = data[0]; break; } if (recover && abort) { break; } } row++; if ((row == rows) && (!noRowCount)) { if (rows > maxRows) { if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) { SDDS_SetError("Unable to lengthen table"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = rows; } n=0; for (i=0;i<columns;i++) { if (columnValues[i].skip) continue; if (columnValues[i].type == SDDS_STRING) { SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].stringValues, rows, n); } else { SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].values, rows, n); } n++; } } } } if ((par == parameters) && (((!noRowCount) && (rows != -1)) || (noRowCount)) && (((columnOrder) && (col == columns)) || ((columns > 0) && (row == rows)) || (columns == 0))) { if (!SDDS_WritePage(&SDDS_dataset)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = 10000; if (!SDDS_StartPage(&SDDS_dataset, initRows)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); row = par = col = 0; rows = -1; } ptr[0] = 0; } if (noRowCount) { if (row > 0) { if (row > maxRows) { if (!SDDS_LengthenTable(&SDDS_dataset, row - maxRows)) { SDDS_SetError("Unable to lengthen table"); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = row; } n=0; for (j=0;j<columns;j++) { if (columnValues[j].skip) continue; if (columnValues[j].type == SDDS_STRING) { SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].stringValues, row, n); } else { SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].values, row, n); } n++; } if (!SDDS_WritePage(&SDDS_dataset)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } maxRows = 10000; } } for (i=0;i<columns;i++) { if (columnValues[i].type == SDDS_STRING) { for (j=0;j<columnValues[i].elements;j++) { free(columnValues[i].stringValues[j]); } free(columnValues[i].stringValues); } else { free(columnValues[i].values); } if (columnValues[i].name) free(columnValues[i].name); if (columnValues[i].units) free(columnValues[i].units); if (columnValues[i].description) free(columnValues[i].description); if (columnValues[i].symbol) free(columnValues[i].symbol); } for (i=0;i<parameters;i++) { free(parameterValues[i].name); if (parameterValues[i].units) free(parameterValues[i].units); if (parameterValues[i].description) free(parameterValues[i].description); if (parameterValues[i].symbol) free(parameterValues[i].symbol); } if (columnValues) free(columnValues); if (parameterValues) free(parameterValues); if (columnIndex) free(columnIndex); if (parameterIndex) free(parameterIndex); if (ptr) free(ptr); if (!SDDS_Terminate(&SDDS_dataset)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); free_scanargs(&s_arg,argc); return 0; }
int main(int argc, char **argv) { SDDS_DATASET SDDS_orig, SDDS_out; int32_t i, j, k, i_arg, rows, xfilter_provided, yfilter_provided, zfilter_provided, row; long power=1; SCANNED_ARG *s_arg; char *inputFile, *outputRoot, output[1024], tmpcol[256]; double xmin, xmax, ymin, ymax, zmin, zmax, xinterval, yinterval, zinterval; int32_t xdim, ydim, zdim, columnNames, outputColumns, page=0; char **columnName, **outputColumn; double ***Rho, ***Jz, rhoSum, rhoSum1, yRho, zRho, jzRho; double x_min, x_max, y_min, y_max, z_min, z_max, x, y, z; unsigned long dummyFlags = 0; x_min = x_max = y_min = y_max = z_min = z_max = 0; xfilter_provided = yfilter_provided = zfilter_provided = 0; inputFile = outputRoot = NULL; SDDS_RegisterProgramName(argv[0]); argc = scanargs(&s_arg, argc, argv); if (argc<2) bomb(NULL, USAGE); columnNames = outputColumns = 0; columnName = outputColumn = NULL; Rho = Jz = NULL; for (i_arg=1; i_arg<argc; i_arg++) { if (s_arg[i_arg].arg_type==OPTION) { delete_chars(s_arg[i_arg].list[0], "_"); switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) { case SET_POWER: if (s_arg[i_arg].n_items!=2) SDDS_Bomb("Invalid -power syntax."); if (!get_long(&power, s_arg[i_arg].list[1])) SDDS_Bomb("Invalid -power value provided."); break; case SET_XFILTER: if (s_arg[i_arg].n_items<2) SDDS_Bomb("Invalid -xfilter syntax."); s_arg[i_arg].n_items--; if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0, "minimum", SDDS_DOUBLE, &x_min, 1, 0, "maximum", SDDS_DOUBLE, &x_max, 1, 0, NULL)) SDDS_Bomb("Invalid -xfilter syntax"); s_arg[i_arg].n_items++; if (x_max<=x_min) { fprintf(stderr, "Invalid -xfilter provided, x_max <= x_min\n"); exit(1); } xfilter_provided =1; break; case SET_YFILTER: if (s_arg[i_arg].n_items<2) SDDS_Bomb("Invalid -yfilter syntax."); s_arg[i_arg].n_items--; if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0, "minimum", SDDS_DOUBLE, &y_min, 1, 0, "maximum", SDDS_DOUBLE, &y_max, 1, 0, NULL)) SDDS_Bomb("Invalid -yfilter syntax"); s_arg[i_arg].n_items++; if (y_max<=y_min) { fprintf(stderr, "Invalid -yfilter provided, y_max <= y_min\n"); exit(1); } yfilter_provided =1; break; case SET_ZFILTER: if (s_arg[i_arg].n_items<2) SDDS_Bomb("Invalid -zfilter syntax."); s_arg[i_arg].n_items--; if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0, "minimum", SDDS_DOUBLE, &z_min, 1, 0, "maximum", SDDS_DOUBLE, &z_max, 1, 0, NULL)) SDDS_Bomb("Invalid -zfilter syntax"); s_arg[i_arg].n_items++; if (z_max<=z_min) { fprintf(stderr, "Invalid -yfilter provided, z_max <= z_min\n"); exit(1); } zfilter_provided =1; break; default: fprintf(stderr, "Unknown option - %s provided.\n", s_arg[i_arg].list[0]); exit(1); } } else { if (!inputFile) inputFile = s_arg[i_arg].list[0]; else if (!outputRoot) outputRoot = s_arg[i_arg].list[0]; else SDDS_Bomb("Too many file names provided."); } } if (!outputRoot) outputRoot = inputFile; sprintf(output, "%s.ave", outputRoot); if (!SDDS_InitializeInput(&SDDS_orig, inputFile)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } xdim = ydim = zdim = 1; zmin = zmax = zinterval = 0; while (SDDS_ReadPage(&SDDS_orig)>0) { if (page==0) { if (!SDDS_GetParameterAsDouble(&SDDS_orig, "origin1", &xmin) || !SDDS_GetParameterAsDouble(&SDDS_orig, "max_ext1", &xmax) || !SDDS_GetParameterAsDouble(&SDDS_orig, "delta1", &xinterval) || !SDDS_GetParameterAsLong(&SDDS_orig, "numPhysCells1", &xdim) || !SDDS_GetParameterAsDouble(&SDDS_orig, "origin2", &ymin) || !SDDS_GetParameterAsDouble(&SDDS_orig, "max_ext2", &ymax) || !SDDS_GetParameterAsDouble(&SDDS_orig, "delta2", &yinterval) || !SDDS_GetParameterAsLong(&SDDS_orig, "numPhysCells2", &ydim)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } if (SDDS_CheckParameter(&SDDS_orig, "origin3", NULL, SDDS_ANY_NUMERIC_TYPE, NULL)==SDDS_CHECK_OK) { if (!SDDS_GetParameterAsDouble(&SDDS_orig, "origin3", &zmin) || !SDDS_GetParameterAsDouble(&SDDS_orig, "max_ext3", &zmax) || !SDDS_GetParameterAsDouble(&SDDS_orig, "delta3", &zinterval) || !SDDS_GetParameterAsLong(&SDDS_orig, "numPhysCells3", &zdim)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } } if (xfilter_provided) { if (x_min>xmax || x_max<xmin) { fprintf(stderr, "Invalid xfilter provided, it should be between %le and %le\n", xmin, xmax); if (!SDDS_Terminate(&SDDS_orig)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); exit(1); } } else { x_min = xmin; x_max = xmax; } if (yfilter_provided) { if (y_min>ymax || y_max<ymin) { fprintf(stderr, "Invalid yfilter provided, it should be between %le and %le\n", ymin, ymax); if (!SDDS_Terminate(&SDDS_orig)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); exit(1); } } else { y_min = ymin; y_max = ymax; } if (zfilter_provided && zmin!=0 && zmax!=0) { if (z_min>zmax || z_max<zmin) { fprintf(stderr, "Invalid zfilter provided, it should be between %le and %le\n", zmin, zmax); if (!SDDS_Terminate(&SDDS_orig)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); exit(1); } } else { z_min = zmin; z_max = zmax; } Rho = malloc(sizeof(*Rho)*zdim); Jz = malloc(sizeof(*Rho)*zdim); for (i=0; i<zdim; i++) { Rho[i] = malloc(sizeof(**Rho)*ydim); Jz[i] = malloc(sizeof(**Jz)*ydim); } SetupOutputFile(&SDDS_out, output, zdim); } rows = SDDS_CountRowsOfInterest(&SDDS_orig); if (rows!=xdim) { fprintf(stderr, "Row number does not equal xdim size.\n"); exit(1); } for (j=1; j<=ydim; j++) { sprintf(tmpcol, "Rho_%d",j); Rho[page][j-1] = NULL; if (!(Rho[page][j-1]=SDDS_GetColumnInDoubles(&SDDS_orig, tmpcol))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); sprintf(tmpcol, "Jz_%d",j); Jz[page][j-1] = NULL; if (!(Jz[page][j-1]=SDDS_GetColumnInDoubles(&SDDS_orig, tmpcol))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } page ++; } if (!SDDS_Terminate(&SDDS_orig)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } if (page!=zdim) { free_data_memory(Rho, zdim, ydim); free_data_memory(Jz, zdim, ydim); fprintf(stderr, "Error, the page number does not equal to zdim size.\n"); exit(1); } if (!SDDS_StartPage(&SDDS_out, xdim) || !SDDS_SetParameters(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "origin1", xmin, "origin2", ymin, "origin3", zmin, "max_ext1", xmax, "max_ext2", ymax, "delta1", xinterval, "delta2", yinterval, "numPhysCells1", xdim, "numPhysCells2", ydim, "xstart", x_min, "xend", x_max, "ystart", y_min, "yend", y_max, NULL)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (zdim>1) { if (!SDDS_SetParameters(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "origin3", zmin, "max_ext3", zmax, "delta3", zinterval, "numPhysCells3", zdim, "zstart", z_min, "zend", z_max, NULL)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } row = 0; x = y = z = 0; for (i=0; i<xdim; i++) { rhoSum = rhoSum1 = 0; yRho = zRho = jzRho = 0; x = i * xinterval + xmin; if (xfilter_provided && (x<x_min || x>x_max)) continue; for (j=0; j<ydim; j++) { y = j * yinterval + ymin; if (yfilter_provided && (y<y_min || y>y_max)) continue; for (k=0; k<zdim; k++) { z = k * zinterval + zmin; if (zfilter_provided && zdim>1 && (z<z_min || z>z_max)) continue; if (power==1) { yRho += fabs(Rho[k][j][i]) * y; zRho += fabs(Rho[k][j][i]) * z; jzRho += Rho[k][j][i] * Jz[k][j][i]; rhoSum += fabs(Rho[k][j][i]); rhoSum1 += Rho[k][j][i]; } else { yRho += pow(fabs(Rho[k][j][i]), power) * y; zRho += pow(fabs(Rho[k][j][i]), power) * z; jzRho += pow(Rho[k][j][i] * Jz[k][j][i], power); rhoSum += pow(fabs(Rho[k][j][i]), power); rhoSum1 += pow(Rho[k][j][i], power); } } } /*set row values */ if (!SDDS_SetRowValues(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, row, "x", x, "YAve", yRho/(rhoSum+1.0e-20), "JzAve", jzRho/(rhoSum1 + 1.0e-20), NULL)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (zdim>1 && !SDDS_SetRowValues(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, row, "ZAve",zRho/(rhoSum+1.0e-20), NULL)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); row++; } if (!SDDS_WritePage(&SDDS_out) || !SDDS_Terminate(&SDDS_out)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); free_data_memory(Rho, zdim, ydim); free_data_memory(Jz, zdim, ydim); return 0; }
void label_contour( double **data, long nx, long ny, double value, char *string, double xmin, double dx, double ymin, double dy, double error_limit, long label_mode ) { /* long label_mode 0 -> on contours, 1 -> around border */ register double distance, best_distance, nbest_distance; register long iy; long ix, ix_best, iy_best, ix_nbest=0, iy_nbest=0, n_data; double x, y, xmax, ymax, i_int; double xd, yd; double hoff, voff; xmax = xmin + dx*(nx-1); ymax = ymin + dy*(ny-1); if (label_mode==0) { distance = best_distance = 1.0E37; ix_best = iy_best = -1; n_data = nx*ny; for (ix=1; ix<nx-2; ix++) { for (iy=1; iy<ny-2; iy++) { distance = fabs(value - data[ix][iy])/error_limit; if (distance<1) { distance += sqr((ix-nx/2.)/nx)+sqr((iy-ny/2.)/ny); if (distance<best_distance) { ix_nbest = ix_best; iy_nbest = iy_best; nbest_distance = best_distance; ix_best = ix; iy_best = iy; best_distance = distance; } } } } ix = ix_best; iy = iy_best; if (ix==-1) { ix = 0; for (iy=1; iy<ny-2; iy++) { distance = fabs(value - data[ix][iy])/error_limit; if (distance<1) { distance += sqr((ix-nx/2.)/nx)+sqr((iy-ny/2.)/ny); if (distance<best_distance) { ix_nbest = ix_best; iy_nbest = iy_best; nbest_distance = best_distance; ix_best = ix; iy_best = iy; best_distance = distance; } } } if (ix_best==-1) { printf("note: failed to find acceptable contour to label for value %e\n", value); return; } ix = ix_best; iy = iy_best; } if (fabs(value-data[ix][iy])>error_limit) bomb("algorithmic error (1) in label_contour()", NULL); x = dx*ix + xmin; y = dy*iy + ymin; if (ix<nx-1 && data[ix][iy]!=data[ix+1][iy]) x += dx*(value-data[ix][iy])/(data[ix+1][iy]-data[ix][iy]); else if (iy<ny-1 && data[ix][iy]!=data[ix][iy+1]) y += dy*(value-data[ix][iy])/(data[ix][iy+1]-data[ix][iy]); if (x>=xmax-dx/2 || y>=ymax-dy/2 || x<xmin+dx/4 || y<ymin+dy/4) { ix = ix_nbest; iy = iy_nbest; if (ix!=-1) { x = dx*ix + xmin; y = dy*iy + ymin; if (ix<nx-1 && data[ix][iy]!=data[ix+1][iy]) x += dx*(value-data[ix][iy])/(data[ix+1][iy]-data[ix][iy]); else if (iy<ny-1 && data[ix][iy]!=data[ix][iy+1]) y += dy*(value-data[ix][iy])/(data[ix][iy+1]-data[ix][iy]); if (x>=xmax-dx/2 || y>=ymax-dy/2 || x<xmin+dx/4 || y<ymin+dy/4) { printf("note: label algorithm went outside plot region for value %e\n", value); return; } } else { printf("note: label algorithm went outside plot region for value %e\n", value); return; } } xd = x; yd = y; plot_string(&xd, &yd, string); } else { distance = best_distance = 1.0E37; vertical_print(1); /* search for end of contour along top edge */ iy = ny-1; get_char_size(&hoff, &voff, 1); for (ix=nx-1; ix>0; ix--) { if ((data[ix][iy]<value && data[(ix-1)][iy]>=value) || (data[ix][iy]>value && data[(ix-1)][iy]<=value) ) { xd = xmin + hoff/3 + dx*(i_int=INTERPOLATE(ix-1, ix, data[ix-1][iy], data[ix][iy], value)); if (i_int>=ix-1 && i_int<=ix) { yd = ymin + (ny-1)*dy + (value>0?voff:voff/2); plot_string(&xd, &yd, string); } } } /* search for end of contour along right edge */ ix = nx-1; vertical_print(0); get_char_size(&hoff, &voff, 1); for (iy=1; iy<ny; iy++) { if ((data[ix][iy]<value && value<=data[ix][iy-1]) || (data[ix][iy]>value && value>=data[ix][iy-1]) ) { yd = ymin - 2*voff/3 + dy*(i_int=INTERPOLATE(iy-1, iy, data[ix][iy-1], data[ix][iy], value)); if (!(i_int<iy-1 || i_int>iy)) { xd = xmin + (nx-1)*dx + hoff/2; plot_string(&xd, &yd, string); } } } } }
int main(int argc, char **argv) { FILE *outfile; SDDS_TABLE SDDS_table; SDDS_LAYOUT *layout; COLUMN_DEFINITION *coldef; PARAMETER_DEFINITION *pardef; ARRAY_DEFINITION *arraydef; long list_request; char *input, *output; long i, j, i_arg, append_units, nrows, ntable; SCANNED_ARG *s_arg; char *text, *contents, *delimiter; long verbose=0, all=0, nvariableparms=0, excel=0, line=0; void *data; unsigned long pipeFlags; #ifdef USE_XLS workbook *w; worksheet *ws; #endif int ret; char sheet[256]; char buffer[5]; SDDS_RegisterProgramName(argv[0]); list_request = -1; input = output = NULL; append_units = 0; delimiter = DELIMITER; pipeFlags = 0; argc = scanargs(&s_arg, argc, argv); if (argc==1) bomb(NULL, USAGE); for (i_arg=1; i_arg<argc; i_arg++) { if (s_arg[i_arg].arg_type==OPTION) { switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) { case SET_DELIMITER: if (s_arg[i_arg].n_items<2) SDDS_Bomb("Invalid -delimiter syntax"); delimiter = s_arg[i_arg].list[1]; break; case SET_ALL: all = 1; break; case SET_EXCEL: #ifdef USE_XLS excel = 1; #else SDDS_Bomb("-excel option is not available becuase sdds2spreadsheet was not compiled with xlslib support"); #endif break; case SET_VERBOSE: verbose = 1; break; case SET_PIPE: if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags)) SDDS_Bomb("invalid -pipe syntax"); break; default: SDDS_Bomb(strcat("Unknown option: ", s_arg[i_arg].list[0])); break; } } else { if (input==NULL) input = s_arg[i_arg].list[0]; else if (output==NULL) output = s_arg[i_arg].list[0]; else SDDS_Bomb("too many filenames"); } } processFilenames("sdds2spreadsheet", &input, &output, pipeFlags, 0, NULL); if (output) { if (!excel) { outfile=fopen(output,"w"); if(!outfile) SDDS_Bomb(strcat("Can't open output file ", output)); } } else { if (excel) { SDDS_Bomb("-pipe=out and -excel options cannot be used together"); } outfile = stdout; } if (input && !excel) fprintf(outfile,"Created from SDDS file: %s\n", input); if (!SDDS_InitializeInput(&SDDS_table, input)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } layout = &SDDS_table.layout; /* Description */ if(verbose && input) fprintf(stderr, "\nfile %s is in SDDS protocol version %" PRId32 "\n", input, layout->version); if (!SDDS_GetDescription(&SDDS_table, &text, &contents)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (text) if (verbose) fprintf(stderr, "description: %s\n", text); if (!excel) fprintf(outfile,"%s%s\n",text?text:"No description",delimiter); if (contents) if (verbose) fprintf(stderr, "contents: %s\n", contents); if (!excel) fprintf(outfile,"%s%s\n",contents?contents:"No description",delimiter); if (layout->data_mode.mode==SDDS_ASCII) { if (verbose) { fprintf(stderr, "\ndata is ASCII with %" PRId32 " lines per row and %" PRId32 " additional header lines expected.\n", layout->data_mode.lines_per_row, layout->data_mode.additional_header_lines); fprintf(stderr, "row counts: %s \n", layout->data_mode.no_row_counts?"no":"yes"); } } else if (verbose) fprintf(stderr, "\ndata is binary\n"); /* Columns */ if (layout->n_columns) { if(verbose) { fprintf(stderr, "\n%" PRId32 " columns of data:\n", layout->n_columns); fprintf(stderr, "NAME UNITS SYMBOL FORMAT TYPE FIELD DESCRIPTION\n"); fprintf(stderr, " LENGTH\n"); } if (all && !excel) fprintf(outfile, "\nColumns%s\nName%sUnits%sSymbol%sFormat%sType%sField Length%sDescription%s\n", delimiter, delimiter, delimiter, delimiter, delimiter, delimiter, delimiter, delimiter); for (i=0; i<layout->n_columns; i++) { coldef = layout->column_definition+i; if(verbose) fprintf(stderr, "%-15s %-15s %-15s %-15s %-7s %-7" PRId32 " %s\n", coldef->name, coldef->units?coldef->units:"", coldef->symbol?coldef->symbol:"", coldef->format_string?coldef->format_string:"", SDDS_type_name[coldef->type-1], coldef->field_length, coldef->description?coldef->description:""); if(all && !excel) fprintf(outfile,"%s%s%s%s%s%s%s%s%s%s%-7" PRId32 "%s%s%s\n", coldef->name, delimiter, coldef->units?coldef->units:"", delimiter, coldef->symbol?coldef->symbol:"", delimiter, coldef->format_string?coldef->format_string:"", delimiter, SDDS_type_name[coldef->type-1], delimiter, coldef->field_length, delimiter, coldef->description?coldef->description:"", delimiter); } } /* Parameters */ if (layout->n_parameters) { if (verbose) { fprintf(stderr, "\n%" PRId32 " parameters:\n", layout->n_parameters); fprintf(stderr, "NAME UNITS SYMBOL TYPE DESCRIPTION\n"); } if(all && !excel) fprintf(outfile,"\nParameters%s\nName%sFixedValue%sUnits%sSymbol%sType%sDescription%s\n", delimiter, delimiter, delimiter, delimiter, delimiter, delimiter, delimiter); for (i=0; i<layout->n_parameters; i++) { pardef = layout->parameter_definition+i; if(!pardef->fixed_value) { nvariableparms++; if(!all) continue; } if(verbose) fprintf(stderr, "%-19s %-19s %-19s %-19s %s\n", pardef->name, pardef->units?pardef->units:"", pardef->symbol?pardef->symbol:"", SDDS_type_name[pardef->type-1], pardef->description?pardef->description:""); if (!excel) { if(all) fprintf(outfile,"%s%s%s%s%s%s%s%s%s%s%s%s\n", pardef->name, delimiter, pardef->fixed_value?pardef->fixed_value:"", delimiter, pardef->units?pardef->units:"", delimiter, pardef->symbol?pardef->symbol:"", delimiter, SDDS_type_name[pardef->type-1], delimiter, pardef->description?pardef->description:"", delimiter); else fprintf(outfile,"%s%s%s%s%s\n", pardef->name, delimiter, delimiter, pardef->fixed_value?pardef->fixed_value:"", delimiter); } } } /* Arrays */ if (layout->n_arrays && all) { if(verbose) { fprintf(stderr, "\n%" PRId32 " arrays of data:\n", layout->n_arrays); fprintf(stderr, "NAME UNITS SYMBOL" " FORMAT TYPE FIELD GROUP DESCRIPTION\n"); fprintf(stderr, " LENGTH NAME\n"); } if (!excel) { fprintf(outfile,"\nArrays%s\nName%sUnits%sSymbol%sFormat%sType%sField Length%sGroup Name%sDescription%s\n", delimiter, delimiter, delimiter, delimiter, delimiter, delimiter, delimiter, delimiter, delimiter); } for (i=0; i<layout->n_arrays; i++) { arraydef = layout->array_definition+i; if(verbose) fprintf(stderr, "%-15s %-15s %-15s %-7s %-8s*^%-5" PRId32 " %-7" PRId32 " %-15s %s\n", arraydef->name, arraydef->units, arraydef->symbol, arraydef->format_string, SDDS_type_name[arraydef->type-1], arraydef->dimensions, arraydef->field_length, arraydef->group_name, arraydef->description); if (!excel) { fprintf(outfile,"%s%s%s%s%s%s%s%s%s*^%-5" PRId32 "%s%-7" PRId32 "%s%s%s%s%s\n", arraydef->name, delimiter, arraydef->units, delimiter, arraydef->symbol, delimiter, arraydef->format_string, delimiter, SDDS_type_name[arraydef->type-1], arraydef->dimensions, delimiter, arraydef->field_length, delimiter, arraydef->group_name, delimiter, arraydef->description, delimiter); } } } /* Associates */ /* if (layout->n_associates && all) { if(verbose) { fprintf(stderr, "\n%ld associates:\n", layout->n_associates); fprintf(stderr, "SDDS FILENAME PATH CONTENTS DESCRIPTION\n"); } fprintf(outfile,"\nAssociates%s\nType%sFilename%sPath%sContents%sDescription%s\n", delimiter, delimiter, delimiter, delimiter, delimiter, delimiter); for (i=0; i<layout->n_associates; i++) if(verbose) fprintf(stderr, "%-5s %-19s %-29s %-19s %s\n", layout->associate_definition[i].sdds?"SDDS":"Non-SDDS", layout->associate_definition[i].filename, layout->associate_definition[i].path, layout->associate_definition[i].contents, layout->associate_definition[i].description); fprintf(outfile,"%s%s%s%s%s%s%s%s%s%s\n", layout->associate_definition[i].sdds?"yes":"no", delimiter, layout->associate_definition[i].filename, delimiter, layout->associate_definition[i].path, delimiter, layout->associate_definition[i].contents, delimiter, layout->associate_definition[i].description, delimiter); } */ #ifdef USE_XLS w = xlsNewWorkbook(); #ifdef __APPLE__ xlsWorkbookIconvInType(w, "UCS-4-INTERNAL"); #endif #endif /* Process tables */ while ((ntable=SDDS_ReadTable(&SDDS_table))>0) { line=0; #ifdef USE_XLS if (excel) { sprintf(sheet, "Sheet%d", ntable); ws = xlsWorkbookSheet(w, sheet); } else fprintf(outfile,"\nTable %ld\n",ntable); #else fprintf(outfile,"\nTable %ld\n",ntable); #endif /* Variable parameters */ if (nvariableparms) { for (i=0; i<layout->n_parameters; i++) { pardef = layout->parameter_definition+i; if(pardef->fixed_value) continue; if (!(data=SDDS_GetParameter(&SDDS_table, pardef->name, NULL))) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } #ifdef USE_XLS if (excel) { xlsWorksheetLabel(ws, line, 0, pardef->name, NULL); switch(pardef->type) { case SDDS_DOUBLE: xlsWorksheetNumberDbl(ws, line, 1, *((double*)data), NULL); break; case SDDS_FLOAT: xlsWorksheetNumberDbl(ws, line, 1, *((float*)data), NULL); break; case SDDS_ULONG: xlsWorksheetNumberInt(ws, line, 1, *((uint32_t*)data), NULL); break; case SDDS_LONG: xlsWorksheetNumberInt(ws, line, 1, *((int32_t*)data), NULL); break; case SDDS_USHORT: xlsWorksheetNumberInt(ws, line, 1, *((unsigned short*)data), NULL); break; case SDDS_SHORT: xlsWorksheetNumberInt(ws, line, 1, *((short*)data), NULL); break; case SDDS_STRING: xlsWorksheetLabel(ws, line, 1, *((char**)data), NULL); break; case SDDS_CHARACTER: sprintf(buffer, "%c", *((char*)data)); xlsWorksheetLabel(ws, line, 1, buffer, NULL); break; default: break; } line++; } else { #endif fprintf(outfile,"%s%s%s",pardef->name,delimiter,delimiter); SDDS_PrintTypedValue(data, 0, pardef->type, NULL, outfile, 0); fprintf(outfile,"%s\n",delimiter); #ifdef USE_XLS } #endif } line++; } /* Columns */ if (layout->n_columns) { SDDS_SetColumnFlags(&SDDS_table, 1); SDDS_SetRowFlags(&SDDS_table, 1); if ((nrows=SDDS_CountRowsOfInterest(&SDDS_table))<0) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } for (i=0; i<layout->n_columns; i++) { coldef = layout->column_definition+i; #ifdef USE_XLS if (excel) { xlsWorksheetLabel(ws, line, i, coldef->name, NULL); } else fprintf(outfile,"%s%s",coldef->name,delimiter); #else fprintf(outfile,"%s%s",coldef->name,delimiter); #endif } line++; if (!excel) fprintf(outfile,"\n"); if (nrows) { for (j=0; j<nrows; j++) { for (i=0; i<layout->n_columns; i++) { coldef = layout->column_definition+i; if (!(data=SDDS_GetValue(&SDDS_table, coldef->name,j,NULL))) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } #ifdef USE_XLS if (excel) { switch(coldef->type) { case SDDS_DOUBLE: xlsWorksheetNumberDbl(ws, line, i, *((double*)data), NULL); break; case SDDS_FLOAT: xlsWorksheetNumberDbl(ws, line, i, *((float*)data), NULL); break; case SDDS_ULONG: xlsWorksheetNumberInt(ws, line, i, *((uint32_t*)data), NULL); break; case SDDS_LONG: xlsWorksheetNumberInt(ws, line, i, *((int32_t*)data), NULL); break; case SDDS_USHORT: xlsWorksheetNumberInt(ws, line, i, *((unsigned short*)data), NULL); break; case SDDS_SHORT: xlsWorksheetNumberInt(ws, line, i, *((short*)data), NULL); break; case SDDS_STRING: xlsWorksheetLabel(ws, line, i, *((char**)data), NULL); break; case SDDS_CHARACTER: sprintf(buffer, "%c", *((char*)data)); xlsWorksheetLabel(ws, line, i, buffer, NULL); break; default: break; } } else { #endif switch(coldef->type) { case SDDS_DOUBLE: fprintf(outfile, "%.*g", DBL_DIG, *((double*)data)); break; case SDDS_FLOAT: fprintf(outfile, "%.*g", FLT_DIG, *((float*)data)); break; default: SDDS_PrintTypedValue(data, 0, coldef->type, NULL, outfile, 0); break; } fprintf(outfile,delimiter); #ifdef USE_XLS } #endif } if (!excel) fprintf(outfile,"\n"); line++; } } } } #ifdef USE_XLS ret = xlsWorkbookDump(w, output); xlsDeleteWorkbook(w); #endif /* QUIT: */ fflush(stdout); if (!SDDS_Terminate(&SDDS_table)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } return(0); }
long despikeData(double *data, long rows, long neighbors, long passes, long averageOf, double threshold, long countLimit) { long i0, i1, i2, i, j, imin, imax, i1a, i2a; double *deltaSum, sum, *tempdata; long despikeCount; neighbors = 2*((neighbors+1)/2); if (!(tempdata = (double*)malloc(sizeof(*tempdata)*rows)) || !(deltaSum = (double*)malloc(sizeof(*deltaSum)*(neighbors+1)))) bomb("despikeData: memory allocation failure", NULL); memcpy(tempdata, data, sizeof(*data)*rows); despikeCount = 0; while (passes-- > 0) { despikeCount = 0; for (i0=0; i0<rows; i0+=neighbors/2) { i1 = i0-neighbors/2; i2 = i0+neighbors/2; if (i1<0) i1 = 0; if (i2>=rows) i2 = rows-1; if (i2-i1==0) continue; for (i=i1; i<=i2; i++) { deltaSum[i-i1] = 0; for (j=i1; j<=i2; j++) deltaSum[i-i1] += fabs(tempdata[i]-tempdata[j]); } if (index_min_max(&imin, &imax, deltaSum, i2-i1+1)) { if ((imax += i1)<0 || imax>rows) { fprintf(stderr, "Error: index out of range in despikeData (sddssmooth)\n"); fprintf(stderr, " imax = %ld, rows=%ld, i1=%ld, i2=%ld, neighbors=%ld\n", imax-1, rows, i1, i2, neighbors); exit(1); } if (threshold==0 || threshold*neighbors<deltaSum[imax-i1]) { if ((i1a = imax-averageOf/2)<0) i1a = 0; if ((i2a = imax+averageOf/2)>=rows) i2a = rows-1; for (sum=0, i=i1a; i<=i2a; i++) { if (i!=imax) sum += tempdata[i]; } despikeCount++; tempdata[imax] = sum/(i2a-i1a); } } } if (!despikeCount || (countLimit>0 && despikeCount>countLimit)) break; } if (countLimit<=0 || despikeCount<countLimit) for (i=0;i<rows;i++) data[i] = tempdata[i]; else despikeCount = 0; free(tempdata); free(deltaSum); return despikeCount; }
int main(int argc, char **argv) { int iArg; char *indepQuantity, **depenQuantity, *fileValuesQuantity, *fileValuesFile, **exclude; long depenQuantities, monotonicity, excludes; char *input, *output; long i, j, rows, readCode, order, valuesReadCode, fillIn, row; long sequencePoints, combineDuplicates, branch; int32_t *rowFlag; double sequenceStart, sequenceEnd; double sequenceSpacing; unsigned long flags, interpCode, printFlags, forceMonotonic; SCANNED_ARG *scanned; SDDS_DATASET SDDSin, SDDSout, SDDSvalues; OUTRANGE_CONTROL aboveRange, belowRange; double *atValue; long atValues, interpPoints, doNotRead, parallelPages; double *indepValue, **depenValue, *interpPoint, **outputData; unsigned long pipeFlags; FILE *fpPrint; short interpShort=0, interpShortOrder=-1, *shortValue=NULL; long nextPos; SDDS_RegisterProgramName(argv[0]); argc = scanargs(&scanned, argc, argv); if (argc<3 || argc>(3+CLO_OPTIONS)) bomb(NULL, USAGE); atValue = NULL; atValues = fillIn = 0; output = input = NULL; combineDuplicates = branch = sequencePoints = parallelPages = 0; indepQuantity = NULL; depenQuantity = exclude = NULL; depenQuantities = excludes = 0; aboveRange.flags = belowRange.flags = OUTRANGE_SATURATE; order = 1; readCode = interpPoints = 0; fileValuesFile = fileValuesQuantity = NULL; sequenceStart = sequenceEnd = sequenceSpacing = 0; printFlags = pipeFlags = 0; forceMonotonic = 0; indepValue = interpPoint = NULL; depenValue = outputData = NULL; for (iArg=1; iArg<argc; iArg++) { if (scanned[iArg].arg_type==OPTION) { /* process options here */ switch (match_string(scanned[iArg].list[0], option, CLO_OPTIONS, 0)) { case CLO_ORDER: if (scanned[iArg].n_items!=2 || sscanf(scanned[iArg].list[1], "%ld", &order)!=1 || order<1) SDDS_Bomb("invalid -order syntax/value"); break; case CLO_ATVALUES: if (scanned[iArg].n_items<2) SDDS_Bomb("invalid -atValues syntax"); if (atValue) SDDS_Bomb("give -atValues only once"); atValue = tmalloc(sizeof(*atValue)*(atValues=scanned[iArg].n_items-1)); for (i=0; i<atValues; i++) if (sscanf(scanned[iArg].list[i+1], "%lf", &atValue[i])!=1) SDDS_Bomb("invalid -atValues value"); break; case CLO_INTERP_SHORT: if (scanned[iArg].n_items==2) { if (sscanf(scanned[iArg].list[1], "%hd", &interpShortOrder)!=1) SDDS_Bomb("invalid -interpShort value"); } interpShort = 1; break; case CLO_SEQUENCE: if ((scanned[iArg].n_items!=2 && scanned[iArg].n_items!=4) || sscanf(scanned[iArg].list[1], "%ld", &sequencePoints)!=1 || sequencePoints<2) SDDS_Bomb("invalid -sequence syntax/value"); if (scanned[iArg].n_items==4 && (sscanf(scanned[iArg].list[2], "%lf", &sequenceStart)!=1 || sscanf(scanned[iArg].list[3], "%lf", &sequenceEnd)!=1)) SDDS_Bomb("invalid -sequence syntax/value"); if (sequenceSpacing) SDDS_Bomb("give only one of -sequence and -equispaced"); break; case CLO_EQUISPACED: if ((scanned[iArg].n_items!=2 && scanned[iArg].n_items!=4) || sscanf(scanned[iArg].list[1], "%lf", &sequenceSpacing)!=1 || sequenceSpacing<=0) SDDS_Bomb("invalid -equispaced syntax/value"); if (scanned[iArg].n_items==4 && (sscanf(scanned[iArg].list[2], "%lf", &sequenceStart)!=1 || sscanf(scanned[iArg].list[3], "%lf", &sequenceEnd)!=1)) SDDS_Bomb("invalid -equispaced syntax/values"); if (sequencePoints) SDDS_Bomb("give only one of -sequence and -equispaced"); break; case CLO_COLUMNS: if (indepQuantity) SDDS_Bomb("only one -columns option may be given"); if (scanned[iArg].n_items<2) SDDS_Bomb("invalid -columns syntax"); indepQuantity = scanned[iArg].list[1]; if (scanned[iArg].n_items>=2) { depenQuantity = tmalloc(sizeof(*depenQuantity)*(depenQuantities=scanned[iArg].n_items-2)); for (i=0; i<depenQuantities; i++) depenQuantity[i] = scanned[iArg].list[i+2]; } break; case CLO_PRINTOUT: if ((scanned[iArg].n_items-=1)>=1) { if (!scanItemList(&printFlags, scanned[iArg].list+1, &scanned[iArg].n_items, 0, "bare", -1, NULL, 0, BARE_PRINTOUT, "stdout", -1, NULL, 0, STDOUT_PRINTOUT, NULL)) SDDS_Bomb("invalid -printout syntax"); } if (!(printFlags&BARE_PRINTOUT)) printFlags |= NORMAL_PRINTOUT; break; case CLO_FILEVALUES: if (scanned[iArg].n_items<2) SDDS_Bomb("invalid -fileValues syntax"); fileValuesFile = scanned[iArg].list[1]; scanned[iArg].n_items -= 2; if (!scanItemList(&flags, scanned[iArg].list+2, &scanned[iArg].n_items, 0, "column", SDDS_STRING, &fileValuesQuantity, 1, 0, "parallelpages", -1, NULL, 0, FILEVALUES_PARALLEL_PAGES, NULL)) SDDS_Bomb("invalid -fileValues syntax"); if (flags&FILEVALUES_PARALLEL_PAGES) parallelPages = 1; break; case CLO_COMBINEDUPLICATES: SDDS_Bomb("-combineDuplicates option not implemented yet--send email to [email protected]"); combineDuplicates = 1; break; case CLO_BRANCH: SDDS_Bomb("-branch option not implemented yet--send email to [email protected]"); if (scanned[iArg].n_items!=2 || sscanf(scanned[iArg].list[1], "%ld", &branch)!=1 || branch<1) SDDS_Bomb("invalid -branch syntax/value"); break; case CLO_BELOWRANGE: if ((scanned[iArg].n_items-=1)<1 || !scanItemList(&belowRange.flags, scanned[iArg].list+1, &scanned[iArg].n_items, 0, "value", SDDS_DOUBLE, &belowRange.value, 1, OUTRANGE_VALUE, "skip", -1, NULL, 0, OUTRANGE_SKIP, "saturate", -1, NULL, 0, OUTRANGE_SATURATE, "extrapolate", -1, NULL, 0, OUTRANGE_EXTRAPOLATE, "wrap", -1, NULL, 0, OUTRANGE_WRAP, "abort", -1, NULL, 0, OUTRANGE_ABORT, "warn", -1, NULL, 0, OUTRANGE_WARN, NULL)) SDDS_Bomb("invalid -belowRange syntax/value"); if ((i=bitsSet(belowRange.flags& (OUTRANGE_VALUE|OUTRANGE_SKIP|OUTRANGE_SATURATE|OUTRANGE_EXTRAPOLATE|OUTRANGE_WRAP|OUTRANGE_ABORT)))>1) SDDS_Bomb("incompatible keywords given for -belowRange"); if (i!=1) belowRange.flags |= OUTRANGE_SATURATE; break; case CLO_ABOVERANGE: if ((scanned[iArg].n_items-=1)<1 || !scanItemList(&aboveRange.flags, scanned[iArg].list+1, &scanned[iArg].n_items, 0, "value", SDDS_DOUBLE, &aboveRange.value, 1, OUTRANGE_VALUE, "skip", -1, NULL, 0, OUTRANGE_SKIP, "saturate", -1, NULL, 0, OUTRANGE_SATURATE, "extrapolate", -1, NULL, 0, OUTRANGE_EXTRAPOLATE, "wrap", -1, NULL, 0, OUTRANGE_WRAP, "abort", -1, NULL, 0, OUTRANGE_ABORT, "warn", -1, NULL, 0, OUTRANGE_WARN, NULL)) SDDS_Bomb("invalid -aboveRange syntax/value"); if ((i=bitsSet(aboveRange.flags& (OUTRANGE_VALUE|OUTRANGE_SKIP|OUTRANGE_SATURATE|OUTRANGE_EXTRAPOLATE|OUTRANGE_WRAP|OUTRANGE_ABORT)))>1) SDDS_Bomb("incompatible keywords given for -aboveRange"); if (i!=1) aboveRange.flags |= OUTRANGE_SATURATE; break; case CLO_PIPE: if (!processPipeOption(scanned[iArg].list+1, scanned[iArg].n_items-1, &pipeFlags)) SDDS_Bomb("invalid -pipe syntax"); break; case CLO_EXCLUDE: if (scanned[iArg].n_items<2) SDDS_Bomb("invalid -exclude syntax"); moveToStringArray(&exclude, &excludes, scanned[iArg].list+1, scanned[iArg].n_items-1); break; case CLO_FORCEMONOTONIC: if ((scanned[iArg].n_items-=1)>0) { if (!scanItemList(&forceMonotonic, scanned[iArg].list+1, &scanned[iArg].n_items, 0, "increasing", -1, NULL, 0, FORCE_INCREASING, "decreasing", -1, NULL, 0, FORCE_DECREASING, NULL) || bitsSet(forceMonotonic)!=1) SDDS_Bomb("invalid -forceMonotonic syntax/value"); } else forceMonotonic = FORCE_MONOTONIC; break; case CLO_FILLIN: fillIn = 1; break; default: fprintf(stderr, "error: unknown/ambiguous option: %s\n", scanned[iArg].list[0]); exit(1); break; } } else { if (!input) input = scanned[iArg].list[0]; else if (!output) output = scanned[iArg].list[0]; else SDDS_Bomb("too many filenames seen"); } } processFilenames("sddsinterp", &input, &output, pipeFlags, 0, NULL); fpPrint = stderr; if (printFlags&STDOUT_PRINTOUT) fpPrint = stdout; if (!indepQuantity) SDDS_Bomb("supply the independent quantity name with the -columns option"); if ((atValues?1:0)+(fileValuesFile?1:0)+(sequencePoints?1:0)+fillIn+(sequenceSpacing>0?1:0) != 1) SDDS_Bomb("you must give one and only one of -atValues, -fileValues, -sequence, -equispaced, and -fillIn"); if (!SDDS_InitializeInput(&SDDSin, input)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); excludes = appendToStringArray(&exclude, excludes, indepQuantity); if (!depenQuantities) depenQuantities = appendToStringArray(&depenQuantity, depenQuantities, "*"); if ((depenQuantities=expandColumnPairNames(&SDDSin, &depenQuantity, NULL, depenQuantities, exclude, excludes, FIND_NUMERIC_TYPE, 0))<=0) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); SDDS_Bomb("no dependent quantities selected for interpolation"); } if (fileValuesFile && !SDDS_InitializeInput(&SDDSvalues, fileValuesFile)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (!SDDS_InitializeOutput(&SDDSout, SDDS_BINARY, 0, NULL, "sddsinterp output", output)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (!SDDS_TransferColumnDefinition(&SDDSout, &SDDSin, indepQuantity, NULL)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); /* if (fileValuesQuantity && strcmp(fileValuesQuantity, indepQuantity)!=0 && !SDDS_TransferColumnDefinition(&SDDSout, &SDDSvalues, fileValuesQuantity, NULL)) { fprintf(stderr, "problem creating -fileValues column %s\n", fileValuesQuantity); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } */ if (SDDS_DefineParameter(&SDDSout, "InterpDataPage", NULL, NULL, "Page of interpolation data file used to create this page", NULL, SDDS_LONG, NULL)<0 || SDDS_DefineParameter(&SDDSout, "InterpPointsPage", NULL, NULL, "Page of interpolation points file used to create this page", NULL, SDDS_LONG, NULL)<0) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); for (i=0; i<depenQuantities; i++) if (!SDDS_TransferColumnDefinition(&SDDSout, &SDDSin, depenQuantity[i], NULL)) { fprintf(stderr, "problem creating interpolated-output column %s\n", depenQuantity[i]); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (!SDDS_TransferAllParameterDefinitions(&SDDSout, &SDDSin, SDDS_TRANSFER_KEEPOLD) || !SDDS_WriteLayout(&SDDSout)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); doNotRead = 0; interpPoint = NULL; outputData = tmalloc(sizeof(*outputData)*(depenQuantities)); depenValue = tmalloc(sizeof(*depenValue)*(depenQuantities)); rowFlag = NULL; valuesReadCode = 0; while (doNotRead || (readCode=SDDS_ReadPage(&SDDSin))>0) { rows = SDDS_CountRowsOfInterest(&SDDSin); if (!(indepValue = SDDS_GetColumnInDoubles(&SDDSin, indepQuantity))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (atValues) { interpPoint = atValue; interpPoints = atValues; } else if (fileValuesFile) { if (interpPoint) free(interpPoint); if ((valuesReadCode=SDDS_ReadPage(&SDDSvalues))==0) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); else if (valuesReadCode==-1) { if (parallelPages) { fprintf(stderr, "warning: file %s ends before file %s\n", fileValuesFile, input); break; } else { /* "rewind" the values file */ if (!SDDS_Terminate(&SDDSvalues) || !SDDS_InitializeInput(&SDDSvalues, fileValuesFile)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if ((valuesReadCode=SDDS_ReadPage(&SDDSvalues))<1) { fprintf(stderr, "error: unable to (re)read file %s\n", fileValuesFile); SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } /* read the next page of the interpolation data file */ if ((readCode=SDDS_ReadPage(&SDDSin))<1) { if (readCode==-1) break; SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } rows = SDDS_CountRowsOfInterest(&SDDSin); if (indepValue) free(indepValue); if (!(indepValue = SDDS_GetColumnInDoubles(&SDDSin, indepQuantity))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } } if (!parallelPages) doNotRead = 1; interpPoints = SDDS_CountRowsOfInterest(&SDDSvalues); interpPoint = SDDS_GetColumnInDoubles(&SDDSvalues, fileValuesQuantity); if (SDDS_NumberOfErrors()) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } else if (sequencePoints || sequenceSpacing) { if (interpPoint) free(interpPoint); interpPoints = sequencePoints; if (!(interpPoint = makeSequence(&interpPoints, sequenceStart, sequenceEnd, sequenceSpacing, indepValue, rows))) exit(1); } else { /* fillIn interpolation */ if (interpPoint) free(interpPoint); if (!(interpPoint = makeFillInSequence(indepValue, rows, &interpPoints))) exit(1); } for (i=0; i<depenQuantities; i++) outputData[i] = tmalloc(sizeof(*outputData[i])*interpPoints); rowFlag = trealloc(rowFlag, sizeof(*rowFlag)*interpPoints); for (j=0; j<interpPoints; j++) rowFlag[j] = 1; for (i=0; i<depenQuantities; i++) { if (!(depenValue[i] = SDDS_GetColumnInDoubles(&SDDSin, depenQuantity[i]))) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); } if (forceMonotonic) rows = forceMonotonicity(indepValue, depenValue, depenQuantities, rows, forceMonotonic); else if (combineDuplicates) rows = combineDuplicatePoints(indepValue, depenValue, depenQuantities, rows, 0.0); if ((monotonicity=checkMonotonicity(indepValue, rows))==0) SDDS_Bomb("independent data values do not change monotonically or repeated independent values exist"); if (interpShort) shortValue = malloc(sizeof(*shortValue)*rows); for (i=0; i<depenQuantities; i++) { if (interpShort) { for (row=0; row<rows; row++) { shortValue[row] = (short)depenValue[i][row]; } } for (j=0; j<interpPoints; j++) { if (!interpShort) { outputData[i][j] = interpolate(depenValue[i], indepValue, rows, interpPoint[j], &belowRange, &aboveRange, order, &interpCode, monotonicity); } else { outputData[i][j] = (double)interp_short(shortValue, indepValue, rows, interpPoint[j], 0, -1, &interpCode, &nextPos); } if (interpCode) { if (interpCode&OUTRANGE_ABORT) { fprintf(stderr, "error: value %e is out of range for column %s\n", interpPoint[j], depenQuantity[i]); exit(1); } if (interpCode&OUTRANGE_WARN) fprintf(stderr, "warning: value %e is out of range for column %s\n", interpPoint[j], depenQuantity[i]); if (interpCode&OUTRANGE_SKIP) rowFlag[j] = 0; } } } if (interpShort) free(shortValue); if (!SDDS_StartPage(&SDDSout, interpPoints) || !SDDS_SetColumnFromDoubles(&SDDSout, SDDS_SET_BY_NAME, interpPoint, interpPoints, indepQuantity)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (!SDDS_SetParameters(&SDDSout, SDDS_BY_NAME|SDDS_PASS_BY_VALUE, "InterpDataPage", readCode, "InterpPointsPage", valuesReadCode, NULL) || !SDDS_CopyParameters(&SDDSout, &SDDSin)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); for (i=0; i<depenQuantities; i++) if (!SDDS_SetColumnFromDoubles(&SDDSout, SDDS_SET_BY_NAME, outputData[i], interpPoints, depenQuantity[i])) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (!SDDS_AssertRowFlags(&SDDSout, SDDS_FLAG_ARRAY, rowFlag, rows) || !SDDS_WritePage(&SDDSout)) SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); if (printFlags&BARE_PRINTOUT) { for (j=0; j<interpPoints; j++) if (rowFlag[j]) { fprintf(fpPrint, "%21.15e ", interpPoint[j]); for (i=0; i<depenQuantities; i++) fprintf(fpPrint, "%21.15e ", outputData[i][j]); fputc('\n', fpPrint); } } else if (printFlags&NORMAL_PRINTOUT) { for (j=0; j<interpPoints; j++) if (rowFlag[j]) { fprintf(fpPrint, "%s=%21.15e ", indepQuantity, interpPoint[j]); for (i=0; i<depenQuantities; i++) fprintf(fpPrint, "%s=%21.15e ", depenQuantity[i], outputData[i][j]); fputc('\n', fpPrint); } } if (indepValue) free(indepValue); indepValue = NULL; for (i=0; i<depenQuantities; i++) { if (outputData[i]) free(outputData[i]); outputData[i] = NULL; if (depenValue[i]) free(depenValue[i]); depenValue[i] = NULL; } if (fileValuesFile) { if (interpPoint) free(interpPoint); interpPoint = NULL; } if (rowFlag) free(rowFlag); rowFlag = NULL; } if (!SDDS_Terminate(&SDDSin)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } if (!SDDS_Terminate(&SDDSout)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } if (fileValuesFile) { if (!SDDS_Terminate(&SDDSvalues)) { SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); exit(1); } } return 0; }