コード例 #1
0
ファイル: int.cpp プロジェクト: Gecode/gecode
  void
  rel(Home home, SetVar s, IntRelType r, IntVar x) {
    GECODE_POST;
    switch (r) {
    case IRT_EQ:
      {
        Gecode::Int::IntView xv(x);
        Set::SingletonView xsingle(xv);
        GECODE_ES_FAIL(
                       (Set::Rel::Eq<Set::SetView,Set::SingletonView>
                        ::post(home,s,xsingle)));

      }
      break;
    case IRT_NQ:
      {
        Gecode::Set::SetView sv(s);
        GECODE_ME_FAIL( sv.cardMin(home, 1));
        Gecode::Int::IntView xv(x);
        Set::SingletonView xsingle(xv);
        GECODE_ES_FAIL(
                       (Set::Rel::NoSubset<Set::SingletonView,Set::SetView>
                        ::post(home,xsingle,sv)));

      }
      break;
    case IRT_LQ:
      {
        IntVar tmp(home, Int::Limits::min, Int::Limits::max);
        rel(home, tmp, IRT_LQ, x);
        GECODE_ES_FAIL(Set::Int::MaxElement<Set::SetView>::post(home,s,tmp));
      }
      break;
    case IRT_LE:
      {
        IntVar tmp(home, Int::Limits::min, Int::Limits::max);
        rel(home, tmp, IRT_LE, x);
        GECODE_ES_FAIL(Set::Int::MaxElement<Set::SetView>::post(home,s,tmp));
      }
      break;
    case IRT_GQ:
      {
        IntVar tmp(home, Int::Limits::min, Int::Limits::max);
        rel(home, tmp, IRT_GQ, x);
        GECODE_ES_FAIL(Set::Int::MinElement<Set::SetView>::post(home,s,tmp));
      }
      break;
    case IRT_GR:
      {
        IntVar tmp(home, Int::Limits::min, Int::Limits::max);
        rel(home, tmp, IRT_GR, x);
        GECODE_ES_FAIL(Set::Int::MinElement<Set::SetView>::post(home,s,tmp));
      }
      break;
    default:
      throw Int::UnknownRelation("Set::rel");
    }

  }
コード例 #2
0
ファイル: exec.cpp プロジェクト: celikpence/gecode
 void
 wait(Home home, const BoolVarArgs& x, void (*c)(Space& home),
      IntConLevel) {
   if (home.failed()) return;
   ViewArray<Int::BoolView> xv(home,x);
   GECODE_ES_FAIL(Kernel::NaryWait<Int::BoolView>::post(home,xv,c));
 }
コード例 #3
0
ファイル: Lib.cpp プロジェクト: wwbrannon/BayesTree
void Lib::sortedUnique(int n, double *x, Vec& uv)
{
   uv.clear();
   if(n==0) return;
   typedef std::vector<double>::size_type vec_sz;

   //copy x into vector xv
   Vec xv(n);
   vec_sz nv = (vec_sz)n;
   for(vec_sz i=0;i<nv;i++) xv[i] = *(x+i);

   //sort xv
   std::sort(xv.begin(),xv.end());

   //get unique values of xv into uv
   uv.push_back(xv[0]);
   vec_sz nu = 1;
   double ov = uv[0];
   for(vec_sz i=1;i<nv;i++) {
      if(xv[i] != ov) {
         ov = xv[i];
         uv.push_back(ov);
      }
   }

}
コード例 #4
0
 void
 channel(Home home, const BoolVarArgs& x, SetVar y) {
   if (home.failed()) return;
   ViewArray<Int::BoolView> xv(home,x);
   GECODE_ES_FAIL((Set::Int::ChannelBool<Set::SetView>
                        ::post(home,xv,y)));
 }
コード例 #5
0
ファイル: builder.cpp プロジェクト: stevenmizuno/QGIS
void Builder::FinalizeAnyPolyline()
{
  // Save the last polyline / polygon if one exists.
  if ( current_polyline_pointcount > 0 )
  {
    if ( current_polyline_willclose )
    {
      polyVertex << DL_VertexData( closePolyX, closePolyY, closePolyZ );
    }

    int dim = polyVertex.size();
    QVector<double> xv( dim );
    QVector<double> yv( dim );
    QVector<double> zv( dim );

    for ( int i = 0; i < dim; i++ )
    {
      xv[i] = polyVertex[i].x;
      yv[i] = polyVertex[i].y;
      zv[i] = polyVertex[i].z;
    }

    shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, NULL, NULL, dim, xv.data(), yv.data(), zv.data(), NULL );
    polyVertex.clear();

    QgsDebugMsg( QString( "Finalized adding of polyline shape %1" ).arg( shpObjects.size() - 1 ) );
    current_polyline_pointcount = 0;
  }
}
コード例 #6
0
ファイル: circuit.cpp プロジェクト: lquan/CSAI
 void
 circuit(Home home, const IntVarArgs& x, IntConLevel icl) {
   if (x.same(home))
     throw Int::ArgumentSame("Graph::circuit");
   if (x.size() == 0)
     throw Int::TooFewArguments("Graph::circuit");
   if (home.failed()) return;
   ViewArray<Int::IntView> xv(home,x);
   if (icl == ICL_DOM) {
     GECODE_ES_FAIL(Graph::Circuit::Dom<Int::IntView>::post(home,xv));
   } else {
     GECODE_ES_FAIL(Graph::Circuit::Val<Int::IntView>::post(home,xv));
   }
 }
コード例 #7
0
ファイル: builder.cpp プロジェクト: stevenmizuno/QGIS
void Builder::addCircle( const DL_CircleData& data )
{
  if ( shapefileType != SHPT_ARC && shapefileType != SHPT_POLYGON )
  {
    QgsDebugMsg( "ignoring circle" );
    return;
  }

  QgsDebugMsg( QString( "circle (%1,%2,%3 r=%4)" ).arg( data.cx ).arg( data.cy ).arg( data.cz ).arg( data.radius ) );

  if ( ignoringBlock )
  {
    QgsDebugMsg( "skipping circle in block" );
    return;
  }


  std::vector <DL_PointData> circlePoints;
  DL_PointData myPoint;

  // Approximate the circle with 360 line segments connecting points along that circle
  long shpIndex = 0;
  for ( double i = 0.0; i <= 2*M_PI; i += M_PI / 180.0, shpIndex++ )
  {
    myPoint.x = data.radius * cos( i ) + data.cx;
    myPoint.y = data.radius * sin( i ) + data.cy;
    myPoint.z = data.cz;

    circlePoints.push_back( myPoint );
  }

  int dim = circlePoints.size();
  QVector<double> xv( dim );
  QVector<double> yv( dim );
  QVector<double> zv( dim );

  for ( int i = 0; i < dim; i++ )
  {
    xv[i] = circlePoints[i].x;
    yv[i] = circlePoints[i].y;
    zv[i] = circlePoints[i].z;
  }

  shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, NULL, NULL, dim, xv.data(), yv.data(), zv.data(), NULL );

  circlePoints.clear();
}
コード例 #8
0
/** \brief This method, that must be invoked after divide, extends the data of the sources so that
 *         each one has the same points on the time axis.
 *
 * Suppose that s and t are the names of the two sources with some data over time.
 * Let source s have data at t0, t4 and t9 and source t at t1,t3,t4 and t8.
 * The fill method will make s and t time scales equal. s and t will have points at times t0,t1,t3,t4,t8 and t9.
 * The values of s in t1,t2 and t3 will be the same as the value at t0 and the value of s in t8 will be the same
 * as the value in t4, and so on.
 * This time filling routine is useful if you want to deal with time-aligned results.
 *
 * \note divide must be called before fill
 *
 * It is possible to attach a DataSieverListener in order to be notified of the progress in data
 * filling. It may be a time consuming process though.
 *
 * @see divide
 */
