コード例 #1
0
ファイル: drvrmem.c プロジェクト: geechee/iraf
/*--------------------------------------------------------------------------*/
int mem_write(int hdl, void *buffer, long nbytes)
/*
  write bytes at the current position in the file
*/
{
    size_t newsize;
    char *ptr;

    if ((size_t) (memTable[hdl].currentpos + nbytes) > 
         *(memTable[hdl].memsizeptr) )
    {
               
        if (!(memTable[hdl].mem_realloc))
        {
            ffpmsg("realloc function not defined (mem_write)");
            return(WRITE_ERROR);
        }

        /*
          Attempt to reallocate additional memory:
          the memory buffer size is incremented by the larger of:
             1 FITS block (2880 bytes) or
             the defined 'deltasize' parameter
         */

        newsize = maxvalue( (size_t)
            (((memTable[hdl].currentpos + nbytes - 1) / 2880) + 1) * 2880,
            *(memTable[hdl].memsizeptr) + memTable[hdl].deltasize);

        /* call the realloc function */
        ptr = (memTable[hdl].mem_realloc)(
                                    *(memTable[hdl].memaddrptr),
                                     newsize);
        if (!ptr)
        {
            ffpmsg("Failed to reallocate memory (mem_write)");
            return(MEMORY_ALLOCATION);
        }

        *(memTable[hdl].memaddrptr) = ptr;
        *(memTable[hdl].memsizeptr) = newsize;
    }

    /* now copy the bytes from the buffer into memory */
    memcpy( *(memTable[hdl].memaddrptr) + memTable[hdl].currentpos,
             buffer,
             nbytes);

    memTable[hdl].currentpos += nbytes;
    memTable[hdl].fitsfilesize =
               maxvalue(memTable[hdl].fitsfilesize,
                        memTable[hdl].currentpos);
    return(0);
}
コード例 #2
0
ファイル: Delete.c プロジェクト: tiljo/BinaryTrees
void Delete(struct node** node,int target)
{
        struct node* tar = NULL;
        struct node** headRef = &tar;
        struct node* temp = NULL;
        struct node* current = NULL;


        struct node* head = look(*node,target,*node);
        assert(head != NULL);

        if(head->data == target){
                tar=(*node);
                headRef = node;
        }
        else if(head->data < target){
                tar = head->right;
                headRef = &(head->right);
        }
        else{
                tar = head->left;
                headRef = &(head->left);
        }



        if((tar->left != NULL)  || (tar->right != NULL)){
                if((tar->right !=NULL) && (tar->left == NULL)){
                         temp = tar->right;
                }
                else{
                        if(maxvalue(tar->left) == (tar->left->data)){
                                        temp = tar->left;
                                        temp->right = tar->right;
                        }
                        else{
                                tar->data = maxvalue(tar->left);
                                Delete(&(tar->left),maxvalue(tar->left));
				return;
                        }
                }
        }
         
       current = *headRef;
       free(current);
       *headRef = temp;
       
}
コード例 #3
0
ファイル: bstree.c プロジェクト: matfil/projekt3
node* maxvalue (node* root)
{
  if (root->right != NULL)
  { return maxvalue (root->right); }
  else
  { return root; }
}
コード例 #4
0
int alphabeta(struct game *state,int alpha, int beta)
{

  /*  printf("minimax: Calculating minimax for board '%s' with player %c\n",state->board,state->player); */

  /* loop through next states getting minimax values */

  char outcome = isTerminal(state->board);

  switch(outcome)
  {
	case 'x':
	  return 1;
	case 'o':
	  return -1;
	case 'd':
	  return 0;
	case ' ':
	  if (state->player == 'x') {
		return maxvalue(gennextstates(state),alpha,beta);
	  } else {
		return minvalue(gennextstates(state),alpha,beta);
	  }
  }

}
コード例 #5
0
ファイル: putcolj.c プロジェクト: chopley/controlCode
/*--------------------------------------------------------------------------*/
int ffpprj( fitsfile *fptr,  /* I - FITS file pointer                       */
            long  group,     /* I - group to write(1 = 1st group)           */
            long  firstelem, /* I - first vector element to write(1 = 1st)  */
            long  nelem,     /* I - number of values to write               */
            long  *array,    /* I - array of values that are written        */
            int  *status)    /* IO - error status                           */
/*
  Write an array of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of
  the FITS array is not the same as the array being written).
*/
{
    long row;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */

        ffpmsg("writing to compressed image is not supported");

        return(*status = DATA_COMPRESSION_ERR);
    }

    row=maxvalue(1,group);

    ffpclj(fptr, 2, row, firstelem, nelem, array, status);
    return(*status);
}
コード例 #6
0
/*--------------------------------------------------------------------------*/
int ffppru( fitsfile *fptr,  /* I - FITS file pointer                       */
            long  group,      /* I - group to write(1 = 1st group)          */
            LONGLONG  firstelem,  /* I - first vector element to write(1 = 1st) */
            LONGLONG  nelem,      /* I - number of values to write              */
            int  *status)     /* IO - error status                          */
/*
  Write null values to the primary array.

*/
{
    long row;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */

        ffpmsg("writing to compressed image is not supported");

        return(*status = DATA_COMPRESSION_ERR);
    }

    row=maxvalue(1,group);

    ffpclu(fptr, 2, row, firstelem, nelem, status);
    return(*status);
}
コード例 #7
0
/*--------------------------------------------------------------------------*/
int ffppnb( fitsfile *fptr,  /* I - FITS file pointer                       */
            long  group,     /* I - group to write(1 = 1st group)           */
            long  firstelem, /* I - first vector element to write(1 = 1st)  */
            long  nelem,     /* I - number of values to write               */
            unsigned char *array, /* I - array of values that are written   */
            unsigned char nulval, /* I - undefined pixel value              */
            int  *status)    /* IO - error status                           */
/*
  Write an array of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of the
  FITS array is not the same as the array being written).  Any array values
  that are equal to the value of nulval will be replaced with the null
  pixel value that is appropriate for this column.
*/
{
    long row;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    row=maxvalue(1,group);

    ffpcnb(fptr, 2, row, firstelem, nelem, array, nulval, status);
    return(*status);
}
コード例 #8
0
ファイル: putcold.c プロジェクト: ARO-user/astropy
/*--------------------------------------------------------------------------*/
int ffpgpd( fitsfile *fptr,   /* I - FITS file pointer                      */
            long  group,      /* I - group to write(1 = 1st group)          */
            long  firstelem,  /* I - first vector element to write(1 = 1st) */
            long  nelem,      /* I - number of values to write              */
            double *array,    /* I - array of values that are written       */
            int  *status)     /* IO - error status                          */
/*
  Write an array of group parameters to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of
  the FITS array is not the same as the array being written).
*/
{
    long row;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    row=maxvalue(1,group);

    ffpcld(fptr, 1L, row, firstelem, nelem, array, status);
    return(*status);
}
コード例 #9
0
ファイル: maxvalue.c プロジェクト: tiljo/BinaryTrees
int maxvalue(struct node* node)
{
        int a,b,c;
        if((node->left ==0)&&(node->right==0))
                return node->data;
        else{
                if(node->left)
                        a = maxvalue(node->left);
                else a= node->data;

                if(node->right)
                        b=maxvalue(node->right);
                else b=node->data;

                c=(a>b)?a:b;
                return (c > node->data)?c:node->data;
        }
}
コード例 #10
0
ファイル: bstree.c プロジェクト: matfil/projekt3
void dprint (node* root) /* nie nadaje się do printowania poddrzew 
                            zawsze wyprintuje całe, bo root 
                            będzie miał rodzica */
{
  node* sth;
  sth = maxvalue (root);
  while ( sth != NULL )
  {
    printsingle (sth);
    sth = bstpred (sth);
  }
}
コード例 #11
0
/*--------------------------------------------------------------------------*/
int ffp3db(fitsfile *fptr,   /* I - FITS file pointer                     */
           long  group,      /* I - group to write(1 = 1st group)         */
           long  ncols,      /* I - number of pixels in each row of array */
           long  nrows,      /* I - number of rows in each plane of array */
           long  naxis1,     /* I - FITS image NAXIS1 value               */
           long  naxis2,     /* I - FITS image NAXIS2 value               */
           long  naxis3,     /* I - FITS image NAXIS3 value               */
           unsigned char *array, /* I - array to be written               */
           int  *status)     /* IO - error status                         */
/*
  Write an entire 3-D cube of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of the
  FITS array is not the same as the array being written).
*/
{
    long tablerow, nfits, narray, ii, jj;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */
    tablerow=maxvalue(1,group);

    if (ncols == naxis1 && nrows == naxis2)  /* arrays have same size? */
    {
      /* all the image pixels are contiguous, so write all at once */
      ffpclb(fptr, 2, tablerow, 1L, naxis1 * naxis2 * naxis3, array, status);
      return(*status);
    }

    nfits = 1;   /* next pixel in FITS image to write to */
    narray = 0;  /* next pixel in input array to be written */

    /* loop over naxis3 planes in the data cube */
    for (jj = 0; jj < naxis3; jj++)
    {
      /* loop over the naxis2 rows in the FITS image, */
      /* writing naxis1 pixels to each row            */

      for (ii = 0; ii < naxis2; ii++)
      {
       if (ffpclb(fptr, 2, tablerow, nfits, naxis1,&array[narray],status) > 0)
         return(*status);

       nfits += naxis1;
       narray += ncols;
      }
    }
    return(*status);
}
コード例 #12
0
ファイル: bstree.c プロジェクト: matfil/projekt3
node* bstpred (node* what)
{
  node* pred;
  pred = what->up;
  if (what == NULL)
  { return NULL; }
  if (what->left != NULL)
  { return maxvalue(what->left); }
  while(pred != NULL && pred->left == what )
  {
    what = pred;
    pred = pred->up;
  }
  return pred;
}
コード例 #13
0
ファイル: putcold.c プロジェクト: geechee/iraf
/*--------------------------------------------------------------------------*/
int ffppnd( fitsfile *fptr,   /* I - FITS file pointer                       */
            long  group,      /* I - group to write(1 = 1st group)           */
            long  firstelem,  /* I - first vector element to write(1 = 1st)  */
            long  nelem,      /* I - number of values to write               */
            double *array,    /* I - array of values that are written        */
            double nulval,    /* I - undefined pixel value                   */
            int  *status)     /* IO - error status                           */
/*
  Write an array of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of the
  FITS array is not the same as the array being written).  Any array values
  that are equal to the value of nulval will be replaced with the null
  pixel value that is appropriate for this column.
*/
{
    long row;
    double nullvalue;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */

        /* use the OFF_T variable to pass the first element value */
        if (firstelem != USE_LARGE_VALUE)
            large_first_elem_val = firstelem;

        nullvalue = nulval;  /* set local variable */
        fits_write_compressed_pixels(fptr, TDOUBLE, large_first_elem_val, nelem,
            1, array, &nullvalue, status);
        return(*status);
    }

    row=maxvalue(1,group);

    ffpcnd(fptr, 2, row, firstelem, nelem, array, nulval, status);
    return(*status);
}
コード例 #14
0
ファイル: putcole.c プロジェクト: ARO-user/astropy
/*--------------------------------------------------------------------------*/
int ffppne( fitsfile *fptr,  /* I - FITS file pointer                       */
            long  group,     /* I - group to write(1 = 1st group)           */
            LONGLONG firstelem, /* I - first vector element to write(1 = 1st)  */
            LONGLONG nelem,     /* I - number of values to write               */
            float *array,    /* I - array of values that are written        */
            float nulval,    /* I - undefined pixel value                   */
            int  *status)    /* IO - error status                           */
