Пример #1
0
int
main(int argc, char** argv){


SndWave infile(argv[1], READ);
SndIn   sig1(&infile,1);
SndIn   sig2(&infile,2);
SndAiff output1(argv[2], OVERWRITE);
SndAiff output2(argv[3], OVERWRITE);

output1.SetOutput(1, &sig1);
output2.SetOutput(1, &sig1);

while(!infile.Eof()){

infile.Read();
sig1.DoProcess();
sig2.DoProcess();
output1.Write();
output2.Write();

}

return 0;
}
Пример #2
0
void ScenePlayTD::reload_map(){

	Input::Signal sig("push_scene","Game");
	Input::Signal sig2("pop_scene","Game");

	sig2.sent();

	sig.ex_data=new AOC::ScenePlayTD(map_name,glm::ivec3(1,1,1));
	sig.sent();
}
Пример #3
0
void EMDHistogramCostExtractorImpl::buildCostMatrix(InputArray _descriptors1, InputArray _descriptors2, OutputArray _costMatrix)
{
    // size of the costMatrix with dummies //
    Mat descriptors1=_descriptors1.getMat();
    Mat descriptors2=_descriptors2.getMat();
    int costrows = std::max(descriptors1.rows, descriptors2.rows)+nDummies;
    _costMatrix.create(costrows, costrows, CV_32F);
    Mat costMatrix=_costMatrix.getMat();

    // Obtain copies of the descriptors //
    cv::Mat scd1=descriptors1.clone();
    cv::Mat scd2=descriptors2.clone();

    // row normalization //
    for(int i=0; i<scd1.rows; i++)
    {
        cv::Mat row = scd1.row(i);
        scd1.row(i)/=(sum(row)[0]+FLT_EPSILON);
    }
    for(int i=0; i<scd2.rows; i++)
    {
        cv::Mat row = scd2.row(i);
        scd2.row(i)/=(sum(row)[0]+FLT_EPSILON);
    }

    // Compute the Cost Matrix //
    for(int i=0; i<costrows; i++)
    {
        for(int j=0; j<costrows; j++)
        {
            if (i<scd1.rows && j<scd2.rows)
            {
                cv::Mat sig1(scd1.cols,2,CV_32F), sig2(scd2.cols,2,CV_32F);
                sig1.col(0)=scd1.row(i).t();
                sig2.col(0)=scd2.row(j).t();
                for (int k=0; k<sig1.rows; k++)
                {
                    sig1.at<float>(k,1)=float(k);
                }
                for (int k=0; k<sig2.rows; k++)
                {
                    sig2.at<float>(k,1)=float(k);
                }

                costMatrix.at<float>(i,j) = cv::EMD(sig1, sig2, flag);
            }
            else
            {
                costMatrix.at<float>(i,j) = defaultCost;
            }
        }
    }
}
Пример #4
0
// Compute the mapping between linear array and the hypercube
// corresponding to all the trees.
void GeneratorTrees::ComputeCubeMapping()
{
  assert(trees.length()>=1);

  if (trees.length()==1) {  // A single tree
    ComputeOneGenMapping(map2array, trees[0]);
  }
  else { // more than one generator
    // Compute the sub-mapping for every generator. Also prepare two hypercube
    // signature objects for the index calculations, with the two ordering of
    // the generators: one for the generators ordered by their index 0,1,2...
    // and the other odred the generators by the order of their trees

    Vec<long> dims1(INIT_SIZE,trees.length()), dims2(INIT_SIZE,trees.length());
    Vec<Permut> genMappings(INIT_SIZE, trees.length());
    for (long i=0; i<trees.length(); i++) {
      dims1[i] = trees[i][0].getData().size;
      ComputeOneGenMapping(genMappings[i], trees[i]);
    }
    getCubeDims(dims2);
    CubeSignature sig1(dims1), sig2(dims2);


    // Allocate space for the mapping
    map2array.SetLength(sig1.getSize());

    // Combine the generator perms to a single permutation over the cube
    for (long i=0; i<map2array.length(); i++) {
      long t=0;
      for (long j1=0; j1<trees.length(); j1++) {
	long j2 = trees[j1].getAuxKey();
	long digit = sig1.getCoord(i,j1); // the j1 digit of i in base dims
	digit = genMappings[j1][digit];   // apply the j1 permutation to it
	t += digit * sig2.getProd(j2+1);  // adds the permuted digit

      }
      map2array[i] = t;
    }
  }

  // Compute the inverse permutation
  map2cube.SetLength(map2array.length());
  for (long i=0; i<map2array.length(); i++) map2cube[ map2array[i] ] = i;
}
Пример #5
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  const size_t MAX_DEPTH = argc == 1 ? 10 : ACE_OS::atoi (argv[1]);

  ACE_OS::atexit (exithook);

  if (argc > 2)
    ACE_Trace::set_nesting_indent (ACE_OS::atoi (argv[2]));

  ACE_TRACE ("int ACE_TMAIN (int argc, ACE_TCHAR *argv[])");

  ACE_Sig_Action sig1 ((ACE_SignalHandler) ACE_Trace::start_tracing,
                       SIGUSR1);
  ACE_UNUSED_ARG (sig1);
  ACE_Sig_Action sig2 ((ACE_SignalHandler) ACE_Trace::stop_tracing,
                       SIGUSR2);
  ACE_UNUSED_ARG (sig2);

  My_Task task (MAX_DEPTH);

