Example #1
0
//' Generate a White Noise Process (\eqn{WN(\sigma^2)})
//' Generates a White Noise Process with variance parameter \eqn{\sigma ^2}.
//' @param N      An \code{integer} for signal length.
//' @param sigma2 A \code{double} that contains process variance.
//' @return wn A \code{vec} containing the white noise.
//' @backref src/gen_process.cpp
//' @backref src/gen_process.h
//' @keywords internal
//' @examples
//' gen_wn(10, 1.5)
// [[Rcpp::export]]
arma::vec gen_wn(const unsigned int N, const double sigma2 = 1)
{
  arma::vec wn(N);
  double sigma = sqrt(sigma2);
  for(unsigned int i = 0; i < N; i++){
      wn(i) = R::rnorm(0.0, sigma);
  }

	return wn;
}
Example #2
0
//' Generate an ARMA(1,1) sequence
//' 
//' Generate an ARMA(1,1) sequence given \eqn{\phi}, \eqn{\theta}, and \eqn{\sigma^2}.
//' @param N      An \code{integer} for signal length.
//' @param phi    A \code{double} that contains autoregressive.
//' @param theta  A \code{double} that contains moving average.
//' @param sigma2 A \code{double} that contains process variance.
//' @return A \code{vec} containing the MA(1) process.
//' @details
//' The function implements a way to generate the \eqn{x_t}{x[t]} values without calling the general ARMA function.
//' The autoregressive order 1 and moving average order 1 process is defined as \eqn{{x_t} = {\phi _1}{x_{t - 1}} + {w_t} + {\theta _1}{w_{t - 1}} }{x[t] = phi*x[t-1] + w[t] + theta*w[t-1]},
//'  where \eqn{{w_t}\mathop  \sim \limits^{iid} N\left( {0,\sigma _w^2} \right)}{w[t] ~ N(0,sigma^2) iid}
//' 
//' The function first generates a vector of white noise using \code{\link[gmwm]{gen_wn}} and then obtains the
//' ARMA values under the above equation.
//' 
//' @backref src/gen_process.cpp
//' @backref src/gen_process.h
//' @keywords internal
//' @examples
//' gen_ma1(10, .2, 1.2)
// [[Rcpp::export]]
arma::vec gen_arma11(const unsigned int N, const double phi = .1, const double theta = .3, const double sigma2 = 1)
{
  
  arma::vec wn = gen_wn(N+1, sigma2);
  arma::vec arma = arma::zeros<arma::vec>(N+1);
  for(unsigned int i=1; i <= N; i++ )
  {		
    arma(i) = phi*arma(i-1) + theta*wn(i-1) + wn(i);
  }
  
  return arma.rows(1,N);
}
void simplifyWay(const OSMWay &way) {
    if (way.size < 2) {
        /// Rare but exists in map: a node with only one node
        /// -> ignore those artefacts
        Error::warn("Way %llu has only %d nodes", way.id, way.size);
        return;
    }

    static const size_t simplifiedWay_size = 8192; /// largest observed way length is 2304
    static uint64_t simplifiedWay[simplifiedWay_size];
    if (way.size > simplifiedWay_size)
        Error::err("Way %llu of size %d is longer than acceptable (%d)", way.id, way.size, simplifiedWay_size);

    const size_t simplifiedWaySize = applyRamerDouglasPeucker(way, simplifiedWay);
    if (simplifiedWaySize < 2) {
        Error::warn("Way %llu got simplified to only %d nodes", way.id, simplifiedWay);
        return;
    }

    WayNodes wn(simplifiedWaySize);
    memcpy(wn.nodes, simplifiedWay, sizeof(uint64_t) * wn.num_nodes);
    for (size_t k = 0; k < simplifiedWaySize; ++k)
        node2Coord->increaseCounter((simplifiedWay)[k]);
    wayNodes->insert(way.id, wn);
}
Example #4
0
void BigIntegerStrassen::FastFourierTransform(vcomp &vect, bool invert){
    //static long double PI = 3.14159265358979323846;
    static long double PI = 3.14159265358979323846264338327950288419716939937510L;
    
    ll n = (ll)vect.size();
    if (n == 1)  return;

    vcomp vect0(n / 2), vect1(n / 2);
    for (ll i = 0, j = 0; i<n; i += 2, ++j){
        vect0[j] = vect[i];
        vect1[j] = vect[i + 1];
    }

    FastFourierTransform(vect0, invert);
    FastFourierTransform(vect1, invert);

    long double ang = 2 * PI / n * (invert ? -1 : 1);
    std::complex<long double> w(1), wn(cos(ang), sin(ang));
    for (ll i = 0; i < n / 2; ++i) {
        vect[i] = vect0[i] + w * vect1[i];
        vect[i + n / 2] = vect0[i] - w * vect1[i];
        if (invert){
            vect[i] /= 2;
            vect[i + n / 2] /= 2;
        }
        w *= wn;
    }

}
Example #5
0
void FFT(complex a[], int n, int flag)
{
    for(int i = 1, j = n >> 1, k; i < n - 1; ++i)
    {
        if(i < j)
            std::swap(a[i], a[j]);
        for(k = n >> 1; j >= k; k >>= 1)
            j -= k;
        if(j < k)
            j += k;
    }
    for(int i = 1; i < n; i <<= 1)
    {
        complex wn(cos(pi / i), flag * sin(pi / i));
        for(int j = 0; j < n; j += i << 1)
        {
            complex w(1, 0);
            for(int k = 0; k < i; ++k, w = w * wn)
            {
                complex t = w * a[j + k + i];
                a[j + k + i] = a[j + k] - t;
                a[j + k] = a[j + k] + t;
            }
        }
    }
    if(flag == -1)
        for(int i = 0; i < n; ++i)
            a[i].r /= n;
}
Example #6
0
File: fft.hpp Project: maxrev17/hpc
void fft(int n, const std::complex<double> *pIn, std::complex<double> *pOut)
{
	const double pi2=6.283185307179586476925286766559;
	double angle = pi2/n;
	std::complex<double> wn(cos(angle), sin(angle));
	fft_impl(n, wn, pIn, 1, pOut, 1);
}
Example #7
0
File: dft.cpp Project: sanhuan/FFT
ComplexSeries* dft(ComplexSeries* a)
{
	if(NULL == a)
		return NULL;
	int i, j;
	int length = a->getLength();
	if(length <= 0)
		return NULL;
	ComplexNum w(1.0, 0.0);
	ComplexNum wn(-1*length);
	ComplexNum aa;
	ComplexSeries* y = new ComplexSeries(length);
	if(NULL == y)
	{
		cout<<"dft memory malloc failed"<<endl;
		return NULL;
	}
	ComplexNum yy(0.0, 0.0);

	for(i=0;i<length;i++)
	{
		for(j=0;j<length-1;j++)
		{
			aa = *(a->getValue(length-j-1));
			yy = w*(aa+yy);
		}
		aa = *(a->getValue(0));
		yy = yy+aa;
		y->setValue(i, &yy);
		w = w*wn;
		yy.setValue(0.0, 0.0);
	}
	return y;
}
Example #8
0
void fft(vcd &a, bool invert)
{
	int n = a.size();
	if (n == 1)
		return;

	vcd a0, a1;
	a0.resize(n / 2); a1.resize(n / 2);
	for (int i = 0, j = 0; i < n; i += 2, ++j)
	{
		a0[j] = a[i];
		a1[j] = a[i + 1];
	}
	fft(a0, invert);
	fft(a1, invert);

	double ang = 2 * 3.14159265359 / n * (invert ? -1 : 1);
	complex<double> w(1), wn(cos(ang), sin(ang));

	for (int i = 0; i < n / 2; ++i)
	{
		a[i] = a0[i] + (w * a1[i]);
		a[i + n / 2] = a0[i] - (w * a1[i]);
		w = w * wn;
	}
	if (invert)
	{
		for (int i = 0; i < n; ++i)
			a[i] /= 2;
	}
}
Example #9
0
void FFT(complex a[], int n, int flag)
{
	static int bitLen = 0, bitRev[maxm] = {};
	if(n != (1 << bitLen))
	{
		for(bitLen = 0; 1 << bitLen < n; ++bitLen);
		for(int i = 1; i < n; ++i)
			bitRev[i] = (bitRev[i >> 1] >> 1) | ((i & 1) << (bitLen - 1));
	}
	for(int i = 0; i < n; ++i)
		if(i < bitRev[i])
			std::swap(a[i], a[bitRev[i]]);
	for(int i = 1; i < n; i <<= 1)
	{
		complex wn(cos(pi / i), flag * sin(pi / i));
		for(int j = 0; j < n; j += i << 1)
		{
			complex w(1, 0);
			for(int k = 0; k < i; ++k, w = w * wn)
			{
				complex t = w * a[j + k + i];
				a[j + k + i] = a[j + k] - t;
				a[j + k] = a[j + k] + t;
			}
		}
	}
	if(flag == -1)
		for(int i = 0; i < n; ++i)
		{
			a[i].r /= n;
			a[i].i /= n;
		}
}
/*
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
*/
void CForegroundObserver::ConstructL()
{
	CActiveScheduler::Add(this);

	User::LeaveIfError(iWsSession.Connect());
	iWg = RWindowGroup(iWsSession);
	
	User::LeaveIfError(iWg.Construct((TUint32)&iWg, EFalse));
	iWg.SetOrdinalPosition(-1);
	iWg.EnableReceiptOfFocus(EFalse);

//	iWg.SetPointerCapture(RWindowBase::TCaptureDragDrop);

	CApaWindowGroupName* wn(NULL);
	wn =CApaWindowGroupName::NewL(iWsSession);
	if(wn)
	{
		CleanupStack::PushL(wn);
		
		wn->SetHidden(ETrue);
		wn->SetWindowGroupName(iWg);
		
		CleanupStack::PopAndDestroy();
	}
	
	iWg.EnableFocusChangeEvents();
	
	Listen();
}
/*
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
*/
void CKeyObserver::ConstructL()
{
	CActiveScheduler::Add(this);
	iHandle1 = iHandle2 = iHandle3 = iHandle4 = iHandle5 = -1;
	
	User::LeaveIfError(iWsSession.Connect());
	iWg = RWindowGroup(iWsSession);
		
	User::LeaveIfError(iWg.Construct((TUint32)&iWg, EFalse));
	iWg.SetOrdinalPosition(-1);
	iWg.EnableReceiptOfFocus(EFalse);

	CApaWindowGroupName* wn(NULL);
	wn=CApaWindowGroupName::NewL(iWsSession);
	if(wn)
	{
		CleanupStack::PushL(wn);
		
		wn->SetHidden(ETrue);
		wn->SetWindowGroupName(iWg);
		
		CleanupStack::PopAndDestroy();
	}
	
	iWg.EnableOnEvents();

	CaptureKeys();
	Listen();
}
Example #12
0
double v(double m, double phi, double v_0, double mu, double k, double l_0)
{
	/* Calculates the velocity at a point given the velocity d_phi away 
	   from the point we care about. Derivation explained in lab report. 
	*/ 
	return sqrt(((2*r*d_phi)/m)*(wt(m,phi)-Fst(phi,k,l_0)-mu*wn(m,phi)
	       -mu*Fsn(phi,k,l_0)+((mu*m*pow(v_0,2))/(r))
		   +(m*pow(v_0,2)/(2*r*d_phi))));
}
// test only for posix
void tst_QSocketNotifier::posixSockets()
{
    QTcpServer server;
    QVERIFY(server.listen(QHostAddress::LocalHost, 0));

    int posixSocket = qt_safe_socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr;
    addr.sin_addr.s_addr = htonl(0x7f000001);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(server.serverPort());
    qt_safe_connect(posixSocket, (const struct sockaddr*)&addr, sizeof(sockaddr_in));
    QVERIFY(server.waitForNewConnection(5000));
    QScopedPointer<QTcpSocket> passive(server.nextPendingConnection());

    ::fcntl(posixSocket, F_SETFL, ::fcntl(posixSocket, F_GETFL) | O_NONBLOCK);

    {
        QSocketNotifier rn(posixSocket, QSocketNotifier::Read);
        connect(&rn, SIGNAL(activated(int)), &QTestEventLoop::instance(), SLOT(exitLoop()));
        QSignalSpy readSpy(&rn, SIGNAL(activated(int)));
        QVERIFY(readSpy.isValid());
        // No write notifier, some systems trigger write notification on socket creation, but not all
        QSocketNotifier en(posixSocket, QSocketNotifier::Exception);
        connect(&en, SIGNAL(activated(int)), &QTestEventLoop::instance(), SLOT(exitLoop()));
        QSignalSpy errorSpy(&en, SIGNAL(activated(int)));
        QVERIFY(errorSpy.isValid());

        passive->write("hello",6);
        passive->waitForBytesWritten(5000);

        QTestEventLoop::instance().enterLoop(3);
        QCOMPARE(readSpy.count(), 1);
        QCOMPARE(errorSpy.count(), 0);

        char buffer[100];
        int r = qt_safe_read(posixSocket, buffer, 100);
        QCOMPARE(r, 6);
        QCOMPARE(buffer, "hello");

        QSocketNotifier wn(posixSocket, QSocketNotifier::Write);
        connect(&wn, SIGNAL(activated(int)), &QTestEventLoop::instance(), SLOT(exitLoop()));
        QSignalSpy writeSpy(&wn, SIGNAL(activated(int)));
        QVERIFY(writeSpy.isValid());
        qt_safe_write(posixSocket, "goodbye", 8);

        QTestEventLoop::instance().enterLoop(3);
        QCOMPARE(readSpy.count(), 1);
        QCOMPARE(writeSpy.count(), 1);
        QCOMPARE(errorSpy.count(), 0);

        // Write notifier may have fired before the read notifier inside
        // QTcpSocket, give QTcpSocket a chance to see the incoming data
        passive->waitForReadyRead(100);
        QCOMPARE(passive->readAll(), QByteArray("goodbye",8));
    }
    qt_safe_close(posixSocket);
}
Example #14
0
int main( int argc, char *argv[])
{
	try {
		
		// check command line
		if (argc != 2 && argc != 3) {
			std::cerr << "Usage:\n  WNXMLConsole <WN_XML_file> [<semantic_features_XML_file>]\n";
			return 1;
		}

		// init WN
		std::cerr << "Reading XML...\n";
		std::auto_ptr<ML::MultiLog> logger( ML::MultiLog::create( std::cerr, 100));
		std::auto_ptr<LibWNXML::WNQuery> wn( new LibWNXML::WNQuery( argv[1], *logger));
		wn->writeStats( std::cerr);

		// init SemFeatures (if appl.)
		std::auto_ptr<ML_NPro2::SemFeatures> sf( NULL);
		if (argc == 3) {
			std::cerr << "Reading SemFeatures...\n";
			sf = std::auto_ptr<ML_NPro2::SemFeatures>( new ML_NPro2::SemFeatures( *wn));
			std::cerr << sf->readXML( argv[2]) << " pairs read\n";
		}

		// query loop
		std::cerr << "Type your query, or .h for help, .q to quit\n";
		std::string line;
		while (true) {	
			
			std::cerr << ">";
			std::getline( std::cin, line);

			if (line == ".q")
				break;
			else if (line != "") {
				try {
					process_query( *wn, sf.get(), line, std::cout);
				}
				catch (const LibWNXML::InvalidPOSException& e) {
					std::cerr << e.msg() << std::endl;
				}
			}

		} // while (true)

	} // try {
	catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		return 1;
	}
	catch (...) {
		std::cerr << "Unknown exception\n";
		return 1;
	}
	
	return 0;
}
 WindowsManager::WindowID WindowsManager::createWindow (const char* winName)
 {
     std::string wn (winName);
     WindowManagerPtr_t newWindow = WindowManager::create ();
     WindowID windowId = addWindow (wn, newWindow);
     boost::thread refreshThread (boost::bind
             (&WindowsManager::threadRefreshing,
              this, newWindow));
     return windowId;
 }