/*
  Write an array of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of the
  FITS array is not the same as the array being written).  Any array values
  that are equal to the value of nulval will be replaced with the null
  pixel value that is appropriate for this column.

  This routine cannot be called directly by users to write to large
  arrays with > 2**31 pixels (although CFITSIO can do so by passing
  the firstelem thru a LONGLONG sized global variable)
*/
{
    long row;
    float nullvalue;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */

        nullvalue = nulval;  /* set local variable */
        fits_write_compressed_pixels(fptr, TFLOAT, firstelem, nelem,
            1, array, &nullvalue, status);
        return(*status);
    }

    row=maxvalue(1,group);

    ffpcne(fptr, 2, row, firstelem, nelem, array, nulval, status);
    return(*status);
}
コード例 #15
0
ファイル: putcolk.c プロジェクト: geechee/iraf
/*--------------------------------------------------------------------------*/
int ffpprk( fitsfile *fptr,  /* I - FITS file pointer                       */
            long  group,     /* I - group to write(1 = 1st group)           */
            long  firstelem, /* I - first vector element to write(1 = 1st)  */
            long  nelem,     /* I - number of values to write               */
            int   *array,    /* I - array of values that are written        */
            int  *status)    /* IO - error status                           */
/*
  Write an array of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of
  the FITS array is not the same as the array being written).
*/
{
    long row;
    int nullvalue;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */

        /* use the OFF_T variable to pass the first element value */
        if (firstelem != USE_LARGE_VALUE)
            large_first_elem_val = firstelem;

        fits_write_compressed_pixels(fptr, TINT, large_first_elem_val, nelem,
            0, array, &nullvalue, status);
        return(*status);
    }

    row=maxvalue(1,group);

    ffpclk(fptr, 2, row, firstelem, nelem, array, status);
    return(*status);
}
コード例 #16
0
void countingsort(int *A, int n){
    int k = maxvalue(A, n);
    int m = minvalue(A, n);
    int sep = m < 0 ? -m : 0;
    int *B = new int[n];
    int *C = new int[k+sep+1];
    for(int i = 0; i < k+sep+1; i++)
        C[i] = 0;
    for(int i = 0; i < n; i++)
        C[A[i]+sep]++;
    for(int i = 1; i < k+1+sep; i++)
        C[i] += C[i-1];
    for(int i = n-1; i >= 0; i--){
        B[C[A[i]+sep]-1] = A[i];
        C[A[i]+sep]--;
    }
    for(int i = 0; i < n; i++){
        A[i]=B[i];
    }
    delete [] B;
    delete [] C;
}
コード例 #17
0
ファイル: histo.c プロジェクト: agnwinds/python
/*--------------------------------------------------------------------------*/
int fits_get_col_minmax(fitsfile *fptr, int colnum, float *datamin, 
                     float *datamax, int *status)
/* 
   Simple utility routine to compute the min and max value in a column
*/
{
    int anynul;
    long nrows, ntodo, firstrow, ii;
    float array[1000], nulval;

    ffgky(fptr, TLONG, "NAXIS2", &nrows, NULL, status); /* no. of rows */

    firstrow = 1;
    nulval = FLOATNULLVALUE;
    *datamin =  9.0E36F;
    *datamax = -9.0E36F;

    while(nrows)
    {
        ntodo = minvalue(nrows, 100);
        ffgcv(fptr, TFLOAT, colnum, firstrow, 1, ntodo, &nulval, array,
              &anynul, status);

        for (ii = 0; ii < ntodo; ii++)
        {
            if (array[ii] != nulval)
            {
                *datamin = minvalue(*datamin, array[ii]);
                *datamax = maxvalue(*datamax, array[ii]);
            }
        }

        nrows -= ntodo;
        firstrow += ntodo;
    }
    return(*status);
}
コード例 #18
0
ファイル: putcold.c プロジェクト: ARO-user/astropy
/*--------------------------------------------------------------------------*/
int ffpprd( fitsfile *fptr,  /* I - FITS file pointer                       */
            long  group,     /* I - group to write(1 = 1st group)           */
            LONGLONG  firstelem, /* I - first vector element to write(1 = 1st)  */
            LONGLONG  nelem,     /* I - number of values to write               */
            double *array,   /* I - array of values that are written        */
            int  *status)    /* IO - error status                           */
/*
  Write an array of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of
  the FITS array is not the same as the array being written).
*/
{
    long row;
    double nullvalue;

    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */

        fits_write_compressed_pixels(fptr, TDOUBLE, firstelem, nelem,
            0, array, &nullvalue, status);
        return(*status);
    }

    row=maxvalue(1,group);

    ffpcld(fptr, 2, row, firstelem, nelem, array, status);
    return(*status);
}
コード例 #19
0
ファイル: putcold.c プロジェクト: ARO-user/astropy
/*--------------------------------------------------------------------------*/
int ffp3dd(fitsfile *fptr,   /* I - FITS file pointer                     */
           long  group,      /* I - group to write(1 = 1st group)         */
           LONGLONG  ncols,      /* I - number of pixels in each row of array */
           LONGLONG  nrows,      /* I - number of rows in each plane of array */
           LONGLONG  naxis1,     /* I - FITS image NAXIS1 value               */
           LONGLONG  naxis2,     /* I - FITS image NAXIS2 value               */
           LONGLONG  naxis3,     /* I - FITS image NAXIS3 value               */
           double *array,    /* I - array to be written                   */
           int  *status)     /* IO - error status                         */
/*
  Write an entire 3-D cube of values to the primary array. Data conversion
  and scaling will be performed if necessary (e.g, if the datatype of the
  FITS array is not the same as the array being written).
*/
{
    long tablerow, ii, jj;
    long fpixel[3]= {1,1,1}, lpixel[3];
    LONGLONG nfits, narray;
    /*
      the primary array is represented as a binary table:
      each group of the primary array is a row in the table,
      where the first column contains the group parameters
      and the second column contains the image itself.
    */

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */
        lpixel[0] = (long) ncols;
        lpixel[1] = (long) nrows;
        lpixel[2] = (long) naxis3;

        fits_write_compressed_img(fptr, TDOUBLE, fpixel, lpixel,
            0,  array, NULL, status);
    
        return(*status);
    }

    tablerow=maxvalue(1,group);

    if (ncols == naxis1 && nrows == naxis2)  /* arrays have same size? */
    {
      /* all the image pixels are contiguous, so write all at once */
      ffpcld(fptr, 2, tablerow, 1L, naxis1 * naxis2 * naxis3, array, status);
      return(*status);
    }

    if (ncols < naxis1 || nrows < naxis2)
       return(*status = BAD_DIMEN);

    nfits = 1;   /* next pixel in FITS image to write to */
    narray = 0;  /* next pixel in input array to be written */

    /* loop over naxis3 planes in the data cube */
    for (jj = 0; jj < naxis3; jj++)
    {
      /* loop over the naxis2 rows in the FITS image, */
      /* writing naxis1 pixels to each row            */

      for (ii = 0; ii < naxis2; ii++)
      {
       if (ffpcld(fptr, 2, tablerow, nfits, naxis1,&array[narray],status) > 0)
         return(*status);

       nfits += naxis1;
       narray += ncols;
      }
      narray += (nrows - naxis2) * ncols;
    }
    return(*status);
}
コード例 #20
0
ファイル: Game.cpp プロジェクト: anygo/uniprojectsdn
/*!\brief Playing several rounds of black jack.
//
// \param rounds The number of rounds to be played.
// \return void
*/
void Game::play( size_t rounds )
{
   // Early exit in case no players or only a single player participate in the game
   if( players_.size() < 2 ) return;

   const size_t num( players_.size() );

   CardID card;
   size_t out( 0u );
   size_t maxvalue( 0u );

   for( size_t round=0u; round<rounds; ++round )
   {
      const Iterator begin( players_.begin() );
      const Iterator end  ( players_.end()   );

      // Drawing the first card
      for( Iterator player=begin; player!=end; ++player ) {
         card = deck_.draw();
         player->give( card );
         for( Iterator other=begin; other!=end; ++other ) {
            if( player != other )
               other->playerDrawsCard( *player, card );
         }
      }

      // Drawing the second card
      for( Iterator player=begin; player!=end; ++player ) {
         card = deck_.draw();
         player->give( card );
         for( Iterator other=begin; other!=end; ++other ) {
            if( player != other )
               other->playerDrawsCard( *player, card );
         }
      }

      // Drawing all other cards
      while( out < num )
      {
         for( Iterator player=begin; player!=end; ++player )
         {
            if( player->isOut() ) {
               continue;
            }

            if( !player->offer() ) {
               for( Iterator other=begin; other!=end; ++other ) {
                  if( player != other )
                     other->playerStands( *player );
               }
               ++out;
               continue;
            }

            card = deck_.draw();
            player->give( card );

            for( Iterator other=begin; other!=end; ++other ) {
               if( player != other )
                  other->playerDrawsCard( *player, card );
            }

            if( player->count() > 21u ) {
               ++out;
            }
         }
      }

      // Resetting the out counter
      out = 0u;

      // Estimating the winners
      maxvalue = 0u;
      for( Iterator player=begin; player!=end; ++player ) {
         const size_t value( player->count() );
         if( value > maxvalue && value < 22u ) {
            maxvalue = value;
         }
      }

      for( Iterator player=begin; player!=end; ++player ) {
         if( player->count() == maxvalue )
            player->addWin();
      }

      // Reshuffling the deck of cards
      const bool shuffle( deck_.size() < 100u );
      if( shuffle ) {
         deck_.shuffle();
      }
      for( Iterator player=begin; player!=end; ++player ) {
         player->newRound( shuffle );
      }

      // Estimating a new start player
      players_.push_back( players_.front() );
      players_.erase( players_.begin() );
   }
}
コード例 #21
0
/*--------------------------------------------------------------------------*/
int ffpcls( fitsfile *fptr,  /* I - FITS file pointer                       */
            int  colnum,     /* I - number of column to write (1 = 1st col) */
            LONGLONG  firstrow,  /* I - first row to write (1 = 1st row)        */
            LONGLONG  firstelem, /* I - first vector element to write (1 = 1st) */
            LONGLONG  nelem,     /* I - number of strings to write              */
            char  **array,   /* I - array of pointers to strings            */
            int  *status)    /* IO - error status                           */