void DataSiever::fill()
{
    size_t tstamps_size, step = 0, steps_to_estimate, total_steps;
    double timestamp, data_timestamp_0, data_timestamp_1;
    struct timeval timeva, tv1, tv0, started_tv, ended_tv;
    gettimeofday(&started_tv, NULL);

    /* create a std set (always sorted following a specific strict weak
     * ordering criterion indicated by its internal comparison object)
     * with all the required timestamps that will fill the n vectors of
     * data.
     */
    std::set<double> timestamp_set;
    for(std::map<std::string, std::list<XVariant> >::iterator it = d_ptr->dataMap.begin();
        it != d_ptr->dataMap.end(); ++it)
    {
        std::list<XVariant> &data = it->second;
        for(std::list<XVariant>::iterator it = data.begin(); it != data.end(); it++)
        {
            timeva = it->getTimevalTimestamp();
            timestamp = timeva.tv_sec + timeva.tv_usec * 1e-6;
            /* insert timestamp in the set. If timestamp is duplicate, it's not inserted */
            timestamp_set.insert(timestamp);
        }
    }

    tstamps_size = timestamp_set.size();
    total_steps = tstamps_size * d_ptr->dataMap.size();
    steps_to_estimate = tstamps_size * 0.05;
    if(steps_to_estimate == 0)
        steps_to_estimate = tstamps_size;

    printf("\e[1;32m*\e[0m final data size will be %ld for each source... steps_to_estimate %ld\n",
           tstamps_size, steps_to_estimate);

    /* for each data row */
    for(std::map<std::string, std::list<XVariant> >::iterator it = d_ptr->dataMap.begin();
        it != d_ptr->dataMap.end(); ++it)
    {
        std::set<double>::iterator ts_set_iterator = timestamp_set.begin();
        /* take the vector of data from the map */
        std::list<XVariant> &data = it->second;
        /* create an iterator over data */
        std::list<XVariant>::iterator datait = data.begin();
        datait++; /* point to element 1 */

        while(datait != data.end())
        {
            step++;
            /* end of interval */
            tv1 = datait->getTimevalTimestamp();
            data_timestamp_1 = tv1.tv_sec + tv1.tv_usec * 1e-6;
            /* start of interval */
            tv0 = (--datait)->getTimevalTimestamp();
            data_timestamp_0 = tv0.tv_sec + tv0.tv_usec * 1e-6;
            datait++;
            /* iterate over the timestamps stored in the timestamp set. As we walk the set, avoid
             * searching the same interval multiple times. For this, keep ts_set_iterator as
             * start and update it in the last else if branch.
             */
            std::set<double>::iterator tsiter = ts_set_iterator;
            while(tsiter != timestamp_set.end())
            {
                if((*tsiter) >  data_timestamp_0 && (*tsiter) < data_timestamp_1)
                {
                    XVariant xv(*datait);
                    xv.setTimestamp((*tsiter));
                    datait = data.insert(datait, xv);
                }
                else if(*tsiter == data_timestamp_1) /* simply skip */
                {
//                    printf("\e[1;35m - skipping element cuz equal to timestamp_1: %s\e[0m", ctime(&tt));
                    tsiter++;
                    ts_set_iterator = tsiter; /* point to next */
                    break;
                }
                else if((*tsiter) > data_timestamp_1)
                {
                  //  tsiter++;
                    ts_set_iterator = tsiter; /* save to optimize next for */
//                    printf("\e[1;32m > going to next point after %s \e[0m", ctime(&tt));
                    break;
                }
                tsiter++;
                ts_set_iterator = tsiter; /* save to optimize next for */
            }
            datait++;
//            printf("\e[1;34m data index %ld data size %ld data %p\e[0m\n", dataidx, data.size(), &data);
            if(step % steps_to_estimate == 0)
            {
                double time_remaining = mEstimateFillTimeRemaining(&started_tv, step, total_steps);
                if(step == steps_to_estimate)
                    printf("\e[1;32m* \e[0mestimated time remaining: %.3fs\n", time_remaining);
            }
        }
    }
コード例 #9
0
ファイル: builder.cpp プロジェクト: stevenmizuno/QGIS
void Builder::addPolyline( const DL_PolylineData& data )
{
  if ( shapefileType != SHPT_ARC && shapefileType != SHPT_POLYGON )
  {
    QgsDebugMsg( "ignoring polyline" );
    return;
  }

  QgsDebugMsg( "reading polyline - expecting vertices" );

  if ( ignoringBlock )
  {
    QgsDebugMsg( "skipping polyline in block" );
    return;
  }

  // Add previously created polyline if not finalized yet
  if ( current_polyline_pointcount > 0 )
  {
    if ( current_polyline_willclose )
    {

      DL_VertexData myVertex;

      myVertex.x = closePolyX;
      myVertex.y = closePolyY;
      myVertex.z = closePolyZ;

      polyVertex.push_back( myVertex );

    }

    int dim = polyVertex.size();
    QVector<double> xv( dim );
    QVector<double> yv( dim );
    QVector<double> zv( dim );

    for ( int i = 0; i < dim; i++ )
    {
      xv[i] = polyVertex[i].x;
      yv[i] = polyVertex[i].y;
      zv[i] = polyVertex[i].z;
    }

    shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, NULL, NULL, dim, xv.data(), yv.data(), zv.data(), NULL );

    polyVertex.clear();

    QgsDebugMsg( QString( "polyline prepared: %1" ).arg( shpObjects.size() - 1 ) );
    current_polyline_pointcount = 0;
  }

  // Now that the currently-adding polyline (if any) is
  // finalized, parse out the flag options

  if ( data.flags == 1 || data.flags == 32 )
  {
    current_polyline_willclose = true;
    store_next_vertex_for_polyline_close = true;
  }
  else
  {
    current_polyline_willclose = false;
    store_next_vertex_for_polyline_close = false;
  }

  current_polyline_pointcount = 0;

}
コード例 #10
0
  void
  multibinpacking(Home home, 
         int n, int m, int k,
         const IntVarArgs& y, 
         const IntVarArgs& x, 
         const IntSharedArray& D,
         const IntSharedArray& B,
         IntConLevel) 
   {
      /// Check input sizes
      if (n*k != D.size() )
         throw ArgumentSizeMismatch("Int::multibinpacking");      

      if (k != B.size() )
         throw ArgumentSizeMismatch("Int::multibinpacking");      
    
      if (n != x.size() )
         throw ArgumentSizeMismatch("Int::multibinpacking");      
      
      if (m*k != y.size() )
         throw ArgumentSizeMismatch("Int::multibinpacking");      
      
      for (int i=B.size(); i--; )
         Limits::nonnegative(B[i],"Int::multibinpacking");

      if (home.failed()) return;

      /// Post first each single binpacking constraint
      /// Capacity constraint for each dimension
      for ( int j = 0; j < m; ++j )
         for ( int l = 0; l < k; ++l ) {
            IntView yi(y[j*k+l]);
            GECODE_ME_FAIL(yi.lq(home,B[l]));
         }

      /// Post a binpacking constraints for each dimension
      for ( int l = 0; l < k; ++l ) {
         ViewArray<OffsetView> yv(home,m);
         for (int j=m; j--; )
            yv[j] = OffsetView(y[j*k+l],0);

         ViewArray<BinPacking::Item> xs(home,x.size());
         for (int i=xs.size(); i--; )
            xs[i] = BinPacking::Item(x[i],D[i*k+l]);

         Support::quicksort(&xs[0], xs.size());

         GECODE_ES_FAIL(Int::BinPacking::Pack::post(home,yv,xs));
      }

      /// Clique Finding and Alldifferent posting
      {
         /// Firt construct the conflict graph
         graph_t* g = graph_new(n);
         for ( int a = 0; a < n-1; ++a ) {
            for ( int b = a+1; b < n; ++b ) {
               int v = a;  /// The variable with smaller domain
               int w = b;
               unsigned int nl = 0;
               if ( x[a].size() > x[b].size() ) {
                  v = b;
                  w = a;
               }
               IntVarValues i(x[v]);
               IntVarValues j(x[w]);
               while ( i() ) {
                  if ( i.val() != j.val() ) {
                     if ( i.val() < j.val() )
                        break;
                     else
                        ++i;
                  } else {
                     for ( int l = 0; l < k; ++l )
                        if ( D[a*k+l] + D[b*k+l] > B[l] ) {
                           nl++;
                           break;
                        }
                     ++i; ++j;
                  }
               }
               if ( nl >= x[v].size() )
                  GRAPH_ADD_EDGE(g,a,b);
            }
         }
         /// Consitency cheking: look for the maximum clique
         clique_options* opts;
         opts = (clique_options*) malloc (sizeof(clique_options));
         opts->time_function=NULL;
         opts->reorder_function=reorder_by_default;
         opts->reorder_map=NULL;
         opts->user_function=NULL;
         opts->user_data=NULL;
         opts->clique_list=NULL;
         opts->clique_list_length=0;
         set_t s;
         s = clique_find_single ( g, 0, 0, TRUE, opts);
         if ( s != NULL ) {
            if ( set_size(s) > m ) {
                set_free(s);
                free(opts);
                graph_free(g);
                GECODE_ES_FAIL(ES_FAILED);
            }
            if ( true ) { //option == 1 ) {  FIXING
               for ( int a = 0, j = 0; a < n; ++a ) {
                  if ( SET_CONTAINS_FAST(s,a) ) {
                     assert( x[a].in(j) );
                     IntView xi(x[a]);
                     GECODE_ME_FAIL(xi.eq(home,j++));
                  }
               }
            }
         }
         if ( s!=NULL )
            set_free(s);
         /// List every maximal clique in the conflict graph
         opts->user_function=record_clique_func;
         clique_find_all ( g, 2, 0, TRUE, opts);
         for ( int c = 0; c < clique_count; c++ ) {
            ViewArray<IntView> xv(home, set_size(clique_list[c]));
            for ( int a = 0, idx = 0; a < n; ++a )
               if ( SET_CONTAINS_FAST(clique_list[c],a) )
                  xv[idx++] = x[a];
            GECODE_ES_FAIL(Distinct::Dom<IntView>::post(home,xv));
            set_free(clique_list[c]);
         }
         free(opts);
         graph_free(g);
      }
   }
