Exemple #1
0
void
SolveTheBGIP(BGIP_sharedPtr bgip)
{
    // Specify the solution method.
    // (See above and in BGIP_SolverType.h)
    BGIP_SolverType::BGIP_Solver_t method = BGIP_SolverType::AM;
    try {
        Timing timer;
        timer.Start( SoftPrint(method) );
        BayesianGameIdenticalPayoffSolver * bgip_solver = NewBGIPSolver(bgip, method);
        cout << "running " <<  SoftPrint(method) << "..."<<endl;
        cout << "...value is " << bgip_solver->Solve() << endl;
        timer.Stop(  SoftPrint(method) );
        delete bgip_solver;
    }
    catch(E& e)
    {
        e.Print();
    }
}
int main(int argc, char** argv)
{
	Timing t;
	int i;

	// TODO: debug should be enabled with a command-line option
	// FILELog::ReportingLevel() = FILELog::FromString("DEBUG4");
	// FILELog::ReportingLevel() = FILELog::FromString("DEBUG1");
	FILELog::ReportingLevel() = FILELog::FromString("INFO");
	FILE_LOG(logDEBUG4) << "starting";

	t.Start();
	try {

		Picoscope6000 *pico = new Picoscope6000();
		Measurement   *meas = new Measurement(pico);
		Channel       *ch[4];

		meas->SetTimebaseInPs(400);
		meas->EnableChannels(true,false,false,false);
		for(i=0; i<PICOSCOPE_N_CHANNELS; i++) {
			ch[i] = meas->GetChannel(i);
			FILE_LOG(logDEBUG4) << "main - Channel " << (char)('A'+i) << " has index " << ch[i]->GetIndex();
		}

		Args x;
		x.parse_options(argc, argv, meas);
		if(x.IsJustHelp()) {
			return 0;
		}

		if(x.GetFilename() == NULL) { // TODO: maybe we want to use just text file
			throw("You have to provide some filename using '--name <filename>'.\n");
		}

		// meas->SetTimebaseInPs(10000);

		// TODO: fixme
		for(i=0; i<PICOSCOPE_N_CHANNELS; i++) {
			ch[i]->SetVoltage(x.GetVoltage());
		}

		// a->SetVoltage(U_100mV);
		// a[0]->SetVoltage(x.GetVoltage());
		// meas->SetLength(GIGA(1));
		meas->SetLength(x.GetLength());

		if(x.GetNTraces() > 1) {
			meas->SetNTraces(x.GetNTraces());
			// TODO: fix trigger
			FILE_LOG(logDEBUG4) << "main - checking for triggered events";
			if(x.IsTriggered()) {
				for(i=0; i<PICOSCOPE_N_CHANNELS && !(ch[i]->IsEnabled()); i++);
				FILE_LOG(logDEBUG4) << "main - will trigger on channel " << (char)('A'+i);
				meas->SetTrigger(x.GetTrigger(ch[i]));
			}
			meas->AllocateMemoryRapidBlock(MEGA(50));
		} else {
			meas->AllocateMemoryBlock(MEGA(50));
		}

		// std::cerr << "test w5\n";

		// it only makes sense to measure if we decided to use some positive number of samples
		if(x.GetLength()>0) {

			FILE *f = NULL;
			FILE *fb[4] = {NULL,NULL,NULL,NULL}, *ft[4] = {NULL,NULL,NULL,NULL};

			struct tm *current;
			time_t now;
			time(&now);
			current = localtime(&now);

			for(i=0; i<PICOSCOPE_N_CHANNELS; i++) {
				if(ch[i]->IsEnabled()) {
					if(x.IsTextOutput()) {
						ft[i] = fopen(x.GetFilenameText(i), "wt");
						if(ft[i] == NULL) {
							throw("Unable to open text file.\n"); // TODO: write filename
						}
					}
					if(x.IsBinaryOutput()) {
						fb[i] = fopen(x.GetFilenameBinary(i), "wb");
						if(fb[i] == NULL) {
							throw("Unable to open binary file.\n"); // TODO: write filename
						}
					}
				}
			}

			/************************************************************/
			double tmp_dbl;
			short  tmp_short;
			pico->Open();
			meas->InitializeSignalGenerator();
			meas->RunBlock();

			/* metadata */
			f = fopen(x.GetFilenameMeta(), "wt");
			if(f == NULL) {
				throw("Unable to open file with metadata.\n");
			}
			fprintf(f, "command:   ");
			for(i=0; i<argc; i++) {
				fprintf(f, " %s", argv[i]);
			}
			fprintf(f, "\n");
			fprintf(f, "timestamp:  %d-%02d-%02d %02d:%02d:%02d\n\n",
				current->tm_year+1900, current->tm_mon+1, current->tm_mday,
				current->tm_hour, current->tm_min, current->tm_sec);
			fprintf(f, "channels:   ");
			for(i=0; i<PICOSCOPE_N_CHANNELS; i++) {
				if(ch[i]->IsEnabled()) {
					fprintf(f, "%c", 'A'+i);
				}
			}
			fprintf(f, "\n");
			fprintf(f, "length:     %ld\n", x.GetLength());
			fprintf(f, "samples:    %ld\n", x.GetNTraces());
			// fprintf(f, "unit_x:    %.1lf ns | %.1lf ns\n", meas->GetTimebaseInNs(), meas->GetReportedTimebaseInNs());
			tmp_dbl = meas->GetTimebaseInNs();
			fprintf(f, "unit_x:     %.1lf ns\n", tmp_dbl);
			fprintf(f, "range_x:    %.1lf ns\n", x.GetLength()*tmp_dbl);
			tmp_dbl = x.GetVoltageDouble();
			fprintf(f, "unit_y:     %.10le V\n", tmp_dbl*3.0757874015748e-5); // 1/(127*256) actually, but this might have to be fixed for series 4000
			fprintf(f, "range_y:    %g V\n", tmp_dbl);

			if(x.GetNTraces() > 1) {
				if(x.IsTriggered()) {
					fprintf(f, "trigger_ch: %c\n", (char)(meas->GetTrigger()->GetChannel()->GetIndex()+'A'));
					// fprintf(f, "trigger_xfrac: %g\n", meas->GetTrigger()->GetXFraction());
					// fprintf(f, "trigger_yfrac: %g\n", meas->GetTrigger()->GetYFraction());
					fprintf(f, "trigger_dx: %d (%g %% of %ld)\n", meas->GetLengthBeforeTrigger(), meas->GetLengthBeforeTrigger()*100.0/x.GetLength(), x.GetLength());
					tmp_short = meas->GetTrigger()->GetThreshold();
					tmp_dbl   = meas->GetTrigger()->GetYFraction();
					fprintf(f, "trigger_dy: %g V (%d)\n", meas->GetTrigger()->GetThresholdInVolts() /*tmp_dbl*x.GetVoltageDouble()*/, tmp_short);
				}
			}

			// fprintf(f, "unit_x:    %.1lf ns | %.1lf ns\n", meas->GetTimebaseInNs(), meas->GetReportedTimebaseInNs());
			fprintf(f, "out_bin:    %s\n", x.IsBinaryOutput() ? "yes" : "no");
			fprintf(f, "out_dat:    %s\n", x.IsTextOutput()   ? "yes" : "no");
			
			// triggered (TODO: we could also ask for a single triggered event)
			if(x.GetNTraces() > 1) {
				unsigned int run=0;
				for(run=0; run<x.GetNRepeats() && !_kbhit(); run++) {
					//FILE_LOG(logINFO) << "Running experiment nr. " << run+1;
					if(run>0) {
						cerr << "\nRepeat #" << run+1 << endl;
						meas->RunBlock();
					}
					while(meas->GetNextDataBulk() > 0) {
						for(i=0; i<PICOSCOPE_N_CHANNELS; i++) {
							if(ch[i]->IsEnabled()) {
								if(x.IsTextOutput()) {
									meas->WriteDataTxt(ft[i], i); // zero for channel A
								}
								if(x.IsBinaryOutput()) {
									meas->WriteDataBin(fb[i], i); // zero for channel A
								}
							}
						}
					}
				}
				if(run>1) {
					fprintf(f, "repeats:    %u\n", run);
				}
				// tmp_dbl = meas->GetRatePerSecond();
				// fprintf(f, "\nrate:       \n");
				// if(fabs(tmp_dbl) > 1e6) {
				// 	fprintf(f, "%.3f MS/s\n", tmp_dbl*1e-6);
				// } else if(fabs(tmp_dbl) > 1e3) {
				// 	fprintf(f, "%.3f kS/s\n", tmp_dbl*1e-3);
				// } else {
				// 	fprintf(f, "%f S/s\n", tmp_dbl);
				// }
			} else {
				unsigned int run=0;
				for(run=0; run<x.GetNRepeats() && !_kbhit(); run++) {
					if(run>0) {
						cerr << "\nRepeat #" << run+1 << endl;
						meas->RunBlock();
					}
					while(meas->GetNextData() > 0) {
						for(i=0; i<PICOSCOPE_N_CHANNELS; i++) {
							if(ch[i]->IsEnabled()) {
								if(x.IsTextOutput()) {
									meas->WriteDataTxt(ft[i], i); // zero for channel A
								}
								if(x.IsBinaryOutput()) {
									meas->WriteDataBin(fb[i], i); // zero for channel A
								}
							}
						}
					}
				}
				if(run>1) {
					fprintf(f, "repeats:    %u\n", run);
				}
			}

			fclose(f);

			for(i=0; i<PICOSCOPE_N_CHANNELS; i++) {
				if(ft[i] != NULL) {
					fclose(ft[i]);
				}
				if(fb[i] != NULL) {
					fclose(fb[i]);
				}
			}

			// apparently this doesn't work for some weird reason
			// meas->RunBlock(); meas->GetNextData();
			// meas->RunBlock(); meas->GetNextData();
			// meas->RunBlock(); meas->GetNextData();
			// meas->RunBlock(); meas->GetNextData();

			pico->Close();
			t.Stop();

			cerr << "Timing: " << t.GetSecondsDouble() << "s\n";
		}

		delete pico; pico = NULL;
		delete meas; meas = NULL;


	} catch(Picoscope::PicoscopeException& ex) {
		cerr << "Some picoscope exception:" << endl
		     << "Error number " << ex.GetErrorNumber() << ": " << ex.GetErrorMessage() << endl
		     << '(' << ex.GetVerboseErrorMessage() << ')' << endl;
		try {
			// pico.Close();
		} catch(...) {}
	} catch(Picoscope::PicoscopeUserException& ex) {
		cerr << "Some exception:" << endl
		     << ex.GetErrorMessage() << endl;
	// catch any exceptions
	} catch(const char* s) {
		cerr << "Some exception has occurred:\n" << s << endl;
	} catch (std::bad_alloc& ba) {
		std::cerr << "Exception: bad_alloc: " << ba.what() << endl;
	} catch (const std::exception &exc) {
		// catch anything thrown within try block that derives from std::exception
		std::cerr << "Exception: " << exc.what() << endl;
	} catch(...) {
		cerr << "Some exception has occurred" << endl;
	}
	return 0;
}
Exemple #3
0
int main(int argc, char **argv)
{
    DecPOMDPDiscreteInterface* decpomdp;
    try {
        ArgumentHandlers::Arguments args;
        argp_parse (&ArgumentHandlers::theArgpStruc, argc, argv, 0, 0, &args);

        Timing times;
        times.Start("Parsing");
        //DecPOMDPDiscreteInterface* 
        decpomdp = GetDecPOMDPDiscreteInterfaceFromArgs(args);
        TransitionObservationIndependentMADPDiscrete *toi=0;
        if((toi=dynamic_cast<TransitionObservationIndependentMADPDiscrete*>(decpomdp)) &&
           args.qheur==eQMDP &&
           !args.cache_flat_models /* otherwise
                                    * GetDecPOMDPDiscreteInterfaceFromArgs
                                    * already caches the flat
                                    * models */)
        {
            // we don't need a centralized obs model
            toi->CreateCentralizedSparseTransitionModel();
        }

        times.Stop("Parsing");

        if(!args.dryrun)
            directories::MADPCreateResultsDir("GMAA",*decpomdp);
        
        size_t horizon;
        if(args.infiniteHorizon)
            horizon=MAXHORIZON;
        else
            horizon=args.horizon;

        times.Start("Overall");

        PlanningUnitMADPDiscreteParameters params;
#if 0 // Caching doesn't seem worth the trouble if we're computing
      // just one thing (not to mention the memory savings)
        if(Qheur==eQMDP) // don't need any of this for solving the MDP
            params.SetComputeAll(false);
        else
        {
            params.SetComputeAll(true);
            params.SetUseSparseJointBeliefs(true);
        }
#else
        params.SetComputeAll(false);
        if(args.sparse)
            params.SetUseSparseJointBeliefs(true);
#endif

        times.Start("PlanningUnit");
        NullPlanner np(params,horizon,decpomdp);
        times.Stop("PlanningUnit");

        struct timeval tvStart, tvEnd;
        gettimeofday (&tvStart, NULL);

        QFunctionJAOHInterface* q=0;
        for(int restartI = 0; restartI < args.nrRestarts; restartI++)
        {
            // with hybrid heuristics already some computation is done
            // before Compute(), so start timing now
            times.Start("ComputeQ");
            q = GetQheuristicFromArgs(&np, args);
            q->Compute();
            times.Stop("ComputeQ");

            // we want to keep the last q computed
            if(restartI<(args.nrRestarts-1))
                delete q;
        }

        gettimeofday (&tvEnd, NULL);

        clock_t wallclockTime = 
            static_cast<clock_t>(((tvEnd.tv_sec - tvStart.tv_sec) +
                                  static_cast<double>(tvEnd.tv_usec-tvStart.tv_usec)/1e6) * sysconf(_SC_CLK_TCK));

        cout << "Wallclock: from "
             << tvStart.tv_sec << "." << tvStart.tv_usec
             << " until "
             << tvEnd.tv_sec << "." << tvEnd.tv_usec
             << " which took " << wallclockTime << " clock ticks"
             << endl;
        
        times.AddEvent("WallclockTime", wallclockTime);

        if(!args.dryrun)
        {
            times.Start("Save");
            q->Save();
            times.Stop("Save");
            if(args.verbose >= 0)
                cout << "Q saved to " << q->GetCacheFilename() << endl;
        }
        times.Stop("Overall");

        if(args.verbose >= 0)
            times.PrintSummary();

        if(!args.dryrun)
        {
            stringstream ss;
            ss << directories::MADPGetResultsDir("GMAA",*decpomdp)
               << "/calculateQheuristic" << q->SoftPrintBrief() << "_h"
               << horizon;
            if(decpomdp->GetDiscount()!=1)
                ss << "_g" << decpomdp->GetDiscount();
            ss << "_Timings";
            times.Save(ss.str());
            if(args.verbose >= 0)
                cout << "Timings saved to " << ss.str() << endl;
        }

        if(horizon!=MAXHORIZON)
        {
            double Vjb0=-DBL_MAX;
            for(Index a=0;a!=np.GetNrJointActions();++a)
                Vjb0=max(q->GetQ(Globals::INITIAL_JAOHI,a),Vjb0);
            cout << "Value of jaohI 0 = " << Vjb0 << endl;
        }

        delete q;
    }
    catch(E& e){ e.Print(); }

    cout << "cleanup..." << endl;
    delete decpomdp;
}
unsigned long Measurement::GetNextDataBulk()
{
	FILE_LOG(logDEBUG3) << "Measurement::GetNextDataBulk";

	unsigned long i, j, index;
	short *overflow;
	uint32_t traces_asked_for, length_of_trace_fetched;
	// unsigned long length_of_trace_askedfor, length_of_trace_fetched;
	Timing t;

	// std::cerr << "(GetNextDataBulk: " << GetNextIndex() << ", " << GetMaxTracesToFetch() << ")\n";

	// it makes no sense to read any further: we are already at the end
	if(GetNextIndex() >= GetNTraces()) {
		std::cerr << "Stop fetching data from ociloscope." << std::endl;
		return 0UL;
	}

/*
	try {
		for(i=0; i<GetNumberOfChannels(); i++) {
			if(GetChannel(i)->IsEnabled()) {
				delete [] data[i];
				data[i] = new short[GetMaxTracesToFetch()*GetLength()];
			}
		}
	} catch(...) {
		std::cerr << "Unable to allocate memory in Measurement::AllocateMemoryBlock." << std::endl;
		throw;
	}
/**/

	traces_asked_for = GetMaxTracesToFetch();
	if(GetNextIndex() + traces_asked_for > GetNTraces()) {
		traces_asked_for = GetNTraces() - GetNextIndex();
	}
	// allocate buffers
	for(i=0; i<GetNumberOfChannels(); i++) {
		if(GetChannel(i)->IsEnabled()) {
			FILE_LOG(logDEBUG4) << "Measurement::GetNextDataBulk - memset data[i]" << GetLength()*traces_asked_for*sizeof(short);
			memset(data[i], 0, GetLength()*traces_asked_for*sizeof(short));
			FILE_LOG(logDEBUG4) << "done";
		}
		for(j=0; j<traces_asked_for; j++) {
			index = j+GetNextIndex();
			if(GetChannel(i)->IsEnabled()) {
				if(data_allocated[i] == false) {
					throw "Unable to get data. Memory is not allocated.";
				}
				if(GetSeries() == PICO_4000) {
					// GetPicoscope()->SetStatus(ps4000SetDataBufferBulk(
					// 	GetHandle(),                  // handle
					// 	(PS4000_CHANNEL)i,            // channel
					// 	data[i],                      // *buffer
					// 	GetMaxTraceLengthToFetch())); // bufferLength
					GetPicoscope()->SetStatus(ps4000SetDataBufferBulk(
						GetHandle(),                // handle
						(PS4000_CHANNEL)i,          // channel
						&data[i][j*GetLength()],    // *buffer
						GetLength(),                // bufferLength
						index));                    // waveform
				} else {
					// unsigned long dj = (j+GetNextIndex()/GetMaxTracesToFetch())%traces_asked_for;
					// std::cerr << "-- (set data buffer bulk: [" << i << "][" << dj
					// 	<< "], len:" << GetLength() << ", index:" << index
					// 	<< ", from:" << GetNextIndex()
					// 	<< ", to:" << GetNextIndex()+traces_asked_for-1 << "\n";
					GetPicoscope()->SetStatus(ps6000SetDataBufferBulk(
						GetHandle(),                // handle
						(PS6000_CHANNEL)i,          // channel
						&data[i][j*GetLength()],    // *buffer
						GetLength(),                // bufferLength
						index,                      // waveform
						PS6000_RATIO_MODE_NONE));   // downSampleRatioMode
				}
				if(GetPicoscope()->GetStatus() != PICO_OK) {
					std::cerr << "Unable to set memory for channel." << std::endl;
					throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
				}
			}
		}
	}
	// fetch data
	// length_of_trace_fetched = length_of_trace_askedfor;
	std::cerr << "Get data for traces " << GetNextIndex() << "-" << GetNextIndex()+traces_asked_for << " (" << 100.0*(GetNextIndex()+traces_asked_for)/GetNTraces() << "%) ... ";
	overflow = new short[traces_asked_for];
	memset(overflow, 0, traces_asked_for*sizeof(short));
	// std::cerr << "-- x1\n";
	t.Start();
	// std::cerr << "length of buffer: " << data_length[0] << ", length of requested trace: " << length_of_trace_askedfor << " ... ";
	if(GetSeries() == PICO_4000) {
		length_of_trace_fetched = GetLength();
		GetPicoscope()->SetStatus(ps4000GetValuesBulk(
			GetHandle(),                // handle
			&length_of_trace_fetched,   // *noOfSamples
			// TODO: start index
			GetNextIndex(),             // fromSegmentIndex
			GetNextIndex()+traces_asked_for-1, // toSegmentIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			overflow));                // *overflow
	} else {
		// TODO: not sure about this ...
		length_of_trace_fetched = GetLength();
		GetPicoscope()->SetStatus(ps6000GetValuesBulk(
			GetHandle(),                // handle
			&length_of_trace_fetched,   // *noOfSamples
			// TODO: start index
			GetNextIndex(),             // fromSegmentIndex
			GetNextIndex()+traces_asked_for-1, // toSegmentIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			1,                          // downSampleRatio
			PS6000_RATIO_MODE_NONE,     // downSampleRatioMode
			overflow));                // *overflow
	}
	t.Stop();
	// std::cerr << "-- x2\n";
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to set memory for channel." << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	}
	for(i=0; i<traces_asked_for; i++) {
		for(j=0; i<GetNumberOfChannels(); i++) {
			if(overflow[i] & (1<<j)) {
				FILE_LOG(logWARNING) << "Warning: Overflow on channel " << (char)('A'+j) << " of trace " << i+GetNextIndex() << ".\n";
			}
		}
	}
	delete [] overflow;
	// if(length_of_trace_fetched != length_of_trace_askedfor) {
	// 	std::cerr << "Warning: The number of read samples was smaller than requested.\n";
	// }

	// getting timestamps
	int64_t *timestamps;
	PS6000_TIME_UNITS *timeunits;

	timestamps = new int64_t[traces_asked_for];
	timeunits  = new PS6000_TIME_UNITS[traces_asked_for];

	if(GetSeries() == PICO_4000) {
		// NOT YET IMPLEMENTED
	} else {
		FILE_LOG(logDEBUG2) << "ps6000GetValuesTriggerTimeOffsetBulk64(handle=" << GetHandle() << ", *timestamps, *timeunits, fromSegmentIndex=" << GetNextIndex() << ", toSegmentIndex=" << GetNextIndex()+traces_asked_for-1 << ")";
		GetPicoscope()->SetStatus(ps6000GetValuesTriggerTimeOffsetBulk64(
			GetHandle(),                // handle
			timestamps,                 // *times
			timeunits,                  // *timeUnits
			GetNextIndex(),                      // fromSegmentIndex
			GetNextIndex()+traces_asked_for-1)); // toSegmentIndex
	}
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to get timestamps." << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	}

	// for(i=0; i<traces_asked_for; i++) {
	// 	std::cerr << "time " << i << ": " << timestamps[i] << "\n";
	// }
	SetRate(traces_asked_for, timestamps[0], timeunits[0], timestamps[traces_asked_for-1], timeunits[traces_asked_for-1]);
	// if(timeunits[0] != timeunits[traces_asked_for-1]) {
	// 	FILE_LOG(logWARNING) << "time unit of the first and last sample differ; rate is not reliable; TIMING seems to be broken anyway";
	// }

	delete [] timestamps;
	delete [] timeunits;


	std::cerr << "OK ("<< t.GetSecondsDouble() <<"s)\n";

	// std::cerr << "length of trace fetched: " << length_of_trace_fetched << "\n";
	// std::cerr << "total length: " << traces_asked_for*length_of_trace_fetched << "\n";

	SetLengthFetched(traces_asked_for*length_of_trace_fetched);
	// std::cerr << "-- next index is now " << GetNextIndex() << ", will be set to " << GetNextIndex() + traces_asked_for << "\n";
	SetNextIndex(GetNextIndex()+traces_asked_for);
	// std::cerr << "-- next index is now " << GetNextIndex() << "\n";
	// std::cerr << "-- return value " << traces_asked_for << "\n";

	return traces_asked_for;
}
// TODO: we might want to use multiple buffers at the same time
// returns the length of data
// TODO: the first part only needs to be called once; so we should move the code at the end of RunBlock
//       unless we want to alternate between allocated memory (to enable parallel readouts)
unsigned long Measurement::GetNextData()
{
	FILE_LOG(logDEBUG3) << "Measurement::GetNextData";

	int i;
	short overflow=0;
	uint32_t length_of_trace_askedfor, length_of_trace_fetched;
	Timing t;

	// it makes no sense to read any further: we are already at the end
	if(GetNextIndex() >= GetLength()) {
		std::cerr << "Stop fetching data from osciloscope." << std::endl;
		return 0UL;
	}

	length_of_trace_askedfor = GetMaxTraceLengthToFetch();
	if(GetNextIndex() + length_of_trace_askedfor > GetLength()) {
		length_of_trace_askedfor = GetLength() - GetNextIndex();
	}
	// allocate buffers
	for(i=0; i<GetNumberOfChannels(); i++) {
		if(GetChannel(i)->IsEnabled()) {
			if(data_allocated[i] == false) {
				throw "Unable to get data. Memory is not allocated.";
			}
			if(GetSeries() == PICO_4000) {
				FILE_LOG(logDEBUG2) << "ps4000SetDataBuffer(handle=" << GetHandle() << ", channel=" << i << ", *buffer=<data[i]>, bufferLength=" << GetMaxTraceLengthToFetch() << ")";
				GetPicoscope()->SetStatus(ps4000SetDataBuffer(
					GetHandle(),                  // handle
					(PS4000_CHANNEL)i,            // channel
					data[i],                      // *buffer
					GetMaxTraceLengthToFetch())); // bufferLength
			} else {
				FILE_LOG(logDEBUG2) << "ps6000SetDataBuffer(handle=" << GetHandle() << ", channel=" << i << ", *buffer=<data[i]>, bufferLength=" << GetMaxTraceLengthToFetch() << ", downSampleRatioMode=PS6000_RATIO_MODE_NONE)";
				GetPicoscope()->SetStatus(ps6000SetDataBuffer(
					GetHandle(),                // handle
					(PS6000_CHANNEL)i,          // channel
					data[i],                    // *buffer
					GetMaxTraceLengthToFetch(), // bufferLength
					PS6000_RATIO_MODE_NONE));   // downSampleRatioMode
			}
			if(GetPicoscope()->GetStatus() != PICO_OK) {
				std::cerr << "Unable to set memory for channel." << std::endl;
				throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
			}
		}
	}
	// fetch data
	length_of_trace_fetched = length_of_trace_askedfor;
	std::cerr << "Get data for points " << GetNextIndex() << "-" << GetNextIndex()+length_of_trace_askedfor << " (" << 100.0*(GetNextIndex()+length_of_trace_askedfor)/GetLength() << "%) ... ";
	t.Start();
	// std::cerr << "length of buffer: " << data_length[0] << ", length of requested trace: " << length_of_trace_askedfor << " ... ";
	if(GetSeries() == PICO_4000) {
		FILE_LOG(logDEBUG2) << "ps4000GetValues(handle=" << GetHandle() << ", startIndex=" << GetNextIndex() << ", *noOfSamples=" << length_of_trace_fetched << ", downSampleRatio=1, downSampleRatioMode=PS4000_RATIO_MODE_NONE, segmentIndex=0, *overflow)";
		GetPicoscope()->SetStatus(ps4000GetValues(
			GetHandle(),                // handle
			// TODO: start index
			GetNextIndex(),             // startIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			&length_of_trace_fetched,   // *noOfSamples
			1,                          // downSampleRatio
			PS4000_RATIO_MODE_NONE,     // downSampleRatioMode
			0,                          // segmentIndex
			&overflow));                // *overflow
		FILE_LOG(logDEBUG2) << "-> length_of_trace_fetched=" << length_of_trace_fetched << "\n";
	} else {
		FILE_LOG(logDEBUG2) << "ps6000GetValues(handle=" << GetHandle() << ", startIndex=" << GetNextIndex() << ", *noOfSamples=" << length_of_trace_fetched << ", downSampleRatio=1, downSampleRatioMode=PS6000_RATIO_MODE_NONE, segmentIndex=0, *overflow)";
		GetPicoscope()->SetStatus(ps6000GetValues(
			GetHandle(),                // handle
			// TODO: start index
			GetNextIndex(),             // startIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			&length_of_trace_fetched,   // *noOfSamples
			1,                          // downSampleRatio
			PS6000_RATIO_MODE_NONE,     // downSampleRatioMode
			0,                          // segmentIndex
			&overflow));                // *overflow
		FILE_LOG(logDEBUG2) << "-> length_of_trace_fetched=" << length_of_trace_fetched << "\n";
	}
	t.Stop();
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to set memory for channel." << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	}
	if(overflow) {
		for(i=0; i<GetNumberOfChannels(); i++) {
			if(overflow & (1<<i)) {
				std::cerr << "Warning: Overflow on channel " << (char)('A'+i) << ".\n";
			}
		}
	}
	if(length_of_trace_fetched != length_of_trace_askedfor) {
		std::cerr << "Warning: The number of read samples was smaller than requested.\n";
	}
	std::cerr << "OK ("<< t.GetSecondsDouble() <<"s)\n";
	SetLengthFetched(length_of_trace_fetched);
	SetNextIndex(GetNextIndex()+length_of_trace_fetched);

	return length_of_trace_fetched;
}
void Measurement::RunBlock()
{
	FILE_LOG(logDEBUG3) << "Measurement::RunBlock";

	int i;
	Timing t;
	uint32_t max_length=0;

	// we will have to start reading our data from beginning again
	SetNextIndex(0);
	// test if channel settings have already been passed to picoscope
	// and only pass them again if that isn't the case
	FILE_LOG(logDEBUG4) << "Measurement::RunBlock - we have " << GetNumberOfChannels() << " channels";
	for(i=0; i<GetNumberOfChannels(); i++) {
		FILE_LOG(logDEBUG4) << "Measurement::RunBlock - setting channel " << (char)('A'+i) << " (which holds index " << GetChannel(i)->GetIndex() << ")";
		GetChannel(i)->SetChannelInPicoscope();
	}
	// this fixes the timebase if more than a single channel is selected
	FixTimebase();
	// timebase
	SetTimebaseInPicoscope();
	// trigger
	if(IsTriggered()) {
		GetTrigger()->SetTriggerInPicoscope();
	}

	// for rapid block mode
	if(GetNTraces() > 1) {
		// TODO - check that GetLength()*GetNumberOfEnabledChannels()*GetNTraces() doesn't exceed the limit
		if(GetSeries() == PICO_4000) {
			FILE_LOG(logDEBUG2) << "ps4000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps4000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		} else {
			FILE_LOG(logDEBUG2) << "ps6000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps6000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		}
		if(GetPicoscope()->GetStatus() != PICO_OK) {
			std::cerr << "Unable to set number of captures to " << GetNTraces() << std::endl;
			throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
		}
		if(GetSeries() == PICO_4000) {
			FILE_LOG(logDEBUG2) << "ps4000MemorySegments(handle=" << GetHandle() << ", nSegments=" << GetNTraces() << ", &max_length=" << max_length << ")";
			GetPicoscope()->SetStatus(ps4000MemorySegments(
				GetHandle(),   // handle
				GetNTraces(),  // nSegments
				&max_length));
			FILE_LOG(logDEBUG2) << "->ps4000MemorySegments(... max_length=" << max_length << ")";
		} else {
			FILE_LOG(logDEBUG2) << "ps6000MemorySegments(handle=" << GetHandle() << ", nSegments=" << GetNTraces() << ", &max_length=" << max_length << ")";
			GetPicoscope()->SetStatus(ps6000MemorySegments(
				GetHandle(),   // handle
				GetNTraces(),  // nSegments
				&max_length));
			FILE_LOG(logDEBUG2) << "->ps6000MemorySegments(... max_length=" << max_length << ")";
		}
		if(GetPicoscope()->GetStatus() != PICO_OK) {
			std::cerr << "Unable to set number of segments to " << GetNTraces() << std::endl;
			throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
		}
		if(max_length < GetLength()) { // TODO: times number of enabled channels
			std::cerr << "The maximum length of trace you can get with " << GetNTraces()
			          << " traces is " << max_length << ", but you requested " << GetLength() << "\n";
			throw;
		}
		if(GetSeries() == PICO_4000) {
			FILE_LOG(logDEBUG2) << "ps4000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps4000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		} else {
			FILE_LOG(logDEBUG2) << "ps6000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps6000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		}
		if(GetPicoscope()->GetStatus() != PICO_OK) {
			std::cerr << "Unable to set number of captures to " << GetNTraces() << std::endl;
			throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
		}
	}

	//std::cerr << "\nPress a key to start fetching the data ...\n";
	//_getch();

	t.Start();
	GetPicoscope()->SetReady(false);
	if(GetSeries() == PICO_4000) {
		FILE_LOG(logDEBUG2) << "ps4000RunBlock(handle=" << GetHandle() << ", noOfPreTriggerSamples=" << GetLengthBeforeTrigger() << ", noOfPostTriggerSamples=" << GetLengthAfterTrigger() << ", timebase=" << timebase << ", oversample=1, *timeIndisposedMs=NULL, segmentIndex=0, lpReady=CallBackBlock, *pParameter=NULL)";
		GetPicoscope()->SetStatus(ps4000RunBlock(
			GetHandle(),              // handle
			GetLengthBeforeTrigger(), // noOfPreTriggerSamples
			GetLengthAfterTrigger(),  // noOfPostTriggerSamples
			timebase,                 // timebase
			1,                        // ovesample
			NULL,                     // *timeIndisposedMs
			0,                        // segmentIndex
			CallBackBlock,            // lpReady
			NULL));                   // *pParameter
	} else {
		FILE_LOG(logDEBUG2) << "ps6000RunBlock(handle=" << GetHandle() << ", noOfPreTriggerSamples=" << GetLengthBeforeTrigger() << ", noOfPostTriggerSamples=" << GetLengthAfterTrigger() << ", timebase=" << timebase << ", oversample=1, *timeIndisposedMs=NULL, segmentIndex=0, lpReady=CallBackBlock, *pParameter=NULL)";
		GetPicoscope()->SetStatus(ps6000RunBlock(
			GetHandle(),              // handle
			GetLengthBeforeTrigger(), // noOfPreTriggerSamples
			GetLengthAfterTrigger(),  // noOfPostTriggerSamples
			timebase,                 // timebase
			1,                        // ovesample
			NULL,                     // *timeIndisposedMs
			0,                        // segmentIndex
			CallBackBlock,            // lpReady
			NULL));                   // *pParameter
	}
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to start collecting samples" << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	} else {
		std::cerr << "Start collecting samples in "
		          << ((GetNTraces() > 1) ? "rapid " : "") << "block mode ... ";
	}
	// TODO: maybe we want it to be asynchronous
	// TODO: catch the _kbhit event!!!
	// while (!Picoscope::IsReady() && !_kbhit()) {
	while (!Picoscope::IsReady()) {
		Sleep(200);
	}
	t.Stop();
	std::cerr << "OK (" << t.GetSecondsDouble() << "s)\n";

	// sets the index from where we want to start reading data to zero
	SetNextIndex(0UL);
}
Exemple #7
0
int main(int argc, char **argv)
{
    ArgumentHandlers::Arguments args;
    argp_parse (&ArgumentHandlers::theArgpStruc, argc, argv, 0, 0, &args);
    int restarts = args.nrRestarts;

    srand(time(0));

    int horizon=args.horizon;

    try {
    //start timers
    Timing Time;    
    Time.Start("Overall");

    DecPOMDPDiscreteInterface & decpomdp = * GetDecPOMDPDiscreteInterfaceFromArgs(args);

    //set the filename etc.
    string filename="/dev/null",timingsFilename="/dev/null";
    ofstream of;
    stringstream ss;
    ss  << directories::MADPGetResultsFilename("JESP",decpomdp,args)
        << SoftPrint(args.jesp) //the jesp type
        << "_h" << horizon
        << "_JESPrestarts"<< restarts;
    //check the method specific arguments and add them to file name
    switch(args.jesp)
    {
    case JESPtype::JESPExhaustive:
        break;
    case JESPtype::JESPDP:
        break;
    }
    if(!args.dryrun)
    {
        filename=ss.str();
        timingsFilename=filename + "_Timings";

        of.open(filename.c_str());
        if(!of)
        {
            cout << "JESP: could not open " << filename << endl;
            cout << "Results will not be stored to disk." << endl;
            args.dryrun=true;
        }

        if(!args.dryrun)
        {
            cout << "Computing " << ss.str() << endl;
            //write headers
            of << "#horiz."<<"\t";
            of << "value     " <<"\t";
            of << "ticks"<< "\t";
            of << "utime" <<"\t";
            of << "found jpol index\t(1tick=1/"<<sysconf(_SC_CLK_TCK)<<"s)\n";
            of.flush();
        }
    }
    
    //Initialization of the planner with typical options for JESP:
    Time.Start("PlanningUnit");
    PlanningUnitMADPDiscreteParameters params;
    params.SetComputeAll(true);
    params.SetComputeJointActionObservationHistories(false);
    params.SetComputeJointObservationHistories(false);
    params.SetComputeJointBeliefs(false);
    if(args.sparse)
        params.SetUseSparseJointBeliefs(true);
    else
        params.SetUseSparseJointBeliefs(false);
    PlanningUnitDecPOMDPDiscrete* jesp = 0;
    if(args.jesp == JESPtype::JESPExhaustive)
    {
        jesp = new JESPExhaustivePlanner (params,horizon,&decpomdp);
        cout << "JESPExhaustivePlanner initialized" << endl;
    }
    else if(args.jesp == JESPtype::JESPDP)
    {
        jesp = new JESPDynamicProgrammingPlanner (params,horizon,&decpomdp);
        cout << "JESPDynamicProgrammingPlanner initialized" << endl;
    }
    Time.Stop("PlanningUnit");
    cout << "JESP Planner initialized" << endl;

    for(int restartI = 0; restartI < restarts; restartI++)
    {
        //start all timers:
        Time.Start("Plan");
        tms ts_before, ts_after;
        clock_t ticks_before, ticks_after;
        ticks_before = times(&ts_before);

        jesp->Plan();
        double V = jesp->GetExpectedReward();
        if(args.verbose >= 0)
        {
            cout << "value="<< V << endl;
            if(args.verbose)        {
            jesp->GetJointPolicyPureVector()->Print();
            cout <<  endl;
            }
        }

        //stop all timers
        ticks_after = times(&ts_after);
        clock_t ticks =  ticks_after - ticks_before;
        clock_t utime =   ts_after.tms_utime - ts_before.tms_utime;
        Time.Stop("Plan");

#if CHECK_RESULT
        ValueFunctionDecPOMDPDiscrete vf(jesp, jesp->GetJointPolicyPureVector());
        double v = vf.CalculateV(true);
        cout << "Validated value (exact/approx):="<<v;
        SimulationDecPOMDPDiscrete sim(*jesp, 1000);
        SimulationResult simres = 
            sim.RunSimulations( jesp->GetJointPolicyPureVector() );
        v = simres.GetAvgReward();
        cout << " / "<<v <<endl;
#endif
        if(!args.dryrun)
        {
            of << horizon<<"\t";
            char formvalue[10];
            sprintf(formvalue, "%.6f", V);
            of << formvalue <<"\t";
            of << ticks <<"\t";
            of << utime <<"\t";
            of << jesp->GetJointPolicyPureVector()->GetIndex() <<"\n";
            of.flush();
        }
    }

    delete jesp;
    
    Time.Stop("Overall");

    if(args.verbose >= 0)
    {
        Time.PrintSummary();
    }
    if(args.saveTimings && !args.dryrun)
        Time.Save(timingsFilename);
    }
    catch(E& e){ e.Print(); }
}
Exemple #8
0
int main(int argc, char **argv)
{
    cout << "DICE: direct CE Policy Search"<<endl;
    cout << "-----------------------------"<<endl;
    // parse the command line arguments
    ArgumentHandlers::Arguments args;
    argp_parse (&ArgumentHandlers::theArgpStruc, argc, argv, 0, 0, &args);
    int restarts = args.nrCERestarts;

    srand(time(0));


    int horizon = args.horizon;
    cout << "Horizon = " << horizon << endl;


    try {
    //start timers
    Timing Time;    
    Time.Start("Overall");

    DecPOMDPDiscreteInterface & decpomdp = * GetDecPOMDPDiscreteInterfaceFromArgs(args);

    // setup the output file stream 
    string filename="/dev/null",timingsFilename="/dev/null";
    ofstream of;
    stringstream ss;
    ss << directories::MADPGetResultsFilename("DICEPS",decpomdp,args)
        << "h" << horizon;
    // add the CE parameters into the output file name
    ss  << "_CEr" << args.nrCERestarts 
        << "_i" << args.nrCEIterations
        << "_s" << args.nrCESamples 
        << "_sfu" << args.nrCESamplesForUpdate
        << "_a" << args.CE_alpha 
        << "_ht" << args.CE_use_hard_threshold
        << "_evals" << args.nrCEEvalutionRuns;
    if(!args.dryrun)
    {
        directories::MADPCreateResultsDir("DICEPS",decpomdp);
        filename=ss.str();
        timingsFilename=filename + "_Timings";
    }
    of.open(filename.c_str());
    if(!of)
    {
        cerr << "could not open " << filename << endl;
        return(1);
    }
    cout << "Computing " << ss.str() << endl;
    //write headers
    of << "#horiz."<<"\t";
    of << "value     " <<"\t";
    of << "wctime"<< "\t";
    of << "utime " <<"\t";
    of << "stime " <<"\t";
    of << "found jpol index\t(1tick=1/"<<sysconf(_SC_CLK_TCK)<<"s)\n";
    of.flush();
    
    //Initialization of the planner with typical options for JESP:
    Time.Start("PlanningUnit");
    PlanningUnitMADPDiscreteParameters params;
    params.SetComputeAll(true);
    params.SetComputeJointActionObservationHistories(false);
    params.SetComputeJointActionHistories(false);
    params.SetComputeIndividualActionObservationHistories(false);
    params.SetComputeIndividualActionHistories(false);
    //params.SetComputeIndividualObservationHistories(false);
    // joint observations histories are needed for
    // efficient computation of joint actions
    params.SetComputeJointObservationHistories(true);
    params.SetComputeJointBeliefs(false);
    if(args.sparse)
        params.SetUseSparseJointBeliefs(true);
    else
        params.SetUseSparseJointBeliefs(false);
    DICEPSPlanner* planner;
    planner = new DICEPSPlanner (params, &decpomdp,
        horizon,
        //CE params
        args.nrCERestarts,
        args.nrCEIterations,
        args.nrCESamples,
        args.nrCESamplesForUpdate, 
        args.CE_use_hard_threshold, //(gamma in CE papers)
        args.CE_alpha, //the learning rate
        args.nrCEEvalutionRuns //the number of evaluation runs
        , args.verbose
    );
    Time.Stop("PlanningUnit");
    cout << "DICEPSPlanner initialized" << endl;

    clock_t total_utime_diceps=0;
    double total_value=0;
    for(int restartI = 0; restartI < restarts; restartI++)
    {
        //start all timers:
        tms ts_before, ts_after;
        clock_t ticks_before, ticks_after;
        Time.Start("Plan");
        ticks_before = times(&ts_before);
        planner->Plan();
        //stop all timers
        ticks_after = times(&ts_after);
        Time.Stop("Plan");
        clock_t ticks =  ticks_after - ticks_before;
        clock_t utime =   ts_after.tms_utime - ts_before.tms_utime;
        clock_t stime =   ts_after.tms_stime - ts_before.tms_stime;

        total_utime_diceps+=utime;

        double V = planner->GetExpectedReward();
        if(args.verbose >= 0)
        {
            cout << "value="<< V << endl;
            if(args.verbose)        {
            planner->GetJointPolicyPureVector()->Print();
            cout <<  endl;
            }
        }
        total_value+=V;
        
        of << horizon<<"\t";
        char formvalue[10];
        sprintf(formvalue, "%.6f", V);
        of << formvalue <<"\t";
        of << ticks <<"\t";
        of << utime <<"\t";
        of << stime <<"\t";
        of << "-1\n";//Cannot get index of joint pol., since  "planner->GetJointPolicyPureVector()->GetIndex()" does not work
        of.flush();

        // output average statistics after completing the last restart
        if(restartI==(restarts-1))
            of << "# h " << args.horizon<<"\t"
               << " avg DICEPS time (s): "
               << (static_cast<double>(total_utime_diceps)/
                   sysconf(_SC_CLK_TCK))/restarts
               << " avg value: " << total_value/restarts
               << endl;
    }
    /* clean up */

    Time.Stop("Overall");

    if(args.verbose >= 0)
    {
        Time.PrintSummary();
        planner->PrintTimersSummary();
    }
#if 0
    if(//args.saveTimings && 
            !args.dryrun)
    {
        Time.Save(timingsFilename);
        planner->SaveTimers(timingsFilename);
    }
#endif
    delete planner;
    }
    catch(E& e){ e.Print(); }
}
Exemple #9
0
int main(int argc, char **argv)
{
    ArgumentHandlers::Arguments args;
    argp_parse (&ArgumentHandlers::theArgpStruc, argc, argv, 0, 0, &args);

    try
    {
        Timing Time;
        cout << "Instantiating the problem..."<<endl;
        DecPOMDPDiscreteInterface* decpomdp = GetDecPOMDPDiscreteInterfaceFromArgs(args);
        cout << "...done."<<endl;

        //set up output files
        string filename="/dev/null", timingsFilename="/dev/null";
        if(!args.dryrun)
        {
            stringstream ss;
            ss  << directories::MADPGetResultsFilename("VI", *decpomdp, args)
                << "_h" << args.horizon;
            filename=ss.str();
            timingsFilename=filename + "_Timings";
            if(!file_exists(filename))
            {
                cout << "VI: could not open " << filename <<endl;
                cout << "Results will not be stored to disk." <<endl;
                args.dryrun = true;
            }
        }

        //start VI
        PlanningUnitDecPOMDPDiscrete *np = new NullPlanner(args.horizon, decpomdp);
        MDPValueIteration vi(*np);
        cout << "Running value iteration..."<<endl;
        Time.Start("Plan");
        vi.Plan();
        Time.Stop("Plan");
        cout << "...done."<<endl;
        QTable q = vi.GetQTable(0); //<- infinite horizon, so get 1 value function of stage 0

        int nrRuns = args.nrRuns; //defaults to 1000, see argumentHandlers.h
        int seed = args.randomSeed; //defaults to 42
        cout << "Simulating policy with nrRuns: "
             << nrRuns << " and seed: " << seed <<endl;
        SimulationDecPOMDPDiscrete sim(*np, nrRuns, seed);

        //write intermediate simulation results to file
        if(!args.dryrun)
            sim.SaveIntermediateResults(filename);

        vector<double> avgRewards;
        double r = runOneSimulation(q, np, sim);
        cout << "...done"<<endl;

        avgRewards.push_back(r);
        cout << "Avg rewards: " << SoftPrintVector(avgRewards) << endl;

        //write VI timing information to file
        if(!args.dryrun)
            Time.Save(timingsFilename);
    }
    catch(E& e){ e.Print(); }

    return(0);
}