Пример #1
0
void main(int argc, char *argv[])
{
	int i;
	char *ap;
	int estat;
	
	int nfile = sysconf(_SC_OPEN_MAX);

	while (argc>1 && *argv[1]=='-') {
		for (ap = &argv[1][1]; *ap != '\0'; ap++)
			switch (*ap) {
			case 'a':
				aflag = 1;
				break;

			case 's':
				sflag = 1;
				break;

			default:
				usage();
			}
		argc--;
		argv++;
	}
	if (argc < 2)
		estat = du(".");
	else {
		estat = 0;
		for (i=1; i<argc; i++)
			estat |= du(argv[i]);
	}
	exit (estat);
}
// Compute Jacobian via finite differences
void NewtonSolver::
ComputeDFDU(const arma::vec& u, const arma::vec& f, arma::mat& jacobian)
{

  // Perturbed solution
  arma::vec du(u);

  // Problem size
  int problem_size = mpInitialGuess->n_rows;

  // Perturbed residual
  arma::vec df(problem_size);

  // Epsilon
  double epsilon = mpParameterList->finiteDifferenceEpsilon;

  // For each column
  for (int i=0; i<problem_size; i++)
  {
    // Restore original solution, then perturb it
    if (i>0)
    {
      du(i-1) = u(i-1);
    }
    du(i) += epsilon;

    // Perturbed residual
    mpProblem->ComputeF(du,df);

    // Assign jacobian column
    jacobian.col(i) = (df - f) * pow(epsilon,-1);
  }

}
int du_main(int argc, char **argv)
{
	int status = EXIT_SUCCESS;
	int i;
	int c;

	/* default behaviour */
	print = print_normal;

	/* parse argv[] */
	while ((c = getopt(argc, argv, "sl"
#ifdef BB_FEATURE_HUMAN_READABLE
"hm"
#endif
"k")) != EOF) {
			switch (c) {
			case 's':
					print = print_summary;
					break;
			case 'l':
					count_hardlinks = 1;
					break;
#ifdef BB_FEATURE_HUMAN_READABLE
			case 'h': disp_hr = 0;        break;
			case 'm': disp_hr = MEGABYTE; break;
#endif
			case 'k': break;
			default:
					show_usage();
			}
	}

	/* go through remaining args (if any) */
	if (optind >= argc) {
		if (du(".") == 0)
			status = EXIT_FAILURE;
	} else {
		long sum;

		for (i=optind; i < argc; i++) {
			if ((sum = du(argv[i])) == 0)
				status = EXIT_FAILURE;
			if(is_directory(argv[i], FALSE, NULL)==FALSE) {
				print_normal(sum, argv[i]);
			}
			reset_ino_dev_hashtable();
		}
	}

	return status;
}
Пример #4
0
void FenetreUnitaire::enregistrerTacheUnitaire()
{
    Duree du(dureeUnitaire->time().hour(), dureeUnitaire->time().minute());
    ProjetManager& pm = ProjetManager::getInstance();
    Projet* projet = pm.trouverProjet(idProjet->currentText());
    if(projet->trouverTache(idUnitaire->text()))
    {
        QMessageBox::warning(this, "erreur","sauvegarde impossible, tache deja existante");
        dispoUnitaire->setDateTime(QDateTime::currentDateTime());
        echeanceUnitaire->setDateTime(QDateTime::currentDateTime());
    }
    else if(projet->getEcheance()<echeanceUnitaire->dateTime())
    {
        QMessageBox::warning(this, "erreur","sauvegarde impossible, date d'échéance de la tache postérieure à la date d'échéance du projet");
        echeanceUnitaire->setDateTime(QDateTime::currentDateTime());
    }
    else if(projet->getDispo()>dispoUnitaire->dateTime())
    {
        QMessageBox::warning(this, "erreur","sauvegarde impossible, date de dispo de la tache antérieure a la date de dispo du projet");
        dispoUnitaire->setDateTime(QDateTime::currentDateTime());
    }
    else if(preemptive->isChecked())
    {
        if(idComposite->currentText()!="")
        {
            if(projet->getTache(idComposite->currentText()).getEcheance()<echeanceUnitaire->dateTime())
            {
                QMessageBox::warning(this, "erreur", "date echeance de la composite inferieure a l'echeance de la tache que vous ajoutez");
            }
            else if(projet->getTache(idComposite->currentText()).getDate()>dispoUnitaire->dateTime())
            {
                QMessageBox::warning(this, "erreur", "date dispo de la composite superieure a la dispo que la date que vous ajoutez");
            }
            else {
                projet->ajouterTacheUnitaire(idUnitaire->text(),titreUnitaire->text(),dispoUnitaire->dateTime(), echeanceUnitaire->dateTime(), du);
                projet->getTache(idComposite->currentText()).ajouterSousTache(projet->trouverTache(idUnitaire->text()));
                QMessageBox::about(this, "ajout", "Tache preemptive dans composite ajoutée");
                this->close();
            }
        }else{
            pm.trouverProjet(idProjet->currentText())->ajouterTachePreemptable(idUnitaire->text(),titreUnitaire->text(),dispoUnitaire->dateTime(), echeanceUnitaire->dateTime(), du);
            QMessageBox::about(this, "ajout", "Tache préemptive ajoutée");
            this->close();
        }
    }else{
        if(idComposite->currentText()!="")
        {
            projet->ajouterTacheUnitaire(idUnitaire->text(),titreUnitaire->text(),dispoUnitaire->dateTime(), echeanceUnitaire->dateTime(), du);
            projet->getTache(idComposite->currentText()).ajouterSousTache(projet->trouverTache(idUnitaire->text()));
            QMessageBox::about(this, "ajout", "Tache unitaire dans composite ajoutée");
            this->close();
        }
        else
        {
            projet->ajouterTacheUnitaire(idUnitaire->text(),titreUnitaire->text(),dispoUnitaire->dateTime(), echeanceUnitaire->dateTime(), du);
            QMessageBox::about(this, "ajout", "Tache unitaire ajoutée");
            this->close();
       }
    }
}
Пример #5
0
inline void
time_step_indexed(array2d& u, const Constants& c)
{
  // compute du/dt
  array2d du(c.nx, c.ny, u.rate(), 0, u.cache_size());
  for (int y = 1; y < c.ny - 1; y++) {
    for (int x = 1; x < c.nx - 1; x++) {
      double uxx = (u(x - 1, y) - 2 * u(x, y) + u(x + 1, y)) / (c.dx * c.dx);
      double uyy = (u(x, y - 1) - 2 * u(x, y) + u(x, y + 1)) / (c.dy * c.dy);
      du(x, y) = c.dt * c.k * (uxx + uyy);
    }
  }
  // take forward Euler step
  for (uint i = 0; i < u.size(); i++)
    u[i] += du[i];
}
void trisolve(Teuchos::RCP<Teuchos::LAPACK<int,Real> > lapack,
              const std::vector<Real>& a,
              const std::vector<Real>& b,
              const std::vector<Real>& c,
              const std::vector<Real>& r,
                    std::vector<Real>& x ) {

    const char TRANS = 'N'; 
    const int  N = b.size();
    const int  NRHS = 1;
    int info;
   
    std::vector<Real> dl(a);
    std::vector<Real> d(b);
    std::vector<Real> du(c);
    std::vector<Real> du2(N-2,0.0);
    std::vector<int>  ipiv(N);
   
    // Do matrix factorization, overwriting the LU bands 
    lapack->GTTRF(N,&dl[0],&d[0],&du[0],&du2[0],&ipiv[0],&info);
   
    x = r;
    
    // Solve the system using the banded LU factors 
    lapack->GTTRS(TRANS,N,NRHS,&dl[0],&d[0],&du[0],&du2[0],&ipiv[0],&x[0],N,&info);
}
Пример #7
0
void EvoAlgoTestIndividual::newDatumAvailable(DataDownloader<DownloadedData>* /*downloader*/)
{
	QMutexLocker locker(&m_mutex);

	const EvoAlgoTestIndividualDataFromGUI* dd = downloadDatum();

	if (dd->filenameChanged) {
		// We have to load genotypes from the new file
		m_filename = dd->filename;
		if (loadGenotypes()) {
			// Sending the number of gentypes in the file to the GUI
			DatumToUpload du(*this);
			du->numIndividuals = m_genotypes.size();

			m_genotypesChanged = true;

			salsa::Logger::info(QString("Loaded %1 genotypes from file: %2").arg(m_genotypes.size()).arg(m_filename));
		} else {
			salsa::Logger::info(QString("Failed loading genotypes from file: %1").arg(m_filename));
		}
	}

	// Saving the index of the genotype to test
	m_individual = dd->individual;
}
Пример #8
0
void LipmConstHeightPlanner::backwardPass(const Traj<1,1> &com)
{
  Eigen::Matrix<double,2,1> z;
  Eigen::Matrix<double,1,1> u;

  Eigen::Matrix<double,2,1> Lx;
  Eigen::Matrix<double,1,1> Lu;
  Eigen::Matrix<double,2,1> Qx;
  Eigen::Matrix<double,1,1> Qu;

  for (int i=(int)_zmp_d.size()-1; i>0; i--) {
    z(0) = com[i].x[0] - _zmp_d[i].x[0];
    z(1) = com[i].x[1];
    u(0) = com[i].u[0];

    Lx = _Q*z;
    Lu = _R*u;

    Qx = _A.transpose()*_Vx[i] + Lx;    
    Qu = _B.transpose()*_Vx[i] + Lu;

    _Vx[i-1] = _K.transpose()*Qu + Qx;
    _du[i] = -_Quu_inv.transpose()*Qu;
  }

#if 0
  std::fstream du("tmp/du", std::fstream::out);
  for (size_t i=0; i<_du.size(); i++) {
    du << _du[i](0) << std::endl;
  }
  du.close();
#endif
}
Пример #9
0
 void MapGradient::compute_tangent_and_binormal(
     MapVertexProperty<vec3>& tangent,
     MapVertexProperty<vec3>& binormal
 ) {
     vec2 du(1,0) ; vec2 dv(0,1) ;
     FOR_EACH_VERTEX(Map, map_, it) {
         tangent[it] = compute_gradient(it, du) ;
         binormal[it] = compute_gradient(it, dv) ;
     }
Пример #10
0
main(int argc, char *argv[])
{
	int	i, n = 0, recurse=0, all=0, verbose=0;
	__int64	sz = 0L;

	while (argc > 1  &&  argv[1][0] == '-')  {
		for (i=1 ; argv[1][i] ; ++i)
			switch (argv[1][i])  {
			case 'a':
			case 'A':
				all = 1;
				break;
			case 'h':
			case 'H':
				usage();
				break;
			case 'r':
			case 'R':
				recurse = 1;
				break;
			case 'v':
			case 'V':
				verbose = 1;
				break;
			default:
				fprintf(stderr, "du:  Unknown flag %c\n", argv[1][i]);
				break;
			}
		argv++;
		argc--;
	}

	if (argc == 1)
		sz = du(".", recurse, all, verbose);
	else while (argc > 1)  {
		sz += du(argv[1], recurse, all, verbose);
		n++;
		argv++;
		argc--;
	}
	if (n > 1  ||  (!all  &&  !verbose))
		printf("\nTotal = %s\n", format(sz));
	return 0;
}
Пример #11
0
static void ParticlesAdvector_RKII()
{
	VFXEpoch::Grid2DfScalarField du(v.getDimY(), v.getDimX(), 1.0f / v.getDimX(), 1.0f / v.getDimY());
	VFXEpoch::Grid2DfScalarField dv(v.getDimY(), v.getDimX(), 1.0f / v.getDimX(), 1.0f / v.getDimY());
	VFXEpoch::ExtractComponents(du, v, VFXEpoch::VECTOR_COMPONENTS::X);
	VFXEpoch::ExtractComponents(dv, v, VFXEpoch::VECTOR_COMPONENTS::Y);
	sl2D_solver._advect_particles_rk2(du, dv, particles);
	du.clear();
	dv.clear();
}
Пример #12
0
 ImageConverter()
   : it_(nh_), dist(0)
 {
   ros::Time::init();
   ros::Duration du(5.0);
   du.sleep();
   image_pub_ = it_.advertise("out", 1);
   //image_sub_ = it_.subscribe("in", 1, &ImageConverter::imageCb, this, image_transport::TransportHints("compressed"));
   image_sub_ = it_.subscribe("camera/rgb/image_color", 1, &ImageConverter::imageCb, this);
   cmd_vel_pub = nh.advertise<geometry_msgs::Twist>("cmd_vel",1);
 }
  ImageConverter()
    : it_(nh_), minDist(90)
  {
    ros::Time::init();
    ros::Duration du(5.0);
    du.sleep();
    image_pub_ = it_.advertise("out", 1);
    //image_sub_ = it_.subscribe("in", 1, &ImageConverter::imageCb, this, image_transport::TransportHints("compressed"));
    image_sub_ = it_.subscribe("camera/rgb/image_color", 1, &ImageConverter::imageCb, this);

    target[0] = target[1] = target[2] = 0;
    //cv::namedWindow(WINDOW);
  }
    Real GemanRoncoroniProcess::evolve(Time t0, Real x0, 
                                       Time dt, Real dw) const {
        // random number generator for the jump part 
        if (!urng_) {
            typedef PseudoRandom::urng_type urng_type;
            urng_ = boost::shared_ptr<urng_type>(
                     new urng_type((unsigned long)(1234ul*dw+56789ul)));
        }
        Array du(3); 
        du[0] = urng_->next().value; 
        du[1] = urng_->next().value;

        return evolve(t0, x0, dt, dw, du);
    }
Пример #15
0
 int main(){
     node *root=(node *)malloc(sizeof(node));
     node *temp=root;
     for(int i=0;i<10;i++){
               temp->data=i+1;
               temp->next=(node *)malloc(sizeof(node));
               temp=temp->next;        
               } // bagli liste tanimlandi
               temp->next=NULL;
               temp=root; //listeyi basa aldi
               du(temp); // fonksiyona temp atildi
               getch();
               return 0; 
               }
Пример #16
0
vlong
du(char *name, Dir *dir)
{
	int fd, i, n;
	Dir *buf, *d;
	String *file;
	vlong nk, t;

	if(dir == nil)
		return warn(name);

	if((dir->qid.type&QTDIR) == 0)
		return dirval(dir, blkmultiple(dir->length));

	fd = open(name, OREAD);
	if(fd < 0)
		return warn(name);
	nk = 0;
	while((n=dirread(fd, &buf)) > 0) {
		d = buf;
		for(i = n; i > 0; i--, d++) {
			if((d->qid.type&QTDIR) == 0) {
				nk += dufile(name, d);
				continue;
			}

			if(strcmp(d->name, ".") == 0 ||
			   strcmp(d->name, "..") == 0 ||
			   /* !readflg && */ seen(d))
				continue;	/* don't get stuck */

			file = s_copy(name);
			s_append(file, "/");
			s_append(file, d->name);

			t = du(s_to_c(file), d);

			nk += t;
			t = dirval(d, t);
			if(!sflag)
				printamt(t, s_to_c(file));
			s_free(file);
		}
		free(buf);
	}
	if(n < 0)
		warn(name);
	close(fd);
	return dirval(dir, nk);
}
Пример #17
0
void block::CreateCells(complex* c)
{
   bitcode dl(cube_bits+chomDIM); // minimum vertex -- diagonal
   dl.SetAs(this->bc);

   bitcode du(cube_bits+chomDIM); // maximum vertex -- diagonal
   du.SetAs(this->bc);
   for(int i=0; i<chomDIM; ++i)
     du.Increment(i);

   cell* new_cell=NULL;
   Create(&new_cell,dl,du,chomDIM,c,bdry_verts);
   new_cell->MarkInterior();

//   for(int i=0; i<chomDIM+1; ++i)
//     assert(cells[i].Empty());
   cells[chomDIM].Insert(new_cell);
}
Пример #18
0
inline void
time_step_iterated(array2d& u, const Constants& c)
{
  // compute du/dt
  array2d du(c.nx, c.ny, u.rate(), 0, u.cache_size());
  for (typename array2d::iterator p = du.begin(); p != du.end(); p++) {
    int x = p.i();
    int y = p.j();
    if (1 <= x && x <= c.nx - 2 &&
        1 <= y && y <= c.ny - 2) {
      double uxx = (u(x - 1, y) - 2 * u(x, y) + u(x + 1, y)) / (c.dx * c.dx);
      double uyy = (u(x, y - 1) - 2 * u(x, y) + u(x, y + 1)) / (c.dy * c.dy);
      *p = c.dt * c.k * (uxx + uyy);
    }
  }
  // take forward Euler step
  for (typename array2d::iterator p = u.begin(), q = du.begin(); p != u.end(); p++, q++)
    *p += *q;
}
Пример #19
0
static	__int64 du(char *path, int recurse, int all, int verbose)
{
	int	r, flg;
	HANDLE	h;
	WIN32_FIND_DATA	fi;
	struct	_stati64	sb;
	__int64	sz = 0L;
	char	buf[256];

	r = strlen(path) - 1;
	if (flg = (path[r] == '/'  ||  path[r] == '\\'  ||  path[r] == ':'))
		sprintf(buf, "%s*.*", path);
	else
		sprintf(buf, "%s/*.*", path);
	h = FindFirstFile(buf, &fi);
	r = h != INVALID_HANDLE_VALUE;
	while (r)  {
		if (strcmp(fi.cFileName, ".")  &&  strcmp(fi.cFileName, ".."))  {
			if (flg)
				sprintf(buf, "%s%s", path, fi.cFileName);
			else
				sprintf(buf, "%s/%s", path, fi.cFileName);
			r = _stati64(buf, &sb);
			if (!r)  {
				if (sb.st_mode & _S_IFDIR)  {
					if (recurse)
						sz += du(buf, recurse, all, verbose);
				}  else  {
					if (all)
						printf("%s %s\n", buf, format(sb.st_size));
					sz += sb.st_size;
				}
			}
		}
		r = FindNextFile(h, &fi);
	}
	if (h != INVALID_HANDLE_VALUE)
		FindClose(h);
	if (verbose || all)
		printf("%s %s\n", path, format(sz));
	return sz;
}
Пример #20
0
/** Initialise the environment for the specified grid size.
 * \param iGridRes Integer grid resolution.
 * \param iGridRes Integer grid resolution.
 */
void CqLightsource::Initialise( TqInt uGridRes, TqInt vGridRes, TqInt microPolygonCount, TqInt shadingPointCount, bool hasValidDerivatives )
{
	TqInt Uses = gDefLightUses;
	if ( m_pShader )
	{
		Uses |= m_pShader->Uses();
		m_pShaderExecEnv->Initialise( uGridRes, vGridRes, microPolygonCount, shadingPointCount, hasValidDerivatives, m_pAttributes, boost::shared_ptr<IqTransform>(), m_pShader.get(), Uses );
	}

	if ( m_pShader )
		m_pShader->Initialise( uGridRes, vGridRes, shadingPointCount, m_pShaderExecEnv.get() );

	if ( USES( Uses, EnvVars_L ) )
		L() ->Initialise( shadingPointCount );
	if ( USES( Uses, EnvVars_Cl ) )
		Cl() ->Initialise( shadingPointCount );

	// Initialise the geometric parameters in the shader exec env.
	if ( USES( Uses, EnvVars_P ) )
	{
		CqMatrix mat;
		QGetRenderContext() ->matSpaceToSpace( "shader", "current", m_pShader->getTransform(), NULL, QGetRenderContextI()->Time(), mat );
		P() ->SetPoint( mat * CqVector3D( 0.0f, 0.0f, 0.0f ) );
	}
	if ( USES( Uses, EnvVars_u ) )
		u() ->SetFloat( 0.0f );
	if ( USES( Uses, EnvVars_v ) )
		v() ->SetFloat( 0.0f );
	if ( USES( Uses, EnvVars_du ) )
		du() ->SetFloat( 0.0f );
	if ( USES( Uses, EnvVars_dv ) )
		dv() ->SetFloat( 0.0f );
	if ( USES( Uses, EnvVars_s ) )
		s() ->SetFloat( 0.0f );
	if ( USES( Uses, EnvVars_t ) )
		t() ->SetFloat( 0.0f );
	if ( USES( Uses, EnvVars_N ) )
		N() ->SetNormal( CqVector3D( 0.0f, 0.0f, 0.0f ) );
}
Пример #21
0
void CameraScreen::reinit() {
	Camera::reinit();
	// find the position of the center of the screen in 3D space
	this->centerScreen = position + (screenDist * direction);
	double cosrot = cos(rotation);
	double sinrot = sin(rotation);
	// compute the directions of the u and v vector along the screen
	P3S sDir(direction);
	P3S sdu(P3(cosrot,0.0,sinrot));
	P3S sdv(P3(sinrot,0.0,cosrot));
	sdu.u += sDir.u + M_PI/2;
	sdv.v += sDir.v;
	P3 du(sdu);
	P3 dv(sdv);
	du.normalize();
	dv.normalize();
	// deduce dx and dy
	this->dx = du;
	this->dy = - dv;
	// precompute the top left corner of the screen
	int width = screen->getWidth();
	int height = screen->getHeight();
	this->topLeftCornerScreen = centerScreen - ((width/2)*dx) - ((height/2)*dy);
}
Пример #22
0
inline void
time_step_parallel(zfp::array2d& u, const Constants& c)
{
#ifdef _OPENMP
  // flush shared cache to ensure cache consistency across threads
  u.flush_cache();
  // compute du/dt in parallel
  zfp::array2d du(c.nx, c.ny, u.rate(), 0, u.cache_size());
  #pragma omp parallel
  {
    // create read-only private view of entire array u
    zfp::array2d::private_const_view myu(&u);
    // create read-write private view into rectangular subset of du
    zfp::array2d::private_view mydu(&du);
    mydu.partition(omp_get_thread_num(), omp_get_num_threads());
    // process rectangular region owned by this thread
    for (uint j = 0; j < mydu.size_y(); j++) {
      int y = mydu.global_y(j);
      if (1 <= y && y <= c.ny - 2)
        for (uint i = 0; i < mydu.size_x(); i++) {
          int x = mydu.global_x(i);
          if (1 <= x && x <= c.nx - 2) {
            double uxx = (myu(x - 1, y) - 2 * myu(x, y) + myu(x + 1, y)) / (c.dx * c.dx);
            double uyy = (myu(x, y - 1) - 2 * myu(x, y) + myu(x, y + 1)) / (c.dy * c.dy);
            mydu(i, j) = c.dt * c.k * (uxx + uyy);
          }
        }
    }
    // compress all private cached blocks to shared storage
    mydu.flush_cache();
  }
  // take forward Euler step in serial
  for (uint i = 0; i < u.size(); i++)
    u[i] += du[i];
#endif
}
Пример #23
0
void damage_instance::add_damage( damage_type dt, float a, float rp, float rm, float mul )
{
    damage_unit du( dt, a, rp, rm, mul );
    add( du );
}
Пример #24
0
void World::computeJacobian(MatrixXd* J) {
  double t0 = GetClock();

  World* world_copy = new World(*this, test_world_manager);

  //cout << "copying took = " << GetClock() - t0 << endl;  

  VectorXd world_state;
  //getStateForJacobian(world_state);
  world_copy->getStateForJacobian(world_state);
  int size_each_state = world_state.size();
  int size_each_control = 12; 
  J->resize(world_state.size(), size_each_control);
  J->setZero();
  double eps = 1e-1;//5e-2;

  t0 = GetClock();

  boost::thread_group group;

  /*for (int i = 0; i < 12; i++) {
    VectorXd du(12);
    du.setZero(); 
    du(i) = eps;
    if (i >= 3 && i <= 5) du(i) = 0.5 * eps; 
    if (i >= 9 && i <= 11) du(i) = 0.5 * eps;

    group.create_thread( boost::bind(computeJacCord,
          this, i, size_each_state, &du, &J) ); 

  }

  group.join_all();
  */
  
  for (int i = 0 ; i < 12; i++) { 
    VectorXd du(12);
    du.setZero(); 
    du(i) = eps;
    if (i >= 3 && i <= 5) du(i) = 0.5 * eps; 
    if (i >= 9 && i <= 11) du(i) = 0.5 * eps; 
    world_copy->applyRelativeControlJacobian(du,0.0); 
    VectorXd new_state;
    world_copy->getStateForJacobian(new_state);
    J->block(0,i, size_each_state, 1) = new_state;
    world_copy->setStateForJacobian(world_state);

    du(i) = -eps;
    if (i >= 3 && i <= 5) du(i) = 0.5 * -eps; 
    if (i >= 9 && i <= 11) du(i) = 0.5 * -eps; 
    world_copy->applyRelativeControlJacobian(du,0.0); 
    world_copy->getStateForJacobian(new_state);
    J->block(0,i, size_each_state, 1) -= new_state;
    world_copy->setStateForJacobian(world_state);

  }
  //cout << GetClock() - t0 << endl; 

  delete world_copy;
  
  (*J) /= (2 * eps); 
  //J /= eps; 

}
Пример #25
0
void damage_instance::add_damage( damage_type dt, float a, int rp, float rm, float mul )
{
    damage_unit du( dt, a, rp, rm, mul );
    damage_units.push_back( du );
}
Пример #26
0
void StateInitializerQP::testQP()
{
	int n_vars = _stateInitializer->_n_controls;


	Vector u(n_vars);

	for(int i=0;i<n_vars;i++)
		u.setTo(double(i)*1.47);


	double delta = 0.000001;
	Vector du(n_vars);

	Vector gradient_analytic(n_vars);
	Vector gradient_numeric(n_vars);

	//numeric gradient
	double f=0.0,f_new =0.0;
	objectiveFunc(u,true,f);
	gradientFunc(u,true,gradient_analytic);
	
	for(int i=0;i<n_vars;i++)
	{
		du.setToZero();
		du(i) = delta;
		objectiveFunc(u+du,true,f_new);
		double df = f_new-f;
		gradient_numeric(i) = df/delta; 
	}


	Matrix gradient_comparison(n_vars,3);
	gradient_comparison.updCol(0) = gradient_analytic;
	gradient_comparison.updCol(1) = gradient_numeric;
	gradient_comparison.updCol(2) = (gradient_analytic-gradient_numeric).elementwiseDivide(gradient_analytic);


	PrintMatrix(gradient_comparison,"gradient_comparison",std::cout);

	int n_c = _stateInitializer->_UDotRef.size();

	Matrix Jacob_analytic(n_c,n_vars);
	Matrix Jacob_numeric(n_c,n_vars);

	Vector c(n_c),c_new(n_c);
	constraintFunc(u,true,c);
	constraintJacobian(u,true,Jacob_analytic);

	for(int i=0;i<n_vars;i++)
	{
		du.setToZero();
		du(i) = delta;
		constraintFunc(u+du,true,c_new);
		Jacob_numeric.updCol(i) = (c_new-c)/delta;
	}

	Matrix Jacob_diff = Jacob_analytic - Jacob_numeric;
	Matrix Jacob_diff_normalize = Jacob_diff.elementwiseDivide(Jacob_analytic);

	PrintMatrix(Jacob_diff,"Jacob_diff",std::cout);
	PrintMatrix(Jacob_diff_normalize,"Jacob_diff_normalize",std::cout);

}
Пример #27
0
const Vector &
PFEMElement2DBubble::getResistingForceSensitivity(int gradnumber)
{
    // resize P
    int ndf = this->getNumDOF();
    P.resize(ndf);
    P.Zero();

    Vector dF(6), dFp(3), vdot(6), v(6), p(3), du(6);
    for(int i=0; i<3; i++) {
        const Vector& accel = nodes[2*i]->getTrialAccel();
        vdot(2*i) = accel(0);
        vdot(2*i+1) = accel(1);

        const Vector& vel = nodes[2*i]->getTrialVel();
        v(2*i) = vel(0);
        v(2*i+1) = vel(1);

        const Vector& vel2 = nodes[2*i+1]->getTrialVel();   // pressure
        p(i) = vel2(0);

        du(2*i) = nodes[2*i]->getDispSensitivity(1,gradnumber);
        du(2*i+1) = nodes[2*i]->getDispSensitivity(2,gradnumber);
    }
    
    // consditional sensitivity
    getdF(dF);
    double dm = getdM();
    dF.addVector(-1.0, vdot, dm);

    getdFp(dFp);
    Matrix dl;
    getdL(dl);
    dFp.addMatrixVector(-1.0, dl, p, 1.0);

    // geometric sensitivity
    Matrix dM, dg, df;
    getdM(vdot, dM);
    getdG(p, dg);
    getdF(df);
    dF.addMatrixVector(1.0, dM, du, 1.0);
    dF.addMatrixVector(1.0, dg, du, -1.0);
    dF.addMatrixVector(1.0, df, du, -1.0);

    Matrix dgt, dL, dfp;
    getdGt(v, dgt);
    getdL(p, dL);
    getdFp(dfp);
    dFp.addMatrixVector(1.0, dgt, du, 1.0);
    dFp.addMatrixVector(1.0, dL, du, 1.0);
    dFp.addMatrixVector(1.0, dfp, du, -1.0);

    // copy
    for(int i=0; i<3; i++) {
        P(numDOFs(2*i)) += dF(2*i);
        P(numDOFs(2*i)+1) += dF(2*i+1);
        P(numDOFs(2*i+1)) += dFp(i);
    }

    return P;
}
Пример #28
0
/* tiny recursive du */
static long du(const char * const filename)
{
	struct stat statbuf;
	long sum;

	if (lstat(filename, &statbuf) != 0) {
		bb_perror_msg("%s", filename);
		status = EXIT_FAILURE;
		return 0;
	}

	if (one_file_system) {
		if (du_depth == 0) {
			dir_dev = statbuf.st_dev;
		} else if (dir_dev != statbuf.st_dev) {
			return 0;
		}
	}

	sum = statbuf.st_blocks;

	if (S_ISLNK(statbuf.st_mode)) {
		if (slink_depth > du_depth) {	/* -H or -L */
			if (stat(filename, &statbuf) != 0) {
				bb_perror_msg("%s", filename);
				status = EXIT_FAILURE;
				return 0;
			}
			sum = statbuf.st_blocks;
			if (slink_depth == 1) {
				slink_depth = INT_MAX;	/* Convert -H to -L. */
			}
		}
	}

	if (statbuf.st_nlink > count_hardlinks) {
		/* Add files/directories with links only once */
		if (is_in_ino_dev_hashtable(&statbuf)) {
			return 0;
		}
		add_to_ino_dev_hashtable(&statbuf, NULL);
	}

	if (S_ISDIR(statbuf.st_mode)) {
		DIR *dir;
		struct dirent *entry;
		char *newfile;

		dir = warn_opendir(filename);
		if (!dir) {
			status = EXIT_FAILURE;
			return sum;
		}

		newfile = last_char_is(filename, '/');
		if (newfile)
			*newfile = '\0';

		while ((entry = readdir(dir))) {
			char *name = entry->d_name;

			newfile = concat_subpath_file(filename, name);
			if (newfile == NULL)
				continue;
			++du_depth;
			sum += du(newfile);
			--du_depth;
			free(newfile);
		}
		closedir(dir);
	} else if (du_depth > print_files) {
		return sum;
	}
	if (du_depth <= max_print_depth) {
		print(sum, filename);
	}
	return sum;
}
Пример #29
0
int sockinfo::setsockopt(int __level, int __optname, const void *__optval, socklen_t __optlen)
{
	int ret = SOCKOPT_PASS_TO_OS;

	if (__level == SOL_SOCKET) {
		switch(__optname) {
		case SO_VMA_USER_DATA:
			if (__optlen == sizeof(m_fd_context)) {
				m_fd_context = *(void **)__optval;
				ret = SOCKOPT_INTERNAL_VMA_SUPPORT;
			} else {
				ret = SOCKOPT_NO_VMA_SUPPORT;
				errno = EINVAL;
			}
			break;
		case SO_VMA_RING_USER_MEMORY:
			if (__optval) {
				if (__optlen == sizeof(iovec)) {
					iovec *attr = (iovec *)__optval;
					m_ring_alloc_log_rx.set_memory_descriptor(*attr);
					m_ring_alloc_logic = ring_allocation_logic_rx(get_fd(), m_ring_alloc_log_rx, this);
					if (m_p_rx_ring || m_rx_ring_map.size()) {
						si_logwarn("user asked to assign memory for "
							   "RX ring but ring already exists");
					}
					ret = SOCKOPT_INTERNAL_VMA_SUPPORT;
				} else {
					ret = SOCKOPT_NO_VMA_SUPPORT;
					errno = EINVAL;
					si_logdbg("SOL_SOCKET, SO_VMA_RING_USER_MEMORY - "
						  "bad length expected %d got %d",
						  sizeof(iovec), __optlen);
				}
			}
			else {
				ret = SOCKOPT_NO_VMA_SUPPORT;
				errno = EINVAL;
				si_logdbg("SOL_SOCKET, SO_VMA_RING_USER_MEMORY - NOT HANDLED, optval == NULL");
			}
			break;
		case SO_VMA_FLOW_TAG:
			if (__optval) {
				if (__optlen == sizeof(uint32_t)) {
					if (set_flow_tag(*(uint32_t*)__optval)) {
						si_logdbg("SO_VMA_FLOW_TAG, set "
							  "socket %s to flow id %d",
							  m_fd, m_flow_tag_id);
						// not supported in OS
						ret = SOCKOPT_INTERNAL_VMA_SUPPORT;
					} else {
						ret = SOCKOPT_NO_VMA_SUPPORT;
						errno = EINVAL;
					}
				} else {
					ret = SOCKOPT_NO_VMA_SUPPORT;
					errno = EINVAL;
					si_logdbg("SO_VMA_FLOW_TAG, bad length "
						  "expected %d got %d",
						  sizeof(uint32_t), __optlen);
					break;
				}
			} else {
				ret = SOCKOPT_NO_VMA_SUPPORT;
				errno = EINVAL;
				si_logdbg("SO_VMA_FLOW_TAG - NOT HANDLED, "
					  "optval == NULL");
			}
			break;
		case SO_TIMESTAMP:
		case SO_TIMESTAMPNS:
			if (__optval) {
				m_b_rcvtstamp = *(bool*)__optval;
				if (__optname == SO_TIMESTAMPNS)
					m_b_rcvtstampns = m_b_rcvtstamp;
				si_logdbg("SOL_SOCKET, %s=%s", setsockopt_so_opt_to_str(__optname), (m_b_rcvtstamp ? "true" : "false"));
			}
			else {
				si_logdbg("SOL_SOCKET, %s=\"???\" - NOT HANDLED, optval == NULL", setsockopt_so_opt_to_str(__optname));
			}
			break;

		case SO_TIMESTAMPING:
			if (__optval) {
				uint8_t val = *(uint8_t*)__optval;

				// SOF_TIMESTAMPING_TX_SOFTWARE and SOF_TIMESTAMPING_TX_HARDWARE is NOT supported.
				if (val & (SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_TX_HARDWARE)) {
					ret = SOCKOPT_NO_VMA_SUPPORT;
					errno = EOPNOTSUPP;
					si_logdbg("SOL_SOCKET, SOF_TIMESTAMPING_TX_SOFTWARE and SOF_TIMESTAMPING_TX_HARDWARE is not supported, errno set to EOPNOTSUPP");
				}

				if (val & (SOF_TIMESTAMPING_RAW_HARDWARE | SOF_TIMESTAMPING_RX_HARDWARE)) {
					if (g_p_ib_ctx_handler_collection->get_ctx_time_conversion_mode() == TS_CONVERSION_MODE_DISABLE){
						if (safe_mce_sys().hw_ts_conversion_mode ==  TS_CONVERSION_MODE_DISABLE) {
							ret = SOCKOPT_NO_VMA_SUPPORT;
							errno = EPERM;
							si_logdbg("SOL_SOCKET, SOF_TIMESTAMPING_RAW_HARDWARE and SOF_TIMESTAMPING_RX_HARDWARE socket options were disabled (VMA_HW_TS_CONVERSION = %d) , errno set to EPERM", TS_CONVERSION_MODE_DISABLE);
						} else {
							ret = SOCKOPT_NO_VMA_SUPPORT;
							errno = ENODEV;
							si_logdbg("SOL_SOCKET, SOF_TIMESTAMPING_RAW_HARDWARE and SOF_TIMESTAMPING_RX_HARDWARE is not supported by device(s), errno set to ENODEV");
						}
					}
				}

				m_n_tsing_flags  = val;
				si_logdbg("SOL_SOCKET, SO_TIMESTAMPING=%u", m_n_tsing_flags);
			}
			else {
				si_logdbg("SOL_SOCKET, %s=\"???\" - NOT HANDLED, optval == NULL", setsockopt_so_opt_to_str(__optname));
			}
			break;
		default:
			break;
		}
	} else if (__level == IPPROTO_IP) {
		switch(__optname) {
		case IP_TTL:
			if (__optlen < sizeof(m_n_uc_ttl)) {
				ret = SOCKOPT_NO_VMA_SUPPORT;
				errno = EINVAL;
			} else {
				int val = __optlen < sizeof(val) ?  (uint8_t) *(uint8_t *)__optval : (int) *(int *)__optval;
				if (val != -1 && (val < 1 || val > 255)) {
					ret = SOCKOPT_NO_VMA_SUPPORT;
					errno = EINVAL;
				} else {
					m_n_uc_ttl = (val == -1) ? safe_mce_sys().sysctl_reader.get_net_ipv4_ttl() : (uint8_t) val;
					header_ttl_updater du(m_n_uc_ttl, false);
					update_header_field(&du);
					si_logdbg("IPPROTO_IP, optname=IP_TTL (%d)", m_n_uc_ttl);
				}
			}
			break;
		default:
			break;
		}
	}

	si_logdbg("ret (%d)", ret);
	return ret;
}
Пример #30
0
int du_main(int argc, char **argv)
{
	long total;
	int slink_depth_save;
	int print_final_total;
	char *smax_print_depth;
	unsigned opt;

#if ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
	if (getenv("POSIXLY_CORRECT")) {	/* TODO - a new libbb function? */
#if ENABLE_FEATURE_HUMAN_READABLE
		disp_hr = 512;
#else
		disp_k = 0;
#endif
	}
#endif

	/* Note: SUSv3 specifies that -a and -s options cannot be used together
	 * in strictly conforming applications.  However, it also says that some
	 * du implementations may produce output when -a and -s are used together.
	 * gnu du exits with an error code in this case.  We choose to simply
	 * ignore -a.  This is consistent with -s being equivalent to -d 0.
	 */
#if ENABLE_FEATURE_HUMAN_READABLE
	opt_complementary = "h-km:k-hm:m-hk:H-L:L-H:s-d:d-s";
	opt = getopt32(argc, argv, "aHkLsx" "d:" "lc" "hm", &smax_print_depth);
	if (opt & (1 << 9)) {
		/* -h opt */
		disp_hr = 0;
	}
	if (opt & (1 << 10)) {
		/* -m opt */
		disp_hr = 1024*1024;
	}
	if (opt & (1 << 2)) {
		/* -k opt */
		disp_hr = 1024;
	}
#else
	opt_complementary = "H-L:L-H:s-d:d-s";
	opt = getopt32(argc, argv, "aHkLsx" "d:" "lc", &smax_print_depth);
#if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
	if (opt & (1 << 2)) {
		/* -k opt */
		disp_k = 1;
	}
#endif
#endif
	if (opt & (1 << 0)) {
		/* -a opt */
		print_files = INT_MAX;
	}
	if (opt & (1 << 1)) {
		/* -H opt */
		slink_depth = 1;
	}
	if (opt & (1 << 3)) {
		/* -L opt */
		slink_depth = INT_MAX;
	}
	if (opt & (1 << 4)) {
		/* -s opt */
		max_print_depth = 0;
	}
	one_file_system = opt & (1 << 5); /* -x opt */
	if (opt & (1 << 6)) {
		/* -d opt */
		max_print_depth = xatoi_u(smax_print_depth);
	}
	if (opt & (1 << 7)) {
		/* -l opt */
		count_hardlinks = MAXINT(nlink_t);
	}
	print_final_total = opt & (1 << 8); /* -c opt */

	/* go through remaining args (if any) */
	argv += optind;
	if (optind >= argc) {
		*--argv = (char*)".";
		if (slink_depth == 1) {
			slink_depth = 0;
		}
	}

	slink_depth_save = slink_depth;
	total = 0;
	do {
		total += du(*argv);
		slink_depth = slink_depth_save;
	} while (*++argv);
	if (ENABLE_FEATURE_CLEAN_UP)
		reset_ino_dev_hashtable();
	if (print_final_total) {
		print(total, "total");
	}

	fflush_stdout_and_exit(status);
}