コード例 #1
0
ファイル: main.c プロジェクト: cherry-wb/Hot-Fuzz
PRIVATE void debug_help(void)
{
#ifdef DEBUG
     uu("Debugging options: -D{adehpstuvy}");
     uu("Codes: Allocation, Dependencies, Expressions, Hash table,");
     uu("       Lisp dump, Prelude, Scribble on freed storage,");
     uu("       Type storage, Unification, Version, Yacc parser");
#else
     uu("No debugging code compiled");
#endif

     exit(2);
}
コード例 #2
0
ファイル: testZ_px.cpp プロジェクト: dgquintas/libmpplas
int main(){
  mpplas::Z_px u("[(112,10)(132,9)(1,8)(331,6)(121,5)(31,4)(41,0)]",2);
  mpplas::Z_px v("[(1,9)(1,6)(1,5)(1,3)(1,2)(1,0)]",2);
  mpplas::Z_px q(2),r(2);
  std::cout << u << std::endl;
  std::cout << u.getAddInverse() << std::endl;
  std::cout << u+u.getAddInverse() << std::endl;

  std::cout << v << std::endl;
  u *= mpplas::Z_px::ONE;
  std::cout << u << std::endl;

  mpplas::Z_px f("[(1,4)(1,1)(1,0)]",7);
  std::cout << f << std::endl;
  u = mpplas::Z_px("[(1,3)(1,2)(1,0)]",2);
  v = mpplas::Z_px("[(1,3)(1,0)]",2);
  u *= v;
  u %= f;
  std::cout << u << std::endl;


  mpplas::Z_px uu("[(1,3)(1,1)(1,0)]",2);
  mpplas::Z_px::gcd(uu,f,&q,&r);
  std::cout << q << std::endl;
  uu *= q;
  uu %= f;
  std::cout << uu  << std::endl;

  std::cout << std::endl;


  return 0;
}
コード例 #3
0
ファイル: main.c プロジェクト: cherry-wb/Hot-Fuzz
PRIVATE void usage(void)
{
     uu("Usage: fuzz [-aqstv] [-p file] file ...");
     uu("Flags: -a       Don't use type abbreviations");
     uu("       -d       Allow use before definition");
     uu("       -l       Lisp-style echoing of input");
     uu("       -p file  Use <file> in place of standard prelude");
     uu("       -q       Assume quantifiers for undeclared variables");
     uu("       -s       Syntax check only");
     uu("       -t       Report types of global definitions");
     uu("       -v       Echo input as it is parsed");
     exit(2);
}
コード例 #4
0
ファイル: MATH_Spline.hpp プロジェクト: davidyu/Q-bert
    inline Vec3f Spline::getPosHermite(float u)
    {
        Vec4f uu(u*u*u, u*u, u, 1);
        Vec4f inter = GetVecMatProd4(uu, m_Hermite);
        float x = inter * m_x;
        float y = inter * m_y;
        float z = inter * m_z;

        return Vec3f(x, y, z);
    }
コード例 #5
0
ファイル: MATH_Spline.hpp プロジェクト: davidyu/Q-bert
    inline Vec3f Spline::getPosCatmull(float u)
    {
        Vec4f uu(0.5, 0.5*u, 0.5*u*u, 0.5*u*u*u);
        Vec4f inter = GetVecMatProd4(uu, m_CatmullRom);
        float x = inter * m_x;
        float y = inter * m_y;
        float z = inter * m_z;

        return Vec3f(x, y, z);
    }
コード例 #6
0
ファイル: rotation.cpp プロジェクト: beta-robots/btr-libs
void Crotation::rotateUaxis(const double alpha, double ux, double uy, double uz, bool rd)
{
      dlib::matrix<double,3,3> P, Q, I, R;
      dlib::matrix<double,3,1> uu;
      double ar, aux; //angle in radians

      //check if matrix is updated and rad/deg option
      if ( rStatus & OLD_MATRIX ) updateMatrix();
      
      //set angle in radians whatever the input choice
      if ( rd == inRADIANS ) ar = alpha;
      else ar=alpha*M_PI/180.0;//inDEGREES
      
      //updates rM matrix with Rodrigue's formula 
      aux = sqrt(ux*ux+uy*uy+uz*uz);
      uu = ux/aux, uy/aux, uz/aux;
      P = uu*trans(uu);
      //Q = 0, -uz, uy, uz, 0, -ux, -uy, ux, 0;
      Q = 0, -uu(2), uu(1), uu(2), 0, -uu(0), -uu(1), uu(0), 0;
      I = dlib::identity_matrix(dlib::matrix<double>(3,3));
      R=P+(I-P)*cos(ar)+Q*sin(ar);
      rM=R*rM;
      
      //updates new status
      rStatus = OLD_EULER | OLD_QUATERNION;
}
コード例 #7
0
ファイル: tests.hpp プロジェクト: faldah/nt2
  inline bool test_ulp_eq( char const* x1
                           , char const* x2             
                           , char const* x3                             
                           , int line
                           , char const * fn                    
                           , T const & t
                           , U const & u                        
                           , V const & v                                
                           )                                            
  {                                                                     
    test_count()++;                                                     
    /*volatile*/ T tt(t);
    /*volatile*/ U uu(u);
    /*volatile*/ V vv(v);
//     typedef typename boost::dispatch::meta::upgrade<T>::type TT;
//     typedef typename boost::dispatch::meta::upgrade<U>::type UU;
       typedef T TT;
       typedef U UU; 
    typedef typename boost::dispatch::meta::call<nt2::tag::ulpdist_(T, U)>::type R;
    if( nt2::ulpdist(T(tt), U(uu) ) <= (R)vv)
    {                                                                   
      std::cout << " * Test `"                                  
                << "ulpdist(" << x1 << ", " <<  x2 << ") ( == " << nt2::ulpdist(T(tt), U(uu) ) << ") <= " << x3     
                << "` **passed**."                                      
                << " (" << line << ")"                          
                << std::endl;
      return true; 
    }                                                                   
    else                                                                
    {
      std::cout << " * Test `"                                  
                << "ulpdist(" << x1 << ", " <<  x2 << ") <= " << x3     
                << "` **failed** in function "                  
                << fn << " (" << line << ")"                            
                << "ulpdist(" << TT(tt) << ", " <<  UU(uu) << ") == "           
                <<  nt2::ulpdist(T(tt), U(uu) )
                << std::endl;                                           
      ++error_count();
      return false; 
    }
  }
コード例 #8
0
	/// Accumulate pose based on velocity
	void step(double dt=1){
		mVelScale = dt;
	
		double amt = 1.-smooth();	// TODO: adjust for dt

		//Vec3d angVel = mSpin0 + mTurn;

		// low-pass filter velocities
		mMove1.lerp(mMove0*dt + mNudge, amt);
		mSpin1.lerp(mSpin0*dt + mTurn, amt);

		// turn and nudge are a one-shot increments, so clear each frame
		mTurn.set(0);
		mNudge.set(0);

		mQuat *= vel().quat();
		updateDirectionVectors();

		// accumulate position:
		for(int i=0; i<pos().size(); ++i){
			pos()[i] += mMove1.dot(Vec3d(ur()[i], uu()[i], uf()[i]));
		}
	}