コード例 #11
0
ファイル: csg.cpp プロジェクト: jl2/Renderman-Tests
void doFrame(int fNum, char *fName) {

    RiFrameBegin(fNum);
    static RtColor Color = {.2, .4, .6} ;

    char buffer[256];
    sprintf(buffer, "images/%s%03d.tif", fName, fNum);
    RiDisplay(buffer,(char*)"file",(char*)"rgba",RI_NULL);

    RiFormat(800, 600,  1.25);
    RiLightSource((char*)"distantlight",RI_NULL);
    RiProjection((char*)"perspective",RI_NULL);

    RiTranslate(0.0,0.0,50);
    // RiRotate(-40.0, 1.0,0.0,0.0);
    // RiRotate(-20.0, 0.0,1.0,0.0);

    RiWorldBegin();

    RiColor(Color);

    RiRotate(fNum, 0.0,1.0,0.0);

    RtFloat  roughness = 0.03;
    int trace = 1;
    //RtFloat km = .3;
    //RtFloat maxKm = 1.0;
    RtFloat opac[] = {0.5, 0.9, 0.3};

    // RiBasis(RiBezierBasis, 3, RiBezierBasis, 3);
    //km = abs(sin(2.0*PI*((double)fNum/100.0)));

    // RiSurface((char*)"funkyglass", "roughness", (RtPointer)&roughness, RI_NULL);
    // RiOpacity(opac);
    // RiAttribute((char*)"visibility", "int trace", &trace, RI_NULL);

    RiSurface((char*)"matte", RI_NULL);
    RiSolidBegin("difference");

    // RiTranslate(15,0,0);
    // RiSolidBegin("primitive");
    // RiSphere(10, -10, 10, 360, RI_NULL);
    // RiSolidEnd();

    double t=-PI;
    int steps = 8;
    double dt = (2*PI)/steps;
    RiSolidBegin("primitive");
    double rad=5.0;
    for (int ti=0; ti<steps; ++ti) {
        RiTransformBegin();
        RiTranslate(xv(t),yv(t),0);
        // RiSolidBegin("primitive");
        RiSphere(rad, -rad, rad, 360, RI_NULL);
        // RiSolidEnd();
        RiTransformEnd();
        t += dt;
    }

    for (int ti=0; ti<steps; ++ti) {
        RiTransformBegin();
        RiTranslate(0,xv(t),yv(t));
        // RiSolidBegin("primitive");
        RiSphere(rad, -rad, rad, 360, RI_NULL);
        // RiSolidEnd();
        RiTransformEnd();
        t += dt;
    }

    RiSolidEnd();

    RiSolidBegin("primitive");
    RiSphere(15, -15, 15, 360, RI_NULL);
    RiSolidEnd();

    // RiTranslate(-30.0,-30.0,0);
    // RiSolidBegin("primitive");
    // RiSphere(10, -10, 10, 360, RI_NULL);
    // RiSolidEnd();

    // RiTranslate(15.0,-15.0,0);
    // RiSolidBegin("primitive");
    // RiSphere(15, -15, 15, 360, RI_NULL);
    // RiSolidEnd();

    RiSolidEnd();
    RiWorldEnd();
    RiFrameEnd();
}
コード例 #12
0
ファイル: spline.cpp プロジェクト: luca-penasa/spc
void magnet::math::Spline::generate()
{
    if (size() < 2)
        throw std::runtime_error("Spline requires at least 2 points");

    // If any spline points are at the same x location, we have to
    // just slightly seperate them
    {
        bool testPassed(false);
        while (!testPassed) {
            testPassed = true;
            std::sort(base::begin(), base::end());

            for (auto iPtr = base::begin(); iPtr != base::end() - 1; ++iPtr)
                if (iPtr->first == (iPtr + 1)->first) {
                    if ((iPtr + 1)->first != 0)
                        (iPtr + 1)->first += (iPtr + 1)->first
                                             * std::numeric_limits
                                             <double>::epsilon() * 10;
                    else
                        (iPtr + 1)->first = std::numeric_limits
                                            <double>::epsilon() * 10;
                    testPassed = false;
                    break;
                }
        }
    }

    const size_t e = size() - 1;

    switch (_type) {
    case LINEAR: {
        _data.resize(e);
        for (size_t i(0); i < e; ++i) {
            _data[i].x = x(i);
            _data[i].a = 0;
            _data[i].b = 0;
            _data[i].c = (y(i + 1) - y(i)) / (x(i + 1) - x(i));
            _data[i].d = y(i);
        }
        break;
    }
    case CUBIC: {
        ublas::matrix<double> A(size(), size());
        for (size_t yv(0); yv <= e; ++yv)
            for (size_t xv(0); xv <= e; ++xv)
                A(xv, yv) = 0;

        for (size_t i(1); i < e; ++i) {
            A(i - 1, i) = h(i - 1);
            A(i, i) = 2 * (h(i - 1) + h(i));
            A(i + 1, i) = h(i);
        }

        ublas::vector<double> C(size());
        for (size_t xv(0); xv <= e; ++xv)
            C(xv) = 0;

        for (size_t i(1); i < e; ++i)
            C(i) = 6
                   * ((y(i + 1) - y(i)) / h(i) - (y(i) - y(i - 1)) / h(i - 1));

        // Boundary conditions
        switch (_BCLow) {
        case FIXED_1ST_DERIV_BC:
            C(0) = 6 * ((y(1) - y(0)) / h(0) - _BCLowVal);
            A(0, 0) = 2 * h(0);
            A(1, 0) = h(0);
            break;
        case FIXED_2ND_DERIV_BC:
            C(0) = _BCLowVal;
            A(0, 0) = 1;
            break;
        case PARABOLIC_RUNOUT_BC:
            C(0) = 0;
            A(0, 0) = 1;
            A(1, 0) = -1;
            break;
        }

        switch (_BCHigh) {
        case FIXED_1ST_DERIV_BC:
            C(e) = 6 * (_BCHighVal - (y(e) - y(e - 1)) / h(e - 1));
            A(e, e) = 2 * h(e - 1);
            A(e - 1, e) = h(e - 1);
            break;
        case FIXED_2ND_DERIV_BC:
            C(e) = _BCHighVal;
            A(e, e) = 1;
            break;
        case PARABOLIC_RUNOUT_BC:
            C(e) = 0;
            A(e, e) = 1;
            A(e - 1, e) = -1;
            break;
        }

        ublas::matrix<double> AInv(size(), size());
        InvertMatrix(A, AInv);

        _ddy = ublas::prod(C, AInv);

        _data.resize(size() - 1);
        for (size_t i(0); i < e; ++i) {
            _data[i].x = x(i);
            _data[i].a = (_ddy(i + 1) - _ddy(i)) / (6 * h(i));
            _data[i].b = _ddy(i) / 2;
            _data[i].c = (y(i + 1) - y(i)) / h(i) - _ddy(i + 1) * h(i) / 6
                         - _ddy(i) * h(i) / 3;
            _data[i].d = y(i);
        }
    }
    }
    _valid = true;
}
コード例 #13
0
	virtual double DoEval(const double * x) const { 
		std::vector<double> xv(x,x+2*nbound_);
		std::vector<double> pv(cutoffs_,cutoffs_+2);
		return this->operator()(&xv[0],&pv[0]); 
	}; 