#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0)
  int n_threads = argc > 3 ? ACE_OS::atoi (argv[3]) : 4;

  if (task.activate (THR_BOUND | THR_DETACHED, n_threads) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%p\n",
                       "activate"),
                      -1);

  // Wait for all the threads to exit.
  ACE_Thread_Manager::instance ()->wait ();
#else
  const int MAX_ITERATIONS = argc > 3 ? ACE_OS::atoi (argv[3]) : 10;

  for (int i = 0; i < MAX_ITERATIONS; i++)
    task.svc ();
#endif /* ACE_MT_SAFE */

  // Destructor automatically called.
  return 0;
}
Пример #6
0
/** the gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    /* [t, b] = ddm_rand_full(mu, sig2, b_lo, b_up, 
                              delta_t, n[, inv_leak[, seed]]) */

    /* Check argument number */
    if (nlhs != 2) {
        mexErrMsgIdAndTxt("ddm_rand_full:WrongOutputs", 
                          "Wrong number of output arguments");
    }
    if (nrhs < 6) {
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInputs",
                          "Too few input arguments");
    }

    /* Process first 8 arguments */
    if (!MEX_ARGIN_IS_REAL_VECTOR(0))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "First input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(1))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Second input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(2))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Third input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(3))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Fourth input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(4))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Fifth input argument expected to be a double");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(5))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Sixth input argument expected to be a double");
    if (nrhs >= 7 && !MEX_ARGIN_IS_REAL_DOUBLE(6))
        mexErrMsgIdAndTxt("ddm_rand_sym:WrongInput",
                          "Seventh input argument expected to be a double");
    if (nrhs >= 8 && !MEX_ARGIN_IS_REAL_DOUBLE(7))
        mexErrMsgIdAndTxt("ddm_rand_sym:WrongInput",
                          "Eighth input argument expected to be a double");
    int mu_size = std::max(mxGetN(prhs[0]), mxGetM(prhs[0]));
    int sig2_size = std::max(mxGetN(prhs[1]), mxGetM(prhs[1]));
    int b_lo_size = std::max(mxGetN(prhs[2]), mxGetM(prhs[2]));
    int b_up_size = std::max(mxGetN(prhs[3]), mxGetM(prhs[3]));
    ExtArray mu(ExtArray::shared_noowner(mxGetPr(prhs[0])), mu_size);
    ExtArray sig2(ExtArray::shared_noowner(mxGetPr(prhs[1])), sig2_size);
    ExtArray b_lo(ExtArray::shared_noowner(mxGetPr(prhs[2])), b_lo_size);
    ExtArray b_up(ExtArray::shared_noowner(mxGetPr(prhs[3])), b_up_size);
    ExtArray b_lo_deriv = ExtArray::const_array(0.0);
    ExtArray b_up_deriv = ExtArray::const_array(0.0);
    double delta_t = mxGetScalar(prhs[4]);
    int n = (int) mxGetScalar(prhs[5]);
    if (delta_t <= 0.0)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "delta_t needs to be larger than 0.0");
    if (n <= 0)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "n needs to be larger than 1");
    bool has_leak = false;
    double inv_leak = 0.0;
    if (nrhs >= 7) {
        inv_leak = mxGetScalar(prhs[6]);
        has_leak = (inv_leak != 0.0);
        if (inv_leak < 0.0)
            mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                              "inv_leak needs to be non-negative");
    }
    int rngseed = 0;
    if (nrhs >= 8)
        rngseed = (int) mxGetScalar(prhs[7]);
    if (nrhs > 8)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInputs",
                          "Too many input arguments");

    /* reserve space for output */
    plhs[0] = mxCreateDoubleMatrix(1, n, mxREAL);
    plhs[1] = mxCreateLogicalMatrix(1, n);
    double* t = mxGetPr(plhs[0]);
    mxLogical* b = mxGetLogicals(plhs[1]);

    /* perform sampling */
    DMBase* dm = nullptr;
    if (has_leak)
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t, inv_leak);
    else
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t);
    DMBase::rngeng_t rngeng;
    if (rngseed == 0) rngeng.seed(std::random_device()());
    else rngeng.seed(rngseed);
    for (int i = 0; i < n; ++i) {
        DMSample s = dm->rand(rngeng);
        t[i] = s.t();
        b[i] = s.upper_bound() ? 1 : 0;
    }
    delete dm;
}
Пример #7
0
 std::complex<double> signal::correlation(const signal& other) const {
     signal sig1(*this), sig2(other);
     sig1 /= sig1.abs(); sig2 /= sig2.abs();
     return sig1 ^ sig2;
 }
