Esempio n. 1
0
void print_item(string tag)
{
    string type, stag;
    int *dims;

    type = get_type(instr, tag);
    if (streq(type, SetType)) {
	get_set(instr, tag);
	print_set(tag);
	while ((stag = next_item_tag(instr)) != NULL) {
	    print_item(stag);
	    free(stag);
	}
	get_tes(instr, tag);
	print_tes(tag);
    } else {
	dims = get_dimensions(instr, tag);
	print_head(tag, type, dims);
	print_data(tag, type, dims);
	endline();
	if (dims != NULL)
	    free(dims);
    }
    free(type);
}
Esempio n. 2
0
int Cuser_paradise::insert(userid_t userid, bool is_vip)
{
	char pattire_list[200];
    char pattire_list_mysql[401];
    memset(pattire_list,0,sizeof(pattire_list) );

	paradise_attirelist *p_attire=(paradise_attirelist*)pattire_list;
	p_attire->count=1;
	p_attire->item[0].attireid = 1353000;
	set_mysql_string(pattire_list_mysql ,(char *)pattire_list, 20);

	uint32_t dimension_1 = 0, dimension_2 = 0;
	uint32_t ret = get_dimensions(1, is_vip, dimension_1, dimension_2);
	if(ret != SUCC){
		return ret;
	}
	uint32_t limit_count = plant_angel[dimension_1][dimension_2];
	uint32_t nimbus_count = 1920;
	sprintf(this->sqlstr, "insert into %s values(%u, %u, 0, %u, 1 ,300, '%s', \
		0x00000000,0,0,0,0,0,0,0,0)",
		this->get_table_name(userid),
		userid,
		nimbus_count,
		limit_count,
		pattire_list_mysql
		);
		
    STD_SET_RETURN_EX(this->sqlstr, USER_ID_EXISTED_ERR);
}
Esempio n. 3
0
ErrorCode ReadNC::read_header()
{
  dbgOut.tprint(1, "Reading header...\n");

  // Get the global attributes
  int numgatts;
  int success;
  success = NCFUNC(inq_natts )(fileId, &numgatts);
  if (success)
    MB_SET_ERR(MB_FAILURE, "Couldn't get number of global attributes");

  // Read attributes into globalAtts
  ErrorCode result = get_attributes(NC_GLOBAL, numgatts, globalAtts);MB_CHK_SET_ERR(result, "Trouble getting global attributes");
  dbgOut.tprintf(1, "Read %u attributes\n", (unsigned int) globalAtts.size());

  // Read in dimensions into dimNames and dimLens
  result = get_dimensions(fileId, dimNames, dimLens);MB_CHK_SET_ERR(result, "Trouble getting dimensions");
  dbgOut.tprintf(1, "Read %u dimensions\n", (unsigned int) dimNames.size());

  // Read in variables into varInfo
  result = get_variables();MB_CHK_SET_ERR(result, "Trouble getting variables");
  dbgOut.tprintf(1, "Read %u variables\n", (unsigned int) varInfo.size());

  return MB_SUCCESS;
}
Esempio n. 4
0
/*
** Terminal redimension event
*/
void			sigwinch()
{
  struct winsize	w;
  if (ioctl(0, TIOCGWINSZ, &w) >= 0)
    get_dimensions(w.ws_row, w.ws_col);
  else
    my_printf("ERROR SIGWINCH\n");
}
Esempio n. 5
0
/* 
* Creates the new bit2 with given width and height and size 
*/
extern T Bit2_new(int width, int height)
{
        assert ((height && width >= 0));
        int dimensions = get_dimensions(width , height);
        Bit2_T bit2 = malloc(sizeof(struct Bit2_T));
        bit2->bit_vector = Bit_new(dimensions);
        bit2->width = width;
        bit2->height = height;
        bit2->dimensions = dimensions;
        return bit2;
}
Esempio n. 6
0
int VTrack::update_translation(int cursor_x, int cursor_y, int shift_down)
{
	int result = 0;
	float view_start, view_units, zoom_units;
	get_dimensions(view_start, view_units, zoom_units);

	for(Edit* current = edits->first; current && !result; current = NEXT)
	{
		result = ((VEdit*)current)->update_translation(cursor_x, cursor_y, shift_down, view_start, zoom_units);
	}
	return result;
}
Esempio n. 7
0
/*
** Displays a line in the term
*/
void			display_line(t_caps_str *vars)
{
  struct winsize	w;
  int			off;

  w = get_dimensions(-1, -1);
  tputs(vars->cr, 1, my_outc);
  tputs(vars->dl, 1, my_outc);
  off = my_printf("%s%s", PROMPT, command_line(NULL)) - my_strlen(PROMPT);
  while (off-- - cursor(-2) > 0)
    tputs("\b", 1, my_outc);
}
Esempio n. 8
0
int VTrack::select_translation(int cursor_x, int cursor_y)
{
// cursor position is relative to time
	int result = 0;
	float view_start, view_units, zoom_units;
	get_dimensions(view_start, view_units, zoom_units);

	if(cursor_y > pixel && cursor_y < pixel + mwindow->zoom_track)
	{
		for(Edit* current = edits->first; current && !result; current = NEXT)
		{
			result = ((VEdit*)current)->select_translation(cursor_x, cursor_y, view_start, zoom_units);
		}
	}
	return result;
}
Esempio n. 9
0
 void apply(const View& view) {
     jpeg_start_decompress(&_cinfo);    // lbourdev: Can this return an error? You need to check and throw. Check all other library methods that can return an error state...
     io_error_if(_cinfo.data_precision!=8,"jpeg_reader::apply(): this image file is not supported");
     io_error_if(_cinfo.out_color_space!=jpeg_read_support_private<typename channel_type<View>::type,
                                                                   typename color_space_type<View>::type>::color_type,
                 "jpeg_reader::apply(): input view type does not match the image file");
     io_error_if(view.dimensions() != get_dimensions(), "jpeg_reader::apply(): input view dimensions do not match the image file");
     std::vector<pixel<bits8,layout<typename color_space_type<View>::type> > > row(view.width());
     JSAMPLE* row_address=(JSAMPLE*)&row.front();
     for(int y=0;y<view.height();++y) {
         io_error_if(jpeg_read_scanlines(&_cinfo,(JSAMPARRAY)&row_address,1)!=1,
                     "jpeg_reader::apply(): fail to read JPEG file");
         std::copy(row.begin(),row.end(),view.row_begin(y));
     }
     jpeg_finish_decompress(&_cinfo);
 }
