Beispiel #1
0
xyz_t set_xyz(const double v)
{
	return xyz(v, v, v);
}
Beispiel #2
0
/** Updates skidding status.
 *  \param dt Time step size.
 *  \param is_on_ground True if the kart is on ground.
 *  \param steering Raw steering of the kart [-1,1], i.e. not adjusted by
 *               the kart's max steering angle.
 *  \param skidding  True if the skid button is pressed.
 */
void Skidding::update(float dt, bool is_on_ground,
                      float steering, KartControl::SkidControl skidding)
{
    // If a kart animation is shown, stop all skidding bonuses.
    if(m_kart->getKartAnimation())
    {
        reset();
        return;
    }
#ifdef SKIDDING_PARTICLE_DEBUG
    // This code will cause skidmarks to be displayed all the time, even
    // when the kart is not moving.
    m_kart->getKartGFX()->setCreationRateRelative(KartGFX::KGFX_SKIDL, 0.5f);
    m_kart->getKartGFX()->setCreationRateRelative(KartGFX::KGFX_SKIDR, 0.5f);
#endif

    // No skidding backwards or while stopped
    if(m_kart->getSpeed() < m_min_skid_speed &&
       m_skid_state != SKID_NONE && m_skid_state != SKID_BREAK)
    {
        m_skid_state = SKID_BREAK;
        m_kart->getKartGFX()->setCreationRateAbsolute(KartGFX::KGFX_SKIDL, 0);
        m_kart->getKartGFX()->setCreationRateAbsolute(KartGFX::KGFX_SKIDR, 0);
    }

    m_skid_bonus_ready = false;
    if (is_on_ground)
    {
        if((fabs(steering) > 0.001f) &&
            m_kart->getSpeed()>m_min_skid_speed &&
            (skidding==KartControl::SC_LEFT||skidding==KartControl::SC_RIGHT))
        {
            m_skid_factor +=  m_skid_increase *dt/m_time_till_max_skid;
        }
        else if(m_skid_factor>1.0f)
        {
            m_skid_factor *= m_skid_decrease;
        }
    }
    else
    {
        m_skid_factor = 1.0f; // Lose any skid factor as soon as we fly
    }

    if(m_skid_factor>m_skid_max)
        m_skid_factor = m_skid_max;
    else
        if(m_skid_factor<1.0f) m_skid_factor = 1.0f;

    // If skidding was started and a graphical jump should still
    // be displayed, update the data
    if(m_remaining_jump_time>0)
    {
        m_jump_speed -= World::getWorld()->getTrack()->getGravity()*dt;
        m_gfx_jump_offset += m_jump_speed * dt;
        m_remaining_jump_time -= dt;
        if(m_remaining_jump_time<0)
        {
            m_remaining_jump_time = 0.0f;
            m_gfx_jump_offset     = 0.0f;
        }
    }

    // This is only reached if the new skidding is enabled
    // ---------------------------------------------------

    // There are four distinct states related to skidding, controlled
    // by m_skid_state:
    // SKID_NONE: no skidding is happening. From here SKID_ACCUMULATE
    //    is reached when the skid key is pressed.
    // SKID_ACCUMULATE_{LEFT,RIGHT}:
    //    The kart is still skidding. The skidding time will be
    //    accumulated in m_skid_time, and once the minimum time for a
    //    bonus is reached, the "bonus gfx now available" gfx is shown.
    //    If the skid button is not pressed anymore, this will trigger
    //    a potential bonus. Also the rotation of the physical body to
    //    be in synch with the graphical kart is started (which is
    //    independently handled in the kart physics).
    // SKID_SHOW_GFX_{LEFT<RIGHT}
    //    Shows the skidding gfx while the bonus is available.
    // FIXME: what should we do if skid key is pressed while still in
    //   SKID_SHOW_GFX??? Adjusting the body rotation is difficult.
    //   For now skidding will only start again once SKID_SHOW_GFX
    //   is changed to SKID_NONE.
    switch(m_skid_state)
    {
    case SKID_NONE:
        {
            if(skidding!=KartControl::SC_LEFT &&
                skidding!=KartControl::SC_RIGHT)
                break;
            // Don't allow skidding while the kart is (apparently)
            // still in the air, or when the kart is too slow
            if(m_remaining_jump_time>0 ||
                m_kart->getSpeed() <m_min_skid_speed) break;

            m_skid_state = skidding==KartControl::SC_RIGHT
                         ? SKID_ACCUMULATE_RIGHT
                         : SKID_ACCUMULATE_LEFT;
            // Add a little jump to the kart. Determine the vertical speed
            // necessary for the kart to go 0.5*jump_time up (then it needs
            // the same time to come down again), based on v = gravity * t.
            // Then use this speed to determine the impulse necessary to
            // reach this speed.
            float v = World::getWorld()->getTrack()->getGravity()
                    * 0.5f*m_physical_jump_time;
            btVector3 imp(0, v / m_kart->getBody()->getInvMass(),0);
            m_kart->getVehicle()->getRigidBody()->applyCentralImpulse(imp);

            // Some karts might use a graphical-only jump. Set it up:
            m_jump_speed = World::getWorld()->getTrack()->getGravity()
                         * 0.5f*m_graphical_jump_time;
            m_remaining_jump_time = m_graphical_jump_time;

#ifdef SKID_DEBUG
#define SPEED 20.0f
            updateSteering(steering, dt);
            m_actual_curve->clear();
            m_actual_curve->setVisible(true);
            m_predicted_curve->clear();
            m_predicted_curve->setVisible(true);
            m_predicted_curve->setPosition(m_kart->getXYZ());
            m_predicted_curve->setHeading(m_kart->getHeading());
            float angle = m_kart->getKartProperties()
                                ->getMaxSteerAngle(m_kart->getSpeed())
                        * fabsf(getSteeringFraction());
            angle = m_kart->getKartProperties()
                                ->getMaxSteerAngle(SPEED)
                        * fabsf(getSteeringFraction());
            float r = m_kart->getKartProperties()->getWheelBase()
                   / asin(angle)*1.0f;

            const int num_steps = 50;

            float dx = 2*r / num_steps;

            for(float x = 0; x <=2*r; x+=dx)
            {
                float real_x = m_skid_state==SKID_ACCUMULATE_LEFT ? -x : x;
                Vec3 xyz(real_x, 0.2f, sqrt(r*r-(r-x)*(r-x))*(1.0f+SPEED/150.0f)
                          *(1+(angle/m_kart->getKartProperties()->getMaxSteerAngle(SPEED)-0.6f)*0.1f));
                Vec3 xyz1=m_kart->getTrans()(xyz);
                Log::debug("Skidding", "predict %f %f %f speed %f angle %f",
                    xyz1.getX(), xyz1.getY(), xyz1.getZ(),
                    m_kart->getSpeed(), angle);
                m_predicted_curve->addPoint(xyz);
            }

#endif
            m_skid_time  = 0;   // fallthrough
        }
    case SKID_BREAK:
        {
            break;
        }
    case SKID_ACCUMULATE_LEFT:
    case SKID_ACCUMULATE_RIGHT:
        {
#ifdef SKID_DEBUG
            Vec3 v=m_kart->getVelocity();
            if(v.length()>5)
            {
                float r = SPEED/sqrt(v.getX()*v.getX() + v.getZ()*v.getZ());
                v.setX(v.getX()*r);
                v.setZ(v.getZ()*r);
                m_kart->getBody()->setLinearVelocity(v);

            }

            m_actual_curve->addPoint(m_kart->getXYZ());
            Log::debug("Skidding", "actual %f %f %f turn %f speed %f angle %f",
                m_kart->getXYZ().getX(),m_kart->getXYZ().getY(),m_kart->getXYZ().getZ(),
                m_real_steering, m_kart->getSpeed(),
                m_kart->getKartProperties()->getMaxSteerAngle(m_kart->getSpeed()));
#endif
            m_skid_time += dt;
            float bonus_time, bonus_speed, bonus_force;
            unsigned int level = getSkidBonus(&bonus_time, &bonus_speed,
                                              &bonus_force);
            // If at least level 1 bonus is reached, show appropriate gfx
            if(level>0)
            {
                m_skid_bonus_ready = true;
                m_kart->getKartGFX()->setSkidLevel(level);
                m_kart->getKartGFX()->updateSkidLight(level);
            }
            // If player stops skidding, trigger bonus, and change state to
            // SKID_SHOW_GFX_*
            if(skidding == KartControl::SC_NONE)
            {
                m_skid_state = m_skid_state == SKID_ACCUMULATE_LEFT
                             ? SKID_SHOW_GFX_LEFT
                             : SKID_SHOW_GFX_RIGHT;
                float t = std::min(m_skid_time, m_skid_visual_time);
                t       = std::min(t,           m_skid_revert_visual_time);

                float vso = getVisualSkidRotation();
                btVector3 rot(0, vso*m_post_skid_rotate_factor, 0);
                m_kart->getVehicle()->setTimedRotation(t, rot);
                // skid_time is used to count backwards for the GFX
                m_skid_time = t;
                if(bonus_time>0)
                {
                    m_kart->getKartGFX()
                          ->setCreationRateRelative(KartGFX::KGFX_SKIDL, 1.0f);
                    m_kart->getKartGFX()
                          ->setCreationRateRelative(KartGFX::KGFX_SKIDR, 1.0f);
                    m_kart->m_max_speed->
                        instantSpeedIncrease(MaxSpeed::MS_INCREASE_SKIDDING,
                                             bonus_speed, bonus_speed,
                                             bonus_force, bonus_time,
                                             /*fade-out-time*/ 1.0f);
                    
                    StateManager::ActivePlayer *c = m_kart->getController()->getPlayer();
                    if (c && c->getConstProfile() == PlayerManager::getCurrentPlayer())
                    {
                        PlayerManager::increaseAchievement(AchievementInfo::ACHIEVE_SKIDDING, "skidding");
                    }
                }
                else {
                    m_kart->getKartGFX()
                          ->setCreationRateAbsolute(KartGFX::KGFX_SKIDL, 0);
                    m_kart->getKartGFX()
                          ->setCreationRateAbsolute(KartGFX::KGFX_SKIDR, 0);
            }
            }
            break;
        }   // case
    case SKID_SHOW_GFX_LEFT:
    case SKID_SHOW_GFX_RIGHT:
        m_skid_time -= dt;
        if(m_skid_time<=0)
        {
            m_skid_time = 0;
            m_kart->getKartGFX()
                  ->setCreationRateAbsolute(KartGFX::KGFX_SKIDL, 0);
            m_kart->getKartGFX()
                  ->setCreationRateAbsolute(KartGFX::KGFX_SKIDR, 0);
            m_kart->getKartGFX()->updateSkidLight(0);
            m_skid_state = SKID_NONE;
        }
    }   // switch
    updateSteering(steering, dt);
}   // update
Beispiel #3
0
int main() {
    std::cout << is_complete<int>(0) << '\n';
    std::cout << xyz() << '\n';
    std::cout << is_complete<S>(0);
}
Beispiel #4
0
void MblkGeometry::buildWedgeGridOnPatch(
   const hier::Patch& patch,
   const int xyz_id,
   const int level_number,
   const int block_number)
{

   std::shared_ptr<pdat::NodeData<double> > xyz(
      SAMRAI_SHARED_PTR_CAST<pdat::NodeData<double>, hier::PatchData>(
         patch.getPatchData(xyz_id)));

   TBOX_ASSERT(xyz);

   const hier::Index ifirst = patch.getBox().lower();
   const hier::Index ilast = patch.getBox().upper();
   hier::IntVector nghost_cells = xyz->getGhostCellWidth();

   int nd_imin = ifirst(0) - nghost_cells(0);
   int nd_imax = ilast(0) + 1 + nghost_cells(0);
   int nd_jmin = ifirst(1) - nghost_cells(1);
   int nd_jmax = ilast(1) + 1 + nghost_cells(1);
   int nd_nx = nd_imax - nd_imin + 1;
   int nd_ny = nd_jmax - nd_jmin + 1;
   //int nd_nz   = nd_kmax - nd_kmin + 1;
   int nd_nxny = nd_nx * nd_ny;
   //int nd_nel  = nd_nx*nd_ny*nd_nz;

   double dx[SAMRAI::MAX_DIM_VAL];
   dx[0] = d_dx[level_number][block_number][0];
   dx[1] = d_dx[level_number][block_number][1];

   double* x = xyz->getPointer(0);
   double* y = xyz->getPointer(1);

   int nd_kmin;
   int nd_kmax;
   dx[2] = d_dx[level_number][block_number][2];
   double* z = 0;
   if (d_dim == tbox::Dimension(3)) {
      nd_kmin = ifirst(2) - nghost_cells(2);
      nd_kmax = ilast(2) + 1 + nghost_cells(2);
      dx[2] = d_dx[level_number][block_number][2];
      z = xyz->getPointer(2);
   } else {
      nd_kmin = 0;
      nd_kmax = 0;
   }

   //
   // ----------- set the wedge nodal positions
   //

   for (int k = nd_kmin; k <= nd_kmax; ++k) {
      for (int j = nd_jmin; j <= nd_jmax; ++j) {
         for (int i = nd_imin; i <= nd_imax; ++i) {

            int ind = POLY3(i, j, k, nd_imin, nd_jmin, nd_kmin, nd_nx, nd_nxny);

            double r = d_wedge_rmin[block_number] + dx[0] * (i);
            double th = d_wedge_thmin + dx[1] * (j);

            double xx = r * cos(th);
            double yy = r * sin(th);

            x[ind] = xx;
            y[ind] = yy;

            if (d_dim == tbox::Dimension(3)) {
               double zz = d_wedge_zmin + dx[2] * (k);
               z[ind] = zz;
            }
         }
      }
   }
}
Beispiel #5
0
Coord readPole(std::istream &is)
{
	double lon, lat;
	is >> lon >> lat;
	return (lon<=380 && lat<=380) ? xyz(lon, lat) : ORIGIN;
}
void GridStates::load_particle_state(unsigned int i,
                                     Particle *p) const {
  algebra::Transformation3D T(get_orientation(i), get_position(i));
  core::XYZ xyz(p);
  core::transform(xyz, T);
}
/** Reads all data from a replay file for a specific kart.
 *  \param fd The file descriptor from which to read.
 */