コード例 #9
0
ファイル: getProof.C プロジェクト: MycrofD/root
TProof *getProof(const char *url = "proof://localhost:40000", Int_t nwrks = -1, const char *dir = 0,
                 const char *opt = "ask", Bool_t dyn = kFALSE, Bool_t tutords = kFALSE)
{

#ifdef __CINT__
   Printf("getProof: this script can only be executed via ACliC:");
   Printf("getProof:      root [] .x <path>/getProof.C+");
   Printf("getProof: or   root [] .L <path>/getProof.C+");
   Printf("getProof:      root [] getProof(...)");
   return;
#endif

   TProof *p = 0;

   // Valgrind options, if any
   TString vopt, vopts;
#ifndef WIN32
   if (gSystem->Getenv("GETPROOF_VALGRIND")) {
      TString s(gSystem->Getenv("GETPROOF_VALGRIND")), t;
      Int_t from = 0;
      while (s.Tokenize(t, from , " ")) {
         if (t.BeginsWith("valgrind_opts:"))
            vopts = t;
         else
            vopt = t;
      }
      if (vopts.IsNull()) vopts = "valgrind_opts:--leak-check=full --track-origins=yes";
      TProof::AddEnvVar("PROOF_WRAPPERCMD", vopts.Data());
      Printf("getProof: valgrind run: '%s' (opts: '%s')", vopt.Data(), vopts.Data());
   }
#endif

   // If an URL has specified get a session there
   TUrl uu(url), uref(refloc);
   Bool_t ext = (strcmp(uu.GetHost(), uref.GetHost()) ||
                 (uu.GetPort() != uref.GetPort())) ? kTRUE : kFALSE;
   Bool_t lite = kFALSE;
   if (ext && url) {
      if (!strcmp(url, "lite://") || !url[0]) {
         if (!url[0]) uu.SetUrl("lite://");
         if (dir && strlen(dir) > 0) gEnv->SetValue("Proof.Sandbox", dir);
         TString swrk("<default> workers");
         if (nwrks > 0) {
            uu.SetOptions(Form("workers=%d", nwrks));
            swrk.Form("%d workers", nwrks);
         }
         lite = kTRUE;
         gEnv->SetValue("Proof.MaxOldSessions", 1);
         Printf("getProof: trying to open a PROOF-Lite session with %s", swrk.Data());
      } else {
         Printf("getProof: trying to open a session on the external cluster at '%s'", url);
      }
      p = TProof::Open(uu.GetUrl(), vopt);
      if (p && p->IsValid()) {
         // Check consistency
         if (ext && !lite && nwrks > 0) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'nwrks=%d' ignored", url, nwrks);
         }
         if (ext && !lite && dir && strlen(dir) > 0) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'dir=\"%s\"' ignored", url, dir);
         }
         if (ext && !strcmp(opt,"force")) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'opt=\"force\"' ignored", url);
         }
         if (ext && dyn) {
            Printf("getProof: WARNING: started/attached a session on external cluster (%s):"
                   " 'dyn=kTRUE' ignored", url);
         }
         // Done
         return p;
      } else {
         if (ext) {
            Printf("getProof: could not get/start a valid session at %s", url);
            return p;
         } else {
            Printf("getProof: could not get/start a valid session at %s - try resarting the daemon", url);
         }
      }
      if (p) delete p;
      p = 0;
   }

#ifdef WIN32
   // No support for local PROOF on Win32 (yet; the optimized local Proof will work there too)
   Printf("getProof: local PROOF not yet supported on Windows, sorry!");
   return p;