Esempio n. 10
0
Math::range_t TSet::get_y_range() const
{
    Math::range_t r(std::numeric_limits<double>::max(),
                    std::numeric_limits<double>::min());

    unsigned int d = get_dimensions();
    unsigned int x[d];
    unsigned int c[d];

    for (unsigned int i = 0; i < d; i++)
    {
        if (get_count(i) == 0)
            throw Error("data set contains no data");

        x[i] = 0;
        c[i] = get_count(i) - 1;
    }

    while (1)
    {
        double y = get_y_value(x);

        if (y < r.first)
            r.first = y;

        if (y > r.second)
            r.second = y;

        for (unsigned int i = 0; ; )
        {
            if (x[i] < c[i])
            {
                x[i]++;
                break;
            }
            else
            {
                x[i++] = 0;

                if (i == d)
                    return r;
            }
        }
    }
}
Esempio n. 11
0
Horizon::Implementation::Implementation (const BlockModel& al)
  : dry_bulk_density (al.number ("dry_bulk_density", -42.42e42)),
    SOM_C_per_N (al.number_sequence ("SOM_C_per_N")),
    C_per_N (al.number ("C_per_N", -42.42e42)),
    SOM_fractions (al.check ("SOM_fractions") 
                   ? al.number_sequence ("SOM_fractions")
                   : std::vector<double> ()),
    turnover_factor (al.number ("turnover_factor")),
    anisotropy (al.number ("anisotropy")),
    attributes (get_attributes (al.submodel_sequence ("attributes"))),
    dimensions (get_dimensions (al.submodel_sequence ("attributes"))),
    nitrification (Librarian::build_item<Nitrification> (al, "Nitrification")),
    secondary (Librarian::build_item<Secondary> (al, "secondary_domain")),
    r_pore_min (al.number ("r_pore_min")),
    primary_sorption_fraction (NAN),
    hor_heat (al.submodel ("HorHeat")),
    CEC (al.number ("CEC", -42.42e42))
{ }
Esempio n. 12
0
int main() {
    // Model, Domain and Boundary
    const auto flow = std::make_unique<Flow>("Couette3D");
    const auto lbmodel = flow->get_lbmodel();
    const auto domain = flow->get_domain();
    const auto boundary = flow->get_boundary();

    // Define problem and its data
    const auto problem = std::make_unique<PLBPD>(lbmodel, domain, boundary);
    auto simdata =
        SimData(domain->get_dimensions(), lbmodel->get_num_directions());

    // Solve problem
    problem->initialize(simdata);
    simdata.write_state("init_state.h5");
    problem->march_in_time(flow->get_num_timesteps(), simdata);
    simdata.write_state("final_state.h5");
    problem->print_times();
}
Esempio n. 13
0
 void apply(const View& view) {
     jpeg_start_decompress(&_cinfo);    // lbourdev: Can this return an error? You need to check and throw. Check all other library methods that can return an error state...
     io_error_if(_cinfo.data_precision!=8,"jpeg_reader_color_covert::apply(): this image file is not supported");
     io_error_if(view.dimensions() != get_dimensions(), "jpeg_reader_color_covert::apply(): input view dimensions don't match the image file");
     switch (_cinfo.out_color_space) {
     case JCS_GRAYSCALE: {
         std::vector<gray8_pixel_t> row(view.width());
         JSAMPLE* row_address=(JSAMPLE*)&row.front();
         for(int y=0;y<view.height();++y) {
             io_error_if(jpeg_read_scanlines(&_cinfo,(JSAMPARRAY)&row_address,1)!=1,
                         "jpeg_reader_color_covert::apply(): fail to read JPEG file");
             std::transform(row.begin(),row.end(),view.row_begin(y),color_convert_deref_fn<gray8_ref_t, typename View::value_type,CC>(_cc));
         }
         break;
     }
     case JCS_RGB: {
         std::vector<rgb8_pixel_t> row(view.width());
         JSAMPLE* row_address=(JSAMPLE*)&row.front();
         for(int y=0;y<view.height();++y) {
             io_error_if(jpeg_read_scanlines(&_cinfo,(JSAMPARRAY)&row_address,1)!=1,
                         "jpeg_reader_color_covert::apply(): fail to read JPEG file");
             std::transform(row.begin(),row.end(),view.row_begin(y),color_convert_deref_fn<rgb8_ref_t, typename View::value_type,CC>(_cc));
         }
         break;
     }
     case JCS_CMYK: {
         std::vector<cmyk8_pixel_t> row(view.width());
         JSAMPLE* row_address=(JSAMPLE*)&row.front();
         for(int y=0;y<view.height();++y) {
             io_error_if(jpeg_read_scanlines(&_cinfo,(JSAMPARRAY)&row_address,1)!=1,
                         "jpeg_reader_color_covert::apply(): fail to read JPEG file");
             std::transform(row.begin(),row.end(),view.row_begin(y),color_convert_deref_fn<cmyk8_ref_t, typename View::value_type,CC>(_cc));
         }
         break;
     }
     default:
         io_error("jpeg_reader_color_covert::apply(): unknown color type");
     }
     jpeg_finish_decompress(&_cinfo);
 }    
