Beispiel #1
0
int MapFile::findEntry(long addr) const
{
	for(int j = 0 ; j < segments() ; ++j)
	{
		const MapFileEntry & segment = getSegment(j);
		long section = segment.section();
		long segmentBegin = loadAddress() + (segment.section() << 12) + segment.offset();
		long segmentEnd = segmentBegin + segment.length();

		if(addr >= segmentBegin && addr < segmentEnd)
		{
			for(int i = entries() - 1 ; i >= 0  ; --i)
			{
				const MapFileEntry entry = getEntry(i);
				if(entry.section() == section)
				{
					long entryAddr = loadAddress() + (entry.section() << 12) + entry.offset();
					if(entryAddr <= addr)
						return i;
				}
			}
		}
	}
	return -1;
}
void VerifyTokenProcessor::Run()
{
    std::string signature = m_querys["signature"];
    std::string echostr = m_querys["echostr"];
    std::vector<std::string> segments(3);
    segments[0] = FLAGS_verify_token;
    segments[1] = m_querys["timestamp"];
    segments[2] = m_querys["nonce"];
    std::sort(segments.begin(), segments.end());
    std::string join = JoinStrings(segments, "");
    std::string result = SHA1::HexDigest(join);

    if (result != signature) {
        LOG(ERROR)
            << "verify failed. join [" << join
            << "] result [" << result
            << "] signature [" << signature << "]";
        m_output->assign("verify failed.");
    } else {
        LOG(INFO)
            << "verify success. join [" << join
            << "] result [" << result
            << "] signature [" << signature << "]";
        m_output->assign("verify success.");
    }
}
Beispiel #3
0
void plot_segment_order(const Route& r, const char* filename) {
  std::ofstream os(filename);
  SvgWriter svg(r, os);

  hsl_color hsl;
  rgb_color rgb;

  hsl.h = 0;
  hsl.s = 100;
  hsl.l = 50;


  float step = 360.0f / segments(r).size();
  for(const SegmentPtr seg : segments(r)) {
    hsl.h = (hsl.h+step);
    if (hsl.h >= 360) {
      hsl.h = 1;
    }
    rgb = hsl_to_rgb(hsl);
    string strokergb = (boost::format("stroke:rgb(%u,%u,%u)") % round(rgb.r) % round(rgb.g) % round(rgb.b)).str();
    svg.write(*seg.get(), strokergb + ";stroke-width:10;");
 }

  uint32_t count = 0;
  Coord_t a,b;
  Point front, back, mark;

  for(const SegmentPtr seg : segments(r)) {
    front = seg.get()->front();
    back = seg.get()->back();
    a = std::abs(front.x - back.x);
    b = std::abs(front.y - back.y);

    mark.x = std::min(front.x, back.x) + a/2;
    mark.y = std::min(front.y, back.y) + b/2;

    svg.write(mark, "stroke:rgb(255,0,0);stroke-width:40;");
    svg.write((boost::format("%d") % count).str(), mark, "font-size=\"50\" fill=\"black\"");

    ++count;
  }
}
Beispiel #4
0
void find_shared_points(const Route& r, std::vector<Point>& sharedPoints) {
  SegmentGraph g;

  for(const SegmentPtr seg : segments(r)) {
    g.addSegment(*seg.get());
  }

  BOOST_FOREACH(SegmentGraph::Vertex v, vertices(g)) {
    if (boost::degree(v, g) > 2) {
      sharedPoints.push_back(g[v]);
    }
  }
}
Beispiel #5
0
/// Returns true if the segment crosses a boundary line of the polygon.
/// It is not enough for the segment to simply intersect the boundary
/// line -- it must cross it such that the segment extends to both inside
/// and outside of the boundary of the polygon.
bool intersects_proper(const Segment_2& segment, const Polygon_2& polygon)
{
  static log4cplus::Logger logger = log4cplus::Logger::getInstance("tiler.intersects_proper");

  Point_2 seg_pts[] = { segment.source(), segment.target() };

  // Get intersection points between segment and polygon
  LOG4CPLUS_TRACE(logger, "Doing a line sweep: " << pp(segment));
  list<Segment_2> segments(polygon.edges_begin(), polygon.edges_end());
  segments.push_back(segment);
  list<Point_2> points;
  get_intersection_points(segments.begin(), segments.end(), back_inserter(points), true, false);

  CGAL::Bounded_side side1 = polygon.bounded_side(seg_pts[0]);
  CGAL::Bounded_side side2 = polygon.bounded_side(seg_pts[1]);

  LOG4CPLUS_TRACE(logger, "Checking with cross checker");
  if (points.size() == 0)
    return false;
  Cross_checker checker;
  checker.add(side1);
  checker.add(side2);
  if (checker.crosses())
    return true;
  if (points.size() == 1)
    return false;

  points.push_back(seg_pts[0]);
  points.push_back(seg_pts[1]);
  points.sort();
  list<Point_2>::iterator it0 = points.begin();
  list<Point_2>::iterator it1 = it0;
  ++it1;
  while (it1 != points.end())
  {
    const Point_2& p0 = *it0;
    const Point_2& p1 = *it1;
    
    // find an intermediate point and test for where it is
    Point_2 midpoint((p0.x()+p1.x())/2.0, (p0.y()+p1.y())/2.0);
    checker.add(polygon.bounded_side(midpoint));
    if (checker.crosses())
      return true;

    ++it0;
    ++it1;
  }
  return false;
}
Beispiel #6
0
void plot_point_order(const Route& r, const char* filename) {
  std::ofstream os(filename);
  SvgWriter svg(r, os);

  hsl_color hsl;
  rgb_color rgb;

  hsl.h = 0;
  hsl.s = 100;
  hsl.l = 50;


  float step = 360.0f / segments(r).size();
  for(const SegmentPtr seg : segments(r)) {
    hsl.h = (hsl.h+step);
    if (hsl.h >= 360) {
      hsl.h = 1;
    }
    rgb = hsl_to_rgb(hsl);
    string strokergb = (boost::format("stroke:rgb(%u,%u,%u)") % round(rgb.r) % round(rgb.g) % round(rgb.b)).str();
    svg.write(*seg.get(), strokergb + ";stroke-width:10;");
  }

  uint32_t count = 0;
  Point last;
  for(const Path& path : r) {
    for(const Point& p : path) {
      if(p == last)
        return;
      svg.write(p, "fill:rgb(127,127,127);stroke-width:0;");
      svg.write((boost::format("%d") % count).str(), p, "font-size=\"50\" fill=\"black\"");
      ++count;
      last = p;
    }
  }
}
Beispiel #7
0
void plot_shared_segments(const Route& r, const char* filename) {
  std::set<Segment> segidx;
  std::ofstream os(filename);
  SvgWriter svg(r, os);

  for(const Path& path : r) {
    svg.write(path, "stroke:rgb(0,0,0);stroke-width:1");

    for(const SegmentPtr seg : segments(path)) {
      if (segidx.find(*seg.get()) != segidx.end()) {
        svg.write(*seg.get(), "stroke:rgb(0,255,0);stroke-width:1");
        break;
      }
    }
  }
}
Beispiel #8
0
Path Path::getParent() const {
    if (isEmpty()) return "";

    std::string result;

    std::vector<std::string> segments(split());

    // if our path is absolute with a single segment,
    // be sure to keep the prefix component
    if (!isAbsolute() || segments.size() > 1) {
        segments.pop_back(); // peel the last one
    }

    for (auto const& s : segments) {
        result.append(s).append(SEPARATOR_STR);
    }
    return getCanonicalPath(result);
}
Beispiel #9
0
    int maximumGap(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }

        const auto minimum = *min_element(nums.begin(), nums.end());
        const auto maximum = *max_element(nums.begin(), nums.end());
        const auto range = maximum - minimum;
        if (range == 0) {
            return 0;
        }

        const auto minMaxGap = max(range / (static_cast<int>(nums.size()) - 1), 1);

        const auto initialSegment = Segment{false, numeric_limits<int>::max(), numeric_limits<int>::min()};
        vector<Segment> segments((range + minMaxGap) / minMaxGap, initialSegment);

        for (const int x : nums) {
            const auto segment = &segments[(x - minimum) / minMaxGap];
            segment->valid = true;
            segment->low = min(segment->low, x);
            segment->high = max(segment->high, x);
        }

        int maxGap = minMaxGap;
        bool previousHighValid = false;
        int previousHigh = 0;

        for (const auto& segment : segments) {
            if (segment.valid) {
                if (previousHighValid) {
                    maxGap = max(maxGap, segment.low - previousHigh);
                }
                previousHigh = segment.high;
                previousHighValid = true;
            }
        }

        return maxGap;
    }
Beispiel #10
0
	bool World::isVisible(const float3 &eye_pos, EntityRef target_ref, EntityRef ignore, int density) const {
		float step = 0.8f * (density == 1? 0.0f : 1.0f / float(density - 1));

		const Entity *target = const_cast<World*>(this)->refEntity(target_ref);
		if(!target)
			return false;
		const FBox &box = target->boundingBox();

		vector<float3> points = genPointsOnPlane(box, normalize(eye_pos - box.center()), density, false);
		vector<Segment> segments(points.size());
		for(int n = 0; n < (int)points.size(); n++)
			segments[n] = Segment(eye_pos, points[n]);

		vector<Intersection> isects;
		traceCoherent(segments, isects, {Flags::all | Flags::occluding, ignore});

		for(int n = 0; n < (int)points.size(); n++) {
			const Intersection &isect = isects[n];
			if(isect.isEmpty() || isect.distance() >= intersection(segments[n], box) - constant::epsilon)
				return true;
		}

		return false;
	}
