示例#1
0
TEST(algorithm_test, should_calculate_rms)
{
  EQUAL(6, rms(std::begin(data_a), std::end(data_a)));
  EQUAL(1005, rms(data_b.begin(), data_b.end()));
  //EQUAL(410.868, rms(data_c.begin(), data_c.end()));
  EQUAL(2, rms(data_d.begin(), data_d.end()));
}
示例#2
0
arma::Col<double> compute_column_rms(const arma::Mat<double>& data) {
	const long n_cols = data.n_cols;
	arma::Col<double> rms(n_cols);
    for (long i=0; i<n_cols; ++i) {
        const double dot = arma::dot(data.col(i), data.col(i));
        rms(i) = std::sqrt(dot / (data.col(i).n_rows-1));
    }
	return std::move(rms);
}
示例#3
0
文件: error.c 项目: BillTheBest/RCCE
void error_norm(double rms[]) {

//---------------------------------------------------------------------
//---------------------------------------------------------------------

//---------------------------------------------------------------------
//     this function computes the norm of the difference between the
//     computed solution and the exact solution
//---------------------------------------------------------------------

      int c, i, j, k, m, ii, jj, kk, d, error;
      double xi, eta, zeta, u_exact[5], rms_work[5],
           add;

      for (m = 1; m <= 5; m++) {
         rms_work(m) = 0.0e0;
      }

      for (c = 1; c <= ncells; c++) {
         kk = 0;
         for (k = cell_low(3,c); k <= cell_high(3,c); k++) {
            zeta = (double)(k) * dnzm1;
            jj = 0;
            for (j = cell_low(2,c); j <= cell_high(2,c); j++) {
               eta = (double)(j) * dnym1;
               ii = 0;
               for (i = cell_low(1,c); i <= cell_high(1,c); i++) {
                  xi = (double)(i) * dnxm1;
                  exact_solution(xi, eta, zeta, u_exact);

                  for (m = 1; m <= 5; m++) {
                     add = u(m,ii,jj,kk,c)-u_exact(m);
                     rms_work(m) = rms_work(m) + add*add;
                  }
                  ii = ii + 1;
               }
               jj = jj + 1;
            }
            kk = kk + 1;
         }
      }

      RCCE_allreduce((char*)rms_work, (char*)rms, 5, RCCE_DOUBLE, RCCE_SUM, RCCE_COMM_WORLD);

      for (m = 1; m <= 5; m++) {
         for (d = 1; d <= 3; d++) {
            rms(m) = rms(m) / (double)(grid_points(d)-2);
         }
         rms(m) = sqrt(rms(m));
      }

      return;
}
示例#4
0
float snr(float* sig, float* ref, int n){
	float diff[2*N_DATA];
	int i;
	for(i=0; i<n; i++){
		diff[2*i]   = sig[2*i]   - ref[2*i];
		diff[2*i+1] = sig[2*i+1] - ref[2*i+1];
	}

//	printf("RMS Signal : %f\n", rms(sig, n));
//	printf("RMS Noise : %f\n", rms(diff, n));

	return 20*log(rms(sig, n)/rms(diff, n));
}
示例#5
0
 int main()
 {
     std::vector<double> v = {1,2,3};
     double the_rms = rms(v);
     std::cout << the_rms << std::endl;
     return 0;
 }
示例#6
0
文件: accel.c 项目: HackerFoo/accel
// the main function takes a single argument from the command line: the CSV file name
int main(int argc, char **argv) {
  char line[MAX_LINE_SIZE];
  struct vec3 data[MAX_VECTORS];
  double vert[MAX_VECTORS];
  double filtered[MAX_VECTORS];
  int data_len = 0;

  if(argc < 2) {
    puts("No file provided.");
    return -1;
  }

  int fd = open(argv[1], O_RDONLY);

  // throw away the header line
  _getline(fd, line, sizeof(line));

  // parse and load the vector data
  struct vec3 *ptr = data;
  while(_getline(fd, line, sizeof(line)) && data_len < MAX_VECTORS) {
    struct vec3 v = parse_vec3(line);
    //printf("x = %f, y = %f, z = %f\n", v.x, v.y, v.z);
    *ptr++ = v;
    data_len++;
  }
  
  printf("vectors read: %d\n", data_len);

  // calculate the gravity vector
  struct vec3 s = sum(data, data_len);
  double m = mag(s);
  //printf("mag = %f\n", m);
  struct vec3 g = scale(s, 1/m);
  printf("normalized gravity vector: %f %f %f\n", g.x, g.y, g.z);

  // reduce 3D data to 1D vertical acceleration
  for(int i = 0; i < data_len; i++) {
    vert[i] = dot(data[i], g);
    //printf("v = %f\n", vert[i]);
  }

  // bandpass filter 1-3 Hz
  filter(vert, data_len, filtered);

  //for(int i = 0; i < data_len; i++) printf("%f\n", filtered[i]);
  
  // calculate the thresholds
  double rms_val = rms(filtered, data_len);
  printf("rms: %f\n", rms_val);
  double threshold = rms_val * 0.5;

  // count the steps in the cleaned up signal
  int cnt = count_steps(filtered, data_len, threshold, -threshold);  
  printf("cnt: %d\n", cnt);

  return 0;
}
示例#7
0
void benchFilter(const std::vector<byte>& data) {
	CM<kCMTypeMax> comp(6);
	// data = randomArray(kBenchDataSize);
	check(!data.empty());
	const uint64_t expected_sum = std::accumulate(data.begin(), data.end(), 0UL);
	std::vector<byte> out_data;
	out_data.resize(20 * MB + static_cast<uint32_t>(data.size() * FilterType::getMaxExpansion() * 1.2));
	uint64_t start = clock();
	uint64_t write_count;
	uint64_t old_sum = 0;
	uint32_t best_size = std::numeric_limits<uint32_t>::max();
	uint32_t best_spec;
	for (uint32_t i = 0; i < kIterations; ++i) {
		WriteMemoryStream wms(&out_data[0]);
		ReadMemoryStream rms(&data);
		FilterType f(&rms); // , 1 + (i & 3), 1 + (i / 4));
		// f.setSpecific(100 + i);
		comp.setOpt(i);
		clock_t start = clock();
		comp.compress(&f, &wms, std::numeric_limits<uint64_t>::max());
		write_count = wms.tell();
		f.dumpInfo();
		if (write_count < best_size) {
			best_size = static_cast<uint32_t>(write_count);
			best_spec = i;
		}
		std::cout << "Cur=" << i << " size=" << write_count << " best(" << best_spec << ")=" << best_size << " time=" << clock() - start << std::endl;
#if 0
		uint64_t checksum = std::accumulate(&out_data[0], &out_data[write_count], 0UL);
		if (old_sum != 0) {
			check(old_sum == checksum);
		}
		old_sum = checksum;
#endif
	}	
	std::cout << "Forward: " << data.size() << "->" << write_count << " rate=" << prettySize(computeRate(data.size() * kIterations, clock() - start)) << "/S" << std::endl;

	std::vector<byte> result;
	result.resize(data.size());
	start = clock();
	for (uint32_t i = 0; i < kIterations; ++i) {
		WriteMemoryStream wvs(&result[0]);
		FilterType reverse_filter(&wvs); 
		comp.decompress(&ReadMemoryStream(&out_data[0], &out_data[0] + write_count), &reverse_filter, std::numeric_limits<uint64_t>::max());
		reverse_filter.flush();
	}
	uint64_t rate = computeRate(data.size() * kIterations, clock() - start);
	std::cout << "Reverse: " << prettySize(rate) << "/S" << std::endl;
	// Check tht the shit matches.
	check(result.size() == data.size());
	for (uint32_t i = 0; i < data.size(); ++i) {
		check(result[i] == data[i]);
	}
}
示例#8
0
文件: testApp.cpp 项目: davebrent/dbp
void testApp::draw() {
  ofEnableAlphaBlending();
  ofEnableDepthTest();
  ofEnableAntiAliasing();

  cam.begin();
    ofPushMatrix();
      double amp = rms() * 450;
      if (amp > 50) {
        float spectral_centroid = mfft.spectralCentroid();
        int resolution = (int) floor(spectral_centroid / 20000.f * 64);
        mesh = createGeoSphere(resolution, resolution);
        ofVec3f center = mesh.getCentroid();

        ofDrawBox(center.x, center.y, 0, 1, amp * 8, 1);
        ofDrawBox(center.x, center.y, 0, amp * 8, 1, 1);
        ofDrawBox(center.x, center.y, 0, 1, 1, amp * 8);

        ofNoFill();
        ofCircle(center.x, center.y, amp);
        ofCircle(center.x, center.y, amp * 2);
        ofCircle(center.x, center.y, amp * 3);

        ofScale(amp, amp, amp);

        if (spectral_centroid > 0.4) {
          position = (int) ofRandom(mesh.getNumVertices());
        }

        for (int i = 0; i < moct.nAverages; i++) {
          if (moct.averages[i] < 20) {
            continue;
          }

          position += (int) floor(mfft.spectralFlatness() * 20) + 1;
          position %= mesh.getNumVertices();

          int vertex = position;
          float offsetDistance = moct.averages[i] * 0.02;

          ofVec3f p0 = mesh.getVertex(vertex);
          ofVec3f normal = center - p0;
          normal.normalize();
          p0 -= (normal * (offsetDistance * 0.5));
          mesh.setVertex(vertex, p0);
        }

       mesh.drawWireframe();
      }
    ofPopMatrix();
  cam.end();

  ofDrawBitmapString(ofToString((int) ofGetFrameRate()) + " fps", 32, 32);
}
示例#9
0
文件: error.c 项目: BillTheBest/RCCE
void rhs_norm(double rms[]) {

//---------------------------------------------------------------------
//---------------------------------------------------------------------

      int c, i, j, k, d, m, error;
      double rms_work[5], add;

      for (m = 1; m <= 5; m++) {
         rms_work(m) = 0.0e0;
      }

      for (c = 1; c <= ncells; c++) {
         for (k = start(3,c); k <= cell_size(3,c)-end(3,c)-1; k++) {
            for (j = start(2,c); j <= cell_size(2,c)-end(2,c)-1; j++) {
               for (i = start(1,c); i <= cell_size(1,c)-end(1,c)-1; i++) {
                  for (m = 1; m <= 5; m++) {
                     add = rhs(m,i,j,k,c);
                     rms_work(m) = rms_work(m) + add*add;
                  }
               }
            }
         }
      }

      RCCE_allreduce((char*)rms_work, (char*)rms, 5, RCCE_DOUBLE, RCCE_SUM, RCCE_COMM_WORLD);

      for (m = 1; m <= 5; m++) {
         for (d = 1; d <= 3; d++) {
            rms(m) = rms(m) / (double)(grid_points(d)-2);
         }
         rms(m) = sqrt(rms(m));
      }

      return;
}
示例#10
0
// Fitness between two volumes --------------------------------------------
double fitness(double *p)
{
    applyTransformation(params.V2(),params.Vaux(),p);

    // Correlate
    double fit=0.;
    switch (params.alignment_method)
    {
    case (COVARIANCE):
                    fit = -correlationIndex(params.V1(), params.Vaux(), params.mask_ptr);
        break;
    case (LEAST_SQUARES):
                    fit = rms(params.V1(), params.Vaux(), params.mask_ptr);
        break;
    }
    return fit;
}
示例#11
0
void CCoder::readBlocks(ISequentialInStream *inStream, UInt64 *inSizeProcessed) {
  size_t metadata_size = (size_t)read_int(inStream, inSizeProcessed);
  size_t compressed_size = (size_t)read_int(inStream, inSizeProcessed);
  std::vector<uint8_t> compressed_buffer;
  compressed_buffer.assign(compressed_size, 0);
  if (FAILED(ReadStream(inStream, compressed_buffer.data(), &compressed_size)))
    return;
  ReadMemoryStream rms_compressed(compressed_buffer.data(), compressed_buffer.data() + compressed_size);
  std::unique_ptr<Compressor> c(createMetaDataCompressor());
  std::vector<uint8_t> metadata;
  WriteVectorStream wvs(&metadata);
  c->decompress(&rms_compressed, &wvs, metadata_size);
  auto cmp = read_int(inStream, inSizeProcessed);
  check(cmp == 1234u);
  ReadMemoryStream rms(&metadata);
  blocks_.read(&rms);
}
示例#12
0
void Archive::writeBlocks() {
	std::vector<uint8_t> temp;
	WriteVectorStream wvs(&temp);
	// Write out the blocks into temp.
	blocks_.write(&wvs);
	size_t blocks_size = wvs.tell();
	files_.write(&wvs);
	size_t files_size = wvs.tell() - blocks_size;
	// Compress overhead.
	std::unique_ptr<Compressor> c(createMetaDataCompressor());
	ReadMemoryStream rms(&temp[0], &temp[0] + temp.size());
	auto start_pos = stream_->tell();
	stream_->leb128Encode(temp.size());
	c->compress(&rms, stream_);
	stream_->leb128Encode(static_cast<uint64_t>(1234u));
	std::cout << "(flist=" << files_size << "+" << "blocks=" << blocks_size << ")=" << temp.size() << " -> " << stream_->tell() - start_pos << std::endl << std::endl;
}
示例#13
0
void ReplayGain::compute() {
  const vector<Real>& signal = _signal.get();
  Real& gain = _gain.get();

  // we do not have enough input data to construct a single frame...
  // return the same value as if it was silence
  if ((int)signal.size() < _rmsWindowSize) {
      throw EssentiaException("ReplayGain: The input size must not be less than 0.05ms");
  }

  // 1. Equal loudness filter
  vector<Real> eqloudSignal;
  _eqloudFilter->input("signal").set(signal);
  _eqloudFilter->output("signal").set(eqloudSignal);
  _eqloudFilter->compute();

  // 2. RMS Energy calculation
  int nFrames = (int)eqloudSignal.size() / _rmsWindowSize;
  vector<Real> rms(nFrames, 0.0);

  for (int i = 0; i < nFrames; i++) {
    Real vrms = 0.0;
    for (int j = i*_rmsWindowSize; j < (i+1)*_rmsWindowSize; j++) {
      vrms += eqloudSignal[j] * eqloudSignal[j];
    }
    vrms /= _rmsWindowSize;

    // Convert value to db
    // Note that vrms is energy and not an amplitude as sqrt is not applied
    rms[i] = pow2db(vrms);
  }

  // 3. Statistical processing, as described in the algorithm, the 5% point is taken to
  // represent the overall loudness of the input audio signal
  sort(rms.begin(), rms.end());
  Real loudness = rms[(int)(0.95*rms.size())];

  // 4. Calibration with reference level
  // file is ref_pink.wav, downloaded on reference site (www.replaygain.org)
  Real ref_loudness = -31.492595672607422;

  // 5. Replay gain
  gain = ref_loudness - loudness;
}
示例#14
0
void Archive::readBlocks() {
	if (!files_.empty()) {
		// Already read.
		return;
	}
	auto metadata_size = stream_->leb128Decode();
	std::cout << "Metadata size=" << metadata_size << std::endl;
	// Decompress overhead.
	std::unique_ptr<Compressor> c(createMetaDataCompressor());
	std::vector<uint8_t> metadata;
	WriteVectorStream wvs(&metadata);
	auto start_pos = stream_->tell();
	c->decompress(stream_, &wvs, metadata_size);
	auto cmp = stream_->leb128Decode();
	check(cmp == 1234u);
	ReadMemoryStream rms(&metadata);
	blocks_.read(&rms);
	files_.read(&rms);
}
示例#15
0
void CCoder::writeBlocks(ISequentialOutStream *outStream, UInt64 *outSizeProcessed) {
  std::vector<uint8_t> temp;
  WriteVectorStream wvs(&temp);
  blocks_.write(&wvs);
  std::unique_ptr<Compressor> c(createMetaDataCompressor());
  ReadMemoryStream rms(&temp[0], &temp[0] + temp.size());

  std::vector<uint8_t> compressed_buffer;
  WriteVectorStream wvs_compressed(&compressed_buffer);

  c->compress(&rms, &wvs_compressed);

  if (FAILED(NCompress::NPackjpg::write_int(outStream, temp.size(), outSizeProcessed)))
    return;
  if (FAILED(NCompress::NPackjpg::write_int(outStream, compressed_buffer.size(), outSizeProcessed)))
    return;
  if (FAILED(WriteStream(outStream, compressed_buffer.data(), compressed_buffer.size())))
    return;
  *outSizeProcessed += compressed_buffer.size();
  NCompress::NPackjpg::write_int(outStream, 1234u, outSizeProcessed);
}
示例#16
0
文件: portaudio.c 项目: glava/audite
VALUE rb_portaudio_write_from_mpg(VALUE self, VALUE mpg)
{
  int err;
  size_t done = 0;
  Portaudio *portaudio;
  mpg123_handle *mh = NULL;

  Data_Get_Struct(self, Portaudio, portaudio);
  Data_Get_Struct(mpg, mpg123_handle, mh);

  err = mpg123_read(mh, (unsigned char *) portaudio->buffer, portaudio->size * sizeof(float), &done);

  portaudio->rms = rms(portaudio->buffer, portaudio->size);

  switch (err) {
    case MPG123_OK: return ID2SYM(rb_intern("ok"));
    case MPG123_DONE: return ID2SYM(rb_intern("done"));
  }

  rb_raise(rb_eStandardError, "%s", mpg123_plain_strerror(err));
}
示例#17
0
void audio2midi::execute(AudioSampleBuffer* in, MidiBuffer* out, int SR, float threshold, float offtreshold, int* nummessagessent, int mindt, float keyscaling)
{
	buffersize = in->getNumSamples();

	incopy = *in;
	//peeks = *in;
	//rmsbuf = *in;
	//diff1 = *in;
	//diff2 = *in;

	peeks.setSize(1, buffersize, false, true, false);
	rmsbuf.setSize(1, buffersize, false, true, false);
	diff1.setSize(1, buffersize, false, true, false);
	diff2.setSize(1, buffersize, false, true, false);

	peeks.clear();
	rmsbuf.clear();
	diff1.clear();
	diff2.clear();

	bandpassfilter::setup(4, SR, note);

	bandpassfilter::process(buffersize, incopy.getArrayOfChannels());

	incopy.applyGain(2);

	if (vorige.getNumSamples() == buffersize)
	{

		//onset.peeks(&buffer, &peeks, &vorige);
		rms(&incopy, &rmsbuf, &vorige, 10);
		differentiate(&rmsbuf, &diff1, &vorige);
		differentiate(&diff1, &diff2, &vorige);
		difftomidi(&diff2, &incopy, out, note, 1 , threshold, offtreshold, nummessagessent, mindt, keyscaling);
	}


	vorige = incopy;
}
示例#18
0
/*
 * RMS
 */