#else

   // Temp dir for tutorial daemons
   TString tutdir = dir;
   if (!tutdir.IsNull()) {
      if (gSystem->AccessPathName(tutdir)) {
         // Directory does not exist: try to make it
         gSystem->mkdir(tutdir.Data(), kTRUE);
         if (gSystem->AccessPathName(tutdir, kWritePermission)) {
            if (gSystem->AccessPathName(tutdir)) {
               Printf("getProof: unable to create the working area at the requested path: '%s'"
                      " - cannot continue", tutdir.Data());
            } else {
               Printf("getProof: working area at the requested path '%s'"
                      " created but it is not writable - cannot continue", tutdir.Data());
            }
            return p;
         }
      } else {
         // Check if it is writable ...
         if (gSystem->AccessPathName(dir, kWritePermission)) {
            // ... fail if not
            Printf("getProof: working area at the requested path '%s'"
                      " exists but is not writable - cannot continue", tutdir.Data());
            return p;
         }
      }
   } else {
      // Notify
      Printf("getProof: working area not specified temp ");
      // Force "/tmp/<user>" whenever possible to avoid length problems on MacOsX
      tutdir="/tmp";
      if (gSystem->AccessPathName(tutdir, kWritePermission)) tutdir = gSystem->TempDirectory();
      TString us;
      UserGroup_t *ug = gSystem->GetUserInfo(gSystem->GetUid());
      if (!ug) {
         Printf("getProof: could not get user info");
         return p;
      }
      us.Form("/%s", ug->fUser.Data());
      if (!tutdir.EndsWith(us.Data())) tutdir += us;
      // Add our own subdir
      tutdir += "/.getproof";
      if (gSystem->AccessPathName(tutdir)) {
         gSystem->mkdir(tutdir.Data(), kTRUE);
         if (gSystem->AccessPathName(tutdir, kWritePermission)) {
            Printf("getProof: unable to get a writable working area (tried: %s)"
                  " - cannot continue", tutdir.Data());
            return p;
         }
      }
   }
   Printf("getProof: working area (tutorial dir): %s", tutdir.Data());

   // Dataset dir
   TString datasetdir;
   if (tutords) {
      datasetdir = Form("%s/dataset", tutdir.Data());
      if (gSystem->AccessPathName(datasetdir, kWritePermission)) {
         gSystem->mkdir(datasetdir, kTRUE);
         if (gSystem->AccessPathName(datasetdir, kWritePermission)) {
            Printf("getProof: unable to get a writable dataset directory (tried: %s)"
                   " - cannot continue", datasetdir.Data());
            return p;
         }
         Printf("getProof: dataset dir: %s", datasetdir.Data());
      }
   }

   // Local url (use a special port to try to not disturb running daemons)
   TUrl u(refloc);
   u.SetProtocol("proof");
   if (!strcmp(uu.GetHost(), uref.GetHost()) && (uu.GetPort() != uref.GetPort()))
      u.SetPort(uu.GetPort());
   Int_t lportp = u.GetPort();
   Int_t lportx = lportp + 1;
   TString lurl = u.GetUrl();

   // Prepare to start the daemon
   TString workarea = Form("%s/proof", tutdir.Data());
   TString xpdcf(Form("%s/xpd.cf",tutdir.Data()));
   TString xpdlog(Form("%s/xpd.log",tutdir.Data()));
   TString xpdlogprt(Form("%s/xpdtut/xpd.log",tutdir.Data()));
   TString xpdpid(Form("%s/xpd.pid",tutdir.Data()));
   TString proofsessions(Form("%s/sessions",tutdir.Data()));
   TString cmd;
   Int_t rc = 0;

   // Is there something listening already ?
   Int_t pid = -1;
   Bool_t restart = kTRUE;
   if ((rc = checkXproofdAt(lportp)) == 1) {
      Printf("getProof: something else the a XProofd service is running on"
             " port %d - cannot continue", lportp);
      return p;

   } else if (rc == 0) {

      restart = kFALSE;

      pid = getXrootdPid(lportx);
      Printf("getProof: daemon found listening on dedicated ports {%d,%d} (pid: %d)",
              lportx, lportp, pid);
      if (isatty(0) == 0 || isatty(1) == 0) {
         // Cannot ask: always restart
         restart = kTRUE;
      } else {
         if (!strcmp(opt,"ask")) {
            char *answer = (char *) Getline("getProof: would you like to restart it (N,Y)? [N] ");
            if (answer && (answer[0] == 'Y' || answer[0] == 'y'))
               restart = kTRUE;
         }
      }
      if (!strcmp(opt,"force"))
         // Always restart
         restart = kTRUE;

      // Cleanup, if required
      if (restart) {
         Printf("getProof: cleaning existing instance ...");
         // Cleaning up existing daemon
         cmd = Form("kill -9 %d", pid);
         if ((rc = gSystem->Exec(cmd)) != 0)
            Printf("getProof: problems stopping xrootd process %d (%d)", pid, rc);
         // Wait for all previous connections being cleaned
         Printf("getProof: wait 5 secs so that previous connections are cleaned ...");
         gSystem->Sleep(5000);
      }
   }

   if (restart) {
      // Try to start something locally; make sure that everything is there
      char *xrootd = gSystem->Which(gSystem->Getenv("PATH"), "xrootd", kExecutePermission);
      if (!xrootd) {
         Printf("getProof: xrootd not found: please check the environment!");
         return p;
      }

      // Cleanup the working area
      cmd = Form("rm -fr %s/xpdtut %s %s %s %s", tutdir.Data(), workarea.Data(),
                                                 xpdcf.Data(), xpdpid.Data(), proofsessions.Data());
      gSystem->Exec(cmd);

      // Try to start something locally; create the xrootd config file
      FILE *fcf = fopen(xpdcf.Data(), "w");
      if (!fcf) {
         Printf("getProof: could not create config file for XPD (%s)", xpdcf.Data());
         return p;
      }
      fprintf(fcf,"### Use admin path at %s/admin to avoid interferences with other users\n", tutdir.Data());
      fprintf(fcf,"xrd.adminpath %s/admin\n", tutdir.Data());
#if defined(R__MACOSX)
      fprintf(fcf,"### Use dedicated socket path under /tmp to avoid length problems\n");
      fprintf(fcf,"xpd.sockpathdir /tmp/xpd-sock\n");
#endif
      fprintf(fcf,"### Run data serving on port %d\n", lportp+1);
      fprintf(fcf,"xrd.port %d\n", lportp+1);
      fprintf(fcf,"### Load the XrdProofd protocol on port %d\n", lportp);
      fprintf(fcf,"xrd.protocol xproofd libXrdProofd.so\n");
      fprintf(fcf,"xpd.port %d\n", lportp);
      if (nwrks > 0) {
         fprintf(fcf,"### Force number of local workers\n");
         fprintf(fcf,"xpd.localwrks %d\n", nwrks);
      }
      fprintf(fcf,"### Root path for working dir\n");
      fprintf(fcf,"xpd.workdir %s\n", workarea.Data());
      fprintf(fcf,"### Allow different users to connect\n");
      fprintf(fcf,"xpd.multiuser 1\n");
      fprintf(fcf,"### Limit the number of query results kept in the master sandbox\n");
      fprintf(fcf,"xpd.putrc ProofServ.UserQuotas: maxquerykept=10\n");
      fprintf(fcf,"### Limit the number of sessions kept in the sandbox\n");
      fprintf(fcf,"xpd.putrc Proof.MaxOldSessions: 1\n");
      if (tutords) {
         fprintf(fcf,"### Use dataset directory under the tutorial dir\n");
         fprintf(fcf,"xpd.datasetsrc file url:%s opt:-Cq:Av:As:\n", datasetdir.Data());
      }
      if (dyn) {
         fprintf(fcf,"### Use dynamic, per-job scheduling\n");
         fprintf(fcf,"xpd.putrc Proof.DynamicStartup 1\n");
      }
      fprintf(fcf,"### Local data server for the temporary output files\n");
      fprintf(fcf,"xpd.putenv LOCALDATASERVER=root://%s:%d\n", gSystem->HostName(), lportx);
      fclose(fcf);
      Printf("getProof: xrootd config file at %s", xpdcf.Data());

      // Start xrootd in the background
      Printf("getProof: xrootd log file at %s", xpdlogprt.Data());
      cmd = Form("%s -c %s -b -l %s -n xpdtut -p %d",
               xrootd, xpdcf.Data(), xpdlog.Data(), lportx);
      Printf("(NB: any error line from XrdClientSock::RecvRaw and XrdClientMessage::ReadRaw should be ignored)");
      if ((rc = gSystem->Exec(cmd)) != 0) {
         Printf("getProof: problems starting xrootd (%d)", rc);
         return p;
      }
      delete[] xrootd;

      // Wait a bit
      Printf("getProof: waiting for xrootd to start ...");
      gSystem->Sleep(2000);

      pid = getXrootdPid(lportx);
      Printf("getProof: xrootd pid: %d", pid);

      // Save it in the PID file
      FILE *fpid = fopen(xpdpid.Data(), "w");
      if (!fpid) {
         Printf("getProof: could not create pid file for XPD");
      } else {
         fprintf(fpid,"%d\n", pid);
         fclose(fpid);
      }
   }
   Printf("getProof: start / attach the PROOF session ...");

   // Start / attach the session now
   p = TProof::Open(lurl, vopt.Data());
   if (!p || !(p->IsValid())) {
      Printf("getProof: starting local session failed");
      if (p) delete p;
      p = 0;
      return p;
   }

   // Return the session
   return p;
#endif
}
コード例 #10
0
ファイル: df1b2lp9.cpp プロジェクト: colemonnahan/admb
/**
 * Description not yet available.
 * \param
 */