void tst_QSocketNotifier::posixSockets()
{
#ifndef Q_OS_UNIX
    QSKIP("test only for posix", SkipAll);
#else

    QTcpServer server;
    QVERIFY(server.listen(QHostAddress::LocalHost, 0));

    int posixSocket = qt_safe_socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr;
    addr.sin_addr.s_addr = htonl(0x7f000001);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(server.serverPort());
    qt_safe_connect(posixSocket, (const struct sockaddr*)&addr, sizeof(sockaddr_in));
    QVERIFY(server.waitForNewConnection(5000));
    QScopedPointer<QTcpSocket> passive(server.nextPendingConnection());

    ::fcntl(posixSocket, F_SETFL, ::fcntl(posixSocket, F_GETFL) | O_NONBLOCK);

    {
        QSocketNotifier rn(posixSocket, QSocketNotifier::Read);
        connect(&rn, SIGNAL(activated(int)), &QTestEventLoop::instance(), SLOT(exitLoop()));
        QSignalSpy readSpy(&rn, SIGNAL(activated(int)));
        QSocketNotifier wn(posixSocket, QSocketNotifier::Write);
        connect(&wn, SIGNAL(activated(int)), &QTestEventLoop::instance(), SLOT(exitLoop()));
        QSignalSpy writeSpy(&wn, SIGNAL(activated(int)));
        QSocketNotifier en(posixSocket, QSocketNotifier::Exception);
        connect(&en, SIGNAL(activated(int)), &QTestEventLoop::instance(), SLOT(exitLoop()));
        QSignalSpy errorSpy(&en, SIGNAL(activated(int)));

        passive->write("hello",6);
        passive->waitForBytesWritten(5000);

        QTestEventLoop::instance().enterLoop(3);
        QCOMPARE(readSpy.count(), 1);
        writeSpy.clear(); //depending on OS, write notifier triggers on creation or not.
        QCOMPARE(errorSpy.count(), 0);

        char buffer[100];
        qt_safe_read(posixSocket, buffer, 100);
        QCOMPARE(buffer, "hello");

        qt_safe_write(posixSocket, "goodbye", 8);

        QTestEventLoop::instance().enterLoop(3);
        QCOMPARE(readSpy.count(), 1);
        QCOMPARE(writeSpy.count(), 1);
        QCOMPARE(errorSpy.count(), 0);
        QCOMPARE(passive->readAll(), QByteArray("goodbye",8));
    }
    qt_safe_close(posixSocket);
#endif
}
Example #17
0
//' Generate an Autoregressive Order 1 ( AR(1) ) sequence
//' Generate an Autoregressive Order 1 sequence given \eqn{\phi} and \eqn{\sigma^2}.
//' @param N      An \code{unsigned integer} for signal length.
//' @param phi    A \code{double} that contains autocorrection.
//' @param sigma2 A \code{double} that contains process variance.
//' @return A \code{vec} containing the AR(1) process.
//' @details
//' The function implements a way to generate the AR(1)'s \eqn{x_t}{x[t]} values without calling the general ARMA function.
//' The autoregressive order 1 process is defined as \eqn{{x_t} = {\phi _1}{x_{t - 1}} + {w_t} }{x[t] = phi[1]x[t-1]  + w[t]},
//'  where \eqn{{w_t}\mathop  \sim \limits^{iid} N\left( {0,\sigma _w^2} \right)}{w[t] ~ N(0,sigma^2) iid}
//' 
//' The function first generates a vector of white noise using \code{\link[gmwm]{gen_wn}} and then obtains the
//' AR values under the above equation.
//' @backref src/gen_process.cpp
//' @backref src/gen_process.h
//' @keywords internal
//' @examples
//' gen_ar1(10, 5, 1.2)
// [[Rcpp::export]]
arma::vec gen_ar1(const unsigned int N, const double phi = .3, const double sigma2 = 1)
{

	arma::vec wn = gen_wn(N+1, sigma2);
	arma::vec gm = arma::zeros<arma::vec>(N+1);
	for(unsigned int i=1; i <= N; i++ )
	{		
		gm(i) = phi*gm(i-1) + wn(i);
	}

	return gm.rows(1,N);
}
Example #18
0
void FFT(Complex y[],int len,int on) {
    change(y,len);
    for(int h = 2; h <= len; h <<= 1) {
        Complex wn(cos(-on*2*PI/h),sin(-on*2*PI/h));
        for(int j = 0;j < len;j+=h) {
            Complex w(1,0);
            for(int k = j;k < j+h/2;k++) {
                Complex u = y[k];
                Complex t = w*y[k+h/2];
                y[k] = u+t;
                y[k+h/2] = u-t;
                w = w*wn;
            }
        }
    }
    if(on == -1)
        for(int i = 0;i < len;i++)
            y[i].r /= len;
}
void fft(complex *c, int len, int on)
{
	int i, j, k;
	for (i = 1, j = len / 2; i < len - 1; i++)
	{
		if (i < j)
			swap(c[i], c[j]);
		k = len / 2;
		while (j >= k)
		{
			j -= k;
			k /= 2;
		}
		if (j < k) j += k;
	}

	for (int h = 2; h <= len; h <<= 1)
	{
		complex wn(cos(-on * 2 * PI / h), sin(-on * 2 * PI / h));
		for (int j = 0; j < len; j += h)
		{
			complex w(1, 0);
			for (int k = j; k < j + h / 2; k++)
			{
				complex u = c[k];
				complex t = w * c[k + h / 2];
				c[k] = u + t;
				c[k + h / 2] = u - t;
				w = w * wn;
			}
		}
	}

	if (on == -1)
	for (int i = 0; i < len; i++)
		c[i].r /= len;
}
Example #20
0
double N(double m, double phi, double k, double l_0, double v)
{
	//Calculates the normal force under a specific circumstance
	return (wn(m,phi)+Fsn(phi,k,l_0)-(m*pow(v,2))/r);
}
void nmf(viennacl::matrix_base<NumericT> const & V,
         viennacl::matrix_base<NumericT>       & W,
         viennacl::matrix_base<NumericT>       & H,
         viennacl::linalg::nmf_config const & conf)
{
  viennacl::hsa::context & ctx = const_cast<viennacl::hsa::context &>(viennacl::traits::hsa_context(V));

  const std::string NMF_MUL_DIV_KERNEL = "el_wise_mul_div";

  viennacl::linalg::opencl::kernels::nmf<NumericT, viennacl::hsa::context>::init(ctx);

  vcl_size_t k = W.size2();
  conf.iters_ = 0;

  if (viennacl::linalg::norm_frobenius(W) <= 0)
    W = viennacl::scalar_matrix<NumericT>(W.size1(), W.size2(), NumericT(1), ctx);

  if (viennacl::linalg::norm_frobenius(H) <= 0)
    H = viennacl::scalar_matrix<NumericT>(H.size1(), H.size2(), NumericT(1), ctx);

  viennacl::matrix_base<NumericT> wn(V.size1(), k, W.row_major(), ctx);
  viennacl::matrix_base<NumericT> wd(V.size1(), k, W.row_major(), ctx);
  viennacl::matrix_base<NumericT> wtmp(V.size1(), V.size2(), W.row_major(), ctx);

  viennacl::matrix_base<NumericT> hn(k, V.size2(), H.row_major(), ctx);
  viennacl::matrix_base<NumericT> hd(k, V.size2(), H.row_major(), ctx);
  viennacl::matrix_base<NumericT> htmp(k, k, H.row_major(), ctx);

  viennacl::matrix_base<NumericT> appr(V.size1(), V.size2(), V.row_major(), ctx);

  NumericT last_diff = 0;
  NumericT diff_init = 0;
  bool stagnation_flag = false;

  for (vcl_size_t i = 0; i < conf.max_iterations(); i++)
  {
    conf.iters_ = i + 1;
    {
      hn = viennacl::linalg::prod(trans(W), V);
      htmp = viennacl::linalg::prod(trans(W), W);
      hd = viennacl::linalg::prod(htmp, H);

      viennacl::hsa::kernel & mul_div_kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::nmf<NumericT>::program_name(), NMF_MUL_DIV_KERNEL);
      viennacl::hsa::enqueue(mul_div_kernel(H, hn, hd, cl_uint(H.internal_size1() * H.internal_size2())));
    }
    {
      wn = viennacl::linalg::prod(V, trans(H));
      wtmp = viennacl::linalg::prod(W, H);
      wd = viennacl::linalg::prod(wtmp, trans(H));

      viennacl::hsa::kernel & mul_div_kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::nmf<NumericT>::program_name(), NMF_MUL_DIV_KERNEL);

      viennacl::hsa::enqueue(mul_div_kernel(W, wn, wd, cl_uint(W.internal_size1() * W.internal_size2())));
    }

    if (i % conf.check_after_steps() == 0)  //check for convergence
    {
      appr = viennacl::linalg::prod(W, H);

      appr -= V;
      NumericT diff_val = viennacl::linalg::norm_frobenius(appr);

      if (i == 0)
        diff_init = diff_val;

      if (conf.print_relative_error())
        std::cout << diff_val / diff_init << std::endl;

      // Approximation check
      if (diff_val / diff_init < conf.tolerance())
        break;

      // Stagnation check
      if (std::fabs(diff_val - last_diff) / (diff_val * NumericT(conf.check_after_steps())) < conf.stagnation_tolerance()) //avoid situations where convergence stagnates
      {
        if (stagnation_flag)    // iteration stagnates (two iterates with no notable progress)
          break;
        else
          // record stagnation in this iteration
          stagnation_flag = true;
      } else
        // good progress in this iteration, so unset stagnation flag
        stagnation_flag = false;

      // prepare for next iterate:
      last_diff = diff_val;
    }
  }
}
Example #22
0
void basics::Persistor_blog::write_blog(bfs::path content_storage_file, basics::Persistable_blog blog)
{
    // Getting containers
    std::vector<basics::Post> posts = blog.posts();
    basics::Configuration_blog config = blog.config();

    // Declaration
    rapidxml::xml_document<> content;
    rapidxml::xml_node<> *decl = content.allocate_node(rapidxml::node_declaration);
    decl->append_attribute(content.allocate_attribute("version", "1.0"));
    decl->append_attribute(content.allocate_attribute("encoding", "utf-8"));
    content.append_node(decl);

    // Blog root <blog>
    rapidxml::xml_node<> *blog_root = content.allocate_node(rapidxml::node_element, "blog");
    content.append_node(blog_root);

    // Configuration <config>
    rapidxml::xml_node<> *conf = content.allocate_node(rapidxml::node_element, "config");
    blog_root->append_node(conf);
    wn(conf, "meta-desc", config.meta_desc_);
    wn(conf, "meta-author", config.meta_author_);
    wn(conf, "meta-title", config.meta_title_);
    wn(conf, "meta-conf-bootstrap", config.bootstrap_);
    wn(conf, "meta-conf-css", config.css_);
    wns(conf, "nav-items", "href", "item", config.menu_);
    wn(conf, "home-link", config.home_link_);
    wn(conf, "title", config.title_);
    wn(conf, "subtitle", config.subtitle_);
    wn(conf, "about", config.about_, "line", config.about_headline_);
    wns(conf, "links", "href", "item", config.links_, "line", config.links_headline_);
    wn(conf, "philosophy", config.philosophy_);
    wn(conf, "backtotop", config.back_to_top_);
    wn(conf, "post-per-page", std::to_string(config.post_per_page_));

    // Post root <post prev="#" next="#">
    rapidxml::xml_node<> *post_node = content.allocate_node(rapidxml::node_element, "posts");
    rapidxml::xml_attribute<> *prev_attr = content.allocate_attribute("prev", "#");
    post_node->append_attribute(prev_attr);
    rapidxml::xml_attribute<> *next_attr = content.allocate_attribute("next", "#");
    post_node->append_attribute(next_attr);
    blog_root->append_node(post_node);

    for (std::vector<basics::Post>::iterator it = posts.begin(); it != posts.end(); ++it) {
        char *timestamp_str = content.allocate_string(it->get_timestamp_str().c_str());
        char *author = content.allocate_string(it->get_author().c_str());
        char *title = content.allocate_string(it->get_title().c_str());

        std::string escaped_life = basics::escape_string(it->get_life());
        char *life = content.allocate_string(escaped_life.c_str());

        // Building new post node
        rapidxml::xml_node<> *another_post = content.allocate_node(rapidxml::node_element, "post");
        rapidxml::xml_attribute<> *date_attr = content.allocate_attribute("date", timestamp_str);
        another_post->append_attribute(date_attr);
        rapidxml::xml_attribute<> *author_attr = content.allocate_attribute("author", author);
        another_post->append_attribute(author_attr);
        rapidxml::xml_node<> *title_child = content.allocate_node(rapidxml::node_element, "title", title);
        another_post->append_node(title_child);
        rapidxml::xml_node<> *mylife_child = content.allocate_node(rapidxml::node_element, "mylife", life);
        another_post->append_node(mylife_child);

        // Adding edition dates
        rapidxml::xml_node<> *eds_node = content.allocate_node(rapidxml::node_element, "editions");
        std::vector<std::string> editions = it->editions();
        for (std::vector<std::string>::iterator it = editions.begin(); it != editions.end(); ++it) {
            char *edition = content.allocate_string(it->c_str());
            rapidxml::xml_node<> *ed_node = content.allocate_node(rapidxml::node_element, "edition", edition);
            eds_node->append_node(ed_node);
        }
        another_post->append_node(eds_node);

        // Adding node to post root
        post_node->append_node(another_post);
    }

    std::string content_string;
    rapidxml::print(std::back_inserter(content_string), content);

    std::ofstream content_output_stream(content_storage_file.string());
    content_output_stream << content_string;
    content_output_stream.close();
}
void Algorithm::FFT(QVector< std::complex<double> > &a, bool invert)
{
    //qDebug()<<a;
    int n=a.length();
    if(n==1)
    {
        return;
    }
    int i;
    QVector< std::complex<double> >a0(n/2),a1(n/2);
    for(i=0;i<n;i+=2)
    {

        a0[i/2]=a[i];
        a1[i/2]=a[i+1];
    }
    FFT(a0,invert);
    FFT(a1,invert);
    static double pi_2;//=M_PI *2;
    double ang=(pi_2/n)*(invert?-1:1);
    std::complex<double> w(1),wn(cos(ang),sin(ang));
    for(i=0;i<n/2;i++)
    {
        a[i]=a0[i]+w*a1[i];
        a[i+ n/2 ]=a0[i]-w*a1[i];
        if(invert)
        {
            a[i]/=2;
            a[i+ n/2 ]/=2;
        }
        w*=wn;

    }
    /*/
    int i,j=0;
    int n=a.length();
    //double pi_2=M_PI *2;
    double ang;
    std::complex<double> w,wn;
    QVector< std::complex<double> > _a(n);
    for(i=0;i<n;i++)
    {
        a_[j]=a[i];
        j=j+n/2;
    }
    n/=2;
    for(;n>1;n/=2)
    {
        ang=(M_PI/n)*(invert?-1:1);
        qDebug()<<"length"<<n;
        w=1,wn={cos(ang),sin(ang)};
        i=0;
        j=0;
        while(1)
        {
            _a[i]=a[i]+w*a[i+n/2];
            _a[i+n]=a[i]-w*a[i+n/2];
            i++,j++;
            if(j==n/2)
            {
                w*=wn;
                j=0;
                i+=n/2;
            }
            qDebug()<<i<<j;
            if(i>=a.length())
            {
                break;
            }
            a=_a;
        }

    }
    /*/
}
Example #24
0
    void nmf(viennacl::matrix<ScalarType> const & v,
             viennacl::matrix<ScalarType> & w,
             viennacl::matrix<ScalarType> & h,
             std::size_t k,
             ScalarType eps = 0.000001,
             std::size_t max_iter = 10000,
             std::size_t check_diff_every_step = 100)
    {
      viennacl::linalg::kernels::nmf<ScalarType, 1>::init();
      
      w.resize(v.size1(), k);
      h.resize(k, v.size2());

      std::vector<ScalarType> stl_w(w.internal_size1() * w.internal_size2());
      std::vector<ScalarType> stl_h(h.internal_size1() * h.internal_size2());

      for (std::size_t j = 0; j < stl_w.size(); j++)
          stl_w[j] = static_cast<ScalarType>(rand()) / RAND_MAX;

      for (std::size_t j = 0; j < stl_h.size(); j++)
          stl_h[j] = static_cast<ScalarType>(rand()) / RAND_MAX;

      viennacl::matrix<ScalarType> wn(v.size1(), k);
      viennacl::matrix<ScalarType> wd(v.size1(), k);
      viennacl::matrix<ScalarType> wtmp(v.size1(), v.size2());

      viennacl::matrix<ScalarType> hn(k, v.size2());
      viennacl::matrix<ScalarType> hd(k, v.size2());
      viennacl::matrix<ScalarType> htmp(k, k);

      viennacl::matrix<ScalarType> appr(v.size1(), v.size2());
      viennacl::vector<ScalarType> diff(v.size1() * v.size2());

      viennacl::fast_copy(&stl_w[0], &stl_w[0] + stl_w.size(), w);
      viennacl::fast_copy(&stl_h[0], &stl_h[0] + stl_h.size(), h);

      ScalarType last_diff = 0.0f;


      
      for (std::size_t i = 0; i < max_iter; i++)
      {
        {
          hn = viennacl::linalg::prod(trans(w), v);
          htmp = viennacl::linalg::prod(trans(w), w);
          hd = viennacl::linalg::prod(htmp, h);

          viennacl::ocl::kernel & mul_div_kernel = viennacl::ocl::get_kernel(viennacl::linalg::kernels::nmf<ScalarType, 1>::program_name(), 
                                                                             NMF_MUL_DIV_KERNEL);
          viennacl::ocl::enqueue(mul_div_kernel(h, hn, hd, cl_uint(stl_h.size())));
        }
        {
          wn = viennacl::linalg::prod(v, trans(h));
          wtmp = viennacl::linalg::prod(w, h);
          wd = viennacl::linalg::prod(wtmp, trans(h));

          viennacl::ocl::kernel & mul_div_kernel = viennacl::ocl::get_kernel(viennacl::linalg::kernels::nmf<ScalarType, 1>::program_name(), 
                                                                             NMF_MUL_DIV_KERNEL);
          
          viennacl::ocl::enqueue(mul_div_kernel(w, wn, wd, cl_uint(stl_w.size())));
        }

        if (i % check_diff_every_step == 0)
        {
          appr = viennacl::linalg::prod(w, h);

         viennacl::ocl::kernel & sub_kernel = viennacl::ocl::get_kernel(viennacl::linalg::kernels::nmf<ScalarType, 1>::program_name(), 
                                                                        NMF_SUB_KERNEL);
          //this is a cheat. i.e save difference of two matrix into vector to get norm_2
          viennacl::ocl::enqueue(sub_kernel(appr, v, diff, cl_uint(v.size1() * v.size2())));
          ScalarType diff_val = viennacl::linalg::norm_2(diff);

          if((diff_val < eps) || (fabs(diff_val - last_diff) < eps))
          {
              //std::cout << "Breaked at diff - " << diff_val << "\n";
              break;
          }

          last_diff = diff_val;

          //printf("Iteration #%lu - %.5f \n", i, diff_val);
        }
      }
      
      
    }