void ReplayPlay::readKartData(FILE *fd, char *next_line)
{
    char s[1024];
    const unsigned int kart_num = m_ghost_karts.size();
    m_ghost_karts.push_back(new GhostKart(m_replay_file_list
        [m_current_replay_file].m_kart_list.at(kart_num),
        kart_num, kart_num + 1));
    m_ghost_karts[kart_num].init(RaceManager::KT_GHOST);
    Controller* controller = new GhostController(getGhostKart(kart_num));
    getGhostKart(kart_num)->setController(controller);

    unsigned int size;
    if(sscanf(next_line,"size: %u",&size)!=1)
        Log::fatal("Replay", "Number of records not found in replay file "
            "for kart %d.", kart_num);

    for(unsigned int i=0; i<size; i++)
    {
        fgets(s, 1023, fd);
        float x, y, z, rx, ry, rz, rw, time, speed, steer, w1, w2, w3, w4;
        int nitro, zipper, skidding, red_skidding, jumping;

        // Check for EV_TRANSFORM event:
        // -----------------------------
        if(sscanf(s, "%f  %f %f %f  %f %f %f %f  %f  %f  %f %f %f %f  %d %d %d %d %d\n",
            &time,
            &x, &y, &z,
            &rx, &ry, &rz, &rw,
            &speed, &steer, &w1, &w2, &w3, &w4,
            &nitro, &zipper, &skidding, &red_skidding, &jumping
            )==19)
        {
            btQuaternion q(rx, ry, rz, rw);
            btVector3 xyz(x, y, z);
            PhysicInfo pi = {0};
            KartReplayEvent kre = {0};
            pi.m_speed = speed;
            pi.m_steer = steer;
            pi.m_suspension_length[0] = w1;
            pi.m_suspension_length[1] = w2;
            pi.m_suspension_length[2] = w3;
            pi.m_suspension_length[3] = w4;
            kre.m_nitro_usage = nitro;
            kre.m_zipper_usage = (bool)zipper;
            kre.m_skidding_state = skidding;
            kre.m_red_skidding = (bool)red_skidding;
            kre.m_jumping = jumping != 0;
            m_ghost_karts[kart_num].addReplayEvent(time,
                btTransform(q, xyz), pi, kre);
        }
        else
        {
            // Invalid record found
            // ---------------------
            Log::warn("Replay", "Can't read replay data line %d:", i);
            Log::warn("Replay", "%s", s);
            Log::warn("Replay", "Ignored.");
        }
    }   // for i

}   // readKartData
Beispiel #8
0
inline Matrix<T, 4, 1> get_nearest_direction(const AABB<T, 3>& aabb, const Matrix<T, 4, 1>& vec)
{
    return Matrix<T, 4, 1>(get_nearest_direction( xyz(vec) ), 0);
}
Beispiel #9
0
    void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop)
    {
        if (object == &Obj && Prop.getTypeId() == Part::PropertyGeometryList::getClassTypeId()) {
            const Part::PropertyGeometryList& geom = static_cast<const Part::PropertyGeometryList&>(Prop);
            const std::vector<Part::Geometry*>& items = geom.getValues();
            if (items.size() != 2)
                return;
            Part::Geometry* g1 = items[0];
            Part::Geometry* g2 = items[1];
            if (!g1 || g1->getTypeId() != Part::GeomArcOfCircle::getClassTypeId())
                return;
            if (!g2 || g2->getTypeId() != Part::GeomLineSegment::getClassTypeId())
                return;
            Part::GeomArcOfCircle* arc = static_cast<Part::GeomArcOfCircle*>(g1);
            Part::GeomLineSegment* seg = static_cast<Part::GeomLineSegment*>(g2);

            try {
                Base::Vector3d m1 = arc->getCenter();
              //Base::Vector3d a3 = arc->getStartPoint();
                Base::Vector3d a3 = arc->getEndPoint(true);
              //Base::Vector3d l1 = seg->getStartPoint();
                Base::Vector3d l2 = seg->getEndPoint();
#if 0
                Py::Module pd("FilletArc");
                Py::Callable method(pd.getAttr(std::string("makeFilletArc")));
                Py::Callable vector(pd.getAttr(std::string("Vector")));

                Py::Tuple xyz(3);
                Py::Tuple args(6);
                xyz.setItem(0, Py::Float(m1.x));
                xyz.setItem(1, Py::Float(m1.y));
                xyz.setItem(2, Py::Float(m1.z));
                args.setItem(0,vector.apply(xyz));

                xyz.setItem(0, Py::Float(a3.x));
                xyz.setItem(1, Py::Float(a3.y));
                xyz.setItem(2, Py::Float(a3.z));
                args.setItem(1,vector.apply(xyz));

                xyz.setItem(0, Py::Float(l2.x));
                xyz.setItem(1, Py::Float(l2.y));
                xyz.setItem(2, Py::Float(l2.z));
                args.setItem(2,vector.apply(xyz));

                xyz.setItem(0, Py::Float((float)0));
                xyz.setItem(1, Py::Float((float)0));
                xyz.setItem(2, Py::Float((float)1));
                args.setItem(3,vector.apply(xyz));

                args.setItem(4,Py::Float(radius));
                args.setItem(5,Py::Int((int)0));
                Py::Tuple ret(method.apply(args));
                Py::Object S1(ret.getItem(0));
                Py::Object S2(ret.getItem(1));
                Py::Object M2(ret.getItem(2));

                Base::Vector3d s1, s2, m2;
                s1.x = (double)Py::Float(S1.getAttr("x"));
                s1.y = (double)Py::Float(S1.getAttr("y"));
                s1.z = (double)Py::Float(S1.getAttr("z"));

                s2.x = (double)Py::Float(S2.getAttr("x"));
                s2.y = (double)Py::Float(S2.getAttr("y"));
                s2.z = (double)Py::Float(S2.getAttr("z"));

                m2.x = (double)Py::Float(M2.getAttr("x"));
                m2.y = (double)Py::Float(M2.getAttr("y"));
                m2.z = (double)Py::Float(M2.getAttr("z"));

                coords->point.set1Value(0, (float)s1.x,(float)s1.y,(float)s1.z);
                coords->point.set1Value(1, (float)m2.x,(float)m2.y,(float)m2.z);
                coords->point.set1Value(2, (float)s2.x,(float)s2.y,(float)s2.z);

                Base::Console().Message("M1=<%.4f,%.4f>\n", m1.x,m1.y);
                Base::Console().Message("M2=<%.4f,%.4f>\n", m2.x,m2.y);
                Base::Console().Message("S1=<%.4f,%.4f>\n", s1.x,s1.y);
                Base::Console().Message("S2=<%.4f,%.4f>\n", s2.x,s2.y);
                Base::Console().Message("P=<%.4f,%.4f>\n", a3.x,a3.y);
                Base::Console().Message("Q=<%.4f,%.4f>\n", l2.x,l2.y);
                Base::Console().Message("\n");
#else
                Py::Module pd("PartDesign");
                Py::Callable method(pd.getAttr(std::string("makeFilletArc")));

                Py::Tuple args(6);
                args.setItem(0,Py::Vector(m1));
                args.setItem(1,Py::Vector(a3));
                args.setItem(2,Py::Vector(l2));
                args.setItem(3,Py::Vector(Base::Vector3d(0,0,1)));
                args.setItem(4,Py::Float(radius));
              //args.setItem(5,Py::Int((int)0));
                args.setItem(5,Py::Int((int)1));
                Py::Tuple ret(method.apply(args));
                Py::Vector S1(ret.getItem(0));
                Py::Vector S2(ret.getItem(1));
                Py::Vector M2(ret.getItem(2));

                Base::Vector3d s1 = S1.toVector();
                Base::Vector3d s2 = S2.toVector();
                Base::Vector3d m2 = M2.toVector();
                coords->point.set1Value(0, (float)s1.x,(float)s1.y,(float)s1.z);
                coords->point.set1Value(1, (float)m2.x,(float)m2.y,(float)m2.z);
                coords->point.set1Value(2, (float)s2.x,(float)s2.y,(float)s2.z);

                Base::Console().Message("M1=<%.4f,%.4f>\n", m1.x,m1.y);
                Base::Console().Message("M2=<%.4f,%.4f>\n", m2.x,m2.y);
                Base::Console().Message("S1=<%.4f,%.4f>\n", s1.x,s1.y);
                Base::Console().Message("S2=<%.4f,%.4f>\n", s2.x,s2.y);
                Base::Console().Message("P=<%.4f,%.4f>\n", a3.x,a3.y);
                Base::Console().Message("Q=<%.4f,%.4f>\n", l2.x,l2.y);
                Base::Console().Message("\n");
#endif
            }
            catch (Py::Exception&) {
                Base::PyException e; // extract the Python error text
                Base::Console().Error("%s\n", e.what());
            }
        }
    }
Beispiel #10
0
	  ivec3 rgb() const { return xyz(); }
Beispiel #11
0
/*
*************************************************************************
* Set up the initial guess and problem parameters                       *
* and solve the Stokes problem.  We explicitly initialize and          *
* deallocate the solver state in this example.                          *
*************************************************************************
*/
bool Stokes::FAC::solve()
{

  if (!d_hierarchy) {
    TBOX_ERROR(d_object_name
               << "Cannot solve using an uninitialized object.\n");
  }

  int ln;
  /*
   * Fill in the initial guess.
   */
  for (ln = 0; ln <= d_hierarchy->getFinestLevelNumber(); ++ln) {
    boost::shared_ptr<SAMRAI::hier::PatchLevel> level = d_hierarchy->getPatchLevel(ln);
    SAMRAI::hier::PatchLevel::Iterator ip(level->begin());
    SAMRAI::hier::PatchLevel::Iterator iend(level->end());
    for ( ; ip!=iend; ++ip) {
      boost::shared_ptr<SAMRAI::hier::Patch> patch = *ip;
      boost::shared_ptr<SAMRAI::pdat::CellData<double> > p =
        boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> >
        (patch->getPatchData(p_id));

      boost::shared_ptr<SAMRAI::geom::CartesianPatchGeometry> geom =
        boost::dynamic_pointer_cast<SAMRAI::geom::CartesianPatchGeometry>
        (patch->getPatchGeometry());

      if(p_initial.empty())
        {
          p->fill(0.0);
        }
      else
        {
          const int dim=d_dim.getValue();
          const double *dx=geom->getDx();
          std::vector<double> xyz(dim);
          std::vector<double> dx_p(dim);
          for(int d=0;d<dim;++d)
            dx_p[d]=(p_initial_xyz_max[d]
                     - p_initial_xyz_min[d])/(p_initial_ijk[d]-1);
          std::vector<int> di(dim);
          di[0]=1;
          for(int d=1;d<dim;++d)
            di[d]=di[d-1]*p_initial_ijk[d-1];

          SAMRAI::hier::Box pbox = p->getBox();
          SAMRAI::pdat::CellIterator
            cend(SAMRAI::pdat::CellGeometry::end(p->getGhostBox()));
          for(SAMRAI::pdat::CellIterator
                ci(SAMRAI::pdat::CellGeometry::begin(p->getGhostBox()));
              ci!=cend; ++ci)
            {
              const SAMRAI::pdat::CellIndex &c(*ci);
              std::vector<double> xyz(dim);
              /* VLA's not allowed by clang */
              double weight[3][2];
              for(int d=0;d<dim;++d)
                xyz[d]=geom->getXLower()[d]
                  + dx[d]*(c[d]-pbox.lower()[d] + 0.5);

              int ijk(0);
              std::vector<int> ddi(dim);
              for(int d=0;d<dim;++d)
                {
                  int i=static_cast<int>(xyz[d]*(p_initial_ijk[d]-1)
                                         /(p_initial_xyz_max[d]
                                           - p_initial_xyz_min[d]));
                  i=std::max(0,std::min(p_initial_ijk[d]-1,i));
                  ijk+=i*di[d];

                  if(i==p_initial_ijk[d]-1)
                    {
                      weight[d][0]=1;
                      weight[d][1]=0;
                      ddi[d]=0;
                    }
                  else
                    {
                      weight[d][1]=
                        (xyz[d]-(i*dx_p[d] + p_initial_xyz_min[d]))/dx_p[d];
                      weight[d][0]=1-weight[d][1];
                      ddi[d]=di[d];
                    }
                }

              if(dim==2)
                {
                  (*p)(c)=p_initial[ijk]*weight[0][0]*weight[1][0]
                    + p_initial[ijk+ddi[0]]*weight[0][1]*weight[1][0]
                    + p_initial[ijk+ddi[1]]*weight[0][0]*weight[1][1]
                    + p_initial[ijk+ddi[0]+ddi[1]]*weight[0][1]*weight[1][1];
                }
              else
                {
                  (*p)(c)=p_initial[ijk]*weight[0][0]*weight[1][0]*weight[2][0]
                    + p_initial[ijk+ddi[0]]*weight[0][1]*weight[1][0]*weight[2][0]
                    + p_initial[ijk+ddi[1]]*weight[0][0]*weight[1][1]*weight[2][0]
                    + p_initial[ijk+ddi[0]+ddi[1]]*weight[0][1]*weight[1][1]*weight[2][0]
                    
                    + p_initial[ijk+ddi[2]]*weight[0][0]*weight[1][0]*weight[2][1]
                    + p_initial[ijk+ddi[0]+ddi[2]]*weight[0][1]*weight[1][0]*weight[2][1]
                    + p_initial[ijk+ddi[1]+ddi[2]]*weight[0][0]*weight[1][1]*weight[2][1]
                    + p_initial[ijk+ddi[0]+ddi[1]+ddi[2]]*weight[0][1]*weight[1][1]*weight[2][1];
                }
            }
        }

      boost::shared_ptr<SAMRAI::pdat::SideData<double> > v =
        boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> >
        (patch->getPatchData(v_id));
      v->fill(0.0);
    }
    d_stokes_fac_solver.set_boundaries(p_id,v_id,level,false);
  }

  fix_viscosity();

  d_stokes_fac_solver.initializeSolverState
    (p_id,cell_viscosity_id,edge_viscosity_id,dp_id,p_rhs_id,v_id,v_rhs_id,
     d_hierarchy,0,d_hierarchy->getFinestLevelNumber());

  SAMRAI::tbox::plog << "solving..." << std::endl;
  int solver_ret;
  solver_ret = d_stokes_fac_solver.solveSystem(p_id,p_rhs_id,v_id,v_rhs_id);

  double avg_factor, final_factor;
  d_stokes_fac_solver.getConvergenceFactors(avg_factor, final_factor);
  SAMRAI::tbox::plog << "\t" << (solver_ret ? "" : "NOT ") << "converged " << "\n"
             << "	iterations: "
             << d_stokes_fac_solver.getNumberOfIterations() << "\n"
             << "	residual: "<< d_stokes_fac_solver.getResidualNorm()
             << "\n"
             << "	average convergence: "<< avg_factor << "\n"
             << "	final convergence: "<< final_factor << "\n"
             << std::flush;

  d_stokes_fac_solver.deallocateSolverState();

  return solver_ret;
}
Beispiel #12
0
	  ivec3 stp() const { return xyz(); }
