void SaveISISNexus::dae() { NXmakegroup(handle, "dae", "IXdae"); NXopengroup(handle, "dae", "IXdae"); saveString("detector_table_file", " "); saveString("spectra_table_file", " "); saveString("wiring_table_file", " "); saveIntOpen("period_index", m_isisRaw->t_pmap, nper); NXgetdataID(handle, &period_index_link); close(); NXmakegroup(handle, "time_channels_1", "IXtime_channels"); NXopengroup(handle, "time_channels_1", "IXtime_channels"); boost::scoped_array<float> timeChannels(new float[ntc + 1]); m_isisRaw->getTimeChannels(timeChannels.get(), ntc + 1); saveFloatOpen("time_of_flight", timeChannels.get(), ntc + 1); putAttr("axis", 1); putAttr("primary", 1); putAttr("units", "microseconds"); NXgetdataID(handle, &time_of_flight_link); close(); saveIntOpen("time_of_flight_raw", m_isisRaw->t_tcb1, ntc + 1); putAttr("units", "pulses"); putAttr("frequency", "32 MHz"); NXgetdataID(handle, &time_of_flight_raw_link); close(); NXclosegroup(handle); // time_channels_1 NXclosegroup(handle); // dae }
/** * Add properties from a nexus file to * the workspace run. * API entry for recursive routine below * * * @param nxfileID :: Nexus file handle to be parsed, just after an NXopengroup * @param runDetails :: where to add properties * */ void LoadHelper::addNexusFieldsToWsRun(NXhandle nxfileID, API::Run& runDetails) { std::string emptyStr; // needed for first call int datatype; char nxname[NX_MAXNAMELEN], nxclass[NX_MAXNAMELEN]; // As a workaround against some "not so good" old ILL nexus files (ILLIN5_Vana_095893.nxs for example) // we begin the parse on the first entry (entry0). This allow to avoid the bogus entries that follows. NXstatus getnextentry_status = NXgetnextentry(nxfileID, nxname, nxclass, &datatype); if (getnextentry_status == NX_OK) { NXstatus opengroup_status; if ((opengroup_status = NXopengroup(nxfileID, nxname, nxclass)) == NX_OK) { if (std::string(nxname) == "entry0") { recurseAndAddNexusFieldsToWsRun(nxfileID, runDetails, emptyStr, emptyStr, 1 /* level */); } else { g_log.debug() << "Unexpected group name in nexus file : " << nxname << std::endl; } NXclosegroup(nxfileID); } } }
int NexusFileIO::getXValues(MantidVec& xValues, const int& spectra) const { // // find the X values for spectra. If uniform, the spectra number is ignored. // int rank,dim[2],type; //open workspace group NXstatus status=NXopengroup(fileID,"workspace","NXdata"); if(status==NX_ERROR) return(1); // read axis1 size status=NXopendata(fileID,"axis1"); if(status==NX_ERROR) return(2); NXgetinfo(fileID, &rank, dim, &type); if(rank==1) { NXgetdata(fileID,&xValues[0]); } else { int start[2]={spectra,0}; int size[2]={1,dim[1]}; NXgetslab(fileID,&xValues[0],start,size); } NXclosedata(fileID); NXclosegroup(fileID); return(0); }
/** * Write monitor_i gorup * @param i Index of a monitor */ void SaveISISNexus::monitor_i(int i) { int nper = m_isisRaw->t_nper; // number of periods int ntc = m_isisRaw->t_ntc1; // number of time channels int dim[] = {nper, 1, ntc}; int size[] = {1, 1, ntc}; std::ostringstream ostr; int mon_num = i + 1; ostr << "monitor_" << mon_num; NXmakegroup(handle, ostr.str().c_str(), "NXmonitor"); NXopengroup(handle, ostr.str().c_str(), "NXmonitor"); // int imon = m_isisRaw->mdet[i]; // spectrum number NXmakedata(handle, "data", NX_INT32, 3, dim); NXopendata(handle, "data"); for (int p = 0; p < nper; ++p) { int start[] = {p, 0, 0}; NXputslab(handle, getMonitorData(p, i), start, size); } putAttr("units", "counts"); putAttr("signal", 1); putAttr("axes", "period_index,spectrum_index,time_of_flight"); NXclosedata(handle); saveInt("monitor_number", &mon_num); NXmakelink(handle, &period_index_link); saveInt("spectrum_index", &m_isisRaw->mdet[i]); NXmakelink(handle, &time_of_flight_link); NXclosegroup(handle); }
void SaveISISNexus::sample() { NXmakegroup(handle, "sample", "NXsample"); NXopengroup(handle, "sample", "NXsample"); saveChar("name", m_isisRaw->spb.e_name, 40); saveFloat("height", &m_isisRaw->spb.e_height, 1); saveFloat("width", &m_isisRaw->spb.e_width, 1); saveFloat("thickness", &m_isisRaw->spb.e_thick, 1); saveString("id", " "); float tmp(0.0); saveFloat("distance", &tmp, 1); std::string shape[] = {"cylinder", "flat plate", "HRPD slab", "unknown"}; int i = m_isisRaw->spb.e_geom - 1; if (i < 0 || i > 3) i = 3; saveString("shape", shape[i]); std::string type[] = {"sample+can", "empty can", "vanadium", "absorber", "nothing", "sample, no can", "unknown"}; i = m_isisRaw->spb.e_type - 1; if (i < 0 || i > 6) i = 6; saveString("type", type[i]); NXclosegroup(handle); // sample }
int main(int argc, char *argv[]) { NXdict pDict = NULL; NXhandle hfil; void *pData = NULL; float fTina[3] = { 0.123, 0.234, 0.456}; float fTest[3], fDelta; float fTust[20*20]; char pBuffer[256]; int i; /* test nxdict */ NXDinitfromfile("test.dict",&pDict); NXopen("test.hdf",NXACC_CREATE,&hfil); NXDadd(pDict,"Gundula", "/entry1,NXentry/SphereOmeter,NXinstrument/SDS"); NXDupdate(pDict,"Bea","/entry1,NXentry/SDS"); NXDget(pDict,"Bea",pBuffer,131); printf("Bea = %s\n",pBuffer); NXDget(pDict,"Linda",pBuffer,254); NXDopendef(hfil,pDict,pBuffer); NXDputalias(hfil,pDict,"Tina",fTina); NXDputalias(hfil,pDict,"Gina",fTina); NXDgetalias(hfil,pDict,"Tina",fTest); NXDgetalias(hfil,pDict,"Gina",fTest); NXDputalias(hfil,pDict,"Linda",fTust); NXDaliaslink(hfil,pDict,"Eva","Linda"); NXDclose(pDict,"close.dict"); NXclose(&hfil); printf("NXDICT seemed to have worked \n"); /* test Utility functions */ printf(" Proceeding to test of utility functions \n"); NXopen("test2.hdf",NXACC_CREATE,&hfil); NXUwriteglobals(hfil, "test2.hdf", "Willibald Wuergehals", "Rue des Martyrs, 26505 Timbuktu, Legoland ", "+41-56-3102512", "*****@*****.**", " 755-898767", "Dingsbums"); NXUentergroup(hfil, "TestGroup", "NXtest"); NXclosegroup(hfil); NXUentergroup(hfil, "TestGroup", "NXtest"); i = 120; NXUenterdata(hfil,"TestData",DFNT_INT8, 1,&i,"Testis"); NXclosedata(hfil); NXUenterdata(hfil,"TestData",DFNT_INT8, 1,&i,"Testis"); NXUallocSDS(hfil,&pData); NXUfreeSDS(&pData); NXclose(&hfil); printf("All tests seem to have worked OK, %s %s\n", "but the test is pathetic\n", "Do not rely, in any circumstances, on this test alone"); }
int NDFileNexus::processStreamData(NDArray *pArray) { int fileWriteMode; int numCapture; int slabOffset[ND_ARRAY_MAX_DIMS]; int slabSize[ND_ARRAY_MAX_DIMS]; int rank; int ii; int addr = 0; //static const char *functionName = "processNode"; /* Must lock when accessing parameter library */ this->lock(); getIntegerParam(addr, NDFileWriteMode, &fileWriteMode); getIntegerParam(addr, NDFileNumCapture, &numCapture); this->unlock(); rank = pArray->ndims; for (ii=0; ii<rank; ii++) { switch(fileWriteMode) { case NDFileModeSingle: slabOffset[(rank-1) - ii] = 0; slabSize[(rank-1) -ii] = (int)pArray->dims[ii].size; break; case NDFileModeCapture: case NDFileModeStream: slabOffset[(rank) - ii] = 0; slabSize[(rank) -ii] = (int)pArray->dims[ii].size; break; } } //printf ("%s: dataPath %s\ndataName %s\nimageNumber %d\n", functionName, this->dataPath, this->dataName, this->imageNumber); if (this->imageNumber == 0) { NXopenpath( this->nxFileHandle, this->dataPath); NXopendata( this->nxFileHandle, this->dataName); } switch (fileWriteMode) { case NDFileModeSingle: NXputdata(this->nxFileHandle, pArray->pData); break; case NDFileModeCapture: case NDFileModeStream: rank = rank+1; slabOffset[0] = this->imageNumber; slabSize[0] = 1; NXputslab(this->nxFileHandle, pArray->pData, slabOffset, slabSize); break; } if (this-> imageNumber == (numCapture-1) ) { NXclosedata(this->nxFileHandle); NXclosegroup(this->nxFileHandle ); } this->imageNumber++; return 0; }
int NexusFileIO::getSpectra(MantidVec& values, MantidVec& errors, const int& spectra) const { // // read the values and errors for spectra // int rank,dim[2],type; //open workspace group NXstatus status=NXopengroup(fileID,"workspace","NXdata"); if(status==NX_ERROR) return(1); std::string entry; if(checkEntryAtLevelByAttribute("signal", entry)) status=NXopendata(fileID, entry.c_str()); else { status=NXclosegroup(fileID); return(2); } if(status==NX_ERROR) { NXclosegroup(fileID); return(2); } NXgetinfo(fileID, &rank, dim, &type); // get buffer and block size int start[2]={spectra-1,0}; int size[2]={1,dim[1]}; NXgetslab(fileID,&values[0],start,size); NXclosedata(fileID); // read errors status=NXopendata(fileID,"errors"); if(status==NX_ERROR) return(2); NXgetinfo(fileID, &rank, dim, &type); // set block size; size[1]=dim[1]; NXgetslab(fileID,&errors[0],start,size); NXclosedata(fileID); NXclosegroup(fileID); return(0); }
void SaveISISNexus::user() { NXmakegroup(handle, "user_1", "NXuser"); NXopengroup(handle, "user_1", "NXuser"); saveChar("name", m_isisRaw->user.r_user, 20); saveChar("affiliation", m_isisRaw->user.r_instit, 20); NXclosegroup(handle); // user_1 }
/** * Write instrument/moderator group */ void SaveISISNexus::moderator() { NXmakegroup(handle, "moderator", "NXmoderator"); NXopengroup(handle, "moderator", "NXmoderator"); float l1 = -m_isisRaw->ivpb.i_l1; saveFloatOpen("distance", &l1, 1); putAttr("units", "metre"); NXclosegroup(handle); }
/** * Write instrument/source group */ void SaveISISNexus::source() { NXmakegroup(handle, "source", "NXsource"); NXopengroup(handle, "source", "NXsource"); saveString("name", "ISIS"); saveString("probe", "neutrons"); saveString("type", "Pulsed Neutron Source"); NXclosegroup(handle); }
/** * Create group "detector_1" at NXentry level and link to some of the data in * instrument/detector_1 */ void SaveISISNexus::make_detector_1_link() { NXmakegroup(handle, "detector_1", "NXdata"); NXopengroup(handle, "detector_1", "NXdata"); NXmakelink(handle, &counts_link); NXmakelink(handle, &period_index_link); NXmakelink(handle, &spectrum_index_link); NXmakelink(handle, &time_of_flight_link); NXclosegroup(handle); }
void SaveISISNexus::instrument() { NXmakegroup(handle, "instrument", "NXinstrument"); NXopengroup(handle, "instrument", "NXinstrument"); saveCharOpen("name", &m_isisRaw->i_inst, 8); putAttr("short_name", m_isisRaw->hdr.inst_abrv, 3); close(); dae(); detector_1(); moderator(); source(); NXclosegroup(handle); }
/*--------------------------------------------------------------------*/ int nx_closegroup(void *handle){ int status; NXhandle hfil; hfil = (NXhandle)handle; status = NXclosegroup(hfil); if(status == NX_OK){ return 1; } else { return 0; } }
/* Outputs the contents of a NeXus group */ int NXBdir(NXhandle fileId) { int status, dataType, dataRank, dataDimensions[NX_MAXRANK], length; NXname name, nxclass, nxurl; if (NXinitgroupdir(fileId) != NX_OK) return NX_ERROR; do { status = NXgetnextentry(fileId, name, nxclass, &dataType); if (status == NX_ERROR) break; if (status == NX_OK) { if (strncmp(nxclass, "CDF", 3) == 0) { ; } else if (strcmp(nxclass, "SDS") == 0) { printf(" NX Data : %s", name); if (NXopendata(fileId, name) != NX_OK) return NX_ERROR; if (NXgetinfo (fileId, &dataRank, dataDimensions, &dataType) != NX_OK) return NX_ERROR; if (NXclosedata(fileId) != NX_OK) return NX_ERROR; PrintDimensions(dataRank, dataDimensions); printf(" "); PrintType(dataType); printf("\n"); } else { length = sizeof(nxurl); if (NXisexternalgroup(fileId, name, nxclass, nxurl, length) == NX_OK) { printf(" NX external Group: %s (%s), linked to: %s \n", name, nxclass, nxurl); } else { printf(" NX Group : %s (%s)\n", name, nxclass); if ((status = NXopengroup(fileId, name, nxclass)) != NX_OK) { return status; } PrintGroupAttributes(fileId, name); if ((status = NXclosegroup(fileId)) != NX_OK) { return status; } } } } } while (status == NX_OK); return status; }
/** Write out all of the event lists in the given workspace * @param ws :: an EventWorkspace */ int NexusFileIO::writeNexusProcessedDataEvent( const DataObjects::EventWorkspace_const_sptr& ws) { //write data entry NXstatus status=NXmakegroup(fileID,"event_workspace","NXdata"); if(status==NX_ERROR) return(2); NXopengroup(fileID,"event_workspace","NXdata"); for (size_t wi=0; wi < ws->getNumberHistograms(); wi++) { std::ostringstream group_name; group_name << "event_list_" << wi; this->writeEventList( ws->getEventList(wi), group_name.str()); } // Close up the overall group status=NXclosegroup(fileID); return((status==NX_ERROR)?3:0); }
/** Write out a combined chunk of event data * * @param ws :: an EventWorkspace * @param indices :: array of event list indexes * @param tofs :: array of TOFs * @param weights :: array of event weights * @param errorSquareds :: array of event squared errors * @param pulsetimes :: array of pulsetimes * @param compress :: if true, compress the entry */ int NexusFileIO::writeNexusProcessedDataEventCombined( const DataObjects::EventWorkspace_const_sptr& ws, std::vector<int64_t> & indices, double * tofs, float * weights, float * errorSquareds, int64_t * pulsetimes, bool compress) const { NXopengroup(fileID,"event_workspace","NXdata"); // The array of indices for each event list # int dims_array[1] = { static_cast<int>(indices.size()) }; if (indices.size() > 0) { if (compress) NXcompmakedata(fileID, "indices", NX_INT64, 1, dims_array, m_nexuscompression, dims_array); else NXmakedata(fileID, "indices", NX_INT64, 1, dims_array); NXopendata(fileID, "indices"); NXputdata(fileID, (void*)(indices.data()) ); std::string yUnits=ws->YUnit(); std::string yUnitLabel=ws->YUnitLabel(); NXputattr (fileID, "units", reinterpret_cast<void*>(const_cast<char*>(yUnits.c_str())), static_cast<int>(yUnits.size()), NX_CHAR); NXputattr (fileID, "unit_label", reinterpret_cast<void*>(const_cast<char*>(yUnitLabel.c_str())), static_cast<int>(yUnitLabel.size()), NX_CHAR); NXclosedata(fileID); } // Write out each field dims_array[0] = static_cast<int>(indices.back()); // TODO big truncation error! This is the # of events if (tofs) NXwritedata("tof", NX_FLOAT64, 1, dims_array, (void *)(tofs), compress); if (pulsetimes) NXwritedata("pulsetime", NX_INT64, 1, dims_array, (void *)(pulsetimes), compress); if (weights) NXwritedata("weight", NX_FLOAT32, 1, dims_array, (void *)(weights), compress); if (errorSquareds) NXwritedata("error_squared", NX_FLOAT32, 1, dims_array, (void *)(errorSquareds), compress); // Close up the overall group NXstatus status=NXclosegroup(fileID); return((status==NX_ERROR)?3:0); }
int main (int argc, char *argv[]) { int i, j, k, n, NXrank, NXdims[32], NXtype, NXlen, entry_status, attr_status; float r; void *data_buffer; unsigned char i1_array[4] = {1, 2, 3, 4}; short int i2_array[4] = {1000, 2000, 3000, 4000}; int i4_array[4] = {1000000, 2000000, 3000000, 4000000}; float r4_array[5][4] = {{1., 2., 3., 4.}, {5., 6., 7., 8.}, {9., 10., 11., 12.}, {13., 14., 15., 16.}, {17., 18., 19., 20.}}; double r8_array[5][4] = {{1., 2., 3., 4.}, {5., 6., 7., 8.}, {9., 10., 11., 12.}, {13., 14., 15., 16.}, {17., 18., 19., 20.}}; int array_dims[2] = {5, 4}; int unlimited_dims[1] = {NX_UNLIMITED}; int chunk_size[2]={5,4}; int slab_start[2], slab_size[2]; char name[64], char_class[64], char_buffer[128]; char group_name[64], class_name[64]; char c1_array[5][4] = {{'a', 'b', 'c' ,'d'}, {'e', 'f', 'g' ,'h'}, {'i', 'j', 'k', 'l'}, {'m', 'n', 'o', 'p'}, {'q', 'r', 's' , 't'}}; int unlimited_cdims[2] = {NX_UNLIMITED, 4}; NXhandle fileid, clone_fileid; NXlink glink, dlink, blink; int comp_array[100][20]; int dims[2]; int cdims[2]; int nx_creation_code; char nxFile[80]; char filename[256]; int64_t grossezahl[4]; const char* ch_test_data = "NeXus ><}&{'\\&\" Data"; char path[512]; grossezahl[0] = 12; grossezahl[2] = 23; #if HAVE_LONG_LONG_INT grossezahl[1] = (int64_t)555555555555LL; grossezahl[3] = (int64_t)777777777777LL; #else grossezahl[1] = (int64_t)555555555555; grossezahl[3] = (int64_t)777777777777; #endif /* HAVE_LONG_LONG_INT */ if(strstr(argv[0],"napi_test-hdf5") != NULL){ nx_creation_code = NXACC_CREATE5; strcpy(nxFile,"NXtest.h5"); }else if(strstr(argv[0],"napi_test-xml-table") != NULL){ nx_creation_code = NXACC_CREATEXML | NXACC_TABLE; strcpy(nxFile,"NXtest-table.xml"); }else if(strstr(argv[0],"napi_test-xml") != NULL){ nx_creation_code = NXACC_CREATEXML; strcpy(nxFile,"NXtest.xml"); } else { nx_creation_code = NXACC_CREATE; strcpy(nxFile,"NXtest.hdf"); } /* create file */ if (NXopen (nxFile, nx_creation_code, &fileid) != NX_OK) return 1; if (nx_creation_code == NXACC_CREATE5) { if (NXreopen (fileid, &clone_fileid) != NX_OK) return 1; } NXsetnumberformat(fileid,NX_FLOAT32,"%9.3f"); if (NXmakegroup (fileid, "entry", "NXentry") != NX_OK) return 1; if (NXopengroup (fileid, "entry", "NXentry") != NX_OK) return 1; if(NXputattr(fileid,"hugo","namenlos",strlen("namenlos"), NX_CHAR) != NX_OK) return 1; if(NXputattr(fileid,"cucumber","passion",strlen("passion"), NX_CHAR) != NX_OK) return 1; NXlen = strlen(ch_test_data); if (NXmakedata (fileid, "ch_data", NX_CHAR, 1, &NXlen) != NX_OK) return 1; if (NXopendata (fileid, "ch_data") != NX_OK) return 1; if (NXputdata (fileid, ch_test_data) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXmakedata (fileid, "c1_data", NX_CHAR, 2, array_dims) != NX_OK) return 1; if (NXopendata (fileid, "c1_data") != NX_OK) return 1; if (NXputdata (fileid, c1_array) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXmakedata (fileid, "i1_data", NX_INT8, 1, &array_dims[1]) != NX_OK) return 1; if (NXopendata (fileid, "i1_data") != NX_OK) return 1; if (NXputdata (fileid, i1_array) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXmakedata (fileid, "i2_data", NX_INT16, 1, &array_dims[1]) != NX_OK) return 1; if (NXopendata (fileid, "i2_data") != NX_OK) return 1; if (NXputdata (fileid, i2_array) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXmakedata (fileid, "i4_data", NX_INT32, 1, &array_dims[1]) != NX_OK) return 1; if (NXopendata (fileid, "i4_data") != NX_OK) return 1; if (NXputdata (fileid, i4_array) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXcompmakedata (fileid, "r4_data", NX_FLOAT32, 2, array_dims,NX_COMP_LZW,chunk_size) != NX_OK) return 1; if (NXopendata (fileid, "r4_data") != NX_OK) return 1; if (NXputdata (fileid, r4_array) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXmakedata (fileid, "r8_data", NX_FLOAT64, 2, array_dims) != NX_OK) return 1; if (NXopendata (fileid, "r8_data") != NX_OK) return 1; slab_start[0] = 4; slab_start[1] = 0; slab_size[0] = 1; slab_size[1] = 4; if (NXputslab (fileid, (double*)r8_array + 16, slab_start, slab_size) != NX_OK) return 1; slab_start[0] = 0; slab_start[1] = 0; slab_size[0] = 4; slab_size[1] = 4; if (NXputslab (fileid, r8_array, slab_start, slab_size) != NX_OK) return 1; if (NXputattr (fileid, "ch_attribute", ch_test_data, strlen (ch_test_data), NX_CHAR) != NX_OK) return 1; i = 42; if (NXputattr (fileid, "i4_attribute", &i, 1, NX_INT32) != NX_OK) return 1; r = 3.14159265; if (NXputattr (fileid, "r4_attribute", &r, 1, NX_FLOAT32) != NX_OK) return 1; if (NXgetdataID (fileid, &dlink) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; dims[0] = 4; if (nx_creation_code != NXACC_CREATE) { if (NXmakedata (fileid, "grosse_zahl", NX_INT64, 1,dims) == NX_OK) { if (NXopendata (fileid, "grosse_zahl") != NX_OK) return 1; if (NXputdata (fileid, grossezahl) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; } } if (NXmakegroup (fileid, "data", "NXdata") != NX_OK) return 1; if (NXopengroup (fileid, "data", "NXdata") != NX_OK) return 1; if (NXmakelink (fileid, &dlink) != NX_OK) return 1; dims[0] = 100; dims[1] = 20; for(i = 0; i < 100; i++) { for(j = 0; j < 20; j++) { comp_array[i][j] = i; } } cdims[0] = 20; cdims[1] = 20; if (NXcompmakedata (fileid, "comp_data", NX_INT32, 2, dims, NX_COMP_LZW, cdims) != NX_OK) return 1; if (NXopendata (fileid, "comp_data") != NX_OK) return 1; if (NXputdata (fileid, comp_array) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXflush (&fileid) != NX_OK) return 1; if (NXmakedata (fileid, "flush_data", NX_INT32, 1, unlimited_dims) != NX_OK) return 1; slab_size[0] = 1; for (i = 0; i < 7; i++) { slab_start[0] = i; if (NXopendata (fileid, "flush_data") != NX_OK) return 1; if (NXputslab (fileid, &i, slab_start, slab_size) != NX_OK) return 1; if (NXflush (&fileid) != NX_OK) return 1; } if (NXclosegroup (fileid) != NX_OK) return 1; if (NXmakegroup (fileid, "sample", "NXsample") != NX_OK) return 1; if (NXopengroup (fileid, "sample", "NXsample") != NX_OK) return 1; NXlen = 12; if (NXmakedata (fileid, "ch_data", NX_CHAR, 1, &NXlen) != NX_OK) return 1; if (NXopendata (fileid, "ch_data") != NX_OK) return 1; if (NXputdata (fileid, "NeXus sample") != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXgetgroupID (fileid, &glink) != NX_OK) return 1; if (( nx_creation_code & NXACC_CREATEXML) == 0 ) { if (NXmakedata (fileid, "cdata_unlimited", NX_CHAR, 2, unlimited_cdims) != NX_OK) return 1; if (NXopendata (fileid, "cdata_unlimited") != NX_OK) return 1; slab_size[0] = 1; slab_size[1] = 4; slab_start[1] = 0; for (i = 0; i < 5; i++) { slab_start[0] = i; if (NXputslab (fileid, &(c1_array[i][0]), slab_start, slab_size) != NX_OK) return 1; } if (NXclosedata (fileid) != NX_OK) return 1; } if (NXclosegroup (fileid) != NX_OK) return 1; if (NXclosegroup (fileid) != NX_OK) return 1; if (NXmakegroup (fileid, "link", "NXentry") != NX_OK) return 1; if (NXopengroup (fileid, "link", "NXentry") != NX_OK) return 1; if (NXmakelink (fileid, &glink) != NX_OK) return 1; if (NXmakenamedlink (fileid,"renLinkGroup", &glink) != NX_OK) return 1; if (NXmakenamedlink (fileid, "renLinkData", &dlink) != NX_OK) return 1; if (NXclosegroup (fileid) != NX_OK) return 1; if (NXclose (&fileid) != NX_OK) return 1; if ( (argc >= 2) && !strcmp(argv[1], "-q") ) { return 0; /* create only */ } /* read test */ if (NXopen (nxFile, NXACC_RDWR,&fileid) != NX_OK) return 1; if(NXinquirefile(fileid,filename,256) != NX_OK){ return 1; } printf("NXinquirefile found: %s\n", relativePathOf(filename)); NXgetattrinfo (fileid, &i); if (i > 0) { printf ("Number of global attributes: %d\n", i); } do { attr_status = NXgetnextattr (fileid, name, NXdims, &NXtype); if (attr_status == NX_ERROR) return 1; if (attr_status == NX_OK) { switch (NXtype) { case NX_CHAR: NXlen = sizeof (char_buffer); if (NXgetattr (fileid, name, char_buffer, &NXlen, &NXtype) != NX_OK) return 1; if ( strcmp(name, "file_time") && strcmp(name, "HDF_version") && strcmp(name, "HDF5_Version") && strcmp(name, "XML_version") ) { printf (" %s = %s\n", name, char_buffer); } break; } } } while (attr_status == NX_OK); if (NXopengroup (fileid, "entry", "NXentry") != NX_OK) return 1; NXgetattrinfo(fileid,&i); printf("Number of group attributes: %d\n", i); if(NXgetpath(fileid,path,512) != NX_OK)return 1; printf("NXentry path %s\n", path); do { attr_status = NXgetnextattr (fileid, name, NXdims, &NXtype); if (attr_status == NX_ERROR) return 1; if (attr_status == NX_OK) { switch (NXtype) { case NX_CHAR: NXlen = sizeof (char_buffer); if (NXgetattr (fileid, name, char_buffer, &NXlen, &NXtype) != NX_OK) return 1; printf (" %s = %s\n", name, char_buffer); } } } while (attr_status == NX_OK); if (NXgetgroupinfo (fileid, &i, group_name, class_name) != NX_OK) return 1; printf ("Group: %s(%s) contains %d items\n", group_name, class_name, i); do { entry_status = NXgetnextentry (fileid, name, char_class, &NXtype); if (entry_status == NX_ERROR) return 1; if (strcmp(char_class,"SDS") != 0) { if (entry_status != NX_EOD) { printf (" Subgroup: %s(%s)\n", name, char_class); entry_status = NX_OK; } } else { if (entry_status == NX_OK) { if (NXopendata (fileid, name) != NX_OK) return 1; if(NXgetpath(fileid,path,512) != NX_OK)return 1; printf("Data path %s\n", path); if (NXgetinfo (fileid, &NXrank, NXdims, &NXtype) != NX_OK) return 1; printf (" %s(%d)", name, NXtype); if (NXmalloc ((void **) &data_buffer, NXrank, NXdims, NXtype) != NX_OK) return 1; n = 1; for(k=0; k<NXrank; k++) { n *= NXdims[k]; } if (NXtype == NX_CHAR) { if (NXgetdata (fileid, data_buffer) != NX_OK) return 1; print_data (" = ", data_buffer, NXtype, n); } else if (NXtype != NX_FLOAT32 && NXtype != NX_FLOAT64) { if (NXgetdata (fileid, data_buffer) != NX_OK) return 1; print_data (" = ", data_buffer, NXtype, n); } else { slab_start[0] = 0; slab_start[1] = 0; slab_size[0] = 1; slab_size[1] = 4; if (NXgetslab (fileid, data_buffer, slab_start, slab_size) != NX_OK) return 1; print_data ("\n ", data_buffer, NXtype, 4); slab_start[0] = 1; if (NXgetslab (fileid, data_buffer, slab_start, slab_size) != NX_OK) return 1; print_data (" ", data_buffer, NXtype, 4); slab_start[0] = 2; if (NXgetslab (fileid, data_buffer, slab_start, slab_size) != NX_OK) return 1; print_data (" ", data_buffer, NXtype, 4); slab_start[0] = 3; if (NXgetslab (fileid, data_buffer, slab_start, slab_size) != NX_OK) return 1; print_data (" ", data_buffer, NXtype, 4); slab_start[0] = 4; if (NXgetslab (fileid, data_buffer, slab_start, slab_size) != NX_OK) return 1; print_data (" ", data_buffer, NXtype, 4); if (NXgetattrinfo (fileid, &i) != NX_OK) return 1; if (i > 0) { printf (" Number of attributes : %d\n", i); } do { attr_status = NXgetnextattr (fileid, name, NXdims, &NXtype); if (attr_status == NX_ERROR) return 1; if (attr_status == NX_OK) { switch (NXtype) { case NX_INT32: NXlen = 1; if (NXgetattr (fileid, name, &i, &NXlen, &NXtype) != NX_OK) return 1; printf (" %s : %d\n", name, i); break; case NX_FLOAT32: NXlen = 1; if (NXgetattr (fileid, name, &r, &NXlen, &NXtype) != NX_OK) return 1; printf (" %s : %f\n", name, r); break; case NX_CHAR: NXlen = sizeof (char_buffer); if (NXgetattr (fileid, name, char_buffer, &NXlen, &NXtype) != NX_OK) return 1; printf (" %s : %s\n", name, char_buffer); break; } } } while (attr_status == NX_OK); } if (NXclosedata (fileid) != NX_OK) return 1; if (NXfree ((void **) &data_buffer) != NX_OK) return 1; } } } while (entry_status == NX_OK); if (NXclosegroup (fileid) != NX_OK) return 1; /* * check links */ if (NXopengroup (fileid, "entry", "NXentry") != NX_OK) return 1; if (NXopengroup (fileid, "sample", "NXsample") != NX_OK) return 1; if (NXgetgroupID (fileid, &glink) != NX_OK) return 1; if (NXclosegroup (fileid) != NX_OK) return 1; if (NXopengroup (fileid, "data", "NXdata") != NX_OK) return 1; if (NXopendata (fileid, "r8_data") != NX_OK) return 1; if (NXgetdataID (fileid, &dlink) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXclosegroup (fileid) != NX_OK) return 1; if (NXopendata (fileid, "r8_data") != NX_OK) return 1; if (NXgetdataID (fileid, &blink) != NX_OK) return 1; if (NXclosedata (fileid) != NX_OK) return 1; if (NXsameID(fileid, &dlink, &blink) != NX_OK) { printf ("Link check FAILED (r8_data)\n"); printf ("original data\n"); NXIprintlink(fileid, &dlink); printf ("linked data\n"); NXIprintlink(fileid, &blink); return 1; } if (NXclosegroup (fileid) != NX_OK) return 1; if (NXopengroup (fileid, "link", "NXentry") != NX_OK) return 1; if (NXopengroup (fileid, "sample", "NXsample") != NX_OK) return 1; if(NXgetpath(fileid,path,512) != NX_OK)return 1; printf("Group path %s\n", path); if (NXgetgroupID (fileid, &blink) != NX_OK) return 1; if (NXsameID(fileid, &glink, &blink) != NX_OK) { printf ("Link check FAILED (sample)\n"); printf ("original group\n"); NXIprintlink(fileid, &glink); printf ("linked group\n"); NXIprintlink(fileid, &blink); return 1; } if (NXclosegroup (fileid) != NX_OK) return 1; if (NXopengroup (fileid, "renLinkGroup", "NXsample") != NX_OK) return 1; if (NXgetgroupID (fileid, &blink) != NX_OK) return 1; if (NXsameID(fileid, &glink, &blink) != NX_OK) { printf ("Link check FAILED (renLinkGroup)\n"); printf ("original group\n"); NXIprintlink(fileid, &glink); printf ("linked group\n"); NXIprintlink(fileid, &blink); return 1; } if (NXclosegroup (fileid) != NX_OK) return 1; if(NXopendata(fileid,"renLinkData") != NX_OK) return 1; if(NXgetdataID(fileid,&blink) != NX_OK) return 1; if (NXsameID(fileid, &dlink, &blink) != NX_OK) { printf ("Link check FAILED (renLinkData)\n"); printf ("original group\n"); NXIprintlink(fileid, &glink); printf ("linked group\n"); NXIprintlink(fileid, &blink); return 1; } if(NXclosedata(fileid) != NX_OK) return 1; if (NXclosegroup (fileid) != NX_OK) return 1; printf ("Link check OK\n"); /* tests for NXopenpath */ if(NXopenpath(fileid,"/entry/data/comp_data") != NX_OK){ printf("Failure on NXopenpath\n"); return 0; } if(NXopenpath(fileid,"/entry/data/comp_data") != NX_OK){ printf("Failure on NXopenpath\n"); return 0; } if(NXopenpath(fileid,"../r8_data") != NX_OK){ printf("Failure on NXopenpath\n"); return 0; } if(NXopengrouppath(fileid,"/entry/data/comp_data") != NX_OK){ printf("Failure on NXopengrouppath\n"); return 0; } if(NXopenpath(fileid,"/entry/data/r8_data") != NX_OK){ printf("Failure on NXopenpath\n"); return 0; } printf("NXopenpath checks OK\n"); if (NXclose (&fileid) != NX_OK) return 1; printf("before load path tests\n"); if(testLoadPath() != 0) return 1; printf("before external link tests\n"); if(testExternal(argv[0]) != 0) { return 1; } printf("all ok - done\n"); return 0; }
/** Execute the algorithm. Currently just calls SaveISISNexusProcessed but could * call write other formats if support added * * @throw runtime_error Thrown if algorithm cannot execute */ void SaveISISNexus::exec() { // Retrieve the filename from the properties inputFilename = getPropertyValue("InputFileName"); m_isisRaw = new ISISRAW2; rawFile = fopen(inputFilename.c_str(), "rb"); if (rawFile == nullptr) { throw Exception::FileError("Cannot open file ", inputFilename); } m_isisRaw->ioRAW(rawFile, true); nper = m_isisRaw->t_nper; // number of periods nsp = m_isisRaw->t_nsp1; // number of spectra ntc = m_isisRaw->t_ntc1; // number of time channels nmon = m_isisRaw->i_mon; // number of monitors ndet = m_isisRaw->i_det; // number of detectors std::string outputFilename = getPropertyValue("OutputFileName"); NXstatus status; float flt; status = NXopen(outputFilename.c_str(), NXACC_CREATE5, &handle); if (status != NX_OK) { throw std::runtime_error("Cannot open file " + outputFilename + " for writing."); } NXmakegroup(handle, "raw_data_1", "NXentry"); NXopengroup(handle, "raw_data_1", "NXentry"); write_isis_vms_compat(); saveString("beamline", " "); flt = static_cast<float>(m_isisRaw->rpb.r_dur); // could be wrong saveFloatOpen("collection_time", &flt, 1); putAttr("units", "second"); close(); saveStringOpen("definition", "TOFRAW"); putAttr("version", "1.0"); putAttr("url", "http://definition.nexusformat.org/instruments/TOFRAW/?version=1.0"); close(); saveStringOpen("definition_local", "ISISTOFRAW"); putAttr("version", "1.0"); putAttr("url", "http://svn.isis.rl.ac.uk/instruments/ISISTOFRAW/?version=1.0"); close(); flt = static_cast<float>(m_isisRaw->rpb.r_dur); saveFloatOpen("duration", &flt, 1); putAttr("units", "second"); close(); start_time_str.assign(m_isisRaw->hdr.hd_date, m_isisRaw->hdr.hd_date + 12); toISO8601(start_time_str); start_time_str += 'T'; start_time_str += std::string(m_isisRaw->hdr.hd_time, m_isisRaw->hdr.hd_time + 8); saveCharOpen("start_time", &start_time_str[0], 19); putAttr("units", "ISO8601"); close(); std::string str; str.assign(m_isisRaw->rpb.r_enddate, m_isisRaw->rpb.r_enddate + 12); toISO8601(str); str += 'T'; str += std::string(m_isisRaw->rpb.r_endtime, m_isisRaw->rpb.r_endtime + 8); saveCharOpen("end_time", &str[0], 19); putAttr("units", "ISO8601"); close(); saveChar("title", m_isisRaw->r_title, 80); saveInt("good_frames", &m_isisRaw->rpb.r_goodfrm); std::string experiment_identifier = std::to_string(m_isisRaw->rpb.r_prop); saveChar("experiment_identifier", &experiment_identifier[0], static_cast<int>(experiment_identifier.size())); int tmp_int(0); saveInt("measurement_first_run", &tmp_int); saveString("measurement_id", " "); saveString("measurement_label", " "); saveString("measurement_subid", " "); saveString("measurement_type", " "); saveCharOpen("name", &m_isisRaw->i_inst, 8); putAttr("short_name", m_isisRaw->hdr.inst_abrv, 3); close(); logNotes(); saveString("program_name", "isisicp"); saveFloatOpen("proton_charge", &m_isisRaw->rpb.r_gd_prtn_chrg, 1); putAttr("units", "uamp.hour"); close(); saveFloatOpen("proton_charge_raw", &m_isisRaw->rpb.r_tot_prtn_chrg, 1); putAttr("units", "uamp.hour"); close(); saveInt("raw_frames", &m_isisRaw->rpb.r_rawfrm); run_cycle(); saveInt("run_number", &m_isisRaw->r_number); // script_name // seci_config instrument(); make_detector_1_link(); write_monitors(); user(); sample(); runlog(); selog(); NXclosegroup(handle); // raw_data_1 status = NXclose(&handle); delete m_isisRaw; }
void SaveISISNexus::selog() { // find log files with names <RawFilenameWithoutExt>_LogName.txt and save them // in potentialLogFiles std::vector<std::string> potentialLogFiles; Poco::File l_path(inputFilename); std::string l_filenamePart = Poco::Path(l_path.path()).getFileName(); std::string::size_type i = l_filenamePart.find_last_of('.'); if (i != std::string::npos) // remove the file extension { l_filenamePart.erase(i); } std::string base_name = l_filenamePart; boost::regex regex(l_filenamePart + "_.*\\.txt", boost::regex_constants::icase); Poco::DirectoryIterator end_iter; for (Poco::DirectoryIterator dir_itr(Poco::Path(inputFilename).parent()); dir_itr != end_iter; ++dir_itr) { if (!Poco::File(dir_itr->path()).isFile()) continue; l_filenamePart = Poco::Path(dir_itr->path()).getFileName(); if (boost::regex_match(l_filenamePart, regex)) { potentialLogFiles.push_back(dir_itr->path()); } } Progress prog(this, 0.5, 1, potentialLogFiles.size()); NXmakegroup(handle, "selog", "IXselog"); NXopengroup(handle, "selog", "IXselog"); // create a log for each of the found log files std::size_t nBase = base_name.size() + 1; for (auto &potentialLogFile : potentialLogFiles) { std::string logName = Poco::Path(potentialLogFile).getFileName(); logName.erase(0, nBase); logName.erase(logName.size() - 4); if (logName.size() > 3) { std::string icp = logName.substr(0, 3); std::transform(icp.begin(), icp.end(), icp.begin(), toupper); if (icp == "ICP") continue; } std::ifstream fil(potentialLogFile.c_str()); if (!fil) { g_log.warning("Cannot open log file " + potentialLogFile); continue; } start_time_str[10] = ' '; // make it compatible with boost::posix_time::ptime boost::posix_time::ptime start_time( boost::posix_time::time_from_string(start_time_str)); start_time_str[10] = 'T'; // revert std::vector<float> time_vec; std::vector<std::string> str_vec; std::vector<float> flt_vec; std::string line; bool isNotNumeric = false; while (std::getline(fil, line)) { if (line.empty()) continue; std::string date_time_str = line.substr(0, 19); date_time_str[10] = ' '; boost::posix_time::ptime time( boost::posix_time::time_from_string(date_time_str)); boost::posix_time::time_duration dt = time - start_time; time_vec.push_back(float(dt.total_seconds())); std::istringstream istr(line.substr(20)); // check if the data are numeric then save them in flt_vec if (!isNotNumeric) { float flt; istr >> flt; if (istr.bad() || istr.fail()) { isNotNumeric = true; } else { flt_vec.push_back(flt); } } str_vec.push_back(istr.str()); } fil.close(); NXmakegroup(handle, &logName[0], "IXseblock"); NXopengroup(handle, &logName[0], "IXseblock"); { saveString("vi_name", " "); saveString("set_control", " "); saveString("read_control", " "); float tmp = 0.0; saveFloatOpen("setpoint", &tmp, 1); putAttr("units", "mV"); close(); } NXmakegroup(handle, "value_log", "NXlog"); NXopengroup(handle, "value_log", "NXlog"); saveFloatOpen("time", &time_vec[0], static_cast<int>(time_vec.size())); putAttr("start", start_time_str); putAttr("units", "seconds"); close(); if (flt_vec.size() == str_vec.size()) { saveFloatOpen("value", &flt_vec[0], static_cast<int>(flt_vec.size())); } else { saveStringVectorOpen("value", str_vec); } putAttr("units", " "); close(); saveString("name", " "); NXclosegroup(handle); // value_log NXclosegroup(handle); // logName prog.report(); }
/** * Create and write run logs form \<RawFilename\>_ICPstatus.txt log file */ void SaveISISNexus::runlog() { progress(0); std::string ICPstatus_filename = inputFilename; std::string ICPevent_filename; std::string::size_type i = ICPstatus_filename.find_last_of('.'); if (i != std::string::npos) // remove the file extension { ICPstatus_filename.erase(i); } ICPevent_filename = ICPstatus_filename + "_ICPevent.txt"; ICPstatus_filename += "_ICPstatus.txt"; std::ifstream fil(ICPstatus_filename.c_str()); if (!fil) { g_log.warning("Cannot find the ICPstatus file. Skipping runlog"); progress(0.5); return; } std::vector<float> time_vec; std::vector<int> period_vec; std::vector<int> is_running_vec; std::vector<int> is_waiting_vec; std::vector<int> good_frames_vec; std::vector<int> raw_frames_vec; std::vector<int> monitor_sum_1_vec; std::vector<int> total_counts_vec; std::vector<int> run_status_vec; std::vector<float> proton_charge_vec; std::vector<float> proton_charge_raw_vec; std::vector<float> dae_beam_current_vec; std::vector<float> count_rate_vec; std::vector<float> np_ratio_vec; start_time_str[10] = ' '; // make it compatible with boost::posix_time::ptime boost::posix_time::ptime start_time( boost::posix_time::time_from_string(start_time_str)); start_time_str[10] = 'T'; // revert std::string line; std::getline(fil, line); // skip the first line while (std::getline(fil, line)) { std::string date_time_str; int period; int is_running; int is_waiting; int good_frames; int raw_frames; int monitor_sum_1; int total_counts; float proton_charge; float proton_charge_raw; float dae_beam_current; float count_rate; float np_ratio; std::istringstream istr(line); istr >> date_time_str >> period >> is_running >> is_waiting >> good_frames >> raw_frames >> proton_charge >> proton_charge_raw >> monitor_sum_1 >> dae_beam_current >> total_counts >> count_rate >> np_ratio; date_time_str[10] = ' '; boost::posix_time::ptime time( boost::posix_time::time_from_string(date_time_str)); boost::posix_time::time_duration dt = time - start_time; time_vec.push_back(float(dt.total_seconds())); period_vec.push_back(period); is_running_vec.push_back(is_running); is_waiting_vec.push_back(is_waiting); good_frames_vec.push_back(good_frames); raw_frames_vec.push_back(raw_frames); monitor_sum_1_vec.push_back(monitor_sum_1); total_counts_vec.push_back(total_counts); proton_charge_vec.push_back(proton_charge); proton_charge_raw_vec.push_back(proton_charge_raw); dae_beam_current_vec.push_back(dae_beam_current); count_rate_vec.push_back(count_rate); np_ratio_vec.push_back(np_ratio); } fil.close(); run_status_vec.resize(time_vec.size()); std::transform(is_running_vec.begin(), is_running_vec.end(), run_status_vec.begin(), std::bind2nd(std::plus<int>(), 1)); NXmakegroup(handle, "runlog", "IXrunlog"); NXopengroup(handle, "runlog", "IXrunlog"); int time_vec_size = static_cast<int>(time_vec.size()); write_runlog("period", &time_vec[0], &period_vec[0], NX_INT32, time_vec_size, "none"); write_runlog("is_running", &time_vec[0], &is_running_vec[0], NX_INT32, time_vec_size, "none"); write_runlog("is_waiting", &time_vec[0], &is_waiting_vec[0], NX_INT32, time_vec_size, "none"); write_runlog("good_frames", &time_vec[0], &good_frames_vec[0], NX_INT32, time_vec_size, "frames"); write_runlog("raw_frames", &time_vec[0], &raw_frames_vec[0], NX_INT32, time_vec_size, "frames"); write_runlog("monitor_sum_1", &time_vec[0], &monitor_sum_1_vec[0], NX_INT32, time_vec_size, "counts"); write_runlog("total_counts", &time_vec[0], &total_counts_vec[0], NX_INT32, time_vec_size, "counts"); write_runlog("proton_charge", &time_vec[0], &proton_charge_vec[0], NX_FLOAT32, time_vec_size, "uAh"); write_runlog("proton_charge_raw", &time_vec[0], &proton_charge_raw_vec[0], NX_FLOAT32, time_vec_size, "uAh"); write_runlog("dae_beam_current", &time_vec[0], &dae_beam_current_vec[0], NX_FLOAT32, time_vec_size, "uAh"); write_runlog("count_rate", &time_vec[0], &count_rate_vec[0], NX_FLOAT32, time_vec_size, "counts"); write_runlog("np_ratio", &time_vec[0], &np_ratio_vec[0], NX_FLOAT32, time_vec_size, "nones"); write_runlog("run_status", &time_vec[0], &run_status_vec[0], NX_INT32, time_vec_size, "none"); // read in ICPevent file and create icp_event log std::ifstream icpevent_fil(ICPevent_filename.c_str()); if (!icpevent_fil) { g_log.warning("Cannot find the ICPevent file"); progress(0.5); return; } time_vec.clear(); std::vector<std::string> event_vec; while (std::getline(icpevent_fil, line)) { if (line.empty()) continue; std::string date_time_str = line.substr(0, 19); date_time_str[10] = ' '; boost::posix_time::ptime time( boost::posix_time::time_from_string(date_time_str)); boost::posix_time::time_duration dt = time - start_time; time_vec.push_back(float(dt.total_seconds())); event_vec.push_back(line.substr(20)); } icpevent_fil.close(); NXmakegroup(handle, "icp_event", "NXlog"); NXopengroup(handle, "icp_event", "NXlog"); saveFloatOpen("time", &time_vec[0], static_cast<int>(time_vec.size())); putAttr("start", start_time_str); putAttr("units", "seconds"); close(); saveStringVectorOpen("value", event_vec, 72); putAttr("units", " "); close(); NXclosegroup(handle); // icp_event NXclosegroup(handle); // runlog progress(0.5); }
/** Write out a MatrixWorkspace's data as a 2D matrix. * Use writeNexusProcessedDataEvent if writing an EventWorkspace. */ int NexusFileIO::writeNexusProcessedData2D( const API::MatrixWorkspace_const_sptr& localworkspace, const bool& uniformSpectra, const std::vector<int>& spec, const char * group_name, bool write2Ddata) const { NXstatus status; //write data entry status=NXmakegroup(fileID,group_name,"NXdata"); if(status==NX_ERROR) return(2); NXopengroup(fileID,group_name,"NXdata"); // write workspace data const size_t nHist=localworkspace->getNumberHistograms(); if(nHist<1) return(2); const size_t nSpectBins=localworkspace->readY(0).size(); const size_t nSpect=spec.size(); int dims_array[2] = { static_cast<int>(nSpect),static_cast<int>(nSpectBins) }; // Set the axis labels and values Mantid::API::Axis *xAxis=localworkspace->getAxis(0); Mantid::API::Axis *sAxis=localworkspace->getAxis(1); std::string xLabel,sLabel; if ( xAxis->isSpectra() ) xLabel = "spectraNumber"; else { if ( xAxis->unit() ) xLabel = xAxis->unit()->unitID(); else xLabel = "unknown"; } if ( sAxis->isSpectra() ) sLabel = "spectraNumber"; else { if ( sAxis->unit() ) sLabel = sAxis->unit()->unitID(); else sLabel = "unknown"; } // Get the values on the vertical axis std::vector<double> axis2; if (nSpect < nHist) for (size_t i=0;i<nSpect;i++) axis2.push_back((*sAxis)(spec[i])); else for (size_t i=0;i<sAxis->length();i++) axis2.push_back((*sAxis)(i)); int start[2]={0,0}; int asize[2]={1,dims_array[1]}; // -------------- Actually write the 2D data ---------------------------- if (write2Ddata) { std::string name="values"; NXcompmakedata(fileID, name.c_str(), NX_FLOAT64, 2, dims_array,m_nexuscompression,asize); NXopendata(fileID, name.c_str()); for(size_t i=0;i<nSpect;i++) { int s = spec[i]; NXputslab(fileID, reinterpret_cast<void*>(const_cast<double*>(&(localworkspace->readY(s)[0]))),start,asize); start[0]++; } if(m_progress != 0) m_progress->reportIncrement(1, "Writing data"); int signal=1; NXputattr (fileID, "signal", &signal, 1, NX_INT32); // More properties const std::string axesNames="axis2,axis1"; NXputattr (fileID, "axes", reinterpret_cast<void*>(const_cast<char*>(axesNames.c_str())), static_cast<int>(axesNames.size()), NX_CHAR); std::string yUnits=localworkspace->YUnit(); std::string yUnitLabel=localworkspace->YUnitLabel(); NXputattr (fileID, "units", reinterpret_cast<void*>(const_cast<char*>(yUnits.c_str())), static_cast<int>(yUnits.size()), NX_CHAR); NXputattr (fileID, "unit_label", reinterpret_cast<void*>(const_cast<char*>(yUnitLabel.c_str())), static_cast<int>(yUnitLabel.size()), NX_CHAR); NXclosedata(fileID); // error name="errors"; NXcompmakedata(fileID, name.c_str(), NX_FLOAT64, 2, dims_array,m_nexuscompression,asize); NXopendata(fileID, name.c_str()); start[0]=0; for(size_t i=0;i<nSpect;i++) { int s = spec[i]; NXputslab(fileID, reinterpret_cast<void*>(const_cast<double*>(&(localworkspace->readE(s)[0]))),start,asize); start[0]++; } if(m_progress != 0) m_progress->reportIncrement(1, "Writing data"); // Fractional area for RebinnedOutput if (localworkspace->id() == "RebinnedOutput") { RebinnedOutput_const_sptr rebin_workspace = boost::dynamic_pointer_cast<const RebinnedOutput>(localworkspace); name="frac_area"; NXcompmakedata(fileID, name.c_str(), NX_FLOAT64, 2, dims_array,m_nexuscompression,asize); NXopendata(fileID, name.c_str()); start[0]=0; for(size_t i=0;i<nSpect;i++) { int s = spec[i]; NXputslab(fileID, reinterpret_cast<void*>(const_cast<double*>(&(rebin_workspace->readF(s)[0]))), start, asize); start[0]++; } if(m_progress != 0) m_progress->reportIncrement(1, "Writing data"); } NXclosedata(fileID); } // write X data, as single array or all values if "ragged" if(uniformSpectra) { dims_array[0]=static_cast<int>(localworkspace->readX(0).size()); NXmakedata(fileID, "axis1", NX_FLOAT64, 1, dims_array); NXopendata(fileID, "axis1"); NXputdata(fileID, reinterpret_cast<void*>(const_cast<double*>(&(localworkspace->readX(0)[0])))); } else { dims_array[0]=static_cast<int>(nSpect); dims_array[1]=static_cast<int>(localworkspace->readX(0).size()); NXmakedata(fileID, "axis1", NX_FLOAT64, 2, dims_array); NXopendata(fileID, "axis1"); start[0]=0; asize[1]=dims_array[1]; for(size_t i=0;i<nSpect;i++) { NXputslab(fileID, reinterpret_cast<void*>(const_cast<double*>(&(localworkspace->readX(i)[0]))),start,asize); start[0]++; } } std::string dist=(localworkspace->isDistribution()) ? "1" : "0"; NXputattr(fileID, "distribution", reinterpret_cast<void*>(const_cast<char*>(dist.c_str())), 2, NX_CHAR); NXputattr (fileID, "units", reinterpret_cast<void*>(const_cast<char*>(xLabel.c_str())), static_cast<int>(xLabel.size()), NX_CHAR); auto label = boost::dynamic_pointer_cast<Mantid::Kernel::Units::Label>(xAxis->unit()); if(label) { NXputattr (fileID, "caption", reinterpret_cast<void*>(const_cast<char*>(label->caption().c_str())), static_cast<int>(label->caption().size()), NX_CHAR); auto unitLbl = label->label(); NXputattr (fileID, "label", reinterpret_cast<void*>(const_cast<char*>(unitLbl.ascii().c_str())), static_cast<int>(unitLbl.ascii().size()), NX_CHAR); } NXclosedata(fileID); if ( ! sAxis->isText() ) { // write axis2, maybe just spectra number dims_array[0]=static_cast<int>(axis2.size()); NXmakedata(fileID, "axis2", NX_FLOAT64, 1, dims_array); NXopendata(fileID, "axis2"); NXputdata(fileID, (void*)&(axis2[0])); NXputattr (fileID, "units", reinterpret_cast<void*>(const_cast<char*>(sLabel.c_str())), static_cast<int>(sLabel.size()), NX_CHAR); auto label = boost::dynamic_pointer_cast<Mantid::Kernel::Units::Label>(sAxis->unit()); if(label) { NXputattr (fileID, "caption", reinterpret_cast<void*>(const_cast<char*>(label->caption().c_str())), static_cast<int>(label->caption().size()), NX_CHAR); auto unitLbl = label->label(); NXputattr (fileID, "label", reinterpret_cast<void*>(const_cast<char*>(unitLbl.ascii().c_str())), static_cast<int>(unitLbl.ascii().size()), NX_CHAR); } NXclosedata(fileID); } else { std::string textAxis; for ( size_t i = 0; i < sAxis->length(); i ++ ) { std::string label = sAxis->label(i); textAxis += label + "\n"; } dims_array[0] = static_cast<int>(textAxis.size()); NXmakedata(fileID, "axis2", NX_CHAR, 2, dims_array); NXopendata(fileID, "axis2"); NXputdata(fileID, reinterpret_cast<void*>(const_cast<char*>(textAxis.c_str()))); NXputattr (fileID, "units", reinterpret_cast<void*>(const_cast<char*>("TextAxis")), 8, NX_CHAR); auto label = boost::dynamic_pointer_cast<Mantid::Kernel::Units::Label>(sAxis->unit()); if(label) { NXputattr (fileID, "caption", reinterpret_cast<void*>(const_cast<char*>(label->caption().c_str())), static_cast<int>(label->caption().size()), NX_CHAR); auto unitLbl = label->label(); NXputattr (fileID, "label", reinterpret_cast<void*>(const_cast<char*>(unitLbl.ascii().c_str())), static_cast<int>(unitLbl.ascii().size()), NX_CHAR); } NXclosedata(fileID); } writeNexusBinMasking(localworkspace); status=NXclosegroup(fileID); return((status==NX_ERROR)?3:0); }
/** Write out a table Workspace's */ int NexusFileIO::writeNexusTableWorkspace( const API::ITableWorkspace_const_sptr& itableworkspace, const char * group_name) const { NXstatus status = 0; boost::shared_ptr<const TableWorkspace> tableworkspace = boost::dynamic_pointer_cast<const TableWorkspace>(itableworkspace); boost::shared_ptr<const PeaksWorkspace> peakworkspace = boost::dynamic_pointer_cast<const PeaksWorkspace>(itableworkspace); if ( !tableworkspace && !peakworkspace ) return((status==NX_ERROR)?3:0); //write data entry status=NXmakegroup(fileID,group_name,"NXdata"); if(status==NX_ERROR) return(2); NXopengroup(fileID,group_name,"NXdata"); int nRows = static_cast<int>(itableworkspace->rowCount()); int dims_array[1] = { nRows }; for (size_t i = 0; i < itableworkspace->columnCount(); i++) { Column_const_sptr col = itableworkspace->getColumn(i); std::string str = "column_" + boost::lexical_cast<std::string>(i+1); if ( col->isType<double>() ) { double * toNexus = new double[nRows]; for (int ii = 0; ii < nRows; ii++) toNexus[ii] = col->cell<double>(ii); NXwritedata(str.c_str(), NX_FLOAT64, 1, dims_array, (void *)(toNexus), false); delete[] toNexus; // attributes NXopendata(fileID, str.c_str()); std::string units = "Not known"; std::string interpret_as = "A double"; NXputattr(fileID, "units", reinterpret_cast<void*>(const_cast<char*>(units.c_str())), static_cast<int>(units.size()), NX_CHAR); NXputattr(fileID, "interpret_as", reinterpret_cast<void*>(const_cast<char*>(interpret_as.c_str())), static_cast<int>(interpret_as.size()), NX_CHAR); NXclosedata(fileID); } else if ( col->isType<int>() ) { int * toNexus = new int[nRows]; for (int ii = 0; ii < nRows; ii++) toNexus[ii] = col->cell<int>(ii); NXwritedata(str.c_str(), NX_INT32, 1, dims_array, (void *)(toNexus), false); delete[] toNexus; // attributes NXopendata(fileID, str.c_str()); std::string units = "Not known"; std::string interpret_as = "An integer"; NXputattr(fileID, "units", reinterpret_cast<void*>(const_cast<char*>(units.c_str())), static_cast<int>(units.size()), NX_CHAR); NXputattr(fileID, "interpret_as", reinterpret_cast<void*>(const_cast<char*>(interpret_as.c_str())), static_cast<int>(interpret_as.size()), NX_CHAR); NXclosedata(fileID); } else if ( col->isType<std::string>() ) { // determine max string size size_t maxStr = 0; for (int ii = 0; ii < nRows; ii++) { if ( col->cell<std::string>(ii).size() > maxStr) maxStr = col->cell<std::string>(ii).size(); } int dims_array[2] = { nRows, static_cast<int>(maxStr) }; int asize[2]={1,dims_array[1]}; NXcompmakedata(fileID, str.c_str(), NX_CHAR, 2, dims_array,false,asize); NXopendata(fileID, str.c_str()); char* toNexus = new char[maxStr*nRows]; for(int ii = 0; ii < nRows; ii++) { std::string rowStr = col->cell<std::string>(ii); for (size_t ic = 0; ic < rowStr.size(); ic++) toNexus[ii*maxStr+ic] = rowStr[ic]; for (size_t ic = rowStr.size(); ic < static_cast<size_t>(maxStr); ic++) toNexus[ii*maxStr+ic] = ' '; } NXputdata(fileID, (void *)(toNexus)); delete[] toNexus; // attributes std::string units = "N/A"; std::string interpret_as = "A string"; NXputattr(fileID, "units", reinterpret_cast<void*>(const_cast<char*>(units.c_str())), static_cast<int>(units.size()), NX_CHAR); NXputattr(fileID, "interpret_as", reinterpret_cast<void*>(const_cast<char*>(interpret_as.c_str())), static_cast<int>(interpret_as.size()), NX_CHAR); NXclosedata(fileID); } #define IF_VECTOR_COLUMN(Type, NexusType) \ else if ( col->isType< std::vector<Type> >() ) \ { \ auto vecCol = boost::dynamic_pointer_cast< const VectorColumn<Type> >(col); \ writeNexusVectorColumn<Type>(vecCol, str, NexusType, #Type); \ } IF_VECTOR_COLUMN(int,NX_INT32) IF_VECTOR_COLUMN(double,NX_FLOAT64) // write out title NXopendata(fileID, str.c_str()); NXputattr(fileID, "name", reinterpret_cast<void*>(const_cast<char*>(col->name().c_str())), static_cast<int>(col->name().size()), NX_CHAR); NXclosedata(fileID); } status=NXclosegroup(fileID); return((status==NX_ERROR)?3:0); }
int NexusFileIO::getWorkspaceSize( int& numberOfSpectra, int& numberOfChannels, int& numberOfXpoints , bool& uniformBounds, std::string& axesUnits, std::string& yUnits ) const { NXstatus status; //open workspace group status=NXopengroup(fileID,"workspace","NXdata"); if(status==NX_ERROR) return(1); // open "values" data which is identified by attribute "signal", if it exists std::string entry; if(checkEntryAtLevelByAttribute("signal", entry)) status=NXopendata(fileID, entry.c_str()); else { status=NXclosegroup(fileID); return(2); } if(status==NX_ERROR) { status=NXclosegroup(fileID); return(2); } // read workspace data size int rank,dim[2],type; status=NXgetinfo(fileID, &rank, dim, &type); if(status==NX_ERROR) return(3); numberOfSpectra=dim[0]; numberOfChannels=dim[1]; // get axes attribute char sbuf[NX_MAXNAMELEN]; int len=NX_MAXNAMELEN; type=NX_CHAR; if(checkAttributeName("units")) { status=NXgetattr(fileID,const_cast<char*>("units"),(void *)sbuf,&len,&type); if(status!=NX_ERROR) yUnits=sbuf; NXclosedata(fileID); } // // read axis1 size status=NXopendata(fileID,"axis1"); if(status==NX_ERROR) return(4); len=NX_MAXNAMELEN; type=NX_CHAR; NXgetattr(fileID,const_cast<char*>("units"),(void *)sbuf,&len,&type); axesUnits = std::string(sbuf,len); NXgetinfo(fileID, &rank, dim, &type); // non-uniform X has 2D axis1 data if(rank==1) { numberOfXpoints=dim[0]; uniformBounds=true; } else { numberOfXpoints=dim[1]; uniformBounds=false; } NXclosedata(fileID); NXopendata(fileID,"axis2"); len=NX_MAXNAMELEN; type=NX_CHAR; NXgetattr(fileID,const_cast<char*>("units"),(void *)sbuf,&len,&type); axesUnits += std::string(":") + std::string(sbuf,len); NXclosedata(fileID); NXclosegroup(fileID); return(0); }
/** Write out an event list into an already-opened group * @param el :: reference to the EventList to write. * @param group_name :: group_name to create. * */ int NexusFileIO::writeEventList( const DataObjects::EventList & el, std::string group_name) const { //write data entry NXstatus status=NXmakegroup(fileID, group_name.c_str(), "NXdata"); if(status==NX_ERROR) return(2); NXopengroup(fileID, group_name.c_str(), "NXdata"); // Copy the detector IDs to an array. const std::set<detid_t>& dets = el.getDetectorIDs(); // Write out the detector IDs if (!dets.empty()) { std::vector<detid_t> detectorIDs(dets.begin(),dets.end()); int dims_array[1]; NXwritedata("detector_IDs", NX_INT64, 1, dims_array, (void*)(detectorIDs.data()), false ); } std::string eventType("UNKNOWN"); size_t num = el.getNumberEvents(); switch (el.getEventType()) { case TOF: eventType = "TOF"; writeEventListData( el.getEvents(), true, true, false, false ); break; case WEIGHTED: eventType = "WEIGHTED"; writeEventListData( el.getWeightedEvents(), true, true, true, true ); break; case WEIGHTED_NOTIME: eventType = "WEIGHTED_NOTIME"; writeEventListData( el.getWeightedEventsNoTime(), true, false, true, true ); break; } // --- Save the type of sorting ----- std::string sortType; switch (el.getSortType()) { case TOF_SORT: sortType = "TOF_SORT"; break; case PULSETIME_SORT: sortType = "PULSETIME_SORT"; break; case UNSORTED: default: sortType = "UNSORTED"; break; } NXputattr (fileID, "sort_type", reinterpret_cast<void*>(const_cast<char*>(sortType.c_str())), static_cast<int>(sortType.size()), NX_CHAR); // Save an attribute with the type of each event. NXputattr (fileID, "event_type", reinterpret_cast<void*>(const_cast<char*>(eventType.c_str())), static_cast<int>(eventType.size()), NX_CHAR); // Save an attribute with the number of events NXputattr (fileID, "num_events", (void*)(&num), 1, NX_INT64); // Close it up! status=NXclosegroup(fileID); return((status==NX_ERROR)?3:0); }
int NDFileNexus::processNode(TiXmlNode *curNode, NDArray *pArray) { int status = 0; const char *nodeName; const char *nodeValue; const char *nodeOuttype; const char *nodeSource; const char *nodeType; //float data; int rank; NDDataType_t type; int ii; int dims[ND_ARRAY_MAX_DIMS]; int numCapture; int fileWriteMode; NDAttrDataType_t attrDataType; NDAttribute *pAttr; size_t attrDataSize; size_t nodeTextLen; int wordSize; int dataOutType=NDInt8; size_t numWords; int numItems = 0; int addr =0; void *pValue; char nodeText[256]; NXname dataclass; NXname dPath; static const char *functionName = "processNode"; asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW, "Entering %s:%s\n", driverName, functionName ); /* Must lock when accessing parameter library */ this->lock(); getIntegerParam(addr, NDFileWriteMode, &fileWriteMode); getIntegerParam(addr, NDFileNumCapture, &numCapture); this->unlock(); nodeValue = curNode->Value(); asynPrint(this->pasynUserSelf, ASYN_TRACEIO_DRIVER, "%s:%s Value=%s Type=%d\n", driverName, functionName, curNode->Value(), curNode->Type()); nodeType = curNode->ToElement()->Attribute("type"); NXstatus stat; if (strcmp (nodeValue, "NXroot") == 0) { this->iterateNodes(curNode, pArray); } /* only include all the NeXus base classes */ else if ((strcmp (nodeValue, "NXentry") ==0) || (strcmp (nodeValue, "NXinstrument") ==0) || (strcmp (nodeValue, "NXsample") ==0) || (strcmp (nodeValue, "NXmonitor") ==0) || (strcmp (nodeValue, "NXsource") ==0) || (strcmp (nodeValue, "NXuser") ==0) || (strcmp (nodeValue, "NXdata") ==0) || (strcmp (nodeValue, "NXdetector") ==0) || (strcmp (nodeValue, "NXaperature") ==0) || (strcmp (nodeValue, "NXattenuator") ==0) || (strcmp (nodeValue, "NXbeam_stop") ==0) || (strcmp (nodeValue, "NXbending_magnet") ==0) || (strcmp (nodeValue, "NXcollimator") ==0) || (strcmp (nodeValue, "NXcrystal") ==0) || (strcmp (nodeValue, "NXdisk_chopper") ==0) || (strcmp (nodeValue, "NXfermi_chopper") ==0) || (strcmp (nodeValue, "NXfilter") ==0) || (strcmp (nodeValue, "NXflipper") ==0) || (strcmp (nodeValue, "NXguide") ==0) || (strcmp (nodeValue, "NXinsertion_device") ==0) || (strcmp (nodeValue, "NXmirror") ==0) || (strcmp (nodeValue, "NXmoderator") ==0) || (strcmp (nodeValue, "NXmonochromator") ==0) || (strcmp (nodeValue, "NXpolarizer") ==0) || (strcmp (nodeValue, "NXpositioner") ==0) || (strcmp (nodeValue, "NXvelocity_selector") ==0) || (strcmp (nodeValue, "NXevent_data") ==0) || (strcmp (nodeValue, "NXprocess") ==0) || (strcmp (nodeValue, "NXcharacterization") ==0) || (strcmp (nodeValue, "NXlog") ==0) || (strcmp (nodeValue, "NXnote") ==0) || (strcmp (nodeValue, "NXbeam") ==0) || (strcmp (nodeValue, "NXgeometry") ==0) || (strcmp (nodeValue, "NXtranslation") ==0) || (strcmp (nodeValue, "NXshape") ==0) || (strcmp (nodeValue, "NXorientation") ==0) || (strcmp (nodeValue, "NXenvironment") ==0) || (strcmp (nodeValue, "NXsensor") ==0) || (strcmp (nodeValue, "NXcapillary") ==0) || (strcmp (nodeValue, "NXcollection") ==0) || (strcmp (nodeValue, "NXdetector_group") ==0) || (strcmp (nodeValue, "NXparameters") ==0) || (strcmp (nodeValue, "NXsubentry") ==0) || (strcmp (nodeValue, "NXxraylens") ==0) || (nodeType && strcmp (nodeType, "UserGroup") == 0) ) { nodeName = curNode->ToElement()->Attribute("name"); if (nodeName == NULL) { nodeName = nodeValue; } stat = NXmakegroup(this->nxFileHandle, (const char *)nodeName, (const char *)nodeValue); stat |= NXopengroup(this->nxFileHandle, (const char *)nodeName, (const char *)nodeValue); if (stat != NX_OK ) { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s Error creating group %s %s\n", driverName, functionName, nodeName, nodeValue); } this->iterateNodes(curNode, pArray); stat = NXclosegroup(this->nxFileHandle); if (stat != NX_OK ) { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s Error closing group %s %s\n", driverName, functionName, nodeName, nodeValue); } } else if (strcmp (nodeValue, "Attr") ==0) { nodeName = curNode->ToElement()->Attribute("name"); nodeSource = curNode->ToElement()->Attribute("source"); if (nodeType && strcmp(nodeType, "ND_ATTR") == 0 ) { pAttr = this->pFileAttributes->find(nodeSource); if (pAttr != NULL ){ pAttr->getValueInfo(&attrDataType, &attrDataSize); this->getAttrTypeNSize(pAttr, &dataOutType, &wordSize); if (dataOutType > 0) { pValue = calloc( attrDataSize, wordSize ); pAttr->getValue(attrDataType, (char *)pValue, attrDataSize*wordSize); NXputattr(this->nxFileHandle, nodeName, pValue, (int)(attrDataSize/wordSize), dataOutType); free(pValue); } } else { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s Could not find attribute named %s\n", driverName, functionName, nodeSource); } } else if (nodeType && strcmp(nodeType, "CONST") == 0 ) { this->findConstText( curNode, nodeText); nodeOuttype = curNode->ToElement()->Attribute("outtype"); if (nodeOuttype == NULL){ nodeOuttype = "NX_CHAR"; } dataOutType = this->typeStringToVal((const char *)nodeOuttype); if ( dataOutType == NX_CHAR ) { nodeTextLen = strlen(nodeText); } else { nodeTextLen = 1; } pValue = allocConstValue( dataOutType, nodeTextLen); constTextToDataType(nodeText, dataOutType, pValue); NXputattr(this->nxFileHandle, nodeName, pValue, (int)nodeTextLen, dataOutType); free(pValue); } else if (nodeType) { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s Node type %s for node %s is invalid\n", driverName, functionName, nodeType, nodeValue); } } else { nodeSource = curNode->ToElement()->Attribute("source"); if (nodeType && strcmp(nodeType, "ND_ATTR") == 0 ) { pAttr = this->pFileAttributes->find(nodeSource); if ( pAttr != NULL) { pAttr->getValueInfo(&attrDataType, &attrDataSize); this->getAttrTypeNSize(pAttr, &dataOutType, &wordSize); if (dataOutType > 0) { pValue = calloc( attrDataSize, wordSize ); pAttr->getValue(attrDataType, (char *)pValue, attrDataSize); numWords = attrDataSize/wordSize; NXmakedata( this->nxFileHandle, nodeValue, dataOutType, 1, (int *)&(numWords)); NXopendata(this->nxFileHandle, nodeValue); NXputdata(this->nxFileHandle, (char *)pValue); free(pValue); this->iterateNodes(curNode, pArray); NXclosedata(this->nxFileHandle); } } else { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s Could not add node %s could not find an attribute by that name\n", driverName, functionName, nodeSource); } } else if (nodeType && strcmp(nodeType, "pArray") == 0 ){ rank = pArray->ndims; type = pArray->dataType; for (ii=0; ii<rank; ii++) { dims[(rank-1) - ii] = (int)pArray->dims[ii].size; } switch(type) { case NDInt8: dataOutType = NX_INT8; wordSize = 1; break; case NDUInt8: dataOutType = NX_UINT8; wordSize = 1; break; case NDInt16: dataOutType = NX_INT16; wordSize = 2; break; case NDUInt16: dataOutType = NX_UINT16; wordSize = 2; break; case NDInt32: dataOutType = NX_INT32; wordSize = 4; break; case NDUInt32: dataOutType = NX_UINT32; wordSize = 4; break; case NDFloat32: dataOutType = NX_FLOAT32; wordSize = 4; break; case NDFloat64: dataOutType = NX_FLOAT64; wordSize = 8; break; } asynPrint(this->pasynUserSelf, ASYN_TRACEIO_DRIVER, "%s:%s Starting to write data making group\n", driverName, functionName ); if ( fileWriteMode == NDFileModeSingle ) { NXmakedata( this->nxFileHandle, nodeValue, dataOutType, rank, dims); } else if ((fileWriteMode == NDFileModeCapture) || (fileWriteMode == NDFileModeStream)) { for (ii = 0; ii < rank; ii++) { dims[(rank) - ii] = dims[(rank-1) - ii]; } rank = rank +1; dims[0] = numCapture; NXmakedata( this->nxFileHandle, nodeValue, dataOutType, rank, dims); } dPath[0] = '\0'; dataclass[0] = '\0'; NXopendata(this->nxFileHandle, nodeValue); // If you are having problems with NXgetgroupinfo in Visual Studio, // Checkout this link: http://trac.nexusformat.org/code/ticket/217 // Fixed in Nexus 4.2.1 //printf("%s:%s: calling NXgetgroupinfo!\n", driverName, functionName); NXgetgroupinfo(this->nxFileHandle, &numItems, dPath, dataclass); //printf("dPath=%s, nodeValue=%s\n", dPath, nodeValue ); sprintf(this->dataName, "%s", nodeValue); sprintf(this->dataPath, "%c%s", '/', dPath); this->iterateNodes(curNode, pArray); NXclosedata(this->nxFileHandle); } else if (nodeType && strcmp(nodeType, "CONST") == 0 ){ this->findConstText( curNode, nodeText); nodeOuttype = curNode->ToElement()->Attribute("outtype"); if (nodeOuttype == NULL){ nodeOuttype = "NX_CHAR"; } dataOutType = this->typeStringToVal(nodeOuttype); if ( dataOutType == NX_CHAR ) { nodeTextLen = strlen(nodeText); } else { nodeTextLen = 1; } pValue = allocConstValue( dataOutType, nodeTextLen); constTextToDataType(nodeText, dataOutType, pValue); NXmakedata( this->nxFileHandle, nodeValue, dataOutType, 1, (int *)&nodeTextLen); NXopendata(this->nxFileHandle, nodeValue); NXputdata(this->nxFileHandle, pValue); free(pValue); this->iterateNodes(curNode, pArray); NXclosedata(this->nxFileHandle); } else if (nodeType) { asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s Node type %s for node %s is invalid\n", driverName, functionName, nodeType, nodeValue); } else { this->findConstText( curNode, nodeText); dataOutType = NX_CHAR; nodeTextLen = strlen(nodeText); if (nodeTextLen == 0) { sprintf(nodeText, "LEFT BLANK"); nodeTextLen = strlen(nodeText); } pValue = allocConstValue( dataOutType, nodeTextLen); constTextToDataType(nodeText, dataOutType, pValue); NXmakedata( this->nxFileHandle, nodeValue, dataOutType, 1, (int *)&nodeTextLen); NXopendata(this->nxFileHandle, nodeValue); NXputdata(this->nxFileHandle, pValue); this->iterateNodes(curNode, pArray); NXclosedata(this->nxFileHandle); } } asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW, "Leaving %s:%s\n", driverName, functionName ); return (status); }
void SaveISISNexus::detector_1() { NXmakegroup(handle, "detector_1", "NXdata"); NXopengroup(handle, "detector_1", "NXdata"); for (int i = 0; i < nmon; ++i) { int si = int(std::distance( m_isisRaw->spec, std::find(m_isisRaw->spec, m_isisRaw->spec + nsp, m_isisRaw->mdet[i]))); monitor_index[si] = i; } // write counts int dim[3]; dim[0] = nper; dim[1] = nsp - nmon; dim[2] = ntc; NXmakedata(handle, "counts", NX_INT32, 3, dim); NXopendata(handle, "counts"); putAttr("units", "counts"); putAttr("signal", 1); putAttr("axes", "period_index,spectrum_index,time_of_flight"); int size[] = {1, 1, ntc}; int index = 0; for (int p = 0; p < nper; ++p) { int ispec = 0; m_isisRaw->skipData(rawFile, index++); for (int si = 0; si < nsp; ++si) { if (monitor_index.find(si) != monitor_index.end()) { m_isisRaw->readData(rawFile, index); monitorData.insert(monitorData.end(), m_isisRaw->dat1 + 1, m_isisRaw->dat1 + ntc + 1); } else { m_isisRaw->readData(rawFile, index); int start[] = {p, ispec, 0}; NXputslab(handle, m_isisRaw->dat1 + 1, start, size); ++ispec; } ++index; } } NXgetdataID(handle, &counts_link); NXclosedata(handle); NXmakelink(handle, &period_index_link); std::vector<int> spec_minus_monitors(nsp - nmon); std::generate(spec_minus_monitors.begin(), spec_minus_monitors.end(), getWithoutMonitors<int>(this, m_isisRaw->spec)); saveIntOpen("spectrum_index", &spec_minus_monitors[0], nsp - nmon); NXgetdataID(handle, &spectrum_index_link); close(); NXmakelink(handle, &time_of_flight_link); NXmakelink(handle, &time_of_flight_raw_link); std::vector<float> float_vec(ndet - nmon); std::generate(float_vec.begin(), float_vec.end(), getWithoutMonitors<float>(this, m_isisRaw->delt)); saveFloat("delt", &float_vec[0], ndet - nmon); saveFloat("source_detector_distance", &m_isisRaw->ivpb.i_sddist, 1); // using the same float_vec, size unchanged ndet-nmon std::generate(float_vec.begin(), float_vec.end(), getWithoutMonitors<float>(this, m_isisRaw->len2)); saveFloatOpen("distance", &float_vec[0], ndet - nmon); putAttr("units", "metre"); close(); // using the same float_vec, size unchanged ndet-nmon std::generate(float_vec.begin(), float_vec.end(), getWithoutMonitors<float>(this, m_isisRaw->tthe)); saveFloatOpen("polar_angle", &float_vec[0], ndet - nmon); putAttr("units", "degree"); close(); NXclosegroup(handle); }
/** * Recursively add properties from a nexus file to * the workspace run. * * @param nxfileID :: Nexus file handle to be parsed, just after an NXopengroup * @param runDetails :: where to add properties * @param parent_name :: nexus caller name * @param parent_class :: nexus caller class * @param level :: current level in nexus tree * */ void LoadHelper::recurseAndAddNexusFieldsToWsRun(NXhandle nxfileID, API::Run& runDetails, std::string& parent_name, std::string& parent_class, int level) { std::string indent_str(level * 2, ' '); // Two space by indent level // Link ? // Attributes ? // Classes NXstatus getnextentry_status; ///< return status int datatype; ///< NX data type if a dataset, e.g. NX_CHAR, NX_FLOAT32, see napi.h char nxname[NX_MAXNAMELEN], nxclass[NX_MAXNAMELEN]; nxname[0] = '0'; nxclass[0] = '0'; bool has_entry = true; // follows getnextentry_status while (has_entry) { getnextentry_status = NXgetnextentry(nxfileID, nxname, nxclass, &datatype); if (getnextentry_status == NX_OK) { g_log.debug() << indent_str << parent_name << "." << nxname << " ; " << nxclass << std::endl; NXstatus opengroup_status; NXstatus opendata_status; if ((opengroup_status = NXopengroup(nxfileID, nxname, nxclass)) == NX_OK) { // Go down to one level std::string p_nxname(nxname); //current names can be useful for next level std::string p_nxclass(nxclass); recurseAndAddNexusFieldsToWsRun(nxfileID, runDetails, p_nxname, p_nxclass, level + 1); NXclosegroup(nxfileID); } // if(NXopengroup else if ((opendata_status = NXopendata(nxfileID, nxname)) == NX_OK) { //dump_attributes(nxfileID, indent_str); g_log.debug() << indent_str << nxname << " opened." << std::endl; if (parent_class == "NXData" || parent_class == "NXMonitor" || std::string(nxname) == "data") { g_log.debug() << indent_str << "skipping " << parent_class << " (" << nxname << ")" << std::endl; /* nothing */ } else { // create a property int rank; int dims[4]; int type; dims[0] = dims[1] = dims[2] = dims[3] = 0; std::string property_name = (parent_name.empty() ? nxname : parent_name + "." + nxname); g_log.debug() << indent_str << "considering property " << property_name << std::endl; // Get the value NXgetinfo(nxfileID, &rank, dims, &type); // Note, we choose to only build properties on small float arrays // filter logic is below bool build_small_float_array = false; // default if ((type == NX_FLOAT32) || (type == NX_FLOAT64)) { if ((rank == 1) && (dims[0] <= 9)) { build_small_float_array = true; } else { g_log.debug() << indent_str << "ignored multi dimension float data on " << property_name << std::endl; } } else if (type != NX_CHAR) { if ((rank != 1) || (dims[0] != 1) || (dims[1] != 1) || (dims[2] != 1) || (dims[3] != 1)) { g_log.debug() << indent_str << "ignored multi dimension data on " << property_name << std::endl; } } void *dataBuffer; NXmalloc(&dataBuffer, rank, dims, type); if (NXgetdata(nxfileID, dataBuffer) != NX_OK) { NXfree(&dataBuffer); throw std::runtime_error("Cannot read data from NeXus file"); } if (type == NX_CHAR) { std::string property_value((const char *) dataBuffer); if (boost::algorithm::ends_with(property_name, "_time")) { // That's a time value! Convert to Mantid standard property_value = dateTimeInIsoFormat(property_value); } runDetails.addProperty(property_name, property_value); } else if ((type == NX_FLOAT32) || (type == NX_FLOAT64) || (type == NX_INT16) || (type == NX_INT32) || (type == NX_UINT16)) { // Look for "units" NXstatus units_status; char units_sbuf[NX_MAXNAMELEN]; int units_len = NX_MAXNAMELEN; int units_type = NX_CHAR; units_status = NXgetattr(nxfileID, const_cast<char*>("units"), (void *) units_sbuf, &units_len, &units_type); if (units_status != NX_ERROR) { g_log.debug() << indent_str << "[ " << property_name << " has unit " << units_sbuf << " ]" << std::endl; } if ((type == NX_FLOAT32) || (type == NX_FLOAT64)) { // Mantid numerical properties are double only. double property_double_value = 0.0; // Simple case, one value if (dims[0] == 1) { if (type == NX_FLOAT32) { property_double_value = *((float*) dataBuffer); } else if (type == NX_FLOAT64) { property_double_value = *((double*) dataBuffer); } if (units_status != NX_ERROR) runDetails.addProperty(property_name, property_double_value, std::string(units_sbuf)); else runDetails.addProperty(property_name, property_double_value); } else if (build_small_float_array) { // An array, converted to "name_index", with index < 10 (see test above) for (int dim_index = 0; dim_index < dims[0]; dim_index++) { if (type == NX_FLOAT32) { property_double_value = ((float*) dataBuffer)[dim_index]; } else if (type == NX_FLOAT64) { property_double_value = ((double*) dataBuffer)[dim_index]; } std::string indexed_property_name = property_name + std::string("_") + boost::lexical_cast<std::string>(dim_index); if (units_status != NX_ERROR) runDetails.addProperty(indexed_property_name, property_double_value, std::string(units_sbuf)); else runDetails.addProperty(indexed_property_name, property_double_value); } } } else { // int case int property_int_value = 0; if (type == NX_INT16) { property_int_value = *((short int*) dataBuffer); } else if (type == NX_INT32) { property_int_value = *((int*) dataBuffer); } else if (type == NX_UINT16) { property_int_value = *((short unsigned int*) dataBuffer); } if (units_status != NX_ERROR) runDetails.addProperty(property_name, property_int_value, std::string(units_sbuf)); else runDetails.addProperty(property_name, property_int_value); } // if (type==... } else { g_log.debug() << indent_str << "unexpected data on " << property_name << std::endl; } // test on nxdata type NXfree(&dataBuffer); dataBuffer = NULL; } // if (parent_class == "NXData" || parent_class == "NXMonitor") else NXclosedata(nxfileID); } else { g_log.debug() << indent_str << "unexpected status (" << opendata_status << ") on " << nxname << std::endl; } } else if (getnextentry_status == NX_EOD) { g_log.debug() << indent_str << "End of Dir" << std::endl; has_entry = false; // end of loop } else { g_log.debug() << indent_str << "unexpected status (" << getnextentry_status << ")" << std::endl; has_entry = false; // end of loop } } // while } // recurseAndAddNexusFieldsToWsRun
/// Write isis_vms_compat void SaveISISNexus::write_isis_vms_compat() { NXmakegroup(handle, "isis_vms_compat", "IXvms"); NXopengroup(handle, "isis_vms_compat", "IXvms"); int ndet = m_isisRaw->i_det; int nmon = m_isisRaw->i_mon; saveInt("ADD", &m_isisRaw->add, 9); saveInt("CODE", m_isisRaw->code, ndet); saveInt("CRAT", m_isisRaw->crat, ndet); write_rpb(); write_spb(); write_vpb(); saveInt("DAEP", &m_isisRaw->daep, 64); saveInt("DELT", m_isisRaw->delt, ndet); saveInt("FORM", &m_isisRaw->data_format); saveChar("HDR", &m_isisRaw->hdr, 80); saveFloat("LEN2", m_isisRaw->len2, ndet); saveInt("MDET", m_isisRaw->mdet, nmon); saveInt("MODN", m_isisRaw->modn, ndet); saveInt("MONP", m_isisRaw->monp, nmon); saveInt("MPOS", m_isisRaw->mpos, ndet); saveChar("NAME", m_isisRaw->i_inst, 8); saveInt("NDET", &ndet); saveInt("NFPP", &m_isisRaw->t_nfpp); saveInt("NMON", &nmon); saveInt("NPER", &m_isisRaw->t_nper); saveInt("NSER", &m_isisRaw->e_nse); saveInt("NSP1", &m_isisRaw->t_nsp1); saveInt("NTC1", &m_isisRaw->t_ntc1); saveInt("NTRG", &m_isisRaw->t_ntrg); saveInt("NUSE", &m_isisRaw->i_use); saveInt("PMAP", &m_isisRaw->t_pmap, 256); saveInt("PRE1", &m_isisRaw->t_pre1); saveInt("RUN", &m_isisRaw->r_number); saveInt("SPEC", m_isisRaw->spec, ndet); saveInt("TCM1", &m_isisRaw->t_tcm1); saveFloat("TCP1", m_isisRaw->t_tcp1, 20); saveInt("TIMR", m_isisRaw->timr, ndet); saveChar("TITL", m_isisRaw->r_title, 80); saveFloat("TTHE", m_isisRaw->tthe, ndet); saveInt("UDET", m_isisRaw->udet, ndet); saveInt("ULEN", &m_isisRaw->u_len); std::string user_info(160, ' '); if (m_isisRaw->u_len > 0) { std::copy(reinterpret_cast<char *>(&m_isisRaw->user), reinterpret_cast<char *>(&m_isisRaw->user) + m_isisRaw->u_len, user_info.begin()); } saveString("USER", user_info); saveInt("VER1", &m_isisRaw->frmt_ver_no); saveInt("VER2", &m_isisRaw->ver2); saveInt("VER3", &m_isisRaw->ver3); saveInt("VER4", &m_isisRaw->ver4); saveInt("VER5", &m_isisRaw->ver5); saveInt("VER6", &m_isisRaw->ver6); saveInt("VER7", &m_isisRaw->ver7); saveInt("VER8", &m_isisRaw->ver8); int tmp_int(0); saveInt("VER9", &tmp_int); int n = m_isisRaw->logsect.nlines; log_notes.resize(n); for (int i = 0; i < n; ++i) { log_notes[i].assign(m_isisRaw->logsect.lines[i].data, m_isisRaw->logsect.lines[i].len); } int ll = saveStringVectorOpen("NOTE", log_notes); saveInt("NTNL", &n); saveInt("NTLL", &ll); NXclosegroup(handle); // isis_vms_compat }
int main(int argc, char *argv[]) { char fileName[256], oldwd[256], *command, *dimensions, *stringPtr; char prompt[512]; char *inputText; NXname dataName; int status; #if HAVE_LIBREADLINE rl_readline_name = "NXbrowse"; rl_attempted_completion_function = nxbrowse_complete; #if READLINE_VERSION >= 0x500 rl_catch_signals = 0; #else #define rl_crlf() fprintf(rl_outstream, "\r\n"); #define rl_on_new_line() 1 #endif using_history(); #else #define rl_crlf() #define rl_on_new_line() #define add_history(a) #endif printf("NXBrowse %s Copyright (C) 2009-2014 NeXus Data Format\n", NEXUS_VERSION); #if HAVE_LIBREADLINE printf ("Built with readline support - use <TAB> to complete commands and paths\n"); #endif /* HAVE_LIBREADLINE */ /* if there is a filename given on the command line use that, else ask for a filename */ if (argc < 2) { printf("Give name of NeXus file : "); if (fgets(fileName, sizeof(fileName), stdin) == NULL) { printf("Failed to open %s\n", fileName); return NX_ERROR; } if ((stringPtr = strchr(fileName, '\n')) != NULL) *stringPtr = '\0'; } else { strcpy(fileName, argv[1]); } strcpy(nxFile, fileName); /* Open input file and output global attributes */ if (NXopen(fileName, NXACC_READ, &the_fileId) != NX_OK) { printf("NX_ERROR: Can't open %s\n", fileName); return NX_ERROR; } PrintAttributes(the_fileId); iByteAsChar = 0; /* Display remaining NX_INT8 and NX_UINT8 variables as integers by default */ /* Input commands until the EXIT command is given */ strcpy(oldwd, "/"); strcpy(path, "/"); do { sprintf(prompt, "NX%s> ", path); if (getenv("NO_READLINE") != NULL) { inputText = my_readline(prompt); } else { inputText = readline(prompt); } if (inputText == NULL) { inputText = strdup("EXIT"); } if (*inputText) { add_history(inputText); } command = strtok(inputText, " "); /* Check if a command has been given */ if (command == NULL) command = " "; /* Convert it to upper case characters */ ConvertUpperCase(command); if (StrEq(command, "PWD")) { fprintf(rl_outstream, "%s\n", path); } if (StrEq(command, "TEST")) { char a[256], b[256]; stringPtr = strtok(NULL, " "); if (stringPtr != NULL) { parsepath(stringPtr, a, b); fprintf(rl_outstream," you entered >%s< - i think the full path is >%s< and the final component looks like this >%s<.\n", stringPtr, a, b); } else { fprintf(rl_outstream," you entered nothing\n"); } } /* Command is to print a directory of the current group */ if (StrEq(command, "DIR") || StrEq(command, "LS")) { stringPtr = strtok(NULL, " "); if (stringPtr != NULL) { char a[256], b[256]; parsepath(stringPtr, a, b); strcat(a, "/"); strcat(a, b); NXopengrouppath(the_fileId, a); NXBdir(the_fileId); NXopengrouppath(the_fileId, path); } else { NXBdir(the_fileId); } } /* Command is to open the specified group */ if (StrEq(command, "OPEN") || StrEq(command, "CD")) { stringPtr = strtok(NULL, " "); if (stringPtr != NULL) { char a[256], b[256]; if (StrEq(stringPtr, "-")) { stringPtr = oldwd; } parsepath(stringPtr, a, b); strcat(a, "/"); strcat(a, b); status = NXopengrouppath(the_fileId, a); if (status == NX_OK) { strcpy(oldwd, path); strcpy(path, a); } else { fprintf(rl_outstream, "NX_ERROR: cannot change into %s\n", stringPtr); NXopengrouppath(the_fileId, path); /* to be sure */ } } else { fprintf(rl_outstream, "NX_ERROR: Specify a group\n"); } } /* Command is to dump data values to a file */ if (StrEq(command, "DUMP")) { stringPtr = strtok(NULL, " "); if (stringPtr != NULL) { strcpy(dataName, stringPtr); stringPtr = strtok(NULL, " "); if (stringPtr != NULL) { strcpy(fileName, stringPtr); status = NXBdump(the_fileId, dataName, fileName); } else { fprintf(rl_outstream, "NX_ERROR: Specify a dump file name \n"); } } else { fprintf(rl_outstream, "NX_ERROR: Specify a data item\n"); } } /* Command is to print the values of the data */ if (StrEq(command, "READ") || StrEq(command, "CAT")) { stringPtr = strtok(NULL, " ["); if (stringPtr != NULL) { strcpy(dataName, stringPtr); dimensions = strtok(NULL, "[]"); status = NXBread(the_fileId, dataName, dimensions); } else { fprintf(rl_outstream, "NX_ERROR: Specify a data item\n"); } } /* Command is to close the current group */ if (StrEq(command, "CLOSE")) { if (strlen(path) > 1) { if (NXclosegroup(the_fileId) == NX_OK) { /* Remove the group from the prompt string */ strcpy(oldwd, path); stringPtr = strrchr(path, '/'); /* position of last group delimiter */ if (stringPtr != NULL) *stringPtr = '\0'; /* terminate the string there */ } } else { fprintf(rl_outstream, "NX_WARNING: Already at root level of file\n"); } } /* Command is to print help information */ if (StrEq(command, "HELP") || StrEq(command, "INFO")) { printf("NXbrowse commands : DIR\n"); printf(" LS\n"); printf(" OPEN <groupName>\n"); printf(" CD <groupName>\n"); printf(" READ <dataName>\n"); printf(" READ <dataName>[<dimension indices...>]\n"); printf(" DUMP <dataName> <fileName> \n"); printf(" CLOSE\n"); printf(" BYTEASCHAR\n"); printf(" HELP\n"); printf(" EXIT\n"); printf("\n"); #if HAVE_LIBREADLINE printf("Pressing <TAB> after a command or partial nexus object name will complete\n"); printf("possible names. For example:\n"); printf("\n"); printf(" cd ent<TAB KEY PRESSED> # all items starting with ent are listed\n"); printf("\n"); #endif } /* Command is to print byte as char information */ if (StrEq(command, "BYTEASCHAR")) { if (iByteAsChar == 1) iByteAsChar = 0; else iByteAsChar = 1; } /* Command is to exit the program */ if (StrEq(command, "EXIT") || StrEq(command, "QUIT")) { /* for (i = groupLevel; i > 0; i--) NXclosegroup (the_fileId); */ NXclose(&the_fileId); return NX_OK; } status = NX_OK; free(inputText); } while (status == NX_OK); return NX_OK; }