void MovePointCommandObject::move()
{
    // We start from a clean state
    CurveSegmentMap segments(m_startSegments.cbegin(), m_startSegments.cend());

    // Locking between bounds
    handleLocking();

    // Manage point - segment replacement
    handlePointOverlap(segments);

    // This handles what happens when we cross another point.
    if(m_presenter->editionSettings().suppressOnOverlap())
    {
        handleSuppressOnOverlap(segments);
    }
    else
    {
        handleCrossOnOverlap(segments);
    }

    // Rewirte and make a command
    submit(std::vector<SegmentData>(segments.begin(), segments.end()));
}
Beispiel #12
0
void chop(const Route& src, Route& sink, double maxLength) {
  for(SegmentPtr seg : segments(src)) {
    if(double len = seg->length() > maxLength) {
      Point lastPoint = seg->first;
      Point currentPoint;
      for(size_t i = 0; i < (len / maxLength); i++) {
        Segment newSeg;
        double t = i/(len/maxLength);
        currentPoint.x = seg->first.x * (1-t) + seg->second.x * t;
        currentPoint.y = seg->first.y * (1-t) + seg->second.y * t;
        append(sink, Segment(lastPoint, currentPoint));
        lastPoint = currentPoint;
      }
      if(fmod(len, maxLength) > 0) {
        append(sink, Segment(lastPoint, seg->second));
      }
    } else {
      append(sink, *seg);
    }
  }

  LOG_INFO_STR("chop");
  LOG_DEBUG(sink.size());
}
void copyAllFiles(Options& opts) {
  if (opts.imgSegs.size()) {
    std::cout << "Copying files out of image..." << std::endl;
    boost::scoped_array<const char*> segments(new const char*[opts.imgSegs.size()]);
    for (unsigned int i = 0; i < opts.imgSegs.size(); ++i) {
      segments[i] = opts.imgSegs[i].c_str();
    }
    VolumeWalker walker(opts.input);
    walker.openImageUtf8(opts.imgSegs.size(), segments.get(), TSK_IMG_TYPE_DETECT, 0);
    walker.findFilesInImg();

    if (walker.DidItWork) {
      std::cout << std::endl;
      std::cout << "Copying completed successfully. Summary: " << std::endl;
      std::cout << walker.getSummary() << std::endl;
      std::cout << std::endl;
    }
    else {
      std::cerr << "Error: unable to copy out files. Terminating." << std::endl;
      exit(1);
    }

  }
}
Beispiel #14
0
void create_testcase_for(IfcHierarchyHelper& file, const EllipsePie& pie, Ifc2x3::IfcTrimmingPreference::IfcTrimmingPreference pref) {
	const double deg = 1. / 180. * 3.141592653;
	double flt1[] = {0.                      , 0.                      };
	double flt2[] = {pie.r1 * cos(pie.t1*deg), pie.r2 * sin(pie.t1*deg)};
	double flt3[] = {pie.r1 * cos(pie.t2*deg), pie.r2 * sin(pie.t2*deg)};

	std::vector<double> coords1(flt1, flt1 + 2);
	std::vector<double> coords2(flt2, flt2 + 2);
	std::vector<double> coords3(flt3, flt3 + 2);
	
	Ifc2x3::IfcCartesianPoint* p1 = new Ifc2x3::IfcCartesianPoint(coords1);
	Ifc2x3::IfcCartesianPoint* p2 = new Ifc2x3::IfcCartesianPoint(coords2);
	Ifc2x3::IfcCartesianPoint* p3 = new Ifc2x3::IfcCartesianPoint(coords3);
	
	Ifc2x3::IfcCartesianPoint::list points(new IfcTemplatedEntityList<Ifc2x3::IfcCartesianPoint>());
	points->push(p3);
	points->push(p1);
	points->push(p2);
	file.AddEntities(points->generalize());

	
	Ifc2x3::IfcEllipse* ellipse = new Ifc2x3::IfcEllipse(file.addPlacement2d(), pie.r1, pie.r2);
	file.AddEntity(ellipse);
	IfcEntities trim1(new IfcEntityList());
	IfcEntities trim2(new IfcEntityList());
	if (pref == Ifc2x3::IfcTrimmingPreference::IfcTrimmingPreference_PARAMETER) {
		trim1->push(new IfcWrite::IfcSelectHelper(pie.t1, Ifc2x3::Type::IfcParameterValue));
		trim2->push(new IfcWrite::IfcSelectHelper(pie.t2, Ifc2x3::Type::IfcParameterValue));
	} else {
		trim1->push(p2);
		trim2->push(p3);
	}
	Ifc2x3::IfcTrimmedCurve* trim = new Ifc2x3::IfcTrimmedCurve(ellipse, trim1, trim2, true, pref);
	file.AddEntity(trim);
	
	Ifc2x3::IfcCompositeCurveSegment::list segments(new IfcTemplatedEntityList<Ifc2x3::IfcCompositeCurveSegment>());
	Ifc2x3::IfcCompositeCurveSegment* s2 = new Ifc2x3::IfcCompositeCurveSegment(Ifc2x3::IfcTransitionCode::IfcTransitionCode_CONTINUOUS, true, trim);
	
	Ifc2x3::IfcPolyline* poly = new Ifc2x3::IfcPolyline(points);	
	file.AddEntity(poly);
	Ifc2x3::IfcCompositeCurveSegment* s1 = new Ifc2x3::IfcCompositeCurveSegment(Ifc2x3::IfcTransitionCode::IfcTransitionCode_CONTINUOUS, true, poly);
	segments->push(s1);
	
	segments->push(s2);
	file.AddEntities(segments->generalize());
	
	Ifc2x3::IfcCompositeCurve* ccurve = new Ifc2x3::IfcCompositeCurve(segments, false);
	Ifc2x3::IfcArbitraryClosedProfileDef* profile = new Ifc2x3::IfcArbitraryClosedProfileDef(Ifc2x3::IfcProfileTypeEnum::IfcProfileType_AREA, null, ccurve);
	file.AddEntity(ccurve);
	file.AddEntity(profile);

	IfcSchema::IfcBuildingElementProxy* product = new IfcSchema::IfcBuildingElementProxy(
		guid(), 0, S("profile"), null, null, 0, 0, null, null);
	file.addBuildingProduct(product);
	product->setOwnerHistory(file.getSingle<IfcSchema::IfcOwnerHistory>());

	product->setObjectPlacement(file.addLocalPlacement(200 * i++));

	IfcSchema::IfcExtrudedAreaSolid* solid = new IfcSchema::IfcExtrudedAreaSolid(profile,
		file.addPlacement3d(), file.addTriplet<IfcSchema::IfcDirection>(0, 0, 1), 20.0);

	file.AddEntity(solid);
		
	IfcSchema::IfcRepresentation::list reps (new IfcTemplatedEntityList<IfcSchema::IfcRepresentation>());
	IfcSchema::IfcRepresentationItem::list items (new IfcTemplatedEntityList<IfcSchema::IfcRepresentationItem>());
		
	items->push(solid);
	IfcSchema::IfcShapeRepresentation* rep = new IfcSchema::IfcShapeRepresentation(
		file.getSingle<IfcSchema::IfcRepresentationContext>(), S("Body"), S("SweptSolid"), items);
	reps->push(rep);

	IfcSchema::IfcProductDefinitionShape* shape = new IfcSchema::IfcProductDefinitionShape(0, 0, reps);
	file.AddEntity(rep);
	file.AddEntity(shape);
		
	product->setRepresentation(shape);
}
Beispiel #15
0
/*
 * Clips segments agains a box
 */