int main(int argc, char **argv) {

  // Parameters
  po::variables_map vm = get_parameters(argc,argv);
  // vector for options values
  std::vector<str> opt;

  // Read PDB
  IMP_NEW(IMP::Model, smodel, ());
  IMP::Pointer<atom::ATOMPDBSelector> ssel= new atom::ATOMPDBSelector();
  // Read only first model
  if(digest_parameter("i",vm,opt) == false) {
      std::cout << "Input file not found or missing parameter." << std::endl;
      exit(0);
  }
  atom::Hierarchy smh = atom::read_pdb(opt[0],smodel,ssel,true);
  IMP::ParticlesTemp sps = core::get_leaves(smh);
//  atom::add_radii(smh);
  double resolution = vm["res"].as<double>();
  IMP_NEW(em2d::SpiderImageReaderWriter,  srw, ());
  IMP_NEW(em::MRCReaderWriter,  mrw, ());


  // Generate a map
  if(digest_parameter("map",vm,opt)) {
    if( check_parameters(vm,"apix") == false) {
      std::cerr << "The requested --map option is missing "
                   "additional parameters"  << std::endl;
      std::exit(0);
    }
    double apix= vm["apix"].as<double>();
    str fn_map= vm["map"].as<str>();
    std::cout << "Generating map ... " << fn_map << std::endl;
    em::SampledDensityMap *map= new em::SampledDensityMap(sps,resolution,apix);
    em::write_map(map,fn_map.c_str(),mrw);
  }

  // Project IMAGES
  if( vm.count("proj_img")) {
    if(check_parameters(vm,"np,apix,size_i,proj_dist,proj_params") == false) {
      std::cerr << "--proj is missing additional parameters." << std::endl;
      std::exit(0);
    }
    // Parameters
    unsigned int np=vm["np"].as<unsigned int>();
    double apix       = vm["apix"].as<double>();
    digest_parameter("size_i",vm,opt);
    unsigned int cols = std::atoi(opt[0].c_str());
    unsigned int rows =std::atoi(opt[1].c_str());
    digest_parameter("proj_dist",vm,opt);
    em2d::RegistrationResults registration_values=
                            get_registration_values(opt,np);
    em2d::ProjectingOptions options( apix, resolution);
    em2d::Images projections = em2d::get_projections(sps,
                                                     registration_values,
                                                     rows,
                                                     cols,
                                                     options);
    // Normalize and add noise if requested
    np = registration_values.size(); // for the case when the values are read
    if(vm.count("SNR")) {
      double SNR = vm["SNR"].as<double>();
      for (unsigned int i=0;i<np;++i) {
        em2d::do_normalize(projections[i]);
        // Noise added of mean = 0  and stddev = stddev_signal / sqrt(SNR)
        // As the image is normalized, stddev_signal is 1.0
        em2d::add_noise(
                  projections[i]->get_data(),0.0,1./sqrt(SNR), "gaussian");
      }
    }
    // Save projections and projection parameters
    IMP::Strings proj_names;
    if(digest_parameter("proj_names",vm,opt)) {
      proj_names = em2d::read_selection_file(opt[0]);
    } else {
      proj_names = em2d::create_filenames(np,"proj","spi");
    }
    for (unsigned int i=0;i<np;++i) {
      projections[i]->write(proj_names[i],srw);
    }
    if(digest_parameter("proj_params",vm,opt)) {
      em2d::write_registration_results(opt[0],registration_values);
    }
  }

  // Project PDBs
  if(vm.count("proj_pdb")) {
    IMP::String param_error = "More parameters are required with --proj_pdb\n";
    IMP_USAGE_CHECK(check_parameters(vm,"np,proj_dist"),param_error);
    // Parameters
    unsigned int np=vm["np"].as<unsigned int>();
    digest_parameter("proj_dist",vm,opt);
    em2d::RegistrationResults registration_values=
                      get_registration_values(opt,np);
    np = registration_values.size(); // for the case when the values are read
    // Get coordinates
    unsigned int n_atoms=sps.size();
    alg::Vector3Ds pdb_atoms(n_atoms);
    for (unsigned i=0;i<n_atoms;++i ) {
      core::XYZ xyz(sps[i]);
      pdb_atoms[i] = xyz.get_coordinates();
    }
    alg::Vector3D centroid = alg::get_centroid(pdb_atoms);
    // Project
    IMP::Strings proj_names;
    if(vm.count("proj_names")) {
      proj_names=em2d::read_selection_file(vm["proj_names"].as<IMP::String>());
    } else {
      proj_names = em2d::create_filenames(np,"proj","pdb");
    }
    for(unsigned int i=0;i<np;++i) {
      // To project vectors here, the shift is understood a as translation
      alg::Vector3D translation = registration_values[i].get_shift_3d();
      alg::Rotation3D R = registration_values[i].get_rotation();
      alg::Vector2Ds projected_points=
                em2d::do_project_vectors(pdb_atoms,R,translation,centroid);
      // Save projection
      em2d::write_vectors_as_pdb(projected_points,proj_names[i]);
    }
    // Save projection parameters
    if(digest_parameter("proj_params",vm,opt)) {
      em2d::write_registration_results(opt[0],registration_values);
    }
  }
}
 List() : prev(&node) { xyz(); }