Example #25
0
ComplexSeries* fft_recursive(ComplexSeries* a)
{
	if(NULL == a)
		return NULL;
	int length = a->getLength();
	int i;

	if(length <= 0)
		return NULL;
	if(1 == length)
		return a;
	int half_len = ((unsigned int)length) >> 1;
	ComplexSeries* a0 = new ComplexSeries(half_len);
	if(NULL==a0)
	{
		cout<<"fft_recusive memory malloc failed"<<endl;
		return NULL;
	}
	ComplexSeries* a1 = new ComplexSeries(half_len);
	if(NULL==a1)
	{
		delete a0;
		cout<<"fft_recusive memory malloc failed"<<endl;
		return NULL;
	}
	for(i=0;i<half_len;i++)
	{
		a0->setValue(i, a->getValue(i*2));
		a1->setValue(i, a->getValue(i*2+1));
	}
	delete a;

	ComplexSeries* y0 = fft_recursive(a0);
	ComplexSeries* y1 = fft_recursive(a1);
	ComplexSeries* y = new ComplexSeries(length);
	if(NULL == y)
	{
		delete a0;
		delete a1;
		cout<<"fft_recusive memory malloc failed"<<endl;
		return NULL;
	}
	ComplexNum w(1.0, 0.0);
	ComplexNum wn(-1*length);

	for(i=0;i<half_len;i++)
	{
		ComplexNum* yy0 = y0->getValue(i);
		ComplexNum* yy1 = y1->getValue(i);
		ComplexNum ww = w*(*yy1);

		ComplexNum result1 = *yy0 + ww;
		ComplexNum result2 = *yy0 - ww;
		y->setValue(i, &result1);
		y->setValue(i+half_len, &result2);

		w = w*wn;
	}
	delete y0;
	delete y1;

	return y;
}