Esempio n. 14
0
volume_data_type
Volume_loader_raw::load_volume(std::string filepath)
{
  std::ifstream volume_file;
  volume_file.open(filepath, std::ios::in | std::ios::binary);

  volume_data_type data;

  if (volume_file.is_open()) {
    glm::ivec3 vol_dim = get_dimensions(filepath);
    unsigned channels = get_channel_count(filepath);
    unsigned byte_per_channel = get_bit_per_channel(filepath) / 8;


    size_t data_size = vol_dim.x
                      * vol_dim.y
                      * vol_dim.z
                      * channels
                      * byte_per_channel;

    
    data.resize(data_size);

    volume_file.seekg(0, std::ios::beg);
    volume_file.read((char*)&data.front(), data_size);
    volume_file.close();

    //std::cout << "File " << filepath << " successfully loaded" << std::endl;

    return data;
  } else {
    std::cerr << "File " << filepath << " doesnt exist! Check Filepath!" << std::endl;
    assert(0);
    return data;
  }

  //never reached
  assert(0);
  return data;
}
Esempio n. 15
0
void
put_fill(struct driz_param_t* p, const float fill_value) {
  integer_t i, j, osize[2];

  assert(p);
  get_dimensions(p->output_data, osize);
  for (j = 0; j < osize[1]; ++j) {
    for (i = 0; i < osize[0]; ++i) {
      if (oob_pixel(p->output_counts, i, j)) {
        driz_error_format_message(p->error, "OOB in output_counts[%d,%d]", i, j);
        return;

      } else if (oob_pixel(p->output_data, i, j)) {
        driz_error_format_message(p->error, "OOB in output_data[%d,%d]", i, j);
        return;

      } else if (get_pixel(p->output_counts, i, j) == 0.0) {
        set_pixel(p->output_data, i, j, fill_value);
      }
    }
  }
}
Esempio n. 16
0
template<class T> SGNDArray<T> SGNDArray<T>::clone() const
{
	SGNDArray<T> array_clone(get_dimensions());
	sg_memcpy(array_clone.array, array, sizeof(T)*len_array);
	return array_clone;
}
int MatlabBufferGadget::process(GadgetContainerMessage<IsmrmrdReconData>* m1)
{
	// Initialize a string for matlab commands
	std::string cmd;

	auto recon_data = m1->getObjectPtr();
	mwSize nencoding_spaces = recon_data->rbit_.size();

	const char* fieldnames[2] = {"data","reference"};
	auto reconArray = mxCreateStructArray(1,&nencoding_spaces,2,fieldnames);
	//auto reconArray = mxCreateCellArray(1,&nencoding_spaces);

	for (int i = 0; i <  recon_data->rbit_.size(); i++){
		auto mxrecon = BufferToMatlabStruct(&recon_data->rbit_[i].data_);
		mxSetField(reconArray,i,"data",mxrecon);
		if (recon_data->rbit_[i].ref_){
			auto mxref = BufferToMatlabStruct(recon_data->rbit_[i].ref_.get_ptr());
			mxSetField(reconArray,i,"reference",mxref);
		}

	}
	engPutVariable(engine_, "recon_data", reconArray);

	cmd = "[imageQ,bufferQ] = matgadget.run_process(recon_data); matgadget.emptyQ(); whos()";
	send_matlab_command(cmd);

	// Get the size of the gadget's queue

	mxArray *imageQ = engGetVariable(engine_, "imageQ");
	if (imageQ == NULL) {
		GERROR("Failed to get the imageQ from matgadget\n");
		return GADGET_FAIL;
	}

	size_t qlen = mxGetNumberOfElements(imageQ);
	GDEBUG("Image Queue size: %d \n", qlen);

	const mwSize* dims = mxGetDimensions(imageQ);
	mwSize ndims = mxGetNumberOfDimensions(imageQ);



	//Read all Image bytes
	for (mwIndex idx = 0; idx < qlen; idx++) {
		mxArray *res_hdr  = mxGetField(imageQ, idx, "bytes");
		mxArray *res_data = mxGetField(imageQ, idx, "image");

		GadgetContainerMessage<ISMRMRD::ImageHeader>* m3 =
				new GadgetContainerMessage<ISMRMRD::ImageHeader>();
		ISMRMRD::ImageHeader *hdr_new = m3->getObjectPtr();
		memcpy(hdr_new, mxGetData(res_hdr), sizeof(ISMRMRD::ImageHeader));

		auto image= MatlabToHoNDArray<std::complex<float>>(res_data);
		auto m4 = new GadgetContainerMessage< hoNDArray< std::complex<float> > >(image);
		auto dims = *image->get_dimensions();

		delete image;
		m3->cont(m4);
		if (this->next()->putq(m3) < 0) {
			GDEBUG("Failed to put Image message on queue\n");
			return GADGET_FAIL;
		}

	}
	//Match engGetVariable with mxDestroy___s


	mxArray* bufferQ = engGetVariable(engine_,"bufferQ");

	qlen = mxGetNumberOfElements(bufferQ);
	GDEBUG("Buffer Queue size: %d \n", qlen);

	for (mwIndex idx = 0; idx <qlen; idx++){

		IsmrmrdReconData output_data;
		IsmrmrdReconBit bit;
		bit.data_ = MatlabStructToBuffer(mxGetField(bufferQ,idx,"data"));

		auto ref = mxGetField(bufferQ,idx,"reference");
		if (ref){
			GDEBUG("Adding reference");
			bit.ref_ = MatlabStructToBuffer(ref);
		}
		output_data.rbit_.push_back(bit);
		auto m3 = new GadgetContainerMessage<IsmrmrdReconData>(output_data.rbit_);
		if (this->next()->putq(m3) < 0){
			GDEBUG("Failed to put Buffer message on queue\n");
			return GADGET_FAIL;
		}

	}





	mxDestroyArray(bufferQ);
	mxDestroyArray(imageQ);
	//mxDestroyArray(reconArray); //We're not supposed to delete this?

	// We are finished with the incoming messages m1 and m2
	m1->release();

	return GADGET_OK;
}
Esempio n. 18
0
 void read_image(Image& im) {
     im.recreate(get_dimensions());
     apply(view(im));
 }