Пример #8
0
//--------------------------------------------------------------------
void bridge_reg_stable(double *betap,
		       double *lambdap,
		       double *sig2p,
		       double *taup,
		       double *alphap,
		       const double *yp,
		       const double *Xp,
		       const double *sig2_shape,
		       const double *sig2_scale,
		       const double *nu_shape,
		       const double *nu_rate,
		       const double *alpha_a,
		       const double *alpha_b,
		       const double *true_sig2,
		       const double *true_tau,
		       const double *true_alpha,
		       const int *P,
		       const int *N,
		       const int *M,
		       const int *burn,
		       double *runtime,
		       const bool *ortho)
{
  Matrix y(yp, *N,  1);
  Matrix X(Xp, *N, *P);

  Matrix beta  (*P, 1, *M);
  Matrix lambda(*P, 1, *M, 1.0);
  Matrix sig2  ( 1, 1, *M);
  Matrix tau   ( 1, 1, *M);
  Matrix alpha ( 1, 1, *M);

  #ifdef USE_R
  GetRNGstate();
  #endif

  if (!*ortho) {
    *runtime = bridge_regression_stable(beta, lambda, sig2, tau, alpha,
					y, X,
					*sig2_shape, *sig2_scale,
					*nu_shape, *nu_rate,
					*alpha_a, *alpha_b,
					*true_sig2, *true_tau, *true_alpha,
					(uint)*burn);
  }
  else {
    *runtime = bridge_regression_stable_ortho(beta, lambda, sig2, tau, alpha,
					      y, X,
					      *sig2_shape, *sig2_scale,
					      *nu_shape, *nu_rate,
					      *alpha_a, *alpha_b,
					      *true_sig2, *true_tau, *true_alpha,
					      (uint)*burn);
  }

  #ifdef USE_R
  PutRNGstate();
  #endif

  // std::copy(&beta(0), &beta(0) + beta.vol(), betap);

  MatrixFrame beta_mf (betap, *P, 1, *M);
  MatrixFrame lambda_mf(lambdap, *P, 1, *M);
  MatrixFrame sig2_mf (sig2p,  1, 1, *M);
  MatrixFrame tau_mf  (taup,   1, 1, *M);
  MatrixFrame alpha_mf(alphap, 1, 1, *M);

  beta_mf.copy(beta);
  lambda_mf.copy(lambda);
  sig2_mf.copy(sig2);
  tau_mf.copy(tau);
  alpha_mf.copy(alpha);

} // bridge_regression
Пример #9
0
void bridge_regression(double *betap,
		       double *up,
		       double *omegap,
		       double *shapep,
		       double *sig2p,
		       double *taup,
		       double *alphap,
		       const double *yp,
		       const double *Xp,
		       const double *sig2_shape,
		       const double *sig2_scale,
		       const double *nu_shape,
		       const double *nu_rate,
		       const double *alpha_a,
		       const double *alpha_b,
		       const double *true_sig2,
		       const double *true_tau,
		       const double *true_alpha,
		       const int *P,
		       const int *N,
		       const int *M,
		       const int *burn,
		       double *runtime,		 
		       const bool *ortho,
		       const int *betaburn,
		       const bool *use_hmc)
{
  Matrix y(yp, *N,  1);
  Matrix X(Xp, *N, *P);

  Matrix beta(*P, 1, *M);
  Matrix u    (*P, 1, *M, 0.0);
  Matrix omega(*P, 1, *M, 1.0);
  Matrix shape(*P, 1, *M, 0.0);
  Matrix sig2( 1, 1, *M);
  Matrix tau ( 1, 1, *M);
  Matrix alpha(1, 1, *M);

  #ifdef USE_R
  GetRNGstate();
  #endif

  if (!*ortho) {


    *runtime = bridge_regression(beta, u, omega, shape, sig2, tau, alpha, y, X,
				 *sig2_shape, *sig2_scale,
				 *nu_shape, *nu_rate,
				 *alpha_a, *alpha_b,
				 *true_sig2, *true_tau, *true_alpha,
				 *burn, *betaburn, *use_hmc);
  }
  else {
    
    *runtime = bridge_regression_ortho(beta, u, omega, shape, sig2, tau, alpha,
				       y, X,
				       *sig2_shape, *sig2_scale,
				       *nu_shape, *nu_rate,
				       *alpha_a, *alpha_b,
				       *true_sig2, *true_tau, *true_alpha,
				       *burn);

  }

  #ifdef USE_R
  PutRNGstate();
  #endif

  MatrixFrame beta_mf (betap, *P, 1 , *M);
  MatrixFrame u_mf    (up    , *P, 1, *M);
  MatrixFrame omega_mf(omegap, *P, 1, *M);
  MatrixFrame shape_mf(shapep, *P, 1, *M);
  MatrixFrame sig2_mf (sig2p, 1 , 1 , *M);
  MatrixFrame tau_mf  (taup , 1 , 1 , *M);
  MatrixFrame alpha_mf(alphap, 1, 1,  *M);

  beta_mf.copy(beta);
  u_mf.copy(u);
  omega_mf.copy(omega);
  shape_mf.copy(shape);
  sig2_mf.copy(sig2);
  tau_mf.copy (tau );
  alpha_mf.copy(alpha);

} // bridge_regression
Пример #10
0
/* method fpt_full(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv, dt, tmax,
 *                 [inv_leak, mnorm]) */