Beispiel #15
0
int xyz(const Vector3i & halfCell)
{
    return xyz(octant(halfCell));
}
Beispiel #16
0
//------------------------------------------------------------------------------
void Grid::createGrid()
{
    double x_len = m_boundaryLength[0];
    double y_len = m_boundaryLength[1];
    double z_len = m_boundaryLength[2];

    // Finding the optimal length
    int nx = floor(x_len/m_gridspacing) > 0 ? floor(x_len/m_gridspacing) : 1;
    int ny = floor(y_len/m_gridspacing) > 0 ? floor(y_len/m_gridspacing) : 1;
    int nz = floor(z_len/m_gridspacing) > 0 ? floor(z_len/m_gridspacing) : 1;

    m_gridSpacing = {x_len/nx, y_len/ny, z_len/nz };
    m_nGrid = {nx, ny, nz};
    vector<ivec> inner_points;
    vector<ivec> boundary_points;

    for(int d=0;d<3; d++)
    {
        if(m_periodicBoundaries[d])
        {
            inner_points.push_back(linspace<ivec>(1, m_nGrid(d), m_nGrid(d)));
            boundary_points.push_back({0, m_nGrid(d) + 1});
            m_nGrid(d) += 2;
            m_boundary[d].first -= m_gridSpacing(d);
            m_boundary[d].second += m_gridSpacing(d);
        }
        else
        {
            inner_points.push_back(linspace<ivec>(0, m_nGrid(d)-1, m_nGrid(d)));
            boundary_points.push_back({});
        }
    }

    // Setting the grid
    for(int x:inner_points[X])
    {
        for(int y:inner_points[Y])
        {
            for(int z:inner_points[Z])
            {
                // id = x + nx*y + nx*ny*z;
                // Center of gridpoint
                vec3 center = {
                    m_boundary[X].first + m_gridSpacing(X)*(x + 0.5)
                    ,m_boundary[Y].first + m_gridSpacing(Y)*(y + 0.5)
                    ,m_boundary[Z].first + m_gridSpacing(Z)*(z + 0.5)};

                int id = gridId(center);
                m_gridpoints[id] = new GridPoint(id, center, false);
                m_myGridPoints.push_back(id);
            }
        }
    }

    // Boundary conditions
    for(int d=0; d<3; d++)
    {
        ivec3 xyz = {0, 0, 0};

        for(int point_0:boundary_points[d])
        {
            vector<int> inn_p = {0, 1, 2};
            inn_p.erase(inn_p.begin() + d);

            ivec p1 = join_cols(inner_points[inn_p[0]], boundary_points[inn_p[0]]);
            for(int point_1:p1)
            {
                ivec p2 = join_cols(inner_points[inn_p[1]], boundary_points[inn_p[1]]);

                for(int point_2:p2)
                {
                    xyz(d) = point_0;
                    xyz(inn_p[0]) = point_1;
                    xyz(inn_p[1]) = point_2;

                    // Center of gridpoint
                    vec3 center = {
                        m_boundary[X].first + m_gridSpacing(X)*(xyz(X) + 0.5)
                        ,m_boundary[Y].first + m_gridSpacing(Y)*(xyz(Y) + 0.5)
                        ,m_boundary[Z].first + m_gridSpacing(Z)*(xyz(Z) + 0.5)};

                    int id = gridId(center);
                    m_gridpoints[id] = new GridPoint(id, center, true);
                }
            }
        }
    }
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
cvf::Vec3d RimWellPathGeometryDef::referencePointXyz() const
{
    cvf::Vec3d xyz(m_referencePointUtmXyd()); 
    xyz.z() = -xyz.z(); 
    return xyz;
}
Beispiel #18
0
void Widget::paintEvent(QPaintEvent *)
{
    int i, nSteps, count;
    double t, tt, scale = ( width()/4 + height()/4 )/6, sum, k;
    double x, y, z, delta = 0.005, dxdt = 1, dydt = 1, tempDelta;

    my_vector4 xyz(0.0, 0.0, 0.0), xyz0(width()/2, height()/2, scale*5.0), xxyyzz(0.0, 0.0, 0.0),
            light_point(0.0, 0.0, scale*13.0), xyz_s(0.0,0.0,0.0), xxyyzz_s(0.0, 0.0, 0.0);

    QPainter p(this);

    if (!dF){
        delta = inpDelta;
        nSteps =  (2*pi) / delta  + 1;
    }
    else{
        delta = 0.05;
        count = 0;
        sum = 0;
        t = 0;
        tt = 0;
        k = 1;
        while (sum < 2*pi){
            dxdt = -inpA * sin( t ) + inpB * inpC * sin ( inpC * t );
            dydt = inpA * cos( t ) - inpB * inpC * cos ( inpC * t );
            tempDelta = delta/maxAbs(dxdt, dydt);
            t += tempDelta;
            sum+=tempDelta;
            count++;
        }
        nSteps = count + 1;
    }

    k = 1;
    t = 0;
    tt = 0;
    dxdt = 1;
    dydt = 1;

    for (i = 0; i < nSteps; i++){

        if(dF){
            dxdt = -inpA * sin( t ) + inpB * inpC * sin ( inpC * t );
            dydt = inpA * cos( t ) - inpB * inpC * cos ( inpC * t );
            k = 1/maxAbs(dxdt, dydt);
        }

        tempDelta = delta * k;
        tt = t + tempDelta;

        x = inpA * cos( t ) - inpB * cos ( inpC * t );
        y = inpA * sin( t ) - inpB * sin ( inpC * t );
        z = cos ( sqrt( x * x + y * y ) );
        t = t + tempDelta;

        xyz.setElem(0, x );
        xyz.setElem(1, y );
        xyz.setElem(2, z );

        x = inpA * cos( tt ) - inpB * cos ( inpC * tt );
        y = inpA * sin( tt ) - inpB * sin ( inpC * tt );
        z = cos ( sqrt( x * x + y * y ) );

        xxyyzz.setElem(0, x );
        xxyyzz.setElem(1, y );
        xxyyzz.setElem(2, z );


        if (flag) {
            rotateX ( xyz , beta);
            rotateX ( xxyyzz, beta );

            rotateY ( xyz, alpha );
            rotateY ( xxyyzz, alpha );
        }

        if (!flag){
            rotateY ( xyz , alpha);
            rotateY ( xxyyzz, alpha );

            rotateX ( xyz, beta );
            rotateX ( xxyyzz, beta );
        }

        xyz.numMul(scale);
        xxyyzz.numMul(scale);

        vecSum(xyz, xyz0);
        vecSum(xxyyzz, xyz0);

        getShadowXY(light_point, xyz, xyz_s);
        getShadowXY(light_point, xxyyzz, xxyyzz_s);

        p.setPen(Qt::darkMagenta);
        p.drawLine( xyz.getElem(0), xyz.getElem(1), xxyyzz.getElem(0), xxyyzz.getElem(1) );

        p.setPen(Qt::darkGray);
        p.drawLine( xyz_s.getElem(0), xyz_s.getElem(1), xxyyzz_s.getElem(0), xxyyzz_s.getElem(1) );

    }
}
double Chi2Func(const double *xx ){
 const Double_t DX = xx[0];
 const Double_t DY = xx[1];
 const Double_t DZ = xx[2];
 
 const Double_t DPHIEuler = xx[3]; ///==== Euler angles
 const Double_t DTHETAEuler = xx[4];
 const Double_t DPSIEuler = xx[5];
 
///  The transform rotates first, then translates.
///  The Euler angles are gotten from HepRotation::eulerAngles()
///  (a HepTransform3D is a HepRotation and a HepTranslation).
 
//  CLHEP::HepEulerAngles RotMat((CLHEP::HepRotationZ( DPHIEuler )).eulerAngles());
 CLHEP::HepEulerAngles RotMat(DPHIEuler,DTHETAEuler,DPSIEuler);
 
 HepGeom::Transform3D RotoTrasl( RotMat,
		                 CLHEP::Hep3Vector(DX,DY,DZ));

 myTree->SetEntryList(0); 
 myTree->Draw(">> myList",globalCut.Data(),"entrylist");
 TEntryList *myList = (TEntryList*)gDirectory->Get("myList");

 //==== bux fix in ROOT see https://savannah.cern.ch/bugs/?60569 ====
 /*
 TIter next( myList->GetLists() ); 
 if (myList->GetLists() != 0){
// if ((int) myList->GetLists() != 0){
  TEntryList *ilist;
  while( (ilist = (TEntryList*) *next ) ) {
   ilist->SetTreeName(myTree->GetName()); 
   next();
   } 
  TEntryList *duplist = (TEntryList*) myList->Clone(); 
  delete myList; myList = duplist; 
 }
 else {
  myList->SetTreeName(myTree->GetName());
 }
 */
  //==== end bux fix in ROOT see https://savannah.cern.ch/bugs/?60569 ==== 
 myTree->SetEntryList(myList); 
 
 myTree->Draw("DeltaEtaIn:DeltaPhiIn:etaSC:phiSC","","para goff");
 int nEntries = myList->GetN();
 Double_t *vTemp = myTree->GetV1();
 Double_t *vDEta = new Double_t[nEntries];
 for (int iEntry = 0; iEntry<nEntries; iEntry++){
  vDEta[iEntry] = vTemp[iEntry];
 }
 Double_t *vTemp2 = myTree->GetV2();
 Double_t *vDPhi = new Double_t[nEntries];
 for (int iEntry = 0; iEntry<nEntries; iEntry++){
  vDPhi[iEntry] = vTemp2[iEntry];
 }
 Double_t *vEta = myTree->GetV3();
 Double_t *vPhi = myTree->GetV4();
 myTree->Draw("E5x5:eleCharge","","para goff");
 Double_t *vEnergy = myTree->GetV1();
 Double_t *vCharge = myTree->GetV2();

  Double_t vErrDEta;
  Double_t vErrDPhi;
  Double_t vErrEta;
  Double_t vErrPhi;
  
  double Chi2 = 0;
  
  int counter = 0;
  for (int iEntry = 0; iEntry < nEntries; iEntry++){
   if ((even && !(iEntry%2)) || (odd && (iEntry%2))) {
//    if (!(iEntry%10)) {
    counter++;
    
//   for (int iEntry = 0; iEntry<nEntries; iEntry++){
//     if (!(iEntry/100)) std::cout << " iEntry = " << iEntry << " : " << nEntries << std::endl;
//     std::cerr << " " << vDEta[iEntry] << std::endl;
//     std::cerr << " " << vDPhi[iEntry] << std::endl;
//     std::cerr << " " << vEta[iEntry] << std::endl;
//     std::cerr << " " << vPhi[iEntry] << std::endl;
//     std::cerr << " " << vEnergy[iEntry] << " " << std::endl;
    
    vErrDEta = fabs((sqrt(3.6 / sqrt(vEnergy[iEntry]) * 3.6 / sqrt(vEnergy[iEntry]) + 12. / vEnergy[iEntry] * 12. / vEnergy[iEntry] + 0.54*0.54)) / 1000. / (Z * tan(2*atan(exp(-vEta[iEntry])))) * fabs(sin(2*atan(exp(-vEta[iEntry]))))); ///===> /1000 perchè è in "mm" -> "m"
  
    vErrDPhi = 1.3 * fabs((sqrt(3.6 / sqrt(vEnergy[iEntry]) * 3.6 / sqrt(vEnergy[iEntry]) + 12. / vEnergy[iEntry] * 12. / vEnergy[iEntry] + 0.54*0.54)) / 1000. / (Z * tan(2*atan(exp(-vEta[iEntry]))))); ///===> /1000 perchè è in "mm" -> "m"
    
    vErrEta = 0.0;
    vErrPhi = 0.0;


    ///==== (x,y,z) 
     HepGeom::Point3D<double> xyz( Z / cos(2*atan(exp(-vEta[iEntry]))) * sin(2*atan(exp(-vEta[iEntry]))) * cos (vPhi[iEntry]),
				  Z / cos(2*atan(exp(-vEta[iEntry]))) * sin(2*atan(exp(-vEta[iEntry]))) * sin (vPhi[iEntry]),
				  Z );

			   
    ///==== (x',y',z') = RotoTrasl(x,y,z) 
    HepGeom::Point3D<double> xyz_prime = RotoTrasl * xyz;
    ///==== deta / dphi [(x',y',z'),(x,y,z)]
    

    double deta = xyz.pseudoRapidity() - xyz_prime.pseudoRapidity(); ///==== deta_data = SC - Tracker
    double dphi = deltaPhi(xyz.phi() , xyz_prime.phi()); ///==== check sign convention!!!!!!!!!!!!!!!!!!!!!
    double ddeta = (vDEta[iEntry] - deta);
    double ddphi = (vDPhi[iEntry] - dphi);
    
    ddeta = ddeta - FunctionDeta->Eval(vEta[iEntry],vCharge[iEntry]);
    ddphi = ddphi - FunctionDphi->Eval(vEta[iEntry],vCharge[iEntry]);
         
    Chi2 += (ddeta / vErrDEta * ddeta / vErrDEta + ddphi / vErrDPhi * ddphi / vErrDPhi);
    
   }
  }
  
  std::cout << " Chi2 = " << Chi2 << " / " << counter << " = " << Chi2/counter << " - " << DX*1000 << " mm: " << DY*1000 << " mm: " << DZ*1000 << " mm: "  <<  DPHIEuler << " : "  <<  DTHETAEuler << " : "  <<  DPSIEuler << std::endl;
   return Chi2;
}
Beispiel #20
0
//===================================================
/// This function assembles the matrix and the rhs:
 void GenMatRhsNS(MultiLevelProblem &ml_prob)  {

   SystemTwo & my_system = ml_prob.get_system<SystemTwo>("Eqn_NS");
   const unsigned Level = my_system.GetLevelToAssemble();
    
   const uint   _AdvPic_fl = 1;
   const uint   _AdvNew_fl = 0;
   const uint   _Stab_fl = 0;
   const double _Komp_fac = 0.;

  //========== GEOMETRIC ELEMENT ========
  const uint           space_dim = ml_prob._ml_msh->GetDimension();

  //====== reference values ========================
//====== related to Quantities on which Operators act, and to the choice of the "LEADING" EQUATION Operator
  const double IRe = 1./ml_prob.GetInputParser().get("Re");
  const double IFr = 1./ml_prob.GetInputParser().get("Fr");
//================================================  

//================================================  
//=======Operators @ gauss =======================
  std::vector<double>    dphijdx_g(space_dim); // ShapeDer(): used for Laplacian,Divergence, ..., associated to an Unknown Quantity
  std::vector<double>    dphiidx_g(space_dim); // Test(): used for Laplacian,Advection,Divergence... associated to an Unknown Quantity
  std::vector<double>     AdvRhs_g(space_dim); //Operator: Adv(u,u,phi)
//================================================  

        my_system._LinSolver[Level]->_KK->zero();
        my_system._LinSolver[Level]->_RESC->zero();

// ==========================================  
  Mesh		*mymsh		=  ml_prob._ml_msh->GetLevel(Level);
  elem		*myel		=  mymsh->el;
  const unsigned myproc  = mymsh->processor_id();
	
// ==========================================  
// ==========================================  

  {//BEGIN VOLUME
//========================
//========================
    const uint mesh_vb = VV;
  
    const uint nel_e = ml_prob.GetMeshTwo()._off_el[mesh_vb][ml_prob.GetMeshTwo()._NoLevels*myproc+Level+1];
    const uint nel_b = ml_prob.GetMeshTwo()._off_el[mesh_vb][ml_prob.GetMeshTwo()._NoLevels*myproc+Level];

  for (int iel=0; iel < (nel_e - nel_b); iel++) {
    
    CurrentElem<double>       currelem(iel,myproc,Level,VV,&my_system,ml_prob.GetMeshTwo(),ml_prob.GetElemType(),mymsh);
    CurrentGaussPointBase & currgp = CurrentGaussPointBase::build(currelem,ml_prob.GetQuadratureRule(currelem.GetDim()));
 
  
//=========INTERNAL QUANTITIES (unknowns of the equation) ==================
    CurrentQuantity VelOldX(currgp);
    VelOldX._qtyptr  = ml_prob.GetQtyMap().GetQuantity("Qty_Velocity0");
    VelOldX._SolName = "Qty_Velocity0";
    VelOldX.VectWithQtyFillBasic();
    VelOldX.Allocate();

    CurrentQuantity VelOldY(currgp);
    VelOldY._qtyptr  = ml_prob.GetQtyMap().GetQuantity("Qty_Velocity1");
    VelOldY._SolName = "Qty_Velocity1";
    VelOldY.VectWithQtyFillBasic();
    VelOldY.Allocate();

    std::vector<CurrentQuantity*> VelOld_vec;   
    VelOld_vec.push_back(&VelOldX);
    VelOld_vec.push_back(&VelOldY);
    
  
    const uint   qtyzero_ord  = VelOldX._FEord;
    const uint   qtyzero_ndof = VelOldX._ndof;  //same as Y 

//=========
    CurrentQuantity pressOld(currgp);
    pressOld._qtyptr  = ml_prob.GetQtyMap().GetQuantity("Qty_Pressure");
    pressOld._SolName = "Qty_Pressure";
    pressOld.VectWithQtyFillBasic();
    pressOld.Allocate();

   const uint qtyone_ord  = pressOld._FEord;
   const uint qtyone_ndof = pressOld._ndof; 

   //order
   const uint  qtyZeroToOne_DofOffset = VelOldX._ndof + VelOldY._ndof;//VelOld._ndof*VelOld._dim;
   
//========= END INTERNAL QUANTITIES (unknowns of the equation) =================

//=========EXTERNAL QUANTITIES (couplings) =====
  //========= //DOMAIN MAPPING
    CurrentQuantity xyz(currgp); //domain
    xyz._dim      = space_dim;
    xyz._FEord    = MESH_MAPPING_FE;
    xyz._ndof     = currelem.GetElemType(xyz._FEord)->GetNDofs();
    xyz.Allocate();
    
//other Physical constant Quantities
//=======gravity==================================
  CurrentQuantity gravity(currgp);
  gravity._dim = space_dim;
//   gravity.Allocate(); CANNOT DO THIS NOW BECAUSE NOT ALL THE DATA FOR THE ALLOCATION ARE FILLED
  gravity._val_g.resize(gravity._dim);
  gravity._val_g[0] = ml_prob.GetInputParser().get("dirgx");
  gravity._val_g[1] = ml_prob.GetInputParser().get("dirgy");
  if ( space_dim == 3 )   gravity._val_g[2] = ml_prob.GetInputParser().get("dirgz"); 

//========================
//========================
 
    currelem.Mat().zero();
    currelem.Rhs().zero(); 

    currelem.SetDofobjConnCoords();
    currelem.SetElDofsBc();

    currelem.ConvertElemCoordsToMappingOrd(xyz);

//=======RETRIEVE the DOFS of the UNKNOWN QUANTITIES,i.e. MY EQUATION
     VelOldX.GetElemDofs();
     VelOldY.GetElemDofs();
    pressOld.GetElemDofs();

   const uint el_ngauss = ml_prob.GetQuadratureRule(currelem.GetDim()).GetGaussPointsNumber();
   
    for (uint qp = 0; qp < el_ngauss; qp++) {  

//=======here starts the "COMMON SHAPE PART"==================
// the call of these things should be related to the Operator
//also, the choice of the QuadratureRule should be dependent of the Involved Operators
//and the FE orders on which these Operators act

//these  phi and dphi are used for the different stages:
//BEFORE i: by the interpolation functions
//INSIDE i: for the tEST functions and derivatives
//INSIDE j: for the SHAPE functions and derivatives
//again, it should be the Operator to decide what functions to be called,
//for what FE ORDER and what DERIVATIVE ORDER
//if we decide that the PREPARATION of the tEST and SHAPE 
//of a certain Unknown are COMMON TO ALL,
//Then we must only concentrate on preparing the OTHER involved quantities in that Operator
for (uint fe = 0; fe < QL; fe++)     {          
  currgp.SetPhiElDofsFEVB_g (fe,qp);
  currgp.SetDPhiDxezetaElDofsFEVB_g (fe,qp);  
  }
	  
const double      det = currgp.JacVectVV_g(xyz);
const double dtxJxW_g = det*ml_prob.GetQuadratureRule(currelem.GetDim()).GetGaussWeight(qp);
const double     detb = det/el_ngauss;
	  
for (uint fe = 0; fe < QL; fe++)     { 
  currgp.SetDPhiDxyzElDofsFEVB_g   (fe,qp);
  currgp.ExtendDphiDxyzElDofsFEVB_g(fe);
  }
//=======end of the "COMMON SHAPE PART"==================

//now we want to fill the element matrix and rhs with ONLY values AT GAUSS POINTS
//we can divide the values at Gauss points into three parts:
//1-constant values
//2-values which depend on (i)
//3-values which depend on (i,j)
//1- can be used for filling both Ke and Fe
//2- can be used to fill Fe and also Ke
//3- can be used only for filling Ke

//Here, before entering the (i,j) loop, you compute quantities that DO NOT depend on (i,j),
//therefore the ELEMENT SUM, GAUSS SUM And tEST/SHAPE sums have ALL been performed
//but, these quantities depend on idim and jdim, because they are  involved in multiplications with tEST and SHAPE functions

//Internal Quantities
      VelOldX.val_g();
      VelOldX.grad_g();
      VelOldY.val_g();
      VelOldY.grad_g();
      
//Advection all VelOld
      for (uint idim=0; idim<space_dim; idim++) { AdvRhs_g[idim]=0.;}
      
       for (uint idim=0; idim<space_dim; idim++)  {
          for (uint b=0; b<space_dim; b++) {
	    AdvRhs_g[idim] += VelOld_vec[b]->_val_g[0]*VelOld_vec[idim]->_grad_g[0][b];
	  } 
      }   // grad is [ivar][idim], i.e. [u v w][x y z]	  
	    
//Divergence VelOld
	  double Div_g=0.;
          for (uint idim=0; idim<space_dim; idim++)    Div_g += VelOld_vec[idim]->_grad_g[0][idim];

//==============================================================
//========= FILLING ELEMENT MAT/RHS (i loop) ====================
//==============================================================
// TODO according to the order we should switch DIM loop and DOF loop
    for (uint i=0; i<qtyzero_ndof; i++)     {
//======="COMMON tEST PART for QTYZERO": func and derivative, of the QTYZERO FE ORD ==========
                                    const double phii_g       =      currgp._phi_ndsQLVB_g[qtyzero_ord][i];
        for (uint idim=0; idim<space_dim; idim++)  dphiidx_g[idim] = currgp._dphidxyz_ndsQLVB_g[qtyzero_ord][i+idim*qtyzero_ndof];
//======= END "COMMON tEST PART for QTYZERO" ==========
	
	  for (uint idim=0; idim<space_dim; idim++) {
            const uint irowq=i+idim*qtyzero_ndof;  //  (i):       dof of the tEST function
                                                  //(idim): component of the tEST function
           currelem.Rhs()(irowq) += 
         currelem.GetBCDofFlag()[irowq]*
           dtxJxW_g*(       + _AdvNew_fl*          AdvRhs_g[idim]*phii_g     // NONLIN
                            +            IFr*gravity._val_g[idim]*phii_g     // gravity                           
                               )
            + (1-currelem.GetBCDofFlag()[irowq])*detb*VelOld_vec[idim]->_val_dofs[i] //Dirichlet bc    
	;
          }
           // end filling element rhs u

  for (uint idim=0; idim<space_dim; idim++) { // filling diagonal for Dirichlet bc
          const uint irowq = i+idim*qtyzero_ndof;
          currelem.Mat()(irowq,irowq) += (1-currelem.GetBCDofFlag()[irowq])*detb;
        }
                                       // end filling diagonal for Dirichlet bc

//============ QTYZERO x QTYZERO dofs matrix (A matrix) ============
        for (uint j=0; j< qtyzero_ndof; j++) {
//======="COMMON SHAPE PART for QTYZERO": func and derivative, of the QTYZERO FE ORD ==========
//   (j):       dof of the SHAPE function
           double                                  phij_g       =      currgp._phi_ndsQLVB_g[qtyzero_ord][j];
           for (uint idim=0; idim<space_dim; idim++) dphijdx_g[idim] = currgp._dphidxyz_ndsQLVB_g[qtyzero_ord][j+idim*qtyzero_ndof];
//======= END "COMMON SHAPE PART for QTYZERO" ==========
  
          double Lap_g = Math::dot(&dphijdx_g[0],&dphiidx_g[0],space_dim);
	  double Adv_g=0.;
	  for (uint idim=0; idim<space_dim; idim++) Adv_g += VelOld_vec[idim]->_val_g[0] * dphijdx_g[idim]; // =Math::dot(&VelOld._val_g[0],dphijdx_g,space_dim);
         
          for (uint idim=0; idim<space_dim; idim++) { //filled in as 1-2-3 // 4-5-6 // 7-8-9
            int irowq = i+idim*qtyzero_ndof;      //(i) is still the dof of the tEST functions
                                                  //(idim): component of the tEST functions

            currelem.Mat()(irowq,j+idim*qtyzero_ndof)  // diagonal blocks [1-5-9] [idim(rows),idim(columns)]  //(idim): component of the SHAPE functions
               += 
            currelem.GetBCDofFlag()[irowq]*    
            dtxJxW_g*(
                 + _AdvPic_fl*                           Adv_g*phii_g                //TODO NONLIN
                 + _AdvNew_fl*phij_g*VelOld_vec[idim]->_grad_g[0][idim]*phii_g        //TODO NONLIN
                 + _AdvPic_fl*_Stab_fl*        0.5*Div_g*phij_g*phii_g                //TODO NONLIN
                 +                         IRe*(      dphijdx_g[idim]*dphiidx_g[idim] + Lap_g)
               );

            int idimp1=(idim+1)%space_dim;    // block +1 [2-6-7] [idim(rows),idim+1(columns)]  //(idimp1): component of the SHAPE functions
            currelem.Mat()(irowq,j+idimp1*qtyzero_ndof)
               +=
            currelem.GetBCDofFlag()[irowq]*
            dtxJxW_g*(
                   _AdvNew_fl*phij_g*VelOld_vec[idim]->_grad_g[0][idimp1]*phii_g           //TODO NONLIN
                              +            IRe*(     dphijdx_g[idim]*dphiidx_g[idimp1])
               );

          }
 
        } 
//============ END QTYZERO x QTYZERO dofs matrix (A matrix) ============

//============ QTYZERO x QTYONE dofs matrix (B^T matrix) // ( p*div(v) ) (NS eq) ============
       for (uint j=0; j<qtyone_ndof; j++) {
//======="COMMON SHAPE PART for QTYONE" ==================
	 const double psij_g = currgp._phi_ndsQLVB_g[qtyone_ord][j];
//======="COMMON SHAPE PART for QTYONE" - END ============

          const int jclml = j + qtyZeroToOne_DofOffset;
          for (uint idim=0; idim<space_dim; idim++) {
            uint irowq = i+idim*qtyzero_ndof;
            currelem.Mat()(irowq,jclml) +=
               currelem.GetBCDofFlag()[irowq]*                    
               dtxJxW_g*(-psij_g*dphiidx_g[idim]);   /**   (-1.)*/
	    
           } 

        }
//============ END QTYZERO x QTYONE dofs matrix (B^T matrix) ============

          if (i < qtyone_ndof) {
//======="COMMON tEST PART for QTYONE" ============
          double psii_g = currgp._phi_ndsQLVB_g[qtyone_ord][i];
//======= "COMMON tEST PART for QTYONE" - END ============
	  const uint irowl = i + qtyZeroToOne_DofOffset;
          currelem.Rhs()(irowl)=0.;  // rhs
 //             Mat()(irowl,j+space_dim*qtyzero_ndof)  += (1./dt)*dtxJxW_g*(psii_g*psij_g)*_Komp_fac/dt;  //no bc here (KOMP dp/dt=rho*div)

          for (uint j=0; j<qtyzero_ndof; j++) { // B element matrix q*div(u)
//======="COMMON SHAPE PART for QTYZERO" ==================
            for (uint idim=0; idim<space_dim; idim++) dphijdx_g[idim] = currgp._dphidxyz_ndsQLVB_g[qtyzero_ord][j+idim*qtyzero_ndof];
//======="COMMON SHAPE PART for QTYZERO" - END ============
	    
            for (uint idim=0; idim<space_dim; idim++) currelem.Mat()(irowl,j+idim*qtyzero_ndof) += -/*(1./dt)**/dtxJxW_g*psii_g*dphijdx_g[idim]; 
                }

        }
                         // end pressure eq (cont)
      }
//===================================================================
//========= END FILLING ELEMENT MAT/RHS (i loop) =====================
//===================================================================
    }
//==============================================================
//================== END GAUSS LOOP (qp loop) ======================
//==============================================================
    
    ///  Add element matrix and rhs to the global ones.
                   my_system._LinSolver[Level]->_KK->add_matrix(currelem.Mat(),currelem.GetDofIndices());
                   my_system._LinSolver[Level]->_RESC->add_vector(currelem.Rhs(),currelem.GetDofIndices());

    
  } 
  // end of element loop

 
  }//END VOLUME

        my_system._LinSolver[Level]->_KK->close();
        my_system._LinSolver[Level]->_RESC->close();


#ifdef DEFAULT_PRINT_INFO
 std::cout << " GenMatRhs " << my_system.name() << ": assembled  Level " << Level
           << " with " << my_system._LinSolver[Level]->_KK->m() << " dofs" << std::endl;
#endif

    return;
}
Beispiel #21
0
void triangleMesher(const Vector3d& v1, const Vector3d& v2, const Vector3d& v3, const int nArcDiv, MV3& vertex)
{
	M3 xyz(3,27,4);
	IA1 ixstr(4), ixend(4), iystr(4), iyend(4), izstr(4), izend(4), nzsti(4), itype(4);
	itype(1)=itype(2)=itype(3)=itype(4)=1;

    const int ndiv = ((nArcDiv+1)/2)*2;
	ixstr(1)=iystr(1)=izstr(1)=1;
	ixend(1)=iyend(1)=ndiv+1;
	izend(1)=1;
	const int izn = 1;
    const int lengx=ixend(izn)-ixstr(izn);
    const int lengy=iyend(izn)-iystr(izn);
    const int lengz=izend(izn)-izstr(izn);
    ixstr(izn)=ixstr(izn);
    ixend(izn)=ixstr(izn)+lengx/2;
    iystr(izn)=iystr(izn);
    iyend(izn)=iystr(izn)+lengy/2;
    izstr(izn)=izstr(izn);
    izend(izn)=izend(izn);
	const int izn1=izn+1;
    ixstr(izn1)=ixstr(izn)+lengx/2;
    ixend(izn1)=ixstr(izn)+lengx;
    iystr(izn1)=iystr(izn);
    iyend(izn1)=iystr(izn)+lengy/2;
    izstr(izn1)=izstr(izn);
    izend(izn1)=izend(izn);
	const int izn2=izn+2;
    ixstr(izn2)=ixstr(izn)+lengx/2;
    ixend(izn2)=ixstr(izn)+lengx;
    iystr(izn2)=iystr(izn)+lengy/2;
    iyend(izn2)=iystr(izn)+lengy;
    izstr(izn2)=izstr(izn);
    izend(izn2)=izend(izn);

	const int nx=ixend(1)-ixstr(1)+1;
	const int nz=izend(1)-izstr(1)+1;
	nzsti(1)=1;
	nzsti(2)=nzsti(1)+nx;
	nzsti(3)=nzsti(2)+nx;
	vertex.reSize(nx*3, nx, nz);

	const Vector3d v123 = (v1+v2+v3)*(1.0/3);
	const Vector3d v12 = (v1+v2)*0.5;
	const Vector3d v23 = (v2+v3)*0.5;
	const Vector3d v13 = (v1+v3)*0.5;

	//zone 1
	Vector3dToFMatrix(v1, xyz, 1, izn);
	Vector3dToFMatrix(v12, xyz, 2, izn);
	Vector3dToFMatrix(v123, xyz, 3, izn);
	Vector3dToFMatrix(v13, xyz, 4, izn);
	Vector3dToFMatrix(v1, xyz, 5, izn);
	Vector3dToFMatrix(v12, xyz, 6, izn);
	Vector3dToFMatrix(v123, xyz, 7, izn);
	Vector3dToFMatrix(v13, xyz, 8, izn);
	
	//zone 2
	Vector3dToFMatrix(v2, xyz, 1, izn1);
	Vector3dToFMatrix(v23, xyz, 2, izn1);
	Vector3dToFMatrix(v123, xyz, 3, izn1);
	Vector3dToFMatrix(v12, xyz, 4, izn1);
	Vector3dToFMatrix(v2, xyz, 5, izn1);
	Vector3dToFMatrix(v23, xyz, 6, izn1);
	Vector3dToFMatrix(v123, xyz, 7, izn1);
	Vector3dToFMatrix(v12, xyz, 8, izn1);

	//zone 3
	Vector3dToFMatrix(v3, xyz, 1, izn2);
	Vector3dToFMatrix(v13, xyz, 2, izn2);
	Vector3dToFMatrix(v123, xyz, 3, izn2);
	Vector3dToFMatrix(v23, xyz, 4, izn2);
	Vector3dToFMatrix(v3, xyz, 5, izn2);
	Vector3dToFMatrix(v13, xyz, 6, izn2);
	Vector3dToFMatrix(v123, xyz, 7, izn2);
	Vector3dToFMatrix(v23, xyz, 8, izn2);

	for (int iz=izn; iz<=3; iz++){
		MV3 mat=vertex(nzsti(iz));
        mesh8zn(mat,ixstr,ixend,iystr,iyend,izstr,izend,xyz,iz,itype);
	}
}
Beispiel #22
0
void  FluxBC::
setupInterpolation(const int numberOfOutputComponents /*=1 */)
  // sets up interpolation of bc id = idFluxBoundary
{
  //printf("FluxBC::applyBoundaryCondition called...\n");

  assert( pCg     != NULL ); CompositeGrid &cg          = *pCg;
  assert( pInterp != NULL ); Interpolant   &interp      = *pInterp;
  assert( pOp     != NULL ); CompositeGridOperators &op = *pOp;

  printf("***FluxBC::setupInterpolation: numComponents %d\n",
	 numberOfOutputComponents);

  //..interpolate in a two step process: 
  //   Collect data:
  //    *Step 1: setupInterpolation:
  //    (1) allocate the start/stop index arrays [ngrids][naxis][nsides]
  //    (2) loop through grids/edges; compute # points & collect xyz
  //    (3) form long xyzInterp array & set pointers to it

  //    *Step 2: applyBoundaryCondition -- see the next subroutine
  
  timerInterpSetupCode = getCPU();

  const int nGrids= cg.numberOfComponentGrids(); //shorthand
  const int nAxes = cg.numberOfDimensions();
  const int nSides= 2;

  // (1) allocate 
  edgeStart.redim(nGrids,nAxes,nSides);
  edgeEnd.redim(nGrids,nAxes,nSides);
  isInterpolatedEdge.redim(nGrids,nAxes,nSides);
  edgeCoords.redim(nGrids,nAxes,nSides);
  int totalNumberOfInterpolationPoints=0; //local counter, global count in xyzInterpolate

#define checkdim(X,n0,n1,n2) ( (n0<=X.size(0)) && (n1<=X.size(1)) && (n2<=X.size(2)))


  // (2) collect local xyz edge coordinates
  for ( int ig=0; ig< cg.numberOfComponentGrids(); ++ig ) {
    MappedGrid & mg = cg[ig];
    
    Index Ib1,Ib2,Ib3;
    Index Ig1,Ig2,Ig3;
    Index All;
    
    for( int axis=0; axis<mg.numberOfDimensions(); axis++ ) {
      for( int side=0; side<=1; side++ ) {
	edgeStart(ig,axis,side) = -1;
	edgeEnd(ig,axis,side)   = -1;

	isInterpolatedEdge(ig, axis,side) = false;
	if( mg.boundaryCondition()(side,axis) == idFluxBoundary  ) {
	  isInterpolatedEdge(ig,axis,side) = true;
	  getBoundaryIndex(mg.gridIndexRange(),side,axis,Ib1,Ib2,Ib3);
	  //getGhostIndex(mg.gridIndexRange(),side,axis,Ig1,Ig2,Ig3);
	  //const realArray &zz=mg.vertex();
	  int zaxis        =axis3;
	  if (nAxes==2) zaxis=axis2; // to make sure we don't seg.fault
	  const realArray &xb  = mg.vertex()(Ib1,Ib2,Ib3, axis1);
	  const realArray &yb  = mg.vertex()(Ib1,Ib2,Ib3, axis2);
	  const realArray &zb  = mg.vertex()(Ib1,Ib2,Ib3, zaxis);
	  
	  int axisLength[3]={xb.getLength(axis1),xb.getLength(axis2),xb.getLength(axis3)};
	  int nInterpPoints= axisLength[axis1]*axisLength[axis2];
	  if (cg.numberOfDimensions()==3) nInterpPoints = nInterpPoints* axisLength[axis3];
	  
	  //realArray xyInt( Ib1,Ib2,Ib3, nAxes );
	  edgeCoords(ig,axis,side).redim( Ib1,Ib2,Ib3, nAxes );
	  realArray &xyz = edgeCoords(ig,axis,side); //shorthand
	  xyz(All, All, All, axis1) = xb;
	  xyz(All, All, All, axis2) = yb;
	  if( nAxes == 3) {
	    xyz(All, All, All, axis3) = zb;
	  }
	  xyz.reshape(nInterpPoints, nAxes);
	  totalNumberOfInterpolationPoints += nInterpPoints;

	  //printf("..On (grid %d, axis %d,side %d); ",  ig,axis,side);
	  //printf("passing in xyz array of dimensions [%d, %d], ntotal=%d\n",
	  //	 edgeCoords(ig,axis,side).getLength(0), 
	  //	 edgeCoords(ig,axis,side).getLength(1), totalNumberOfInterpolationPoints);
	} // end if ibc==fluxBoundaryID
      }// end for side
    }//end for axis
  }//end for ig

  // (3) form long xyzInterp array & set start/end indices
  xyzInterpolate.redim(totalNumberOfInterpolationPoints, nAxes );
  //const int nComponents=1; //set bcs one component at a time for now.
  valuesInterpolate.redim(totalNumberOfInterpolationPoints, 
			  numberOfOutputComponents );
  valuesInterpolate=-981.;
  ignoreGrid.redim(totalNumberOfInterpolationPoints);
  xyzInterpolate=-99;
  ignoreGrid=-1;
  int iNextStart=0;
  for (int ig=0; ig< nGrids; ++ig ) {
    for( int axis=0; axis<nAxes; ++axis ) {
      for( int side=0; side<nSides; ++side ) {
	if( isInterpolatedEdge(ig,axis,side) ) {
	  //printf("--grid %3d, axis %d, side %d:\n", ig,axis,side);
	  realArray &xyz          = edgeCoords(ig,axis,side); //shorthand
	  const int nInterpPoints = xyz.getLength(0);	  
	  const int iThisEnd      = iNextStart+nInterpPoints-1;
	  edgeStart(ig,axis,side) = iNextStart;
	  edgeEnd(ig,axis,side)   = iThisEnd;

	  Range dims(0,nAxes-1);
	  Range subset(iNextStart,iThisEnd);

#if 0  //debug
	  std::string namexyz=          "xyz              ";
	  std::string namexyzreshape=   "xyz reshaped     ";
	  std::string namexyzInterp=    "xyzInterpolate   ";
	  std::string namexyzInterpSub= "xyzInterp(sub)   ";
	  std::string subsetname=       "range subset     ";
	  std::string dimsname=         "range dims       ";
	  printBaseBound(namexyz, xyz);
	  printBaseBound(subsetname, subset);
	  printBaseBound(dimsname, dims);
#endif
	  xyz.reshape(subset,dims);

#if 0 //debug
	  printBaseBound(namexyzreshape, xyz);
	  printBaseBound(namexyzInterp, xyzInterpolate);fflush(0);
	  printBaseBound(namexyzInterpSub, xyzInterpolate(subset,dims));fflush(0);
#endif

	  xyzInterpolate(subset, dims) = xyz;  //interp. points for this edge
	  ignoreGrid(subset)           = ig;   //do not interp 'xyz' from grid =ig

	  iNextStart += nInterpPoints;
	}
      }
    }
  }
  interpolator. buildInterpolationInfo(  xyzInterpolate, cg, ignoreGrid );
  timerInterpSetupCode = getCPU() - timerInterpSetupCode;

  //..CHECK -- if some 'ignoreGrid(index)' items were not set==> skipped some = problem
  printf("Checking 'ignoreGrid'...\n");
  bool igok=true;
  for(int i=0; i<totalNumberOfInterpolationPoints; ++i ) {
    int ig=ignoreGrid(i);
    if( ig<0 ) {
      printf("..bug: ignoreGrid[%5d] = %3d\n", i, ig);
      igok=false;
    }
  }	 
  printf("--> ignoreGrid is "); 
  if( igok ) printf("OK\n");    //covered all items
  else       printf("NOT OK\n");//skipped some=problem

}
Beispiel #23
0
void MblkGeometry::buildSShellGridOnPatch(
   const hier::Patch& patch,
   const hier::Box& domain,
   const int xyz_id,
   const int level_number,
   const int block_number)
{

   bool xyz_allocated = patch.checkAllocated(xyz_id);
   if (!xyz_allocated) {
      TBOX_ERROR("xyz data not allocated" << std::endl);
      //patch.allocatePatchData(xyz_id);
   }

   std::shared_ptr<pdat::NodeData<double> > xyz(
      SAMRAI_SHARED_PTR_CAST<pdat::NodeData<double>, hier::PatchData>(
         patch.getPatchData(xyz_id)));

   TBOX_ASSERT(xyz);

   if (d_dim == tbox::Dimension(3)) {

      const hier::Index ifirst = patch.getBox().lower();
      const hier::Index ilast = patch.getBox().upper();
      hier::IntVector nghost_cells = xyz->getGhostCellWidth();

      //int imin = ifirst(0);
      //int imax = ilast(0)  + 1;
      //int jmin = ifirst(1);
      //int jmax = ilast(1)  + 1;
      //int kmin = ifirst(2);
      //int kmax = ilast(2)  + 1;
      //int nx   = imax - imin + 1;
      //int ny   = jmax - jmin + 1;
      //int nxny = nx*ny;

      int nd_imin = ifirst(0) - nghost_cells(0);
      int nd_imax = ilast(0) + 1 + nghost_cells(0);
      int nd_jmin = ifirst(1) - nghost_cells(1);
      int nd_jmax = ilast(1) + 1 + nghost_cells(1);
      int nd_kmin = ifirst(2) - nghost_cells(2);
      int nd_kmax = ilast(2) + 1 + nghost_cells(2);
      int nd_nx = nd_imax - nd_imin + 1;
      int nd_ny = nd_jmax - nd_jmin + 1;
      int nd_nxny = nd_nx * nd_ny;

      double* x = xyz->getPointer(0);
      double* y = xyz->getPointer(1);
      double* z = xyz->getPointer(2);

      bool found = false;

      int nrad = (domain.upper(0) - domain.lower(0) + 1);
      int nth = (domain.upper(1) - domain.lower(1) + 1);
      int nphi = (domain.upper(2) - domain.lower(2) + 1);

      /*
       * If its a solid shell, its a single block and dx = dr, dth, dphi
       */
      if (d_sshell_type == "SOLID") {

         d_dx[level_number][block_number][0] = (d_sshell_rmax - d_sshell_rmin) / (double)nrad;
         d_dx[level_number][block_number][1] =
            2.0 * tbox::MathUtilities<double>::Abs(d_sangle_thmin)
            / (double)nth;
         d_dx[level_number][block_number][2] =
            2.0 * tbox::MathUtilities<double>::Abs(d_sangle_thmin)
            / (double)nphi;

         //
         // step in a radial direction in x and set y and z appropriately
         // for a solid angle we go -th to th and -phi to phi
         //
         for (int k = nd_kmin; k <= nd_kmax; ++k) {
            for (int j = nd_jmin; j <= nd_jmax; ++j) {

               double theta = d_sangle_thmin + j * d_dx[level_number][block_number][1]; // dx used for dth
               double phi = d_sangle_thmin + k * d_dx[level_number][block_number][2];

               double xface = cos(theta) * cos(phi);
               double yface = sin(theta) * cos(phi);
               double zface = sin(phi);

               for (int i = nd_imin; i <= nd_imax; ++i) {

                  int ind = POLY3(i,
                        j,
                        k,
                        nd_imin,
                        nd_jmin,
                        nd_kmin,
                        nd_nx,
                        nd_nxny);

                  double r = d_sshell_rmin + d_dx[level_number][block_number][0] * (i);

                  double xx = r * xface;
                  double yy = r * yface;
                  double zz = r * zface;

                  x[ind] = xx;
                  y[ind] = yy;
                  z[ind] = zz;
               }
            }
         }

         found = true;
      }

      /*
       * If its an octant problem, then its got multiple (three) blocks
       */
      if (d_sshell_type == "OCTANT") {

         double drad = (d_sshell_rmax - d_sshell_rmin) / nrad;

         //
         // as in the solid angle we go along a radial direction in
         // x setting y and z appropriately, but here we have logic for
         // the block we are in.  This is contained in the dispOctant.m
         // matlab code.
         //
         for (int k = nd_kmin; k <= nd_kmax; ++k) {
            for (int j = nd_jmin; j <= nd_jmax; ++j) {

               //
               // compute the position on the unit sphere for our radial line
               //
               double xface, yface, zface;
               computeUnitSphereOctant(block_number, nth, j, k,
                  &xface, &yface, &zface);

               for (int i = nd_imin; i <= nd_imax; ++i) {
                  int ind = POLY3(i,
                        j,
                        k,
                        nd_imin,
                        nd_jmin,
                        nd_kmin,
                        nd_nx,
                        nd_nxny);

                  double r = d_sshell_rmin + drad * (i);

                  double xx = r * xface;
                  double yy = r * yface;
                  double zz = r * zface;

                  x[ind] = xx;
                  y[ind] = yy;
                  z[ind] = zz;
               }
            }
         }
         found = true;
      }

      if (!found) {
         TBOX_ERROR(
            d_object_name << ": "
                          << "spherical shell nodal positions for "
                          << d_sshell_type
                          << " not found" << std::endl);
      }

   }

}
void Nodes_method::run(Program_options & options, ostream & output)
{
  ofstream os; //for writing to *.plt files
  string pltfile; //name of plotfile being written
  string confile; //name of configuration of electrons to be  being written
  double max_value,min_value;
  int count;
  Array1 <doublevar> xyz(3), xyz2(3),
    resolution_array(3); //position of electron "in" MO
  Array1 <int> D_array1(3); //dummy array1
  Array2 <doublevar> oldpos(mywalker->electronSize(),3);
  Array1 <doublevar> tmp(3);
  D_array1=0; //sets all 3 components to 0. use as counter for gridpoints
  
  
  D_array1(0)=roundoff((minmax(1)-minmax(0))/resolution);
  D_array1(1)=roundoff((minmax(3)-minmax(2))/resolution);
  D_array1(2)=roundoff((minmax(5)-minmax(4))/resolution);

  resolution_array(0)=(minmax(1)-minmax(0))/(D_array1(0)-1);  
  resolution_array(1)=(minmax(3)-minmax(2))/(D_array1(1)-1);
  resolution_array(2)=(minmax(5)-minmax(4))/(D_array1(2)-1);

  Array2 <doublevar> grid(plots.GetSize(),D_array1(0)*D_array1(1)*D_array1(2));
  Wf_return wfvals(wf->nfunc(), 2); //where wfval fist index labels 
    //wf number ie. ground state
    // excited state and so on, and second label is for two values, sign and log(wf).

 //scan electron positions
  cout << "Using these electron positions:"<<endl;
  for(int i=0; i<mywalker->electronSize(); i++){
    mywalker->getElectronPos(i, tmp);
    cout.precision(5);
    cout.width(8);
    cout <<i+1<<" "<<tmp(0)<<" "<<tmp(1)<<" "<<tmp(2)<<endl;
    for (int d=0;d<3;d++)
      oldpos(i,d)=tmp(d);
    //    cout << "pos " << oldpos(i,0) << "   " << oldpos(i,1) << "   " << oldpos(i,2)
    //     << endl;
  }

  //generate .xyz file for gOpenMol to view coordinates
  pltfile=options.runid + ".xyz";
  os.open(pltfile.c_str());
  cout<<"writing to "<<pltfile<<endl;
  vector <string> atomlabels;
  sysprop->getAtomicLabels(atomlabels);
  os<<atomlabels.size()+mywalker->electronSize()<<endl;
  os<<endl;
  
  int spin_up=sysprop->nelectrons(0);
  //cout << "Up electrons "<<spin_up<<endl;

  
  for(unsigned int i=0; i<atomlabels.size(); i++){
    Array1 <doublevar> pos(3);
    mywalker->getIonPos(i, pos);
    os<<atomlabels[i] <<" "<< pos(0)
    <<" "<<pos(1)
    <<" "<< pos(2)<<endl;
  }
  for(int j=0; j<mywalker->electronSize(); j++){
    if (j<spin_up) os<<"Eu";
    else os<<"Ed";
        // mywalker->getElectronPos(j, pos);
       os<<" "<< oldpos(j,0)<<" "<<oldpos(j,1) <<" "<< oldpos(j,2)<<endl;
  }
  os.close();
  

  if (!doublemove) {
    //calculate value of each molecular orbital at each grid point and store in an Array1
    // grid values with x=fastest running variable, and z=slowest

    cout<<"calculating "<<D_array1(0)*D_array1(1)*D_array1(2)
        <<" grid points"<<endl;
    cout<<"for "<< plots.GetDim(0) <<" 3D projections of wavefunction"<<endl;
    count=0;
    xyz(0)=minmax(0);
    xyz(1)=minmax(2);
    xyz(2)=minmax(4); //init elec probe to xmin ymin zmin
    //Array1 <doublevar> oldpos(3)

  
  
    for(int i=0; i<plots.GetSize(); i++){
      cout.width(3);
      cout <<"============================="<<plots(i)
           <<"=============================="
           <<endl;
      count=0;
      for(int xx=0; xx<D_array1(0);xx++){
	xyz(0)=minmax(0)+xx*resolution_array(0);  //move forward on x axis one resolution unit
	max_value=min_value=0.0;
	cout << "x ";
        cout.precision(5);
        cout.width(8);
        cout<< xyz(0);
	for(int yy=0; yy<D_array1(1);yy++){
          xyz(1)=minmax(2)+yy*resolution_array(1);  //move forward on y axis one resolution unit
	  for(int zz=0;zz<D_array1(2);zz++){
	    xyz(2)=minmax(4)+zz*resolution_array(2); //move forward on z axis one resolution unit
	    // mywalker->getElectronPos(plots(i), oldpos);
            mywalker->setElectronPos(plots(i)-1,xyz); //move elec#plots(i) to point specified by xyz
            wf->updateVal(wfdata, mywalker); //update wfdata
            wf->getVal(wfdata, 0, wfvals); //get wf value
            const doublevar cutoff=15;
            if(wfvals.amp(0,0)<cutoff) { 
              grid(i,count)=wfvals.sign(0)*exp(wfvals.amp(0,0));
            }
            else { //cut off the maximum value output so that there aren't overflow errors
              grid(i,count)=wfvals.sign(0)*exp(cutoff);
            }
            //grid(i,count)=exp(2.0*wfvals(0,1));//!square of wavefunction
            if (grid(i,count)>max_value) max_value=grid(i,count);
            if (grid(i,count)<min_value) min_value=grid(i,count);
            //  cout << "grid " << grid(i,count)<< " " << xyz(0) << endl;
	    count++; //index for cycling through grid points
          }
        }
        cout.setf(ios::scientific| ios:: showpos);
        cout <<", max. value "<<max_value<<", min. value "<<min_value<< endl;
        cout.unsetf(ios::scientific| ios:: showpos);
        
      }
      mywalker->setElectronPos(plots(i)-1, oldpos(plots(i)-1));
    }
  
  
    //Loop through and generate plot files for each orbital requested
    if(plots.GetSize()<=0)
      error("Number of requested plots is not a positive number");
    cout<<"saving data for "<<plots.GetSize()<<" 3D projections of wavefunction"<<endl;
    for(int i=0; i<plots.GetSize(); i++)
      {
        //output to file with orbital number in it
        char strbuff[40];
        sprintf(strbuff, "%d", plots(i));
        confile=pltfile = options.runid;
        confile += ".orb.";
        pltfile += ".orb.";
        pltfile += strbuff;
        confile += strbuff;
        pltfile += ".cube"; /*FIGURE OUT HOW TO CONVERT INT TO STRING*/
        confile += ".xyz";
        
        os.open(pltfile.c_str());
        cout<<"writing to "<<pltfile<<endl;

        os << "QWalk nodes output\n";
        os << "Wavefunction single scan with " <<   plots(i) <<" electron"<<endl;
        int natoms=sysprop->nIons();
        os << "  " << natoms+ mywalker->electronSize()-1 << "   " << minmax(0) << "   "
          << minmax(2) << "   " << minmax(4) << endl;
        os << D_array1(0) << "   " << resolution_array(0) << "  0.0000   0.0000" << endl;
        os << D_array1(1) << "   0.0000   " << resolution_array(1) << "  0.0000" << endl;
        os << D_array1(2) << "   0.0000    0.0000    " << resolution_array(2) << endl;
        Array1 <doublevar> pos(3);
        for(int at=0; at< natoms; at++) {
          mywalker->getIonPos(at,pos);
          os << "   " << mywalker->getIonCharge(at) << "   0.0000    " << pos(0) 
            <<"    " << pos(1) << "   " << pos(2) << endl;
        }
        for(int j=0; j<mywalker->electronSize(); j++){
          if (j!=plots(i)-1){
            if (j<spin_up) os<<"     3   0.0000    ";
            else os<<"     3     0.0000    ";
            os<< oldpos(j,0)<<"   "<<oldpos(j,1)<<"   "<< oldpos(j,2)<<endl;
          }
        }
        os.setf(ios::scientific);
        for(int j=0; j< D_array1(0)*D_array1(1)*D_array1(2); j++) {
          os <<setw(16)<<setprecision(8)<<grid(i,j);
          if(j%6 ==5) os << endl;
        }
        os << endl;
        os.unsetf(ios::scientific);
        os<<setprecision(6);
        os.close();

	
        /*
	  old plt file plots
        // http://www.csc.fi/gopenmol/developers/plt_format.phtml
        os<<"3 "; //rank=3 always
        os<<"2\n"; //dummy variable => "Orbital/density surface"
        //number of grid points for x, y, & z direction
        os <<D_array1(2)<<" "<<D_array1(1)<<" "<<D_array1(0)<<endl;
        os <<minmax(4)<<" "<<minmax(5)<<" "<<minmax(2)<<" "<<minmax(3)
           <<" "<<minmax(0)<<" "<<minmax(1)<<endl;
        
        for(int j=0; j<(D_array1(0)*D_array1(1)*D_array1(2)); j++)
          os<<grid(i,j)<<endl;
        os.close();
        
        os.open(confile.c_str());
        cout<<"writing to "<<confile<<endl;
        Array1 <doublevar> pos(3);
        sysprop->getAtomicLabels(atomlabels);
        os<<atomlabels.size()+ mywalker->electronSize()-1 <<endl;
        os << endl;
        for(unsigned int j=0; j<atomlabels.size();j++){
          mywalker->getIonPos(j, pos);
          os<<atomlabels[j] <<" "<< pos(0)
            <<" "<<pos(1)
            <<" "<< pos(2)<<endl;
        }
        for(int j=0; j<mywalker->electronSize(); j++){
          if (j!=plots(i)-1){
            if (j<spin_up) os<<"Eu";
            else os<<"Ed";
            // mywalker->getElectronPos(j, pos);
            os<<" "<< oldpos(j,0)<<" "<<oldpos(j,1)
              <<" "<< oldpos(j,2)<<endl;
          }
        }
        os.close();   
	*/
	
      }
    
  }
  else {
    cout << "Using translation vector(s): "<<endl;
    for(int i=0;i<dxyz.GetDim(0);i++)    
      cout<<"( "<<dxyz(i,0)<<" , "<<dxyz(i,1)<<" , "<<dxyz(i,2)<<" )"<<endl;

    for(int i=0; i<plots.GetSize(); i=i+2){
      count=0;
      xyz(0)=minmax(0);
      xyz(1)=minmax(2);
      xyz(2)=minmax(4); //init elec probe to xmin ymin zmin
      //Array1 <doublevar> oldpos(3)
      cout.width(3);
      cout <<"============================="<<plots(i)<<" and "<<plots(i+1)
           <<"=============================="
           <<endl;
      for(int xx=0; xx<D_array1(0);xx++){
        max_value=min_value=0.0;
        xyz(0)=minmax(0)+xx*resolution_array(0); 
        xyz2(0)=xyz(0)+dxyz(i/2,0);  
        cout << "x ";
        cout.precision(5);
        cout.width(8);
        cout<< xyz(0);
        for(int yy=0; yy<D_array1(1);yy++){
          xyz(1)=minmax(2)+yy*resolution_array(1); 
          xyz2(1)=xyz(1)+dxyz(i/2,1);
          for(int zz=0;zz<D_array1(2);zz++){
            xyz(2)=minmax(4)+zz*resolution_array(2); 
            xyz2(2)=xyz(2)+dxyz(i/2,2);
            // mywalker->getElectronPos(plots(i), oldpos);
            mywalker->setElectronPos(plots(i)-1,xyz);//move elec#plots(i) 
            //to point specified by xyz
            mywalker->setElectronPos(plots(i+1)-1,xyz2);//move elec#plots(i) 
            //to point specified by xyz
            wf->updateVal(wfdata, mywalker); //update wfdata
            wf->getVal(wfdata, 0, wfvals); //get wf value
            grid(i,count)=wfvals.sign(0)*exp(wfvals.amp(0,0));
            //grid(i,count)=exp(2.0*wfvals(0,1));//!square of wavefunction
            //  cout << "grid " << grid(i,count)<< " " << xyz(0) << endl;
            if (grid(i,count)>max_value) max_value=grid(i,count);
            if (grid(i,count)<min_value) min_value=grid(i,count);
            
            count++; //index for cycling through grid points
          }
        }
        cout.setf(ios::scientific| ios:: showpos);
        cout <<", max. value "<<max_value<<", min. value "<<min_value<< endl;
        cout.unsetf(ios::scientific| ios:: showpos);
      }
      
      mywalker->setElectronPos(plots(i)-1, oldpos(plots(i)-1));
      mywalker->setElectronPos(plots(i+1)-1, oldpos(plots(i+1)-1)); 
    }
    
    //Loop through and generate plot files for each orbital requested
    if(plots.GetSize()<=0)
      error("Number of requested plots is not a positive number");
    cout<<"saving data for "<<plots.GetSize()<<" 3D projections of wavefunction"<<endl;
    for(int i=0; i<plots.GetSize(); i=i+2)
      {
        char strbuff2[40],strbuff[40];
        //output to file with orbital number in it
        sprintf(strbuff, "%d", plots(i));
        sprintf(strbuff2, "%d", plots(i+1));
        confile=pltfile = options.runid;
        confile += ".orb.";
        pltfile += ".orb.";
        pltfile += strbuff;
        confile += strbuff;
        pltfile += "with";
        confile += "with";
        pltfile += strbuff2;
        confile += strbuff2;
        
        pltfile += ".cube"; /*FIGURE OUT HOW TO CONVERT INT TO STRING*/
        confile += ".xyz";
        
        os.open(pltfile.c_str());
        cout<<"writing to "<<pltfile<<endl;
	os << "GOS nodes output\n";
	os << "Wave function double scan with "<<   plots(i) <<" & "<<plots(i+1)<<" electrons"<< endl;
        int natoms=sysprop->nIons();
        os << "  " << natoms + mywalker->electronSize()-2 << "   " << minmax(0) << "   "
           << minmax(2) << "   " << minmax(4) << endl;
        os << D_array1(0) << "   " << resolution_array(0) << "  0.0000   0.0000" << endl;
        os << D_array1(1) << "   0.0000   " << resolution_array(1) << "  0.0000" << endl;
        os << D_array1(2) << "   0.0000    0.0000    " << resolution_array(2) << endl;
        Array1 <doublevar> pos(3);
        for(int at=0; at< natoms; at++) {
          mywalker->getIonPos(at,pos);
          os << "   " << mywalker->getIonCharge(at) << "   0.0000    " << pos(0) 
             <<"    " << pos(1) << "   " << pos(2) << endl;
        }
        for(int j=0; j<mywalker->electronSize(); j++){
          if ((j!=plots(i)-1)&&(j!=plots(i+1)-1)){
            if (j<spin_up) os<<"    3    0.0000    ";
            else os<<"    3    0.0000   ";
            os<< oldpos(j,0)<<"    "<<oldpos(j,1)<<"    "<< oldpos(j,2)<<endl;
          }
        }
	os.setf(ios::scientific);
        for(int j=0; j< D_array1(0)*D_array1(1)*D_array1(2); j++) {
          os << setw(16) << setprecision(8) << grid(i,j);
          if(j%6 ==5) os << endl;
        }
        os << endl;
	os.unsetf(ios::scientific);
	os<<setprecision(6);
        os.close();

        /*
          old plot to plt file version
        // http://www.csc.fi/gopenmol/developers/plt_format.phtml
        os<<"3 "; //rank=3 always
        os<<"2\n"; //dummy variable => "Orbital/density surface"
        //number of grid points for x, y, & z direction
        os <<D_array1(2)<<" "<<D_array1(1)<<" "<<D_array1(0)<<endl;
        os <<minmax(4)<<" "<<minmax(5)<<" "<<minmax(2)<<" "<<minmax(3)
           <<" "<<minmax(0)<<" "<<minmax(1)<<endl;
        
        for(int j=0; j<(D_array1(0)*D_array1(1)*D_array1(2)); j++)
          os<<grid(i,j)<<endl;
        os.close();
        
        os.open(confile.c_str());
        cout<<"writing to "<<confile<<endl;
        Array1 <doublevar> pos(3);
        sysprop->getAtomicLabels(atomlabels);
        os<<atomlabels.size()+ mywalker->electronSize()-2 <<endl;
        os << endl;
        for(unsigned int j=0; j<atomlabels.size();j++){
          mywalker->getIonPos(j, pos);
          os<<atomlabels[j] <<" "<< pos(0)
            <<" "<<pos(1)
            <<" "<< pos(2)<<endl;
        }
        for(int j=0; j<mywalker->electronSize(); j++){
          if ((j!=plots(i)-1)&&(j!=plots(i+1)-1)){
            if (j<spin_up) os<<"Eu";
            else os<<"Ed";
            // mywalker->getElectronPos(j, pos);
            os<<" "<< oldpos(j,0)<<" "<<oldpos(j,1)
              <<" "<< oldpos(j,2)<<endl;
          }
        }
        os.close();    
        */
    
      } 
  }
  cout <<"End of Nodes Method"<<endl;  
}
Beispiel #25
0
void
RigidArmNode :: computeMasterContribution(std::map< DofIDItem, IntArray > &masterDofID, 
                                          std::map< DofIDItem, FloatArray > &masterContribution)
{
#if 0 // original implementation without support of different LCS in slave and master
    int k;
    IntArray R_uvw(3), uvw(3);
    FloatArray xyz(3);
    int numberOfMasterDofs = masterNode->giveNumberOfDofs();
    //IntArray countOfMasterDofs((int)masterDofID.size());

    // decode of masterMask
    uvw.at(1) = this->dofidmask->findFirstIndexOf(R_u);
    uvw.at(2) = this->dofidmask->findFirstIndexOf(R_v);
    uvw.at(3) = this->dofidmask->findFirstIndexOf(R_w);

    xyz.beDifferenceOf(*this->giveCoordinates(), *masterNode->giveCoordinates());

    if ( hasLocalCS() ) {
        // LCS is stored as global-to-local, so LCS*xyz_glob = xyz_loc
        xyz.rotatedWith(* this->localCoordinateSystem, 'n');
    }

    for ( int i = 1; i <= this->dofidmask->giveSize(); i++ ) {
        Dof *dof = this->giveDofWithID(dofidmask->at(i));
        DofIDItem id = dof->giveDofID();
        masterDofID [ id ].resize(numberOfMasterDofs);
        masterContribution [ id ].resize(numberOfMasterDofs);
        R_uvw.zero();

        switch ( masterMask.at(i) ) {
        case 0: continue;
            break;
        case 1:
            if ( id == D_u ) {
                if ( uvw.at(2) && masterMask.at( uvw.at(2) ) ) {
                    R_uvw.at(3) =  ( ( int ) R_v );
                }

                if ( uvw.at(3) && masterMask.at( uvw.at(3) ) ) {
                    R_uvw.at(2) = -( ( int ) R_w );
                }
            } else if ( id == D_v ) {
                if ( uvw.at(1) && masterMask.at( uvw.at(1) ) ) {
                    R_uvw.at(3) = -( ( int ) R_u );
                }

                if ( uvw.at(3) && masterMask.at( uvw.at(3) ) ) {
                    R_uvw.at(1) =  ( ( int ) R_w );
                }
            } else if ( id == D_w ) {
                if ( uvw.at(1) && masterMask.at( uvw.at(1) ) ) {
                    R_uvw.at(2) =  ( ( int ) R_u );
                }

                if ( uvw.at(2) && masterMask.at( uvw.at(2) ) ) {
                    R_uvw.at(1) = -( ( int ) R_v );
                }
            }

            break;
        default:
            OOFEM_ERROR("unknown value in masterMask");
        }

        //k = ++countOfMasterDofs.at(i);
        k = 1;
        masterDofID [ id ].at(k) = ( int ) id;
        masterContribution [ id ].at(k) = 1.0;

        for ( int j = 1; j <= 3; j++ ) {
            if ( R_uvw.at(j) != 0 ) {
                int sign = R_uvw.at(j) < 0 ? -1 : 1;
                //k = ++countOfMasterDofs.at(i);
                k++;
                masterDofID [ id ].at(k) = sign * R_uvw.at(j);
                masterContribution [ id ].at(k) = sign * xyz.at(j);
            }
        }
        masterDofID [ id ].resizeWithValues(k);
        masterContribution [ id ].resizeWithValues(k);
    }
#else
    // receiver lcs stored in localCoordinateSystem
    // (this defines the transformation from global to local)
    FloatArray xyz(3);
    FloatMatrix TG2L(6,6); // receiver global to receiver local
    FloatMatrix TR(6,6); // rigid arm transformation between receiver global DOFs and Master global DOFs
    FloatMatrix TMG2L(6,6); // master global to local
    FloatMatrix T(6,6); // full transformation for all dofs
    IntArray fullDofMask = {D_u, D_v, D_w, R_u, R_v, R_w};
    bool hasg2l = this->computeL2GTransformation(TG2L, fullDofMask);
    bool mhasg2l = masterNode->computeL2GTransformation(TMG2L, fullDofMask);

    xyz.beDifferenceOf(*this->giveCoordinates(), *masterNode->giveCoordinates());
    
    TR.beUnitMatrix();
    TR.at(1,5) =  xyz.at(3);
    TR.at(1,6) = -xyz.at(2);
    TR.at(2,4) = -xyz.at(3);
    TR.at(2,6) =  xyz.at(1);
    TR.at(3,4) =  xyz.at(2);
    TR.at(3,5) = -xyz.at(1);

    if (hasg2l && mhasg2l) {
      FloatMatrix h; 
      h.beTProductOf(TG2L, TR);  // T transforms global master DOfs to local dofs;
      T.beProductOf(h,TMG2L);    // Add transformation to master local c.s.
    } else if (hasg2l) {
      T.beTProductOf(TG2L, TR);  // T transforms global master DOfs to local dofs;
    } else if (mhasg2l) {
      T.beProductOf(TR,TMG2L);   // Add transformation to master local c.s.
    } else {
      T = TR;
    }
    
    // assemble DOF weights for relevant dofs
    for ( int i = 1; i <= this->dofidmask->giveSize(); i++ ) {
      Dof *dof = this->giveDofWithID(dofidmask->at(i));
      DofIDItem id = dof->giveDofID();
      masterDofID [ id ] = *dofidmask;
      masterContribution [ id ].resize(dofidmask->giveSize());
      
      for (int j = 1; j <= this->dofidmask->giveSize(); j++ ) {
        masterContribution [ id ].at(j) = T.at(id, dofidmask->at(j));
      }
    }

#endif

}
Beispiel #26
0
xyz_t frgb_to_yuv(frgb_t pv)
{
	return xyz( frgb_to_yuv_y(pv), frgb_to_yuv_u(pv), frgb_to_yuv_v(pv) );
}
Beispiel #27
0
void VTKIO::read (const std::string & name)
{
  // This is a serial-only process for now;
  // the Mesh should be read on processor 0 and
  // broadcast later
  libmesh_assert_equal_to (MeshOutput<MeshBase>::mesh().processor_id(), 0);

  // Keep track of what kinds of elements this file contains
  elems_of_dimension.clear();
  elems_of_dimension.resize(4, false);

  // Use a typedef, because these names are just crazy
  typedef vtkSmartPointer<vtkXMLUnstructuredGridReader> MyReader;
  MyReader reader = MyReader::New();

  // Pass the filename along to the reader
  reader->SetFileName(name.c_str());

  // Force reading
  reader->Update();

  // read in the grid
  _vtk_grid = reader->GetOutput();

  // Get a reference to the mesh
  MeshBase & mesh = MeshInput<MeshBase>::mesh();

  // Clear out any pre-existing data from the Mesh
  mesh.clear();

  // Get the number of points from the _vtk_grid object
  const unsigned int vtk_num_points = static_cast<unsigned int>(_vtk_grid->GetNumberOfPoints());

  // always numbered nicely so we can loop like this
  for (unsigned int i=0; i<vtk_num_points; ++i)
    {
      // add to the id map
      // and add the actual point
      double pnt[3];
      _vtk_grid->GetPoint(static_cast<vtkIdType>(i), pnt);
      Point xyz(pnt[0], pnt[1], pnt[2]);
      mesh.add_point(xyz, i);
    }

  // Get the number of cells from the _vtk_grid object
  const unsigned int vtk_num_cells = static_cast<unsigned int>(_vtk_grid->GetNumberOfCells());

  vtkSmartPointer<vtkGenericCell> cell = vtkSmartPointer<vtkGenericCell>::New();
  for (unsigned int i=0; i<vtk_num_cells; ++i)
    {
      _vtk_grid->GetCell(i, cell);

      // Get the libMesh element type corresponding to this VTK element type.
      ElemType libmesh_elem_type = _element_maps.find(cell->GetCellType());
      Elem * elem = Elem::build(libmesh_elem_type).release();

      // get the straightforward numbering from the VTK cells
      for (unsigned int j=0; j<elem->n_nodes(); ++j)
        elem->set_node(j) =
          mesh.node_ptr(cast_int<dof_id_type>(cell->GetPointId(j)));

      // then get the connectivity
      std::vector<dof_id_type> conn;
      elem->connectivity(0, VTK, conn);

      // then reshuffle the nodes according to the connectivity, this
      // two-time-assign would evade the definition of the vtk_mapping
      for (std::size_t j=0; j<conn.size(); ++j)
        elem->set_node(j) = mesh.node_ptr(conn[j]);

      elem->set_id(i);

      elems_of_dimension[elem->dim()] = true;

      mesh.add_elem(elem);
    } // end loop over VTK cells

  // Set the mesh dimension to the largest encountered for an element
  for (unsigned char i=0; i!=4; ++i)
    if (elems_of_dimension[i])
      mesh.set_mesh_dimension(i);

#if LIBMESH_DIM < 3
  if (mesh.mesh_dimension() > LIBMESH_DIM)
    libmesh_error_msg("Cannot open dimension "  \
                      << mesh.mesh_dimension()              \
                      << " mesh file when configured without "  \
                      << mesh.mesh_dimension()                  \
                      << "D support.");
#endif // LIBMESH_DIM < 3
}
void
RigidArmNode :: computeMasterContribution()
{
    int k, sign;
    IntArray R_uvw(3), uvw(3);
    FloatArray xyz(3);
    DofIDItem id;

    // decode of masterMask
    uvw.at(1) = this->findDofWithDofId(R_u);
    uvw.at(2) = this->findDofWithDofId(R_v);
    uvw.at(3) = this->findDofWithDofId(R_w);

    for ( int i = 1; i <= 3; i++ ) {
        xyz.at(i) = this->giveCoordinate(i) - masterNode->giveCoordinate(i);
    }

    if ( hasLocalCS() ) {
        // LCS is stored as global-to-local, so LCS*xyz_glob = xyz_loc
        xyz.rotatedWith(* this->localCoordinateSystem, 'n');
    }

    for ( int i = 1; i <= numberOfDofs; i++ ) {
        id = this->giveDof(i)->giveDofID();
        R_uvw.zero();

        switch ( masterMask.at(i) ) {
        case 0: continue;
            break;
        case 1:
            if ( id == D_u ) {
                if ( uvw.at(2) && masterMask.at( uvw.at(2) ) ) {
                    R_uvw.at(3) =  ( ( int ) R_v );
                }

                if ( uvw.at(3) && masterMask.at( uvw.at(3) ) ) {
                    R_uvw.at(2) = -( ( int ) R_w );
                }
            } else if ( id == D_v ) {
                if ( uvw.at(1) && masterMask.at( uvw.at(1) ) ) {
                    R_uvw.at(3) = -( ( int ) R_u );
                }

                if ( uvw.at(3) && masterMask.at( uvw.at(3) ) ) {
                    R_uvw.at(1) =  ( ( int ) R_w );
                }
            } else if ( id == D_w ) {
                if ( uvw.at(1) && masterMask.at( uvw.at(1) ) ) {
                    R_uvw.at(2) =  ( ( int ) R_u );
                }

                if ( uvw.at(2) && masterMask.at( uvw.at(2) ) ) {
                    R_uvw.at(1) = -( ( int ) R_v );
                }
            }

            break;
        default:
            _error("computeMasterContribution: unknown value in masterMask");
        }

        k = ++ this->countOfMasterDofs->at(i);
        this->masterDofID [ i - 1 ]->at(k) = ( int ) id;
        this->masterContribution [ i - 1 ]->at(k) = 1.0;

        for ( int j = 1; j <= 3; j++ ) {
            if ( R_uvw.at(j) != 0 ) {
                sign = R_uvw.at(j) < 0 ? -1 : 1;

                k = ++ this->countOfMasterDofs->at(i);
                this->masterDofID [ i - 1 ]->at(k) = sign * R_uvw.at(j);
                this->masterContribution [ i - 1 ]->at(k) = sign * xyz.at(j);
            }
        }
    }
}
Beispiel #29
0
void VTKIO::read (const std::string& name)
{
  // This is a serial-only process for now;
  // the Mesh should be read on processor 0 and
  // broadcast later
  libmesh_assert_equal_to (MeshOutput<MeshBase>::mesh().processor_id(), 0);

  // Keep track of what kinds of elements this file contains
  elems_of_dimension.clear();
  elems_of_dimension.resize(4, false);

#ifndef LIBMESH_HAVE_VTK
  libMesh::err << "Cannot read VTK file: " << name
	        << "\nYou must have VTK installed and correctly configured to read VTK meshes."
	        << std::endl;
  libmesh_error();

#else
  // Use a typedef, because these names are just crazy
  typedef vtkSmartPointer<vtkXMLUnstructuredGridReader> MyReader;
  MyReader reader = MyReader::New();

  // Pass the filename along to the reader
  reader->SetFileName( name.c_str() );

  // Force reading
  reader->Update();

  // read in the grid
  _vtk_grid = reader->GetOutput();
  // _vtk_grid->Update(); // FIXME: Necessary?

  // Get a reference to the mesh
  MeshBase& mesh = MeshInput<MeshBase>::mesh();

  // Clear out any pre-existing data from the Mesh
  mesh.clear();

  // Get the number of points from the _vtk_grid object
  const unsigned int vtk_num_points = static_cast<unsigned int>(_vtk_grid->GetNumberOfPoints());

  // always numbered nicely??, so we can loop like this
  // I'm pretty sure it is numbered nicely
  for (unsigned int i=0; i<vtk_num_points; ++i)
    {
      // add to the id map
      // and add the actual point
      double * pnt = _vtk_grid->GetPoint(static_cast<vtkIdType>(i));
      Point xyz(pnt[0], pnt[1], pnt[2]);
      Node* newnode = mesh.add_point(xyz, i);

      // Add node to the nodes vector &
      // tell the MeshData object the foreign node id.
      if (this->_mesh_data != NULL)
	this->_mesh_data->add_foreign_node_id (newnode, i);
    }

  // Get the number of cells from the _vtk_grid object
  const unsigned int vtk_num_cells = static_cast<unsigned int>(_vtk_grid->GetNumberOfCells());

  for (unsigned int i=0; i<vtk_num_cells; ++i)
    {
      vtkCell* cell = _vtk_grid->GetCell(i);
      Elem* elem = NULL;
      switch (cell->GetCellType())
	{
        case VTK_LINE:
          elem = new Edge2;
          break;
        case VTK_QUADRATIC_EDGE:
          elem = new Edge3;
          break;
        case VTK_TRIANGLE:
          elem = new Tri3();
          break;
        case VTK_QUADRATIC_TRIANGLE:
          elem = new Tri6();
          break;
        case VTK_QUAD:
          elem = new Quad4();
          break;
        case VTK_QUADRATIC_QUAD:
          elem = new Quad8();
          break;
#if VTK_MAJOR_VERSION > 5 || (VTK_MAJOR_VERSION == 5 && VTK_MINOR_VERSION > 0)
        case VTK_BIQUADRATIC_QUAD:
          elem = new Quad9();
          break;
#endif
	case VTK_TETRA:
	  elem = new Tet4();
	  break;
        case VTK_QUADRATIC_TETRA:
	  elem = new Tet10();
	  break;
	case VTK_WEDGE:
	  elem = new Prism6();
	  break;
        case VTK_QUADRATIC_WEDGE:
	  elem = new Prism15();
	  break;
        case VTK_BIQUADRATIC_QUADRATIC_WEDGE:
	  elem = new Prism18();
	  break;
	case VTK_HEXAHEDRON:
	  elem = new Hex8();
	  break;
	case VTK_QUADRATIC_HEXAHEDRON:
  	  elem = new Hex20();
	  break;
        case VTK_TRIQUADRATIC_HEXAHEDRON:
	  elem = new Hex27();
	  break;
	case VTK_PYRAMID:
	  elem = new Pyramid5();
	  break;
	default:
	  libMesh::err << "element type not implemented in vtkinterface " << cell->GetCellType() << std::endl;
	  libmesh_error();
          break;
	}

      // get the straightforward numbering from the VTK cells
      for (unsigned int j=0; j<elem->n_nodes(); ++j)
        elem->set_node(j) = mesh.node_ptr(cell->GetPointId(j));

      // then get the connectivity
      std::vector<dof_id_type> conn;
      elem->connectivity(0, VTK, conn);

      // then reshuffle the nodes according to the connectivity, this
      // two-time-assign would evade the definition of the vtk_mapping
      for (unsigned int j=0; j<conn.size(); ++j)
        elem->set_node(j) = mesh.node_ptr(conn[j]);

      elem->set_id(i);

      elems_of_dimension[elem->dim()] = true;

      mesh.add_elem(elem);
    } // end loop over VTK cells

  // Set the mesh dimension to the largest encountered for an element
  for (unsigned int i=0; i!=4; ++i)
    if (elems_of_dimension[i])
      mesh.set_mesh_dimension(i);

#if LIBMESH_DIM < 3
  if (mesh.mesh_dimension() > LIBMESH_DIM)
    {
      libMesh::err << "Cannot open dimension " <<
		      mesh.mesh_dimension() <<
		      " mesh file when configured without " <<
                      mesh.mesh_dimension() << "D support." <<
                      std::endl;
      libmesh_error();
    }
#endif

#endif // LIBMESH_HAVE_VTK
}
Beispiel #30
0
/* ************************************************************************* */
Vector3 Rot3::rpy() const {
  return xyz();
}