コード例 #14
0
void FnirtFileWriter::common_field_construction(const string&            fname,
                                                const volume<float>&     ref,
                                                const volume<float>&     fieldx,
                                                const volume<float>&     fieldy,
                                                const volume<float>&     fieldz, 
                                                const Matrix&            aff)
{
  volume4D<float>   fields(ref.xsize(),ref.ysize(),ref.zsize(),3);
  fields.copyproperties(ref); 

  Matrix M;
  bool   add_affine = false;
  if (add_affine = ((aff-IdentityMatrix(4)).MaximumAbsoluteValue() > 1e-6)) { // Add affine part to fields
    M = (aff.i() - IdentityMatrix(4))*ref.sampling_mat();
  }

  if (samesize(ref,fieldx,true)) { // If ref is same size as the original field
    fields[0] = fieldx; fields[1] = fieldy; fields[2] = fieldz;
    fields.copyproperties(ref);    // Put qform/sform and stuff back.
    if (add_affine) {
      ColumnVector xv(4), xo(4);
      int zs = ref.zsize(), ys = ref.ysize(), xs = ref.xsize();
      xv(4) = 1.0;
      for (int z=0; z<zs; z++) {
        xv(3) = double(z);
        for (int y=0; y<ys; y++) {
          xv(2) = double(y);
          for (int x=0; x<xs; x++) {
            xv(1) = double(x);
            xo = M*xv;
            fields(x,y,z,0) += xo(1);
            fields(x,y,z,1) += xo(2);
            fields(x,y,z,2) += xo(3);
	  }
        }
      }
    } 
  }
  else {
    fieldx.setextrapolationmethod(extraslice);
    fieldy.setextrapolationmethod(extraslice);
    fieldz.setextrapolationmethod(extraslice);
    Matrix R2F = fieldx.sampling_mat().i() * ref.sampling_mat();
    ColumnVector xv(4), xo(4), xr(4);
    int zs = ref.zsize(), ys = ref.ysize(), xs = ref.xsize();
    xv(4) = 1.0;
    for (int z=0; z<zs; z++) {
      xv(3) = double(z);
      for (int y=0; y<ys; y++) {
        xv(2) = double(y);
        for (int x=0; x<xs; x++) {
          xv(1) = double(x);
          xr = R2F*xv;
          fields(x,y,z,0) = fieldx.interpolate(xr(1),xr(2),xr(3));
          fields(x,y,z,1) = fieldy.interpolate(xr(1),xr(2),xr(3));
          fields(x,y,z,2) = fieldz.interpolate(xr(1),xr(2),xr(3));
          if (add_affine) {
            xo = M*xv;
            fields(x,y,z,0) += xo(1);
            fields(x,y,z,1) += xo(2);
            fields(x,y,z,2) += xo(3);
	  }
        }
      }
    }
  }

  fields.set_intent(FSL_FNIRT_DISPLACEMENT_FIELD,fields.intent_param(0),fields.intent_param(1),fields.intent_param(2));
  fields.setDisplayMaximum(0.0);
  fields.setDisplayMinimum(0.0);

  // Save resulting field
  save_volume4D(fields,fname);
}
コード例 #15
0
void SMDImporter::CreateAnimationSource()
{
	XSI::ActionSource actionSource;

	float animStart = 9999;
	float animEnd = -9999;

	XSI::CString animatedObjects;

	for (int c=0;c<m_pNodes.GetUsed();c++)
	{
		SMDNode* node = m_pNodes[c];

		if ( node->m_pKeys.GetUsed() > 1 )
		{
			if ( !actionSource.IsValid() )
			{
				LPWSTR l_wszActionName;
				DSA2W(&l_wszActionName,m_szActionName);

				actionSource = m_pModel.AddActionSource( l_wszActionName );
			}

			XSI::Parameter x = node->m_x3d.GetParameters().GetItem( L"posx" );
			XSI::Parameter y = node->m_x3d.GetParameters().GetItem( L"posy" );
			XSI::Parameter z = node->m_x3d.GetParameters().GetItem( L"posz" );

			XSI::Parameter rx = node->m_x3d.GetParameters().GetItem( L"rotx" );
			XSI::Parameter ry = node->m_x3d.GetParameters().GetItem( L"roty" );
			XSI::Parameter rz = node->m_x3d.GetParameters().GetItem( L"rotz" );

			node->m_fOldX = x.GetValue();
			node->m_fOldY = y.GetValue();
			node->m_fOldZ = z.GetValue();
			node->m_fOldRX = rx.GetValue();
			node->m_fOldRY = ry.GetValue();
			node->m_fOldRZ = rz.GetValue();


			XSI::FCurve fcrvx;
			x.AddFCurve( XSI::siStandardFCurve, fcrvx	);
			XSI::FCurve fcrvy;
			y.AddFCurve( XSI::siStandardFCurve, fcrvy	);
			XSI::FCurve fcrvz;
			z.AddFCurve( XSI::siStandardFCurve, fcrvz	);
			XSI::FCurve fcrvrx;
			rx.AddFCurve( XSI::siStandardFCurve, fcrvrx	);
			XSI::FCurve fcrvry;
			ry.AddFCurve( XSI::siStandardFCurve, fcrvry	);
			XSI::FCurve fcrvrz;
			rz.AddFCurve( XSI::siStandardFCurve, fcrvrz	);
			
			XSI::CTimeArray time(node->m_pKeys.GetUsed());
			XSI::CValueArray xv(node->m_pKeys.GetUsed());
			XSI::CValueArray yv(node->m_pKeys.GetUsed());
			XSI::CValueArray zv(node->m_pKeys.GetUsed());
			
			XSI::CValueArray rxv(node->m_pKeys.GetUsed());
			XSI::CValueArray ryv(node->m_pKeys.GetUsed());
			XSI::CValueArray rzv(node->m_pKeys.GetUsed());
	
			if ( node->m_pParent ==NULL )
			{
				for (int k=0;k<node->m_pKeys.GetUsed();k++)
				{
				
					if ( node->GetKey(k)->m_fTime < animStart )
					{
						animStart = node->GetKey(k)->m_fTime;
					}

					if ( node->GetKey(k)->m_fTime > animEnd )
					{
						animEnd = node->GetKey(k)->m_fTime;
					}

					XSI::MATH::CTransformation xfo1;
					XSI::MATH::CTransformation xfo2;
					
					xfo1.SetRotationFromXYZAnglesValues ( node->GetKey(k)->m_vRotation.GetX(), node->GetKey(k)->m_vRotation.GetY(), node->GetKey(k)->m_vRotation.GetZ() );
					xfo1.SetTranslationFromValues ( node->GetKey(k)->m_vPosition.GetX(), node->GetKey(k)->m_vPosition.GetY(), node->GetKey(k)->m_vPosition.GetZ() );

					xfo2.SetRotationFromXYZAnglesValues ( -1.570796, 0.0, 0.0 );
					xfo1.MulInPlace(xfo2);

					double dx,dy,dz;
					double drx, dry, drz;

					xfo1.GetTranslationValues ( dx, dy, dz);
					xfo1.GetRotationFromXYZAnglesValues(drx, dry, drz);

					time[k] = k;
					xv[k] = dx;
					yv[k] = dy;
					zv[k] = dz;
					
					rxv[k] = drx * 57.29577951308232286465;
					ryv[k] = dry * 57.29577951308232286465;
					rzv[k] = drz * 57.29577951308232286465;

				}
				
			} else {
				
				for (int k=0;k<node->m_pKeys.GetUsed();k++)
				{
					
					if ( node->GetKey(k)->m_fTime < animStart )
					{
						animStart = node->GetKey(k)->m_fTime;
					}

					if ( node->GetKey(k)->m_fTime > animEnd )
					{
						animEnd = node->GetKey(k)->m_fTime;
					}

					time[k] = k;
					xv[k] = node->GetKey(k)->m_vPosition.GetX();
					yv[k] = node->GetKey(k)->m_vPosition.GetY();
					zv[k] = node->GetKey(k)->m_vPosition.GetZ();
					
					rxv[k] = node->GetKey(k)->m_vRotation.GetX() * 57.29577951308232286465;
					ryv[k] = node->GetKey(k)->m_vRotation.GetY() * 57.29577951308232286465;
					rzv[k] = node->GetKey(k)->m_vRotation.GetZ() * 57.29577951308232286465;
				}
			}

			fcrvx.SetKeys ( time, xv );
			fcrvy.SetKeys ( time, yv );
			fcrvz.SetKeys ( time, zv );

			fcrvrx.SetKeys ( time, rxv );
			fcrvry.SetKeys ( time, ryv );
			fcrvrz.SetKeys ( time, rzv );

			LPWSTR l_wszModelName;
			DSA2W(&l_wszModelName,FixName(node->m_szName));
			XSI::CString cname = l_wszModelName;

			actionSource.AddSourceItem ( cname + L".kine.local.posx", fcrvx, true ); 
			actionSource.AddSourceItem ( cname + L".kine.local.posy", fcrvy, true );
			actionSource.AddSourceItem ( cname + L".kine.local.posz", fcrvz, true );

			actionSource.AddSourceItem ( cname + L".kine.local.rotx", fcrvrx, true ); 
			actionSource.AddSourceItem ( cname + L".kine.local.roty", fcrvry, true );
			actionSource.AddSourceItem ( cname + L".kine.local.rotz", fcrvrz, true );
		
			// build up the string list of objects that we want to remove animation from
			if (animatedObjects.IsEmpty() == false) {
				animatedObjects += L", ";
			}
			animatedObjects += node->m_x3d.GetFullName();
		}
	}

	if ( actionSource.IsValid() )
	{
		actionSource.PutParameterValue(L"FrameStart", (double)animStart);
		actionSource.PutParameterValue(L"FrameEnd", (double)animEnd);
	}

	// remove animation on all objects that were imported
	// and animated
	if (animatedObjects.IsEmpty() == false) {
		XSI::Application app;
		XSI::CValue out;
		XSI::CValueArray args(4);

		args[0] = animatedObjects;
		args[1] = XSI::CValue();
		args[2] = (long)XSI::siBranch;
		args[3] = (long)(XSI::siFCurveSource);
		app.ExecuteCommand(L"RemoveAllAnimation", args, out);
	}
}
コード例 #16
0
ファイル: main.cpp プロジェクト: rainbow23/GameLib2008
	void Framework::update(){

		WindowCreator wc = WindowCreator::instance();
		if ( gFirst ){
			const char* filename = wc.commandLineString();
			if ( filename && filename[ 0 ] != '\0' ){
				load( filename );
			}
			gFirst = false;
		}else{
			//ドラッグアンドドロップを処理する
			int dropN = wc.droppedItemNumber();
			if ( dropN > 0 ){
				const char* filename = wc.droppedItem( 0 ); //0番以外無視
				load( filename );
				wc.clearDroppedItem(); //これを呼ぶとfilenameもこわれるので最後に。
			}
		}
		
		//カメラ入力反映
		Input::Manager im = Input::Manager::instance();
		Input::Mouse mouse = im.mouse();
		Input::Keyboard keyboard = im.keyboard();
		if ( mouse.isOn( Input::Mouse::BUTTON_MIDDLE ) ){
			Graphics::Manager().captureScreen( "capture.tga" );
		}
		//ビュー行列を作ろう
		Vector3 eyePosition = gEyeTarget;
		eyePosition.z += gEyeDistance;

		Matrix34 rm;
		rm.setRotationY( gAngleY );
		rm.rotateX( gAngleX );
		Vector3 tv( 0.f, 0.f, 1.f );
		rm.mul( &tv, tv );
		eyePosition.setMadd( gEyeTarget, tv, gEyeDistance );
		Matrix34 zrm;
		zrm.setRotationZ( gAngleZ );
		Vector3 up( 0.f, 1.f, 0.f );
		zrm.mul( &up, up );

		Matrix34 vm;
		vm.setViewTransform( eyePosition, gEyeTarget, up );
		if ( gContainer ){
			float x = static_cast< float >( mouse.velocityX() );
			float y = static_cast< float >( mouse.velocityY() );
			if ( mouse.isOn( Input::Mouse::BUTTON_LEFT ) && mouse.isOn( Input::Mouse::BUTTON_RIGHT ) ){ //両ボタンでZ回転
				gAngleZ -= 0.2f * x;
				gAngleZ -= 0.2f * y;
			}else if ( mouse.isOn( Input::Mouse::BUTTON_LEFT ) ){ //左ボタン回転
				gAngleX -= 0.2f * y;
				if ( gAngleX > 89.9f ){
					gAngleX = 89.9f;
				}else if ( gAngleX < -89.9f ){
					gAngleX = -89.9f;
				}
				gAngleY -= 0.5f * x;
			}else if ( mouse.isOn( Input::Mouse::BUTTON_RIGHT ) ){ //右ボタン、注視点移動
				Vector3 xv( vm.m00, vm.m01, vm.m02 );
				xv *= x;
				Vector3 yv( vm.m10, vm.m11, vm.m12 );
				yv *= y;
				gEyeTarget.madd( xv, -0.003f * gEyeDistance );
				gEyeTarget.madd( yv, 0.003f * gEyeDistance );
			}
			int w = mouse.wheel();
			if ( w < 0 ){
				gEyeDistance *= 0.9f;
			}else if ( w > 0 ){
				gEyeDistance *= 1.1f;
			}
		}
		//透視変換行列
		Matrix44 pm;
		pm.setPerspectiveTransform( 
			60.f, 
			static_cast< float >( width() ),
			static_cast< float >( height() ),
			gEyeDistance * 0.01f, gEyeDistance * 10.f );
		//次にPVを作る
		pm *= vm;
	
		if ( keyboard.isOn( 'G' ) ){
			gAngleX = gAngleY = gAngleZ = 0.f;
			gEyeTarget = 0.f;
		}

		//ライトでもうごかそか
		Graphics::Manager gm = Graphics::Manager::instance(); 
		gm.setProjectionViewMatrix( pm );
		gm.setLightingMode( LIGHTING_PER_PIXEL );
		gm.enableDepthTest( true );
		gm.enableDepthWrite( true );
		gm.setLightColor( 0, Vector3( 1.f, 1.f, 1.f ) ); //白
		gm.setLightColor( 1, Vector3( 1.f, 0.7f, 0.7f ) ); //赤
		gm.setLightColor( 2, Vector3( 0.7f, 1.f, 0.7f ) ); //緑
		gm.setLightColor( 3, Vector3( 0.7f, 0.7f, 1.f ) ); //青
		gm.setAmbientColor( Vector3( 0.2f, 0.2f, 0.2f ) );
		gm.setEyePosition( eyePosition );
		float t = gEyeDistance * 0.4f;
		float lightIntensity[ 4 ];
		for ( int i = 0; i < 4; ++i ){
			lightIntensity[ i ] = t;
		}
		Vector3 lightPositions[ 4 ];
		for ( int i = 0; i < 4; ++i ){
			float t = static_cast< float >( gCount * ( i + 1 ) ) / 5.f;
			float d = gEyeDistance * 2.f;
			lightPositions[ i ].set( sin( t )*cos( t ) * d,  sin( t )*sin( t ) * d, cos( t ) * d );
			lightPositions[ i ] += gEyeTarget;
		}
		for ( int i = 0; i < 4; ++i ){
			gm.setLightPosition( i, lightPositions[ i ] );
			gm.setLightIntensity( i, lightIntensity[ i ] );
		}
		for ( int i = 0; i < gModels.size(); ++i ){
			gModels[ i ].draw();
		}
		//アニメ切り替え
		if ( keyboard.isTriggered( ' ' ) ){
			if ( gContainer.animationNumber() > 0 ){
				++gAnimationIndex;
				if ( gAnimationIndex >= gContainer.animationNumber() ){
					gAnimationIndex = 0;
				}
				for ( int i = 0; i < gTrees.size(); ++i ){
					gTrees[ i ].setAnimation( gContainer.animation( gAnimationIndex ) );
				}
			}
		}
		for ( int i = 0; i < gTrees.size(); ++i ){
			gTrees[ i ].updateAnimation();
			gTrees[ i ].draw();
		}
		if ( isEndRequested() ){
			gModels.clear();
			gTrees.clear();
			gContainer.release();
		}


		++gCount;
	}