dvector laplace_approximation_calculator::get_uhat_quasi_newton_block_diagonal
  (const dvector& x,function_minimizer * pfmin)
{
  if (separable_function_difference)
  {
    delete separable_function_difference;
    separable_function_difference=0;
  }
#ifndef OPT_LIB
  assert(num_separable_calls > 0);
#endif

  separable_function_difference = new dvector(1,num_separable_calls);

  fmm** pfmc1 = new pfmm[static_cast<unsigned int>(num_separable_calls)];
  pfmc1--;
  ivector ishape(1,num_separable_calls);
  dvector gmax(1,num_separable_calls);
  gmax.initialize();

  for (int i=1;i<=num_separable_calls;i++)
  {
    int m=(*derindex)(i).indexmax();
    ishape(i)=m;
    if (m>0)
    {
    pfmc1[i] = new fmm(m);
    pfmc1[i]->iprint=0;
    pfmc1[i]->crit=inner_crit;
    pfmc1[i]->ireturn=0;
    pfmc1[i]->itn=0;
    pfmc1[i]->ifn=0;
    pfmc1[i]->ialph=0;
    pfmc1[i]->ihang=0;
    pfmc1[i]->ihflag=0;
    pfmc1[i]->maxfn=100;
    pfmc1[i]->gmax=1.e+100;
    pfmc1[i]->use_control_c=0;
    }
    else
    {
      pfmc1[i]= (fmm *)(0);
    }
  }
  dmatrix gg(1,num_separable_calls,1,ishape);
  dmatrix ggb(1,num_separable_calls,1,ishape);
  dmatrix uu(1,num_separable_calls,1,ishape);
  dmatrix uub(1,num_separable_calls,1,ishape);
  dvector ff(1,num_separable_calls);
  dvector ffb(1,num_separable_calls);
  ivector icon(1,num_separable_calls);
  icon.initialize();
  ffb=1.e+100;

  double f=0.0;
  double fb=1.e+100;
  dvector g(1,usize);
  dvector ub(1,usize);
  independent_variables u(1,usize);
  gradcalc(0,g);
  fmc1.itn=0;
  fmc1.ifn=0;
  fmc1.ireturn=0;
  initial_params::xinit(u);    // get the initial values into the
  fmc1.ialph=0;
  fmc1.ihang=0;
  fmc1.ihflag=0;

  if (init_switch)
  {
    u.initialize();
  }

  for (int ii=1;ii<=2;ii++)
  {
    // get the initial u into the uu's
    for (int i=1;i<=num_separable_calls;i++)
    {
      int m=(*derindex)(i).indexmax();
      for (int j=1;j<=m;j++)
      {
        uu(i,j)=u((*derindex)(i)(j));
      }
    }

#ifdef DIAG
    bool loop_flag = false;
    int loop_counter = 0;
#endif

    fmc1.dfn=1.e-2;
    dvariable pen=0.0;
    int converged=0;
    int initrun_flag=1;
    while (converged==0)
    {
#ifdef DIAG
      if (loop_flag) loop_counter++;
      if (loop_counter > 18)
      {
        cout << loop_counter;
      }
#endif
      if (!initrun_flag)
      {
        converged=1;
      }
      for (int i=1;i<=num_separable_calls;i++)
      {
        if (ishape(i)>0) //check to see if there are any active randoem effects
        {               // in this function call
          if (!icon(i))
          {
            independent_variables& uuu=*(independent_variables*)(&(uu(i)));
            (pfmc1[i])->fmin(ff[i],uuu,gg(i));
            gmax(i)=fabs(pfmc1[i]->gmax);
            if (!initrun_flag)
            {
              if (gmax(i)<1.e-4  || pfmc1[i]->ireturn<=0)
              {
                icon(i)=1;
              }
              else
              {
                converged=0;
              }
            }
          }
        }
      }
      initrun_flag=0;
      for (int i2=1;i2<=num_separable_calls;i2++)
      {
        int m=(*derindex)(i2).indexmax();
        for (int j=1;j<=m;j++)
        {
          u((*derindex)(i2)(j))=uu(i2,j);
        }
      }
      // put the
      //if (fmc1.ireturn>0)
      {
        dvariable vf=0.0;
        pen=initial_params::reset(dvar_vector(u));
        *objective_function_value::pobjfun=0.0;

        //num_separable_calls=0;

        pmin->inner_opt_flag=1;
        pfmin->AD_uf_inner();
        pmin->inner_opt_flag=0;

        if (saddlepointflag)
        {
          *objective_function_value::pobjfun*=-1.0;
        }
        if ( no_stuff==0 && quadratic_prior::get_num_quadratic_prior()>0)
        {
          quadratic_prior::get_M_calculations();
        }
        vf+=*objective_function_value::pobjfun;

        objective_function_value::fun_without_pen=value(vf);
        vf+=pen;

        gradcalc(usize,g);
        for (int i=1;i<=num_separable_calls;i++)
        {
          int m=(*derindex)(i).indexmax();
          for (int j=1;j<=m;j++)
          {
            gg(i,j)=g((*derindex)(i)(j));
          }
        }
        {
          ofstream ofs("l:/temp1.dat");
          ofs << g.indexmax() << " " << setprecision(15) << g << endl;
        }
        if (saddlepointflag==2)
        {
          ff[1]=-(*separable_function_difference)(1);
          for (int i=2;i<=num_separable_calls;i++)
          {
            ff[i]=-(*separable_function_difference)(i);
            //ff[i]=-(*separable_function_difference)(i)
             // +(*separable_function_difference)(i-1);

            if (ff[i] < ffb[i])
            {
              ffb[i]=ff[i];
              uub[i]=uu[i];
              ggb[i]=gg[i];
            }
          }
        }
        else
        {
          ff[1]=(*separable_function_difference)(1);
          for (int i=2;i<=num_separable_calls;i++)
          {
            ff[i]=(*separable_function_difference)(i);
            //ff[i]=(*separable_function_difference)(i)
             // -(*separable_function_difference)(i-1);

            if (ff[i] < ffb[i])
            {
              ffb[i]=ff[i];
              uub[i]=uu[i];
              ggb[i]=gg[i];
            }
          }
        }
        f=0.0;
        for (int i2=1;i2<=num_separable_calls;i2++)
        {
          f+=ff[i2];
        }
        if (f<fb)
        {
          fb=f;
          ub=u;
        }
      }
      u=ub;
    }
    double tmax=max(gmax);
    cout <<  " inner maxg = " << tmax << endl;

    if (tmax< 1.e-4) break;
  }
  fmc1.ireturn=0;
  fmc1.fbest=fb;
  gradient_structure::set_NO_DERIVATIVES();
  //num_separable_calls=0;
  pmin->inner_opt_flag=1;
  pfmin->AD_uf_inner();
  pmin->inner_opt_flag=0;
  if ( no_stuff==0 && quadratic_prior::get_num_quadratic_prior()>0)
  {
    quadratic_prior::get_M_calculations();
  }
  gradient_structure::set_YES_DERIVATIVES();
  for (int i=1;i<=num_separable_calls;i++)
  {
    if (pfmc1[i])
    {
      delete pfmc1[i];
    }
  }
  pfmc1++;
  delete [] pfmc1;
  pfmc1 = 0;
  return u;
}
コード例 #11
0
ファイル: ProofAux.C プロジェクト: gganis/proof
//_____________________________________________________________________________
Int_t ProofAux::GenerateFriend(const char *fnt, const char *fnf)
{
   // Generate the friend tree for the main tree in the 'friends' tutorial fetched
   // from 'fnt'.
   // the tree is called 'Tfriend', has the same number of entries as the main
   // tree and is saved to file 'fnf'. If 'fnf' is not defined the filename is
   // derived from 'fnt' either replacing 'tree' with 'friend', or adding '_friend'
   // before the '.root' extension.
   // Return 0 on success, -1 on error.

   Int_t rc = -1;
   // Check the input filename
   TString fin(fnt);
   if (fin.IsNull()) {
      Error("GenerateFriend", "file name for the main tree undefined!");
      return rc;
   }
   // Make sure that the file can be read
   if (gSystem->AccessPathName(fin, kReadPermission)) {
      Error("GenerateFriend", "input file does not exist or cannot be read: %s", fin.Data());
      return rc;
   }

   // File handlers
   Bool_t sameFile = kTRUE;
   const char *openMain = "UPDATE";

   // The output filename
   TString fout(fnf);
   if (!fout.IsNull()) {
      sameFile = kFALSE;
      openMain = "READ";
      // Make sure the directory exists
      TString dir = gSystem->DirName(fout);
      if (gSystem->AccessPathName(dir, kWritePermission)) {
         if (gSystem->mkdir(dir, kTRUE) != 0) {
            Error("GenerateFriend", "problems creating directory %s to store the file", dir.Data());
            return rc;
         }
      }
   } else {
      // We set the same name
      fout = fin;
   }

   // Get main tree
   TFile *fi = TFile::Open(fin, openMain);
   if (!fi || fi->IsZombie()) {
      Error("GenerateFriend", "problems opening input file %s", fin.Data());
      return rc;
   }
   TTree *Tin = (TTree *) fi->Get("Tmain");
   if (!Tin) {
      Error("GenerateFriend", "problems getting tree 'Tmain' from file %s", fin.Data());
      delete fi;
      return rc;
   }
   // Set branches
   Float_t x, y, z;
   Tin->SetBranchAddress("x", &x);
   Tin->SetBranchAddress("y", &y);
   Tin->SetBranchAddress("z", &z);
   TBranch *b_x = Tin->GetBranch("x");
   TBranch *b_y = Tin->GetBranch("y");
   TBranch *b_z = Tin->GetBranch("z");

   TDirectory* savedir = gDirectory;
   // Create output file
   TFile *fo = 0;
   if (!sameFile) {
      fo = new TFile(fout, "RECREATE");
      if (!fo || fo->IsZombie()) {
         Error("GenerateFriend", "problems opening file %s", fout.Data());
         delete fi;
         return rc;
      }
      savedir->cd();
   } else {
      // Same file
      fo = fi;
   }
   rc = 0;

   // Create the tree
   TTree *Tfrnd = new TTree("Tfrnd", "Friend tree for tutorial 'friends'");
   Tfrnd->SetDirectory(fo);
   Float_t r = 0;
   Tfrnd->Branch("r",&r,"r/F");
   Long64_t ent = Tin->GetEntries();
   for (Long64_t i = 0; i < ent; i++) {
      b_x->GetEntry(i);
      b_y->GetEntry(i);
      b_z->GetEntry(i);
      r = TMath::Sqrt(x*x + y*y + z*z);
      Tfrnd->Fill();
   }
   if (!sameFile) {
      fi->Close();
      delete fi;
   }
   Tfrnd->Print();
   fo->cd();
   Tfrnd->Write();
   Tfrnd->SetDirectory(0);
   fo->Close();
   delete fo;
   delete Tfrnd;

   // Notify success
   Info("GenerateFriend", "friend file '%s' successfully created", fout.Data());

   // Add to the list
   TUrl uu(fout);
   if (!strcmp(uu.GetProtocol(), "file")) {
      if (gSystem->Getenv("LOCALDATASERVER")) {
         if (strcmp(TUrl(gSystem->Getenv("LOCALDATASERVER"), kTRUE).GetProtocol(), "file"))
            fout.Insert(0, TString::Format("%s/", gSystem->Getenv("LOCALDATASERVER")));
      } else {
         fout.Insert(0, TString::Format("root://%s/", gSystem->HostName()));
      }
   }
   fFriendList->Add(new TObjString(fout));

   // Done
   return rc;
}
コード例 #12
0
ファイル: ProofAux.C プロジェクト: gganis/proof
//_____________________________________________________________________________
Int_t ProofAux::GenerateTree(const char *fnt, Long64_t ent, TString &fn)
{
   // Generate the main tree for the 'friends' tutorial; the tree is called
   // 'Tmain', has 'ent' entries and is saved to file 'fnt'.
   // The full file path is returned in 'fn'.
   // Return 0 on success, -1 on error.

   Int_t rc = -1;

   // Check the filename
   fn = fnt;
   if (fn.IsNull()) {
      Error("GenerateTree", "file name undefined!");
      return rc;
   }
   TUrl uu(fn, kTRUE);
   if (!strcmp(uu.GetProtocol(), "file") && !fn.BeginsWith("/")) {
      // Local file with relative path: create under the data directory
      if (!gProofServ ||
          !(gProofServ->GetDataDir()) || strlen(gProofServ->GetDataDir()) <= 0) {
         Error("GenerateTree", "data directory undefined!");
         return rc;
      }
      // Insert data directory
      fn.Insert(0, TString::Format("%s/", gProofServ->GetDataDir()));
      // Make sure the directory exists
      TString dir = gSystem->DirName(fn);
      if (gSystem->AccessPathName(dir, kWritePermission)) {
         if (gSystem->mkdir(dir, kTRUE) != 0) {
            Error("GenerateTree", "problems creating directory %s to store the file", dir.Data());
            return rc;
         }
      }
   }

   // Create the file
   TDirectory* savedir = gDirectory;
   TFile *f = new TFile(fn, "RECREATE");
   if (!f || f->IsZombie()) {
      Error("GenerateTree", "problems opening file %s", fn.Data());
      return rc;
   }
   savedir->cd();
   rc = 0;

   // Create the tree
   TTree *T = new TTree("Tmain","Main tree for tutorial friends");
   T->SetDirectory(f);
   Int_t Run = 1;
   T->Branch("Run",&Run,"Run/I");
   Long64_t Event = 0;
   T->Branch("Event",&Event,"Event/L");
   Float_t x = 0., y = 0., z = 0.;
   T->Branch("x",&x,"x/F");
   T->Branch("y",&y,"y/F");
   T->Branch("z",&z,"z/F");
   TRandom r;
   for (Long64_t i = 0; i < ent; i++) {
      if (i > 0 && i%1000 == 0) Run++;
      Event = i;
      x = r.Gaus(10,1);
      y = r.Gaus(20,2);
      z = r.Landau(2,1);
      T->Fill();
   }
   T->Print();
   f->cd();
   T->Write();
   T->SetDirectory(0);
   f->Close();
   delete f;
   delete T;

   // Notify success
   Info("GenerateTree", "file '%s' successfully created", fn.Data());

   // Add to the list
   TString fds(fn);
   if (!strcmp(uu.GetProtocol(), "file")) {
      if (gSystem->Getenv("LOCALDATASERVER")) {
         if (strcmp(TUrl(gSystem->Getenv("LOCALDATASERVER"), kTRUE).GetProtocol(), "file"))
            fds.Insert(0, TString::Format("%s/", gSystem->Getenv("LOCALDATASERVER")));
      } else {
         fds.Insert(0, TString::Format("root://%s/", gSystem->HostName()));
      }
   }
   fMainList->Add(new TObjString(fds));

   // Done
   return rc;
}
コード例 #13
0
void SetPositivePoints_Unst(const int& space_order, dTensor2& spts)
{

    // Positivity points with duplicates removed.  I am unaware of a clever
    // solution to construct these without saving duplicates
    //
    // TODO - hard code the points for second, fourth and fifth-order case
    //
    if( space_order == 3 )
    {
        spts.set(1,1, -2.206316679540750e-01 );
        spts.set(1,2, -3.333333333333334e-01 );
        spts.set(2,1, 5.539650012874083e-01  );
        spts.set(2,2, -2.206316679540750e-01 );
        spts.set(3,1, -3.333333333333334e-01 );
        spts.set(3,2, 5.539650012874083e-01  );
        spts.set(4,1, 1.666666666666667e-01  );
        spts.set(4,2, -3.333333333333333e-01 );
        spts.set(5,1, 1.666666666666667e-01  );
        spts.set(5,2, 1.666666666666667e-01  );
        spts.set(6,1, -3.333333333333333e-01 );
        spts.set(6,2, 1.666666666666667e-01  );
        spts.set(7,1, 5.539650012874083e-01  );
        spts.set(7,2, -3.333333333333334e-01 );
        spts.set(8,1, -2.206316679540750e-01 );
        spts.set(8,2, 5.539650012874083e-01  );
        spts.set(9,1, -3.333333333333334e-01 );
        spts.set(9,2, -2.206316679540750e-01);
        spts.set(10,1, -2.769825006437042e-01 );
        spts.set(10,2, -2.769825006437042e-01);
        spts.set(11,1, 5.539650012874084e-01 );
        spts.set(11,2, -2.769825006437042e-01);
        spts.set(12,1, -2.769825006437042e-01 );
        spts.set(12,2, 5.539650012874084e-01);
        spts.set(13,1, -8.333333333333334e-02 );
        spts.set(13,2, -8.333333333333333e-02);
        spts.set(14,1, 1.666666666666667e-01 );
        spts.set(14,2, -8.333333333333334e-02);
        spts.set(15,1, -8.333333333333333e-02 );
        spts.set(15,2, 1.666666666666667e-01);
        spts.set(16,1, 1.103158339770375e-01 );
        spts.set(16,2, 1.103158339770375e-01);
        spts.set(17,1, -2.206316679540750e-01 );
        spts.set(17,2, 1.103158339770375e-01);
        spts.set(18,1, 1.103158339770375e-01 );
        spts.set(18,2, -2.206316679540750e-01);
        return;

    } 

    // -------------------------------------------------------------- //
    // Positivity points for the general case.  There are many duplicates that
    // will be saved if you enter this part of the code!
    // -------------------------------------------------------------- //

    // Gaussian Quadrature points
    dTensor1 s1d_ga(space_order);
    setGaussPoints1d( s1d_ga );

    // Gauss lobatto points
    dTensor1 s1d_gl(space_order);  
    setGaussLobattoPoints1d( s1d_gl );

    // values for defining quadrature points (TODO - remove these)
    double A, B, C;

    // Vertices of Canonical triangle (in Clockwise order)
    double v1[] = {-1./3., -1./3.};
    double v2[] = {-1./3.,  2./3.};
    double v3[] = { 2./3., -1./3.};

// TESTING VERTICES
//  double v1[] = {-1., 0.};
//  double v2[] = { 1., 0.};
//  double v3[] = { 0., 1.};

    // 2D points (on the square) //
    dTensor3 uu( spts.getsize(1), spts.getsize(1), 2 );
    dTensor3 vv( spts.getsize(1), spts.getsize(1), 2 );
    for (int m=1; m<=space_order; m++)
    for (int k=1; k<=space_order; k++)
    {
        uu.set(m,k, 1, s1d_gl.get(m) );
        vv.set(m,k, 2, s1d_ga.get(k) );
    }

    // Weird mapping from unit square to triangles
    int z = 0;
    for( int m=1; m<=space_order; m++)
    for( int k=1; k<=space_order; k++)
    {

        double ua = uu.get(m,k,1);
        double vb = vv.get(m,k,2);

        A = 0.5*( 1.0 + vb );
        B = 0.25*( 1. + ua )*( 1. - vb );
        C = 0.25*( 1. - ua )*( 1. - vb );

        z++;
        spts.set( z, 1, A*v1[0] + B*v2[0] + C*v3[0] );
        spts.set( z, 2, A*v1[1] + B*v2[1] + C*v3[1] );
//      printf("spts(%d,:) = [%2.15e %2.15e];\n", z, spts.get(z,1), spts.get(z,2) );

        z++;
        spts.set( z, 1, A*v3[0] + B*v1[0] + C*v2[0] );
        spts.set( z, 2, A*v3[1] + B*v1[1] + C*v2[1] );
//      printf("spts(%d,:) = [%2.15e %2.15e];\n", z, spts.get(z,1), spts.get(z,2) );

        z++;
        spts.set( z, 1, A*v2[0] + B*v3[0] + C*v1[0] );
        spts.set( z, 2, A*v2[1] + B*v3[1] + C*v1[1] );
//      printf("spts(%d,:) = [%2.15e %2.15e];\n", z, spts.get(z,1), spts.get(z,2) );

    }

}
コード例 #14
0
ファイル: dmga_worker.cpp プロジェクト: svn2github/UltraScan3
// Find the minimum fitness value close to a discrete GA gene using
//  inverse hessian minimization
double US_MPI_Analysis::minimize_dmga( DGene& dgene, double fitness )
{
DbgLv(1) << my_rank << "dg:IHM:minimize dgene comps" << dgene.components.size() << fitness;
   int vsize     = nfloatc;
   US_Vector vv( vsize );  // Input values
   US_Vector uu( vsize );  // Vector of derivatives
   US_Vector zz( vsize );  // Vector of normalizing factors

   // Create hessian as identity matrix
   QVector< QVector< double > > hessian( vsize );

   for ( int ii = 0; ii < vsize; ii++ ) 
   {
      hessian[ ii ]       = QVector< double >( vsize, 0.0 );
      hessian[ ii ][ ii ] = 1.0;
   }

   dgmarker.resize( vsize );
   marker_from_dgene( dgmarker, dgene );

   // Convert gene to array of normalized doubles and save normalizing factors
   for ( int ii = 0; ii < vsize; ii++ )
   {
      double vval   = dgmarker[ ii ];
      double vpwr   = (double)qFloor( log10( vval ) );
      double vnorm  = pow( 10.0, -vpwr );
      vv.assign( ii, vval * vnorm );
      zz.assign( ii, vnorm );
DbgLv(1) << my_rank << "dg:IHM:  ii" << ii << "vval vnorm" << vval << vnorm
         << "vpwr" << vpwr << "vvi" << vv[ii];
   }

   lamm_gsm_df_dmga( vv, uu, zz );   // uu is vector of derivatives

   static const double epsilon_f      = 1.0e-7;
   static const int    max_iterations = 20;
   int    iteration      = 0;
   double epsilon        = epsilon_f * fitness * 4.0;
   bool   neg_cnstr      = ( vv[ 0 ] < 0.1 );  // Negative constraint?

   while ( uu.L2norm() >= epsilon_f  && iteration < max_iterations )
   {
      iteration++;
      if ( fitness == 0.0 ) break;

      US_Vector v_s1 = vv;
      double g_s1    = fitness;
      double s1      = 0.0;
      double s2      = 0.5;
      double s3      = 1.0;
DbgLv(1) << my_rank << "dg:IHM:   iteration" << iteration << "fitness" << fitness;

      // v_s2 = vv - uu * s2
      US_Vector v_s2( vsize );
      vector_scaled_sum( v_s2, uu, -s2, vv );

      if ( neg_cnstr  &&  v_s2[ 0 ] < 0.1 )
      {
         v_s2.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
      }

      double g_s2 = get_fitness_v_dmga( v_s2, zz );
DbgLv(1) << my_rank << "dg:IHM: g_s2" << g_s2 << "s2" << s2 << "epsilon" << epsilon;

      // Cut down until we have a decrease
      while ( s2 > epsilon  &&  g_s2 > g_s1 )
      {
         s3  = s2;
         s2 *= 0.5;
         // v_s2 = vv - uu * s2
         vector_scaled_sum( v_s2, uu, -s2, vv );

         if ( neg_cnstr  &&  v_s2[ 0 ] < 0.1 )
         {
            v_s2.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
         }

         g_s2 = get_fitness_v_dmga( v_s2, zz );
      }
DbgLv(1) << my_rank << "dg:IHM:  g_s2" << g_s2;

      // Test for initial decrease
      if ( s2 <= epsilon  ||  ( s3 - s2 ) < epsilon ) break;

      US_Vector v_s3( vsize );

      // v_s3 = vv - uu * s3
      vector_scaled_sum( v_s3, uu, -s3, vv );

      if ( neg_cnstr  &&  v_s3[ 0 ] < 0.1 )
      {
         v_s3.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
      }

      double g_s3 = get_fitness_v_dmga( v_s3, zz );

      int              reps     = 0;
      static const int max_reps = 100;

      while ( ( ( s2 - s1 ) > epsilon )  &&
              ( ( s3 - s2 ) > epsilon )  &&
              ( reps++ < max_reps ) )
      {
         double s1_s2 = 1.0 / ( s1 - s2 );
         double s1_s3 = 1.0 / ( s1 - s3 );
         double s2_s3 = 1.0 / ( s2 - s3 );

         double s1_2 = sq( s1 );
         double s2_2 = sq( s2 );
         double s3_2 = sq( s3 );

         double aa = ( ( g_s1 - g_s3 ) * s1_s3 -
                       ( g_s2 - g_s3 ) * s2_s3
                     ) * s1_s2;

         double bb = ( g_s3 * ( s2_2 - s1_2 ) +
                       g_s2 * ( s1_2 - s3_2 ) +
                       g_s1 * ( s3_2 - s2_2 )
                     ) *
                     s1_s2 * s1_s3 * s2_s3;

         static const double max_a = 1.0e-25;

         if ( qAbs( aa ) < max_a )
         {
            // Restore gene from array of normalized doubles
            for ( int ii = 0; ii < vsize; ii++ )
            {
               dgmarker[ ii ] = vv[ ii ] / zz[ ii ];
            }

            dgene_from_marker( dgmarker, dgene );

            return fitness;
         }

         double xx        = -bb / ( 2.0 * aa );
         double prev_g_s2 = g_s2;

         if ( xx < s1 )
         {
            if ( xx < ( s1 + s1 - s2 ) ) // Keep it close
            {
               xx = s1 + s1 - s2;             // xx <- s1 + ds
               if ( xx < 0 ) xx = s1 / 2.0;
            }

            if ( xx < 0 )  //  Wrong direction!
            {
               if ( s1 < 0 ) s1 = 0.0;
               xx = 0;
            }

            // OK, take xx, s1, s2 
            v_s3  = v_s2;
            g_s3  = g_s2;                  // 3 <- 2
            s3    = s2;
            v_s2  = v_s1;
            g_s2  = g_s1;
            s2    = s1;                    // 2 <- 1
            s1    = xx;                    // 1 <- xx
 
            // v_s1 = vv - uu * s1
            vector_scaled_sum( v_s1, uu, -s1, vv );
 
            if ( neg_cnstr  &&  v_s1[ 0 ] < 0.1 )
            {
               v_s1.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
            }

            g_s1 = get_fitness_v_dmga( v_s1, zz ); 
         }
         else if ( xx < s2 ) // Take s1, xx, s2
         {
            v_s3  = v_s2;
            g_s3  = g_s2;             // 3 <- 2
            s3    = s2;
            s2    = xx;               // 2 <- xx

            // v_s2 = vv - uu * s2
            vector_scaled_sum( v_s2, uu, -s2, vv );

            if ( neg_cnstr  &&  v_s2[ 0 ] < 0.1 )
            {
               v_s2.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
            }

            g_s2 = get_fitness_v_dmga( v_s2, zz );
         }
         else if ( xx < s3 )  // Take s2, xx, s3
         {
            v_s1  = v_s2;
            g_s1  = g_s2;
            s1    = s2;              // 2 <- 1
            s2    = xx;              // 2 <- xx

            // v_s2 = vv - uu * s2
            vector_scaled_sum( v_s2, uu, -s2, vv );

            if ( neg_cnstr  &&  v_s2[ 0 ] < 0.1 )
            {
               v_s2.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
            }

            g_s2 = get_fitness_v_dmga( v_s2, zz );
         }
         else  // xx >= s3
         {
            if ( xx > ( s3 + s3 - s2 ) ) // if xx > s3 + ds/2
            { 
               // v_s4 = vv - uu * xx
               US_Vector v_s4( vsize );
               vector_scaled_sum( v_s4, uu, -xx, vv );

               if ( neg_cnstr  &&  v_s4[ 0 ] < 0.1 )
               {
                  v_s4.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
               }

               double g_s4 = get_fitness_v_dmga( v_s4, zz );

               if ( g_s4 > g_s2  &&  g_s4 > g_s3  &&  g_s4 > g_s1 ) 
               {
                  xx = s3 + s3 - s2;   // xx = s3 + ds/2
               }
            }

            // Take s2, s3, xx 
            v_s1  = v_s2;
            g_s1  = g_s2;            // 1 <- 2
            s1    = s2;
            v_s2  = v_s3;
            g_s2  = g_s3;
            s2    = s3;              // 2 <- 3
            s3    = xx;              // 3 <- xx

            // v_s3 = vv - uu * s3
            vector_scaled_sum( v_s3, uu, -s3, vv );

            if ( neg_cnstr  &&  v_s3[ 0 ] < 0.1 )
            {
               v_s3.assign( 0, 0.1 + u_random( 100 ) * 0.001 );
            }

            g_s3 = get_fitness_v_dmga( v_s3, zz );
         }

         if ( qAbs( prev_g_s2 - g_s2 ) < epsilon ) break;
      }  // end of inner loop

      US_Vector v_p( vsize );

      if ( g_s2 < g_s3  &&  g_s2 < g_s1 )
      {
         v_p     = v_s2;
         fitness = g_s2;
      }
      else if ( g_s1 < g_s3 )
      {
         v_p     = v_s1;
         fitness = g_s1;
      }
      else
      {
         v_p     = v_s3;
         fitness = g_s3;
      }
      
      US_Vector v_g( vsize );            // Vector of derivatives
      lamm_gsm_df_dmga( v_p, v_g, zz );  // New gradient in v_g (old in uu) 

      US_Vector v_dx( vsize );
      // v_dx = v_p - vv
      vector_scaled_sum( v_dx, vv, -1.0, v_p );


      vv = v_p;                      // vv   = v_p

      // dgradient  v_dg = v_g - uu
      US_Vector v_dg( vsize );
      vector_scaled_sum( v_dg, uu, -1.0, v_g );

      US_Vector v_hdg( vsize );

      // v_hdg = hessian * v_dg ( matrix * vector )
      for ( int ii = 0; ii < vsize; ii++ )
      {
         double dotprod = 0.0;

         for ( int jj = 0; jj < vsize; jj++ )
            dotprod += ( hessian[ ii ][ jj ] * v_dg[ jj ] );

         v_hdg.assign( ii, dotprod );
      }

      double fac   = v_dg.dot( v_dx  );
      double fae   = v_dg.dot( v_hdg );
      double sumdg = v_dg.dot( v_dg  );
      double sumxi = v_dx.dot( v_dx  );

      if ( fac > sqrt( epsilon * sumdg * sumxi ) )
      {
         fac        = 1.0 / fac;
         double fad = 1.0 / fae;

         for ( int ii = 0; ii < vsize; ii++ )
         {
            v_dg.assign( ii, fac * v_dx[ ii ] - fad * v_hdg[ ii ] );
         }

         for ( int ii = 0; ii < vsize; ii++ )
         {
            for ( int jj = ii; jj < vsize; jj++ )
            {
               hessian[ ii ][ jj ] +=
                  fac * v_dx [ ii ] * v_dx [ jj ] -
                  fad * v_hdg[ ii ] * v_hdg[ jj ] +
                  fae * v_dg [ ii ] * v_dg [ jj ];

                 // It's a symmetrical matrix
                 hessian[ jj ][ ii ] = hessian[ ii ][ jj ];
            }
         }
      }

      // uu = hessian * v_g ( matrix * vector )
      for ( int ii = 0; ii < vsize; ii++ )
      {
         double dotprod = 0.0;

         for ( int jj = 0; jj < vsize; jj++ )
            dotprod    += ( hessian[ ii ][ jj ] * v_g[ jj ] );

         uu.assign( ii, dotprod );
      }

   }  // end while ( uu.L2norm() > epsilon )

   // Restore gene from array of normalized doubles
   for ( int ii = 0; ii < vsize; ii++ )
   {
      dgmarker[ ii ] = vv[ ii ] / zz[ ii ];
DbgLv(1) << my_rank << "dg:IHM: ii" << ii << "vvi zzi dgmi"
         << vv[ii] << zz[ii] << dgmarker[ii];
   }

   dgene_from_marker( dgmarker, dgene );
DbgLv(1) << my_rank << "dg:IHM: FITNESS" << fitness;

   return fitness;
}
コード例 #15
0
ファイル: SparseSVD.cpp プロジェクト: ValeevGroup/iTEBD
void SparseSVD (
  const std::vector<int>& qR, // Spin quantum #s for row index
  const std::vector<int>& qC, // Spin quantum #s for col index
  const Wavefunction<double>& Wfn,
        std::vector<int>& qS, // Spin quantum #s for selected singular values
        std::vector<std::vector<double>>& lambda,
        MPS<double>& aMps,
        MPS<double>& bMps,
        double CUTOFF_)
{
  // define reference for convenience

  const matrix_type<double>& uu = Wfn.matrix_uu;
  const matrix_type<double>& ud = Wfn.matrix_ud;
  const matrix_type<double>& du = Wfn.matrix_du;
  const matrix_type<double>& dd = Wfn.matrix_dd;

  // Calculating qS0 from row quanta
  std::vector<int> qS0; qS0.reserve(2*qR.size());

  for(size_t i = 0; i < qR.size(); ++i) {
    qS0.push_back(qR[i]+1);
    qS0.push_back(qR[i]-1);
  }
  // Remove duplication...
  std::sort(qS0.begin(),qS0.end());
  qS0.resize(std::distance(qS0.begin(),std::unique(qS0.begin(),qS0.end())));

  qS.clear();
  qS.reserve(qS0.size());

  lambda.clear();
  lambda.reserve(qS0.size());

  MPS<double> aMps_;
  aMps_.matrix_u.resize(qR.size(),qS0.size());
  aMps_.matrix_d.resize(qR.size(),qS0.size());

  MPS<double> bMps_;
  bMps_.matrix_u.resize(qS0.size(),qC.size());
  bMps_.matrix_d.resize(qS0.size(),qC.size());

  matrix_type<double>& ua = aMps_.matrix_u;
  matrix_type<double>& da = aMps_.matrix_d;
  matrix_type<double>& ub = bMps_.matrix_u;
  matrix_type<double>& db = bMps_.matrix_d;

  size_t nSym = 0; // Total # of qunatum blocks to be seletected
  size_t nSel = 0; // Total # of states

  // Loop over symmetry of singular values

  for(size_t k = 0; k < qS0.size(); ++k) {

//  std::cout << "\t\t\tSymmetry sector " << std::setw(4) << k << " (" << std::setw(4) << qS0[k] << ")" << std::endl;

    // (0)  (4)  (f)  (2)
    // 0 0  0 1  1 1  0 0
    // 0 0, 0 0, 1 1, 1 0
    unsigned char bitShape = 0x0;

    int nrow = 0;
    int ncol = 0;

    // offset
    int prow = 0;
    int pcol = 0;

    // find spin symmetry viewed as forward...

    // e.g.)
    // cQ = 0 2 4 6 8 10 ...
    // rQ = 1 3 5 7 9 11 ...

    int iu,ju,id,jd;

    iu = findQuantaIndex(qR,qS0[k]-1); // Find qR[:]+1 == qS0[i]
    ju = findQuantaIndex(qC,qS0[k]+1); // Find -qS0[i] == -qC[:]+1

    id = findQuantaIndex(qR,qS0[k]+1); // Find qR[:]-1 == qS0[i]
    jd = findQuantaIndex(qC,qS0[k]-1); // Find -qS0[i] == -qC[:]+1

    if(iu >= 0 && ju >= 0 && uu(iu,ju)) {
      prow = uu(iu,ju)->rows();
      pcol = uu(iu,ju)->cols();
    //if((bitShape ^ 0xf) & 0x4) -- always true at this line
        nrow += prow;
    //if((bitShape ^ 0xf) & 0x2) -- always true at this line
        ncol += pcol;
      bitShape |= 0x8;
    }

    if(iu >= 0 && jd >= 0 && ud(iu,jd)) {
      prow = ud(iu,jd)->rows();
      if((bitShape ^ 0xf) & 0x8)
        nrow += prow;
    //if((bitShape ^ 0xf) & 0x1) -- always true at this line
        ncol += ud(iu,jd)->cols();
      bitShape |= 0x4;
    }

    if(id >= 0 && ju >= 0 && du(id,ju)) {
      pcol = du(id,ju)->cols();
    //if((bitShape ^ 0xf) & 0x1) -- always true at this line
        nrow += du(id,ju)->rows();
      if((bitShape ^ 0xf) & 0x8)
        ncol += pcol;
      bitShape |= 0x2;
    }

    if(id >= 0 && jd >= 0 && dd(id,jd)) {
      if((bitShape ^ 0xf) & 0x2)
        nrow += dd(id,jd)->rows();
      if((bitShape ^ 0xf) & 0x4)
        ncol += dd(id,jd)->cols();
      bitShape |= 0x1;
    }

    if(!bitShape) continue;

    local_matrix_type<double> C = local_matrix_type<double>::Zero(nrow,ncol);

    if(bitShape & 0x8)
      C.block(   0,   0,     prow,     pcol) = *uu(iu,ju);
    if(bitShape & 0x4)
      C.block(   0,pcol,     prow,ncol-pcol) = *ud(iu,jd);
    if(bitShape & 0x2)
      C.block(prow,   0,nrow-prow,     pcol) = *du(id,ju);
    if(bitShape & 0x1)
      C.block(prow,pcol,nrow-prow,ncol-pcol) = *dd(id,jd);

    // now having a merged blcok matrix

//  double cNorm2 = 0.0;
//  for(int ix = 0; ix < C.rows(); ++ix)
//    for(int jx = 0; jx < C.cols(); ++jx)
//      cNorm2 += C(ix,jx)*C(ix,jx);

    // Ignore the case |C| is too small, to avoid numerical instability?
//  if(cNorm2 < 1.0e-16) continue;

    Eigen::JacobiSVD<local_matrix_type<double>> svds(C,Eigen::ComputeThinU|Eigen::ComputeThinV);

    local_matrix_type<double> U = svds.matrixU();
    local_matrix_type<double> Vt= svds.matrixV().transpose();

    int nSvd = 0;
    for(; nSvd < svds.singularValues().size(); ++nSvd)
      if(svds.singularValues()[nSvd] < CUTOFF_) break;

//  std::cout << "\t\t\tTruncating " << std::setw(4) << svds.singularValues().size() << " vectors to " << std::setw(4) << nSvd << std::endl;

    // No singular value is selected...
    if(nSvd == 0) continue;

    nSel += nSvd;

    qS.push_back(qS0[k]);

    lambda.push_back(std::vector<double>(nSvd));
    for(int kSel = 0; kSel < nSvd; ++kSel)
      lambda[nSym][kSel] = svds.singularValues()[kSel];

//DEBUG
//  std::cout << "\t\t\tblock size :: " << std::setw(4) << lambda[k].size() << " ";
//  for(int ksel = 0; ksel < nSvd; ++ksel) {
//    std::cout << std::setw(10) << std::scientific << std::setprecision(2) << lambda[k][ksel];
//    if(ksel % 10 == 9) std::cout << std::endl;
//  }
//  if(lambda[k].size() % 10 > 0) std::cout << std::endl;
//DEBUG

    if(iu >= 0 && prow != 0)
      ua(iu,nSym).reset(new local_matrix_type<double>(U.block(   0,   0,     prow,nSvd)));

    if(id >= 0 && prow != nrow)
      da(id,nSym).reset(new local_matrix_type<double>(U.block(prow,   0,nrow-prow,nSvd)));

    if(ju >= 0 && pcol != 0)
      ub(nSym,ju).reset(new local_matrix_type<double>(Vt.block(   0,   0,nSvd,     pcol)));

    if(jd >= 0 && pcol != ncol)
      db(nSym,jd).reset(new local_matrix_type<double>(Vt.block(   0,pcol,nSvd,ncol-pcol)));

    ++nSym;
  }

  aMps.matrix_u.resize(qR.size(),qS.size());
  aMps.matrix_d.resize(qR.size(),qS.size());
  for(size_t i = 0; i < qR.size(); ++i)
    for(size_t j = 0; j < qS.size(); ++j) {
      aMps.matrix_u(i,j) = ua(i,j);
      aMps.matrix_d(i,j) = da(i,j);
    }

  bMps.matrix_u.resize(qS.size(),qC.size());
  bMps.matrix_d.resize(qS.size(),qC.size());
  for(size_t i = 0; i < qS.size(); ++i)
    for(size_t j = 0; j < qC.size(); ++j) {
      bMps.matrix_u(i,j) = ub(i,j);
      bMps.matrix_d(i,j) = db(i,j);
    }

//std::cout << "\t\t\t" << std::setw(4) << nSel << " vectors are selected..." << std::endl;

}