/*
  Write an array of string values to a column in the current FITS HDU.
*/
{
    int tcode, maxelem, hdutype, nchar;
    long twidth, incre;
    long ii, jj, ntodo;
    LONGLONG repeat, startpos, elemnum, wrtptr, rowlen, rownum, remain, next, tnull;
    double scale, zero;
    char tform[20], *blanks;
    char message[FLEN_ERRMSG];
    char snull[20];   /*  the FITS null value  */
    tcolumn *colptr;

    double cbuff[DBUFFSIZE / sizeof(double)]; /* align cbuff on word boundary */
    char *buffer, *arrayptr;

    if (*status > 0)           /* inherit input status value if > 0 */
        return(*status);

    /* reset position to the correct HDU if necessary */
    if (fptr->HDUposition != (fptr->Fptr)->curhdu)
    {
        ffmahd(fptr, (fptr->HDUposition) + 1, NULL, status);
    }
    else if ((fptr->Fptr)->datastart == DATA_UNDEFINED)
    {
        if ( ffrdef(fptr, status) > 0)               /* rescan header */
            return(*status);
    }

    /*---------------------------------------------------*/
    /*  Check input and get parameters about the column: */
    /*---------------------------------------------------*/
    if (colnum < 1 || colnum > (fptr->Fptr)->tfield)
    {
        sprintf(message, "Specified column number is out of range: %d",
                colnum);
        ffpmsg(message);
        return(*status = BAD_COL_NUM);
    }

    colptr  = (fptr->Fptr)->tableptr;   /* point to first column */
    colptr += (colnum - 1);     /* offset to correct column structure */
    tcode = colptr->tdatatype;

    if (tcode == -TSTRING) /* variable length column in a binary table? */
    {
      /* only write a single string; ignore value of firstelem */
      nchar = maxvalue(1,strlen(array[0])); /* will write at least 1 char */
                                          /* even if input string is null */

      if (ffgcprll( fptr, colnum, firstrow, 1, nchar, 1, &scale, &zero,
        tform, &twidth, &tcode, &maxelem, &startpos,  &elemnum, &incre,
        &repeat, &rowlen, &hdutype, &tnull, snull, status) > 0)
        return(*status);
	
      /* simply move to write position, then write the string */
      ffmbyt(fptr, startpos, IGNORE_EOF, status); 
      ffpbyt(fptr, nchar, array[0], status);

      if (*status > 0)  /* test for error during previous write operation */
      {
         sprintf(message,
          "Error writing to variable length string column (ffpcls).");
         ffpmsg(message);
      }

      return(*status);
    }
    else if (tcode == TSTRING)
    {
      if (ffgcprll( fptr, colnum, firstrow, firstelem, nelem, 1, &scale, &zero,
        tform, &twidth, &tcode, &maxelem, &startpos,  &elemnum, &incre,
        &repeat, &rowlen, &hdutype, &tnull, snull, status) > 0)
        return(*status);

      /* if string length is greater than a FITS block (2880 char) then must */
      /* only write 1 string at a time, to force writein by ffpbyt instead of */
      /* ffpbytoff (ffpbytoff can't handle this case) */
      if (twidth > IOBUFLEN) {
        maxelem = 1;
        incre = twidth;
        repeat = 1;
      }   

      blanks = (char *) malloc(twidth); /* string for blank fill values */
      if (!blanks)
      {
        ffpmsg("Could not allocate memory for string (ffpcls)");
        return(*status = ARRAY_TOO_BIG);
      }

      for (ii = 0; ii < twidth; ii++)
          blanks[ii] = ' ';          /* fill string with blanks */

      remain = nelem;           /* remaining number of values to write  */
    }
    else 
      return(*status = NOT_ASCII_COL);
 
    /*-------------------------------------------------------*/
    /*  Now write the strings to the FITS column.            */
    /*-------------------------------------------------------*/

    next = 0;                 /* next element in array to be written  */
    rownum = 0;               /* row number, relative to firstrow     */

    while (remain)
    {
      /* limit the number of pixels to process at one time to the number that
         will fit in the buffer space or to the number of pixels that remain
         in the current vector, which ever is smaller.
      */
      ntodo = (long) minvalue(remain, maxelem);      
      ntodo = (long) minvalue(ntodo, (repeat - elemnum));

      wrtptr = startpos + (rownum * rowlen) + (elemnum * incre);
      ffmbyt(fptr, wrtptr, IGNORE_EOF, status);  /* move to write position */

      buffer = (char *) cbuff;

      /* copy the user's strings into the buffer */
      for (ii = 0; ii < ntodo; ii++)
      {
         arrayptr = array[next];

         for (jj = 0; jj < twidth; jj++)  /*  copy the string, char by char */
         {
            if (*arrayptr)
            {
              *buffer = *arrayptr;
              buffer++;
              arrayptr++;
            }
            else
              break;
         }

         for (;jj < twidth; jj++)    /* fill field with blanks, if needed */
         {
           *buffer = ' ';
           buffer++;
         }

         next++;
      }

      /* write the buffer full of strings to the FITS file */
      if (incre == twidth)
         ffpbyt(fptr, ntodo * twidth, cbuff, status);
      else
         ffpbytoff(fptr, twidth, ntodo, incre - twidth, cbuff, status);

      if (*status > 0)  /* test for error during previous write operation */
      {
         sprintf(message,
          "Error writing elements %.0f thru %.0f of input data array (ffpcls).",
             (double) (next+1), (double) (next+ntodo));
         ffpmsg(message);

         if (blanks)
           free(blanks);

         return(*status);
      }

      /*--------------------------------------------*/
      /*  increment the counters for the next loop  */
      /*--------------------------------------------*/
      remain -= ntodo;
      if (remain)
      {
          elemnum += ntodo;
          if (elemnum == repeat)  /* completed a row; start on next row */
          {
              elemnum = 0;
              rownum++;
          }
       }
    }  /*  End of main while Loop  */

    if (blanks)
      free(blanks);

    return(*status);
}
コード例 #22
0
ファイル: mp3rtp.c プロジェクト: artclarke/humble-video
int
lame_main(lame_t gf, int argc, char **argv)
{
    unsigned char mp3buffer[LAME_MAXMP3BUFFER];
    char    inPath[PATH_MAX + 1];
    char    outPath[PATH_MAX + 1];
    int     Buffer[2][1152];

    int     maxx = 0, tmpx = 0;
    int     ret;
    int     wavsamples;
    int     mp3bytes;
    FILE   *outf;

    char    ip[16];
    unsigned int port = 5004;
    unsigned int ttl = 2;
    char    dummy;

    if (argc <= 2) {
        console_printf("Encode (via LAME) to mp3 with RTP streaming of the output\n"
                       "\n"
                       "    mp3rtp ip[:port[:ttl]] [lame encoding options] infile outfile\n"
                       "\n"
                       "    examples:\n"
                       "      arecord -b 16 -s 22050 -w | ./mp3rtp 224.17.23.42:5004:2 -b 56 - /dev/null\n"
                       "      arecord -b 16 -s 44100 -w | ./mp3rtp 10.1.1.42 -V2 -b128 -B256 - my_mp3file.mp3\n"
                       "\n");
        return 1;
    }

    switch (sscanf(argv[1], "%11[.0-9]:%u:%u%c", ip, &port, &ttl, &dummy)) {
    case 1:
    case 2:
    case 3:
        break;
    default:
        error_printf("Illegal destination selector '%s', must be ip[:port[:ttl]]\n", argv[1]);
        return -1;
    }
    rtp_initialization();
    if (rtp_socket(ip, port, ttl)) {
        rtp_deinitialization();
        error_printf("fatal error during initialization\n");
        return 1;
    }

    lame_set_errorf(gf, &frontend_errorf);
    lame_set_debugf(gf, &frontend_debugf);
    lame_set_msgf(gf, &frontend_msgf);

    /* Remove the argumets that are rtp related, and then 
     * parse the command line arguments, setting various flags in the
     * struct pointed to by 'gf'.  If you want to parse your own arguments,
     * or call libmp3lame from a program which uses a GUI to set arguments,
     * skip this call and set the values of interest in the gf struct.  
     * (see lame.h for documentation about these parameters)
     */
    {
        int     i;
        int     argc_mod = argc-1; /* leaving out exactly one argument */
        char**  argv_mod = calloc(argc_mod, sizeof(char*));
        argv_mod[0] = argv[0];
        for (i = 2; i < argc; ++i) { /* leaving out argument number 1, parsed above */
            argv_mod[i-1] = argv[i];
        }
        parse_args(gf, argc_mod, argv_mod, inPath, outPath, NULL, NULL);
        free(argv_mod);
    }

    /* open the output file.  Filename parsed into gf.inPath */
    if (0 == strcmp(outPath, "-")) {
        lame_set_stream_binary_mode(outf = stdout);
    }
    else {
        if ((outf = lame_fopen(outPath, "wb+")) == NULL) {
            rtp_deinitialization();
            error_printf("Could not create \"%s\".\n", outPath);
            return 1;
        }
    }


    /* open the wav/aiff/raw pcm or mp3 input file.  This call will
     * open the file with name gf.inFile, try to parse the headers and
     * set gf.samplerate, gf.num_channels, gf.num_samples.
     * if you want to do your own file input, skip this call and set
     * these values yourself.  
     */
    if (init_infile(gf, inPath) < 0) {
        rtp_deinitialization();
        fclose(outf);
        error_printf("Can't init infile '%s'\n", inPath);
        return 1;
    }


    /* Now that all the options are set, lame needs to analyze them and
     * set some more options 
     */
    ret = lame_init_params(gf);
    if (ret < 0) {
        if (ret == -1)
            display_bitrates(stderr);
        rtp_deinitialization();
        fclose(outf);
        close_infile();
        error_printf("fatal error during initialization\n");
        return -1;
    }

    lame_print_config(gf); /* print useful information about options being used */

    if (global_ui_config.update_interval < 0.)
        global_ui_config.update_interval = 2.;

    /* encode until we hit EOF */
    while ((wavsamples = get_audio(gf, Buffer)) > 0) { /* read in 'wavsamples' samples */
        levelmessage(maxvalue(Buffer), &maxx, &tmpx);
        mp3bytes = lame_encode_buffer_int(gf, /* encode the frame */
                                          Buffer[0], Buffer[1], wavsamples,
                                          mp3buffer, sizeof(mp3buffer));
        rtp_output(mp3buffer, mp3bytes); /* write MP3 output to RTP port */
        fwrite(mp3buffer, 1, mp3bytes, outf); /* write the MP3 output to file */
    }

    mp3bytes = lame_encode_flush(gf, /* may return one or more mp3 frame */
                                 mp3buffer, sizeof(mp3buffer));
    rtp_output(mp3buffer, mp3bytes); /* write MP3 output to RTP port */
    fwrite(mp3buffer, 1, mp3bytes, outf); /* write the MP3 output to file */

    lame_mp3_tags_fid(gf, outf); /* add VBR tags to mp3 file */

    rtp_deinitialization();
    fclose(outf);
    close_infile();     /* close the sound input file */
    return 0;
}
コード例 #23
0
ファイル: putcol.c プロジェクト: chopley/controlCode
/*--------------------------------------------------------------------------*/
int ffiter(int n_cols,
           iteratorCol *cols,
           long offset,
           long n_per_loop,
           int (*work_fn)(long total_n,
                          long offset,
                          long first_n,
                          long n_values,
                          int n_cols,
                          iteratorCol *cols,
                          void *userPointer),
           void *userPointer,
           int *status)