コード例 #17
0
ファイル: exec.cpp プロジェクト: Wushaowei001/gecode-clone
 void
 wait(Home home, const FloatVarArgs& x, void (*c)(Space& home)) {
   if (home.failed()) return;
   ViewArray<Float::FloatView> xv(home,x);
   GECODE_ES_FAIL(Kernel::NaryWait<Float::FloatView>::post(home,xv,c));
 }
コード例 #18
0
ファイル: builder.cpp プロジェクト: stevenmizuno/QGIS
void Builder::addArc( const DL_ArcData& data )
{
  if ( shapefileType != SHPT_ARC )
  {
    QgsDebugMsg( "ignoring arc" );
    return;
  }

  int fromAngle = ( int ) data.angle1 + 1;
  int toAngle = ( int ) data.angle2 + 1;

  QgsDebugMsg( QString( "arc (%1,%2,%3 r=%4 a1=%5 a2=%6)" )
               .arg( data.cx ).arg( data.cy ).arg( data.cz )
               .arg( data.radius )
               .arg( data.angle1 ).arg( data.angle2 ) );

  if ( ignoringBlock )
  {
    QgsDebugMsg( "skipping arc in block" );
    return;
  }

  int i = 0;
  long shpIndex = 0;

  // Approximate the arc

  double radianMeasure;

  std::vector <DL_PointData> arcPoints;
  DL_PointData myPoint;

  for ( i = fromAngle; ; i++, shpIndex++ )
  {
    if ( i > 360 )
      i = 0;

    if ( shpIndex > 1000 )
      break;

    radianMeasure = i * M_PI / 180.0;

    myPoint.x = data.radius * cos( radianMeasure ) + data.cx;
    myPoint.y = data.radius * sin( radianMeasure ) + data.cy;
    myPoint.z = data.cz;

    arcPoints.push_back( myPoint );

    if ( i == toAngle )
      break;
  }

  // Finalize

  int dim = arcPoints.size();
  QVector<double> xv( dim );
  QVector<double> yv( dim );
  QVector<double> zv( dim );

  for ( int i = 0; i < dim; i++ )
  {
    xv[i] = arcPoints[i].x;
    yv[i] = arcPoints[i].y;
    zv[i] = arcPoints[i].z;

  }

  shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, NULL, NULL, dim, xv.data(), yv.data(), zv.data(), NULL );
  arcPoints.clear();
}
コード例 #19
0
bool ON_BrepFace::ChangeSurface(
  int si
  )
{
  if ( 0 == m_brep )
    return false;
  if ( si < 0 || si >= m_brep->m_S.Count() )
    return false;
  const ON_Surface* pSurface = m_brep->m_S[si];
  
  m_brep->DestroyMesh( ON::any_mesh );

  const ON_Surface* old_srf = SurfaceOf();
  m_si = si;
  SetProxySurface(pSurface);
  if ( pSurface )
    m_bbox = pSurface->BoundingBox();
  else
    m_bbox.Destroy();
  m_brep->m_bbox.Destroy();

  if ( old_srf && pSurface )
  {
    // If domain changed, tehn update 2d trim curve locations
    ON_Interval udom0 = old_srf->Domain(0);
    ON_Interval vdom0 = old_srf->Domain(1);
    ON_Interval udom1 = pSurface->Domain(0);
    ON_Interval vdom1 = pSurface->Domain(1);
    if ( udom0 != udom1 || vdom0 != vdom1 )
    {
      // need to transform trimming curves
      ON_Xform x(1), xu(1), xv(1);
      if ( udom0 != udom1 )
        xu.IntervalChange(0,udom0,udom1);
      if ( vdom0 != vdom1 )
        xv.IntervalChange(1,vdom0,vdom1);
      x = xv*xu;
      TransformTrim(x);
    }

    int vcount0 = m_brep->m_V.Count();

    // If singular points changed, then add/remove edges
    // and update trim.m_type flags
    int i;
    {
      bool bSing0[4];
      bool bSing1[4];
      for ( i = 0; i < 4; i++ )
      {
        bSing0[i] = old_srf->IsSingular(i) ? true : false;
        bSing1[i] = pSurface->IsSingular(i) ? true : false;
      }
      int sing_fix, sing_fix_max = 1;
      for ( sing_fix = 0; sing_fix < sing_fix_max; sing_fix++ )
      {
        // sing_fix:
        //   0: expands old singularities and checks for new ones
        //   1: collapses old edges to new singular points.
        for ( i = 0; i < 4; i++ )
        {
          if ( bSing0[i] == bSing1[i] )
            continue;

          ON_Surface::ISO iso = ON_Surface::not_iso;
          switch(i)
          {
          case 0: iso = ON_Surface::S_iso; break;
          case 1: iso = ON_Surface::E_iso; break;
          case 2: iso = ON_Surface::N_iso; break;
          case 3: iso = ON_Surface::W_iso; break;
          }

          if ( bSing0[i] && sing_fix != 0 )
          {
            // we already expanded old singular trims into edge trims
            continue;
          }

          for ( int fli = 0; fli < m_li.Count(); fli++ )
          {
            const ON_BrepLoop* loop = Loop(fli);
            if ( 0 == loop )
              continue;
            if ( loop->m_type != ON_BrepLoop::outer )
              continue;
            for ( int lti = 0; lti < loop->m_ti.Count(); lti++ )
            {
              ON_BrepTrim* trim = loop->Trim(lti);
              if ( !trim )
                continue;
              if ( trim->m_iso != iso )
                continue;
              ON_BrepTrim* nexttrim = loop->Trim((lti+1)%loop->m_ti.Count());
              if ( bSing0[i] )
              {
                // valid singular trim changing to non-singular trim
                if( 0 == sing_fix )
                  ChangeTrimSingToBdry( *m_brep, *trim, nexttrim );
              }
              else if ( bSing1[i] )
              {
                if ( 0 == sing_fix )
                {
                  // we need a 2nd pass to collapse this edge
                  // to a singular trim.
                  sing_fix_max = 2;
                }
                else
                {
                  // valid non-singular trim changing to singular trim
                  ON_BrepTrim* prevtrim = loop->Trim((lti-1+loop->m_ti.Count())%loop->m_ti.Count());
                  ChangeTrimBdryToSing( *m_brep, *trim, prevtrim, nexttrim );
                }
              }
            }
          }
        }
      }
    }

    // If closed/open status changed, then add/remove edges
    // and update m_type flag
    for ( i = 0; i < 2; i++ )
    {
      bool bClosed0 = old_srf->IsClosed(i) ? true : false;
      bool bClosed1 = pSurface->IsClosed(i) ? true : false;
      if ( bClosed0 == bClosed1 )
        continue;
      ON_Surface::ISO isoA = ON_Surface::not_iso;
      ON_Surface::ISO isoB = ON_Surface::not_iso;
      switch(i)
      {
      case 0: isoA = ON_Surface::W_iso; isoB = ON_Surface::E_iso; break;
      case 1: isoA = ON_Surface::S_iso; isoB = ON_Surface::N_iso; break;
      }

      for ( int fli = 0; fli < m_li.Count(); fli++ )
      {
        const ON_BrepLoop* loop = Loop(fli);
        if ( 0 == loop )
          continue;
        if ( loop->m_type != ON_BrepLoop::outer )
          continue;
        int loop_trim_count = loop->m_ti.Count();
        for ( int ltiA = 0; ltiA < loop_trim_count; ltiA++ )
        {
          ON_BrepTrim* trimA = loop->Trim(ltiA);
          if ( !trimA )
            continue;
          if ( trimA->m_iso != isoA )
            continue;

          if ( bClosed0 )
          {
            // old surface has a seam and new surface does not
            if ( trimA->m_type != ON_BrepTrim::seam )
              continue;
            const ON_BrepEdge* edge = m_brep->Edge(trimA->m_ei);
            if ( 0 == edge )
              continue;
            if ( edge->m_ti.Count() != 2 )
              continue;
            int etiB = (edge->m_ti[0] == trimA->m_trim_index) ? 1 : 0;
            ON_BrepTrim* trimB = edge->Trim(etiB);
            if ( 0 == trimB )
              continue;
            if ( trimA == trimB )
              continue;
            if ( trimB->m_li != trimA->m_li )
              continue;
            if ( trimB->m_type != ON_BrepTrim::seam )
              continue;
            if ( trimB->m_iso != isoB )
              continue;
            for ( int ltiB = 0; ltiB < loop_trim_count; ltiB++ )
            {
              if ( trimB != loop->Trim(ltiB) )
                continue;
              ON_BrepTrim* prevtrimB = loop->Trim((ltiB+loop_trim_count-1)%loop_trim_count);
              ON_BrepTrim* nexttrimB = loop->Trim((ltiB+1)%loop_trim_count);
              if ( 0 == prevtrimB )
                continue;
              if ( 0 == nexttrimB )
                continue;
              if ( prevtrimB == trimA || prevtrimB == trimB )
                continue;
              if ( nexttrimB == trimA || nexttrimB == trimB )
                continue;
              if ( prevtrimB == nexttrimB )
                continue;
              SplitSeam( *m_brep, *trimA, *trimB, *prevtrimB, *nexttrimB, vcount0 );
              break;
            }
          }
          else
          {
            // open sides replaced with a seam
            // TODO
            bool sok;
            sok = SealSeam(i, *this);
            if (sok)
              sok = !sok;
          }
        }
      }
    }
  }

  if ( pSurface )
  {
    for ( int fli = 0; fli < m_li.Count(); fli++ )
    {
      const ON_BrepLoop* loop = Loop(fli);
      if ( 0 == loop )
        continue;
      for ( int lti = 0; lti < loop->m_ti.Count(); lti++ )
      {
        const ON_BrepTrim* trim = loop->Trim(lti);
        if ( 0 ==  trim )
          continue;
        ON_BrepVertex* v0 = m_brep->Vertex(trim->m_vi[0]);
        if ( 0 != v0 )
        {
          if ( v0->point == ON_UNSET_POINT )
          {
            ON_3dPoint uv = trim->PointAtStart();
            v0->point = pSurface->PointAt( uv.x, uv.y );
          }
        }
      }
    }
  }

  return true;
}
コード例 #20
0
ファイル: df1b2ghmult.cpp プロジェクト: cran/marked
/**
 * Description not yet available.
 * \param
 */