static PyObject* ddmmod_fpt_full(PyObject* self, PyObject* args, PyObject* keywds)
{
    /* process arguments */
    static char* kwlist[] = {"mu", "sig2", "b_lo", "b_up", "b_lo_deriv",
                             "b_up_deriv", "dt", "tmax", "inv_leak", "mnorm", NULL};
    PyArrayObject *py_mu, *py_sig2, *py_b_lo, *py_b_up, *py_b_lo_deriv, *py_b_up_deriv;
    double dt, t_max, inv_leak = 0.0;
    PyObject* mnorm_obj = NULL;
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "O!O!O!O!O!O!dd|dO", kwlist, 
                                     &PyArray_Type, &py_mu,
                                     &PyArray_Type, &py_sig2,
                                     &PyArray_Type, &py_b_lo,
                                     &PyArray_Type, &py_b_up,
                                     &PyArray_Type, &py_b_lo_deriv,
                                     &PyArray_Type, &py_b_up_deriv,
                                     &dt, &t_max, &inv_leak, &mnorm_obj))
        return NULL;
    if (!(is1DDoubleArray(py_mu) && is1DDoubleArray(py_sig2) &&
          is1DDoubleArray(py_b_lo) && is1DDoubleArray(py_b_up) &&
          is1DDoubleArray(py_b_lo_deriv) && is1DDoubleArray(py_b_up_deriv)))
        return NULL;
    if (dt <= 0.0) {
        PyErr_SetString(PyExc_ValueError, "dt needs to be larger than 0");
        return NULL;
    }
    if (t_max <= 0.0) {
        PyErr_SetString(PyExc_ValueError, "tmax needs to be larger than 0");
        return NULL;
    }
    if (inv_leak < 0.0) {
        PyErr_SetString(PyExc_ValueError, "inv_leak needs to be non-negative");
        return NULL;
    }
    bool mnorm_bool = (mnorm_obj != NULL && PyObject_IsTrue(mnorm_obj) == 1);
    ExtArray mu(ExtArray::shared_noowner((double*) PyArray_DATA(py_mu)),
                PyArray_DIM(py_mu, 0));
    ExtArray sig2(ExtArray::shared_noowner((double*) PyArray_DATA(py_sig2)),
                  PyArray_DIM(py_sig2, 0));
    ExtArray b_lo(ExtArray::shared_noowner((double*) PyArray_DATA(py_b_lo)),
                  PyArray_DIM(py_b_lo, 0));
    ExtArray b_up(ExtArray::shared_noowner((double*) PyArray_DATA(py_b_up)),
                  PyArray_DIM(py_b_up, 0));
    ExtArray b_lo_deriv(ExtArray::shared_noowner((double*) PyArray_DATA(py_b_lo_deriv)),
                        PyArray_DIM(py_b_lo_deriv, 0));
    ExtArray b_up_deriv(ExtArray::shared_noowner((double*) PyArray_DATA(py_b_up_deriv)),
                        PyArray_DIM(py_b_up_deriv, 0));

    /* get output length and reserve space */
    int n_max = (int) ceil(t_max / dt);
    npy_intp out_size[1] = { n_max };
    PyObject* py_g1 = PyArray_SimpleNew(1, out_size, NPY_DOUBLE);
    if (py_g1 == NULL) return NULL;
    PyObject* py_g2 = PyArray_SimpleNew(1, out_size, NPY_DOUBLE);
    if (py_g2 == NULL) {
        Py_DECREF(py_g1);
        return NULL;
    }
    ExtArray g1(ExtArray::shared_noowner(
        (double*) PyArray_DATA((PyArrayObject*) py_g1)), n_max);
    ExtArray g2(ExtArray::shared_noowner(
        (double*) PyArray_DATA((PyArrayObject*) py_g2)), n_max);


    /* compute fpt */
    DMBase* dm = nullptr;
    if (inv_leak > 0.0)
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            dt, inv_leak);
    else
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv, dt);
    dm->pdfseq(n_max, g1, g2);
    if (mnorm_bool) dm->mnorm(g1, g2);
    delete dm;

    /* create tuple to return */
    PyObject* py_tuple = PyTuple_New(2);
    if (py_tuple == NULL) goto memory_fail;
    PyTuple_SET_ITEM(py_tuple, 0, py_g1);
    PyTuple_SET_ITEM(py_tuple, 1, py_g2);
    return py_tuple;

