void BulkReader::run() { m_stop = 0; unsigned char data[255]; while (load_atomic(m_stop) == 0) { // Blocked polling: The only problem with this is that we can't close // the device until the block is released, which means the controller // has to send more data //result = hid_read_timeout(m_pHidDevice, data, 255, -1); // This relieves that at the cost of higher CPU usage since we only // block for a short while (500ms) int transferred; int result; result = libusb_bulk_transfer(m_phandle, m_in_epaddr, data, sizeof(data), &transferred, 500); Trace timeout("BulkReader timeout"); if (result >= 0) { Trace process("BulkReader process packet"); //qDebug() << "Read" << result << "bytes, pointer:" << data; QByteArray outData((char*)data, transferred); emit(incomingData(outData, Time::elapsed())); } } qDebug() << "Stopped Reader"; }
SICALLBACK ToonixLighter_Evaluate( ICENodeContext& in_ctxt ) { // Get User Data TXLight* light = (TXLight*)(CValue::siPtrType)in_ctxt.GetUserData( ); // The current output port being evaluated... LONG out_portID = in_ctxt.GetEvaluatedOutputPortID( ); switch( out_portID ) { case ID_OUT_Vertices: { // Get the output port array ... CDataArray2DVector3f outData( in_ctxt ); CDataArray2DVector3f::Accessor outDataSubArray = outData.Resize(0,light->_nbv); for(ULONG n=0;n<light->_nbv;n++) { outDataSubArray[n].Set(light->_vertices[n].GetX(),light->_vertices[n].GetY(),light->_vertices[n].GetZ()); } } break; case ID_OUT_Polygons: { // Get the output port array ... CDataArray2DLong outData( in_ctxt ); CDataArray2DLong::Accessor outDataSubArray = outData.Resize(0,light->_nbp); for(ULONG n=0;n<light->_nbp;n++) { outDataSubArray[n] = light->_polygons[n]; } } break; } return CStatus::OK; }
SICALLBACK ToonixCurve_Evaluate(ICENodeContext& in_ctxt) { // Get User Data TXLine* line = (TXLine*)(CValue::siPtrType)in_ctxt.GetUserData(); // Get the output port array ... CDataArrayCustomType outData(in_ctxt); XSI::CDataArrayCustomType::TData* pOutData = outData.Resize(0, sizeof(TXLine)); ::memcpy(pOutData, line, sizeof(TXLine)); return CStatus::OK; }
void CCameraOpencv::slotTimeOut() { #ifdef DEBUG_VIDEO_TIME LOG_MODEL_DEBUG("CCameraOpencv", "CCameraOpencv::slotTimeOut threadid:0x%X", QThread::currentThread()); #endif cv::Mat frame; #ifdef ANDROID if(!m_videoCapture.grab()) return; m_videoCapture.retrieve(frame, CV_CAP_ANDROID_COLOR_FRAME_RGB);//cv::CAP_ANDROID_COLOR_FRAME_RGB #else m_videoCapture >> frame; //因为opencv会在内部把图像转化为BGR格式 cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB); #endif if(frame.empty()) return; /*LOG_MODEL_DEBUG("CCameraOpencv", "frame.type:%d;format:%d", frame.type(), #ifdef ANDROID m_videoCapture.get(cv::CAP_PROP_ANDROID_PREVIEW_FORMAT) #else m_videoCapture.get(cv::CAP_PROP_FORMAT) #endif ); */ /*第一种转换方法:用QImage QImage image((uchar*)(frame.data), frame.cols, frame.rows, QImage::Format_RGB888); //RGB888就是RGB24即RGB QVideoFrame outFrame(image);//*/ //*第二种转换方法:用CDataVideoBuffer QByteArray outData((const char*)frame.data, (int)(frame.total() * frame.channels())); //frame.total指图片像素个数,总字节数(dst.data)=dst.total*dst.channels() //由QVideoFrame进行释放 CDataVideoBuffer* pBuffer = new CDataVideoBuffer(outData, frame.cols, frame.rows); //LOG_MODEL_DEBUG("CCameraOpencv", "CCameraOpencv format:%d", dbFormat); QVideoFrame outFrame(pBuffer, QSize(frame.cols, frame.rows), QVideoFrame::Format_RGB24);//*/ #ifdef ANDROID emit sigCaptureRawFrame(outFrame); #else emit sigCaptureFrame(outFrame);//opencv已经做过镜像了 #endif }
BString ClientAgent::FilterCrap(const char* data, bool force) { BString outData("", 440); int32 theChars(strlen(data)); bool ViewCodes(false); int32 i(0), j(0); for (i = 0; i < theChars; ++i) { if (data[i] == 3 && !force && !vision_app->GetBool("stripcolors")) outData << data[i]; else if (data[i] > 1 && data[i] < 32) { if (data[i] == 3) { if (ViewCodes) outData << "[0x03]{"; ++i; // filter foreground for (j = 0; j < 2; j++) if (data[i] >= '0' && data[i] <= '9') { if (ViewCodes) outData << data[i]; ++i; } else break; if (data[i] == ',') { if (ViewCodes) outData << data[i]; ++i; for (j = 0; j < 2; j++) if (data[i] >= '0' && data[i] <= '9') { if (ViewCodes) outData << data[i]; ++i; } else break; } --i; if (ViewCodes) outData << "}"; } else if (ViewCodes) { char buffer[16]; sprintf(buffer, "[0x%02x]", data[i]); outData << buffer; } } else outData << data[i]; } return outData; }
void TcpConnector::readAndSplit() { QByteArray data = socket->readAll(); data.replace( QByteArray("\r\n"), QByteArray("\n") ); data.replace( QByteArray("\n\r"), QByteArray("\n") ); QList<QByteArray> sp = data.split('\n'); for( QList<QByteArray>::iterator i = sp.begin(); i != sp.end(); i++) { QByteArray packet = (*i); if(packet.startsWith((char)12)) packet = packet.right( packet.length()-1); if(packet.length() == 0) continue; emit outData(packet); } }
void HidReader::run() { m_stop = 0; unsigned char *data = new unsigned char[255]; while (m_stop == 0) { // Blocked polling: The only problem with this is that we can't close // the device until the block is released, which means the controller // has to send more data //result = hid_read_timeout(m_pHidDevice, data, 255, -1); // This relieves that at the cost of higher CPU usage since we only // block for a short while (500ms) int result = hid_read_timeout(m_pHidDevice, data, 255, 500); if (result > 0) { //qDebug() << "Read" << result << "bytes, pointer:" << data; QByteArray outData(reinterpret_cast<char*>(data), result); emit(incomingData(outData)); } } delete [] data; }
ReturnType HelloMaker::onExecute() { std::string msg("Hello"); ptrMessagePrint->print(msg); std::string outData("hello"); std::stringstream pData; DataOut.push("Sample Msg"); EventData<std::string> outEvent; outEvent.setId("messageid"); outEvent.setContentData("hello world"); EventOut.push(&outEvent); return OPROS_SUCCESS; }
XSIPLUGINCALLBACK CStatus ToonixGetData_Evaluate( ICENodeContext& in_ctxt ) { // Get User Data TXData* data = (TXData*)(CValue::siPtrType)in_ctxt.GetUserData( ); // The current output port being evaluated... LONG out_portID = in_ctxt.GetEvaluatedOutputPortID( ); switch( out_portID ) { case ID_OUT_ToonixData : { //Application().LogMessage(L"Toonix Get Data :: Nb Crease Edges : "+(CString)(ULONG)data->_geom->_creases.size()); // Get the output port array ... CDataArrayCustomType outData( in_ctxt ); XSI::CDataArrayCustomType::TData* pOutData = outData.Resize(0,sizeof(TXData)); ::memcpy( pOutData, data, sizeof(TXData) ); }break; } return CStatus::OK; }
SICALLBACK ToonixMesher_Evaluate( ICENodeContext& in_ctxt ) { TXMesh* mesh = (TXMesh*)(CValue::siPtrType)in_ctxt.GetUserData( ); if(!mesh->_valid || GetMesherDirtyState(in_ctxt)) { // Get the input TXLine CDataArrayCustomType ToonixLine( in_ctxt, ID_IN_ToonixLine ); CDataArrayCustomType::TData* pBufferToonixLine; ULONG nSizeToonixLine; ToonixLine.GetData( 0,(const CDataArrayCustomType::TData**)&pBufferToonixLine, nSizeToonixLine ); TXLine* line = (TXLine*)pBufferToonixLine; if(!line) { mesh->_nbv = mesh->_nbp = 0; } else { mesh->_line = line; CDataArrayLong subdivData(in_ctxt, ID_IN_Subdiv); mesh->_subdiv = subdivData[0]; CDataArrayVector3f viewData(in_ctxt, ID_IN_ViewPosition); mesh->_view = viewData[0]; mesh->Build(); } mesh->_valid = true; } // The current output port being evaluated... LONG out_portID = in_ctxt.GetEvaluatedOutputPortID( ); switch( out_portID ) { case ID_OUT_Vertices: { // Get the output port array ... CDataArray2DVector3f outData( in_ctxt ); CDataArray2DVector3f::Accessor outDataSubArray = outData.Resize(0,mesh->_nbv); for(ULONG n=0;n<mesh->_nbv;n++) { outDataSubArray[n].Set(mesh->_vertices[n].GetX(),mesh->_vertices[n].GetY(),mesh->_vertices[n].GetZ()); } } break; case ID_OUT_Polygons: { // Get the output port array ... CDataArray2DLong outData( in_ctxt ); CDataArray2DLong::Accessor outDataSubArray = outData.Resize(0,mesh->_nbp); for(ULONG n=0;n<mesh->_nbp;n++) { outDataSubArray[n] = mesh->_polygons[n]; } } break; } return CStatus::OK; }
int main(int argc, char *argv[]) { input_file input(argc, argv); std::string mdl = input.getStringOpt("model"); unsigned seed = input.getUnsignedOpt("seed"); unsigned M = input.getUnsignedOpt("M", 3); if(M<2) { fprintf(stderr, "Memory (M) must be larger or equal to 2\n"); exit(3); } std::string infections = input.getStringOpt("infections"); std::string network = input.getStringOpt("network"); std::string output = input.getStringOpt("output"); std::string name = input.getStringOpt("name", std::string("0")); unsigned days = input.getUnsignedOpt("days"); unsigned events = input.getUnsignedOpt("events", 2); string outVal = input.getStringOpt("outVal"); string date = input.getStringOpt("date"); string frames = input.getStringOpt("frames", "none"); output = unquoteString(output); outVal = unquoteString(outVal); frames = unquoteString(frames); #ifdef BGDEBUG input.writeToFile(stderr); input.writeToFile(stderr, mdl); input.writeToFile(stderr, infections); #endif //Ensure that the directory name has a trailing "/" if(output[output.size()-1]!='/') output+="/"; if(frames != "none" && frames[frames.size()-1]!='/') frames+="/"; #ifdef _WIN32 freopen((output + "NetEM." + name + ".out.dat").c_str(), "w", stdout); freopen((output + "NetEM." + name + ".err.dat").c_str(), "w", stderr); #else stdout = fopen((output+"NetEM."+name+".out.dat").c_str(),"w"); stderr = fopen((output+"NetEM."+name+".err.dat").c_str(),"w"); #endif // _WIN32 for(unsigned i=0; i<argc; ++i) printf("# %u %s\n", i, argv[i]); Parse parse(mdl); Rand r(seed); Graph g(network); std::vector<std::vector<NODE> > graph = g.getGraph(); unsigned N = graph.size(); unsigned susIndex = parse.susceptible(); unsigned recIndex = parse.recovered(); unsigned NStates = parse.NStates(); std::vector<unsigned> Ni = g.getPi(); ModelNetwork model(parse, &r); uint64_t secondary; std::vector<std::string> outComp = getVector(outVal); std::vector<unsigned> outCompIndex; fprintf(stderr,"# Found %u comps\n", unsigned(outComp.size())); std::vector<Transition> transList = parse.getTransitions(); std::vector<unsigned> outTrans(transList.size(), 0); for(unsigned i=0; i<outComp.size(); ++i) { fprintf(stderr,"%u \"%s\"",i,outComp[i].c_str()); unsigned comp = parse.label(outComp[i]); outCompIndex.push_back(comp); for(unsigned j=0; j<transList.size(); ++j) { if(transList[j].j == comp) { outTrans[j] = 1; fprintf(stderr," %u",j); } } fprintf(stderr, "\n"); } bool hasFrames = false; if(frames != "none") hasFrames = true; do { Population nodes(M, N, susIndex, recIndex); nodes.seeding(infections, 0, parse, r); FILE *fpout = input.openFile((output + "NetEM." + name + ".out")); FILE *fperr = input.openFile((output + "NetEM." + name + ".err")); FILE *fpsec = input.openFile((output + "NetEM." + name + ".sec")); FILE *fpstate; if(hasFrames) { fpstate = input.openFile((frames + "NetEM." + name + ".state")); g.saveHeader(fpstate); } fprintf(fpout, "# time"); Output outData(N, days+1); for(unsigned i=0; i<NStates; ++i) fprintf(fpout, " %s", parse.index(i).c_str()); fprintf(fpout, "\n"); secondary = 0; vector<uint64_t> transCount; Calendar cal(date); unsigned day0 = cal.day(); for(unsigned step = 0; step < days; ++step) { unsigned delta = model.step(graph, nodes, Ni, step, fperr, outTrans, transCount); secondary += delta; outData.add(transCount, step); if(hasFrames) nodes.saveState(step, fpstate); nodes.savePopulations(step, NStates, fpout); fprintf(fpsec, "%u %u\n",step, delta); } fclose(fpout); fclose(fperr); fclose(fpsec); if (hasFrames) fclose(fpstate); fprintf(stderr, "outbreak = %Lu\n", secondary); if(secondary > events) { outData.writeToFile(output+"sum"); } } while(secondary < events); return 0; }
/** * @SYMTestCaseID BA-CTSY-INT-MB-0036 * @SYMFssID BA/CTSY/MB-0036 * @SYMTestCaseDesc MBMS is currently used * @SYMTestPriority High * @SYMTestActions RPacketContext::InitialiseContext, RPacketContext::SetConfig, RPacketService::NotifyDynamicCapsChange, RPacketService::GetDynamicCaps, RPacketContext::Activate, RPacketService::NotifyStatusChange, RPacketService::GetStatus, RPacketContext::NotifyStatusChange, RPacketContext::GetStatus, RPacketContext::Deactivate * @SYMTestExpectedResults Pass - Client gets correct capability * @SYMTestType CIT * @SYMTestCaseDependencies live/manual * * Reason for test: Verify that client get correct capability. * * @return - none */ void CCTsyUCaseMbms020::CCtsyIntegrationTestMbms0001L() { // // SET UP // OpenEtelServerL( EUseExtendedError ); CleanupStack::PushL( TCleanupItem( Cleanup, this ) ); OpenPhoneL(); RPacketService packetService; OpenPacketServiceL( packetService ); CleanupClosePushL( packetService ); TInfoName contextId; RPacketMbmsContext mbmsContext; mbmsContext.OpenNewContext( packetService, contextId ); CleanupClosePushL( mbmsContext ); RBuf8 data; CleanupClosePushL(data); RBuf8 expectData; CleanupClosePushL(expectData); // initialisation of the context TInt status = InitMbmsContextL(mbmsContext, contextId); ASSERT_EQUALS(KErrNone, status); // data for SetConfig TRequestStatus requestStatus; RPacketMbmsContext::TContextConfigMbmsV1 setConfig; setConfig.iTmgi.SetServiceId(1); setConfig.iTmgi.SetMCC(111); setConfig.iTmgi.SetMNC(111); setConfig.iMbmsAccessBearer = E3GBearer; setConfig.iMbmsServicePriority = EMbmsHighServicePriority; setConfig.iMbmsServiceMode = KBroadcast; setConfig.iMbmsSessionFlag = ETrue; // configure context status = SetMbmsConfigL(mbmsContext, contextId, setConfig); ASSERT_EQUALS(KErrNone, status); // add sessions TInt maxSessions( 1 ); TMockLtsyData1 <TInfoName > expData( contextId ); expData.SerialiseL( expectData ); TMockLtsyData1 <TInfoName> outData( contextId ); outData.SerialiseL( data ); for( TInt i = 0; i < maxSessions; i++ ) { TMbmsSessionId session(i); iMockLTSY.ExpectL(EPacketContextUpdateMbmsSessionList, expectData); iMockLTSY.CompleteL(EPacketContextUpdateMbmsSessionList, KErrNone, data); mbmsContext.UpdateMbmsSessionList(requestStatus, EAddEntries, session); User::WaitForRequest( requestStatus ); ASSERT_EQUALS( KErrNone, requestStatus.Int() ) ; } // Activate MBMS context status = SetMbmsActiveL(mbmsContext, setConfig, contextId); ASSERT_EQUALS(KErrNone, status); RPacketService::TStatus sendStatus = RPacketService::EStatusActive; TBool isResumed = EFalse; TInt err = SetPacketServiceStatusL(sendStatus, isResumed); ASSERT_EQUALS(KErrNone, err); RPacketService::TStatus attachStatus; TInt ret = packetService.GetStatus(attachStatus); ASSERT_EQUALS(KErrNone, ret); ASSERT_EQUALS(RPacketService::EStatusActive, attachStatus); // Ensure MBMS Context status is Active RPacketContext::TContextStatus expectedStatus = RPacketContext::EStatusActive; RPacketContext::TContextStatus contextStatus; ret = mbmsContext.GetStatus(contextStatus); ASSERT_EQUALS(KErrNone, ret); ASSERT_EQUALS((TInt)expectedStatus, (TInt)contextStatus); // Add a session CFilteringActiveScheduler scheduler; CActiveScheduler::Install(&scheduler); RPacketMbmsContext::CMbmsSession* session = RPacketMbmsContext::CMbmsSession::NewL(); CleanupStack::PushL(session); CRetrievePcktMbmsSessionList* sessionList = CRetrievePcktMbmsSessionList::NewL(mbmsContext, *session); CleanupStack::PushL(sessionList); CActiveRetriever::ResetRequestsNumber(); CActiveRetriever retriever(*sessionList); scheduler.AddRetrieverL(retriever); sessionList->Start( retriever.Status() ); retriever.Activate(); scheduler.StartScheduler(); ASSERT_EQUALS(KErrNone, retriever.iStatus.Int()); // ensure there is session added to a MBMS context for( TUint i = 0; i < session->iSessionIdList.Count(); i++) { TMbmsSessionId sessionId = session->iSessionIdList[i]; ASSERT_EQUALS( sessionId, i); } ASSERT_EQUALS(0, CActiveRetriever::ResetRequestsNumber()); AssertMockLtsyStatusL(); // // SET UP END // // // TEST START // // Network sends MBMS Notification to handset indicating MBMS service delivery about to start. // post notify RPacketContext::NotifyStatusChange mbmsContext.NotifyStatusChange(requestStatus, contextStatus); // post RPacketService::NotifyDynamicCapsChange RPacketService::TDynamicCapsFlags caps; TRequestStatus dynamicCapsStatus; packetService.NotifyDynamicCapsChange(dynamicCapsStatus, caps); TContextMisc completeMisc; completeMisc.iStatus = RPacketContext::EStatusReceiving; TMockLtsyData2 <TInfoName, TContextMisc>ltsyData1(contextId, completeMisc); ltsyData1.SerialiseL(data); TRequestStatus mockLtsyStatus; iMockLTSY.NotifyTerminated(mockLtsyStatus); iMockLTSY.CompleteL(EPacketContextNotifyStatusChange , KErrNone, data); User::WaitForRequest(mockLtsyStatus); User::WaitForRequest(requestStatus); // Ensure RPacketContext::NotifyStatusChange completes MBMS context status RPacketContext::EStatusReceiving ASSERT_EQUALS(KErrNone, requestStatus.Int()); ASSERT_EQUALS(completeMisc.iStatus, contextStatus); AssertMockLtsyStatusL(); // Check RPacketContext::GetStatus returns RPacketContext::EStatusReceiving expectedStatus = RPacketContext::EStatusReceiving; ret = mbmsContext.GetStatus(contextStatus); ASSERT_EQUALS(KErrNone, ret); ASSERT_EQUALS((TInt)expectedStatus, (TInt)contextStatus); // Ensure RPacketService::NotifyDynamicCapsChange doens't return RPacketService::KCapsMBMS User::WaitForRequest(dynamicCapsStatus); ASSERT_EQUALS(KErrNone, dynamicCapsStatus.Int()); ASSERT_TRUE(RPacketService::KCapsMBMS & caps); // Ensure GetDynamicCaps capabilities return RPacketService::KCapsMBMS caps packetService.GetDynamicCaps(caps); ASSERT_TRUE(RPacketService::KCapsMBMS & caps); AssertMockLtsyStatusL(); // deactivate context status = SetMbmsDeactiveL(mbmsContext, contextId); ASSERT_EQUALS(KErrNone, status); // delete context status = SetMbmsDeleteL(mbmsContext, contextId); ASSERT_EQUALS(KErrNone, status); // close context mbmsContext.Close( ); // // TEST END // AssertMockLtsyStatusL(); CActiveScheduler::Install(NULL); CleanupStack::PopAndDestroy( 7, this ); // sessionList, session, expectData, data, mbmsContext, packetService, this }
SICALLBACK aaOcean_Evaluate( ICENodeContext& in_ctxt ) { aaOcean *pOcean = (aaOcean *)(CValue::siPtrType)in_ctxt.GetUserData(); CIndexSet indexSet(in_ctxt, ID_IN_PointID ); CDataArrayLong PointID(in_ctxt, ID_IN_PointID ); CDataArrayBool bEnable(in_ctxt, ID_IN_ENABLE); CDataArrayFloat uCoord(in_ctxt, ID_IN_U); CDataArrayFloat vCoord(in_ctxt, ID_IN_V); CDataArrayBool enableFoam( in_ctxt, ID_IN_ENABLEFOAM); CDataArrayMatrix4f transform(in_ctxt, ID_IN_TRANSFORM); const int count = PointID.GetCount(); float worldSpaceVec[3] = {0.0f, 0.0f, 0.0f}; float localSpaceVec[3] = {0.0f, 0.0f, 0.0f}; int transformArraySize = 0; bool transformSingleton = TRUE; if(transform.GetCount() > 1) transformSingleton = FALSE; ULONG out_portID = in_ctxt.GetEvaluatedOutputPortID( ); switch( out_portID ) { case ID_OUT_OCEAN: { CDataArrayVector3f outData( in_ctxt ); if(bEnable[0]) { #pragma omp parallel for private(worldSpaceVec, localSpaceVec) for(int i = 0; i<count; ++i) { // get ocean displacement vector worldSpaceVec[1] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eHEIGHTFIELD); if(pOcean->isChoppy()) { worldSpaceVec[0] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eCHOPX); worldSpaceVec[2] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eCHOPZ); } // multiply displacement vector by input transform matrix if(!transformSingleton) transformArraySize = i; multiplyMatrix(&worldSpaceVec[0], &localSpaceVec[0], transform, transformArraySize); outData[i].PutX(localSpaceVec[0]); outData[i].PutY(localSpaceVec[1]); outData[i].PutZ(localSpaceVec[2]); outData[i].PutX(worldSpaceVec[0]); outData[i].PutY(worldSpaceVec[1]); outData[i].PutZ(worldSpaceVec[2]); } } else { #pragma omp parallel for for(int i = 0; i<count; ++i) { outData[i].PutX(0.f); outData[i].PutY(0.f); outData[i].PutZ(0.f); } } } break; case ID_OUT_FOAM: { if(pOcean->isChoppy() && bEnable[0] && enableFoam[0]) { CDataArrayFloat outData( in_ctxt ); // output raw (unscaled) foam in ICE deformer #pragma omp parallel for for(int i = 0; i<count; ++i) outData[i] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eFOAM); } } break; case ID_OUT_EIGEN_MINUS: { CDataArrayVector3f outData( in_ctxt ); if(pOcean->isChoppy() && bEnable[0] && enableFoam[0]) { #pragma omp parallel for private(worldSpaceVec, localSpaceVec) for(int i = 0; i<count; ++i) { worldSpaceVec[0] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eEIGENMINUSX); worldSpaceVec[2] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eEIGENMINUSZ); multiplyMatrix(&worldSpaceVec[0], &localSpaceVec[0], transform, transformArraySize); outData[i].PutX(localSpaceVec[0]); outData[i].PutY(0.0f); outData[i].PutZ(localSpaceVec[2]); } } else { #pragma omp parallel for for(int i = 0; i<count; ++i){ outData[i].PutX(0);outData[i].PutY(0);outData[i].PutZ(0);} } } break; case ID_OUT_EIGEN_PLUS: { CDataArrayVector3f outData( in_ctxt ); if(pOcean->isChoppy() && bEnable[0] && enableFoam[0]) { #pragma omp parallel for private(worldSpaceVec, localSpaceVec) for(int i = 0; i<count; ++i) { worldSpaceVec[0] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eEIGENPLUSX); worldSpaceVec[2] = pOcean->getOceanData(uCoord[i], vCoord[i], aaOcean::eEIGENPLUSZ); multiplyMatrix(&worldSpaceVec[0], &localSpaceVec[0], transform, transformArraySize); outData[i].PutX(localSpaceVec[0]); outData[i].PutY(0.0f); outData[i].PutZ(localSpaceVec[2]); } } else { #pragma omp parallel for for(int i = 0; i<count; ++i){ outData[i].PutX(0); outData[i].PutY(0); outData[i].PutZ(0);} } } break; } return CStatus::OK; }
void SteadyStateAlgo::runEvolution() { int startGeneration = 0; char statfile[64]; char inFilename[128]; char outFilename[128]; char bestOutFilename[128]; int bestGeneration = -1; float bestFitness = -1.0; // Define the final mutation rate (i.e., the lower bound for the mutation rate) const double finalMutRate = m_mutRate; // Initialise the mutation rate m_mutRate = m_initMutRate; // initially mutation (default 50%) // Set the seed setSeed(m_rngSeed); // Initialise the population randomisePopulation(); // Check whether to recover a previous evolution sprintf(statfile, "S%d.fit", seed()); // Check if the file exists DataChunk statTest(QString("stattest"), Qt::blue, 2000, false); if (statTest.loadRawData(QString(statfile), 0)) { startGeneration = statTest.getIndex(); sprintf(inFilename, "S%dG%d.gen", (seed()), startGeneration); Logger::info("Recovering from startGeneration: " + QString::number(startGeneration)); Logger::info(QString("Loading file: ") + inFilename); QFile inData(inFilename); if (inData.open(QFile::ReadOnly)) { QTextStream in(&inData); for (int i = 0; i < m_popSize; i++) { bool loaded = m_population[i]->loadGen(in); // Check possible errors during the loading operation if (!loaded) { Logger::error("Error in the loading of the genotype"); } // Check the consistency of the genotype (i.e., the number of genes) if (m_population[i]->getLength() != m_numGenes) { Logger::error("Wrong genotype length!"); } } inData.close(); } } // Flow control pauseFlow(); if (stopFlow()) { // Cleanup return; } // Do all generations for (int gn = startGeneration; gn < m_numGenerations; gn++) { // Define a fitness array for all the individuals to be tested QVector<float> fit(m_popSize * 2); m_gae->setIndividualCounter(); m_gae->initGeneration(gn); // Evaluate all the individuals for (int i = 0; i < m_popSize; i++) { // Set the genotype to be tested m_gt->setGenotype(m_population[i]); // Evaluate the genotype m_gae->evaluate(); // Get the fitness fit[i] = m_gae->getFitness(); // Set the fitness of the current genotype m_population[i]->setFitness(fit[i]); // Use subclasses for modifying and/or getting elements (i.e., genes) GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]); GenotypeInt* off = dynamic_cast<GenotypeInt*>(m_population[i + m_popSize]); // Now generate an offspring and evaluate it for (int g = 0; g < m_numGenes; g++) { int val = ind->getGene(g); // Mutate the value int newVal = mutate(val, m_mutRate); off->setGene(g, newVal); } m_gt->setGenotype(m_population[i + m_popSize]); // Evaluate the genotype m_gae->evaluate(); // Get the fitness fit[i + m_popSize] = m_gae->getFitness(); // Flow control pauseFlow(); if (stopFlow()) { return; } } m_gae->resetIndividualCounter(); // Select the best <popSize> individuals QVector<int> indices = sortFit(fit); // Define a temporary array for storing // the best <popSize> individuals QVector<float*> tmpPop(m_popSize); // Define a temporary array for storing // the fitnesses of the best individuals QVector<float> tmpFit(m_popSize); for (int i = 0; i < m_popSize; i++) { tmpPop[i] = new float[m_numGenes]; int idx = indices[i]; GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[idx]); for (int g = 0; g < m_numGenes; g++) { tmpPop[i][g] = ind->getGene(g); } tmpFit[i] = fit[idx]; } // Swap individuals for (int i = 0; i < m_popSize; i++) { GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]); for (int g = 0; g < m_numGenes; g++) { ind->setGene(g, tmpPop[i][g]); ind->setFitness(tmpFit[i]); } } // Flow control pauseFlow(); if (stopFlow()) { break; } // Save fitness statistics char fitStatFilename[64]; sprintf(fitStatFilename, "S%d.fit", seed()); QFile fitStatData(fitStatFilename); bool openOk = false; if (gn == 0) { openOk = fitStatData.open(QIODevice::WriteOnly); } else { openOk = fitStatData.open(QIODevice::Append); } if (openOk) { QTextStream fitStat(&fitStatData); // Compute maximum, minimum and average fitness and store them in a vector QVector<float> fitArray(3); // Max float maxFit = fit[indices[0]]; fitArray[0] = maxFit; // Average float avgFit = 0.0; for (int i = 0; i < m_popSize; i++) { avgFit += fit[indices[i]]; } avgFit /= m_popSize; fitArray[1] = avgFit; // Min float minFit = fit[indices[m_popSize - 1]]; fitArray[2] = minFit; saveFitStats(fitArray, fitStat); fitStatData.close(); } // Save all fitness statistics if <saveFitnessAllIndividuals> flag is set to true if (m_saveFitnessAllIndividuals) { char allFitStatFilename[64]; sprintf(allFitStatFilename, "S%dall.fit", seed()); QFile allFitStatData(allFitStatFilename); openOk = false; if (gn == 0) { openOk = allFitStatData.open(QIODevice::WriteOnly); } else { openOk = allFitStatData.open(QIODevice::Append); } if (openOk) { QTextStream allFitStat(&allFitStatData); saveFitStats(fit, allFitStat); allFitStatData.close(); } } // Save the best genotype sprintf(bestOutFilename, "S%dB%d.gen", seed(), 0); QFile bestOutData(bestOutFilename); bool operation = false; if (gn == 0) { // Open the QFile in write mode operation = bestOutData.open(QIODevice::WriteOnly); } else { // Open the QFile in append mode operation = bestOutData.open(QFile::Append); } if (operation) { QTextStream bestOut(&bestOutData); GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[0]); ind->saveGen(bestOut); bestOutData.close(); } // Save all the genotypes sprintf(outFilename, "S%dG%d.gen", seed(), (gn + 1)); QFile outData(outFilename); if (outData.open(QIODevice::WriteOnly)) { QTextStream out(&outData); // Save the population for (int i = 0; i < m_popSize; i++) { GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]); ind->saveGen(out); } outData.close(); } // Decrease the mutation rate (until it becomes equal to the lower bound) if (m_mutRate > finalMutRate) { m_mutRate -= m_mutDecay; } else { m_mutRate = finalMutRate; } // Check the best generation if (fit[indices[0]] > bestFitness) { bestFitness = fit[indices[0]]; bestGeneration = gn; } m_gae->endGeneration(gn); } // Save the information about the best generation char bestGenFileName[64]; sprintf(bestGenFileName, "S%dbest.fit", seed()); QFile bestGenData(bestGenFileName); // Open the QFile in write mode if (bestGenData.open(QIODevice::WriteOnly)) { QTextStream bestGenOut(&bestGenData); QString outStr; //! Write the best generation index outStr = QString::number(bestGeneration); bestGenOut << outStr; //! Write the fitness of the best generation outStr = QString::number(bestFitness); bestGenOut << " " << outStr; bestGenOut << endl; bestGenData.close(); } }
bool Modulator::modulate(const std::vector<byte>& data, const std::string& fileName) { //check if wave tables built and create if not if (lowTable.empty() || highTable.empty()) { buildWaveTable(lowTable, lowFreq); buildWaveTable(highTable, highFreq); } //create ostream / check valid std::fstream file(fileName, std::ios::binary | std::ios::out); if (!file.good() || !file.is_open()) { std::cout << "Failed to open file for writing" << std::endl; file.close(); return false; } std::cout << "Processing..." << std::endl; //test data size and limit if necessary auto dataSize = data.size() * highTable.size(); auto segmentCount = std::min(dataSize / maxSegmentSize, maxSegmentCount); dataSize = segmentCount * maxSegmentSize * 8 * highTable.size(); //create header WavHeader header; //add to header / update header data count - riffChuknSize and dataChunkSize header.riffChunkSize += dataSize; header.dataChunkSize = dataSize; file.write((const char*)&header, sizeof(header)); //output segments for (auto i = 0; i < segmentCount; ++i) { std::vector<short> outData(maxSegmentSize * 8 * highTable.size()); auto ptr = outData.data(); for (auto j = 0u; j < maxSegmentSize; ++j) { for (auto k = 0; k < 8; ++k) { if (data[j] & (1 << k)) { std::memcpy((void*)ptr, lowTable.data(), lowTable.size() * sizeof(short)); ptr += lowTable.size(); } else { std::memcpy((void*)ptr, highTable.data(), highTable.size() * sizeof(short)); ptr += highTable.size(); } } } file.write((const char*)outData.data(), outData.size() * sizeof(short)); } file.close(); std::cout << "wrote " << dataSize << "bytes" << std::endl; return true; }