double do_gauss_hermite_block_diagonal_multi(const dvector& x,
  const dvector& u0,const dmatrix& Hess,const dvector& _xadjoint,
  const dvector& _uadjoint,const dmatrix& _Hessadjoint,
  function_minimizer * pmin)
{
  ADUNCONST(dvector,xadjoint)
  ADUNCONST(dvector,uadjoint)
  //ADUNCONST(dmatrix,Hessadjoint)

  dvector & w= *(pmin->multinomial_weights);

  const int xs=x.size();
  const int us=u0.size();
  gradient_structure::set_NO_DERIVATIVES();
  int nsc=pmin->lapprox->num_separable_calls;
  const ivector lrea = (*pmin->lapprox->num_local_re_array)(1,nsc);
  int hroom =  sum(square(lrea));
  int nvar=x.size()+u0.size()+hroom;
  independent_variables y(1,nvar);
  
  // need to set random effects active together with whatever
  // init parameters should be active in this phase
  initial_params::set_inactive_only_random_effects(); 
  initial_params::set_active_random_effects(); 
  /*int onvar=*/initial_params::nvarcalc(); 
  initial_params::xinit(y);    // get the initial values into the
  // do we need this next line?
  y(1,xs)=x;

  int i,j;

  // contribution for quadratic prior
  if (quadratic_prior::get_num_quadratic_prior()>0)
  {
    //Hess+=quadratic_prior::get_cHessian_contribution();
    int & vxs = (int&)(xs);
    quadratic_prior::get_cHessian_contribution(Hess,vxs);
  }
 // Here need hooks for sparse matrix structures
  
  dvar3_array & block_diagonal_vhessian=
    *pmin->lapprox->block_diagonal_vhessian;
  block_diagonal_vhessian.initialize();
  dvar3_array& block_diagonal_ch=
    *pmin->lapprox->block_diagonal_vch;
    //dvar3_array(*pmin->lapprox->block_diagonal_ch);
  int ii=xs+us+1;
  d3_array& bdH=(*pmin->lapprox->block_diagonal_hessian);
  int ic;
  for (ic=1;ic<=nsc;ic++)
  {
    int lus=lrea(ic);
    for (i=1;i<=lus;i++)
      for (j=1;j<=lus;j++)
        y(ii++)=bdH(ic)(i,j);
  }

  dvector g(1,nvar);
  gradcalc(0,g);
  gradient_structure::set_YES_DERIVATIVES();
  dvar_vector vy=dvar_vector(y); 
  //initial_params::stddev_vscale(d,vy);
  ii=xs+us+1;
  if (initial_df1b2params::have_bounded_random_effects)
  {
    cerr << "can't do importance sampling with bounded random effects"
     " at present" << endl;
    ad_exit(1);
  }
  else
  {
    for (int ic=1;ic<=nsc;ic++)
    {
      int lus=lrea(ic);
      if (lus>0)
      {
        for (i=1;i<=lus;i++)
        {
          for (j=1;j<=lus;j++)
          {
            block_diagonal_vhessian(ic,i,j)=vy(ii++);
          }
        }
        block_diagonal_ch(ic)=
          choleski_decomp(inv(block_diagonal_vhessian(ic)));
      }
    }
  }

   int nsamp=pmin->lapprox->use_gauss_hermite;
   pmin->lapprox->in_gauss_hermite_phase=1;
   dvar_vector sample_value(1,nsamp);
   sample_value.initialize();

   dvar_vector tau(1,us);;
   // !!! This only works for one random efect in each separable call
   // at present.

   if (pmin->lapprox->gh->mi)
   {
     delete pmin->lapprox->gh->mi;
     pmin->lapprox->gh->mi=0;
   }
   
   pmin->lapprox->gh->mi=new multi_index(1,nsamp,
    pmin->lapprox->multi_random_effects);

   multi_index & mi = *(pmin->lapprox->gh->mi);

   //for (int is=1;is<=nsamp;is++)
   dvector& xx=pmin->lapprox->gh->x;
   do
   {
     int offset=0;
     pmin->lapprox->num_separable_calls=0;
     //pmin->lapprox->gh->is=is;
     for (ic=1;ic<=nsc;ic++)
     {
       int lus=lrea(ic);
       // will need vector stuff here when more than one random effect
       if (lus>0)
       {
         //tau(offset+1,offset+lus).shift(1)=block_diagonal_ch(ic)(1,1)*
         //  pmin->lapprox->gh->x(is);
         dvector xv(1,lus);
         for (int iu=1;iu<=lus;iu++)
         {
           xv(iu)= xx(mi()(iu));
         }
         tau(offset+1,offset+lus).shift(1)=block_diagonal_ch(ic)*xv;
           
         offset+=lus;
       }
     }
    
     // have to reorder the terms to match the block diagonal hessian
     imatrix & ls=*(pmin->lapprox->block_diagonal_re_list);
     int mmin=ls.indexmin();
     int mmax=ls.indexmax();
    
     int ii=1;
     int i;
     for (i=mmin;i<=mmax;i++)
     {
       int cmin=ls(i).indexmin();
       int cmax=ls(i).indexmax();
       for (int j=cmin;j<=cmax;j++)
       {
         vy(ls(i,j))+=tau(ii++);
       }
     }
     if (ii-1 != us)
     {
       cerr << "error in interface" << endl;
       ad_exit(1);
     }
     initial_params::reset(vy);    // get the values into the model
     ii=1;
     for (i=mmin;i<=mmax;i++)
     {
       int cmin=ls(i).indexmin();
       int cmax=ls(i).indexmax();
       for (int j=cmin;j<=cmax;j++)
       {
         vy(ls(i,j))-=tau(ii++);
       }
     }

     *objective_function_value::pobjfun=0.0;
     pmin->AD_uf_outer();
     ++mi;

   }
   while(mi.get_depth()<=pmin->lapprox->multi_random_effects);

   nsc=pmin->lapprox->num_separable_calls;

   dvariable vf=pmin->do_gauss_hermite_integration();

   int sgn=0;
   dvariable ld=0.0;
   if (ad_comm::no_ln_det_choleski_flag)
   {
     for (int ic=1;ic<=nsc;ic++)
     {
       if (allocated(block_diagonal_vhessian(ic)))
       {
         ld+=w(2*ic)*ln_det(block_diagonal_vhessian(ic),sgn);
       }
     }
     ld*=0.5;
   }
   else
   {
     for (int ic=1;ic<=nsc;ic++)
     {
       if (allocated(block_diagonal_vhessian(ic)))
       {
         ld+=w(2*ic)*ln_det_choleski(block_diagonal_vhessian(ic));
       }
     }
     ld*=0.5;
   }

   vf+=ld;
   //vf+=us*0.91893853320467241; 

   double f=value(vf);
   gradcalc(nvar,g);

   // put uhat back into the model
   gradient_structure::set_NO_DERIVATIVES();
   vy(xs+1,xs+us).shift(1)=u0;
   initial_params::reset(vy);    // get the values into the model
   gradient_structure::set_YES_DERIVATIVES();
  
   pmin->lapprox->in_gauss_hermite_phase=0;
  
  ii=1;
  for (i=1;i<=xs;i++)
    xadjoint(i)=g(ii++);
  for (i=1;i<=us;i++)
    uadjoint(i)=g(ii++);
  for (ic=1;ic<=nsc;ic++)
  {
    int lus=lrea(ic);
    for (i=1;i<=lus;i++)
    {
      for (j=1;j<=lus;j++)
      {
        (*pmin->lapprox->block_diagonal_vhessianadjoint)(ic)(i,j)=g(ii++);
      }
    }
  }
  return f;
}
コード例 #21
0
ファイル: blv.cpp プロジェクト: ansonn/esl_systemc
void compare(int W)
{ // functionality verification
  sc_bv_base x(W);
  T st;
  // initialize
  for(int i=0; i<W; i++)
  {
    bool la = (rng.rand()&1) == 0;
    x[i] = la;
    st[i] = la;
  }
  if(st.to_string()!=x.to_string())
    cout<<"\nERROR: x= "<<x<<" st= "<<st<<"\n"<<
    "st="<<st<<"\nx="<<x<< endl;
  if( (int) st.xor_reduce()!= x.xor_reduce())
    cout<<"\nERROR: st.xor_reduce="<<(short)st.xor_reduce()<<"; x.xor_reduce="<<
    (short)x.xor_reduce()<<"\n"<<
    "st="<<st<<"\nx="<<x<< endl;
  if( (int) x.or_reduce()!=st.or_reduce())
     cout<<"\nERROR: st.or_reduce="<<(short)st.or_reduce()<<
     "; x.or_reduce="<<(short)x.or_reduce()<<"\n"<<
    "st="<<st<<"\nx="<<x<< endl;
  if( (int) x.and_reduce()!=st.and_reduce())
    cout<<"\nERROR: st.and_reduce="<<(short)st.and_reduce()<<
    "; x.and_reduce="<<(short)x.and_reduce()<<"\n"<<
    "st="<<st<<"\nx="<<x<< endl;

  if((st,st).to_string()!=(x,x).to_string())
    cout<<"\nERROR: st,st="<<(st,st)<<
    "; x,x="<<(x,x)<<"\n"<<
    "st="<<st<<"\nx="<<x<< endl;
  int first = (int) ( (double) W * ((double)rng.rand() / (double)0x7fffffff));
  int second = (int) ( (double) W * ((double)rng.rand() / (double)0x7fffffff));
  if(st.range(first,second).to_string()!=x.range(first,second).to_string())
    cout<<"st.range("<<first<<","<<second<<")="<<st.range(first,second)<<
    "; x.range("<<first<<","<<second<<")="<<x.range(first,second)<<"\n"<<
    "st="<<st<<"\nx="<<x<< endl;

  sc_bv_base bv(2*W);
  sc_bv_base xv(2*W);
  bv = (st,st);
  xv = (x,x);
  if(bv.to_string()!=xv.to_string())
    cout<<"\nERROR: bv(st,st)="<<bv<<"; xv(x,x)="<<xv<<"\n"<<
    "st="<<st<<"\nx="<<x<< endl;
  int Len=0;
  if(first>second)
    Len = first-second;
  else
    Len = second-first;
  sc_bv_base br(Len+1);
  sc_bv_base xr(Len+1);
  br = st.range(first,second);
  xr = x.range(first,second);
  if(br.to_string()!=xr.to_string())
  {
    cout<<"\nERROR: br("<<first<<","<<second<<")!= xr("<<first<<","<<second
        <<")" << endl;
    br = st.range(first,second);
    xr = x.range(first,second);
    cout<<"br="<<br.to_string()<<"  xr="<<xr.to_string()<<
    "st.range="<<st.range(first,second)<<"  x.range="<<x.range(first,second)<<
    "st="<<st<<"\nx="<<x<< endl;
  }

  // verify assignments
  long ra = rng.rand();
  x  = ra;
  st = ra;
  if(st.to_string()!=x.to_string())
    cout<<"\nERROR (assignment): x= "<<x<<" st= "<<st<<" original long="<<ra
        << endl;
}