Esempio n. 19
0
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
void ExecThread::run()
{
	LOG_MSG("Invoking DLL...");
	int res=0;
    int hour;
	const char *infile, *outfile;
    char version[12];
	QString infile_path, outfile_path;
	int len_infile, len_outfile;
    int len_version;
    QString dll_version;
    bool cused[32];

	infile_path = inputFile;
	QString casename = QFileInfo(inputFile).baseName();
	len_infile = infile_path.length();
	std::string std_infile = infile_path.toStdString();
	infile = std_infile.c_str();
	outfile_path = casename.append(".res");
	len_outfile = outfile_path.length();
	std::string std_outfile = outfile_path.toStdString();
    outfile = std_outfile.c_str();

    get_dll_build_version(version,&len_version);
    dll_version = version;
    // We can compare the version of the actual DLL that is linked
    // with the GUI's idea of the DLL version (i.e. the version of the library the GUI was built with)
    if (dll_version != Global::DLL_build_version) {
        LOG_QMSG("Bad DLL version: " + dll_version);
        emit(badDLL(dll_version));
        return;
    }
	paused = false;
    LOG_MSG("call execute");
    execute(&ncpu,const_cast<char *>(infile),&len_infile,const_cast<char *>(outfile),&len_outfile,&res);
    LOG_MSG("did execute");
    if (res) {
        terminate_run(&res);
        return;
    }

//    char *b;
//    get_string(&b);
//    LOG_MSG(b);

    get_dimensions(&nsteps, &Global::DELTA_T, &Global::NT_DISPLAY, &Global::MAX_CHEMO, &Global::N_EXTRA, cused);
//    summary_interval = int(3600./Global::DELTA_T);
    summary_interval = Global::NT_DISPLAY;
    sprintf(msg,"exthread: nsteps: %d summary_interval: %d",nsteps,summary_interval);
    LOG_MSG(msg);
    Global::conc_nc_ic = 0;
    Global::conc_nc_ex = 0;
    hour = 0;

    int ndisplay = nsteps/Global::NT_DISPLAY + 1;
    mutex1.lock();
    emit setupC(ndisplay);
    mutex1.unlock();
    LOG_MSG("did setupC");

//    LOG_MSG("call tester");
//    tester();
//    LOG_MSG("did tester");
//    emit run_tester();

    get_summary(Global::summaryData, &Global::i_hypoxia_cutoff, &Global::i_growth_cutoff);
//    getProfiles();
    emit summary(hour);		// Emit signal to initialise summary plots

    for (int i=1; i <= nsteps+1; i++) {
        sleep(10);
        bool updated = false;
		if (paused && !updated) {
//			snapshot();
//            sprintf(msg,"got snapshot: i: %d",i);
//            LOG_MSG(msg);
            updated = true;
		}
        while(paused || Global::leftb) {
            sleep(100);
		}
        if (stopped) {
            LOG_MSG("stopped");
            res = -1;
            break;
        }

        mutex1.lock();
//        LOG_MSG("call simulate_step");
        simulate_step(&res);
//        LOG_MSG("did simulate_step");
        mutex1.unlock();
        if (res != 0) {
            LOG_MSG("simulate_step: res != 0");
            break;
        }

        if (i%summary_interval == 0) {
            mutex1.lock();
            get_summary(Global::summaryData, &Global::i_hypoxia_cutoff, &Global::i_growth_cutoff);
//            get_volprob(&Global::vol_nv, &Global::vol_v0, &Global::vol_dv, Global::volProb);
//            get_oxyprob(&Global::oxy_nv, &Global::oxy_v0, &Global::oxy_dv, Global::oxyProb);
//            get_distdata(&Global::dist_nv, Global::distParams, Global::distData);
            get_concdata(&Global::conc_nvars, &Global::conc_nc_ex, &Global::conc_dx_ex, Global::concData);
//            get_ic_concdata(&Global::conc_nvars, &Global::conc_nc_ic, &Global::conc_dx_ic, Global::IC_concData);
            if (Global::showingFACS || Global::recordingFACS) {
                getFACS();
            }
            mutex1.unlock();
            if (Global::showingFACS || Global::recordingFACS) {
                emit facs_update();
                emit histo_update();
            }
//            hour++;
            hour = int(hour + (Global::DELTA_T*Global::NT_DISPLAY)/3600.);
            mutex1.lock();
            emit summary(hour);		// Emit signal to update summary plots, at hourly intervals
        }

        if (stopped) {
            res = -1;
            break;
        }
//        if (i%Global::nt_vtk == 0) {
//            if (Global::showingVTK || Global::recordingVTK) {
//				snapshot();
//                Global::istep = i;
//                sleep(10);
//			}
//		}
        if (stopped) {
            res = -1;
            break;
        }
    }
    LOG_MSG("ExecThread::run: stopped or completed");
//    snapshot();
//    LOG_MSG("got snapshot:");
    sleep(100);

    if (Global::simulate_colony) {
        make_colony_distribution(&Global::colony_days, Global::dist, &Global::ddist, &Global::ndist);
    }

	LOG_MSG("ExecThread::run: call terminate_run");
	terminate_run(&res);

	return;
}
Esempio n. 20
0
File: utilW.c Progetto: gavin971/ncl
NhlErrorTypes generate_2d_array_W( void )
{
/*
 * Input array variables
 */
  void *tmp_dsizes_data;
  ng_size_t *dsizes_data;
  int *mlow, *mhigh, *iseed;
  void *dlow, *dhigh;
  double *tmp_dlow, *tmp_dhigh;
  NclBasicDataTypes type_dlow, type_dhigh, type_dsizes_data;
/*
 * Output variables.
 */
  void *data;
  double *tmp_data;
  NclBasicDataTypes type_data;
  int ret, id0, id1;
/*
 * Declare various variables for random purposes.
 */
  ng_size_t size_data;
/*
 * Retrieve arguments.
 *
 *
 * Get number of lows and highs. These two values will be forced to
 * be between 1 and 25.
 */
  mlow = (int*)NclGetArgValue(
          0,
          6,
          NULL,
          NULL,
          NULL,
          NULL,
          NULL,
          DONT_CARE);

  mhigh = (int*)NclGetArgValue(
          1,
          6,
          NULL,
          NULL,
          NULL,
          NULL,
          NULL,
          DONT_CARE);

/*
 * Retrieve minimum and maximum values that the data is supposed to have.
 */
  dlow = (void*)NclGetArgValue(
          2,
          6,
          NULL,
          NULL,
          NULL,
          NULL,
          &type_dlow,
          DONT_CARE);

  dhigh = (void*)NclGetArgValue(
          3,
          6,
          NULL,
          NULL,
          NULL,
          NULL,
          &type_dhigh,
          DONT_CARE);

/*
 * Get size of output array.
 */
  iseed = (int*)NclGetArgValue(
          4,
          6,
          NULL,
          NULL,
          NULL,
          NULL,
          NULL,
          DONT_CARE);
/*
 * Get size of output array.
 */
  tmp_dsizes_data = (void*)NclGetArgValue(
          5,
          6,
          NULL,
          NULL,
          NULL,
          NULL,
          &type_dsizes_data,
          DONT_CARE);

/*
 * Error checking.
 */
  dsizes_data = get_dimensions(tmp_dsizes_data,2,type_dsizes_data,"generate_2d_array");
  if(dsizes_data == NULL) 
    return(NhlFATAL);

  if(dsizes_data[0] <= 1 && dsizes_data[1] <= 1) {
    NhlPError(NhlFATAL,NhlEUNKNOWN,"generate_2d_array: the dimensions of the output array must be such that it has at least two elements");
    return(NhlFATAL);
  }
  if((dsizes_data[0] > INT_MAX) ||
     (dsizes_data[1] > INT_MAX)) {
    NhlPError(NhlFATAL,NhlEUNKNOWN,"generate_2d_array: input dimensions are greater than INT_MAX");
    return(NhlFATAL);
  }
  id0 = (int) dsizes_data[0];
  id1 = (int) dsizes_data[1];

  if(*iseed < 0 || *iseed > 100) {
    NhlPError(NhlWARNING,NhlEUNKNOWN,"generate_2d_array: iseed must be between 0 and 100. Will reset to 0.");
    *iseed = 0;
  }  
  if(*mlow < 1) {
    NhlPError(NhlWARNING,NhlEUNKNOWN,"generate_2d_array: mlow must be between 1 and 25. Will reset to 1.");
    *mlow = 1;
  }
  if(*mlow > 25) {
    NhlPError(NhlWARNING,NhlEUNKNOWN,"generate_2d_array: mlow must be between 1 and 25. Will reset to 25.");
    *mlow = 25;
  }

  if(*mhigh < 1) {
    NhlPError(NhlWARNING,NhlEUNKNOWN,"generate_2d_array: mhigh must be between 1 and 25. Will reset to 1.");
    *mhigh = 1;
  }
  if(*mhigh > 25) {
    NhlPError(NhlWARNING,NhlEUNKNOWN,"generate_2d_array: mhigh must be between 1 and 25. Will reset to 25.");
    *mhigh = 25;
  }

/*
 * Coerce dlow and dhigh to double.
 */
  tmp_dlow  = coerce_input_double(dlow, type_dlow, 1,0,NULL,NULL);
  tmp_dhigh = coerce_input_double(dhigh,type_dhigh,1,0,NULL,NULL);

/*
 * Compute the size of the 2D output array.
 */
  size_data = dsizes_data[0] * dsizes_data[1];

/*
 * The type of the output array depends on dlow and dhigh.
 */
  if(type_dlow == NCL_double || type_dhigh == NCL_double) {
    type_data = NCL_double;
  }
  else {
    type_data = NCL_float;
  }

/*
 * Allocate memory for output.
 */
  if(type_data == NCL_double) {
    data     = (void*)malloc(size_data*sizeof(double));
    tmp_data = (double *)data;
    if(data == NULL) {
      NhlPError(NhlFATAL,NhlEUNKNOWN,"generate_2d_array: Unable to allocate memory for output array");
      return(NhlFATAL);
    }
  }
  else {
    data     = (void*)malloc(size_data*sizeof(float));
    tmp_data = (double*)malloc(size_data*sizeof(double));
    if(tmp_data == NULL || data == NULL) {
      NhlPError(NhlFATAL,NhlEUNKNOWN,"generate_2d_array: Unable to allocate memory for output array");
      return(NhlFATAL);
    }
  }
/*
 * Call the Fortran version of this routine.
 */
  NGCALLF(dgendat,DGENDAT)(tmp_data,&id1,&id1,
			   &id0,mlow,mhigh,tmp_dlow,tmp_dhigh,
			   iseed);

/*
 * Figure out if we need to coerce output back to float.
 */
  if(type_data == NCL_float) {
    coerce_output_float_only(data,tmp_data,size_data,0);
  }
/*
 * Free memory.
 */
  if(type_data  != NCL_double) NclFree(tmp_data);
  if(type_dlow  != NCL_double) NclFree(tmp_dlow);
  if(type_dhigh != NCL_double) NclFree(tmp_dhigh);

  ret = NclReturnValue(data,2,dsizes_data,NULL,type_data,0);
  NclFree(dsizes_data);
  return(ret);
}
Esempio n. 21
0
NhlErrorTypes ezfftb_W( void )
{
/*
 * Input array variables
 */
  void *cf;
  double *tmp_cf1 = NULL;
  double *tmp_cf2 = NULL;
  int ndims_cf;
  ng_size_t dsizes_cf[NCL_MAX_DIMENSIONS];
  ng_size_t dsizes_xbar[1];
  void *xbar;
  double *tmp_xbar = NULL;
  NclBasicDataTypes type_cf, type_xbar;
  NclScalar missing_cf, missing_dcf, missing_rcf, missing_x;
  int has_missing_cf;
/*
 * Some variables we need to retrieve the "npts" atttribute (if it exists).
 */
  NclAttList *att_list;
  NclAtt tmp_attobj;
  NclStackEntry data;
/*
 * Output array variables
 */
  void *x;
  double *tmp_x;
  int ndims_x;
  ng_size_t dsizes_x[NCL_MAX_DIMENSIONS];
  NclBasicDataTypes type_x;
/*
 * various
 */
  double *work;
  ng_size_t index_cf, index_x;
  ng_size_t i, *tmp_npts, npts, npts2, lnpts2, size_x, size_leftmost;
  int found_missing1, found_missing2, any_missing, scalar_xbar;
  int inpts;
/*
 * Retrieve parameters
 *
 * Note any of the pointer parameters can be set to NULL, which
 * implies you don't care about its value.
 */
  cf = (void*)NclGetArgValue(
           0,
           2,
           &ndims_cf, 
           dsizes_cf,
           &missing_cf,
           &has_missing_cf,
           &type_cf,
           DONT_CARE);
  xbar = (void*)NclGetArgValue(
           1,
           2,
           NULL,
           dsizes_xbar,
           NULL,
           NULL,
           &type_xbar,
           DONT_CARE);
/*
 * Calculate number of leftmost elements.
 */
  size_leftmost = 1;
  for( i = 1; i < ndims_cf-1; i++ ) size_leftmost *= dsizes_cf[i];
/*
 * Check xbar dimension sizes.
 */
  scalar_xbar = is_scalar(1,dsizes_xbar);

  if(!scalar_xbar) {
/*
 * If xbar is not a scalar, it must be an array of the same dimension
 * sizes as the leftmost dimensions of cf (except the first dimension
 * of '2').
 */ 
    if(dsizes_xbar[0] != size_leftmost) {
      NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: If xbar is not a scalar, then it must be a single vector of the length of the product of the leftmost dimensions of 'cf' (not including the '2' dimension)") ;
      return(NhlFATAL);
    }
  }

/*
 * Coerce missing values.
 */
  coerce_missing(type_cf,has_missing_cf,&missing_cf,&missing_dcf,&missing_rcf);
/*
 * Okay, what follows here is some code for retrieving the "npts"
 * attribute if it exists. This attribute is one that should have been
 * set when "ezfftf" was called, and it indicates the length of the
 * original series.
 */
  npts2  = dsizes_cf[ndims_cf-1];     /* Calculate the length in case  */
                                      /* it is not set explicitly. */
  npts = 2*npts2;

  data = _NclGetArg(0,2,DONT_CARE);
  switch(data.kind) {
  case NclStk_VAR:
    if(data.u.data_var->var.att_id != -1) {
      tmp_attobj = (NclAtt)_NclGetObj(data.u.data_var->var.att_id);
      if(tmp_attobj == NULL) {
        NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: Bad attribute list, can't continue");
        return(NhlFATAL);
      }
      if(tmp_attobj->att.n_atts == 0) {
        break;
      }
      att_list = tmp_attobj->att.att_list;
      i = 0;
      while(att_list != NULL) {
        if(att_list->quark == NrmStringToQuark("npts")) {
          tmp_npts = get_dimensions(att_list->attvalue->multidval.val,1,
                                    att_list->attvalue->multidval.data_type,
                                    "ezfftb");
          npts = *tmp_npts;
          free(tmp_npts);
	  if((npts % 2) == 0) {
	    npts2 = npts/2;
	  }
	  else {
	    npts2 = (npts-1)/2;
	  }
          break;
        }
        att_list = att_list->next;
      }
    }
    break;
  default:
        NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: data.kind, can't continue");
        return(NhlFATAL);
  }
/*
 * Test input array size
 */
  if(npts > INT_MAX) {
    NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: npts = %d is greater than INT_MAX", npts);
    return(NhlFATAL);
  }
  inpts = (int) npts;

/*
 * Calculate size of output array.
 */
  lnpts2 = npts2 * size_leftmost;
  size_x = size_leftmost * npts;

  ndims_x = ndims_cf - 1;
  for(i = 0; i < ndims_x-1; i++ ) dsizes_x[i] = dsizes_cf[i+1];
  dsizes_x[ndims_x-1] = npts;
/*
 * Create arrays to coerce input to double if necessary.
 */
  if(type_cf != NCL_double) {
    tmp_cf1 = (double*)calloc(npts2,sizeof(double));
    tmp_cf2 = (double*)calloc(npts2,sizeof(double));
    if(tmp_cf1 == NULL || tmp_cf2 == NULL) {
      NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: Unable to allocate memory for coercing input array to double precision");
      return(NhlFATAL);
    }
  }

  if(type_xbar != NCL_double) {
    tmp_xbar = (double*)calloc(1,sizeof(double));
    if(tmp_xbar == NULL) {
      NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: Unable to allocate memory for coercing input array to double precision");
      return(NhlFATAL);
    }
  }

/*
 * Allocate memory for output array.
 */
  tmp_x = (double *)calloc(npts,sizeof(double));
  if (tmp_x == NULL) {
    NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: Cannot allocate memory for temporary output array" );
    return(NhlFATAL);
  }
  if(type_cf == NCL_double) {
    type_x = NCL_double;
    x = (void*)calloc(size_x,sizeof(double));
    if(has_missing_cf) missing_x = missing_dcf;
  }
  else {
    type_x = NCL_float;
    x = (void*)calloc(size_x,sizeof(float));
    if(has_missing_cf) missing_x = missing_rcf;
  }
  if (x == NULL) {
    NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: Cannot allocate memory for output array" );
    return(NhlFATAL);
  }
/*
 * Allocate memory for work array
 */
  work = (double*)calloc(4*npts+15,sizeof(double));
  if ( work == NULL ) {
    NhlPError(NhlFATAL,NhlEUNKNOWN,"ezfftb: Cannot allocate memory for work array" );
    return(NhlFATAL);
  }
/*
 * If xbar is a scalar, coerce it outside the loop.
 */
  if(scalar_xbar) {
    if(type_xbar != NCL_double) { 
      coerce_subset_input_double(xbar,tmp_xbar,0,type_xbar,1,0,NULL,NULL);
    }
    else {
      tmp_xbar = &((double*)xbar)[0];
    }
  }

/*
 * Call the f77 version of 'dezfftb' with the full argument list.
 */
  index_x = index_cf = 0;
  any_missing = 0;
  for(i = 0; i < size_leftmost; i++) {
    if(type_cf != NCL_double) { 
      coerce_subset_input_double(cf,tmp_cf1,index_cf,type_cf,npts2,0,
                                 NULL,NULL);
      coerce_subset_input_double(cf,tmp_cf2,lnpts2+index_cf,type_cf,npts2,0,
                                 NULL,NULL);
    }
    else {
      tmp_cf1 = &((double*)cf)[index_cf];
      tmp_cf2 = &((double*)cf)[lnpts2+index_cf];
    }
/*
 * Check for missing values in cf.  If any, then coerce that section of
 * the output to missing.
 */
    found_missing1 = contains_missing(tmp_cf1,npts2,has_missing_cf,
                                      missing_dcf.doubleval);
    found_missing2 = contains_missing(tmp_cf2,npts2,has_missing_cf,
                                      missing_dcf.doubleval);
    if(found_missing1 || found_missing2) {
      any_missing++;
      set_subset_output_missing(x,index_x,type_x,npts,missing_dcf.doubleval);
    }
    else {
/*
 * If xbar is not a scalar, then we need to coerce each element
 * to double or else just grab its value.
 */
      if(!scalar_xbar) {
        if(type_xbar != NCL_double) { 
          coerce_subset_input_double(xbar,tmp_xbar,i,type_xbar,1,0,NULL,NULL);
        }
        else {
          tmp_xbar = &((double*)xbar)[i];
        }
      }

      NGCALLF(dezffti,DEZFFTI)(&inpts,work);
      NGCALLF(dezfftb,DEZFFTB)(&inpts,tmp_x,tmp_xbar,tmp_cf1,tmp_cf2,work);
/*
 * Copy results back into x.
 */
      coerce_output_float_or_double(x,tmp_x,type_cf,npts,index_x);
    }
    index_x  += npts;
    index_cf += npts2;
  }

/*
 * Free up memory.
 */
  if(type_cf != NCL_double) {
    free(tmp_cf1);
    free(tmp_cf2);
  }
  if(type_xbar != NCL_double) free(tmp_xbar);
  free(tmp_x);
  free(work);

  if(any_missing) {
    NhlPError(NhlWARNING,NhlEUNKNOWN,"ezfftb: %d input arrays contained missing values. No calculations performed on these arrays.",any_missing);

    return(NclReturnValue(x,ndims_x,dsizes_x,&missing_x,type_x,0));
  }
  else {
    return(NclReturnValue(x,ndims_x,dsizes_x,NULL,type_x,0));
  }
}