memory_fail:
    Py_DECREF(py_g1);
    Py_DECREF(py_g2);
    PyErr_SetString(PyExc_MemoryError, "out of memory");
    return NULL;
}
Пример #11
0
inline bool TRobustRegressionL1PD(
  const MATRIX_TYPE& A,
  const Eigen::Matrix<REAL, Eigen::Dynamic, 1>& y,
  Eigen::Matrix<REAL, Eigen::Dynamic, 1>& xp,
  REAL pdtol=1e-3, unsigned pdmaxiter=50)
{
  typedef Eigen::Matrix<REAL, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix;
  typedef Eigen::Matrix<REAL, Eigen::Dynamic, 1> Vector;
  const unsigned M = (unsigned)y.size();
  const unsigned N = (unsigned)xp.size();
  assert(A.rows() == M && A.cols() == N);

  const REAL alpha(0.01);
  const REAL beta(0.5);
  const REAL mu(10);

  Vector x(xp);
  Vector Ax(A*x);
  Vector tmpM1(y-Ax);
  Vector tmpM2(-tmpM1);
  Vector tmpM3(tmpM1.cwiseAbs()), tmpM4(M);
  Vector u = (tmpM3*REAL(0.95)).array() + tmpM3.maxCoeff()*REAL(0.10);
  Vector fu1 = tmpM2-u;
  Vector fu2 = tmpM1-u;

  Vector lamu1(M), lamu2(M);
  for (unsigned i=0; i<M; ++i) {
    lamu1(i) = -1.0/fu1(i);
    lamu2(i) = -1.0/fu2(i);
  }
  const MATRIX_TYPE At(A.transpose());
  Vector Atv(At*(lamu1-lamu2));
  REAL AtvNormSq = Atv.squaredNorm();
  Vector rdual((-lamu1-lamu2).array() + REAL(1));
  REAL rdualNormSq = rdual.squaredNorm();

  Vector w2(M), sig1(M), sig2(M), sigx(M), dx(N), up(N), Atdv(N);
  Vector Axp(M), Atvp(M);
  Vector &Adx(sigx), &du(w2), &w1p(dx);
  Matrix H11p(N,N);
  Vector &dlamu1(tmpM3), &dlamu2(tmpM4);
  for (unsigned pditer=0; pditer<pdmaxiter; ++pditer) {
    // surrogate duality gap
    const REAL sdg(-(fu1.dot(lamu1) + fu2.dot(lamu2)));
    if (sdg < pdtol)
      break;
    const REAL tau(mu*2*M/sdg);
    const REAL inv_tau = REAL(-1)/tau;
    tmpM1 = (-lamu1.cwiseProduct(fu1)).array() + inv_tau;
    tmpM2 = (-lamu2.cwiseProduct(fu2)).array() + inv_tau;
    const REAL resnorm = sqrt(AtvNormSq + rdualNormSq + tmpM1.squaredNorm() + tmpM2.squaredNorm());

    for (unsigned i=0; i<M; ++i) {
      REAL& tmpM3i = tmpM3(i);
      tmpM3i = inv_tau/fu1(i);
      REAL& tmpM4i = tmpM4(i);
      tmpM4i = inv_tau/fu2(i);
      w2(i) = tmpM3i + tmpM4i - REAL(1);
    }

    tmpM1 = lamu1.cwiseQuotient(fu1);
    tmpM2 = lamu2.cwiseQuotient(fu2);
    sig1 = -tmpM1 - tmpM2;
    sig2 = tmpM1 - tmpM2;
    sigx = sig1 - sig2.cwiseAbs2().cwiseQuotient(sig1);

    H11p = At*(Eigen::DiagonalMatrix<REAL,Eigen::Dynamic>(sigx)*A);
    w1p = At*(tmpM4 - tmpM3 - (sig2.cwiseQuotient(sig1).cwiseProduct(w2)));

    // optimized solver as A is positive definite and symmetric
    dx = H11p.ldlt().solve(w1p);

    Adx = A*dx;

    du = (w2 - sig2.cwiseProduct(Adx)).cwiseQuotient(sig1);

    dlamu1 = -tmpM1.cwiseProduct(Adx-du) - lamu1 + tmpM3;
    dlamu2 =  tmpM2.cwiseProduct(Adx+du) - lamu2 + tmpM4;
    Atdv = At*(dlamu1-dlamu2);

    // make sure that the step is feasible: keeps lamu1,lamu2 > 0, fu1,fu2 < 0
    REAL s(1);
    for (unsigned i=0; i<M; ++i) {
      REAL& dlamu1i = dlamu1(i);
      if (dlamu1i < 0) {
        const REAL tmp = -lamu1(i)/dlamu1i;
        if (s > tmp)
          s = tmp;
      }
      REAL& dlamu2i = dlamu2(i);
      if (dlamu2i < 0) {
        const REAL tmp = -lamu2(i)/dlamu2i;
        if (s > tmp)
          s = tmp;
      }
    }
    for (unsigned i=0; i<M; ++i) {
      REAL& Adxi = Adx(i);
      REAL& dui = du(i);
      REAL Adx_du = Adxi-dui;
      if (Adx_du > 0) {
        const REAL tmp = -fu1(i)/Adx_du;
        if (s > tmp)
          s = tmp;
      }
      Adx_du = -Adxi-dui;
      if (Adx_du > 0) {
        const REAL tmp = -fu2(i)/Adx_du;
        if (s > tmp)
          s = tmp;
      }
    }
    s *= REAL(0.99);

    // backtrack
    lamu1 += s*dlamu1;  lamu2 += s*dlamu2;
    rdual = (-lamu1-lamu2).array() + REAL(1);
    rdualNormSq = rdual.squaredNorm();
    bool suffdec = false;
    unsigned backiter = 0;
    do {
      xp = x + s*dx;  up = u + s*du;
      Axp = Ax + s*Adx;  Atvp = Atv + s*Atdv;
      fu1 = Axp - y - up;  fu2 = -Axp + y - up;
      AtvNormSq = Atvp.squaredNorm();
      tmpM1 = (-lamu1.cwiseProduct(fu1)).array() + inv_tau;
      tmpM2 = (-lamu2.cwiseProduct(fu2)).array() + inv_tau;
      const REAL newresnorm = sqrt(AtvNormSq + rdualNormSq + tmpM1.squaredNorm() + tmpM2.squaredNorm());
      suffdec = (newresnorm <= (REAL(1)-alpha*s)*resnorm);
      s = beta*s;
      if (++backiter > 32) {
        //("error: stuck backtracking, returning last iterate"); // see Section 4 of notes for more information
        xp.swap(x);
        return false;
      }
    } while (!suffdec);

    // next iteration
    x.swap(xp);  u.swap(up);
    Ax.swap(Axp);  Atv.swap(Atvp);
  }
  return true;
}
Пример #12
0
/** the gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    /* [g1, g2] = ddm_fpt_full(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                               delta_t, t_max, [leak]) */

    /* Check argument number */
    if (nlhs != 2) {
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongOutputs", 
                          "Wrong number of output arguments");
    }
    if (nrhs < 8) {
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInputs",
                          "Too few input arguments");
    }

    /* Process first 8 arguments */
    if (!MEX_ARGIN_IS_REAL_VECTOR(0))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "First input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(1))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "Second input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(2))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "Third input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(3))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "Fourth input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(4))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "Fifth input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(5))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "Sixth input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(6))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "Seventh input argument expected to be a double");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(7))
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "Eight input argument expected to be a double");
    int mu_size = std::max(mxGetN(prhs[0]), mxGetM(prhs[0]));
    int sig2_size = std::max(mxGetN(prhs[1]), mxGetM(prhs[1]));
    int b_lo_size = std::max(mxGetN(prhs[2]), mxGetM(prhs[2]));
    int b_up_size = std::max(mxGetN(prhs[3]), mxGetM(prhs[3]));
    int b_lo_deriv_size = std::max(mxGetN(prhs[4]), mxGetM(prhs[4]));
    int b_up_deriv_size = std::max(mxGetN(prhs[5]), mxGetM(prhs[5]));
    ExtArray mu(ExtArray::shared_noowner(mxGetPr(prhs[0])), mu_size);
    ExtArray sig2(ExtArray::shared_noowner(mxGetPr(prhs[1])), sig2_size);
    ExtArray b_lo(ExtArray::shared_noowner(mxGetPr(prhs[2])), b_lo_size);
    ExtArray b_up(ExtArray::shared_noowner(mxGetPr(prhs[3])), b_up_size);
    ExtArray b_lo_deriv(ExtArray::shared_noowner(mxGetPr(prhs[4])), 0.0, b_lo_deriv_size);
    ExtArray b_up_deriv(ExtArray::shared_noowner(mxGetPr(prhs[5])), 0.0, b_up_deriv_size);
    double delta_t = mxGetScalar(prhs[6]);
    double t_max = mxGetScalar(prhs[7]);
    if (delta_t <= 0.0)
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "delta_t needs to be larger than 0.0");
    if (t_max <= delta_t)
        mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                          "t_max needs to be at least as large as delta_t");

    /* Process possible 9th non-string argument */
    int cur_argin = 8;
    bool has_leak = false;
    double inv_leak = 0.0;
    if (nrhs > cur_argin && !mxIsChar(prhs[cur_argin])) {
        if (!MEX_ARGIN_IS_REAL_DOUBLE(cur_argin))
            mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                              "Ninth input argument expected to be a double");
        inv_leak = mxGetScalar(prhs[cur_argin]);
        if (inv_leak < 0.0)
            mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                              "inv_leak needs to be non-negative");
        has_leak = (inv_leak != 0.0);
        ++cur_argin;
    }
        
    /* Process string arguments */
    bool normalise_mass = false;
    if (nrhs > cur_argin) {
        char str_arg[6];
        /* current only accept 'mnorm' string argument */
        if (!mxIsChar(prhs[cur_argin]))
            mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                              "String argument expected but not found");
        if (mxGetString(prhs[cur_argin], str_arg, sizeof(str_arg)) == 1 ||
            strcmp(str_arg, "mnorm") != 0)
            mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                              "\"mnorm\" string argument expected");
        /* this needs to be followed by "yes" or "no" */
        if (nrhs <= cur_argin + 1 || !mxIsChar(prhs[cur_argin + 1]))
            mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                              "String expected after \"mnorm\"");
        if (mxGetString(prhs[cur_argin + 1], str_arg, sizeof(str_arg)) == 1 ||
            (strcmp(str_arg, "yes") != 0 && strcmp(str_arg, "no") != 0))
            mexErrMsgIdAndTxt("ddm_fpt_full:WrongInput",
                              "\"yes\" or \"no\" expected after \"mnorm\"");
        normalise_mass = (strcmp(str_arg, "yes") == 0);
        
        /* no arguments allowed after that */
        if (nrhs > cur_argin + 2)
            mexErrMsgIdAndTxt("ddm_fpt_full:WrongInputs",
                              "Too many input arguments");
    }

    /* reserve space for output */
    int n = (int) ceil(t_max / delta_t);
    plhs[0] = mxCreateDoubleMatrix(1, n, mxREAL);
    plhs[1] = mxCreateDoubleMatrix(1, n, mxREAL);
    ExtArray g1(ExtArray::shared_noowner(mxGetPr(plhs[0])), n);
    ExtArray g2(ExtArray::shared_noowner(mxGetPr(plhs[1])), n);
    
    /* compute the pdf's */
    DMBase* dm = nullptr;
    if (has_leak)
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t, inv_leak);
    else
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t);
    dm->pdfseq(n, g1, g2);
    if (normalise_mass) dm->mnorm(g1, g2);
    delete dm;
}