/*
   The iterator function.  This function will pass the specified
   columns from a FITS table or pixels from a FITS image to the 
   user-supplied function.  Depending on the size of the table
   or image, only a subset of the rows or pixels may be passed to the
   function on each call, in which case the function will be called
   multiple times until all the rows or pixels have been processed.
*/
{
    typedef struct  /* structure to store the column null value */
    {  
        int      nullsize;    /* length of the null value, in bytes */
        union {   /*  default null value for the column */
            char   *stringnull;
            unsigned char   charnull;
            int    intnull;
            short  shortnull;
            long   longnull;
            unsigned int   uintnull;
            unsigned short ushortnull;
            unsigned long  ulongnull;
            float  floatnull;
            double doublenull;
        } null;
    } colNulls;

    void *dataptr, *defaultnull;
    colNulls *col;
    int ii, jj, tstatus;
    int typecode, hdutype, jtype, type, anynul, nfiles, nbytes;
    long totaln, nleft, frow, felement, n_optimum, i_optimum, ntodo;
    long rept, width, tnull;
    double zeros = 0.;
    char message[FLEN_ERRMSG], keyname[FLEN_KEYWORD], nullstr[FLEN_VALUE];
    char **stringptr, *nullptr, *cptr;

    if (*status > 0)
        return(*status);

    if (n_cols  < 0 || n_cols > 999 )
    {
        ffpmsg("Illegal number of columms (ffiter)");
        return(*status = BAD_COL_NUM);  /* negative number of columns */
    }

    col = calloc(n_cols, sizeof(colNulls) ); /* memory for the null values */

    /*------------------------------------------------------------*/
    /* Make sure column numbers and datatypes are in legal range  */
    /* and column numbers and datatypes are legal.                */ 
    /* Also fill in other parameters in the column structure.     */
    /*------------------------------------------------------------*/

    ffghdt(cols[0].fptr, &hdutype, status);  /* type of first HDU */

    for (jj = 0; jj < n_cols; jj++)
    {
        /* check that output datatype code value is legal */
        type = cols[jj].datatype;  
        if (type != 0 &&
            type != TBYTE  && type != TLOGICAL && type != TSTRING &&
            type != TSHORT && type != TINT     && type != TLONG && 
            type != TFLOAT && type != TDOUBLE  && type != TCOMPLEX &&
            type != TULONG && type != TUSHORT  && type != TDBLCOMPLEX)
        {
            sprintf(message,
                   "Illegal datatype for column number %d: %d  (ffiter)",
                    jj + 1, cols[jj].datatype);
            ffpmsg(message);
            return(*status = BAD_DATATYPE);
        }

        /* initialize TLMINn, TLMAXn, column name, and display format */
        cols[jj].tlmin = 0;
        cols[jj].tlmax = 0;
        cols[jj].tunit[0] = '\0';
        cols[jj].tdisp[0] = '\0';

        ffghdt(cols[jj].fptr, &jtype, status);  /* get HDU type */

        if (hdutype == IMAGE_HDU)
        {
            if (jtype != IMAGE_HDU)
            {
                sprintf(message,
                "File %d not positioned to an image extension (ffiter)",
                    jj + 1);
                return(*status = NOT_IMAGE);
            }

            /* images are stored in column 2; ignore the input value */
            cols[jj].colnum = 2;
            strcpy(cols[jj].colname, "IMAGE");  /* dummy name for images */

            tstatus = 0;
            ffgkys(cols[jj].fptr, "BUNIT", cols[jj].tunit, 0, &tstatus);
        }
        else
        {
            if (jtype == IMAGE_HDU)
            {
                sprintf(message,
                "File %d not positioned to a table extension (ffiter)",
                    jj + 1);
                return(*status = NOT_TABLE);
            }

            if (cols[jj].colnum < 1)
            {
                /* find the column number for the named column */
                if (ffgcno(cols[jj].fptr, CASEINSEN, cols[jj].colname,
                           &cols[jj].colnum, status) )
                {
                    sprintf(message,
                      "Column '%s' not found for column number %d  (ffiter)",
                       cols[jj].colname, jj + 1);
                    ffpmsg(message);
                    return(*status);
                }
            }

            if (cols[jj].colnum < 1 || 
                cols[jj].colnum > ((cols[jj].fptr)->Fptr)->tfield)
            {
                sprintf(message,
                  "Column %d has illegal table position number: %d  (ffiter)",
                    jj + 1, cols[jj].colnum);
                ffpmsg(message);
                return(*status = BAD_COL_NUM);
            }

            /* look for column description keywords and update structure */
            tstatus = 0;
            ffkeyn("TLMIN", cols[jj].colnum, keyname, &tstatus);
            ffgkyj(cols[jj].fptr, keyname, &cols[jj].tlmin, 0, &tstatus);

            tstatus = 0;
            ffkeyn("TLMAX", cols[jj].colnum, keyname, &tstatus);
            ffgkyj(cols[jj].fptr, keyname, &cols[jj].tlmax, 0, &tstatus);

            tstatus = 0;
            ffkeyn("TTYPE", cols[jj].colnum, keyname, &tstatus);
            ffgkys(cols[jj].fptr, keyname, cols[jj].colname, 0, &tstatus);
            if (tstatus)
                cols[jj].colname[0] = '\0';

            tstatus = 0;
            ffkeyn("TUNIT", cols[jj].colnum, keyname, &tstatus);
            ffgkys(cols[jj].fptr, keyname, cols[jj].tunit, 0, &tstatus);

            tstatus = 0;
            ffkeyn("TDISP", cols[jj].colnum, keyname, &tstatus);
            ffgkys(cols[jj].fptr, keyname, cols[jj].tdisp, 0, &tstatus);
        }
    }

    /*-----------------------------------------------------------------*/
    /* use the first file to set the total number of values to process */
    /*-----------------------------------------------------------------*/

    offset = maxvalue(offset, 0L);  /* make sure offset is legal */

    if (hdutype == IMAGE_HDU)   /* get total number of pixels in the image */
    {
      ffgtcl(cols[0].fptr, cols[0].colnum, NULL, &totaln, &width, status);
      frow = 1;
      felement = 1 + offset;
    }
    else   /* get total number or rows in the table */
    {
      ffgkyj(cols[0].fptr, "NAXIS2", &totaln, 0, status);
      frow = 1 + offset;
      felement = 1;
    }

    /*  adjust total by the input starting offset value */
    totaln -= offset;
    totaln = maxvalue(totaln, 0L);   /* don't allow negative number */

    /*------------------------------------------------------------------*/
    /* Determine number of values to pass to work function on each loop */
    /*------------------------------------------------------------------*/

    if (n_per_loop == 0)
    {
        /* Determine optimum number of values for each iteration.    */
        /* Look at all the fitsfile pointers to determine the number */
        /* of unique files.                                          */

        nfiles = 1;
        ffgrsz(cols[0].fptr, &n_optimum, status);

        for (jj = 1; jj < n_cols; jj++)
        {
            for (ii = 0; ii < jj; ii++)
            {
                if (cols[ii].fptr == cols[jj].fptr)
                   break;
            }

            if (ii == jj)  /* this is a new file */
            {
                nfiles++;
                ffgrsz(cols[jj].fptr, &i_optimum, status);
                n_optimum = minvalue(n_optimum, i_optimum);
            }
        }

        n_optimum = n_optimum / nfiles;
    }
    else if (n_per_loop < 0)  /* must pass all the values at one time */
    {
        n_optimum = totaln;
    }
    else /* calling routine specified how many values to pass at a time */
    {
        n_optimum = minvalue(n_per_loop, totaln);
    }

    /*--------------------------------------*/
    /* allocate work arrays for each column */
    /* and determine the null pixel value   */
    /*--------------------------------------*/

    for (jj = 0; jj < n_cols; jj++)
    {
        /* get column datatype and vector length */
        if (ffgtcl(cols[jj].fptr, cols[jj].colnum, &typecode, &rept,
                  &width, status) > 0)
            goto cleanup;

        /* special case where sizeof(long) = 8: use TINT instead of TLONG */
        if (typecode == TLONG && sizeof(long) == 8 && sizeof(int) == 4)
            typecode = TINT;

        /* Special case: interprete 'X' column as 'B' */
        if (abs(typecode) == TBIT)
        {
            typecode  = typecode / TBIT * TBYTE;
            rept = (rept + 7) / 8;
        }

        if (cols[jj].datatype == 0)    /* output datatype not specified? */
        {
            /* special case if sizeof(long) = 8: use TINT instead of TLONG */
            if (typecode == TLONG && sizeof(long) == 8 && sizeof(int) == 4)
                cols[jj].datatype = TINT;
            else
                cols[jj].datatype = typecode;
        }

        /* calc total number of elements to do on each iteration */
        if (hdutype == IMAGE_HDU || cols[jj].datatype == TSTRING)
        {
            ntodo = n_optimum; 
            cols[jj].repeat = 1;

            /* get the BLANK keyword value, if it exists */
            if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
            {
                tstatus = 0;
                ffgkyj(cols[jj].fptr, "BLANK", &tnull, 0, &tstatus);
                if (tstatus)
                {
                    tnull = 0L;  /* no null values */
                }
            }
        }
        else
        {
            ntodo = n_optimum * rept;   /* vector columns */
            cols[jj].repeat = rept;

            /* get the TNULL keyword value, if it exists */
            if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
            {
                tstatus = 0;
                if (hdutype == ASCII_TBL) /* TNULLn value is a string */
                {
                    ffkeyn("TNULL", cols[jj].colnum, keyname, &tstatus);
                    ffgkys(cols[jj].fptr, keyname, nullstr, 0, &tstatus);
                    if (tstatus)
                    {
                        tnull = 0L; /* keyword doesn't exist; no null values */
                    }
                    else
                    {
                        cptr = nullstr;
                        while (*cptr == ' ')  /* skip over leading blanks */
                           cptr++;

                        if (*cptr == '\0')  /* TNULLn is all blanks? */
                            tnull = LONG_MIN;
                        else
                        {                                                
                            /* attempt to read TNULLn string as an integer */
                            ffc2ii(nullstr, &tnull, &tstatus);

                            if (tstatus)
                                tnull = LONG_MIN;  /* choose smallest value */
                        }                          /* to represent nulls */
                    }
                }
                else  /* Binary table; TNULLn value is an integer */
                {
                    ffkeyn("TNULL", cols[jj].colnum, keyname, &tstatus);
                    ffgkyj(cols[jj].fptr, keyname, &tnull, 0, &tstatus);
                    if (tstatus)
                    {
                        tnull = 0L; /* keyword doesn't exist; no null values */
                    }
                    else if (tnull == 0)
                    {
                        /* worst possible case: a value of 0 is used to   */
                        /* represent nulls in the FITS file.  We have to  */
                        /* use a non-zero null value here (zero is used to */
                        /* mean there are no null values in the array) so we */
                        /* will use the smallest possible integer instead. */

                        tnull = LONG_MIN;  /* choose smallest possible value */
                    }
                }
            }
        }

        /* Note that the data array starts with 2nd element;  */
        /* 1st element of the array gives the null data value */

        switch (cols[jj].datatype)
        {
         case TBYTE:
          cols[jj].array = calloc(ntodo + 1, sizeof(char));
          col[jj].nullsize  = sizeof(char);  /* number of bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              tnull = minvalue(tnull, 255);
              tnull = maxvalue(tnull, 0);
              col[jj].null.charnull = (unsigned char) tnull;
          }
          else
          {
              col[jj].null.charnull = (unsigned char) 255; /* use 255 as null */
          }
          break;

         case TSHORT:
          cols[jj].array = calloc(ntodo + 1, sizeof(short));
          col[jj].nullsize  = sizeof(short);  /* number of bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              tnull = minvalue(tnull, SHRT_MAX);
              tnull = maxvalue(tnull, SHRT_MIN);
              col[jj].null.shortnull = (short) tnull;
          }
          else
          {
              col[jj].null.shortnull = SHRT_MIN;  /* use minimum as null */
          }
          break;

         case TUSHORT:
          cols[jj].array = calloc(ntodo + 1, sizeof(unsigned short));
          col[jj].nullsize  = sizeof(unsigned short);  /* bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              tnull = minvalue(tnull, USHRT_MAX);
              tnull = maxvalue(tnull, 0);  /* don't allow negative value */
              col[jj].null.ushortnull = (unsigned short) tnull;
          }
          else
          {
              col[jj].null.ushortnull = USHRT_MAX;   /* use maximum null */
          }
          break;

         case TINT:
          cols[jj].array = calloc(ntodo + 1, sizeof(int));
          col[jj].nullsize  = sizeof(int);  /* number of bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              tnull = minvalue(tnull, INT_MAX);
              tnull = maxvalue(tnull, INT_MIN);
              col[jj].null.intnull = (int) tnull;
          }
          else
          {
              col[jj].null.intnull = INT_MIN;  /* use minimum as null */
          }
          break;

         case TUINT:
          cols[jj].array = calloc(ntodo + 1, sizeof(unsigned int));
          col[jj].nullsize  = sizeof(unsigned int);  /* bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              tnull = minvalue(tnull, INT32_MAX);
              tnull = maxvalue(tnull, 0);
              col[jj].null.uintnull = (unsigned int) tnull;
          }
          else
          {
              col[jj].null.intnull = UINT_MAX;  /* use maximum as null */
          }
          break;

         case TLONG:
          cols[jj].array = calloc(ntodo + 1, sizeof(long));
          col[jj].nullsize  = sizeof(long);  /* number of bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              col[jj].null.longnull = tnull;
          }
          else
          {
              col[jj].null.longnull = LONG_MIN;   /* use minimum as null */
          }
          break;

         case TULONG:
          cols[jj].array = calloc(ntodo + 1, sizeof(unsigned long));
          col[jj].nullsize  = sizeof(unsigned long);  /* bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              if (tnull < 0)  /* can't use a negative null value */
                  col[jj].null.ulongnull = LONG_MAX;
              else
                  col[jj].null.ulongnull = (unsigned long) tnull;
          }
          else
          {
              col[jj].null.ulongnull = LONG_MAX;   /* use maximum as null */
          }
          break;

         case TFLOAT:
          cols[jj].array = calloc(ntodo + 1, sizeof(float));
          col[jj].nullsize  = sizeof(float);  /* number of bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              col[jj].null.floatnull = (float) tnull;
          }
          else
          {
              col[jj].null.floatnull = FLOATNULLVALUE;  /* special value */
          }
          break;

         case TCOMPLEX:
          cols[jj].array = calloc((ntodo * 2) + 1, sizeof(float));
          col[jj].nullsize  = sizeof(float);  /* number of bytes per value */
          col[jj].null.floatnull = FLOATNULLVALUE;  /* special value */
          break;

         case TDOUBLE:
          cols[jj].array = calloc(ntodo + 1, sizeof(double));
          col[jj].nullsize  = sizeof(double);  /* number of bytes per value */

          if (typecode == TBYTE || typecode == TSHORT || typecode == TLONG)
          {
              col[jj].null.doublenull = (double) tnull;
          }
          else
          {
              col[jj].null.doublenull = DOUBLENULLVALUE;  /* special value */
          }
          break;

         case TDBLCOMPLEX:
          cols[jj].array = calloc((ntodo * 2) + 1, sizeof(double));
          col[jj].nullsize  = sizeof(double);  /* number of bytes per value */
          col[jj].null.doublenull = DOUBLENULLVALUE;  /* special value */
          break;

         case TSTRING:
          /* allocate array of pointers to all the strings  */
	  if( hdutype==ASCII_TBL ) rept = width;
          stringptr = calloc((ntodo + 1) , sizeof(stringptr));
          cols[jj].array = stringptr;
          col[jj].nullsize  = rept + 1;  /* number of bytes per value */

          if (stringptr)
          {
            /* allocate string to store the null string value */
            col[jj].null.stringnull = calloc(rept + 1, sizeof(char) );
            col[jj].null.stringnull[1] = 1; /* to make sure string != 0 */

            /* allocate big block for the array of table column strings */
            stringptr[0] = calloc((ntodo + 1) * (rept + 1), sizeof(char) );

            if (stringptr[0])
            {
              for (ii = 1; ii <= ntodo; ii++)
              {   /* pointer to each string */
                stringptr[ii] = stringptr[ii - 1] + (rept + 1);
              }

              /* get the TNULL keyword value, if it exists */
              tstatus = 0;
              ffkeyn("TNULL", cols[jj].colnum, keyname, &tstatus);
              ffgkys(cols[jj].fptr, keyname, nullstr, 0, &tstatus);
              if (!tstatus)
                  strncat(col[jj].null.stringnull, nullstr, rept);
            }
            else
            {
              ffpmsg("ffiter failed to allocate memory arrays");
              *status = MEMORY_ALLOCATION;  /* memory allocation failed */
              goto cleanup;
            }
          }
          break;

         case TLOGICAL:

          cols[jj].array = calloc(ntodo + 1, sizeof(char));
          col[jj].nullsize  = sizeof(char);  /* number of bytes per value */

          /* use value = 2 to flag null values in logical columns */
          col[jj].null.charnull = 2;
          break;

         default:
          sprintf(message,
                  "Column %d datatype currently not supported: %d:  (ffiter)",
                   jj + 1, cols[jj].datatype);
          ffpmsg(message);
          *status = BAD_DATATYPE;
          goto cleanup;

        }   /* end of switch block */

        /* check that all the arrays were allocated successfully */
        if (!cols[jj].array)
        {
            ffpmsg("ffiter failed to allocate memory arrays");
            *status = MEMORY_ALLOCATION;  /* memory allocation failed */
            goto cleanup;
        }
    }
 
    /*--------------------------------------------------*/
    /* main loop while there are values left to process */
    /*--------------------------------------------------*/

    nleft = totaln;

    while (nleft)
    {
      ntodo = minvalue(nleft, n_optimum); /* no. of values for this loop */

      /*  read input columns from FITS file(s)  */
      for (jj = 0; jj < n_cols; jj++)
      {
        if (cols[jj].iotype != OutputCol)
        {
          if (cols[jj].datatype == TSTRING)
          {
            stringptr = cols[jj].array;
            dataptr = stringptr + 1;
            defaultnull = col[jj].null.stringnull; /* ptr to the null value */
          }
          else
          {
            dataptr = (char *) cols[jj].array + col[jj].nullsize;
            defaultnull = &col[jj].null.charnull; /* ptr to the null value */
          }
          if (ffgcv(cols[jj].fptr, cols[jj].datatype, cols[jj].colnum,
                    frow, felement, cols[jj].repeat * ntodo, defaultnull,
                    dataptr,  &anynul, status) > 0)
          {
            break;
          }

          /* copy the appropriate null value into first array element */

          if (anynul)   /* are there any nulls in the data? */
          {   
            if (cols[jj].datatype == TSTRING)
            {
              stringptr = cols[jj].array;
              memcpy(*stringptr, col[jj].null.stringnull, col[jj].nullsize);
            }
            else
            {
              memcpy(cols[jj].array, defaultnull, col[jj].nullsize);
            }
          }
          else /* no null values so copy zero into first element */
          {
            if (cols[jj].datatype == TSTRING)
            {
              stringptr = cols[jj].array;
              memset(*stringptr, 0, col[jj].nullsize);  
            }
            else
            {
              memset(cols[jj].array, 0, col[jj].nullsize);  
            }
          }
        }
      }

      if (*status > 0) 
         break;   /* looks like an error occurred; quit immediately */

      /* call work function */

      if (hdutype == IMAGE_HDU) 
          *status = work_fn(totaln, offset, felement, ntodo, n_cols, cols,
                    userPointer);
      else
          *status = work_fn(totaln, offset, frow, ntodo, n_cols, cols,
                    userPointer);

      if (*status > 0 || *status < -1 ) 
         break;   /* looks like an error occurred; quit immediately */

      /*  write output columns  before quiting if status = -1 */
      tstatus = 0;
      for (jj = 0; jj < n_cols; jj++)
      {
        if (cols[jj].iotype != InputCol)
        {
          if (cols[jj].datatype == TSTRING)
          {
            stringptr = cols[jj].array;
            dataptr = stringptr + 1;
            nullptr = *stringptr;
            nbytes = 2;
          }
          else
          {
            dataptr = (char *) cols[jj].array + col[jj].nullsize;
            nullptr = (char *) cols[jj].array;
            nbytes = col[jj].nullsize;
          }

          if (memcmp(nullptr, &zeros, nbytes) ) 
          {
            /* null value flag not zero; must check for and write nulls */
            if (ffpcn(cols[jj].fptr, cols[jj].datatype, cols[jj].colnum, frow,
                      felement, cols[jj].repeat * ntodo, dataptr,
                      nullptr, &tstatus) > 0)
              break;
          }
          else
          { 
            /* no null values; just write the array */
            if (ffpcl(cols[jj].fptr, cols[jj].datatype, cols[jj].colnum, frow,
                      felement, cols[jj].repeat * ntodo, dataptr,
                      &tstatus) > 0)
              break;
          }
        }
      }

      if (*status == 0)
         *status = tstatus;   /* propagate any error status from the writes */

      if (*status) 
         break;   /* exit on any error */

      nleft -= ntodo;

      if (hdutype == IMAGE_HDU)
          felement += ntodo;
      else
          frow  += ntodo;
    }