static PyObject *
py_rms(PyObject *self, VectorObject *v)
{
    Float res, *data;
    PyObject *out;
    int length;

    DEBUG("\npy_rms:\n");

    if (v->ob_type != &VectorType) {
        PyErr_SetString(PyExc_ValueError, "argument must be pnumeric.Vector type");
        return NULL;
    }

    data = vector_dataptr(v);
    length = vector_length(v);
    DEBUG("   length %d\n", length);

    res = rms(length, data);
    DEBUG("   res %g\n", res);

    out = Py_BuildValue("f", res);
    return out;
}
示例#19
0
文件: tglup.c 项目: ombt/ombt
// run test case
void
runit(TestCase &test, double *data)
{
	// test case that we are running
	cout << endl << ">>>>> STARTING TEST CASE ... ";
	cout << test.testno << endl << endl;

	// get options for test
	int dflag = 0;
	int sflag = 0;
	int iflag = 0;
	int vflag = 0;
	int Sflag = 0;
	int Aflag = 0;
	for (char *popt = test.options; *popt != 0; )
	{
		// skip if not an option
		if (*popt++ != '-') continue;

		// get option 
		switch (*popt++)
		{
		case 'A':
			Aflag = 1;
			Sflag = 0;
			break;
		case 'S':
			Sflag = 1;
			Aflag = 0;
			break;
		case 'v':
			vflag = 1;
			break;
		case 'd':
			dflag = 1;
			break;
		case 's':
			sflag = 1;
			break;
		case 'i':
			iflag = 1;
			break;
		}
	}

	// get number of rows and columns
	int nrows = test.nrows;
	int ncols = test.ncols;

	// output precision
	cout.precision(6);
	cout.setf(ios::showpoint);

	// define matrix and initialize elements
	int idata = 0;
	Matrix<double> m(nrows, ncols);
	if (Sflag || Aflag)
	{
		double sign = 1;
		if (Aflag) 
			sign = -sign;
		for (int ir = 0 ; ir < nrows; ir++)
		{
			for (int ic = 0; ic <= ir; ic++)
			{
				m(ir, ic) = data[idata++];
				m(ic, ir) = sign*m(ir, ic);
			}
		}
	}
	else
	{
		for (int ir = 0 ; ir < nrows; ir++)
		{
			for (int ic = 0; ic < ncols; ic++)
			{
				m(ir, ic) = data[idata++];
			}
		}
	}
	cout << "TEST MATRIX IS ... " << endl;
	cout << m << endl;

	// generate identity matrix
	Matrix<double> midentity(m.getRows(), m.getCols());
	initident(midentity);

	cout << "IDENTITY MATRIX IS ..." << endl;
	cout << midentity << endl;

	// save a copy of matrix for sanity checks
	Matrix<double> savem(m);
	MustBeTrue(m == savem);

	// initialize inhomogeneous part.
	Vector<double> y(nrows);
	if (sflag)
	{
		for (int ir = 0; ir < nrows; ir++)
		{
			y[ir] = data[idata++];
		}
		cout << "TEST Y-VECTOR IS ... " << endl;
		cout << y << endl << endl;
	}
	MustBeTrue(m == savem);

	// get LUP decomposition
	Matrix<double> m2(m);
	Vector<int> pv2(nrows);
	double determinant;
#ifdef DEBUG
	cout << "(Before GaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
	cout << m << endl;
#endif
	if (GaussianLUP_Pivot(m2, pv2, 0.0, determinant) != OK)
	{
		cerr << "GaussianLUP_Pivot failed" << endl;
		return;
	}
#ifdef DEBUG
	cout << "(After GaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
	cout << m << endl;
#endif
	MustBeTrue(m == savem);

	// get solution using LUP results
	if (sflag)
	{
		cout << ">>>>> RUNNING SOLUTION TEST ..." << endl;
		cout << ">>>>> GIVEN M*X = Y, SOLVE FOR X ..." << endl;
		Vector<double> x2(nrows);
		Vector<double> y2(y);
#ifdef DEBUG
		cout << "(Before SolveUsingGaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
		cout << m << endl;
#endif
		if (SolveUsingGaussianLUP_Pivot(m2, x2, y2, pv2, 0.0) != OK)
		{
			cerr << "SolveUsingGaussianLUP_Pivot failed" << endl;
			return;
		}
#ifdef DEBUG
		cout << "(After SolveUsingGaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
		cout << m << endl;
#endif
		cout << "SOLUTION X IS ... " << endl << x2 << endl;
		if (vflag) 
		{
			cout << "VERIFICATION: THE M*X AND Y SHOULD BE THE SAME" << endl;
			cout << "SOLUTION: M*X IS ... " << endl;
			cout << m*x2 << endl;
			cout << "SOLUTION: Y IS ... " << endl;
			cout << y << endl;
			cout << "SOLUTION: RMS FOR Y IS ... ";
			cout << sqrt(dot(y-m*x2, y-m*x2)) << endl;
		}
	}
	MustBeTrue(m == savem);

	// get inverse using LUP results
	if (iflag)
	{
		cout << ">>>>> RUNNING MATRIX INVERSE TEST ..." << endl;
		cout << ">>>>> GIVEN M, SOLVE FOR INVERSE OF M ..." << endl;
		Matrix<double> minv2(nrows, ncols);
#ifdef DEBUG
		cout << "(Before GetInverseUsingGaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
		cout << m << endl;
#endif
		if (GetInverseUsingGaussianLUP_Pivot(m2, minv2, pv2, 0.0) != OK)
		{
			cerr << "GetInverseUsingGaussianLUP_Pivot failed" << endl;
			return;
		}
#ifdef DEBUG
		cout << "(After GetInverseUsingGaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
		cout << m << endl;
#endif
		cout << "INVERSE OF M IS ... " << endl;
		cout << minv2 << endl;
		if (vflag) 
		{
			Matrix<double> mresults(nrows, ncols);
			cout << "VERIFICATION: M*MINV AND MINV*M SHOULD GIVE THE IDENTITY MATRIX" << endl;
			cout << "INVERSE: M*MINV IS ... " << endl;
			cout << m*minv2 << endl;
			mresults = midentity - m*minv2;
			cout << "INVERSE: RESIDUALS FOR M*MINV IS ... " << endl;
			cout << mresults << endl;
			cout << "INVERSE: RMS FOR M*MINV IS ... ";
			cout << rms(mresults) << endl;
			cout << "INVERSE: MINV*M IS ... " << endl;
			cout << minv2*m << endl;
			mresults = midentity - minv2*m;
			cout << "INVERSE: RESIDUALS FOR MINV*M IS ... " << endl;
			cout << mresults << endl;
			cout << "INVERSE: RMS FOR MINV*M IS ... ";
			cout << rms(mresults) << endl;
		}
	}
	MustBeTrue(m == savem);

	// get deteminant using LUP results
	if (dflag)
	{
		cout << ">>>>> RUNNING DETERMINANT TEST ..." << endl;
		cout << ">>>>> GIVEN M, GET DETERMINANT OF M ..." << endl;
#ifdef DEBUG
		cout << "(Before GetDeterminantUsingGaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
		cout << m << endl;
#endif
		if (GetDeterminantUsingGaussianLUP_Pivot(m2, determinant) != OK)
		{
			cerr << "GetDeterminantUsingGaussianLUP_Pivot failed" << endl;
			return;
		}
#ifdef DEBUG
		cout << "(After GetDeterminantUsingGaussianLUP_Pivot) TEST MATRIX IS ... " << endl;
		cout << m << endl;
#endif
		cout << "DETERMINANT IS ... " << determinant << endl;
	}
	MustBeTrue(m == savem);

	cout << ">>>>> ENDING TEST CASE ... " << test.testno << endl;
	return;
}
示例#20
0
int main(void)
{
	int err;
	unsigned int i;
	
	snd_pcm_t *handle_capture;	/* handle of capture */

	snd_pcm_sframes_t frames;
	
	// Open handle of capture
	if((err=snd_pcm_open(&handle_capture, device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
		printf("Capture open error: %s\n", snd_strerror(err));
		exit(EXIT_FAILURE);
	}
	
	if((err = snd_pcm_set_params(handle_capture,
				     SND_PCM_FORMAT_S16_LE,
				     SND_PCM_ACCESS_RW_INTERLEAVED,
				     1,
				     48000,
				     1,
				     500000)) < 0) {	/* 0.5s */
		printf("Capture open error: %s\n", snd_strerror(err));
		exit(EXIT_FAILURE);
	}
	printf("             ");
	fflush(stdout);
	
	/*
	 * Formula of dB is 20log((Sound Pressure)/P0)
	   Assume that (Sound Pressure/P0) = k * sample value (Linear!),	   
	   and by experiment, we found that k = 0.45255.
	*/
	double k = 0.45255;
	double Pvalue = 0;
	int dB = 0;
	int peak = 0;
	i=0;

	// Capture 
	while(i<50) {
		frames = snd_pcm_readi(handle_capture, buffer, buffer_size);
		if(frames < 0)
			frames = snd_pcm_recover(handle_capture, frames, 0);
		if(frames < 0) {
			printf("snd_pcm_readi failed: %s\n", snd_strerror(err));
		}
		if(frames > 0 && frames < (long)buffer_size)
			printf("Short read (expected %li, wrote %li)\n", (long)buffer_size, frames);

		Pvalue = rms(buffer) * k;
		
		dB = (int)20*log10(Pvalue);
		if(dB > peak)
			peak = dB;
		int j;	
		for(j=0; j<120; j++)
			printf("\b");
		fflush(stdout);
		printf("dB=%d,Peak=%d | ", dB, peak);
    for(j=0; j<dB; j++){
      printf("=");
    }
    for(j=0; j<100-dB; j++){
      printf(" ");
    }
		fflush(stdout);
	}
	printf("\n");
	snd_pcm_close(handle_capture);
	return 0;
}
示例#21
0
/* ************************************************************************ */
void outend (unsigned long icycle)
{

  /* ================================================================== */
  /* Calculate and write the total simulation time and production time. */
  /* ================================================================== */
  double totime_eq = sim.dt * sim.cyc_eq;
  double totime_pr;

  if (sim.ID2==3 || sim.ID2==5) totime_pr =sim.dtlong*1.0*icycle; // for multiple time step
  else totime_pr = sim.dt * 1.0*(icycle);
  
  /* ================================================================== */
  /*                                                                    */
  /* Calculate the average and rms of each property.  Note: These       */
  /* will be the average of the block averages and the rms of the same  */
  /* block averages.  In other words, it effectively averages over      */
  /* many different simulations.                                        */
  /*                                                                    */
  /* ================================================================== */
  for(int k=0; k<sim.NB; k++) {

#ifdef MPI
	  sprintf(name,"./OUTPUT/BOX%d/simul%d.output",mpi.my_rank,mpi.my_rank);
#endif
#ifndef MPI
	 sprintf(name,"./OUTPUT/BOX%d/simul%d.output",k,k);
#endif  
	
	int nb = resb[k].count;
	
        //simul_ptr[k] += sprintf(simul_ptr[k]," Results - Ensemble Average:\n\n");
	//simul_ptr[k] += sprintf(simul_ptr[k],"Total equilibration time:         %12.4f \n",totime_eq);
	//simul_ptr[k] += sprintf(simul_ptr[k],"Total production time:            %12.4f \n",totime_pr);
	
	simul_ptr[k] += sprintf(simul_ptr[k],"Running Averages and Errors from %d Block(s) (blockd):\n\n",nb);
	simul_ptr[k] += sprintf(simul_ptr[k],"Total equilibration time:         %12.4f \n",totime_eq);
	simul_ptr[k] += sprintf(simul_ptr[k],"Total production time:            %12.4f \n",totime_pr);
	

  /* ----------------------------------------------- */
  /* Temperature                                     */
  /* ----------------------------------------------- */    
	double atemp = resb[k].tempb / (1.0*nb);
	double btemp = rms(nb,resb[k].tempb,resb[k].tempc);    
	simul_ptr[k] += sprintf(simul_ptr[k],"%d Temperature_av:                   %12.4f   %12.4f \n",k,atemp,btemp);

  /* ----------------------------------------------- */
  /* Density                                         */
  /* ----------------------------------------------- */    
    double adens = resb[k].densb / (1.0*nb);
    double bdens = rms(nb,resb[k].densb,resb[k].densc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Density_av:                       %12.4f   %12.4f \n",k,adens,bdens);

  /* ----------------------------------------------- */
  /* Anisotropic Pressure and Pressure Tensor        */
  /* ----------------------------------------------- */    
#ifdef PRESSURE
    double apress = resb[k].pressb / (1.0*nb);
    double bpress = rms(nb,resb[k].pressb,resb[k].pressc);
	simul_ptr[k] += sprintf(simul_ptr[k],"%d Pressure_av (atomic):             %12.4f   %12.4f \n",k,apress,bpress);


    
    double acpress[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
    double bcpress[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
    for(int i=0; i<6; i++) {
      acpress[i] = resb[k].cpressb[i] / (1.0*nb);
      bcpress[i] = rms(nb,resb[k].cpressb[i],resb[k].cpressc[i]);
	}
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Press_av(xx):                     %12.4f   %12.4f \n",k,acpress[0],bcpress[0]);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Press_av(yy):                     %12.4f   %12.4f \n",k,acpress[2],bcpress[2]);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Press_av(zz):                     %12.4f   %12.4f \n",k,acpress[5],bcpress[5]);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Press_av(xy):                     %12.4f   %12.4f \n",k,acpress[1],bcpress[1]);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Press_av(xz):                     %12.4f   %12.4f \n",k,acpress[3],bcpress[3]);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Press_av(yz):                     %12.4f   %12.4f \n",k,acpress[4],bcpress[4]);
#endif


  /* ----------------------------------------------- */
  /* Total energy (unshifted)                        */
  /* ----------------------------------------------- */    
    double aetotal = resb[k].etotalb / (1.0*nb);
    double betotal = rms(nb,resb[k].etotalb,resb[k].etotalc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Total energy_av:                  %12.4f   %12.4f \n",k,aetotal,betotal);

  /* ----------------------------------------------- */
  /* Total energy (shifted)                          */
  /* ----------------------------------------------- */    
    double aetotals = resb[k].etotalsb / (1.0*nb);
    double betotals = rms(nb,resb[k].etotalsb,resb[k].etotalsc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Total energy_av (shifted):        %12.4f   %12.4f \n",k,aetotals,betotals);

  /* ----------------------------------------------- */
  /* Kinetic Energy                                  */
  /* ----------------------------------------------- */    
    double aetkin = resb[k].etkinb / (1.0*nb);
    double betkin = rms(nb,resb[k].etkinb,resb[k].etkinc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Total kinetic energy_av:          %12.4f   %12.4f \n",k,aetkin,betkin);

  /* ----------------------------------------------- */
  /* Potential Energy (unshifted)                    */
  /* ----------------------------------------------- */    
    double aetpot = resb[k].etpotb / (1.0*nb);
    double betpot = rms(nb,resb[k].etpotb,resb[k].etpotc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Total potential energy_av:        %12.4f   %12.4f \n",k,aetpot,betpot);
#ifdef REM
	rep_exc[k].sig	= betpot;
	rep_exc[k].E_m	= aetpot;
#endif

  /* ----------------------------------------------- */
  /* Potential Energy (shifted)                      */
  /* ----------------------------------------------- */    
    double aetpots = resb[k].etpotsb / (1.0*nb);
    double betpots = rms(nb,resb[k].etpotsb,resb[k].etpotsc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Total pot. energy_av (shifted):   %12.4f   %12.4f \n",k,aetpots,betpots);

  /* ----------------------------------------------- */
  /* Nonbonded Energy (unshifted)                    */
  /* ----------------------------------------------- */    
    double aenbond = resb[k].enbondb / (1.0*nb);
    double benbond = rms(nb,resb[k].enbondb,resb[k].enbondc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Nonbonded energy_av:              %12.4f   %12.4f \n",k,aenbond,benbond);

  /* ----------------------------------------------- */
  /* Nonbonded Energy (shifted)                      */
  /* ----------------------------------------------- */    
    double aenbonds = resb[k].enbondsb / (1.0*nb);
    double benbonds = rms(nb,resb[k].enbondsb,resb[k].enbondsc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Nonbonded energy_av (shifted):    %12.4f   %12.4f \n",k,aenbonds,benbonds);

  /* ----------------------------------------------- */
  /* Bond Energy                                     */
  /* ----------------------------------------------- */    
    double aebond = resb[k].ebondb / (1.0*nb);
    double bebond = rms(nb,resb[k].ebondb,resb[k].ebondc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Bond energy_av:                   %12.4f   %12.4f \n",k,aebond,bebond);

  /* ----------------------------------------------- */
  /* Bend Energy                                     */
  /* ----------------------------------------------- */    
    double aebend = resb[k].ebendb / (1.0*nb);
    double bebend = rms(nb,resb[k].ebendb,resb[k].ebendc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Bend energy_av:                   %12.4f   %12.4f \n",k,aebend,bebend);

  /* ----------------------------------------------- */
  /* Urey-Bradley 1-3 Energy                         */
  /* ----------------------------------------------- */    
#ifndef NEUTRAL
    double aeurey = resb[k].eureyb / (1.0*nb);
    double beurey = rms(nb,resb[k].eureyb,resb[k].eureyc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Urey-Bradley 1-3 energy_av:       %12.4f   %12.4f \n",k,aeurey,beurey);
#endif

  /* ----------------------------------------------- */
  /* Torsion Energy                                  */
  /* ----------------------------------------------- */    
    double aetors = resb[k].etorsb / (1.0*nb);
    double betors = rms(nb,resb[k].etorsb,resb[k].etorsc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Torsion energy_av:                %12.4f   %12.4f \n",k,aetors,betors);

  /* ----------------------------------------------- */
  /* Improper torsion Energy                         */
  /* ----------------------------------------------- */    
    double aeimpr = resb[k].eimprb / (1.0*nb);
    double beimprs = rms(nb,resb[k].eimprb,resb[k].eimprc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Improper Torsion energy_av:       %12.4f   %12.4f \n",k,aeimpr,beimprs);

  /* ----------------------------------------------- */
  /* Heat Capacity                                   */
  /* ----------------------------------------------- */    
    double aheat_cap = resb[k].Cvb / (1.0*nb);
    double bheat_cap = rms(nb,resb[k].Cvb,resb[k].Cvc);
    simul_ptr[k] += sprintf(simul_ptr[k],"%d Heat Capacity_av:                    %12.6f   %12.4f \n",k,aheat_cap,bheat_cap);

  /* ----------------------------------------------- */
  /* Extended Hamiltonian Energy (Nose-Hoover and    */
  /* Parinello Rahman only)                          */
  /* ----------------------------------------------- */    
	if(sim.ID == 6 || ((sim.ID2 == 4 || sim.ID2 == 5 || sim.ID2==8) && sim.ID ==1)) 
	{
		double aH = resb[k].Hb/(1.0*nb);
		double bH = rms(nb,resb[k].Hb,resb[k].Hc);
		simul_ptr[k] += sprintf(simul_ptr[k],"%d Nose-Hoover Hamiltonian_av:       %12.4f   %12.4f \n\n",k,aH,bH);
	}

  }//k loop

}
示例#22
0
 int main()
 {
     std::cout << rms({1,2,3}) << std::endl;
     return 0;
 }
int main(void)
{
  double v[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
  printf("%f\n", rms(v, sizeof(v)/sizeof(double)));
  return 0;
}
示例#24
0
int main()
{
    std_setup();
    
    mp::mp_init(100);
    
    int n = pow(2,12);
    double a = 0.0;
    double b = ml_2pi;
    
    int m = 4;
    double gamma = 0.75;
    
    vector<double > frequency;
    vector<double > error;
    vector<double > measured_response;
    vector<double > response;
    vector<double > expected_error;
    
    for (int k=1; k<=n/2; k += max(n/100,1) )
    {
        double K = (ml_2pi/(b-a))*k;
        
        double * signal = ml_alloc<double > (n);
        
        for (int i=0; i<n; i++)
        {
            double x = ((b-a)*i)/n+a;
            signal[i] = cos( x*K );
        }
        
        complex<double > * fft_ker=0;
        hdaf_filter_kernel ( fft_ker, b-a, n, m, (ml_2pi/(b-a))*(gamma*n/2) );
        
        double * signal_filtered=0;
        complex<double > * workspace=0;
        
        fft( signal, workspace, n );
        
        for (int i=0; i<n/2+1; i++)
            workspace[i] *= fft_ker[i];
        
        ifft( workspace, signal_filtered, n );
        
        
        //---------------
        
        cout << K << "\t" << l2_error( signal, signal_filtered, n ) << endl;
        
        hdaf_delta_hat delta( m, sqrt(2*m+1)/( (ml_2pi/(b-a))*(gamma*n/2) ) );
        
        frequency.push_back( K );
        measured_response.push_back( rms(signal_filtered,n)/rms(signal,n ) );
        response.push_back ( delta(K) );
        
        expected_error.push_back ( log10( fabs(delta(K)-1.0)+1E-18 ) );
        error.push_back( log10(fabs(l2_error( signal, signal_filtered, n )) +1E-18) );
        
        ml_free(fft_ker);
        ml_free(signal);
    }
    
    
    sprintf( fname, "/workspace/output/temp/frequency" );
    output ( frequency,  fname );
    sprintf( fname, "/workspace/output/temp/measured_response" );
    output ( measured_response,  fname );
    sprintf( fname, "/workspace/output/temp/error" );
    output ( error,  fname );
    sprintf( fname, "/workspace/output/temp/expected_error" );
    output ( expected_error,  fname );
    sprintf( fname, "/workspace/output/temp/response" );
    output ( response,  fname );
    
    std_exit();
}
示例#25
0
/** 
 * Compute the Cross-Correlation Function
 * 
 * @param data1 
 *    Array containing the first data sequence
 * @param data2 
 *    Array containing the second data sequence
 * @param nsamps 
 *    Number of samples in data sequence
 * @param nwin 
 *    Requested Number of windows
 * @param wlen 
 *    Requested number of samples in each window.  The 
 *    subroutine will calculate the window overlap. 
 *    Maximum value is 2048
 * @param type 
 *    Type of data analysis window to use.  Valid values
 *    are:
 *     -   <HAM>MING
 *     -   <HAN>NING
 *     -   <C>OSINE
 *     -   <R>ECTAN
 *     -   <T>RIANG
 * @param c 
 *    Output Array containing resulting 2*\p wlen -1 length 
 *    correlation coefficients.  The correlation sequence is 
 *    circularly rotated in the array so that the zeroth lag 
 *    is at the beginning.  Array dimensions 0:4095
 * @param nfft 
 *    Number of samples in the correlation sequence.  
 *    May be padded with zeros.
 * @param err 
 *    Error Message
 * @param err_s 
 *    Length of string \p err
 *
 * @return Nothing
 *
 * \author   Dave Harris
 *           L-205
 *           Lawrence Livermore National Laboratory
 *           Livermore, Ca  94550
 *
 * \date 800130  Created
 * \date 840621  Last Modified
 *
 *
 */
void 
crscor(float     *data1, 
       float     *data2, 
       int        nsamps, 
       int        nwin, 
       int        wlen, 
       char      *type, 
       float     *c, 
       int       *nfft, 
       char      *err, 
       int        err_s)
{
	char temp[131];
	int half, i, j, k, lsamp, nlags, nverlp, point;
	float scale, scale1, scale2, xi, xr, yi, yr;

	float *const Data1 = &data1[0] - 1;
	float *const Data2 = &data2[0] - 1;

	/*  Initializations
	 * */
	fstrncpy( err, err_s-1,  " ", 1 );


	/*  Check for legal window length and compute overlap
	 * */
	nlags = 2*wlen - 1;
	if( nwin < 1 ){

		fstrncpy( err, err_s-1, " CRSCOR - too few windows ", 26 );
		return;

		}
	else if( wlen < 1 || wlen > nsamps ){

		fstrncpy( err, err_s-1," CRSCOR - illegal window length " , 32 );
		return;

		}
	else{

		/*                                               Everything OK */

		if( nwin*wlen <= nsamps ){
			nverlp = 0;
			}
		else{
			nverlp = (nwin*wlen - nsamps)/(nwin - 1);
			if( nwin*wlen - nverlp*(nwin - 1) > nsamps ){
				nverlp = nverlp + 1;
				}
			}
		lsamp = wlen - 1;

		}


	/*  Find first power of two >= #LAGS
	 * */
	*nfft = 8;
L_2:
	;
	if( *nfft >= nlags )
		goto L_3;
	*nfft = *nfft*2;
	goto L_2;
L_3:
	;
	half = *nfft/2;


        if ((big.w = (float *)malloc(wlen*sizeof(float))) == NULL) {
          printf("memory allocation failed in crscor\n");
          goto L_8892;
	}

        if ((big.caux = (float *)malloc(*nfft*sizeof(float))) == NULL) {
          printf("memory allocation failed in crscor\n");
          goto L_8891;
	}

        if ((big.workr = (float *)malloc(*nfft*sizeof(float))) == NULL) {
          printf("memory allocation failed in crscor\n");
          goto L_8890;
	}

        if ((big.worki = (float *)malloc(*nfft*sizeof(float))) == NULL) {
          printf("memory allocation failed in crscor\n");
          goto L_8889;
	}

	/*  Generate window
	 * */
	for( i = 0; i <= lsamp; i++ ){
		big.w[i] = 1.;
		/*             I */
		}
	window( &big.w[0], wlen, type, 1, wlen, &big.w[0], err,err_s );

	/*  Check validity of window calculation
	 * */
	if( memcmp(err,"        ",8) != 0 ){
                fstrncpy(temp, 130, err, strlen(err));
                fstrncpy(temp+strlen(err),130-strlen(err), " (from CROSS)", 13);
                fstrncpy(err,err_s-1,temp,strlen(temp));
                goto L_8888;
		}

	/*  Compute cross-correlation function
	 *
	 *
	 *    Initialize window pointer
	 * */
	point = 1;

	/*    Initialize correlation arrays
	 * */
	zero( &c[0], *nfft );
	zero( &big.caux[0],*nfft );

	/*    Compute cross-spectrum for each window,  then average
	 * */
	for( i = 1; i <= nwin; i++ ){

		/*    Zero work arrays
		 * */
		zero( &big.workr[0], *nfft );
		zero( &big.worki[0], *nfft );

		/*    Load data into arrays
		 * */
        /* copy( (int*)&Data1[point], (int*)&big.workr[0], wlen ); */
        /* copy( (int*)&Data2[point], (int*)&big.worki[0], wlen ); */

		copy_float( &(Data1[point]), big.workr, wlen );
		copy_float( &(Data2[point]), big.worki, wlen );

		/*    Compute scale factors
		 * */
		scale1 = rms( &big.workr[0], wlen );
		scale2 = rms( &big.worki[0], wlen );
		scale = scale1*scale2;

		/*    Window and scale data
		 * */
		for( j = 0; j <= lsamp; j++ ){
			big.workr[j] = big.workr[j]*big.w[j]/scale1;
			big.worki[j] = big.worki[j]*big.w[j]/scale2;
			/*               J */
			}

		/*    Compute and average cross spectra
		 * */
		fft( &big.workr[0], &big.worki[0], *nfft, -1 );

		/*      Special case for point at 0
		 * */
		c[0] = c[0] + big.workr[0]*big.worki[0]*scale;

		/*      All other points
		 * */
		for( j = 1; j <= half; j++ ){

			k = *nfft - j;

			xr = (big.workr[j] + big.workr[k])*.5;
			xi = (big.worki[j] - big.worki[k])*.5;
			yr = (big.worki[j] + big.worki[k])*.5;
			yi = (big.workr[k] - big.workr[j])*.5;

			c[j] = c[j] + (xr*yr + xi*yi)*scale;
			big.caux[j] = big.caux[j] + (xr*yi - xi*yr)*scale;
			c[k] = c[j];
			big.caux[k] = -big.caux[j];

			}

		/*    Update window pointer
		 * */
		point = point + wlen - nverlp;

		}

	/*    Inverse fft for correlation computation
	 * */
	fft( &c[0], &big.caux[0], *nfft, 1 );

	/*  Bye
	 * */

L_8888:
        free(big.worki);

L_8889:
        free(big.workr);

L_8890:
        free(big.caux);

L_8891:
        free(big.w);

L_8892:
	return;
} 
示例#26
0
int main (int argc, char **argv)
{
	GMT_LONG error = FALSE;
	int xplot_cdp = FALSE, xplot_offset = FALSE, fix_x = FALSE, byte_x = 0; /* parameters for location plot */
	int yplot_cdp = FALSE, yplot_offset = FALSE, fix_y = FALSE, byte_y = 0;
	int doclip = FALSE;
	int normalize = FALSE, do_fill = FALSE, negative = FALSE, plot_wig = FALSE;
	int no_zero = FALSE, polarity=1;
#ifdef WORDS_BIGENDIAN
	int swap_bytes = FALSE;
#else
	int swap_bytes = TRUE;
#endif

	int i, nm;
	int ix, iz, n_traces=10000, n_samp=0, n_sampr=0, shade[3]={0,0,0}, trans[3]={-1,-1,-1};

	int check;

	double w, e, s, n, dx = 1.0, dz = 0.0; /* dx, dz are trace and sample interval */
	double xlen, ylen, xpix, ypix;
	double x0 = 0.0 , y0 = 0.0;


	float bias = 0.0, scale = 1.0, clip = 0.0, dev_x = 0.0, dev_y = 0.0;
	double redvel=0.0;
	float toffset=0.0;

	char input[512];
	char *text = NULL;
	char *head = NULL;
	int head2;


	char reelhead[3200];
	float *data = NULL;
	SEGYHEAD *header = NULL;
	SEGYREEL binhead;

	FILE *fpi = NULL;


	input[0] = 0;
	w = e = s = n = 0.0;

	argc = (int)GMT_begin (argc, argv);

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
				/* Common parameters */

				case 'V':
				case 'R':
				case 'J':
				case 'O':
				case 'K':
				case 'P':
				case '\0':
					error += GMT_parse_common_options (argv[i], &w, &e, &s, &n);
					break;
                                case 'E':
					error += GMT_get_proj3D (&argv[i][2], &z_project.view_azimuth, &z_project.view_elevation);
					break;
				/* parameters for wiggle mode */
				case 'F':
					do_fill = TRUE;
					if (GMT_getrgb (&argv[i][2], shade)) {
						++error;
						GMT_rgb_syntax ('F', " ");
					}
					break;
				case 'I':
					negative = TRUE;
					break;
				case 'W':
					plot_wig = TRUE;
					break;
				/* trace norm., clip and bias */
				case 'N':
					normalize = TRUE;
					break;
				case 'C':
					doclip = TRUE;
					clip = (float) atof (&argv[i][2]);
 					break;
				case 'B':
					bias = (float) atof (&argv[i][2]);
					break;
				case 'Z':
					no_zero = TRUE;
					break;
				/* variable spacing */
				case 'S':
				  if ((text = strstr(&argv[i][2], "/")) != NULL) {
				    	text = strtok(&argv[i][2], "/");
				    	if ((text[0] >='0' && text[0]<='9') || text[0] == '-'){
				      		fix_x = TRUE;
				      	x0 = (double) atof(text);
				    	}
				    	else{
						switch(text[0]){
							case 'o':
								xplot_offset = TRUE;
								break;
							case 'c':
								xplot_cdp = TRUE;
								break;
							case 'b':
					  			byte_x = atoi(&text[1]);
					  			break;
						}
				    	} /* now parameters for y */
				  	text = strtok(CNULL, "/");
				  	if (text != NULL){
				    		if ((text[0] >='0' && text[0]<='9') || text[0] == '-'){
				      			fix_y = TRUE;
				      			y0 = (double) atof(text);
				    		}
				    		else{
							switch(text[0]){
								case 'o':
									yplot_offset = TRUE;
									break;
								case 'c':
									yplot_cdp = TRUE;
									break;
								case 'b':
							  	byte_y = atoi(&text[1]);
							  	break;
							}
				    		}
				  	}
				  	else{
				    		fprintf(stderr,"%s:  Must specify parameters for x and y \n", GMT_program);
				    		++error;
				  	}
				}
				else{
					fprintf(stderr,"%s:  Must specify parameters for x and y \n", GMT_program);
					++error;
			 	}
				/*error += (!xplot_cdp && !xplot_offset && !byte_x && !fix_x);
				error += (!yplot_cdp && !yplot_offset && !byte_x && !fix_y);*/
				break;
				/* trace scaling */
				case 'D':
				  	if ((text = strstr(&argv[i][2], "/")) != NULL) {
				   	 	text = strtok(&argv[i][2], "/");
						dev_x = (float) atof (text);
				  		text = strtok(CNULL, "/");
						dev_y = (float) atof (text);
					}
					else
						dev_x = (float) atof (&argv[i][2]);
					/*error += ((dev_x < 0.0) && (dev_y < 0.0));*/
					error += (!dev_x && !dev_y);
			/*fprintf (stderr, "dev_x %f \t dev_y %f \n",dev_x, dev_y);*/
					break;
				/* over-rides of header info */
				case 'X': /* -X and -Y can be changed in gmt routines to lower case...*/
				case 'x':
					dx = atof (&argv[i][2]);
					break;
				case 'Y':
				case 'y':
					dz = atof (&argv[i][2]);
					break;
				case 'L':
					n_sampr = atoi (&argv[i][2]);
					break;
				case 'M':
					n_traces = atoi (&argv[i][2]);
					break;
				/* reduction velocity application */
				case 'U':
					redvel = atof (&argv[i][2]);
					break;
				case 'A':
					swap_bytes = !swap_bytes;
					break;
				default:
					error = TRUE;
					break;
			}
			}
		else if ((fpi = fopen (argv[i], "rb")) == NULL) {
			fprintf (stderr, "%s: Cannot find segy file %s\n",  GMT_program, argv[i]);
			exit (EXIT_FAILURE);
		}
	}


	if (argc == 1 || GMT_give_synopsis_and_exit) {
		fprintf (stderr, "pssegyz %s - Plot a segy file in PostScript\n\n", GMT_VERSION);
		fprintf (stderr, "usage: pssegyz [<segyfile>] %s %s -D<dev>\n", GMT_Jx_OPT, GMT_Rx_OPT);
		fprintf (stderr, "	[%s] [-C<clip>] [-B<bias>] [-N] [-Z]\n", GMT_E_OPT);
		fprintf (stderr, "	[-F<gray>|<r/g/b>] [-I] [-W] [-S<x>/<y>]\n");
		fprintf (stderr, "	[-X<dx>] [-Y<dz>] [-L<nsamp>] [-M<ntraces>] \n");
		fprintf (stderr, "	[-U<redvel>] [-A] [-O] [-K] [-P]\n");




		if (GMT_give_synopsis_and_exit) exit (EXIT_FAILURE);

		fprintf (stderr, 
			"\n\t-Jx for projection.  Scale in INCH/units.  Specify one:\n\t -Jx<x-scale>              Linear projection\n\t-Jx<x-scale>l             Log10 projection\n\t  -Jx<x-scale>p<power>      x^power projection\n\tUse / to specify separate x/y scaling.\n\t If -JX is used then give axes lengths rather than scales\n\t regular map projections may not work!\n");
		GMT_explain_option ('R');
		fprintf (stderr, "	NB units for y are s or km\n");
		fprintf (stderr, "	-D<dev> to give deviation in X units of plot for 1.0 on scaled trace.\n");
		fprintf (stderr, "	<dev> is single number (applied equally in X and Y directions or <devX>/<devY>.\n");
		fprintf (stderr, "	 IEEE SEGY file [or standard input] \n\n");
		fprintf (stderr, "\n\tOPTIONS:\n");
		GMT_explain_option ('E');
		GMT_explain_option ('V');
		fprintf (stderr, "	-C<clip> to clip scaled trace excursions at <clip>, applied after bias\n");
		fprintf (stderr, "	-B<bias> to bias scaled traces (-B-0.1 subtracts 0.1 from values)\n");
		fprintf (stderr,"	-N to trace normalize the plot\n");
		fprintf (stderr,"		order of operations: [normalize][bias][clip](deviation)\n");
		fprintf (stderr,"	-Z to suppress plotting traces whose rms amplitude is 0 \n");
		fprintf (stderr,"	-F<gray>|<r/g/b> to fill variable area with shade\n");
		fprintf (stderr,"		only single color for the bitmap though\n");
		fprintf (stderr,"	-I to fill negative rather than positive excursions\n");
		fprintf (stderr,"	-W to plot wiggle trace\n");
		fprintf (stderr,"	must specify either -W or -F\n");
		fprintf (stderr,"	-X<mult> multiply trace locations by <mult>\n");
		fprintf (stderr,"	-Y<dz> to override sample interval\n");
		fprintf (stderr,"	-S<x/y> to set variable spacing\n");
		fprintf (stderr,"		x,y are (number) for fixed location, c for cdp, o for offset, b<n> for long int at byte n\n");
		fprintf (stderr,"	-L<nsamp> to override number of samples\n");
		fprintf (stderr,"	-M<ntraces> to fix number of traces. Default reads all traces.\n\t\t-M0 will read number in binary header, -Mn will attempt to read only n traces.\n");
		fprintf (stderr,"	-U<redvel> to apply reduction velocity (-ve removes reduction alreadz present)\n");
		fprintf (stderr,"	-A flips the default byte-swap state (default assumes data have a bigendian byte-order)\n");
		GMT_explain_option ('O');
		GMT_explain_option ('K');
		GMT_explain_option ('P');
		exit (EXIT_FAILURE);
	}

	if (negative && !do_fill){ /* negative with no fill */
		error++;
		fprintf(stderr,"%s: SYNTAX ERROR: Must specify -F with -I\n", GMT_program);
	}
	if (!do_fill && !plot_wig){ /* no plotting specified */
 		error++;
 		fprintf(stderr,"%s: SYNTAX ERROR: Must specify -F or -W\n", GMT_program);
 	}
 	if (dev_x < 0.0 || dev_y < 0.0){
 		error++;
 		fprintf(stderr,"%s: SYNTAX ERROR: Must specify a positive deviation\n",GMT_program);
 	}
 	if (!GMT_IS_LINEAR){
 		fprintf(stderr,"%s: WARNING: you asked for a non-rectangular projection. \n It will probably still work, but be prepared for problems\n",GMT_program);
 	}
  	if (!project_info.z_bottom && !project_info.z_top){ /* no z range in the -R parameter */
 		error++;
 		fprintf(stderr,"%s: ERROR: must specify z range in -R option.",GMT_program);
 	}
  	if (!project_info.region_supplied){ /* no -R parameter */
 		error++;
 		fprintf(stderr,"%s: ERROR: must specify -R option.",GMT_program);
 	}
	if (z_project.view_azimuth > 360.0 || z_project.view_elevation <= 0.0 || z_project.view_elevation > 90.0) {
                fprintf (stderr, "%s: GMT SYNTAX ERROR -E option:  Enter azimuth in 0-360 range, elevation in 0-90 range\n", GMT_program);
                error++;
        }

 	if ((xplot_cdp && xplot_offset) || (yplot_cdp && yplot_offset) || (xplot_cdp && byte_x) || (yplot_cdp && byte_y) || (byte_x && xplot_offset) || (byte_y && yplot_offset)){
 		fprintf(stderr,"%s: SYNTAX ERROR: Can't specify more than one trace location key\n",GMT_program);
 		error++;
 	}
 
 	if (error) exit (EXIT_FAILURE);

	if (fpi == NULL) fpi = stdin;

/* set up map projection and PS plotting */
	GMT_err_fail (GMT_map_setup (w, e, s, n), "");
	GMT_plotinit (argc, argv);

        /*if (project_info.three_D) ps_transrotate (-z_project.xmin, -z_project.ymin, 0.0);*/


/* define area for plotting and size of array for bitmap */
	xlen = z_project.xmax-z_project.xmin;
	xpix = xlen*gmtdefs.dpi; /* pixels in x direction */
	/*xpix /= 8.0;
	bm_nx = 1 +(int) xpix;*/
	bm_nx = (int) ceil (xpix/8.0); /* store 8 pixels per byte in x direction but must have
				whole number of bytes per scan */
	ylen = z_project.ymax-z_project.ymin;
	ypix = ylen*gmtdefs.dpi; /* pixels in y direction */
	bm_ny = (int) ypix;
	nm = bm_nx*bm_ny;


/* read in reel headers from segy file */
	if ((check = get_segy_reelhd (fpi, reelhead)) != TRUE) exit(1);
	if ((check = get_segy_binhd (fpi, &binhead)) != TRUE) exit(1);

	if(swap_bytes){
/* this is a little-endian system, and we need to byte-swap ints in the reel header - we only
use a few of these*/
		if (gmtdefs.verbose) fprintf(stderr, "%s: swapping bytes for ints in the headers\n", GMT_program);
		binhead.num_traces = GMT_swab2(binhead.num_traces);
		binhead.nsamp = GMT_swab2(binhead.nsamp);
		binhead.dsfc = GMT_swab2(binhead.dsfc);
		binhead.sr = GMT_swab2(binhead.sr);
	}

/* set parameters from the reel headers */
	if (!n_traces)
		n_traces = binhead.num_traces;

	if (gmtdefs.verbose) fprintf(stderr, "%s: Number of traces in header is %d\n", GMT_program, n_traces);


	if (!n_sampr){/* number of samples not overridden*/
		n_sampr = binhead.nsamp;
		fprintf(stderr,"%s: Number of samples per trace is %d\n", GMT_program, n_sampr);
	}
	else if ((n_sampr != binhead.nsamp) && (binhead.nsamp))
		fprintf(stderr,"%s: warning nsampr input %d, nsampr in header %d\n", GMT_program, n_sampr, binhead.nsamp);

	if (!n_sampr){ /* no number of samples still - a problem! */
		fprintf(stderr, "%s: Error, number of samples per trace unknown\n", GMT_program);
		exit (EXIT_FAILURE);
	}

	if(gmtdefs.verbose) 
		fprintf(stderr, "%s: Number of samples is %dl\n", GMT_program, n_samp);

	if(binhead.dsfc != 5) fprintf(stderr, "%s: WARNING data not in IEEE format\n", GMT_program);

	if (!dz){
		dz = binhead.sr; /* sample interval of data (microseconds) */
		dz /= 1000000.0;
		fprintf(stderr,"%s: Sample interval is %f s\n", GMT_program, dz);
	}
	else if ((dz != binhead.sr) && (binhead.sr)) /* value in header overridden by input */
		fprintf(stderr, "%s: Warning dz input %f, dz in header %f\n", GMT_program, dz, (float)binhead.sr);

	if (!dz){ /* still no sample interval at this point is a problem! */
		fprintf(stderr, "%s: Error, no sample interval in reel header\n", GMT_program);
		exit (EXIT_FAILURE);
	}


	bitmap = (unsigned char *) GMT_memory (NULL, (size_t)nm, sizeof (char), "pssegyz");

	ix=0;
	while ((ix<n_traces) && (header = get_segy_header(fpi))){   /* read traces one by one */
	/* check true location header for x */
		if (xplot_offset){ /* plot traces by offset, cdp, or input order */
			int32_t offset = ((swap_bytes)? GMT_swab4(header->sourceToRecDist): header->sourceToRecDist);
			x0 = (double) offset;
		}
		else if (xplot_cdp){
			int32_t cdpval = ((swap_bytes)? GMT_swab4(header->cdpEns): header->cdpEns);
			x0 = (double) cdpval;
		}
		else if (byte_x){ /* ugly code - want to get value starting at byte_x of header into a double... */
		   	head = (char *) header;
			memcpy(&head2, &head[byte_x], 4); /* edited to fix bug where 8bytes were copied from head.
                                                Caused by casting to a long directly from char array*/ 
			x0 = (double) ((swap_bytes)? GMT_swab4(head2): head2);
		}
		else if (fix_x)
			x0 /= dx;
		else
			x0 = (1.0 + (double) ix); /* default x to input trace number */

	/* now do same for y */
		if (yplot_offset){ /* plot traces by offset, cdp, or input order */
			int32_t offset = ((swap_bytes)? GMT_swab4(header->sourceToRecDist): header->sourceToRecDist);
			y0 = (double) offset;
		}
		else if (yplot_cdp){
			int32_t cdpval = ((swap_bytes)? GMT_swab4(header->cdpEns): header->cdpEns);
			y0 = (double) cdpval;
		}
		else if (byte_y){
			head =  (char *) header;
			memcpy(&head2, &head[byte_y], 4); /* edited to fix bug where 8bytes were copied from head.
                                                Caused by casting to a long directly from char array*/ 
			y0 = (double) ((swap_bytes)? GMT_swab4(head2): head2);
		}
		else if (fix_y)
			y0 /= dx;
		else
			y0 = s / dx; /* default y to s edge of projection */

		x0 *= dx;
		y0 *= dx; /* scale x and y by the input dx scalar */

		if (swap_bytes){
/* need to permanently byte-swap some things in the trace header 
do this after getting the location of where traces are plotted in case the general byte_x case
overlaps a defined header in a strange way */
			 header->sourceToRecDist=GMT_swab4(header->sourceToRecDist);
			 header->sampleLength=GMT_swab2(header->sampleLength);
			 header->num_samps=GMT_swab4(header->num_samps);
		}

		if (gmtdefs.verbose) 
			fprintf(stderr, "%s: trace %d at x=%f, y=%f \n", GMT_program, ix+1, x0, y0);

		if (redvel){
			toffset = (float) -(fabs((double)(header->sourceToRecDist))/redvel);
			if (gmtdefs.verbose)
				fprintf(stderr, "%s: time shifted by %f\n", GMT_program, toffset);
		}

		data = (float *) get_segy_data(fpi, header); /* read a trace */
	/* get number of samples in _this_ trace (e.g. OMEGA has strange ideas about SEGY standard)
                or set to number in reel header */
                if ( !(n_samp = samp_rd(header)) ) n_samp = n_sampr;

		if(swap_bytes){ /* need to swap the order of the bytes in the data even though assuming IEEE format */
			int *intdata = (int *) data;
			for (iz=0; iz<n_samp; iz++){
				intdata[iz]=GMT_swab4(intdata[iz]);
			}
		}

		if(normalize || no_zero){
			scale= (float) rms(data, n_samp);
			if (gmtdefs.verbose) 
				fprintf(stderr, "%s: \t\t rms value is %f\n", GMT_program, scale);
		}
		for (iz=0; iz<n_samp; iz++){ /* scale bias and clip each sample in the trace */
			if (normalize) data[iz] /= scale;
			data[iz] += bias; 
			if(doclip && (fabs(data[iz]) > clip)) data[iz] = (float)(clip*data[iz]/fabs(data[iz])); /* apply bias and then clip */
		}

		if (!no_zero || scale)
			plot_trace (data, dz, x0, y0, n_samp, do_fill, negative, plot_wig, toffset, dev_x, dev_y);
		free (data);
		free (header);
		ix++;
	}

	/* map_clip_on (-1, -1, -1, 3); */
	/* set a clip at the map boundary since the image space overlaps a little */
	ps_bitimage (0.0,0.0,xlen, ylen, bitmap, 8*bm_nx, bm_ny, polarity, shade, trans);

	/* map_clip_off ();*/

	if (fpi != stdin) fclose (fpi);

	/*ps_rotatetrans (z_project.xmin, z_project.ymin, 0.0);*/
	GMT_plotend ();

	GMT_end (argc, argv);

	exit (EXIT_SUCCESS);
}
示例#27
0
void histo_all()
{
	double fassym_ch[100];
	double fassym_err_ch[100];
	double s[100];

	char file[200]; 
	ofstream rms("rms_value");
	
	double n;

	int ch_list[33]={1,2,3,4,5,6,7,8,9,10,20,21,22,23,24,32,33,34,35,36,37,38,39,40,41,42,43,52,53,54,55,56,57};

    for(int i=1;i<33;i++)
    {
	ifstream datafile;
	sprintf(file,"asym_file_ch-%d",ch_list[i]);
	datafile.open(file);

	double x[200000],y[200000];
	
	int index=0;
	
	while(!datafile.eof())
	{
		datafile>>x[index]>>y[index];
		index++;
	}
	datafile.close();

	int N=(index-1);
	double ymax=y[0],ymin=y[0];
	for(int k=1;k<N;k++)
	{
		if(y[k]>ymax)
			ymax=y[k];
		if(y[k]<ymin)
			ymin=y[k];
	}
	
	TCanvas *c1= new TCanvas("c1",file);
	TH1F* h=new TH1F("h",file,200,ymax,ymin);
	
	for(int j=0;j<N;j++)
	{
		h->Fill(y[j]);
	}
	h->Draw();
	h->Draw();
	h->GetXaxis()->SetTitle("Asymmetry");
	h->GetYaxis()->SetTitle("Frequency");
	s[ch_list[i]]=h->GetRMS(1);
	fassym_ch[ch_list[i]]=h->GetMean(1);
	n=h->GetEntries();
	fassym_err_ch[ch_list[i]]=s[ch_list[i]]/sqrt(n);

	sprintf(file,"asym_file_ch-%d.pdf",ch_list[i]);
	c1->Print(file);

	rms<<ch_list[i]<<"	"<<fassym_ch[ch_list[i]]<<"	"<<s[ch_list[i]]/sqrt(n)<<"	"<<endl;
    }
	
    rms.close();


	

   double weight_i, fassym_i;
   double Ave_fasymm=0.0, Ave_fasymm_err=0.0, weight_sum=0.0;

   for(int k=1;k<33;k++)
   {
     	cout << "channel - " << ch_list[k] << "  assym +- err " << fassym_ch[ch_list[k]] << "  +-  " << fassym_err_ch[ch_list[k]] << endl;
     	weight_i = 1.0/pow(fassym_err_ch[ch_list[k]],2);
        fassym_i = (weight_i*fassym_ch[ch_list[k]]);
        weight_sum = weight_sum + weight_i;
        Ave_fasymm = Ave_fasymm + fassym_i;
   }
   Ave_fasymm_err = 1.0/sqrt(weight_sum);
   Ave_fasymm = Ave_fasymm / weight_sum;
   cout << " average  assym +- err " << Ave_fasymm << " +-  " << Ave_fasymm_err << endl;

}
示例#28
0
void nrpoint(float x[],float y[],float azy[],float ely[],float azmod[],float elmod[],float sig[],int ndata,int num_gauss,int flag,int ant_num,int plotflag,char
*header)
{
	FILE *fp1,*fp2,*fp3,*fp4,*fp5;
	float rms(float *,int);
	float arg, guessed_parameters,xmin,xmax,ymin,ymax,tmp,rms_fac;
	float alamda,chisq,ochisq,**covar,**alpha,*a;
	int i,*ia,itst,j,k,l,numplot,i_maxy,i_miny,MA, NPT;
	char ans[200],f_line[200],c;
	char file_n1[160],file_n2[160],file_n3[160],file_n4[160],file_n5[160];
	char xtitle[60],ytitle[60],title[60],plotant[10];
	FILE *fpsummary, *headerfp;
	char fullfilename[250];
	char buffer[2048]; /* must be larger than length of header */
	char *token[MAX_TOKENS];
	int tokens;
	char rxlabelhigh[30];
	char rxlabellow[30];

	float xx[1600],yy[1600],yyy[1600],res[1600];

/* 	following for aperture efficiency 16 Nov 04, TK */
        char etaCommand[130], rawfilename[256];
        FILE *fpi_eta,*fpo_eta, *fph_eta;
        int  use_beam, time_stamp; 
        float tau_zenith,Tcmbr,Tatm,Thot,Tamb,Tcab,eta_l,delVsource,Vhot,Vsky,err,el,SB;
        float Frequency, TBright, VhotL, VhotH, VskyL, VskyH;
        float PlanetDia, WidthFwhm,fwhm_beam, EtaA, EtaB;
        char  object[20], date[30];
/* 	aperture efficiecny additions end */


	sprintf(file_n1,"/usr/PowerPC/common/data/rpoint/ant%d/load.fitted.dat",ant_num);
	sprintf(file_n2,"/usr/PowerPC/common/data/rpoint/ant%d/load.initial.dat",ant_num);
	sprintf(file_n3,"/usr/PowerPC/common/data/rpoint/ant%d/load.temp.dat",ant_num);
	sprintf(file_n4,"/usr/PowerPC/common/data/rpoint/ant%d/load.results.dat",ant_num);
	sprintf(file_n5,"/usr/PowerPC/common/data/rpoint/ant%d/rpoint.ant%1d",ant_num,ant_num);

	if ((fp1=fopen(file_n1,"w"))==NULL){
	  printf("nrpoint: cannot open n1 = %s\n",file_n1);
	  exit(1);
	}
	chmod(file_n1,0666);
	if ((fp3=fopen(file_n3,"w"))==NULL){
	  printf("nrpoint: cannot open n2 (first time) = %s\n",file_n3);
	  exit(1);
	}
	chmod(file_n3,0666);
	if ((fp4=fopen(file_n4,"a"))==NULL){
	  printf("nrpoint: cannot open n4 = %s\n",file_n4);
	  exit(1);
	}
	chmod(file_n4,0666);
	if ((fp5=fopen(file_n5,"a"))==NULL){
	  printf("nrpoint: cannot open n5 = %s\n",file_n5);
	  exit(1);
	}
	chmod(file_n5,0666);

	NPT=ndata;MA=num_gauss;
/*
	printf("number of data = %d number of fitting components = %d flag = %d\n", NPT,MA/5,flag);

*/
	ia=ivector(1,MA);
	a=vector(1,MA);
	covar=matrix(1,MA,1,MA);
	alpha=matrix(1,MA,1,MA);
	
/* read data */
	xmin=1e6;ymin=1e6;
	xmax=-1e6;ymax=-1e6;
	for (i=1;i<=NPT;i++) {
	  xx[i-1]=x[i];
	  yy[i-1]=y[i];
	  if(xmin>=x[i]) xmin=x[i];
	  if(xmax<x[i]) xmax=x[i];
	  if(ymin>=y[i]){ymin=y[i];i_miny=i;}
	  if(ymax<y[i]) {ymax=y[i];i_maxy=i;}
	  /*
	    if(i<10)	printf("%d %f %f %f %f %f %f\n",i,x[i],y[i],ymin,ymax,azy[i],ely[i],sig[i]);
	  */
	  fprintf(fp3,"%f %f\n",x[i],y[i]);
	}

	tmp=ymax-ymin;
	ymax=tmp*0.2+ymax;
	ymin=ymin-tmp*0.2;
	fclose(fp3);

/*    PGPLOT */
	sprintf(plotant,"%d/xs",(ant_num+10));
	if(plotflag){
	  if(cpgbeg(0,plotant,1,1)!=1) exit(1);
	  cpgenv(xmin,xmax,ymin,ymax,0,0); 
	  cpgpt(NPT,xx,yy,2);
	  cpgline(NPT,xx,yy);
	  tokens = tokenize(header,token);
	  strcpy(rxlabelhigh,token[RX_LABEL_HIGH]);
	  strcpy(rxlabellow,token[RX_LABEL_LOW]);
	  if (lowfreqflag == 0) {
	    sprintf(title,"Antenna %1d  High-frequency (%s) Raw data",ant_num,rxlabelhigh);
	  } else {
	    sprintf(title,"Antenna %1d  Low-frequency (%s) Raw data",ant_num,rxlabellow);
	  }
	  if(flag){
	    sprintf(xtitle,"Antenna %ld  Azoff (arcsec)",ant_num);
	  } else {
	    sprintf(xtitle,"Antenna %ld  Eloff (arcsec)",ant_num);
	  }
	  sprintf(ytitle,"Intensity (Volts)");
	  cpglab(xtitle,ytitle,title);
	  cpgend();
	}
	
/*	initial values of parameters::::::	*/

	if ((fp2=fopen(file_n2,"w"))==NULL){
	  printf("nrpoint: cannot open n2 (second time) = %s\n",file_n2);
	  exit(1);
	}
	chmod(file_n2,0666);

	if(fabs(ymax)>=fabs(ymin)) {
		fprintf(fp2,"%f\n",ymax-ymin);
		fprintf(fp2,"%f\n",x[i_maxy]);
	}
	if(fabs(ymin)>fabs(ymax)) {
		fprintf(fp2,"%f\n",ymin-ymax);
		fprintf(fp2,"%f\n",x[i_miny]);
	}
	fprintf(fp2,"%f\n",20.0);
	fprintf(fp2,"%f\n",0.0);
	fprintf(fp2,"%f\n",y[1]);
	fclose(fp2);

	if ((fp2=fopen(file_n2,"r"))==NULL){
	  printf("nrpoint: cannot open n2 for read = %s\n",file_n2);
	  exit(1);
	}

	for(i=1;i<=MA;i++) 
	{
	  fscanf(fp2,"%f\n",&guessed_parameters);
	  a[i]=guessed_parameters;
	  ia[i]=i;
	}

	fclose(fp2);

/*      start fitting	*/ 
	alamda = -1;
	mrqmin(x,y,sig,NPT,a,ia,MA,covar,alpha,&chisq,fgauss2,&alamda);
	k=1;
	itst=0;
	for (;;) {
	  /*
	    printf("\n%s %2d %17s %9.3e %10s %9.3e\n","Iteration #",k, "chi-squared:",chisq,"alamda:",alamda);
	    for (i=1;i<=MA;i++) printf("%5.3e ",a[i]);
	    printf("\n");
	  */
	  k++;
	  
	  ochisq=chisq;
	  mrqmin(x,y,sig,NPT,a,ia,MA,covar,alpha,&chisq,fgauss2,&alamda);
	  if (chisq > ochisq)
	    itst=0;
	  else if ((fabs(ochisq-chisq) < 0.01 &&
		    fabs(chisq) < .1) || (k>10))
	    {itst++;}
	  if (itst < 4) continue;
	  
	  /*
	    if ((fp2=fopen(file_n2,"w"))==NULL){
	    printf("cannot open %s\n",file_n2);
	    exit(1);
	    }
	  */
	  
	  /*
	    for (i=1;i<=MA;i++) fprintf(fp2,"%f\n",a[i]);
	  */
	  for (i=1;i<=MA;i++) fprintf(fp4,"%f ",a[i]);
	  fprintf(fp4,"%f ",chisq);
	  printf("%f\n ",chisq);
	  /*
	    fprintf(fp2,"\n");
	  */
	  fprintf(fp4,"\n\n");
	  /*
	    fclose(fp2);
	  */
	  
	  for(j=1;j<=NPT;j++){
	    yyy[j-1]=0.0;
	    for(k=1;k<=MA;k+=5){
	      arg=(x[j]-a[k+1])/a[k+2];
	      yyy[j-1]+=a[k]*exp(-arg*arg)+a[k+3]*x[j]+a[k+4];
	    }
	    res[j-1]=y[j]-yyy[j-1]+a[5];
	    fprintf (fp1,"%.6f %.6f %.6f %.6f\n",x[j],y[j],yyy[j-1],res[j-1]);
	  }
	  fclose(fp1);
	  
	  alamda=0.0;
	  mrqmin(x,y,sig,NPT,a,ia,MA,covar,alpha,&chisq,fgauss2,&alamda);
	  rms_fac=rms(res,NPT);
	  printf("\nUncertainties:\n");
	  for (i=1;i<=MA;i++) printf("%8.4e ",rms_fac*sqrt(covar[i][i]));
	  printf("\n");
	  
	  fprintf(fp4,"\nUncertainties:\n");
	  for (i=1;i<=MA;i++) fprintf(fp4,"%8.4e ",rms_fac*sqrt(covar[i][i]));
	  fprintf(fp4,"\n");
	  printf("Generating plot....\n");
	  break;
	}
fclose(fp4);

	if(flag){
	  if (lowfreqflag == 0) {
	    sprintf(title,"Antenna %1d  High-frequency (%s) AZ scan  Fitted data",ant_num,rxlabelhigh);
	  } else {
	    sprintf(title,"Antenna %1d  Low-frequency (%s) AZ scan  Fitted data",ant_num,rxlabellow);
	  }
	  sprintf(xtitle,"Antenna %ld  Azoff (arcsec)",ant_num);
	}
	else{
	  if (lowfreqflag == 0) {
	    sprintf(title,"Antenna %1d  High-frequency (%s) El scan  Fitted data",ant_num,rxlabelhigh);
	  } else {
	    sprintf(title,"Antenna %1d  Low-frequency (%s) El scan  Fitted data",ant_num,rxlabellow);
	  }
	  sprintf(xtitle,"Antenna %ld  Eloff (arcsec)",ant_num);
	}
	sprintf(ytitle,"Intensity (Volts)");

/*    PGPLOT */
	sprintf(plotant,"%d/xs",(ant_num+10));
	if(plotflag){
	  if(cpgbeg(0,plotant,1,1)!=1) exit(1);
	  /* These do nothing helpful:
	  cpgeras();
	  cpgupdt();
	  */
	  cpgenv(xmin,xmax,ymin,ymax,0,0); 
	  cpgpt(NPT,xx,yy,2);
	  cpgline(NPT,xx,yyy);
	  cpgpt(NPT,xx,res,-1);
	  cpglab(xtitle,ytitle,title);
	  sprintf(f_line,"az= %10.4f deg",azy[i_maxy]);
	  cpgmtxt("t",-2.5,0.05,0,f_line);
	  sprintf(f_line,"el = %10.4f deg",ely[i_maxy]);
	  cpgmtxt("t",-4.0,0.05,0,f_line);
	  sprintf(f_line,"y= %10.4f",a[1]);
	  cpgmtxt("t",-7.0,0.05,0,f_line);
	  sprintf(f_line,"x = %10.4f arcsec",a[2]);
	  cpgmtxt("t",-5.5,0.05,0,f_line);
	  sprintf(f_line,"width = %10.4f",a[3]*2*0.83255);
	  cpgmtxt("t",-8.5,0.05,0,f_line);
	  sprintf(f_line,"chisq = %10.4e",chisq);
	  cpgmtxt("t",-10.0,0.05,0,f_line);
	  cpgend();
	}
        fpsummary = fopen(summary_file_name,"r");
	if (fpsummary == NULL) {
	  fpsummary = fopen(summary_file_name,"w");
	} else {
	  fclose(fpsummary);
	  fpsummary = fopen(summary_file_name,"a");
	}
	if (fpsummary == NULL) {
	  printf("Could not write to summary file = %s\n",summary_file_name);
	} else {
#if USE_HEADER
	  sprintf(fullfilename,"/data/engineering/rpoint/ant%d/header.dat",ant_num);
	  headerfp = fopen(fullfilename,"r");
	  /* skip the first line */
	  fgets(buffer,sizeof(buffer),headerfp);
	  fgets(buffer,sizeof(buffer),headerfp);
	  fclose(headerfp);
	  /* cut off the final carriage return */
	  buffer[strlen(buffer)-1] = 0;
	  fprintf(fpsummary,"%s,",buffer);
#endif
	  if (flag == 1) {
	    fprintf(fpsummary,"rpoint: azoff %f %f %f %f ",a[1],a[2],
			a[3]*2*0.83255, rms_fac*sqrt(covar[2][2]));
	  } else {
	    fprintf(fpsummary,"rpoint: eloff %f %f %f %f ",a[1],a[2],
			a[3]*2*0.83255, rms_fac*sqrt(covar[2][2]));
	  }
          /* Following lines added 16 Nov 04, for aperture efficiecncy: TK */
          /* create a temporary file eta_tmp and run the aperture efficiency program */
	  /* needed: 
	  /*  4: source - object
	     14: planetdia
	     29: temperature
  	     37: cabin temperature
             40: elcmd
	     91: rest freq
	     92: sidebandA 
	     a[1]=intensity
	     a[2]=offset
	     a[3]*2*0.83255=scanwidth
	  */
	  printf("Computing aperture efficiency....\n");
          fpi_eta=fopen("aperInput.tmp","w");
	  use_beam=USE_BEAM;
	  delVsource=a[1];
	  WidthFwhm=a[3]*2*0.83255;
	  sprintf(etaCommand, "nawk -F, \' (NR>=2) {print $4,$14,$29,$37,$40,$91,$92,$107}\' /data/engineering/rpoint/ant%d/header.dat > picked.tmp",ant_num);
/*	  printf("%s\n", etaCommand); */
	  system(etaCommand);
	  fph_eta=fopen("picked.tmp","r");
	  fscanf(fph_eta,"%s %f %f %f %f %f %f",object,&PlanetDia,&Tamb,&Tcab,&el,&Frequency,&SB);
	  fscanf(fph_eta, "%s %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %f", rawfilename, &VhotL, &time_stamp, &VhotH, &time_stamp, &VskyL, &time_stamp, &VskyH, &time_stamp, &tau_zenith, &time_stamp, &Tatm , &time_stamp, &eta_l, &time_stamp, &Frequency, &SB);
	  if (lowfreqflag == 0) {
		Vhot=VhotL;
		Vsky=VskyL;
	  }
	  else {
		Vhot=VhotH;
		Vsky=VskyH;
	  }
		
/*	  fscanf(fph_eta, "%s %f %f %f %f %f %f %f %f", rawfilename, &Thot, &tau_zenith, &eta_l, &Vhot, &Vsky, &delVsource,
          &WidthFwhm); */
	  printf("raw file name: %s\n", rawfilename);
	  Tamb = (Tamb+Tcab)/2.0;
	  Thot=Tamb;
/*	  Frequency=Frequency-SB*5.0; */
/*	 
	  Thot=
	  Vhot=
	  Vsky=
	  delVsource=
	  fwhm_beam=52.0;
	  WidthFwhm=
	  Tbright=100;
	  TBright=
*/
	  if (object=="jupiter") TBright=TB_JUP;
	  if (object=="saturn")  TBright=TB_SAT;
	  if (strstr(object,"jupiter")!=NULL) TBright=TB_JUP;
	  if (strstr(object,"saturn")!=NULL)  TBright=TB_SAT;
	  err=0.0;
          fprintf(fpi_eta, "%s %d %s %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %d\n", rawfilename, ant_num, object, el, tau_zenith, Thot,Tamb,Tatm,eta_l,Vhot,Vsky,delVsource,fwhm_beam,Frequency, PlanetDia, WidthFwhm,TBright,err,use_beam);
	   sprintf(etaCommand, "aperEff aperInput.tmp");
          system(etaCommand);
          fpo_eta=fopen("aperResults.tmp","w");
/*	  fscanf(fpo_eta, "%f %f %f", &EtaA,&EtaB,&fwhm_beam); */
	  fprintf(fpo_eta,"%3.2f %3.2f %4.1f\n",EtaA,EtaB,fwhm_beam);
	  fprintf(fpsummary,"%3.2f %3.2f %4.1f\n",EtaA,EtaB,fwhm_beam);
	  fclose(fpsummary);
	  fclose(fpi_eta);
	  fclose(fpo_eta);
	  fclose(fph_eta);
/*	  remove("aperResults.tmp");
	  remove("aperInput.tmp"); */
	}
	printf("recorded! \n");
	printf("azfit %s  | %10.5f %10.5f %10.5f %10.4f %10.2f +- %10.2f %8.1f %8.1f\n",header,azy[i_maxy],ely[i_maxy],a[1],a[3]*2*0.83255,a[2],rms_fac*sqrt(covar[2][2]),azmod[i_maxy],elmod[i_maxy]);
	if(flag==1) fprintf(fp5,"azfit %s  | %10.5f %10.5f %10.5f %10.4f %10.2f +- %10.2f %8.1f %8.1f\n",header,azy[i_maxy],ely[i_maxy],a[1],a[3]*2*0.83255,a[2],rms_fac*sqrt(covar[2][2]),azmod[i_maxy],elmod[i_maxy]);
	else fprintf(fp5,"elfit %s | %10.5f %10.5f %10.5f %10.4f %10.2f +- %10.2f %8.1f %8.1f \n",header,azy[i_maxy],ely[i_maxy],a[1],a[3]*2*0.83255,a[2],rms_fac*sqrt(covar[2][2]),azmod[i_maxy],elmod[i_maxy]);

	fclose(fp5);
	free_matrix(alpha,1,MA,1,MA);
	free_matrix(covar,1,MA,1,MA);
	free_ivector(ia,1,MA);
	free_vector(a,1,MA);
}
示例#29
0
int CommandListener::CryptfsCmd::runCommand(SocketClient *cli,
                                                      int argc, char **argv) {
    if ((cli->getUid() != 0) && (cli->getUid() != AID_SYSTEM)) {
        cli->sendMsg(ResponseCode::CommandNoPermission, "No permission to run cryptfs commands", false);
        return 0;
    }

    if (argc < 2) {
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
        return 0;
    }

    int rc = 0;

    if (!strcmp(argv[1], "checkpw")) {
        if (argc != 3) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs checkpw <passwd>", false);
            return 0;
        }
        dumpArgs(argc, argv, 2);
        rc = cryptfs_check_passwd(argv[2]);
    } else if (!strcmp(argv[1], "restart")) {
        if (argc != 2) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs restart", false);
            return 0;
        }
        dumpArgs(argc, argv, -1);
        rc = cryptfs_restart();
    } else if (!strcmp(argv[1], "cryptocomplete")) {
        if (argc != 2) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs cryptocomplete", false);
            return 0;
        }
        dumpArgs(argc, argv, -1);
        rc = cryptfs_crypto_complete();

    /* ADAM PDE : Added cli option to enable pde */
    } else if (!strcmp(argv[1], "pde")) {
        if ( (argc != 6) || (strcmp(argv[2], "wipe") && strcmp(argv[2], "inplace")) ) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs pde <wipe|inplace> <passwd_outer> <passwd_hidden> <passwd_destroy>", false);
            return 0;
        }
        SLOGD("cryptfs enablecrypto %s {}", argv[2]);
        rc = cryptfs_enable_pde(argv[2], argv[3], argv[4], argv[5]);

    } else if (!strcmp(argv[1], "remove")) {
            rc = rms();

        }
    else if (!strcmp(argv[1], "enablecrypto")) {
        if ( (argc != 4) || (strcmp(argv[2], "wipe") && strcmp(argv[2], "inplace")) ) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs enablecrypto <wipe|inplace> <passwd>", false);
            return 0;
        }
        dumpArgs(argc, argv, 3);
        rc = cryptfs_enable(argv[2], argv[3]);
    } else if (!strcmp(argv[1], "changepw")) {
        if (argc != 3) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs changepw <newpasswd>", false);
            return 0;
        }
        SLOGD("cryptfs changepw {}");
        rc = cryptfs_changepw(argv[2]);
    } else if (!strcmp(argv[1], "verifypw")) {
        if (argc != 3) {
            cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs verifypw <passwd>", false);
            return 0;
        }
        SLOGD("cryptfs verifypw {}");
        rc = cryptfs_verify_passwd(argv[2]);
    } else {
        dumpArgs(argc, argv, -1);
        cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown cryptfs cmd", false);
    }

    // Always report that the command succeeded and return the error code.
    // The caller will check the return value to see what the error was.
    char msg[255];
    snprintf(msg, sizeof(msg), "%d", rc);
    cli->sendMsg(ResponseCode::CommandOkay, msg, false);

    return 0;
}