void clip(Route& src, Route& sink, const Box& bounds) {
  LOG_DEBUG(src.size());

  for (const SegmentPtr segPtr : segments(src)) {
    Segment& seg = *segPtr.get();
    double width = bounds.width();
    double height = bounds.height();

    Segment leftBedBorder(Point(0, 0), Point(0, height - 1));
    Segment bottomBedBorder(Point(0, height - 1), Point(width - 1, height - 1));
    Segment rightBedBorder(Point(width - 1, height - 1), Point(width - 1, 0));
    Segment topBedBorder(Point(width - 1, 0), Point(0, 0));

    Point intersection;
    Segment clipped = seg;

    if (clipped.first.x < 0 || clipped.second.x < 0
        || clipped.first.y < 0 || clipped.second.y < 0
        || clipped.first.x > width - 1 || clipped.second.x > width - 1
        || clipped.first.y > height - 1 || clipped.second.y > height - 1) {
      if (clipped.first.x < 0 || clipped.second.x < 0) {
        // out of bounds;
        if (clipped.first.x < 0 && clipped.second.x < 0) {
          continue;
        }

        if (intersects(clipped, leftBedBorder, intersection) == ALIGN_INTERSECT) {
          if (clipped.first.x >= clipped.second.x)
            clipped.second = clipped.first;

          clipped.first = intersection;
          intersection = Point();
        }
      }

      if (clipped.first.y < 0 || clipped.second.y < 0) {
        if (clipped.first.y < 0 && clipped.second.y < 0) {
          continue;
        }

        if (intersects(clipped, topBedBorder, intersection) == ALIGN_INTERSECT) {
          if (clipped.first.y >= clipped.second.y)
            clipped.second = clipped.first;

          clipped.first = intersection;

          intersection = Point();
        }
      }

      if (greater_than(clipped.first.x, width - 1) || greater_than(clipped.second.x, width - 1)) {
        if (greater_than(clipped.first.x, width - 1) && greater_than(clipped.second.x, width - 1)) {
          continue;
        }

        if (intersects(clipped, rightBedBorder, intersection) == ALIGN_INTERSECT) {
          if (clipped.first.x <= clipped.second.x)
            clipped.second = clipped.first;

          clipped.first = intersection;

          intersection = Point();
        }
      }

      if (clipped.first.y > height - 1 || clipped.second.y > height - 1) {
        if (clipped.first.y > height - 1 && clipped.second.y > height - 1) {
          continue;
        }
        if (intersects(clipped, bottomBedBorder, intersection) == ALIGN_INTERSECT) {
          if (clipped.first.y <= clipped.second.y)

            clipped.second = clipped.first;
          clipped.first = intersection;
        }
      }
    }
    add(sink, clipped);
  }
  LOG_DEBUG(sink.size());
}
Beispiel #16
0
bool toxi::geom::Polygon2D::toOutLine()
{
	int corners = vertices.size();
	int maxSegs = corners * 3;
	std::vector<Vec2D> newVerts;

	std::vector< Vec2D > segments( maxSegs );
	std::vector< Vec2D > segEnds( maxSegs );
	std::vector< double > segAngles( maxSegs );

	//Vec2D * segments;
	//segments = ( Vec2D* ) malloc( sizeof( Vec2D ) * maxSegs);
	//Vec2D * segEnds;
	//segEnds = (Vec2D * ) malloc(sizeof( Vec2D ) * maxSegs );
	//float * segAngles;
	//segAngles = (float * ) malloc( sizeof( float ) * maxSegs );
	//Vec2D[] segments = new Vec2D[maxSegs];
	//Vec2D[] segEnds = new Vec2D[maxSegs];
	//float[] segAngles = new float[maxSegs];
	Vec2D start = vertices.at(0);
	double lastAngle = toxi::math::MathUtils::PI;
	float a, b, c, d, e, f;
	double angleDif, bestAngleDif;
	int i, j = corners - 1, segs = 0;

	if (corners > maxSegs) {
		return false;
	}

	// 1,3. Reformulate the polygon as a set of line segments, and choose a
	// starting point that must be on the perimeter.
	for (i = 0; i < corners; i++) {
		Vec2D pi = vertices.at(i);
		Vec2D pj = vertices.at(j);
		if (!( pi == pj )) {
			segments[segs] = pi;
			segEnds[segs++] = pj;
		}
		j = i;
		if (pi.getY() > start.getY() || (pi.getY() == start.getY() && pi.getX() < start.getX())) {
			start.set( pi);
		}
	}
	if (segs == 0) {
		return false;
	}

	// 2. Break the segments up at their intersection points.
	for (i = 0; i < segs - 1; i++) {
		for (j = i + 1; j < segs; j++) {
			Line2D li = toxi::geom::Line2D( segments[i], segEnds[i]);
			Line2D lj = toxi::geom::Line2D( segments[j], segEnds[j]);
			LineIntersection isec = li.intersectLine( lj );
			if (isec.getType() == toxi::geom::LineIntersection::Type::INTERSECTING) {
				Vec2D ipos = isec.getPos();
				if (!( ipos == segments[i] ) && !( ipos == segEnds[i])) {
					if (segs == maxSegs) {
						return false;
					}
					segments[segs] = segments[i];
					segEnds[segs++] = ipos;
					segments[i] = ipos;
				}
				if (!( ipos == segments[j] ) && !( ipos ==  segEnds[ j ] ) ) {
					if (segs == maxSegs) {
						return false;
					}
					segments[segs] = segments[j];
					segEnds[segs++] = ipos;
					segments[j] = ipos;
				}
			}
		}
	}

	// Calculate the angle of each segment.
	for (i = 0; i < segs; i++) {
		segAngles[i] = segEnds[i].sub( segments[i] ).positiveHeading();
	}

	// 4. Build the perimeter polygon.
	c = static_cast< float > ( start.getX() );
	d = static_cast< float > ( start.getY() );
	a = c - 1;
	b = d;
	e = 0;
	f = 0;
	newVerts.push_back(Vec2D(c, d));
	corners = 1;
	while (true) {
		bestAngleDif = toxi::math::MathUtils::TWO_PI;
		for (i = 0; i < segs; i++) {
			if (segments[i].getX() == c && segments[i].getY() == d
				&& (segEnds[i].getX() != a || segEnds[i].getY() != b)) {
					angleDif = lastAngle - segAngles[i];
					while (angleDif >= toxi::math::MathUtils::TWO_PI) {
						angleDif -= toxi::math::MathUtils::TWO_PI;
					}
					while (angleDif < 0) {
						angleDif += toxi::math::MathUtils::TWO_PI;
					}
					if (angleDif < bestAngleDif) {
						bestAngleDif = angleDif;
						e =  static_cast< float > ( segEnds[i].getX() );
						f = static_cast< float > ( segEnds[i].getY() );
					}
			}
			if (segEnds[i].getX() == c && segEnds[i].getY() == d
				&& (segments[i].getX() != a || segments[i].getY() != b)) {
					angleDif = lastAngle - segAngles[i] + toxi::math::MathUtils::PI;
					while (angleDif >= toxi::math::MathUtils::TWO_PI) {
						angleDif -= toxi::math::MathUtils::TWO_PI;
					}
					while (angleDif < 0) {
						angleDif += toxi::math::MathUtils::TWO_PI;
					}
					if (angleDif < bestAngleDif) {
						bestAngleDif = angleDif;
						e = static_cast< float > ( segments[i].getX() );
						f = static_cast< float > ( segments[i].getY() );
					}
			}
		}
		if (corners > 1 && c == newVerts.at(0).getX() && d == newVerts.at(0).getY()
			&& e == newVerts.at(1).getX() && f == newVerts.at(1).getY()) {
				corners--;
				vertices = newVerts;
				return true;
		}
		if (bestAngleDif == toxi::math::MathUtils::TWO_PI || corners == maxSegs) {
			return false;
		}
		lastAngle -= bestAngleDif + toxi::math::MathUtils::PI;
		newVerts.push_back(Vec2D(e, f));
		corners++;
		a = c;
		b = d;
		c = e;
		d = f;
	}
}
int main(int argc, char ** argv)
{
  utils::mpi_world mpi_world(argc, argv);
  
  const int mpi_rank = MPI::COMM_WORLD.Get_rank();
  const int mpi_size = MPI::COMM_WORLD.Get_size();
  
  try {
    options(argc, argv);

    cicada::optimize::LineSearch::value_min = value_lower;
    cicada::optimize::LineSearch::value_max = value_upper;
    
    if (scorer_list) {
      std::cout << cicada::eval::Scorer::lists();
      return 0;
    }
    
    if (int(yield_sentence) + yield_alignment + yield_span > 1)
      throw std::runtime_error("specify either sentence|alignment|span yield");
    if (int(yield_sentence) + yield_alignment + yield_span == 0)
      yield_sentence = true;

    if (weights_file.empty() || ! boost::filesystem::exists(weights_file))
      throw std::runtime_error("no weight file? " + weights_file.string());
    if (direction_name.empty())
      throw std::runtime_error("no direction?");
    
    // read reference set
    scorer_document_type scorers(scorer_name);
    
    read_refset(refset_files, scorers);
    
    if (mpi_rank == 0 && debug)
      std::cerr << "# of references: " << scorers.size() << std::endl;

    // read test set
    
    if (mpi_rank == 0 && debug)
      std::cerr << "reading hypergraphs" << std::endl;

    hypergraph_set_type graphs(scorers.size());
    
    read_tstset(tstset_files, graphs);
    
    weight_set_type weights;
    {
      utils::compress_istream is(weights_file, 1024 * 1024);
      is >> weights;
    }
    
    weight_set_type direction;
    direction[direction_name] = 1.0;
    
    segment_document_type segments(graphs.size());
    
    compute_envelope(scorers, graphs, weights, direction, segments);

    if (mpi_rank == 0) {
      line_search_type line_search(debug);
      
      utils::compress_ostream os(output_file, 1024 * 1024);
      
      line_search(segments, value_lower, value_upper, OutputIterator(os, weights[direction_name]));
    }
  }
  catch (const std::exception& err) {
    std::cerr << "error: " << err.what() << std::endl;
    return 1;
  }
  return 0;
}
void create_curve_rebar(IfcHierarchyHelper& file)
{
	int dia = 24;
	int R = 3 * dia;
	int length = 12 * dia;

	double crossSectionarea = M_PI * (dia / 2) * 2;
	IfcSchema::IfcReinforcingBar* rebar = new IfcSchema::IfcReinforcingBar(
		guid(), 0, S("test"), null,
		null, 0, 0,
		null, S("SR24"),		//SteelGrade
		dia,						//diameter
		crossSectionarea,		//crossSectionarea = math.pi*(12.0/2)**2
		0,
		IfcSchema::IfcReinforcingBarRoleEnum::IfcReinforcingBarRoleEnum::IfcReinforcingBarRole_LIGATURE,
		IfcSchema::IfcReinforcingBarSurfaceEnum::IfcReinforcingBarSurfaceEnum::IfcReinforcingBarSurface_PLAIN	//PLAIN or TEXTURED
		);

	file.addBuildingProduct(rebar);
	rebar->setOwnerHistory(file.getSingle<IfcSchema::IfcOwnerHistory>());

	IfcSchema::IfcCompositeCurveSegment::list::ptr segments(new IfcSchema::IfcCompositeCurveSegment::list());

	IfcSchema::IfcCartesianPoint* p1 = file.addTriplet<IfcSchema::IfcCartesianPoint>(0, 0, 1000.);
	IfcSchema::IfcCartesianPoint* p2 = file.addTriplet<IfcSchema::IfcCartesianPoint>(0, 0, 0);
	IfcSchema::IfcCartesianPoint* p3 = file.addTriplet<IfcSchema::IfcCartesianPoint>(0, R, 0);
	IfcSchema::IfcCartesianPoint* p4 = file.addTriplet<IfcSchema::IfcCartesianPoint>(0, R, -R);
	IfcSchema::IfcCartesianPoint* p5 = file.addTriplet<IfcSchema::IfcCartesianPoint>(0, R + length, -R);

	/*first segment - line */
	IfcSchema::IfcCartesianPoint::list::ptr points1(new IfcSchema::IfcCartesianPoint::list());
	points1->push(p1);
	points1->push(p2);
	file.addEntities(points1->generalize());
	IfcSchema::IfcPolyline* poly1 = new IfcSchema::IfcPolyline(points1);
	file.addEntity(poly1);

	IfcSchema::IfcCompositeCurveSegment* segment1 = new IfcSchema::IfcCompositeCurveSegment(IfcSchema::IfcTransitionCode::IfcTransitionCode_CONTINUOUS, true, poly1);
	file.addEntity(segment1);
	segments->push(segment1);

	/*second segment - arc */
	IfcSchema::IfcAxis2Placement3D* axis1 = new IfcSchema::IfcAxis2Placement3D(p3, file.addTriplet<IfcSchema::IfcDirection>(1, 0, 0), file.addTriplet<IfcSchema::IfcDirection>(0, 1, 0));
	file.addEntity(axis1);
	IfcSchema::IfcCircle* circle = new IfcSchema::IfcCircle(axis1, R);
	file.addEntity(circle);

	IfcEntityList::ptr trim1(new IfcEntityList);
	IfcEntityList::ptr trim2(new IfcEntityList);

	trim1->push(new IfcSchema::IfcParameterValue(180));
	trim1->push(p2);

	trim2->push(new IfcSchema::IfcParameterValue(270));
	trim2->push(p4);
	IfcSchema::IfcTrimmedCurve* trimmed_curve = new IfcSchema::IfcTrimmedCurve(circle, trim1, trim2, false, IfcSchema::IfcTrimmingPreference::IfcTrimmingPreference_PARAMETER);
	file.addEntity(trimmed_curve);

	IfcSchema::IfcCompositeCurveSegment* segment2 = new IfcSchema::IfcCompositeCurveSegment(IfcSchema::IfcTransitionCode::IfcTransitionCode_CONTSAMEGRADIENT, false, trimmed_curve);
	file.addEntity(segment2);
	segments->push(segment2);

	/*third segment - line */
	IfcSchema::IfcCartesianPoint::list::ptr points2(new IfcSchema::IfcCartesianPoint::list());
	points2->push(p4);
	points2->push(p5);
	file.addEntities(points2->generalize());
	IfcSchema::IfcPolyline* poly2 = new IfcSchema::IfcPolyline(points2);
	file.addEntity(poly2);

	IfcSchema::IfcCompositeCurveSegment* segment3 = new IfcSchema::IfcCompositeCurveSegment(IfcSchema::IfcTransitionCode::IfcTransitionCode_CONTINUOUS, true, poly2);
	file.addEntity(segment3);
	segments->push(segment3);

	IfcSchema::IfcCompositeCurve* curve = new IfcSchema::IfcCompositeCurve(segments, false);
	file.addEntity(curve);

	IfcSchema::IfcSweptDiskSolid* solid = new IfcSchema::IfcSweptDiskSolid(curve, dia / 2, null, 0, 1);

	IfcSchema::IfcRepresentation::list::ptr reps(new IfcSchema::IfcRepresentation::list());
	IfcSchema::IfcRepresentationItem::list::ptr items(new IfcSchema::IfcRepresentationItem::list());
	items->push(solid);
	IfcSchema::IfcShapeRepresentation* rep = new IfcSchema::IfcShapeRepresentation(
		file.getSingle<IfcSchema::IfcRepresentationContext>(), S("Body"), S("AdvancedSweptSolid"), items);
	reps->push(rep);

	IfcSchema::IfcProductDefinitionShape* shape = new IfcSchema::IfcProductDefinitionShape(null, null, reps);
	file.addEntity(shape);

	rebar->setRepresentation(shape);

	IfcSchema::IfcObjectPlacement* storey_placement = file.getSingle<IfcSchema::IfcBuildingStorey>()->ObjectPlacement();
	rebar->setObjectPlacement(file.addLocalPlacement(storey_placement, 0, 0, 0));
}
Beispiel #19
0
void
PrintTrace(
    tcp_pair *ptp)
{
    double etime;
    u_long etime_secs;
    u_long etime_usecs;
    double etime_data1;
    double etime_data2;
    tcb *pab = &ptp->a2b;
    tcb *pba = &ptp->b2a;
    char *host1 = pab->host_letter;
    char *host2 = pba->host_letter;
    char bufl[40],bufr[40];
   
    /* counters to use for seq. space wrap around calculations
     */
    u_llong stream_length_pab=0, stream_length_pba=0;
    u_long pab_last, pba_last;

   /* Reset the counter for each connection */
   sv_print_count = 1; /* The first field (conn_#) gets printed in trace.c */
   

    /* calculate elapsed time */
    etime = elapsed(ptp->first_time,ptp->last_time);
    etime_secs = etime / 1000000.0;
    etime_usecs = 1000000 * (etime/1000000.0 - (double)etime_secs);

    /* Check if comma-separated-values or tab-separated-values
     * has been requested.
     */ 
   if(csv || tsv || (sv != NULL)) {
       fprintf(stdout,"%s%s%s%s%s%s%s%s",
	       ptp->a_hostname, sp, ptp->b_hostname, sp,
	       ptp->a_portname, sp, ptp->b_portname, sp);
       sv_print_count += 4;
       /* Print the start and end times. In other words,
	* print the time of the first and the last packet
	*/ 
       fprintf(stdout,"%ld.%ld %s %ld.%ld %s",
	       (long)ptp->first_time.tv_sec, (long)ptp->first_time.tv_usec, sp,
	       (long)ptp->last_time.tv_sec, (long)ptp->last_time.tv_usec, sp);
       sv_print_count += 2;      
    }
    else {
       fprintf(stdout,"\thost %-4s      %s\n",
	       (snprintf(bufl,sizeof(bufl),"%s:", host1),bufl), ptp->a_endpoint);
       fprintf(stdout,"\thost %-4s      %s\n",
	       (snprintf(bufl,sizeof(bufl),"%s:", host2),bufl), ptp->b_endpoint);
       fprintf(stdout,"\tcomplete conn: %s",
	       ConnReset(ptp)?"RESET":(
				       ConnComplete(ptp)?"yes":"no"));
       if (ConnComplete(ptp))
	 fprintf(stdout,"\n");
       else
	 fprintf(stdout,"\t(SYNs: %u)  (FINs: %u)\n",
		 SynCount(ptp), FinCount(ptp));
       
       fprintf(stdout,"\tfirst packet:  %s\n", ts2ascii(&ptp->first_time));
       fprintf(stdout,"\tlast packet:   %s\n", ts2ascii(&ptp->last_time));
       
       fprintf(stdout,"\telapsed time:  %s\n", elapsed2str(etime));
       
       fprintf(stdout,"\ttotal packets: %" FS_ULL "\n", ptp->packets);
       
       fprintf(stdout,"\tfilename:      %s\n", ptp->filename);
       
       fprintf(stdout,"   %s->%s:			      %s->%s:\n",
	       host1,host2,host2,host1);
    }
   
    StatLineI("total packets","", pab->packets, pba->packets);
    if (pab->reset_count || pba->reset_count || csv || tsv || (sv != NULL))
	StatLineI("resets sent","", pab->reset_count, pba->reset_count);
    StatLineI("ack pkts sent","", pab->ack_pkts, pba->ack_pkts);
    StatLineI("pure acks sent","", pab->pureack_pkts, pba->pureack_pkts);
    StatLineI("sack pkts sent","", pab->num_sacks, pba->num_sacks);
    StatLineI("dsack pkts sent","", pab->num_dsacks, pba->num_dsacks);
    StatLineI("max sack blks/ack","", pab->max_sack_blocks, pba->max_sack_blocks);
    StatLineI("unique bytes sent","",
	      pab->unique_bytes, pba->unique_bytes);
    StatLineI("actual data pkts","", pab->data_pkts, pba->data_pkts);
    StatLineI("actual data bytes","", pab->data_bytes, pba->data_bytes);
    StatLineI("rexmt data pkts","", pab->rexmit_pkts, pba->rexmit_pkts);
    StatLineI("rexmt data bytes","",
	      pab->rexmit_bytes, pba->rexmit_bytes);
    StatLineI("zwnd probe pkts","", 
		  pab->num_zwnd_probes, pba->num_zwnd_probes);
    StatLineI("zwnd probe bytes","",
	      pab->zwnd_probe_bytes, pba->zwnd_probe_bytes);
    StatLineI("outoforder pkts","",
	      pab->out_order_pkts, pba->out_order_pkts);
    StatLineI("pushed data pkts","", pab->data_pkts_push, pba->data_pkts_push);
    StatLineP("SYN/FIN pkts sent","","%s",
	      (snprintf(bufl,sizeof(bufl),"%d/%d",
		       pab->syn_count, pab->fin_count),bufl),
	      (snprintf(bufr,sizeof(bufr),"%d/%d",
		       pba->syn_count, pba->fin_count),bufr));
    if (pab->f1323_ws || pba->f1323_ws || pab->f1323_ts || pba->f1323_ts || csv || tsv || (sv != NULL)) {
	StatLineP("req 1323 ws/ts","","%s",
		  (snprintf(bufl,sizeof(bufl),"%c/%c",
		      pab->f1323_ws?'Y':'N',pab->f1323_ts?'Y':'N'),bufl),
		  (snprintf(bufr,sizeof(bufr),"%c/%c",
		      pba->f1323_ws?'Y':'N',pba->f1323_ts?'Y':'N'),bufr));
    }
    if (pab->f1323_ws || pba->f1323_ws || csv || tsv || (sv != NULL)) {
	StatLineI("adv wind scale","",
		  (u_long)pab->window_scale, (u_long)pba->window_scale);
    }
    if (pab->fsack_req || pba->fsack_req || csv || tsv || (sv != NULL)) {
	StatLineP("req sack","","%s",
		  pab->fsack_req?"Y":"N",
		  pba->fsack_req?"Y":"N");
	StatLineI("sacks sent","",
		  pab->sacks_sent,
		  pba->sacks_sent);
    }
    StatLineI("urgent data pkts", "pkts",
	      pab->urg_data_pkts,
	      pba->urg_data_pkts);
    StatLineI("urgent data bytes", "bytes",
	      pab->urg_data_bytes,
	      pba->urg_data_bytes);
    StatLineI("mss requested","bytes", pab->mss, pba->mss);
    StatLineI("max segm size","bytes",
	      pab->max_seg_size,
	      pba->max_seg_size);
    StatLineI("min segm size","bytes",
	      pab->min_seg_size,
	      pba->min_seg_size);
    StatLineI("avg segm size","bytes",
	      (int)((double)pab->data_bytes / ((double)pab->data_pkts+.001)),
	      (int)((double)pba->data_bytes / ((double)pba->data_pkts+.001)));
    StatLineI("max win adv","bytes", pab->win_max, pba->win_max);
    StatLineI("min win adv","bytes", pab->win_min, pba->win_min);
    StatLineI("zero win adv","times",
	      pab->win_zero_ct, pba->win_zero_ct);
    // Average window advertisement is calculated only for window scaled pkts
    // if we have seen this connection using window scaling.
    // Otherwise, it is just the regular way of dividing the sum of 
    // all window advertisements by the total number of packets.
     
    if (pab->window_stats_updated_for_scaling &&
	pba->window_stats_updated_for_scaling)
	  StatLineI("avg win adv","bytes",
		    pab->win_scaled_pkts==0?0:
		    (pab->win_tot/pab->win_scaled_pkts),
		    pba->win_scaled_pkts==0?0:
		    (pba->win_tot/pba->win_scaled_pkts));
    else
	  StatLineI("avg win adv","bytes",
		    pab->packets==0?0:pab->win_tot/pab->packets,
		    pba->packets==0?0:pba->win_tot/pba->packets);
    if (print_owin) {
	StatLineI("max owin","bytes", pab->owin_max, pba->owin_max);
	StatLineI("min non-zero owin","bytes", pab->owin_min, pba->owin_min);
	StatLineI("avg owin","bytes",
		  pab->owin_count==0?0:pab->owin_tot/pab->owin_count,
		  pba->owin_count==0?0:pba->owin_tot/pba->owin_count);
	if (etime == 0.0) {
		StatLineP("wavg owin", "", "%s", "NA", "NA");	
	}
	else {
		StatLineI("wavg owin","bytes", 
			  (u_llong)(pab->owin_wavg/((double)etime/1000000)), 
		  	  (u_llong)(pba->owin_wavg/((double)etime/1000000)));
   	} 
    }
    StatLineI("initial window","bytes",
	      pab->initialwin_bytes, pba->initialwin_bytes);
    StatLineI("initial window","pkts",
	      pab->initialwin_segs, pba->initialwin_segs);

    /* compare to theoretical length of the stream (not just what
       we saw) using the SYN and FIN
     * Seq. Space wrap around calculations:
     * Calculate stream length using last_seq_num seen, first_seq_num
     * seen and wrap_count.
     * first_seq_num = syn
     * If reset_set, last_seq_num = latest_seq
     *          else last_seq_num = fin
     */
    
    pab_last = (pab->reset_count>0)?pab->latest_seq:pab->fin;
    
    pba_last = (pba->reset_count>0)?pba->latest_seq:pba->fin;
    
    /* calculating stream length for direction pab */
    if ((pab->syn_count > 0) && (pab->fin_count > 0)) {
	if (pab->seq_wrap_count > 0) {
	    if (pab_last > pab->syn) {
		stream_length_pab = pab_last + (MAX_32 * pab->seq_wrap_count) - pab->syn - 1;
	    }
	    else {
		stream_length_pab = pab_last + (MAX_32 * (pab->seq_wrap_count+1)) - pab->syn - 1;
	    }
	}
	else {
	    if (pab_last > pab->syn) {
		stream_length_pab = pab_last - pab->syn - 1;
	    }
	    else {
		stream_length_pab = MAX_32 + pab_last - pab->syn - 1;
	    }
	}
    }

    /* calculating stream length for direction pba */
    if ((pba->syn_count > 0) && (pba->fin_count > 0)) {
	if (pba->seq_wrap_count > 0) {
	    if (pba_last > pba->syn) {
		stream_length_pba = pba_last + (MAX_32 * pba->seq_wrap_count) - pba->syn - 1;
	    }
	    else {
		stream_length_pba = pba_last + (MAX_32 * (pba->seq_wrap_count+1)) - pba->syn - 1;
	    }
	}
	else {
	    if (pba_last > pba->syn) {
		stream_length_pba = pba_last - pba->syn - 1;
	    }
	    else {
		stream_length_pba = MAX_32 + pba_last - pba->syn - 1;
	    }
	}
    }

    /* print out values */
    if ((pab->fin_count > 0) && (pab->syn_count > 0)) {
	char *format = "%8" FS_ULL;
	StatLineFieldL("ttl stream length", "bytes", format, stream_length_pab, 0);
    }
    else {
	StatLineField("ttl stream length", "", "%s", (u_long)"NA", 0);
    }
    if ((pba->fin_count > 0) && (pba->syn_count > 0)) {
	char *format = "%8" FS_ULL;
	StatLineFieldL("ttl stream length", "bytes", format, stream_length_pba, 1);
    }
    else {
	StatLineField("ttl stream length", "", "%s", (u_long)"NA", 1);
    }

    if ((pab->fin_count > 0) && (pab->syn_count > 0)) {
	char *format = "%8" FS_ULL;
	StatLineFieldL("missed data", "bytes", format, (stream_length_pab - pab->unique_bytes), 0);
    }
    else {
	StatLineField("missed data", "", "%s", (u_long)"NA", 0);
    }
    if ((pba->fin_count > 0) && (pba->syn_count > 0)) {
	char *format = "%8" FS_ULL;
	StatLineFieldL("missed data", "bytes", format, (stream_length_pba - pba->unique_bytes), 1);
    }
    else {
	StatLineField("missed data", "", "%s", (u_long)"NA", 1);
    }
    
    /* tell how much data was NOT captured in the files */
    StatLineI("truncated data","bytes",
	      pab->trunc_bytes, pba->trunc_bytes);
    StatLineI("truncated packets","pkts",
	      pab->trunc_segs, pba->trunc_segs);

    /* stats on just the data */
    etime_data1 = elapsed(pab->first_data_time,
			  pab->last_data_time); /* in usecs */
    etime_data2 = elapsed(pba->first_data_time,
			  pba->last_data_time); /* in usecs */
    /* fix from Rob Austein */
    StatLineF("data xmit time","secs","%7.3f",
	      etime_data1 / 1000000.0,
	      etime_data2 / 1000000.0);
    StatLineP("idletime max","ms","%s",
	      ZERO_TIME(&pab->last_time)?"NA":
	      (snprintf(bufl,sizeof(bufl),"%8.1f",(double)pab->idle_max/1000.0),bufl),
	      ZERO_TIME(&pba->last_time)?"NA":
	      (snprintf(bufr,sizeof(bufr),"%8.1f",(double)pba->idle_max/1000.0),bufr));

    if ((pab->num_hardware_dups != 0) || (pba->num_hardware_dups != 0)  || csv || tsv || (sv != NULL)) {
	StatLineI("hardware dups","segs",
		  pab->num_hardware_dups, pba->num_hardware_dups);

        if(!(csv || tsv || (sv != NULL)))       
	  fprintf(stdout,
		  "       ** WARNING: presence of hardware duplicates makes these figures suspect!\n");
    }

    /* do the throughput calcs */
    etime /= 1000000.0;  /* convert to seconds */
    if (etime == 0.0)
	StatLineP("throughput","","%s","NA","NA");
    else
	StatLineF("throughput","Bps","%8.0f",
		  (double) (pab->unique_bytes) / etime,
		  (double) (pba->unique_bytes) / etime);

    if (print_rtt) {
        if(!(csv || tsv || (sv != NULL)))
	  fprintf(stdout,"\n");
	StatLineI("RTT samples","", pab->rtt_count, pba->rtt_count);
	StatLineF("RTT min","ms","%8.1f",
		  (double)pab->rtt_min/1000.0,
		  (double)pba->rtt_min/1000.0);
	StatLineF("RTT max","ms","%8.1f",
		  (double)pab->rtt_max/1000.0,
		  (double)pba->rtt_max/1000.0);
	StatLineF("RTT avg","ms","%8.1f",
		  Average(pab->rtt_sum, pab->rtt_count) / 1000.0,
		  Average(pba->rtt_sum, pba->rtt_count) / 1000.0);
	StatLineF("RTT stdev","ms","%8.1f",
		  Stdev(pab->rtt_sum, pab->rtt_sum2, pab->rtt_count) / 1000.0,
		  Stdev(pba->rtt_sum, pba->rtt_sum2, pba->rtt_count) / 1000.0);
        if(!(csv || tsv || (sv != NULL)))
	  fprintf(stdout,"\n");
	StatLineF("RTT from 3WHS","ms","%8.1f",
		  (double)pab->rtt_3WHS/1000.0,
		  (double)pba->rtt_3WHS/1000.0);
        if(!(csv || tsv || (sv != NULL)))
	  fprintf(stdout,"\n");
	StatLineI("RTT full_sz smpls","", 
		  pab->rtt_full_count, pba->rtt_full_count);
	StatLineF("RTT full_sz min","ms","%8.1f",
		  (double)pab->rtt_full_min/1000.0,
		  (double)pba->rtt_full_min/1000.0);
	StatLineF("RTT full_sz max","ms","%8.1f",
		  (double)pab->rtt_full_max/1000.0,
		  (double)pba->rtt_full_max/1000.0);
	StatLineF("RTT full_sz avg","ms","%8.1f",
		  Average(pab->rtt_full_sum, pab->rtt_full_count) / 1000.0,
		  Average(pba->rtt_full_sum, pba->rtt_full_count) / 1000.0);
	StatLineF("RTT full_sz stdev","ms","%8.1f",
		  Stdev(pab->rtt_full_sum, pab->rtt_full_sum2, pab->rtt_full_count) / 1000.0,
		  Stdev(pba->rtt_full_sum, pba->rtt_full_sum2, pba->rtt_full_count) / 1000.0);
        if(!(csv || tsv || (sv != NULL)))
	  fprintf(stdout,"\n");
	StatLineI("post-loss acks","",
		  pab->rtt_nosample, pba->rtt_nosample);
	if (pab->rtt_amback || pba->rtt_amback || csv || tsv || (sv != NULL)) {
	   if(!(csv || tsv || (sv != NULL)))
	     fprintf(stdout, "\
\t  For the following 5 RTT statistics, only ACKs for\n\
\t  multiply-transmitted segments (ambiguous ACKs) were\n\
\t  considered.  Times are taken from the last instance\n\
\t  of a segment.\n\
");
	    StatLineI("ambiguous acks","",
		      pab->rtt_amback, pba->rtt_amback);
	    StatLineF("RTT min (last)","ms","%8.1f",
		      (double)pab->rtt_min_last/1000.0,
		      (double)pba->rtt_min_last/1000.0);
	    StatLineF("RTT max (last)","ms","%8.1f",
		      (double)pab->rtt_max_last/1000.0,
		      (double)pba->rtt_max_last/1000.0);
	    StatLineF("RTT avg (last)","ms","%8.1f",
		      Average(pab->rtt_sum_last, pab->rtt_count_last) / 1000.0,
		      Average(pba->rtt_sum_last, pba->rtt_count_last) / 1000.0);
	    StatLineF("RTT sdv (last)","ms","%8.1f",
		      Stdev(pab->rtt_sum_last, pab->rtt_sum2_last, pab->rtt_count_last) / 1000.0,
		      Stdev(pba->rtt_sum_last, pba->rtt_sum2_last, pba->rtt_count_last) / 1000.0);

	}
	StatLineI("segs cum acked","",
		  pab->rtt_cumack, pba->rtt_cumack);
	StatLineI("duplicate acks","",
		  pab->rtt_dupack, pba->rtt_dupack);
	StatLineI("triple dupacks","",
		  pab->rtt_triple_dupack, pba->rtt_triple_dupack);
	if (debug)
	    StatLineI("unknown acks:","",
		      pab->rtt_unkack, pba->rtt_unkack);
	StatLineI("max # retrans","",
		  pab->retr_max, pba->retr_max);
	StatLineF("min retr time","ms","%8.1f",
		  (double)((double)pab->retr_min_tm/1000.0),
		  (double)((double)pba->retr_min_tm/1000.0));
	StatLineF("max retr time","ms","%8.1f",
		  (double)((double)pab->retr_max_tm/1000.0),
		  (double)((double)pba->retr_max_tm/1000.0));
	StatLineF("avg retr time","ms","%8.1f",
		  Average(pab->retr_tm_sum, pab->retr_tm_count) / 1000.0,
		  Average(pba->retr_tm_sum, pba->retr_tm_count) / 1000.0);
	StatLineF("sdv retr time","ms","%8.1f",
		  Stdev(pab->retr_tm_sum, pab->retr_tm_sum2,
			pab->retr_tm_count) / 1000.0,
		  Stdev(pba->retr_tm_sum, pba->retr_tm_sum2,
			pba->retr_tm_count) / 1000.0);
    }
   
   if(csv || tsv || (sv != NULL)) {
      printf("\n");
      /* Error checking: print an error message if the count of printed fields
       * doesn't correspond to the actual fields expected.
       */
      if(sv_print_count != sv_expected_count) {
	fprintf(stderr, "output.c: Count of printed fields does not correspond to count of header fields for long output with comma/tab/<SP>-separated values.\n");
	fprintf(stderr,"sv_print_count=%u, sv_expected_count=%u\n",
		sv_print_count, sv_expected_count);
	exit(-1);
      }
   }
}
int main()
{
  typedef viennagrid::triangular_2d_mesh                                                  DomainType;
  typedef viennagrid::result_of::segmentation<DomainType>::type                           SegmentationType;
  typedef SegmentationType::iterator                                                      SegmentationIteratorType;
  typedef viennagrid::result_of::segment_handle<SegmentationType>::type                   SegmentType;
  typedef viennagrid::result_of::cell_tag<DomainType>::type                               CellTagType;
  typedef viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type        VertexType;
  typedef viennagrid::result_of::element<DomainType, CellTagType>::type                   CellType;

  typedef viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type  VertexContainerType;
  typedef viennagrid::result_of::iterator<VertexContainerType>::type                      VertexIteratorType;
  typedef viennagrid::result_of::element_range<SegmentType, CellTagType>::type            CellOnSegmentContainerType;
  typedef viennagrid::result_of::iterator<CellOnSegmentContainerType>::type               CellOnSegmentIteratorType;

  typedef boost::numeric::ublas::compressed_matrix<viennafem::numeric_type>  MatrixType;
  typedef boost::numeric::ublas::vector<viennafem::numeric_type>             VectorType;

  typedef viennamath::function_symbol   FunctionSymbol;
  typedef viennamath::equation          Equation;

  //
  // Create a domain from file
  //
  DomainType my_domain;
  SegmentationType segments(my_domain);

  //
  // Create a storage object
  //
  typedef viennadata::storage<> StorageType;
  StorageType   storage;

  try
  {
    viennagrid::io::netgen_reader my_netgen_reader;
    my_netgen_reader(my_domain, segments, "../examples/data/square224.mesh");
  }
  catch (...)
  {
    std::cerr << "File-Reader failed. Aborting program..." << std::endl;
    return EXIT_FAILURE;
  }


  //
  // Specify Poisson equation with inhomogeneous permittivity:
  //
  FunctionSymbol u(0, viennamath::unknown_tag<>());   //an unknown function used for PDE specification
  FunctionSymbol v(0, viennamath::test_tag<>());   //an unknown function used for PDE specification
  viennafem::cell_quan<CellType, viennamath::expr::interface_type>  permittivity; permittivity.wrap_constant( storage, permittivity_key() );

  //the strong form (not yet functional because of ViennaMath limitations)
  //Equation poisson_equ = viennamath::make_equation( viennamath::div(permittivity * viennamath::grad(u)), 0);

  //the weak form:
  Equation poisson_equ = viennamath::make_equation(
                          viennamath::integral(viennamath::symbolic_interval(),
                                               permittivity * (viennamath::grad(u) * viennamath::grad(v)) ),
                          0);

  MatrixType system_matrix;
  VectorType load_vector;

  //
  // Setting boundary information on domain (this should come from device specification)
  //
  //setting some boundary flags:
  VertexContainerType vertices = viennagrid::elements<VertexType>(my_domain);
  for (VertexIteratorType vit = vertices.begin();
      vit != vertices.end();
      ++vit)
  {
    // Boundary condition: 0 at left boundary, 1 at right boundary
    if ( viennagrid::point(my_domain, *vit)[0] == 0.0)
      viennafem::set_dirichlet_boundary(storage, *vit, 0.0);
    else if ( viennagrid::point(my_domain, *vit)[0] == 1.0)
      viennafem::set_dirichlet_boundary(storage, *vit, 1.0);

  }


  //
  // Create PDE solver functors: (discussion about proper interface required)
  //
  viennafem::pde_assembler<StorageType> fem_assembler(storage);


  //
  // Solve system and write solution vector to pde_result:
  // (discussion about proper interface required. Introduce a pde_result class?)
  //
  std::size_t si = 0;
  for(SegmentationIteratorType sit = segments.begin(); sit != segments.end(); sit++)
  {
    //set permittivity:
    CellOnSegmentContainerType cells = viennagrid::elements<CellType>(*sit);
    for (CellOnSegmentIteratorType cit  = cells.begin();
                                   cit != cells.end();
                                 ++cit)
    {
      if (si == 0) //Si
        viennadata::access<permittivity_key, double>(storage, permittivity_key(), *cit) = 3.9;
      else //SiO2
        viennadata::access<permittivity_key, double>(storage, permittivity_key(), *cit) = 11.9;
    }


    fem_assembler(viennafem::make_linear_pde_system(poisson_equ,
                                                    u,
                                                    viennafem::make_linear_pde_options(0,
                                                                                       viennafem::lagrange_tag<1>(),
                                                                                       viennafem::lagrange_tag<1>())
                                                  ),
                  *sit,
                  system_matrix,
                  load_vector
                );
  }

  VectorType pde_result = viennacl::linalg::solve(system_matrix, load_vector, viennacl::linalg::cg_tag());
  std::cout << "* solve(): Residual: " << norm_2(prod(system_matrix, pde_result) - load_vector) << std::endl;

  //
  // Writing solution back to domain (discussion about proper way of returning a solution required...)
  //
  viennafem::io::write_solution_to_VTK_file(pde_result, "poisson_cellquan_2d", my_domain, segments, storage, 0);

  std::cout << "*****************************************" << std::endl;
  std::cout << "* Poisson solver finished successfully! *" << std::endl;
  std::cout << "*****************************************" << std::endl;
  return EXIT_SUCCESS;
}
std::array<std::uint32_t, SegmentNumber> summarizeRoute(const std::vector<PathData> &route_data,
                                                        const PhantomNode &target_node,
                                                        const bool target_traversed_in_reverse)
{
    // merges segments with same name id
    const auto collapse_segments = [](std::vector<NamedSegment> &segments) {
        auto out = segments.begin();
        auto end = segments.end();

        // Do nothing if we were given an empty array
        if (out == end)
        {
            return end;
        }

        for (auto in = std::next(out); in != end; ++in)
        {
            if (in->name_id == out->name_id)
            {
                out->duration += in->duration;
            }
            else
            {
                ++out;
                BOOST_ASSERT(out != end);
                *out = *in;
            }
        }
        BOOST_ASSERT(out != end);
        return ++out;
    };

    std::vector<NamedSegment> segments(route_data.size());
    std::uint32_t index = 0;
    std::transform(
        route_data.begin(), route_data.end(), segments.begin(), [&index](const PathData &point) {
            return NamedSegment{point.duration_until_turn, index++, point.name_id};
        });
    const auto target_duration =
        target_traversed_in_reverse ? target_node.reverse_weight : target_node.forward_weight;
    if (target_duration > 1)
        segments.push_back({target_duration, index++, target_node.name_id});
    // this makes sure that the segment with the lowest position comes first
    std::sort(
        segments.begin(), segments.end(), [](const NamedSegment &lhs, const NamedSegment &rhs) {
            return lhs.name_id < rhs.name_id ||
                   (lhs.name_id == rhs.name_id && lhs.position < rhs.position);
        });
    auto new_end = collapse_segments(segments);
    segments.resize(new_end - segments.begin());

    // Filter out segments with an empty name (name_id == 0)
    new_end = std::remove_if(segments.begin(), segments.end(), [](const NamedSegment &segment) {
        return segment.name_id == 0;
    });
    segments.resize(new_end - segments.begin());

    // sort descending
    std::sort(
        segments.begin(), segments.end(), [](const NamedSegment &lhs, const NamedSegment &rhs) {
            return lhs.duration > rhs.duration ||
                   (lhs.duration == rhs.duration && lhs.position < rhs.position);
        });

    // make sure the segments are sorted by position
    segments.resize(std::min(segments.size(), SegmentNumber));
    std::sort(
        segments.begin(), segments.end(), [](const NamedSegment &lhs, const NamedSegment &rhs) {
            return lhs.position < rhs.position;
        });

    std::array<std::uint32_t, SegmentNumber> summary;
    std::fill(summary.begin(), summary.end(), 0);
    std::transform(segments.begin(),
                   segments.end(),
                   summary.begin(),
                   [](const NamedSegment &segment) { return segment.name_id; });
    return summary;
}
Beispiel #22
0
void Presenter::modelReset()
{
    // 1. We put our current elements in our pool.
    std::vector<PointView*> points(m_points.get().begin(), m_points.get().end());
    std::vector<SegmentView*> segments(m_segments.get().begin(), m_segments.get().end());

    std::vector<PointView*> newPoints;
    std::vector<SegmentView*> newSegments;

    // 2. We add / remove new elements if necessary
    {
        int diff_points = m_model.points().size() - points.size();
        if(diff_points > 0)
        {
            points.reserve(points.size() + diff_points);
            for(;diff_points --> 0;)
            {
                auto pt = new PointView{nullptr, m_style, m_view};
                points.push_back(pt);
                newPoints.push_back(pt);
            }
        }
        else if(diff_points < 0)
        {
            int inv_diff_points = -diff_points;
            for(;inv_diff_points --> 0;)
            {
                deleteGraphicsObject(points[points.size() - inv_diff_points - 1]);
            }
            points.resize(points.size() + diff_points);
        }
    }

    // Same for segments
    {
        int diff_segts = m_model.segments().size() - segments.size();
        if(diff_segts > 0)
        {
            segments.reserve(segments.size() + diff_segts);
            for(;diff_segts --> 0;)
            {
                auto seg = new SegmentView{nullptr, m_style, m_view};
                segments.push_back(seg);
                newSegments.push_back(seg);
            }
        }
        else if(diff_segts < 0)
        {
            int inv_diff_segts = -diff_segts;
            for(;inv_diff_segts --> 0;)
            {
                deleteGraphicsObject(segments[segments.size() - inv_diff_segts - 1]);
            }
            segments.resize(segments.size() + diff_segts);
        }
    }

    ISCORE_ASSERT(points.size() == m_model.points().size());
    ISCORE_ASSERT(segments.size() == m_model.segments().size());

    // 3. We set the data
    { // Points
        int i = 0;
        for(const auto& point : m_model.points())
        {
            points.at(i)->setModel(point);
            i++;
        }
    }
    { // Segments
        int i = 0;
        for(const auto& segment : m_model.segments())
        {
            segments[i]->setModel(&segment);
            i++;
        }
    }

    for(const auto& seg : newSegments)
        setupSegmentConnections(seg);
    for(const auto& pt: newPoints)
        setupPointConnections(pt);

    // Now the ones that have a new model
    // 4. We put them all back in our maps.
    m_points.clear();
    m_segments.clear();

    for(const auto& pt_view : points)
    {
        addPoint_impl(pt_view);
    }
    for(const auto& seg_view : segments)
    {
        addSegment_impl(seg_view);
    }
}
Beispiel #23
0
int main (int argc, char** argv) {
    if(argc < 4) {
        std::cout << "3 command line arguments are needed.\nPlease execute with ./hw0 <input_filename> <process #> <number of match list>\n";
        return 0;
    }
    FILE* fPtr; //file pointer to file to be parsed
    char *line; //line to parse file line by line

    fPtr = fopen(argv[1], "r");
    int total_rows = 0;
    line = (char*)malloc(sizeof(char)*LINE_MAX);
    VectorsMap points;
    Parser fileParser;
    //vectors that will be generated for the runs.
    std::vector<std::vector<float>> generated_vectors(30);

    //parse the file line by line
    while(fgets(line, LINE_MAX, fPtr)) {
        //make sure that we do not read an empty line
        if(line[0] != '\0') {
            //send the line to be further parsed
            points.push_back(fileParser.parseLine(line));
            //increment total rows count
            total_rows++;
        }
    }
    free(line);
    fclose(fPtr);

    srand(34122);
    int i,j, process_count=atoi(argv[2]), num_max=atoi(argv[3]), size=0;
    //the size of the search vectors
    int sizes[] = {9,11,17,29};
    int sizes_count = 4;
    //will hold the offsets for each process
    std::vector<segment> segments(process_count);

    //initialize shared memory
    size_t memory_space = process_count*4*num_max;
    float shm_size = memory_space * sizeof(float);
    int shmId;
    // use current time as seed for random generator
    std::srand(std::time(0));
    key_t shmKey = std::rand();
    int shmFlag = IPC_CREAT | 0666;
    float * shm;

    /* Initialize shared memory */
    if((shmId = shmget(shmKey, shm_size, shmFlag)) < 0)
    {
        std::cerr << "Init: Failed to initialize shared memory (" << shmId << ")" << std::endl;
        exit(1);
    }

    if((shm = (float *)shmat(shmId, NULL, 0)) == (float *) -1)
    {
        std::cerr << "Init: Failed to attach shared memory (" << shmId << ")" << std::endl;
        exit(1);
    }
    //get number of items for each process in shared memory
    const unsigned int per_procc_mem = num_max*4;
    //initialize offsets
    for(i=0; i< process_count; i++) {
        //get segments for dataset
        int size = total_rows/process_count;
        segments.at(i).start = size*i;
        segments.at(i).end = size*i + size;

        //get segments for shared memory location segment for each process
        segments.at(i).shm_start = i*per_procc_mem;
        segments.at(i).shm_end = i*per_procc_mem + per_procc_mem;

        //if at the last process, check to see if the division is not even
        if(i==process_count-1)
            segments.at(i).end += total_rows%process_count;
    }

    //create the final results vector
    //reserve enough space to be able to merge all of our processes' stuff
    std::vector<ResultType> final_results;
    std::vector<float> copy;
    final_results.reserve(process_count*num_max);

    //create start and end chrono time points
    std::chrono::time_point<std::chrono::system_clock> start, end;
    std::map<int, double> times;

    //loop through the 4 different sizes of vectors
    for(i=0; i<sizes_count; i++) {


        std::cout << "\n\n==============TEST BEGIN==================\n" << std::endl;
        //run the test:
        copy = generateScottVector(sizes[i]);
        final_results = circularSubvectorMatch(sizes[i], &copy, &points, num_max, 0, total_rows, 0, 0, NULL, true);
        copy.clear();
        //run the test
        if(runTest(sizes[i], &final_results, num_max)) {
            std::cout << "Test was SUCCESSFUL against vector: \n" << std::endl;
            std::cout << scottgs::vectorToCSV(generateScottVector(sizes[i])) << "\n\n" << std::endl;
        } else {
            std::cout << "Test FAILED against vector: \n" << std::endl;
            std::cout << scottgs::vectorToCSV(generateScottVector(sizes[i])) << "\n\n" << std::endl;
            //exit(-1);
        }
        std::cout << "Expected vector results" << std::endl;
        printVector(num_max, final_results, sizes[i]);
        std::cout << "\n\nGenerated vector results" << std::endl;
        printVector(num_max, generateVectorTest(sizes[i]), sizes[i]);

        final_results.clear();
        std::cout << "\n\n==============TEST END==================\n\n\n" << std::endl;


        //generate 30 random vectors of size size[i]
        for(int ii=0; ii< 30; ii++) {
            generated_vectors.at(ii) = generateRandomVector(sizes[i]);
        }

        //for testing purposes I am only doing 1.
        //generated_vectors.at(0).reserve(sizes[i]);
        //generated_vectors.at(0) = generateScottVector(sizes[i]);
        //loop through the (30 vectors specified in the description)
        for(j=0; j<30; j++) {
            //let the first process print the results.
            std::cout << "\n-----------------" << std::endl;
            std::cout << "Search: "<< sizes[i] << "-D" << std::endl;
            std::cout << "-----------------" << std::endl;
            //get an object of the process spawner class..
            start = std::chrono::system_clock::now();
            scottgs::Splitter splitter;
            for (int p = 0; p < process_count; ++p)
            {
                pid_t pid = splitter.spawn();
                if (pid < 0)
                {
                    std::cerr << "Could not fork!!! ("<< pid <<")" << std::endl;
                    // do not exit, we may have a process
                    // spawned from an earlier iteration
                    break;
                }
                if (0 == pid) // Child
                {
                    /* Attach shared memory */
                    if((shm = (float *)shmat(shmId, NULL, 0)) == (float *) -1)
                    {
                        std::cerr << "Init: Failed to attach shared memory (" << shmId << ")" << std::endl;
                        exit(1);
                    }

                    //let only process 0 to print this vector.
                    if(p == 0) {
                        std::cout << "\nSearch Vector: " << std::endl;
                        //print the created vector.
                        std::cout << scottgs::vectorToCSV(generated_vectors[j]) << std::endl;
                    }

                    //perform the test(delete this as it is not needed)
                    //pas the size of the search vector, the auto generated vector, the vectors from the file,
                    //the number of top results to return, and the offset from which to search.
                    circularSubvectorMatch(sizes[i], &generated_vectors[j], &points, num_max, segments.at(p).start, segments.at(p).end, segments.at(p).shm_start, segments.at(p).shm_end, shm, false);

                    //child exists
                    _exit(0);
                }//end if pid==0
            }
            //wait for all children before looping again..
            splitter.reap_all();
            //calculate end time.
            end = std::chrono::system_clock::now();
            //now perform printing and stuff. from shared memory.
            //print end time
            std::chrono::duration<double, std::milli> elapsed_seconds = end-start;
            //std::cout << "\nTime: " << elapsed_seconds.count() << " milliseconds\n" << std::endl;
            //keep a record of the time
            times[sizes[i]] += elapsed_seconds.count();

            //print top num_max results
            printResults(shm, num_max, process_count, sizes[i]);
        }//end 30 vectors loop
    }//end vector_size loop
    std::cout << "\n-----------------" << std::endl;
    std::cout << "Final Results:" << std::endl;
    std::cout << "-----------------\n" << std::endl;
    std::cout << "Size" << "|" << "Average Time" << std::endl;
    std::cout << "-----------------" << std::endl;
    std::cout << times[sizes[0]]/1 << " " << times[sizes[1]]/1 << " " << times[sizes[2]]/1 << " " << times[sizes[3]]/1 << std::endl;

    //detach the memory
    shmdt(shm);
    //delete shared memory after we are done with it.
    shmctl(shmId, IPC_RMID, NULL);

    return 0;
}
bool KDLRobotModel::init(std::string robot_description, std::vector<std::string> &planning_joints)
{
  urdf_ = boost::shared_ptr<urdf::Model>(new urdf::Model());
  if (!urdf_->initString(robot_description))
  {
    ROS_ERROR("Failed to parse the URDF.");
    return false;
  }

  if (!kdl_parser::treeFromUrdfModel(*urdf_, ktree_))
  {
    ROS_ERROR("Failed to parse the kdl tree from robot description.");
    return false;
  }

  std::vector<std::string> segments(planning_joints.size());
  for(size_t j = 0; j < planning_joints.size(); ++j)
  {
    if(!leatherman::getSegmentOfJoint(ktree_, planning_joints[j], segments[j]))
    {
      ROS_ERROR("Failed to find kdl segment for '%s'.", planning_joints_[j].c_str());
      return false;
    }
  }

  /*
  if(!leatherman::getChainTip(ktree_, segments, chain_root_name_, chain_tip_name_))
  {
    ROS_ERROR("Failed to find a valid chain tip link.");
    return false;
  }
  */

  if(!ktree_.getChain(chain_root_name_, chain_tip_name_, kchain_))
  {
    ROS_ERROR("Failed to fetch the KDL chain for the robot. (root: %s, tip: %s)", chain_root_name_.c_str(), chain_tip_name_.c_str());
    return false;
  }

  // check if our chain includes all planning joints
  for(size_t i = 0; i < planning_joints.size(); ++i)
  {
    if(planning_joints[i].empty())
    {
      ROS_ERROR("Planning joint name is empty (index: %d).", int(i));
      return false;
    }
    int index;
    if(!leatherman::getJointIndex(kchain_, planning_joints[i], index))
    {
      ROS_ERROR("Failed to find '%s' in the kinematic chain. Maybe your chain root or tip joints are wrong? (%s, %s)", planning_joints[i].c_str(), chain_root_name_.c_str(), chain_tip_name_.c_str());
      return false;
    }
  }

  // joint limits
  planning_joints_ = planning_joints;
  if(!getJointLimits(planning_joints_, min_limits_, max_limits_, continuous_))
  {
    ROS_ERROR("Failed to get the joint limits.");
    return false;
  }

  // FK solver
  fk_solver_ = new KDL::ChainFkSolverPos_recursive(kchain_);
  jnt_pos_in_.resize(kchain_.getNrOfJoints());
  jnt_pos_out_.resize(kchain_.getNrOfJoints());

  // IK solver
  KDL::JntArray q_min(planning_joints_.size());
  KDL::JntArray q_max(planning_joints_.size());
  for(size_t i = 0; i < planning_joints_.size(); ++i)
  {
    q_min(i) = min_limits_[i];
    q_max(i) = max_limits_[i];
  }
  ik_vel_solver_ = new KDL::ChainIkSolverVel_pinv(kchain_);
  ik_solver_ = new KDL::ChainIkSolverPos_NR_JL(kchain_, q_min, q_max, *fk_solver_, *ik_vel_solver_, 200, 0.001);

  // joint name -> index mapping
  for(size_t i = 0; i < planning_joints_.size(); ++i)
    joint_map_[planning_joints_[i]] = i;

  // link name -> kdl index mapping
  for(size_t i = 0; i < kchain_.getNrOfSegments(); ++i)
    link_map_[kchain_.getSegment(i).getName()] = i;

  initialized_ = true;
  return true;
}
Beispiel #25
0
int main(int argc, char *argv[]) {
  std::string command,
              ucMode,
              volMode,
              inodeMapFile,
              diskMapFile;
  uint64_t    maxUcBlockSize;

  po::options_description desc("Allowed Options");
  po::positional_options_description posOpts;
  posOpts.add("command", 1);
  posOpts.add("ev-files", -1);
  desc.add_options()
    ("help", "produce help message")
    ("command", po::value< std::string >(&command), "command to perform [info|dumpimg|dumpfs|dumpfiles]")
    ("overview-file", po::value< std::string >(), "output disk overview information")
    ("unallocated", po::value< std::string >(&ucMode)->default_value("none"), "how to handle unallocated [none|fragment|block]")
    ("max-unallocated-block-size", po::value< uint64_t >(&maxUcBlockSize)->default_value(std::numeric_limits<uint64_t>::max()), "Maximum size of an unallocated entry, in blocks")
    ("ev-files", po::value< std::vector< std::string > >(), "evidence files")
    ("inode-map-file", po::value<std::string>(&inodeMapFile)->default_value(""), "optional file to output containing directory entry to inode map")
    ("disk-map-file", po::value<std::string>(&diskMapFile)->default_value(""), "optional file to output containing disk data to inode map");

  po::variables_map vm;
  try {
    po::store(po::command_line_parser(argc, argv).options(desc).positional(posOpts).run(), vm);
    po::notify(vm);

    std::shared_ptr<LbtTskAuto> walker;

    std::vector< std::string > imgSegs;
    if (vm.count("ev-files")) {
      imgSegs = vm["ev-files"].as< std::vector< std::string > >();
    }
    if (vm.count("help")) {
      printHelp(desc);
    }
    else if (vm.count("command") && vm.count("ev-files") && (walker = createVisitor(command, std::cout, imgSegs))) {
      std_binary_io();

      boost::scoped_array< const char* >  segments(new const char*[imgSegs.size()]);
      for (unsigned int i = 0; i < imgSegs.size(); ++i) {
        segments[i] = imgSegs[i].c_str();
      }
      if (0 == walker->openImageUtf8(imgSegs.size(), segments.get(), TSK_IMG_TYPE_DETECT, 0)) {
        if (vm.count("overview-file")) {
          std::ofstream file(vm["overview-file"].as<std::string>().c_str(), std::ios::out);
          file << *(walker->getImage(imgSegs));
          file.close();
        }

        walker->setVolFilterFlags((TSK_VS_PART_FLAG_ENUM)(TSK_VS_PART_FLAG_ALLOC | TSK_VS_PART_FLAG_UNALLOC | TSK_VS_PART_FLAG_META));
        walker->setFileFilterFlags((TSK_FS_DIR_WALK_FLAG_ENUM)(TSK_FS_DIR_WALK_FLAG_RECURSE | TSK_FS_DIR_WALK_FLAG_UNALLOC | TSK_FS_DIR_WALK_FLAG_ALLOC));
        if (ucMode == "fragment") {
          walker->setUnallocatedMode(LbtTskAuto::FRAGMENT);
          walker->setMaxUnallocatedBlockSize(maxUcBlockSize);
        }
        else if (ucMode == "block") {
          walker->setUnallocatedMode(LbtTskAuto::BLOCK);
        }
        else {
          walker->setUnallocatedMode(LbtTskAuto::NONE);
        }
        if (0 == walker->start()) {
          walker->startUnallocated();
          walker->finishWalk();
          std::vector<std::future<void>> futs;
          if (vm.count("disk-map-file") && command == "dumpfs") {
            futs.emplace_back(std::async(outputDiskMap, diskMapFile, walker));
          }
          if (vm.count("inode-map-file") && command == "dumpfs") {
            futs.emplace_back(std::async(outputInodeMap, inodeMapFile, walker));
          }
          for (auto& fut: futs) {
            fut.get();
          }
          return 0;
        }
        else {
          std::cout.flush();
          std::cerr << "Had an error parsing filesystem" << std::endl;
          for (auto& err: walker->getErrorList()) {
            std::cerr << err.msg1 << " " << err.msg2 << std::endl;
          }
        }
      }
      else {
        std::cerr << "Had an error opening the evidence file" << std::endl;
        for (unsigned int i = 0; i < imgSegs.size(); ++i) {
          std::cerr << " ** seg[" << i << "] = " << imgSegs[i] << std::endl;
        }
        return 1;
      }
    }
    else {
      std::cerr << "Error: did not understand arguments\n\n";
      printHelp(desc);
      return 1;
    }
  }
  catch (std::exception& err) {
    std::cerr << "Error: " << err.what() << "\n\n";
    printHelp(desc);
    return 1;
  }
  return 0;
}
Beispiel #26
0
int main()
{
  //
  // Create a domain from file
  //
  viennamini::MeshTriangular2DType           mesh;
  viennamini::SegmentationTriangular2DType   segments(mesh);
  viennamini::StorageType                    storage;

  try
  {
    viennagrid::io::netgen_reader my_reader;
//    my_reader(mesh, segments, "../external/ViennaDeviceCollection/nin2d/nin2d.mesh");
    my_reader(mesh, segments, "/home/weinbub/git/ViennaMini/external/ViennaDeviceCollection/nin2d/nin2d.mesh");
  }
  catch (...)
  {
    std::cerr << "File-Reader failed. Aborting program..." << std::endl;
    return EXIT_FAILURE;
  }

  //
  // scale to nanometer
  //
  viennagrid::scale(mesh, 1e-9);

  //
  // Prepare material library
  //
  viennamini::MatLibPugixmlType matlib;
  matlib.load("/home/weinbub/git/ViennaMini/external/ViennaMaterials/database/materials.xml");

  //
  // Create a device and a config object
  //
  viennamini::DeviceTriangular2DType device(mesh, segments, storage);
  viennamini::config config;

  //
  // Prepare device, i.e., assign doping and segment roles,
  // e.g., oxide, semiconductor, contact
  //
  prepare(device);

  //
  // Assign contact values
  //
  prepare_boundary_conditions(config);

  //
  // Set simulation parameters
  //
  config.temperature()                        = 300;
  config.damping()                            = 1.0;
  config.linear_breaktol()                    = 1.0E-13;
  config.linear_iterations()                  = 700;
  config.nonlinear_iterations()               = 100;
  config.nonlinear_breaktol()                 = 1.0E-3;
  config.initial_guess_smoothing_iterations() = 4;

  //
  // Create a simulator object
  //
  viennamini::SimulatorTriangular2DType sim(device, matlib, config);

  //
  // Run the simulation
  //
  sim();

  // Write results to vtk files
  sim.write_result("nin2d");


  std::cout << "********************************************" << std::endl;
  std::cout << "* NIN2D simulation finished successfully! *" << std::endl;
  std::cout << "********************************************" << std::endl;
  return EXIT_SUCCESS;
}
Beispiel #27
0
const CrisisAlgorithmResult& CrisisAlgorithmChecker::execute()
{
    if (m_executed)
        return m_result;

    m_executed = true;
    m_months = 1;
    clock_t timeVal = clock();

    vector<int> segments(boost::num_vertices(m_graph));

    int nmbOfComponents = boost::connected_components(m_graph, &segments[0]);

    if (nmbOfComponents != 1) {
        int capitolComponent = segments[m_capitol];

        int connectedWithCapitol = 0;
        for (int i = 0; i < m_numberOfCities; ++i) {
            if (segments[i] != capitolComponent) {
                if (m_result[i] == -1) {
                    m_result.addResult(i, 0);
                }
            } else {
                ++connectedWithCapitol;
            }
        }
        if (connectedWithCapitol == 0) {
            timeVal = clock() - timeVal;
            m_result.addExecutionTime(timeVal);
            return m_result;
        }
    }

    bool exist;
    EdgeID edge;
    for (vector<pair<int, int> >::const_iterator it = m_toCut->begin();
            it != m_toCut->end(); ++it, ++m_months) {
        boost::tie(edge, exist) = boost::edge(m_verticles[it->first],
                m_verticles[it->second], m_graph);

        if (exist) {
            if (m_graph[edge].m_isDouble) {
                m_graph[edge].m_isDouble = false;
                continue;
            } else {
                m_graph.remove_edge(edge);
            }
        } else {
            throw InvalidArgumentsException("No such connection");
        }

        vector<int> component(boost::num_vertices(m_graph));

        int nmbOfComponents = boost::connected_components(m_graph,
                &component[0]);

        if (nmbOfComponents != 1) {
            int capitolComponent = component[m_capitol];

            int connectedWithCapitol = 0;
            for (int i = 0; i < m_numberOfCities; ++i) {
                if (component[i] != capitolComponent) {
                    if (m_result[i] == -1) {
                        m_result.addResult(i, m_months);
                    }
                } else {
                    ++connectedWithCapitol;
                }
            }
            if (connectedWithCapitol == 0)
                break;
        }
    }

    timeVal = clock() - timeVal;
    m_result.addExecutionTime(timeVal);
    return m_result;
}
Beispiel #28
0
std::string Path::getName() const {
    if (isEmpty()) return "";

    std::vector<std::string> segments(split());
    return segments.back();
}
Beispiel #29
0
void reduce(Route& src, Route& sink, double maxDistance) {
  if(maxDistance == 0)
    return;
  LOG_DEBUG(src.size());

  typedef SegmentGraphImpl<boost::setS, boost::setS> UniqueSegmentGraph;
  UniqueSegmentGraph g;

  for(const SegmentPtr seg : segments(src)) {
    g.addSegment(*seg.get());
  }

  std::map<Point, UniqueSegmentGraph::Vertex> index;
  BOOST_FOREACH(UniqueSegmentGraph::Vertex v, vertices(g)) {
    index[g[v]] = v;
  }

  for(Path& path : src) {
    Path singleBranch;
    Path simplified;
    Point last = path.front();
    Point current;
    for(const SegmentPtr segPtr :  segments(path)) {
      const Segment& seg = *segPtr.get();
      concat(singleBranch,seg);
      if(last == seg.first)
        current = seg.second;
      else
        assert(false);

      last = current;
      if(boost::degree(index[current],g) > 2) {
        boost::geometry::simplify(singleBranch, simplified, maxDistance);
        if(!is_collapsed(singleBranch, simplified))
          add(sink, simplified);
        else {
          Box b;
          boost::geometry::envelope(simplified, b);
          if(b.width() > maxDistance && b.height() > maxDistance) {
            add(sink, simplified);
          }
        }

        singleBranch.clear();
        simplified.clear();
      }
    }

    if (!singleBranch.empty()) {
      boost::geometry::simplify(singleBranch, simplified, maxDistance);
      if (!is_collapsed(singleBranch, simplified))
        add(sink, simplified);
      else {
        Box b;
        boost::geometry::envelope(simplified, b);
        if(b.width() > maxDistance && b.height() > maxDistance) {
          add(sink, simplified);
        }
      }
    }

    singleBranch.clear();
    simplified.clear();
  }
  LOG_DEBUG(sink.size());
}
int main()
{
  typedef viennagrid::hexahedral_3d_mesh                                                  DomainType;
  typedef viennagrid::result_of::segmentation<DomainType>::type                           SegmentationType;

  typedef viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type        VertexType;
  typedef viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type  VertexContainer;
  typedef viennagrid::result_of::iterator<VertexContainer>::type                          VertexIterator;

  typedef boost::numeric::ublas::compressed_matrix<viennafem::numeric_type>  MatrixType;
  typedef boost::numeric::ublas::vector<viennafem::numeric_type>             VectorType;

  typedef viennamath::function_symbol   FunctionSymbol;
  typedef viennamath::equation          Equation;

  //
  // Create a domain from file
  //
  DomainType my_domain;
  SegmentationType segments(my_domain);

  //
  // Create a storage object
  //
  typedef viennadata::storage<> StorageType;
  StorageType   storage;

  try
  {
    viennagrid::io::netgen_reader my_reader;
    my_reader(my_domain, segments, "../examples/data/cube343_hex.mesh");
  }
  catch (...)
  {
    std::cerr << "File-Reader failed. Aborting program..." << std::endl;
    exit(EXIT_FAILURE);
  }


  //
  // Specify two PDEs:
  //
  FunctionSymbol u(0, viennamath::unknown_tag<>());   //an unknown function used for PDE specification
  Equation poisson_equ_1 = viennamath::make_equation( viennamath::laplace(u), -1);
  Equation poisson_equ_2 = viennamath::make_equation( viennamath::laplace(u), -1);

  MatrixType system_matrix_1, system_matrix_2;
  VectorType load_vector_1, load_vector_2;

  //
  // Setting boundary information on domain (this should come from device specification)
  //
  //setting some boundary flags:
  VertexContainer vertices = viennagrid::elements<VertexType>(my_domain);
  for (VertexIterator vit = vertices.begin();
      vit != vertices.end();
      ++vit)
  {
    // First equation: Homogeneous boundary conditions at x=0, x=1, y=0, or y=1
    if ( viennagrid::point(my_domain, *vit)[0] == 0.0 || viennagrid::point(my_domain, *vit)[0] == 1.0
         || viennagrid::point(my_domain, *vit)[1] == 0.0 || viennagrid::point(my_domain, *vit)[1] == 1.0 )
      viennafem::set_dirichlet_boundary(storage, *vit, 0.0, 0);  //simulation with ID 0 uses homogeneous boundary data

    // Boundary for second equation (ID 1): 0 at left boundary, 1 at right boundary
    if ( viennagrid::point(my_domain, *vit)[0] == 0.0)
      viennafem::set_dirichlet_boundary(storage, *vit, 0.0, 1);
    else if ( viennagrid::point(my_domain, *vit)[0] == 1.0)
      viennafem::set_dirichlet_boundary(storage, *vit, 1.0, 1);
  }


  //
  // Create PDE solver functors: (discussion about proper interface required)
  //
  viennafem::pde_assembler<StorageType> fem_assembler(storage);


  //
  // Solve system and write solution vector to pde_result:
  // (discussion about proper interface required. Introduce a pde_result class?)
  //
  fem_assembler(viennafem::make_linear_pde_system(poisson_equ_1,
                                                  u,
                                                  viennafem::make_linear_pde_options(0,
                                                                                     viennafem::lagrange_tag<1>(),
                                                                                     viennafem::lagrange_tag<1>())
                                                 ),
                my_domain,
                system_matrix_1,
                load_vector_1
               );

  fem_assembler(viennafem::make_linear_pde_system(poisson_equ_2,
                                                  u,
                                                  viennafem::make_linear_pde_options(1,
                                                                                     viennafem::lagrange_tag<1>(),
                                                                                     viennafem::lagrange_tag<1>())
                                                 ),
                my_domain,
                system_matrix_2,
                load_vector_2
               );

  VectorType pde_result_1 = viennacl::linalg::solve(system_matrix_1, load_vector_1, viennacl::linalg::cg_tag());
  std::cout << "* solve(): Residual: " << norm_2(prod(system_matrix_1, pde_result_1) - load_vector_1) << std::endl;

  VectorType pde_result_2 = viennacl::linalg::solve(system_matrix_2, load_vector_2, viennacl::linalg::cg_tag());
  std::cout << "* solve(): Residual: " << norm_2(prod(system_matrix_2, pde_result_2) - load_vector_2) << std::endl;


  //
  // Writing solution back to domain (discussion about proper way of returning a solution required...)
  //
  viennafem::io::write_solution_to_VTK_file(pde_result_1, "poisson_3d_hex_1", my_domain, segments, storage, 0);
  viennafem::io::write_solution_to_VTK_file(pde_result_2, "poisson_3d_hex_2", my_domain, segments, storage, 1);

  std::cout << "*****************************************" << std::endl;
  std::cout << "* Poisson solver finished successfully! *" << std::endl;
  std::cout << "*****************************************" << std::endl;
  return EXIT_SUCCESS;
}