cleanup:

    /*----------------------------------*/
    /* free work arrays for the columns */
    /*----------------------------------*/

    for (jj = 0; jj < n_cols; jj++)
    {
        if (cols[jj].datatype == TSTRING)
        {
            if (cols[jj].array)
            {
                stringptr = cols[jj].array;
                free(*stringptr);     /* free the block of strings */
                free(col[jj].null.stringnull); /* free the null string */
            }
        }
        free(cols[jj].array); /* memory for the array of values from the col */
    }
    free(col);   /* the structure containing the null values */
    return(*status);
}
コード例 #24
0
ファイル: isBST2.c プロジェクト: tiljo/BinaryTrees
int isBST2(struct node* node)
{
	int min = minvalue(node);
	int max = maxvalue(node);
	return isBSTRecur(node,min,max);
}
コード例 #25
0
ファイル: migration_0826.c プロジェクト: yujinyu/QEMU_PACER
static void migration_rate_tick(void *opaque)
{
   FdMigrationState *s = opaque;
   int interval=30000;

   int64_t total_transfer =  my_blk_mig_bytes_transferred();
   int64_t current_transfer = total_transfer - s->last_transferred;
   int64_t real_speed = current_transfer*1000/s->last_interval; //Bytes per second 
   
   int64_t pasttime=(qemu_get_clock(rt_clock)-s->starttime)/1000L;
   printf("time %"PRId64" real_speed %"PRId64" ",pasttime,real_speed);

   int64_t memsize=ram_bytes_remaining();
   int64_t remaindisksize=get_remaining_dirty();
   int64_t speed = 0L;
   int64_t maxspeed=80L*1024L*1024L;
   int64_t restdisk=(bdrv_get_totallength()-total_transfer);
 
   //old version for dirtyrate which is the average rate comparing to time zero
 /*int64_t dirtyamount=(disksize-restdisk);
   int64_t dirtyrate=dirtyamount/pasttime;
   int64_t newdirtyrate=dirtyrate;
  */
 
   //old drity - transferred + generated = new dirty 
   int64_t newgenerate = remaindisksize + current_transfer - s->last_dirty;
   int64_t dirtyrate=newgenerate*1000/s->last_interval;
   int64_t newdirtyrate=dirtyrate;

   int64_t resttime=(uint64_t)(s->mig_state.mig_time)-pasttime;
   int64_t real_speed_MB = real_speed >> 20L;
   int64_t last_speed_MB = s->last_speed >> 20L;
   int64_t speed_MB = 0L;
 
   if(s->mig_state.mig_time <= pasttime)
   {
      //already over the time
      speed=maxspeed;
   }else { 
        /*pess*/      
     //  speed=(disksize+memsize+dirtyrate*resttime)/(resttime);
        /*opt*/
//      speed=(disksize+memsize)/resttime;
       /*pess-80*/
       if((bdrv_get_totallength()<=total_transfer)||(s->precopy==0))
       { 
          s->precopy=0;
       //   speed=maxspeed;
          interval=5000;

  /*        if(dirtyrate>s->last_dirtyrate)
                newdirtyrate=dirtyrate+(dirtyrate-s->last_dirtyrate)*disksize/(real_speed*s->last_interval/1000L);
          else{
                int64_t temprate=(s->last_dirtyrate-dirtyrate)*disksize/(real_speed*s->last_interval/1000L);
                if(temprate>dirtyrate)
                    newdirtyrate=0;
                else
                    newdirtyrate=dirtyrate-temprate;
          } */
          speed=(remaindisksize+memsize+newdirtyrate*resttime)/resttime;
       }
      else {
       //    newdirtyrate=dirtyrate;
   /*       if(dirtyrate>s->last_dirtyrate)
          	newdirtyrate=dirtyrate+(dirtyrate-s->last_dirtyrate)*restdisk/(real_speed*s->last_interval/1000L);
          else{
                int64_t temprate=(s->last_dirtyrate-dirtyrate)*restdisk/(real_speed*s->last_interval/1000L);
                if(temprate>dirtyrate)
                    newdirtyrate=0;
                else
                    newdirtyrate=dirtyrate-temprate;
          } */
          speed=(remaindisksize+memsize+newdirtyrate*resttime)/resttime;          
          if(restdisk<speed*30L) {
             uint64_t interval_64=restdisk*1000/speed; 
             interval=interval_64;
             printf("approaching pre-copy ending: interval %"PRId64"\n",interval_64);
          }
      }

      speed_MB = speed >> 20L; 
      if((real_speed_MB<last_speed_MB)&&(speed_MB>=real_speed_MB)){
          printf("extend speed from %"PRId64" ",speed);
          speed=speed*s->last_speed/real_speed;
          printf(" to %"PRId64" ",speed);
      }
      if(speed>maxspeed)
          speed =maxspeed;
   }
   speed_MB = speed >> 20L;
   printf("new generate %"PRId64" dirtyrate %"PRId64" new dirty rate %"PRId64" remaining disk %"PRId64" ram %"PRId64" \n",newgenerate,dirtyrate,newdirtyrate,remaindisksize,memsize);
     
    printf("real_speed_%"PRId64" last_speed_%"PRId64" speed_%"PRId64"\n",real_speed,s->last_speed,speed);
    printf("real_speed_MB %"PRId64" last_speed_MB %"PRId64" speed_MB %"PRId64"\n",real_speed_MB,last_speed_MB,speed_MB);

   if((s->mig_state.metricopt==1)||(s->mig_state.metricopt==2)){   
   	int64_t total_throughput = get_throughput();
   	int64_t current_throughput=(total_throughput-s->last_throughput)*1000/s->last_interval; //Bytes per second
   	s->last_throughput = total_throughput;

   	int64_t current_throughput_MB = current_throughput >> 20L; 

  	printf("current_throughput_MB %"PRId64"\n",current_throughput_MB);
  
        if(s->mig_state.metricopt==1){
  		if(current_throughput_MB>=s->mig_state.metricvalue)
  		{
     			printf("case 1 ");
                	printf("max speed %"PRId64" s->last_speed+step %"PRId64"\n",speed,s->last_speed+speed_step);
     			speed=maxvalue(speed,s->last_speed+speed_step);  
  		}
  		else
  		{
     			printf("case 2 ");
                        printf("max speed %"PRId64" s->last_speed-step %"PRId64"\n",speed,s->last_speed-speed_step);
     			speed=maxvalue(speed,s->last_speed-speed_step);
  		}
        }
  }
コード例 #26
0
QPointF KisVisualColorSelectorShape::convertKoColorToShapeCoordinate(KoColor c)
{
    ////qDebug() << this  << ">>>>>>>>> convertKoColorToShapeCoordinate()";

    if (c.colorSpace() != m_d->colorSpace) {
        c.convertTo(m_d->colorSpace);
    }
    QVector <float> channelValues (m_d->currentColor.colorSpace()->channelCount());
    channelValues.fill(1.0);
    m_d->colorSpace->normalisedChannelsValue(c.data(), channelValues);
    QVector <float> channelValuesDisplay = channelValues;
    QVector <qreal> maxvalue(c.colorSpace()->channelCount());
    maxvalue.fill(1.0);
    if (m_d->displayRenderer
            && (m_d->colorSpace->colorDepthId() == Float16BitsColorDepthID
                || m_d->colorSpace->colorDepthId() == Float32BitsColorDepthID
                || m_d->colorSpace->colorDepthId() == Float64BitsColorDepthID)
            && m_d->colorSpace->colorModelId() != LABAColorModelID
            && m_d->colorSpace->colorModelId() != CMYKAColorModelID) {
        for (int ch = 0; ch<maxvalue.size(); ch++) {
            KoChannelInfo *channel = m_d->colorSpace->channels()[ch];
            maxvalue[ch] = m_d->displayRenderer->maxVisibleFloatValue(channel);
            channelValues[ch] = channelValues[ch]/(maxvalue[ch]);
            channelValuesDisplay[KoChannelInfo::displayPositionToChannelIndex(ch, m_d->colorSpace->channels())] = channelValues[ch];
        }
    } else {
        for (int i =0; i<channelValues.size();i++) {
            channelValuesDisplay[KoChannelInfo::displayPositionToChannelIndex(i, m_d->colorSpace->channels())] = qBound((float)0.0,channelValues[i], (float)1.0);
        }
    }
    QPointF coordinates(0.0,0.0);
    qreal huedivider = 1.0;
    qreal huedivider2 = 1.0;
    if (m_d->channel1==0) {
        huedivider = 360.0;
    }
    if (m_d->channel2==0) {
        huedivider2 = 360.0;
    }
    if (m_d->model != ColorModel::Channel && c.colorSpace()->colorModelId().id() == "RGBA") {
        if (c.colorSpace()->colorModelId().id() == "RGBA") {
            if (m_d->model == ColorModel::HSV){
                QVector <float> inbetween(3);
                RGBToHSV(channelValuesDisplay[0],channelValuesDisplay[1], channelValuesDisplay[2], &inbetween[0], &inbetween[1], &inbetween[2]);
                inbetween = convertvectorqrealTofloat(getHSX(convertvectorfloatToqreal(inbetween)));
                coordinates.setX(inbetween[m_d->channel1]/huedivider);
                if (m_d->dimension == Dimensions::twodimensional) {
                    coordinates.setY(inbetween[m_d->channel2]/huedivider2);
                }
            } else if (m_d->model == ColorModel::HSL) {
                QVector <float> inbetween(3);
                RGBToHSL(channelValuesDisplay[0],channelValuesDisplay[1], channelValuesDisplay[2], &inbetween[0], &inbetween[1], &inbetween[2]);
                inbetween = convertvectorqrealTofloat(getHSX(convertvectorfloatToqreal(inbetween)));
                coordinates.setX(inbetween[m_d->channel1]/huedivider);
                if (m_d->dimension == Dimensions::twodimensional) {
                    coordinates.setY(inbetween[m_d->channel2]/huedivider2);
                }
            } else if (m_d->model == ColorModel::HSI) {
                QVector <qreal> chan2 = convertvectorfloatToqreal(channelValuesDisplay);
                QVector <qreal> inbetween(3);
                RGBToHSI(channelValuesDisplay[0],channelValuesDisplay[1], channelValuesDisplay[2], &inbetween[0], &inbetween[1], &inbetween[2]);
                inbetween = getHSX(inbetween);
                coordinates.setX(inbetween[m_d->channel1]);
                if (m_d->dimension == Dimensions::twodimensional) {
                    coordinates.setY(inbetween[m_d->channel2]);
                }
            } else if (m_d->model == ColorModel::HSY) {
                QVector <qreal> luma = m_d->colorSpace->lumaCoefficients();
                QVector <qreal> chan2 = convertvectorfloatToqreal(channelValuesDisplay);
                QVector <qreal> inbetween(3);
                RGBToHSY(channelValuesDisplay[0],channelValuesDisplay[1], channelValuesDisplay[2], &inbetween[0], &inbetween[1], &inbetween[2], luma[0], luma[1], luma[2]);
                inbetween = getHSX(inbetween);
                coordinates.setX(inbetween[m_d->channel1]);
                if (m_d->dimension == Dimensions::twodimensional) {
                    coordinates.setY(inbetween[m_d->channel2]);
                }
            }
        }
    } else {
        coordinates.setX(qBound((float)0.0, channelValuesDisplay[m_d->channel1], (float)1.0));
        if (m_d->dimension == Dimensions::twodimensional) {
            coordinates.setY(qBound((float)0.0, channelValuesDisplay[m_d->channel2], (float)1.0));
        }
    }
    return coordinates;
}
コード例 #27
0
ファイル: putcold.c プロジェクト: ARO-user/astropy
/*--------------------------------------------------------------------------*/
int ffpssd(fitsfile *fptr,   /* I - FITS file pointer                       */
           long  group,      /* I - group to write(1 = 1st group)           */
           long  naxis,      /* I - number of data axes in array            */
           long  *naxes,     /* I - size of each FITS axis                  */
           long  *fpixel,    /* I - 1st pixel in each axis to write (1=1st) */
           long  *lpixel,    /* I - last pixel in each axis to write        */
           double *array,    /* I - array to be written                     */
           int  *status)     /* IO - error status                           */
/*
  Write a subsection of pixels to the primary array or image.
  A subsection is defined to be any contiguous rectangular
  array of pixels within the n-dimensional FITS data file.
  Data conversion and scaling will be performed if necessary 
  (e.g, if the datatype of the FITS array is not the same as
  the array being written).
*/
{
    long tablerow;
    LONGLONG fpix[7], dimen[7], astart, pstart;
    LONGLONG off2, off3, off4, off5, off6, off7;
    LONGLONG st10, st20, st30, st40, st50, st60, st70;
    LONGLONG st1, st2, st3, st4, st5, st6, st7;
    long ii, i1, i2, i3, i4, i5, i6, i7, irange[7];

    if (*status > 0)
        return(*status);

    if (fits_is_compressed_image(fptr, status))
    {
        /* this is a compressed image in a binary table */

        fits_write_compressed_img(fptr, TDOUBLE, fpixel, lpixel,
            0,  array, NULL, status);
    
        return(*status);
    }

    if (naxis < 1 || naxis > 7)
      return(*status = BAD_DIMEN);

    tablerow=maxvalue(1,group);

     /* calculate the size and number of loops to perform in each dimension */
    for (ii = 0; ii < 7; ii++)
    {
      fpix[ii]=1;
      irange[ii]=1;
      dimen[ii]=1;
    }

    for (ii = 0; ii < naxis; ii++)
    {    
      fpix[ii]=fpixel[ii];
      irange[ii]=lpixel[ii]-fpixel[ii]+1;
      dimen[ii]=naxes[ii];
    }

    i1=irange[0];

    /* compute the pixel offset between each dimension */
    off2 =     dimen[0];
    off3 = off2 * dimen[1];
    off4 = off3 * dimen[2];
    off5 = off4 * dimen[3];
    off6 = off5 * dimen[4];
    off7 = off6 * dimen[5];

    st10 = fpix[0];
    st20 = (fpix[1] - 1) * off2;
    st30 = (fpix[2] - 1) * off3;
    st40 = (fpix[3] - 1) * off4;
    st50 = (fpix[4] - 1) * off5;
    st60 = (fpix[5] - 1) * off6;
    st70 = (fpix[6] - 1) * off7;

    /* store the initial offset in each dimension */
    st1 = st10;
    st2 = st20;
    st3 = st30;
    st4 = st40;
    st5 = st50;
    st6 = st60;
    st7 = st70;

    astart = 0;

    for (i7 = 0; i7 < irange[6]; i7++)
    {
     for (i6 = 0; i6 < irange[5]; i6++)
     {
      for (i5 = 0; i5 < irange[4]; i5++)
      {
       for (i4 = 0; i4 < irange[3]; i4++)
       {
        for (i3 = 0; i3 < irange[2]; i3++)
        {
         pstart = st1 + st2 + st3 + st4 + st5 + st6 + st7;

         for (i2 = 0; i2 < irange[1]; i2++)
         {
           if (ffpcld(fptr, 2, tablerow, pstart, i1, &array[astart],
              status) > 0)
              return(*status);

           astart += i1;
           pstart += off2;
         }
         st2 = st20;
         st3 = st3+off3;    
        }
        st3 = st30;
        st4 = st4+off4;
       }
       st4 = st40;
       st5 = st5+off5;
      }
      st5 = st50;
      st6 = st6+off6;
     }
     st6 = st60;
     st7 = st7+off7;
    }
    return(*status);
}
コード例 #28
0
ファイル: quantize.c プロジェクト: joezuntz/cmbview
int fits_quantize_float (float fdata[], int nx, float in_null_value,
                  int noise_bits, int idata[], double *bscale,
                  double *bZero, int *iminval, int *imaxval) {

/* arguments:
float fdata[]       i: array of image pixels to be compressed
int nx              i: length of fdata array
float in_null_value i: value used to represent undefined pixels in fdata
int noise_bits      i: quantization level (number of bits)
int idata[]         o: values of fdata after applying bZero and bscale
double bscale       o: scale factor
double bZero        o: zero offset
int iminval         o: minimum quantized value that is returned
int imaxval         o: maximum quantized value that is returned

The function value will be one if the input fdata were copied to idata;
in this case the parameters bscale and bZero can be used to convert back to
nearly the original floating point values:  fdata ~= idata * bscale + bZero.
If the function value is zero, the data were not copied to idata.
*/

	float *diff;		/* difference array */
	int ndiff;		/* size of diff array */
	int intflag;		/* true if data are really integer */
	int i, j, iter;		/* loop indices */
        int anynulls = 0;       /* set if fdata contains any null values */
        int nshift;
        int first_nonnull = 0;
	double mean, stdev;	/* mean and RMS of differences */
	double minval = 0., maxval = 0.;  /* min & max of fdata */
	double delta;		/* bscale, 1 in idata = delta in fdata */
	double zeropt;	        /* bZero */
	double median;		/* median of diff array */
	double temp;

	if (nx <= 1) {
	    *bscale = 1.;
	    *bZero  = 0.;
	    return (0);
	}

        *iminval = INT32_MAX;
        *imaxval = INT32_MIN;

	/* Check to see if data are "floating point integer." */
        /* This also catches the case where all the pixels are null */
	intflag = 1;		/* initial value */
	for (i = 0;  i < nx;  i++) {
            if (fdata[i] == in_null_value) {
                idata[i] = NULL_VALUE;
                anynulls = 1;
            }
	    else if (fdata[i] > INT32_MAX || 
                     fdata[i] < NULL_VALUE + N_RESERVED_VALUES) {
		intflag = 0;	/* not integer */
		break;
	    }
            else {
  	        idata[i] = (int)(fdata[i] + 0.5);
                *iminval = minvalue(idata[i], *iminval);
                *imaxval = maxvalue(idata[i], *imaxval);

	        if (idata[i] != fdata[i]) {
		    intflag = 0;	/* not integer */
		    break;
                }
	    }
	}
	if (intflag) {  /* data are "floating point integer" */
            if (anynulls) {
                /* Shift the range of values so they lie close to NULL_VALUE. */
                /* This will make the compression more efficient.             */
                nshift = *iminval - NULL_VALUE - N_RESERVED_VALUES;
                for (i = 0;  i < nx;  i++) {
                    if (idata[i] != NULL_VALUE) {
                        idata[i] -= nshift;
                    }
                }
                *iminval = *iminval - nshift;
                *imaxval = *imaxval - nshift;
  	        *bscale = 1.;
	        *bZero = (double) nshift;
            }
            else {
                /* there were no null values, so no need to shift the range */
  	        *bscale = 1.;
	        *bZero = 0.;
            }
	    return (1);
	}

        /* data are not "floating point integer"; need to quantize them */

        /* find first non-null pixel, and initialize min and max values */
	for (i = 0;  i < nx;  i++) {
	    if (fdata[i] != in_null_value) {
               minval = fdata[i];
               maxval = fdata[i];
               first_nonnull = i;
               break;
            }
        }

        /* allocate temporary buffer for differences */
	ndiff = nx - first_nonnull - 1;
	if ((diff = malloc (ndiff * sizeof (float))) == NULL) {
            ffpmsg("Out of memory in 'fits_quantize_float'.");  
	    return (0);
	}

        /* calc ABS difference between successive non-null pixels */
        j = first_nonnull;
        ndiff = 0;
	for (i = j + 1 ;  i < nx;  i++) {
            if (fdata[i] != in_null_value) {
 	        diff[ndiff] = fabs (fdata[i] - fdata[j]);
                j = i;
                ndiff++;
                minval = minvalue(minval, fdata[i]);
                maxval = maxvalue(maxval, fdata[i]);
            }
        }

        /* check if there were any null values */
        if (ndiff + 1 == nx)
            anynulls = 0;
        else
            anynulls = 1;

	/* use median of absolute deviations */

	median = xMedian (diff, ndiff);
	stdev = median * MEDIAN_TO_RMS;
	/* substitute sigma-clipping if median is zero */
	if (stdev == 0.0) {

            /* calculate differences between non-null pixels */
            j = first_nonnull;
            ndiff = 0;
	    for (i = j + 1 ;  i < nx;  i++) {
                if (fdata[i] != in_null_value) {
 	            diff[ndiff] = fdata[i] - fdata[j];
                    j = i;
                    ndiff++;
                }
            }

	    FqMean (diff, ndiff, &mean, &stdev);

	    for (iter = 0;  iter < NITER;  iter++) {
		j = 0;
		for (i = 0;  i < ndiff;  i++) {
		    if (fabs (diff[i] - mean) < SIGMA_CLIP * stdev) {
			if (j < i)
			    diff[j] = diff[i];
			j++;
		    }
		}
		if (j == ndiff)
		    break;
		ndiff = j;
		FqMean (diff, ndiff, &mean, &stdev);
	    }
	}
	free (diff);

	delta = stdev / pow (2., (double)noise_bits);
	if (delta == 0. && ndiff > 0)
	    return (0);	/* Zero variance in differences!  Don't quantize. */

        /* check that the range of quantized levels is not > range of int */
	if ((maxval - minval) / delta > 2. * 2147483647. - N_RESERVED_VALUES )
	    return (0);			/* don't quantize */

        if (!anynulls) {   /* don't have to check for nulls */
            /* return all positive values, if possible since some */
            /* compression algorithms either only work for positive integers, */
            /* or are more efficient.  */
            if ((maxval - minval) / delta < 2147483647. - N_RESERVED_VALUES )
            {
                zeropt = minval;
            }
            else
            {
                /* center the quantized levels around zero */
                zeropt = (minval + maxval) / 2.;
            }

       	    for (i = 0;  i < nx;  i++) {
	        temp = (fdata[i] - zeropt) / delta;
	        idata[i] = NINT (temp);
            }
        }
        else {
            /* data contains null values; shift the range to be */
            /* close to the value used to represent null values */
            zeropt = minval - delta * (NULL_VALUE + N_RESERVED_VALUES);
	    for (i = 0;  i < nx;  i++) {
                if (fdata[i] != in_null_value) {
	            temp = (fdata[i] - zeropt) / delta;
	            idata[i] = NINT (temp);
                }
                else
                    idata[i] = NULL_VALUE;
            }
	}

        /* calc min and max values */
        temp = (minval - zeropt) / delta;
        *iminval =  NINT (temp);
        temp = (maxval - zeropt) / delta;
        *imaxval =  NINT (temp);

	*bscale = delta;
	*bZero = zeropt;

	return (1);			/* yes, data have been quantized */
}
コード例 #29
0
/*--------------------------------------------------------------------------*/
int ffitab(fitsfile *fptr,  /* I - FITS file pointer                        */
           LONGLONG naxis1,     /* I - width of row in the table                */
           LONGLONG naxis2,     /* I - number of rows in the table              */
           int tfields,     /* I - number of columns in the table           */
           char **ttype,    /* I - name of each column                      */
           long *tbcol,     /* I - byte offset in row to each column        */
           char **tform,    /* I - value of TFORMn keyword for each column  */
           char **tunit,    /* I - value of TUNITn keyword for each column  */
           const char *extnmx,   /* I - value of EXTNAME keyword, if any         */
           int *status)     /* IO - error status                            */
/*
  insert an ASCII table extension following the current HDU 
*/
{
    int nexthdu, maxhdu, ii, nunit, nhead, ncols, gotmem = 0;
    long nblocks, rowlen;
    LONGLONG datasize, newstart;
    char errmsg[81], extnm[FLEN_VALUE];

    if (*status > 0)
        return(*status);

    extnm[0] = '\0';
    if (extnmx)
      strncat(extnm, extnmx, FLEN_VALUE-1);

    if (fptr->HDUposition != (fptr->Fptr)->curhdu)
        ffmahd(fptr, (fptr->HDUposition) + 1, NULL, status);

    maxhdu = (fptr->Fptr)->maxhdu;
    /* if the current header is completely empty ...  */
    if (( (fptr->Fptr)->headend == (fptr->Fptr)->headstart[(fptr->Fptr)->curhdu] )
        /* or, if we are at the end of the file, ... */
    ||  ( (((fptr->Fptr)->curhdu) == maxhdu ) &&
       ((fptr->Fptr)->headstart[maxhdu + 1] >= (fptr->Fptr)->logfilesize ) ) )
    {
        /* then simply append new image extension */
        ffcrtb(fptr, ASCII_TBL, naxis2, tfields, ttype, tform, tunit,
               extnm, status);
        return(*status);
    }

    if (naxis1 < 0)
        return(*status = NEG_WIDTH);
    else if (naxis2 < 0)
        return(*status = NEG_ROWS);
    else if (tfields < 0 || tfields > 999)
    {
        sprintf(errmsg,
        "Illegal value for TFIELDS keyword: %d", tfields);
        ffpmsg(errmsg);
        return(*status = BAD_TFIELDS);
    }

    /* count number of optional TUNIT keywords to be written */
    nunit = 0;
    for (ii = 0; ii < tfields; ii++)
    {
        if (tunit && *tunit && *tunit[ii])
            nunit++;
    }

    if (extnm && *extnm)
         nunit++;     /* add one for the EXTNAME keyword */

    rowlen = (long) naxis1;

    if (!tbcol || !tbcol[0] || (!naxis1 && tfields)) /* spacing not defined? */
    {
      /* allocate mem for tbcol; malloc may have problems allocating small */
      /* arrays, so allocate at least 20 bytes */

      ncols = maxvalue(5, tfields);
      tbcol = (long *) calloc(ncols, sizeof(long));

      if (tbcol)
      {
        gotmem = 1;

        /* calculate width of a row and starting position of each column. */
        /* Each column will be separated by 1 blank space */
        ffgabc(tfields, tform, 1, &rowlen, tbcol, status);
      }
    }

    nhead = (9 + (3 * tfields) + nunit + 35) / 36;  /* no. of header blocks */
    datasize = (LONGLONG)rowlen * naxis2;          /* size of table in bytes */
    nblocks = (long) (((datasize + 2879) / 2880) + nhead);  /* size of HDU */

    if ((fptr->Fptr)->writemode == READWRITE) /* must have write access */
    {   /* close the CHDU */
        ffrdef(fptr, status);  /* scan header to redefine structure */
        ffpdfl(fptr, status);  /* insure correct data file values */
    }
    else
        return(*status = READONLY_FILE);

    nexthdu = ((fptr->Fptr)->curhdu) + 1; /* number of the next (new) hdu */
    newstart = (fptr->Fptr)->headstart[nexthdu]; /* save starting addr of HDU */

    (fptr->Fptr)->hdutype = ASCII_TBL;  /* so that correct fill value is used */
    /* ffiblk also increments headstart for all following HDUs */
    if (ffiblk(fptr, nblocks, 1, status) > 0)  /* insert the blocks */
    {
        if (gotmem)
            free(tbcol); 
        return(*status);
    }

    ((fptr->Fptr)->maxhdu)++;      /* increment known number of HDUs in the file */
    for (ii = (fptr->Fptr)->maxhdu; ii > (fptr->Fptr)->curhdu; ii--)
        (fptr->Fptr)->headstart[ii + 1] = (fptr->Fptr)->headstart[ii]; /* incre start addr */

    (fptr->Fptr)->headstart[nexthdu] = newstart; /* set starting addr of HDU */

    /* set default parameters for this new empty HDU */
    (fptr->Fptr)->curhdu = nexthdu;   /* we are now located at the next HDU */
    fptr->HDUposition = nexthdu;      /* we are now located at the next HDU */
    (fptr->Fptr)->nextkey = (fptr->Fptr)->headstart[nexthdu];  
    (fptr->Fptr)->headend = (fptr->Fptr)->headstart[nexthdu];
    (fptr->Fptr)->datastart = ((fptr->Fptr)->headstart[nexthdu]) + (nhead * 2880);
    (fptr->Fptr)->hdutype = ASCII_TBL;  /* might need to be reset... */

    /* write the required header keywords */

    ffphtb(fptr, rowlen, naxis2, tfields, ttype, tbcol, tform, tunit,
           extnm, status);

    if (gotmem)
        free(tbcol); 

    /* redefine internal structure for this HDU */

    ffrdef(fptr, status);
    return(*status);
}
コード例 #30
0
KoColor KisVisualColorSelectorShape::convertShapeCoordinateToKoColor(QPointF coordinates, bool cursor)
{
    //qDebug() << this  << ">>>>>>>>> convertShapeCoordinateToKoColor()" << coordinates;

    KoColor c = m_d->currentColor;
    QVector <float> channelValues (c.colorSpace()->channelCount());
    channelValues.fill(1.0);
    c.colorSpace()->normalisedChannelsValue(c.data(), channelValues);
    QVector <float> channelValuesDisplay = channelValues;
    QVector <qreal> maxvalue(c.colorSpace()->channelCount());
    maxvalue.fill(1.0);

    if (m_d->displayRenderer
            && (m_d->colorSpace->colorDepthId() == Float16BitsColorDepthID
                || m_d->colorSpace->colorDepthId() == Float32BitsColorDepthID
                || m_d->colorSpace->colorDepthId() == Float64BitsColorDepthID)
            && m_d->colorSpace->colorModelId() != LABAColorModelID
            && m_d->colorSpace->colorModelId() != CMYKAColorModelID) {

        for (int ch = 0; ch < maxvalue.size(); ch++) {
            KoChannelInfo *channel = m_d->colorSpace->channels()[ch];
            maxvalue[ch] = m_d->displayRenderer->maxVisibleFloatValue(channel);
            channelValues[ch] = channelValues[ch]/(maxvalue[ch]);
            channelValuesDisplay[KoChannelInfo::displayPositionToChannelIndex(ch, m_d->colorSpace->channels())] = channelValues[ch];
        }
    }
    else {
        for (int i =0; i < channelValues.size();i++) {
            channelValuesDisplay[KoChannelInfo::displayPositionToChannelIndex(i, m_d->colorSpace->channels())] = qBound((float)0.0,channelValues[i], (float)1.0);
        }
    }

    qreal huedivider = 1.0;
    qreal huedivider2 = 1.0;

    if (m_d->channel1 == 0) {
        huedivider = 360.0;
    }

    if (m_d->channel2 == 0) {
        huedivider2 = 360.0;
    }

    if (m_d->model != ColorModel::Channel && c.colorSpace()->colorModelId().id() == "RGBA") {

        if (m_d->model == ColorModel::HSV) {
            /*
             * RGBToHSV has a undefined hue possibility. This means that hue will be -1.
             * This can be annoying for dealing with a selector, but I understand it is being
             * used for the KoColorSelector... For now implement a qMax here.
             */
            QVector <float> inbetween(3);
            RGBToHSV(channelValuesDisplay[0],channelValuesDisplay[1], channelValuesDisplay[2], &inbetween[0], &inbetween[1], &inbetween[2]);
            inbetween = convertvectorqrealTofloat(getHSX(convertvectorfloatToqreal(inbetween)));
            inbetween[m_d->channel1] = coordinates.x()*huedivider;
            if (m_d->dimension == Dimensions::twodimensional) {
                inbetween[m_d->channel2] = coordinates.y()*huedivider2;
            }
            if (cursor) {
                setHSX(convertvectorfloatToqreal(inbetween));
                Q_EMIT sigHSXchange();
            }
            HSVToRGB(qMax(inbetween[0],(float)0.0), inbetween[1], inbetween[2], &channelValuesDisplay[0], &channelValuesDisplay[1], &channelValuesDisplay[2]);
        }
        else if (m_d->model == ColorModel::HSL) {
            /*
             * HSLToRGB can give negative values on the grey. I fixed the fromNormalisedChannel function to clamp,
             * but you might want to manually clamp for floating point values.
             */
            QVector <float> inbetween(3);
            RGBToHSL(channelValuesDisplay[0],channelValuesDisplay[1], channelValuesDisplay[2], &inbetween[0], &inbetween[1], &inbetween[2]);
            inbetween = convertvectorqrealTofloat(getHSX(convertvectorfloatToqreal(inbetween)));
            inbetween[m_d->channel1] = fmod(coordinates.x()*huedivider, 360.0);
            if (m_d->dimension == Dimensions::twodimensional) {
                inbetween[m_d->channel2] = coordinates.y()*huedivider2;
            }
            if (cursor) {
                setHSX(convertvectorfloatToqreal(inbetween));
                Q_EMIT sigHSXchange();
            }
            HSLToRGB(qMax(inbetween[0], (float)0.0), inbetween[1], inbetween[2], &channelValuesDisplay[0], &channelValuesDisplay[1], &channelValuesDisplay[2]);
        }
        else if (m_d->model == ColorModel::HSI) {
            /*
             * HSI is a modified HSY function.
             */
            QVector <qreal> chan2 = convertvectorfloatToqreal(channelValuesDisplay);
            QVector <qreal> inbetween(3);
            RGBToHSI(chan2[0],chan2[1], chan2[2], &inbetween[0], &inbetween[1], &inbetween[2]);
            inbetween = getHSX(inbetween);
            inbetween[m_d->channel1] = coordinates.x();
            if (m_d->dimension == Dimensions::twodimensional) {
                inbetween[m_d->channel2] = coordinates.y();
            }
            if (cursor) {
                setHSX(inbetween);
                Q_EMIT sigHSXchange();
            }
            HSIToRGB(inbetween[0], inbetween[1], inbetween[2],&chan2[0],&chan2[1], &chan2[2]);
            channelValuesDisplay = convertvectorqrealTofloat(chan2);
        }
        else /*if (m_d->model == ColorModel::HSY)*/ {
            /*
             * HSY is pretty slow to render due being a pretty over-the-top function.
             * Might be worth investigating whether HCY can be used instead, but I have had
             * some weird results with that.
             */
            QVector <qreal> luma= m_d->colorSpace->lumaCoefficients();
            QVector <qreal> chan2 = convertvectorfloatToqreal(channelValuesDisplay);
            QVector <qreal> inbetween(3);
            RGBToHSY(chan2[0],chan2[1], chan2[2], &inbetween[0], &inbetween[1], &inbetween[2],
                    luma[0], luma[1], luma[2]);
            inbetween = getHSX(inbetween);
            inbetween[m_d->channel1] = coordinates.x();
            if (m_d->dimension == Dimensions::twodimensional) {
                inbetween[m_d->channel2] = coordinates.y();
            }
            if (cursor) {
                setHSX(inbetween);
                Q_EMIT sigHSXchange();
            }
            HSYToRGB(inbetween[0], inbetween[1], inbetween[2],&chan2[0],&chan2[1], &chan2[2],
                    luma[0], luma[1], luma[2]);
            channelValuesDisplay = convertvectorqrealTofloat(chan2);
        }

    }
    else {
        channelValuesDisplay[m_d->channel1] = coordinates.x();
        if (m_d->dimension == Dimensions::twodimensional) {
            channelValuesDisplay[m_d->channel2] = coordinates.y();
        }
    }

    for (int i=0; i<channelValues.size();i++) {
        channelValues[i] = channelValuesDisplay[KoChannelInfo::displayPositionToChannelIndex(i, m_d->colorSpace->channels())]*(maxvalue[i]);
    }

    c.colorSpace()->fromNormalisedChannelsValue(c.data(), channelValues);

    return c;
}