hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
0f4b2620111c0c637ebf58c05c1096e8cdbd07e2
3,525
cpp
C++
src/batchQuery.cpp
drtamermansour/Kprocessor
3356d7dad5a8c55cebe49a63113c41ef536d1b9c
[ "BSD-3-Clause" ]
8
2018-10-12T11:02:55.000Z
2021-08-29T14:46:02.000Z
src/batchQuery.cpp
drtamermansour/Kprocessor
3356d7dad5a8c55cebe49a63113c41ef536d1b9c
[ "BSD-3-Clause" ]
79
2019-03-16T15:31:43.000Z
2022-03-21T18:56:55.000Z
src/batchQuery.cpp
drtamermansour/Kprocessor
3356d7dad5a8c55cebe49a63113c41ef536d1b9c
[ "BSD-3-Clause" ]
2
2019-06-21T11:48:11.000Z
2021-04-09T00:47:54.000Z
#include "batchQuery.hpp" #include "algorithms.hpp" // ----------------- colored kDataFrame Batch Query ----------------- ckf_batchQuery::ckf_batchQuery(colored_kDataFrame *ckFrame, std::string filename, std::map<std::string, int> parse_params, int chunk_size) { // parse_params["mode"] = 1 > Default: Kmers // parse_params["mode"] = 2 > Skipmers // parse_params["mode"] = 3 > Minimizers // Initialize kmerDecoder std::string mode = "kmers"; bool check_mode = (parse_params.find("mode") != parse_params.end()); if (check_mode) { if (parse_params["mode"] == 2) mode = "skipmers"; else if (parse_params["mode"] == 3) mode = "minimizers"; } this->KD = kProcessor::initialize_kmerDecoder(filename, chunk_size, mode, parse_params); this->ckFrame = ckFrame; } void ckf_batchQuery::next() { this->KD->next_chunk(); } bool ckf_batchQuery::end() { return this->KD->end(); } void ckf_batchQuery::flush_results() { this->results.clear(); } std::unordered_map<std::string, vector<vector<uint32_t>>> ckf_batchQuery::get_transcripts() { this->flush_results(); for (const auto &seq : *KD->getKmers()) { std::vector<vector<uint32_t>> temp_tr_ids; for (const auto &kmer : seq.second) { std::vector<uint32_t> temp_kmer_sources; this->ckFrame->getKmerSource(kmer.hash, temp_kmer_sources); temp_tr_ids.emplace_back(temp_kmer_sources); } this->results[seq.first] = temp_tr_ids; } return this->results; } // ----------------- kDataFrame Batch Query ----------------- kf_batchQuery::kf_batchQuery(colored_kDataFrame *ckFrame, std::string filename, std::map<std::string, int> parse_params, int chunk_size) { // parse_params["mode"] = 1 > Default: Kmers // parse_params["mode"] = 2 > Skipmers // parse_params["mode"] = 3 > Minimizers // Initialize kmerDecoder std::string mode = "kmers"; bool check_mode = (parse_params.find("mode") != parse_params.end()); if (check_mode) { if (parse_params["mode"] == 2) mode = "skipmers"; else if (parse_params["mode"] == 3) mode = "minimizers"; } this->KD = kProcessor::initialize_kmerDecoder(filename, chunk_size, mode, parse_params); this->kFrame = ckFrame->getkDataFrame(); } kf_batchQuery::kf_batchQuery(kDataFrame *kFrame, std::string filename, std::map<std::string, int> parse_params, int chunk_size) { std::string mode = "kmers"; bool check_mode = (parse_params.find("mode") != parse_params.end()); if (check_mode) { if (parse_params["mode"] == 2) mode = "skipmers"; else if (parse_params["mode"] == 3) mode = "minimizers"; } this->KD = kProcessor::initialize_kmerDecoder(filename, chunk_size, mode, parse_params); this->kFrame = kFrame; } void kf_batchQuery::next() { this->KD->next_chunk(); } bool kf_batchQuery::end() { return this->KD->end(); } void kf_batchQuery::flush_results() { this->results.clear(); } std::unordered_map<std::string, vector<uint32_t>> kf_batchQuery::get_transcripts() { this->flush_results(); for (const auto &seq : *KD->getKmers()) { std::vector<uint32_t> temp_counts; for (const auto &kmer : seq.second) { temp_counts.emplace_back(this->kFrame->getCount(kmer.hash)); } this->results[seq.first] = temp_counts; } return this->results; }
29.132231
93
0.61844
[ "vector" ]
0f4deb7f85aac27838ec20254021e53ca62d4987
497
cpp
C++
LeetCode/Problems/Algorithms/#264_UglyNumberII_sol3_full_generation_404ms_19.8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#264_UglyNumberII_sol3_full_generation_404ms_19.8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#264_UglyNumberII_sol3_full_generation_404ms_19.8MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int nthUglyNumber(int n) { vector<int> ugly_numbers; for(long long two = 1; two <= INT_MAX; two *= 2){ for(long long three = two; three <= INT_MAX; three *= 3){ for(long long five = three; five <= INT_MAX; five *= 5){ ugly_numbers.push_back(five); } } } sort(ugly_numbers.begin(), ugly_numbers.end()); return ugly_numbers[n - 1]; } };
33.133333
73
0.488934
[ "vector" ]
0f4e146c1a5c4b7a333f049d81294fd0c782e903
630
hh
C++
cc/scan-lineages.hh
acorg/seqdb-3
55513a55381f9911ebfe58d0d60fac366f89c07b
[ "MIT" ]
null
null
null
cc/scan-lineages.hh
acorg/seqdb-3
55513a55381f9911ebfe58d0d60fac366f89c07b
[ "MIT" ]
null
null
null
cc/scan-lineages.hh
acorg/seqdb-3
55513a55381f9911ebfe58d0d60fac366f89c07b
[ "MIT" ]
null
null
null
#pragma once #include <vector> // ---------------------------------------------------------------------- namespace acmacs::seqdb { inline namespace v3 { namespace scan { namespace fasta { struct scan_result_t; } void detect_lineages_clades(std::vector<fasta::scan_result_t>& sequences); } // namespace scan } // namespace v3 } // namespace acmacs::seqdb // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
22.5
86
0.428571
[ "vector" ]
0f5180c2b5b51988ad86fcabdf7dfb76c1515fc0
39,108
cpp
C++
Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
19,438
2019-05-20T15:11:11.000Z
2022-03-31T23:31:32.000Z
Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
7,882
2019-05-20T01:03:52.000Z
2022-03-31T23:26:31.000Z
Userland/Libraries/LibWeb/CSS/StyleComputer.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
2,721
2019-05-23T00:44:57.000Z
2022-03-31T22:49:34.000Z
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * Copyright (c) 2021, the SerenityOS developers. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/QuickSort.h> #include <AK/TemporaryChange.h> #include <LibGfx/Font.h> #include <LibGfx/FontDatabase.h> #include <LibWeb/CSS/CSSStyleRule.h> #include <LibWeb/CSS/Parser/Parser.h> #include <LibWeb/CSS/SelectorEngine.h> #include <LibWeb/CSS/StyleComputer.h> #include <LibWeb/CSS/StyleSheet.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Element.h> #include <LibWeb/Dump.h> #include <LibWeb/FontCache.h> #include <LibWeb/HTML/BrowsingContext.h> #include <ctype.h> #include <stdio.h> namespace Web::CSS { StyleComputer::StyleComputer(DOM::Document& document) : m_document(document) { } StyleComputer::~StyleComputer() { } static StyleSheet& default_stylesheet() { static StyleSheet* sheet; if (!sheet) { extern char const default_stylesheet_source[]; String css = default_stylesheet_source; sheet = parse_css(CSS::ParsingContext(), css).leak_ref(); } return *sheet; } static StyleSheet& quirks_mode_stylesheet() { static StyleSheet* sheet; if (!sheet) { extern char const quirks_mode_stylesheet_source[]; String css = quirks_mode_stylesheet_source; sheet = parse_css(CSS::ParsingContext(), css).leak_ref(); } return *sheet; } template<typename Callback> void StyleComputer::for_each_stylesheet(CascadeOrigin cascade_origin, Callback callback) const { if (cascade_origin == CascadeOrigin::Any || cascade_origin == CascadeOrigin::UserAgent) { callback(default_stylesheet()); if (document().in_quirks_mode()) callback(quirks_mode_stylesheet()); } if (cascade_origin == CascadeOrigin::Any || cascade_origin == CascadeOrigin::Author) { for (auto& sheet : document().style_sheets().sheets()) { callback(sheet); } } } Vector<MatchingRule> StyleComputer::collect_matching_rules(DOM::Element const& element, CascadeOrigin declaration_type) const { Vector<MatchingRule> matching_rules; size_t style_sheet_index = 0; for_each_stylesheet(declaration_type, [&](auto& sheet) { size_t rule_index = 0; static_cast<CSSStyleSheet const&>(sheet).for_each_effective_style_rule([&](auto const& rule) { size_t selector_index = 0; for (auto& selector : rule.selectors()) { if (SelectorEngine::matches(selector, element)) { matching_rules.append({ rule, style_sheet_index, rule_index, selector_index, selector.specificity() }); break; } ++selector_index; } ++rule_index; }); ++style_sheet_index; }); return matching_rules; } void StyleComputer::sort_matching_rules(Vector<MatchingRule>& matching_rules) const { quick_sort(matching_rules, [&](MatchingRule& a, MatchingRule& b) { auto& a_selector = a.rule->selectors()[a.selector_index]; auto& b_selector = b.rule->selectors()[b.selector_index]; auto a_specificity = a_selector.specificity(); auto b_specificity = b_selector.specificity(); if (a_selector.specificity() == b_selector.specificity()) { if (a.style_sheet_index == b.style_sheet_index) return a.rule_index < b.rule_index; return a.style_sheet_index < b.style_sheet_index; } return a_specificity < b_specificity; }); } enum class Edge { Top, Right, Bottom, Left, All, }; static bool contains(Edge a, Edge b) { return a == b || b == Edge::All; } static void set_property_expanding_shorthands(StyleProperties& style, CSS::PropertyID property_id, StyleValue const& value, DOM::Document& document) { auto assign_edge_values = [&style](PropertyID top_property, PropertyID right_property, PropertyID bottom_property, PropertyID left_property, auto const& values) { if (values.size() == 4) { style.set_property(top_property, values[0]); style.set_property(right_property, values[1]); style.set_property(bottom_property, values[2]); style.set_property(left_property, values[3]); } else if (values.size() == 3) { style.set_property(top_property, values[0]); style.set_property(right_property, values[1]); style.set_property(bottom_property, values[2]); style.set_property(left_property, values[1]); } else if (values.size() == 2) { style.set_property(top_property, values[0]); style.set_property(right_property, values[1]); style.set_property(bottom_property, values[0]); style.set_property(left_property, values[1]); } else if (values.size() == 1) { style.set_property(top_property, values[0]); style.set_property(right_property, values[0]); style.set_property(bottom_property, values[0]); style.set_property(left_property, values[0]); } }; if (property_id == CSS::PropertyID::TextDecoration) { if (value.is_text_decoration()) { auto& text_decoration = value.as_text_decoration(); style.set_property(CSS::PropertyID::TextDecorationLine, text_decoration.line()); style.set_property(CSS::PropertyID::TextDecorationStyle, text_decoration.style()); style.set_property(CSS::PropertyID::TextDecorationColor, text_decoration.color()); return; } style.set_property(CSS::PropertyID::TextDecorationLine, value); style.set_property(CSS::PropertyID::TextDecorationStyle, value); style.set_property(CSS::PropertyID::TextDecorationColor, value); return; } if (property_id == CSS::PropertyID::Overflow) { if (value.is_overflow()) { auto& overflow = value.as_overflow(); style.set_property(CSS::PropertyID::OverflowX, overflow.overflow_x()); style.set_property(CSS::PropertyID::OverflowY, overflow.overflow_y()); return; } style.set_property(CSS::PropertyID::OverflowX, value); style.set_property(CSS::PropertyID::OverflowY, value); return; } if (property_id == CSS::PropertyID::Border) { set_property_expanding_shorthands(style, CSS::PropertyID::BorderTop, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BorderRight, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BorderBottom, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BorderLeft, value, document); // FIXME: Also reset border-image, in line with the spec: https://www.w3.org/TR/css-backgrounds-3/#border-shorthands return; } if (property_id == CSS::PropertyID::BorderRadius) { if (value.is_value_list()) { auto& values_list = value.as_value_list(); assign_edge_values(PropertyID::BorderTopLeftRadius, PropertyID::BorderTopRightRadius, PropertyID::BorderBottomRightRadius, PropertyID::BorderBottomLeftRadius, values_list.values()); return; } style.set_property(CSS::PropertyID::BorderTopLeftRadius, value); style.set_property(CSS::PropertyID::BorderTopRightRadius, value); style.set_property(CSS::PropertyID::BorderBottomRightRadius, value); style.set_property(CSS::PropertyID::BorderBottomLeftRadius, value); return; } if (property_id == CSS::PropertyID::BorderTop || property_id == CSS::PropertyID::BorderRight || property_id == CSS::PropertyID::BorderBottom || property_id == CSS::PropertyID::BorderLeft) { Edge edge = Edge::All; switch (property_id) { case CSS::PropertyID::BorderTop: edge = Edge::Top; break; case CSS::PropertyID::BorderRight: edge = Edge::Right; break; case CSS::PropertyID::BorderBottom: edge = Edge::Bottom; break; case CSS::PropertyID::BorderLeft: edge = Edge::Left; break; default: break; } if (value.is_border()) { auto& border = value.as_border(); if (contains(Edge::Top, edge)) { style.set_property(PropertyID::BorderTopWidth, border.border_width()); style.set_property(PropertyID::BorderTopStyle, border.border_style()); style.set_property(PropertyID::BorderTopColor, border.border_color()); } if (contains(Edge::Right, edge)) { style.set_property(PropertyID::BorderRightWidth, border.border_width()); style.set_property(PropertyID::BorderRightStyle, border.border_style()); style.set_property(PropertyID::BorderRightColor, border.border_color()); } if (contains(Edge::Bottom, edge)) { style.set_property(PropertyID::BorderBottomWidth, border.border_width()); style.set_property(PropertyID::BorderBottomStyle, border.border_style()); style.set_property(PropertyID::BorderBottomColor, border.border_color()); } if (contains(Edge::Left, edge)) { style.set_property(PropertyID::BorderLeftWidth, border.border_width()); style.set_property(PropertyID::BorderLeftStyle, border.border_style()); style.set_property(PropertyID::BorderLeftColor, border.border_color()); } return; } return; } if (property_id == CSS::PropertyID::BorderStyle) { if (value.is_value_list()) { auto& values_list = value.as_value_list(); assign_edge_values(PropertyID::BorderTopStyle, PropertyID::BorderRightStyle, PropertyID::BorderBottomStyle, PropertyID::BorderLeftStyle, values_list.values()); return; } style.set_property(CSS::PropertyID::BorderTopStyle, value); style.set_property(CSS::PropertyID::BorderRightStyle, value); style.set_property(CSS::PropertyID::BorderBottomStyle, value); style.set_property(CSS::PropertyID::BorderLeftStyle, value); return; } if (property_id == CSS::PropertyID::BorderWidth) { if (value.is_value_list()) { auto& values_list = value.as_value_list(); assign_edge_values(PropertyID::BorderTopWidth, PropertyID::BorderRightWidth, PropertyID::BorderBottomWidth, PropertyID::BorderLeftWidth, values_list.values()); return; } style.set_property(CSS::PropertyID::BorderTopWidth, value); style.set_property(CSS::PropertyID::BorderRightWidth, value); style.set_property(CSS::PropertyID::BorderBottomWidth, value); style.set_property(CSS::PropertyID::BorderLeftWidth, value); return; } if (property_id == CSS::PropertyID::BorderColor) { if (value.is_value_list()) { auto& values_list = value.as_value_list(); assign_edge_values(PropertyID::BorderTopColor, PropertyID::BorderRightColor, PropertyID::BorderBottomColor, PropertyID::BorderLeftColor, values_list.values()); return; } style.set_property(CSS::PropertyID::BorderTopColor, value); style.set_property(CSS::PropertyID::BorderRightColor, value); style.set_property(CSS::PropertyID::BorderBottomColor, value); style.set_property(CSS::PropertyID::BorderLeftColor, value); return; } if (property_id == CSS::PropertyID::Background) { if (value.is_background()) { auto& background = value.as_background(); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, background.color(), document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, background.image(), document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, background.position(), document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, background.size(), document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, background.repeat(), document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, background.attachment(), document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, background.origin(), document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, background.clip(), document); return; } set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundColor, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundImage, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundPosition, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundSize, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundRepeat, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundAttachment, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundOrigin, value, document); set_property_expanding_shorthands(style, CSS::PropertyID::BackgroundClip, value, document); return; } if (property_id == CSS::PropertyID::Margin) { if (value.is_value_list()) { auto& values_list = value.as_value_list(); assign_edge_values(PropertyID::MarginTop, PropertyID::MarginRight, PropertyID::MarginBottom, PropertyID::MarginLeft, values_list.values()); return; } style.set_property(CSS::PropertyID::MarginTop, value); style.set_property(CSS::PropertyID::MarginRight, value); style.set_property(CSS::PropertyID::MarginBottom, value); style.set_property(CSS::PropertyID::MarginLeft, value); return; } if (property_id == CSS::PropertyID::Padding) { if (value.is_value_list()) { auto& values_list = value.as_value_list(); assign_edge_values(PropertyID::PaddingTop, PropertyID::PaddingRight, PropertyID::PaddingBottom, PropertyID::PaddingLeft, values_list.values()); return; } style.set_property(CSS::PropertyID::PaddingTop, value); style.set_property(CSS::PropertyID::PaddingRight, value); style.set_property(CSS::PropertyID::PaddingBottom, value); style.set_property(CSS::PropertyID::PaddingLeft, value); return; } if (property_id == CSS::PropertyID::ListStyle) { if (value.is_list_style()) { auto& list_style = value.as_list_style(); style.set_property(CSS::PropertyID::ListStylePosition, list_style.position()); style.set_property(CSS::PropertyID::ListStyleImage, list_style.image()); style.set_property(CSS::PropertyID::ListStyleType, list_style.style_type()); return; } style.set_property(CSS::PropertyID::ListStylePosition, value); style.set_property(CSS::PropertyID::ListStyleImage, value); style.set_property(CSS::PropertyID::ListStyleType, value); return; } if (property_id == CSS::PropertyID::Font) { if (value.is_font()) { auto& font_shorthand = value.as_font(); style.set_property(CSS::PropertyID::FontSize, font_shorthand.font_size()); style.set_property(CSS::PropertyID::FontFamily, font_shorthand.font_families()); style.set_property(CSS::PropertyID::FontStyle, font_shorthand.font_style()); style.set_property(CSS::PropertyID::FontWeight, font_shorthand.font_weight()); style.set_property(CSS::PropertyID::LineHeight, font_shorthand.line_height()); // FIXME: Implement font-stretch and font-variant return; } style.set_property(CSS::PropertyID::FontSize, value); style.set_property(CSS::PropertyID::FontFamily, value); style.set_property(CSS::PropertyID::FontStyle, value); style.set_property(CSS::PropertyID::FontWeight, value); style.set_property(CSS::PropertyID::LineHeight, value); // FIXME: Implement font-stretch and font-variant return; } if (property_id == CSS::PropertyID::Flex) { if (value.is_flex()) { auto& flex = value.as_flex(); style.set_property(CSS::PropertyID::FlexGrow, flex.grow()); style.set_property(CSS::PropertyID::FlexShrink, flex.shrink()); style.set_property(CSS::PropertyID::FlexBasis, flex.basis()); return; } style.set_property(CSS::PropertyID::FlexGrow, value); style.set_property(CSS::PropertyID::FlexShrink, value); style.set_property(CSS::PropertyID::FlexBasis, value); return; } if (property_id == CSS::PropertyID::FlexFlow) { if (value.is_flex_flow()) { auto& flex_flow = value.as_flex_flow(); style.set_property(CSS::PropertyID::FlexDirection, flex_flow.flex_direction()); style.set_property(CSS::PropertyID::FlexWrap, flex_flow.flex_wrap()); return; } style.set_property(CSS::PropertyID::FlexDirection, value); style.set_property(CSS::PropertyID::FlexWrap, value); return; } style.set_property(property_id, value); } StyleComputer::CustomPropertyResolutionTuple StyleComputer::resolve_custom_property_with_specificity(DOM::Element& element, String const& custom_property_name) const { if (auto maybe_property = element.resolve_custom_property(custom_property_name); maybe_property.has_value()) return maybe_property.value(); auto parent_element = element.parent_element(); CustomPropertyResolutionTuple parent_resolved {}; if (parent_element) parent_resolved = resolve_custom_property_with_specificity(*parent_element, custom_property_name); auto matching_rules = collect_matching_rules(element); sort_matching_rules(matching_rules); for (int i = matching_rules.size() - 1; i >= 0; --i) { auto& match = matching_rules[i]; if (match.specificity < parent_resolved.specificity) continue; auto custom_property_style = verify_cast<PropertyOwningCSSStyleDeclaration>(match.rule->declaration()).custom_property(custom_property_name); if (custom_property_style.has_value()) { element.add_custom_property(custom_property_name, { custom_property_style.value(), match.specificity }); return { custom_property_style.value(), match.specificity }; } } return parent_resolved; } Optional<StyleProperty> StyleComputer::resolve_custom_property(DOM::Element& element, String const& custom_property_name) const { auto resolved_with_specificity = resolve_custom_property_with_specificity(element, custom_property_name); return resolved_with_specificity.style; } struct MatchingDeclarations { Vector<MatchingRule> user_agent_rules; Vector<MatchingRule> author_rules; }; bool StyleComputer::expand_unresolved_values(DOM::Element& element, StringView property_name, HashMap<String, NonnullRefPtr<PropertyDependencyNode>>& dependencies, Vector<StyleComponentValueRule> const& source, Vector<StyleComponentValueRule>& dest, size_t source_start_index) const { // FIXME: Do this better! // We build a copy of the tree of StyleComponentValueRules, with all var()s replaced with their contents. // This is a very naive solution, and we could do better if the CSS Parser could accept tokens one at a time. // Arbitrary large value chosen to avoid the billion-laughs attack. // https://www.w3.org/TR/css-variables-1/#long-variables const size_t MAX_VALUE_COUNT = 16384; if (source.size() + dest.size() > MAX_VALUE_COUNT) { dbgln("Stopped expanding CSS variables: maximum length reached."); return false; } auto get_custom_property = [this, &element](auto& name) -> RefPtr<StyleValue> { auto custom_property = resolve_custom_property(element, name); if (custom_property.has_value()) return custom_property.value().value; return nullptr; }; auto get_dependency_node = [&](auto name) -> NonnullRefPtr<PropertyDependencyNode> { if (auto existing = dependencies.get(name); existing.has_value()) { return *existing.value(); } else { auto new_node = PropertyDependencyNode::create(name); dependencies.set(name, new_node); return new_node; } }; for (size_t source_index = source_start_index; source_index < source.size(); source_index++) { auto& value = source[source_index]; if (value.is_function()) { if (value.function().name().equals_ignoring_case("var"sv)) { auto& var_contents = value.function().values(); if (var_contents.is_empty()) return false; auto& custom_property_name_token = var_contents.first(); if (!custom_property_name_token.is(Token::Type::Ident)) return false; auto custom_property_name = custom_property_name_token.token().ident(); if (!custom_property_name.starts_with("--")) return false; // Detect dependency cycles. https://www.w3.org/TR/css-variables-1/#cycles // We do not do this by the spec, since we are not keeping a graph of var dependencies around, // but rebuilding it every time. if (custom_property_name == property_name) return false; auto parent = get_dependency_node(property_name); auto child = get_dependency_node(custom_property_name); parent->add_child(child); if (parent->has_cycles()) return false; if (auto custom_property_value = get_custom_property(custom_property_name)) { VERIFY(custom_property_value->is_unresolved()); if (!expand_unresolved_values(element, custom_property_name, dependencies, custom_property_value->as_unresolved().values(), dest)) return false; continue; } // Use the provided fallback value, if any. if (var_contents.size() > 2 && var_contents[1].is(Token::Type::Comma)) { if (!expand_unresolved_values(element, property_name, dependencies, var_contents, dest, 2)) return false; continue; } } auto& source_function = value.function(); Vector<StyleComponentValueRule> function_values; if (!expand_unresolved_values(element, property_name, dependencies, source_function.values(), function_values)) return false; NonnullRefPtr<StyleFunctionRule> function = adopt_ref(*new StyleFunctionRule(source_function.name(), move(function_values))); dest.empend(function); continue; } if (value.is_block()) { auto& source_block = value.block(); Vector<StyleComponentValueRule> block_values; if (!expand_unresolved_values(element, property_name, dependencies, source_block.values(), block_values)) return false; NonnullRefPtr<StyleBlockRule> block = adopt_ref(*new StyleBlockRule(source_block.token(), move(block_values))); dest.empend(block); continue; } dest.empend(value.token()); } return true; } RefPtr<StyleValue> StyleComputer::resolve_unresolved_style_value(DOM::Element& element, PropertyID property_id, UnresolvedStyleValue const& unresolved) const { // Unresolved always contains a var(), unless it is a custom property's value, in which case we shouldn't be trying // to produce a different StyleValue from it. VERIFY(unresolved.contains_var()); Vector<StyleComponentValueRule> expanded_values; HashMap<String, NonnullRefPtr<PropertyDependencyNode>> dependencies; if (!expand_unresolved_values(element, string_from_property_id(property_id), dependencies, unresolved.values(), expanded_values)) return {}; if (auto parsed_value = Parser::parse_css_value({}, ParsingContext { document() }, property_id, expanded_values)) return parsed_value.release_nonnull(); return {}; } void StyleComputer::cascade_declarations(StyleProperties& style, DOM::Element& element, Vector<MatchingRule> const& matching_rules, CascadeOrigin cascade_origin, bool important) const { for (auto& match : matching_rules) { for (auto& property : verify_cast<PropertyOwningCSSStyleDeclaration>(match.rule->declaration()).properties()) { if (important != property.important) continue; auto property_value = property.value; if (property.value->is_unresolved()) { if (auto resolved = resolve_unresolved_style_value(element, property.property_id, property.value->as_unresolved())) property_value = resolved.release_nonnull(); } set_property_expanding_shorthands(style, property.property_id, property_value, m_document); } } if (cascade_origin == CascadeOrigin::Author) { if (auto* inline_style = verify_cast<ElementInlineCSSStyleDeclaration>(element.inline_style())) { for (auto& property : inline_style->properties()) { if (important != property.important) continue; set_property_expanding_shorthands(style, property.property_id, property.value, m_document); } } } } // https://www.w3.org/TR/css-cascade/#cascading void StyleComputer::compute_cascaded_values(StyleProperties& style, DOM::Element& element) const { // First, we collect all the CSS rules whose selectors match `element`: MatchingRuleSet matching_rule_set; matching_rule_set.user_agent_rules = collect_matching_rules(element, CascadeOrigin::UserAgent); sort_matching_rules(matching_rule_set.user_agent_rules); matching_rule_set.author_rules = collect_matching_rules(element, CascadeOrigin::Author); sort_matching_rules(matching_rule_set.author_rules); // Then we apply the declarations from the matched rules in cascade order: // Normal user agent declarations cascade_declarations(style, element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, false); // FIXME: Normal user declarations // Normal author declarations cascade_declarations(style, element, matching_rule_set.author_rules, CascadeOrigin::Author, false); // Author presentational hints (NOTE: The spec doesn't say exactly how to prioritize these.) element.apply_presentational_hints(style); // FIXME: Animation declarations [css-animations-1] // Important author declarations cascade_declarations(style, element, matching_rule_set.author_rules, CascadeOrigin::Author, true); // FIXME: Important user declarations // Important user agent declarations cascade_declarations(style, element, matching_rule_set.user_agent_rules, CascadeOrigin::UserAgent, true); // FIXME: Transition declarations [css-transitions-1] } static NonnullRefPtr<StyleValue> get_inherit_value(CSS::PropertyID property_id, DOM::Element const* element) { if (!element || !element->parent_element() || !element->parent_element()->specified_css_values()) return property_initial_value(property_id); auto& map = element->parent_element()->specified_css_values()->properties(); auto it = map.find(property_id); VERIFY(it != map.end()); return *it->value; }; void StyleComputer::compute_defaulted_property_value(StyleProperties& style, DOM::Element const* element, CSS::PropertyID property_id) const { // FIXME: If we don't know the correct initial value for a property, we fall back to InitialStyleValue. auto it = style.m_property_values.find(property_id); if (it == style.m_property_values.end()) { if (is_inherited_property(property_id)) style.m_property_values.set(property_id, get_inherit_value(property_id, element)); else style.m_property_values.set(property_id, property_initial_value(property_id)); return; } if (it->value->is_initial()) { it->value = property_initial_value(property_id); return; } if (it->value->is_inherit()) { it->value = get_inherit_value(property_id, element); return; } } // https://www.w3.org/TR/css-cascade/#defaulting void StyleComputer::compute_defaulted_values(StyleProperties& style, DOM::Element const* element) const { // Walk the list of all known CSS properties and: // - Add them to `style` if they are missing. // - Resolve `inherit` and `initial` as needed. for (auto i = to_underlying(CSS::first_longhand_property_id); i <= to_underlying(CSS::last_longhand_property_id); ++i) { auto property_id = (CSS::PropertyID)i; compute_defaulted_property_value(style, element, property_id); } } void StyleComputer::compute_font(StyleProperties& style, DOM::Element const* element) const { // To compute the font, first ensure that we've defaulted the relevant CSS font properties. // FIXME: This should be more sophisticated. compute_defaulted_property_value(style, element, CSS::PropertyID::FontFamily); compute_defaulted_property_value(style, element, CSS::PropertyID::FontSize); compute_defaulted_property_value(style, element, CSS::PropertyID::FontWeight); auto viewport_rect = document().browsing_context()->viewport_rect(); auto font_size = style.property(CSS::PropertyID::FontSize).value(); auto font_weight = style.property(CSS::PropertyID::FontWeight).value(); int weight = Gfx::FontWeight::Regular; if (font_weight->is_identifier()) { switch (static_cast<IdentifierStyleValue const&>(*font_weight).id()) { case CSS::ValueID::Normal: weight = Gfx::FontWeight::Regular; break; case CSS::ValueID::Bold: weight = Gfx::FontWeight::Bold; break; case CSS::ValueID::Lighter: // FIXME: This should be relative to the parent. weight = Gfx::FontWeight::Regular; break; case CSS::ValueID::Bolder: // FIXME: This should be relative to the parent. weight = Gfx::FontWeight::Bold; break; default: break; } } else if (font_weight->has_integer()) { int font_weight_integer = font_weight->to_integer(); if (font_weight_integer <= Gfx::FontWeight::Regular) weight = Gfx::FontWeight::Regular; else if (font_weight_integer <= Gfx::FontWeight::Bold) weight = Gfx::FontWeight::Bold; else weight = Gfx::FontWeight::Black; } // FIXME: calc() for font-weight bool bold = weight > Gfx::FontWeight::Regular; int size = 10; if (font_size->is_identifier()) { switch (static_cast<const IdentifierStyleValue&>(*font_size).id()) { case CSS::ValueID::XxSmall: case CSS::ValueID::XSmall: case CSS::ValueID::Small: case CSS::ValueID::Medium: // FIXME: Should be based on "user's default font size" size = 10; break; case CSS::ValueID::Large: case CSS::ValueID::XLarge: case CSS::ValueID::XxLarge: case CSS::ValueID::XxxLarge: // FIXME: Should be based on "user's default font size" size = 12; break; case CSS::ValueID::Smaller: case CSS::ValueID::Larger: // FIXME: Should be based on parent element break; default: break; } } else { // FIXME: Get the root element font. float root_font_size = 10; Gfx::FontMetrics font_metrics; if (element && element->parent_element() && element->parent_element()->specified_css_values()) font_metrics = element->parent_element()->specified_css_values()->computed_font().metrics('M'); else font_metrics = Gfx::FontDatabase::default_font().metrics('M'); Optional<Length> maybe_length; if (font_size->is_length()) { maybe_length = font_size->to_length(); if (maybe_length->is_percentage()) { auto parent_font_size = size; if (element && element->parent_element() && element->parent_element()->layout_node() && element->parent_element()->specified_css_values()) { auto value = element->parent_element()->specified_css_values()->property(CSS::PropertyID::FontSize).value(); if (value->is_length()) { auto length = static_cast<LengthStyleValue const&>(*value).to_length(); if (length.is_absolute() || length.is_relative()) parent_font_size = length.to_px(viewport_rect, font_metrics, root_font_size); } } maybe_length = Length::make_px(maybe_length->raw_value() / 100.0f * (parent_font_size)); } } else if (font_size->is_calculated()) { Length length = Length(0, Length::Type::Calculated); length.set_calculated_style(verify_cast<CalculatedStyleValue>(font_size.ptr())); maybe_length = length; } if (maybe_length.has_value()) { // FIXME: Support font-size: calc(...) if (!maybe_length->is_calculated()) { auto px = maybe_length.value().to_px(viewport_rect, font_metrics, root_font_size); if (px != 0) size = px; } } } // FIXME: Implement the full font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm // Note: This is modified by the find_font() lambda FontSelector font_selector; bool monospace = false; auto find_font = [&](String const& family) -> RefPtr<Gfx::Font> { font_selector = { family, size, weight }; if (auto found_font = FontCache::the().get(font_selector)) return found_font; if (auto found_font = Gfx::FontDatabase::the().get(family, size, weight)) return found_font; return {}; }; // FIXME: Replace hard-coded font names with a relevant call to FontDatabase. // Currently, we cannot request the default font's name, or request it at a specific size and weight. // So, hard-coded font names it is. auto find_generic_font = [&](ValueID font_id) -> RefPtr<Gfx::Font> { switch (font_id) { case ValueID::Monospace: case ValueID::UiMonospace: monospace = true; return find_font("Csilla"); case ValueID::Serif: case ValueID::SansSerif: case ValueID::Cursive: case ValueID::Fantasy: case ValueID::UiSerif: case ValueID::UiSansSerif: case ValueID::UiRounded: return find_font("Katica"); default: return {}; } }; RefPtr<Gfx::Font> found_font; auto family_value = style.property(PropertyID::FontFamily).value(); if (family_value->is_value_list()) { auto& family_list = static_cast<StyleValueList const&>(*family_value).values(); for (auto& family : family_list) { if (family.is_identifier()) { found_font = find_generic_font(family.to_identifier()); } else if (family.is_string()) { found_font = find_font(family.to_string()); } if (found_font) break; } } else if (family_value->is_identifier()) { found_font = find_generic_font(family_value->to_identifier()); } else if (family_value->is_string()) { found_font = find_font(family_value->to_string()); } if (!found_font) { found_font = StyleProperties::font_fallback(monospace, bold); } FontCache::the().set(font_selector, *found_font); style.set_computed_font(found_font.release_nonnull()); } void StyleComputer::absolutize_values(StyleProperties& style, DOM::Element const*) const { auto viewport_rect = document().browsing_context()->viewport_rect(); auto font_metrics = style.computed_font().metrics('M'); // FIXME: Get the root element font. float root_font_size = 10; for (auto& it : style.properties()) { it.value->visit_lengths([&](Length& length) { if (length.is_absolute() || length.is_relative()) { auto px = length.to_px(viewport_rect, font_metrics, root_font_size); length = Length::make_px(px); } }); } } NonnullRefPtr<StyleProperties> StyleComputer::create_document_style() const { auto style = StyleProperties::create(); compute_font(style, nullptr); compute_defaulted_values(style, nullptr); absolutize_values(style, nullptr); return style; } NonnullRefPtr<StyleProperties> StyleComputer::compute_style(DOM::Element& element) const { auto style = StyleProperties::create(); // 1. Perform the cascade. This produces the "specified style" compute_cascaded_values(style, element); // 2. Compute the font, since that may be needed for font-relative CSS units compute_font(style, &element); // 3. Absolutize values, turning font/viewport relative lengths into absolute lengths absolutize_values(style, &element); // 4. Default the values, applying inheritance and 'initial' as needed compute_defaulted_values(style, &element); return style; } PropertyDependencyNode::PropertyDependencyNode(String name) : m_name(move(name)) { } void PropertyDependencyNode::add_child(NonnullRefPtr<PropertyDependencyNode> new_child) { for (auto const& child : m_children) { if (child.m_name == new_child->m_name) return; } // We detect self-reference already. VERIFY(new_child->m_name != m_name); m_children.append(move(new_child)); } bool PropertyDependencyNode::has_cycles() { if (m_marked) return true; TemporaryChange change { m_marked, true }; for (auto& child : m_children) { if (child.has_cycles()) return true; } return false; } }
42.006445
282
0.657052
[ "vector" ]
0f55ff4e94f5540424e35263cbee3b6ae053f04d
38,060
cpp
C++
lib/PhasarLLVM/DataFlowSolver/IfdsIde/Problems/IDELinearConstantAnalysis.cpp
jplehr/phasar
54eb46acbc4beb45587a1d383bbf0d65b306270a
[ "MIT" ]
null
null
null
lib/PhasarLLVM/DataFlowSolver/IfdsIde/Problems/IDELinearConstantAnalysis.cpp
jplehr/phasar
54eb46acbc4beb45587a1d383bbf0d65b306270a
[ "MIT" ]
null
null
null
lib/PhasarLLVM/DataFlowSolver/IfdsIde/Problems/IDELinearConstantAnalysis.cpp
jplehr/phasar
54eb46acbc4beb45587a1d383bbf0d65b306270a
[ "MIT" ]
null
null
null
/****************************************************************************** * Copyright (c) 2017 Philipp Schubert. * All rights reserved. This program and the accompanying materials are made * available under the terms of LICENSE.txt. * * Contributors: * Philipp Schubert and others *****************************************************************************/ // #include <functional> #include <limits> #include <utility> #include "llvm/IR/CallSite.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #include "phasar/DB/ProjectIRDB.h" #include "phasar/PhasarLLVM/ControlFlow/LLVMBasedICFG.h" #include "phasar/PhasarLLVM/DataFlowSolver/IfdsIde/EdgeFunctions.h" #include "phasar/PhasarLLVM/DataFlowSolver/IfdsIde/FlowFunctions.h" #include "phasar/PhasarLLVM/DataFlowSolver/IfdsIde/LLVMFlowFunctions.h" #include "phasar/PhasarLLVM/DataFlowSolver/IfdsIde/LLVMZeroValue.h" #include "phasar/PhasarLLVM/DataFlowSolver/IfdsIde/Problems/IDELinearConstantAnalysis.h" #include "phasar/PhasarLLVM/Pointer/LLVMPointsToInfo.h" #include "phasar/PhasarLLVM/TypeHierarchy/LLVMTypeHierarchy.h" #include "phasar/Utils/LLVMIRToSrc.h" #include "phasar/Utils/LLVMShorthands.h" #include "phasar/Utils/Logger.h" using namespace std; using namespace psr; namespace psr { // Initialize debug counter for edge functions unsigned IDELinearConstantAnalysis::CurrGenConstantId = 0; unsigned IDELinearConstantAnalysis::CurrLCAIDId = 0; unsigned IDELinearConstantAnalysis::CurrBinaryId = 0; const IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::TOP = numeric_limits<IDELinearConstantAnalysis::l_t>::min(); const IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::BOTTOM = numeric_limits<IDELinearConstantAnalysis::l_t>::max(); IDELinearConstantAnalysis::IDELinearConstantAnalysis( const ProjectIRDB *IRDB, const LLVMTypeHierarchy *TH, const LLVMBasedICFG *ICF, LLVMPointsToInfo *PT, std::set<std::string> EntryPoints) : IDETabulationProblem(IRDB, TH, ICF, PT, std::move(EntryPoints)) { IDETabulationProblem::ZeroValue = createZeroValue(); } IDELinearConstantAnalysis::~IDELinearConstantAnalysis() { IDELinearConstantAnalysis::CurrGenConstantId = 0; IDELinearConstantAnalysis::CurrLCAIDId = 0; IDELinearConstantAnalysis::CurrBinaryId = 0; } // Start formulating our analysis by specifying the parts required for IFDS IDELinearConstantAnalysis::FlowFunctionPtrType IDELinearConstantAnalysis::getNormalFlowFunction( IDELinearConstantAnalysis::n_t Curr, IDELinearConstantAnalysis::n_t Succ) { if (const auto *Alloca = llvm::dyn_cast<llvm::AllocaInst>(Curr)) { if (Alloca->getAllocatedType()->isIntegerTy()) { return make_shared<Gen<IDELinearConstantAnalysis::d_t>>(Alloca, getZeroValue()); } } // Check store instructions. Store instructions override previous value // of their pointer operand, i.e. kills previous fact (= pointer operand). if (const auto *Store = llvm::dyn_cast<llvm::StoreInst>(Curr)) { IDELinearConstantAnalysis::d_t ValueOp = Store->getValueOperand(); // Case I: Storing a constant integer. if (llvm::isa<llvm::ConstantInt>(ValueOp)) { return make_shared<StrongUpdateStore<IDELinearConstantAnalysis::d_t>>( Store, [this](IDELinearConstantAnalysis::d_t Source) { return Source == getZeroValue(); }); } // Case II: Storing an integer typed value. if (ValueOp->getType()->isIntegerTy()) { return make_shared<StrongUpdateStore<IDELinearConstantAnalysis::d_t>>( Store, [Store](IDELinearConstantAnalysis::d_t Source) { return Source == Store->getValueOperand(); }); } } // check load instructions if (const auto *Load = llvm::dyn_cast<llvm::LoadInst>(Curr)) { // only consider i32 load if (Load->getPointerOperandType()->getPointerElementType()->isIntegerTy()) { return make_shared<GenIf<IDELinearConstantAnalysis::d_t>>( Load, [Load](IDELinearConstantAnalysis::d_t Source) { return Source == Load->getPointerOperand(); }); } } // check for binary operations: add, sub, mul, udiv/sdiv, urem/srem if (llvm::isa<llvm::BinaryOperator>(Curr)) { auto *Lop = Curr->getOperand(0); auto *Rop = Curr->getOperand(1); return make_shared<GenIf<IDELinearConstantAnalysis::d_t>>( Curr, [this, Lop, Rop](IDELinearConstantAnalysis::d_t Source) { return (Lop == Source && llvm::isa<llvm::ConstantInt>(Rop)) || (Rop == Source && llvm::isa<llvm::ConstantInt>(Lop)) || (Source == getZeroValue() && !llvm::isa<llvm::ConstantInt>(Lop) && !llvm::isa<llvm::ConstantInt>(Rop)); }); } return Identity<IDELinearConstantAnalysis::d_t>::getInstance(); } IDELinearConstantAnalysis::FlowFunctionPtrType IDELinearConstantAnalysis::getCallFlowFunction( IDELinearConstantAnalysis::n_t CallStmt, IDELinearConstantAnalysis::f_t DestFun) { // Map the actual parameters into the formal parameters if (llvm::isa<llvm::CallInst>(CallStmt) || llvm::isa<llvm::InvokeInst>(CallStmt)) { struct LCAFF : FlowFunction<const llvm::Value *> { vector<const llvm::Value *> Actuals; vector<const llvm::Value *> Formals; const llvm::Function *DestFun; LCAFF(llvm::ImmutableCallSite CallSite, IDELinearConstantAnalysis::f_t DestFun) : DestFun(DestFun) { // Set up the actual parameters for (unsigned Idx = 0; Idx < CallSite.getNumArgOperands(); ++Idx) { Actuals.push_back(CallSite.getArgOperand(Idx)); } // Set up the formal parameters for (unsigned Idx = 0; Idx < DestFun->arg_size(); ++Idx) { Formals.push_back(getNthFunctionArgument(DestFun, Idx)); } } set<IDELinearConstantAnalysis::d_t> computeTargets(IDELinearConstantAnalysis::d_t Source) override { set<IDELinearConstantAnalysis::d_t> Res; for (unsigned Idx = 0; Idx < Actuals.size(); ++Idx) { if (Source == Actuals[Idx]) { // Check for C-style varargs: idx >= destFun->arg_size() if (Idx >= DestFun->arg_size() && !DestFun->isDeclaration()) { // Over-approximate by trying to add the // alloca [1 x %struct.__va_list_tag], align 16 // to the results // find the allocated %struct.__va_list_tag and generate it for (const auto &BB : *DestFun) { for (const auto &I : BB) { if (const auto *Alloc = llvm::dyn_cast<llvm::AllocaInst>(&I)) { if (Alloc->getAllocatedType()->isArrayTy() && Alloc->getAllocatedType()->getArrayNumElements() > 0 && Alloc->getAllocatedType() ->getArrayElementType() ->isStructTy() && Alloc->getAllocatedType() ->getArrayElementType() ->getStructName() == "struct.__va_list_tag") { Res.insert(Alloc); } } } } } else { // Ordinary case: Just perform mapping Res.insert(Formals[Idx]); // corresponding formal } } // Special case: Check if function is called with integer literals as // parameter (in case of varargs ignore) if (LLVMZeroValue::getInstance()->isLLVMZeroValue(Source) && Idx < DestFun->arg_size() && llvm::isa<llvm::ConstantInt>(Actuals[Idx])) { Res.insert(Formals[Idx]); // corresponding formal } } if (!LLVMZeroValue::getInstance()->isLLVMZeroValue(Source) && llvm::isa<llvm::GlobalVariable>(Source)) { Res.insert(Source); } return Res; } }; return make_shared<LCAFF>(llvm::ImmutableCallSite(CallStmt), DestFun); } // Pass everything else as identity return Identity<IDELinearConstantAnalysis::d_t>::getInstance(); } IDELinearConstantAnalysis::FlowFunctionPtrType IDELinearConstantAnalysis::getRetFlowFunction( IDELinearConstantAnalysis::n_t CallSite, IDELinearConstantAnalysis::f_t CalleeFun, IDELinearConstantAnalysis::n_t ExitStmt, IDELinearConstantAnalysis::n_t RetSite) { // Handle the case: %x = call i32 ... if (CallSite->getType()->isIntegerTy()) { const auto *Return = llvm::dyn_cast<llvm::ReturnInst>(ExitStmt); auto *ReturnValue = Return->getReturnValue(); struct LCAFF : FlowFunction<IDELinearConstantAnalysis::d_t> { IDELinearConstantAnalysis::n_t CallSite; IDELinearConstantAnalysis::d_t ReturnValue; LCAFF(IDELinearConstantAnalysis::n_t CS, IDELinearConstantAnalysis::d_t RetVal) : CallSite(CS), ReturnValue(RetVal) {} set<IDELinearConstantAnalysis::d_t> computeTargets(IDELinearConstantAnalysis::d_t Source) override { set<IDELinearConstantAnalysis::d_t> Res; // Collect return value fact if (Source == ReturnValue) { Res.insert(CallSite); } // Return value is integer literal if (LLVMZeroValue::getInstance()->isLLVMZeroValue(Source) && llvm::isa<llvm::ConstantInt>(ReturnValue)) { Res.insert(CallSite); } if (!LLVMZeroValue::getInstance()->isLLVMZeroValue(Source) && llvm::isa<llvm::GlobalVariable>(Source)) { Res.insert(Source); } return Res; } }; return make_shared<LCAFF>(CallSite, ReturnValue); } // All other facts except GlobalVariables are killed at this point return make_shared<KillIf<IDELinearConstantAnalysis::d_t>>( [](IDELinearConstantAnalysis::d_t Source) { return !llvm::isa<llvm::GlobalVariable>(Source); }); } IDELinearConstantAnalysis::FlowFunctionPtrType IDELinearConstantAnalysis::getCallToRetFlowFunction( IDELinearConstantAnalysis::n_t CallSite, IDELinearConstantAnalysis::n_t RetSite, set<f_t> Callees) { for (const auto *Callee : Callees) { if (!ICF->getStartPointsOf(Callee).empty()) { return make_shared<KillIf<IDELinearConstantAnalysis::d_t>>( [this](IDELinearConstantAnalysis::d_t Source) { return !isZeroValue(Source) && llvm::isa<llvm::GlobalVariable>(Source); }); } else { return Identity<IDELinearConstantAnalysis::d_t>::getInstance(); } } return Identity<IDELinearConstantAnalysis::d_t>::getInstance(); } IDELinearConstantAnalysis::FlowFunctionPtrType IDELinearConstantAnalysis::getSummaryFlowFunction( IDELinearConstantAnalysis::n_t CallStmt, IDELinearConstantAnalysis::f_t DestFun) { return nullptr; } map<IDELinearConstantAnalysis::n_t, set<IDELinearConstantAnalysis::d_t>> IDELinearConstantAnalysis::initialSeeds() { // Check commandline arguments, e.g. argc, and generate all integer // typed arguments. map<IDELinearConstantAnalysis::n_t, set<IDELinearConstantAnalysis::d_t>> SeedMap; // Collect global variables of integer type for (const auto &EntryPoint : EntryPoints) { set<IDELinearConstantAnalysis::d_t> Globals; for (const auto &G : IRDB->getModuleDefiningFunction(EntryPoint)->globals()) { if (const auto *GV = llvm::dyn_cast<llvm::GlobalVariable>(&G)) { if (GV->hasInitializer() && llvm::isa<llvm::ConstantInt>(GV->getInitializer())) { Globals.insert(GV); } } } Globals.insert(getZeroValue()); if (!Globals.empty()) { SeedMap.insert( make_pair(&ICF->getFunction(EntryPoint)->front().front(), Globals)); } // Collect commandline arguments of integer type if (EntryPoint == "main") { set<IDELinearConstantAnalysis::d_t> CmdArgs; for (const auto &Arg : ICF->getFunction(EntryPoint)->args()) { if (Arg.getType()->isIntegerTy()) { CmdArgs.insert(&Arg); } } CmdArgs.insert(getZeroValue()); SeedMap.insert( make_pair(&ICF->getFunction(EntryPoint)->front().front(), CmdArgs)); } else { SeedMap.insert( make_pair(&ICF->getFunction(EntryPoint)->front().front(), set<IDELinearConstantAnalysis::d_t>({getZeroValue()}))); } } return SeedMap; } IDELinearConstantAnalysis::d_t IDELinearConstantAnalysis::createZeroValue() const { // create a special value to represent the zero value! return LLVMZeroValue::getInstance(); } bool IDELinearConstantAnalysis::isZeroValue( IDELinearConstantAnalysis::d_t D) const { return LLVMZeroValue::getInstance()->isLLVMZeroValue(D); } // In addition provide specifications for the IDE parts shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::getNormalEdgeFunction( IDELinearConstantAnalysis::n_t Curr, IDELinearConstantAnalysis::d_t CurrNode, IDELinearConstantAnalysis::n_t Succ, IDELinearConstantAnalysis::d_t SuccNode) { // Initialize global variables at entry point if (!isZeroValue(CurrNode) && ICF->isStartPoint(Curr) && isEntryPoint(ICF->getFunctionOf(Curr)->getName().str()) && llvm::isa<llvm::GlobalVariable>(CurrNode) && CurrNode == SuccNode) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Case: Intialize global variable at entry point."); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); const auto *GV = llvm::dyn_cast<llvm::GlobalVariable>(CurrNode); const auto *CI = llvm::dyn_cast<llvm::ConstantInt>(GV->getInitializer()); auto IntConst = CI->getSExtValue(); return make_shared<IDELinearConstantAnalysis::GenConstant>(IntConst); } // ALL_BOTTOM for zero value if ((isZeroValue(CurrNode) && isZeroValue(SuccNode)) || (llvm::isa<llvm::AllocaInst>(Curr) && isZeroValue(CurrNode))) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Case: Zero value."); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); return make_shared<AllBottom<IDELinearConstantAnalysis::l_t>>( IDELinearConstantAnalysis::BOTTOM); } // Check store instruction if (const auto *Store = llvm::dyn_cast<llvm::StoreInst>(Curr)) { IDELinearConstantAnalysis::d_t PointerOperand = Store->getPointerOperand(); IDELinearConstantAnalysis::d_t ValueOperand = Store->getValueOperand(); if (PointerOperand == SuccNode) { // Case I: Storing a constant integer. if (isZeroValue(CurrNode) && llvm::isa<llvm::ConstantInt>(ValueOperand)) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Case: Storing constant integer."); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); const auto *CI = llvm::dyn_cast<llvm::ConstantInt>(ValueOperand); auto IntConst = CI->getSExtValue(); return make_shared<IDELinearConstantAnalysis::GenConstant>(IntConst); } // Case II: Storing an integer typed value. if (CurrNode != SuccNode && ValueOperand->getType()->isIntegerTy()) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Case: Storing an integer typed value."); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); return make_shared<IDELinearConstantAnalysis::LCAIdentity>(); } } } // Check load instruction if (const auto *Load = llvm::dyn_cast<llvm::LoadInst>(Curr)) { if (Load == SuccNode) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Case: Loading an integer typed value."); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); return make_shared<IDELinearConstantAnalysis::LCAIdentity>(); } } // Check for binary operations add, sub, mul, udiv/sdiv and urem/srem if (Curr == SuccNode && llvm::isa<llvm::BinaryOperator>(Curr)) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Case: Binary operation."); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); unsigned OP = Curr->getOpcode(); auto *Lop = Curr->getOperand(0); auto *Rop = Curr->getOperand(1); // For non linear constant computation we propagate bottom if (CurrNode == ZeroValue && !llvm::isa<llvm::ConstantInt>(Lop) && !llvm::isa<llvm::ConstantInt>(Rop)) { return make_shared<AllBottom<IDELinearConstantAnalysis::l_t>>( IDELinearConstantAnalysis::BOTTOM); } else { return make_shared<IDELinearConstantAnalysis::BinOp>(OP, Lop, Rop, CurrNode); } } LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Case: Edge identity."); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); return EdgeIdentity<IDELinearConstantAnalysis::l_t>::getInstance(); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::getCallEdgeFunction( IDELinearConstantAnalysis::n_t CallStmt, IDELinearConstantAnalysis::d_t SrcNode, IDELinearConstantAnalysis::f_t DestinationFunction, IDELinearConstantAnalysis::d_t DestNode) { // Case: Passing constant integer as parameter if (isZeroValue(SrcNode) && !isZeroValue(DestNode)) { if (const auto *A = llvm::dyn_cast<llvm::Argument>(DestNode)) { llvm::ImmutableCallSite CS(CallStmt); const auto *Actual = CS.getArgOperand(getFunctionArgumentNr(A)); if (const auto *CI = llvm::dyn_cast<llvm::ConstantInt>(Actual)) { auto IntConst = CI->getSExtValue(); return make_shared<IDELinearConstantAnalysis::GenConstant>(IntConst); } } } return EdgeIdentity<IDELinearConstantAnalysis::l_t>::getInstance(); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::getReturnEdgeFunction( IDELinearConstantAnalysis::n_t CallSite, IDELinearConstantAnalysis::f_t CalleeFunction, IDELinearConstantAnalysis::n_t ExitStmt, IDELinearConstantAnalysis::d_t ExitNode, IDELinearConstantAnalysis::n_t ReSite, IDELinearConstantAnalysis::d_t RetNode) { // Case: Returning constant integer if (isZeroValue(ExitNode) && !isZeroValue(RetNode)) { const auto *Return = llvm::dyn_cast<llvm::ReturnInst>(ExitStmt); auto *ReturnValue = Return->getReturnValue(); if (auto *CI = llvm::dyn_cast<llvm::ConstantInt>(ReturnValue)) { auto IntConst = CI->getSExtValue(); return make_shared<IDELinearConstantAnalysis::GenConstant>(IntConst); } } return EdgeIdentity<IDELinearConstantAnalysis::l_t>::getInstance(); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::getCallToRetEdgeFunction( IDELinearConstantAnalysis::n_t CallSite, IDELinearConstantAnalysis::d_t CallNode, IDELinearConstantAnalysis::n_t RetSite, IDELinearConstantAnalysis::d_t RetSiteNode, set<IDELinearConstantAnalysis::f_t> Callees) { return EdgeIdentity<IDELinearConstantAnalysis::l_t>::getInstance(); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::getSummaryEdgeFunction( IDELinearConstantAnalysis::n_t CallStmt, IDELinearConstantAnalysis::d_t CallNode, IDELinearConstantAnalysis::n_t RetSite, IDELinearConstantAnalysis::d_t RetSiteNode) { return EdgeIdentity<IDELinearConstantAnalysis::l_t>::getInstance(); } IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::topElement() { return TOP; } IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::bottomElement() { return BOTTOM; } IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::join(IDELinearConstantAnalysis::l_t Lhs, IDELinearConstantAnalysis::l_t Rhs) { if (Lhs == TOP && Rhs != BOTTOM) { return Rhs; } else if (Rhs == TOP && Lhs != BOTTOM) { return Lhs; } else if (Rhs == Lhs) { return Rhs; } else { return BOTTOM; } } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::allTopFunction() { return make_shared<AllTop<IDELinearConstantAnalysis::l_t>>(TOP); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::LCAEdgeFunctionComposer::composeWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> SecondFunction) { if (auto *AB = dynamic_cast<AllBottom<IDELinearConstantAnalysis::l_t> *>( SecondFunction.get())) { return this->shared_from_this(); } if (auto *EI = dynamic_cast<EdgeIdentity<IDELinearConstantAnalysis::l_t> *>( SecondFunction.get())) { return this->shared_from_this(); } if (auto *LCAID = dynamic_cast<LCAIdentity *>(SecondFunction.get())) { return this->shared_from_this(); } return F->composeWith(G->composeWith(SecondFunction)); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::LCAEdgeFunctionComposer::joinWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> OtherFunction) { if (OtherFunction.get() == this || OtherFunction->equal_to(this->shared_from_this())) { return this->shared_from_this(); } if (auto *AT = dynamic_cast<AllTop<IDELinearConstantAnalysis::l_t> *>( OtherFunction.get())) { return this->shared_from_this(); } return make_shared<AllBottom<IDELinearConstantAnalysis::l_t>>( IDELinearConstantAnalysis::BOTTOM); } IDELinearConstantAnalysis::GenConstant::GenConstant( IDELinearConstantAnalysis::l_t IntConst) : GenConstant_Id(++IDELinearConstantAnalysis::CurrGenConstantId), IntConst(IntConst) {} IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::GenConstant::computeTarget( IDELinearConstantAnalysis::l_t Source) { return IntConst; } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::GenConstant::composeWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> SecondFunction) { if (auto *AB = dynamic_cast<AllBottom<IDELinearConstantAnalysis::l_t> *>( SecondFunction.get())) { return this->shared_from_this(); } if (auto *EI = dynamic_cast<EdgeIdentity<IDELinearConstantAnalysis::l_t> *>( SecondFunction.get())) { return this->shared_from_this(); } if (auto *LSVI = dynamic_cast<LCAIdentity *>(SecondFunction.get())) { return this->shared_from_this(); } return make_shared<IDELinearConstantAnalysis::LCAEdgeFunctionComposer>( this->shared_from_this(), SecondFunction); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::GenConstant::joinWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> OtherFunction) { if (OtherFunction.get() == this || OtherFunction->equal_to(this->shared_from_this())) { return this->shared_from_this(); } if (auto *AT = dynamic_cast<AllTop<IDELinearConstantAnalysis::l_t> *>( OtherFunction.get())) { return this->shared_from_this(); } return make_shared<AllBottom<IDELinearConstantAnalysis::l_t>>( IDELinearConstantAnalysis::BOTTOM); } bool IDELinearConstantAnalysis::GenConstant::equal_to( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> Other) const { if (auto *GC = dynamic_cast<IDELinearConstantAnalysis::GenConstant *>(Other.get())) { return (GC->IntConst == this->IntConst); } return this == Other.get(); } void IDELinearConstantAnalysis::GenConstant::print(ostream &OS, bool IsForDebug) const { OS << IntConst << " (EF:" << GenConstant_Id << ')'; } IDELinearConstantAnalysis::LCAIdentity::LCAIdentity() : LCAID_Id(++IDELinearConstantAnalysis::CurrLCAIDId) {} IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::LCAIdentity::computeTarget( IDELinearConstantAnalysis::l_t Source) { return Source; } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::LCAIdentity::composeWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> SecondFunction) { return SecondFunction; } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::LCAIdentity::joinWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> OtherFunction) { if (OtherFunction.get() == this || OtherFunction->equal_to(this->shared_from_this())) { return this->shared_from_this(); } if (auto *AT = dynamic_cast<AllTop<IDELinearConstantAnalysis::l_t> *>( OtherFunction.get())) { return this->shared_from_this(); } return make_shared<AllBottom<IDELinearConstantAnalysis::l_t>>( IDELinearConstantAnalysis::BOTTOM); } bool IDELinearConstantAnalysis::LCAIdentity::equal_to( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> Other) const { return this == Other.get(); } void IDELinearConstantAnalysis::LCAIdentity::print(ostream &OS, bool IsForDebug) const { OS << "Id (EF:" << LCAID_Id << ')'; } IDELinearConstantAnalysis::BinOp::BinOp(const unsigned Op, IDELinearConstantAnalysis::d_t Lop, IDELinearConstantAnalysis::d_t Rop, IDELinearConstantAnalysis::d_t CurrNode) : EdgeFunctionID(++IDELinearConstantAnalysis::CurrBinaryId), Op(Op), lop(Lop), rop(Rop), currNode(CurrNode) {} IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::BinOp::computeTarget( IDELinearConstantAnalysis::l_t Source) { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Left Op : " << llvmIRToString(lop)); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Right Op : " << llvmIRToString(rop)); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Curr Node : " << llvmIRToString(currNode)); LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << ' '); if (LLVMZeroValue::getInstance()->isLLVMZeroValue(currNode) && llvm::isa<llvm::ConstantInt>(lop) && llvm::isa<llvm::ConstantInt>(rop)) { const auto *Lic = llvm::dyn_cast<llvm::ConstantInt>(lop); const auto *Ric = llvm::dyn_cast<llvm::ConstantInt>(rop); return IDELinearConstantAnalysis::executeBinOperation( Op, Lic->getSExtValue(), Ric->getSExtValue()); } else if (Source == BOTTOM) { return BOTTOM; } else if (lop == currNode && llvm::isa<llvm::ConstantInt>(rop)) { const auto *Ric = llvm::dyn_cast<llvm::ConstantInt>(rop); return IDELinearConstantAnalysis::executeBinOperation(Op, Source, Ric->getSExtValue()); } else if (rop == currNode && llvm::isa<llvm::ConstantInt>(lop)) { const auto *Lic = llvm::dyn_cast<llvm::ConstantInt>(lop); return IDELinearConstantAnalysis::executeBinOperation( Op, Lic->getSExtValue(), Source); } throw runtime_error("Only linear constant propagation can be specified!"); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::BinOp::composeWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> SecondFunction) { if (auto *AB = dynamic_cast<AllBottom<IDELinearConstantAnalysis::l_t> *>( SecondFunction.get())) { return this->shared_from_this(); } if (auto *EI = dynamic_cast<EdgeIdentity<IDELinearConstantAnalysis::l_t> *>( SecondFunction.get())) { return this->shared_from_this(); } if (auto *LSVI = dynamic_cast<IDELinearConstantAnalysis::LCAIdentity *>( SecondFunction.get())) { return this->shared_from_this(); } return make_shared<IDELinearConstantAnalysis::LCAEdgeFunctionComposer>( this->shared_from_this(), SecondFunction); } shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> IDELinearConstantAnalysis::BinOp::joinWith( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> OtherFunction) { if (OtherFunction.get() == this || OtherFunction->equal_to(this->shared_from_this())) { return this->shared_from_this(); } if (auto *AT = dynamic_cast<AllTop<IDELinearConstantAnalysis::l_t> *>( OtherFunction.get())) { return this->shared_from_this(); } return make_shared<AllBottom<IDELinearConstantAnalysis::l_t>>( IDELinearConstantAnalysis::BOTTOM); } bool IDELinearConstantAnalysis::BinOp::equal_to( shared_ptr<EdgeFunction<IDELinearConstantAnalysis::l_t>> Other) const { if (auto *BOP = dynamic_cast<IDELinearConstantAnalysis::BinOp *>(Other.get())) { return BOP->Op == this->Op && BOP->lop == this->lop && BOP->rop == this->rop; } return this == Other.get(); } void IDELinearConstantAnalysis::BinOp::print(ostream &OS, bool IsForDebug) const { if (const auto *LIC = llvm::dyn_cast<llvm::ConstantInt>(lop)) { OS << LIC->getSExtValue(); } else { OS << "ID:" << getMetaDataID(lop); } OS << ' ' << opToChar(Op) << ' '; if (const auto *RIC = llvm::dyn_cast<llvm::ConstantInt>(rop)) { OS << RIC->getSExtValue(); } else { OS << "ID:" << getMetaDataID(rop); } } char IDELinearConstantAnalysis::opToChar(const unsigned Op) { char OpAsChar; switch (Op) { case llvm::Instruction::Add: OpAsChar = '+'; break; case llvm::Instruction::Sub: OpAsChar = '-'; break; case llvm::Instruction::Mul: OpAsChar = '*'; break; case llvm::Instruction::UDiv: case llvm::Instruction::SDiv: OpAsChar = '/'; break; case llvm::Instruction::URem: case llvm::Instruction::SRem: OpAsChar = '%'; break; default: OpAsChar = ' '; break; } return OpAsChar; } bool IDELinearConstantAnalysis::isEntryPoint( const std::string &FunctionName) const { return std::find(EntryPoints.begin(), EntryPoints.end(), FunctionName) != EntryPoints.end(); } IDELinearConstantAnalysis::l_t IDELinearConstantAnalysis::executeBinOperation( const unsigned Op, IDELinearConstantAnalysis::l_t Lop, IDELinearConstantAnalysis::l_t Rop) { // default initialize with BOTTOM (all information) IDELinearConstantAnalysis::l_t Res = BOTTOM; switch (Op) { case llvm::Instruction::Add: Res = Lop + Rop; break; case llvm::Instruction::Sub: Res = Lop - Rop; break; case llvm::Instruction::Mul: Res = Lop * Rop; break; case llvm::Instruction::UDiv: case llvm::Instruction::SDiv: Res = Lop / Rop; break; case llvm::Instruction::URem: case llvm::Instruction::SRem: Res = Lop % Rop; break; default: LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Operation not supported by " "IDELinearConstantAnalysis::" "executeBinOperation()"); break; } return Res; } void IDELinearConstantAnalysis::printNode( ostream &OS, IDELinearConstantAnalysis::n_t N) const { OS << llvmIRToString(N); } void IDELinearConstantAnalysis::printDataFlowFact( ostream &OS, IDELinearConstantAnalysis::d_t D) const { OS << llvmIRToShortString(D); } void IDELinearConstantAnalysis::printFunction( ostream &OS, IDELinearConstantAnalysis::f_t M) const { OS << M->getName().str(); } void IDELinearConstantAnalysis::printEdgeFact( ostream &OS, IDELinearConstantAnalysis::l_t L) const { if (L == BOTTOM) { OS << "Bottom"; } else if (L == TOP) { OS << "Top"; } else { OS << std::to_string(L); } } void IDELinearConstantAnalysis::emitTextReport( const SolverResults<IDELinearConstantAnalysis::n_t, IDELinearConstantAnalysis::d_t, IDELinearConstantAnalysis::l_t> &SR, std::ostream &OS) { OS << "\n====================== IDE-Linear-Constant-Analysis Report " "======================\n"; if (!IRDB->debugInfoAvailable()) { // Emit only IR code, function name and module info OS << "\nWARNING: No Debug Info available - emiting results without " "source code mapping!\n"; for (const auto *F : ICF->getAllFunctions()) { std::string FName = getFunctionNameFromIR(F); OS << "\nFunction: " << FName << "\n----------" << std::string(FName.size(), '-') << '\n'; for (const auto *Stmt : ICF->getAllInstructionsOf(F)) { auto Results = SR.resultsAt(Stmt, true); stripBottomResults(Results); if (!Results.empty()) { OS << "At IR statement: " << NtoString(Stmt) << '\n'; for (auto Res : Results) { if (Res.second != IDELinearConstantAnalysis::BOTTOM) { OS << " Fact: " << DtoString(Res.first) << "\n Value: " << LtoString(Res.second) << '\n'; } } OS << '\n'; } } OS << '\n'; } } else { auto LcaResults = getLCAResults(SR); for (const auto &Entry : LcaResults) { OS << "\nFunction: " << Entry.first << "\n==========" << std::string(Entry.first.size(), '=') << '\n'; for (auto FResult : Entry.second) { FResult.second.print(OS); OS << "--------------------------------------\n\n"; } OS << '\n'; } } } void IDELinearConstantAnalysis::stripBottomResults( std::unordered_map<IDELinearConstantAnalysis::d_t, IDELinearConstantAnalysis::l_t> &Res) { for (auto It = Res.begin(); It != Res.end();) { if (It->second == IDELinearConstantAnalysis::BOTTOM) { It = Res.erase(It); } else { ++It; } } } IDELinearConstantAnalysis::lca_results_t IDELinearConstantAnalysis::getLCAResults( SolverResults<IDELinearConstantAnalysis::n_t, IDELinearConstantAnalysis::d_t, IDELinearConstantAnalysis::l_t> SR) { std::map<std::string, std::map<unsigned, LCAResult>> AggResults; std::cout << "\n==== Computing LCA Results ====\n"; for (const auto *F : ICF->getAllFunctions()) { std::string FName = getFunctionNameFromIR(F); std::cout << "\n-- Function: " << FName << " --\n"; std::map<unsigned, LCAResult> FResults; std::set<std::string> AllocatedVars; for (const auto *Stmt : ICF->getAllInstructionsOf(F)) { unsigned Lnr = getLineFromIR(Stmt); std::cout << "\nIR : " << NtoString(Stmt) << "\nLNR: " << Lnr << '\n'; // We skip statements with no source code mapping if (Lnr == 0) { std::cout << "Skipping this stmt!\n"; continue; } LCAResult *LcaRes = &FResults[Lnr]; // Check if it is a new result if (LcaRes->src_code.empty()) { std::string SourceCode = getSrcCodeFromIR(Stmt); // Skip results for line containing only closed braces which is the // case for functions with void return value if (SourceCode == "}") { FResults.erase(Lnr); continue; } LcaRes->src_code = SourceCode; LcaRes->line_nr = Lnr; } LcaRes->ir_trace.push_back(Stmt); if (Stmt->isTerminator() && !ICF->isExitStmt(Stmt)) { std::cout << "Delete result since stmt is Terminator or Exit!\n"; FResults.erase(Lnr); } else { // check results of succ(stmt) std::unordered_map<d_t, l_t> Results; if (ICF->isExitStmt(Stmt)) { Results = SR.resultsAt(Stmt, true); } else { // It's not a terminator inst, hence it has only a single successor const auto *Succ = ICF->getSuccsOf(Stmt)[0]; std::cout << "Succ stmt: " << NtoString(Succ) << '\n'; Results = SR.resultsAt(Succ, true); } stripBottomResults(Results); std::set<std::string> ValidVarsAtStmt; for (auto Res : Results) { auto VarName = getVarNameFromIR(Res.first); std::cout << " D: " << DtoString(Res.first) << " | V: " << LtoString(Res.second) << " | Var: " << VarName << '\n'; if (!VarName.empty()) { // Only store/overwrite values of variables from allocas or globals // unless there is no value stored for a variable if (llvm::isa<llvm::AllocaInst>(Res.first) || llvm::isa<llvm::GlobalVariable>(Res.first)) { // lcaRes->variableToValue.find(varName) == // lcaRes->variableToValue.end()) { ValidVarsAtStmt.insert(VarName); AllocatedVars.insert(VarName); LcaRes->variableToValue[VarName] = Res.second; } else if (AllocatedVars.find(VarName) == AllocatedVars.end()) { ValidVarsAtStmt.insert(VarName); LcaRes->variableToValue[VarName] = Res.second; } } } // remove no longer valid variables at current IR stmt for (auto It = LcaRes->variableToValue.begin(); It != LcaRes->variableToValue.end();) { if (ValidVarsAtStmt.find(It->first) == ValidVarsAtStmt.end()) { std::cout << "Erase var: " << It->first << '\n'; It = LcaRes->variableToValue.erase(It); } else { ++It; } } } } // delete entries with no result for (auto It = FResults.begin(); It != FResults.end();) { if (It->second.variableToValue.empty()) { It = FResults.erase(It); } else { ++It; } } AggResults[FName] = FResults; } return AggResults; } void IDELinearConstantAnalysis::LCAResult::print(std::ostream &OS) { OS << "Line " << line_nr << ": " << src_code << '\n'; OS << "Var(s): "; for (auto It = variableToValue.begin(); It != variableToValue.end(); ++It) { if (It != variableToValue.begin()) { OS << ", "; } OS << It->first << " = " << It->second; } OS << "\nCorresponding IR Instructions:\n"; for (const auto *Ir : ir_trace) { OS << " " << llvmIRToString(Ir) << '\n'; } } } // namespace psr
38.561297
88
0.651261
[ "vector" ]
0f59ee9386ab7f50a76ef3c99e0257a3ca9fcf03
5,136
cpp
C++
src/webots/scene_tree/WbTreeView.cpp
nishantkr18/webots
6ab631adb2e69906fc251cc77d690e67195de222
[ "Apache-2.0" ]
1
2020-06-08T13:38:11.000Z
2020-06-08T13:38:11.000Z
src/webots/scene_tree/WbTreeView.cpp
nishantkr18/webots
6ab631adb2e69906fc251cc77d690e67195de222
[ "Apache-2.0" ]
null
null
null
src/webots/scene_tree/WbTreeView.cpp
nishantkr18/webots
6ab631adb2e69906fc251cc77d690e67195de222
[ "Apache-2.0" ]
null
null
null
// Copyright 1996-2020 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "WbTreeView.hpp" #include "WbActionManager.hpp" #include "WbContextMenuGenerator.hpp" #include "WbNodeOperations.hpp" #include "WbSelection.hpp" #include "WbTreeItem.hpp" #include <QtWidgets/QHeaderView> #include <QtWidgets/QScrollBar> #include <QtWidgets/QStyle> #include <QtWidgets/QStyledItemDelegate> class WbTreeItemDelegate : public QStyledItemDelegate { public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override { QStyleOptionViewItem itemOption(option); WbTreeItem *item = static_cast<WbTreeItem *>(index.internalPointer()); if (item->isDefault()) // paint unmodified tree items in black itemOption.palette.setColor(QPalette::Text, mDefaultColor); else // paint modified tree items in dark cyan itemOption.palette.setColor(QPalette::Text, mModifiedColor); // call the base class method for drawing the normal // parts of the item of the QTreeView. QStyledItemDelegate::paint(painter, itemOption, index); } void setDefaultColor(const QColor &color) { mDefaultColor = color; } void setModifiedColor(const QColor &color) { mModifiedColor = color; } private: QColor mDefaultColor, mModifiedColor; }; WbTreeView::WbTreeView(QWidget *parent) : QTreeView(parent) { setObjectName("TreeView"); mIsScrollActive = false; mTreeItemDelegate = new WbTreeItemDelegate(); style()->polish(this); mTreeItemDelegate->setDefaultColor(defaultColor()); mTreeItemDelegate->setModifiedColor(modifiedColor()); setItemDelegate(mTreeItemDelegate); // display an horizontal scroll bar rather than // cutting strings with '...' characters header()->setSectionResizeMode(QHeaderView::ResizeToContents); // Qt5 version header()->setStretchLastSection(false); header()->setDefaultSectionSize(10000); setContextMenuPolicy(Qt::CustomContextMenu); connect(this, &QTreeView::customContextMenuRequested, this, &WbTreeView::showMenu); } WbTreeView::~WbTreeView() { delete mTreeItemDelegate; } void WbTreeView::focusInEvent(QFocusEvent *event) { QTreeView::focusInEvent(event); WbActionManager::instance()->enableTextEditActions(false); WbActionManager::instance()->setFocusObject(this); // when this widget gets keyboard focus the higlighted color of the current // item does not change unless we force Qt to redraw the tree view, so do // this by refreshing the item model emit refreshRequested(); emit focusIn(); } void WbTreeView::focusOutEvent(QFocusEvent *event) { if (WbActionManager::instance()->focusObject() == this) WbActionManager::instance()->setFocusObject(NULL); emit refreshRequested(); } void WbTreeView::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Left) { if (currentIndex().parent() != rootIndex() && !isExpanded(currentIndex())) setCurrentIndex(currentIndex().parent()); else if (isExpanded(currentIndex())) collapse(currentIndex()); } else if (event->key() == Qt::Key_Right && isExpanded(currentIndex())) setCurrentIndex(currentIndex().model()->index(0, 0, currentIndex())); else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) emit doubleClickOrEnterPressed(); else QTreeView::keyPressEvent(event); scrollToSelection(); } void WbTreeView::currentChanged(const QModelIndex &current, const QModelIndex &previous) { emit selectionHasChanged(); } void WbTreeView::itemInserted(const QModelIndex &index) { if (!WbNodeOperations::instance()->isFromSupervisor()) // select new tree item setCurrentIndex(index); } void WbTreeView::showMenu(const QPoint &position) { const WbBaseNode *selectedNode = WbSelection::instance() ? WbSelection::instance()->selectedNode() : NULL; WbContextMenuGenerator::generateContextMenu(mapToGlobal(position), selectedNode); } void WbTreeView::scrollToModelIndex(const QModelIndex &index) { mIsScrollActive = true; scrollTo(index); mIsScrollActive = false; } void WbTreeView::scrollTo(const QModelIndex &index, QTreeView::ScrollHint hint) { if (!mIsScrollActive) return; QTreeView::scrollTo(index, hint); if (!index.isValid()) return; // compute improved horizontal scroll position int level = -1; QModelIndex parentIndex = index.parent(); while (parentIndex.isValid()) { ++level; parentIndex = parentIndex.parent(); } horizontalScrollBar()->setValue(indentation() * level); } void WbTreeView::mouseDoubleClickEvent(QMouseEvent *event) { emit doubleClickOrEnterPressed(); }
32.923077
110
0.739097
[ "model" ]
0f5e9f80f03ce5b1c981bfc04d159c257a6fbca7
13,002
cxx
C++
Widgets/vtkSeedWidget.cxx
Lin1225/vtk_v5.10.0
b54ac74f4716572862365fbff28cd0ecb8d08c3d
[ "BSD-3-Clause" ]
3
2020-06-20T23:31:06.000Z
2021-01-11T02:17:16.000Z
Widgets/vtkSeedWidget.cxx
Lin1225/vtk_v5.10.0
b54ac74f4716572862365fbff28cd0ecb8d08c3d
[ "BSD-3-Clause" ]
1
2020-12-01T23:21:02.000Z
2020-12-02T23:44:43.000Z
Widgets/vtkSeedWidget.cxx
Lin1225/vtk_v5.10.0
b54ac74f4716572862365fbff28cd0ecb8d08c3d
[ "BSD-3-Clause" ]
5
2015-10-09T04:12:29.000Z
2021-12-15T16:57:11.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkSeedWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSeedWidget.h" #include "vtkCallbackCommand.h" #include "vtkCommand.h" #include "vtkCoordinate.h" #include "vtkEvent.h" #include "vtkHandleRepresentation.h" #include "vtkHandleWidget.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSeedRepresentation.h" #include "vtkWidgetCallbackMapper.h" #include "vtkWidgetEvent.h" #include <iterator> #include <list> vtkStandardNewMacro(vtkSeedWidget); // The vtkSeedList is a PIMPLed list<T>. class vtkSeedList : public std::list<vtkHandleWidget*> {}; typedef std::list<vtkHandleWidget*>::iterator vtkSeedListIterator; //---------------------------------------------------------------------- vtkSeedWidget::vtkSeedWidget() { this->ManagesCursor = 1; this->WidgetState = vtkSeedWidget::Start; // The widgets for moving the seeds. this->Seeds = new vtkSeedList; // These are the event callbacks supported by this widget this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkWidgetEvent::AddPoint, this, vtkSeedWidget::AddPointAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonPressEvent, vtkWidgetEvent::Completed, this, vtkSeedWidget::CompletedAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, vtkSeedWidget::MoveAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent, vtkWidgetEvent::EndSelect, this, vtkSeedWidget::EndSelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 127, 1, "Delete", vtkWidgetEvent::Delete, this, vtkSeedWidget::DeleteAction); this->Defining = 1; } //---------------------------------------------------------------------- void vtkSeedWidget::DeleteSeed(int i) { if( this->Seeds->size() <= static_cast< size_t >(i) ) { return; } vtkSeedRepresentation *rep = static_cast<vtkSeedRepresentation*>(this->WidgetRep); if (rep) { rep->RemoveHandle( i ); } vtkSeedListIterator iter = this->Seeds->begin(); std::advance(iter,i); (*iter)->SetEnabled(0); (*iter)->RemoveObservers(vtkCommand::StartInteractionEvent); (*iter)->RemoveObservers(vtkCommand::InteractionEvent); (*iter)->RemoveObservers(vtkCommand::EndInteractionEvent); vtkHandleWidget * w = (*iter); this->Seeds->erase( iter ); w->Delete(); } //---------------------------------------------------------------------- vtkSeedWidget::~vtkSeedWidget() { // Loop over all seeds releasing their observers and deleting them while( !this->Seeds->empty() ) { this->DeleteSeed(static_cast<int>(this->Seeds->size())-1); } delete this->Seeds; } //---------------------------------------------------------------------- vtkHandleWidget * vtkSeedWidget::GetSeed(int i) { if( this->Seeds->size() <= static_cast< size_t >(i) ) { return NULL; } vtkSeedListIterator iter = this->Seeds->begin(); std::advance(iter,i); return *iter; } //---------------------------------------------------------------------- void vtkSeedWidget::CreateDefaultRepresentation() { if ( ! this->WidgetRep ) { this->WidgetRep = vtkSeedRepresentation::New(); } } //---------------------------------------------------------------------- void vtkSeedWidget::SetEnabled(int enabling) { this->Superclass::SetEnabled( enabling ); vtkSeedListIterator iter; for ( iter = this->Seeds->begin(); iter != this->Seeds->end(); ++iter ) { (*iter)->SetEnabled( enabling ); } if ( !enabling ) { this->RequestCursorShape( VTK_CURSOR_DEFAULT ); this->WidgetState = vtkSeedWidget::Start; } this->Render(); } // The following methods are the callbacks that the seed widget responds to. //------------------------------------------------------------------------- void vtkSeedWidget::AddPointAction(vtkAbstractWidget *w) { vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w); // Need to distinguish between placing handles and manipulating handles if ( self->WidgetState == vtkSeedWidget::MovingSeed ) { return; } // compute some info we need for all cases int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; // When a seed is placed, a new handle widget must be created and enabled. int state = self->WidgetRep->ComputeInteractionState(X,Y); if ( state == vtkSeedRepresentation::NearSeed ) { self->WidgetState = vtkSeedWidget::MovingSeed; // Invoke an event on ourself for the handles self->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL); self->Superclass::StartInteraction(); self->InvokeEvent(vtkCommand::StartInteractionEvent,NULL); self->EventCallbackCommand->SetAbortFlag(1); self->Render(); } else if ( self->WidgetState != vtkSeedWidget::PlacedSeeds) { // we are placing a new seed. Just make sure we aren't in a mode which // dictates we've placed all seeds. self->WidgetState = vtkSeedWidget::PlacingSeeds; double e[3]; e[2]=0.0; e[0] = static_cast<double>(X); e[1] = static_cast<double>(Y); vtkSeedRepresentation *rep = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep); // if the handle representation is constrained, check to see if // the position follows the constraint. if ( !rep->GetHandleRepresentation()->CheckConstraint( self->GetCurrentRenderer(), e ) ) { return ; } int currentHandleNumber = rep->CreateHandle(e); vtkHandleWidget *currentHandle = self->CreateNewHandle(); rep->SetSeedDisplayPosition(currentHandleNumber,e); currentHandle->SetEnabled(1); self->InvokeEvent(vtkCommand::PlacePointEvent,&(currentHandleNumber)); self->InvokeEvent(vtkCommand::InteractionEvent,&(currentHandleNumber)); self->EventCallbackCommand->SetAbortFlag(1); self->Render(); } } //------------------------------------------------------------------------- void vtkSeedWidget::CompletedAction(vtkAbstractWidget *w) { vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w); // Do something only if we are in the middle of placing the seeds if ( self->WidgetState == vtkSeedWidget::PlacingSeeds ) { self->CompleteInteraction(); } } //------------------------------------------------------------------------- void vtkSeedWidget::CompleteInteraction() { this->WidgetState = vtkSeedWidget::PlacedSeeds; this->EventCallbackCommand->SetAbortFlag(1); this->Defining = 0; } //------------------------------------------------------------------------- void vtkSeedWidget::RestartInteraction() { this->WidgetState = vtkSeedWidget::Start; this->Defining = 1; } //------------------------------------------------------------------------- void vtkSeedWidget::MoveAction(vtkAbstractWidget *w) { vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w); // Do nothing if outside if ( self->WidgetState == vtkSeedWidget::Start ) { return; } // else we are moving a seed self->InvokeEvent(vtkCommand::MouseMoveEvent, NULL); // set the cursor shape to a hand if we are near a seed. int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; int state = self->WidgetRep->ComputeInteractionState(X,Y); // Change the cursor shape to a hand and invoke an interaction event if we // are near the seed if (state == vtkSeedRepresentation::NearSeed) { self->RequestCursorShape( VTK_CURSOR_HAND ); vtkSeedRepresentation *rep = static_cast< vtkSeedRepresentation * >(self->WidgetRep); int seedIdx = rep->GetActiveHandle(); self->InvokeEvent( vtkCommand::InteractionEvent, &seedIdx ); self->EventCallbackCommand->SetAbortFlag(1); } else { self->RequestCursorShape( VTK_CURSOR_DEFAULT ); } self->Render(); } //------------------------------------------------------------------------- void vtkSeedWidget::EndSelectAction(vtkAbstractWidget *w) { vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w); // Do nothing if outside if ( self->WidgetState != vtkSeedWidget::MovingSeed ) { return; } // Revert back to the mode we were in prior to selection. self->WidgetState = self->Defining ? vtkSeedWidget::PlacingSeeds : vtkSeedWidget::PlacedSeeds; // Invoke event for seed handle self->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); self->EventCallbackCommand->SetAbortFlag(1); self->InvokeEvent(vtkCommand::EndInteractionEvent,NULL); self->Superclass::EndInteraction(); self->Render(); } //------------------------------------------------------------------------- void vtkSeedWidget::DeleteAction(vtkAbstractWidget *w) { vtkSeedWidget *self = reinterpret_cast<vtkSeedWidget*>(w); // Do nothing if outside if ( self->WidgetState != vtkSeedWidget::PlacingSeeds ) { return; } // Remove last seed vtkSeedRepresentation *rep = reinterpret_cast<vtkSeedRepresentation*>(self->WidgetRep); int removeId = rep->GetActiveHandle(); if ( removeId != -1 ) { rep->RemoveActiveHandle(); } else { rep->RemoveLastHandle(); removeId = static_cast<int>(self->Seeds->size())-1; } self->DeleteSeed(removeId); // Got this event, abort processing if it self->EventCallbackCommand->SetAbortFlag(1); self->Render(); } //---------------------------------------------------------------------- void vtkSeedWidget::SetProcessEvents(int pe) { this->Superclass::SetProcessEvents(pe); vtkSeedListIterator iter = this->Seeds->begin(); for (; iter != this->Seeds->end(); ++iter ) { (*iter)->SetProcessEvents(pe); } } //---------------------------------------------------------------------- void vtkSeedWidget::SetInteractor( vtkRenderWindowInteractor *rwi ) { this->Superclass::SetInteractor(rwi); vtkSeedListIterator iter = this->Seeds->begin(); for (; iter != this->Seeds->end(); ++iter ) { (*iter)->SetInteractor(rwi); } } //---------------------------------------------------------------------- void vtkSeedWidget::SetCurrentRenderer( vtkRenderer *ren ) { this->Superclass::SetCurrentRenderer(ren); vtkSeedListIterator iter = this->Seeds->begin(); for (; iter != this->Seeds->end(); ++iter ) { if (!ren) { // Disable widget if its being removed from the the renderer (*iter)->EnabledOff(); } (*iter)->SetCurrentRenderer(ren); } } //---------------------------------------------------------------------- // Programmatically create a new handle. vtkHandleWidget * vtkSeedWidget::CreateNewHandle() { vtkSeedRepresentation *rep = vtkSeedRepresentation::SafeDownCast(this->WidgetRep); if (!rep) { vtkErrorMacro( << "Please set, or create a default seed representation " << "before adding requesting creation of a new handle." ); return NULL; } // Create the handle widget or reuse an old one int currentHandleNumber = static_cast<int>(this->Seeds->size()); vtkHandleWidget *widget = vtkHandleWidget::New(); // Configure the handle widget widget->SetParent(this); widget->SetInteractor(this->Interactor); vtkHandleRepresentation *handleRep = rep->GetHandleRepresentation(currentHandleNumber); if (!handleRep) { widget->Delete(); return NULL; } else { handleRep->SetRenderer(this->CurrentRenderer); widget->SetRepresentation(handleRep); // Now place the widget into the list of handle widgets (if not already there) this->Seeds->push_back( widget ); return widget; } } //---------------------------------------------------------------------- void vtkSeedWidget::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); os << indent << "WidgetState: " << this->WidgetState << endl; }
31.405797
89
0.5996
[ "render", "shape" ]
0f61e2ca5e4ac5807b2416ad36723fa504890d8b
8,145
cc
C++
test/scenario/network/network_emulation_pc_unittest.cc
Numbrs/WebRTC
d9348ec831b8a1f178ce1a92877f04b1fbd27a04
[ "BSD-3-Clause" ]
4
2019-11-26T07:08:00.000Z
2021-06-20T08:53:50.000Z
test/scenario/network/network_emulation_pc_unittest.cc
Numbrs/WebRTC
d9348ec831b8a1f178ce1a92877f04b1fbd27a04
[ "BSD-3-Clause" ]
null
null
null
test/scenario/network/network_emulation_pc_unittest.cc
Numbrs/WebRTC
d9348ec831b8a1f178ce1a92877f04b1fbd27a04
[ "BSD-3-Clause" ]
4
2019-11-25T09:25:01.000Z
2021-08-20T06:00:04.000Z
/* * Copyright 2019 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <cstdint> #include <memory> #include "absl/memory/memory.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/call/call_factory_interface.h" #include "api/peer_connection_interface.h" #include "api/scoped_refptr.h" #include "api/video_codecs/builtin_video_decoder_factory.h" #include "api/video_codecs/builtin_video_encoder_factory.h" #include "call/simulated_network.h" #include "logging/rtc_event_log/rtc_event_log_factory.h" #include "media/engine/webrtc_media_engine.h" #include "modules/audio_device/include/test_audio_device.h" #include "p2p/client/basic_port_allocator.h" #include "pc/peer_connection_wrapper.h" #include "pc/test/mock_peer_connection_observers.h" #include "rtc_base/async_invoker.h" #include "rtc_base/fake_network.h" #include "rtc_base/gunit.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/scenario/network/network_emulation.h" #include "test/scenario/network/network_emulation_manager.h" namespace webrtc { namespace test { namespace { constexpr int kDefaultTimeoutMs = 1000; constexpr int kMaxAptitude = 32000; constexpr int kSamplingFrequency = 48000; constexpr char kSignalThreadName[] = "signaling_thread"; bool AddIceCandidates(PeerConnectionWrapper* peer, std::vector<const IceCandidateInterface*> candidates) { bool success = true; for (const auto candidate : candidates) { if (!peer->pc()->AddIceCandidate(candidate)) { success = false; } } return success; } rtc::scoped_refptr<PeerConnectionFactoryInterface> CreatePeerConnectionFactory( rtc::Thread* signaling_thread, rtc::Thread* network_thread) { PeerConnectionFactoryDependencies pcf_deps; pcf_deps.call_factory = webrtc::CreateCallFactory(); pcf_deps.event_log_factory = webrtc::CreateRtcEventLogFactory(); pcf_deps.network_thread = network_thread; pcf_deps.signaling_thread = signaling_thread; pcf_deps.media_engine = cricket::WebRtcMediaEngineFactory::Create( TestAudioDeviceModule::CreateTestAudioDeviceModule( TestAudioDeviceModule::CreatePulsedNoiseCapturer(kMaxAptitude, kSamplingFrequency), TestAudioDeviceModule::CreateDiscardRenderer(kSamplingFrequency)), webrtc::CreateBuiltinAudioEncoderFactory(), webrtc::CreateBuiltinAudioDecoderFactory(), webrtc::CreateBuiltinVideoEncoderFactory(), webrtc::CreateBuiltinVideoDecoderFactory(), /*audio_mixer=*/nullptr, webrtc::AudioProcessingBuilder().Create()); return CreateModularPeerConnectionFactory(std::move(pcf_deps)); } rtc::scoped_refptr<PeerConnectionInterface> CreatePeerConnection( const rtc::scoped_refptr<PeerConnectionFactoryInterface>& pcf, PeerConnectionObserver* observer, rtc::NetworkManager* network_manager) { PeerConnectionDependencies pc_deps(observer); auto port_allocator = absl::make_unique<cricket::BasicPortAllocator>(network_manager); // This test does not support TCP int flags = cricket::PORTALLOCATOR_DISABLE_TCP; port_allocator->set_flags(port_allocator->flags() | flags); pc_deps.allocator = std::move(port_allocator); PeerConnectionInterface::RTCConfiguration rtc_configuration; rtc_configuration.sdp_semantics = SdpSemantics::kUnifiedPlan; return pcf->CreatePeerConnection(rtc_configuration, std::move(pc_deps)); } } // namespace TEST(NetworkEmulationManagerPCTest, Run) { std::unique_ptr<rtc::Thread> signaling_thread = rtc::Thread::Create(); signaling_thread->SetName(kSignalThreadName, nullptr); signaling_thread->Start(); // Setup emulated network NetworkEmulationManager network_manager; EmulatedNetworkNode* alice_node = network_manager.CreateEmulatedNode( absl::make_unique<SimulatedNetwork>(BuiltInNetworkBehaviorConfig())); EmulatedNetworkNode* bob_node = network_manager.CreateEmulatedNode( absl::make_unique<SimulatedNetwork>(BuiltInNetworkBehaviorConfig())); EndpointNode* alice_endpoint = network_manager.CreateEndpoint(EndpointConfig()); EndpointNode* bob_endpoint = network_manager.CreateEndpoint(EndpointConfig()); network_manager.CreateRoute(alice_endpoint, {alice_node}, bob_endpoint); network_manager.CreateRoute(bob_endpoint, {bob_node}, alice_endpoint); rtc::Thread* alice_network_thread = network_manager.CreateNetworkThread({alice_endpoint}); rtc::Thread* bob_network_thread = network_manager.CreateNetworkThread({bob_endpoint}); // Setup peer connections. rtc::scoped_refptr<PeerConnectionFactoryInterface> alice_pcf; rtc::scoped_refptr<PeerConnectionInterface> alice_pc; std::unique_ptr<MockPeerConnectionObserver> alice_observer = absl::make_unique<MockPeerConnectionObserver>(); std::unique_ptr<rtc::FakeNetworkManager> alice_network_manager = absl::make_unique<rtc::FakeNetworkManager>(); alice_network_manager->AddInterface( rtc::SocketAddress(alice_endpoint->GetPeerLocalAddress(), 0)); rtc::scoped_refptr<PeerConnectionFactoryInterface> bob_pcf; rtc::scoped_refptr<PeerConnectionInterface> bob_pc; std::unique_ptr<MockPeerConnectionObserver> bob_observer = absl::make_unique<MockPeerConnectionObserver>(); std::unique_ptr<rtc::FakeNetworkManager> bob_network_manager = absl::make_unique<rtc::FakeNetworkManager>(); bob_network_manager->AddInterface( rtc::SocketAddress(bob_endpoint->GetPeerLocalAddress(), 0)); signaling_thread->Invoke<void>(RTC_FROM_HERE, [&]() { alice_pcf = CreatePeerConnectionFactory(signaling_thread.get(), alice_network_thread); alice_pc = CreatePeerConnection(alice_pcf, alice_observer.get(), alice_network_manager.get()); bob_pcf = CreatePeerConnectionFactory(signaling_thread.get(), bob_network_thread); bob_pc = CreatePeerConnection(bob_pcf, bob_observer.get(), bob_network_manager.get()); }); std::unique_ptr<PeerConnectionWrapper> alice = absl::make_unique<PeerConnectionWrapper>(alice_pcf, alice_pc, std::move(alice_observer)); std::unique_ptr<PeerConnectionWrapper> bob = absl::make_unique<PeerConnectionWrapper>(bob_pcf, bob_pc, std::move(bob_observer)); signaling_thread->Invoke<void>(RTC_FROM_HERE, [&]() { rtc::scoped_refptr<webrtc::AudioSourceInterface> source = alice_pcf->CreateAudioSource(cricket::AudioOptions()); rtc::scoped_refptr<AudioTrackInterface> track = alice_pcf->CreateAudioTrack("audio", source); alice->AddTransceiver(track); // Connect peers. ASSERT_TRUE(alice->ExchangeOfferAnswerWith(bob.get())); // Do the SDP negotiation, and also exchange ice candidates. ASSERT_TRUE_WAIT( alice->signaling_state() == PeerConnectionInterface::kStable, kDefaultTimeoutMs); ASSERT_TRUE_WAIT(alice->IsIceGatheringDone(), kDefaultTimeoutMs); ASSERT_TRUE_WAIT(bob->IsIceGatheringDone(), kDefaultTimeoutMs); // Connect an ICE candidate pairs. ASSERT_TRUE( AddIceCandidates(bob.get(), alice->observer()->GetAllCandidates())); ASSERT_TRUE( AddIceCandidates(alice.get(), bob->observer()->GetAllCandidates())); // This means that ICE and DTLS are connected. ASSERT_TRUE_WAIT(bob->IsIceConnected(), kDefaultTimeoutMs); ASSERT_TRUE_WAIT(alice->IsIceConnected(), kDefaultTimeoutMs); // Close peer connections alice->pc()->Close(); bob->pc()->Close(); // Delete peers. alice.reset(); bob.reset(); }); } } // namespace test } // namespace webrtc
41.345178
80
0.742787
[ "vector" ]
0f64f70f4b676599cec3b9b0c501d596d77b8007
9,780
hpp
C++
include/filesplitter.hpp
jmcarter9t/filesplitter
c92a2fca23c064688e18336baf86092ab538dba8
[ "Apache-2.0" ]
null
null
null
include/filesplitter.hpp
jmcarter9t/filesplitter
c92a2fca23c064688e18336baf86092ab538dba8
[ "Apache-2.0" ]
null
null
null
include/filesplitter.hpp
jmcarter9t/filesplitter
c92a2fca23c064688e18336baf86092ab538dba8
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef FILESPLITTER_HPP #define FILESPLITTER_HPP #include <mutex> #include <cstdio> #include "tool.hpp" #include "spdlog/spdlog.h" /** * @brief predicate indicating whether a file exists on the filesystem. * * @param fn the file name and path to check the existance of. * * @return true if it exists, false otherwise. */ bool fileExists( const std::string& fn ); /** * @brief predicate indicating whether a path/directory exists on the filesystem. * * @param dn the directory path to check the existance of. * * @return true if it exists, false otherwise. */ bool dirExists( const std::string& dn ); /** * A class that performs multithreaded file split operations. */ class FileSplitter : public tool::Tool { public: using FSPtr = std::shared_ptr<FileSplitter>; using LogPtr = std::shared_ptr<spdlog::logger>; static char rdelim; static char fdelim; /** * @brief Construct a FileSplitter instance. * * @param name the name of the tool * @param description a description for the tool */ FileSplitter(const std::string& name, const std::string& description); /** * @brief Get the full path and name to the input file being split. * * @return the full path and name as a string. */ const std::string& getInputFileName() const; /** * @brief Get the full path to the output directory where split files will be written. * * @return the full path and name as a string. */ const std::string& getOutputDirectoryName() const; /** * @brief Get the size of the input file in bytes. * * @return the size of the file in bytes. */ long getFileSize() const; /** * @brief If the input file has a header this will produce that line INCLUDING the newline character. * * @return the header including newline; empty string if no header exists. */ const std::string& getHeader() const; /** * @brief a predicate that indicates whether the input file had a header. * * @return true if the input file has a header; false otherwise. */ bool hasHeader() const; /** * @brief Initialize a multithreaded logger for the filesplitter. * * @param logname the name of the log file. * @param path where the log file will be written, relative or absolute. * * @return true on success; false otherwise. */ bool initLogger( std::string& logname, std::string& path ); int operator() ( void ) override; /** * Splits the file. * * @param filename the file to split. * * @return the program exit status. */ int splitFile( void ); private: std::string ifname_; ///> the name of the file to split. std::string odname_; ///> the directory for the split files. long ifsize_; ///> the size in bytes of the file. std::string header_; ///> the header line of the file or the empty string if no header. LogPtr logger_; ///> multithreaded logger. std::vector<uint32_t> keylist_; ///> Contains the indices of the colums to use as keys. bool initOutputDirectory( std::string& odname ); long initInputFile( std::string& ifname, std::string& header ); }; /** * Functor for finding and writing blocks in a thread. * Good link on copy options: http://stackoverflow.com/questions/10195343/copy-a-file-in-a-sane-safe-and-efficient-way */ class BlockHandler { public: static constexpr int BUFSIZE = 8 * 1024; ///> 8k seems a good buffer size. /** * @param ifname the name of the file. * @param ifsize the total size of the file; this includes HEADER. * @param header header to append to all blocks; could be the empty string. * @param begin byte offset of the "proposed" beginning of the data portion of the block (will never include header). * @param end byte offset of the "proposed" end of the block; could be the last byte in the file. */ BlockHandler( const std::string& ifname, const std::string& odname, long ifsize, const std::string& header, FileSplitter::LogPtr logger, const std::vector<uint32_t>& keylist ); /** * @brief Destroy the block handler. */ ~BlockHandler( void ); /** * @brief Execute the thread to handle a file block. * * Strategy to identify boundaries of focus: * * 1. Both begin and end positions move forward during the search unless they cannot. * a. begin position cannot move forward by definition. * b. end position is "sticky" and cannot move forward by algorithm. * 2. When a block is homogeneous (same key found at beginning and end) and end is not EOF, the thread will exit. * 3. search for record offset only looks forward; therefore, when searching from EOF it will find the key on * the last line. * * Once BOUNDS are found, then we can partition into blocks. * * 1. If begin key and end key are the same, then write the entire block. * 2. current key is the end key. * 3. epos = end; bpos = begin (do not modify begin and end yet...) * 4. Jump toward the front: jp = floor((bpos+epos)/2) * 5. While jp >= bpos && jp <= epos * 6. Get key. * 7. If the same as end, * a. update epos = jp * b. jump toward front: jp = floor((bpos+jp)/2); goto 4. * 8. If different, * a. update bpos = jp * b. jump toward the end: jp = floor((jp+epos)/2); goto 5. * * Expected Results for Special Cases: * * 1. When file is entirely of one key, the thread with end == EOF will write a copy of the entire file; all * other threads will exit doing nothing. * 2. All homogeneous blocks will do nothing */ void operator()( long begin, long end ); /** * @brief Set the position in a file (inf), to the beginning of the current record and return the byte offset of that * position. * * If start <= begin, the file will be positioned at start (this is an abnormal parameter setting). * If start or begin is less than 0 it will be set to 0. * If start is greater than the size of the file (or within the last record), the start of the last record will be * returned. * * @param inf the file pointer to set; it is expected to be open. * @param soff the position in the file from which to start the search; start should be >= 0. * @return the byte offset of the start of the record the parameter was within, or -1 on error. */ long setRecordStartOffset( FILE* inf, long soff ); /** * @brief Extract the record key from the record designated by spos return it along with the byte offset of the first * byte in that key. * * @param f the file to identify the key within. * @param soff the starting search byte offset within f; this can be anywhere within the record of interest. * @param key location to set the key (this is modified by the method). * @return long the byte offset of the first character in key (the beginning of the record). */ long setRecordKey( FILE* f, long soff, std::string& key ); long setRecordMultiKey( FILE* f, long soff, std::string& key ); /** * @brief Return the byte offset of the first record in f having the same key as the record that includes the byte at * soff. In other words, soff can be anywhere in a record (start, ending \n, etc). * * Steps: * * 1. Find the key of the initial record. * 2. Perform a logarithmic search, i.e., jump to half-way points forward and backward for the first instance of that * key moving forward in the file. * 3. Return the offset of the first byte of that first record. * * @param f the file to search. * @param soff the byte offset in f to start and identify the key to search for. * @param begin the absolute beginning byte offset in f. * @param end the absoute end byte offset in f. * * @return the byte offset of the first record in f having the required key. * @note bkey_ will contain the key for the first record (it is private) */ long findFirstRecord( FILE* f, long soff, long end ); /** * NOTE: This is faster than using c++ streams. Not by much, but the code is almost the same when you have to slice * out of the file. */ long transfer( long soff, long bytes_to_write, const std::string& ofn ); private: const std::string& ifname_; const std::string& odname_; long ifsize_; const std::string& header_; FileSplitter::LogPtr logger_; const std::vector<uint32_t>& keylist_; std::string bkey_; std::string ckey_; char buf[BUFSIZE]; ///> one buffer per handler. }; #endif
40.75
184
0.586605
[ "vector" ]
0f6e5d71ee2e674621b0d58bfb89643937c2da1c
45,609
cpp
C++
src/raven_src/src/CustomOutput.cpp
Okanagan-Basin-Water-Board/obwb-hydro-modelling
91ee6b914e344de65a495093c3b9427986182ef2
[ "Artistic-2.0" ]
null
null
null
src/raven_src/src/CustomOutput.cpp
Okanagan-Basin-Water-Board/obwb-hydro-modelling
91ee6b914e344de65a495093c3b9427986182ef2
[ "Artistic-2.0" ]
null
null
null
src/raven_src/src/CustomOutput.cpp
Okanagan-Basin-Water-Board/obwb-hydro-modelling
91ee6b914e344de65a495093c3b9427986182ef2
[ "Artistic-2.0" ]
null
null
null
/*---------------------------------------------------------------- Raven Library Source Code Copyright (c) 2008-2019 the Raven Development Team, Ayman Khedr ----------------------------------------------------------------*/ #include "CustomOutput.h" void WriteNetCDFGlobalAttributes(int out_ncid,const optStruct &Options,string descript);//in StandardOutput.cpp /***************************************************************** Constructor/Destructor ------------------------------------------------------------------ *****************************************************************/ ////////////////////////////////////////////////////////////////// /// \brief Implementation of the CCustomOutput constructor /// \param variable [in] Output variable assessed in custom output file /// \param sv [in] State variable output type (if output is a SV) /// \param sv_index [in] State variable index (if output is a state variable) /// \param force_string [in] Forcing function name (if output is a forcing function) /// \param stat [in] Time aggregate statistic (average, maximum, range, etc.) /// \param time_aggregation [in] How frequently data is aggregated (monthly, daily, hourly, etc.) /// \param space_aggregation [in] How data is spatially aggregated (by HRU, by basin, etc.) /// \param *pMod [in] Pointer to model /// \param &Options [in] Global model options information // CCustomOutput::CCustomOutput( const diagnostic variable, const sv_type sv, const int sv_index, const int sv_index2, const string force_string, const agg_stat stat, const time_agg time_aggregation, const spatial_agg space_aggregation, const string filename_spec, const int kk, const CModel *pMod, const optStruct &Options) { // no point in going further if we don't have a model ExitGracefullyIf(pMod==NULL,"CCustomOutput Constructor: NULL model",BAD_DATA); // set up the objects member variables _netcdf_ID = -9; //doesn't exist _var =variable; // forcing variable, state variable, flux, etc. _svtype =sv; // state variable type (if output var is a SV) _svind =sv_index; // state variable index (if output var is a SV or flux) _svind2 =sv_index2; // state variable target index (if output var is a flux between) _force_str=force_string; // name of forcing variable (if output var is a forcing function) _spaceAgg =space_aggregation; // how we're aggregation the data (ByHRU,BySubbasin, etc.) _timeAgg =time_aggregation; // yearly, monthly, etc. _aggstat =stat; // the statistic we're calculating pModel =pMod; // pointer to the main model _varName ="UNKNOWN"; _varUnits ="none"; _timeAggStr ="UNKNOWN"; _statStr ="UNKNOWN"; _spaceAggStr ="UNKNOWN"; num_data =1; data =NULL; // pointer to data storage for aggregation _hist_min =0; _hist_max =10; _nBins =1; //Arbitrary default count =0; kk_only =kk; ExitGracefullyIf((kk_only==DOESNT_EXIST) && (_spaceAgg==BY_SELECT_HRUS), "CCustomOutput Constructor: invalid HRU group index for Select HRU Aggregation. Undefined HRU group?",BAD_DATA); _time_index=0; //------------------------------------------------------------- // figure out filename here // RunName if available ostrstream FILENAME; if (Options.run_name!=""){FILENAME<<Options.output_dir<<Options.run_name<<"_";} else {FILENAME<<Options.output_dir; } // Get the variable name (either the state variable name of the forcing variable name) // and the units switch(_var) { case (VAR_STATE_VAR): { sv_type typ=pModel->GetStateVarType(_svind); int ind=pModel->GetStateVarLayer(_svind); _varName = CStateVariable::SVTypeToString(typ,ind); _varUnits = CStateVariable::GetStateVarUnits(typ); if (pModel->GetStateVarType(_svind)==CONSTITUENT){ _varUnits = "mg/L"; } //overridden for concentrations break; } case (VAR_FORCING_FUNCTION): { _varName = _force_str; forcing_type typ=GetForcingTypeFromString(_force_str); ExitGracefullyIf(typ==F_UNRECOGNIZED, "CCustomOutput Constructor: invalid forcing type string",BAD_DATA); _varUnits = GetForcingTypeUnits(typ); break; } case (VAR_TO_FLUX) : //cumulative flux { sv_type typ=pModel->GetStateVarType(_svind); int ind=pModel->GetStateVarLayer(_svind); _varName = "TO_"+CStateVariable::SVTypeToString(typ,ind); _varUnits = CStateVariable::GetStateVarUnits(typ); break; } case (VAR_FROM_FLUX) : //cumulative flux { sv_type typ=pModel->GetStateVarType(_svind); int ind=pModel->GetStateVarLayer(_svind); _varName = "FROM_"+CStateVariable::SVTypeToString(typ,ind); _varUnits = CStateVariable::GetStateVarUnits(typ); break; } case (VAR_BETWEEN_FLUX) : { sv_type typ=pModel->GetStateVarType(_svind); int ind=pModel->GetStateVarLayer(_svind); ExitGracefullyIf(_svind2==DOESNT_EXIST,"Invalid second SV index in :CustomOutput :Between command",BAD_DATA_WARN); sv_type typ2=pModel->GetStateVarType(_svind2); int ind2=pModel->GetStateVarLayer(_svind2); _varName = "BETWEEN_"+CStateVariable::SVTypeToString(typ,ind)+"_AND_"+CStateVariable::SVTypeToString(typ2,ind2); _varUnits = CStateVariable::GetStateVarUnits(typ)+"/d"; break; } default: { _varName = "UNKNOWN"; _varUnits = "none"; break; } } FILENAME<<_varName<<"_"; // temporal aggregation switch(_timeAgg) { case YEARLY: _timeAggStr="Yearly"; break; case MONTHLY: _timeAggStr="Monthly"; break; case DAILY: _timeAggStr="Daily"; break; case WATER_YEARLY: _timeAggStr="WYearly";break; case EVERY_NDAYS: _timeAggStr="Every"+to_string(int(Options.custom_interval))+"days";break; case EVERY_TSTEP: _timeAggStr="Continuous"; break; } FILENAME<<_timeAggStr<<"_"; // statistic switch(_aggstat) { case AGG_AVERAGE: _statStr="Average"; break; case AGG_MAXIMUM: _statStr="Maximum"; break; case AGG_MINIMUM: _statStr="Minimum"; break; case AGG_RANGE: _statStr="Range"; break; case AGG_MEDIAN: _statStr="Median"; break; case AGG_95CI: _statStr="95%"; break; case AGG_QUARTILES: _statStr="Quartiles"; break; case AGG_HISTOGRAM: _statStr="Histogram"; break; } FILENAME<<_statStr<<"_"; // spatial aggregation switch(_spaceAgg) { case BY_HRU: _spaceAggStr="ByHRU"; break; case BY_BASIN: _spaceAggStr="BySubbasin"; break; case BY_WSHED: _spaceAggStr="ByWatershed"; break; case BY_HRU_GROUP: _spaceAggStr="ByHRUGroup"; break; case BY_SELECT_HRUS: _spaceAggStr="ByHRU"; break; } FILENAME<<_spaceAggStr; // filename extension switch(Options.output_format) { case OUTPUT_ENSIM: FILENAME<<".tb0"<<ends; break; case OUTPUT_NETCDF: FILENAME<<".nc" <<ends; break; case OUTPUT_STANDARD: default: FILENAME<<".csv"<<ends; break; } if (filename_spec==""){_filename=FILENAME.str();} else { if (Options.run_name!=""){_filename=Options.output_dir+Options.run_name+"_"+filename_spec;} else {_filename=Options.output_dir+filename_spec; } // \todo [QA/QC]: should check for proper extension of filename_spec } } ////////////////////////////////////////////////////////////////// /// \brief Implementation of the default destructor // CCustomOutput::~CCustomOutput() { delete [] data; data=NULL; CloseFiles(); } ////////////////////////////////////////////////////////////////// /// \brief Set histogram-related parameters /// \param minv [in] Histogram minimum /// \param maxv [in] Histogram maximum /// \param numBins [in] Histogram number of bins // void CCustomOutput::SetHistogramParams(const double minv,const double maxv, const int numBins) { _hist_min=minv; _hist_max=maxv; _nBins=numBins; } /////////////////////////////////////////////////////////////////// /// \brief Allocates memory and initialize data storage of a CCustomOutput object /// \remarks Called prior to simulation. Determines size of and allocates memory for (member) data[][] array needed in statistical calculations /// \param &Options [in] Global model options information // void CCustomOutput::InitializeCustomOutput(const optStruct &Options) { // figure out how much space we need if (_spaceAgg==BY_HRU ){num_data=pModel->GetNumHRUs();} else if (_spaceAgg==BY_BASIN ){num_data=pModel->GetNumSubBasins();} else if (_spaceAgg==BY_WSHED ){num_data=1;} else if (_spaceAgg==BY_HRU_GROUP ){num_data=pModel->GetNumHRUGroups();} else if (_spaceAgg==BY_SELECT_HRUS){num_data=pModel->GetHRUGroup(kk_only)->GetNumHRUs();} if (_aggstat==AGG_AVERAGE){num_store=1;} else if (_aggstat==AGG_MAXIMUM){num_store=1;} else if (_aggstat==AGG_MINIMUM){num_store=1;} else if (_aggstat==AGG_RANGE) {num_store=2;} else if ((_aggstat==AGG_MEDIAN ) || (_aggstat==AGG_95CI ) || (_aggstat==AGG_QUARTILES) || (_aggstat==AGG_HISTOGRAM)) { if (_timeAgg==YEARLY ){num_store=(int)ceil(366/Options.timestep)+1;} else if (_timeAgg==WATER_YEARLY){num_store=(int)ceil(366/Options.timestep)+1;} else if (_timeAgg==EVERY_NDAYS ){num_store=(int)ceil(Options.custom_interval/Options.timestep)+1; } else if (_timeAgg==MONTHLY ){num_store=(int)ceil( 31/Options.timestep)+1;} else if (_timeAgg==DAILY ){num_store=(int)ceil( 1/Options.timestep)+1;} else if (_timeAgg==EVERY_TSTEP ){num_store=1;} } else{ ExitGracefully("CCustomOutput::InitializeCustomOutput(): bad aggregator",BAD_DATA); } // allocate space for the aggregation data =new double *[num_data]; for (int k=0;k<num_data;k++) { data[k]=NULL; data[k]=new double [num_store]; ExitGracefullyIf(data[k]==NULL,"CCustomOutput constructor",OUT_OF_MEMORY); for (int a=0;a<num_store;a++){data[k][a]=0.0;} } } ////////////////////////////////////////////////////////////////// /// \brief Open a stream to the file and write header info // void CCustomOutput::WriteFileHeader(const optStruct &Options) { _CUSTOM.open(_filename.c_str()); if (_CUSTOM.fail()){ WriteWarning("CCustomOutput::WriteFileHeader: Unable to create file "+_filename,true); } // clear data (for ensembles) for(int k=0;k<num_data;k++){ for(int a=0;a<num_store;a++) { data[k][a]=0.0; } } // write the appropriately formatted header switch(Options.output_format) { case OUTPUT_STANDARD: default: WriteCSVFileHeader(); return; break; case OUTPUT_ENSIM: WriteEnSimFileHeader(Options); return; break; case OUTPUT_NETCDF: WriteNetCDFFileHeader(Options); return; break; } } ////////////////////////////////////////////////////////////////// /// \brief Write header info to "STANDARD" CSV file // void CCustomOutput::WriteCSVFileHeader(void) { // standard csv output //-Line 1- if (_timeAgg==YEARLY ){_CUSTOM<<",";} else if (_timeAgg==MONTHLY ){_CUSTOM<<",";} else if (_timeAgg==DAILY ){_CUSTOM<<",";} else if (_timeAgg==EVERY_TSTEP ){_CUSTOM<<",,";} else if (_timeAgg==WATER_YEARLY){_CUSTOM<<",";} else if (_timeAgg==EVERY_NDAYS ){_CUSTOM<<",";} if (_spaceAgg==BY_HRU ){_CUSTOM<<"HRU:,";} else if (_spaceAgg==BY_BASIN ){_CUSTOM<<"SubBasin:,";} else if (_spaceAgg==BY_WSHED ){_CUSTOM<<"Watershed:,";} else if (_spaceAgg==BY_HRU_GROUP ){_CUSTOM<<"HRUGroup:,";} else if (_spaceAgg==BY_SELECT_HRUS){_CUSTOM<<"HRU:,";} for (int k=0;k<num_data;k++) { string title; ostrstream TMP; if (_spaceAgg==BY_HRU ){TMP<<pModel->GetHydroUnit(k)->GetID() <<ends;} else if (_spaceAgg==BY_HRU_GROUP ){TMP<<pModel->GetHRUGroup(k)->GetName()<<ends;} else if (_spaceAgg==BY_WSHED ){TMP<<"Watershed" <<ends;} else if (_spaceAgg==BY_BASIN ){TMP<<pModel->GetSubBasin(k)->GetID() <<ends;} else if (_spaceAgg==BY_SELECT_HRUS){TMP<<pModel->GetHRUGroup(kk_only)->GetHRU(k)->GetID()<<ends;} title=TMP.str(); if (_aggstat == AGG_MEDIAN ){_CUSTOM<<title<<",";} else if (_aggstat == AGG_95CI ){_CUSTOM<<title<<",,";} else if (_aggstat == AGG_QUARTILES){_CUSTOM<<title<<",,,";} else if (_aggstat == AGG_HISTOGRAM){ _CUSTOM<<title; for (int bin=0;bin<_nBins;bin++){_CUSTOM<<",";} } else { _CUSTOM<<title<<",";for (int i=1;i<num_store;i++){_CUSTOM<<",";} } } _CUSTOM<<endl; //-Line 2- if (_timeAgg==YEARLY ){_CUSTOM<<"time,year,";} else if (_timeAgg==WATER_YEARLY){_CUSTOM<<"time,water year,";} else if (_timeAgg==EVERY_NDAYS) {_CUSTOM<<"time,day,"; } else if (_timeAgg==MONTHLY ){_CUSTOM<<"time,month,";} else if (_timeAgg==DAILY ){_CUSTOM<<"time,day,";} else if (_timeAgg==EVERY_TSTEP ){_CUSTOM<<"time,day,hour,";} for (int k=0;k<num_data;k++) { if (_aggstat==AGG_AVERAGE ){_CUSTOM<<"mean,";} else if (_aggstat==AGG_MAXIMUM ){_CUSTOM<<"maximum,";} else if (_aggstat==AGG_MINIMUM ){_CUSTOM<<"minimum,";} else if (_aggstat==AGG_RANGE ){_CUSTOM<<"minimum,maximum,";} else if (_aggstat==AGG_MEDIAN ){_CUSTOM<<"median,";} else if (_aggstat==AGG_95CI ){_CUSTOM<<"5% quantile,95% quantile,";} else if (_aggstat==AGG_QUARTILES){_CUSTOM<<"25% quartile,50% quartile,75% quartile,";} else if (_aggstat==AGG_HISTOGRAM){ for (int bin=0;bin<_nBins;bin++){ _CUSTOM<<_hist_min+bin*(_hist_max-_hist_min)/_nBins<<"-"<<_hist_min+(bin+1)*(_hist_max-_hist_min)/_nBins<<","; } } } _CUSTOM<<endl; } ////////////////////////////////////////////////////////////////// /// \brief Write header info to EnSim file // void CCustomOutput::WriteEnSimFileHeader(const optStruct &Options) { // Write the header _CUSTOM<<"#########################################################################"<<endl; _CUSTOM<<":FileType tb0 ASCII EnSim 1.0"<<endl; _CUSTOM<<"#"<<endl; _CUSTOM<<":Application Raven"<<endl; if(!Options.benchmarking){ _CUSTOM<<":Version "<<Options.version <<endl; _CUSTOM<<":CreationDate "<<GetCurrentTime()<<endl; } _CUSTOM<<"#"<<endl; _CUSTOM<<"#------------------------------------------------------------------------"<<endl; _CUSTOM<<"#"<<endl; // some meta data information describing the contents of this file _CUSTOM<<":RunName "<<Options.run_name <<endl; _CUSTOM<<"#"<<endl; if ((_var == VAR_FORCING_FUNCTION) && (_timeAgg==EVERY_TSTEP)){ _CUSTOM<<":Format PeriodEnding "<<endl; }//period ending else if ((_var == VAR_FROM_FLUX ) && (_timeAgg==EVERY_TSTEP)){ _CUSTOM<<":Format Instantaneous"<<endl; }//snapshot else if ((_var == VAR_TO_FLUX ) && (_timeAgg==EVERY_TSTEP)){ _CUSTOM<<":Format Instantaneous"<<endl; }//snapshot else if ((_var == VAR_BETWEEN_FLUX ) && (_timeAgg==EVERY_TSTEP)){ _CUSTOM<<":Format PeriodEnding"<<endl; }//period ending else if ((_var == VAR_STATE_VAR ) && (_timeAgg==EVERY_TSTEP)){ _CUSTOM<<":Format Instantaneous"<<endl; }//snapshot else { _CUSTOM<<":Format PeriodStarting"<<endl; }//period starting _CUSTOM<<"#"<<endl; _CUSTOM<<"# Custom output meta-data"<<endl; _CUSTOM<<"#"<<endl; _CUSTOM<<":Variable "<<_varName <<endl; _CUSTOM<<":TemporalAggregation "<<_timeAggStr <<endl; _CUSTOM<<":Statistic "<<_statStr <<endl; _CUSTOM<<":SpatialAggregation "<<_spaceAggStr<<endl; _CUSTOM<<"#"<<endl; // Now define the column meta data _CUSTOM<<":ColumnMetaData"<<endl; // First column is a year, month or date(the default) // second column is model time (in days) string col1Name="Date", col1Units="date", col1Type="date"; string colType="float"; // the default, (histogram however is integer) switch(_timeAgg) { case YEARLY: col1Name="Year"; col1Units="years"; col1Type="int"; break; case WATER_YEARLY: col1Name="WaterYear"; col1Units="years"; col1Type="int"; break; case EVERY_NDAYS: col1Name="Date"; col1Units="date"; col1Type="date"; break; case MONTHLY: col1Name="MonthEnd"; col1Units="months"; col1Type="date"; break; default: break; } _CUSTOM<<" :ColumnName "<<col1Name<<" time "; // Build the rest of the column names int dataColumnCount = 0; for (int k=0;k<num_data;k++) { ostrstream curSpaceIdentifier; switch(_spaceAgg) { case BY_HRU: curSpaceIdentifier<<"HRU_" <<pModel->GetHydroUnit(k)->GetID() <<ends; break; case BY_HRU_GROUP: curSpaceIdentifier<<"HRUGroup_" <<pModel->GetHRUGroup(k)->GetName()<<ends; break; case BY_WSHED: curSpaceIdentifier<<"Watershed_"<<"Watershed" <<ends; break; case BY_BASIN: curSpaceIdentifier<<"SubBasin_" <<pModel->GetSubBasin(k)->GetID() <<ends; break; case BY_SELECT_HRUS: curSpaceIdentifier<<"HRU_" <<pModel->GetHRUGroup(kk_only)->GetHRU(k)->GetID() <<ends; break; } string title=curSpaceIdentifier.str(); switch(_aggstat) { case AGG_AVERAGE: _CUSTOM<<title<<"_mean "; dataColumnCount++; break; case AGG_MAXIMUM: _CUSTOM<<title<<"_max "; dataColumnCount++; break; case AGG_MINIMUM: _CUSTOM<<title<<"_min "; dataColumnCount++; break; case AGG_RANGE: _CUSTOM<<title<<"_min "<<title<<"_max "; dataColumnCount+=2; break; case AGG_MEDIAN: _CUSTOM<<title<<"_median "; dataColumnCount++; break; case AGG_95CI: _CUSTOM<<title<<"_5%_quantile "<<title<<"_95%_quantile "; dataColumnCount+=2; break; case AGG_QUARTILES: _CUSTOM<<title<<"_25%_quartile "<<title<<"_50%_quartile "<<title<<"_75%_quartile "; dataColumnCount+=3; break; case AGG_HISTOGRAM: { for (int bin=0;bin<_nBins;bin++) {_CUSTOM<<title<<"_"<<_hist_min+bin*(_hist_max-_hist_min)/_nBins << "-" << _hist_min+(bin+1)*(_hist_max-_hist_min)/_nBins<<" ";} dataColumnCount+=_nBins; _varUnits="count"; colType="int"; } break; } } _CUSTOM<<endl; int colFormat; if ((_var == VAR_FORCING_FUNCTION) && (_timeAgg==EVERY_TSTEP)){ colFormat = -1; }//period ending else if ((_var == VAR_FROM_FLUX ) && (_timeAgg==EVERY_TSTEP)){ colFormat = 0; }//snapshot (cumulative) else if ((_var == VAR_TO_FLUX ) && (_timeAgg==EVERY_TSTEP)){ colFormat = 0; }//snapshot (cumulative) else if ((_var == VAR_BETWEEN_FLUX ) && (_timeAgg==EVERY_TSTEP)){ colFormat = -1; }//period ending else if ((_var == VAR_STATE_VAR ) && (_timeAgg==EVERY_TSTEP)){ colFormat = 0; }//snapshot else { colFormat = 1; }//period starting _CUSTOM<<" :ColumnUnits "<<col1Units<<" days"; for(int i=0;i<dataColumnCount;i++) {_CUSTOM<<" "<<_varUnits;} _CUSTOM<<endl; _CUSTOM<<" :ColumnType "<<col1Type<<" float"; for(int i=0;i<dataColumnCount;i++) {_CUSTOM<<" "<<colType;} _CUSTOM<<endl; _CUSTOM << " :ColumnFormat 0 0"; for(int i=0;i<dataColumnCount;i++) {_CUSTOM<<" "<<colFormat;} _CUSTOM<<endl; _CUSTOM<<":EndColumnMetaData"<<endl; _CUSTOM<<"#"<<endl; _CUSTOM<<":EndHeader"<<endl; } ////////////////////////////////////////////////////////////////// /// \brief Write header info to netCDF file // void CCustomOutput::WriteNetCDFFileHeader(const optStruct &Options) { #ifdef _RVNETCDF_ time_struct tt; // start time structure const int ndims1 = 1; const int ndims2 = 2; int dimids1[ndims1]; // array which will contain all dimension ids for a variable int dimids2[ndims2]; // array which will contain all dimension ids for a variable int time_dimid, varid_time; // dimension ID (holds number of time steps) and variable ID (holds time values) for time int ndata_dimid,varid_data,varid_grps(0); // dimension ID, variable ID for simulated data and group (HRU/SB) info int retval; // error value for NetCDF routines size_t start[1], count[1]; // determines where and how much will be written to NetCDF string tmp,tmp2,tmp3,tmp4; bool cant_support=(_aggstat==AGG_RANGE || _aggstat==AGG_95CI || _aggstat==AGG_QUARTILES || _aggstat==AGG_HISTOGRAM); if(cant_support){ WriteWarning("CCustomOutput::WriteNetCDFFileHeader: cannot support custom aggregation by range/quartile/histogram/95CI with netCDF output",Options.noisy); } // create file and obtain _netcdf_ID _CUSTOM.close(); //because netcdf does the opening/closing retval = nc_create(_filename.c_str(), NC_CLOBBER|NC_NETCDF4, &_netcdf_ID); HandleNetCDFErrors(retval); // ---------------------------------------------------------- // global attributes // ---------------------------------------------------------- WriteNetCDFGlobalAttributes(_netcdf_ID,Options,"Custom Output"); // ---------------------------------------------------------- // time // ---------------------------------------------------------- // (a) Define the DIMENSIONS. NetCDF will hand back an ID for each. retval = nc_def_dim(_netcdf_ID, "time", NC_UNLIMITED, &time_dimid); HandleNetCDFErrors(retval); // (b) Define the time variable. dimids1[0] = time_dimid; retval = nc_def_var(_netcdf_ID, "time", NC_DOUBLE, ndims1,dimids1, &varid_time); HandleNetCDFErrors(retval); // (c) Assign units attributes to the netCDF VARIABLES. // --> converts start day into "days since YYYY-MM-DD HH:MM:SS" char starttime[200]; // start time string in format 'days since YYY-MM-DD HH:MM:SS' JulianConvert( 0.0+Options.timestep,Options.julian_start_day, Options.julian_start_year, Options.calendar, tt); //File is referenced to end of first time step strcpy(starttime, "days since ") ; strcat(starttime, tt.date_string.c_str()) ; strcat(starttime," "); strcat(starttime,DecDaysToHours(tt.julian_day,true).c_str()); if(Options.time_zone!=0) { strcat(starttime,TimeZoneToString(Options.time_zone).c_str()); } retval = nc_put_att_text(_netcdf_ID, varid_time, "units" , strlen(starttime) , starttime); HandleNetCDFErrors(retval); retval = nc_put_att_text(_netcdf_ID, varid_time, "calendar", strlen("gregorian"), "gregorian"); HandleNetCDFErrors(retval); retval = nc_put_att_text(_netcdf_ID, varid_time, "standard_name", strlen("time"), "time"); HandleNetCDFErrors(retval); retval = nc_put_att_text(_netcdf_ID, varid_time, "long_name", strlen("time"), "time"); HandleNetCDFErrors(retval); // ---------------------------------------------------------- // custom data // ---------------------------------------------------------- if (num_data > 0) { // (a) create dimension "ndata" retval = nc_def_dim(_netcdf_ID, "ndata", num_data, &ndata_dimid); HandleNetCDFErrors(retval); // (b) create variable "HRUID" or "SBID" or... string group_name="HRU_ID"; string long_name="ID of HRU"; if (_spaceAgg==BY_HRU ){group_name="HRU_ID"; long_name="ID of HRU";} else if (_spaceAgg==BY_BASIN ){group_name="SBID"; long_name="ID of subbasin";} else if (_spaceAgg==BY_WSHED ){group_name="Watershed"; long_name="entire watershed";} else if (_spaceAgg==BY_HRU_GROUP ){group_name="HRUGroup"; long_name="HRU group name";} else if (_spaceAgg==BY_SELECT_HRUS){group_name="HRU_ID"; long_name="ID of HRU";} dimids1[0] = ndata_dimid; retval = nc_def_var(_netcdf_ID, group_name.c_str(), NC_STRING, ndims1, dimids1, &varid_grps); HandleNetCDFErrors(retval); //(c) set some attributes to variable "HRUID" or "SBID" tmp =long_name; tmp2="timeseries_id"; tmp3="1"; tmp4="basin_name"; retval = nc_put_att_text(_netcdf_ID, varid_grps, "long_name" , tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text(_netcdf_ID, varid_grps, "cf_role" , tmp2.length(),tmp2.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text(_netcdf_ID, varid_grps, "units" , tmp3.length(),tmp3.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text(_netcdf_ID, varid_grps, "coordinates", tmp4.length(),tmp4.c_str()); HandleNetCDFErrors(retval); //(d) create variable "custom_data" which will contain at the end custom data; shape=(tt,num_data) string netCDFtag=_statStr+"_"+_varName; dimids2[0] = time_dimid; dimids2[1] = ndata_dimid; retval = nc_def_var(_netcdf_ID, netCDFtag.c_str(), NC_DOUBLE, ndims2, dimids2, &varid_data); HandleNetCDFErrors(retval); //(f) set some attributes to variable _netCDFtag tmp=_timeAggStr+" "+_statStr+" "+_varName+" "+_spaceAggStr; tmp2=_varUnits; static double fill_val[] = {NETCDF_BLANK_VALUE}; static double miss_val[] = {NETCDF_BLANK_VALUE}; retval = nc_put_att_text (_netcdf_ID, varid_data, "long_name" , tmp.length(), tmp.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_text (_netcdf_ID, varid_data, "units" , tmp2.length(),tmp2.c_str()); HandleNetCDFErrors(retval); retval = nc_put_att_double(_netcdf_ID, varid_data, "_FillValue" , NC_DOUBLE,1, fill_val); HandleNetCDFErrors(retval); retval = nc_put_att_double(_netcdf_ID, varid_data, "missing_value", NC_DOUBLE,1, miss_val); HandleNetCDFErrors(retval); }// end if (num_data>0) // End define mode. This tells netCDF we are done defining metadata. retval = nc_enddef(_netcdf_ID); HandleNetCDFErrors(retval); // write values to NetCDF // write HRU/subbasin/HRU group names to variable "HRUID" or "SBID" or... int k = 0; const char *group_name[1]; // HRU/watershed/basin name for(k=0; k<num_data; k++) { ostrstream TMP; string temp; if (_spaceAgg==BY_HRU ){TMP<<pModel->GetHydroUnit(k)->GetID() <<ends;} else if (_spaceAgg==BY_HRU_GROUP ){TMP<<pModel->GetHRUGroup(k)->GetName()<<ends;} else if (_spaceAgg==BY_WSHED ){TMP<<"Watershed" <<ends;} else if (_spaceAgg==BY_BASIN ){TMP<<pModel->GetSubBasin(k)->GetID() <<ends;} else if (_spaceAgg==BY_SELECT_HRUS){TMP<<pModel->GetHRUGroup(kk_only)->GetHRU(k)->GetID()<<ends;} temp=TMP.str(); group_name[0]=temp.c_str(); start[0]=k; count[0]=1; retval = nc_put_vara_string(_netcdf_ID,varid_grps,start,count,&group_name[0]); HandleNetCDFErrors(retval); } if(Options.noisy){ cout<<"netCDF file header written for "<<_filename<<endl; } #endif // end compilation if NetCDF library is available } ////////////////////////////////////////////////////////////////// /// \brief Calculates quartiles of passed 1D data array /// \note values[] array (size 'size') must be pre-sorted /// \author code developed by Ayman Khedr, University of Waterloo 3A, 2011 /// \param *values [in] Array of values whose quartiles are to be found /// \param size [in] Size of values[] array /// \param &Q1 [out] First quartile value /// \param &Q2 [out] Second quartile value /// \param &Q3 [out] Third Quartile value // void GetQuartiles(const double *values, const int size, double &Q1, double &Q2, double &Q3) { if (size%2==0) { if ((size/2)%2==0) { // since values is sorted index value quartile values associated with quartiles of index Q1=(values[(int) ceil((double)(size-1)*0.25)]+values[(int)floor((double)(size-1)*0.25)])/2; } else { Q1=values[(int)floor((double)(size-1)*0.25)]; } Q2=(values[(int)ceil((double)(size-1)*0.5)]+values[(int)floor((double)(size-1)*0.5)])/2; if ((size/2)%2==0) { Q3=(values[(int)ceil((double)(size-1)*0.75)]+values[(int)floor((double)(size-2)*0.75)])/2; } else{ Q3=values[(int)ceil((double)(size-1)*0.75)]; } } else { if ((int)floor((double)(size-1)/2)%2 == 0) { Q1=values[(int)floor((double)(size-1)*0.25)]; } else { Q1=(values[(int)ceil((double)(size-1)/4)]+values[(int)floor((double)(size-1)/4)])/2; } Q2=values[((size-1)/2)]; if ((int)floor((double)(size-1)/2)%2 == 0) { Q3=(values[(int)ceil((double)(size-1)*0.75)]+values[(int)floor((double)(size-2)*0.75)])/2; } else { Q3=values[(int)ceil((double)(size-1)*0.75)]; } } } ////////////////////////////////////////////////////////////////// /// \brief Write custom output to file by querying the model and calculating diagnostics /// \brief now handles .csv, .nc, and .tb0 (Ensim) formats /// \param &tt [in] Current model time /// \param &Options [in] Global model options information // void CCustomOutput::WriteCustomOutput(const time_struct &tt, const optStruct &Options) { //each custom output gets values of vals data[nHRUs] (max size) double val=0; double dday;//,jul_day; int dmon,dyr; string thisdate, thishour, yesterday; bool reset; double t=tt.model_time; double time_shift=Options.julian_start_day-floor(Options.julian_start_day); time_struct yest; JulianConvert(t-time_shift-1.0,Options.julian_start_day,Options.julian_start_year,Options.calendar,yest); //get 00:00 AM previous day, yest yesterday=yest.date_string; thisdate=tt.date_string; dday =tt.day_of_month; dmon =tt.month; dyr =tt.year; thishour =DecDaysToHours(tt.julian_day); if (t==0){return;} //initial conditions should not be printed to custom output, only period data. double *output=NULL; if(Options.output_format==OUTPUT_NETCDF){output=new double[num_data]; } //Check to see if it is time to write to file //------------------------------------------------------------------------------ reset=false; if ((_timeAgg==YEARLY) && (dday==1) && (dmon==1)) {reset=true;}//Jan 1 - print preceding year else if ((_timeAgg==MONTHLY) && (dday==1)) {reset=true;}//first day of month - print preceding month info else if ((_timeAgg==DAILY) && (fabs(floor(t+time_shift+TIME_CORRECTION)-(t+time_shift)) <0.5*Options.timestep)) {reset=true;}//start of day - print preceding day else if (_timeAgg==EVERY_TSTEP) {reset=true;}//every timestep else if((_timeAgg==EVERY_NDAYS) && (fabs(ffmod(t,Options.custom_interval)) <=0.5*Options.timestep))//every N days print preceding N days {reset=true;} else if ((_timeAgg==WATER_YEARLY) && (dday==1) && (dmon==Options.wateryr_mo)) {reset=true;}//Oct 1 - print preceding year //cout <<t <<" ->"<<fabs(floor(t)-t)<<" "<<(fabs(floor(t)-t) <0.5*Options.timestep)<<endl; if (reset) { if(Options.output_format==OUTPUT_STANDARD)//================================================================= { if (_timeAgg==YEARLY ){_CUSTOM<<t<<","<<yest.year<<",";} else if (_timeAgg==MONTHLY ){_CUSTOM<<t<<","<<yesterday.substr(0,7)<<",";}//trims day, e.g., just return 2011-02, else if (_timeAgg==DAILY ){_CUSTOM<<t<<","<<yesterday<<",";} else if (_timeAgg==EVERY_TSTEP ){_CUSTOM<<t<<","<<thisdate<<","<<thishour<<","; }//period ending for forcing data else if (_timeAgg==WATER_YEARLY){_CUSTOM<<t<<","<<yest.year<<"-"<<yest.year+1<<",";} else if (_timeAgg==EVERY_NDAYS ){ _CUSTOM<<t<<","<<yesterday<<","; } } else if(Options.output_format==OUTPUT_ENSIM)//=============================================================== { switch(_timeAgg) { case YEARLY: _CUSTOM<<yest.year<<" "<<t<<" "; break; case MONTHLY: _CUSTOM<<yest.year<<"-"<<yest.month<<"-"<<yest.day_of_month<<" "<<t<<" "; break; case DAILY: _CUSTOM<<yest.year<<"-"<<yest.month<<"-"<<yest.day_of_month<<" "<<t<<" "; break; case EVERY_NDAYS: _CUSTOM<<yest.year<<"-"<<yest.month<<"-"<<yest.day_of_month<<" "<<t<<" "; break; case EVERY_TSTEP: { char dQuote = '"'; _CUSTOM<<dQuote<<tt.date_string<<" "<<DecDaysToHours(tt.julian_day)<<dQuote<<" "<<t<<" "; //period ending for forcings } break; case WATER_YEARLY: _CUSTOM<<t<<","<<yest.year<<"-"<<yest.year+1<<","; break; } } else if(Options.output_format==OUTPUT_NETCDF)//============================================================= { #ifdef _RVNETCDF_ int retval,time_id; size_t start1[1], count1[1]; // determines where and how much will be written to NetCDF; 1D variable (time) double current_time[1]; // current time in days since start of interval if (_timeAgg==YEARLY ){current_time[0]=yest.model_time-yest.julian_day;} else if (_timeAgg==MONTHLY ){current_time[0]=yest.model_time-yest.day_of_month;} else if (_timeAgg==DAILY ){current_time[0]=yest.model_time;} else if (_timeAgg==EVERY_TSTEP ){current_time[0]=tt.model_time-Options.timestep; } else if (_timeAgg==EVERY_NDAYS ){current_time[0]=yest.model_time-Options.custom_interval*floor(yest.model_time/Options.custom_interval); } else if (_timeAgg==WATER_YEARLY){ double days_to_first_of_month=0; for (int m=0; m<Options.wateryr_mo;m++){days_to_first_of_month+=DAYS_PER_MONTH[m];} if (IsLeapYear(yest.year,Options.calendar) && (Options.wateryr_mo>2)){days_to_first_of_month+=1;} current_time[0]=yest.model_time-yest.julian_day+days_to_first_of_month; } //start1[0] = int(round(current_time[0]/Options.timestep)); // element of NetCDF array that will be written start1[0]=_time_index; count1[0] = 1; // writes exactly one time step retval = nc_inq_varid (_netcdf_ID, "time", &time_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_netcdf_ID, time_id, start1, count1, &current_time[0]); HandleNetCDFErrors(retval); #endif } } bool is_concentration=false; is_concentration = (_var == VAR_STATE_VAR) && (pModel->GetStateVarType(_svind)==CONSTITUENT); //Sift through HRUs, BASINs or watershed, updating aggregate statistics //-------------------------------------------------------------------------- //numdata=1 if BY_WATERSHED, =nSubBasins if BY_BASIN, =nHRUs if BY_HRU... for (int k=0;k<num_data;k++) { //---access current diagnostic variable (from end of timestep)------------ if (is_concentration){ int m = pModel->GetStateVarLayer(_svind); int i_stor=pModel->GetTransportModel()->GetWaterStorIndexFromLayer(m); double conv=(MM_PER_METER/LITER_PER_M3); val=-9999; if (_spaceAgg==BY_HRU ){val=pModel->GetHydroUnit(k)->GetStateVarValue(_svind)/pModel->GetHydroUnit(k)->GetStateVarValue(i_stor)*conv;} else { ExitGracefully("CustomOutput: cannot currently generate basin,watershed, or hru group based aggregate constituent concentrations",STUB); } /*else if (_spaceAgg==BY_BASIN ){val=-9999;}// \todo [funct] pTransModel->GetSubBasinAvgConc(k,_svind) else if (_spaceAgg==BY_WSHED ){val=-9999;} else if (_spaceAgg==BY_HRU_GROUP ){val=-9999;} else if (_spaceAgg==BY_SELECT_HRUS){val=-9999;}*/ } else if (_var==VAR_STATE_VAR){ if (_spaceAgg==BY_HRU ){val=pModel->GetHydroUnit(k)->GetStateVarValue(_svind);} else if (_spaceAgg==BY_BASIN ){val=pModel->GetSubBasin (k)->GetAvgStateVar (_svind);} else if (_spaceAgg==BY_WSHED ){val=pModel-> GetAvgStateVar (_svind);} else if (_spaceAgg==BY_HRU_GROUP ){val=pModel->GetHRUGroup (k)->GetAvgStateVar (_svind);} else if (_spaceAgg==BY_SELECT_HRUS){val=pModel->GetHRUGroup (kk_only)->GetHRU(k)->GetStateVarValue(_svind);} } else if (_var==VAR_FORCING_FUNCTION){ if (_spaceAgg==BY_HRU ){val=pModel->GetHydroUnit(k)->GetForcing (_force_str);} else if (_spaceAgg==BY_BASIN ){val=pModel->GetSubBasin (k)->GetAvgForcing(_force_str);} else if (_spaceAgg==BY_WSHED ){val=pModel-> GetAvgForcing(_force_str);} else if (_spaceAgg==BY_HRU_GROUP ){val=pModel->GetHRUGroup (k)->GetAvgForcing(_force_str);} else if (_spaceAgg==BY_SELECT_HRUS){val=pModel->GetHRUGroup (kk_only)->GetHRU(k)->GetForcing(_force_str);} } else if (_var == VAR_TO_FLUX){ if (_spaceAgg==BY_HRU ){val=pModel->GetHydroUnit(k)->GetCumulFlux (_svind,true);} else if (_spaceAgg==BY_BASIN ){val=pModel->GetSubBasin (k)->GetAvgCumulFlux(_svind,true);} else if (_spaceAgg==BY_WSHED ){val=pModel-> GetAvgCumulFlux(_svind,true);} else if (_spaceAgg==BY_HRU_GROUP ){val=pModel->GetHRUGroup (k)->GetAvgCumulFlux(_svind,true);} else if (_spaceAgg==BY_SELECT_HRUS){val=pModel->GetHRUGroup (kk_only)->GetHRU(k)->GetCumulFlux(_svind,true);} } else if (_var == VAR_FROM_FLUX){ if (_spaceAgg==BY_HRU ){val=pModel->GetHydroUnit(k)->GetCumulFlux (_svind,false);} else if (_spaceAgg==BY_BASIN ){val=pModel->GetSubBasin (k)->GetAvgCumulFlux(_svind,false);} else if (_spaceAgg==BY_WSHED ){val=pModel-> GetAvgCumulFlux(_svind,false);} else if (_spaceAgg==BY_HRU_GROUP ){val=pModel->GetHRUGroup (k)->GetAvgCumulFlux(_svind,false);} else if (_spaceAgg==BY_SELECT_HRUS){val=pModel->GetHRUGroup (kk_only)->GetHRU(k)->GetCumulFlux(_svind,false);} } else if (_var == VAR_BETWEEN_FLUX){ if (_spaceAgg==BY_HRU ){val=pModel->GetHydroUnit(k)->GetCumulFluxBet(_svind,_svind2);} else if (_spaceAgg==BY_BASIN ){val=pModel->GetSubBasin (k)->GetAvgCumulFluxBet(_svind,_svind2);} else if (_spaceAgg==BY_WSHED ){val=pModel-> GetAvgCumulFluxBet(_svind,_svind2);} else if (_spaceAgg==BY_HRU_GROUP ){val=pModel->GetHRUGroup (k)->GetAvgCumulFluxBet(_svind,_svind2);} else if (_spaceAgg==BY_SELECT_HRUS){val=pModel->GetHRUGroup (kk_only)->GetHRU(k)->GetCumulFluxBet(_svind,_svind2);} } if (k==0){count++;}//increment number of data items stored //---Update diagnostics-------------------------------------------------- //----------------------------------------------------------------------- if (_aggstat==AGG_AVERAGE) { // \todo[funct] - should handle pointwise variables (e.g., state vars) differently from periodwise variables (e.g., forcings) if (_var == VAR_STATE_VAR){ data[k][0]=(double)(count-1)/(double)(count)*data[k][0]+val/count; //NOT CURRENTLY STRICTLY VALID } else { data[k][0]=(double)(count-1)/(double)(count)*data[k][0]+val/count; } } else if (_aggstat==AGG_MAXIMUM) { upperswap(data[k][0],val); } else if (_aggstat==AGG_MINIMUM) { lowerswap(data[k][0],val); } else if (_aggstat==AGG_RANGE) { lowerswap(data[k][0],val); upperswap(data[k][1],val); } else if ((_aggstat==AGG_MEDIAN) || (_aggstat==AGG_QUARTILES) || (_aggstat==AGG_95CI) || (_aggstat==AGG_HISTOGRAM)) { //populate data data [k][count-1] = val; } else { data[k][0]=val;//most recent value } //---Write output to file and reinitialize statistics, if needed--------- //----------------------------------------------------------------------- if (reset) { if((Options.output_format==OUTPUT_STANDARD) || (Options.output_format==OUTPUT_ENSIM)) { string sep=","; if(Options.output_format==OUTPUT_ENSIM){ sep=" "; }//space separated //write to .csv or .tb0 file if (_aggstat==AGG_AVERAGE){ _CUSTOM<<FormatDouble(data[k][0]) <<sep; } else if(_aggstat==AGG_MAXIMUM){ _CUSTOM<<FormatDouble(data[k][0]) <<sep; } else if(_aggstat==AGG_MINIMUM){ _CUSTOM<<FormatDouble(data[k][0]) <<sep; } else if(_aggstat==AGG_RANGE ){ _CUSTOM<<FormatDouble(data[k][0]) <<sep<<FormatDouble(data[k][1])<<sep; } else if(_aggstat==AGG_MEDIAN) { double Q1,Q2,Q3; quickSort(data[k],0,count-1); GetQuartiles(data[k],count,Q1,Q2,Q3); _CUSTOM<<FormatDouble(Q2)<<sep; } else if(_aggstat==AGG_QUARTILES) //find lower quartile, median, then upper quartile { double Q1,Q2,Q3; quickSort(data[k],0,count-1); GetQuartiles(data[k],count,Q1,Q2,Q3); _CUSTOM<<FormatDouble(Q1)<<sep<<FormatDouble(Q2)<<sep<<FormatDouble(Q3)<<sep; } else if(_aggstat==AGG_95CI) { quickSort(data[k],0,count-1);//take floor and ceiling of lower and upper intervals to be conservative _CUSTOM << FormatDouble(data[k][(int)floor((double)(count-1)*0.025)])<<sep; _CUSTOM << FormatDouble(data[k][(int)ceil((double)(count-1)*0.975)])<<sep; } else if(_aggstat==AGG_HISTOGRAM) { quickSort(data[k],0,count-1); double binsize = (_hist_max-_hist_min)/_nBins; int bincount[MAX_HISTOGRAM_BINS]; for(int bin=0;bin<_nBins;bin++){ bincount[bin]=0; } for(int a=0;a<count;a++) { for(int bin=0;bin<_nBins;bin++){ if((data[k][a]>=(_hist_min+bin*binsize)) && (data[k][a]<(_hist_min+(bin+1)*binsize))){ bincount[bin]++; } } } for(int bin=0;bin<_nBins;bin++){ _CUSTOM<<bincount[bin]<<sep; } } } else if(Options.output_format==OUTPUT_NETCDF) { #ifdef _RVNETCDF_ // Collect Data double out=0.0; if (_aggstat==AGG_AVERAGE){ out=data[k][0]; } else if(_aggstat==AGG_MAXIMUM){ out=data[k][0]; } else if(_aggstat==AGG_MINIMUM){ out=data[k][0]; } else if(_aggstat==AGG_MEDIAN) { double Q1,Q2,Q3; quickSort(data[k],0,count-1); GetQuartiles(data[k],count,Q1,Q2,Q3); out=Q2; } output[k]=out; #endif } //-reset to initial conditions //----------------------------------------------------------------------- if (_aggstat==AGG_AVERAGE){data[k][0]= 0.0;} else if (_aggstat==AGG_MAXIMUM){data[k][0]=-ALMOST_INF;} else if (_aggstat==AGG_MINIMUM){data[k][0]= ALMOST_INF;} else if (_aggstat==AGG_RANGE ) { data[k][0]= ALMOST_INF; data[k][1]=-ALMOST_INF; } else if ((_aggstat==AGG_MEDIAN) || (_aggstat==AGG_QUARTILES) || (_aggstat==AGG_95CI) || (_aggstat==AGG_HISTOGRAM)) { for(int j=0;j<num_store;j++){ data[k][j]=0; } } //...more stats here if (k==num_data-1){count=0;}//don't reboot count until last HRU/basin is done }//end if (reset) }//end for (k=0;... if (reset){ if((Options.output_format==OUTPUT_STANDARD) || (Options.output_format==OUTPUT_ENSIM)) { _CUSTOM<<endl;//valid for ensim or .csv format } else if (Options.output_format==OUTPUT_NETCDF) { #ifdef _RVNETCDF_ // Write to NetCDF (done entire vector of data at once) if (num_data > 0) { int retval,data_id; size_t start2[2], count2[2]; start2[0]=_time_index; count2[0] = 1; // writes exactly one time interval (yr/mo/day/hr) start2[1] = 0; count2[1] = num_data; // writes exactly num_data elements string netCDFtag=_statStr+"_"+_varName; retval = nc_inq_varid (_netcdf_ID, netCDFtag.c_str(), &data_id); HandleNetCDFErrors(retval); retval = nc_put_vara_double(_netcdf_ID, data_id, start2, count2, &output[0]); HandleNetCDFErrors(retval); } delete [] output; #endif } _time_index++; } } ////////////////////////////////////////////////////////////////// /// \brief Closes output stream after all information written to file // void CCustomOutput::CloseFiles() { if (_CUSTOM.is_open()){_CUSTOM.close();} }
45.517964
160
0.590256
[ "object", "shape", "vector", "model" ]
0f702271941ef6130bb1e1ce195e34a3d1aa3e98
9,588
cc
C++
src/simd/simd_bits_range_ref.test.cc
dstrain115/Stim
82a161741c05d637fe16ea20b1d99a48b4ca4750
[ "Apache-2.0" ]
null
null
null
src/simd/simd_bits_range_ref.test.cc
dstrain115/Stim
82a161741c05d637fe16ea20b1d99a48b4ca4750
[ "Apache-2.0" ]
null
null
null
src/simd/simd_bits_range_ref.test.cc
dstrain115/Stim
82a161741c05d637fe16ea20b1d99a48b4ca4750
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "simd_bits_range_ref.h" #include <gtest/gtest.h> #include "../test_util.test.h" using namespace stim_internal; TEST(simd_bits_range_ref, construct) { alignas(64) uint64_t data[16]{}; simd_bits_range_ref ref((simd_word *)data, sizeof(data) / sizeof(simd_word)); ASSERT_EQ(ref.ptr_simd, (simd_word *)&data[0]); ASSERT_EQ(ref.num_simd_words, 16 * sizeof(uint64_t) / sizeof(simd_word)); ASSERT_EQ(ref.num_bits_padded(), 1024); ASSERT_EQ(ref.num_u8_padded(), 128); ASSERT_EQ(ref.num_u16_padded(), 64); ASSERT_EQ(ref.num_u32_padded(), 32); ASSERT_EQ(ref.num_u64_padded(), 16); } TEST(simd_bits_range_ref, aliased_editing_and_bit_refs) { alignas(64) uint64_t data[16]{}; auto c = (char *)&data; simd_bits_range_ref ref((simd_word *)data, sizeof(data) / sizeof(simd_word)); const simd_bits_range_ref cref((simd_word *)data, sizeof(data) / sizeof(simd_word)); ASSERT_EQ(c[0], 0); ASSERT_EQ(c[13], 0); ref[5] = true; ASSERT_EQ(c[0], 32); ref[0] = true; ASSERT_EQ(c[0], 33); ref[100] = true; ASSERT_EQ(ref[100], true); ASSERT_EQ(c[12], 16); c[12] = 0; ASSERT_EQ(ref[100], false); ASSERT_EQ(cref[100], ref[100]); } TEST(simd_bits_range_ref, str) { alignas(64) uint64_t data[8]{}; simd_bits_range_ref ref((simd_word *)data, sizeof(data) / sizeof(simd_word)); ASSERT_EQ( ref.str(), "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________"); ref[5] = 1; ASSERT_EQ( ref.str(), "_____1__________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________" "________________________________________________________________"); } TEST(simd_bits_range_ref, randomize) { alignas(64) uint64_t data[16]{}; simd_bits_range_ref ref((simd_word *)data, sizeof(data) / sizeof(simd_word)); ref.randomize(64 + 57, SHARED_TEST_RNG()); uint64_t mask = (1ULL << 57) - 1; // Randomized. ASSERT_NE(ref.u64[0], 0); ASSERT_NE(ref.u64[0], SIZE_MAX); ASSERT_NE(ref.u64[1] & mask, 0); ASSERT_NE(ref.u64[1] & mask, 0); // Not touched. ASSERT_EQ(ref.u64[1] & ~mask, 0); ASSERT_EQ(ref.u64[2], 0); ASSERT_EQ(ref.u64[3], 0); for (size_t k = 0; k < ref.num_u64_padded(); k++) { ref.u64[k] = UINT64_MAX; } ref.randomize(64 + 57, SHARED_TEST_RNG()); // Randomized. ASSERT_NE(ref.u64[0], 0); ASSERT_NE(ref.u64[0], SIZE_MAX); ASSERT_NE(ref.u64[1] & mask, 0); ASSERT_NE(ref.u64[1] & mask, 0); // Not touched. ASSERT_EQ(ref.u64[1] & ~mask, UINT64_MAX & ~mask); ASSERT_EQ(ref.u64[2], UINT64_MAX); ASSERT_EQ(ref.u64[3], UINT64_MAX); } TEST(simd_bits_range_ref, xor_assignment) { alignas(64) uint64_t data[24]{}; simd_bits_range_ref m0((simd_word *)&data[0], sizeof(data) / sizeof(simd_word) / 3); simd_bits_range_ref m1((simd_word *)&data[8], sizeof(data) / sizeof(simd_word) / 3); simd_bits_range_ref m2((simd_word *)&data[16], sizeof(data) / sizeof(simd_word) / 3); m0.randomize(512, SHARED_TEST_RNG()); m1.randomize(512, SHARED_TEST_RNG()); ASSERT_NE(m0, m1); ASSERT_NE(m0, m2); m2 ^= m0; ASSERT_EQ(m0, m2); m2 ^= m1; for (size_t k = 0; k < m0.num_u64_padded(); k++) { ASSERT_EQ(m2.u64[k], m0.u64[k] ^ m1.u64[k]); } } TEST(simd_bits_range_ref, assignment) { alignas(64) uint64_t data[16]{}; simd_bits_range_ref m0((simd_word *)&data[0], sizeof(data) / sizeof(simd_word) / 2); simd_bits_range_ref m1((simd_word *)&data[8], sizeof(data) / sizeof(simd_word) / 2); m0.randomize(512, SHARED_TEST_RNG()); m1.randomize(512, SHARED_TEST_RNG()); auto old_m1 = m1.u64[0]; ASSERT_NE(m0, m1); m0 = m1; ASSERT_EQ(m0, m1); ASSERT_EQ(m0.u64[0], old_m1); ASSERT_EQ(m1.u64[0], old_m1); } TEST(simd_bits_range_ref, equality) { alignas(64) uint64_t data[32]{}; simd_bits_range_ref m0((simd_word *)&data[0], sizeof(data) / sizeof(simd_word) / 4); simd_bits_range_ref m1((simd_word *)&data[8], sizeof(data) / sizeof(simd_word) / 4); simd_bits_range_ref m4((simd_word *)&data[16], sizeof(data) / sizeof(simd_word) / 2); ASSERT_TRUE(m0 == m1); ASSERT_FALSE(m0 != m1); ASSERT_FALSE(m0 == m4); ASSERT_TRUE(m0 != m4); m1[505] = 1; ASSERT_FALSE(m0 == m1); ASSERT_TRUE(m0 != m1); m0[505] = 1; ASSERT_TRUE(m0 == m1); ASSERT_FALSE(m0 != m1); } TEST(simd_bits_range_ref, swap_with) { alignas(64) uint64_t data[32]{}; simd_bits_range_ref m0((simd_word *)&data[0], sizeof(data) / sizeof(simd_word) / 4); simd_bits_range_ref m1((simd_word *)&data[8], sizeof(data) / sizeof(simd_word) / 4); simd_bits_range_ref m2((simd_word *)&data[16], sizeof(data) / sizeof(simd_word) / 4); simd_bits_range_ref m3((simd_word *)&data[24], sizeof(data) / sizeof(simd_word) / 4); m0.randomize(512, SHARED_TEST_RNG()); m1.randomize(512, SHARED_TEST_RNG()); m2 = m0; m3 = m1; ASSERT_EQ(m0, m2); ASSERT_EQ(m1, m3); m0.swap_with(m1); ASSERT_EQ(m0, m3); ASSERT_EQ(m1, m2); } TEST(simd_bits_range_ref, clear) { alignas(64) uint64_t data[8]{}; simd_bits_range_ref m0((simd_word *)&data[0], sizeof(data) / sizeof(simd_word)); m0.randomize(512, SHARED_TEST_RNG()); ASSERT_TRUE(m0.not_zero()); m0.clear(); ASSERT_TRUE(!m0.not_zero()); } TEST(simd_bits_range_ref, not_zero256) { alignas(64) uint64_t data[8]{}; simd_bits_range_ref m0((simd_word *)&data[0], sizeof(data) / sizeof(simd_word)); ASSERT_FALSE(m0.not_zero()); m0[5] = true; ASSERT_TRUE(m0.not_zero()); m0[511] = true; ASSERT_TRUE(m0.not_zero()); m0[5] = false; ASSERT_TRUE(m0.not_zero()); } TEST(simd_bits_range_ref, word_range_ref) { simd_word d[sizeof(uint64_t) * 16 / sizeof(simd_word)]{}; simd_bits_range_ref ref(d, sizeof(d) / sizeof(simd_word)); const simd_bits_range_ref cref(d, sizeof(d) / sizeof(simd_word)); auto r1 = ref.word_range_ref(1, 2); auto r2 = ref.word_range_ref(2, 2); r1[1] = true; ASSERT_TRUE(!r2.not_zero()); auto k = sizeof(simd_word) * 8 + 1; ASSERT_EQ(r1[k], false); r2[1] = true; ASSERT_EQ(r1[k], true); ASSERT_EQ(cref.word_range_ref(1, 2)[k], true); } TEST(simd_bits_range_ref, for_each_set_bit) { simd_bits data(256); simd_bits_range_ref ref(data); ref[5] = true; ref[101] = true; std::vector<size_t> hits; ref.for_each_set_bit([&](size_t k) { hits.push_back(k); }); ASSERT_EQ(hits, (std::vector<size_t>{5, 101})); } TEST(simd_bits_range_ref, truncated_overwrite_from) { simd_bits dat = simd_bits::random(1024, SHARED_TEST_RNG()); simd_bits mut = simd_bits::random(1024, SHARED_TEST_RNG()); simd_bits old = mut; simd_bits_range_ref(mut).truncated_overwrite_from(dat, 455); for (size_t k = 0; k < 1024; k++) { ASSERT_EQ(mut[k], k < 455 ? dat[k] : old[k]) << k; } } TEST(simd_bits_range_ref, popcnt) { simd_bits data(1024); simd_bits_range_ref ref(data); ASSERT_EQ(ref.popcnt(), 0); data[101] = 1; ASSERT_EQ(ref.popcnt(), 1); data[0] = 1; ASSERT_EQ(ref.popcnt(), 2); data.u64[8] = 0xFFFFFFFFFFFFFFFFULL; ASSERT_EQ(ref.popcnt(), 66); } TEST(simd_bits_range_ref, intersects) { simd_bits data(1024); simd_bits other(512); simd_bits_range_ref ref(data); ASSERT_EQ(data.intersects(other), false); ASSERT_EQ(ref.intersects(other), false); other[511] = true; ASSERT_EQ(data.intersects(other), false); ASSERT_EQ(ref.intersects(other), false); data[513] = true; ASSERT_EQ(data.intersects(other), false); ASSERT_EQ(ref.intersects(other), false); data[511] = true; ASSERT_EQ(data.intersects(other), true); ASSERT_EQ(ref.intersects(other), true); data[101] = true; ASSERT_EQ(data.intersects(other), true); ASSERT_EQ(ref.intersects(other), true); other[101] = true; ASSERT_EQ(data.intersects(other), true); ASSERT_EQ(ref.intersects(other), true); }
34.992701
89
0.674489
[ "vector" ]
0f72277593f9529a401e195d80959f3eb70cdeb4
250,541
cxx
C++
PWGHF/vertexingHF/AliAnalysisTaskSELc2V0bachelor.cxx
peckalec/AliPhysics
b5661f0dd0bb24534397615b26260d35f0809830
[ "BSD-3-Clause" ]
1
2019-10-03T15:11:04.000Z
2019-10-03T15:11:04.000Z
PWGHF/vertexingHF/AliAnalysisTaskSELc2V0bachelor.cxx
abarreirALICE/AliPhysics
b2cd6e45bb7fc1b76fec02fe20c70a828a30cb6d
[ "BSD-3-Clause" ]
null
null
null
PWGHF/vertexingHF/AliAnalysisTaskSELc2V0bachelor.cxx
abarreirALICE/AliPhysics
b2cd6e45bb7fc1b76fec02fe20c70a828a30cb6d
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appeuear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // // // Base class for Lc2V0 Analysis // // // The Lc spectra study is done 2D histograms: // cascade_invariantMass VS cascade_pT // // Cuts have been centralized in AliRDHFCutsLctoV0 class // //------------------------------------------------------------------------- // // Authors: A.De Caro(a,b), P. Pagano(b) // (a) Centro 'E.Fermi' - Roma // (b) INFN and University of Salerno // // Contatcs: decaro@sa.infn.it // paola.pagano@sa.infn.it //------------------------------------------------------------------------- #include <TSystem.h> #include <TParticle.h> #include <TParticlePDG.h> #include <TH1F.h> #include <TH2F.h> #include <TH3F.h> #include <THnSparse.h> #include <TTree.h> #include "TROOT.h" #include <TDatabasePDG.h> #include <AliAnalysisDataSlot.h> #include <AliAnalysisDataContainer.h> #include "AliMCEvent.h" #include "AliAnalysisManager.h" #include "AliAODMCHeader.h" #include "AliAODHandler.h" #include "AliLog.h" #include "AliExternalTrackParam.h" #include "AliAODVertex.h" #include "AliAODRecoDecay.h" #include "AliAODRecoDecayHF.h" #include "AliAODRecoCascadeHF.h" #include "AliAnalysisVertexingHF.h" #include "AliESDtrack.h" #include "AliAODTrack.h" #include "AliAODv0.h" #include "AliAODMCParticle.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisTaskSELc2V0bachelor.h" #include "AliNormalizationCounter.h" #include "AliAODPidHF.h" #include "AliInputEventHandler.h" #include "AliESDtrackCuts.h" #include "AliNeutralTrackParam.h" #include "AliVertexingHFUtils.h" using std::cout; using std::endl; /// \cond CLASSIMP ClassImp(AliAnalysisTaskSELc2V0bachelor); /// \endcond //__________________________________________________________________________ AliAnalysisTaskSELc2V0bachelor::AliAnalysisTaskSELc2V0bachelor() : AliAnalysisTaskSE(), fUseMCInfo(kFALSE), fOutput(0), fOutputAll(0), fOutputPIDBach(0), fCEvents(0), fEventCounter(0), fCounter(0), fAnalCuts(0), fUseOnTheFlyV0(kFALSE), fAODProtection(1), fIsEventSelected(kFALSE), fWriteVariableTree(kFALSE), fVariablesTree(0), fCandidateVariables(), fVtx1(0), fBzkG(0), fAdditionalChecks(kFALSE), fFillSubSampleHist(kFALSE), fTrackRotation(kFALSE), fOutputPIDBachTR(0), fMinAngleForRot(5*TMath::Pi()/6), fMaxAngleForRot(7*TMath::Pi()/6), fMinMass(0), fMaxMass(0), fNRotations(9), fPtMinToFillTheTree(0.), fPtMaxToFillTheTree(999.), fUseTPCPIDtoFillTree(kFALSE), fSign(2), fCheckOrigin(kFALSE), fReconstructSecVtx(kFALSE), fDoSingleAnalysisForSystK0SP(0), fGenerateBGEventFromTracks(0), fNumberOfEventsForMixing (10), fNzVtxBins (0), fNCentBins (0), fNOfPools(1), fPoolIndex(-9999), fNextResVec(), fReservoirsReady(), fReservoirP() { // /// Default ctor // Double_t mLcPDG = TDatabasePDG::Instance()->GetParticle(4122)->Mass(); fMinMass=mLcPDG-0.250; fMaxMass=mLcPDG+0.250; for(Int_t i=0;i<100;i++){ fZvtxBins[i] = 9999; fCentBins[i] = 9999; } } //___________________________________________________________________________ AliAnalysisTaskSELc2V0bachelor::AliAnalysisTaskSELc2V0bachelor(const Char_t* name, AliRDHFCutsLctoV0* analCuts, Bool_t useOnTheFly, Bool_t writeVariableTree, Bool_t additionalChecks, Bool_t trackRotation, Bool_t useTPCpid, Char_t sign, Bool_t origin) : AliAnalysisTaskSE(name), fUseMCInfo(kFALSE), fOutput(0), fOutputAll(0), fOutputPIDBach(0), fCEvents(0), fEventCounter(0), fCounter(0), fAnalCuts(analCuts), fUseOnTheFlyV0(useOnTheFly), fAODProtection(1), fIsEventSelected(kFALSE), fWriteVariableTree(writeVariableTree), fVariablesTree(0), fCandidateVariables(), fVtx1(0), fBzkG(0), fAdditionalChecks(additionalChecks), fFillSubSampleHist(kFALSE), fTrackRotation(trackRotation), fOutputPIDBachTR(0), fMinAngleForRot(5*TMath::Pi()/6), fMaxAngleForRot(7*TMath::Pi()/6), fMinMass(0), fMaxMass(0), fNRotations(9), fPtMinToFillTheTree(0.), fPtMaxToFillTheTree(999.), fUseTPCPIDtoFillTree(useTPCpid), fSign(sign), fCheckOrigin(origin), fReconstructSecVtx(kFALSE), fDoSingleAnalysisForSystK0SP(0), fGenerateBGEventFromTracks(0), fNumberOfEventsForMixing (10), fNzVtxBins (0), fNCentBins (0), fNOfPools(1), fPoolIndex(-9999), fNextResVec(), fReservoirsReady(), fReservoirP() { // /// Constructor. Initialization of Inputs and Outputs // Info("AliAnalysisTaskSELc2V0bachelor","Calling Constructor"); if (fWriteVariableTree && fTrackRotation) { AliInfo(Form("You cannot initialize fWriteVariableTree=%d and fTrackRotation=%d => fTrackRotation=0",fWriteVariableTree,fTrackRotation)); fTrackRotation=kFALSE; } for(Int_t i=0;i<100;i++){ fZvtxBins[i] = -9999; fCentBins[i] = -9999; } Double_t mLcPDG = TDatabasePDG::Instance()->GetParticle(4122)->Mass(); fMinMass=mLcPDG-0.250; fMaxMass=mLcPDG+0.250; DefineOutput(1,TList::Class()); //conters DefineOutput(2,AliNormalizationCounter::Class()); DefineOutput(3,AliRDHFCutsLctoV0::Class()); if (!writeVariableTree) { DefineOutput(4,TList::Class()); //All Entries output DefineOutput(5,TList::Class()); //3sigma PID output if (trackRotation) { DefineOutput(6,TList::Class()); //All Entries output } } else { // Output slot #4 keeps a tree of the candidate variables after track selection DefineOutput(4,TTree::Class()); //My private output } if (fWriteVariableTree) fSign=2; } //___________________________________________________________________________ AliAnalysisTaskSELc2V0bachelor::~AliAnalysisTaskSELc2V0bachelor() { // /// destructor // Info("~AliAnalysisTaskSELc2V0bachelor","Calling Destructor"); if (fOutput) { delete fOutput; fOutput = 0; } if (fOutputAll) { delete fOutputAll; fOutputAll = 0; } if (fOutputPIDBach) { delete fOutputPIDBach; fOutputPIDBach = 0; } if (fCounter) { delete fCounter; fCounter = 0; } if (fAnalCuts) { delete fAnalCuts; fAnalCuts = 0; } if (fVariablesTree) { delete fVariablesTree; fVariablesTree = 0; } if (fOutputPIDBachTR) { delete fOutputPIDBachTR; fOutputPIDBachTR = 0; } } //_________________________________________________ void AliAnalysisTaskSELc2V0bachelor::Init() { // /// Initialization // fIsEventSelected=kFALSE; if (fDebug > 1) AliInfo("Init"); PostData(3,fAnalCuts); return; } //_________________________________________________ void AliAnalysisTaskSELc2V0bachelor::UserExec(Option_t *) { /// user exec if (!fInputEvent) { AliError("NO EVENT FOUND!"); return; } AliAODEvent* aodEvent = dynamic_cast<AliAODEvent*>(fInputEvent); if(fAODProtection>=0) { // Protection against different number of events in the AOD and deltaAOD // In case of discrepancy the event is rejected. Int_t matchingAODdeltaAODlevel = AliRDHFCuts::CheckMatchingAODdeltaAODevents(); if (matchingAODdeltaAODlevel<0 || (matchingAODdeltaAODlevel==0 && fAODProtection==1)) { // AOD/deltaAOD trees have different number of entries || TProcessID do not match while it was required fCEvents->Fill(19); return; } } TClonesArray *arrayLctopKos=0; if (!aodEvent && AODEvent() && IsStandardAOD()) { // In case there is an AOD handler writing a standard AOD, use the AOD // event in memory rather than the input (ESD) event. aodEvent = dynamic_cast<AliAODEvent*> (AODEvent()); // in this case the braches in the deltaAOD (AliAOD.VertexingHF.root) // have to taken from the AOD event hold by the AliAODExtension AliAODHandler* aodHandler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (aodHandler->GetExtensions()) { AliAODExtension *ext = (AliAODExtension*)aodHandler->GetExtensions()->FindObject("AliAOD.VertexingHF.root"); AliAODEvent *aodFromExt = ext->GetAOD(); arrayLctopKos=(TClonesArray*)aodFromExt->GetList()->FindObject("CascadesHF"); } } else { arrayLctopKos=(TClonesArray*)aodEvent->GetList()->FindObject("CascadesHF"); } fCEvents->Fill(1); if (fUseMCInfo) fAnalCuts->SetTriggerClass(""); // AOD primary vertex fVtx1 = (AliAODVertex*)aodEvent->GetPrimaryVertex(); if (!fVtx1) return; fIsEventSelected = fAnalCuts->IsEventSelected(aodEvent); // better to initialize before CheckEventSelection call CheckEventSelection(aodEvent); // fix for temporary bug in ESDfilter fBzkG = (Double_t)aodEvent->GetMagneticField(); fAnalCuts->SetMagneticField(fBzkG); if (TMath::Abs(fBzkG)<0.001) return; fCEvents->Fill(2); if (!arrayLctopKos) { AliInfo("Could not find array of HF cascades, skipping the event"); return; } else { if (arrayLctopKos->GetEntriesFast()) { AliInfo(Form("Found %d cascades",arrayLctopKos->GetEntriesFast())); } } fCEvents->Fill(3); // mc analysis TClonesArray *mcArray = 0; AliAODMCHeader *mcHeader=0; if (fUseMCInfo) { // MC array need for maching mcArray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName())); if (!mcArray) { AliError("Could not find Monte-Carlo in AOD"); return; } fCEvents->Fill(4); // in case of MC events // load MC header mcHeader = (AliAODMCHeader*)aodEvent->GetList()->FindObject(AliAODMCHeader::StdBranchName()); if (!mcHeader) { AliError("AliAnalysisTaskSELc2V0bachelor::UserExec: MC header branch not found!\n"); return; } fCEvents->Fill(5); // in case of MC events Double_t zMCVertex = mcHeader->GetVtxZ(); if (TMath::Abs(zMCVertex) > fAnalCuts->GetMaxVtxZ()) { AliDebug(2,Form("Event rejected: abs(zVtxMC)=%f > fAnalCuts->GetMaxVtxZ()=%f",zMCVertex,fAnalCuts->GetMaxVtxZ())); return; } else { fCEvents->Fill(17); // in case of MC events } } Int_t runnumber = aodEvent->GetRunNumber(); if (aodEvent->GetTriggerMask() == 0 && (runnumber >= 195344 && runnumber <= 195677)){ AliDebug(3,"Event rejected because of null trigger mask"); return; } fCounter->StoreEvent(aodEvent,fAnalCuts,fUseMCInfo); // it is very important that it stays BEFORE any other event selection if (fVtx1->GetNContributors()>0) // this check is done in IsEventSelected fCEvents->Fill(6); if ( !fIsEventSelected ) return; // don't take into account not selected events fCEvents->Fill(7); if(fDoSingleAnalysisForSystK0SP>0){ MakeSingleAnalysisForSystK0SP(aodEvent,mcArray,fAnalCuts); if(fDoSingleAnalysisForSystK0SP==2) return; } if(fGenerateBGEventFromTracks==1){ DoEventMixing(aodEvent,mcArray,fAnalCuts); }else if(fGenerateBGEventFromTracks==2){ DoRotationFromTrack(aodEvent,mcArray,fAnalCuts); } fEventCounter++; Int_t nSelectedAnal = 0; MakeAnalysisForLc2prK0S(aodEvent,arrayLctopKos,mcArray, nSelectedAnal, fAnalCuts); if (nSelectedAnal) CheckEventSelectionWithCandidates(aodEvent); fCounter->StoreCandidates(aodEvent,nSelectedAnal,kTRUE); fCounter->StoreCandidates(aodEvent,nSelectedAnal,kFALSE); PostData(1,fOutput); PostData(2,fCounter); if (!fWriteVariableTree) { PostData(4,fOutputAll); PostData(5,fOutputPIDBach); if (fTrackRotation) PostData(6,fOutputPIDBachTR); } else { PostData(4,fVariablesTree); } fIsEventSelected=kFALSE; return; } //________________________________________ terminate ___________________________ void AliAnalysisTaskSELc2V0bachelor::Terminate(Option_t*) { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. //AliInfo("Terminate",""); AliAnalysisTaskSE::Terminate(); fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { AliError("fOutput not available"); return; } //fCEvents = dynamic_cast<TH1F*>(fOutput->FindObject("fCEvents")); if (!fWriteVariableTree) { fOutputAll = dynamic_cast<TList*> (GetOutputData(4)); if (!fOutputAll) { AliError("fOutputAll not available"); return; } fOutputPIDBach = dynamic_cast<TList*> (GetOutputData(5)); if (!fOutputPIDBach) { AliError("fOutputPIDBach not available"); return; } if (fTrackRotation) { fOutputPIDBachTR = dynamic_cast<TList*> (GetOutputData(6)); if (!fOutputPIDBachTR) { AliError("fOutputPIDBachTR not available"); return; } } } else { fVariablesTree = dynamic_cast<TTree*> (GetOutputData(4)); if (!fVariablesTree) { AliError("fVariablesTree not available"); return; } } return; } //___________________________________________________________________________ void AliAnalysisTaskSELc2V0bachelor::UserCreateOutputObjects() { /// output AliInfo(Form("CreateOutputObjects of task %s\n", GetName())); fOutput = new TList(); fOutput->SetOwner(); fOutput->SetName("chist0"); DefineGeneralHistograms(); // define general histograms PostData(1,fOutput); fCounter = new AliNormalizationCounter("NormalizationCounter"); fCounter->Init(); PostData(2,fCounter); if (!fWriteVariableTree) { fOutputAll = new TList(); fOutputAll->SetOwner(); fOutputAll->SetName("listAll"); fOutputPIDBach = new TList(); fOutputPIDBach->SetOwner(); fOutputPIDBach->SetName("listPIDBach"); if (fTrackRotation) { fOutputPIDBachTR = new TList(); fOutputPIDBachTR->SetOwner(); fOutputPIDBachTR->SetName("listPIDBachTR"); } DefineK0SHistos(); // define analysis histograms if (fUseMCInfo && fCheckOrigin) DefineSignalHistosSeparatedPerOrigin(); // define analysis histograms for SNG separated for origin PostData(4,fOutputAll); PostData(5,fOutputPIDBach); if (fTrackRotation) PostData(6,fOutputPIDBachTR); } else { DefineTreeVariables(); PostData(4,fVariablesTree); } if(fGenerateBGEventFromTracks==1){ fNzVtxBins = 10; for(Int_t i=0;i<11;i++){ fZvtxBins[i] = -10.+2.*(Double_t)i; } fNCentBins = 10; for(Int_t i=0;i<11;i++){ fCentBins[i] = 10.*(Double_t)i; } fNOfPools=fNCentBins*fNzVtxBins; fReservoirP.resize(fNOfPools,std::vector<std::vector<TVector *> > (fNumberOfEventsForMixing)); fNextResVec.resize(fNOfPools,0); fReservoirsReady.resize(fNOfPools,kFALSE); for(Int_t s=0; s<fNOfPools; s++) { for(Int_t k=0;k<fNumberOfEventsForMixing;k++){ fReservoirP[s][k].clear(); } } }else if(fGenerateBGEventFromTracks==2){ fNzVtxBins = 1; fZvtxBins[0] = -10.; fZvtxBins[1] = 10.; fNCentBins = 1; fCentBins[0] = 0.; fCentBins[1] = 100.; fNOfPools=1; fReservoirP.resize(fNOfPools,std::vector<std::vector<TVector *> > (1)); fNextResVec.resize(fNOfPools,0); fReservoirsReady.resize(fNOfPools,kFALSE); fReservoirP[0][0].clear(); } return; } //------------------------------------------------------------------------------- void AliAnalysisTaskSELc2V0bachelor::MakeAnalysisForLc2prK0S(AliAODEvent *aodEvent,TClonesArray *arrayLctopKos, TClonesArray *mcArray, Int_t &nSelectedAnal, AliRDHFCutsLctoV0 *cutsAnal) { /// make the analysis Int_t pdgCand = 4122; Int_t pdgDgLctoV0bachelor[2]={2212,310}; // always 1st bachelor, 2nd V0 Int_t pdgDgV0toDaughters[2]={211,211}; // loop over cascades to search for candidates Lc->p+K0S Int_t nCascades= arrayLctopKos->GetEntriesFast(); if (nCascades==0) { AliInfo("Could not find cascades, skipping the event"); return; } AliAnalysisVertexingHF *vHF = new AliAnalysisVertexingHF(); for (Int_t iLctopK0S = 0; iLctopK0S<nCascades; iLctopK0S++) { ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(0); // Lc candidates and K0S from Lc AliAODRecoCascadeHF* lcK0Spr = dynamic_cast<AliAODRecoCascadeHF*>(arrayLctopKos->At(iLctopK0S)); if (!lcK0Spr) { AliDebug(2,Form("Cascade %d doens't exist, skipping",iLctopK0S)); continue; } if (!(lcK0Spr->CheckCascadeFlags())) { AliDebug(2,Form("Cascade %d is not flagged as Lc candidate",iLctopK0S)); continue; } if(!vHF->FillRecoCasc(aodEvent,lcK0Spr,kFALSE)){//Fill the data members of the candidate only if they are empty. fCEvents->Fill(18);//monitor how often this fails continue; } if (fReconstructSecVtx) { if (!(vHF->RecoSecondaryVertexForCascades(aodEvent, lcK0Spr))) { continue; } } if (!lcK0Spr->GetSecondaryVtx()) { AliInfo("No secondary vertex"); // it will be done in AliRDHFCutsLctoV0::IsSelected continue; } if (lcK0Spr->GetNDaughters()!=2) { AliDebug(2,Form("Cascade %d has not 2 daughters (nDaughters=%d)",iLctopK0S,lcK0Spr->GetNDaughters())); // it will be done in AliRDHFCutsLctoV0::IsSelected continue; } if ( (fSign == 0 && lcK0Spr->Charge()<0) || (fSign == 1 && lcK0Spr->Charge()>0) ) { AliDebug(2,Form("Charge of the cascade %d is different with respect to the required one",iLctopK0S)); // continue; } AliAODv0 * v0part = dynamic_cast<AliAODv0*>(lcK0Spr->Getv0()); AliAODTrack * bachPart = dynamic_cast<AliAODTrack*>(lcK0Spr->GetBachelor()); if (!v0part || !bachPart) { AliDebug(2,Form("Cascade %d has no V0 or no bachelor object",iLctopK0S)); // it will be done in AliRDHFCutsLctoV0::IsSelected continue; } if (!v0part->GetSecondaryVtx()) { AliDebug(2,Form("No secondary vertex for V0 by cascade %d",iLctopK0S)); // it will be done in AliRDHFCutsLctoV0::IsSelected continue; } if (v0part->GetNDaughters()!=2) { AliDebug(2,Form("current V0 has not 2 daughters (onTheFly=%d, nDaughters=%d)",v0part->GetOnFlyStatus(),v0part->GetNDaughters())); // it will be done in AliRDHFCutsLctoV0::IsSelected continue; } AliAODTrack * v0Pos = dynamic_cast<AliAODTrack*>(lcK0Spr->Getv0PositiveTrack()); AliAODTrack * v0Neg = dynamic_cast<AliAODTrack*>(lcK0Spr->Getv0NegativeTrack()); if (!v0Neg || !v0Pos) { AliDebug(2,Form("V0 by cascade %d has no V0positive of V0negative object",iLctopK0S)); // it will be done in AliRDHFCutsLctoV0::IsSelected continue; } ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(1); if (v0Pos->Charge() == v0Neg->Charge()) continue; ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(2); Int_t isLc = 0; Int_t originLc = -1; // -1 -> RD; 0 -> BKG; 1 -> form c; 2 -> from b; 3 -> not from quark if (fUseMCInfo) { Int_t pdgCode=-2; // find associated MC particle for Lc -> p+K0 and K0S->pi+pi Int_t mcLabel = lcK0Spr->MatchToMC(pdgCand,pdgDgLctoV0bachelor[1],pdgDgLctoV0bachelor,pdgDgV0toDaughters,mcArray,kTRUE); if (mcLabel!=-1) { AliDebug(2,Form(" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~cascade number %d (total cascade number = %d)", iLctopK0S,nCascades)); AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel)); if (partLc) { pdgCode = partLc->GetPdgCode(); if (pdgCode<0) AliDebug(2,Form(" ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ MClabel=%d ~~~~~~~~~~ pdgCode=%d", mcLabel, pdgCode)); pdgCode = TMath::Abs(pdgCode); isLc = 1; AliVertexingHFUtils *util = new AliVertexingHFUtils(); Int_t pdgMom = util->CheckOrigin(mcArray,partLc,kFALSE); if (pdgMom == 4) { originLc=1; // from c } else if (pdgMom == 5) { originLc=2; // form b } else { Int_t isThereaQuark=util->CheckOrigin(mcArray,partLc,kTRUE); if (isThereaQuark<=0) originLc=3; // not from q } delete util; } } else { AliDebug(2,Form("No MC candidate (cascade number %d -total cascade number = %d -)", iLctopK0S,nCascades)); pdgCode=-1; } } else { originLc=-1; // real data } FillLc2pK0Sspectrum(lcK0Spr, isLc, nSelectedAnal, cutsAnal, mcArray, originLc, aodEvent); } delete vHF; AliDebug(2, Form("Found %d Reco particles that are Lc!!", nSelectedAnal)); return; } //________________________________________________________________________ void AliAnalysisTaskSELc2V0bachelor::FillLc2pK0Sspectrum(AliAODRecoCascadeHF *part, Int_t isLc, Int_t &nSelectedAnal, AliRDHFCutsLctoV0 *cutsAnal, TClonesArray *mcArray, Int_t originLc, AliAODEvent *aod) { // /// Fill histos for Lc -> K0S+proton // TString fillthis=""; AliAODTrack *bachelor = (AliAODTrack*)part->GetBachelor(); Double_t momBach = bachelor->P(); AliAODv0 * v0part = (AliAODv0*)part->Getv0(); Bool_t onFlyV0 = v0part->GetOnFlyStatus(); // on-the-flight V0s Bool_t areCutsUsingPID = cutsAnal->GetIsUsePID(); cutsAnal->SetUsePID(kFALSE); Bool_t isInCascadeWindow = (((cutsAnal->IsSelectedSingleCut(part,AliRDHFCuts::kCandidate,0,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)); // cut on Lc->p+K0S invMass cutsAnal->SetUsePID(areCutsUsingPID); if ( onFlyV0 && !fUseOnTheFlyV0 ) return; if (fAdditionalChecks) CheckCandidatesAtDifferentLevels(part,cutsAnal,aod); // track rotation if (fTrackRotation) { if (onFlyV0) { TrackRotation(cutsAnal,part,"",aod); } else { TrackRotation(cutsAnal,part,"Offline",aod); } if (fUseMCInfo) { if (isLc==1) { if (onFlyV0) { TrackRotation(cutsAnal,part,"Sgn",aod); } else { TrackRotation(cutsAnal,part,"OfflineSgn",aod); } }// sgn else { // bkg if (onFlyV0) { TrackRotation(cutsAnal,part,"Bkg",aod); } else { TrackRotation(cutsAnal,part,"OfflineBkg",aod); } } } // if fUseMCInfo } // if fTrackRotation if ( !(cutsAnal->IsInFiducialAcceptance(part->Pt(),part->Y(4122))) ) return; if ( !( ( (cutsAnal->IsSelected(part,AliRDHFCuts::kTracks,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) ) return; if ( ( ( (cutsAnal->IsSelected(part,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) ) nSelectedAnal++; // Fill candidate variable Tree (track selection, V0 invMass selection) if ( fWriteVariableTree ) { Double_t invmassK0S = v0part->MassK0Short(); Double_t mk0sPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass(); Double_t nSigmaTPCpr=-999.; cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor,4,nSigmaTPCpr); if ( !onFlyV0 && isInCascadeWindow && part->CosV0PointingAngle()>0.99 && TMath::Abs(invmassK0S-mk0sPDG)<=0.05 && part->Pt()>=fPtMinToFillTheTree && part->Pt()<fPtMaxToFillTheTree && (!fUseTPCPIDtoFillTree || (fUseTPCPIDtoFillTree && TMath::Abs(nSigmaTPCpr)<cutsAnal->GetNTPCSigmaCutForPreselection()))) FillTheTree(part,cutsAnal,mcArray,isLc,originLc); return; } cutsAnal->SetUsePID(kFALSE); Bool_t isCandidateSelectedCuts = (((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)); // kinematic/topological cuts cutsAnal->SetUsePID(areCutsUsingPID); Bool_t isBachelorID = (((cutsAnal->IsSelected(part,AliRDHFCuts::kPID,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)); // ID x bachelor //if (((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)) { if (((cutsAnal->IsSelected(part,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)) { if (fUseMCInfo && isLc && !fWriteVariableTree) { Int_t pdgCand1 = 4122; Int_t pdgDgLctoV0bachelor1[2]={2212,310}; Int_t pdgDgV0toDaughters1[2]={211,211}; Int_t mcLabel1=part->MatchToMC(pdgCand1,pdgDgLctoV0bachelor1[1],pdgDgLctoV0bachelor1,pdgDgV0toDaughters1,mcArray,kTRUE); AliDebug(2,Form(" Found true MC candidate: Lc->pK0S(%d) - onTheFly=%1d",mcLabel1,onFlyV0)); } } Double_t nSigmaTPCpr=-999.; cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor,4,nSigmaTPCpr); Double_t nSigmaTOFpr=-999.; cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor,4,nSigmaTOFpr); Double_t nSigmaTPCpi=-999.; cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor,2,nSigmaTPCpi); Double_t nSigmaTOFpi=-999.; cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor,2,nSigmaTOFpi); Double_t nSigmaTPCka=-999.; cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor,3,nSigmaTPCka); Double_t nSigmaTOFka=-999.; cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor,3,nSigmaTOFka); if (onFlyV0) { fillthis="histArmPodK0S"; FillArmPodDistribution(v0part,fillthis,isCandidateSelectedCuts,isBachelorID); fillthis="histArmPodLc"; FillArmPodDistribution(part,fillthis,isCandidateSelectedCuts,isBachelorID); //if (isCandidateSelectedCuts) { FillAnalysisHistograms(part,cutsAnal,"",aod); //} } else { fillthis="histArmPodK0SOffline"; FillArmPodDistribution(v0part,fillthis,isCandidateSelectedCuts,isBachelorID); fillthis="histArmPodLcOffline"; FillArmPodDistribution(part,fillthis,isCandidateSelectedCuts,isBachelorID); FillAnalysisHistograms(part,cutsAnal,"Offline",aod); if (isCandidateSelectedCuts) { fillthis="histoprotonBachSigmaVspTOF"; ((TH2F*)(fOutput->FindObject(fillthis)))->Fill(momBach,nSigmaTOFpr); fillthis="histoprotonBachSigmaVspTPC"; ((TH2F*)(fOutput->FindObject(fillthis)))->Fill(momBach,nSigmaTPCpr); //FillAnalysisHistograms(part,cutsAnal,"Offline",aod); } } if (fUseMCInfo) { if (isLc==1) { if (onFlyV0) { fillthis="histArmPodK0SSgn"; FillArmPodDistribution(v0part,fillthis,isCandidateSelectedCuts,isBachelorID); fillthis="histArmPodLcSgn"; FillArmPodDistribution(part,fillthis,isCandidateSelectedCuts,isBachelorID); //if (isCandidateSelectedCuts) { FillAnalysisHistograms(part,cutsAnal,"Sgn",aod); //} if (fCheckOrigin) { switch (originLc) { case 1: FillAnalysisHistograms(part,cutsAnal,"SgnC",aod); break; case 2: FillAnalysisHistograms(part,cutsAnal,"SgnB",aod); break; case 3: FillAnalysisHistograms(part,cutsAnal,"SgnNoQ",aod); break; } } } else { fillthis="histArmPodK0SOfflineSgn"; FillArmPodDistribution(v0part,fillthis,isCandidateSelectedCuts,isBachelorID); fillthis="histArmPodLcOfflineSgn"; FillArmPodDistribution(part,fillthis,isCandidateSelectedCuts,isBachelorID); if (isCandidateSelectedCuts) { fillthis="histoprotonBachSigmaVspTOFsgn"; ((TH2F*)(fOutput->FindObject(fillthis)))->Fill(momBach,nSigmaTOFpr); fillthis="histoprotonBachSigmaVspTPCsgn"; ((TH2F*)(fOutput->FindObject(fillthis)))->Fill(momBach,nSigmaTPCpr); //FillAnalysisHistograms(part,cutsAnal,"OfflineSgn",aod); } if (fCheckOrigin) { switch (originLc) { case 1: FillAnalysisHistograms(part,cutsAnal,"OfflineSgnC",aod); break; case 2: FillAnalysisHistograms(part,cutsAnal,"OfflineSgnB",aod); break; case 3: FillAnalysisHistograms(part,cutsAnal,"OfflineSgnNoQ",aod); break; } } FillAnalysisHistograms(part,cutsAnal,"OfflineSgn",aod); } }// sgn else { // bkg if (onFlyV0) { fillthis="histArmPodK0SBkg"; FillArmPodDistribution(v0part,fillthis,isCandidateSelectedCuts,isBachelorID); fillthis="histArmPodLcBkg"; FillArmPodDistribution(part,fillthis,isCandidateSelectedCuts,isBachelorID); //if (isCandidateSelectedCuts) { FillAnalysisHistograms(part,cutsAnal,"Bkg",aod); //} } else { fillthis="histArmPodK0SOfflineBkg"; FillArmPodDistribution(v0part,fillthis,isCandidateSelectedCuts,isBachelorID); fillthis="histArmPodLcOfflineBkg"; FillArmPodDistribution(part,fillthis,isCandidateSelectedCuts,isBachelorID); FillAnalysisHistograms(part,cutsAnal,"OfflineBkg",aod); if (isCandidateSelectedCuts) { fillthis="histoprotonBachSigmaVspTOFbkg"; ((TH2F*)(fOutput->FindObject(fillthis)))->Fill(momBach,nSigmaTOFpr); fillthis="histoprotonBachSigmaVspTPCbkg"; ((TH2F*)(fOutput->FindObject(fillthis)))->Fill(momBach,nSigmaTPCpr); //FillAnalysisHistograms(part,cutsAnal,"OfflineBkg",aod); } } } } // if fUseMCInfo return; } //---------------------------------------------------- void AliAnalysisTaskSELc2V0bachelor::DefineK0SHistos() { Double_t mLcPDG = TDatabasePDG::Instance()->GetParticle(4122)->Mass(); Double_t mK0SPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass(); Double_t mMinLambdaPDG = TDatabasePDG::Instance()->GetParticle(2212)->Mass()+ TDatabasePDG::Instance()->GetParticle(211)->Mass(); Double_t mLPDG = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); TString nameHisto=" ", nameHistoSgn=" ", nameHistoBkg=" "; TString titleHisto=" ", titleHistoSgn=" ", titleHistoBkg=" "; // pt(Lc) Double_t *binLimpTLc=new Double_t[11+1]; // 11 pT(Lc) bins binLimpTLc[ 0]= 0.; binLimpTLc[ 1]= 1.; binLimpTLc[ 2]= 2.; binLimpTLc[ 3]= 3.; binLimpTLc[ 4]= 4.; binLimpTLc[ 5]= 5.; binLimpTLc[ 6]= 6.; binLimpTLc[ 7]= 8.; binLimpTLc[ 8]=12.; binLimpTLc[ 9]=17.; binLimpTLc[10]=25.; binLimpTLc[11]=35.; // pt(prong) Double_t *binLimpTprong=new Double_t[41+1]; // 41 pT(prong) bins binLimpTprong[ 0]= 0.0; binLimpTprong[ 1]= 0.1; binLimpTprong[ 2]= 0.2; binLimpTprong[ 3]= 0.3; binLimpTprong[ 4]= 0.4; binLimpTprong[ 5]= 0.5; binLimpTprong[ 6]= 0.6; binLimpTprong[ 7]= 0.7; binLimpTprong[ 8]= 0.8; binLimpTprong[ 9]= 0.9; binLimpTprong[10]= 1.0; binLimpTprong[11]= 1.2; binLimpTprong[12]= 1.4; binLimpTprong[13]= 1.6; binLimpTprong[14]= 1.8; binLimpTprong[15]= 2.0; binLimpTprong[16]= 2.2; binLimpTprong[17]= 2.4; binLimpTprong[18]= 2.6; binLimpTprong[19]= 2.8; binLimpTprong[20]= 3.0; binLimpTprong[21]= 3.5; binLimpTprong[22]= 4.0; binLimpTprong[23]= 4.5; binLimpTprong[24]= 5.0; binLimpTprong[25]= 5.5; binLimpTprong[26]= 6.0; binLimpTprong[27]= 6.5; binLimpTprong[28]= 7.0; binLimpTprong[29]= 7.5; binLimpTprong[30]= 8.0; binLimpTprong[31]= 9.0; binLimpTprong[32]=10.0; binLimpTprong[33]=11.0; binLimpTprong[34]=12.0; binLimpTprong[35]=13.0; binLimpTprong[36]=14.0; binLimpTprong[37]=15.0; binLimpTprong[38]=20.0; binLimpTprong[39]=25.0; binLimpTprong[40]=30.0; binLimpTprong[41]=35.0; if (fUseOnTheFlyV0) { // V0 invariant masses (on-the-fly) nameHisto="histK0SMass"; titleHisto="K^{0}_{S} invariant mass VS p_{T}; p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#pi^{+},#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* spectrumK0SMass = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,mK0SPDG-0.050,mK0SPDG+0.050); // Lc invariant masses (x K0S on-the-fly) nameHisto="histLcMassByK0S"; titleHisto="#Lambda_{c} invariant mass (by K^{0}_{S}) vs p_{T}; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; TH2F* spectrumLcMassByK0S = new TH2F(nameHisto.Data(),titleHisto.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); nameHisto="histpK0Svsp"; titleHisto="p(K^{0}_{S}) vs p(p); p(p) [GeV/c]; p(K^{0}_{S}) [GeV/c]"; TH2F* momentumDistributionK0Svsp = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,41,binLimpTprong); nameHisto="histArmPodK0S"; titleHisto="V0-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0S = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-1.,1.,300,0.,0.3); nameHisto="histArmPodLc"; titleHisto="#Lambda_{c}-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLc = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-4.,4.,800,0.,1.6); TH2F* allspectrumK0SMass = (TH2F*)spectrumK0SMass->Clone(); TH2F* allspectrumLcMassByK0S = (TH2F*)spectrumLcMassByK0S->Clone(); TH2F* allmomentumDistributionK0Svsp = (TH2F*)momentumDistributionK0Svsp->Clone(); TH2F* allArmenterosPodK0S = (TH2F*)armenterosPodK0S->Clone(); TH2F* allArmenterosPodLc = (TH2F*)armenterosPodLc->Clone(); TH2F* pidBachspectrumK0SMass = (TH2F*)spectrumK0SMass->Clone(); TH2F* pidBachspectrumLcMassByK0S = (TH2F*)spectrumLcMassByK0S->Clone(); TH2F* pidBachmomentumDistributionK0Svsp = (TH2F*)momentumDistributionK0Svsp->Clone(); TH2F* pidBachArmenterosPodK0S = (TH2F*)armenterosPodK0S->Clone(); TH2F* pidBachArmenterosPodLc = (TH2F*)armenterosPodLc->Clone(); fOutputAll->Add(allspectrumK0SMass); fOutputAll->Add(allspectrumLcMassByK0S); fOutputAll->Add(allmomentumDistributionK0Svsp); fOutputAll->Add(allArmenterosPodK0S); fOutputAll->Add(allArmenterosPodLc); fOutputPIDBach->Add(pidBachspectrumK0SMass); fOutputPIDBach->Add(pidBachspectrumLcMassByK0S); fOutputPIDBach->Add(pidBachmomentumDistributionK0Svsp); fOutputPIDBach->Add(pidBachArmenterosPodK0S); fOutputPIDBach->Add(pidBachArmenterosPodLc); nameHisto="histArmPodK0S0"; titleHisto="V0-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0S0 = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-1.,1.,300,0.,0.3); nameHisto="histArmPodLc0"; titleHisto="#Lambda_{c}-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLc0 = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-4.,4.,800,0.,1.6); fOutputAll->Add(armenterosPodK0S0); fOutputAll->Add(armenterosPodLc0); if (fTrackRotation) { TH2F* pidBachTRspectrumLcMassByK0S = (TH2F*)spectrumLcMassByK0S->Clone(); fOutputPIDBachTR->Add(pidBachTRspectrumLcMassByK0S); } nameHisto="histptK0S"; titleHisto="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; TH2F* ptK0S = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histptP"; titleHisto="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; TH2F* ptP = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histptPip"; titleHisto="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; TH2F* ptPiP = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histptPim"; titleHisto="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; TH2F* ptPiM = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histLambdaMass"; titleHisto="m_{inv}(p,#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(p,#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* massLambda = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHisto="histLambdaBarMass"; titleHisto="m_{inv}(#bar{p},#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#bar{p},#pi^{+}) [GeV/c^{2}]; Entries"; TH2F* massLambdaBar = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHisto="histGammaMass"; titleHisto="m_{inv}(e^{+},e^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(e^{+},e^{-}) [GeV/c^{2}]; Entries"; TH2F* massGamma = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,100,0.,1.); nameHisto="histD0K0S"; titleHisto="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; TH2F* d0K0S = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,-1.,1.); nameHisto="histD0P"; titleHisto="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; TH2F* d0P = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,-1.,1.); nameHisto="histCosPAK0S"; titleHisto="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosPAK0S = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,100,0.99,1.); nameHisto="histCosThetaProtonCMS"; titleHisto="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosThePr = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,100,-1.,1.); nameHisto="histResignedD0"; titleHisto="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; TH2F *resignedD0 = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F* allptK0S = (TH2F*)ptK0S->Clone(); TH2F* allptP = (TH2F*)ptP->Clone(); TH2F* allptPiP = (TH2F*)ptPiP->Clone(); TH2F* allptPiM = (TH2F*)ptPiM->Clone(); TH2F* allmassLambda = (TH2F*)massLambda->Clone(); TH2F* allmassLambdaBar = (TH2F*)massLambdaBar->Clone(); TH2F* allmassGamma = (TH2F*)massGamma->Clone(); TH2F* alld0K0S = (TH2F*)d0K0S->Clone(); TH2F* alld0P = (TH2F*)d0P->Clone(); TH2F* allcosPAK0S = (TH2F*)cosPAK0S->Clone(); TH2F* allcosThePr = (TH2F*)cosThePr->Clone(); TH2F* allresignedD0 = (TH2F*)resignedD0->Clone(); TH2F* pidptK0S = (TH2F*)ptK0S->Clone(); TH2F* pidptP = (TH2F*)ptP->Clone(); TH2F* pidptPiP = (TH2F*)ptPiP->Clone(); TH2F* pidptPiM = (TH2F*)ptPiM->Clone(); TH2F* pidmassLambda = (TH2F*)massLambda->Clone(); TH2F* pidmassLambdaBar = (TH2F*)massLambdaBar->Clone(); TH2F* pidmassGamma = (TH2F*)massGamma->Clone(); TH2F* pidd0K0S = (TH2F*)d0K0S->Clone(); TH2F* pidd0P = (TH2F*)d0P->Clone(); TH2F* pidcosPAK0S = (TH2F*)cosPAK0S->Clone(); TH2F* pidcosThePr = (TH2F*)cosThePr->Clone(); TH2F* pidresignedD0 = (TH2F*)resignedD0->Clone(); fOutputAll->Add(allptK0S); fOutputAll->Add(allptP); fOutputAll->Add(allptPiP); fOutputAll->Add(allptPiM); fOutputAll->Add(allmassLambda); fOutputAll->Add(allmassLambdaBar); fOutputAll->Add(allmassGamma); fOutputAll->Add(alld0K0S); fOutputAll->Add(alld0P); fOutputAll->Add(allcosPAK0S); fOutputAll->Add(allcosThePr); fOutputAll->Add(allresignedD0); fOutputPIDBach->Add(pidptK0S); fOutputPIDBach->Add(pidptP); fOutputPIDBach->Add(pidptPiP); fOutputPIDBach->Add(pidptPiM); fOutputPIDBach->Add(pidmassLambda); fOutputPIDBach->Add(pidmassLambdaBar); fOutputPIDBach->Add(pidmassGamma); fOutputPIDBach->Add(pidd0K0S); fOutputPIDBach->Add(pidd0P); fOutputPIDBach->Add(pidcosPAK0S); fOutputPIDBach->Add(pidcosThePr); fOutputPIDBach->Add(pidresignedD0); if (fTrackRotation) { TH2F* pidTRptK0S = (TH2F*)ptK0S->Clone(); TH2F* pidTRptP = (TH2F*)ptP->Clone(); TH2F* pidTRptPiP = (TH2F*)ptPiP->Clone(); TH2F* pidTRptPiM = (TH2F*)ptPiM->Clone(); TH2F* pidTRmassLambda = (TH2F*)massLambda->Clone(); TH2F* pidTRmassLambdaBar = (TH2F*)massLambdaBar->Clone(); TH2F* pidTRmassGamma = (TH2F*)massGamma->Clone(); TH2F* pidTRcosPAK0S = (TH2F*)cosPAK0S->Clone(); TH2F* pidTRcosThePr = (TH2F*)cosThePr->Clone(); TH2F* pidTRresignedD0 = (TH2F*)resignedD0->Clone(); fOutputPIDBachTR->Add(pidTRptK0S); fOutputPIDBachTR->Add(pidTRptP); fOutputPIDBachTR->Add(pidTRptPiP); fOutputPIDBachTR->Add(pidTRptPiM); fOutputPIDBachTR->Add(pidTRmassLambda); fOutputPIDBachTR->Add(pidTRmassLambdaBar); fOutputPIDBachTR->Add(pidTRmassGamma); fOutputPIDBachTR->Add(pidTRcosPAK0S); fOutputPIDBachTR->Add(pidTRcosThePr); fOutputPIDBachTR->Add(pidTRresignedD0); } } // V0 invariant masses (offline) nameHisto="histK0SMassOffline"; titleHisto="K^{0}_{S} invariant mass VS p_{T}; p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#pi^{+},#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* spectrumK0SMassOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,mK0SPDG-0.050,mK0SPDG+0.050); // Lc invariant masses (x K0S offline) nameHisto="histLcMassByK0SOffline"; titleHisto="#Lambda_{c} invariant mass (by K^{0}_{S}) vs p_{T}; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; TH2F* spectrumLcMassOfflineByK0S = new TH2F(nameHisto.Data(),titleHisto.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); nameHisto="histpK0SvspOffline"; titleHisto="p(K^{0}_{S}) vs p(p); p(p) [GeV/c]; p(K^{0}_{S}) [GeV/c]"; TH2F* momentumDistributionK0SvspOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,41,binLimpTprong); nameHisto="histArmPodK0SOffline"; titleHisto="V0-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0SOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-1.,1.,300,0.,0.3); nameHisto="histArmPodLcOffline"; titleHisto="#Lambda_{c}-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLcOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-4.,4.,800,0.,1.6); TH2F* allspectrumK0SMassOffline = (TH2F*)spectrumK0SMassOffline->Clone(); TH2F* allspectrumLcMassOfflineByK0S = (TH2F*)spectrumLcMassOfflineByK0S->Clone(); TH2F* allmomentumDistributionK0SvspOffline = (TH2F*)momentumDistributionK0SvspOffline->Clone(); TH2F* allArmenterosPodK0SOffline = (TH2F*)armenterosPodK0SOffline->Clone(); TH2F* allArmenterosPodLcOffline = (TH2F*)armenterosPodLcOffline->Clone(); TH2F* pidBachspectrumK0SMassOffline = (TH2F*)spectrumK0SMassOffline->Clone(); TH2F* pidBachspectrumLcMassOfflineByK0S = (TH2F*)spectrumLcMassOfflineByK0S->Clone(); TH2F* pidBachmomentumDistributionK0SvspOffline = (TH2F*)momentumDistributionK0SvspOffline->Clone(); TH2F* pidBachArmenterosPodK0SOffline = (TH2F*)armenterosPodK0SOffline->Clone(); TH2F* pidBachArmenterosPodLcOffline = (TH2F*)armenterosPodLcOffline->Clone(); fOutputAll->Add(allspectrumK0SMassOffline); fOutputAll->Add(allspectrumLcMassOfflineByK0S); fOutputAll->Add(allmomentumDistributionK0SvspOffline); fOutputAll->Add(allArmenterosPodK0SOffline); fOutputAll->Add(allArmenterosPodLcOffline); fOutputPIDBach->Add(pidBachspectrumK0SMassOffline); fOutputPIDBach->Add(pidBachspectrumLcMassOfflineByK0S); fOutputPIDBach->Add(pidBachmomentumDistributionK0SvspOffline); fOutputPIDBach->Add(pidBachArmenterosPodK0SOffline); fOutputPIDBach->Add(pidBachArmenterosPodLcOffline); if(fFillSubSampleHist){ nameHisto="histLcMassByK0SSubSampleOffline"; titleHisto="#Lambda_{c} invariant mass (by K^{0}_{S}) vs p_{T} vs Sub ID"; Int_t bins_subsample[3]= {1000,24,25}; Double_t xmin_subsample[3]={mLcPDG-0.25,0,-0.5}; Double_t xmax_subsample[3]={mLcPDG+0.25,24.,24.5}; THnSparse *spectrumLcMassOfflineByK0SSubSample = new THnSparseF(nameHisto.Data(),titleHisto.Data(),3,bins_subsample,xmin_subsample,xmax_subsample); fOutputPIDBach->Add(spectrumLcMassOfflineByK0SSubSample); } if(fGenerateBGEventFromTracks>0){ nameHisto="histLcMassBGByK0SOffline"; titleHisto="#Lambda_{c} invariant mass (by K^{0}_{S}) vs p_{T}; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; TH2F* spectrumLcMassBGOfflineByK0S = new TH2F(nameHisto.Data(),titleHisto.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); fOutputPIDBach->Add(spectrumLcMassBGOfflineByK0S); } nameHisto="histArmPodK0SOffline0"; titleHisto="V0-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0SOffline0 = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-1.,1.,300,0.,0.3); nameHisto="histArmPodLcOffline0"; titleHisto="#Lambda_{c}-candidate Armenteros-Podolanski distribution; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLcOffline0 = new TH2F(nameHisto.Data(),titleHisto.Data(),200,-4.,4.,800,0.,1.6); fOutputAll->Add(armenterosPodK0SOffline0); fOutputAll->Add(armenterosPodLcOffline0); if (fTrackRotation) { TH2F* pidBachTRspectrumLcMassOfflineByK0S = (TH2F*)spectrumLcMassOfflineByK0S->Clone(); fOutputPIDBachTR->Add(pidBachTRspectrumLcMassOfflineByK0S); } nameHisto="histptK0SOffline"; titleHisto="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; TH2F* ptK0SOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histptPOffline"; titleHisto="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; TH2F* ptPOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histptPipOffline"; titleHisto="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; TH2F* ptPiPOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histptPimOffline"; titleHisto="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; TH2F* ptPiMOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,41,binLimpTprong); nameHisto="histLambdaMassOffline"; titleHisto="m_{inv}(p,#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(p,#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* massLambdaOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHisto="histLambdaBarMassOffline"; titleHisto="m_{inv}(#bar{p},#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#bar{p},#pi^{+}) [GeV/c^{2}]; Entries"; TH2F* massLambdaBarOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHisto="histGammaMassOffline"; titleHisto="m_{inv}(e^{+},e^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(e^{+},e^{-}) [GeV/c^{2}]; Entries"; TH2F* massGammaOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,100,0.,1.); nameHisto="histD0K0SOffline"; titleHisto="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; TH2F* d0K0SOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,-1.,1.); nameHisto="histD0POffline"; titleHisto="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; TH2F* d0POffline = new TH2F(nameHisto.Data(),titleHisto.Data(),11,binLimpTLc,1000,-1.,1.); nameHisto="histCosPAK0SOffline"; titleHisto="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosPAK0SOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,100,0.99,1.); nameHisto="histCosThetaProtonCMSOffline"; titleHisto="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosThePrOffline = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,100,-1.,1.); nameHisto="histResignedD0Offline"; titleHisto="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; TH2F *resignedD0Offline = new TH2F(nameHisto.Data(),titleHisto.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F* allptK0SOffline = (TH2F*)ptK0SOffline->Clone(); TH2F* allptPOffline = (TH2F*)ptPOffline->Clone(); TH2F* allptPiPOffline = (TH2F*)ptPiPOffline->Clone(); TH2F* allptPiMOffline = (TH2F*)ptPiMOffline->Clone(); TH2F* allmassLambdaOffline = (TH2F*)massLambdaOffline->Clone(); TH2F* allmassLambdaBarOffline = (TH2F*)massLambdaBarOffline->Clone(); TH2F* allmassGammaOffline = (TH2F*)massGammaOffline->Clone(); TH2F* alld0K0SOffline = (TH2F*)d0K0SOffline->Clone(); TH2F* alld0POffline = (TH2F*)d0POffline->Clone(); TH2F* allcosPAK0SOffline = (TH2F*)cosPAK0SOffline->Clone(); TH2F* allcosThePrOffline = (TH2F*)cosThePrOffline->Clone(); TH2F* allresignedD0Offline = (TH2F*)resignedD0Offline->Clone(); TH2F* pidptK0SOffline = (TH2F*)ptK0SOffline->Clone(); TH2F* pidptPOffline = (TH2F*)ptPOffline->Clone(); TH2F* pidptPiPOffline = (TH2F*)ptPiPOffline->Clone(); TH2F* pidptPiMOffline = (TH2F*)ptPiMOffline->Clone(); TH2F* pidmassLambdaOffline = (TH2F*)massLambdaOffline->Clone(); TH2F* pidmassLambdaBarOffline = (TH2F*)massLambdaBarOffline->Clone(); TH2F* pidmassGammaOffline = (TH2F*)massGammaOffline->Clone(); TH2F* pidd0K0SOffline = (TH2F*)d0K0SOffline->Clone(); TH2F* pidd0POffline = (TH2F*)d0POffline->Clone(); TH2F* pidcosPAK0SOffline = (TH2F*)cosPAK0SOffline->Clone(); TH2F* pidcosThePrOffline = (TH2F*)cosThePrOffline->Clone(); TH2F* pidresignedD0Offline = (TH2F*)resignedD0Offline->Clone(); fOutputAll->Add(allptK0SOffline); fOutputAll->Add(allptPOffline); fOutputAll->Add(allptPiPOffline); fOutputAll->Add(allptPiMOffline); fOutputAll->Add(allmassLambdaOffline); fOutputAll->Add(allmassLambdaBarOffline); fOutputAll->Add(allmassGammaOffline); fOutputAll->Add(alld0K0SOffline); fOutputAll->Add(alld0POffline); fOutputAll->Add(allcosPAK0SOffline); fOutputAll->Add(allcosThePrOffline); fOutputAll->Add(allresignedD0Offline); fOutputPIDBach->Add(pidptK0SOffline); fOutputPIDBach->Add(pidptPOffline); fOutputPIDBach->Add(pidptPiPOffline); fOutputPIDBach->Add(pidptPiMOffline); fOutputPIDBach->Add(pidmassLambdaOffline); fOutputPIDBach->Add(pidmassLambdaBarOffline); fOutputPIDBach->Add(pidmassGammaOffline); fOutputPIDBach->Add(pidd0K0SOffline); fOutputPIDBach->Add(pidd0POffline); fOutputPIDBach->Add(pidcosPAK0SOffline); fOutputPIDBach->Add(pidcosThePrOffline); fOutputPIDBach->Add(pidresignedD0Offline); if (fTrackRotation) { TH2F* pidTRptK0SOffline = (TH2F*)ptK0SOffline->Clone(); TH2F* pidTRptPOffline = (TH2F*)ptPOffline->Clone(); TH2F* pidTRptPiPOffline = (TH2F*)ptPiPOffline->Clone(); TH2F* pidTRptPiMOffline = (TH2F*)ptPiMOffline->Clone(); TH2F* pidTRmassLambdaOffline = (TH2F*)massLambdaOffline->Clone(); TH2F* pidTRmassLambdaBarOffline = (TH2F*)massLambdaBarOffline->Clone(); TH2F* pidTRmassGammaOffline = (TH2F*)massGammaOffline->Clone(); TH2F* pidTRcosPAK0SOffline = (TH2F*)cosPAK0SOffline->Clone(); TH2F* pidTRcosThePrOffline = (TH2F*)cosThePrOffline->Clone(); TH2F* pidTRresignedD0Offline = (TH2F*)resignedD0Offline->Clone(); fOutputPIDBachTR->Add(pidTRptK0SOffline); fOutputPIDBachTR->Add(pidTRptPOffline); fOutputPIDBachTR->Add(pidTRptPiPOffline); fOutputPIDBachTR->Add(pidTRptPiMOffline); fOutputPIDBachTR->Add(pidTRmassLambdaOffline); fOutputPIDBachTR->Add(pidTRmassLambdaBarOffline); fOutputPIDBachTR->Add(pidTRmassGammaOffline); fOutputPIDBachTR->Add(pidTRcosPAK0SOffline); fOutputPIDBachTR->Add(pidTRcosThePrOffline); fOutputPIDBachTR->Add(pidTRresignedD0Offline); } if (fUseMCInfo) { if (fUseOnTheFlyV0) { nameHistoSgn="histK0SMassSgn"; nameHistoBkg="histK0SMassBkg"; titleHistoSgn="K^{0}_{S} - sgn: invariant mass VS p_{T} - MC; p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#pi^{+},#pi^{-}) [GeV/c^{2}]; Entries"; titleHistoBkg="K^{0}_{S} - bkg: invariant mass VS p_{T} - MC; p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#pi^{+},#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* spectrumK0SMassSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,mK0SPDG-0.050,mK0SPDG+0.050); TH2F* spectrumK0SMassBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,mK0SPDG-0.050,mK0SPDG+0.050); nameHistoSgn="histLcMassByK0SSgn"; nameHistoBkg="histLcMassByK0SBkg"; titleHistoSgn="#Lambda_{c} - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; titleHistoBkg="#Lambda_{c} - bkg: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; TH2F* spectrumLcMassByK0SSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* spectrumLcMassByK0SBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); nameHistoSgn="histpK0SvspSgn"; nameHistoBkg="histpK0SvspBkg"; titleHistoSgn="#Lambda_{c} - sgn: K^{0}_{S} vs p Total Momentum Distribution - MC; p(p) [GeV/c]; p(K^{0}_{S}) [GeV/c]"; titleHistoBkg="#Lambda_{c} - bkg: K^{0}_{S} vs p Total Momentum Distribution - MC; p(p) [GeV/c]; p(K^{0}_{S}) [GeV/c]"; TH2F* momentumDistributionK0SvspSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,41,binLimpTprong); TH2F* momentumDistributionK0SvspBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,41,binLimpTprong); // armenteros-podolanski plots K0S nameHistoSgn="histArmPodK0SSgn"; nameHistoBkg="histArmPodK0SBkg"; titleHistoSgn="V0-candidate Armenteros-Podolanski distribution (sgn); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="V0-candidate Armenteros-Podolanski distribution (bkg); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0SSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-1.,1.,300,0.,0.3); TH2F* armenterosPodK0SBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-1.,1.,300,0.,0.3); nameHistoSgn="histArmPodLcSgn"; nameHistoBkg="histArmPodLcBkg"; titleHistoSgn="#Lambda_{c}-candidate Armenteros-Podolanski distribution (sgn); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="#Lambda_{c}-candidate Armenteros-Podolanski distribution (bkg); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLcSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-4.,4.,800,0.,1.6); TH2F* armenterosPodLcBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-4.,4.,800,0.,1.6); TH2F* allspectrumK0SMassSgn = (TH2F*)spectrumK0SMassSgn->Clone(); TH2F* allspectrumK0SMassBkg = (TH2F*)spectrumK0SMassBkg->Clone(); TH2F* allspectrumLcMassByK0SSgn = (TH2F*)spectrumLcMassByK0SSgn->Clone(); TH2F* allspectrumLcMassByK0SBkg = (TH2F*)spectrumLcMassByK0SBkg->Clone(); TH2F* allmomentumDistributionK0SvspSgn = (TH2F*)momentumDistributionK0SvspSgn->Clone(); TH2F* allmomentumDistributionK0SvspBkg = (TH2F*)momentumDistributionK0SvspBkg->Clone(); TH2F* allArmenterosPodK0SSgn = (TH2F*)armenterosPodK0SSgn->Clone(); TH2F* allArmenterosPodK0SBkg = (TH2F*)armenterosPodK0SBkg->Clone(); TH2F* allArmenterosPodLcSgn = (TH2F*)armenterosPodLcSgn->Clone(); TH2F* allArmenterosPodLcBkg = (TH2F*)armenterosPodLcBkg->Clone(); TH2F* pidBachspectrumK0SMassSgn = (TH2F*)spectrumK0SMassSgn->Clone(); TH2F* pidBachspectrumK0SMassBkg = (TH2F*)spectrumK0SMassBkg->Clone(); TH2F* pidBachspectrumLcMassByK0SSgn = (TH2F*)spectrumLcMassByK0SSgn->Clone(); TH2F* pidBachspectrumLcMassByK0SBkg = (TH2F*)spectrumLcMassByK0SBkg->Clone(); TH2F* pidBachmomentumDistributionK0SvspSgn = (TH2F*)momentumDistributionK0SvspSgn->Clone(); TH2F* pidBachmomentumDistributionK0SvspBkg = (TH2F*)momentumDistributionK0SvspBkg->Clone(); TH2F* pidBachArmenterosPodK0SSgn = (TH2F*)armenterosPodK0SSgn->Clone(); TH2F* pidBachArmenterosPodK0SBkg = (TH2F*)armenterosPodK0SBkg->Clone(); TH2F* pidBachArmenterosPodLcSgn = (TH2F*)armenterosPodLcSgn->Clone(); TH2F* pidBachArmenterosPodLcBkg = (TH2F*)armenterosPodLcBkg->Clone(); fOutputAll->Add(allspectrumK0SMassSgn); fOutputAll->Add(allspectrumK0SMassBkg); fOutputAll->Add(allspectrumLcMassByK0SSgn); fOutputAll->Add(allspectrumLcMassByK0SBkg); fOutputAll->Add(allmomentumDistributionK0SvspSgn); fOutputAll->Add(allmomentumDistributionK0SvspBkg); fOutputAll->Add(allArmenterosPodK0SSgn); fOutputAll->Add(allArmenterosPodK0SBkg); fOutputAll->Add(allArmenterosPodLcSgn); fOutputAll->Add(allArmenterosPodLcBkg); fOutputPIDBach->Add(pidBachspectrumK0SMassSgn); fOutputPIDBach->Add(pidBachspectrumK0SMassBkg); fOutputPIDBach->Add(pidBachspectrumLcMassByK0SSgn); fOutputPIDBach->Add(pidBachspectrumLcMassByK0SBkg); fOutputPIDBach->Add(pidBachmomentumDistributionK0SvspSgn); fOutputPIDBach->Add(pidBachmomentumDistributionK0SvspBkg); fOutputPIDBach->Add(pidBachArmenterosPodK0SSgn); fOutputPIDBach->Add(pidBachArmenterosPodK0SBkg); fOutputPIDBach->Add(pidBachArmenterosPodLcSgn); fOutputPIDBach->Add(pidBachArmenterosPodLcBkg); nameHistoSgn="histArmPodK0SSgn0"; nameHistoBkg="histArmPodK0SBkg0"; titleHistoSgn="V0-candidate Armenteros-Podolanski distribution (sgn); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="V0-candidate Armenteros-Podolanski distribution (bkg); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0SSgn0 = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-1.,1.,300,0.,0.3); TH2F* armenterosPodK0SBkg0 = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-1.,1.,300,0.,0.3); fOutputAll->Add(armenterosPodK0SSgn0); fOutputAll->Add(armenterosPodK0SBkg0); nameHistoSgn="histArmPodLcSgn0"; nameHistoBkg="histArmPodLcBkg0"; titleHistoSgn="#Lambda_{c}-candidate Armenteros-Podolanski distribution (sgn); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="#Lambda_{c}-candidate Armenteros-Podolanski distribution (bkg); #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLcSgn0 = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-4.,4.,800,0.,1.6); TH2F* armenterosPodLcBkg0 = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-4.,4.,800,0.,1.6); fOutputAll->Add(armenterosPodLcSgn0); fOutputAll->Add(armenterosPodLcBkg0); if (fTrackRotation) { TH2F* pidBachTRspectrumLcMassByK0SSgn = (TH2F*)spectrumLcMassByK0SSgn->Clone(); TH2F* pidBachTRspectrumLcMassByK0SBkg = (TH2F*)spectrumLcMassByK0SBkg->Clone(); fOutputPIDBachTR->Add(pidBachTRspectrumLcMassByK0SSgn); fOutputPIDBachTR->Add(pidBachTRspectrumLcMassByK0SBkg); } nameHistoSgn="histptK0SSgn"; nameHistoBkg="histptK0SBkg"; titleHistoSgn="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; titleHistoBkg="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; TH2F* ptK0SSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptK0SBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histptPSgn"; nameHistoBkg="histptPBkg"; titleHistoSgn="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; titleHistoBkg="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; TH2F* ptPSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histptPipSgn"; nameHistoBkg="histptPipBkg"; titleHistoSgn="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; titleHistoBkg="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; TH2F* ptPiPSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiPBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histptPimSgn"; nameHistoBkg="histptPimBkg"; titleHistoSgn="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; titleHistoBkg="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; TH2F* ptPiMSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiMBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histLambdaMassSgn"; nameHistoBkg="histLambdaMassBkg"; titleHistoSgn="m_{inv}(p,#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(p,#pi^{-}) [GeV/c^{2}]; Entries"; titleHistoBkg="m_{inv}(p,#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(p,#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* massLambdaSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); TH2F* massLambdaBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHistoSgn="histLambdaBarMassSgn"; nameHistoBkg="histLambdaBarMassBkg"; titleHistoSgn="m_{inv}(#bar{p},#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#bar{p},#pi^{+}) [GeV/c^{2}]; Entries"; titleHistoBkg="m_{inv}(#bar{p},#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#bar{p},#pi^{+}) [GeV/c^{2}]; Entries"; TH2F* massLambdaBarSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); TH2F* massLambdaBarBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHistoSgn="histGammaMassSgn"; nameHistoBkg="histGammaMassBkg"; titleHistoSgn="m_{inv}(e^{+},e^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(e^{+},e^{-}) [GeV/c^{2}]; Entries"; titleHistoBkg="m_{inv}(e^{+},e^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(e^{+},e^{-}) [GeV/c^{2}]; Entries"; TH2F* massGammaSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,100,0.,1.); TH2F* massGammaBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,100,0.,1.); nameHistoSgn="histD0K0SSgn"; nameHistoBkg="histD0K0SBkg"; titleHistoSgn="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; titleHistoBkg="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; TH2F* d0K0SSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0K0SBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgn="histD0PSgn"; nameHistoBkg="histD0PBkg"; titleHistoSgn="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; titleHistoBkg="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; TH2F* d0PSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0PBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgn="histCosPAK0SSgn"; nameHistoBkg="histCosPAK0SBkg"; titleHistoSgn="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoBkg="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosPAK0SSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,100,0.99,1.); TH2F *cosPAK0SBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,100,0.99,1.); nameHistoSgn="histCosThetaProtonCMSSgn"; nameHistoBkg="histCosThetaProtonCMSBkg"; titleHistoSgn="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoBkg="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosThePrSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,100,-1.,1.); TH2F *cosThePrBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,100,-1.,1.); nameHistoSgn="histResignedD0Sgn"; nameHistoBkg="histResignedD0Bkg"; titleHistoSgn="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; titleHistoBkg="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; TH2F *resignedD0Sgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F *resignedD0Bkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F* allptK0SSgn = (TH2F*)ptK0SSgn->Clone(); TH2F* allptK0SBkg = (TH2F*)ptK0SBkg->Clone(); TH2F* allptPSgn = (TH2F*)ptPSgn->Clone(); TH2F* allptPBkg = (TH2F*)ptPBkg->Clone(); TH2F* allptPiPSgn = (TH2F*)ptPiPSgn->Clone(); TH2F* allptPiPBkg = (TH2F*)ptPiPBkg->Clone(); TH2F* allptPiMSgn = (TH2F*)ptPiMSgn->Clone(); TH2F* allptPiMBkg = (TH2F*)ptPiMBkg->Clone(); TH2F* allmassLambdaSgn = (TH2F*)massLambdaSgn->Clone(); TH2F* allmassLambdaBkg = (TH2F*)massLambdaBkg->Clone(); TH2F* allmassLambdaBarSgn = (TH2F*)massLambdaBarSgn->Clone(); TH2F* allmassLambdaBarBkg = (TH2F*)massLambdaBarBkg->Clone(); TH2F* allmassGammaSgn = (TH2F*)massGammaSgn->Clone(); TH2F* allmassGammaBkg = (TH2F*)massGammaBkg->Clone(); TH2F* alld0K0SSgn = (TH2F*)d0K0SSgn->Clone(); TH2F* alld0K0SBkg = (TH2F*)d0K0SBkg->Clone(); TH2F* alld0PSgn = (TH2F*)d0PSgn->Clone(); TH2F* alld0PBkg = (TH2F*)d0PBkg->Clone(); TH2F* allcosPAK0SSgn = (TH2F*)cosPAK0SSgn->Clone(); TH2F* allcosPAK0SBkg = (TH2F*)cosPAK0SBkg->Clone(); TH2F* allcosThePrSgn = (TH2F*)cosThePrSgn->Clone(); TH2F* allcosThePrBkg = (TH2F*)cosThePrBkg->Clone(); TH2F* allresignedD0Sgn = (TH2F*)resignedD0Sgn->Clone(); TH2F* allresignedD0Bkg = (TH2F*)resignedD0Bkg->Clone(); TH2F* pidptK0SSgn = (TH2F*)ptK0SSgn->Clone(); TH2F* pidptK0SBkg = (TH2F*)ptK0SBkg->Clone(); TH2F* pidptPSgn = (TH2F*)ptPSgn->Clone(); TH2F* pidptPBkg = (TH2F*)ptPBkg->Clone(); TH2F* pidptPiPSgn = (TH2F*)ptPiPSgn->Clone(); TH2F* pidptPiPBkg = (TH2F*)ptPiPBkg->Clone(); TH2F* pidptPiMSgn = (TH2F*)ptPiMSgn->Clone(); TH2F* pidptPiMBkg = (TH2F*)ptPiMBkg->Clone(); TH2F* pidmassLambdaSgn = (TH2F*)massLambdaSgn->Clone(); TH2F* pidmassLambdaBkg = (TH2F*)massLambdaBkg->Clone(); TH2F* pidmassLambdaBarSgn = (TH2F*)massLambdaBarSgn->Clone(); TH2F* pidmassLambdaBarBkg = (TH2F*)massLambdaBarBkg->Clone(); TH2F* pidmassGammaSgn = (TH2F*)massGammaSgn->Clone(); TH2F* pidmassGammaBkg = (TH2F*)massGammaBkg->Clone(); TH2F* pidd0K0SSgn = (TH2F*)d0K0SSgn->Clone(); TH2F* pidd0K0SBkg = (TH2F*)d0K0SBkg->Clone(); TH2F* pidd0PSgn = (TH2F*)d0PSgn->Clone(); TH2F* pidd0PBkg = (TH2F*)d0PBkg->Clone(); TH2F* pidcosPAK0SSgn = (TH2F*)cosPAK0SSgn->Clone(); TH2F* pidcosPAK0SBkg = (TH2F*)cosPAK0SBkg->Clone(); TH2F* pidcosThePrSgn = (TH2F*)cosThePrSgn->Clone(); TH2F* pidcosThePrBkg = (TH2F*)cosThePrBkg->Clone(); TH2F* pidresignedD0Sgn = (TH2F*)resignedD0Sgn->Clone(); TH2F* pidresignedD0Bkg = (TH2F*)resignedD0Bkg->Clone(); fOutputAll->Add(allptK0SSgn); fOutputAll->Add(allptK0SBkg); fOutputAll->Add(allptPSgn); fOutputAll->Add(allptPBkg); fOutputAll->Add(allptPiPSgn); fOutputAll->Add(allptPiPBkg); fOutputAll->Add(allptPiMSgn); fOutputAll->Add(allptPiMBkg); fOutputAll->Add(allmassLambdaSgn); fOutputAll->Add(allmassLambdaBkg); fOutputAll->Add(allmassLambdaBarSgn); fOutputAll->Add(allmassLambdaBarBkg); fOutputAll->Add(allmassGammaSgn); fOutputAll->Add(allmassGammaBkg); fOutputAll->Add(alld0K0SSgn); fOutputAll->Add(alld0K0SBkg); fOutputAll->Add(alld0PSgn); fOutputAll->Add(alld0PBkg); fOutputAll->Add(allcosPAK0SSgn); fOutputAll->Add(allcosPAK0SBkg); fOutputAll->Add(allcosThePrSgn); fOutputAll->Add(allcosThePrBkg); fOutputAll->Add(allresignedD0Sgn); fOutputAll->Add(allresignedD0Bkg); fOutputPIDBach->Add(pidptK0SSgn); fOutputPIDBach->Add(pidptK0SBkg); fOutputPIDBach->Add(pidptPSgn); fOutputPIDBach->Add(pidptPBkg); fOutputPIDBach->Add(pidptPiPSgn); fOutputPIDBach->Add(pidptPiPBkg); fOutputPIDBach->Add(pidptPiMSgn); fOutputPIDBach->Add(pidptPiMBkg); fOutputPIDBach->Add(pidmassLambdaSgn); fOutputPIDBach->Add(pidmassLambdaBkg); fOutputPIDBach->Add(pidmassLambdaBarSgn); fOutputPIDBach->Add(pidmassLambdaBarBkg); fOutputPIDBach->Add(pidmassGammaSgn); fOutputPIDBach->Add(pidmassGammaBkg); fOutputPIDBach->Add(pidd0K0SSgn); fOutputPIDBach->Add(pidd0K0SBkg); fOutputPIDBach->Add(pidd0PSgn); fOutputPIDBach->Add(pidd0PBkg); fOutputPIDBach->Add(pidcosPAK0SSgn); fOutputPIDBach->Add(pidcosPAK0SBkg); fOutputPIDBach->Add(pidcosThePrSgn); fOutputPIDBach->Add(pidcosThePrBkg); fOutputPIDBach->Add(pidresignedD0Sgn); fOutputPIDBach->Add(pidresignedD0Bkg); if (fTrackRotation) { TH2F* pidTRptK0SSgn = (TH2F*)ptK0SSgn->Clone(); TH2F* pidTRptK0SBkg = (TH2F*)ptK0SBkg->Clone(); TH2F* pidTRptPSgn = (TH2F*)ptPSgn->Clone(); TH2F* pidTRptPBkg = (TH2F*)ptPBkg->Clone(); TH2F* pidTRptPiPSgn = (TH2F*)ptPiPSgn->Clone(); TH2F* pidTRptPiPBkg = (TH2F*)ptPiPBkg->Clone(); TH2F* pidTRptPiMSgn = (TH2F*)ptPiMSgn->Clone(); TH2F* pidTRptPiMBkg = (TH2F*)ptPiMBkg->Clone(); TH2F* pidTRmassLambdaSgn = (TH2F*)massLambdaSgn->Clone(); TH2F* pidTRmassLambdaBkg = (TH2F*)massLambdaBkg->Clone(); TH2F* pidTRmassLambdaBarSgn = (TH2F*)massLambdaBarSgn->Clone(); TH2F* pidTRmassLambdaBarBkg = (TH2F*)massLambdaBarBkg->Clone(); TH2F* pidTRmassGammaSgn = (TH2F*)massGammaSgn->Clone(); TH2F* pidTRmassGammaBkg = (TH2F*)massGammaBkg->Clone(); TH2F* pidTRcosPAK0SSgn = (TH2F*)cosPAK0SSgn->Clone(); TH2F* pidTRcosPAK0SBkg = (TH2F*)cosPAK0SBkg->Clone(); TH2F* pidTRcosThePrSgn = (TH2F*)cosThePrSgn->Clone(); TH2F* pidTRcosThePrBkg = (TH2F*)cosThePrBkg->Clone(); TH2F* pidTRresignedD0Sgn = (TH2F*)resignedD0Sgn->Clone(); TH2F* pidTRresignedD0Bkg = (TH2F*)resignedD0Bkg->Clone(); fOutputPIDBachTR->Add(pidTRptK0SSgn); fOutputPIDBachTR->Add(pidTRptK0SBkg); fOutputPIDBachTR->Add(pidTRptPSgn); fOutputPIDBachTR->Add(pidTRptPBkg); fOutputPIDBachTR->Add(pidTRptPiPSgn); fOutputPIDBachTR->Add(pidTRptPiPBkg); fOutputPIDBachTR->Add(pidTRptPiMSgn); fOutputPIDBachTR->Add(pidTRptPiMBkg); fOutputPIDBachTR->Add(pidTRmassLambdaSgn); fOutputPIDBachTR->Add(pidTRmassLambdaBkg); fOutputPIDBachTR->Add(pidTRmassLambdaBarSgn); fOutputPIDBachTR->Add(pidTRmassLambdaBarBkg); fOutputPIDBachTR->Add(pidTRmassGammaSgn); fOutputPIDBachTR->Add(pidTRmassGammaBkg); fOutputPIDBachTR->Add(pidTRcosPAK0SSgn); fOutputPIDBachTR->Add(pidTRcosPAK0SBkg); fOutputPIDBachTR->Add(pidTRcosThePrSgn); fOutputPIDBachTR->Add(pidTRcosThePrBkg); fOutputPIDBachTR->Add(pidTRresignedD0Sgn); fOutputPIDBachTR->Add(pidTRresignedD0Bkg); } } // useOnTheFly nameHistoSgn="histK0SMassOfflineSgn"; nameHistoBkg="histK0SMassOfflineBkg"; titleHistoSgn="K^{0}_{S} - sgn: invariant mass VS p_{T} - MC; p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#pi^{+},#pi^{-}) [GeV/c^{2}]; Entries"; titleHistoBkg="K^{0}_{S} - bkg: invariant mass VS p_{T} - MC; p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#pi^{+},#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* spectrumK0SMassOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,mK0SPDG-0.050,mK0SPDG+0.050); TH2F* spectrumK0SMassOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,mK0SPDG-0.050,mK0SPDG+0.050); nameHistoSgn="histLcMassByK0SOfflineSgn"; nameHistoBkg="histLcMassByK0SOfflineBkg"; titleHistoSgn="#Lambda_{c} - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; titleHistoBkg="#Lambda_{c} - bkg: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; TH2F* spectrumLcMassOfflineByK0SSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* spectrumLcMassOfflineByK0SBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); nameHistoSgn="histpK0SvspOfflineSgn"; nameHistoBkg="histpK0SvspOfflineBkg"; titleHistoSgn="#Lambda_{c} - sgn: K^{0}_{S} vs p Total Momentum Distribution - Offline - MC; p(p) [GeV/c]; p(K^{0}_{S}) [GeV/c]"; titleHistoBkg="#Lambda_{c} - bkg: K^{0}_{S} vs p Total Momentum Distribution - Offline - MC; p(p) [GeV/c]; p(K^{0}_{S}) [GeV/c]"; TH2F* momentumDistributionK0SvspOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,41,binLimpTprong); TH2F* momentumDistributionK0SvspOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,41,binLimpTprong); // armenteros-podolanski plots K0S (offline) nameHistoSgn="histArmPodK0SOfflineSgn"; nameHistoBkg="histArmPodK0SOfflineBkg"; titleHistoSgn="V0-candidate Armenteros-Podolanski distribution (sgn) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="V0-candidate Armenteros-Podolanski distribution (bkg) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0SOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-1.,1.,300,0.,0.3); TH2F* armenterosPodK0SOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-1.,1.,300,0.,0.3); nameHistoSgn="histArmPodLcOfflineSgn"; nameHistoBkg="histArmPodLcOfflineBkg"; titleHistoSgn="#Lambda_{c}-candidate Armenteros-Podolanski distribution (sgn) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="#Lambda_{c}-candidate Armenteros-Podolanski distribution (bkg) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLcOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-4.,4.,800,0.,1.6); TH2F* armenterosPodLcOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-4.,4.,800,0.,1.6); TH2F* allspectrumK0SMassOfflineSgn = (TH2F*)spectrumK0SMassOfflineSgn->Clone(); TH2F* allspectrumK0SMassOfflineBkg = (TH2F*) spectrumK0SMassOfflineBkg->Clone(); TH2F* allspectrumLcMassOfflineByK0SSgn = (TH2F*)spectrumLcMassOfflineByK0SSgn->Clone(); TH2F* allspectrumLcMassOfflineByK0SBkg = (TH2F*) spectrumLcMassOfflineByK0SBkg->Clone(); TH2F* allmomentumDistributionK0SvspOfflineSgn = (TH2F*)momentumDistributionK0SvspOfflineSgn->Clone(); TH2F* allmomentumDistributionK0SvspOfflineBkg = (TH2F*)momentumDistributionK0SvspOfflineBkg->Clone(); TH2F* allArmenterosPodK0SOfflineSgn = (TH2F*)armenterosPodK0SOfflineSgn->Clone(); TH2F* allArmenterosPodK0SOfflineBkg = (TH2F*)armenterosPodK0SOfflineBkg->Clone(); TH2F* allArmenterosPodLcOfflineSgn = (TH2F*)armenterosPodLcOfflineSgn->Clone(); TH2F* allArmenterosPodLcOfflineBkg = (TH2F*)armenterosPodLcOfflineBkg->Clone(); TH2F* pidBachspectrumLcMassOfflineByK0SSgn = (TH2F*)spectrumLcMassOfflineByK0SSgn->Clone(); TH2F* pidBachspectrumLcMassOfflineByK0SBkg = (TH2F*) spectrumLcMassOfflineByK0SBkg->Clone(); TH2F* pidBachspectrumK0SMassOfflineSgn = (TH2F*)spectrumK0SMassOfflineSgn->Clone(); TH2F* pidBachspectrumK0SMassOfflineBkg = (TH2F*) spectrumK0SMassOfflineBkg->Clone(); TH2F* pidBachmomentumDistributionK0SvspOfflineSgn = (TH2F*)momentumDistributionK0SvspOfflineSgn->Clone(); TH2F* pidBachmomentumDistributionK0SvspOfflineBkg = (TH2F*)momentumDistributionK0SvspOfflineBkg->Clone(); TH2F* pidBachArmenterosPodK0SOfflineSgn = (TH2F*)armenterosPodK0SOfflineSgn->Clone(); TH2F* pidBachArmenterosPodK0SOfflineBkg = (TH2F*)armenterosPodK0SOfflineBkg->Clone(); TH2F* pidBachArmenterosPodLcOfflineSgn = (TH2F*)armenterosPodLcOfflineSgn->Clone(); TH2F* pidBachArmenterosPodLcOfflineBkg = (TH2F*)armenterosPodLcOfflineBkg->Clone(); fOutputAll->Add(allspectrumK0SMassOfflineSgn); fOutputAll->Add(allspectrumK0SMassOfflineBkg); fOutputAll->Add(allspectrumLcMassOfflineByK0SSgn); fOutputAll->Add(allspectrumLcMassOfflineByK0SBkg); fOutputAll->Add(allmomentumDistributionK0SvspOfflineSgn); fOutputAll->Add(allmomentumDistributionK0SvspOfflineBkg); fOutputAll->Add(allArmenterosPodK0SOfflineSgn); fOutputAll->Add(allArmenterosPodK0SOfflineBkg); fOutputAll->Add(allArmenterosPodLcOfflineSgn); fOutputAll->Add(allArmenterosPodLcOfflineBkg); fOutputPIDBach->Add(pidBachspectrumK0SMassOfflineSgn); fOutputPIDBach->Add(pidBachspectrumK0SMassOfflineBkg); fOutputPIDBach->Add(pidBachspectrumLcMassOfflineByK0SSgn); fOutputPIDBach->Add(pidBachspectrumLcMassOfflineByK0SBkg); fOutputPIDBach->Add(pidBachmomentumDistributionK0SvspOfflineSgn); fOutputPIDBach->Add(pidBachmomentumDistributionK0SvspOfflineBkg); fOutputPIDBach->Add(pidBachArmenterosPodK0SOfflineSgn); fOutputPIDBach->Add(pidBachArmenterosPodK0SOfflineBkg); fOutputPIDBach->Add(pidBachArmenterosPodLcOfflineSgn); fOutputPIDBach->Add(pidBachArmenterosPodLcOfflineBkg); nameHistoSgn="histArmPodK0SOfflineSgn0"; nameHistoBkg="histArmPodK0SOfflineBkg0"; titleHistoSgn="V0-candidate Armenteros-Podolanski distribution (sgn) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="V0-candidate Armenteros-Podolanski distribution (bkg) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodK0SOfflineSgn0 = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-1.,1.,300,0.,0.3); TH2F* armenterosPodK0SOfflineBkg0 = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-1.,1.,300,0.,0.3); nameHistoSgn="histArmPodLcOfflineSgn0"; nameHistoBkg="histArmPodLcOfflineBkg0"; titleHistoSgn="#Lambda_{c}-candidate Armenteros-Podolanski distribution (sgn) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; titleHistoBkg="#Lambda_{c}-candidate Armenteros-Podolanski distribution (bkg) -offline-; #frac{p_{L}^{+}-p_{L}^{-}}{p_{L}^{+}+p_{L}^{-}}; p_{T}^{+} [GeV/c]"; TH2F* armenterosPodLcOfflineSgn0 = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),200,-4.,4.,800,0.,1.6); TH2F* armenterosPodLcOfflineBkg0 = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),200,-4.,4.,800,0.,1.6); fOutputAll->Add(armenterosPodK0SOfflineSgn0); fOutputAll->Add(armenterosPodK0SOfflineBkg0); fOutputAll->Add(armenterosPodLcOfflineSgn0); fOutputAll->Add(armenterosPodLcOfflineBkg0); if (fTrackRotation) { TH2F* pidBachTRspectrumLcMassOfflineByK0SSgn = (TH2F*)spectrumLcMassOfflineByK0SSgn->Clone(); TH2F* pidBachTRspectrumLcMassOfflineByK0SBkg = (TH2F*) spectrumLcMassOfflineByK0SBkg->Clone(); fOutputPIDBachTR->Add(pidBachTRspectrumLcMassOfflineByK0SSgn); fOutputPIDBachTR->Add(pidBachTRspectrumLcMassOfflineByK0SBkg); } nameHistoSgn="histptK0SOfflineSgn"; nameHistoBkg="histptK0SOfflineBkg"; titleHistoSgn="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; titleHistoBkg="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; TH2F* ptK0SOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptK0SOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histptPOfflineSgn"; nameHistoBkg="histptPOfflineBkg"; titleHistoSgn="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; titleHistoBkg="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; TH2F* ptPOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histptPipOfflineSgn"; nameHistoBkg="histptPipOfflineBkg"; titleHistoSgn="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; titleHistoBkg="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; TH2F* ptPiPOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiPOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histptPimOfflineSgn"; nameHistoBkg="histptPimOfflineBkg"; titleHistoSgn="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; titleHistoBkg="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; TH2F* ptPiMOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiMOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgn="histLambdaMassOfflineSgn"; nameHistoBkg="histLambdaMassOfflineBkg"; titleHistoSgn="m_{inv}(p,#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(p,#pi^{-}) [GeV/c^{2}]; Entries"; titleHistoBkg="m_{inv}(p,#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(p,#pi^{-}) [GeV/c^{2}]; Entries"; TH2F* massLambdaOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); TH2F* massLambdaOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHistoSgn="histLambdaBarMassOfflineSgn"; nameHistoBkg="histLambdaBarMassOfflineBkg"; titleHistoSgn="m_{inv}(#bar{p},#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#bar{p},#pi^{+}) [GeV/c^{2}]; Entries"; titleHistoBkg="m_{inv}(#bar{p},#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(#bar{p},#pi^{+}) [GeV/c^{2}]; Entries"; TH2F* massLambdaBarOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); TH2F* massLambdaBarOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,mMinLambdaPDG,mMinLambdaPDG+0.5); nameHistoSgn="histGammaMassOfflineSgn"; nameHistoBkg="histGammaMassOfflineBkg"; titleHistoSgn="m_{inv}(e^{+},e^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(e^{+},e^{-}) [GeV/c^{2}]; Entries"; titleHistoBkg="m_{inv}(e^{+},e^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; m_{inv}(e^{+},e^{-}) [GeV/c^{2}]; Entries"; TH2F* massGammaOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,100,0.,1.); TH2F* massGammaOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,100,0.,1.); nameHistoSgn="histD0K0SOfflineSgn"; nameHistoBkg="histD0K0SOfflineBkg"; titleHistoSgn="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; titleHistoBkg="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; TH2F* d0K0SOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0K0SOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgn="histD0POfflineSgn"; nameHistoBkg="histD0POfflineBkg"; titleHistoSgn="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; titleHistoBkg="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; TH2F* d0POfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0POfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgn="histCosPAK0SOfflineSgn"; nameHistoBkg="histCosPAK0SOfflineBkg"; titleHistoSgn="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoBkg="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosPAK0SOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,100,0.99,1.); TH2F *cosPAK0SOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,100,0.99,1.); nameHistoSgn="histCosThetaProtonCMSOfflineSgn"; nameHistoBkg="histCosThetaProtonCMSOfflineBkg"; titleHistoSgn="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoBkg="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosThePrOfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,100,-1.,1.); TH2F *cosThePrOfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,100,-1.,1.); nameHistoSgn="histResignedD0OfflineSgn"; nameHistoBkg="histResignedD0OfflineBkg"; titleHistoSgn="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; titleHistoBkg="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; TH2F *resignedD0OfflineSgn = new TH2F(nameHistoSgn.Data(),titleHistoSgn.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F *resignedD0OfflineBkg = new TH2F(nameHistoBkg.Data(),titleHistoBkg.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F* allptK0SOfflineSgn = (TH2F*)ptK0SOfflineSgn->Clone(); TH2F* allptK0SOfflineBkg = (TH2F*)ptK0SOfflineBkg->Clone(); TH2F* allptPOfflineSgn = (TH2F*)ptPOfflineSgn->Clone(); TH2F* allptPOfflineBkg = (TH2F*)ptPOfflineBkg->Clone(); TH2F* allptPiPOfflineSgn = (TH2F*)ptPiPOfflineSgn->Clone(); TH2F* allptPiPOfflineBkg = (TH2F*)ptPiPOfflineBkg->Clone(); TH2F* allptPiMOfflineSgn = (TH2F*)ptPiMOfflineSgn->Clone(); TH2F* allptPiMOfflineBkg = (TH2F*)ptPiMOfflineBkg->Clone(); TH2F* allmassLambdaOfflineSgn = (TH2F*)massLambdaOfflineSgn->Clone(); TH2F* allmassLambdaOfflineBkg = (TH2F*)massLambdaOfflineBkg->Clone(); TH2F* allmassLambdaBarOfflineSgn = (TH2F*)massLambdaBarOfflineSgn->Clone(); TH2F* allmassLambdaBarOfflineBkg = (TH2F*)massLambdaBarOfflineBkg->Clone(); TH2F* allmassGammaOfflineSgn = (TH2F*)massGammaOfflineSgn->Clone(); TH2F* allmassGammaOfflineBkg = (TH2F*)massGammaOfflineBkg->Clone(); TH2F* alld0K0SOfflineSgn = (TH2F*)d0K0SOfflineSgn->Clone(); TH2F* alld0K0SOfflineBkg = (TH2F*)d0K0SOfflineBkg->Clone(); TH2F* alld0POfflineSgn = (TH2F*)d0POfflineSgn->Clone(); TH2F* alld0POfflineBkg = (TH2F*)d0POfflineBkg->Clone(); TH2F* allcosPAK0SOfflineSgn = (TH2F*)cosPAK0SOfflineSgn->Clone(); TH2F* allcosPAK0SOfflineBkg = (TH2F*)cosPAK0SOfflineBkg->Clone(); TH2F* allcosThePrOfflineSgn = (TH2F*)cosThePrOfflineSgn->Clone(); TH2F* allcosThePrOfflineBkg = (TH2F*)cosThePrOfflineBkg->Clone(); TH2F* allresignedD0OfflineSgn = (TH2F*)resignedD0OfflineSgn->Clone(); TH2F* allresignedD0OfflineBkg = (TH2F*)resignedD0OfflineBkg->Clone(); TH2F* pidptK0SOfflineSgn = (TH2F*)ptK0SOfflineSgn->Clone(); TH2F* pidptK0SOfflineBkg = (TH2F*)ptK0SOfflineBkg->Clone(); TH2F* pidptPOfflineSgn = (TH2F*)ptPOfflineSgn->Clone(); TH2F* pidptPOfflineBkg = (TH2F*)ptPOfflineBkg->Clone(); TH2F* pidptPiPOfflineSgn = (TH2F*)ptPiPOfflineSgn->Clone(); TH2F* pidptPiPOfflineBkg = (TH2F*)ptPiPOfflineBkg->Clone(); TH2F* pidptPiMOfflineSgn = (TH2F*)ptPiMOfflineSgn->Clone(); TH2F* pidptPiMOfflineBkg = (TH2F*)ptPiMOfflineBkg->Clone(); TH2F* pidmassLambdaOfflineSgn = (TH2F*)massLambdaOfflineSgn->Clone(); TH2F* pidmassLambdaOfflineBkg = (TH2F*)massLambdaOfflineBkg->Clone(); TH2F* pidmassLambdaBarOfflineSgn = (TH2F*)massLambdaBarOfflineSgn->Clone(); TH2F* pidmassLambdaBarOfflineBkg = (TH2F*)massLambdaBarOfflineBkg->Clone(); TH2F* pidmassGammaOfflineSgn = (TH2F*)massGammaOfflineSgn->Clone(); TH2F* pidmassGammaOfflineBkg = (TH2F*)massGammaOfflineBkg->Clone(); TH2F* pidd0K0SOfflineSgn = (TH2F*)d0K0SOfflineSgn->Clone(); TH2F* pidd0K0SOfflineBkg = (TH2F*)d0K0SOfflineBkg->Clone(); TH2F* pidd0POfflineSgn = (TH2F*)d0POfflineSgn->Clone(); TH2F* pidd0POfflineBkg = (TH2F*)d0POfflineBkg->Clone(); TH2F* pidcosPAK0SOfflineSgn = (TH2F*)cosPAK0SOfflineSgn->Clone(); TH2F* pidcosPAK0SOfflineBkg = (TH2F*)cosPAK0SOfflineBkg->Clone(); TH2F* pidcosThePrOfflineSgn = (TH2F*)cosThePrOfflineSgn->Clone(); TH2F* pidcosThePrOfflineBkg = (TH2F*)cosThePrOfflineBkg->Clone(); TH2F* pidresignedD0OfflineSgn = (TH2F*)resignedD0OfflineSgn->Clone(); TH2F* pidresignedD0OfflineBkg = (TH2F*)resignedD0OfflineBkg->Clone(); fOutputAll->Add(allptK0SOfflineSgn); fOutputAll->Add(allptK0SOfflineBkg); fOutputAll->Add(allptPOfflineSgn); fOutputAll->Add(allptPOfflineBkg); fOutputAll->Add(allptPiPOfflineSgn); fOutputAll->Add(allptPiPOfflineBkg); fOutputAll->Add(allptPiMOfflineSgn); fOutputAll->Add(allptPiMOfflineBkg); fOutputAll->Add(allmassLambdaOfflineSgn); fOutputAll->Add(allmassLambdaOfflineBkg); fOutputAll->Add(allmassLambdaBarOfflineSgn); fOutputAll->Add(allmassLambdaBarOfflineBkg); fOutputAll->Add(allmassGammaOfflineSgn); fOutputAll->Add(allmassGammaOfflineBkg); fOutputAll->Add(alld0K0SOfflineSgn); fOutputAll->Add(alld0K0SOfflineBkg); fOutputAll->Add(alld0POfflineSgn); fOutputAll->Add(alld0POfflineBkg); fOutputAll->Add(allcosPAK0SOfflineSgn); fOutputAll->Add(allcosPAK0SOfflineBkg); fOutputAll->Add(allcosThePrOfflineSgn); fOutputAll->Add(allcosThePrOfflineBkg); fOutputAll->Add(allresignedD0OfflineSgn); fOutputAll->Add(allresignedD0OfflineBkg); fOutputPIDBach->Add(pidptK0SOfflineSgn); fOutputPIDBach->Add(pidptK0SOfflineBkg); fOutputPIDBach->Add(pidptPOfflineSgn); fOutputPIDBach->Add(pidptPOfflineBkg); fOutputPIDBach->Add(pidptPiPOfflineSgn); fOutputPIDBach->Add(pidptPiPOfflineBkg); fOutputPIDBach->Add(pidptPiMOfflineSgn); fOutputPIDBach->Add(pidptPiMOfflineBkg); fOutputPIDBach->Add(pidmassLambdaOfflineSgn); fOutputPIDBach->Add(pidmassLambdaOfflineBkg); fOutputPIDBach->Add(pidmassLambdaBarOfflineSgn); fOutputPIDBach->Add(pidmassLambdaBarOfflineBkg); fOutputPIDBach->Add(pidmassGammaOfflineSgn); fOutputPIDBach->Add(pidmassGammaOfflineBkg); fOutputPIDBach->Add(pidd0K0SOfflineSgn); fOutputPIDBach->Add(pidd0K0SOfflineBkg); fOutputPIDBach->Add(pidd0POfflineSgn); fOutputPIDBach->Add(pidd0POfflineBkg); fOutputPIDBach->Add(pidcosPAK0SOfflineSgn); fOutputPIDBach->Add(pidcosPAK0SOfflineBkg); fOutputPIDBach->Add(pidcosThePrOfflineSgn); fOutputPIDBach->Add(pidcosThePrOfflineBkg); fOutputPIDBach->Add(pidresignedD0OfflineSgn); fOutputPIDBach->Add(pidresignedD0OfflineBkg); if (fTrackRotation) { TH2F* pidTRptK0SOfflineSgn = (TH2F*)ptK0SOfflineSgn->Clone(); TH2F* pidTRptK0SOfflineBkg = (TH2F*)ptK0SOfflineBkg->Clone(); TH2F* pidTRptPOfflineSgn = (TH2F*)ptPOfflineSgn->Clone(); TH2F* pidTRptPOfflineBkg = (TH2F*)ptPOfflineBkg->Clone(); TH2F* pidTRptPiPOfflineSgn = (TH2F*)ptPiPOfflineSgn->Clone(); TH2F* pidTRptPiPOfflineBkg = (TH2F*)ptPiPOfflineBkg->Clone(); TH2F* pidTRptPiMOfflineSgn = (TH2F*)ptPiMOfflineSgn->Clone(); TH2F* pidTRptPiMOfflineBkg = (TH2F*)ptPiMOfflineBkg->Clone(); TH2F* pidTRmassLambdaOfflineSgn = (TH2F*)massLambdaOfflineSgn->Clone(); TH2F* pidTRmassLambdaOfflineBkg = (TH2F*)massLambdaOfflineBkg->Clone(); TH2F* pidTRmassLambdaBarOfflineSgn = (TH2F*)massLambdaBarOfflineSgn->Clone(); TH2F* pidTRmassLambdaBarOfflineBkg = (TH2F*)massLambdaBarOfflineBkg->Clone(); TH2F* pidTRmassGammaOfflineSgn = (TH2F*)massGammaOfflineSgn->Clone(); TH2F* pidTRmassGammaOfflineBkg = (TH2F*)massGammaOfflineBkg->Clone(); TH2F* pidTRcosPAK0SOfflineSgn = (TH2F*)cosPAK0SOfflineSgn->Clone(); TH2F* pidTRcosPAK0SOfflineBkg = (TH2F*)cosPAK0SOfflineBkg->Clone(); TH2F* pidTRcosThePrOfflineSgn = (TH2F*)cosThePrOfflineSgn->Clone(); TH2F* pidTRcosThePrOfflineBkg = (TH2F*)cosThePrOfflineBkg->Clone(); TH2F* pidTRresignedD0OfflineSgn = (TH2F*)resignedD0OfflineSgn->Clone(); TH2F* pidTRresignedD0OfflineBkg = (TH2F*)resignedD0OfflineBkg->Clone(); fOutputPIDBachTR->Add(pidTRptK0SOfflineSgn); fOutputPIDBachTR->Add(pidTRptK0SOfflineBkg); fOutputPIDBachTR->Add(pidTRptPOfflineSgn); fOutputPIDBachTR->Add(pidTRptPOfflineBkg); fOutputPIDBachTR->Add(pidTRptPiPOfflineSgn); fOutputPIDBachTR->Add(pidTRptPiPOfflineBkg); fOutputPIDBachTR->Add(pidTRptPiMOfflineSgn); fOutputPIDBachTR->Add(pidTRptPiMOfflineBkg); fOutputPIDBachTR->Add(pidTRmassLambdaOfflineSgn); fOutputPIDBachTR->Add(pidTRmassLambdaOfflineBkg); fOutputPIDBachTR->Add(pidTRmassLambdaBarOfflineSgn); fOutputPIDBachTR->Add(pidTRmassLambdaBarOfflineBkg); fOutputPIDBachTR->Add(pidTRmassGammaOfflineSgn); fOutputPIDBachTR->Add(pidTRmassGammaOfflineBkg); fOutputPIDBachTR->Add(pidTRcosPAK0SOfflineSgn); fOutputPIDBachTR->Add(pidTRcosPAK0SOfflineBkg); fOutputPIDBachTR->Add(pidTRcosThePrOfflineSgn); fOutputPIDBachTR->Add(pidTRcosThePrOfflineBkg); fOutputPIDBachTR->Add(pidTRresignedD0OfflineSgn); fOutputPIDBachTR->Add(pidTRresignedD0OfflineBkg); } } // useMCinfo if (fTrackRotation) { TH3F *phiVSthetaVSpt = new TH3F("phiVSthetaVSpt","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptRot = new TH3F("phiVSthetaVSptRot","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptOffline = new TH3F("phiVSthetaVSptOffline","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptRotOffline = new TH3F("phiVSthetaVSptRotOffline","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); fOutputPIDBachTR->Add(phiVSthetaVSpt); fOutputPIDBachTR->Add(phiVSthetaVSptRot); fOutputPIDBachTR->Add(phiVSthetaVSptOffline); fOutputPIDBachTR->Add(phiVSthetaVSptRotOffline); TH1F *hNormRotated=new TH1F("hNormRotated","",fNRotations+1,-0.5,fNRotations+0.5); TH1F *hNormRotatedOffline=new TH1F("hNormRotatedOffline","",fNRotations+1,-0.5,fNRotations+0.5); /* hNormRotated->Sumw2(); hNormRotatedOffline->Sumw2(); hNormRotated->SetMinimum(0); hNormRotatedOffline->SetMinimum(0); */ fOutputPIDBachTR->Add(hNormRotated); fOutputPIDBachTR->Add(hNormRotatedOffline); if (fUseMCInfo) { TH3F *phiVSthetaVSptSgn = new TH3F("phiVSthetaVSptSgn","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptRotSgn = new TH3F("phiVSthetaVSptRotSgn","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptOfflineSgn = new TH3F("phiVSthetaVSptOfflineSgn","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptRotOfflineSgn = new TH3F("phiVSthetaVSptRotOfflineSgn","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); fOutputPIDBachTR->Add(phiVSthetaVSptSgn); fOutputPIDBachTR->Add(phiVSthetaVSptRotSgn); fOutputPIDBachTR->Add(phiVSthetaVSptOfflineSgn); fOutputPIDBachTR->Add(phiVSthetaVSptRotOfflineSgn); TH3F *phiVSthetaVSptBkg = new TH3F("phiVSthetaVSptBkg","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptRotBkg = new TH3F("phiVSthetaVSptRotBkg","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptOfflineBkg = new TH3F("phiVSthetaVSptOfflineBkg","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); TH3F *phiVSthetaVSptRotOfflineBkg = new TH3F("phiVSthetaVSptRotOfflineBkg","",35,0.,35.,360,0.,2.*TMath::Pi(),100,40.*TMath::DegToRad(),140.*TMath::DegToRad()); fOutputPIDBachTR->Add(phiVSthetaVSptBkg); fOutputPIDBachTR->Add(phiVSthetaVSptRotBkg); fOutputPIDBachTR->Add(phiVSthetaVSptOfflineBkg); fOutputPIDBachTR->Add(phiVSthetaVSptRotOfflineBkg); TH1F *hNormRotatedSgn=new TH1F("hNormRotatedSgn","",fNRotations+1,-0.5,fNRotations+0.5); TH1F *hNormRotatedOfflineSgn=new TH1F("hNormRotatedOfflineSgn","",fNRotations+1,-0.5,fNRotations+0.5); TH1F *hNormRotatedBkg=new TH1F("hNormRotatedBkg","",fNRotations+1,-0.5,fNRotations+0.5); TH1F *hNormRotatedOfflineBkg=new TH1F("hNormRotatedOfflineBkg","",fNRotations+1,-0.5,fNRotations+0.5); /* hNormRotatedSgn->Sumw2(); hNormRotatedOfflineSgn->Sumw2(); hNormRotatedBkg->Sumw2(); hNormRotatedOfflineBkg->Sumw2(); hNormRotatedSgn->SetMinimum(0); hNormRotatedOfflineSgn->SetMinimum(0); hNormRotatedBkg->SetMinimum(0); hNormRotatedOfflineBkg->SetMinimum(0); */ fOutputPIDBachTR->Add(hNormRotatedSgn); fOutputPIDBachTR->Add(hNormRotatedOfflineSgn); fOutputPIDBachTR->Add(hNormRotatedBkg); fOutputPIDBachTR->Add(hNormRotatedOfflineBkg); } Int_t nMassBins=(Int_t)(fMaxMass*1000.-fMinMass*1000.); Double_t maxm=fMinMass+nMassBins*0.001; TH3F *hMassVsPtVsY=new TH3F("hMassVsPtVsY","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYOffline=new TH3F("hMassVsPtVsYOffline","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); /* hMassVsPtVsY->Sumw2(); hMassVsPtVsYOffline->Sumw2(); hMassVsPtVsY->SetMinimum(0); hMassVsPtVsYOffline->SetMinimum(0); */ fOutputPIDBachTR->Add(hMassVsPtVsY); fOutputPIDBachTR->Add(hMassVsPtVsYOffline); if (fUseMCInfo) { TH3F *hMassVsPtVsYSgn=new TH3F("hMassVsPtVsYSgn","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYOfflineSgn=new TH3F("hMassVsPtVsYOfflineSgn","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYBkg=new TH3F("hMassVsPtVsYBkg","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYOfflineBkg=new TH3F("hMassVsPtVsYOfflineBkg","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); /* hMassVsPtVsYSgn->Sumw2(); hMassVsPtVsYOfflineSgn->Sumw2(); hMassVsPtVsYBkg->Sumw2(); hMassVsPtVsYOfflineBkg->Sumw2(); hMassVsPtVsYSgn->SetMinimum(0); hMassVsPtVsYOfflineSgn->SetMinimum(0); hMassVsPtVsYBkg->SetMinimum(0); hMassVsPtVsYOfflineBkg->SetMinimum(0); */ fOutputPIDBachTR->Add(hMassVsPtVsYSgn); fOutputPIDBachTR->Add(hMassVsPtVsYOfflineSgn); fOutputPIDBachTR->Add(hMassVsPtVsYBkg); fOutputPIDBachTR->Add(hMassVsPtVsYOfflineBkg); } TH3F *hMassVsPtVsYRot=new TH3F("hMassVsPtVsYRot","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYRotOffline=new TH3F("hMassVsPtVsYRotOffline","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); /* hMassVsPtVsYRot->Sumw2(); hMassVsPtVsYRotOffline->Sumw2(); hMassVsPtVsYRot->SetMinimum(0); hMassVsPtVsYRotOffline->SetMinimum(0); */ fOutputPIDBachTR->Add(hMassVsPtVsYRot); fOutputPIDBachTR->Add(hMassVsPtVsYRotOffline); if (fUseMCInfo) { TH3F *hMassVsPtVsYRotSgn=new TH3F("hMassVsPtVsYRotSgn","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYRotOfflineSgn=new TH3F("hMassVsPtVsYRotOfflineSgn","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYRotBkg=new TH3F("hMassVsPtVsYRotBkg","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); TH3F *hMassVsPtVsYRotOfflineBkg=new TH3F("hMassVsPtVsYRotOfflineBkg","",nMassBins,fMinMass,maxm,15,0.,15.,20,-1.,1.); /* hMassVsPtVsYRotSgn->Sumw2(); hMassVsPtVsYRotOfflineSgn->Sumw2(); hMassVsPtVsYRotBkg->Sumw2(); hMassVsPtVsYRotOfflineBkg->Sumw2(); hMassVsPtVsYRotSgn->SetMinimum(0); hMassVsPtVsYRotOfflineSgn->SetMinimum(0); hMassVsPtVsYRotBkg->SetMinimum(0); hMassVsPtVsYRotOfflineBkg->SetMinimum(0); */ fOutputPIDBachTR->Add(hMassVsPtVsYRotSgn); fOutputPIDBachTR->Add(hMassVsPtVsYRotOfflineSgn); fOutputPIDBachTR->Add(hMassVsPtVsYRotBkg); fOutputPIDBachTR->Add(hMassVsPtVsYRotOfflineBkg); } TH1F *hDeltaMass=new TH1F("hDeltaMass","",100,-0.4,0.4); TH1F *hDeltaMassOffline=new TH1F("hDeltaMassOffline","",100,-0.4,0.4); /* hDeltaMass->Sumw2(); hDeltaMassOffline->Sumw2(); hDeltaMass->SetMinimum(0); hDeltaMassOffline->SetMinimum(0); */ fOutputPIDBachTR->Add(hDeltaMass); fOutputPIDBachTR->Add(hDeltaMassOffline); if (fUseMCInfo) { TH1F *hDeltaMassSgn=new TH1F("hDeltaMassSgn","",100,-0.4,0.4); TH1F *hDeltaMassOfflineSgn=new TH1F("hDeltaMassOfflineSgn","",100,-0.4,0.4); TH1F *hDeltaMassBkg=new TH1F("hDeltaMassBkg","",100,-0.4,0.4); TH1F *hDeltaMassOfflineBkg=new TH1F("hDeltaMassOfflineBkg","",100,-0.4,0.4); /* hDeltaMassSgn->Sumw2(); hDeltaMassOfflineSgn->Sumw2(); hDeltaMassBkg->Sumw2(); hDeltaMassOfflineBkg->Sumw2(); hDeltaMassSgn->SetMinimum(0); hDeltaMassOfflineSgn->SetMinimum(0); hDeltaMassBkg->SetMinimum(0); hDeltaMassOfflineBkg->SetMinimum(0); */ fOutputPIDBachTR->Add(hDeltaMassSgn); fOutputPIDBachTR->Add(hDeltaMassOfflineSgn); fOutputPIDBachTR->Add(hDeltaMassBkg); fOutputPIDBachTR->Add(hDeltaMassOfflineBkg); } /* Int_t binSparseDMassRot[5]={nMassBins,100,24,40,20}; Double_t edgeLowSparseDMassRot[5]={fMinMass,-0.4,0.,-4.,0}; Double_t edgeHighSparseDMassRot[5]={maxm,0.4,12.,4.,3.14}; THnSparse *hDeltaMassFullAnalysis=new THnSparseF("hDeltaMassFullAnalysis","hDeltaMassFullAnalysis;inv mass (GeV/c);#Delta inv mass (GeV/c); p_{T}^{#Lambda_{c}} (GeV/c); #Delta p_{T} (GeV/c); daughter angle (2prongs) (rad);",5,binSparseDMassRot,edgeLowSparseDMassRot,edgeHighSparseDMassRot); THnSparse *hDeltaMassFullAnalysisOffline=new THnSparseF("fDeltaMassFullAnalysisOffline","hDeltaMassFullAnalysisOffline;inv mass (GeV/c);#Delta inv mass (GeV/c); p_{T}^{#Lambda_{c}} (GeV/c); #Delta p_{T} (GeV/c); daughter angle (2prongs) (rad);",5,binSparseDMassRot,edgeLowSparseDMassRot,edgeHighSparseDMassRot); fOutputPIDBachTR->Add(hDeltaMassFullAnalysis); fOutputPIDBachTR->Add(hDeltaMassFullAnalysisOffline); if (fUseMCInfo) { THnSparse *hDeltaMassFullAnalysisSgn=new THnSparseF("hDeltaMassFullAnalysisSgn","hDeltaMassFullAnalysisSgn;inv mass (GeV/c);#Delta inv mass (GeV/c); p_{T}^{#Lambda_{c}} (GeV/c); #Delta p_{T} (GeV/c); daughter angle (2prongs) (rad);",5,binSparseDMassRot,edgeLowSparseDMassRot,edgeHighSparseDMassRot); THnSparse *hDeltaMassFullAnalysisOfflineSgn=new THnSparseF("fDeltaMassFullAnalysisOfflineSgn","hDeltaMassFullAnalysisOfflineSgn;inv mass (GeV/c);#Delta inv mass (GeV/c); p_{T}^{#Lambda_{c}} (GeV/c); #Delta p_{T} (GeV/c); daughter angle (2prongs) (rad);",5,binSparseDMassRot,edgeLowSparseDMassRot,edgeHighSparseDMassRot); THnSparse *hDeltaMassFullAnalysisBkg=new THnSparseF("hDeltaMassFullAnalysisBkg","hDeltaMassFullAnalysisBkg;inv mass (GeV/c);#Delta inv mass (GeV/c); p_{T}^{#Lambda_{c}} (GeV/c); #Delta p_{T} (GeV/c); daughter angle (2prongs) (rad);",5,binSparseDMassRot,edgeLowSparseDMassRot,edgeHighSparseDMassRot); THnSparse *hDeltaMassFullAnalysisOfflineBkg=new THnSparseF("fDeltaMassFullAnalysisOfflineBkg","hDeltaMassFullAnalysisOfflineBkg;inv mass (GeV/c);#Delta inv mass (GeV/c); p_{T}^{#Lambda_{c}} (GeV/c); #Delta p_{T} (GeV/c); daughter angle (2prongs) (rad);",5,binSparseDMassRot,edgeLowSparseDMassRot,edgeHighSparseDMassRot); fOutputPIDBachTR->Add(hDeltaMassFullAnalysisSgn); fOutputPIDBachTR->Add(hDeltaMassFullAnalysisOfflineSgn); fOutputPIDBachTR->Add(hDeltaMassFullAnalysisBkg); fOutputPIDBachTR->Add(hDeltaMassFullAnalysisOfflineBkg); } */ } if(fDoSingleAnalysisForSystK0SP){ TH2D *hMassvsPtInclusiveK0S = new TH2D("hMassvsPtInclusiveK0S","",100,mK0SPDG-0.05,mK0SPDG+0.05,20,0.,10.); TH2D *hMassvsPtInclusiveK0SSgn = new TH2D("hMassvsPtInclusiveK0SSgn","",100,mK0SPDG-0.05,mK0SPDG+0.05,20,0.,10.); TH3D *hMassvsPtInclusiveLambda = new TH3D("hMassvsPtInclusiveLambda","",100,mLPDG-0.025,mLPDG+0.025,20,0.,10.,62,0.,62); TH3D *hMassvsPtInclusiveLambdaLoosePID = new TH3D("hMassvsPtInclusiveLambdaLoosePID","",100,mLPDG-0.025,mLPDG+0.025,20,0.,10.,62,0.,62); TH3D *hMassvsPtInclusiveLambdaSgn = new TH3D("hMassvsPtInclusiveLambdaSgn","",100,mLPDG-0.025,mLPDG+0.025,20,0.,10.,62,0.,62); TH3D *hMassvsPtInclusiveLambdaLoosePIDSgn = new TH3D("hMassvsPtInclusiveLambdaLoosePIDSgn","",100,mLPDG-0.025,mLPDG+0.025,20,0.,10.,62,0.,62); TH3D *hMassvsPtInclusiveLambdaPID = (TH3D*)hMassvsPtInclusiveLambda->Clone(); TH3D *hMassvsPtInclusiveLambdaPIDSgn = (TH3D*)hMassvsPtInclusiveLambdaSgn->Clone(); TH3D *hMassvsPtInclusiveLambdaCosThetaStarPID = new TH3D("hMassvsPtInclusiveLambdaCosThetaStarPID","",100,mLPDG-0.025,mLPDG+0.025,20,0.,10.,40,-1.,1.); TH3D *hMassvsPtInclusiveLambdaCosThetaStarPIDSgn = new TH3D("hMassvsPtInclusiveLambdaCosThetaStarPIDSgn","",100,mLPDG-0.025,mLPDG+0.025,20,0.,10.,40,-1.,1.); fOutputAll->Add(hMassvsPtInclusiveK0S); fOutputAll->Add(hMassvsPtInclusiveK0SSgn); fOutputAll->Add(hMassvsPtInclusiveLambda); fOutputAll->Add(hMassvsPtInclusiveLambdaLoosePID); fOutputPIDBach->Add(hMassvsPtInclusiveLambdaPID); fOutputAll->Add(hMassvsPtInclusiveLambdaSgn); fOutputAll->Add(hMassvsPtInclusiveLambdaLoosePIDSgn); fOutputPIDBach->Add(hMassvsPtInclusiveLambdaPIDSgn); fOutputPIDBach->Add(hMassvsPtInclusiveLambdaCosThetaStarPID); fOutputPIDBach->Add(hMassvsPtInclusiveLambdaCosThetaStarPIDSgn); } /* fOutputAll->Print(); fOutputPIDBach->Print(); if (fTrackRotation) fOutputPIDBachTR->Print(); */ return; } //------------------------------------------------------------------------------- void AliAnalysisTaskSELc2V0bachelor::MakeSingleAnalysisForSystK0SP(AliAODEvent *aodEvent, TClonesArray *mcArray, AliRDHFCutsLctoV0 *cutsAnal) { // // make single analysis for the systematics studies // 1: Inclusive K0s (Tracking, K0S cut variation) // 2: Proton from Lambda (PID, Tracking TPC(not yet)) // Double_t mLPDG = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); //Int_t nTracks = aodEvent->GetNumberOfTracks(); Int_t nV0s = aodEvent->GetNumberOfV0s(); Double_t pos[3]; fVtx1->GetXYZ(pos); Double_t cov[6]; fVtx1->GetCovarianceMatrix(cov); const AliESDVertex vESD(pos,cov,100.,100); AliESDtrackCuts *trkCuts = fAnalCuts->GetTrackCuts(); AliESDtrackCuts *v0trkCuts = fAnalCuts->GetTrackCutsV0daughters(); const Float_t *cutVars = fAnalCuts->GetCuts(); //1: Inclusive K0s for (Int_t iv0 = 0; iv0<nV0s; iv0++) { AliAODv0 *v0 = aodEvent->GetV0(iv0); if(!v0) continue; AliAODTrack *ptrk = dynamic_cast<AliAODTrack*>(v0->GetDaughter(0)); if (!ptrk) continue; AliAODTrack *ntrk = dynamic_cast<AliAODTrack*>(v0->GetDaughter(1)); if (!ntrk) continue; Float_t etaMin=0, etaMax=0; v0trkCuts->GetEtaRange(etaMin,etaMax); if ( (ptrk->Eta()<=etaMin || ptrk->Eta()>=etaMax) || (ntrk->Eta()<=etaMin || ntrk->Eta()>=etaMax) ) continue; Float_t ptMin=0, ptMax=0; v0trkCuts->GetPtRange(ptMin,ptMax); if ( (ptrk->Pt()<=ptMin || ptrk->Pt()>=ptMax) || (ntrk->Pt()<=ptMin || ntrk->Pt()>=ptMax) ) continue; // Condition on nTPCclusters if (v0trkCuts->GetMinNClusterTPC()>0) { if ( ( ( ptrk->GetTPCClusterInfo(2,1) ) < v0trkCuts->GetMinNClusterTPC() ) || ( ( ntrk->GetTPCClusterInfo(2,1) ) < v0trkCuts->GetMinNClusterTPC() ) ) continue; } if (v0trkCuts->GetMinRatioCrossedRowsOverFindableClustersTPC()>0.5) { Float_t ratioCrossedRowsOverFindableClustersTPCPos = 1.0; Float_t ratioCrossedRowsOverFindableClustersTPCNeg = 1.0; if (ptrk->GetTPCNclsF()>0) { ratioCrossedRowsOverFindableClustersTPCPos = ptrk->GetTPCClusterInfo(2,1) / ptrk->GetTPCNclsF(); } if (ntrk->GetTPCNclsF()>0) { ratioCrossedRowsOverFindableClustersTPCNeg = ntrk->GetTPCClusterInfo(2,1) / ntrk->GetTPCNclsF(); } if ( ( ( ratioCrossedRowsOverFindableClustersTPCPos ) < v0trkCuts->GetMinRatioCrossedRowsOverFindableClustersTPC() ) || ( ( ratioCrossedRowsOverFindableClustersTPCNeg ) < v0trkCuts->GetMinRatioCrossedRowsOverFindableClustersTPC() ) ) continue; } // kTPCrefit status if (v0->GetOnFlyStatus()==kFALSE) { // only for offline V0s if (v0trkCuts->GetRequireTPCRefit()) { if( !(ptrk->GetStatus() & AliESDtrack::kTPCrefit)) continue; if( !(ntrk->GetStatus() & AliESDtrack::kTPCrefit)) continue; } } AliESDtrack esdTrackP(ptrk); esdTrackP.SetTPCClusterMap(ptrk->GetTPCClusterMap()); esdTrackP.SetTPCSharedMap(ptrk->GetTPCSharedMap()); esdTrackP.SetTPCPointsF(ptrk->GetTPCNclsF()); esdTrackP.RelateToVertex(&vESD,0.,3.); AliESDtrack esdTrackN(ntrk); esdTrackN.SetTPCClusterMap(ntrk->GetTPCClusterMap()); esdTrackN.SetTPCSharedMap(ntrk->GetTPCSharedMap()); esdTrackN.SetTPCPointsF(ntrk->GetTPCNclsF()); esdTrackN.RelateToVertex(&vESD,0.,3.); //appliyng TPC crossed rows pT dependent cut TString tmptxt(fAnalCuts->GetMinCrossedRowsTPCPtDep()); if(tmptxt.Contains("pt")){ tmptxt.ReplaceAll("pt","x"); TF1 funcCutMin("funcCutMin",tmptxt); Float_t nCrossedRowsTPCP = esdTrackP.GetTPCCrossedRows(); Float_t nCrossedRowsTPCN = esdTrackN.GetTPCCrossedRows(); if(nCrossedRowsTPCP<funcCutMin.Eval(esdTrackP.Pt())) continue; if(nCrossedRowsTPCN<funcCutMin.Eval(esdTrackN.Pt())) continue; } //appliyng NTPCcls/NTPCcrossedRows cut if(fAnalCuts->GetMinRatioClsOverCrossRowsTPC()>0){ Float_t nCrossedRowsTPCP = esdTrackP.GetTPCCrossedRows(); Float_t nCrossedRowsTPCN = esdTrackN.GetTPCCrossedRows(); Float_t nClustersTPCP = esdTrackP.GetTPCNcls(); Float_t nClustersTPCN = esdTrackN.GetTPCNcls(); if(nCrossedRowsTPCP!=0){ Float_t ratioP = nClustersTPCP/nCrossedRowsTPCP; if(ratioP<fAnalCuts->GetMinRatioClsOverCrossRowsTPC()) continue; } else continue; if(nCrossedRowsTPCN!=0){ Float_t ratioN = nClustersTPCN/nCrossedRowsTPCN; if(ratioN<fAnalCuts->GetMinRatioClsOverCrossRowsTPC()) continue; } else continue; } //appliyng TPCsignalN/NTPCcrossedRows cut if(fAnalCuts->GetMinRatioSignalNOverCrossRowsTPC()>0){ Float_t nCrossedRowsTPCP = esdTrackP.GetTPCCrossedRows(); Float_t nCrossedRowsTPCN = esdTrackN.GetTPCCrossedRows(); Float_t nTPCsignalP = esdTrackP.GetTPCsignalN(); Float_t nTPCsignalN = esdTrackN.GetTPCsignalN(); if(nCrossedRowsTPCP!=0){ Float_t ratioP = nTPCsignalP/nCrossedRowsTPCP; if(ratioP<fAnalCuts->GetMinRatioSignalNOverCrossRowsTPC()) continue; } else continue; if(nCrossedRowsTPCN!=0){ Float_t ratioN = nTPCsignalN/nCrossedRowsTPCN; if(ratioN<fAnalCuts->GetMinRatioSignalNOverCrossRowsTPC()) continue; } else continue; } // kink condition if (!v0trkCuts->GetAcceptKinkDaughters()) { AliAODVertex *maybeKinkPos = (AliAODVertex*)ptrk->GetProdVertex(); AliAODVertex *maybeKinkNeg = (AliAODVertex*)ntrk->GetProdVertex(); if (maybeKinkPos->GetType()==AliAODVertex::kKink || maybeKinkNeg->GetType()==AliAODVertex::kKink) continue; } //RDHF cuts if(ptrk->Pt()<cutVars[fAnalCuts->GetGlobalIndex(5,0)] || ntrk->Pt()<cutVars[fAnalCuts->GetGlobalIndex(6,0)]) continue; if(v0->GetDCA()>cutVars[fAnalCuts->GetGlobalIndex(8,0)]) continue; if(v0->CosPointingAngle(pos)<cutVars[fAnalCuts->GetGlobalIndex(9,0)]) continue; if(v0->DcaV0ToPrimVertex()>cutVars[fAnalCuts->GetGlobalIndex(11,0)]) continue; if((v0->PtArmV0()/TMath::Abs(v0->AlphaV0())<cutVars[fAnalCuts->GetGlobalIndex(19,0)])) continue; if(TMath::Abs(v0->MassLambda()-mLPDG) < cutVars[fAnalCuts->GetGlobalIndex(13,0)]) continue; if(TMath::Abs(v0->MassAntiLambda()-mLPDG) < cutVars[fAnalCuts->GetGlobalIndex(13,0)]) continue; if(v0->InvMass2Prongs(0,1,11,11) < cutVars[fAnalCuts->GetGlobalIndex(13,0)]) continue; ((TH2D*)(fOutputAll->FindObject("hMassvsPtInclusiveK0S")))->Fill(v0->MassK0Short(),v0->Pt()); if(fUseMCInfo){ Int_t pdgdgv0[2]={211,211}; Int_t labV0 = v0->MatchToMC(310,mcArray,2,pdgdgv0); // the V0 if(labV0>=0){ AliAODMCParticle *mcv0 = (AliAODMCParticle*) mcArray->At(labV0); if(mcv0){ ((TH2D*)(fOutputAll->FindObject("hMassvsPtInclusiveK0SSgn")))->Fill(v0->MassK0Short(),v0->Pt()); } } } } //2: Proton from Lambda for (Int_t iv0 = 0; iv0<nV0s; iv0++) { AliAODv0 *v0 = aodEvent->GetV0(iv0); if(!v0) continue; AliAODTrack *ptrk = dynamic_cast<AliAODTrack*>(v0->GetDaughter(0)); if (!ptrk) continue; AliAODTrack *ntrk = dynamic_cast<AliAODTrack*>(v0->GetDaughter(1)); if (!ntrk) continue; Float_t etaMin=0, etaMax=0; trkCuts->GetEtaRange(etaMin,etaMax); if ( (ptrk->Eta()<=etaMin || ptrk->Eta()>=etaMax) || (ntrk->Eta()<=etaMin || ntrk->Eta()>=etaMax) ) continue; Float_t ptMin=0, ptMax=0; trkCuts->GetPtRange(ptMin,ptMax); if ( (ptrk->Pt()<=ptMin || ptrk->Pt()>=ptMax) || (ntrk->Pt()<=ptMin || ntrk->Pt()>=ptMax) ) continue; // kTPCrefit status if (v0->GetOnFlyStatus()==kFALSE) { // only for offline V0s if (trkCuts->GetRequireTPCRefit()) { if( !(ptrk->GetStatus() & AliESDtrack::kTPCrefit)) continue; if( !(ntrk->GetStatus() & AliESDtrack::kTPCrefit)) continue; } } // kink condition if (!trkCuts->GetAcceptKinkDaughters()) { AliAODVertex *maybeKinkPos = (AliAODVertex*)ptrk->GetProdVertex(); AliAODVertex *maybeKinkNeg = (AliAODVertex*)ntrk->GetProdVertex(); if (maybeKinkPos->GetType()==AliAODVertex::kKink || maybeKinkNeg->GetType()==AliAODVertex::kKink) continue; } //Should decay before TPC Double_t dR = TMath::Sqrt(v0->DecayVertexV0X()*v0->DecayVertexV0X()+v0->DecayVertexV0Y()*v0->DecayVertexV0Y()); if(dR>40.) continue; if(dR<2.) continue; //Use the topological cuts for K0s to improve S/B if(v0->GetDCA()>cutVars[fAnalCuts->GetGlobalIndex(8,0)]) continue; if(v0->CosPointingAngle(pos)<cutVars[fAnalCuts->GetGlobalIndex(9,0)]) continue; Int_t LType = 0; if(TMath::Abs(v0->MassLambda()-mLPDG)<0.02) LType += 1; if(TMath::Abs(v0->MassAntiLambda()-mLPDG)<0.02) LType += 2; if(LType==3) continue;//to avoid complexity AliAODMCParticle *mcv0 = 0x0; if(fUseMCInfo){ Int_t pdgdgv0[2]={2212,211}; Int_t labV0 = v0->MatchToMC(3122,mcArray,2,pdgdgv0); // the V0 if(labV0>=0){ mcv0 = (AliAODMCParticle*) mcArray->At(labV0); } } AliESDtrack esdTrackP(ptrk); esdTrackP.SetTPCClusterMap(ptrk->GetTPCClusterMap()); esdTrackP.SetTPCSharedMap(ptrk->GetTPCSharedMap()); esdTrackP.SetTPCPointsF(ptrk->GetTPCNclsF()); esdTrackP.RelateToVertex(&vESD,0.,3.); AliESDtrack esdTrackN(ntrk); esdTrackN.SetTPCClusterMap(ntrk->GetTPCClusterMap()); esdTrackN.SetTPCSharedMap(ntrk->GetTPCSharedMap()); esdTrackN.SetTPCPointsF(ntrk->GetTPCNclsF()); esdTrackN.RelateToVertex(&vESD,0.,3.); // Condition on nTPCclusters if (trkCuts->GetMinNClusterTPC()>0) { if(LType==1){ if ( ( ( ptrk->GetTPCClusterInfo(2,1) ) < trkCuts->GetMinNClusterTPC() ) || ( ( ntrk->GetTPCClusterInfo(2,1) ) < 70 ) ) continue; } if(LType==2){ if ( ( ( ntrk->GetTPCClusterInfo(2,1) ) < trkCuts->GetMinNClusterTPC() ) || ( ( ptrk->GetTPCClusterInfo(2,1) ) < 70 ) ) continue; } } if (trkCuts->GetMinRatioCrossedRowsOverFindableClustersTPC()>0.5) { Float_t ratioCrossedRowsOverFindableClustersTPCPos = 1.0; Float_t ratioCrossedRowsOverFindableClustersTPCNeg = 1.0; if (ptrk->GetTPCNclsF()>0) { ratioCrossedRowsOverFindableClustersTPCPos = ptrk->GetTPCClusterInfo(2,1) / ptrk->GetTPCNclsF(); } if (ntrk->GetTPCNclsF()>0) { ratioCrossedRowsOverFindableClustersTPCNeg = ntrk->GetTPCClusterInfo(2,1) / ntrk->GetTPCNclsF(); } if(LType==1){ if ( ( ( ratioCrossedRowsOverFindableClustersTPCPos ) < trkCuts->GetMinRatioCrossedRowsOverFindableClustersTPC() ) || ( ( ratioCrossedRowsOverFindableClustersTPCNeg ) < 0.8 ) ) continue; } if(LType==2){ if ( ( ( ratioCrossedRowsOverFindableClustersTPCNeg ) < trkCuts->GetMinRatioCrossedRowsOverFindableClustersTPC() ) || ( ( ratioCrossedRowsOverFindableClustersTPCPos ) < 0.8 ) ) continue; } } //appliyng TPC crossed rows pT dependent cut TString tmptxt(fAnalCuts->GetMinCrossedRowsTPCPtDep()); if(tmptxt.Contains("pt")){ tmptxt.ReplaceAll("pt","x"); TF1 funcCutMin("funcCutMin",tmptxt); Float_t nCrossedRowsTPCP = esdTrackP.GetTPCCrossedRows(); Float_t nCrossedRowsTPCN = esdTrackN.GetTPCCrossedRows(); if(LType==1 && nCrossedRowsTPCP<funcCutMin.Eval(esdTrackP.Pt())) continue; if(LType==2 && nCrossedRowsTPCN<funcCutMin.Eval(esdTrackN.Pt())) continue; } //appliyng NTPCcls/NTPCcrossedRows cut if(fAnalCuts->GetMinRatioClsOverCrossRowsTPC()>0){ Float_t nCrossedRowsTPCP = esdTrackP.GetTPCCrossedRows(); Float_t nCrossedRowsTPCN = esdTrackN.GetTPCCrossedRows(); Float_t nClustersTPCP = esdTrackP.GetTPCNcls(); Float_t nClustersTPCN = esdTrackN.GetTPCNcls(); if(LType==1){ if(nCrossedRowsTPCP!=0){ Float_t ratioP = nClustersTPCP/nCrossedRowsTPCP; if(ratioP<fAnalCuts->GetMinRatioClsOverCrossRowsTPC()) continue; } else continue; } if(LType==2){ if(nCrossedRowsTPCN!=0){ Float_t ratioN = nClustersTPCN/nCrossedRowsTPCN; if(ratioN<fAnalCuts->GetMinRatioClsOverCrossRowsTPC()) continue; } else continue; } } //appliyng TPCsignalN/NTPCcrossedRows cut if(fAnalCuts->GetMinRatioSignalNOverCrossRowsTPC()>0){ Float_t nCrossedRowsTPCP = esdTrackP.GetTPCCrossedRows(); Float_t nCrossedRowsTPCN = esdTrackN.GetTPCCrossedRows(); Float_t nTPCsignalP = esdTrackP.GetTPCsignalN(); Float_t nTPCsignalN = esdTrackN.GetTPCsignalN(); if(LType==1){ if(nCrossedRowsTPCP!=0){ Float_t ratioP = nTPCsignalP/nCrossedRowsTPCP; if(ratioP<fAnalCuts->GetMinRatioSignalNOverCrossRowsTPC()) continue; } else continue; } if(LType==2){ if(nCrossedRowsTPCN!=0){ Float_t ratioN = nTPCsignalN/nCrossedRowsTPCN; if(ratioN<fAnalCuts->GetMinRatioSignalNOverCrossRowsTPC()) continue; } else continue; } } if(LType==1){ Double_t nTPCsigmas=-9999, nTOFsigmas=-9999; fAnalCuts->GetPidHF()->GetnSigmaTPC(ptrk,4,nTPCsigmas); fAnalCuts->GetPidHF()->GetnSigmaTOF(ptrk,4,nTOFsigmas); Bool_t PIDOK=kFALSE; switch(fAnalCuts->GetPidSelectionFlag()){ case 10: if(TMath::Abs(nTPCsigmas)<3. && TMath::Abs(nTOFsigmas)<3.){ PIDOK = !(ptrk->Pt()>fAnalCuts->GetLowPtCut()&& nTOFsigmas<-2.)&&!(ptrk->Pt()>fAnalCuts->GetLowPtCut()&&nTPCsigmas>2.); } break; } ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambda")))->Fill(v0->MassLambda(),ptrk->Pt(),dR); if(TMath::Abs(nTPCsigmas)<5&&TMath::Abs(nTOFsigmas)<5){ ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambdaLoosePID")))->Fill(v0->MassLambda(),ptrk->Pt(),dR); } Double_t bachcosthe = -9999; if(PIDOK){ ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambda")))->Fill(v0->MassLambda(),ptrk->Pt(),dR); TLorentzVector vpr, vpi,vlam; vpr.SetXYZM(ptrk->Px(),ptrk->Py(),ptrk->Pz(),0.938272081); vpi.SetXYZM(ntrk->Px(),ntrk->Py(),ntrk->Pz(),0.13957061); vlam = vpr + vpi; TVector3 vboost = vlam.BoostVector(); vpr.Boost(-vboost); bachcosthe = cos(vpr.Angle(vlam.Vect())); ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambdaCosThetaStarPID")))->Fill(v0->MassLambda(),ptrk->Pt(),bachcosthe); } if(fUseMCInfo && mcv0){ ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambdaSgn")))->Fill(v0->MassLambda(),ptrk->Pt(),dR); if(TMath::Abs(nTPCsigmas)<5&&TMath::Abs(nTOFsigmas)<5){ ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambdaLoosePIDSgn")))->Fill(v0->MassLambda(),ptrk->Pt(),dR); } if(PIDOK){ ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambdaSgn")))->Fill(v0->MassLambda(),ptrk->Pt(),dR); ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambdaCosThetaStarPIDSgn")))->Fill(v0->MassLambda(),ptrk->Pt(),bachcosthe); } } } if(LType==2){ Double_t nTPCsigmas=-9999, nTOFsigmas=-9999; fAnalCuts->GetPidHF()->GetnSigmaTPC(ntrk,4,nTPCsigmas); fAnalCuts->GetPidHF()->GetnSigmaTOF(ntrk,4,nTOFsigmas); Bool_t PIDOK=kFALSE; switch(fAnalCuts->GetPidSelectionFlag()){ case 10: if(TMath::Abs(nTPCsigmas)<3. && TMath::Abs(nTOFsigmas)<3.){ PIDOK = !(ptrk->Pt()>fAnalCuts->GetLowPtCut()&& nTOFsigmas<-2.)&&!(ptrk->Pt()>fAnalCuts->GetLowPtCut()&&nTPCsigmas>2.); } break; } ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambda")))->Fill(v0->MassAntiLambda(),ntrk->Pt(),dR); if(TMath::Abs(nTPCsigmas)<5&&TMath::Abs(nTOFsigmas)<5){ ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambdaLoosePID")))->Fill(v0->MassAntiLambda(),ntrk->Pt(),dR); } Double_t bachcosthe = -9999; if(PIDOK){ ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambda")))->Fill(v0->MassAntiLambda(),ntrk->Pt(),dR); TLorentzVector vpr, vpi,vlam; vpr.SetXYZM(ntrk->Px(),ntrk->Py(),ntrk->Pz(),0.938272081); vpi.SetXYZM(ptrk->Px(),ptrk->Py(),ptrk->Pz(),0.13957061); vlam = vpr + vpi; TVector3 vboost = vlam.BoostVector(); vpr.Boost(-vboost); bachcosthe = cos(vpr.Angle(vlam.Vect())); ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambdaCosThetaStarPID")))->Fill(v0->MassLambda(),ntrk->Pt(),bachcosthe); } if(fUseMCInfo && mcv0){ ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambdaSgn")))->Fill(v0->MassAntiLambda(),ntrk->Pt(),dR); if(TMath::Abs(nTPCsigmas)<5&&TMath::Abs(nTOFsigmas)<5){ ((TH3D*)(fOutputAll->FindObject("hMassvsPtInclusiveLambdaLoosePIDSgn")))->Fill(v0->MassAntiLambda(),ntrk->Pt(),dR); } if(PIDOK){ ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambdaSgn")))->Fill(v0->MassAntiLambda(),ntrk->Pt(),dR); ((TH3D*)(fOutputPIDBach->FindObject("hMassvsPtInclusiveLambdaCosThetaStarPIDSgn")))->Fill(v0->MassLambda(),ntrk->Pt(),bachcosthe); } } } } return; } //--------------------------- void AliAnalysisTaskSELc2V0bachelor::DoEventMixing(AliAODEvent *aodEvent,TClonesArray *mcArray,AliRDHFCutsLctoV0 *cutsAnal) { Double_t vtxz = fVtx1->GetZ(); Double_t centrality = cutsAnal->GetCentrality(aodEvent); fPoolIndex=GetPoolIndex(vtxz,centrality); if(fPoolIndex<0) return; Int_t nextRes( fNextResVec[fPoolIndex] ); while(!fReservoirP[fPoolIndex][nextRes].empty()){ delete fReservoirP[fPoolIndex][nextRes].back(); fReservoirP[fPoolIndex][nextRes].pop_back(); } //Fill proton in the pool Int_t nTracks = aodEvent->GetNumberOfTracks(); for (Int_t itrk = 0; itrk<nTracks; itrk++) { AliAODTrack *trk = (AliAODTrack*)aodEvent->GetTrack(itrk); if(!trk) continue; if(!cutsAnal->ApplySingleProtonCuts(trk,aodEvent)) continue; // Get AliExternalTrackParam out of the AliAODTracks Double_t xyz[3], pxpypz[3], cv[21]; Short_t sign; trk->PxPyPz(pxpypz); trk->GetXYZ(xyz); trk->GetCovarianceXYZPxPyPz(cv); sign=trk->Charge(); TVector *varvec = new TVector(34); for(Int_t ic=0;ic<3;ic++){ (*varvec)[ic] = pxpypz[ic]; } for(Int_t ic=0;ic<3;ic++){ (*varvec)[ic+3] = xyz[ic]; } for(Int_t ic=0;ic<21;ic++){ (*varvec)[ic+6] = cv[ic]; } (*varvec)[27] = sign; (*varvec)[28] = fVtx1->GetX(); (*varvec)[29] = fVtx1->GetY(); (*varvec)[30] = fVtx1->GetZ(); Double_t d0z0bach[2],covd0z0bach[3]; trk->PropagateToDCA(fVtx1,fBzkG,kVeryBig,d0z0bach,covd0z0bach); (*varvec)[31] = d0z0bach[0]; (*varvec)[32] = TMath::Sqrt(covd0z0bach[0]); (*varvec)[33] = (Float_t)trk->HasPointOnITSLayer(0); fReservoirP[fPoolIndex][nextRes].push_back(varvec); } // Do the event mixing for fPoolIndex Int_t KiddiePool = fReservoirP[fPoolIndex].size(); if( !fReservoirsReady[fPoolIndex] ) KiddiePool = nextRes; if( KiddiePool>0 ) { for(Int_t j=0;j<KiddiePool;j++){ if( j!=nextRes ) { FillMixedBackground(fReservoirP[fPoolIndex][j],aodEvent,cutsAnal); } } } // Rolling buffer nextRes++; if( nextRes>=fNumberOfEventsForMixing ){ nextRes = 0; fReservoirsReady[fPoolIndex] = kTRUE; } fNextResVec[fPoolIndex] = nextRes; } //--------------------------- void AliAnalysisTaskSELc2V0bachelor::DoRotationFromTrack(AliAODEvent *aodEvent,TClonesArray *mcArray,AliRDHFCutsLctoV0 *cutsAnal) { while(!fReservoirP[0][0].empty()){ delete fReservoirP[0][0].back(); fReservoirP[0][0].pop_back(); } //Fill proton in the pool Int_t nTracks = aodEvent->GetNumberOfTracks(); Double_t rotStep=(fMaxAngleForRot-fMinAngleForRot)/(fNRotations-1); for (Int_t itrk = 0; itrk<nTracks; itrk++) { AliAODTrack *trk = (AliAODTrack*)aodEvent->GetTrack(itrk); if(!trk) continue; if(!cutsAnal->ApplySingleProtonCuts(trk,aodEvent)) continue; // Get AliExternalTrackParam out of the AliAODTracks Double_t xyz[3], pxpypz[3], pxpypznew[3], cv[21]; Short_t sign; trk->PxPyPz(pxpypz); trk->GetXYZ(xyz); trk->GetCovarianceXYZPxPyPz(cv); sign=trk->Charge(); Double_t d0z0bach[2],covd0z0bach[3]; trk->PropagateToDCA(fVtx1,fBzkG,kVeryBig,d0z0bach,covd0z0bach); for(Int_t irot=0;irot<fNRotations;irot++){ Double_t phirot=fMinAngleForRot+rotStep*irot; Double_t tmpx=pxpypz[0]; Double_t tmpy=pxpypz[1]; pxpypznew[0] = tmpx*TMath::Cos(phirot)-tmpy*TMath::Sin(phirot); pxpypznew[1] = tmpx*TMath::Sin(phirot)+tmpy*TMath::Cos(phirot); pxpypznew[2] = pxpypz[2]; TVector *varvec = new TVector(34); for(Int_t ic=0;ic<3;ic++){ (*varvec)[ic] = pxpypznew[ic]; } for(Int_t ic=0;ic<3;ic++){ (*varvec)[ic+3] = xyz[ic]; } for(Int_t ic=0;ic<21;ic++){ (*varvec)[ic+6] = cv[ic]; } (*varvec)[27] = sign; (*varvec)[28] = fVtx1->GetX(); (*varvec)[29] = fVtx1->GetY(); (*varvec)[30] = fVtx1->GetZ(); (*varvec)[31] = d0z0bach[0]; (*varvec)[32] = TMath::Sqrt(covd0z0bach[0]); (*varvec)[33] = (Float_t)trk->HasPointOnITSLayer(0); fReservoirP[0][0].push_back(varvec); } } FillMixedBackground(fReservoirP[0][0],aodEvent,cutsAnal); } //--------------------------- void AliAnalysisTaskSELc2V0bachelor::FillMixedBackground(std::vector<TVector * > mixTypeP, AliAODEvent *aodEvent, AliRDHFCutsLctoV0 *cutsAnal) { // // Fill background // Double_t mLcPDG = TDatabasePDG::Instance()->GetParticle(4122)->Mass(); Double_t mPrPDG = TDatabasePDG::Instance()->GetParticle(2212)->Mass(); Double_t mK0SPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass(); Int_t nPr = mixTypeP.size(); Int_t nV0s = aodEvent->GetNumberOfV0s(); for(Int_t iv0=0;iv0<nV0s;iv0++){ AliAODv0 *v0 = aodEvent->GetV0(iv0); if(!v0) continue; if(!cutsAnal->ApplySingleK0Cuts(v0,aodEvent)) continue; AliNeutralTrackParam *trackV0=NULL; const AliVTrack *trackVV0 = dynamic_cast<const AliVTrack*>(v0); if(trackVV0) trackV0 = new AliNeutralTrackParam(trackVV0); Double_t d0z0v0[2],covd0z0v0[2]; trackV0->PropagateToDCA(fVtx1,fBzkG,kVeryBig,d0z0v0,covd0z0v0); for(Int_t ip=0;ip<nPr;ip++){ TVector *pvars = mixTypeP[ip]; if(!pvars) continue; Double_t xyzP[3], pxpypzP[3], cvP[21]; Short_t signP; Double_t vtxP[3]; Double_t d0Pr, d0errPr; vtxP[0] = (*pvars)[28]; vtxP[1] = (*pvars)[29]; vtxP[2] = (*pvars)[30]; Double_t vtxthis[3]; fVtx1->GetXYZ(vtxthis); d0Pr = (*pvars)[31]; d0errPr = (*pvars)[32]; for(Int_t ic=0;ic<3;ic++){ pxpypzP[ic] = (*pvars)[ic]; } for(Int_t ic=0;ic<3;ic++){ xyzP[ic] = (*pvars)[ic+3] +(vtxthis[ic]-vtxP[ic]); } for(Int_t ic=0;ic<21;ic++){ cvP[ic] = (*pvars)[ic+6]; } signP = (*pvars)[27]; Bool_t spdfirst = (*pvars)[33]; Double_t pxp = pxpypzP[0]; Double_t pyp = pxpypzP[1]; Double_t pzp = pxpypzP[2]; Double_t Ep = TMath::Sqrt(pow(pxp,2)+pow(pyp,2)+pow(pzp,2)+pow(mPrPDG,2)); Double_t pxv0 = v0->Px(); Double_t pyv0 = v0->Py(); Double_t pzv0 = v0->Pz(); Double_t Ev0 = TMath::Sqrt(pow(pxv0,2)+pow(pyv0,2)+pow(pzv0,2)+pow(mK0SPDG,2)); Double_t pxtot = pxp+pxv0; Double_t pytot = pyp+pyv0; Double_t pztot = pzp+pzv0; Double_t Etot = Ep+Ev0; Double_t pttot = sqrt(pxtot*pxtot+pytot*pytot); Double_t tmass = sqrt(pow(Etot,2)-pow(pxtot,2)-pow(pytot,2)-pow(pztot,2)); if(TMath::Abs(tmass-mLcPDG)>0.20) continue; if(pttot<4.) continue; AliExternalTrackParam *trkp = new AliExternalTrackParam(xyzP,pxpypzP,cvP,signP); Double_t d0[2],d0err[2]; // Double_t d0z0bach[2],covd0z0bach[3]; // trkp->PropagateToDCA(fVtx1,fBzkG,kVeryBig,d0z0bach,covd0z0bach); // d0[0]= d0z0bach[0]; // d0err[0] = TMath::Sqrt(covd0z0bach[0]); d0[0]= d0Pr; d0err[0] = d0errPr; d0[1]= d0z0v0[0]; d0err[1] = TMath::Sqrt(covd0z0v0[0]); Double_t px[2],py[2],pz[2]; px[0] = trkp->Px(); py[0] = trkp->Py(); pz[0] = trkp->Pz(); px[1] = v0->Px(); py[1] = v0->Py(); pz[1] = v0->Pz(); // // FindVertexForCascades is assumed to be FALSE in the filtering // Use Primary vertex as secondary Vtx and dca is 0 // Double_t pos[3],cov[6],chi2perNDF; fVtx1->GetXYZ(pos); fVtx1->GetCovarianceMatrix(cov); chi2perNDF = fVtx1->GetChi2perNDF(); AliAODVertex *secVert = new AliAODVertex(pos,cov,chi2perNDF,0x0,-1,AliAODVertex::kUndef,2); Double_t dca = 0.; AliAODRecoCascadeHF *theCascade = new AliAODRecoCascadeHF(secVert,signP,px,py,pz,d0,d0err,dca); theCascade->SetOwnPrimaryVtx(fVtx1); UShort_t id[2]={(UShort_t)trkp->GetID(),(UShort_t)trackV0->GetID()}; theCascade->SetProngIDs(2,id); theCascade->GetSecondaryVtx()->AddDaughter(trkp); theCascade->GetSecondaryVtx()->AddDaughter(v0); if ( cutsAnal->IsInFiducialAcceptance(theCascade->Pt(),theCascade->Y(4122)) ){ if(cutsAnal->ApplyCandidateCuts(theCascade,aodEvent,(Bool_t)spdfirst)) { ((TH2D*)(fOutputPIDBach->FindObject("histLcMassBGByK0SOffline")))->Fill(theCascade->InvMassLctoK0sP(),theCascade->Pt()); } } delete trkp; delete secVert; delete theCascade; } delete trackV0; } return; } //--------------------------- Int_t AliAnalysisTaskSELc2V0bachelor::GetPoolIndex(Double_t zvert, Double_t mult){ // // check in which of the pools the current event falls // Int_t theBinZ=-9999; for(Int_t iz=0;iz<fNzVtxBins;iz++){ if(zvert>=fZvtxBins[iz] && zvert<fZvtxBins[iz+1]) { theBinZ = iz; break; } } if(theBinZ<0) return -1; Int_t theBinM=-9999; for(Int_t ic=0;ic<fNCentBins;ic++){ if(mult>=fCentBins[ic] && mult<fCentBins[ic+1]){ theBinM = ic; break; } } if(theBinM<0) return -2; return fNCentBins*theBinZ+theBinM; } //--------------------------- void AliAnalysisTaskSELc2V0bachelor::CheckEventSelection(AliAODEvent *aodEvent) { // /// To fill control histograms // TClonesArray *arrayLctopKos=0; if (!aodEvent){ if(AODEvent() && IsStandardAOD()) { // In case there is an AOD handler writing a standard AOD, use the AOD // event in memory rather than the input (ESD) event. aodEvent = dynamic_cast<AliAODEvent*> (AODEvent()); // in this case the braches in the deltaAOD (AliAOD.VertexingHF.root) // have to taken from the AOD event hold by the AliAODExtension AliAODHandler* aodHandler = (AliAODHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (aodHandler->GetExtensions()) { AliAODExtension *ext = (AliAODExtension*)aodHandler->GetExtensions()->FindObject("AliAOD.VertexingHF.root"); AliAODEvent *aodFromExt = ext->GetAOD(); arrayLctopKos=(TClonesArray*)aodFromExt->GetList()->FindObject("CascadesHF"); } } } else { arrayLctopKos=(TClonesArray*)aodEvent->GetList()->FindObject("CascadesHF"); } Float_t zVertex = fVtx1->GetZ(); TString titleVtx=fVtx1->GetTitle(); if (TMath::Abs(fBzkG)>=0.001) { if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ2")))->Fill(zVertex); if (arrayLctopKos) { if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ3")))->Fill(zVertex); // mc analysis TClonesArray *mcArray = 0; AliAODMCHeader *mcHeader=0; if (fUseMCInfo) { // MC array need for maching mcArray = dynamic_cast<TClonesArray*>(aodEvent->FindListObject(AliAODMCParticle::StdBranchName())); if (mcArray) { // load MC header if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ4")))->Fill(zVertex); mcHeader = (AliAODMCHeader*)aodEvent->GetList()->FindObject(AliAODMCHeader::StdBranchName()); if (mcHeader && fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ5")))->Fill(zVertex); // check on MC Lc Daughter if (fAdditionalChecks) { for (Int_t iii=0; iii<mcArray->GetEntries(); iii++) SearchLcDaughter(mcArray,iii); } } } if (fVtx1->GetNContributors()>0) { if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ6")))->Fill(zVertex); TString firedTriggerClasses = aodEvent->GetFiredTriggerClasses(); // trigger class ULong64_t fTriggerMask=AliVEvent::kAnyINT; Bool_t check1 = kFALSE; if ( !fUseMCInfo && // don't do for MC... (aodEvent->GetRunNumber()<136851 || aodEvent->GetRunNumber()>139517) ) { // ...and for PbPb 2010 data if ( !(firedTriggerClasses.Contains("CINT1")) ) { AliInfo(Form(" ======================== firedTriggerClasses.Data() = %s",firedTriggerClasses.Data())); fCEvents->Fill(8); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ8")))->Fill(zVertex); check1 = kTRUE; } } Bool_t isSelectedAAA = (((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & fTriggerMask); if (!isSelectedAAA) { fCEvents->Fill(9); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ9")))->Fill(zVertex); } if (!isSelectedAAA || check1) { fCEvents->Fill(16); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ16")))->Fill(zVertex); } fTriggerMask=AliVEvent::kAny; Bool_t isSelectedBBB = (((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & fTriggerMask); if (!isSelectedBBB) { fCEvents->Fill(10); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ10")))->Fill(zVertex); } if (titleVtx.Contains("Z")) { fCEvents->Fill(11); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ11")))->Fill(zVertex); } else if (titleVtx.Contains("3D")) { fCEvents->Fill(12); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ12")))->Fill(zVertex); } else { fCEvents->Fill(13); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ13")))->Fill(zVertex); } if (TMath::Abs(zVertex)<=fAnalCuts->GetMaxVtxZ()) { fCEvents->Fill(14); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ14")))->Fill(zVertex); } if ( fIsEventSelected ) { if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ7")))->Fill(zVertex); } else { fCEvents->Fill(15); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ15")))->Fill(zVertex); } } // nContributors>=1 } // analysisArray exists } // magnetic field exists return; } //----------------- void AliAnalysisTaskSELc2V0bachelor::CheckEventSelectionWithCandidates(AliAODEvent *aodEvent) { /// /// To fill control histograms /// Float_t zVertex = fVtx1->GetZ(); TString titleVtx=fVtx1->GetTitle(); TString firedTriggerClasses = aodEvent->GetFiredTriggerClasses(); // trigger class ULong64_t fTriggerMask=AliVEvent::kAnyINT; ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(6); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ6a")))->Fill(zVertex); Bool_t check1a = kFALSE; if ( !fUseMCInfo && // don't do for MC... (aodEvent->GetRunNumber()<136851 || aodEvent->GetRunNumber()>139517) ) { // ...and for PbPb 2010 data if ( !(firedTriggerClasses.Contains("CINT1")) ) { AliInfo(Form(" ======================== firedTriggerClasses.Data() = %s",firedTriggerClasses.Data())); ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(8); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ8a")))->Fill(zVertex); check1a = kTRUE; } } Bool_t isSelectedAAAa = (((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & fTriggerMask); if (!isSelectedAAAa) { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(9); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ9a")))->Fill(zVertex); } if (!isSelectedAAAa || check1a) { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(16); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ16a")))->Fill(zVertex); } fTriggerMask=AliVEvent::kAny; Bool_t isSelectedBBBa = (((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & fTriggerMask); if (!isSelectedBBBa) { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(10); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ10a")))->Fill(zVertex); } if (titleVtx.Contains("Z")) { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(11); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ11a")))->Fill(zVertex); } else if (titleVtx.Contains("3D")) { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(12); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ12a")))->Fill(zVertex); } else { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(13); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ13a")))->Fill(zVertex); } if (TMath::Abs(zVertex)<=fAnalCuts->GetMaxVtxZ()) { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(14); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ14a")))->Fill(zVertex); } if ( fIsEventSelected ) { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(7); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ7a")))->Fill(zVertex); } else { ((TH1F*)(fOutput->FindObject("hEventsWithCandidates")))->Fill(15); if (fAdditionalChecks) ((TH1F*)(fOutput->FindObject("hZ15a")))->Fill(zVertex); } return; } //----------------------------- Int_t AliAnalysisTaskSELc2V0bachelor::MatchToMC(AliAODRecoCascadeHF *lc2bacV0, Int_t *pdgDgLc2bacV0, Int_t *pdgDgV0, TClonesArray *mcArray) { // /// This is now implemented in AliAODRecoCascadeHF // // bachelor AliAODTrack *bachelor = (AliAODTrack*)lc2bacV0->GetBachelor(); if (!bachelor) return -1; Int_t labBachelor = TMath::Abs(bachelor->GetLabel()); if (labBachelor<0) return -1; AliAODMCParticle *partBachelor = (AliAODMCParticle*)mcArray->At(labBachelor); if (!partBachelor) return -1; if (TMath::Abs(partBachelor->GetPdgCode())!=pdgDgLc2bacV0[0]) return -1; Int_t labBacMother = partBachelor->GetMother(); if (labBacMother<0) return -1; AliAODMCParticle *partBacMother = (AliAODMCParticle*)mcArray->At(labBacMother); if (!partBacMother) return -1; if (TMath::Abs(partBacMother->GetPdgCode())!=4122) return -1; // V0 AliAODTrack *posV0Daugh = (AliAODTrack*)lc2bacV0->Getv0PositiveTrack(); AliAODTrack *negV0Daugh = (AliAODTrack*)lc2bacV0->Getv0NegativeTrack(); if (!posV0Daugh || !negV0Daugh) return -1; Int_t labV0pos = TMath::Abs(posV0Daugh->GetLabel()); Int_t labV0neg = TMath::Abs(negV0Daugh->GetLabel()); if (labV0pos<0 || labV0neg<0) return -1; AliAODMCParticle *partV0pos = (AliAODMCParticle*)mcArray->At(labV0neg); AliAODMCParticle *partV0neg = (AliAODMCParticle*)mcArray->At(labV0pos); if (!partV0pos || !partV0neg) return -1; if ( ! ( (TMath::Abs(partV0pos->GetPdgCode())==pdgDgV0[0] && TMath::Abs(partV0neg->GetPdgCode())==pdgDgV0[1]) || (TMath::Abs(partV0pos->GetPdgCode())==pdgDgV0[1] && TMath::Abs(partV0neg->GetPdgCode())==pdgDgV0[0]) ) ) return -1; Int_t labV0posMother = partV0pos->GetMother(); Int_t labV0negMother = partV0neg->GetMother(); if (labV0posMother<0 || labV0negMother<0) return -1; if (labV0posMother!=labV0negMother) return -1; AliAODMCParticle *motherV0 = (AliAODMCParticle*)mcArray->At(labV0posMother); if (!motherV0) return-1; if (TMath::Abs(motherV0->GetPdgCode())!=pdgDgLc2bacV0[1]) return -1; Int_t labV0mother = motherV0->GetMother(); if (labV0mother<0) return -1; AliAODMCParticle *gMotherV0 = (AliAODMCParticle*)mcArray->At(labV0mother); if (!gMotherV0) return-1; if ( !(pdgDgLc2bacV0[1]==310 && TMath::Abs(gMotherV0->GetPdgCode())==311) && !(pdgDgLc2bacV0[1]==3122 && TMath::Abs(motherV0->GetPdgCode())==3122) ) return -1; if ( (pdgDgLc2bacV0[1]==310 && TMath::Abs(gMotherV0->GetPdgCode())==311) ) { Int_t labV0GMother = gMotherV0->GetMother(); if (labV0GMother<0) return -1; AliAODMCParticle *ggMotherV0 = (AliAODMCParticle*)mcArray->At(labV0GMother); if (!ggMotherV0) return-1; if (TMath::Abs(ggMotherV0->GetPdgCode())!=4122) return -1; gMotherV0 = (AliAODMCParticle*)ggMotherV0; labV0mother=labV0GMother; } else if (pdgDgLc2bacV0[1]==3122 && TMath::Abs(motherV0->GetPdgCode())==3122) { if (TMath::Abs(gMotherV0->GetPdgCode())!=4122) return -1; } if (labBacMother!=labV0mother) { return -1; } return labBacMother; } //________________________________________________________________ Int_t AliAnalysisTaskSELc2V0bachelor::SearchLcDaughter(TClonesArray *arrayMC, Int_t iii) { // /// This is to check Lc dinasty // Int_t indexToBeReturned=-999; Int_t pdgLc=4122; Int_t pdgLambda=3122; Int_t pdgV0=310; Int_t pdgK0=311; Int_t pdgBachelor=2212; Int_t pdgBachelorPi=211; TString fillthis=""; fillthis="histMcStatLc"; AliAODMCParticle *searchLc = dynamic_cast<AliAODMCParticle*>(arrayMC->At(iii)); if(!searchLc) return -999; if (TMath::Abs(searchLc->GetPdgCode()) != pdgLc) return -999; ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(0); indexToBeReturned = 0; ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*1); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*1; Int_t nDaughLc = searchLc->GetNDaughters(); if (nDaughLc!=2) { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*10); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*10; return indexToBeReturned; } Int_t index1=searchLc->GetDaughterLabel(0); Int_t index2=searchLc->GetDaughterLabel(1); if (index1<=0 || index2<=0) { return -999; } AliAODMCParticle *daugh1 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index1)); AliAODMCParticle *daugh2 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index2)); if (!daugh1 || !daugh2) return -999; Int_t daughPdg1 = TMath::Abs(daugh1->GetPdgCode()); Int_t daughPdg2 = TMath::Abs(daugh2->GetPdgCode()); if ( !( (daughPdg1==pdgBachelor && daughPdg2==pdgK0) || (daughPdg2==pdgBachelor && daughPdg1==pdgK0) || (daughPdg1==pdgLambda && daughPdg2==pdgBachelorPi) || (daughPdg2==pdgLambda && daughPdg1==pdgBachelorPi) ) ) { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*10); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*10; return indexToBeReturned; } if (daughPdg1==pdgK0 || daughPdg1==pdgLambda) { index1=searchLc->GetDaughterLabel(1); index2=searchLc->GetDaughterLabel(0); } daugh1 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index1)); daugh2 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index2)); if (!daugh1 || !daugh2) return -999; daughPdg1=TMath::Abs(daugh1->GetPdgCode()); daughPdg2=TMath::Abs(daugh2->GetPdgCode()); if ( daughPdg1==pdgBachelor && daughPdg2==pdgK0 ) { // Lc+ -> p K0bar ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*2); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*2; Int_t nDaughK0 = daugh2->GetNDaughters(); if (nDaughK0!=1) return -999; Int_t indexK0daugh=daugh2->GetDaughterLabel(0); if (indexK0daugh<=0) return -999; AliAODMCParticle *daughK0 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(indexK0daugh)); if (!daughK0) return -999; Int_t daughK0Pdg=TMath::Abs(daughK0->GetPdgCode()); if (daughK0Pdg!=pdgV0) { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*4); // K0L indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*4; return indexToBeReturned; } ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*3); // K0S indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*3; Int_t nDaughK0S = daughK0->GetNDaughters(); if (nDaughK0S!=2) { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*5); // other decays for K0S indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*5; return indexToBeReturned; } index1=daughK0->GetDaughterLabel(0); index2=daughK0->GetDaughterLabel(1); if(index1<=0 || index2<=0) { return -999; } AliAODMCParticle *daughK0S1 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index1)); AliAODMCParticle *daughK0S2 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index2)); if (!daughK0S1 || !daughK0S2) return -999; Int_t daughK0S1pdg=TMath::Abs(daughK0S1->GetPdgCode()); Int_t daughK0S2pdg=TMath::Abs(daughK0S2->GetPdgCode()); if ( daughK0S1pdg==211 && daughK0S2pdg==211 ) { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*6); // K0S -> pi+ pi- indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*6; } else { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*5); // other decays for K0S indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*5; } } //if (daughPdg1==pdgBachelor && daughPdg2==pdgK0) else if ( daughPdg1==pdgBachelorPi && daughPdg2==pdgLambda ) { // Lc+ -> pi+ Lambda ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*7); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*7; Int_t nDaughL = daugh2->GetNDaughters(); if (nDaughL!=2) { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*8); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*8; return indexToBeReturned; } index1=daugh2->GetDaughterLabel(0); index2=daugh2->GetDaughterLabel(1); if(index1<=0 || index2<=0) { return -999; } AliAODMCParticle *daughL1 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index1)); AliAODMCParticle *daughL2 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(index2)); if (!daughL1 || !daughL2) return -999; Int_t daughL1pdg=TMath::Abs(daughL1->GetPdgCode()); Int_t daughL2pdg=TMath::Abs(daughL2->GetPdgCode()); if ( (daughL1pdg==211 && daughL2pdg==2212) || (daughL2pdg==211 && daughL1pdg==2212) ) { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*9); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*9; } else { ((TH1F*)(fOutput->FindObject(fillthis)))->Fill(TMath::Nint(searchLc->Charge()/3.)*8); indexToBeReturned = TMath::Nint(searchLc->Charge()/3.)*8; } } //else if (daughPdg1==pdgBachelorPi && daughPdg2==pdgLambda) return indexToBeReturned; } //________________________________________________________________ void AliAnalysisTaskSELc2V0bachelor::FillArmPodDistribution(AliAODRecoDecay *vZero, TString histoTitle, Bool_t isCandidateSelectedCuts, Bool_t isBachelorID) { // /// This is to fill Armenteros Podolanski plots // Double_t alpha = vZero->Alpha();//AlphaV0(); Double_t qT = vZero->QtProng();//PtArmV0(); ((TH2F*)(fOutputAll->FindObject(histoTitle+"0")))->Fill(alpha,qT); if (isCandidateSelectedCuts) { ((TH2F*)(fOutputAll->FindObject(histoTitle)))->Fill(alpha,qT); if (isBachelorID) ((TH2F*)(fOutputPIDBach->FindObject(histoTitle)))->Fill(alpha,qT); } } //------------------------------------------------------------------------------- void AliAnalysisTaskSELc2V0bachelor::CheckCandidatesAtDifferentLevels(AliAODRecoCascadeHF *part, AliRDHFCutsLctoV0* cutsAnal, AliAODEvent *aod) { // /// This is to check candidates at different levels // Bool_t areCutsUsingPID = cutsAnal->GetIsUsePID(); AliAODv0 * v0part = (AliAODv0*)part->Getv0(); Bool_t onFlyV0 = v0part->GetOnFlyStatus(); // on-the-flight V0s AliAODTrack *bachelor = (AliAODTrack*)part->GetBachelor(); if ( !onFlyV0 ) ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(3); // it counts number of candidates coming from offline V0s if ( cutsAnal->IsInFiducialAcceptance(part->Pt(),part->Y(4122)) ) ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(4); if ( (((cutsAnal->IsSelected(part,AliRDHFCuts::kTracks,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)) ) ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(5); cutsAnal->SetUsePID(kFALSE); if ( (((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)) ) ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(6); cutsAnal->SetUsePID(areCutsUsingPID); if ( (((cutsAnal->IsSelected(part,AliRDHFCuts::kPID,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)) ) ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(7); if ( (((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)) ) ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(8); if ( (((cutsAnal->IsSelected(part,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)) ) ((TH1F*)(fOutput->FindObject("hCandidateSelection")))->Fill(9); if ( cutsAnal->IsInFiducialAcceptance(part->Pt(),part->Y(4122)) ) { if ( ( (cutsAnal->IsSelected(part,AliRDHFCuts::kTracks,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { Int_t aaa = cutsAnal->IsSelected(part,AliRDHFCuts::kTracks,aod); if ( (aaa&AliRDHFCutsLctoV0::kLcToK0Spr)==AliRDHFCutsLctoV0::kLcToK0Spr ) { if ( ( (aaa&AliRDHFCutsLctoV0::kLcToLpi)==AliRDHFCutsLctoV0::kLcToLpi && bachelor->Charge()<0) || ( (aaa&AliRDHFCutsLctoV0::kLcToLBarpi)==AliRDHFCutsLctoV0::kLcToLBarpi && bachelor->Charge()>0) ) ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates1")))->Fill( -aaa ); else ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates1")))->Fill( aaa ); } cutsAnal->SetUsePID(kFALSE); aaa = cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod); if ((aaa&AliRDHFCutsLctoV0::kLcToK0Spr)==AliRDHFCutsLctoV0::kLcToK0Spr) { if ( ( (aaa&AliRDHFCutsLctoV0::kLcToLpi)==AliRDHFCutsLctoV0::kLcToLpi && bachelor->Charge()<0) || ( (aaa&AliRDHFCutsLctoV0::kLcToLBarpi)==AliRDHFCutsLctoV0::kLcToLBarpi && bachelor->Charge()>0) ) ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates2")))->Fill( -aaa ); else ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates2")))->Fill( aaa ); } cutsAnal->SetUsePID(areCutsUsingPID); aaa = cutsAnal->IsSelected(part,AliRDHFCuts::kPID,aod); if ((aaa&AliRDHFCutsLctoV0::kLcToK0Spr)==AliRDHFCutsLctoV0::kLcToK0Spr) { if ( ( (aaa&AliRDHFCutsLctoV0::kLcToLpi)==AliRDHFCutsLctoV0::kLcToLpi && bachelor->Charge()<0) || ( (aaa&AliRDHFCutsLctoV0::kLcToLBarpi)==AliRDHFCutsLctoV0::kLcToLBarpi && bachelor->Charge()>0) ) ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates3")))->Fill( -aaa ); else ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates3")))->Fill( aaa ); } aaa = cutsAnal->IsSelected(part,AliRDHFCuts::kAll,aod); if ((aaa&AliRDHFCutsLctoV0::kLcToK0Spr)==AliRDHFCutsLctoV0::kLcToK0Spr) { if ( ( (aaa&AliRDHFCutsLctoV0::kLcToLpi)==AliRDHFCutsLctoV0::kLcToLpi && bachelor->Charge()<0) || ( (aaa&AliRDHFCutsLctoV0::kLcToLBarpi)==AliRDHFCutsLctoV0::kLcToLBarpi && bachelor->Charge()>0) ) ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates4")))->Fill( -aaa ); else ((TH1F*)(fOutput->FindObject("hSwitchOnCandidates4")))->Fill( aaa ); } } } return; } //------------------------------------------------------------------------------- void AliAnalysisTaskSELc2V0bachelor::FillTheTree(AliAODRecoCascadeHF *part, AliRDHFCutsLctoV0 *cutsAnal, TClonesArray *mcArray, Int_t isLc, Int_t checkLcOrigin) { // /// This is to fill tree // Double_t mk0sPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass(); Double_t mLPDG = TDatabasePDG::Instance()->GetParticle(3122)->Mass(); Double_t invmassLc = part->InvMassLctoK0sP(); Double_t invmassLc2Lpi = part->InvMassLctoLambdaPi(); AliAODTrack *bachelor = (AliAODTrack*)part->GetBachelor(); AliAODv0 *v0part = (AliAODv0*)part->Getv0(); //Double_t dcaV0ptp = v0part->GetDCA(); Double_t invmassK0S = v0part->MassK0Short(); Double_t invmassLambda = v0part->MassLambda(); Double_t invmassLambdaBar = v0part->MassAntiLambda(); Int_t isLc2LBarpi=0, isLc2Lpi=0; Int_t mcLabel = -1; Int_t isDp2K0Spi=0, isDs2K0SK=0; Int_t mcLabel2 = -1; Int_t mcLabel3 = -1; Int_t isKstar12K0Spi=0, isKstar22K0Spi=0; Int_t mcLabel4 = -1; Int_t mcLabel5 = -1; Double_t ptCandByMC = 0.;//fmcPartCandidate->Pt(); Double_t yCandByMC = 0.;//fmcPartCandidate->Y(); Bool_t isMCparticleInFiducialAcceptance = kTRUE; if (fUseMCInfo) { if (isLc) { Int_t pdgCand0 = 4122; Int_t pdgDgLctoV0bachelor0[2]={2212,310}; Int_t pdgDgV0toDaughters0[2]={211,211}; Int_t mcLabelLc2pK0S = part->MatchToMC(pdgCand0,pdgDgLctoV0bachelor0[1],pdgDgLctoV0bachelor0,pdgDgV0toDaughters0,mcArray,kTRUE); AliAODMCParticle *lambdaCpartMC = (AliAODMCParticle*)mcArray->At(mcLabelLc2pK0S); if (lambdaCpartMC) { ptCandByMC = lambdaCpartMC->Pt(); yCandByMC = lambdaCpartMC->Y(); } } Int_t pdgCand = 4122; Int_t pdgDgLctoV0bachelor[2]={211,3122}; Int_t pdgDgV0toDaughters[2]={2212,211}; mcLabel = part->MatchToMC(pdgCand,pdgDgLctoV0bachelor[1],pdgDgLctoV0bachelor,pdgDgV0toDaughters,mcArray,kTRUE); if (mcLabel!=-1) { if (bachelor->Charge()<0) isLc2LBarpi=1; if (bachelor->Charge()>0) isLc2Lpi=1; AliAODMCParticle *lambdaCpartMC = (AliAODMCParticle*)mcArray->At(mcLabel); if (lambdaCpartMC) { ptCandByMC = lambdaCpartMC->Pt(); yCandByMC = lambdaCpartMC->Y(); } } Int_t pdgCand2 = 411; // D+ -> pi+ K0S Int_t pdgCand3 = 431; // Ds+ -> K+ K0S Int_t pdgDgCand2[2]={211,310}; Int_t pdgDgCand3[2]={321,310}; pdgDgV0toDaughters[0]=211; pdgDgV0toDaughters[1]=211; mcLabel2 = part->MatchToMC(pdgCand2,pdgDgCand2[1],pdgDgCand2,pdgDgV0toDaughters,mcArray,kTRUE); mcLabel3 = part->MatchToMC(pdgCand3,pdgDgCand3[1],pdgDgCand3,pdgDgV0toDaughters,mcArray,kTRUE); if (mcLabel2!=-1) { isDp2K0Spi=1; AliAODMCParticle *lambdaCpartMC = (AliAODMCParticle*)mcArray->At(mcLabel2); if (lambdaCpartMC) { ptCandByMC = lambdaCpartMC->Pt(); yCandByMC = lambdaCpartMC->Y(); } } if (mcLabel3!=-1) { isDs2K0SK=1; AliAODMCParticle *lambdaCpartMC = (AliAODMCParticle*)mcArray->At(mcLabel3); if (lambdaCpartMC) { ptCandByMC = lambdaCpartMC->Pt(); yCandByMC = lambdaCpartMC->Y(); } } Int_t pdgCand4 = 313; // K*(892)+ -> pi+ K0S Int_t pdgCand5 = 325; // K*(1430)+ -> pi+ K0S Int_t pdgDgCand4[2]={211,310}; Int_t pdgDgCand5[2]={211,310}; pdgDgV0toDaughters[0]=211; pdgDgV0toDaughters[1]=211; mcLabel4 = part->MatchToMC(pdgCand4,pdgDgCand4[1],pdgDgCand4,pdgDgV0toDaughters,mcArray,kTRUE); mcLabel5 = part->MatchToMC(pdgCand5,pdgDgCand5[1],pdgDgCand5,pdgDgV0toDaughters,mcArray,kTRUE); if (mcLabel4!=-1) { isKstar12K0Spi=1; AliAODMCParticle *lambdaCpartMC = (AliAODMCParticle*)mcArray->At(mcLabel4); if (lambdaCpartMC) { ptCandByMC = lambdaCpartMC->Pt(); yCandByMC = lambdaCpartMC->Y(); } } if (mcLabel5!=-1) { isKstar22K0Spi=1; AliAODMCParticle *lambdaCpartMC = (AliAODMCParticle*)mcArray->At(mcLabel5); if (lambdaCpartMC) { ptCandByMC = lambdaCpartMC->Pt(); yCandByMC = lambdaCpartMC->Y(); } } if (isLc || isLc2LBarpi || isLc2Lpi || isDp2K0Spi || isDs2K0SK || isKstar12K0Spi || isKstar22K0Spi) { isMCparticleInFiducialAcceptance = cutsAnal->IsInFiducialAcceptance(ptCandByMC,yCandByMC); } } Int_t isLcByMC = isLc+isLc2LBarpi*2+isLc2Lpi*4+isDp2K0Spi*8+isDs2K0SK*16+isKstar12K0Spi*32+isKstar22K0Spi*64; Int_t isK0S = 0; Int_t isLambda = 0; Int_t isLambdaBar = 0; Int_t isGamma = 0; if (fUseMCInfo) { Int_t pdgDg2prong[2] = {211, 211}; Int_t labelK0S = v0part->MatchToMC(310,mcArray,2,pdgDg2prong); if (labelK0S>=0) isK0S = 1; pdgDg2prong[0] = 211; pdgDg2prong[1] = 2212; Int_t lambdaLabel = v0part->MatchToMC(3122,mcArray,2,pdgDg2prong); if (lambdaLabel>=0) { AliAODMCParticle *lambdaTrack = (AliAODMCParticle*)mcArray->At(lambdaLabel); if (lambdaTrack->GetPdgCode()==3122) isLambda = 1; else if (lambdaTrack->GetPdgCode()==-3122) isLambdaBar = 1; } pdgDg2prong[0] = 11; pdgDg2prong[1] = 11; Int_t gammaLabel = v0part->MatchToMC(22,mcArray,2,pdgDg2prong); if (gammaLabel>=0) { AliAODMCParticle *gammaTrack = (AliAODMCParticle*)mcArray->At(gammaLabel); if (gammaTrack->GetPdgCode()==22) isGamma = 1; } } Int_t isV0ByMC = isK0S+isLambdaBar*2+isLambda*4+isGamma*8; Int_t isBachelorSelected = (bachelor->TestFilterMask(BIT(4)))*1 + (!(bachelor->TestFilterMask(BIT(4))))*2; isBachelorSelected += (bachelor->GetLabel()<0)*4 + (bachelor->GetLabel()>=0)*8; if ( ( !(bachelor->HasPointOnITSLayer(0)) && !(bachelor->HasPointOnITSLayer(1)) ) ) isBachelorSelected += 16; else { if ( bachelor->HasPointOnITSLayer(0) && !(bachelor->HasPointOnITSLayer(1)) ) isBachelorSelected += 32; else if ( !(bachelor->HasPointOnITSLayer(0)) && bachelor->HasPointOnITSLayer(1) ) isBachelorSelected += 64; else isBachelorSelected += 128; } AliAODTrack *v0pos = (AliAODTrack*)part->Getv0PositiveTrack(); AliAODTrack *v0neg = (AliAODTrack*)part->Getv0NegativeTrack(); Int_t areV0daughtersSelected = (v0pos->TestFilterMask(BIT(4)))*1 + (!(v0pos->TestFilterMask(BIT(4))))*2; areV0daughtersSelected += (v0pos->GetLabel()<0)*4 + (v0pos->GetLabel()>=0)*8; areV0daughtersSelected += (v0pos->HasPointOnITSLayer(0))*16; areV0daughtersSelected += (v0pos->HasPointOnITSLayer(1))*32; areV0daughtersSelected += (v0pos->HasPointOnITSLayer(2))*64; areV0daughtersSelected += (v0pos->HasPointOnITSLayer(3))*128; areV0daughtersSelected += (v0pos->HasPointOnITSLayer(4))*256; areV0daughtersSelected += (v0pos->HasPointOnITSLayer(5))*512; areV0daughtersSelected += (v0neg->TestFilterMask(BIT(4)))*1024 + (!(v0neg->TestFilterMask(BIT(4))))*2048; areV0daughtersSelected += (v0neg->GetLabel()<0)*4096 + (v0neg->GetLabel()>=0)*8192; areV0daughtersSelected += (v0neg->HasPointOnITSLayer(0))*16384; areV0daughtersSelected += (v0neg->HasPointOnITSLayer(1))*32768; areV0daughtersSelected += (v0neg->HasPointOnITSLayer(2))*65536; areV0daughtersSelected += (v0neg->HasPointOnITSLayer(3))*131072; areV0daughtersSelected += (v0neg->HasPointOnITSLayer(4))*262144; areV0daughtersSelected += (v0neg->HasPointOnITSLayer(5))*524288; Double_t nSigmaITSpr=-999.; cutsAnal->GetPidHF()->GetnSigmaITS(bachelor,4,nSigmaITSpr); Double_t nSigmaTPCpr=-999.; cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor,4,nSigmaTPCpr); Double_t nSigmaTOFpr=-999.; cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor,4,nSigmaTOFpr); Double_t nSigmaITSpi=-999.; cutsAnal->GetPidHF()->GetnSigmaITS(bachelor,2,nSigmaITSpi); Double_t nSigmaTPCpi=-999.; cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor,2,nSigmaTPCpi); Double_t nSigmaTOFpi=-999.; cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor,2,nSigmaTOFpi); Double_t nSigmaITSka=-999.; cutsAnal->GetPidHF()->GetnSigmaITS(bachelor,3,nSigmaITSka); Double_t nSigmaTPCka=-999.; cutsAnal->GetPidHF()->GetnSigmaTPC(bachelor,3,nSigmaTPCka); Double_t nSigmaTOFka=-999.; cutsAnal->GetPidHF()->GetnSigmaTOF(bachelor,3,nSigmaTOFka); Int_t flagToCheckCandidate = 1*(TMath::Abs(invmassK0S-mk0sPDG)<=0.050); flagToCheckCandidate+=2*((TMath::Abs(invmassLambdaBar-mLPDG)<=0.050) && (bachelor->Charge()<0)); flagToCheckCandidate+=4*((TMath::Abs(invmassLambda-mLPDG)<=0.050) && (bachelor->Charge()>0)); flagToCheckCandidate+=8*((TMath::Abs(invmassLambdaBar-mLPDG)<=0.050) && (bachelor->Charge()>0)); flagToCheckCandidate+=16*((TMath::Abs(invmassLambda-mLPDG)<=0.050) && (bachelor->Charge()<0)); Int_t iVariable=0; fCandidateVariables[iVariable++] = fUseMCInfo+isLcByMC; // 0: real data; 1: bkg; 2: Lc->K0S+p; 3: Lc->LambdaBar+pbar; 5: Lc->Lambda+p; 9: D+->K0S+pi; 17: Ds+->K0S+K; 33: K*+->K0S+pi; 65: K*+->K0S+K fCandidateVariables[iVariable++] = fUseMCInfo+isV0ByMC; // 0: real data; 1: bkg; 2: K0S->pi+pi; 3: LambdaBar->pbar+pi+; 5: Lambda->p+pi- fCandidateVariables[iVariable++] = isBachelorSelected; fCandidateVariables[iVariable++] = areV0daughtersSelected; fCandidateVariables[iVariable++] = flagToCheckCandidate; fCandidateVariables[iVariable++] = invmassLc; fCandidateVariables[iVariable++] = invmassLc2Lpi; fCandidateVariables[iVariable++] = part->InvMass2Prongs(0,1,211,310); // D+ -> pi+ K0S fCandidateVariables[iVariable++] = part->InvMass2Prongs(0,1,321,310); // D+S -> K+ K0S fCandidateVariables[iVariable++] = invmassK0S; fCandidateVariables[iVariable++] = invmassLambda; fCandidateVariables[iVariable++] = invmassLambdaBar; fCandidateVariables[iVariable++] = v0part->InvMass2Prongs(0,1,11,11); fCandidateVariables[iVariable++] = part->Getd0Prong(0); fCandidateVariables[iVariable++] = part->Getd0Prong(1); fCandidateVariables[iVariable++] = part->CosV0PointingAngle(); fCandidateVariables[iVariable++] = part->Pt(); fCandidateVariables[iVariable++] = v0part->Pt(); fCandidateVariables[iVariable++] = bachelor->P(); fCandidateVariables[iVariable++] = bachelor->Pt(); fCandidateVariables[iVariable++] = v0pos->Pt(); fCandidateVariables[iVariable++] = v0neg->Pt(); fCandidateVariables[iVariable++] = bachelor->Charge(); fCandidateVariables[iVariable++] = v0part->QtProng(); fCandidateVariables[iVariable++] = v0part->Alpha(); fCandidateVariables[iVariable++] = nSigmaTPCpr; fCandidateVariables[iVariable++] = nSigmaTOFpr; AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *inputHandler=(AliInputEventHandler*)mgr->GetInputEventHandler(); AliPIDResponse *pidResponse = (AliPIDResponse*)inputHandler->GetPIDResponse(); AliPIDCombined *objectPIDCombined=new AliPIDCombined; objectPIDCombined->SetDefaultTPCPriors(); objectPIDCombined->SetDetectorMask(AliPIDResponse::kDetTPC+AliPIDResponse::kDetTOF); Double_t probTPCTOF[AliPID::kSPECIES]={-1.}; UInt_t detUsed = objectPIDCombined->ComputeProbabilities(bachelor, pidResponse, probTPCTOF); Double_t probProton = -1.; // Double_t probPion = -1.; // Double_t probKaon = -1.; if (detUsed == (UInt_t)objectPIDCombined->GetDetectorMask() ) { AliDebug(2, Form("We have found the detector mask for TOF + TPC: probProton will be set to %f", probTPCTOF[AliPID::kProton])); probProton = probTPCTOF[AliPID::kProton]; // probPion = probTPCTOF[AliPID::kPion]; // probKaon = probTPCTOF[AliPID::kKaon]; } else { // if you don't have both TOF and TPC, try only TPC objectPIDCombined->SetDetectorMask(AliPIDResponse::kDetTPC); AliDebug(2, "We did not find the detector mask for TOF + TPC, let's see only TPC"); detUsed = objectPIDCombined->ComputeProbabilities(bachelor, pidResponse, probTPCTOF); AliDebug(2,Form(" detUsed (TPC case) = %d", detUsed)); if (detUsed == (UInt_t)objectPIDCombined->GetDetectorMask()) { probProton = probTPCTOF[AliPID::kProton]; // probPion = probTPCTOF[AliPID::kPion]; // probKaon = probTPCTOF[AliPID::kKaon]; AliDebug(2, Form("TPC only worked: probProton will be set to %f", probTPCTOF[AliPID::kProton])); } else { AliDebug(2, "Only TPC did not work..."); } // resetting mask to ask for both TPC+TOF objectPIDCombined->SetDetectorMask(AliPIDResponse::kDetTPC+AliPIDResponse::kDetTOF); } AliDebug(2, Form("probProton = %f", probProton)); // now we get the TPC and TOF single PID probabilities (only for Proton, or the tree will explode :) ) Double_t probProtonTPC = -1.; Double_t probProtonTOF = -1.; Double_t pidTPC[AliPID::kSPECIES]={-1.}; Double_t pidTOF[AliPID::kSPECIES]={-1.}; Int_t respTPC = pidResponse->ComputePIDProbability(AliPIDResponse::kDetTPC, bachelor, AliPID::kSPECIES, pidTPC); Int_t respTOF = pidResponse->ComputePIDProbability(AliPIDResponse::kDetTOF, bachelor, AliPID::kSPECIES, pidTOF); if (respTPC == AliPIDResponse::kDetPidOk) probProtonTPC = pidTPC[AliPID::kProton]; if (respTOF == AliPIDResponse::kDetPidOk) probProtonTOF = pidTOF[AliPID::kProton]; fCandidateVariables[iVariable++] = probProton; fCandidateVariables[iVariable++] = probProtonTPC; fCandidateVariables[iVariable++] = probProtonTOF; if (fUseMCInfo) { fCandidateVariables[iVariable++] = isMCparticleInFiducialAcceptance; if (bachelor->GetLabel()!=-1) { AliAODMCParticle *partBachelor = dynamic_cast<AliAODMCParticle*>(mcArray->At(TMath::Abs(bachelor->GetLabel()))); if (partBachelor) fCandidateVariables[iVariable++] = partBachelor->GetPdgCode(); else fCandidateVariables[iVariable++] = -1; } else fCandidateVariables[iVariable++] = -1; if (bachelor->GetLabel()!=-1 && v0pos->GetLabel()!=-1 && v0neg->GetLabel()!=-1) { const Int_t ndg=3; Int_t dgLabels[ndg]={TMath::Abs(bachelor->GetLabel()), TMath::Abs(v0pos->GetLabel()), TMath::Abs(v0neg->GetLabel())}; Int_t ndgCk=0; Int_t *pdgDg=0; Int_t absLabelMother=-1; Int_t nDauCand=-1; fCandidateVariables[iVariable++] = SearchForCommonMother(mcArray, dgLabels,ndg,ndgCk,pdgDg,absLabelMother,nDauCand); } else fCandidateVariables[iVariable++] = -1; if (v0pos->GetLabel()!=-1) { AliAODMCParticle *part1 = dynamic_cast<AliAODMCParticle*>(mcArray->At(TMath::Abs(v0pos->GetLabel()))); if (part1) fCandidateVariables[iVariable++] = part1->GetPdgCode(); else fCandidateVariables[iVariable++] = -1; } else fCandidateVariables[iVariable++] = -1; if (v0neg->GetLabel()!=-1) { AliAODMCParticle *part2 = dynamic_cast<AliAODMCParticle*>(mcArray->At(TMath::Abs(v0neg->GetLabel()))); if (part2) fCandidateVariables[iVariable++] = part2->GetPdgCode(); else fCandidateVariables[iVariable++] = -1; } else fCandidateVariables[iVariable++] = -1; if (v0pos->GetLabel()!=-1 && v0neg->GetLabel()!=-1) { const Int_t ndg=2; Int_t dgLabels[ndg]={TMath::Abs(v0pos->GetLabel()), TMath::Abs(v0neg->GetLabel())}; Int_t ndgCk=0; Int_t *pdgDg=0; Int_t absLabelMother=-1; Int_t nDauCand=-1; fCandidateVariables[iVariable++] = SearchForCommonMother(mcArray, dgLabels,ndg,ndgCk,pdgDg,absLabelMother,nDauCand); } else fCandidateVariables[iVariable++] = -1; fCandidateVariables[iVariable++] = checkLcOrigin; } if (fAdditionalChecks) { // ------------------------------siamo qui! fCandidateVariables[iVariable++] = part->P(); fCandidateVariables[iVariable++] = v0part->P(); fCandidateVariables[iVariable++] = v0pos->P(); fCandidateVariables[iVariable++] = v0neg->P(); fCandidateVariables[iVariable++] = nSigmaTPCpi; fCandidateVariables[iVariable++] = nSigmaTPCka; fCandidateVariables[iVariable++] = nSigmaTOFpi; fCandidateVariables[iVariable++] = nSigmaTOFka; fCandidateVariables[iVariable++] = pidResponse->GetTOFResponse().GetStartTimeMask(bachelor->P()); fCandidateVariables[iVariable++] = part->GetDCA(); fCandidateVariables[iVariable++] = v0part->GetDCA(); fCandidateVariables[iVariable++] = v0part->Getd0Prong(0); fCandidateVariables[iVariable++] = v0part->Getd0Prong(1); fCandidateVariables[iVariable++] = part->CosPointingAngle(); fCandidateVariables[iVariable++] = v0part->RadiusSecVtx(); fCandidateVariables[iVariable++] = nSigmaITSpr; fCandidateVariables[iVariable++] = nSigmaITSpi; fCandidateVariables[iVariable++] = nSigmaITSka; fCandidateVariables[iVariable++] = part->Y(4122); fCandidateVariables[iVariable++] = bachelor->Eta(); fCandidateVariables[iVariable++] = v0pos->Eta(); fCandidateVariables[iVariable++] = v0neg->Eta(); fCandidateVariables[iVariable++] = part->DecayLength(); fCandidateVariables[iVariable++] = part->DecayLengthV0(); fCandidateVariables[iVariable++] = part->CosPointingAngleXY(); fCandidateVariables[iVariable++] = part->CosV0PointingAngleXY(); fCandidateVariables[iVariable++] = part->DecayLengthXY(); fCandidateVariables[iVariable++] = part->DecayLengthXYV0(); fCandidateVariables[iVariable++] = part->NormalizedDecayLength(); fCandidateVariables[iVariable++] = part->NormalizedV0DecayLength(); fCandidateVariables[iVariable++] = part->NormalizedDecayLengthXY(); fCandidateVariables[iVariable++] = part->NormalizedV0DecayLengthXY(); Double_t xVtxLc=0, yVtxLc=0, zVtxLc=0; Double_t pxVtxBachelor=0, pyVtxBachelor=0, pzVtxBachelor=0; Double_t dcaForLc = PropagateToDCA(v0part,bachelor,fBzkG, xVtxLc, yVtxLc, zVtxLc, pxVtxBachelor, pyVtxBachelor, pzVtxBachelor); fCandidateVariables[iVariable++] = dcaForLc; fCandidateVariables[iVariable++] = part->CosThetaStar(0,4122,2212,310); fCandidateVariables[iVariable++] = part->CosThetaStar(1,4122,2212,310); fCandidateVariables[iVariable++] = v0part->Eta(); fCandidateVariables[iVariable++] = v0part->Y(310); fCandidateVariables[iVariable++] = part->InvMass2Prongs(0,1,211,310); // Kstar( 892)+ -> pi+K0S fCandidateVariables[iVariable++] = part->InvMass2Prongs(0,1,321,310); // Kstar(1430)+ -> pi+K0S fCandidateVariables[iVariable++] = part->GetSecVtxX(); fCandidateVariables[iVariable++] = part->GetSecVtxY(); fCandidateVariables[iVariable++] = part->GetSecVtxZ(); fCandidateVariables[iVariable++] = xVtxLc; fCandidateVariables[iVariable++] = yVtxLc; fCandidateVariables[iVariable++] = zVtxLc; fCandidateVariables[iVariable++] = bachelor->Px(); fCandidateVariables[iVariable++] = bachelor->Py(); fCandidateVariables[iVariable++] = pxVtxBachelor; fCandidateVariables[iVariable++] = pyVtxBachelor; fCandidateVariables[iVariable++] = pzVtxBachelor; fCandidateVariables[iVariable++] = v0part->Px(); fCandidateVariables[iVariable++] = v0part->Py(); fCandidateVariables[iVariable++] = v0part->Pz(); fCandidateVariables[iVariable++] = fVtx1->GetX(); fCandidateVariables[iVariable++] = fVtx1->GetY(); fCandidateVariables[iVariable++] = fVtx1->GetZ(); if (fUseMCInfo) { Double_t xLcMC=0,yLcMC=0,zLcMC=0; if (isLc) { Int_t pdgCand0 = 4122; Int_t pdgDgLctoV0bachelor0[2]={2212,310}; Int_t pdgDgV0toDaughters0[2]={211,211}; Int_t mcLabel0 = part->MatchToMC(pdgCand0,pdgDgLctoV0bachelor0[1],pdgDgLctoV0bachelor0,pdgDgV0toDaughters0,mcArray,kTRUE); AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel0)); if(partLc){ AliAODMCParticle *partLcDaug0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(partLc->GetDaughterLabel(0))); if(partLcDaug0){ xLcMC=partLcDaug0->Xv(), yLcMC=partLcDaug0->Yv(), zLcMC=partLcDaug0->Zv(); } } } else if (isLc2LBarpi || isLc2Lpi) { AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel)); AliAODMCParticle *partLcDaug0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(partLc->GetDaughterLabel(0))); xLcMC=partLcDaug0->Xv(), yLcMC=partLcDaug0->Yv(), zLcMC=partLcDaug0->Zv(); } else if (isDp2K0Spi) { AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel2)); AliAODMCParticle *partLcDaug0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(partLc->GetDaughterLabel(0))); xLcMC=partLcDaug0->Xv(), yLcMC=partLcDaug0->Yv(), zLcMC=partLcDaug0->Zv(); } else if (isDs2K0SK) { AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel3)); AliAODMCParticle *partLcDaug0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(partLc->GetDaughterLabel(0))); xLcMC=partLcDaug0->Xv(), yLcMC=partLcDaug0->Yv(), zLcMC=partLcDaug0->Zv(); } else if (isKstar12K0Spi) { AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel4)); AliAODMCParticle *partLcDaug0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(partLc->GetDaughterLabel(0))); xLcMC=partLcDaug0->Xv(), yLcMC=partLcDaug0->Yv(), zLcMC=partLcDaug0->Zv(); } else if (isKstar22K0Spi) { AliAODMCParticle *partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(mcLabel5)); AliAODMCParticle *partLcDaug0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(partLc->GetDaughterLabel(0))); xLcMC=partLcDaug0->Xv(), yLcMC=partLcDaug0->Yv(), zLcMC=partLcDaug0->Zv(); } fCandidateVariables[iVariable++] = xLcMC; fCandidateVariables[iVariable++] = yLcMC; fCandidateVariables[iVariable++] = zLcMC; } } delete objectPIDCombined; fVariablesTree->Fill(); AliWarning(Form("IL NUMERO DI VARIABILI E' %d",iVariable)); return; } //------------------------------------------------------------------------------- void AliAnalysisTaskSELc2V0bachelor::DefineTreeVariables() { // /// This is to define tree variables // const char* nameoutput = GetOutputSlot(4)->GetContainer()->GetName(); fVariablesTree = new TTree(nameoutput,"Candidates variables tree"); Int_t nVar = 30; if (fUseMCInfo) nVar += 7; if (fAdditionalChecks) { nVar += 56; if (fUseMCInfo) nVar += 3; } fCandidateVariables = new Float_t [nVar]; Int_t ii=0; TString * fCandidateVariableNames = new TString[nVar]; fCandidateVariableNames[ii++]="isLcByMC"; fCandidateVariableNames[ii++]="isV0ByMC"; fCandidateVariableNames[ii++]="flagToCheckBachelor"; fCandidateVariableNames[ii++]="flagToCheckV0daughters"; fCandidateVariableNames[ii++]="flagToCheckCandidate"; fCandidateVariableNames[ii++]="massLc2K0Sp"; fCandidateVariableNames[ii++]="massLc2Lambdapi"; fCandidateVariableNames[ii++]="massD2K0Spi"; // D+ -> pi+ K0S fCandidateVariableNames[ii++]="massDS2K0SK"; // D+S -> K+ K0S fCandidateVariableNames[ii++]="massK0S"; fCandidateVariableNames[ii++]="massLambda"; fCandidateVariableNames[ii++]="massLambdaBar"; fCandidateVariableNames[ii++]="massGamma"; fCandidateVariableNames[ii++]="tImpParBach"; fCandidateVariableNames[ii++]="tImpParV0"; fCandidateVariableNames[ii++]="cosPAK0S"; fCandidateVariableNames[ii++]="LcPt"; // @ DCA fCandidateVariableNames[ii++]="v0Pt"; // @ V0 DCA fCandidateVariableNames[ii++]="bachelorP"; // @ prim vtx fCandidateVariableNames[ii++]="bachelorPt"; // @ prim vtx fCandidateVariableNames[ii++]="V0positivePt"; // @ prim vtx fCandidateVariableNames[ii++]="V0negativePt"; // @ prim vtx fCandidateVariableNames[ii++]="bachelorCharge"; fCandidateVariableNames[ii++]="qtProng0V0"; fCandidateVariableNames[ii++]="alphaArm"; fCandidateVariableNames[ii++]="nSigmaTPCpr"; fCandidateVariableNames[ii++]="nSigmaTOFpr"; fCandidateVariableNames[ii++]="combinedProtonProb"; fCandidateVariableNames[ii++]="TPCProtonProb"; fCandidateVariableNames[ii++]="TOFProtonProb"; if (fUseMCInfo) { fCandidateVariableNames[ii++]="isMCparticleInFiducialAcceptance"; fCandidateVariableNames[ii++]="pdgBachelor"; // pdg MC bachelor fCandidateVariableNames[ii++]="pdgCandidate"; // pdg MC candidate recovered via new method fCandidateVariableNames[ii++]="pdgV0pos"; // pdg MC V0 positive fCandidateVariableNames[ii++]="pdgV0neg"; // pdg MC V0 negative fCandidateVariableNames[ii++]="pdgV0Candidate"; // pdg MC V0candidate recovered via new method fCandidateVariableNames[ii++]="checkLcOrigin"; } if (fAdditionalChecks) { // ------------------------------siamo qui! fCandidateVariableNames[ii++]="LcP"; // @ DCA fCandidateVariableNames[ii++]="v0P"; // @ V0 DCA fCandidateVariableNames[ii++]="V0positiveP"; // @ prim vtx fCandidateVariableNames[ii++]="V0negativeP"; // @ prim vtx fCandidateVariableNames[ii++]="nSigmaTPCpi"; fCandidateVariableNames[ii++]="nSigmaTPCka"; fCandidateVariableNames[ii++]="nSigmaTOFpi"; fCandidateVariableNames[ii++]="nSigmaTOFka"; fCandidateVariableNames[ii++]="startTimeMask"; // start time mask fCandidateVariableNames[ii++]="dcaLcptp"; // DCA Lc prong-to-prong fCandidateVariableNames[ii++]="dcaV0ptp"; fCandidateVariableNames[ii++]="dcaV0postoPV"; fCandidateVariableNames[ii++]="dcaV0negtoPV"; fCandidateVariableNames[ii++]="cosPALc"; fCandidateVariableNames[ii++]="rhoV0"; fCandidateVariableNames[ii++]="nSigmaITSpr"; fCandidateVariableNames[ii++]="nSigmaITSpi"; fCandidateVariableNames[ii++]="nSigmaITSka"; fCandidateVariableNames[ii++]="yLc"; fCandidateVariableNames[ii++]="etaBach"; // etaBachelor fCandidateVariableNames[ii++]="etaV0pos"; // etaV0pos fCandidateVariableNames[ii++]="etaV0neg"; // etaV0neg fCandidateVariableNames[ii++]="decayLengthLc"; fCandidateVariableNames[ii++]="decayLengthV0"; fCandidateVariableNames[ii++]="cosPALcXY"; // cosPA XY x Lc fCandidateVariableNames[ii++]="cosPAV0XY"; // cosPA XY x V0 fCandidateVariableNames[ii++]="decayLengthLcXY"; // decay length XY x Lc fCandidateVariableNames[ii++]="decayLengthV0XY"; // decay length XY x V0 fCandidateVariableNames[ii++]="normalizedDecayLengthLc"; // normalized decay length x Lc fCandidateVariableNames[ii++]="normalizedDecayLengthV0"; // normalized decay length x V0 fCandidateVariableNames[ii++]="normalizedDecayLengthXYLc"; // normalized decay length XY x Lc fCandidateVariableNames[ii++]="normalizedDecayLengthXYV0"; // normalized decay length XY x V0 fCandidateVariableNames[ii++]="newLcDCA"; fCandidateVariableNames[ii++]="cosThetaStarBachelor"; fCandidateVariableNames[ii++]="cosThetaStarV0"; fCandidateVariableNames[ii++]="etaV0"; fCandidateVariableNames[ii++]="yV0"; fCandidateVariableNames[ii++]="massKstar12K0Spi"; // Kstar( 892)+ -> pi+ K0S fCandidateVariableNames[ii++]="massKstar22K0Spi"; // Kstar(1430)+ -> pi+ K0S fCandidateVariableNames[ii++]="xVtxLcBad"; fCandidateVariableNames[ii++]="yVtxLcBad"; fCandidateVariableNames[ii++]="zVtxLcBad"; fCandidateVariableNames[ii++]="xVtxLcGood"; fCandidateVariableNames[ii++]="yVtxLcGood"; fCandidateVariableNames[ii++]="zVtxLcGood"; fCandidateVariableNames[ii++]="pxVtxBachelorBad"; fCandidateVariableNames[ii++]="pyVtxBachelorBad"; fCandidateVariableNames[ii++]="pxVtxBachelorGood"; fCandidateVariableNames[ii++]="pyVtxBachelorGood"; fCandidateVariableNames[ii++]="pzVtxBachelorGood"; fCandidateVariableNames[ii++]="pxVtxV0"; fCandidateVariableNames[ii++]="pyVtxV0"; fCandidateVariableNames[ii++]="pzVtxV0"; fCandidateVariableNames[ii++]="xPvtx"; fCandidateVariableNames[ii++]="yPvtx"; fCandidateVariableNames[ii++]="zPvtx"; if (fUseMCInfo) { fCandidateVariableNames[ii++]="xVtxLcMC"; fCandidateVariableNames[ii++]="yVtxLcMC"; fCandidateVariableNames[ii++]="zVtxLcMC"; } } if (ii!=nVar) AliError(Form("Please, check the number of tree variables: %d vs %d",nVar,ii)); for (Int_t ivar=0; ivar<nVar; ivar++) { fVariablesTree->Branch(fCandidateVariableNames[ivar].Data(),&fCandidateVariables[ivar],Form("%s/f",fCandidateVariableNames[ivar].Data())); } return; } //__________________________________________________________________________ void AliAnalysisTaskSELc2V0bachelor::DefineGeneralHistograms() { // /// This is to define general histograms // fCEvents = new TH1F("fCEvents","conter",20,0,20); fCEvents->SetStats(kTRUE); fCEvents->GetXaxis()->SetBinLabel(1,"X1"); fCEvents->GetXaxis()->SetBinLabel(2,"Analyzed events"); fCEvents->GetXaxis()->SetBinLabel(3,"AliAODVertex exists"); fCEvents->GetXaxis()->SetBinLabel(4,"CascadesHF exists"); fCEvents->GetXaxis()->SetBinLabel(5,"MCarray exists"); fCEvents->GetXaxis()->SetBinLabel(6,"MCheader exists"); fCEvents->GetXaxis()->SetBinLabel(7,"GetNContributors()>0"); fCEvents->GetXaxis()->SetBinLabel(8,"IsEventSelected"); fCEvents->GetXaxis()->SetBinLabel(9,"triggerClass!=CINT1"); fCEvents->GetXaxis()->SetBinLabel(10,"triggerMask!=kAnyINT"); fCEvents->GetXaxis()->SetBinLabel(11,"triggerMask!=kAny"); fCEvents->GetXaxis()->SetBinLabel(12,"vtxTitle.Contains(Z)"); fCEvents->GetXaxis()->SetBinLabel(13,"vtxTitle.Contains(3D)"); fCEvents->GetXaxis()->SetBinLabel(14,"vtxTitle.Doesn'tContain(Z-3D)"); fCEvents->GetXaxis()->SetBinLabel(15,Form("zVtx<=%2.0fcm",fAnalCuts->GetMaxVtxZ())); fCEvents->GetXaxis()->SetBinLabel(16,"!IsEventSelected"); fCEvents->GetXaxis()->SetBinLabel(17,"triggerMask!=kAnyINT || triggerClass!=CINT1"); fCEvents->GetXaxis()->SetBinLabel(18,Form("zVtxMC<=%2.0fcm",fAnalCuts->GetMaxVtxZ())); fCEvents->GetXaxis()->SetBinLabel(19,"Re-Fill Fail"); fCEvents->GetXaxis()->SetBinLabel(20,"AOD Mismatch"); //fCEvents->GetXaxis()->SetTitle(""); fCEvents->GetYaxis()->SetTitle("counts"); fOutput->Add(fCEvents); TString fillthis=""; if (fUseMCInfo && fAdditionalChecks) { fillthis="histMcStatLc"; TH1F* mcStatisticLc = new TH1F(fillthis.Data(),"#Lambda_{c} generated and their decays",21,-10.5,10.5); fOutput->Add(mcStatisticLc); } //fillthis="histopionV0SigmaVspTOF"; //TH2F *hpionV0SigmaVspTOF=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); fillthis="histoprotonBachSigmaVspTOF"; TH2F *hprotonBachSigmaVspTOF=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); //fOutput->Add(hpionV0SigmaVspTOF); fOutput->Add(hprotonBachSigmaVspTOF); //fillthis="histopionV0SigmaVspTPC"; //TH2F *hpionV0SigmaVspTPC=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); fillthis="histoprotonBachSigmaVspTPC"; TH2F *hprotonBachSigmaVspTPC=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); //fOutput->Add(hpionV0SigmaVspTPC); fOutput->Add(hprotonBachSigmaVspTPC); if (fUseMCInfo) { //fillthis="histopionV0SigmaVspTOFsgn"; //TH2F *hpionV0SigmaVspTOFsgn=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); fillthis="histoprotonBachSigmaVspTOFsgn"; TH2F *hprotonBachSigmaVspTOFsgn=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); //fOutput->Add(hpionV0SigmaVspTOFsgn); fOutput->Add(hprotonBachSigmaVspTOFsgn); //fillthis="histopionV0SigmaVspTPCsgn"; //TH2F *hpionV0SigmaVspTPCsgn=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); fillthis="histoprotonBachSigmaVspTPCsgn"; TH2F *hprotonBachSigmaVspTPCsgn=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); //fOutput->Add(hpionV0SigmaVspTPCsgn); fOutput->Add(hprotonBachSigmaVspTPCsgn); //fillthis="histopionV0SigmaVspTOFbkg"; //TH2F *hpionV0SigmaVspTOFbkg=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); fillthis="histoprotonBachSigmaVspTOFbkg"; TH2F *hprotonBachSigmaVspTOFbkg=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); //fOutput->Add(hpionV0SigmaVspTOFbkg); fOutput->Add(hprotonBachSigmaVspTOFbkg); //fillthis="histopionV0SigmaVspTPCbkg"; //TH2F *hpionV0SigmaVspTPCbkg=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); fillthis="histoprotonBachSigmaVspTPCbkg"; TH2F *hprotonBachSigmaVspTPCbkg=new TH2F(fillthis.Data(),fillthis.Data(),300,0.,30.,100,-5.,5.); //fOutput->Add(hpionV0SigmaVspTPCbkg); fOutput->Add(hprotonBachSigmaVspTPCbkg); } if (fAdditionalChecks) { TH1F *hZ2 = new TH1F("hZ2","",100,-50.,50.); fOutput->Add(hZ2); TH1F *hZ3 = new TH1F("hZ3","",100,-50.,50.); fOutput->Add(hZ3); TH1F *hZ4 = new TH1F("hZ4","",100,-50.,50.); fOutput->Add(hZ4); TH1F *hZ5 = new TH1F("hZ5","",100,-50.,50.); fOutput->Add(hZ5); TH1F *hZ6 = new TH1F("hZ6","",100,-50.,50.); fOutput->Add(hZ6); TH1F *hZ7 = new TH1F("hZ7","",100,-50.,50.); fOutput->Add(hZ7); TH1F *hZ8 = new TH1F("hZ8","",100,-50.,50.); fOutput->Add(hZ8); TH1F *hZ9 = new TH1F("hZ9","",100,-50.,50.); fOutput->Add(hZ9); TH1F *hZ10 = new TH1F("hZ10","",100,-50.,50.); fOutput->Add(hZ10); TH1F *hZ11 = new TH1F("hZ11","",100,-50.,50.); fOutput->Add(hZ11); TH1F *hZ12 = new TH1F("hZ12","",100,-50.,50.); fOutput->Add(hZ12); TH1F *hZ13 = new TH1F("hZ13","",100,-50.,50.); fOutput->Add(hZ13); TH1F *hZ14 = new TH1F("hZ14","",100,-50.,50.); fOutput->Add(hZ14); TH1F *hZ15 = new TH1F("hZ15","",100,-50.,50.); fOutput->Add(hZ15); TH1F *hZ16 = new TH1F("hZ16","",100,-50.,50.); fOutput->Add(hZ16); } TH1F *hCandidateSelection = new TH1F("hCandidateSelection","",10,-0.5,9.5); hCandidateSelection->GetXaxis()->SetBinLabel(1,"IsEventSelected"); hCandidateSelection->GetXaxis()->SetBinLabel(2,"IsSecondaryVtx"); hCandidateSelection->GetXaxis()->SetBinLabel(3,"V0toPosNeg"); hCandidateSelection->GetXaxis()->SetBinLabel(4,"offlineV0"); hCandidateSelection->GetXaxis()->SetBinLabel(5,"isInFiducialAcceptance"); hCandidateSelection->GetXaxis()->SetBinLabel(6,"analCuts::kTracks"); hCandidateSelection->GetXaxis()->SetBinLabel(7,"analCuts::kCandidateNoPID"); hCandidateSelection->GetXaxis()->SetBinLabel(8,"analCuts::kPID"); hCandidateSelection->GetXaxis()->SetBinLabel(9,"analCuts::kCandidateWithPID"); hCandidateSelection->GetXaxis()->SetBinLabel(10,"analCuts::kAll"); fOutput->Add(hCandidateSelection); TH1F *hEventsWithCandidates = new TH1F("hEventsWithCandidates","conter",11,5.5,16.5); hEventsWithCandidates->GetXaxis()->SetBinLabel(1,"GetNContributors()>0"); hEventsWithCandidates->GetXaxis()->SetBinLabel(2,"IsEventSelected"); hEventsWithCandidates->GetXaxis()->SetBinLabel(3,"triggerClass!=CINT1"); hEventsWithCandidates->GetXaxis()->SetBinLabel(4,"triggerMask!=kAnyINT"); hEventsWithCandidates->GetXaxis()->SetBinLabel(5,"triggerMask!=kAny"); hEventsWithCandidates->GetXaxis()->SetBinLabel(6,"vtxTitle.Contains(Z)"); hEventsWithCandidates->GetXaxis()->SetBinLabel(7,"vtxTitle.Contains(3D)"); hEventsWithCandidates->GetXaxis()->SetBinLabel(8,"vtxTitle.Doesn'tContain(Z-3D)"); hEventsWithCandidates->GetXaxis()->SetBinLabel(9,Form("zVtx<=%2.0fcm",fAnalCuts->GetMaxVtxZ())); hEventsWithCandidates->GetXaxis()->SetBinLabel(10,"!IsEventSelected"); hEventsWithCandidates->GetXaxis()->SetBinLabel(11,"triggerMask!=kAnyINT || triggerClass!=CINT1"); fOutput->Add(hEventsWithCandidates); if (fAdditionalChecks) { TH1F *hZ6a = new TH1F("hZ6a","",100,-50.,50.); fOutput->Add(hZ6a); TH1F *hZ7a = new TH1F("hZ7a","",100,-50.,50.); fOutput->Add(hZ7a); TH1F *hZ8a = new TH1F("hZ8a","",100,-50.,50.); fOutput->Add(hZ8a); TH1F *hZ9a = new TH1F("hZ9a","",100,-50.,50.); fOutput->Add(hZ9a); TH1F *hZ10a = new TH1F("hZ10a","",100,-50.,50.); fOutput->Add(hZ10a); TH1F *hZ11a = new TH1F("hZ11a","",100,-50.,50.); fOutput->Add(hZ11a); TH1F *hZ12a = new TH1F("hZ12a","",100,-50.,50.); fOutput->Add(hZ12a); TH1F *hZ13a = new TH1F("hZ13a","",100,-50.,50.); fOutput->Add(hZ13a); TH1F *hZ14a = new TH1F("hZ14a","",100,-50.,50.); fOutput->Add(hZ14a); TH1F *hZ15a = new TH1F("hZ15a","",100,-50.,50.); fOutput->Add(hZ15a); TH1F *hZ16a = new TH1F("hZ16a","",100,-50.,50.); fOutput->Add(hZ16a); } TH1F *hSwitchOnCandidates1 = new TH1F("hSwitchOnCandidates1","",15,-7.5,7.5); fOutput->Add(hSwitchOnCandidates1); TH1F *hSwitchOnCandidates2 = new TH1F("hSwitchOnCandidates2","",15,-7.5,7.5); fOutput->Add(hSwitchOnCandidates2); TH1F *hSwitchOnCandidates3 = new TH1F("hSwitchOnCandidates3","",15,-7.5,7.5); fOutput->Add(hSwitchOnCandidates3); TH1F *hSwitchOnCandidates4 = new TH1F("hSwitchOnCandidates4","",15,-7.5,7.5); fOutput->Add(hSwitchOnCandidates4); return; } //________________________________________________________________________ void AliAnalysisTaskSELc2V0bachelor::FillAnalysisHistograms(AliAODRecoCascadeHF *part, AliRDHFCutsLctoV0 *cutsAnal, TString appendthis, AliAODEvent *aod) { // // This is to fill analysis histograms // TString fillthis=""; Bool_t isBachelorID = (((cutsAnal->IsSelected(part,AliRDHFCuts::kPID, aod))&(AliRDHFCutsLctoV0::kLcToK0Spr))==(AliRDHFCutsLctoV0::kLcToK0Spr)); // ID x bachelor Bool_t areCutsUsingPID = cutsAnal->GetIsUsePID(); cutsAnal->SetUsePID(kFALSE); Double_t invmassLc = part->InvMassLctoK0sP(); Double_t lambdacpt = part->Pt(); AliAODTrack *bachelor = (AliAODTrack*)part->GetBachelor(); Double_t momBach = bachelor->P(); Double_t ptBach = bachelor->Pt(); AliAODv0 *v0part = (AliAODv0*)part->Getv0(); Double_t momK0S = v0part->P(); Double_t ptK0S = v0part->Pt(); //Double_t dcaV0ptp = v0part->GetDCA(); Double_t invmassK0S = v0part->MassK0Short(); AliAODTrack *v0pos = (AliAODTrack*)part->Getv0PositiveTrack(); Double_t ptV0pos = v0pos->Pt(); AliAODTrack *v0neg = (AliAODTrack*)part->Getv0NegativeTrack(); Double_t ptV0neg = v0neg->Pt(); if (!appendthis.Contains("SgnC") && !appendthis.Contains("SgnB") && !appendthis.Contains("SgnNoQ")) { fillthis="histpK0Svsp"+appendthis; //cout << fillthis << endl; if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(momBach,momK0S); if (isBachelorID) ((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(momBach,momK0S); } } fillthis="histLcMassByK0S"+appendthis; //cout << fillthis << endl; if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(invmassLc,lambdacpt); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(invmassLc,lambdacpt); } if(fFillSubSampleHist && appendthis=="Offline"){ fillthis="histLcMassByK0SSubSample"+appendthis; if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { Double_t contsp[3];contsp[0]=invmassLc;contsp[1]=lambdacpt;contsp[2]=(Double_t)(fEventCounter%24); if (isBachelorID)((THnSparse*)(fOutputPIDBach->FindObject(fillthis)))->Fill(contsp); } } if (!appendthis.Contains("SgnC") && !appendthis.Contains("SgnB") && !appendthis.Contains("SgnNoQ")) { fillthis="histK0SMass"+appendthis; // cout << fillthis << endl; cutsAnal->SetExcludedCut(2); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,invmassK0S); if (isBachelorID) ((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,invmassK0S); } cutsAnal->SetExcludedCut(-1); } fillthis="histptK0S"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(15); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,ptK0S); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,ptK0S); } fillthis="histptP"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(4); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,ptBach); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,ptBach); } fillthis="histptPip"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(5); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,ptV0pos); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,ptV0pos); } fillthis="histptPim"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(6); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,ptV0neg); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,ptV0neg); } if (!appendthis.Contains("SgnC") && !appendthis.Contains("SgnB") && !appendthis.Contains("SgnNoQ")) { fillthis="histLambdaMass"+appendthis; // cout << fillthis << endl; cutsAnal->SetExcludedCut(13); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,v0part->MassLambda()); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,v0part->MassLambda()); } fillthis="histLambdaBarMass"+appendthis; // cout << fillthis << endl; cutsAnal->SetExcludedCut(13); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,v0part->MassAntiLambda()); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,v0part->MassAntiLambda()); } fillthis="histGammaMass"+appendthis; // cout << fillthis << endl; cutsAnal->SetExcludedCut(14); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,v0part->InvMass2Prongs(0,1,11,11)); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,v0part->InvMass2Prongs(0,1,11,11)); } } fillthis="histD0K0S"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(11); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,part->Getd0Prong(1)); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,part->Getd0Prong(1)); } fillthis="histD0P"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(10); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,part->Getd0Prong(0)); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,part->Getd0Prong(0)); } fillthis="histCosPAK0S"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(9); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,part->CosV0PointingAngle()); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,part->CosV0PointingAngle()); } fillthis="histCosThetaProtonCMS"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(16); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,cutsAnal->GetProtonEmissionAngleCMS(part)); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,cutsAnal->GetProtonEmissionAngleCMS(part)); } fillthis="histResignedD0"+appendthis; //cout << fillthis << endl; cutsAnal->SetExcludedCut(18); if ( ((cutsAnal->IsSelected(part,AliRDHFCuts::kCandidate,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputAll->FindObject(fillthis)))->Fill(lambdacpt,cutsAnal->GetReSignedd0(part)); if (isBachelorID)((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(lambdacpt,cutsAnal->GetReSignedd0(part)); } cutsAnal->SetExcludedCut(-1); cutsAnal->SetUsePID(areCutsUsingPID); return; } //--------------------------- Double_t AliAnalysisTaskSELc2V0bachelor::PropagateToDCA(AliAODv0 *v, AliAODTrack *bachelor, Double_t b, Double_t &xVtxLc, Double_t &yVtxLc, Double_t &zVtxLc, Double_t &pxVtxBachelor, Double_t &pyVtxBachelor, Double_t &pzVtxBachelor) { //-------------------------------------------------------------------- /// This function returns the DCA between the V0 and the track /// This is a copy of AliCascadeVertexer::PropagateToDCA(...) method //-------------------------------------------------------------------- // Get AliExternalTrackParam out of the AliAODTracks Double_t xyz[3], pxpypz[3], cv[21]; Short_t sign; bachelor->PxPyPz(pxpypz); bachelor->XvYvZv(xyz); bachelor->GetCovarianceXYZPxPyPz(cv); sign=bachelor->Charge(); AliExternalTrackParam *t = new AliExternalTrackParam(xyz,pxpypz,cv,sign); Double_t alpha=t->GetAlpha(), cs1=TMath::Cos(alpha), sn1=TMath::Sin(alpha); //Double_t alpha = GetAlpha(xyz,pxpypz), cs1=TMath::Cos(alpha), sn1=TMath::Sin(alpha); // position and momentum of bachelor Double_t x1=xyz[0], y1=xyz[1], z1=xyz[2]; Double_t px1=pxpypz[0], py1=pxpypz[1], pz1=pxpypz[2]; // position and momentum of V0 Double_t x2=v->DecayVertexV0X(), y2=v->DecayVertexV0Y(), z2=v->DecayVertexV0Z(); Double_t px2=v->Px(), py2=v->Py(), pz2=v->Pz(); /* AliAODTrack *trackP = (AliAODTrack*) v->GetDaughter(0); //Double_t pxpypzP[3]; trackP->PxPyPz(pxpypzP); //Double_t xyzP[3]; trackP->XvYvZv(xyzP); Double_t cvP[21]; trackP->GetCovarianceXYZPxPyPz(cvP); //Short_t signP=trackP->Charge(); //AliExternalTrackParam *tP = new AliExternalTrackParam(xyzP,pxpypzP,cvP,signP); // Get AliExternalTrackParam out of the AliAODTrack AliAODTrack *trackN = (AliAODTrack*) v->GetDaughter(1); //Double_t pxpypzN[3]; trackN->PxPyPz(pxpypzN); //Double_t xyzN[3]; trackN->XvYvZv(xyzN); Double_t cvN[21]; trackN->GetCovarianceXYZPxPyPz(cvN); //Short_t signN=trackN->Charge(); //AliExternalTrackParam *tN = new AliExternalTrackParam(xyzN,pxpypzN,cvN,signN); Double_t xyzV0[3]={x2,y2,z2}; Double_t pxpypzV0[3]={px2,py2,pz2}; Double_t cvV0[21]; for (Int_t ii=0; ii<21; ii++) cvV0[ii]=cvP[ii]+cvN[ii]; AliNeutralTrackParam *trackV0 = new AliNeutralTrackParam(xyzV0,pxpypzV0,cvV0,0); */ // calculation dca Double_t dd= Det(x2-x1,y2-y1,z2-z1,px1,py1,pz1,px2,py2,pz2); Double_t ax= Det(py1,pz1,py2,pz2); Double_t ay=-Det(px1,pz1,px2,pz2); Double_t az= Det(px1,py1,px2,py2); Double_t dca=TMath::Abs(dd)/TMath::Sqrt(ax*ax + ay*ay + az*az); // bachelor point @ the DCA Double_t t1 = Det(x2-x1,y2-y1,z2-z1,px2,py2,pz2,ax,ay,az)/ Det(px1,py1,pz1,px2,py2,pz2,ax,ay,az); x1 += px1*t1; y1 += py1*t1; z1 += pz1*t1; //propagate track to the point of DCA Double_t rho1=x1*cs1 + y1*sn1; if (!t->PropagateTo(rho1,b)) { Error("PropagateToDCA","Propagation failed !"); delete t; t=NULL; return 1.e+33; } Double_t pBachelorDCA[3]; t->GetPxPyPz(pBachelorDCA); pxVtxBachelor=pBachelorDCA[0], pyVtxBachelor=pBachelorDCA[1], pzVtxBachelor=pBachelorDCA[2]; delete t; t=NULL; // V0 point @ the DCA Double_t t2 = Det(x1-x2,y1-y2,z1-z2,px1,py1,pz1,ax,ay,az)/ Det(px2,py2,pz2,px1,py1,pz1,ax,ay,az); x2 += px2*t2; y2 += py2*t2; z2 += pz2*t2; // Lc decay vtx xVtxLc = 0.5*(x1+x2); yVtxLc = 0.5*(y1+y2); zVtxLc = 0.5*(z1+z2); return dca; } //--------------------------- Double_t AliAnalysisTaskSELc2V0bachelor::GetAlpha(Double_t xyz[3],Double_t pxpypz[3]) { // /// To estimate alpha according to what done in the AliExternalTrackParam::Set(...) method // Double_t alpha = 0.; const double kSafe = 1e-5; Double_t radPos2 = xyz[0]*xyz[0]+xyz[1]*xyz[1]; Double_t radMax = 45.; // approximately ITS outer radius if (radPos2 < radMax*radMax) { // inside the ITS alpha = TMath::ATan2(pxpypz[1],pxpypz[0]); } else { // outside the ITS Float_t phiPos = TMath::Pi()+TMath::ATan2(-xyz[1], -xyz[0]); alpha = TMath::DegToRad()*(20*((((Int_t)(phiPos*TMath::RadToDeg()))/20))+10); } Double_t cs=TMath::Cos(alpha), sn=TMath::Sin(alpha); // protection: avoid alpha being too close to 0 or +-pi/2 if (TMath::Abs(sn)<2*kSafe) { if (alpha>0) alpha += alpha< TMath::Pi()/2. ? 2*kSafe : -2*kSafe; else alpha += alpha>-TMath::Pi()/2. ? -2*kSafe : 2*kSafe; cs=TMath::Cos(alpha); sn=TMath::Sin(alpha); } else if (TMath::Abs(cs)<2*kSafe) { if (alpha>0) alpha += alpha> TMath::Pi()/2. ? 2*kSafe : -2*kSafe; else alpha += alpha>-TMath::Pi()/2. ? 2*kSafe : -2*kSafe; cs=TMath::Cos(alpha); sn=TMath::Sin(alpha); } return alpha; } //--------------------------- Double_t AliAnalysisTaskSELc2V0bachelor::Det(Double_t a00, Double_t a01, Double_t a10, Double_t a11) const { //-------------------------------------------------------------------- /// This function calculates locally a 2x2 determinant. /// This is a copy of the AliCascadeVertexer::Det(...) method //-------------------------------------------------------------------- return a00*a11 - a01*a10; } //--------------------------- Double_t AliAnalysisTaskSELc2V0bachelor::Det(Double_t a00,Double_t a01,Double_t a02, Double_t a10,Double_t a11,Double_t a12, Double_t a20,Double_t a21,Double_t a22) const { //-------------------------------------------------------------------- /// This function calculates locally a 3x3 determinant /// This is a copy of the AliCascadeVertexer::Det(...) method //-------------------------------------------------------------------- return a00*Det(a11,a12,a21,a22)-a01*Det(a10,a12,a20,a22)+a02*Det(a10,a11,a20,a21); } //---------------------------------------------------------------------------- Int_t AliAnalysisTaskSELc2V0bachelor::MatchToMClabelC(AliAODRecoCascadeHF *candidate, TClonesArray *mcArray) { // /// Check if this candidate is matched to a MC signal Lc -> p K0S + X /// If no, return -1 /// If yes, return label (>=0) of the AliAODMCParticle // AliAODv0 *theV0 = dynamic_cast<AliAODv0*>(candidate->Getv0()); // the V0 AliVTrack *trk = dynamic_cast<AliVTrack*>(candidate->GetBachelor()); // the bachelor if (!trk || !theV0) return -1; if (trk->GetLabel()==-1) return -1; Int_t bachLabels = TMath::Abs(trk->GetLabel()); AliAODMCParticle*bachelorMC = dynamic_cast<AliAODMCParticle*>(mcArray->At(bachLabels)); if (!bachelorMC) return -1; if (TMath::Abs(bachelorMC->GetPdgCode())!=2212) return -1; Int_t indexMotherBach = bachelorMC->GetMother(); if (indexMotherBach==-1) return -1; Int_t pdgDg2prong[2] = {211,211}; Int_t lab2Prong = theV0->MatchToMC(310,mcArray,2,pdgDg2prong); // the V0 if(lab2Prong<0) return -1; AliAODMCParticle*partK0S = dynamic_cast<AliAODMCParticle*>(mcArray->At(lab2Prong)); if (!partK0S) return -1; Int_t indexMotherK0S = partK0S->GetMother(); if (indexMotherK0S==-1) return -1; AliAODMCParticle*partK0 = dynamic_cast<AliAODMCParticle*>(mcArray->At(indexMotherK0S)); if (!partK0) return -1; Int_t indexMotherK0 = partK0->GetMother(); if (indexMotherK0==-1) return -1; if (indexMotherBach!=indexMotherK0) return -1; // p e K0S sono fratelli AliAODMCParticle*partLc = dynamic_cast<AliAODMCParticle*>(mcArray->At(indexMotherK0)); if (!partLc) return -1; Int_t ndg2 = partLc->GetDaughterLabel(1)-partLc->GetDaughterLabel(0)+1; if (ndg2==2) return -1; TString stringaCheck = Form(">>>>>>>> %d -> ",partLc->GetPdgCode()); for(Int_t ii=0; ii<ndg2; ii++) { AliAODMCParticle* partDau=(AliAODMCParticle*)(mcArray->At(partLc->GetDaughterLabel(0)+ii)); stringaCheck.Append(Form(" %d",partDau->GetPdgCode())); } //printf("%s \n",stringaCheck.Data()); return indexMotherBach; } //-------------------------------------------------------------------------- Int_t AliAnalysisTaskSELc2V0bachelor::SearchForCommonMother(TClonesArray *mcArray, Int_t dgLabels[10],Int_t ndg, Int_t &ndgCk, Int_t *pdgDg, Int_t &absLabelMother, Int_t &nDauCand) const { /// /// Check if this candidate is matched to a MC signal /// If no, return 0 /// If yes, return pdgCode of particle /// Int_t lab=-1,labMother=-1,pdgMother=0; AliAODMCParticle *part=0; AliAODMCParticle *mother=0; // loop on daughter labels TArrayI **labelMother = new TArrayI*[ndg]; for(Int_t i=0; i<ndg; i++) labelMother[i] = new TArrayI(0); for(Int_t i=0; i<ndg; i++) { lab = TMath::Abs(dgLabels[i]); if(lab<0) { AliDebug(2,Form("daughter with negative label %d",lab)); delete [] labelMother; return 0; } part = (AliAODMCParticle*)mcArray->At(lab); if(!part) { AliDebug(2,"no MC particle"); delete [] labelMother; return 0; } mother = part; while(mother->GetMother()>=0) { labMother=mother->GetMother(); mother = (AliAODMCParticle*)mcArray->At(labMother); if(!mother) { AliDebug(2,"no MC mother particle"); break; } pdgMother = TMath::Abs(mother->GetPdgCode()); if (pdgMother<10 || (pdgMother>18 && pdgMother<111)) { break; } labelMother[i]->Set(labelMother[i]->GetSize()+1); labelMother[i]->AddAt(labMother,labelMother[i]->GetSize()-1); } } // end loop on daughters TString stringaCheck; for(Int_t i=0; i<ndg; i++) { AliAODMCParticle*part0 = (AliAODMCParticle*)mcArray->At(TMath::Abs(dgLabels[i])); stringaCheck.Append(Form("part[%d]->GetLabel()=%d(%d) | ",i,dgLabels[i],part0->GetPdgCode())); stringaCheck.Append(Form("labelMother[%d] = ",i)); for (Int_t jj=0;jj<labelMother[i]->GetSize(); jj++) stringaCheck.Append(Form("%d, ",labelMother[i]->At(jj))); } AliDebug(2,Form("%s \n",stringaCheck.Data())); Int_t pdgToBeReturned=0; TString stringaCheck2; ndgCk=ndg; pdgDg = new Int_t[ndgCk]; for (Int_t index=1; index<ndg; index++) { Bool_t found=kFALSE; for (Int_t jj=0;jj<labelMother[index]->GetSize(); jj++) { for (Int_t ii=0;ii<labelMother[0]->GetSize(); ii++) { if (labelMother[0]->At(ii)==labelMother[index]->At(jj) && labelMother[0]->At(ii)!=0 && labelMother[0]->At(ii)!=1 && !found) { mother = (AliAODMCParticle*)mcArray->At(labelMother[0]->At(ii)); pdgToBeReturned=mother->GetPdgCode(); absLabelMother=labelMother[0]->At(ii); AliDebug(2,Form("FOUND label for the mother of this candidate: %d (PDG=%d)\n",labelMother[0]->At(ii),pdgToBeReturned)); //mother->Print(); nDauCand=mother->GetNDaughters(); found = kTRUE; AliAODMCParticle *partMC = (AliAODMCParticle*)mcArray->At(dgLabels[0]); pdgDg[0]=partMC->GetPdgCode(); partMC = (AliAODMCParticle*)mcArray->At(dgLabels[index]); pdgDg[index]=partMC->GetPdgCode(); if (index==1) stringaCheck2.Append(Form("found daughters -> %d(%d)",dgLabels[0],pdgDg[0])); stringaCheck2.Append(Form(" %d(%d)",dgLabels[index],pdgDg[index])); break; } } if (found) break; } } stringaCheck2.Prepend(Form("Ecco quanto trovato: %d(%d) with %d daughters; ",absLabelMother,pdgToBeReturned,nDauCand)); AliDebug(2,Form("%s \n",stringaCheck2.Data())); delete [] labelMother; delete [] pdgDg; return pdgToBeReturned; } void AliAnalysisTaskSELc2V0bachelor::TrackRotation(AliRDHFCutsLctoV0 * cuts, AliAODRecoCascadeHF *part, TString appendthis, AliAODEvent *aod) { AliAODRecoCascadeHF *partCopy = new AliAODRecoCascadeHF(*part); Double_t px[2]={partCopy->PxProng(0),partCopy->PxProng(1)}; Double_t py[2]={partCopy->PyProng(0),partCopy->PyProng(1)}; Double_t pz[2]={partCopy->PzProng(0),partCopy->PzProng(1)}; Double_t pt = partCopy->Pt(); Int_t pdgD=4122; UInt_t pdgLc2pK0S[2]={2212,310}; Double_t minv2 = partCopy->InvMass2(2,pdgLc2pK0S); Double_t mass=TMath::Sqrt(minv2); Double_t rapid = partCopy->Y(pdgD); TString fillthis; if ( ( ( (cuts->IsSelected(part,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) ) { fillthis="hMassVsPtVsY"+appendthis; //cout << fillthis << endl; ((TH3F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(mass,pt,rapid); fillthis="phiVSthetaVSpt"+appendthis; //cout << fillthis << endl; ((TH3F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,part->Phi(),part->Theta()); } Int_t nRotated=0; Double_t massRot=0;// calculated later only if candidate is acceptable // Double_t angleProngXY=TMath::ACos((px[0]*px[1]+py[0]*py[1])/TMath::Sqrt((px[0]*px[0]+py[0]*py[0])*(px[1]*px[1]+py[1]*py[1]))); // Double_t ptOrig=pt; Double_t rotStep=(fMaxAngleForRot-fMinAngleForRot)/(fNRotations-1); // -1 is to ensure that the last rotation is done with angle=fMaxAngleForRot for(Int_t irot=0; irot<fNRotations; irot++){ Double_t phirot=fMinAngleForRot+rotStep*irot; Double_t tmpx=px[0]; Double_t tmpy=py[0]; px[0]=tmpx*TMath::Cos(phirot)-tmpy*TMath::Sin(phirot); py[0]=tmpx*TMath::Sin(phirot)+tmpy*TMath::Cos(phirot); partCopy->SetPxPyPzProngs(2,px,py,pz); pt = partCopy->Pt(); minv2 = partCopy->InvMass2(2,pdgLc2pK0S); massRot=TMath::Sqrt(minv2); rapid = partCopy->Y(pdgD); //if(minv2>fMinMass*fMinMass && minv2<fMaxMass*fMaxMass){ if ( cuts->IsInFiducialAcceptance(pt,partCopy->Y(4122)) ) { if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { fillthis="histLcMassByK0S"+appendthis; //cout << fillthis << endl; ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(massRot,pt); fillthis="hMassVsPtVsYRot"+appendthis; //cout << fillthis << endl; ((TH3F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(mass,pt,rapid); fillthis="phiVSthetaVSptRot"+appendthis; //cout << fillthis << endl; ((TH3F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,partCopy->Phi(),partCopy->Theta()); fillthis="hDeltaMass"+appendthis; //cout << fillthis << endl; ((TH1F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(massRot-mass); //if(fFullAnalysis){ //Double_t pointRot[5]={mass,massRot-mass,ptOrig,pt-ptOrig,angleProngXY}; //fillthis="hDeltaMassFullAnalysis"+appendthis; ////cout << fillthis << endl; //((THnSparse*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pointRot); //} nRotated++; //} } // fill additional histos for track-rotated candidates fillthis="histptK0S"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(15); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,TMath::Sqrt(px[1]*px[1]+py[1]*py[1])); } fillthis="histptP"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(4); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,TMath::Sqrt(px[0]*px[0]+py[0]*py[0])); } fillthis="histptPip"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(5); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,(partCopy->Getv0PositiveTrack())->Pt()); } fillthis="histptPim"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(6); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,(partCopy->Getv0NegativeTrack())->Pt()); } fillthis="histLambdaMass"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(13); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,(partCopy->Getv0())->MassLambda()); } fillthis="histLambdaBarMass"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(13); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,(partCopy->Getv0())->MassAntiLambda()); } fillthis="histGammaMass"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(14); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,(partCopy->Getv0())->InvMass2Prongs(0,1,11,11)); } fillthis="histCosPAK0S"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(9); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,partCopy->CosV0PointingAngle()); } fillthis="histCosThetaProtonCMS"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(16); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(pt,cuts->GetProtonEmissionAngleCMS(partCopy)); } fillthis="histResignedD0"+appendthis; //cout << fillthis << endl; cuts->SetExcludedCut(18); if ( ((cuts->IsSelected(partCopy,AliRDHFCuts::kAll,aod))&(AliRDHFCutsLctoV0::kLcToK0Spr)) == (AliRDHFCutsLctoV0::kLcToK0Spr) ) { ((TH2F*)(fOutputPIDBach->FindObject(fillthis)))->Fill(pt,cuts->GetReSignedd0(partCopy)); } cuts->SetExcludedCut(-1); } // isInFiducialAcceptance px[0]=tmpx; py[0]=tmpy; } fillthis="hNormRotated"+appendthis; //cout << fillthis << endl; ((TH1F*)(fOutputPIDBachTR->FindObject(fillthis)))->Fill(nRotated); delete partCopy; return; } //---------------------------------------------------- void AliAnalysisTaskSELc2V0bachelor::DefineSignalHistosSeparatedPerOrigin() { // // Define analysis histograms for SNG separated for origin (from c, from b and from no-quark) // if (!fUseMCInfo) return; if (!fCheckOrigin) return; Double_t mLcPDG = TDatabasePDG::Instance()->GetParticle(4122)->Mass(); Double_t mK0SPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass(); Double_t mMinLambdaPDG = TDatabasePDG::Instance()->GetParticle(2212)->Mass()+ TDatabasePDG::Instance()->GetParticle(211)->Mass(); TString nameHistoSgnC=" ", nameHistoSgnB=" ", nameHistoSgnNoQ=" "; TString titleHistoSgnC=" ", titleHistoSgnB=" ", titleHistoSgnNoQ=" "; // pt(Lc) Double_t *binLimpTLc=new Double_t[11+1]; // 11 pT(Lc) bins binLimpTLc[ 0]= 0.; binLimpTLc[ 1]= 1.; binLimpTLc[ 2]= 2.; binLimpTLc[ 3]= 3.; binLimpTLc[ 4]= 4.; binLimpTLc[ 5]= 5.; binLimpTLc[ 6]= 6.; binLimpTLc[ 7]= 8.; binLimpTLc[ 8]=12.; binLimpTLc[ 9]=17.; binLimpTLc[10]=25.; binLimpTLc[11]=35.; // pt(prong) Double_t *binLimpTprong=new Double_t[41+1]; // 41 pT(prong) bins binLimpTprong[ 0]= 0.0; binLimpTprong[ 1]= 0.1; binLimpTprong[ 2]= 0.2; binLimpTprong[ 3]= 0.3; binLimpTprong[ 4]= 0.4; binLimpTprong[ 5]= 0.5; binLimpTprong[ 6]= 0.6; binLimpTprong[ 7]= 0.7; binLimpTprong[ 8]= 0.8; binLimpTprong[ 9]= 0.9; binLimpTprong[10]= 1.0; binLimpTprong[11]= 1.2; binLimpTprong[12]= 1.4; binLimpTprong[13]= 1.6; binLimpTprong[14]= 1.8; binLimpTprong[15]= 2.0; binLimpTprong[16]= 2.2; binLimpTprong[17]= 2.4; binLimpTprong[18]= 2.6; binLimpTprong[19]= 2.8; binLimpTprong[20]= 3.0; binLimpTprong[21]= 3.5; binLimpTprong[22]= 4.0; binLimpTprong[23]= 4.5; binLimpTprong[24]= 5.0; binLimpTprong[25]= 5.5; binLimpTprong[26]= 6.0; binLimpTprong[27]= 6.5; binLimpTprong[28]= 7.0; binLimpTprong[29]= 7.5; binLimpTprong[30]= 8.0; binLimpTprong[31]= 9.0; binLimpTprong[32]=10.0; binLimpTprong[33]=11.0; binLimpTprong[34]=12.0; binLimpTprong[35]=13.0; binLimpTprong[36]=14.0; binLimpTprong[37]=15.0; binLimpTprong[38]=20.0; binLimpTprong[39]=25.0; binLimpTprong[40]=30.0; binLimpTprong[41]=35.0; if (fUseOnTheFlyV0) { nameHistoSgnC="histLcMassByK0SSgnC"; nameHistoSgnB="histLcMassByK0SSgnB"; nameHistoSgnNoQ="histLcMassByK0SSgnNoQ"; titleHistoSgnC="#Lambda_{c} #leftarrow c - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; titleHistoSgnB="#Lambda_{c} #leftarrow b - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; titleHistoSgnNoQ="#Lambda_{c} #leftarrow no quark - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; TH2F* spectrumLcMassByK0SSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* spectrumLcMassByK0SSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* spectrumLcMassByK0SSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* allspectrumLcMassByK0SSgnC = (TH2F*)spectrumLcMassByK0SSgnC->Clone(); TH2F* allspectrumLcMassByK0SSgnB = (TH2F*) spectrumLcMassByK0SSgnB->Clone(); TH2F* allspectrumLcMassByK0SSgnNoQ = (TH2F*) spectrumLcMassByK0SSgnNoQ->Clone(); TH2F* pidBachspectrumLcMassByK0SSgnC = (TH2F*)spectrumLcMassByK0SSgnC->Clone(); TH2F* pidBachspectrumLcMassByK0SSgnB = (TH2F*) spectrumLcMassByK0SSgnB->Clone(); TH2F* pidBachspectrumLcMassByK0SSgnNoQ = (TH2F*) spectrumLcMassByK0SSgnNoQ->Clone(); fOutputAll->Add(allspectrumLcMassByK0SSgnC); fOutputAll->Add(allspectrumLcMassByK0SSgnB); fOutputAll->Add(allspectrumLcMassByK0SSgnNoQ); fOutputPIDBach->Add(pidBachspectrumLcMassByK0SSgnC); fOutputPIDBach->Add(pidBachspectrumLcMassByK0SSgnB); fOutputPIDBach->Add(pidBachspectrumLcMassByK0SSgnNoQ); nameHistoSgnC="histptK0SSgnC"; nameHistoSgnB="histptK0SSgnB"; nameHistoSgnNoQ="histptK0SSgnNoQ"; titleHistoSgnC="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; TH2F* ptK0SSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptK0SSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptK0SSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histptPSgnC"; nameHistoSgnB="histptPSgnB"; nameHistoSgnNoQ="histptPSgnNoQ"; titleHistoSgnC="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; TH2F* ptPSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histptPipSgnC"; nameHistoSgnB="histptPipSgnB"; nameHistoSgnNoQ="histptPipSgnNoQ"; titleHistoSgnC="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; TH2F* ptPiPSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiPSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiPSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histptPimSgnC"; nameHistoSgnB="histptPimSgnB"; nameHistoSgnNoQ="histptPimSgnNoQ"; titleHistoSgnC="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; TH2F* ptPiMSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiMSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiMSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histD0K0SSgnC"; nameHistoSgnB="histD0K0SSgnB"; nameHistoSgnNoQ="histD0K0SSgnNoQ"; titleHistoSgnC="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; titleHistoSgnB="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; titleHistoSgnNoQ="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; TH2F* d0K0SSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0K0SSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0K0SSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgnC="histD0PSgnC"; nameHistoSgnB="histD0PSgnB"; nameHistoSgnNoQ="histD0PSgnNoQ"; titleHistoSgnC="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; titleHistoSgnB="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; titleHistoSgnNoQ="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; TH2F* d0PSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0PSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0PSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgnC="histCosPAK0SSgnC"; nameHistoSgnB="histCosPAK0SSgnB"; nameHistoSgnNoQ="histCosPAK0SSgnNoQ"; titleHistoSgnC="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnB="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnNoQ="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosPAK0SSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),41,binLimpTprong,100,0.99,1.); TH2F *cosPAK0SSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),41,binLimpTprong,100,0.99,1.); TH2F *cosPAK0SSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),41,binLimpTprong,100,0.99,1.); nameHistoSgnC="histCosThetaProtonCMSSgnC"; nameHistoSgnB="histCosThetaProtonCMSSgnB"; nameHistoSgnNoQ="histCosThetaProtonCMSSgnNoQ"; titleHistoSgnC="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnB="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnNoQ="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosThePrSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),41,binLimpTprong,100,-1.,1.); TH2F *cosThePrSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),41,binLimpTprong,100,-1.,1.); TH2F *cosThePrSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),41,binLimpTprong,100,-1.,1.); nameHistoSgnC="histResignedD0SgnC"; nameHistoSgnB="histResignedD0SgnB"; nameHistoSgnNoQ="histResignedD0SgnNoQ"; titleHistoSgnC="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; titleHistoSgnB="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; titleHistoSgnNoQ="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; TH2F *resignedD0SgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F *resignedD0SgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F *resignedD0SgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F* allptK0SSgnC = (TH2F*)ptK0SSgnC->Clone(); TH2F* allptK0SSgnB = (TH2F*)ptK0SSgnB->Clone(); TH2F* allptK0SSgnNoQ = (TH2F*)ptK0SSgnNoQ->Clone(); TH2F* allptPSgnC = (TH2F*)ptPSgnC->Clone(); TH2F* allptPSgnB = (TH2F*)ptPSgnB->Clone(); TH2F* allptPSgnNoQ = (TH2F*)ptPSgnNoQ->Clone(); TH2F* allptPiPSgnC = (TH2F*)ptPiPSgnC->Clone(); TH2F* allptPiPSgnB = (TH2F*)ptPiPSgnB->Clone(); TH2F* allptPiPSgnNoQ = (TH2F*)ptPiPSgnNoQ->Clone(); TH2F* allptPiMSgnC = (TH2F*)ptPiMSgnC->Clone(); TH2F* allptPiMSgnB = (TH2F*)ptPiMSgnB->Clone(); TH2F* allptPiMSgnNoQ = (TH2F*)ptPiMSgnNoQ->Clone(); TH2F* alld0K0SSgnC = (TH2F*)d0K0SSgnC->Clone(); TH2F* alld0K0SSgnB = (TH2F*)d0K0SSgnB->Clone(); TH2F* alld0K0SSgnNoQ = (TH2F*)d0K0SSgnNoQ->Clone(); TH2F* alld0PSgnC = (TH2F*)d0PSgnC->Clone(); TH2F* alld0PSgnB = (TH2F*)d0PSgnB->Clone(); TH2F* alld0PSgnNoQ = (TH2F*)d0PSgnNoQ->Clone(); TH2F* allcosPAK0SSgnC = (TH2F*)cosPAK0SSgnC->Clone(); TH2F* allcosPAK0SSgnB = (TH2F*)cosPAK0SSgnB->Clone(); TH2F* allcosPAK0SSgnNoQ = (TH2F*)cosPAK0SSgnNoQ->Clone(); TH2F* allcosThePrSgnC = (TH2F*)cosThePrSgnC->Clone(); TH2F* allcosThePrSgnB = (TH2F*)cosThePrSgnB->Clone(); TH2F* allcosThePrSgnNoQ = (TH2F*)cosThePrSgnNoQ->Clone(); TH2F* allresignedD0SgnC = (TH2F*)resignedD0SgnC->Clone(); TH2F* allresignedD0SgnB = (TH2F*)resignedD0SgnB->Clone(); TH2F* allresignedD0SgnNoQ = (TH2F*)resignedD0SgnNoQ->Clone(); TH2F* pidptK0SSgnC = (TH2F*)ptK0SSgnC->Clone(); TH2F* pidptK0SSgnB = (TH2F*)ptK0SSgnB->Clone(); TH2F* pidptK0SSgnNoQ = (TH2F*)ptK0SSgnNoQ->Clone(); TH2F* pidptPSgnC = (TH2F*)ptPSgnC->Clone(); TH2F* pidptPSgnB = (TH2F*)ptPSgnB->Clone(); TH2F* pidptPSgnNoQ = (TH2F*)ptPSgnNoQ->Clone(); TH2F* pidptPiPSgnC = (TH2F*)ptPiPSgnC->Clone(); TH2F* pidptPiPSgnB = (TH2F*)ptPiPSgnB->Clone(); TH2F* pidptPiPSgnNoQ = (TH2F*)ptPiPSgnNoQ->Clone(); TH2F* pidptPiMSgnC = (TH2F*)ptPiMSgnC->Clone(); TH2F* pidptPiMSgnB = (TH2F*)ptPiMSgnB->Clone(); TH2F* pidptPiMSgnNoQ = (TH2F*)ptPiMSgnNoQ->Clone(); TH2F* pidd0K0SSgnC = (TH2F*)d0K0SSgnC->Clone(); TH2F* pidd0K0SSgnB = (TH2F*)d0K0SSgnB->Clone(); TH2F* pidd0K0SSgnNoQ = (TH2F*)d0K0SSgnNoQ->Clone(); TH2F* pidd0PSgnC = (TH2F*)d0PSgnC->Clone(); TH2F* pidd0PSgnB = (TH2F*)d0PSgnB->Clone(); TH2F* pidd0PSgnNoQ = (TH2F*)d0PSgnNoQ->Clone(); TH2F* pidcosPAK0SSgnC = (TH2F*)cosPAK0SSgnC->Clone(); TH2F* pidcosPAK0SSgnB = (TH2F*)cosPAK0SSgnB->Clone(); TH2F* pidcosPAK0SSgnNoQ = (TH2F*)cosPAK0SSgnNoQ->Clone(); TH2F* pidcosThePrSgnC = (TH2F*)cosThePrSgnC->Clone(); TH2F* pidcosThePrSgnB = (TH2F*)cosThePrSgnB->Clone(); TH2F* pidcosThePrSgnNoQ = (TH2F*)cosThePrSgnNoQ->Clone(); TH2F* pidresignedD0SgnC = (TH2F*)resignedD0SgnC->Clone(); TH2F* pidresignedD0SgnB = (TH2F*)resignedD0SgnB->Clone(); TH2F* pidresignedD0SgnNoQ = (TH2F*)resignedD0SgnNoQ->Clone(); fOutputAll->Add(allptK0SSgnC); fOutputAll->Add(allptK0SSgnB); fOutputAll->Add(allptK0SSgnNoQ); fOutputAll->Add(allptPSgnC); fOutputAll->Add(allptPSgnB); fOutputAll->Add(allptPSgnNoQ); fOutputAll->Add(allptPiPSgnC); fOutputAll->Add(allptPiPSgnB); fOutputAll->Add(allptPiPSgnNoQ); fOutputAll->Add(allptPiMSgnC); fOutputAll->Add(allptPiMSgnB); fOutputAll->Add(allptPiMSgnNoQ); fOutputAll->Add(alld0K0SSgnC); fOutputAll->Add(alld0K0SSgnB); fOutputAll->Add(alld0K0SSgnNoQ); fOutputAll->Add(alld0PSgnC); fOutputAll->Add(alld0PSgnB); fOutputAll->Add(alld0PSgnNoQ); fOutputAll->Add(allcosPAK0SSgnC); fOutputAll->Add(allcosPAK0SSgnB); fOutputAll->Add(allcosPAK0SSgnNoQ); fOutputAll->Add(allcosThePrSgnC); fOutputAll->Add(allcosThePrSgnB); fOutputAll->Add(allcosThePrSgnNoQ); fOutputAll->Add(allresignedD0SgnC); fOutputAll->Add(allresignedD0SgnB); fOutputAll->Add(allresignedD0SgnNoQ); fOutputPIDBach->Add(pidptK0SSgnC); fOutputPIDBach->Add(pidptK0SSgnB); fOutputPIDBach->Add(pidptK0SSgnNoQ); fOutputPIDBach->Add(pidptPSgnC); fOutputPIDBach->Add(pidptPSgnB); fOutputPIDBach->Add(pidptPSgnNoQ); fOutputPIDBach->Add(pidptPiPSgnC); fOutputPIDBach->Add(pidptPiPSgnB); fOutputPIDBach->Add(pidptPiPSgnNoQ); fOutputPIDBach->Add(pidptPiMSgnC); fOutputPIDBach->Add(pidptPiMSgnB); fOutputPIDBach->Add(pidptPiMSgnNoQ); fOutputPIDBach->Add(pidd0K0SSgnC); fOutputPIDBach->Add(pidd0K0SSgnB); fOutputPIDBach->Add(pidd0K0SSgnNoQ); fOutputPIDBach->Add(pidd0PSgnC); fOutputPIDBach->Add(pidd0PSgnB); fOutputPIDBach->Add(pidd0PSgnNoQ); fOutputPIDBach->Add(pidcosPAK0SSgnC); fOutputPIDBach->Add(pidcosPAK0SSgnB); fOutputPIDBach->Add(pidcosPAK0SSgnNoQ); fOutputPIDBach->Add(pidcosThePrSgnC); fOutputPIDBach->Add(pidcosThePrSgnB); fOutputPIDBach->Add(pidcosThePrSgnNoQ); fOutputPIDBach->Add(pidresignedD0SgnC); fOutputPIDBach->Add(pidresignedD0SgnB); fOutputPIDBach->Add(pidresignedD0SgnNoQ); } nameHistoSgnC="histLcMassByK0SOfflineSgnC"; nameHistoSgnB="histLcMassByK0SOfflineSgnB"; nameHistoSgnNoQ="histLcMassByK0SOfflineSgnNoQ"; titleHistoSgnC="#Lambda_{c} #leftarrow c - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; titleHistoSgnB="#Lambda_{c} #leftarrow b - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; titleHistoSgnNoQ="#Lambda_{c} #leftarrow no quark - sgn: invariant mass (by K^{0}_{S}) vs p_{T} - MC; m_{inv}(p,K^{0}_{S}) [GeV/c^{2}]; p_{T}(#Lambda_{c}) [GeV/c]"; TH2F* spectrumLcMassOfflineByK0SSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* spectrumLcMassOfflineByK0SSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* spectrumLcMassOfflineByK0SSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),1000,mLcPDG-0.250,mLcPDG+0.250,11,binLimpTLc); TH2F* allspectrumLcMassOfflineByK0SSgnC = (TH2F*)spectrumLcMassOfflineByK0SSgnC->Clone(); TH2F* allspectrumLcMassOfflineByK0SSgnB = (TH2F*) spectrumLcMassOfflineByK0SSgnB->Clone(); TH2F* allspectrumLcMassOfflineByK0SSgnNoQ = (TH2F*) spectrumLcMassOfflineByK0SSgnNoQ->Clone(); TH2F* pidBachspectrumLcMassOfflineByK0SSgnC = (TH2F*)spectrumLcMassOfflineByK0SSgnC->Clone(); TH2F* pidBachspectrumLcMassOfflineByK0SSgnB = (TH2F*) spectrumLcMassOfflineByK0SSgnB->Clone(); TH2F* pidBachspectrumLcMassOfflineByK0SSgnNoQ = (TH2F*) spectrumLcMassOfflineByK0SSgnNoQ->Clone(); fOutputAll->Add(allspectrumLcMassOfflineByK0SSgnC); fOutputAll->Add(allspectrumLcMassOfflineByK0SSgnB); fOutputAll->Add(allspectrumLcMassOfflineByK0SSgnNoQ); fOutputPIDBach->Add(pidBachspectrumLcMassOfflineByK0SSgnC); fOutputPIDBach->Add(pidBachspectrumLcMassOfflineByK0SSgnB); fOutputPIDBach->Add(pidBachspectrumLcMassOfflineByK0SSgnNoQ); nameHistoSgnC="histptK0SOfflineSgnC"; nameHistoSgnB="histptK0SOfflineSgnB"; nameHistoSgnNoQ="histptK0SOfflineSgnNoQ"; titleHistoSgnC="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(K^{0}_{S}) [GeV/c]; Entries"; TH2F* ptK0SOfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptK0SOfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptK0SOfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histptPOfflineSgnC"; nameHistoSgnB="histptPOfflineSgnB"; nameHistoSgnNoQ="histptPOfflineSgnNoQ"; titleHistoSgnC="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(p) [GeV/c]; Entries"; TH2F* ptPOfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPOfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPOfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histptPipOfflineSgnC"; nameHistoSgnB="histptPipOfflineSgnB"; nameHistoSgnNoQ="histptPipOfflineSgnNoQ"; titleHistoSgnC="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(#pi^{+}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{+}) [GeV/c]; Entries"; TH2F* ptPiPOfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiPOfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiPOfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histptPimOfflineSgnC"; nameHistoSgnB="histptPimOfflineSgnB"; nameHistoSgnNoQ="histptPimOfflineSgnNoQ"; titleHistoSgnC="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; titleHistoSgnB="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; titleHistoSgnNoQ="p_{T}(#pi^{-}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; p_{T}(#pi^{-}) [GeV/c]; Entries"; TH2F* ptPiMOfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiMOfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); TH2F* ptPiMOfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnB.Data(),11,binLimpTLc,41,binLimpTprong); nameHistoSgnC="histD0K0SOfflineSgnC"; nameHistoSgnB="histD0K0SOfflineSgnB"; nameHistoSgnNoQ="histD0K0SOfflineSgnNoQ"; titleHistoSgnC="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; titleHistoSgnB="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; titleHistoSgnNoQ="d_{0}(K^{0}_{S}) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(K^{0}_{S}) [#sigmas]; Entries"; TH2F* d0K0SOfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0K0SOfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0K0SOfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgnC="histD0POfflineSgnC"; nameHistoSgnB="histD0POfflineSgnB"; nameHistoSgnNoQ="histD0POfflineSgnNoQ"; titleHistoSgnC="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; titleHistoSgnB="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; titleHistoSgnNoQ="d_{0}(p) vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; d_{0}(p) [cm]; Entries"; TH2F* d0POfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0POfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),11,binLimpTLc,1000,-1.,1.); TH2F* d0POfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),11,binLimpTLc,1000,-1.,1.); nameHistoSgnC="histCosPAK0SOfflineSgnC"; nameHistoSgnB="histCosPAK0SOfflineSgnB"; nameHistoSgnNoQ="histCosPAK0SOfflineSgnNoQ"; titleHistoSgnC="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnB="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnNoQ="K^{0}_{S} cosine of pointing angle wrt primary vertex vs p_{T}(#Lambda_{c}); p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosPAK0SOfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),41,binLimpTprong,100,0.99,1.); TH2F *cosPAK0SOfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),41,binLimpTprong,100,0.99,1.); TH2F *cosPAK0SOfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),41,binLimpTprong,100,0.99,1.); nameHistoSgnC="histCosThetaProtonCMSOfflineSgnC"; nameHistoSgnB="histCosThetaProtonCMSOfflineSgnB"; nameHistoSgnNoQ="histCosThetaProtonCMSOfflineSgnNoQ"; titleHistoSgnC="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnB="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; titleHistoSgnNoQ="cosien of proton emission angle in Lc rest frame; p_{T}(#Lambda_{c}) [GeV/c]; cosine; Entries"; TH2F *cosThePrOfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),41,binLimpTprong,100,-1.,1.); TH2F *cosThePrOfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),41,binLimpTprong,100,-1.,1.); TH2F *cosThePrOfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),41,binLimpTprong,100,-1.,1.); nameHistoSgnC="histResignedD0OfflineSgnC"; nameHistoSgnB="histResignedD0OfflineSgnB"; nameHistoSgnNoQ="histResignedD0OfflineSgnNoQ"; titleHistoSgnC="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; titleHistoSgnB="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; titleHistoSgnNoQ="Proton d0 with different sign convention; p_{T}(#Lambda_{c}) [GeV/c]; d0 [cm]; Entries"; TH2F *resignedD0OfflineSgnC = new TH2F(nameHistoSgnC.Data(),titleHistoSgnC.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F *resignedD0OfflineSgnB = new TH2F(nameHistoSgnB.Data(),titleHistoSgnB.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F *resignedD0OfflineSgnNoQ = new TH2F(nameHistoSgnNoQ.Data(),titleHistoSgnNoQ.Data(),41,binLimpTprong,100,-0.1,0.1); TH2F* allptK0SOfflineSgnC = (TH2F*)ptK0SOfflineSgnC->Clone(); TH2F* allptK0SOfflineSgnB = (TH2F*)ptK0SOfflineSgnB->Clone(); TH2F* allptK0SOfflineSgnNoQ = (TH2F*)ptK0SOfflineSgnNoQ->Clone(); TH2F* allptPOfflineSgnC = (TH2F*)ptPOfflineSgnC->Clone(); TH2F* allptPOfflineSgnB = (TH2F*)ptPOfflineSgnB->Clone(); TH2F* allptPOfflineSgnNoQ = (TH2F*)ptPOfflineSgnNoQ->Clone(); TH2F* allptPiPOfflineSgnC = (TH2F*)ptPiPOfflineSgnC->Clone(); TH2F* allptPiPOfflineSgnB = (TH2F*)ptPiPOfflineSgnB->Clone(); TH2F* allptPiPOfflineSgnNoQ = (TH2F*)ptPiPOfflineSgnNoQ->Clone(); TH2F* allptPiMOfflineSgnC = (TH2F*)ptPiMOfflineSgnC->Clone(); TH2F* allptPiMOfflineSgnB = (TH2F*)ptPiMOfflineSgnB->Clone(); TH2F* allptPiMOfflineSgnNoQ = (TH2F*)ptPiMOfflineSgnNoQ->Clone(); TH2F* alld0K0SOfflineSgnC = (TH2F*)d0K0SOfflineSgnC->Clone(); TH2F* alld0K0SOfflineSgnB = (TH2F*)d0K0SOfflineSgnB->Clone(); TH2F* alld0K0SOfflineSgnNoQ = (TH2F*)d0K0SOfflineSgnNoQ->Clone(); TH2F* alld0POfflineSgnC = (TH2F*)d0POfflineSgnC->Clone(); TH2F* alld0POfflineSgnB = (TH2F*)d0POfflineSgnB->Clone(); TH2F* alld0POfflineSgnNoQ = (TH2F*)d0POfflineSgnNoQ->Clone(); TH2F* allcosPAK0SOfflineSgnC = (TH2F*)cosPAK0SOfflineSgnC->Clone(); TH2F* allcosPAK0SOfflineSgnB = (TH2F*)cosPAK0SOfflineSgnB->Clone(); TH2F* allcosPAK0SOfflineSgnNoQ = (TH2F*)cosPAK0SOfflineSgnNoQ->Clone(); TH2F* allcosThePrOfflineSgnC = (TH2F*)cosThePrOfflineSgnC->Clone(); TH2F* allcosThePrOfflineSgnB = (TH2F*)cosThePrOfflineSgnB->Clone(); TH2F* allcosThePrOfflineSgnNoQ = (TH2F*)cosThePrOfflineSgnNoQ->Clone(); TH2F* allresignedD0OfflineSgnC = (TH2F*)resignedD0OfflineSgnC->Clone(); TH2F* allresignedD0OfflineSgnB = (TH2F*)resignedD0OfflineSgnB->Clone(); TH2F* allresignedD0OfflineSgnNoQ = (TH2F*)resignedD0OfflineSgnNoQ->Clone(); TH2F* pidptK0SOfflineSgnC = (TH2F*)ptK0SOfflineSgnC->Clone(); TH2F* pidptK0SOfflineSgnB = (TH2F*)ptK0SOfflineSgnB->Clone(); TH2F* pidptK0SOfflineSgnNoQ = (TH2F*)ptK0SOfflineSgnNoQ->Clone(); TH2F* pidptPOfflineSgnC = (TH2F*)ptPOfflineSgnC->Clone(); TH2F* pidptPOfflineSgnB = (TH2F*)ptPOfflineSgnB->Clone(); TH2F* pidptPOfflineSgnNoQ = (TH2F*)ptPOfflineSgnNoQ->Clone(); TH2F* pidptPiPOfflineSgnC = (TH2F*)ptPiPOfflineSgnC->Clone(); TH2F* pidptPiPOfflineSgnB = (TH2F*)ptPiPOfflineSgnB->Clone(); TH2F* pidptPiPOfflineSgnNoQ = (TH2F*)ptPiPOfflineSgnNoQ->Clone(); TH2F* pidptPiMOfflineSgnC = (TH2F*)ptPiMOfflineSgnC->Clone(); TH2F* pidptPiMOfflineSgnB = (TH2F*)ptPiMOfflineSgnB->Clone(); TH2F* pidptPiMOfflineSgnNoQ = (TH2F*)ptPiMOfflineSgnNoQ->Clone(); TH2F* pidd0K0SOfflineSgnC = (TH2F*)d0K0SOfflineSgnC->Clone(); TH2F* pidd0K0SOfflineSgnB = (TH2F*)d0K0SOfflineSgnB->Clone(); TH2F* pidd0K0SOfflineSgnNoQ = (TH2F*)d0K0SOfflineSgnNoQ->Clone(); TH2F* pidd0POfflineSgnC = (TH2F*)d0POfflineSgnC->Clone(); TH2F* pidd0POfflineSgnB = (TH2F*)d0POfflineSgnB->Clone(); TH2F* pidd0POfflineSgnNoQ = (TH2F*)d0POfflineSgnNoQ->Clone(); TH2F* pidcosPAK0SOfflineSgnC = (TH2F*)cosPAK0SOfflineSgnC->Clone(); TH2F* pidcosPAK0SOfflineSgnB = (TH2F*)cosPAK0SOfflineSgnB->Clone(); TH2F* pidcosPAK0SOfflineSgnNoQ = (TH2F*)cosPAK0SOfflineSgnNoQ->Clone(); TH2F* pidcosThePrOfflineSgnC = (TH2F*)cosThePrOfflineSgnC->Clone(); TH2F* pidcosThePrOfflineSgnB = (TH2F*)cosThePrOfflineSgnB->Clone(); TH2F* pidcosThePrOfflineSgnNoQ = (TH2F*)cosThePrOfflineSgnNoQ->Clone(); TH2F* pidresignedD0OfflineSgnC = (TH2F*)resignedD0OfflineSgnC->Clone(); TH2F* pidresignedD0OfflineSgnB = (TH2F*)resignedD0OfflineSgnB->Clone(); TH2F* pidresignedD0OfflineSgnNoQ = (TH2F*)resignedD0OfflineSgnNoQ->Clone(); fOutputAll->Add(allptK0SOfflineSgnC); fOutputAll->Add(allptK0SOfflineSgnB); fOutputAll->Add(allptK0SOfflineSgnNoQ); fOutputAll->Add(allptPOfflineSgnC); fOutputAll->Add(allptPOfflineSgnB); fOutputAll->Add(allptPOfflineSgnNoQ); fOutputAll->Add(allptPiPOfflineSgnC); fOutputAll->Add(allptPiPOfflineSgnB); fOutputAll->Add(allptPiPOfflineSgnNoQ); fOutputAll->Add(allptPiMOfflineSgnC); fOutputAll->Add(allptPiMOfflineSgnB); fOutputAll->Add(allptPiMOfflineSgnNoQ); fOutputAll->Add(alld0K0SOfflineSgnC); fOutputAll->Add(alld0K0SOfflineSgnB); fOutputAll->Add(alld0K0SOfflineSgnNoQ); fOutputAll->Add(alld0POfflineSgnC); fOutputAll->Add(alld0POfflineSgnB); fOutputAll->Add(alld0POfflineSgnNoQ); fOutputAll->Add(allcosPAK0SOfflineSgnC); fOutputAll->Add(allcosPAK0SOfflineSgnB); fOutputAll->Add(allcosPAK0SOfflineSgnNoQ); fOutputAll->Add(allcosThePrOfflineSgnC); fOutputAll->Add(allcosThePrOfflineSgnB); fOutputAll->Add(allcosThePrOfflineSgnNoQ); fOutputAll->Add(allresignedD0OfflineSgnC); fOutputAll->Add(allresignedD0OfflineSgnB); fOutputAll->Add(allresignedD0OfflineSgnNoQ); fOutputPIDBach->Add(pidptK0SOfflineSgnC); fOutputPIDBach->Add(pidptK0SOfflineSgnB); fOutputPIDBach->Add(pidptK0SOfflineSgnNoQ); fOutputPIDBach->Add(pidptPOfflineSgnC); fOutputPIDBach->Add(pidptPOfflineSgnB); fOutputPIDBach->Add(pidptPOfflineSgnNoQ); fOutputPIDBach->Add(pidptPiPOfflineSgnC); fOutputPIDBach->Add(pidptPiPOfflineSgnB); fOutputPIDBach->Add(pidptPiPOfflineSgnNoQ); fOutputPIDBach->Add(pidptPiMOfflineSgnC); fOutputPIDBach->Add(pidptPiMOfflineSgnB); fOutputPIDBach->Add(pidptPiMOfflineSgnNoQ); fOutputPIDBach->Add(pidd0K0SOfflineSgnC); fOutputPIDBach->Add(pidd0K0SOfflineSgnB); fOutputPIDBach->Add(pidd0K0SOfflineSgnNoQ); fOutputPIDBach->Add(pidd0POfflineSgnC); fOutputPIDBach->Add(pidd0POfflineSgnB); fOutputPIDBach->Add(pidd0POfflineSgnNoQ); fOutputPIDBach->Add(pidcosPAK0SOfflineSgnC); fOutputPIDBach->Add(pidcosPAK0SOfflineSgnB); fOutputPIDBach->Add(pidcosPAK0SOfflineSgnNoQ); fOutputPIDBach->Add(pidcosThePrOfflineSgnC); fOutputPIDBach->Add(pidcosThePrOfflineSgnB); fOutputPIDBach->Add(pidcosThePrOfflineSgnNoQ); fOutputPIDBach->Add(pidresignedD0OfflineSgnC); fOutputPIDBach->Add(pidresignedD0OfflineSgnB); fOutputPIDBach->Add(pidresignedD0OfflineSgnNoQ); }
45.338581
326
0.688901
[ "object", "vector", "3d" ]
0f744d547b2ae5f66f985262a4aea0166cde4958
7,547
cpp
C++
event_camera_simulator/esim_common/test/test_utils.cpp
Louis-Jin/rpg_esim
eea20b84e2bb788431f93b8aace82b0f98606982
[ "MIT" ]
371
2018-11-02T10:09:22.000Z
2022-03-31T05:09:39.000Z
event_camera_simulator/esim_common/test/test_utils.cpp
Louis-Jin/rpg_esim
eea20b84e2bb788431f93b8aace82b0f98606982
[ "MIT" ]
97
2018-11-06T11:47:53.000Z
2022-03-10T16:25:59.000Z
event_camera_simulator/esim_common/test/test_utils.cpp
Louis-Jin/rpg_esim
eea20b84e2bb788431f93b8aace82b0f98606982
[ "MIT" ]
101
2018-11-05T12:33:43.000Z
2022-03-24T17:40:50.000Z
#include <esim/common/utils.hpp> #include <ze/common/test_entrypoint.hpp> #include <ze/common/file_utils.hpp> #include <ze/common/path_utils.hpp> #include <ze/common/string_utils.hpp> #include <ze/cameras/camera_rig.hpp> #include <ze/common/random.hpp> std::string getTestDataDir(const std::string& dataset_name) { using namespace ze; const char* datapath_dir = std::getenv("ESIM_TEST_DATA_PATH"); CHECK(datapath_dir != nullptr) << "Did you download the esim_test_data repository and set " << "the ESIM_TEST_DATA_PATH environment variable?"; std::string path(datapath_dir); CHECK(isDir(path)) << "Folder does not exist: " << path; path = path + "/data/" + dataset_name; CHECK(isDir(path)) << "Dataset does not exist: " << path; return path; } namespace event_camera_simulator { void computeOpticFlowFiniteDifference(const ze::Camera::Ptr& camera, const ze::Vector3& angular_velocity, const ze::Vector3& linear_velocity, const DepthmapPtr& depth, OpticFlowPtr& flow) { CHECK(flow); CHECK_EQ(flow->rows, camera->height()); CHECK_EQ(flow->cols, camera->width()); const FloatType dt = 0.001; for(int y=0; y<flow->rows; ++y) { for(int x=0; x<flow->cols; ++x) { ze::Keypoint u_t(x,y); ze::Bearing f = camera->backProject(u_t); const FloatType z = static_cast<FloatType>((*depth)(y,x)); ze::Position Xc_t = z * ze::Position(f[0]/f[2], f[1]/f[2], 1.); ze::Transformation::Rotation dR = ze::Transformation::Rotation::exp(-angular_velocity * dt); ze::Transformation::Position dT = -linear_velocity * dt; // Transform Xc(t) to Xc(t+dt) ze::Transformation T_tdt_t; T_tdt_t.getRotation() = dR; T_tdt_t.getPosition() = dT; VLOG(5) << T_tdt_t; ze::Position Xc_t_dt = T_tdt_t.transform(Xc_t); // Project Xc(t+dt) in the image plane ze::Keypoint u_t_dt = camera->project(Xc_t_dt); VLOG(5) << u_t; VLOG(5) << u_t_dt; ze::Vector2 flow_vec = (u_t_dt - u_t) / dt; (*flow)(y,x) = cv::Vec<FloatType, 2>(flow_vec(0), flow_vec(1)); } } } void computeOpticFlowFiniteDifference(const ze::Camera::Ptr& camera, const ze::Vector3& angular_velocity, const ze::Vector3& linear_velocity, const DepthmapPtr& depth, const ze::Vector3& r_COBJ, const ze::Vector3& angular_velocity_obj, const ze::Vector3& linear_velocity_obj, OpticFlowPtr& flow) { CHECK(flow); CHECK_EQ(flow->rows, camera->height()); CHECK_EQ(flow->cols, camera->width()); const FloatType dt = 0.001; for(int y=0; y<flow->rows; ++y) { for(int x=0; x<flow->cols; ++x) { ze::Keypoint u_t(x,y); ze::Bearing f = camera->backProject(u_t); const FloatType z = static_cast<FloatType>((*depth)(y,x)); ze::Position Xc_t = z * ze::Position(f[0]/f[2], f[1]/f[2], 1.); ze::Position r_OBJX = Xc_t - r_COBJ; ze::Matrix33 w_WOBJ_tilde = ze::skewSymmetric(angular_velocity_obj); ze::Transformation::Rotation dR = ze::Transformation::Rotation::exp(-angular_velocity * dt); ze::Transformation::Position dT = linear_velocity_obj*dt - linear_velocity * dt + w_WOBJ_tilde*r_OBJX*dt; // Transform Xc(t) to Xc(t+dt) ze::Transformation T_tdt_t; T_tdt_t.getRotation() = dR; T_tdt_t.getPosition() = dT; VLOG(5) << T_tdt_t; ze::Position Xc_t_dt = T_tdt_t.transform(Xc_t); // Project Xc(t+dt) in the image plane ze::Keypoint u_t_dt = camera->project(Xc_t_dt); VLOG(5) << u_t; VLOG(5) << u_t_dt; ze::Vector2 flow_vec = (u_t_dt - u_t) / dt; (*flow)(y,x) = cv::Vec<FloatType, 2>(flow_vec(0), flow_vec(1)); } } } } // event_camera_simulator TEST(Utils, testOpticFlowComputation) { using namespace event_camera_simulator; // Load camera calib from folder const std::string path_to_data_folder = getTestDataDir("camera_calibs"); ze::CameraRig::Ptr camera_rig = ze::cameraRigFromYaml(ze::joinPath(path_to_data_folder, "pinhole_mono.yaml")); CHECK(camera_rig); const ze::Camera::Ptr camera = camera_rig->atShared(0); cv::Size sensor_size(camera->width(), camera->height()); OpticFlowPtr flow_analytic = std::make_shared<OpticFlow>(sensor_size); // Sample random depth map const ImageFloatType z_mean = 5.0; const ImageFloatType z_stddev = 0.5; DepthmapPtr depth = std::make_shared<Depthmap>(sensor_size); for(int y=0; y<sensor_size.height; ++y) { for(int x=0; x<sensor_size.width; ++x) { (*depth)(y,x) = ze::sampleNormalDistribution(true, z_mean, z_stddev); } } // Sample random linear and angular velocity ze::Vector3 angular_velocity, linear_velocity; angular_velocity.setRandom(); linear_velocity.setRandom(); LOG(INFO) << "w = " << angular_velocity; LOG(INFO) << "v = " << linear_velocity; // Compute optic flow on the image plane according // to the sampled angular/linear velocity OpticFlowHelper optic_flow_helper(camera); optic_flow_helper.computeFromDepthAndTwist(angular_velocity, linear_velocity, depth, flow_analytic); OpticFlowPtr flow_finite_diff = std::make_shared<OpticFlow>(sensor_size); computeOpticFlowFiniteDifference(camera, angular_velocity, linear_velocity, depth, flow_finite_diff); // Check that the analytical flow and finite-difference flow match for(int y=0; y<sensor_size.height; ++y) { for(int x=0; x<sensor_size.width; ++x) { EXPECT_NEAR((*flow_analytic)(y,x)[0], (*flow_finite_diff)(y,x)[0], 0.1); EXPECT_NEAR((*flow_analytic)(y,x)[1], (*flow_finite_diff)(y,x)[1], 0.1); } } /**********************************************/ /* repeat optic flow test for dynamic objects */ /**********************************************/ // sample random obj position and linear and angular velocity ze::Vector3 r_COBJ; r_COBJ.setRandom(); r_COBJ(2) = ze::sampleNormalDistribution(true, z_mean, z_stddev); // assume object is in front of camera ze::Vector3 angular_velocity_obj, linear_velocity_obj; angular_velocity_obj.setRandom(); linear_velocity_obj.setRandom(); // Compute optic flow on the image plane according // to the sampled angular/linear velocity optic_flow_helper.computeFromDepthCamTwistAndObjDepthAndTwist(angular_velocity, linear_velocity, depth, r_COBJ, angular_velocity_obj, linear_velocity_obj, flow_analytic); computeOpticFlowFiniteDifference(camera, angular_velocity, linear_velocity, depth, r_COBJ, angular_velocity_obj, linear_velocity_obj, flow_finite_diff); // Check that the analytical flow and finite-difference flow match for(int y=0; y<sensor_size.height; ++y) { for(int x=0; x<sensor_size.width; ++x) { EXPECT_NEAR((*flow_analytic)(y,x)[0], (*flow_finite_diff)(y,x)[0], 0.1); EXPECT_NEAR((*flow_analytic)(y,x)[1], (*flow_finite_diff)(y,x)[1], 0.1); } } } ZE_UNITTEST_ENTRYPOINT
35.266355
114
0.614681
[ "object", "transform" ]
0f76aa7b94560451678b6cb3085788750c99f078
30,581
cc
C++
crdb/crdb_db.cc
audreyccheng/taobench
41294425896ed8c2e6c53761dc0f04cf3b32dbd2
[ "CC0-1.0" ]
null
null
null
crdb/crdb_db.cc
audreyccheng/taobench
41294425896ed8c2e6c53761dc0f04cf3b32dbd2
[ "CC0-1.0" ]
null
null
null
crdb/crdb_db.cc
audreyccheng/taobench
41294425896ed8c2e6c53761dc0f04cf3b32dbd2
[ "CC0-1.0" ]
1
2021-12-17T02:21:57.000Z
2021-12-17T02:21:57.000Z
#include "crdb_db.h" #include "db_factory.h" #include <pqxx/pqxx> #include <chrono> using std::cout; using std::endl; namespace { const std::string CONNECTION_STRING = "crdb.connectionstring"; } namespace benchmark { void CrdbDB::Init() { std::lock_guard<std::mutex> lock(mutex_); const utils::Properties &props = *props_; std::string connectionstring = props.GetProperty(CONNECTION_STRING); if (CONNECTION_STRING == "") { throw utils::Exception("Incomplete login credentials in CRDB properties file"); } conn_ = new pqxx::connection(connectionstring); // create prepared statements edge_table_ = props_->GetProperty("edge_table_", "edges"); object_table_ = props_->GetProperty("object_table_", "objects"); conn_->prepare("read_object", "SELECT timestamp, value FROM " + object_table_ + " WHERE id = $1"); conn_->prepare("read_edge", "SELECT timestamp, value FROM " + edge_table_ + " WHERE id1 = $1 AND id2 = $2 AND type = $3"); // scan (not yet implemented) // conn_->prepare("scan_object", "SELECT id FROM " + object_table_ + " WHERE id > $1 AND id < $2 ORDER BY id LIMIT $3"); // conn_->prepare("scan_edge", "SELECT id1, id2, type FROM " + edge_table_ + " WHERE (id1, id2, type) > ($1, $2, $3) AND (id1, id2, type) < ($4, $5, $6) ORDER BY id1, id2, type LIMIT $7"); // update // conn_->prepare("scan_object", "SELECT id FROM " + object_table_ + " WHERE id > $1 ORDER BY id LIMIT $2"); // conn_->prepare("scan_edge", "SELECT id1, id2, type FROM " + edge_table_ + " WHERE (id1, id2, type) > ($1, $2, $3) ORDER BY id1, id2, type LIMIT $4"); conn_->prepare("update_object", "UPDATE " + object_table_ + " SET timestamp = $1, value = $2 WHERE id = $3 AND timestamp < $1"); conn_->prepare("update_edge", "UPDATE " + edge_table_ + " SET timestamp = $1, value = $2 WHERE id1 = $3 AND id2 = $4 AND type = $5 AND timestamp < $1"); // Insert // type: unique = 0, bidirectional = 1, unique_and_bidirectional = 2, other = 3 conn_->prepare("insert_object", "INSERT INTO " +object_table_ + " (id, timestamp, value) VALUES ($1, $2, $3)"); std::string insert_edge = "INSERT INTO " + edge_table_ + " (id1, id2, type, timestamp, value) SELECT $1, $2, $3, $4, $5 WHERE NOT EXISTS "; conn_->prepare("insert_edge_other", insert_edge + "(SELECT 1 FROM " + edge_table_ + " WHERE (id1=$1 AND type=0) OR (id1=$1 AND type=2) OR (id1=$1 AND id2=$2 AND type=1) OR (id1=$2 AND id2=$1))"); conn_->prepare("insert_edge_bidirectional", insert_edge + "(SELECT 1 FROM " + edge_table_ + " WHERE (id1=$1 AND type=0) OR (id1=$1 AND type=2) OR (id1=$1 AND id2=$2 AND type=3) OR (id1=$2 AND id2=$1 AND type=3) OR (id1=$1 AND id2=$2 AND type=0))"); conn_->prepare("insert_edge_unique", insert_edge + "(SELECT 1 FROM " + edge_table_ + " WHERE id1=$1 OR (id1=$2 AND id2=$1))"); conn_->prepare("insert_edge_bi_unique", insert_edge + "(SELECT 1 FROM " + edge_table_ + " WHERE id1=$1 OR (id1=$2 AND id2=$1 AND type=3) OR (id1=$2 AND id2=$1 AND type=0))"); // deletes conn_->prepare("delete_object", "DELETE FROM " + object_table_ + " WHERE id = $1 AND timestamp < $2"); conn_->prepare("delete_edge", "DELETE FROM " + edge_table_ + " WHERE id1 = $1 AND id2 = $2 AND type = $3 AND timestamp < $4"); // batch read conn_->prepare("batch_read", "SELECT id1, id2, type FROM " + edge_table_ + " WHERE ((id1, id2) = ($1, $2) AND type > $3 OR id1 = $1 AND id2 > $2 OR id1 > $1) AND (id1 < $4 OR id1 = $4 AND id2 < $5 OR (id1, id2) = ($4, $5) AND type < $6) LIMIT $7"); } void CrdbDB::Cleanup() { conn_->close(); delete conn_; } /* key always in the order {id1, id2, type} or {id1} fields always in the other {timestamp, value} */ Status CrdbDB::Read(DataTable table, const std::vector<Field> & key, std::vector<TimestampValue> &result) { std::lock_guard<std::mutex> lock(mutex_); try { pqxx::nontransaction tx(*conn_); pqxx::result queryRes = DoRead(tx, table, key); // for (int i = 0; i < fields->size(); i++) { // // Field f((*fields)[i], (queryRes[0][i]).as<std::string>("NULL")); // // result.emplace_back(f); // } result.emplace_back( (queryRes[0][0]).as<int64_t>(0), (queryRes[0][1]).as<std::string>("NULL") ); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } pqxx::result CrdbDB::DoRead(pqxx::transaction_base &tx, const DataTable table, const std::vector<Field> &key) { if (table == DataTable::Objects) { return tx.exec_prepared("read_object", key[0].value); } else if (table == DataTable::Edges) { return tx.exec_prepared("read_edge", key[0].value, key[1].value, key[2].value); } else { throw std::invalid_argument("Received unknown table"); } } Status CrdbDB::Scan(DataTable table, const std::vector<Field> & key, int n, std::vector<TimestampValue> &buffer) { return Status::kNotImplemented; } // Status CrdbDB::Scan(const std::string &table, const std::vector<Field> &key, int len, // const std::vector<std::string> *fields, // std::vector<std::vector<Field>> &result) { // assert(fields == nullptr); // std::vector<std::string> hardcoded_fields{"id1", "id2", "type"}; // if (fields == nullptr) { // fields = &hardcoded_fields; // } // std::lock_guard<std::mutex> lock(mutex_); // try { // pqxx::nontransaction tx(*conn_); // pqxx::result queryRes = DoScan(tx, table, key, len, fields); // for (auto row : queryRes) { // std::vector<Field> oneRowVector; // for (int j = 0; j < fields->size(); j++) { // Field f((*fields)[j], (row)[j].as<std::string>("NULL")); // oneRowVector.push_back(f); // } // result.push_back(oneRowVector); // } // return Status::kOK; // } catch (std::exception const &e) { // std::cerr << e.what() << endl; // return Status::kError; // } // } // pqxx::result CrdbDB::DoScan(pqxx::transaction_base &tx, const std::string &table, const std::vector<Field> &key, int record_count, // const std::vector<std::string> *fields, const std::vector<Field> &limit) { // // conn_->prepare("scan_object", "SELECT id FROM " + object_table_ + " WHERE id > $1 AND id < $2 ORDER BY id LIMIT $3"); // // conn_->prepare("scan_edge", "SELECT id1, id2, type FROM " + edge_table_ + " WHERE (id1, id2, type) > ($1, $2, $3) AND (id1, id2, type) < ($4, $5, $6) ORDER BY id1, id2, type LIMIT $7"); // if (table == object_table_) { // return tx.exec_prepared("scan_object", key[0].value, limit[0].value, record_count); // } else if (table == edge_table_) { // return tx.exec_prepared("scan_edge", key[0].value, key[1].value, key[2].value, limit[0].value, limit[1].value, limit[2].value, record_count); // } else { // throw std::invalid_argument("Received unknown table"); // } // } Status CrdbDB::Update(DataTable table, const std::vector<DB::Field> &key, TimestampValue const &value) { std::lock_guard<std::mutex> lock(mutex_); try { pqxx::nontransaction tx(*conn_); pqxx::result queryRes = DoUpdate(tx, table, key, value); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } pqxx::result CrdbDB::DoUpdate(pqxx::transaction_base &tx, DataTable table, const std::vector<Field> &key, TimestampValue const &value) { if (table == DataTable::Objects) { return tx.exec_prepared("update_object", value.timestamp, value.value, key[0].value); } else if (table == DataTable::Edges) { return tx.exec_prepared("update_edge", value.timestamp, value.value, key[0].value, key[1].value, key[2].value); } else { throw std::invalid_argument("Received unknown table"); } } Status CrdbDB::Insert(DataTable table, const std::vector<Field> &key, const TimestampValue & value) { std::lock_guard<std::mutex> lock(mutex_); try { pqxx::nontransaction tx(*conn_); pqxx::result queryRes = DoInsert(tx, table, key, value); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } pqxx::result CrdbDB::DoInsert(pqxx::transaction_base &tx, DataTable table, const std::vector<Field> &key, const TimestampValue & value) { if (table == DataTable::Objects) { return tx.exec_prepared("insert_object", key[0].value, value.timestamp, value.value); } else if (table == DataTable::Edges) { benchmark::EdgeType type = static_cast<benchmark::EdgeType>(key[2].value); if (type == benchmark::EdgeType::Other) { return tx.exec_prepared("insert_edge_other", key[0].value, key[1].value, key[2].value, value.timestamp, value.value); } else if (type == benchmark::EdgeType::Bidirectional) { return tx.exec_prepared("insert_edge_bidirectional", key[0].value, key[1].value, key[2].value, value.timestamp, value.value); } else if (type == benchmark::EdgeType::Unique) { return tx.exec_prepared("insert_edge_unique", key[0].value, key[1].value, key[2].value, value.timestamp, value.value); } else if (type == benchmark::EdgeType::UniqueAndBidirectional) { return tx.exec_prepared("insert_edge_bi_unique", key[0].value, key[1].value, key[2].value, value.timestamp, value.value); } else { throw std::invalid_argument("Received unknown type"); } } else { throw std::invalid_argument("Received unknown table"); } } Status CrdbDB::BatchInsert(DataTable table, const std::vector<std::vector<Field>> &keys, const std::vector<TimestampValue> &values) { std::lock_guard<std::mutex> lock(mutex_); return table == DataTable::Edges ? BatchInsertEdges(table, keys, values) : BatchInsertObjects(table, keys, values); } Status CrdbDB::BatchInsertEdges(DataTable table, const std::vector<std::vector<Field>> &keys, const std::vector<TimestampValue> &values) { try { pqxx::nontransaction tx(*conn_); std::string query = "INSERT INTO edges (id1, id2, type, timestamp, value) VALUES "; bool is_first = true; for (int i = 0; i < keys.size(); i++) { assert(keys[i].size() == 3); assert(keys[i][0].name == "id1"); assert(keys[i][1].name == "id2"); assert(keys[i][2].name == "type"); if (!is_first) { query += ", "; } else { is_first = false; } query += "(" + std::to_string(keys[i][0].value) // id1 + ", " + std::to_string(keys[i][1].value) // id2 + ", " + std::to_string(keys[i][2].value) // type + ", " + std::to_string(values[i].timestamp) // timestamp + ", " + conn_->quote(values[i].value) // value + ")"; } pqxx::result queryRes = tx.exec(query); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } Status CrdbDB::BatchInsertObjects(DataTable table, const std::vector<std::vector<Field>> &keys, const std::vector<TimestampValue> &values) { try { pqxx::nontransaction tx(*conn_); std::string query = "INSERT INTO objects (id, timestamp, value) VALUES "; bool is_first = true; for (int i = 0; i < keys.size(); i++) { assert(keys[i].size() == 1); assert(keys[i][0].name == "id"); if (!is_first) { query += ", "; } else { is_first = false; } query += "(" + std::to_string(keys[i][0].value) // id + ", " + std::to_string(values[i].timestamp) // timestamp + ", " + conn_->quote(values[i].value) // value + ")"; } pqxx::result queryRes = tx.exec(query); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } Status CrdbDB::BatchRead(DataTable table, std::vector<Field> const & floor_key, std::vector<Field> const & ceil_key, int n, std::vector<std::vector<Field>> &result) { assert(floor_key.size() == 3); assert(floor_key[0].name == "id1"); assert(floor_key[1].name == "id2"); assert(floor_key[2].name == "type"); assert(ceil_key.size() == 3); assert(ceil_key[0].name == "id1"); assert(ceil_key[1].name == "id2"); assert(ceil_key[2].name == "type"); try { pqxx::nontransaction tx(*conn_); pqxx::result queryRes = tx.exec_prepared("batch_read", floor_key[0].value, floor_key[1].value, floor_key[2].value, ceil_key[0].value, ceil_key[1].value, ceil_key[2].value, n); for (auto row : queryRes) { std::vector<Field> row_result = {{"id1", (row)[0].as<int64_t>(0)}, {"id2", (row)[1].as<int64_t>(0)}, {"type", (row)[2].as<int64_t>(0)}}; result.push_back(row_result); } return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } Status CrdbDB::Delete(DataTable table, const std::vector<Field> &key, const TimestampValue &value) { std::lock_guard<std::mutex> lock(mutex_); try { pqxx::nontransaction tx(*conn_); pqxx::result queryRes = DoDelete(tx, table, key, value); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } pqxx::result CrdbDB::DoDelete(pqxx::transaction_base &tx, DataTable table, const std::vector<Field> &key, const TimestampValue &value) { if (table == DataTable::Objects) { return tx.exec_prepared("delete_object", key[0].value, value.timestamp); } else if (table == DataTable::Edges) { return tx.exec_prepared("delete_edge", key[0].value, key[1].value, key[2].value, value.timestamp); } else { throw std::invalid_argument("Received unknown table"); } } Status CrdbDB::Execute(const DB_Operation &operation, std::vector<TimestampValue> &result, bool txn_op) { try { switch (operation.operation) { case Operation::READ: { return Read(operation.table, operation.key, result); } break; case Operation::INSERT: { return Insert(operation.table, operation.key, operation.time_and_value); } break; case Operation::UPDATE: { return Update(operation.table, operation.key, operation.time_and_value); } break; case Operation::SCAN: { return Status::kNotImplemented; } break; case Operation::READMODIFYWRITE: { return Status::kNotImplemented; } break; case Operation::DELETE: { return Delete(operation.table, operation.key, operation.time_and_value); } break; case Operation:: MAXOPTYPE: { return Status::kNotImplemented; } break; default: return Status::kNotFound; } } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } /* * Method executes each operation within a transaction as a prepared statement */ Status CrdbDB::ExecuteTransactionPrepared(const std::vector<DB_Operation> &operations, std::vector<TimestampValue> &results, bool read_only) { std::lock_guard<std::mutex> lock(mutex_); try { pqxx::work tx(*conn_); for (const auto &operation : operations) { pqxx::result queryRes; switch (operation.operation) { case Operation::READ: { queryRes = DoRead(tx, operation.table, operation.key); } break; case Operation::INSERT: { queryRes = DoInsert(tx, operation.table, operation.key, operation.time_and_value); } break; case Operation::UPDATE: { queryRes = DoUpdate(tx, operation.table, operation.key, operation.time_and_value); } break; case Operation::SCAN: { return Status::kNotImplemented; } break; case Operation::READMODIFYWRITE: { return Status::kNotImplemented; } break; case Operation::DELETE: { queryRes = DoDelete(tx, operation.table, operation.key, operation.time_and_value); } break; case Operation:: MAXOPTYPE: { return Status::kNotImplemented; } break; default: return Status::kNotFound; } if (operation.operation == Operation::READ || operation.operation == Operation::SCAN) { for (auto row : queryRes) { results.emplace_back( (row[0]).as<int64_t>(0), (row[1]).as<std::string>("NULL") ); } } } tx.commit(); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } /* * Method batches together statements through semicolon appending and executes it as a plain, not prepared SQL statements * Execution order (first to last): reads, scans, inserts, updates, deletes */ Status CrdbDB::ExecuteTransactionBatch(const std::vector<DB_Operation> &operations, std::vector<TimestampValue> &results, bool read_only) { std::string executionMethod = "plain"; std::lock_guard<std::mutex> lock(mutex_); try { pqxx::work tx(*conn_); std::vector<DB_Operation> read_operations; std::vector<DB_Operation> insert_operations; std::vector<DB_Operation> update_operations; std::vector<DB_Operation> delete_operations; for (const auto &operation : operations) { switch (operation.operation) { case Operation::READ: { read_operations.push_back(operation); } break; case Operation::INSERT: { insert_operations.push_back(operation); } break; case Operation::UPDATE: { update_operations.push_back(operation); } break; case Operation::SCAN: { return Status::kNotImplemented; } break; case Operation::READMODIFYWRITE: { return Status::kNotImplemented; } break; case Operation::DELETE: { delete_operations.push_back(operation); } break; case Operation:: MAXOPTYPE: { return Status::kNotImplemented; } break; default: return Status::kNotFound; } } pqxx::result queryRes; // reads std::string read_query = GenerateMergedReadQuery(read_operations); if (executionMethod == "plain") { queryRes = tx.exec(read_query); for (auto row : queryRes) { results.emplace_back((row[0]).as<int64_t>(0), (row[1]).as<std::string>("NULL")); } } // else if (executionMethod == "stream") { // // UNSURE IF THIS WILL WORK BECAUSE STREAM_FROM USES copy to AND CRDB DOES NOT SUPPORT copy to // auto stream = tx.stream(read_query); // std::tuple<std::string, std::string> row; // while (stream >> row) { // std::vector<Field> oneRowVector; // for (int j = 0; j < operation.fields.size(); j++) { // Field f(operation.fields[j].name, std::get<j>(row)); // oneRowVector.push_back(f); // } // results.push_back(oneRowVector); // } // } // inserts if (executionMethod == "plain") { std::string insert_query = GenerateMergedInsertQuery(insert_operations); queryRes = tx.exec(insert_query); } // else if (executionMethod == "stream") { // std::vector<DB_Operation> edge_inserts; // std::vector<DB_Operation> object_inserts; // for (const DB_Operation &operation : insert_operations) { // if operation. // } // pqxx::stream_to stream{tx, } // } // updates if (executionMethod == "plain") { std::string update_query = GenerateMergedUpdateQuery(update_operations); queryRes = tx.exec(update_query); } // deletes if (executionMethod == "plain") { std::string delete_query = GenerateMergedDeleteQuery(delete_operations); queryRes = tx.exec(delete_query); } tx.commit(); return Status::kOK; } catch (std::exception const &e) { std::cerr << e.what() << endl; return Status::kError; } } Status CrdbDB::ExecuteTransaction(const std::vector<DB_Operation> &operations, std::vector<TimestampValue> &results, bool read_only) { // TODO: replace this hardcoded method with a parameter std::string executionMethod = "batch"; if (executionMethod == "prepared") { return ExecuteTransactionPrepared(operations, results, read_only); } else if (executionMethod == "batch") { return ExecuteTransactionBatch(operations, results, read_only); } else { cout << "Attempted to perform CRDB ExecuteTransaction with unsupported execution method: " << executionMethod << endl; return Status::kNotImplemented; } } std::string CrdbDB::GenerateMergedReadQuery(const std::vector<DB_Operation> &read_operations) { std::string query = ""; for (int i = 0; i < read_operations.size(); i++) { const DB_Operation operation = read_operations[i]; if (operation.table == DataTable::Objects) { query += "SELECT timestamp, value FROM " + object_table_ + " WHERE id = " + std::to_string((operation.key)[0].value); } else if (operation.table == DataTable::Edges) { query += "SELECT timestamp, value FROM " + edge_table_ + " WHERE id1 = " + std::to_string((operation.key)[0].value) + " AND id2 = " + std::to_string((operation.key)[1].value) + " AND type = " + std::to_string((operation.key)[2].value); } query += ";"; } return query; } std::string CrdbDB::GenerateMergedInsertQuery(const std::vector<DB_Operation> &insert_operations) { std::string query = ""; for (int i = 0; i < insert_operations.size(); i++) { const DB_Operation operation = insert_operations[i]; if (operation.table == DataTable::Objects) { query += "INSERT INTO " +object_table_ + " (id, timestamp, value) VALUES (" + std::to_string((operation.key)[0].value) + ", " + std::to_string(operation.time_and_value.timestamp) + ", " + conn_->quote(operation.time_and_value.value) + ")"; } else if (operation.table == DataTable::Edges) { std::string id1 = std::to_string((operation.key)[0].value); std::string id2 = std::to_string((operation.key)[1].value); std::string type = std::to_string((operation.key)[2].value); std::string timestamp = std::to_string(operation.time_and_value.timestamp); std::string value = conn_->quote(operation.time_and_value.value); benchmark::EdgeType edge_type = static_cast<benchmark::EdgeType>((operation.key)[2].value); query += "INSERT INTO " + edge_table_ + " (id1, id2, type, timestamp, value) SELECT " + id1 + ", " + id2 + ", " + type + ", " + timestamp + ", " + value + " WHERE NOT EXISTS "; if (edge_type == benchmark::EdgeType::Other) { query += "(SELECT 1 FROM " + edge_table_ + " WHERE (id1=" + id1 + " AND type=0) OR (id1=" + id1 + " AND type=2) OR (id1=" + id1 + " AND id2=" + id2 + " AND type=1) OR (id1=" + id2 + " AND id2=" + id1 + "))"; } else if (edge_type == benchmark::EdgeType::Bidirectional) { query += "(SELECT 1 FROM " + edge_table_ + " WHERE (id1=" + id1 + " AND type=0) OR (id1=" + id1 + " AND type=2) OR (id1=" + id1 + " AND id2=" + id2 + " AND type=3) OR (id1=" + id2 + " AND id2=" + id1 + " AND type=3) OR (id1=" + id1 + " AND id2=" + id2 + " AND type=0))"; } else if (edge_type == benchmark::EdgeType::Unique) { query += "(SELECT 1 FROM " + edge_table_ + " WHERE id1=" + id1 + " OR (id1=" + id2 + " AND id2=" + id1 + "))"; } else if (edge_type == benchmark::EdgeType::UniqueAndBidirectional) { query += "(SELECT 1 FROM " + edge_table_ + " WHERE id1=" + id1 + " OR (id1=" + id2 + " AND id2=" + id1 + " AND type=3) OR (id1=" + id2 + " AND id2=" + id1 + " AND type=0))"; } } query += ";"; } return query; // queryRes = DoInsert(tx, operation.table, operation.key, operation.fields); // pqxx::result CrdbDB::DoInsert(pqxx::transaction_base &tx, const std::string &table, const std::vector<Field> &key, const std::vector<Field> &values) { // if (table == object_table_) { // return tx.exec_prepared("insert_object", key[0].value, values[0].value, values[1].value); // } else if (table == edge_table_) { // std::string type = key[2].value; // if (type == "other") { // return tx.exec_prepared("insert_edge_other", key[0].value, key[1].value, values[0].value, values[1].value); // } else if (type == "bidirectional") { // return tx.exec_prepared("insert_edge_bidirectional", key[0].value, key[1].value, values[0].value, values[1].value); // } else if (type == "unique") { // return tx.exec_prepared("insert_edge_unique", key[0].value, key[1].value, values[0].value, values[1].value); // } else if (type == "unique_and_bidirectional") { // return tx.exec_prepared("insert_edge_bi_unique", key[0].value, key[1].value, values[0].value, values[1].value); // } else { // throw std::invalid_argument("Received unknown type"); // } // } else { // throw std::invalid_argument("Received unknown table"); // } // } // conn_->prepare("insert_object", "INSERT INTO " + object_table_ + " (id, timestamp, value) SELECT $1, $2, $3"); // conn_->prepare("insert_edge_other", "INSERT INTO " + edge_table_ + " (id1, id2, type, timestamp, value) SELECT $1, $2, 'other', $3, $4 WHERE NOT EXISTS (SELECT id1 AS id1, id2 AS id2, type AS type FROM " + edge_table_ +" WHERE (id1 = $1 AND type = 'unique') OR (id1 = $1 AND type='unique_and_bidirectional') OR (id1 = $1 AND id2 = $2 AND type = 'bidirectional') OR (id1 = $2 AND id2 = $1))"); // conn_->prepare("insert_edge_bidirectional", "INSERT INTO " + edge_table_ + " (id1, id2, type, timestamp, value) SELECT $1, $2, 'bidirectional', $3, $4 WHERE NOT EXISTS (SELECT id1 AS id1, id2 AS id2, type AS type FROM " + edge_table_ +" WHERE (id1 = $1 AND type = 'unique') OR (id1 = $1 AND type='unique_and_bidirectional') OR (id1 = $1 AND id2 = $2 AND type = 'other') OR (id1 = $2 AND id2 = $1 AND type = 'other') OR (id1 = $2 AND id2 = $1 AND type = 'unique'))"); // conn_->prepare("insert_edge_unique", "INSERT INTO " + edge_table_ + " (id1, id2, type, timestamp, value) SELECT $1, $2, 'unique', $3, $4 WHERE NOT EXISTS (SELECT id1 AS id1, id2 AS id2, type AS type FROM " + edge_table_ +" WHERE (id1 = $1) OR (id1 = $2 AND id2 = $1))"); // conn_->prepare("insert_edge_bi_unique", "INSERT INTO " + edge_table_ + " (id1, id2, type, timestamp, value) SELECT $1, $2, 'unique_and_bidirectional', $3, $4 WHERE NOT EXISTS (SELECT id1 AS id1, id2 AS id2, type AS type FROM " + edge_table_ +" WHERE (id1 = $1) OR (id1 = $2 AND id2 = $1 AND type = 'other') OR (id1 = $2 AND id2 = $1 AND type = 'unique'))"); } std::string CrdbDB::GenerateMergedUpdateQuery(const std::vector<DB_Operation> &update_operations) { std::string query = ""; for (int i = 0; i < update_operations.size(); i++) { const DB_Operation operation = update_operations[i]; if (operation.table == DataTable::Objects) { query += "UPDATE " + object_table_ + " SET timestamp = " + std::to_string(operation.time_and_value.timestamp) + ", value = " + conn_->quote(operation.time_and_value.value) + " WHERE id = " + std::to_string((operation.key)[0].value) + " AND timestamp < " + std::to_string(operation.time_and_value.timestamp); } else if (operation.table == DataTable::Edges) { query += "UPDATE " + edge_table_ + " SET timestamp = " + std::to_string(operation.time_and_value.timestamp) + ", value = " + conn_->quote(operation.time_and_value.value) + " WHERE id1 = " + std::to_string((operation.key)[0].value) + " AND id2 = " + std::to_string((operation.key)[1].value) + " AND type = " + std::to_string((operation.key)[2].value) + " AND timestamp < " + std::to_string(operation.time_and_value.timestamp); } query += ";"; } return query; // queryRes = DoUpdate(tx, operation.table, operation.key, operation.fields); // if (table == object_table_) { // return tx.exec_prepared("update_object", values[0].value, values[1].value, key[0].value); // } else if (table == edge_table_) { // return tx.exec_prepared("update_edge", values[0].value, values[1].value, key[0].value, key[1].value, key[2].value); // } else { // throw std::invalid_argument("Received unknown table"); // } // conn_->prepare("update_object", "UPDATE " + object_table_ + " SET timestamp = $1, value = $2 WHERE id = $3 AND timestamp < $1"); // conn_->prepare("update_edge", "UPDATE " + edge_table_ + " SET timestamp = $1, value = $2 WHERE id1 = $3 AND id2 = $4 AND type = $5 AND timestamp < $1"); } std::string CrdbDB::GenerateMergedDeleteQuery(const std::vector<DB_Operation> &delete_operations) { std::string query = ""; for (int i = 0; i < delete_operations.size(); i++) { const DB_Operation operation = delete_operations[i]; if (operation.table == DataTable::Objects) { query += "DELETE FROM " + object_table_ + " WHERE id = " + std::to_string((operation.key)[0].value) + " AND timestamp < " + std::to_string(operation.time_and_value.timestamp); } else if (operation.table == DataTable::Edges) { query += "DELETE FROM " + edge_table_ + " WHERE id1 = " + std::to_string((operation.key)[0].value) + " AND id2 = " + std::to_string((operation.key)[1].value) + " AND type = " + std::to_string((operation.key)[2].value) + " AND timestamp < " + std::to_string(operation.time_and_value.timestamp); } query += ";"; } return query; // queryRes = DoDelete(tx, operation.table, operation.key, operation.fields); // pqxx::result CrdbDB::DoDelete(pqxx::transaction_base &tx, const std::string &table, const std::vector<Field> &key, const std::vector<Field> &values) { // if (table == object_table_) { // return tx.exec_prepared("delete_object", key[0].value, values[0].value); // } else if (table == edge_table_) { // return tx.exec_prepared("delete_edge", key[0].value, key[1].value, key[2].value, values[0].value); // } else { // throw std::invalid_argument("Received unknown table"); // } // } // conn_->prepare("delete_object", "DELETE FROM " + object_table_ + " WHERE id = $1 AND timestamp < $2"); // conn_->prepare("delete_edge", "DELETE FROM " + edge_table_ + " WHERE id1 = $1 AND id2 = $2 AND type = $3 AND timestamp < $4"); } DB *NewCrdbDB() { return new CrdbDB; } const bool registered = DBFactory::RegisterDB("crdb", NewCrdbDB); } // benchmark
43.315864
471
0.620418
[ "vector" ]
0f787aa039113784ae18bd1148a339ae5111d065
28,537
cpp
C++
src/jsonv-tests/serialization_builder_tests.cpp
BeStateless/json-voorhees-1
9752f38d38cfd9d608c9943b6a1ab986ea75f21b
[ "Apache-2.0" ]
138
2015-02-13T08:34:19.000Z
2022-03-04T20:08:11.000Z
src/jsonv-tests/serialization_builder_tests.cpp
BeStateless/json-voorhees-1
9752f38d38cfd9d608c9943b6a1ab986ea75f21b
[ "Apache-2.0" ]
104
2015-01-04T21:14:02.000Z
2022-03-04T21:34:47.000Z
src/jsonv-tests/serialization_builder_tests.cpp
BeStateless/json-voorhees-1
9752f38d38cfd9d608c9943b6a1ab986ea75f21b
[ "Apache-2.0" ]
28
2015-02-21T15:38:24.000Z
2022-01-25T15:46:46.000Z
/** \file * * Copyright (c) 2015-2019 by Travis Gockel. All rights reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the Apache License * as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later * version. * * \author Travis Gockel (travis@gockelhut.com) **/ #include "test.hpp" #include <jsonv/parse.hpp> #include <jsonv/serialization_builder.hpp> #include <jsonv/serialization_optional.hpp> #include <set> #include <sstream> #include <tuple> #include <vector> namespace jsonv_test { using namespace jsonv; namespace { struct person { person() = default; person(std::string f, std::string l, int a, std::set<long> favorite_numbers = std::set<long>{}, std::vector<long> winning_numbers = std::vector<long>{}, optional<std::string> m = nullopt ) : firstname(std::move(f)), middle_name(m), lastname(std::move(l)), age(a), favorite_numbers(std::move(favorite_numbers)), winning_numbers(std::move(winning_numbers)) { } std::string firstname; optional<std::string> middle_name; std::string lastname; int age; std::set<long> favorite_numbers; std::vector<long> winning_numbers; bool operator==(const person& other) const { return std::tie(firstname, middle_name, lastname, age, favorite_numbers, winning_numbers) == std::tie(other.firstname, other.middle_name, other.lastname, other.age, other.favorite_numbers, other.winning_numbers); } friend std::ostream& operator<<(std::ostream& os, const person& p) { return os << p.firstname << " " << (p.middle_name ? *p.middle_name+" " : "") << p.lastname << " (" << p.age << ")"; } friend std::string to_string(const person& p) { std::ostringstream os; os << p; return os.str(); } }; struct sometype { int64_t v; }; } TEST(serialization_builder_members) { formats fmt = formats_builder() .type<person>() .member("firstname", &person::firstname) .member("middle_name", &person::middle_name) .member("lastname", &person::lastname) .member("age", &person::age) .register_optional<optional<std::string>>() .compose_checked(formats::defaults()) ; person p("Bob", "Builder", 29); to_string(p); value expected = object({ { "firstname", p.firstname }, { "middle_name", jsonv::null }, { "lastname", p.lastname }, { "age", p.age } } ); value encoded = to_json(p, fmt); ensure_eq(expected, encoded); person q = extract<person>(encoded, fmt); ensure_eq(expected, encoded); } TEST(serialization_builder_members_since) { using my_pair = std::pair<int, int>; formats fmt = formats_builder() .type<my_pair>() .member("a", &my_pair::first) .member("b", &my_pair::second) .since({ 2, 0 }) .compose_checked(formats::defaults()) ; auto to_json_ver = [&fmt] (const version& v) { serialization_context context(fmt, v); return context.to_json(my_pair(5, 10)); }; ensure_eq(0U, to_json_ver({ 1, 0 }).count("b")); ensure_eq(1U, to_json_ver({ 2, 0 }).count("b")); ensure_eq(1U, to_json_ver({ 3, 0 }).count("b")); } TEST(serialization_builder_container_members) { formats fmt = formats_builder() .type<person>() .member("firstname", &person::firstname) .member("lastname", &person::lastname) .member("age", &person::age) .member("favorite_numbers", &person::favorite_numbers) .member("winning_numbers", &person::winning_numbers) #if JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES .register_containers<long, std::set, std::vector>() #else .register_container<std::set<long>>() .register_container<std::vector<long>>() #endif .compose_checked(formats::defaults()) ; person p("Bob", "Builder", 29, { 1, 2, 3, 4 }, { 5, 6, 7, 8 }); value expected = object({ { "firstname", p.firstname }, { "lastname", p.lastname }, { "age", p.age }, { "favorite_numbers", array({ 1, 2, 3, 4 })}, { "winning_numbers", array({ 5, 6, 7, 8 })}, } ); auto encoded = to_json(p, fmt); ensure_eq(expected, encoded); person q = extract<person>(encoded, fmt); ensure_eq(p, q); } TEST(serialization_builder_extract_extra_keys) { std::set<std::string> extra_keys; auto extra_keys_handler = [&extra_keys] (const extraction_context&, const value&, std::set<std::string> x) { extra_keys = std::move(x); }; formats fmt = formats_builder() .type<person>() .member("firstname", &person::firstname) .member("lastname", &person::lastname) .member("age", &person::age) .on_extract_extra_keys(extra_keys_handler) .compose_checked(formats::defaults()) ; person p("Bob", "Builder", 29); value encoded = object({ { "firstname", p.firstname }, { "lastname", p.lastname }, { "age", p.age }, { "extra1", 10 }, { "extra2", "pie" } } ); person q = extract<person>(encoded, fmt); ensure_eq(p, q); ensure(extra_keys == std::set<std::string>({ "extra1", "extra2" })); } TEST(serialization_builder_post_extract_single) { auto post_extract_handler = [] (const extraction_context&, person&& p) -> person { p.age++; return p; }; formats fmt = formats_builder() .type<person>() .post_extract(post_extract_handler) .member("firstname", &person::firstname) .member("lastname", &person::lastname) .member("age", &person::age) .compose_checked(formats::defaults()) ; person p("Bob", "Builder", 29); auto encoded = to_json(p, fmt); person q = extract<person>(encoded, fmt); ensure_eq(person("Bob", "Builder", 30), q); } TEST(serialization_builder_post_extract_multi) { auto post_extract_handler_1 = [] (const extraction_context&, person&& p) { p.age++; return p; }; auto post_extract_handler_2 = [] (const extraction_context&, person&& p) { p.lastname = "Mc" + p.lastname; return p; }; formats fmt = formats_builder() .type<person>() .post_extract(post_extract_handler_1) .post_extract(post_extract_handler_2) .member("firstname", &person::firstname) .member("lastname", &person::lastname) .member("age", &person::age) .compose_checked(formats::defaults()) ; person p("Bob", "Builder", 29); auto encoded = to_json(p, fmt); person q = extract<person>(encoded, fmt); ensure_eq(person("Bob", "McBuilder", 30), q); } TEST(serialization_builder_defaults) { formats fmt = formats_builder() .type<person>() .member("firstname", &person::firstname) .member("lastname", &person::lastname) .member("age", &person::age) .default_value(20) .member("favorite_numbers", &person::favorite_numbers) .member("winning_numbers", &person::winning_numbers) .default_value([] (const extraction_context& cxt, const value& val) { return cxt.extract_sub<std::vector<long>>(val, "favorite_numbers"); } ) .default_on_null() #if JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES .register_containers<long, std::set, std::vector>() #else .register_container<std::set<long>>() .register_container<std::vector<long>>() #endif .compose_checked(formats::defaults()) ; person p("Bob", "Builder", 20, { 1, 2, 3, 4 }, { 1, 2, 3, 4 }); value input = object({ { "firstname", p.firstname }, { "lastname", p.lastname }, { "favorite_numbers", array({ 1, 2, 3, 4 })}, { "winning_numbers", null }, } ); auto encoded = to_json(p, fmt); person q = extract<person>(encoded, fmt); ensure_eq(p, q); } TEST(serialization_builder_encode_checks) { formats fmt = formats_builder() .type<person>() .member("firstname", &person::firstname) .member("lastname", &person::lastname) .member("age", &person::age) .encode_if([] (const serialization_context&, int age) { return age > 20; }) .member("favorite_numbers", &person::favorite_numbers) .encode_if([] (const serialization_context&, const std::set<long>& nums) { return nums.size(); }) .member("winning_numbers", &person::winning_numbers) .encode_if([] (const serialization_context&, const std::vector<long>& nums) { return nums.size(); }) #if JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES .register_containers<long, std::set, std::vector>() #else .register_container<std::set<long>>() .register_container<std::vector<long>>() #endif .compose_checked(formats::list { formats::defaults() }) ; person p("Bob", "Builder", 20, std::set<long>(), { 1 }); value expected = object({ { "firstname", p.firstname }, { "lastname", p.lastname }, { "winning_numbers", array({ 1 }) }, } ); value encoded = to_json(p, fmt); ensure_eq(expected, encoded); } TEST(serialization_builder_check_references_fails) { formats_builder builder; builder.reference_type(std::type_index(typeid(int))); builder.reference_type(std::type_index(typeid(long)), std::type_index(typeid(person))); ensure_throws(std::logic_error, builder.check_references(formats(), "test")); } namespace { struct foo { int a; int b; std::string c; static foo create_default() { foo out; out.a = 0; out.b = 1; out.c = "default"; return out; } }; struct bar { foo x; foo y; std::string z; std::string w; }; TEST(serialization_builder_extra_unchecked_key) { jsonv::formats local_formats = jsonv::formats_builder() .type<foo>() .member("a", &foo::a) .member("b", &foo::b) .default_value(10) .default_on_null() .member("c", &foo::c) .type<bar>() .member("x", &bar::x) .member("y", &bar::y) .member("z", &bar::z) .since(jsonv::version(2, 0)) .member("w", &bar::w) .until(jsonv::version(5, 0)) ; jsonv::formats format = jsonv::formats::compose({ jsonv::formats::defaults(), local_formats }); jsonv::value val = object({ { "x", object({ { "a", 50 }, { "b", 20 }, { "c", "Blah" }, { "extra", "key" } }) }, { "y", object({ { "a", 10 }, { "c", "No B?" } }) }, { "z", "Only serialized in 2.0+" }, { "w", "Only serialized before 5.0" } } ); bar x = jsonv::extract<bar>(val, format); } TEST(serialization_builder_extra_unchecked_key_throws) { jsonv::formats local_formats = jsonv::formats_builder() .type<foo>() .on_extract_extra_keys(jsonv::throw_extra_keys_extraction_error) .member("a", &foo::a) .member("b", &foo::b) .default_value(10) .default_on_null() .member("c", &foo::c) .type<bar>() .member("x", &bar::x) .member("y", &bar::y) .member("z", &bar::z) .since(jsonv::version(2, 0)) .member("w", &bar::w) .until(jsonv::version(5, 0)) ; jsonv::formats format = jsonv::formats::compose({ jsonv::formats::defaults(), local_formats }); jsonv::value val = object({ { "x", object({ { "a", 50 }, { "b", 20 }, { "c", "Blah" }, { "extra", "key" } }) }, { "y", object({ { "a", 10 }, { "c", "No B?" } }) }, { "z", "Only serialized in 2.0+" }, { "w", "Only serialized before 5.0" } } ); try { jsonv::extract<bar>(val, format); throw std::runtime_error("Should have thrown an extraction_error"); } catch (const extraction_error& err) { ensure_eq(path({"x"}), err.path()); } } TEST(serialization_builder_type_based_default_value) { jsonv::formats local_formats = jsonv::formats_builder() .type<foo>() .member("a", &foo::a) .member("b", &foo::b) .member("c", &foo::c) .type_default_on_null() .type_default_value(foo::create_default()) ; jsonv::formats format = jsonv::formats::compose({ jsonv::formats::defaults(), local_formats }); auto f = jsonv::extract<foo>(value(), format); auto e = foo::create_default(); ensure_eq(e.a, f.a); ensure_eq(e.b, f.b); ensure_eq(e.c, f.c); } class wrapped_things { public: wrapped_things() = default; wrapped_things(int x, int y) : _x(x), _y(y) { } const int& x() const { return _x; } int& x() { return _x; } const int& y() const { return _y; } void y(int&& val) { _y = val; } friend bool operator==(const wrapped_things& a, const wrapped_things& b) { return a.x() == b.x() && a.y() == b.y(); } friend std::ostream& operator<<(std::ostream& os, const wrapped_things& val) { return os << '(' << val.x() << ", " << val.y() << ')'; } private: int _x; int _y; }; TEST(serialization_builder_access_mutate) { #ifndef _MSC_VER jsonv::formats local_formats = jsonv::formats_builder() .type<wrapped_things>() .member("x", &wrapped_things::x, &wrapped_things::x) .member("y", &wrapped_things::y, &wrapped_things::y) ; jsonv::formats format = jsonv::formats::compose({ jsonv::formats::defaults(), local_formats }); #endif } } namespace x { enum class ring { fire, wind, water, earth, heart, }; } TEST(serialization_builder_enum_strings) { using namespace x; jsonv::formats formats = jsonv::formats_builder() .enum_type<ring>("ring", { { ring::fire, "fire" }, { ring::wind, "wind" }, { ring::water, "water" }, { ring::earth, "earth" }, { ring::heart, "heart" }, } ) #if JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES .register_containers<ring, std::vector>() #else .register_container<std::vector<ring>>() #endif .check_references(); ensure(ring::fire == jsonv::extract<ring>("fire", formats)); ensure(ring::wind == jsonv::extract<ring>("wind", formats)); ensure(ring::water == jsonv::extract<ring>("water", formats)); ensure(ring::earth == jsonv::extract<ring>("earth", formats)); ensure(ring::heart == jsonv::extract<ring>("heart", formats)); jsonv::value jsons = jsonv::array({ "fire", "wind", "water", "earth", "heart" }); std::vector<ring> exp = { ring::fire, ring::wind, ring::water, ring::earth, ring::heart }; std::vector<ring> val = jsonv::extract<std::vector<ring>>(jsons, formats); ensure(val == exp); value enc = jsonv::to_json(exp, formats); ensure(enc == jsons); ensure_throws(jsonv::extraction_error, jsonv::extract<ring>("FIRE", formats)); ensure_throws(jsonv::extraction_error, jsonv::extract<ring>("useless", formats)); } TEST(serialization_builder_enum_strings_icase) { using namespace x; jsonv::formats formats = jsonv::formats_builder() .enum_type_icase<ring>("ring", { { ring::fire, "fire" }, { ring::wind, "wind" }, { ring::water, "water" }, { ring::earth, "earth" }, { ring::heart, "heart" }, } ) #if JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES .register_containers<ring, std::vector>() #else .register_container<std::vector<ring>>() #endif .check_references(jsonv::formats::defaults()); ensure(ring::fire == jsonv::extract<ring>("fiRe", formats)); ensure(ring::wind == jsonv::extract<ring>("wIND", formats)); ensure(ring::water == jsonv::extract<ring>("Water", formats)); ensure(ring::earth == jsonv::extract<ring>("EARTH", formats)); ensure(ring::heart == jsonv::extract<ring>("HEART", formats)); jsonv::value jsons = jsonv::array({ "fire", "wind", "water", "earth", "heart" }); std::vector<ring> exp = { ring::fire, ring::wind, ring::water, ring::earth, ring::heart }; std::vector<ring> val = jsonv::extract<std::vector<ring>>(jsons, formats); ensure(val == exp); value enc = jsonv::to_json(exp, formats); ensure(enc == jsons); ensure_throws(jsonv::extraction_error, jsonv::extract<ring>("useless", formats)); } TEST(serialization_builder_enum_strings_icase_multimapping) { using namespace x; jsonv::formats formats = jsonv::formats_builder() .enum_type_icase<ring>("ring", { { ring::fire, "fire" }, { ring::fire, 666 }, { ring::wind, "wind" }, { ring::water, "water" }, { ring::earth, "earth" }, { ring::earth, true }, { ring::heart, "heart" }, { ring::heart, "useless" }, } ) #if JSONV_COMPILER_SUPPORTS_TEMPLATE_TEMPLATES .register_containers<ring, std::vector>() #else .register_container<std::vector<ring>>() #endif .check_references(jsonv::formats::defaults()); ensure(ring::fire == jsonv::extract<ring>("fiRe", formats)); ensure(ring::fire == jsonv::extract<ring>(666, formats)); ensure(ring::wind == jsonv::extract<ring>("wIND", formats)); ensure(ring::water == jsonv::extract<ring>("Water", formats)); ensure(ring::earth == jsonv::extract<ring>("EARTH", formats)); ensure(ring::earth == jsonv::extract<ring>(true, formats)); ensure(ring::heart == jsonv::extract<ring>("HEART", formats)); ensure(ring::heart == jsonv::extract<ring>("useless", formats)); jsonv::value jsons = jsonv::array({ "fire", "wind", "water", "earth", "heart" }); std::vector<ring> exp = { ring::fire, ring::wind, ring::water, ring::earth, ring::heart }; std::vector<ring> val = jsonv::extract<std::vector<ring>>(jsons, formats); ensure(val == exp); value enc = jsonv::to_json(exp, formats); ensure(enc == jsons); ensure_throws(jsonv::extraction_error, jsonv::extract<ring>(false, formats)); ensure_throws(jsonv::extraction_error, jsonv::extract<ring>(5, formats)); } namespace { struct base { virtual std::string get() const = 0; }; struct a_derived : base { virtual std::string get() const override { return "a"; } static void json_adapt(adapter_builder<a_derived>& builder) { builder.member("type", &a_derived::x); } std::string x = "a"; }; struct b_derived : base { virtual std::string get() const override { return "b"; } static void json_adapt(adapter_builder<b_derived>& builder) { builder.member("type", &b_derived::x); } static void json_adapt_bad_value(adapter_builder<b_derived>& builder) { builder.member("type", &b_derived::bad); } static void json_adapt_no_value(adapter_builder<b_derived>&) { } std::string x = "b"; std::string bad = "bad"; }; struct c_derived : base { virtual std::string get() const override { return "c"; } static void json_adapt(adapter_builder<c_derived>&) { } static void json_adapt_some_value(adapter_builder<c_derived>& builder) { builder.member("type", &c_derived::x); } std::string x = "c"; }; } TEST(serialization_builder_polymorphic_direct) { auto make_fmts = [](std::function<void(adapter_builder<b_derived>&)> b_adapter, std::function<void(adapter_builder<c_derived>&)> c_adapter) { return formats::compose ({ formats_builder() .polymorphic_type<std::unique_ptr<base>>("type") .subtype<a_derived>("a") .subtype<b_derived>("b", keyed_subtype_action::check) .subtype<c_derived>("c", keyed_subtype_action::insert) .type<a_derived>(a_derived::json_adapt) .type<b_derived>(b_adapter) .type<c_derived>(c_adapter) .register_container<std::vector<std::unique_ptr<base>>>() .check_references(formats::defaults()), formats::defaults() }); }; auto make_bad_fmts = []() { formats_builder() .polymorphic_type<std::unique_ptr<base>>("type") .subtype<a_derived>("a") .subtype<a_derived>("a"); }; auto fmts = make_fmts(b_derived::json_adapt, c_derived::json_adapt); value input = array({ object({{ "type", "a" }}), object({{ "type", "b" }}), object({{ "type", "c" }}) }); auto output = extract<std::vector<std::unique_ptr<base>>>(input, fmts); ensure(output.at(0)->get() == "a"); ensure(output.at(1)->get() == "b"); ensure(output.at(2)->get() == "c"); value encoded = to_json(output, fmts); ensure_eq(input, encoded); // If the b type serializes the wrong value for "type" we should get a runtime_error. fmts = make_fmts(b_derived::json_adapt_bad_value, c_derived::json_adapt); ensure_throws(std::runtime_error, to_json(output, fmts)); // If the b type does not add a "type" key we should get a runtime_error. fmts = make_fmts(b_derived::json_adapt_no_value, c_derived::json_adapt); ensure_throws(std::runtime_error, to_json(output, fmts)); // If the c type serializes "type" at all we should get an error, because we expected to insert it ourselves. fmts = make_fmts(b_derived::json_adapt, c_derived::json_adapt_some_value); ensure_throws(std::runtime_error, to_json(output, fmts)); // Attempting to register the same keyed subtype twice should result in a duplicate_type_error. ensure_throws(duplicate_type_error, make_bad_fmts()); } TEST(serialization_builder_duplicate_type_actions) { // Make one adapter that serializes and deserializes an int directly. static const auto adapter1 = make_adapter( [](const extraction_context&, const value& v) { return sometype{v.as_integer()}; }, [](const serialization_context&, const sometype& v) { return value(v.v); }); // Make another adapter that adds one each time an int is serialized and deserialized. static const auto adapter2 = make_adapter( [](const extraction_context&, const value& v) { return sometype{v.as_integer() + 1}; }, [](const serialization_context&, const sometype& v) { return value(v.v + 1); }); // Helper that serializes then deserializes an integer and returns the result. static const auto serde = [] (int v, const formats& f) { return extract<sometype>(to_json(sometype{v}, f), f).v; }; // Initial adapter registration. formats_builder builder; builder.register_adapter(&adapter1); ensure_eq(1, serde(1, builder)); // Default should throw, and the adapter should be unchanged. ensure_throws(duplicate_type_error, builder.register_adapter(&adapter2)); ensure_eq(1, serde(1, builder)); // Ignore should not throw, but the adapter should still be unchanged. builder.on_duplicate_type(duplicate_type_action::ignore); builder.register_adapter(&adapter2); ensure_eq(1, serde(1, builder)); // Replace should not throw, and the adapter should be replaced. builder.on_duplicate_type(duplicate_type_action::replace); builder.register_adapter(&adapter2); ensure_eq(3, serde(1, builder)); // Going back to exception should again throw an exception. builder.on_duplicate_type(duplicate_type_action::exception); ensure_throws(duplicate_type_error, builder.register_adapter(&adapter1)); ensure_eq(3, serde(1, builder)); } }
36.260483
134
0.503977
[ "object", "vector" ]
0f7b398a44ad3718a0e7d8765ac5ded7061f90f5
1,434
hpp
C++
controller/session/util/buffer-pool.hpp
UbuntuEvangelist/greyhound
350dfdad9c907391200b75b110bc3bc779eb6da8
[ "MIT" ]
null
null
null
controller/session/util/buffer-pool.hpp
UbuntuEvangelist/greyhound
350dfdad9c907391200b75b110bc3bc779eb6da8
[ "MIT" ]
null
null
null
controller/session/util/buffer-pool.hpp
UbuntuEvangelist/greyhound
350dfdad9c907391200b75b110bc3bc779eb6da8
[ "MIT" ]
18
2017-01-12T09:26:10.000Z
2019-06-18T14:55:37.000Z
#pragma once #include <map> #include <mutex> #include <vector> #include <memory> #include <cstring> #include <condition_variable> class ItcBufferPool; class ItcBuffer { // Don't let anyone besides the ItcBufferPool create or release these. friend class ItcBufferPool; public: // Append vector onto this buffer. If current size plus the size of the // incoming bytes is greater than the max capacity, std::runtime_error is // thrown. std::size_t push(const char* data, std::size_t size); std::size_t size() const; void resize(std::size_t); const std::vector<char>& vecRef() const { return m_buffer; } std::vector<char>& vecRef() { return m_buffer; } char* data(); private: ItcBuffer(std::size_t id); std::size_t id() const { return m_id; } std::vector<char> m_buffer; const std::size_t m_id; std::mutex m_mutex; std::condition_variable m_cv; bool m_available; }; class ItcBufferPool { public: ItcBufferPool(std::size_t numBuffers); std::shared_ptr<ItcBuffer> acquire(); void release(std::shared_ptr<ItcBuffer> buffer); private: // If there are no buffers available, wait for one. Otherwise return. // m_mutex must be locked by the caller. void await(); std::vector<std::size_t> m_available; std::map<std::size_t, std::shared_ptr<ItcBuffer>> m_buffers; std::mutex m_mutex; std::condition_variable m_cv; };
22.761905
77
0.682706
[ "vector" ]
0f7db210e5b7c62670f4cabe516f072304eda130
7,589
cpp
C++
src/HMC5883L.cpp
iamcsharper/RoombaGroup
cdeaae618ba357a5ff2688037d6230c01c7ad839
[ "MIT" ]
2
2021-03-12T18:32:47.000Z
2021-06-01T13:54:26.000Z
src/HMC5883L.cpp
iamcsharper/RoombaGroup
cdeaae618ba357a5ff2688037d6230c01c7ad839
[ "MIT" ]
null
null
null
src/HMC5883L.cpp
iamcsharper/RoombaGroup
cdeaae618ba357a5ff2688037d6230c01c7ad839
[ "MIT" ]
1
2021-03-14T08:24:10.000Z
2021-03-14T08:24:10.000Z
/* HMC5883L.cpp - Class file for the HMC5883L Triple Axis Digital Compass Arduino Library. Version: 1.1.0 (c) 2014 Korneliusz Jarzebski www.jarzebski.pl This program is free software: you can redistribute it and/or modify it under the terms of the version 3 GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include <Wire.h> #include "HMC5883L.h" bool HMC5883L::begin() { Wire.begin(SDA, SCL); if ((fastRegister8(HMC5883L_REG_IDENT_A) != 0x48) || (fastRegister8(HMC5883L_REG_IDENT_B) != 0x34) || (fastRegister8(HMC5883L_REG_IDENT_C) != 0x33)) { return false; } setRange(HMC5883L_RANGE_1_3GA); setMeasurementMode(HMC5883L_CONTINOUS); setDataRate(HMC5883L_DATARATE_15HZ); setSamples(HMC5883L_SAMPLES_1); mgPerDigit = 0.92f; return true; } Vector HMC5883L::readRaw(void) { v.XAxis = readRegister16(HMC5883L_REG_OUT_X_M) - xOffset; v.YAxis = readRegister16(HMC5883L_REG_OUT_Y_M) - yOffset; v.ZAxis = readRegister16(HMC5883L_REG_OUT_Z_M); return v; } Vector HMC5883L::readNormalize(void) { v.XAxis = ((float)readRegister16(HMC5883L_REG_OUT_X_M) - xOffset) * mgPerDigit; v.YAxis = ((float)readRegister16(HMC5883L_REG_OUT_Y_M) - yOffset) * mgPerDigit; v.ZAxis = (float)readRegister16(HMC5883L_REG_OUT_Z_M) * mgPerDigit; return v; } void HMC5883L::setOffset(int xo, int yo) { xOffset = xo; yOffset = yo; } void HMC5883L::setRange(hmc5883l_range_t range) { switch (range) { case HMC5883L_RANGE_0_88GA: mgPerDigit = 0.073f; break; case HMC5883L_RANGE_1_3GA: mgPerDigit = 0.92f; break; case HMC5883L_RANGE_1_9GA: mgPerDigit = 1.22f; break; case HMC5883L_RANGE_2_5GA: mgPerDigit = 1.52f; break; case HMC5883L_RANGE_4GA: mgPerDigit = 2.27f; break; case HMC5883L_RANGE_4_7GA: mgPerDigit = 2.56f; break; case HMC5883L_RANGE_5_6GA: mgPerDigit = 3.03f; break; case HMC5883L_RANGE_8_1GA: mgPerDigit = 4.35f; break; default: break; } writeRegister8(HMC5883L_REG_CONFIG_B, range << 5); } hmc5883l_range_t HMC5883L::getRange(void) { return (hmc5883l_range_t)((readRegister8(HMC5883L_REG_CONFIG_B) >> 5)); } void HMC5883L::setMeasurementMode(hmc5883l_mode_t mode) { uint8_t value; value = readRegister8(HMC5883L_REG_MODE); value &= 0b11111100; value |= mode; writeRegister8(HMC5883L_REG_MODE, value); } hmc5883l_mode_t HMC5883L::getMeasurementMode(void) { uint8_t value; value = readRegister8(HMC5883L_REG_MODE); value &= 0b00000011; return (hmc5883l_mode_t)value; } void HMC5883L::setDataRate(hmc5883l_dataRate_t dataRate) { uint8_t value; value = readRegister8(HMC5883L_REG_CONFIG_A); value &= 0b11100011; value |= (dataRate << 2); writeRegister8(HMC5883L_REG_CONFIG_A, value); } hmc5883l_dataRate_t HMC5883L::getDataRate(void) { uint8_t value; value = readRegister8(HMC5883L_REG_CONFIG_A); value &= 0b00011100; value >>= 2; return (hmc5883l_dataRate_t)value; } void HMC5883L::setSamples(hmc5883l_samples_t samples) { uint8_t value; value = readRegister8(HMC5883L_REG_CONFIG_A); value &= 0b10011111; value |= (samples << 5); writeRegister8(HMC5883L_REG_CONFIG_A, value); } hmc5883l_samples_t HMC5883L::getSamples(void) { uint8_t value; value = readRegister8(HMC5883L_REG_CONFIG_A); value &= 0b01100000; value >>= 5; return (hmc5883l_samples_t)value; } // Write byte to register void HMC5883L::writeRegister8(uint8_t reg, uint8_t value) { Wire.beginTransmission(HMC5883L_ADDRESS); #if ARDUINO >= 100 Wire.write(reg); Wire.write(value); #else Wire.send(reg); Wire.send(value); #endif Wire.endTransmission(); } // Read byte to register uint8_t HMC5883L::fastRegister8(uint8_t reg) { uint8_t value; Wire.beginTransmission(HMC5883L_ADDRESS); #if ARDUINO >= 100 Wire.write(reg); #else Wire.send(reg); #endif Wire.endTransmission(); Wire.requestFrom(HMC5883L_ADDRESS, 1); #if ARDUINO >= 100 value = Wire.read(); #else value = Wire.receive(); #endif; Wire.endTransmission(); return value; } // Read byte from register uint8_t HMC5883L::readRegister8(uint8_t reg) { uint8_t value; Wire.beginTransmission(HMC5883L_ADDRESS); #if ARDUINO >= 100 Wire.write(reg); #else Wire.send(reg); #endif Wire.endTransmission(); Wire.beginTransmission(HMC5883L_ADDRESS); Wire.requestFrom(HMC5883L_ADDRESS, 1); while (!Wire.available()) { }; #if ARDUINO >= 100 value = Wire.read(); #else value = Wire.receive(); #endif; Wire.endTransmission(); return value; } // Read word from register int16_t HMC5883L::readRegister16(uint8_t reg) { int16_t value; Wire.beginTransmission(HMC5883L_ADDRESS); #if ARDUINO >= 100 Wire.write(reg); #else Wire.send(reg); #endif Wire.endTransmission(); Wire.beginTransmission(HMC5883L_ADDRESS); Wire.requestFrom(HMC5883L_ADDRESS, 2); while (!Wire.available()) { }; #if ARDUINO >= 100 uint8_t vha = Wire.read(); uint8_t vla = Wire.read(); #else uint8_t vha = Wire.receive(); uint8_t vla = Wire.receive(); #endif; Wire.endTransmission(); value = vha << 8 | vla; return value; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define M_PI 3.14159265358979323846 HMC5883L compass; void compass_init() { // Initialize Initialize HMC5883L Serial.println("Initialize HMC5883L"); while (!compass.begin()) { Serial.println("Could not find a valid HMC5883L sensor, check wiring!"); delay(500); } // Set measurement range compass.setRange(HMC5883L_RANGE_1_3GA); // Set measurement mode compass.setMeasurementMode(HMC5883L_CONTINOUS); // Set data rate compass.setDataRate(HMC5883L_DATARATE_30HZ); // Set number of samples averaged compass.setSamples(HMC5883L_SAMPLES_8); // Set calibration offset. See HMC5883L_calibration.ino compass.setOffset(0, 0); } float GetCompass() { Vector norm = compass.readNormalize(); // Calculate heading float heading = atan2(norm.YAxis, norm.XAxis); // Set declination angle on your location and fix heading // You can find your declination on: http://magnetic-declination.com/ // (+) Positive or (-) for negative // For Bytom / Poland declination angle is 4'26E (positive) // Formula: (deg + (min / 60.0)) / (180 / M_PI); float declinationAngle = (4.0 + (26.0 / 60.0)) / (180 / M_PI); heading += declinationAngle; // Correct for heading < 0deg and heading > 360deg // if (heading < 0) // { // heading += 2 * PI; // } // if (heading > 2 * PI) // { // heading -= 2 * PI; // } // RETURN AS RADIANS //float headingDegrees = heading * 180 / M_PI; return heading; }
22.125364
174
0.660561
[ "vector" ]
0f7f5649de7a569548ba4cd8a3d3a6fb21042bfc
3,591
hpp
C++
include/range/v3/action/split.hpp
seewpx/range-v3
8527a9741518dd61082bc3e2139aed8ecb5da4f6
[ "MIT" ]
3,436
2015-01-05T14:27:21.000Z
2022-03-31T07:56:04.000Z
include/range/v3/action/split.hpp
seewpx/range-v3
8527a9741518dd61082bc3e2139aed8ecb5da4f6
[ "MIT" ]
1,197
2015-01-01T21:27:32.000Z
2022-03-29T17:46:09.000Z
include/range/v3/action/split.hpp
seewpx/range-v3
8527a9741518dd61082bc3e2139aed8ecb5da4f6
[ "MIT" ]
490
2015-01-04T00:18:04.000Z
2022-03-25T18:59:43.000Z
/// \file // Range v3 library // // Copyright Eric Niebler 2013-present // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_ACTION_SPLIT_HPP #define RANGES_V3_ACTION_SPLIT_HPP #include <vector> #include <meta/meta.hpp> #include <range/v3/range_fwd.hpp> #include <range/v3/action/action.hpp> #include <range/v3/action/concepts.hpp> #include <range/v3/functional/bind_back.hpp> #include <range/v3/iterator/concepts.hpp> #include <range/v3/iterator/traits.hpp> #include <range/v3/range/conversion.hpp> #include <range/v3/utility/static_const.hpp> #include <range/v3/view/split.hpp> #include <range/v3/detail/prologue.hpp> namespace ranges { /// \addtogroup group-actions /// @{ namespace actions { struct split_fn { template<typename Rng> using split_value_t = meta::if_c<(bool)ranges::container<Rng>, // uncvref_t<Rng>, std::vector<range_value_t<Rng>>>; template(typename T)( /// \pre requires range<T &>) constexpr auto operator()(T & t) const { return make_action_closure( bind_back(split_fn{}, detail::reference_wrapper_<T>(t))); } template<typename T> constexpr auto operator()(T && t) const { return make_action_closure(bind_back(split_fn{}, static_cast<T &&>(t))); } // BUGBUG something is not right with the actions. It should be possible // to move a container into a split and have elements moved into the result. template(typename Rng)( /// \pre requires input_range<Rng> AND indirectly_comparable< iterator_t<Rng>, range_value_t<Rng> const *, ranges::equal_to>) std::vector<split_value_t<Rng>> // operator()(Rng && rng, range_value_t<Rng> val) const { return views::split(rng, std::move(val)) | to<std::vector<split_value_t<Rng>>>(); } template(typename Rng, typename Pattern)( /// \pre requires input_range<Rng> AND viewable_range<Pattern> AND forward_range<Pattern> AND indirectly_comparable< iterator_t<Rng>, iterator_t<Pattern>, ranges::equal_to> AND (forward_range<Rng> || detail::tiny_range<Pattern>)) // std::vector<split_value_t<Rng>> operator()(Rng && rng, Pattern && pattern) const { return views::split(rng, static_cast<Pattern &&>(pattern)) | to<std::vector<split_value_t<Rng>>>(); } /// \cond template<typename Rng, typename T> invoke_result_t<split_fn, Rng, T &> // operator()(Rng && rng, detail::reference_wrapper_<T> r) const { return (*this)(static_cast<Rng &&>(rng), r.get()); } /// \endcond }; /// \relates actions::split_fn RANGES_INLINE_VARIABLE(split_fn, split) } // namespace actions /// @} } // namespace ranges #include <range/v3/detail/epilogue.hpp> #endif
32.645455
88
0.558062
[ "vector" ]
abf187f2e7bd3da9a8a9b1b7e127b13c8fa1fcf8
29,301
cxx
C++
oss_test/sframe_query_engine/optimizations.cxx
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
493
2016-07-11T13:35:24.000Z
2022-02-15T13:04:29.000Z
oss_test/sframe_query_engine/optimizations.cxx
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
27
2016-07-13T20:01:07.000Z
2022-02-01T18:55:28.000Z
oss_test/sframe_query_engine/optimizations.cxx
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
229
2016-07-12T10:39:54.000Z
2022-02-15T13:04:31.000Z
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include <sframe_query_engine/planning/planner.hpp> #include <sframe_query_engine/planning/planner_node.hpp> #include <sframe_query_engine/operators/all_operators.hpp> #include <sframe_query_engine/util/aggregates.hpp> #include <sframe_query_engine/operators/operator_transformations.hpp> #include <sframe/sarray.hpp> #include <cxxtest/TestSuite.h> #define ENABLE_HISTORY_TRACKING_OPTIMIZATION true using namespace graphlab; using namespace graphlab::query_eval; static const size_t n = 17; /** The array of planner nodes test different special cases of the * optimization pipeline: * * .v[0] -- reference: no-opt. * .v[1] -- opt + naive * .v[2] -- opt * .v[3] -- opt, with many nodes in the history pre-materialized. * .v[4] -- opt with zero length sframes to test this corner case. * .v[5] -- opt with truncated sframes to test indexing and slicing, 0-n/2 * .v[6] -- opt with truncated sframes to test indexing and slicing, n/4-3*n/4 * .v[7] -- opt with truncated sframes to test indexing and slicing, n/2-n */ // Actually using arrays to make sure full + no-opt + no-opt-naive are all the same struct node { std::array<std::shared_ptr<planner_node>, 8> v; std::set< std::array<std::shared_ptr<planner_node>, 2> > history; void pull_history(const std::vector<node>& nv) { for(const node& n : nv) { history.insert(n.history.begin(), n.history.end()); history.insert({n.v[0], n.v[3]}); } } }; //////////////////////////////////////////////////////////////////////////////// // General sources static void add_sliced_info(node& ret, size_t m) { static std::map<pnode_ptr, pnode_ptr> sliced_graph_memo; ret.v[5] = query_eval::make_sliced_graph(ret.v[0], 0, m / 2, sliced_graph_memo); ret.v[6] = query_eval::make_sliced_graph(ret.v[0], m / 4, (3 * m) / 4, sliced_graph_memo); ret.v[7] = query_eval::make_sliced_graph(ret.v[0], m / 2, m, sliced_graph_memo); }; static node source_sarray() { std::vector<flexible_type> data(n); for (size_t i = 0; i < n; ++i) data[i] = random::fast_uniform<size_t>(0,9); auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); graphlab::copy(data.begin(), data.end(), *sa); sa->close(); node ret; for(auto& n : ret.v) n = op_sarray_source::make_planner_node(sa); { // Element 4 is zero length. auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); sa->close(); ret.v[4] = op_sarray_source::make_planner_node(sa); } add_sliced_info(ret, n); ret.history.insert({ret.v[0], ret.v[3]}); return ret; } static node empty_sarray() { auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); sa->close(); node ret; for(auto& n : ret.v) n = op_sarray_source::make_planner_node(sa); ret.history.insert({ret.v[0], ret.v[3]}); add_sliced_info(ret, 0); return ret; } static node zero_source_sarray() { std::vector<flexible_type> data(n); for (size_t i = 0; i < n; ++i) data[i] = 0; auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); graphlab::copy(data.begin(), data.end(), *sa); sa->close(); node ret; for(auto& n : ret.v) n = op_sarray_source::make_planner_node(sa); { // Element 4 is zero length. auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); sa->close(); ret.v[4] = op_sarray_source::make_planner_node(sa); } add_sliced_info(ret, data.size()); ret.history.insert({ret.v[0], ret.v[3]}); return ret; } static node binary_source_sarray() { std::vector<flexible_type> data(n); for (size_t i = 0; i < n; ++i) { data[i] = (i < 4) ? 1 : random::fast_uniform<int>(0,1); } auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); graphlab::copy(data.begin(), data.end(), *sa); sa->close(); node ret; for(auto& n : ret.v) n = op_sarray_source::make_planner_node(sa); { // Element 4 is zero length. auto sa = std::make_shared<sarray<flexible_type>>(); sa->open_for_write(); sa->close(); ret.v[4] = op_sarray_source::make_planner_node(sa); } add_sliced_info(ret, data.size()); ret.history.insert({ret.v[0], ret.v[3]}); return ret; } static node source_sframe(size_t n_columns) { std::vector<std::vector<flexible_type> > data(n_columns); for(size_t i = 0; i < n_columns; ++i) { data[i].resize(n); for(size_t j = 0; j < n; ++j) { data[i][j] = random::fast_uniform<size_t>(0,9); } } std::vector<std::shared_ptr<sarray<flexible_type> > > sa_l(n_columns); for(size_t i = 0; i < n_columns; ++i) { auto sa = std::make_shared<sarray<flexible_type> >(); sa->open_for_write(); graphlab::copy(data[i].begin(), data[i].end(), *sa); sa->close(); sa_l[i] = sa; } node ret; for(auto& n : ret.v) n = op_sframe_source::make_planner_node(sframe(sa_l)); { for(size_t i = 0; i < n_columns; ++i) { auto sa = std::make_shared<sarray<flexible_type> >(); sa->open_for_write(); sa->close(); sa_l[i] = sa; } ret.v[4] = op_sframe_source::make_planner_node(sframe(sa_l)); } add_sliced_info(ret, data.size()); ret.history.insert({ret.v[0], ret.v[3]}); return ret; } static node shifted_source_sframe(size_t n_columns) { std::vector<std::vector<flexible_type> > data(n_columns); for(size_t i = 0; i < n_columns; ++i) { data[i].resize(2*n); for(size_t j = 0; j < 2*n; ++j) { data[i][j] = random::fast_uniform<size_t>(0,9); } } std::vector<std::shared_ptr<sarray<flexible_type> > > sa_l(n_columns); for(size_t i = 0; i < n_columns; ++i) { auto sa = std::make_shared<sarray<flexible_type> >(); sa->open_for_write(); graphlab::copy(data[i].begin(), data[i].end(), *sa); sa->close(); sa_l[i] = sa; } node ret; for(auto& pn : ret.v) pn = op_sframe_source::make_planner_node(sframe(sa_l), n/2, n/2 + n); { for(size_t i = 0; i < n_columns; ++i) { auto sa = std::make_shared<sarray<flexible_type> >(); sa->open_for_write(); sa->close(); sa_l[i] = sa; } ret.v[4] = op_sframe_source::make_planner_node(sframe(sa_l)); } add_sliced_info(ret, n); ret.history.insert({ret.v[0], ret.v[3]}); return ret; } static node empty_sframe(size_t n_columns) { std::vector<std::shared_ptr<sarray<flexible_type> > > sa_l(n_columns); for(size_t i = 0; i < n_columns; ++i) { auto sa = std::make_shared<sarray<flexible_type> >(); sa->open_for_write(); sa->close(); sa_l[i] = sa; } node ret; for(auto& n : ret.v) n = op_sframe_source::make_planner_node(sframe(sa_l)); add_sliced_info(ret, 0); ret.history.insert({ret.v[0], ret.v[3]}); return ret; } //////////////////////////////////////////////////////////////////////////////// // Transforms static node make_union(node n1, node n2) { node ret; for(size_t i = 0; i < n1.v.size(); ++i) ret.v[i] = op_union::make_planner_node(n1.v[i], n2.v[i]); ret.pull_history({n1, n2}); return ret; } static node make_project(node n1, const std::vector<size_t>& indices) { node ret; for(size_t i = 0; i < n1.v.size(); ++i) ret.v[i] = op_project::make_planner_node(n1.v[i], indices); ret.pull_history({n1}); return ret; } static node make_transform(node n1) { node ret; transform_type tr = [](const sframe_rows::row& r) -> flexible_type { flexible_type out = flex_int(1); for(size_t i = 0; i < r.size(); ++i) { out += r[i]; } return out % 10; }; for(size_t i = 0; i < n1.v.size(); ++i) ret.v[i] = op_transform::make_planner_node(n1.v[i], tr, flex_type_enum::INTEGER); ret.pull_history({n1}); return ret; } static node make_generalized_transform(node n1, size_t n_out) { std::vector<flex_type_enum> output_types(n_out, flex_type_enum::INTEGER); generalized_transform_type f = [=](const sframe_rows::row& r1, sframe_rows::row& r2) { size_t prod = 1; for(size_t i = 0; i < r1.size(); ++i) prod *= (1 + i + size_t(r1[i])); size_t src_idx = 0; for(size_t i = 0; i < n_out; ++i) { size_t idx_1 = (src_idx % r1.size()); ++src_idx; size_t idx_2 = (src_idx % r1.size()); ++src_idx; r2[i] = (prod + r1[idx_1] + r1[idx_2]) % 10; } }; node ret; for(size_t i = 0; i < n1.v.size(); ++i) ret.v[i] = op_generalized_transform::make_planner_node(n1.v[i], f, output_types); ret.pull_history({n1}); return ret; } static node make_logical_filter(node n1, node n2) { node ret; for(size_t i = 0; i < n1.v.size(); ++i) ret.v[i] = op_logical_filter::make_planner_node(n1.v[i], n2.v[i]); ret.pull_history({n1, n2}); return ret; } static node make_append(node n1, node n2) { node ret; for(size_t i = 0; i < n1.v.size(); ++i) ret.v[i] = op_append::make_planner_node(n1.v[i], n2.v[i]); ret.pull_history({n1, n2}); return ret; } static void check_sframes(sframe sf1, sframe sf2, std::string tag) { std::vector<std::vector<std::vector<flexible_type> > > results(2); sf1.get_reader()->read_rows(0, sf1.num_rows(), results[0]); sf2.get_reader()->read_rows(0, sf2.num_rows(), results[1]); bool all_okay = true; for(size_t i = 1; i < results.size() && all_okay; ++i) { if(results[0].size() != results[i].size()) { all_okay = false; break; } for(size_t j = 0; j < results[0].size() && all_okay; ++j) { if(results[0][j].size() != results[i][j].size()) { all_okay = false; break; } for(size_t k = 0; k < results[0][j].size(); ++k) { if(results[0][j][k] != results[i][j][k]) { all_okay = false; break; } // } } } if(!all_okay) { logprogress_stream << "ERROR (left) NO-OPT != OPT (right) [run=" << tag << "]" << std::endl; logprogress_stream << "------------------PATTERN--------------------" << std::endl; for(size_t j = 0; j < results[0].size(); ++j) { auto get_pattern = [&](size_t k, int i) -> char { if(results[0][j].size() <= k) return 'X'; if(results[1][j].size() <= k) return 'X'; int i1 = results[0][j][k]; int i2 = results[1][j][k]; if(i1 == i2) return ' '; if(i == 0) return '#'; if(i < 3) return '.'; if(i < 5) return '/'; if(i < 8) return '\\'; return 'O'; }; std::ostringstream ss; ss << "[ "; for(size_t k = 0; k < results[0][j].size(); ++k) { ss << get_pattern(k, results[0][j][k]) << " "; } ss << "] != [ "; for(size_t k = 0; k < results[1][j].size(); ++k) { ss << get_pattern(k, results[1][j][k]) << " "; } ss << "]"; logprogress_stream << ss.str() << std::endl; } logprogress_stream << std::endl; logprogress_stream << "------------------ACTUAL--------------------" << std::endl; for(size_t j = 0; j < results[0].size(); ++j) { std::ostringstream ss; ss << "[ "; for(size_t k = 0; k < results[0][j].size(); ++k) { ss << int(results[0][j][k]) << " "; } ss << "] != [ "; for(size_t k = 0; k < results[1][j].size(); ++k) { ss << int(results[1][j][k]) << " "; } ss << "]"; logprogress_stream << ss.str() << std::endl; } logprogress_stream << "------------------REPORT--------------------" << std::endl; std::vector<uint64_t> left_hashes(results[0][0].size(), 0); std::vector<uint64_t> right_hashes(results[1][0].size(), 0); for(size_t j = 0; j < results[0].size(); ++j) { for(size_t k = 0; k < results[0][j].size(); ++k) { left_hashes[k] = hash64(left_hashes[k], results[0][j][k]); } for(size_t k = 0; k < results[1][j].size(); ++k) { right_hashes[k] = hash64(right_hashes[k], results[1][j][k]); } } for(size_t i = 0; i < left_hashes.size(); ++i) { auto it = std::find(right_hashes.begin(), right_hashes.end(), left_hashes[i]); if(it == right_hashes.end()) { logprogress_stream << "Column " << i << ": not found in output."; } else { size_t idx = (it - right_hashes.begin()); if(idx == i) { logprogress_stream << "Column " << i << ": correct " << std::endl; } else { logprogress_stream << "Column " << i << ": in position " << idx << std::endl; } } } ASSERT_TRUE(false); } } #define _RUN(n) run(__LINE__, n) static void run(size_t line, node n) { global_logger().set_log_level(LOG_INFO); materialize_options no_opt; no_opt.disable_optimization = true; materialize_options naive; naive.naive_mode = true; std::vector<sframe> out(4); logprogress_stream << std::endl; logprogress_stream << "################################################################" << std::endl; logprogress_stream << ">>> Prewarming Optimizations <<<" << std::endl; logprogress_stream << ">>> " << line << std::endl; std::vector<decltype(n.history)::value_type> history_vect(n.history.begin(), n.history.end()); random::shuffle(history_vect); for(size_t i = 0; i < std::min<size_t>(history_vect.size(), 10); ++i) { sframe sf_1 = planner().materialize(history_vect[i][0], no_opt); sframe sf_2 = planner().materialize(history_vect[i][1], materialize_options()); check_sframes(sf_1, sf_2, "mixed-graph-materialize"); } logprogress_stream << std::endl; logprogress_stream << "################################################################" << std::endl; logprogress_stream << ">>> Optimization Disabled <<<" << std::endl; logprogress_stream << ">>> " << line << std::endl; out[0] = planner().materialize(n.v[0], no_opt); logprogress_stream << std::endl; logprogress_stream << "################################################################" << std::endl; logprogress_stream << ">>> Optimization Enabled, Naive Materialize <<<" << std::endl; logprogress_stream << ">>> " << line << std::endl; out[1] = planner().materialize(n.v[1], naive); logprogress_stream << std::endl; logprogress_stream << "################################################################" << std::endl; logprogress_stream << ">>> Optimization Enabled <<<" << std::endl; logprogress_stream << ">>> " << line << std::endl; out[2] = planner().materialize(n.v[2], materialize_options()); logprogress_stream << std::endl; logprogress_stream << "################################################################" << std::endl; logprogress_stream << ">>> Optimization Enabled, history of evaluation <<<" << std::endl; logprogress_stream << ">>> " << line << std::endl; out[3] = planner().materialize(n.v[3], materialize_options()); check_sframes(out[0], out[1], "naive"); check_sframes(out[0], out[2], "Opt"); check_sframes(out[0], out[3], "Opt-with-history"); } class opts : public CxxTest::TestSuite { public: void test_union_sarray() { node out = make_union(source_sarray(), source_sarray()); _RUN(out); } void test_project_sframe() { node out = make_project(source_sframe(5), {0, 2, 4}); _RUN(out); } void test_union_project_sframe() { random::seed(0); node n = source_sframe(5); for(size_t i = 0; i < 20; ++i) { std::vector<size_t> indices; for(size_t i = 0; i < 5; ++i) indices.push_back(random::fast_uniform<size_t>(0, 9)); if(i % 2 == 0) n = make_union(n, source_sframe(5)); else n = make_union(source_sframe(5), n); n = make_project(n, indices); } _RUN(n); } void test_union_project_elimination_right() { node n1 = make_transform(source_sframe(2)); node n2 = make_transform(source_sframe(2)); node n = make_union(n1, n2); n = make_project(n, {0}); _RUN(n); } void test_union_project_elimination_left() { node n1 = make_transform(source_sframe(2)); node n2 = make_transform(source_sframe(2)); node n = make_union(n1, n2); n = make_project(n, {1}); _RUN(n); } void test_union_project_switch_places() { node n = source_sframe(2); node old_n = source_sframe(2); n = make_union(n, old_n); old_n = n; n = make_project(n, {3,0}); n = make_union(n, old_n); _RUN(n); } void test_union_project_recursive_sframe_2() { random::seed(0); node n = source_sframe(5); node old_n = source_sframe(5); for(size_t i = 0; i < 20; ++i) { std::vector<size_t> indices; for(size_t i = 0; i < 5; ++i) indices.push_back(random::fast_uniform<size_t>(0, 9)); if(random::fast_uniform<size_t>(0, 1) == 0) n = make_union(n, old_n); else n = make_union(old_n, n); old_n = n; n = make_project(n, indices); } _RUN(n); } void test_union_project_recursive_sframe_3() { random::seed(0); node n = source_sframe(5); node old_n = source_sframe(5); std::vector<node> nodes; for(size_t i = 0; i < 10; ++i) { std::vector<size_t> indices; for(size_t i = 0; i < 5; ++i) indices.push_back(random::fast_uniform<size_t>(0, 9)); if(random::fast_uniform<size_t>(0, 1) == 0) n = make_union(n, old_n); else n = make_union(old_n, n); nodes.push_back(n); old_n = n; n = make_project(n, indices); nodes.push_back(n); n = make_union(n, nodes[random::fast_uniform<size_t>(0, nodes.size() - 1)]); n = make_union(n, nodes[random::fast_uniform<size_t>(0, nodes.size() - 1)]); } _RUN(n); } void test_project_union_transform() { node n = source_sframe(5); node out = make_union(n, make_transform(make_project(n, {1, 2}) ) ); _RUN(out); } void test_eliminate_identity_projection_1() { node n = source_sframe(5); n = make_project(make_transform(n), {0}); n = make_project(make_transform(n), {0}); _RUN(n); } void test_eliminate_identity_projection_2() { node n1 = make_union(make_transform(source_sframe(5)), make_transform(source_sframe(5))); node n2 = make_union(make_transform(source_sframe(5)), make_transform(source_sframe(5))); node n = make_union(n1, n2); n = make_project(n, {1, 0, 3, 2}); n = make_project(n, {3, 2, 1, 0}); _RUN(n); } void test_eliminate_identity_projection_3() { random::seed(0); node n1 = make_union(make_transform(source_sframe(5)), make_transform(source_sframe(5))); node n2 = make_union(make_transform(source_sframe(5)), make_transform(source_sframe(5))); node n = make_union(n1, n2); std::vector<size_t> idx = {0, 1, 2, 3}; for(size_t i = 0; i < 50; ++i) { random::shuffle(idx); n = make_project(n, idx); } _RUN(n); } void test_merge_projections() { node n1 = make_union(make_transform(source_sframe(5)), make_transform(source_sframe(5))); node n2 = make_union(make_transform(source_sframe(5)), make_transform(source_sframe(5))); node n3 = make_union(n1, n2); node n = make_project(n3, {0, 1, 2, 3}); _RUN(n); } void test_project_union_transform_recursive_1() { random::seed(0); node n = source_sframe(5); for(size_t i = 0; i < 20; ++i) { std::vector<size_t> indices = {random::fast_uniform<size_t>(0, 5 + i - 1)}; n = make_union(n, make_transform(make_project(n, indices) ) ); } _RUN(n); } void test_project_union_transform_recursive_2() { random::seed(0); node n = source_sframe(5); for(size_t i = 0; i < 20; ++i) { std::vector<size_t> indices; for(size_t j = 0; j < 2; ++j) indices.push_back(random::fast_uniform<size_t>(0, 5 + i - 1)); n = make_union(n, make_transform(make_project(n, indices) ) ); } _RUN(n); } void test_project_union_transform_recursive_3() { random::seed(0); node n = source_sframe(5); for(size_t i = 0; i < 20; ++i) { std::vector<size_t> indices; for(size_t j = 0; j < 4; ++j) indices.push_back(random::fast_uniform<size_t>(0, 5 + i - 1)); n = make_union(n, make_transform(make_project(n, indices) ) ); } _RUN(n); } void test_append_on_source() { node n = make_append(source_sframe(5), source_sframe(5)); _RUN(n); } void test_project_append_exchange_1() { node n1 = source_sframe(5); node n2 = source_sframe(5); node n = make_project(make_append(n1, n2), {1, 3, 4}); _RUN(n); } void test_project_append_exchange_2() { random::seed(0); node n = source_sframe(5); for(size_t i = 0; i < 20; ++i) { node n2 = source_sframe(5); std::vector<size_t> indices; for(size_t j = 0; j < 5; ++j) indices.push_back(random::fast_uniform<size_t>(0, 4)); if(i %3 == 0) n = make_project(make_append(n, n2), indices); else n = make_project(make_append(n2, n), indices); } _RUN(n); } void test_project_logical_filter_exchange_1() { node n1 = source_sframe(5); node n2 = binary_source_sarray(); node n = make_project(make_logical_filter(n1, n2), {1, 3}); _RUN(n); } void test_project_logical_filter_exchange_2() { node n1 = source_sframe(5); node n2 = binary_source_sarray(); node lf = make_logical_filter(n1, n2); node n = make_union(make_project(lf, {0,2,3}), make_project(lf, {1,4})); _RUN(n); } /* * TODO: These cases are currently impossible to produce * via the regular SFrame API since binary operations across of stuff of * unknown sizes will force materialization to check their size, * before allowing the plan to be created. * Thus there are no current means of generating such a plan except via * query optimization, but the query optimizations that reorder * the logical_filter have been disabled * * void disabled_test_project_logical_filter_exchange_3() { * node n1 = source_sframe(5); * node n2 = source_sframe(5); * node mask = binary_source_sarray(); * node lf_1 = make_logical_filter(n1, mask); * node lf_2 = make_logical_filter(n2, mask); * node n = make_union(lf_1, lf_2); * _RUN(n); * } * void disabled_test_project_logical_filter_exchange_4() { * node n1 = source_sframe(5); * node n2 = source_sframe(5); * node mask = binary_source_sarray(); * node lf_1 = make_logical_filter(n1, mask); * node lf_2 = make_logical_filter(n2, mask); * node n = make_project(make_union(lf_1, lf_2), {1,0}); * _RUN(n); * } */ void test_zero_logical_filter() { node n1 = source_sframe(5); node n2 = zero_source_sarray(); node n = make_project(make_logical_filter(n1, n2), {1, 3}); _RUN(n); } void test_union_filter_exchange_1() { node n1 = source_sframe(2); node n2 = source_sframe(2); node mask = binary_source_sarray(); n1 = make_transform(n1); n1 = make_transform(n1); n2 = make_transform(n2); node n = make_logical_filter(make_union(n1, n2), mask); _RUN(n); } void test_union_filter_exchange_2() { random::seed(0); node n = source_sframe(5); for(size_t i = 0; i < 20; ++i) { std::vector<size_t> indices; for(size_t j = 0; j < 2; ++j) indices.push_back(random::fast_uniform<size_t>(0, 5 + i - 1)); n = make_union(n, make_transform(make_project(n, indices) ) ); } node mask = binary_source_sarray(); n = make_logical_filter(n, mask); _RUN(n); } void test_empty_sframe() { node n = empty_sframe(5); _RUN(n); } void test_empty_append_sframe_collapse_1() { node n = empty_sframe(5); n = make_append(n, n); _RUN(n); } void test_empty_append_sframe_collapse_2() { node n = empty_sframe(5); for(size_t i = 0; i < 10; ++i) { n = make_append(n, n); } _RUN(n); } void test_empty_append_sframe_collapse_with_transform() { node n = empty_sframe(5); for(size_t i = 0; i < 5; ++i) { n = make_append(make_transform(n), make_transform(n)); } _RUN(n); } void test_empty_append_sarray_collapse() { node n = empty_sarray(); for(size_t i = 0; i < 10; ++i) { n = make_append(n, n); } _RUN(n); } void test_union_project_merge() { node n = source_sframe(5); n = make_generalized_transform(n, 5); n = make_union(make_project(n, {1, 2, 3}), make_project(n, {0, 4})); _RUN(n); } void test_union_project_merge_2() { node n = source_sframe(5); node n_src = make_generalized_transform(n, 10); n = n_src; for(size_t i = 0; i < 10; ++i) n = make_union(n, make_project(n_src, {i})); _RUN(n); } void test_union_project_merge_2b() { node n_src = make_generalized_transform(source_sframe(10), 10); node n = n_src; for(size_t i = 0; i < 10; ++i) n = make_union(make_project(n, {0, 2, 1, 4, 3, 6, 5, 8, 7, 9}), make_project(n_src, {i})); _RUN(n); } void test_union_project_merge_3() { random::seed(0); node n = source_sframe(5); std::vector<node> node_list = {make_generalized_transform(n, 10)}; for(size_t i = 0; i < 30; ++i) { size_t idx_1 = random::fast_uniform<size_t>(0, node_list.size() - 1); size_t proj_idx = random::fast_uniform<size_t>(0, 9); size_t idx_2 = random::fast_uniform<size_t>(0, node_list.size() - 1); node_list.push_back(make_union(node_list[idx_1], make_project(node_list[idx_2], {proj_idx}))); } _RUN(node_list.back()); } void test_union_project_merge_4() { node n_src = make_generalized_transform(source_sframe(5), 100); node n = make_union(make_project(n_src, {0}), make_project(n_src, {1})); for(size_t i = 2; i < 100; ++i) { n = make_union(n, make_project(n_src, {i})); } _RUN(n); } void test_union_project_merge_5() { random::seed(0); node n = source_sframe(5); std::vector<node> node_list = {make_generalized_transform(n, 10)}; for(size_t i = 0; i < 20; ++i) { size_t idx_1 = random::fast_uniform<size_t>(0, node_list.size() - 1); size_t idx_2 = random::fast_uniform<size_t>(0, node_list.size() - 1); size_t idx_3 = random::fast_uniform<size_t>(0, node_list.size() - 1); std::vector<size_t> project_indices(5); for(size_t& idx : project_indices) idx = random::fast_uniform<size_t>(0, 9); node_list.push_back(make_union(node_list[idx_1], make_project(node_list[idx_2], project_indices))); node_list.push_back(make_union(node_list[idx_1], make_generalized_transform(node_list[idx_3], 10))); } n = make_union(node_list[0], node_list[1]); for(size_t i = 2; i < node_list.size(); ++i) { size_t idx = random::fast_uniform<size_t>(0, 14); n = make_union(n, make_project(node_list[i], {idx})); } _RUN(n); } void test_union_shifted_sframes() { node n1 = source_sframe(5); node n2 = shifted_source_sframe(5); node n = make_union(n1, n2); _RUN(n); } void test_union_duplication() { node n = source_sframe(1); n = make_union(n, n); _RUN(n); } void test_union_duplication_2() { node n = source_sframe(1); n = make_union(n, n); _RUN(n); } void test_union_duplication_3() { node n = source_sframe(1); for(size_t i = 0; i < 5; ++i) { n = make_union(n, n); } _RUN(n); } void test_regression_union_project_identity_issue() { node n = make_generalized_transform(source_sframe(5), 2); n = make_union(n, make_project(n, {0,1})); _RUN(n); } void test_source_merging_as_sarrays() { random::seed(0); node base_1 = make_union(source_sframe(5), shifted_source_sframe(5)); node n = base_1; for(size_t i = 0; i < 20; ++i) { size_t idx_1 = random::fast_uniform<size_t>(0, 9); n = make_union(n, make_transform(make_project(base_1, {idx_1}))); } _RUN(n); } void test_source_merging_as_sframes() { random::seed(0); node base_1 = make_union(source_sframe(5), shifted_source_sframe(5)); node n = base_1; for(size_t i = 0; i < 20; ++i) { size_t idx_1 = random::fast_uniform<size_t>(0, 9); size_t idx_2 = random::fast_uniform<size_t>(0, 9); n = make_union(n, make_transform(make_project(base_1, {idx_1, idx_2}))); } _RUN(n); } };
24.336379
106
0.577967
[ "vector" ]
abf69b9cd895e96f368baddf3de0269b260cbf1e
9,136
cpp
C++
libs/math/benchmark/tensor/tensor.cpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/math/benchmark/tensor/tensor.cpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
null
null
null
libs/math/benchmark/tensor/tensor.cpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
2
2019-11-13T10:55:24.000Z
2019-11-13T11:37:09.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "math/tensor.hpp" #include "benchmark/benchmark.h" // size access should be very fast template <class T, int C, int H, int W> void BM_TensorSize(benchmark::State &state) { fetch::math::Tensor<T> t(std::vector<std::uint64_t>{C, H, W}); for (auto _ : state) { benchmark::DoNotOptimize(t.size()); } } BENCHMARK_TEMPLATE(BM_TensorSize, int, 3, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, float, 3, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, double, 3, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, int, 128, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, float, 128, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, double, 128, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, int, 256, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, float, 256, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorSize, double, 256, 256, 256)->Unit(benchmark::kNanosecond); // shape access should also be very fast template <class T, int C, int H, int W> void BM_TensorShape(benchmark::State &state) { fetch::math::Tensor<T> t(std::vector<std::uint64_t>{C, H, W}); for (auto _ : state) { benchmark::DoNotOptimize(t.shape()); } } BENCHMARK_TEMPLATE(BM_TensorShape, int, 3, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, float, 3, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, double, 3, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, int, 128, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, float, 128, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, double, 128, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, int, 256, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, float, 256, 256, 256)->Unit(benchmark::kNanosecond); BENCHMARK_TEMPLATE(BM_TensorShape, double, 256, 256, 256)->Unit(benchmark::kNanosecond); template <class T, int C, int H, int W> void BM_TensorNaiveIteration(benchmark::State &state) { for (auto _ : state) { state.PauseTiming(); // Construct reference tensor fetch::math::Tensor<T> t(std::vector<std::uint64_t>{C, H, W}); state.ResumeTiming(); for (auto const &e : t) { benchmark::DoNotOptimize(e); } } } BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, int, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, float, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, double, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, int, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, float, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, double, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, int, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, float, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorNaiveIteration, double, 256, 256, 256)->Unit(benchmark::kMillisecond); // Reference implementation of a vector to compare iteration time template <class T, int C, int H, int W> void VectorBaselineRangeIterator(benchmark::State &state) { for (auto _ : state) { state.PauseTiming(); // Construct reference tensor fetch::math::Tensor<T> t(std::vector<std::uint64_t>{C, H, W}); // Baseline - iterate over vector of same number of elements std::vector<T> baseline; baseline.resize(t.size()); state.ResumeTiming(); for (auto const &e : baseline) { benchmark::DoNotOptimize(e); } } } BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, int, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, float, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, double, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, int, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, float, 128, 256, 256) ->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, double, 128, 256, 256) ->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, int, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, float, 256, 256, 256) ->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(VectorBaselineRangeIterator, double, 256, 256, 256) ->Unit(benchmark::kMillisecond); template <class T, int C, int H, int W> void BM_TensorRangeIterator(benchmark::State &state) { for (auto _ : state) { state.PauseTiming(); fetch::math::Tensor<T> t(std::vector<std::uint64_t>{C, H, W}); state.ResumeTiming(); for (auto const &e : t) { benchmark::DoNotOptimize(e); } } } BENCHMARK_TEMPLATE(BM_TensorRangeIterator, int, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, float, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, double, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, int, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, float, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, double, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, int, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, float, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorRangeIterator, double, 256, 256, 256)->Unit(benchmark::kMillisecond); template <class T, int C, int H, int W> void BM_TensorConcat(benchmark::State &state) { fetch::math::Tensor<T> t1(std::vector<std::uint64_t>{C, H, W}); fetch::math::Tensor<T> t2(std::vector<std::uint64_t>{C, H, W}); std::vector<fetch::math::Tensor<T>> vt{t1, t2}; for (auto _ : state) { benchmark::DoNotOptimize(fetch::math::Tensor<T>::Concat(vt, 0)); } } BENCHMARK_TEMPLATE(BM_TensorConcat, int, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, float, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, double, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, int, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, float, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, double, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, int, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, float, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorConcat, double, 256, 256, 256)->Unit(benchmark::kMillisecond); template <class T, int C, int H, int W> void BM_TensorSum(benchmark::State &state) { for (auto _ : state) { state.PauseTiming(); fetch::math::Tensor<T> t(std::vector<std::uint64_t>{C, H, W}); state.ResumeTiming(); benchmark::DoNotOptimize(t.Sum()); } } BENCHMARK_TEMPLATE(BM_TensorSum, int, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, float, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, double, 3, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, int, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, float, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, double, 128, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, int, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, float, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_TEMPLATE(BM_TensorSum, double, 256, 256, 256)->Unit(benchmark::kMillisecond); BENCHMARK_MAIN();
41.908257
100
0.731721
[ "shape", "vector" ]
abf75d87b8d9b73b0dc8bb6d99ec400fd1f372fd
5,195
hpp
C++
src/mlpack/methods/ann/layer/alpha_dropout.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4,216
2015-01-01T02:06:12.000Z
2022-03-31T19:12:06.000Z
src/mlpack/methods/ann/layer/alpha_dropout.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2,621
2015-01-01T01:41:47.000Z
2022-03-31T19:01:26.000Z
src/mlpack/methods/ann/layer/alpha_dropout.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1,972
2015-01-01T23:37:13.000Z
2022-03-28T06:03:41.000Z
/** * @file methods/ann/layer/alpha_dropout.hpp * @author Dakshit Agrawal * * Definition of the Alpha-Dropout class, which implements a regularizer that * randomly sets units to alpha-dash to prevent them from co-adapting and * makes an affine transformation so as to keep the mean and variance of * outputs at their original values. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_HPP #define MLPACK_METHODS_ANN_LAYER_ALPHA_DROPOUT_HPP #include <mlpack/prereqs.hpp> namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * The alpha - dropout layer is a regularizer that randomly with probability * 'ratio' sets input values to alphaDash. The alpha - dropout layer is mostly * used for SELU activation function where successive layers don't have same * mean and variance. * * For more information, see the following. * * @code * @article{Klambauer2017, * author = {Gunter Klambauer and Thomas Unterthiner and * Andreas Mayr}, * title = {Self-Normalizing Neural Networks}, * journal = {Advances in Neural Information Processing Systems}, * year = {2017}, * url = {https://arxiv.org/abs/1706.02515} * } * @endcode * * @tparam InputDataType Type of the input data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat, * arma::sp_mat or arma::cube). */ template <typename InputDataType = arma::mat, typename OutputDataType = arma::mat> class AlphaDropout { public: /** * Create the Alpha_Dropout object using the specified ratio. * * @param ratio The probability of setting a value to alphaDash. * @param alphaDash The dropout scaling parameter. */ AlphaDropout(const double ratio = 0.5, const double alphaDash = -alpha * lambda); /** * Ordinary feed forward pass of the alpha_dropout layer. * * @param input Input data used for evaluating the specified function. * @param output Resulting output activation. */ template<typename eT> void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output); /** * Ordinary feed backward pass of the alpha_dropout layer. * * @param * (input) The propagated input activation. * @param gy The backpropagated error. * @param g The calculated gradient. */ template<typename eT> void Backward(const arma::Mat<eT>& /* input */, const arma::Mat<eT>& gy, arma::Mat<eT>& g); //! Get the output parameter. OutputDataType const& OutputParameter() const { return outputParameter; } //! Modify the output parameter. OutputDataType& OutputParameter() { return outputParameter; } //! Get the detla. OutputDataType const& Delta() const { return delta; } //! Modify the delta. OutputDataType& Delta() { return delta; } //! The value of the deterministic parameter. bool Deterministic() const { return deterministic; } //! Modify the value of the deterministic parameter. bool& Deterministic() { return deterministic; } //! The probability of setting a value to alphaDash. double Ratio() const { return ratio; } //! Value to be multiplied with x for affine transformation. double A() const { return a; } //! Value to be added to a*x for affine transformation. double B() const { return b; } //! Value of alphaDash. double AlphaDash() const {return alphaDash; } //! Get the mask. OutputDataType const& Mask() const {return mask;} //! Modify the probability of setting a value to alphaDash. As //! 'a' and 'b' depend on 'ratio', modify them as well. void Ratio(const double r) { ratio = r; a = pow((1 - ratio) * (1 + ratio * pow(alphaDash, 2)), -0.5); b = -a * alphaDash * ratio; } /** * Serialize the layer. */ template<typename Archive> void serialize(Archive& ar, const uint32_t /* version */); private: //! Locally-stored delta object. OutputDataType delta; //! Locally-stored output parameter object. OutputDataType outputParameter; //! Locally-stored mast object. OutputDataType mask; //! The probability of setting a value to aplhaDash. double ratio; //! The low variance value of SELU activation function. double alphaDash; //! If true dropout and scaling is disabled, see notes above. bool deterministic; //! Value of alpha for normalized inputs (taken from SELU). static constexpr double alpha = 1.6732632423543772848170429916717; //! Value of lambda for normalized inputs (taken from SELU). static constexpr double lambda = 1.0507009873554804934193349852946; //! Value to be multiplied with x for affine transformation. double a; //! Value to be added to a*x for affine transformation. double b; }; // class AlphaDropout } // namespace ann } // namespace mlpack // Include implementation. #include "alpha_dropout_impl.hpp" #endif
31.107784
78
0.693551
[ "object" ]
abfa50cd5560455c7021cc1510d032e67c66bb1f
83,326
cc
C++
DQMOffline/EGamma/plugins/PhotonAnalyzer.cc
eric-moreno/cmssw
3dc2c26f276632ac8357ac7b52675f04649e3903
[ "Apache-2.0" ]
null
null
null
DQMOffline/EGamma/plugins/PhotonAnalyzer.cc
eric-moreno/cmssw
3dc2c26f276632ac8357ac7b52675f04649e3903
[ "Apache-2.0" ]
1
2019-04-12T08:01:26.000Z
2019-04-12T08:01:26.000Z
DQMOffline/EGamma/plugins/PhotonAnalyzer.cc
eric-moreno/cmssw
3dc2c26f276632ac8357ac7b52675f04649e3903
[ "Apache-2.0" ]
2
2019-09-27T08:33:22.000Z
2019-11-14T10:52:30.000Z
#include <iostream> #include <iomanip> // #include "DQMOffline/EGamma/plugins/PhotonAnalyzer.h" /** \class PhotonAnalyzer ** ** ** $Id: PhotonAnalyzer ** authors: ** Nancy Marinelli, U. of Notre Dame, US ** Jamie Antonelli, U. of Notre Dame, US ** ***/ using namespace std; PhotonAnalyzer::PhotonAnalyzer(const edm::ParameterSet& pset) { fName_ = pset.getParameter<string>("analyzerName"); prescaleFactor_ = pset.getUntrackedParameter<int>("prescaleFactor", 1); photon_token_ = consumes<vector<reco::Photon> >(pset.getParameter<edm::InputTag>("phoProducer")); barrelRecHit_token_ = consumes<edm::SortedCollection<EcalRecHit, edm::StrictWeakOrdering<EcalRecHit> > >( pset.getParameter<edm::InputTag>("barrelRecHitProducer")); PhotonIDLoose_token_ = consumes<edm::ValueMap<bool> >(pset.getParameter<edm::InputTag>("photonIDLoose")); PhotonIDTight_token_ = consumes<edm::ValueMap<bool> >(pset.getParameter<edm::InputTag>("photonIDTight")); endcapRecHit_token_ = consumes<edm::SortedCollection<EcalRecHit, edm::StrictWeakOrdering<EcalRecHit> > >( pset.getParameter<edm::InputTag>("endcapRecHitProducer")); triggerEvent_token_ = consumes<trigger::TriggerEvent>(pset.getParameter<edm::InputTag>("triggerEvent")); offline_pvToken_ = consumes<reco::VertexCollection>( pset.getUntrackedParameter<edm::InputTag>("offlinePV", edm::InputTag("offlinePrimaryVertices"))); minPhoEtCut_ = pset.getParameter<double>("minPhoEtCut"); photonMaxEta_ = pset.getParameter<double>("maxPhoEta"); invMassEtCut_ = pset.getParameter<double>("invMassEtCut"); cutStep_ = pset.getParameter<double>("cutStep"); numberOfSteps_ = pset.getParameter<int>("numberOfSteps"); useBinning_ = pset.getParameter<bool>("useBinning"); useTriggerFiltering_ = pset.getParameter<bool>("useTriggerFiltering"); minimalSetOfHistos_ = pset.getParameter<bool>("minimalSetOfHistos"); excludeBkgHistos_ = pset.getParameter<bool>("excludeBkgHistos"); standAlone_ = pset.getParameter<bool>("standAlone"); isolationStrength_ = pset.getParameter<int>("isolationStrength"); isHeavyIon_ = pset.getUntrackedParameter<bool>("isHeavyIon", false); histo_index_photons_ = 0; histo_index_conversions_ = 0; histo_index_efficiency_ = 0; histo_index_invMass_ = 0; nEvt_ = 0; // Determining parts... parts_.push_back("AllEcal"); parts_.push_back("Barrel"); parts_.push_back("Endcaps"); // ...and types types_.push_back("All"); types_.push_back("GoodCandidate"); if (!excludeBkgHistos_) { types_.push_back("Background"); } // Histogram parameters etaBin_ = pset.getParameter<int>("etaBin"); etaMin_ = pset.getParameter<double>("etaMin"); etaMax_ = pset.getParameter<double>("etaMax"); etBin_ = pset.getParameter<int>("etBin"); etMin_ = pset.getParameter<double>("etMin"); etMax_ = pset.getParameter<double>("etMax"); phiBin_ = pset.getParameter<int>("phiBin"); phiMin_ = pset.getParameter<double>("phiMin"); phiMax_ = pset.getParameter<double>("phiMax"); eBin_ = pset.getParameter<int>("eBin"); eMin_ = pset.getParameter<double>("eMin"); eMax_ = pset.getParameter<double>("eMax"); numberBin_ = pset.getParameter<int>("numberBin"); numberMin_ = pset.getParameter<double>("numberMin"); numberMax_ = pset.getParameter<double>("numberMax"); r9Bin_ = pset.getParameter<int>("r9Bin"); r9Min_ = pset.getParameter<double>("r9Min"); r9Max_ = pset.getParameter<double>("r9Max"); sigmaIetaBin_ = pset.getParameter<int>("sigmaIetaBin"); sigmaIetaMin_ = pset.getParameter<double>("sigmaIetaMin"); sigmaIetaMax_ = pset.getParameter<double>("sigmaIetaMax"); sumBin_ = pset.getParameter<int>("sumBin"); sumMin_ = pset.getParameter<double>("sumMin"); sumMax_ = pset.getParameter<double>("sumMax"); hOverEBin_ = pset.getParameter<int>("hOverEBin"); hOverEMin_ = pset.getParameter<double>("hOverEMin"); hOverEMax_ = pset.getParameter<double>("hOverEMax"); eOverPBin_ = pset.getParameter<int>("eOverPBin"); eOverPMin_ = pset.getParameter<double>("eOverPMin"); eOverPMax_ = pset.getParameter<double>("eOverPMax"); dPhiTracksBin_ = pset.getParameter<int>("dPhiTracksBin"); dPhiTracksMin_ = pset.getParameter<double>("dPhiTracksMin"); dPhiTracksMax_ = pset.getParameter<double>("dPhiTracksMax"); dEtaTracksBin_ = pset.getParameter<int>("dEtaTracksBin"); dEtaTracksMin_ = pset.getParameter<double>("dEtaTracksMin"); dEtaTracksMax_ = pset.getParameter<double>("dEtaTracksMax"); chi2Bin_ = pset.getParameter<int>("chi2Bin"); chi2Min_ = pset.getParameter<double>("chi2Min"); chi2Max_ = pset.getParameter<double>("chi2Max"); zBin_ = pset.getParameter<int>("zBin"); zMin_ = pset.getParameter<double>("zMin"); zMax_ = pset.getParameter<double>("zMax"); rBin_ = pset.getParameter<int>("rBin"); rMin_ = pset.getParameter<double>("rMin"); rMax_ = pset.getParameter<double>("rMax"); xBin_ = pset.getParameter<int>("xBin"); xMin_ = pset.getParameter<double>("xMin"); xMax_ = pset.getParameter<double>("xMax"); yBin_ = pset.getParameter<int>("yBin"); yMin_ = pset.getParameter<double>("yMin"); yMax_ = pset.getParameter<double>("yMax"); reducedEtBin_ = etBin_ / 4; reducedEtaBin_ = etaBin_ / 4; reducedR9Bin_ = r9Bin_ / 4; reducedSumBin_ = sumBin_ / 4; } PhotonAnalyzer::~PhotonAnalyzer() {} void PhotonAnalyzer::bookHistograms(DQMStore::IBooker& iBooker, edm::Run const& /* iRun */, edm::EventSetup const& /* iSetup */) { bookHistogramsForHistogramCounts(iBooker); bookHistogramsEfficiency(iBooker); bookHistogramsInvMass(iBooker); bookHistogramsPhotons(iBooker); bookHistogramsConversions(iBooker); fillHistogramsForHistogramCounts(iBooker); } void PhotonAnalyzer::bookHistogramsForHistogramCounts(DQMStore::IBooker& iBooker) { iBooker.setCurrentFolder("Egamma/" + fName_ + "/"); // Int values stored in MEs to keep track of how many histograms are in each folder totalNumberOfHistos_efficiencyFolder = iBooker.bookInt("numberOfHistogramsInEfficiencyFolder"); totalNumberOfHistos_invMassFolder = iBooker.bookInt("numberOfHistogramsInInvMassFolder"); totalNumberOfHistos_photonsFolder = iBooker.bookInt("numberOfHistogramsInPhotonsFolder"); totalNumberOfHistos_conversionsFolder = iBooker.bookInt("numberOfHistogramsInConversionsFolder"); } void PhotonAnalyzer::fillHistogramsForHistogramCounts(DQMStore::IBooker& iBooker) { iBooker.setCurrentFolder("Egamma/" + fName_ + "/"); totalNumberOfHistos_efficiencyFolder->Fill(histo_index_efficiency_); totalNumberOfHistos_invMassFolder->Fill(histo_index_invMass_); totalNumberOfHistos_photonsFolder->Fill(histo_index_photons_); totalNumberOfHistos_conversionsFolder->Fill(histo_index_conversions_); } void PhotonAnalyzer::bookHistogramsEfficiency(DQMStore::IBooker& iBooker) { // Set folder iBooker.setCurrentFolder("Egamma/" + fName_ + "/Efficiencies"); // Don't number these histograms with the "bookHisto" method, since they'll be erased in the offline client h_phoEta_Loose_ = iBooker.book1D("phoEtaLoose", "Loose Photon #eta", etaBin_, etaMin_, etaMax_); h_phoEta_Tight_ = iBooker.book1D("phoEtaTight", "Tight Photon #eta", etaBin_, etaMin_, etaMax_); h_phoEt_Loose_ = iBooker.book1D("phoEtLoose", "Loose Photon E_{T}", etBin_, etMin_, etMax_); h_phoEt_Tight_ = iBooker.book1D("phoEtTight", "Tight Photon E_{T}", etBin_, etMin_, etMax_); h_phoEta_preHLT_ = iBooker.book1D("phoEtaPreHLT", "Photon #eta: before HLT", etaBin_, etaMin_, etaMax_); h_phoEta_postHLT_ = iBooker.book1D("phoEtaPostHLT", "Photon #eta: after HLT", etaBin_, etaMin_, etaMax_); h_phoEt_preHLT_ = iBooker.book1D("phoEtPreHLT", "Photon E_{T}: before HLT", etBin_, etMin_, etMax_); h_phoEt_postHLT_ = iBooker.book1D("phoEtPostHLT", "Photon E_{T}: after HLT", etBin_, etMin_, etMax_); h_convEta_Loose_ = iBooker.book1D("convEtaLoose", "Converted Loose Photon #eta", etaBin_, etaMin_, etaMax_); h_convEta_Tight_ = iBooker.book1D("convEtaTight", "Converted Tight Photon #eta", etaBin_, etaMin_, etaMax_); h_convEt_Loose_ = iBooker.book1D("convEtLoose", "Converted Loose Photon E_{T}", etBin_, etMin_, etMax_); h_convEt_Tight_ = iBooker.book1D("convEtTight", "Converted Tight Photon E_{T}", etBin_, etMin_, etMax_); h_phoEta_Vertex_ = iBooker.book1D("phoEtaVertex", "Converted Photons before valid vertex cut: #eta", etaBin_, etaMin_, etaMax_); // Some temporary vectors vector<MonitorElement*> temp1DVectorEta; vector<MonitorElement*> temp1DVectorPhi; vector<vector<MonitorElement*> > temp2DVectorPhi; for (int cut = 0; cut != numberOfSteps_; ++cut) { //looping over Et cut values for (uint type = 0; type != types_.size(); ++type) { //looping over isolation type currentFolder_.str(""); currentFolder_ << "Egamma/" + fName_ + "/" << types_[type] << "Photons/Et above " << (cut + 1) * cutStep_ << " GeV/Conversions"; iBooker.setCurrentFolder(currentFolder_.str()); temp1DVectorEta.push_back( iBooker.book1D("phoConvEtaForEfficiency", "Converted Photon #eta;#eta", etaBin_, etaMin_, etaMax_)); for (uint part = 0; part != parts_.size(); ++part) { temp1DVectorPhi.push_back(iBooker.book1D( "phoConvPhiForEfficiency" + parts_[part], "Converted Photon #phi;#phi", phiBin_, phiMin_, phiMax_)); } temp2DVectorPhi.push_back(temp1DVectorPhi); temp1DVectorPhi.clear(); } h_phoConvEtaForEfficiency_.push_back(temp1DVectorEta); temp1DVectorEta.clear(); h_phoConvPhiForEfficiency_.push_back(temp2DVectorPhi); temp2DVectorPhi.clear(); } } void PhotonAnalyzer::bookHistogramsInvMass(DQMStore::IBooker& iBooker) { // Set folder iBooker.setCurrentFolder("Egamma/" + fName_ + "/InvMass"); h_invMassAllPhotons_ = bookHisto(iBooker, "invMassAllIsolatedPhotons", "Two photon invariant mass: All isolated photons;M (GeV)", etBin_, etMin_, etMax_); h_invMassPhotonsEBarrel_ = bookHisto(iBooker, "invMassIsoPhotonsEBarrel", "Two photon invariant mass: isolated photons in barrel; M (GeV)", etBin_, etMin_, etMax_); h_invMassPhotonsEEndcap_ = bookHisto(iBooker, "invMassIsoPhotonsEEndcap", "Two photon invariant mass: isolated photons in endcap; M (GeV)", etBin_, etMin_, etMax_); h_invMassPhotonsEEndcapEBarrel_ = bookHisto(iBooker, "invMassIsoPhotonsEEndcapEBarrel", "Two photon invariant mass: isolated photons in endcap-barrel; M (GeV)", etBin_, etMin_, etMax_); h_invMassZeroWithTracks_ = bookHisto( iBooker, "invMassZeroWithTracks", "Two photon invariant mass: Neither has tracks;M (GeV)", etBin_, etMin_, etMax_); h_invMassOneWithTracks_ = bookHisto( iBooker, "invMassOneWithTracks", "Two photon invariant mass: Only one has tracks;M (GeV)", etBin_, etMin_, etMax_); h_invMassTwoWithTracks_ = bookHisto( iBooker, "invMassTwoWithTracks", "Two photon invariant mass: Both have tracks;M (GeV)", etBin_, etMin_, etMax_); h_nRecoVtx_ = bookHisto(iBooker, "nOfflineVtx", "# of Offline Vertices", 200, -0.5, 199.5); } void PhotonAnalyzer::bookHistogramsPhotons(DQMStore::IBooker& iBooker) { // Set folder // Folder is set by the book2DHistoVector and book3DHistoVector methods //ENERGY VARIABLES book3DHistoVector(iBooker, h_phoE_, "1D", "phoE", "Energy;E (GeV)", eBin_, eMin_, eMax_); book3DHistoVector(iBooker, h_phoSigmaEoverE_, "1D", "phoSigmaEoverE", "#sigma_{E}/E; #sigma_{E}/E", 100, 0., 0.08); book3DHistoVector(iBooker, p_phoSigmaEoverEvsNVtx_, "Profile", "phoSigmaEoverEvsNVtx", "#sigma_{E}/E vs NVtx; N_{vtx}; #sigma_{E}/E", 200, -0.5, 199.5, 100, 0., 0.08); book3DHistoVector(iBooker, h_phoEt_, "1D", "phoEt", "E_{T};E_{T} (GeV)", etBin_, etMin_, etMax_); //NUMBER OF PHOTONS book3DHistoVector( iBooker, h_nPho_, "1D", "nPho", "Number of Photons per Event;# #gamma", numberBin_, numberMin_, numberMax_); //GEOMETRICAL VARIABLES //photon eta/phi book2DHistoVector(iBooker, h_phoEta_, "1D", "phoEta", "#eta;#eta", etaBin_, etaMin_, etaMax_); book3DHistoVector(iBooker, h_phoPhi_, "1D", "phoPhi", "#phi;#phi", phiBin_, phiMin_, phiMax_); //supercluster eta/phi book2DHistoVector(iBooker, h_scEta_, "1D", "scEta", "SuperCluster #eta;#eta", etaBin_, etaMin_, etaMax_); book3DHistoVector(iBooker, h_scPhi_, "1D", "scPhi", "SuperCluster #phi;#phi", phiBin_, phiMin_, phiMax_); //SHOWER SHAPE VARIABLES //r9 book3DHistoVector(iBooker, h_r9_, "1D", "r9", "R9;R9", r9Bin_, r9Min_, r9Max_); if (standAlone_) { book2DHistoVector(iBooker, h_r9VsEt_, "2D", "r9VsEt2D", "R9 vs E_{T};E_{T} (GeV);R9", reducedEtBin_, etMin_, etMax_, reducedR9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_r9VsEt_, "Profile", "r9VsEt", "Avg R9 vs E_{T};E_{T} (GeV);R9", etBin_, etMin_, etMax_, r9Bin_, r9Min_, r9Max_); if (standAlone_) { book2DHistoVector(iBooker, h_r9VsEta_, "2D", "r9VsEta2D", "R9 vs #eta;#eta;R9", reducedEtaBin_, etaMin_, etaMax_, reducedR9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_r9VsEta_, "Profile", "r9VsEta", "Avg R9 vs #eta;#eta;R9", etaBin_, etaMin_, etaMax_, r9Bin_, r9Min_, r9Max_); //sigma ieta ieta book3DHistoVector(iBooker, h_phoSigmaIetaIeta_, "1D", "phoSigmaIetaIeta", "#sigma_{i#etai#eta};#sigma_{i#etai#eta}", sigmaIetaBin_, sigmaIetaMin_, sigmaIetaMax_); if (standAlone_) { book2DHistoVector(iBooker, h_sigmaIetaIetaVsEta_, "2D", "sigmaIetaIetaVsEta2D", "#sigma_{i#etai#eta} vs #eta;#eta;#sigma_{i#etai#eta}", reducedEtaBin_, etaMin_, etaMax_, sigmaIetaBin_, sigmaIetaMin_, sigmaIetaMax_); } book2DHistoVector(iBooker, p_sigmaIetaIetaVsEta_, "Profile", "sigmaIetaIetaVsEta", "Avg #sigma_{i#etai#eta} vs #eta;#eta;#sigma_{i#etai#eta}", etaBin_, etaMin_, etaMax_, sigmaIetaBin_, sigmaIetaMin_, sigmaIetaMax_); //e1x5 if (standAlone_) { book2DHistoVector(iBooker, h_e1x5VsEt_, "2D", "e1x5VsEt2D", "E1x5 vs E_{T};E_{T} (GeV);E1X5 (GeV)", reducedEtBin_, etMin_, etMax_, reducedEtBin_, etMin_, etMax_); } book2DHistoVector(iBooker, p_e1x5VsEt_, "Profile", "e1x5VsEt", "Avg E1x5 vs E_{T};E_{T} (GeV);E1X5 (GeV)", etBin_, etMin_, etMax_, etBin_, etMin_, etMax_); if (standAlone_) { book2DHistoVector(iBooker, h_e1x5VsEta_, "2D", "e1x5VsEta2D", "E1x5 vs #eta;#eta;E1X5 (GeV)", reducedEtaBin_, etaMin_, etaMax_, reducedEtBin_, etMin_, etMax_); } book2DHistoVector(iBooker, p_e1x5VsEta_, "Profile", "e1x5VsEta", "Avg E1x5 vs #eta;#eta;E1X5 (GeV)", etaBin_, etaMin_, etaMax_, etBin_, etMin_, etMax_); //e2x5 if (standAlone_) { book2DHistoVector(iBooker, h_e2x5VsEt_, "2D", "e2x5VsEt2D", "E2x5 vs E_{T};E_{T} (GeV);E2X5 (GeV)", reducedEtBin_, etMin_, etMax_, reducedEtBin_, etMin_, etMax_); } book2DHistoVector(iBooker, p_e2x5VsEt_, "Profile", "e2x5VsEt", "Avg E2x5 vs E_{T};E_{T} (GeV);E2X5 (GeV)", etBin_, etMin_, etMax_, etBin_, etMin_, etMax_); if (standAlone_) { book2DHistoVector(iBooker, h_e2x5VsEta_, "2D", "e2x5VsEta2D", "E2x5 vs #eta;#eta;E2X5 (GeV)", reducedEtaBin_, etaMin_, etaMax_, reducedEtBin_, etMin_, etMax_); } book2DHistoVector(iBooker, p_e2x5VsEta_, "Profile", "e2x5VsEta", "Avg E2x5 vs #eta;#eta;E2X5 (GeV)", etaBin_, etaMin_, etaMax_, etBin_, etMin_, etMax_); //r1x5 if (standAlone_) { book2DHistoVector(iBooker, h_r1x5VsEt_, "2D", "r1x5VsEt2D", "R1x5 vs E_{T};E_{T} (GeV);R1X5", reducedEtBin_, etMin_, etMax_, reducedR9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_r1x5VsEt_, "Profile", "r1x5VsEt", "Avg R1x5 vs E_{T};E_{T} (GeV);R1X5", etBin_, etMin_, etMax_, r9Bin_, r9Min_, r9Max_); if (standAlone_) { book2DHistoVector(iBooker, h_r1x5VsEta_, "2D", "r1x5VsEta2D", "R1x5 vs #eta;#eta;R1X5", reducedEtaBin_, etaMin_, etaMax_, reducedR9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_r1x5VsEta_, "Profile", "r1x5VsEta", "Avg R1x5 vs #eta;#eta;R1X5", etaBin_, etaMin_, etaMax_, r9Bin_, r9Min_, r9Max_); //r2x5 if (standAlone_) { book2DHistoVector(iBooker, h_r2x5VsEt_, "2D", "r2x5VsEt2D", "R2x5 vs E_{T};E_{T} (GeV);R2X5", reducedEtBin_, etMin_, etMax_, reducedR9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_r2x5VsEt_, "Profile", "r2x5VsEt", "Avg R2x5 vs E_{T};E_{T} (GeV);R2X5", etBin_, etMin_, etMax_, r9Bin_, r9Min_, r9Max_); if (standAlone_) { book2DHistoVector(iBooker, h_r2x5VsEta_, "2D", "r2x5VsEta2D", "R2x5 vs #eta;#eta;R2X5", reducedEtaBin_, etaMin_, etaMax_, reducedR9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_r2x5VsEta_, "Profile", "r2x5VsEta", "Avg R2x5 vs #eta;#eta;R2X5", etaBin_, etaMin_, etaMax_, r9Bin_, r9Min_, r9Max_); //maxEXtalOver3x3 if (standAlone_) { book2DHistoVector(iBooker, h_maxEXtalOver3x3VsEt_, "2D", "maxEXtalOver3x3VsEt2D", "(Max Xtal E)/E3x3 vs E_{T};E_{T} (GeV);(Max Xtal E)/E3x3", reducedEtBin_, etMin_, etMax_, r9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_maxEXtalOver3x3VsEt_, "Profile", "maxEXtalOver3x3VsEt", "Avg (Max Xtal E)/E3x3 vs E_{T};E_{T} (GeV);(Max Xtal E)/E3x3", etBin_, etMin_, etMax_, r9Bin_, r9Min_, r9Max_); if (standAlone_) { book2DHistoVector(iBooker, h_maxEXtalOver3x3VsEta_, "2D", "maxEXtalOver3x3VsEta2D", "(Max Xtal E)/E3x3 vs #eta;#eta;(Max Xtal E)/E3x3", reducedEtaBin_, etaMin_, etaMax_, r9Bin_, r9Min_, r9Max_); } book2DHistoVector(iBooker, p_maxEXtalOver3x3VsEta_, "Profile", "maxEXtalOver3x3VsEta", "Avg (Max Xtal E)/E3x3 vs #eta;#eta;(Max Xtal E)/E3x3", etaBin_, etaMin_, etaMax_, r9Bin_, r9Min_, r9Max_); //TRACK ISOLATION VARIABLES //nTrackIsolSolid book2DHistoVector(iBooker, h_nTrackIsolSolid_, "1D", "nIsoTracksSolid", "Number Of Tracks in the Solid Iso Cone;# tracks", numberBin_, numberMin_, numberMax_); if (standAlone_) { book2DHistoVector(iBooker, h_nTrackIsolSolidVsEt_, "2D", "nIsoTracksSolidVsEt2D", "Number Of Tracks in the Solid Iso Cone vs E_{T};E_{T};# tracks", reducedEtBin_, etMin_, etMax_, numberBin_, numberMin_, numberMax_); } book2DHistoVector(iBooker, p_nTrackIsolSolidVsEt_, "Profile", "nIsoTracksSolidVsEt", "Avg Number Of Tracks in the Solid Iso Cone vs E_{T};E_{T};# tracks", etBin_, etMin_, etMax_, numberBin_, numberMin_, numberMax_); if (standAlone_) { book2DHistoVector(iBooker, h_nTrackIsolSolidVsEta_, "2D", "nIsoTracksSolidVsEta2D", "Number Of Tracks in the Solid Iso Cone vs #eta;#eta;# tracks", reducedEtaBin_, etaMin_, etaMax_, numberBin_, numberMin_, numberMax_); } book2DHistoVector(iBooker, p_nTrackIsolSolidVsEta_, "Profile", "nIsoTracksSolidVsEta", "Avg Number Of Tracks in the Solid Iso Cone vs #eta;#eta;# tracks", etaBin_, etaMin_, etaMax_, numberBin_, numberMin_, numberMax_); //nTrackIsolHollow book2DHistoVector(iBooker, h_nTrackIsolHollow_, "1D", "nIsoTracksHollow", "Number Of Tracks in the Hollow Iso Cone;# tracks", numberBin_, numberMin_, numberMax_); if (standAlone_) { book2DHistoVector(iBooker, h_nTrackIsolHollowVsEt_, "2D", "nIsoTracksHollowVsEt2D", "Number Of Tracks in the Hollow Iso Cone vs E_{T};E_{T};# tracks", reducedEtBin_, etMin_, etMax_, numberBin_, numberMin_, numberMax_); } book2DHistoVector(iBooker, p_nTrackIsolHollowVsEt_, "Profile", "nIsoTracksHollowVsEt", "Avg Number Of Tracks in the Hollow Iso Cone vs E_{T};E_{T};# tracks", etBin_, etMin_, etMax_, numberBin_, numberMin_, numberMax_); if (standAlone_) { book2DHistoVector(iBooker, h_nTrackIsolHollowVsEta_, "2D", "nIsoTracksHollowVsEta2D", "Number Of Tracks in the Hollow Iso Cone vs #eta;#eta;# tracks", reducedEtaBin_, etaMin_, etaMax_, numberBin_, numberMin_, numberMax_); } book2DHistoVector(iBooker, p_nTrackIsolHollowVsEta_, "Profile", "nIsoTracksHollowVsEta", "Avg Number Of Tracks in the Hollow Iso Cone vs #eta;#eta;# tracks", etaBin_, etaMin_, etaMax_, numberBin_, numberMin_, numberMax_); //trackPtSumSolid book2DHistoVector(iBooker, h_trackPtSumSolid_, "1D", "isoPtSumSolid", "Track P_{T} Sum in the Solid Iso Cone;P_{T} (GeV)", sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_trackPtSumSolidVsEt_, "2D", "isoPtSumSolidVsEt2D", "Track P_{T} Sum in the Solid Iso Cone;E_{T} (GeV);P_{T} (GeV)", reducedEtBin_, etMin_, etMax_, reducedSumBin_, sumMin_, sumMax_); } book2DHistoVector(iBooker, p_trackPtSumSolidVsEt_, "Profile", "isoPtSumSolidVsEt", "Avg Track P_{T} Sum in the Solid Iso Cone vs E_{T};E_{T} (GeV);P_{T} (GeV)", etBin_, etMin_, etMax_, sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_trackPtSumSolidVsEta_, "2D", "isoPtSumSolidVsEta2D", "Track P_{T} Sum in the Solid Iso Cone;#eta;P_{T} (GeV)", reducedEtaBin_, etaMin_, etaMax_, reducedSumBin_, sumMin_, sumMax_); } book2DHistoVector(iBooker, p_trackPtSumSolidVsEta_, "Profile", "isoPtSumSolidVsEta", "Avg Track P_{T} Sum in the Solid Iso Cone vs #eta;#eta;P_{T} (GeV)", etaBin_, etaMin_, etaMax_, sumBin_, sumMin_, sumMax_); //trackPtSumHollow book2DHistoVector(iBooker, h_trackPtSumHollow_, "1D", "isoPtSumHollow", "Track P_{T} Sum in the Hollow Iso Cone;P_{T} (GeV)", sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_trackPtSumHollowVsEt_, "2D", "isoPtSumHollowVsEt2D", "Track P_{T} Sum in the Hollow Iso Cone;E_{T} (GeV);P_{T} (GeV)", reducedEtBin_, etMin_, etMax_, reducedSumBin_, sumMin_, sumMax_); } book2DHistoVector(iBooker, p_trackPtSumHollowVsEt_, "Profile", "isoPtSumHollowVsEt", "Avg Track P_{T} Sum in the Hollow Iso Cone vs E_{T};E_{T} (GeV);P_{T} (GeV)", etBin_, etMin_, etMax_, sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_trackPtSumHollowVsEta_, "2D", "isoPtSumHollowVsEta2D", "Track P_{T} Sum in the Hollow Iso Cone;#eta;P_{T} (GeV)", reducedEtaBin_, etaMin_, etaMax_, reducedSumBin_, sumMin_, sumMax_); } book2DHistoVector(iBooker, p_trackPtSumHollowVsEta_, "Profile", "isoPtSumHollowVsEta", "Avg Track P_{T} Sum in the Hollow Iso Cone vs #eta;#eta;P_{T} (GeV)", etaBin_, etaMin_, etaMax_, sumBin_, sumMin_, sumMax_); //CALORIMETER ISOLATION VARIABLES //ecal sum book2DHistoVector( iBooker, h_ecalSum_, "1D", "ecalSum", "Ecal Sum in the Iso Cone;E (GeV)", sumBin_, sumMin_, sumMax_); book2DHistoVector(iBooker, h_ecalSumEBarrel_, "1D", "ecalSumEBarrel", "Ecal Sum in the IsoCone for Barrel;E (GeV)", sumBin_, sumMin_, sumMax_); book2DHistoVector(iBooker, h_ecalSumEEndcap_, "1D", "ecalSumEEndcap", "Ecal Sum in the IsoCone for Endcap;E (GeV)", sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_ecalSumVsEt_, "2D", "ecalSumVsEt2D", "Ecal Sum in the Iso Cone;E_{T} (GeV);E (GeV)", reducedEtBin_, etMin_, etMax_, reducedSumBin_, sumMin_, sumMax_); } book3DHistoVector(iBooker, p_ecalSumVsEt_, "Profile", "ecalSumVsEt", "Avg Ecal Sum in the Iso Cone vs E_{T};E_{T} (GeV);E (GeV)", etBin_, etMin_, etMax_, sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_ecalSumVsEta_, "2D", "ecalSumVsEta2D", "Ecal Sum in the Iso Cone;#eta;E (GeV)", reducedEtaBin_, etaMin_, etaMax_, reducedSumBin_, sumMin_, sumMax_); } book2DHistoVector(iBooker, p_ecalSumVsEta_, "Profile", "ecalSumVsEta", "Avg Ecal Sum in the Iso Cone vs #eta;#eta;E (GeV)", etaBin_, etaMin_, etaMax_, sumBin_, sumMin_, sumMax_); //hcal sum book2DHistoVector( iBooker, h_hcalSum_, "1D", "hcalSum", "Hcal Sum in the Iso Cone;E (GeV)", sumBin_, sumMin_, sumMax_); book2DHistoVector(iBooker, h_hcalSumEBarrel_, "1D", "hcalSumEBarrel", "Hcal Sum in the IsoCone for Barrel;E (GeV)", sumBin_, sumMin_, sumMax_); book2DHistoVector(iBooker, h_hcalSumEEndcap_, "1D", "hcalSumEEndcap", "Hcal Sum in the IsoCone for Endcap;E (GeV)", sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_hcalSumVsEt_, "2D", "hcalSumVsEt2D", "Hcal Sum in the Iso Cone;E_{T} (GeV);E (GeV)", reducedEtBin_, etMin_, etMax_, reducedSumBin_, sumMin_, sumMax_); } book3DHistoVector(iBooker, p_hcalSumVsEt_, "Profile", "hcalSumVsEt", "Avg Hcal Sum in the Iso Cone vs E_{T};E_{T} (GeV);E (GeV)", etBin_, etMin_, etMax_, sumBin_, sumMin_, sumMax_); if (standAlone_) { book2DHistoVector(iBooker, h_hcalSumVsEta_, "2D", "hcalSumVsEta2D", "Hcal Sum in the Iso Cone;#eta;E (GeV)", reducedEtaBin_, etaMin_, etaMax_, reducedSumBin_, sumMin_, sumMax_); } book2DHistoVector(iBooker, p_hcalSumVsEta_, "Profile", "hcalSumVsEta", "Avg Hcal Sum in the Iso Cone vs #eta;#eta;E (GeV)", etaBin_, etaMin_, etaMax_, sumBin_, sumMin_, sumMax_); //h over e book3DHistoVector(iBooker, h_hOverE_, "1D", "hOverE", "H/E;H/E", hOverEBin_, hOverEMin_, hOverEMax_); book2DHistoVector(iBooker, p_hOverEVsEt_, "Profile", "hOverEVsEt", "Avg H/E vs Et;E_{T} (GeV);H/E", etBin_, etMin_, etMax_, hOverEBin_, hOverEMin_, hOverEMax_); book2DHistoVector(iBooker, p_hOverEVsEta_, "Profile", "hOverEVsEta", "Avg H/E vs #eta;#eta;H/E", etaBin_, etaMin_, etaMax_, hOverEBin_, hOverEMin_, hOverEMax_); book3DHistoVector(iBooker, h_h1OverE_, "1D", "h1OverE", "H/E for Depth 1;H/E", hOverEBin_, hOverEMin_, hOverEMax_); book3DHistoVector(iBooker, h_h2OverE_, "1D", "h2OverE", "H/E for Depth 2;H/E", hOverEBin_, hOverEMin_, hOverEMax_); // pf isolation book2DHistoVector( iBooker, h_phoIsoBarrel_, "1D", "phoIsoBarrel", "PF photon iso Barrel;E (GeV)", reducedEtBin_, etMin_, 25.); book2DHistoVector( iBooker, h_phoIsoEndcap_, "1D", "phoIsoEndcap", "PF photon iso Endcap;E (GeV)", reducedEtBin_, etMin_, 25.); book2DHistoVector(iBooker, h_chHadIsoBarrel_, "1D", "chHadIsoBarrel", "PF charged Had iso Barrel;E (GeV)", reducedEtBin_, etMin_, 25.); book2DHistoVector(iBooker, h_chHadIsoEndcap_, "1D", "chHadIsoEndcap", "PF charged Had iso Endcap;E (GeV)", reducedEtBin_, etMin_, 25.); book2DHistoVector(iBooker, h_nHadIsoBarrel_, "1D", "neutralHadIsoBarrel", "PF neutral Had iso Barrel;E (GeV)", reducedEtBin_, etMin_, 25.); book2DHistoVector(iBooker, h_nHadIsoEndcap_, "1D", "neutralHadIsoEndcap", "PF neutral Had iso Endcap;E (GeV)", reducedEtBin_, etMin_, 25.); //OTHER VARIABLES //bad channel histograms book2DHistoVector(iBooker, h_phoEt_BadChannels_, "1D", "phoEtBadChannels", "Fraction Containing Bad Channels: E_{T};E_{T} (GeV)", etBin_, etMin_, etMax_); book2DHistoVector(iBooker, h_phoEta_BadChannels_, "1D", "phoEtaBadChannels", "Fraction Containing Bad Channels: #eta;#eta", etaBin_, etaMin_, etaMax_); book2DHistoVector(iBooker, h_phoPhi_BadChannels_, "1D", "phoPhiBadChannels", "Fraction Containing Bad Channels: #phi;#phi", phiBin_, phiMin_, phiMax_); } void PhotonAnalyzer::bookHistogramsConversions(DQMStore::IBooker& iBooker) { // Set folder iBooker.setCurrentFolder("Egamma/" + fName_ + "/AllPhotons/Et Above 0 GeV/Conversions"); //ENERGY VARIABLES book3DHistoVector(iBooker, h_phoConvE_, "1D", "phoConvE", "E;E (GeV)", eBin_, eMin_, eMax_); book3DHistoVector(iBooker, h_phoConvEt_, "1D", "phoConvEt", "E_{T};E_{T} (GeV)", etBin_, etMin_, etMax_); //GEOMETRICAL VARIABLES book2DHistoVector(iBooker, h_phoConvEta_, "1D", "phoConvEta", "#eta;#eta", etaBin_, etaMin_, etaMax_); book3DHistoVector(iBooker, h_phoConvPhi_, "1D", "phoConvPhi", "#phi;#phi", phiBin_, phiMin_, phiMax_); //NUMBER OF PHOTONS book3DHistoVector(iBooker, h_nConv_, "1D", "nConv", "Number Of Conversions per Event ;# conversions", numberBin_, numberMin_, numberMax_); //SHOWER SHAPE VARIABLES book3DHistoVector(iBooker, h_phoConvR9_, "1D", "phoConvR9", "R9;R9", r9Bin_, r9Min_, r9Max_); //TRACK RELATED VARIABLES book3DHistoVector(iBooker, h_eOverPTracks_, "1D", "eOverPTracks", "E/P;E/P", eOverPBin_, eOverPMin_, eOverPMax_); book3DHistoVector(iBooker, h_pOverETracks_, "1D", "pOverETracks", "P/E;P/E", eOverPBin_, eOverPMin_, eOverPMax_); book3DHistoVector(iBooker, h_dPhiTracksAtVtx_, "1D", "dPhiTracksAtVtx", "#Delta#phi of Tracks at Vertex;#Delta#phi", dPhiTracksBin_, dPhiTracksMin_, dPhiTracksMax_); book3DHistoVector(iBooker, h_dPhiTracksAtEcal_, "1D", "dPhiTracksAtEcal", "Abs(#Delta#phi) of Tracks at Ecal;#Delta#phi", dPhiTracksBin_, 0., dPhiTracksMax_); book3DHistoVector(iBooker, h_dEtaTracksAtEcal_, "1D", "dEtaTracksAtEcal", "#Delta#eta of Tracks at Ecal;#Delta#eta", dEtaTracksBin_, dEtaTracksMin_, dEtaTracksMax_); book3DHistoVector(iBooker, h_dCotTracks_, "1D", "dCotTracks", "#Deltacot(#theta) of Tracks;#Deltacot(#theta)", dEtaTracksBin_, dEtaTracksMin_, dEtaTracksMax_); book2DHistoVector(iBooker, p_dCotTracksVsEta_, "Profile", "dCotTracksVsEta", "Avg #Deltacot(#theta) of Tracks vs #eta;#eta;#Deltacot(#theta)", etaBin_, etaMin_, etaMax_, dEtaTracksBin_, dEtaTracksMin_, dEtaTracksMax_); book2DHistoVector(iBooker, p_nHitsVsEta_, "Profile", "nHitsVsEta", "Avg Number of Hits per Track vs #eta;#eta;# hits", etaBin_, etaMin_, etaMax_, etaBin_, 0, 16); book2DHistoVector( iBooker, h_tkChi2_, "1D", "tkChi2", "#chi^{2} of Track Fitting;#chi^{2}", chi2Bin_, chi2Min_, chi2Max_); book2DHistoVector(iBooker, p_tkChi2VsEta_, "Profile", "tkChi2VsEta", "Avg #chi^{2} of Track Fitting vs #eta;#eta;#chi^{2}", etaBin_, etaMin_, etaMax_, chi2Bin_, chi2Min_, chi2Max_); //VERTEX RELATED VARIABLES book2DHistoVector(iBooker, h_convVtxRvsZ_, "2D", "convVtxRvsZ", "Vertex Position;Z (cm);R (cm)", 500, zMin_, zMax_, rBin_, rMin_, rMax_); book2DHistoVector( iBooker, h_convVtxZEndcap_, "1D", "convVtxZEndcap", "Vertex Position: #eta > 1.5;Z (cm)", zBin_, zMin_, zMax_); book2DHistoVector(iBooker, h_convVtxZ_, "1D", "convVtxZ", "Vertex Position;Z (cm)", zBin_, zMin_, zMax_); book2DHistoVector(iBooker, h_convVtxR_, "1D", "convVtxR", "Vertex Position: #eta < 1;R (cm)", rBin_, rMin_, rMax_); book2DHistoVector(iBooker, h_convVtxYvsX_, "2D", "convVtxYvsX", "Vertex Position: #eta < 1;X (cm);Y (cm)", xBin_, xMin_, xMax_, yBin_, yMin_, yMax_); book2DHistoVector(iBooker, h_vertexChi2Prob_, "1D", "vertexChi2Prob", "#chi^{2} Probability of Vertex Fitting;#chi^{2}", 100, 0., 1.0); } // Booking helper methods: MonitorElement* PhotonAnalyzer::bookHisto( DQMStore::IBooker& iBooker, string histoName, string title, int bin, double min, double max) { int histo_index = 0; stringstream histo_number_stream; //determining which folder we're in if (iBooker.pwd().find("InvMass") != string::npos) { histo_index_invMass_++; histo_index = histo_index_invMass_; } if (iBooker.pwd().find("Efficiencies") != string::npos) { histo_index_efficiency_++; histo_index = histo_index_efficiency_; } histo_number_stream << "h_"; if (histo_index < 10) histo_number_stream << "0"; histo_number_stream << histo_index; return iBooker.book1D(histo_number_stream.str() + "_" + histoName, title, bin, min, max); } void PhotonAnalyzer::book2DHistoVector(DQMStore::IBooker& iBooker, vector<vector<MonitorElement*> >& temp2DVector, string histoType, string histoName, string title, int xbin, double xmin, double xmax, int ybin, double ymin, double ymax) { int histo_index = 0; vector<MonitorElement*> temp1DVector; //determining which folder we're in bool conversionPlot = false; if (iBooker.pwd().find("Conversions") != string::npos) conversionPlot = true; bool TwoDPlot = false; if (histoName.find("2D") != string::npos) TwoDPlot = true; if (conversionPlot) { histo_index_conversions_++; histo_index = histo_index_conversions_; } else { histo_index_photons_++; histo_index = histo_index_photons_; } stringstream histo_number_stream; histo_number_stream << "h_"; if (histo_index < 10) histo_number_stream << "0"; histo_number_stream << histo_index << "_"; for (int cut = 0; cut != numberOfSteps_; ++cut) { //looping over Et cut values for (uint type = 0; type != types_.size(); ++type) { //looping over isolation type currentFolder_.str(""); currentFolder_ << "Egamma/" + fName_ + "/" << types_[type] << "Photons/Et above " << (cut + 1) * cutStep_ << " GeV"; if (conversionPlot) currentFolder_ << "/Conversions"; iBooker.setCurrentFolder(currentFolder_.str()); string kind; if (conversionPlot) kind = " Conversions: "; else kind = " Photons: "; if (histoType == "1D") temp1DVector.push_back( iBooker.book1D(histo_number_stream.str() + histoName, types_[type] + kind + title, xbin, xmin, xmax)); else if (histoType == "2D") { if ((TwoDPlot && type == 0) || !TwoDPlot) { //only book the 2D plots in the "AllPhotons" folder temp1DVector.push_back(iBooker.book2D( histo_number_stream.str() + histoName, types_[type] + kind + title, xbin, xmin, xmax, ybin, ymin, ymax)); } } else if (histoType == "Profile") temp1DVector.push_back(iBooker.bookProfile( histo_number_stream.str() + histoName, types_[type] + kind + title, xbin, xmin, xmax, ybin, ymin, ymax, "")); else cout << "bad histoType\n"; } temp2DVector.push_back(temp1DVector); temp1DVector.clear(); } } void PhotonAnalyzer::book3DHistoVector(DQMStore::IBooker& iBooker, vector<vector<vector<MonitorElement*> > >& temp3DVector, string histoType, string histoName, string title, int xbin, double xmin, double xmax, int ybin, double ymin, double ymax) { int histo_index = 0; vector<MonitorElement*> temp1DVector; vector<vector<MonitorElement*> > temp2DVector; //determining which folder we're in bool conversionPlot = false; if (iBooker.pwd().find("Conversions") != string::npos) conversionPlot = true; if (conversionPlot) { histo_index_conversions_++; histo_index = histo_index_conversions_; } else { histo_index_photons_++; histo_index = histo_index_photons_; } stringstream histo_number_stream; histo_number_stream << "h_"; if (histo_index < 10) histo_number_stream << "0"; histo_number_stream << histo_index << "_"; for (int cut = 0; cut != numberOfSteps_; ++cut) { //looping over Et cut values for (uint type = 0; type != types_.size(); ++type) { //looping over isolation type for (uint part = 0; part != parts_.size(); ++part) { //looping over different parts of the ecal currentFolder_.str(""); currentFolder_ << "Egamma/" + fName_ + "/" << types_[type] << "Photons/Et above " << (cut + 1) * cutStep_ << " GeV"; if (conversionPlot) currentFolder_ << "/Conversions"; iBooker.setCurrentFolder(currentFolder_.str()); string kind; if (conversionPlot) kind = " Conversions: "; else kind = " Photons: "; if (histoType == "1D") temp1DVector.push_back(iBooker.book1D(histo_number_stream.str() + histoName + parts_[part], types_[type] + kind + parts_[part] + ": " + title, xbin, xmin, xmax)); else if (histoType == "2D") temp1DVector.push_back(iBooker.book2D(histo_number_stream.str() + histoName + parts_[part], types_[type] + kind + parts_[part] + ": " + title, xbin, xmin, xmax, ybin, ymin, ymax)); else if (histoType == "Profile") temp1DVector.push_back(iBooker.bookProfile(histo_number_stream.str() + histoName + parts_[part], types_[type] + kind + parts_[part] + ": " + title, xbin, xmin, xmax, ybin, ymin, ymax, "")); else cout << "bad histoType\n"; } temp2DVector.push_back(temp1DVector); temp1DVector.clear(); } temp3DVector.push_back(temp2DVector); temp2DVector.clear(); } } // Analysis: void PhotonAnalyzer::analyze(const edm::Event& e, const edm::EventSetup& esup) { using namespace edm; if (nEvt_ % prescaleFactor_) return; nEvt_++; LogInfo(fName_) << "PhotonAnalyzer Analyzing event number: " << e.id() << " Global Counter " << nEvt_ << "\n"; // Get the trigger results bool validTriggerEvent = true; edm::Handle<trigger::TriggerEvent> triggerEventHandle; const trigger::TriggerEvent dummyTE; e.getByToken(triggerEvent_token_, triggerEventHandle); if (!triggerEventHandle.isValid()) { edm::LogInfo(fName_) << "Error! Can't get the product: triggerEvent_" << endl; validTriggerEvent = false; } const trigger::TriggerEvent& triggerEvent(validTriggerEvent ? *(triggerEventHandle.product()) : dummyTE); // Get the reconstructed photons // bool validPhotons=true; Handle<reco::PhotonCollection> photonHandle; e.getByToken(photon_token_, photonHandle); if (!photonHandle.isValid()) { edm::LogInfo(fName_) << "Error! Can't get the product: photon_token_" << endl; // validPhotons=false; } const reco::PhotonCollection& photonCollection(*(photonHandle.product())); // Get the PhotonId objects // bool validloosePhotonID=true; Handle<edm::ValueMap<bool> > loosePhotonFlag; e.getByToken(PhotonIDLoose_token_, loosePhotonFlag); if (!loosePhotonFlag.isValid()) { edm::LogInfo(fName_) << "Error! Can't get the product: PhotonIDLoose_token_" << endl; // validloosePhotonID=false; } // edm::ValueMap<bool> dummyLPID; // const edm::ValueMap<bool>& loosePhotonID(validloosePhotonID? *(loosePhotonFlag.product()) : dummyLPID); // bool validtightPhotonID=true; Handle<edm::ValueMap<bool> > tightPhotonFlag; e.getByToken(PhotonIDTight_token_, tightPhotonFlag); if (!tightPhotonFlag.isValid()) { edm::LogInfo(fName_) << "Error! Can't get the product: PhotonIDTight_token_" << endl; // validtightPhotonID=false; } // edm::ValueMap<bool> dummyTPI; // const edm::ValueMap<bool>& tightPhotonID(validtightPhotonID ? *(tightPhotonFlag.product()) : dummyTPI); edm::Handle<reco::VertexCollection> vtxH; if (!isHeavyIon_) { e.getByToken(offline_pvToken_, vtxH); h_nRecoVtx_->Fill(float(vtxH->size())); } // Create array to hold #photons/event information int nPho[100][3][3]; for (int cut = 0; cut != 100; ++cut) { for (unsigned int type = 0; type != types_.size(); ++type) { for (unsigned int part = 0; part != parts_.size(); ++part) { nPho[cut][type][part] = 0; } } } // Create array to hold #conversions/event information int nConv[100][3][3]; for (int cut = 0; cut != 100; ++cut) { for (unsigned int type = 0; type != types_.size(); ++type) { for (unsigned int part = 0; part != parts_.size(); ++part) { nConv[cut][type][part] = 0; } } } //Prepare list of photon-related HLT filter names vector<int> Keys; for (uint filterIndex = 0; filterIndex < triggerEvent.sizeFilters(); ++filterIndex) { //loop over all trigger filters in event (i.e. filters passed) string label = triggerEvent.filterTag(filterIndex).label(); if (label.find("Photon") != string::npos) { //get photon-related filters for (uint filterKeyIndex = 0; filterKeyIndex < triggerEvent.filterKeys(filterIndex).size(); ++filterKeyIndex) { //loop over keys to objects passing this filter Keys.push_back( triggerEvent.filterKeys(filterIndex)[filterKeyIndex]); //add keys to a vector for later reference } } } // sort Keys vector in ascending order // and erases duplicate entries from the vector sort(Keys.begin(), Keys.end()); for (uint i = 0; i < Keys.size();) { if (i != (Keys.size() - 1)) { if (Keys[i] == Keys[i + 1]) Keys.erase(Keys.begin() + i + 1); else ++i; } else ++i; } //We now have a vector of unique keys to TriggerObjects passing a photon-related filter // old int photonCounter = 0; /////////////////////////BEGIN LOOP OVER THE COLLECTION OF PHOTONS IN THE EVENT///////////////////////// for (unsigned int iPho = 0; iPho < photonHandle->size(); iPho++) { const reco::Photon* aPho = &photonCollection[iPho]; // for( reco::PhotonCollection::const_iterator iPho = photonCollection.begin(); iPho != photonCollection.end(); iPho++) { //for HLT efficiency plots h_phoEta_preHLT_->Fill(aPho->eta()); h_phoEt_preHLT_->Fill(aPho->et()); double deltaR = 1000.; double deltaRMin = 1000.; double deltaRMax = 0.05; //sets deltaR threshold for matching photons to trigger objects for (vector<int>::const_iterator objectKey = Keys.begin(); objectKey != Keys.end(); objectKey++) { //loop over keys to objects that fired photon triggers deltaR = reco::deltaR(triggerEvent.getObjects()[(*objectKey)].eta(), triggerEvent.getObjects()[(*objectKey)].phi(), aPho->superCluster()->eta(), aPho->superCluster()->phi()); if (deltaR < deltaRMin) deltaRMin = deltaR; } if (deltaRMin > deltaRMax) { //photon fails delta R cut if (useTriggerFiltering_) continue; //throw away photons that haven't passed any photon filters } if (deltaRMin <= deltaRMax) { //photon passes delta R cut h_phoEta_postHLT_->Fill(aPho->eta()); h_phoEt_postHLT_->Fill(aPho->et()); } // if (aPho->et() < minPhoEtCut_) continue; bool isLoosePhoton(false), isTightPhoton(false); if (photonSelection(aPho)) isLoosePhoton = true; //find out which part of the Ecal contains the photon bool phoIsInBarrel = false; bool phoIsInEndcap = false; float etaPho = aPho->superCluster()->eta(); if (fabs(etaPho) < 1.479) phoIsInBarrel = true; else { phoIsInEndcap = true; } int part = 0; if (phoIsInBarrel) part = 1; if (phoIsInEndcap) part = 2; ///// From 30X on, Photons are already pre-selected at reconstruction level with a looseEM isolation bool isIsolated = false; if (isolationStrength_ == 0) isIsolated = isLoosePhoton; if (isolationStrength_ == 1) isIsolated = isTightPhoton; if (isolationStrength_ == 2) isIsolated = photonSelectionSlimmed(aPho); int type = 0; if (isIsolated) type = 1; if (!excludeBkgHistos_ && !isIsolated) type = 2; //get rechit collection containing this photon bool validEcalRecHits = true; edm::Handle<EcalRecHitCollection> ecalRecHitHandle; EcalRecHitCollection ecalRecHitCollection; if (phoIsInBarrel) { // Get handle to barrel rec hits e.getByToken(barrelRecHit_token_, ecalRecHitHandle); if (!ecalRecHitHandle.isValid()) { edm::LogError(fName_) << "Error! Can't get the product: barrelRecHit_token_"; validEcalRecHits = false; } } else if (phoIsInEndcap) { // Get handle to endcap rec hits e.getByToken(endcapRecHit_token_, ecalRecHitHandle); if (!ecalRecHitHandle.isValid()) { edm::LogError(fName_) << "Error! Can't get the product: endcapRecHit_token"; validEcalRecHits = false; } } if (validEcalRecHits) ecalRecHitCollection = *(ecalRecHitHandle.product()); //if (aPho->isEBEEGap()) continue; //cut out gap photons //filling histograms to make isolation efficiencies if (isLoosePhoton) { h_phoEta_Loose_->Fill(aPho->eta()); h_phoEt_Loose_->Fill(aPho->et()); } if (isTightPhoton) { h_phoEta_Tight_->Fill(aPho->eta()); h_phoEt_Tight_->Fill(aPho->et()); } for (int cut = 0; cut != numberOfSteps_; ++cut) { //loop over different transverse energy cuts double Et = aPho->et(); bool passesCuts = false; //sorting the photon into the right Et-dependant folder if (useBinning_ && Et > (cut + 1) * cutStep_ && ((Et < (cut + 2) * cutStep_) | (cut == numberOfSteps_ - 1))) { passesCuts = true; } else if (!useBinning_ && Et > (cut + 1) * cutStep_) { passesCuts = true; } if (passesCuts) { //filling isolation variable histograms //tracker isolation variables fill2DHistoVector(h_nTrackIsolSolid_, aPho->nTrkSolidConeDR04(), cut, type); fill2DHistoVector(h_nTrackIsolHollow_, aPho->nTrkHollowConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_nTrackIsolSolidVsEta_, aPho->eta(), aPho->nTrkSolidConeDR04(), cut, type); fill2DHistoVector(p_nTrackIsolSolidVsEta_, aPho->eta(), aPho->nTrkSolidConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_nTrackIsolHollowVsEta_, aPho->eta(), aPho->nTrkHollowConeDR04(), cut, type); fill2DHistoVector(p_nTrackIsolHollowVsEta_, aPho->eta(), aPho->nTrkHollowConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_nTrackIsolSolidVsEt_, aPho->et(), aPho->nTrkSolidConeDR04(), cut, type); fill2DHistoVector(p_nTrackIsolSolidVsEt_, aPho->et(), aPho->nTrkSolidConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_nTrackIsolHollowVsEt_, aPho->et(), aPho->nTrkHollowConeDR04(), cut, type); fill2DHistoVector(p_nTrackIsolHollowVsEt_, aPho->et(), aPho->nTrkHollowConeDR04(), cut, type); /////// fill2DHistoVector(h_trackPtSumSolid_, aPho->trkSumPtSolidConeDR04(), cut, type); fill2DHistoVector(h_trackPtSumHollow_, aPho->trkSumPtSolidConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_trackPtSumSolidVsEta_, aPho->eta(), aPho->trkSumPtSolidConeDR04(), cut, type); fill2DHistoVector(p_trackPtSumSolidVsEta_, aPho->eta(), aPho->trkSumPtSolidConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_trackPtSumHollowVsEta_, aPho->eta(), aPho->trkSumPtHollowConeDR04(), cut, type); fill2DHistoVector(p_trackPtSumHollowVsEta_, aPho->eta(), aPho->trkSumPtHollowConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_trackPtSumSolidVsEt_, aPho->et(), aPho->trkSumPtSolidConeDR04(), cut, type); fill2DHistoVector(p_trackPtSumSolidVsEt_, aPho->et(), aPho->trkSumPtSolidConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_trackPtSumHollowVsEt_, aPho->et(), aPho->trkSumPtHollowConeDR04(), cut, type); fill2DHistoVector(p_trackPtSumHollowVsEt_, aPho->et(), aPho->trkSumPtHollowConeDR04(), cut, type); //calorimeter isolation variables fill2DHistoVector(h_ecalSum_, aPho->ecalRecHitSumEtConeDR04(), cut, type); if (aPho->isEB()) { fill2DHistoVector(h_ecalSumEBarrel_, aPho->ecalRecHitSumEtConeDR04(), cut, type); } if (aPho->isEE()) { fill2DHistoVector(h_ecalSumEEndcap_, aPho->ecalRecHitSumEtConeDR04(), cut, type); } if (standAlone_) fill2DHistoVector(h_ecalSumVsEta_, aPho->eta(), aPho->ecalRecHitSumEtConeDR04(), cut, type); fill2DHistoVector(p_ecalSumVsEta_, aPho->eta(), aPho->ecalRecHitSumEtConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_ecalSumVsEt_, aPho->et(), aPho->ecalRecHitSumEtConeDR04(), cut, type); fill3DHistoVector(p_ecalSumVsEt_, aPho->et(), aPho->ecalRecHitSumEtConeDR04(), cut, type, part); /////// fill2DHistoVector(h_hcalSum_, aPho->hcalTowerSumEtConeDR04(), cut, type); if (aPho->isEB()) { fill2DHistoVector(h_hcalSumEBarrel_, aPho->hcalTowerSumEtConeDR04(), cut, type); } if (aPho->isEE()) { fill2DHistoVector(h_hcalSumEEndcap_, aPho->hcalTowerSumEtConeDR04(), cut, type); } if (standAlone_) fill2DHistoVector(h_hcalSumVsEta_, aPho->eta(), aPho->hcalTowerSumEtConeDR04(), cut, type); fill2DHistoVector(p_hcalSumVsEta_, aPho->eta(), aPho->hcalTowerSumEtConeDR04(), cut, type); if (standAlone_) fill2DHistoVector(h_hcalSumVsEt_, aPho->et(), aPho->hcalTowerSumEtConeDR04(), cut, type); fill3DHistoVector(p_hcalSumVsEt_, aPho->et(), aPho->hcalTowerSumEtConeDR04(), cut, type, part); fill3DHistoVector(h_hOverE_, aPho->hadronicOverEm(), cut, type, part); fill2DHistoVector(p_hOverEVsEta_, aPho->eta(), aPho->hadronicOverEm(), cut, type); fill2DHistoVector(p_hOverEVsEt_, aPho->et(), aPho->hadronicOverEm(), cut, type); fill3DHistoVector(h_h1OverE_, aPho->hadronicDepth1OverEm(), cut, type, part); fill3DHistoVector(h_h2OverE_, aPho->hadronicDepth2OverEm(), cut, type, part); // filling pf isolation variables if (aPho->isEB()) { fill2DHistoVector(h_phoIsoBarrel_, aPho->photonIso(), cut, type); fill2DHistoVector(h_chHadIsoBarrel_, aPho->chargedHadronIso(), cut, type); fill2DHistoVector(h_nHadIsoBarrel_, aPho->neutralHadronIso(), cut, type); } if (aPho->isEE()) { fill2DHistoVector(h_phoIsoEndcap_, aPho->photonIso(), cut, type); fill2DHistoVector(h_chHadIsoEndcap_, aPho->chargedHadronIso(), cut, type); fill2DHistoVector(h_nHadIsoEndcap_, aPho->neutralHadronIso(), cut, type); } //filling photon histograms nPho[cut][0][0]++; nPho[cut][0][part]++; if (type != 0) { nPho[cut][type][0]++; nPho[cut][type][part]++; } //energy variables fill3DHistoVector(h_phoE_, aPho->energy(), cut, type, part); fill3DHistoVector(h_phoSigmaEoverE_, aPho->getCorrectedEnergyError(aPho->getCandidateP4type()) / aPho->energy(), cut, type, part); if (!isHeavyIon_) fill3DHistoVector(p_phoSigmaEoverEvsNVtx_, float(vtxH->size()), aPho->getCorrectedEnergyError(aPho->getCandidateP4type()) / aPho->energy(), cut, type, part); fill3DHistoVector(h_phoEt_, aPho->et(), cut, type, part); //geometrical variables fill2DHistoVector(h_phoEta_, aPho->eta(), cut, type); fill2DHistoVector(h_scEta_, aPho->superCluster()->eta(), cut, type); fill3DHistoVector(h_phoPhi_, aPho->phi(), cut, type, part); fill3DHistoVector(h_scPhi_, aPho->superCluster()->phi(), cut, type, part); //shower shape variables fill3DHistoVector(h_r9_, aPho->r9(), cut, type, part); if (standAlone_) fill2DHistoVector(h_r9VsEta_, aPho->eta(), aPho->r9(), cut, type); fill2DHistoVector(p_r9VsEta_, aPho->eta(), aPho->r9(), cut, type); if (standAlone_) fill2DHistoVector(h_r9VsEt_, aPho->et(), aPho->r9(), cut, type); fill2DHistoVector(p_r9VsEt_, aPho->et(), aPho->r9(), cut, type); if (standAlone_) fill2DHistoVector(h_e1x5VsEta_, aPho->eta(), aPho->e1x5(), cut, type); fill2DHistoVector(p_e1x5VsEta_, aPho->eta(), aPho->e1x5(), cut, type); if (standAlone_) fill2DHistoVector(h_e1x5VsEt_, aPho->et(), aPho->e1x5(), cut, type); fill2DHistoVector(p_e1x5VsEt_, aPho->et(), aPho->e1x5(), cut, type); if (standAlone_) fill2DHistoVector(h_e2x5VsEta_, aPho->eta(), aPho->e2x5(), cut, type); fill2DHistoVector(p_e2x5VsEta_, aPho->eta(), aPho->e2x5(), cut, type); if (standAlone_) fill2DHistoVector(h_e2x5VsEt_, aPho->et(), aPho->e2x5(), cut, type); fill2DHistoVector(p_e2x5VsEt_, aPho->et(), aPho->e2x5(), cut, type); if (standAlone_) fill2DHistoVector(h_maxEXtalOver3x3VsEta_, aPho->eta(), aPho->maxEnergyXtal() / aPho->e3x3(), cut, type); fill2DHistoVector(p_maxEXtalOver3x3VsEta_, aPho->eta(), aPho->maxEnergyXtal() / aPho->e3x3(), cut, type); if (standAlone_) fill2DHistoVector(h_maxEXtalOver3x3VsEt_, aPho->et(), aPho->maxEnergyXtal() / aPho->e3x3(), cut, type); fill2DHistoVector(p_maxEXtalOver3x3VsEt_, aPho->et(), aPho->maxEnergyXtal() / aPho->e3x3(), cut, type); if (standAlone_) fill2DHistoVector(h_r1x5VsEta_, aPho->eta(), aPho->r1x5(), cut, type); fill2DHistoVector(p_r1x5VsEta_, aPho->eta(), aPho->r1x5(), cut, type); if (standAlone_) fill2DHistoVector(h_r1x5VsEt_, aPho->et(), aPho->r1x5(), cut, type); fill2DHistoVector(p_r1x5VsEt_, aPho->et(), aPho->r1x5(), cut, type); if (standAlone_) fill2DHistoVector(h_r2x5VsEta_, aPho->eta(), aPho->r2x5(), cut, type); fill2DHistoVector(p_r2x5VsEta_, aPho->eta(), aPho->r2x5(), cut, type); if (standAlone_) fill2DHistoVector(h_r2x5VsEt_, aPho->et(), aPho->r2x5(), cut, type); fill2DHistoVector(p_r2x5VsEt_, aPho->et(), aPho->r2x5(), cut, type); fill3DHistoVector(h_phoSigmaIetaIeta_, aPho->sigmaIetaIeta(), cut, type, part); if (standAlone_) fill2DHistoVector(h_sigmaIetaIetaVsEta_, aPho->eta(), aPho->sigmaIetaIeta(), cut, type); fill2DHistoVector(p_sigmaIetaIetaVsEta_, aPho->eta(), aPho->sigmaIetaIeta(), cut, type); //filling histograms for photons containing a bad ECAL channel bool atLeastOneDeadChannel = false; for (reco::CaloCluster_iterator bcIt = aPho->superCluster()->clustersBegin(); bcIt != aPho->superCluster()->clustersEnd(); ++bcIt) { //loop over basic clusters in SC for (vector<pair<DetId, float> >::const_iterator rhIt = (*bcIt)->hitsAndFractions().begin(); rhIt != (*bcIt)->hitsAndFractions().end(); ++rhIt) { //loop over rec hits in basic cluster for (EcalRecHitCollection::const_iterator it = ecalRecHitCollection.begin(); it != ecalRecHitCollection.end(); ++it) { //loop over all rec hits to find the right ones if (rhIt->first == (*it).id()) { //found the matching rechit if ((*it).recoFlag() == 9) { //has a bad channel atLeastOneDeadChannel = true; break; } } } } } if (atLeastOneDeadChannel) { fill2DHistoVector(h_phoPhi_BadChannels_, aPho->phi(), cut, type); fill2DHistoVector(h_phoEta_BadChannels_, aPho->eta(), cut, type); fill2DHistoVector(h_phoEt_BadChannels_, aPho->et(), cut, type); } // filling conversion-related histograms if (aPho->hasConversionTracks()) { nConv[cut][0][0]++; nConv[cut][0][part]++; nConv[cut][type][0]++; nConv[cut][type][part]++; } //loop over conversions (don't forget, we're still inside the photon loop, // i.e. these are all the conversions for this ONE photon, not for all the photons in the event) reco::ConversionRefVector conversions = aPho->conversions(); for (unsigned int iConv = 0; iConv < conversions.size(); iConv++) { reco::ConversionRef aConv = conversions[iConv]; if (aConv->nTracks() < 2) continue; //fill histogram for denominator of vertex reconstruction efficiency plot if (cut == 0) h_phoEta_Vertex_->Fill(aConv->refittedPairMomentum().eta()); if (!(aConv->conversionVertex().isValid())) continue; float chi2Prob = ChiSquaredProbability(aConv->conversionVertex().chi2(), aConv->conversionVertex().ndof()); if (chi2Prob < 0.0005) continue; fill2DHistoVector(h_vertexChi2Prob_, chi2Prob, cut, type); fill3DHistoVector(h_phoConvE_, aPho->energy(), cut, type, part); fill3DHistoVector(h_phoConvEt_, aPho->et(), cut, type, part); fill3DHistoVector(h_phoConvR9_, aPho->r9(), cut, type, part); if (cut == 0 && isLoosePhoton) { h_convEta_Loose_->Fill(aPho->eta()); h_convEt_Loose_->Fill(aPho->et()); } if (cut == 0 && isTightPhoton) { h_convEta_Tight_->Fill(aPho->eta()); h_convEt_Tight_->Fill(aPho->et()); } fill2DHistoVector(h_phoConvEta_, aConv->refittedPairMomentum().eta(), cut, type); fill3DHistoVector(h_phoConvPhi_, aConv->refittedPairMomentum().phi(), cut, type, part); //we use the photon position because we'll be dividing it by a photon histogram (not a conversion histogram) fill2DHistoVector(h_phoConvEtaForEfficiency_, aPho->eta(), cut, type); fill3DHistoVector(h_phoConvPhiForEfficiency_, aPho->phi(), cut, type, part); //vertex histograms double convR = sqrt(aConv->conversionVertex().position().perp2()); double scalar = aConv->conversionVertex().position().x() * aConv->refittedPairMomentum().x() + aConv->conversionVertex().position().y() * aConv->refittedPairMomentum().y(); if (scalar < 0) convR = -convR; fill2DHistoVector(h_convVtxRvsZ_, aConv->conversionVertex().position().z(), convR, cut, type); //trying to "see" R-Z view of tracker fill2DHistoVector(h_convVtxZ_, aConv->conversionVertex().position().z(), cut, type); if (fabs(aPho->eta()) > 1.5) { //trying to "see" tracker endcaps fill2DHistoVector(h_convVtxZEndcap_, aConv->conversionVertex().position().z(), cut, type); } else if (fabs(aPho->eta()) < 1) { //trying to "see" tracker barrel fill2DHistoVector(h_convVtxR_, convR, cut, type); fill2DHistoVector(h_convVtxYvsX_, aConv->conversionVertex().position().x(), aConv->conversionVertex().position().y(), cut, type); } const std::vector<edm::RefToBase<reco::Track> > tracks = aConv->tracks(); for (unsigned int i = 0; i < tracks.size(); i++) { fill2DHistoVector(h_tkChi2_, tracks[i]->normalizedChi2(), cut, type); fill2DHistoVector(p_tkChi2VsEta_, aPho->eta(), tracks[i]->normalizedChi2(), cut, type); fill2DHistoVector(p_dCotTracksVsEta_, aPho->eta(), aConv->pairCotThetaSeparation(), cut, type); fill2DHistoVector(p_nHitsVsEta_, aPho->eta(), float(tracks[i]->numberOfValidHits()), cut, type); } //calculating delta eta and delta phi of the two tracks float DPhiTracksAtVtx = -99; float dPhiTracksAtEcal = -99; float dEtaTracksAtEcal = -99; float phiTk1 = aConv->tracksPin()[0].phi(); float phiTk2 = aConv->tracksPin()[1].phi(); DPhiTracksAtVtx = phiTk1 - phiTk2; DPhiTracksAtVtx = phiNormalization(DPhiTracksAtVtx); if (!aConv->bcMatchingWithTracks().empty() && aConv->bcMatchingWithTracks()[0].isNonnull() && aConv->bcMatchingWithTracks()[1].isNonnull()) { float recoPhi1 = aConv->ecalImpactPosition()[0].phi(); float recoPhi2 = aConv->ecalImpactPosition()[1].phi(); float recoEta1 = aConv->ecalImpactPosition()[0].eta(); float recoEta2 = aConv->ecalImpactPosition()[1].eta(); recoPhi1 = phiNormalization(recoPhi1); recoPhi2 = phiNormalization(recoPhi2); dPhiTracksAtEcal = recoPhi1 - recoPhi2; dPhiTracksAtEcal = phiNormalization(dPhiTracksAtEcal); dEtaTracksAtEcal = recoEta1 - recoEta2; } fill3DHistoVector(h_dPhiTracksAtVtx_, DPhiTracksAtVtx, cut, type, part); fill3DHistoVector(h_dPhiTracksAtEcal_, fabs(dPhiTracksAtEcal), cut, type, part); fill3DHistoVector(h_dEtaTracksAtEcal_, dEtaTracksAtEcal, cut, type, part); fill3DHistoVector(h_eOverPTracks_, aConv->EoverPrefittedTracks(), cut, type, part); fill3DHistoVector(h_pOverETracks_, 1. / aConv->EoverPrefittedTracks(), cut, type, part); fill3DHistoVector(h_dCotTracks_, aConv->pairCotThetaSeparation(), cut, type, part); } //end loop over conversions } //end loop over photons passing cuts } //end loop over transverse energy cuts //make invariant mass plots if (isIsolated && aPho->et() >= invMassEtCut_) { for (unsigned int iPho2 = iPho + 1; iPho2 < photonHandle->size(); iPho2++) { const reco::Photon* aPho2 = &photonCollection[iPho2]; // for (reco::PhotonCollection::const_iterator iPho2=iPho+1; iPho2!=photonCollection.end(); iPho2++){ // edm::Ref<reco::PhotonCollection> photonref2(photonHandle, photonCounter); //note: it's correct to use photonCounter and not photonCounter+1 //since it has already been incremented earlier bool isTightPhoton2(false), isLoosePhoton2(false); if (photonSelection(aPho2)) isLoosePhoton2 = true; // Old if ( !isHeavyIon_ ) { // isTightPhoton2 = (tightPhotonID)[aPho2]; // isLoosePhoton2 = (loosePhotonID)[aPho2]; // } bool isIsolated2 = false; if (isolationStrength_ == 0) isIsolated2 = isLoosePhoton2; if (isolationStrength_ == 1) isIsolated2 = isTightPhoton2; if (isolationStrength_ == 2) isIsolated2 = photonSelectionSlimmed(aPho2); reco::ConversionRefVector conversions = aPho->conversions(); reco::ConversionRefVector conversions2 = aPho2->conversions(); if (isIsolated2 && aPho2->et() >= invMassEtCut_) { math::XYZTLorentzVector p12 = aPho->p4() + aPho2->p4(); float gamgamMass2 = p12.Dot(p12); h_invMassAllPhotons_->Fill(sqrt(gamgamMass2)); if (aPho->isEB() && aPho2->isEB()) { h_invMassPhotonsEBarrel_->Fill(sqrt(gamgamMass2)); } else if (aPho->isEE() && aPho2->isEE()) { h_invMassPhotonsEEndcap_->Fill(sqrt(gamgamMass2)); } else { h_invMassPhotonsEEndcapEBarrel_->Fill(sqrt(gamgamMass2)); } if (!conversions.empty() && conversions[0]->nTracks() >= 2) { if (!conversions2.empty() && conversions2[0]->nTracks() >= 2) h_invMassTwoWithTracks_->Fill(sqrt(gamgamMass2)); else h_invMassOneWithTracks_->Fill(sqrt(gamgamMass2)); } else if (!conversions2.empty() && conversions2[0]->nTracks() >= 2) h_invMassOneWithTracks_->Fill(sqrt(gamgamMass2)); else h_invMassZeroWithTracks_->Fill(sqrt(gamgamMass2)); } } } } /// End loop over Reco photons //filling number of photons/conversions per event histograms for (int cut = 0; cut != numberOfSteps_; ++cut) { for (uint type = 0; type != types_.size(); ++type) { for (uint part = 0; part != parts_.size(); ++part) { h_nPho_[cut][type][part]->Fill(float(nPho[cut][type][part])); h_nConv_[cut][type][part]->Fill(float(nConv[cut][type][part])); } } } } //End of Analyze method ////////////BEGIN AUXILIARY FUNCTIONS////////////// float PhotonAnalyzer::phiNormalization(float& phi) { const float PI = 3.1415927; const float TWOPI = 2.0 * PI; if (phi > PI) { phi = phi - TWOPI; } if (phi < -PI) { phi = phi + TWOPI; } return phi; } void PhotonAnalyzer::fill2DHistoVector( vector<vector<MonitorElement*> >& histoVector, double x, double y, int cut, int type) { histoVector[cut][0]->Fill(x, y); if (histoVector[cut].size() > 1) histoVector[cut][type]->Fill(x, y); //don't try to fill 2D histos that are only in the "AllPhotons" folder } void PhotonAnalyzer::fill2DHistoVector(vector<vector<MonitorElement*> >& histoVector, double x, int cut, int type) { histoVector[cut][0]->Fill(x); histoVector[cut][type]->Fill(x); } void PhotonAnalyzer::fill3DHistoVector( vector<vector<vector<MonitorElement*> > >& histoVector, double x, int cut, int type, int part) { histoVector[cut][0][0]->Fill(x); histoVector[cut][0][part]->Fill(x); histoVector[cut][type][0]->Fill(x); histoVector[cut][type][part]->Fill(x); } void PhotonAnalyzer::fill3DHistoVector( vector<vector<vector<MonitorElement*> > >& histoVector, double x, double y, int cut, int type, int part) { histoVector[cut][0][0]->Fill(x, y); histoVector[cut][0][part]->Fill(x, y); histoVector[cut][type][0]->Fill(x, y); histoVector[cut][type][part]->Fill(x, y); } bool PhotonAnalyzer::photonSelection(const reco::Photon* pho) { bool result = true; if (pho->pt() < minPhoEtCut_) result = false; if (fabs(pho->eta()) > photonMaxEta_) result = false; if (pho->isEBEEGap()) result = false; double EtCorrHcalIso = pho->hcalTowerSumEtConeDR03() - 0.005 * pho->pt(); double EtCorrTrkIso = pho->trkSumPtHollowConeDR03() - 0.002 * pho->pt(); if (pho->r9() <= 0.9) { if (pho->isEB() && (pho->hadTowOverEm() > 0.075 || pho->sigmaIetaIeta() > 0.014)) result = false; if (pho->isEE() && (pho->hadTowOverEm() > 0.075 || pho->sigmaIetaIeta() > 0.034)) result = false; /// remove after moriond if (EtCorrEcalIso>4.0) result=false; if (EtCorrHcalIso > 4.0) result = false; if (EtCorrTrkIso > 4.0) result = false; if (pho->chargedHadronIso() > 4) result = false; } else { if (pho->isEB() && (pho->hadTowOverEm() > 0.082 || pho->sigmaIetaIeta() > 0.014)) result = false; if (pho->isEE() && (pho->hadTowOverEm() > 0.075 || pho->sigmaIetaIeta() > 0.034)) result = false; /// remove after moriond if (EtCorrEcalIso>50.0) result=false; if (EtCorrHcalIso > 50.0) result = false; if (EtCorrTrkIso > 50.0) result = false; if (pho->chargedHadronIso() > 4) result = false; } return result; } bool PhotonAnalyzer::photonSelectionSlimmed(const reco::Photon* pho) { bool result = true; if (pho->pt() < minPhoEtCut_) result = false; if (fabs(pho->eta()) > photonMaxEta_) result = false; if (pho->isEBEEGap()) result = false; return result; }
39.175364
150
0.530171
[ "shape", "vector", "solid" ]
abfdcb9009eb2b49d41da2930b93c422c0b93dd5
34,575
cpp
C++
src/jit/lsraarm64.cpp
wnmhb/coreclr
e3562c9bcc92ec04eec97cf1a945e7ea6d5234d2
[ "MIT" ]
1
2018-01-29T03:04:43.000Z
2018-01-29T03:04:43.000Z
src/jit/lsraarm64.cpp
wnmhb/coreclr
e3562c9bcc92ec04eec97cf1a945e7ea6d5234d2
[ "MIT" ]
null
null
null
src/jit/lsraarm64.cpp
wnmhb/coreclr
e3562c9bcc92ec04eec97cf1a945e7ea6d5234d2
[ "MIT" ]
null
null
null
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX Register Requirements for ARM64 XX XX XX XX This encapsulates all the logic for setting register requirements for XX XX the ARM64 architecture. XX XX XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator #ifdef _TARGET_ARM64_ #include "jit.h" #include "sideeffects.h" #include "lower.h" //------------------------------------------------------------------------ // TreeNodeInfoInit: Set the register requirements for RA. // // Notes: // Takes care of annotating the register requirements // for every TreeNodeInfo struct that maps to each tree node. // // Preconditions: // LSRA has been initialized and there is a TreeNodeInfo node // already allocated and initialized for every tree in the IR. // // Postconditions: // Every TreeNodeInfo instance has the right annotations on register // requirements needed by LSRA to build the Interval Table (source, // destination and internal [temp] register counts). // void LinearScan::TreeNodeInfoInit(GenTree* tree, TreeNodeInfo* info) { unsigned kind = tree->OperKind(); RegisterType registerType = TypeGet(tree); if (tree->isContained()) { info->dstCount = 0; assert(info->srcCount == 0); return; } // Set the default dstCount. This may be modified below. if (tree->IsValue()) { info->dstCount = 1; if (tree->IsUnusedValue()) { info->isLocalDefUse = true; } } else { info->dstCount = 0; } switch (tree->OperGet()) { GenTree* op1; GenTree* op2; default: if (kind & (GTK_CONST | GTK_LEAF)) { info->srcCount = 0; } else if (kind & (GTK_SMPOP)) { info->srcCount = appendBinaryLocationInfoToList(tree->AsOp()); } else { unreached(); } break; case GT_STORE_LCL_FLD: case GT_STORE_LCL_VAR: info->srcCount = 1; assert(info->dstCount == 0); TreeNodeInfoInitStoreLoc(tree->AsLclVarCommon(), info); break; case GT_LIST: case GT_FIELD_LIST: case GT_ARGPLACE: case GT_NO_OP: case GT_START_NONGC: case GT_PROF_HOOK: info->srcCount = 0; assert(info->dstCount == 0); break; case GT_CNS_DBL: info->srcCount = 0; assert(info->dstCount == 1); { GenTreeDblCon* dblConst = tree->AsDblCon(); double constValue = dblConst->gtDblCon.gtDconVal; if (emitter::emitIns_valid_imm_for_fmov(constValue)) { // Directly encode constant to instructions. } else { // Reserve int to load constant from memory (IF_LARGELDC) info->internalIntCount = 1; } } break; case GT_BOX: case GT_COMMA: case GT_QMARK: case GT_COLON: info->srcCount = 0; assert(info->dstCount == 0); unreached(); break; case GT_RETURN: TreeNodeInfoInitReturn(tree, info); break; case GT_RETFILT: if (tree->TypeGet() == TYP_VOID) { info->srcCount = 0; assert(info->dstCount == 0); } else { assert(tree->TypeGet() == TYP_INT); info->srcCount = 1; assert(info->dstCount == 0); info->setSrcCandidates(this, RBM_INTRET); LocationInfoListNode* locationInfo = getLocationInfo(tree->gtOp.gtOp1); locationInfo->info.setSrcCandidates(this, RBM_INTRET); useList.Append(locationInfo); } break; case GT_NOP: // A GT_NOP is either a passthrough (if it is void, or if it has // a child), but must be considered to produce a dummy value if it // has a type but no child info->srcCount = 0; if (tree->TypeGet() != TYP_VOID && tree->gtOp.gtOp1 == nullptr) { assert(info->dstCount == 1); } else { assert(info->dstCount == 0); } break; case GT_JTRUE: info->srcCount = 0; assert(info->dstCount == 0); break; case GT_JMP: info->srcCount = 0; assert(info->dstCount == 0); break; case GT_SWITCH: // This should never occur since switch nodes must not be visible at this // point in the JIT. info->srcCount = 0; noway_assert(!"Switch must be lowered at this point"); break; case GT_JMPTABLE: info->srcCount = 0; assert(info->dstCount == 1); break; case GT_SWITCH_TABLE: info->srcCount = appendBinaryLocationInfoToList(tree->AsOp()); info->internalIntCount = 1; assert(info->dstCount == 0); break; case GT_ASG: noway_assert(!"We should never hit any assignment operator in lowering"); info->srcCount = 0; break; case GT_ADD: case GT_SUB: if (varTypeIsFloating(tree->TypeGet())) { // overflow operations aren't supported on float/double types. assert(!tree->gtOverflow()); // No implicit conversions at this stage as the expectation is that // everything is made explicit by adding casts. assert(tree->gtOp.gtOp1->TypeGet() == tree->gtOp.gtOp2->TypeGet()); } __fallthrough; case GT_AND: case GT_OR: case GT_XOR: info->srcCount = appendBinaryLocationInfoToList(tree->AsOp()); assert(info->dstCount == 1); break; case GT_RETURNTRAP: // this just turns into a compare of its child with an int // + a conditional call appendLocationInfoToList(tree->gtGetOp1()); info->srcCount = 1; assert(info->dstCount == 0); break; case GT_MOD: case GT_UMOD: NYI_IF(varTypeIsFloating(tree->TypeGet()), "FP Remainder in ARM64"); assert(!"Shouldn't see an integer typed GT_MOD node in ARM64"); break; case GT_MUL: if (tree->gtOverflow()) { // Need a register different from target reg to check for overflow. info->internalIntCount = 1; info->isInternalRegDelayFree = true; } __fallthrough; case GT_DIV: case GT_MULHI: case GT_UDIV: { info->srcCount = appendBinaryLocationInfoToList(tree->AsOp()); assert(info->dstCount == 1); } break; case GT_INTRINSIC: { noway_assert((tree->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Abs) || (tree->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Ceiling) || (tree->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Floor) || (tree->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Round) || (tree->gtIntrinsic.gtIntrinsicId == CORINFO_INTRINSIC_Sqrt)); // Both operand and its result must be of the same floating point type. op1 = tree->gtOp.gtOp1; assert(varTypeIsFloating(op1)); assert(op1->TypeGet() == tree->TypeGet()); appendLocationInfoToList(op1); info->srcCount = 1; assert(info->dstCount == 1); } break; #ifdef FEATURE_SIMD case GT_SIMD: TreeNodeInfoInitSIMD(tree->AsSIMD(), info); break; #endif // FEATURE_SIMD case GT_CAST: { // TODO-ARM64-CQ: Int-To-Int conversions - castOp cannot be a memory op and must have an assigned // register. // see CodeGen::genIntToIntCast() appendLocationInfoToList(tree->gtGetOp1()); info->srcCount = 1; assert(info->dstCount == 1); // Non-overflow casts to/from float/double are done using SSE2 instructions // and that allow the source operand to be either a reg or memop. Given the // fact that casts from small int to float/double are done as two-level casts, // the source operand is always guaranteed to be of size 4 or 8 bytes. var_types castToType = tree->CastToType(); GenTreePtr castOp = tree->gtCast.CastOp(); var_types castOpType = castOp->TypeGet(); if (tree->gtFlags & GTF_UNSIGNED) { castOpType = genUnsignedType(castOpType); } // Some overflow checks need a temp reg Lowering::CastInfo castInfo; // Get information about the cast. Lowering::getCastDescription(tree, &castInfo); if (castInfo.requiresOverflowCheck) { var_types srcType = castOp->TypeGet(); emitAttr cmpSize = EA_ATTR(genTypeSize(srcType)); // If we cannot store the comparisons in an immediate for either // comparing against the max or min value, then we will need to // reserve a temporary register. bool canStoreMaxValue = emitter::emitIns_valid_imm_for_cmp(castInfo.typeMax, cmpSize); bool canStoreMinValue = emitter::emitIns_valid_imm_for_cmp(castInfo.typeMin, cmpSize); if (!canStoreMaxValue || !canStoreMinValue) { info->internalIntCount = 1; } } } break; case GT_NEG: case GT_NOT: appendLocationInfoToList(tree->gtGetOp1()); info->srcCount = 1; assert(info->dstCount == 1); break; case GT_LSH: case GT_RSH: case GT_RSZ: case GT_ROR: TreeNodeInfoInitShiftRotate(tree, info); break; case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GE: case GT_GT: case GT_TEST_EQ: case GT_TEST_NE: case GT_JCMP: TreeNodeInfoInitCmp(tree, info); break; case GT_CKFINITE: appendLocationInfoToList(tree->gtOp.gtOp1); info->srcCount = 1; assert(info->dstCount == 1); info->internalIntCount = 1; break; case GT_CMPXCHG: { GenTreeCmpXchg* cmpXchgNode = tree->AsCmpXchg(); info->srcCount = cmpXchgNode->gtOpComparand->isContained() ? 2 : 3; assert(info->dstCount == 1); info->internalIntCount = 1; // For ARMv8 exclusives the lifetime of the addr and data must be extended because // it may be used used multiple during retries LocationInfoListNode* locationInfo = getLocationInfo(tree->gtCmpXchg.gtOpLocation); locationInfo->info.isDelayFree = true; useList.Append(locationInfo); LocationInfoListNode* valueInfo = getLocationInfo(tree->gtCmpXchg.gtOpValue); valueInfo->info.isDelayFree = true; useList.Append(valueInfo); if (!cmpXchgNode->gtOpComparand->isContained()) { LocationInfoListNode* comparandInfo = getLocationInfo(tree->gtCmpXchg.gtOpComparand); comparandInfo->info.isDelayFree = true; useList.Append(comparandInfo); } info->hasDelayFreeSrc = true; // Internals may not collide with target info->isInternalRegDelayFree = true; } break; case GT_LOCKADD: case GT_XADD: case GT_XCHG: { assert(info->dstCount == (tree->TypeGet() == TYP_VOID) ? 0 : 1); info->srcCount = tree->gtOp.gtOp2->isContained() ? 1 : 2; info->internalIntCount = (tree->OperGet() == GT_XCHG) ? 1 : 2; // For ARMv8 exclusives the lifetime of the addr and data must be extended because // it may be used used multiple during retries assert(!tree->gtOp.gtOp1->isContained()); LocationInfoListNode* op1Info = getLocationInfo(tree->gtOp.gtOp1); op1Info->info.isDelayFree = true; useList.Append(op1Info); if (!tree->gtOp.gtOp2->isContained()) { LocationInfoListNode* op2Info = getLocationInfo(tree->gtOp.gtOp2); op2Info->info.isDelayFree = true; useList.Append(op2Info); } info->hasDelayFreeSrc = true; // Internals may not collide with target info->isInternalRegDelayFree = true; } break; case GT_PUTARG_STK: TreeNodeInfoInitPutArgStk(tree->AsPutArgStk(), info); break; case GT_PUTARG_REG: TreeNodeInfoInitPutArgReg(tree->AsUnOp(), info); break; case GT_CALL: TreeNodeInfoInitCall(tree->AsCall(), info); break; case GT_ADDR: { // For a GT_ADDR, the child node should not be evaluated into a register GenTreePtr child = tree->gtOp.gtOp1; assert(!isCandidateLocalRef(child)); assert(child->isContained()); assert(info->dstCount == 1); info->srcCount = 0; } break; case GT_BLK: case GT_DYN_BLK: // These should all be eliminated prior to Lowering. assert(!"Non-store block node in Lowering"); info->srcCount = 0; break; case GT_STORE_BLK: case GT_STORE_OBJ: case GT_STORE_DYN_BLK: TreeNodeInfoInitBlockStore(tree->AsBlk(), info); break; case GT_INIT_VAL: // Always a passthrough of its child's value. assert(!"INIT_VAL should always be contained"); break; case GT_LCLHEAP: { assert(info->dstCount == 1); // Need a variable number of temp regs (see genLclHeap() in codegenamd64.cpp): // Here '-' means don't care. // // Size? Init Memory? # temp regs // 0 - 0 // const and <=6 ptr words - 0 // const and <PageSize No 0 // >6 ptr words Yes hasPspSym ? 1 : 0 // Non-const Yes hasPspSym ? 1 : 0 // Non-const No 2 // // PSPSym - If the method has PSPSym increment internalIntCount by 1. // bool hasPspSym; #if FEATURE_EH_FUNCLETS hasPspSym = (compiler->lvaPSPSym != BAD_VAR_NUM); #else hasPspSym = false; #endif GenTreePtr size = tree->gtOp.gtOp1; if (size->IsCnsIntOrI()) { assert(size->isContained()); info->srcCount = 0; size_t sizeVal = size->gtIntCon.gtIconVal; if (sizeVal == 0) { info->internalIntCount = 0; } else { // Compute the amount of memory to properly STACK_ALIGN. // Note: The Gentree node is not updated here as it is cheap to recompute stack aligned size. // This should also help in debugging as we can examine the original size specified with // localloc. sizeVal = AlignUp(sizeVal, STACK_ALIGN); size_t cntStackAlignedWidthItems = (sizeVal >> STACK_ALIGN_SHIFT); // For small allocations upto 4 'stp' instructions (i.e. 64 bytes of localloc) // if (cntStackAlignedWidthItems <= 4) { info->internalIntCount = 0; } else if (!compiler->info.compInitMem) { // No need to initialize allocated stack space. if (sizeVal < compiler->eeGetPageSize()) { info->internalIntCount = 0; } else { // We need two registers: regCnt and RegTmp info->internalIntCount = 2; } } else { // greater than 4 and need to zero initialize allocated stack space. // If the method has PSPSym, we need an internal register to hold regCnt // since targetReg allocated to GT_LCLHEAP node could be the same as one of // the the internal registers. info->internalIntCount = hasPspSym ? 1 : 0; } } } else { appendLocationInfoToList(size); info->srcCount = 1; if (!compiler->info.compInitMem) { info->internalIntCount = 2; } else { // If the method has PSPSym, we need an internal register to hold regCnt // since targetReg allocated to GT_LCLHEAP node could be the same as one of // the the internal registers. info->internalIntCount = hasPspSym ? 1 : 0; } } // If the method has PSPSym, we would need an addtional register to relocate it on stack. if (hasPspSym) { // Exclude const size 0 if (!size->IsCnsIntOrI() || (size->gtIntCon.gtIconVal > 0)) info->internalIntCount++; } } break; case GT_ARR_BOUNDS_CHECK: #ifdef FEATURE_SIMD case GT_SIMD_CHK: #endif // FEATURE_SIMD { GenTreeBoundsChk* node = tree->AsBoundsChk(); // Consumes arrLen & index - has no result assert(info->dstCount == 0); GenTree* intCns = nullptr; GenTree* other = nullptr; info->srcCount = GetOperandInfo(tree->AsBoundsChk()->gtIndex); info->srcCount += GetOperandInfo(tree->AsBoundsChk()->gtArrLen); } break; case GT_ARR_ELEM: // These must have been lowered to GT_ARR_INDEX noway_assert(!"We should never see a GT_ARR_ELEM in lowering"); info->srcCount = 0; assert(info->dstCount == 0); break; case GT_ARR_INDEX: { info->srcCount = 2; assert(info->dstCount == 1); info->internalIntCount = 1; info->isInternalRegDelayFree = true; // For GT_ARR_INDEX, the lifetime of the arrObj must be extended because it is actually used multiple // times while the result is being computed. LocationInfoListNode* arrObjInfo = getLocationInfo(tree->AsArrIndex()->ArrObj()); arrObjInfo->info.isDelayFree = true; useList.Append(arrObjInfo); useList.Append(getLocationInfo(tree->AsArrIndex()->IndexExpr())); info->hasDelayFreeSrc = true; } break; case GT_ARR_OFFSET: // This consumes the offset, if any, the arrObj and the effective index, // and produces the flattened offset for this dimension. info->srcCount = 2; if (!tree->gtArrOffs.gtOffset->isContained()) { appendLocationInfoToList(tree->AsArrOffs()->gtOffset); info->srcCount++; } appendLocationInfoToList(tree->AsArrOffs()->gtIndex); appendLocationInfoToList(tree->AsArrOffs()->gtArrObj); assert(info->dstCount == 1); info->internalIntCount = 1; break; case GT_LEA: { GenTreeAddrMode* lea = tree->AsAddrMode(); GenTree* base = lea->Base(); GenTree* index = lea->Index(); int cns = lea->Offset(); // This LEA is instantiating an address, so we set up the srcCount here. info->srcCount = 0; if (base != nullptr) { info->srcCount++; appendLocationInfoToList(base); } if (index != nullptr) { info->srcCount++; appendLocationInfoToList(index); } assert(info->dstCount == 1); // On ARM64 we may need a single internal register // (when both conditions are true then we still only need a single internal register) if ((index != nullptr) && (cns != 0)) { // ARM64 does not support both Index and offset so we need an internal register info->internalIntCount = 1; } else if (!emitter::emitIns_valid_imm_for_add(cns, EA_8BYTE)) { // This offset can't be contained in the add instruction, so we need an internal register info->internalIntCount = 1; } } break; case GT_STOREIND: { assert(info->dstCount == 0); if (compiler->codeGen->gcInfo.gcIsWriteBarrierAsgNode(tree)) { info->srcCount = 2; TreeNodeInfoInitGCWriteBarrier(tree, info); break; } TreeNodeInfoInitIndir(tree->AsIndir(), info); if (!tree->gtGetOp2()->isContained()) { appendLocationInfoToList(tree->gtGetOp2()); info->srcCount++; } } break; case GT_NULLCHECK: // Unlike ARM, ARM64 implements NULLCHECK as a load to REG_ZR, so no internal register // is required, and it is not a localDefUse. assert(info->dstCount == 0); assert(!tree->gtGetOp1()->isContained()); appendLocationInfoToList(tree->gtOp.gtOp1); info->srcCount = 1; break; case GT_IND: assert(info->dstCount == 1); TreeNodeInfoInitIndir(tree->AsIndir(), info); break; case GT_CATCH_ARG: info->srcCount = 0; assert(info->dstCount == 1); info->setDstCandidates(this, RBM_EXCEPTION_OBJECT); break; case GT_CLS_VAR: info->srcCount = 0; // GT_CLS_VAR, by the time we reach the backend, must always // be a pure use. // It will produce a result of the type of the // node, and use an internal register for the address. assert(info->dstCount == 1); assert((tree->gtFlags & (GTF_VAR_DEF | GTF_VAR_USEASG)) == 0); info->internalIntCount = 1; break; case GT_INDEX_ADDR: assert(info->dstCount == 1); info->srcCount = appendBinaryLocationInfoToList(tree->AsOp()); info->internalIntCount = 1; break; } // end switch (tree->OperGet()) if (tree->IsUnusedValue() && (info->dstCount != 0)) { info->isLocalDefUse = true; } // We need to be sure that we've set info->srcCount and info->dstCount appropriately assert((info->dstCount < 2) || tree->IsMultiRegCall()); assert(info->isLocalDefUse == (tree->IsValue() && tree->IsUnusedValue())); assert(!tree->IsUnusedValue() || (info->dstCount != 0)); assert(info->dstCount == tree->GetRegisterDstCount()); } //------------------------------------------------------------------------ // TreeNodeInfoInitReturn: Set the NodeInfo for a GT_RETURN. // // Arguments: // tree - The node of interest // // Return Value: // None. // void LinearScan::TreeNodeInfoInitReturn(GenTree* tree, TreeNodeInfo* info) { GenTree* op1 = tree->gtGetOp1(); regMaskTP useCandidates = RBM_NONE; info->srcCount = ((tree->TypeGet() == TYP_VOID) || op1->isContained()) ? 0 : 1; assert(info->dstCount == 0); if ((tree->TypeGet() != TYP_VOID) && !op1->isContained()) { if (varTypeIsStruct(tree)) { // op1 has to be either an lclvar or a multi-reg returning call if (op1->OperGet() != GT_LCL_VAR) { noway_assert(op1->IsMultiRegCall()); ReturnTypeDesc* retTypeDesc = op1->AsCall()->GetReturnTypeDesc(); info->srcCount = retTypeDesc->GetReturnRegCount(); useCandidates = retTypeDesc->GetABIReturnRegs(); } } else { // Non-struct type return - determine useCandidates switch (tree->TypeGet()) { case TYP_VOID: useCandidates = RBM_NONE; break; case TYP_FLOAT: useCandidates = RBM_FLOATRET; break; case TYP_DOUBLE: useCandidates = RBM_DOUBLERET; break; case TYP_LONG: useCandidates = RBM_LNGRET; break; default: useCandidates = RBM_INTRET; break; } } LocationInfoListNode* locationInfo = getLocationInfo(op1); if (useCandidates != RBM_NONE) { locationInfo->info.setSrcCandidates(this, useCandidates); } useList.Append(locationInfo); } } #ifdef FEATURE_SIMD //------------------------------------------------------------------------ // TreeNodeInfoInitSIMD: Set the NodeInfo for a GT_SIMD tree. // // Arguments: // tree - The GT_SIMD node of interest // // Return Value: // None. void LinearScan::TreeNodeInfoInitSIMD(GenTreeSIMD* simdTree, TreeNodeInfo* info) { // Only SIMDIntrinsicInit can be contained if (simdTree->isContained()) { assert(simdTree->gtSIMDIntrinsicID == SIMDIntrinsicInit); } assert(info->dstCount == 1); GenTree* op1 = simdTree->gtOp.gtOp1; GenTree* op2 = simdTree->gtOp.gtOp2; if (!op1->OperIs(GT_LIST)) { info->srcCount += GetOperandInfo(op1); } if ((op2 != nullptr) && !op2->isContained()) { info->srcCount += GetOperandInfo(op2); } switch (simdTree->gtSIMDIntrinsicID) { case SIMDIntrinsicInit: assert(info->srcCount == (simdTree->gtGetOp1()->isContained() ? 0 : 1)); break; case SIMDIntrinsicCast: case SIMDIntrinsicSqrt: case SIMDIntrinsicAbs: case SIMDIntrinsicConvertToSingle: case SIMDIntrinsicConvertToInt32: case SIMDIntrinsicConvertToDouble: case SIMDIntrinsicConvertToInt64: case SIMDIntrinsicWidenLo: case SIMDIntrinsicWidenHi: assert(info->srcCount == 1); break; case SIMDIntrinsicGetItem: { op1 = simdTree->gtGetOp1(); op2 = simdTree->gtGetOp2(); // We have an object and an index, either of which may be contained. if (!op2->IsCnsIntOrI() && (!op1->isContained() || op1->OperIsLocal())) { // If the index is not a constant and not contained or is a local // we will need a general purpose register to calculate the address info->internalIntCount = 1; // internal register must not clobber input index LocationInfoListNode* op2Info = (op1->isContained()) ? useList.Begin() : useList.GetSecond(INDEBUG(op2)); op2Info->info.isDelayFree = true; info->hasDelayFreeSrc = true; } if (!op2->IsCnsIntOrI() && (!op1->isContained())) { // If vector is not already in memory (contained) and the index is not a constant, // we will use the SIMD temp location to store the vector. compiler->getSIMDInitTempVarNum(); } } break; case SIMDIntrinsicAdd: case SIMDIntrinsicSub: case SIMDIntrinsicMul: case SIMDIntrinsicDiv: case SIMDIntrinsicBitwiseAnd: case SIMDIntrinsicBitwiseAndNot: case SIMDIntrinsicBitwiseOr: case SIMDIntrinsicBitwiseXor: case SIMDIntrinsicMin: case SIMDIntrinsicMax: case SIMDIntrinsicEqual: case SIMDIntrinsicLessThan: case SIMDIntrinsicGreaterThan: case SIMDIntrinsicLessThanOrEqual: case SIMDIntrinsicGreaterThanOrEqual: assert(info->srcCount == 2); break; case SIMDIntrinsicSetX: case SIMDIntrinsicSetY: case SIMDIntrinsicSetZ: case SIMDIntrinsicSetW: case SIMDIntrinsicNarrow: assert(info->srcCount == 2); // Op1 will write to dst before Op2 is free useList.GetSecond(INDEBUG(simdTree->gtGetOp2()))->info.isDelayFree = true; info->hasDelayFreeSrc = true; break; case SIMDIntrinsicInitN: { var_types baseType = simdTree->gtSIMDBaseType; info->srcCount = (short)(simdTree->gtSIMDSize / genTypeSize(baseType)); int initCount = 0; for (GenTree* list = op1; list != nullptr; list = list->gtGetOp2()) { assert(list->OperGet() == GT_LIST); GenTree* listItem = list->gtGetOp1(); assert(listItem->TypeGet() == baseType); assert(!listItem->isContained()); appendLocationInfoToList(listItem); initCount++; } assert(initCount == info->srcCount); if (varTypeIsFloating(simdTree->gtSIMDBaseType)) { // Need an internal register to stitch together all the values into a single vector in a SIMD reg. info->setInternalCandidates(this, RBM_ALLFLOAT); info->internalFloatCount = 1; } break; } case SIMDIntrinsicInitArray: // We have an array and an index, which may be contained. assert(info->srcCount == (simdTree->gtGetOp2()->isContained() ? 1 : 2)); break; case SIMDIntrinsicOpEquality: case SIMDIntrinsicOpInEquality: assert(info->srcCount == (simdTree->gtGetOp2()->isContained() ? 1 : 2)); info->setInternalCandidates(this, RBM_ALLFLOAT); info->internalFloatCount = 1; break; case SIMDIntrinsicDotProduct: assert(info->srcCount == 2); info->setInternalCandidates(this, RBM_ALLFLOAT); info->internalFloatCount = 1; break; case SIMDIntrinsicSelect: // TODO-ARM64-CQ Allow lowering to see SIMDIntrinsicSelect so we can generate BSL VC, VA, VB // bsl target register must be VC. Reserve a temp in case we need to shuffle things. // This will require a different approach, as GenTreeSIMD has only two operands. assert(!"SIMDIntrinsicSelect not yet supported"); assert(info->srcCount == 3); info->setInternalCandidates(this, RBM_ALLFLOAT); info->internalFloatCount = 1; break; case SIMDIntrinsicInitArrayX: case SIMDIntrinsicInitFixed: case SIMDIntrinsicCopyToArray: case SIMDIntrinsicCopyToArrayX: case SIMDIntrinsicNone: case SIMDIntrinsicGetCount: case SIMDIntrinsicGetOne: case SIMDIntrinsicGetZero: case SIMDIntrinsicGetAllOnes: case SIMDIntrinsicGetX: case SIMDIntrinsicGetY: case SIMDIntrinsicGetZ: case SIMDIntrinsicGetW: case SIMDIntrinsicInstEquals: case SIMDIntrinsicHWAccel: case SIMDIntrinsicWiden: case SIMDIntrinsicInvalid: assert(!"These intrinsics should not be seen during register allocation"); __fallthrough; default: noway_assert(!"Unimplemented SIMD node type."); unreached(); } } #endif // FEATURE_SIMD #endif // _TARGET_ARM64_ #endif // !LEGACY_BACKEND
35.244648
116
0.526305
[ "object", "vector" ]
abffa4ec5d62daa95c3cfcc3249162542827e46c
1,211
cc
C++
src/jw/leetcode/most_water/main.cc
wanyaworld/algo-study
d540e9a72bb251a6bf2b04bc3aa7edbf17bee974
[ "MIT" ]
1
2020-10-31T15:28:43.000Z
2020-10-31T15:28:43.000Z
src/jw/leetcode/most_water/main.cc
wanyaworld/algo-study
d540e9a72bb251a6bf2b04bc3aa7edbf17bee974
[ "MIT" ]
null
null
null
src/jw/leetcode/most_water/main.cc
wanyaworld/algo-study
d540e9a72bb251a6bf2b04bc3aa7edbf17bee974
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <stdlib.h> #include <unistd.h> using namespace std; class Solution { public: int min(int a, int b) { if (a < b) return a; return b; } int dnc(vector<int>& vec, int s, int e) { if (s >= e) return 0; int mid = (s + e) / 2; int l_max = dnc(vec, s, mid); int r_max = dnc(vec, mid + 1, e); int max; if (r_max > l_max) max = r_max; else max = l_max; int i = mid, j = mid, min_h = vec[mid]; while (1) { int h; if (i <= s && j >= e) break; if (j >= e) { i--; h = min(min_h, vec[i]); } else if (i <= s) { j++; h = min(min_h, vec[j]); } else if (i <= s || (vec[i - 1] <= vec[j + 1] && j < e)) { j++; h = min(min_h, vec[j]); } else if (j >= e || (vec[i - 1] >= vec[j + 1] && i > s)) { i--; h = min(min_h, vec[i]); } else { break; } min_h = h; int w = (j - i); int tmp = w * h; if (tmp > max) max = tmp; } return max; } int maxArea(vector<int>& height) { return dnc(height, 0, height.size() - 1); } }; int main() { vector<int> v {1,8,100,2,100}; Solution sl; cout << sl.maxArea(v) << endl; return 0; }
18.630769
61
0.463254
[ "vector" ]
28003911be6e6c824584a7bdd13fdbfc970ccd7e
5,503
hpp
C++
src/autonet/AutoNetServerImpl.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autonet/AutoNetServerImpl.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autonet/AutoNetServerImpl.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #pragma once #include "AutoNetServer.h" #include <json11/json11.hpp> #include <cctype> #include <map> #include <set> #include SYSTEM_ERROR_HEADER #include ARRAY_HEADER namespace autowiring { struct CoreObjectDescriptor; } // Protocol layer for AutoNet class AutoNetServerImpl: public AutoNetServer, public AutoNetTransportHandler { public: /// <summary> /// Constructs an AutoNet server with the default HTTP transport mechanism /// </summary> AutoNetServerImpl(void); /// <summary> /// Constructs an AutoNet server with the specified transport /// </summary> AutoNetServerImpl(std::unique_ptr<AutoNetTransport>&& transport); ~AutoNetServerImpl(); // Handle websocket messages void OnOpen(connection_hdl handle) override { } void OnClose(connection_hdl handle) override { *this += [this, handle] { this->m_Subscribers.erase(handle); }; } void OnMessage(AutoNetTransportHandler::connection_hdl hdl, const std::string& payload) override; // Functions from BasicThread virtual void Run(void) override; virtual void OnStop(void) override; // AutoNetServer overrides: void Breakpoint(std::string name) override; void HandleResumeFromBreakpoint(std::string name); /// <summary> /// Updates server when a new context is created /// </summary> /// <param name="pParent">The parent context, or nullptr if one does not exist</param> /// <param name="newCtxt">The new context</param> void NewContext(CoreContext* pParent, CoreContext& newCtxt); /// <summary> /// Updates server when a context has expired /// </summary> /// <param name="ctxt">The expired context</param> void ExpiredContext(CoreContext& ctxt); /// <summary> /// Updates server when a new object is created /// </summary> /// <param name="ctxt">Context containing the object</param> /// <param name="obj">The object</param> void NewObject(CoreContext& ctxt, const autowiring::CoreObjectDescriptor& obj); protected: /// <summary> /// Sends a message to specified client. /// </summary> /// <param name="hdl">Connection pointer on which to send message</param> /// <param name="pRecipient">Message name in CamelCase</param> /// <param name="args...">Arguments to be passed to client side event handler</param> /// <remarks> /// Client callback with same number of arguments passed here will be called /// </remarks> template<typename... Args> void SendMessage(AutoNetTransportHandler::connection_hdl hdl, const char* p_type, Args&&... args) { using json11::Json; Json msg = Json::object{ {"type", p_type}, {"args", Json::array{args...}} }; m_transport->Send(hdl, msg.dump()); } /// <summary> /// Broadcast a message to all subscribers. /// </summary> /// <param name="pRecipient">Message name in CamelCase</param> /// <param name="args...">An arg to be passed to client side event handler</param> template<typename ...Args> void BroadcastMessage(const char* p_type, Args&&... args) { for(auto ptr : m_Subscribers) SendMessage(ptr, p_type, std::forward<Args>(args)...); } // Send custom event to all clients void SendEvent(const std::string& event, const std::vector<std::string>& args) override; /// <summary> /// Called when a "Subscribe" event is sent from a client /// </summary> /// <param name="client">Client that sent event</param> void HandleSubscribe(AutoNetTransportHandler::connection_hdl hdl); /// <summary> /// Called when a "Unsubscribe" event is sent from a client /// </summary> /// <param name="client">Client that sent event</param> void HandleUnsubscribe(AutoNetTransportHandler::connection_hdl hdl); /// <summary> /// Assigns each context a unique ID number /// </summary> /// <param name="ctxt">Client that sent event</param> int ResolveContextID(CoreContext* ctxt); CoreContext* ResolveContextID(int id); /// <summary> /// Append a lambda to this queue that will poll CoreThreads for their utilization /// </summary> void PollThreadUtilization(std::chrono::milliseconds period); /******************************************* * Member variables * *******************************************/ // Set of all subscribers std::set<AutoNetTransportHandler::connection_hdl, std::owner_less<AutoNetTransportHandler::connection_hdl>> m_Subscribers; // one-to-one map of contexts to integers, and a lock because we use this in an unsynchronized setting autowiring::spin_lock m_lock; std::map<CoreContext*, int> m_ContextIDs; std::map<int, CoreContext*> m_ContextPtrs; // All ContextMembers std::map<std::string, std::function<void(void)>> m_AllTypes; // All CoreThreads struct ThreadStats { // Last amount of time the thread was known to be running std::chrono::milliseconds m_lastRuntimeKM; std::chrono::milliseconds m_lastRuntimeUM; }; std::map<std::weak_ptr<BasicThread>, ThreadStats, std::owner_less<std::weak_ptr<BasicThread>>> m_Threads; // Breakpoint functionality std::mutex m_breakpoint_mutex; std::condition_variable m_breakpoint_cv; std::set<std::string> m_breakpoints; // Transport layer for AutoNet std::unique_ptr<AutoNetTransport> m_transport; }; /// <summary> /// Equivalent to new AutoNetServerImpl /// </summary> AutoNetServer* NewAutoNetServerImpl(std::unique_ptr<AutoNetTransport>); AutoNetServer* NewAutoNetServerImpl(void);
32.755952
124
0.693258
[ "object", "vector" ]
28054f23e217ea16f710d45eafd096b14325afe7
5,848
cpp
C++
lib/Mutators/MutatorsFactory.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
null
null
null
lib/Mutators/MutatorsFactory.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
null
null
null
lib/Mutators/MutatorsFactory.cpp
clagah/mull
9b5a7824b4f3ecdeff64e3b77ee63db2b40b3f99
[ "Apache-2.0" ]
1
2019-06-10T02:43:04.000Z
2019-06-10T02:43:04.000Z
#include "mull/Mutators/MutatorsFactory.h" #include "mull/Mutators/AndOrReplacementMutator.h" #include "mull/Mutators/ConditionalsBoundaryMutator.h" #include "mull/Mutators/MathAddMutator.h" #include "mull/Mutators/MathDivMutator.h" #include "mull/Mutators/MathMulMutator.h" #include "mull/Mutators/MathSubMutator.h" #include "mull/Mutators/Mutator.h" #include "mull/Mutators/NegateConditionMutator.h" #include "mull/Mutators/RemoveVoidFunctionMutator.h" #include "mull/Mutators/ReplaceAssignmentMutator.h" #include "mull/Mutators/ReplaceCallMutator.h" #include "mull/Mutators/ScalarValueMutator.h" #include "mull/Logger.h" #include <llvm/ADT/STLExtras.h> #include <set> #include <sstream> using namespace mull; using namespace std; static const string MathMutatorsGroup = "math"; static const string ConditionalMutatorsGroup = "conditional"; static const string FunctionsMutatorsGroup = "functions"; static const string ConstantMutatorsGroup = "constant"; static const string DefaultMutatorsGroup = "default"; static const string ExperimentalMutatorsGroup = "experimental"; static const string CXXMutatorsGroup = "cxx"; static const string AllMutatorsGroup = "all"; static void expandGroups(const vector<string> &groups, const map<string, vector<string>> &mapping, set<string> &expandedGroups) { for (const string &group : groups) { if (mapping.count(group) == 0) { expandedGroups.insert(group); continue; } expandGroups(mapping.at(group), mapping, expandedGroups); } } MutatorsFactory::MutatorsFactory() { groupsMapping[ConditionalMutatorsGroup] = {AndOrReplacementMutator::ID, NegateConditionMutator::ID, ConditionalsBoundaryMutator::ID}; groupsMapping[MathMutatorsGroup] = {MathAddMutator::ID, MathSubMutator::ID, MathMulMutator::ID, MathDivMutator::ID}; groupsMapping[FunctionsMutatorsGroup] = {ReplaceCallMutator::ID, RemoveVoidFunctionMutator::ID}; groupsMapping[ConstantMutatorsGroup] = {ScalarValueMutator::ID}; groupsMapping[DefaultMutatorsGroup] = {MathAddMutator::ID, NegateConditionMutator::ID, RemoveVoidFunctionMutator::ID}; groupsMapping[ExperimentalMutatorsGroup] = { MathSubMutator::ID, MathMulMutator::ID, MathDivMutator::ID, AndOrReplacementMutator::ID, ReplaceAssignmentMutator::ID, ReplaceCallMutator::ID, ScalarValueMutator::ID, ConditionalsBoundaryMutator::ID}; groupsMapping[CXXMutatorsGroup] = {ConditionalsBoundaryMutator::ID}; groupsMapping[AllMutatorsGroup] = {DefaultMutatorsGroup, ExperimentalMutatorsGroup}; } void MutatorsFactory::init() { mutatorsMapping[MathAddMutator::ID] = make_unique<MathAddMutator>(); mutatorsMapping[MathSubMutator::ID] = make_unique<MathSubMutator>(); mutatorsMapping[MathDivMutator::ID] = make_unique<MathDivMutator>(); mutatorsMapping[MathMulMutator::ID] = make_unique<MathMulMutator>(); mutatorsMapping[NegateConditionMutator::ID] = make_unique<NegateConditionMutator>(); mutatorsMapping[AndOrReplacementMutator::ID] = make_unique<AndOrReplacementMutator>(); mutatorsMapping[ReplaceAssignmentMutator::ID] = make_unique<ReplaceAssignmentMutator>(); mutatorsMapping[ReplaceCallMutator::ID] = make_unique<ReplaceCallMutator>(); mutatorsMapping[RemoveVoidFunctionMutator::ID] = make_unique<RemoveVoidFunctionMutator>(); mutatorsMapping[ScalarValueMutator::ID] = make_unique<ScalarValueMutator>(); mutatorsMapping[ConditionalsBoundaryMutator::ID] = make_unique<ConditionalsBoundaryMutator>(); } vector<unique_ptr<Mutator>> MutatorsFactory::mutators(const vector<string> &groups) { /// We need to recreate all mutators in case this method called /// more than once. It does not happen during normal program execution, /// but happens a lot during testing init(); set<string> expandedGroups; if (groups.empty()) { expandGroups({DefaultMutatorsGroup}, groupsMapping, expandedGroups); } else { expandGroups(groups, groupsMapping, expandedGroups); } vector<unique_ptr<Mutator>> mutators; for (const string &group : expandedGroups) { if (mutatorsMapping.count(group) == 0) { Logger::error() << "Unknown mutator: '" << group << "'\n"; continue; } mutators.emplace_back(std::move(mutatorsMapping.at(group))); mutatorsMapping.erase(group); } if (mutators.empty()) { Logger::error() << "No valid mutators found in a config file.\n"; } return mutators; } /// Command Line Options std::string descriptionForGroup(const std::vector<std::string> &groupMembers) { if (groupMembers.empty()) { return std::string("empty group?"); } std::stringstream members; std::copy(groupMembers.begin(), groupMembers.end() - 1, std::ostream_iterator<std::string>(members, ", ")); members << *(groupMembers.end() - 1); return members.str(); } #include <iostream> std::vector<std::pair<std::string, std::string>> MutatorsFactory::commandLineOptions() { std::vector<std::pair<std::string, std::string>> options; for (auto &group : groupsMapping) { options.emplace_back(group.first, descriptionForGroup(group.second)); } std::set<std::string> mutatorsSet; std::vector<std::string> groups({AllMutatorsGroup}); expandGroups({AllMutatorsGroup}, groupsMapping, mutatorsSet); auto allMutators = mutators({AllMutatorsGroup}); for (auto &mutator : allMutators) { options.emplace_back(mutator->getUniqueIdentifier(), mutator->getDescription()); } return options; }
35.442424
79
0.701436
[ "vector" ]
28072372ee6aeeebfeb3e16a26f3010681dc8bdb
3,976
cpp
C++
src/TAO/API/types/users/status.cpp
bibbityjibbity/LLL-TAO
4073ba412f71bf27d21fd297497a7c276ebd2d67
[ "MIT" ]
null
null
null
src/TAO/API/types/users/status.cpp
bibbityjibbity/LLL-TAO
4073ba412f71bf27d21fd297497a7c276ebd2d67
[ "MIT" ]
null
null
null
src/TAO/API/types/users/status.cpp
bibbityjibbity/LLL-TAO
4073ba412f71bf27d21fd297497a7c276ebd2d67
[ "MIT" ]
null
null
null
/*__________________________________________________________________________________________ (c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++ (c) Copyright The Nexus Developers 2014 - 2019 Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. "ad vocem populi" - To the Voice of the People ____________________________________________________________________________________________*/ #include <LLD/include/global.h> #include <TAO/API/types/users.h> #include <TAO/Ledger/types/transaction.h> #include <TAO/Ledger/types/sigchain.h> #include <TAO/Ledger/types/mempool.h> #include <TAO/Ledger/types/sigchain.h> #include <Util/include/hex.h> /* Global TAO namespace. */ namespace TAO { /* API Layer namespace. */ namespace API { /* Get status information for the currently logged in user. */ json::json Users::Status(const json::json& params, bool fHelp) { /* JSON return value. */ json::json ret; /* Restrict Unlock to sessionless API */ if(config::fMultiuser.load()) throw APIException(-145, "Unlock not supported in multiuser mode"); /* Check default session (unlock only supported in single user mode). */ if(!mapSessions.count(0)) throw APIException(-11, "User not logged in."); /* Get the sigchain from map of users. */ memory::encrypted_ptr<TAO::Ledger::SignatureChain>& user = mapSessions[0]; uint256_t hashGenesis = user->Genesis(); /* populate response */ ret["username"] = user->UserName().c_str(); ret["genesis"] = hashGenesis.GetHex(); /* sig chain transaction count */ uint32_t nTransactions = 0; /* flag indicating recovery has been set */ bool fRecovery = false; /* Read the last transaction for the sig chain */ uint512_t hashLast = 0; if(LLD::Ledger->ReadLast(hashGenesis, hashLast, TAO::Ledger::FLAGS::MEMPOOL)) { /* Get the transaction from disk. */ TAO::Ledger::Transaction tx; if(!LLD::Ledger->ReadTx(hashLast, tx, TAO::Ledger::FLAGS::MEMPOOL)) throw APIException(-108, "Failed to read transaction"); /* Number of transactions is the last sequence number + 1 (since the sequence is 0 based) */ nTransactions = tx.nSequence + 1; /* Set recovery flag if recovery hash has been set on the last transaction in the chain */ fRecovery = tx.hashRecovery != 0; } /* populate fecovery flag */ ret["recovery"] = fRecovery; /* populate the transaction count */ ret["transactions"] = nTransactions; /* Get the notifications so that we can return the notification count. */ std::vector<std::tuple<TAO::Operation::Contract, uint32_t, uint256_t>> vContracts; GetOutstanding(hashGenesis, vContracts); /* Get any expired contracts not yet voided. */ GetExpired(hashGenesis, vContracts); ret["notifications"] = vContracts.size(); /* populate unlocked status */ json::json jsonUnlocked; jsonUnlocked["mining"] = !pActivePIN.IsNull() && pActivePIN->CanMine(); jsonUnlocked["notifications"] = !pActivePIN.IsNull() && pActivePIN->ProcessNotifications(); jsonUnlocked["staking"] = !pActivePIN.IsNull() && pActivePIN->CanStake(); jsonUnlocked["transactions"] = !pActivePIN.IsNull() && pActivePIN->CanTransact(); ret["unlocked"] = jsonUnlocked; return ret; } } }
37.158879
108
0.59507
[ "vector" ]
2808a6b377d87ad878efe021be3fff3ede29f374
15,278
cpp
C++
plugin/usdImagingCycles/engine.cpp
tangent-opensource/hdcycles
e77ca61afc78c376f82abfa4f63ebbba2a4ca8bc
[ "Apache-2.0", "BSD-3-Clause" ]
213
2020-08-17T18:55:32.000Z
2021-04-27T02:56:55.000Z
plugin/usdImagingCycles/engine.cpp
MaxSteven/hdBlackbird
e77ca61afc78c376f82abfa4f63ebbba2a4ca8bc
[ "Apache-2.0", "BSD-3-Clause" ]
80
2020-08-18T15:25:07.000Z
2021-05-04T18:20:09.000Z
plugin/usdImagingCycles/engine.cpp
MaxSteven/hdBlackbird
e77ca61afc78c376f82abfa4f63ebbba2a4ca8bc
[ "Apache-2.0", "BSD-3-Clause" ]
22
2020-08-17T21:05:55.000Z
2021-04-16T20:59:58.000Z
// Copyright 2020 Tangent Animation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "engine.h" #include <pxr/pxr.h> #include <pxr/usdImaging/usdImaging/delegate.h> #include <pxr/imaging/hd/engine.h> #include <pxr/imaging/hd/renderBuffer.h> #include <pxr/imaging/hd/renderIndex.h> #include <pxr/imaging/hd/rendererPlugin.h> #include <pxr/imaging/hd/rendererPluginRegistry.h> #include <pxr/imaging/hdx/renderSetupTask.h> #include <pxr/imaging/hdx/renderTask.h> #include <pxr/imaging/hgi/hgi.h> #include <pxr/imaging/hgi/tokens.h> #include <pxr/base/arch/systemInfo.h> #include <pxr/base/plug/plugin.h> #include <pxr/base/plug/registry.h> #include <pxr/usd/usdRender/settings.h> #include <pxr/usd/usdRender/spec.h> #include <pxr/usd/usd/common.h> #include <OpenImageIO/imageio.h> #include <tbb/task_scheduler_init.h> #ifdef USE_HBOOST # include <hboost/program_options.hpp> #else # include <boost/program_options.hpp> #endif PXR_NAMESPACE_OPEN_SCOPE namespace { HdTaskSharedPtrVector GetTasks(HdRenderIndex* renderIndex, const std::vector<SdfPath>& taskIds) { HdTaskSharedPtrVector tasks; tasks.reserve(taskIds.size()); for (const auto& taskId : taskIds) { const auto& task = renderIndex->GetTask(taskId); tasks.push_back(task); } return tasks; } bool IsConverged(const HdTaskSharedPtrVector& tasks) { bool converged = true; for (auto const& task : tasks) { std::shared_ptr<HdxTask> progressiveTask = std::dynamic_pointer_cast<HdxTask>(task); if (progressiveTask) { converged = converged && progressiveTask->IsConverged(); if (!converged) { break; } } } return converged; } } //namespace TF_DEFINE_PRIVATE_TOKENS(_tokens, (renderBufferDescriptor)); /// /// HdSceneDelegate provides Get only interface, but not Set. For tasks and render buffers we need to set parameters /// ParamsDelegate mimics setting behaviour. Tasks and Buffers are added to it and it's parameters are kept in /// the maps. /// class ParamsDelegate final : public HdSceneDelegate { public: ParamsDelegate(HdRenderIndex* parentIndex, SdfPath const& delegateID) : HdSceneDelegate(parentIndex, delegateID) { } template<typename T> void SetParameter(SdfPath const& id, TfToken const& key, T const& value) { _valueCacheMap[id][key] = value; } template<typename T> T GetParameter(SdfPath const& id, TfToken const& key) const { VtValue vParams; _ValueCache vCache; TF_VERIFY(TfMapLookup(_valueCacheMap, id, &vCache) && TfMapLookup(vCache, key, &vParams) && vParams.IsHolding<T>()); return vParams.Get<T>(); } VtValue Get(SdfPath const& id, TfToken const& key) override { _ValueCache* vcache = TfMapLookupPtr(_valueCacheMap, id); VtValue ret; if (vcache && TfMapLookup(*vcache, key, &ret)) { return ret; } TF_CODING_ERROR("%s:%s doesn't exist in the value cache\n", id.GetText(), key.GetText()); return VtValue(); } HdRenderBufferDescriptor GetRenderBufferDescriptor(SdfPath const& id) override { return GetParameter<HdRenderBufferDescriptor>(id, _tokens->renderBufferDescriptor); } private: using _ValueCache = TfHashMap<TfToken, VtValue, TfToken::HashFunctor>; using _ValueCacheMap = TfHashMap<SdfPath, _ValueCache, SdfPath::Hash>; _ValueCacheMap _valueCacheMap; }; UsdImagingBbEngine::~UsdImagingBbEngine() {} HdRendererPlugin* UsdImagingBbEngine::FindPlugin(std::string const& pluginName) { PlugRegistry& plug_registry = PlugRegistry::GetInstance(); TF_UNUSED(plug_registry); HdRendererPluginRegistry& plugin_registry = HdRendererPluginRegistry::GetInstance(); HdRendererPlugin* plugin = plugin_registry.GetRendererPlugin(TfToken{pluginName}); return plugin; } bool UsdImagingBbEngine::CreateDelegates(HdRendererPlugin* plugin, const HdRenderSettingsMap& render_settings) { // // Create Render Delegate // _renderDelegate = plugin->CreateRenderDelegate(render_settings); if (!_renderDelegate) { return false; } // // Create Render Index // _renderIndex = std::unique_ptr<HdRenderIndex>(HdRenderIndex::New(_renderDelegate, HdDriverVector {})); if (!_renderIndex) { return false; } // // Create Scene Delegate // const SdfPath sceneDelegateId = SdfPath::AbsoluteRootPath(); _sceneDelegate = std::make_unique<UsdImagingDelegate>(_renderIndex.get(), sceneDelegateId); _sceneDelegate->Populate(_stage->GetPseudoRoot()); // // Create Params Delegate // _paramsDelegate = std::make_unique<ParamsDelegate>(_renderIndex.get(), SdfPath { "/task_controller" }); // // Create Engine // _engine = std::make_unique<HdEngine>(); // // Render Buffers // _renderBufferId = SdfPath { "/task_controller/render_buffer" }; { _bufferIds.emplace_back("/task_controller/render_buffer"); _renderIndex->InsertBprim(HdPrimTypeTokens->renderBuffer, _paramsDelegate.get(), _renderBufferId); _renderBuffer = dynamic_cast<HdRenderBuffer*>( _renderIndex->GetBprim(HdPrimTypeTokens->renderBuffer, _renderBufferId)); HdRenderBufferDescriptor desc {}; desc.multiSampled = false; desc.format = HdFormatFloat32Vec4; _paramsDelegate->SetParameter(_renderBufferId, _tokens->renderBufferDescriptor, desc); } // // Tasks // HdRprimCollection collection = HdRprimCollection(HdTokens->geometry, HdReprSelector(HdReprTokens->hull)); collection.SetRootPath(SdfPath::AbsoluteRootPath()); _renderTaskId = SdfPath { "/task_controller/render_task" }; { _renderIndex->InsertTask<HdxRenderTask>(_paramsDelegate.get(), _renderTaskId); HdxRenderTaskParams params {}; params.viewport = GfVec4d(0, 0, 1200, 700); // AOV binding must not be empty, empty is assumed to be GL HdRenderPassAovBindingVector aov_binding; aov_binding.emplace_back(); aov_binding.back().aovName = HdAovTokens->color; aov_binding.back().renderBufferId = _renderBufferId; aov_binding.back().renderBuffer = _renderBuffer; params.aovBindings = aov_binding; _paramsDelegate->SetParameter(_renderTaskId, HdTokens->params, params); _paramsDelegate->SetParameter(_renderTaskId, HdTokens->collection, collection); _taskIds.push_back(_renderTaskId); } return true; } bool UsdImagingBbEngine::OpenUsdScene(const std::string& filename) { UsdStageRefPtr usdStage = UsdStage::Open(filename); if (!usdStage) { return false; } _stage = usdStage; return true; } void UsdImagingBbEngine::Render() { auto tasks = GetTasks(_renderIndex.get(), _taskIds); do { TF_PY_ALLOW_THREADS_IN_SCOPE(); _engine->Execute(&_sceneDelegate->GetRenderIndex(), &tasks); } while (!IsConverged(tasks)); } bool UsdImagingBbEngine::WriteToFile(const std::string& filename) const { using namespace OIIO; std::unique_ptr<ImageOutput> out = ImageOutput::create(filename); if (!out) { return false; } HdFormat format = _renderBuffer->GetFormat(); if (format != HdFormatFloat32Vec4) { return false; } void* data = _renderBuffer->Map(); unsigned int xres = _renderBuffer->GetWidth(); unsigned int yres = _renderBuffer->GetHeight(); ImageSpec spec(xres, yres, 4, TypeDesc::TypeFloat4); out->open(filename, spec); out->write_image(TypeDesc::FLOAT, data); out->close(); _renderBuffer->Unmap(); return true; } void UsdImagingBbEngine::SetCamera(const std::string& camera) { // confirm that camera exists SdfPath cameraId { camera }; HdSprim* cameraPrim = _renderIndex->GetSprim(HdPrimTypeTokens->camera, cameraId); if (!cameraPrim) { // TODO camera not found return; } auto tasks = GetTasks(_renderIndex.get(), _taskIds); for (auto& taskId : _taskIds) { const HdTaskSharedPtr& task = _renderIndex->GetTask(taskId); auto renderTask = dynamic_cast<const HdxRenderTask*>(task.get()); if (!renderTask) { continue; } // get existing params and update camera auto params = _paramsDelegate->GetParameter<HdxRenderTaskParams>(taskId, HdTokens->params); params.camera = SdfPath { camera }; _paramsDelegate->SetParameter(taskId, HdTokens->params, params); _renderIndex->GetChangeTracker().MarkTaskDirty(taskId, HdChangeTracker::DirtyParams); } } void UsdImagingBbEngine::SetResolution(int x, int y) { // iterate over buffers for (auto& bufferId : _bufferIds) { const HdBprim* buffer_prim = _renderIndex->GetBprim(HdPrimTypeTokens->renderBuffer, bufferId); if (!buffer_prim) { continue; } auto descr = _paramsDelegate->GetParameter<HdRenderBufferDescriptor>(bufferId, _tokens->renderBufferDescriptor); descr.dimensions = GfVec3i { x, y, 1 }; _paramsDelegate->SetParameter(bufferId, _tokens->renderBufferDescriptor, descr); } // iterate over tasks auto tasks = GetTasks(_renderIndex.get(), _taskIds); for (auto& taskId : _taskIds) { const HdTaskSharedPtr& task = _renderIndex->GetTask(taskId); auto renderTask = dynamic_cast<const HdxRenderTask*>(task.get()); if (!renderTask) { continue; } auto params = _paramsDelegate->GetParameter<HdxRenderTaskParams>(taskId, HdTokens->params); params.viewport = GfVec4d(0, 0, x, y); _paramsDelegate->SetParameter(taskId, HdTokens->params, params); _renderIndex->GetChangeTracker().MarkTaskDirty(taskId, HdChangeTracker::DirtyParams); } } bool UsdImagingBbEngine::ReadRenderSettings(const std::string& path, HdRenderSettingsMap& render_settings) { render_settings.clear(); // find settings UsdRenderSettings settings = UsdRenderSettings::Get(_stage, SdfPath{path}); if(!settings) { return false; } // convert attributes to Render Settings Map std::vector<UsdAttribute> attributes = settings.GetPrim().GetAuthoredAttributes(); for(auto& a : attributes) { std::cout << a.GetName() << " " << a.GetTypeName() << std::endl; VtValue value; a.Get(&value); render_settings[a.GetName()] = value; } // camera rel UsdRelationship cam_rel = settings.GetCameraRel(); if(cam_rel) { SdfPathVector targets; cam_rel.GetTargets(&targets); if(!targets.empty()) { std::string cam_rel_path = targets[0].GetString(); render_settings[HdTokens->camera] = cam_rel_path; } } return true; } PXR_NAMESPACE_CLOSE_SCOPE #include <iostream> PXR_NAMESPACE_USING_DIRECTIVE namespace po = BOOST_NS::program_options; using BOOST_NS::array; using Resolution = std::vector<int>; int main(int argc, char** argv) { // clang goes nuts here // clang-format off po::options_description desc {}; desc.add_options()("help", "Produce help message") ("usd-input", po::value<std::string>(), "The USD file for the scene") ("camera,c", po::value<std::string>(), "Render from the specified camera") ("output,o", po::value<std::string>(), "Output image") ("res,r", po::value<Resolution>(), "Image resolution (e.g. '--res 1280 720')") ("renderer,R", po::value<std::string>()->default_value("HdCyclesRendererPlugin"), "Choose a specific delegate. Default is Blackbird") ("threads,j",po::value<int>()->default_value(-1),"Choose an specific delegate. Default is Blackbird") ("settings,s",po::value<std::string>()->default_value("/Render/rendersettings1"),"Render using properties defined by node."); // clang-format on po::variables_map var_map; po::store(po::command_line_parser(argc, argv).options(desc).run(), var_map); po::notify(var_map); if (var_map.count("help")) { std::cout << desc << '\n'; return EXIT_SUCCESS; } if (!var_map.count("usd-input")) { std::cout << "Missing 'usd-input' argument!" << '\n'; std::cout << desc << '\n'; return EXIT_FAILURE; } if (!var_map.count("output")) { std::cout << "Missing 'output' argument!" << '\n'; std::cout << desc << '\n'; return EXIT_FAILURE; } // // initialize thread count // tbb::task_scheduler_init scheduler_init { var_map["threads"].as<int>() }; // create engine UsdImagingBbEngine engine; HdRendererPlugin* plugin = nullptr; // find renderer plugin { auto renderer = var_map["renderer"].as<std::string>(); plugin = engine.FindPlugin(renderer); if (!plugin) { std::cout << "Unable to create delegate with name: " << renderer << '\n'; return EXIT_FAILURE; } } // open usd scene { auto scene = var_map["usd-input"].as<std::string>(); if (!engine.OpenUsdScene(scene)) { std::cout << "Unable to open scene: " << scene << '\n'; return EXIT_FAILURE; } } // Read RenderSettings HdRenderSettingsMap render_settings; { auto path = var_map["settings"].as<std::string>(); if(!engine.ReadRenderSettings(path, render_settings)) { std::cout << "Unable to read render settings: " << path << '\n'; } } // create delegates { if (!engine.CreateDelegates(plugin, render_settings)) { std::cout << "Unable to create render and scene delegate\n"; return EXIT_FAILURE; } } // override properties from render settings, TODO: maybe there is a better option to feed them to a task. { for(auto& key_val : render_settings) { if(key_val.first == "camera") { engine.SetCamera(key_val.second.Get<std::string>()); } if(key_val.first == "resolution") { auto res = key_val.second.Get<GfVec2i>(); engine.SetResolution(res[0], res[1]); } } } engine.Render(); // write { auto output = var_map["output"].as<std::string>(); engine.WriteToFile(output); } return EXIT_SUCCESS; }
30.802419
141
0.65879
[ "geometry", "render", "vector" ]
280f5ca3c61426d35da5b99c5328413f1a0661b0
970
cpp
C++
aws-cpp-sdk-iot/source/model/PutItemInput.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-iot/source/model/PutItemInput.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-iot/source/model/PutItemInput.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iot/model/PutItemInput.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace IoT { namespace Model { PutItemInput::PutItemInput() : m_tableNameHasBeenSet(false) { } PutItemInput::PutItemInput(JsonView jsonValue) : m_tableNameHasBeenSet(false) { *this = jsonValue; } PutItemInput& PutItemInput::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("tableName")) { m_tableName = jsonValue.GetString("tableName"); m_tableNameHasBeenSet = true; } return *this; } JsonValue PutItemInput::Jsonize() const { JsonValue payload; if(m_tableNameHasBeenSet) { payload.WithString("tableName", m_tableName); } return payload; } } // namespace Model } // namespace IoT } // namespace Aws
16.166667
69
0.715464
[ "model" ]
28141db25dce5950487853d99e6efb4e70aecb43
5,431
cpp
C++
Dev-Cpp/OpenGL/Starfield/Main.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
1
2022-03-22T14:41:15.000Z
2022-03-22T14:41:15.000Z
Dev-Cpp/OpenGL/Starfield/Main.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
Dev-Cpp/OpenGL/Starfield/Main.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
#include <windows.h> #include <gl/gl.h> #include "iPhone/IP_Constants.h" #include "Classes/IP_Camera.h" #include "Classes/IP_Random.h" #include "Classes/IP_Star.h" #define GLInt int LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void EnableOpenGL(HWND hWnd, HDC *hDC, HGLRC *hRC); void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC); /** * WinMain */ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { WNDCLASS wc; HWND hWnd; HDC hDC; HGLRC hRC; MSG msg; BOOL bQuit = FALSE; float theta = 0.0f; // register window class wc.style = CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = ::LoadIcon(hInstance, "A"); wc.hCursor = ::LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = "MainForm"; RegisterClass(&wc); GLint backingWidth = (GLInt)(IP_Constants::m_OrthoScreen_X * 2.0f); GLint backingHeight = (GLInt)(IP_Constants::m_OrthoScreen_Y * 2.0f); // create main window hWnd = CreateWindow("MainForm", "Star field", WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, 0, 0, (unsigned)backingWidth, (unsigned)backingHeight, NULL, NULL, hInstance, NULL); /* enable OpenGL for the window */ EnableOpenGL(hWnd, &hDC, &hRC); // initialize starfield objects IP_Random::Initialize(); IP_Starfield starfield; unsigned char m_BackgroundR = 0; unsigned char m_BackgroundG = 0; unsigned char m_BackgroundB = 0; unsigned char m_ForegroundR = 255; unsigned char m_ForegroundG = 255; unsigned char m_ForegroundB = 255; float m_StarVelocity = 10.0f; float m_RotateVelocity = 0.0001f; unsigned m_StarsQuantity = 500; starfield.InitializeStars(m_StarsQuantity, (unsigned)(backingHeight + 150.0f), (unsigned)(backingHeight + 150.0f)); starfield.SetBackgroundColor(m_BackgroundR, m_BackgroundG, m_BackgroundB); starfield.SetStarsColor(m_ForegroundR, m_ForegroundG, m_ForegroundB); starfield.SetSpeedVelocity(m_StarVelocity); starfield.SetRotateVelocity(m_RotateVelocity); IP_Camera::CreateOrtho(backingWidth, backingHeight, M_StarDepth); std::clock_t last = std::clock(); /* program main loop */ while (!bQuit) { /* check for messages */ if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { /* handle or dispatch messages */ if (msg.message == WM_QUIT) bQuit = TRUE; else { TranslateMessage (&msg); DispatchMessage (&msg); } } else { std::clock_t now = std::clock(); if (now - last > 1) { last = now; float r = (float)m_BackgroundR / 255.0f; float g = (float)m_BackgroundG / 255.0f; float b = (float)m_BackgroundB / 255.0f; glClearColor(r, g, b, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); starfield.Render(backingWidth, backingHeight); SwapBuffers(hDC); } } } /* shutdown OpenGL */ DisableOpenGL(hWnd, hDC, hRC); /* destroy the window explicitly */ DestroyWindow(hWnd); return msg.wParam; } /** * Window Procedure */ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: return 0; case WM_CLOSE: PostQuitMessage (0); return 0; case WM_DESTROY: return 0; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: PostQuitMessage(0); return 0; } return 0; default: return DefWindowProc (hWnd, message, wParam, lParam); } } /** * Enable OpenGL */ void EnableOpenGL(HWND hWnd, HDC *hDC, HGLRC *hRC) { PIXELFORMATDESCRIPTOR pfd; int iFormat; //get the device context (DC) *hDC = GetDC(hWnd); /* set the pixel format for the DC */ ZeroMemory (&pfd, sizeof (pfd)); pfd.nSize = sizeof (pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; iFormat = ChoosePixelFormat (*hDC, &pfd); SetPixelFormat(*hDC, iFormat, &pfd); // create and enable the render context (RC) *hRC = wglCreateContext(*hDC); wglMakeCurrent(*hDC, *hRC); } /** * Disable OpenGL */ void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); ReleaseDC(hWnd, hDC); }
27.0199
81
0.561038
[ "render" ]
2817a197384726761d79555a3287121efb4a0aeb
2,090
cpp
C++
src/external/aws-sdk-cpp/aws-cpp-sdk-s3/source/model/CreateBucketConfiguration.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
2
2019-02-08T21:29:57.000Z
2021-07-27T06:59:19.000Z
src/external/aws-sdk-cpp/aws-cpp-sdk-s3/source/model/CreateBucketConfiguration.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
src/external/aws-sdk-cpp/aws-cpp-sdk-s3/source/model/CreateBucketConfiguration.cpp
ZeroInfinite/turicreate
dd210c2563930881abd51fd69cb73007955b33fd
[ "BSD-3-Clause" ]
1
2020-10-21T17:46:28.000Z
2020-10-21T17:46:28.000Z
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/s3/model/CreateBucketConfiguration.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace S3 { namespace Model { CreateBucketConfiguration::CreateBucketConfiguration() : m_locationConstraintHasBeenSet(false) { } CreateBucketConfiguration::CreateBucketConfiguration(const XmlNode& xmlNode) : m_locationConstraintHasBeenSet(false) { *this = xmlNode; } CreateBucketConfiguration& CreateBucketConfiguration::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode locationConstraintNode = resultNode.FirstChild("LocationConstraint"); if(!locationConstraintNode.IsNull()) { m_locationConstraint = BucketLocationConstraintMapper::GetBucketLocationConstraintForName(StringUtils::Trim(locationConstraintNode.GetText().c_str()).c_str()); m_locationConstraintHasBeenSet = true; } } return *this; } void CreateBucketConfiguration::AddToNode(XmlNode& parentNode) const { Aws::StringStream ss; if(m_locationConstraintHasBeenSet) { XmlNode locationConstraintNode = parentNode.CreateChildElement("LocationConstraint"); locationConstraintNode.SetText(BucketLocationConstraintMapper::GetNameForBucketLocationConstraint(m_locationConstraint)); } } } // namespace Model } // namespace S3 } // namespace Aws
28.243243
165
0.77177
[ "model" ]
281b3cdfe23acc97fd500a80ddb31c4c788af25d
54,933
cc
C++
mindspore/ccsrc/transform/op_declare.cc
doc22940/mindspore
21bcdcd8adb97b9171b2822a7ed2c4c138c99607
[ "Apache-2.0" ]
1
2020-05-13T11:31:21.000Z
2020-05-13T11:31:21.000Z
mindspore/ccsrc/transform/op_declare.cc
doc22940/mindspore
21bcdcd8adb97b9171b2822a7ed2c4c138c99607
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/transform/op_declare.cc
doc22940/mindspore
21bcdcd8adb97b9171b2822a7ed2c4c138c99607
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "transform/op_declare.h" #include <vector> #include "transform/all_ops.h" #include "utils/utils.h" namespace mindspore { namespace transform { #define INPUT_MAP(T) \ template <> \ const std::unordered_map<int, InputDesc> OpAdapter<T>::input_map_ #define EMPTY_INPUT_MAP std::unordered_map<int, InputDesc>() #define INPUT_DESC(name) \ { \ #name, \ [](const OperatorPtr op, const OperatorPtr input) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->set_input_##name(*input); \ }, \ [](const OperatorPtr op, const OutHandler& handle) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->set_input_##name(*(handle.op), handle.out); \ }, \ [](const OperatorPtr op, const GeTensorDesc desc) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->update_input_desc_##name(desc); \ } \ } #define DYN_INPUT_MAP(T) \ template <> \ const std::unordered_map<int, DynInputDesc> OpAdapter<T>::dyn_input_map_ #define DYN_INPUT_DESC(name) \ { \ #name, \ [](const OperatorPtr op, unsigned int num) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->create_dynamic_input_##name(num); \ }, \ [](const OperatorPtr op, unsigned int index, const OperatorPtr input) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->set_dynamic_input_##name(index, *input); \ }, \ [](const OperatorPtr op, unsigned int index, const OutHandler& handle) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->set_dynamic_input_##name(index, *(handle.op), handle.out); \ } \ } #define ATTR_MAP(T) \ template <> \ const std::unordered_map<std::string, AttrDesc> OpAdapter<T>::attr_map_ #define EMPTY_ATTR_MAP std::unordered_map<std::string, AttrDesc>() #define ATTR_DESC(name, ...) \ { \ #name, \ [](const OperatorPtr op, const ValuePtr& value) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->set_attr_##name(ConvertAny(value, __VA_ARGS__)); \ } \ } #define INPUT_ATTR_MAP(T) \ template <> \ const std::unordered_map<unsigned int, AttrDesc> OpAdapter<T>::input_attr_map_ #define OUTPUT_MAP(T) \ template <> \ const std::unordered_map<int, OutputDesc> OpAdapter<T>::output_map_ #define OUTPUT_DESC(name) \ { \ #name, \ [](const OperatorPtr op, const GeTensorDesc desc) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->update_output_desc_##name(desc); \ } \ } #define DYN_OUTPUT_MAP(T) \ template <> \ const std::unordered_map<int, DynOutputDesc> OpAdapter<T>::dyn_output_map_ #define DYN_OUTPUT_DESC(name) \ { \ #name, \ [](const OperatorPtr op, unsigned int num) { \ auto p = std::static_pointer_cast<OpType>(op); \ (void)p->create_dynamic_output_##name(num); \ } \ } template <> std::unordered_map<std::string, std::unordered_map<int, std::string>> OpAdapter<ge::Operator>::cus_input_map_{}; template <> std::unordered_map<std::string, std::unordered_map<int, std::string>> OpAdapter<ge::Operator>::cus_output_map_{}; // --------------specialization for each operator---------- // const INPUT_MAP(Const) = EMPTY_INPUT_MAP; ATTR_MAP(Const) = {{"value", ATTR_DESC(value, AnyTraits<AnyValue>())}}; OUTPUT_MAP(Const) = {{0, OUTPUT_DESC(y)}}; // Assign INPUT_MAP(Assign) = {{1, INPUT_DESC(ref)}, {2, INPUT_DESC(value)}}; ATTR_MAP(Assign) = EMPTY_ATTR_MAP; OUTPUT_MAP(Assign) = {{0, OUTPUT_DESC(ref)}}; // Constant INPUT_MAP(Constant) = EMPTY_INPUT_MAP; ATTR_MAP(Constant) = {{"value", ATTR_DESC(value, AnyTraits<AnyValue>())}}; OUTPUT_MAP(Constant) = {{0, OUTPUT_DESC(y)}}; // ApplyMomentumD INPUT_MAP(ApplyMomentumD) = { {1, INPUT_DESC(var)}, {2, INPUT_DESC(accum)}, {3, INPUT_DESC(lr)}, {4, INPUT_DESC(grad)}, {5, INPUT_DESC(momentum)}}; ATTR_MAP(ApplyMomentumD) = {{"use_nesterov", ATTR_DESC(use_nesterov, AnyTraits<bool>())}, {"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}}; OUTPUT_MAP(ApplyMomentumD) = {{0, OUTPUT_DESC(var)}, {1, OUTPUT_DESC(accum)}}; // ScalarSummary INPUT_MAP(Summary) = {{2, INPUT_DESC(x)}}; ATTR_MAP(Summary) = EMPTY_ATTR_MAP; // Data INPUT_MAP(Data) = EMPTY_INPUT_MAP; ATTR_MAP(Data) = EMPTY_ATTR_MAP; // BatchNorm INPUT_MAP(BatchNorm) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(scale)}, {3, INPUT_DESC(offset)}, {4, INPUT_DESC(mean)}, {5, INPUT_DESC(variance)}}; ATTR_MAP(BatchNorm) = {{"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}, {"epsilon", ATTR_DESC(epsilon, AnyTraits<float>())}, {"is_training", ATTR_DESC(is_training, AnyTraits<bool>())}}; OUTPUT_MAP(BatchNorm) = {{0, OUTPUT_DESC(y)}, {1, OUTPUT_DESC(batch_mean)}, {2, OUTPUT_DESC(batch_variance)}, {3, OUTPUT_DESC(reserve_space_1)}, {4, OUTPUT_DESC(reserve_space_2)}}; // BatchNormGrad INPUT_MAP(BatchNormGrad) = {{1, INPUT_DESC(y_backprop)}, {2, INPUT_DESC(x)}, {3, INPUT_DESC(scale)}, {4, INPUT_DESC(reserve_space_1)}, {5, INPUT_DESC(reserve_space_2)}}; ATTR_MAP(BatchNormGrad) = {{"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}, {"epsilon", ATTR_DESC(epsilon, AnyTraits<float>())}, {"is_training", ATTR_DESC(is_training, AnyTraits<bool>())}}; OUTPUT_MAP(BatchNormGrad) = {{0, OUTPUT_DESC(x_backprop)}, {1, OUTPUT_DESC(scale_backprop)}, {2, OUTPUT_DESC(offset_backprop)}, {3, OUTPUT_DESC(reserve_space_4)}, {4, OUTPUT_DESC(reserve_space_5)}}; // Relu INPUT_MAP(Relu) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Relu) = EMPTY_ATTR_MAP; OUTPUT_MAP(Relu) = {{0, OUTPUT_DESC(y)}}; // Elu INPUT_MAP(Elu) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Elu) = {{"alpha", ATTR_DESC(alpha, AnyTraits<float>())}}; OUTPUT_MAP(Elu) = {{0, OUTPUT_DESC(y)}}; // EluGrad INPUT_MAP(EluGrad) = {{1, INPUT_DESC(grads)}, {2, INPUT_DESC(activations)}}; ATTR_MAP(EluGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(EluGrad) = {{0, OUTPUT_DESC(y)}}; // PRelu INPUT_MAP(PRelu) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(weight)}}; ATTR_MAP(PRelu) = EMPTY_ATTR_MAP; OUTPUT_MAP(PRelu) = {{0, OUTPUT_DESC(y)}}; // PReluGrad INPUT_MAP(PReluGrad) = {{1, INPUT_DESC(grads)}, {2, INPUT_DESC(features)}, {3, INPUT_DESC(weights)}}; ATTR_MAP(PReluGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(PReluGrad) = {{0, OUTPUT_DESC(dx)}, {1, OUTPUT_DESC(da)}}; // Sigmoid INPUT_MAP(Sigmoid) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Sigmoid) = EMPTY_ATTR_MAP; OUTPUT_MAP(Sigmoid) = {{0, OUTPUT_DESC(y)}}; // SigmoidGrad INPUT_MAP(SigmoidGrad) = {{1, INPUT_DESC(y)}, {2, INPUT_DESC(dy)}}; ATTR_MAP(SigmoidGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(SigmoidGrad) = {{0, OUTPUT_DESC(z)}}; // L2NormalizeGrad INPUT_MAP(L2NormalizeGrad) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(y)}, {3, INPUT_DESC(dy)}}; ATTR_MAP(L2NormalizeGrad) = { {"axis", ATTR_DESC(dim, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"epsilon", ATTR_DESC(eps, AnyTraits<float>())}}; OUTPUT_MAP(L2NormalizeGrad) = {{0, OUTPUT_DESC(dx)}}; // LarsV2Update INPUT_MAP(LarsV2Update) = {{1, INPUT_DESC(w)}, {2, INPUT_DESC(g)}, {3, INPUT_DESC(w_square_sum)}, {4, INPUT_DESC(g_square_sum)}, {5, INPUT_DESC(weight_decay)}, {6, INPUT_DESC(learning_rate)}}; ATTR_MAP(LarsV2Update) = {{"epsilon", ATTR_DESC(epsilon, AnyTraits<float>())}, {"hyperpara", ATTR_DESC(hyperpara, AnyTraits<float>())}, {"use_clip", ATTR_DESC(use_clip, AnyTraits<bool>())}}; OUTPUT_MAP(LarsV2Update) = {{0, OUTPUT_DESC(g_new)}}; // L2Normalize INPUT_MAP(L2Normalize) = {{1, INPUT_DESC(x)}}; ATTR_MAP(L2Normalize) = { {"axis", ATTR_DESC(axis, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"epsilon", ATTR_DESC(eps, AnyTraits<float>())}}; OUTPUT_MAP(L2Normalize) = {{0, OUTPUT_DESC(y)}}; // CumsumD INPUT_MAP(CumsumD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(CumsumD) = {{2, ATTR_DESC(axis, AnyTraits<int64_t>())}}; ATTR_MAP(CumsumD) = {{"exclusive", ATTR_DESC(exclusive, AnyTraits<bool>())}, {"reverse", ATTR_DESC(reverse, AnyTraits<bool>())}}; OUTPUT_MAP(CumsumD) = {{0, OUTPUT_DESC(y)}}; // SoftmaxV2 INPUT_MAP(SoftmaxV2) = {{1, INPUT_DESC(x)}}; ATTR_MAP(SoftmaxV2) = { {"axis", ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, }; OUTPUT_MAP(SoftmaxV2) = {{0, OUTPUT_DESC(y)}}; // SoftmaxGrad INPUT_MAP(SoftmaxGrad) = {{1, INPUT_DESC(softmax)}, {2, INPUT_DESC(grad_softmax)}}; OUTPUT_MAP(SoftmaxGrad) = {{0, OUTPUT_DESC(grad_x)}}; ATTR_MAP(SoftmaxGrad) = EMPTY_ATTR_MAP; // Flatten INPUT_MAP(Flatten) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Flatten) = EMPTY_ATTR_MAP; OUTPUT_MAP(Flatten) = {{0, OUTPUT_DESC(y)}}; // add INPUT_MAP(Add) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Add) = EMPTY_ATTR_MAP; OUTPUT_MAP(Add) = {{0, OUTPUT_DESC(y)}}; // GatherV2 INPUT_MAP(GatherV2) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(indices)}, {3, INPUT_DESC(axis)}}; ATTR_MAP(GatherV2) = EMPTY_ATTR_MAP; OUTPUT_MAP(GatherV2) = {{0, OUTPUT_DESC(y)}}; // ReduceSumD INPUT_MAP(ReduceSumD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(ReduceSumD) = { {2, ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(ReduceSumD) = {{"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ReduceSumD) = {{0, OUTPUT_DESC(y)}}; // ReduceProdD INPUT_MAP(ReduceProdD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(ReduceProdD) = { {2, ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(ReduceProdD) = {{"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ReduceProdD) = {{0, OUTPUT_DESC(y)}}; // CumprodD INPUT_MAP(CumprodD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(CumprodD) = {{2, ATTR_DESC(axis, AnyTraits<int64_t>())}}; ATTR_MAP(CumprodD) = {{"exclusive", ATTR_DESC(exclusive, AnyTraits<bool>())}, {"reverse", ATTR_DESC(reverse, AnyTraits<bool>())}}; OUTPUT_MAP(CumprodD) = {{0, OUTPUT_DESC(y)}}; // SoftmaxCrossEntropyWithLogits INPUT_MAP(SoftmaxCrossEntropyWithLogits) = {{1, INPUT_DESC(features)}, {2, INPUT_DESC(labels)}}; ATTR_MAP(SoftmaxCrossEntropyWithLogits) = EMPTY_ATTR_MAP; OUTPUT_MAP(SoftmaxCrossEntropyWithLogits) = {{0, OUTPUT_DESC(loss)}, {1, OUTPUT_DESC(backprop)}}; // MeanGrad INPUT_MAP(MeanGrad) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(MeanGrad) = {{2, ATTR_DESC(mean_grad_output_shape_value, kOpFormat_NHWC, AnyTraits<std::vector<int64_t>>(), AnyTraits<int64_t>())}}; ATTR_MAP(MeanGrad) = {{"mode", ATTR_DESC(mode, AnyTraits<int64_t>())}}; INPUT_MAP(SliceD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(SliceD) = {{2, ATTR_DESC(offsets, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {3, ATTR_DESC(size, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(SliceD) = EMPTY_ATTR_MAP; OUTPUT_MAP(SliceD) = {{0, OUTPUT_DESC(y)}}; // MaxPool INPUT_MAP(MaxPool) = {{1, INPUT_DESC(x)}}; ATTR_MAP(MaxPool) = {{"ksize", ATTR_DESC(ksize, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"strides", ATTR_DESC(strides, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"padding", ATTR_DESC(padding, AnyTraits<std::string>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}}; OUTPUT_MAP(MaxPool) = {{0, OUTPUT_DESC(y)}}; // AvgPool INPUT_MAP(AvgPool) = {{1, INPUT_DESC(x)}}; ATTR_MAP(AvgPool) = {{"ksize", ATTR_DESC(ksize, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"strides", ATTR_DESC(strides, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"padding", ATTR_DESC(padding, AnyTraits<std::string>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}}; OUTPUT_MAP(AvgPool) = {{0, OUTPUT_DESC(y)}}; // GreaterEqual INPUT_MAP(GreaterEqual) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(GreaterEqual) = EMPTY_ATTR_MAP; OUTPUT_MAP(GreaterEqual) = {{0, OUTPUT_DESC(y)}}; // AssignAdd INPUT_MAP(AssignAdd) = {{1, INPUT_DESC(ref)}, {2, INPUT_DESC(value)}}; ATTR_MAP(AssignAdd) = EMPTY_ATTR_MAP; OUTPUT_MAP(AssignAdd) = {{0, OUTPUT_DESC(ref)}}; // AssignSub INPUT_MAP(AssignSub) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(value)}}; ATTR_MAP(AssignSub) = EMPTY_ATTR_MAP; OUTPUT_MAP(AssignSub) = {{0, OUTPUT_DESC(var)}}; // Cos INPUT_MAP(Cos) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Cos) = EMPTY_ATTR_MAP; OUTPUT_MAP(Cos) = {{0, OUTPUT_DESC(y)}}; // Acos INPUT_MAP(Acos) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Acos) = EMPTY_ATTR_MAP; OUTPUT_MAP(Acos) = {{0, OUTPUT_DESC(y)}}; // AcosGrad INPUT_MAP(AcosGrad) = {{1, INPUT_DESC(y)}, {2, INPUT_DESC(dy)}}; ATTR_MAP(AcosGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(AcosGrad) = {{0, OUTPUT_DESC(z)}}; // Acosh INPUT_MAP(Acosh) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Acosh) = EMPTY_ATTR_MAP; OUTPUT_MAP(Acosh) = {{0, OUTPUT_DESC(y)}}; // AcoshGrad INPUT_MAP(AcoshGrad) = {{1, INPUT_DESC(y)}, {2, INPUT_DESC(dy)}}; ATTR_MAP(AcoshGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(AcoshGrad) = {{0, OUTPUT_DESC(z)}}; // Floor INPUT_MAP(Floor) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Floor) = EMPTY_ATTR_MAP; OUTPUT_MAP(Floor) = {{0, OUTPUT_DESC(y)}}; // FloorDiv INPUT_MAP(FloorDiv) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(FloorDiv) = EMPTY_ATTR_MAP; OUTPUT_MAP(FloorDiv) = {{0, OUTPUT_DESC(y)}}; // FloorMod INPUT_MAP(FloorMod) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(FloorMod) = EMPTY_ATTR_MAP; OUTPUT_MAP(FloorMod) = {{0, OUTPUT_DESC(y)}}; // Sin INPUT_MAP(Sin) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Sin) = EMPTY_ATTR_MAP; OUTPUT_MAP(Sin) = {{0, OUTPUT_DESC(y)}}; // Exp INPUT_MAP(Exp) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Exp) = EMPTY_ATTR_MAP; OUTPUT_MAP(Exp) = {{0, OUTPUT_DESC(y)}}; // BoundingBoxEncode INPUT_MAP(BoundingBoxEncode) = { {1, INPUT_DESC(anchor_box)}, {2, INPUT_DESC(ground_truth_box)}, }; ATTR_MAP(BoundingBoxEncode) = { {"means", ATTR_DESC(means, AnyTraits<std::vector<float>>(), AnyTraits<float>())}, {"stds", ATTR_DESC(stds, AnyTraits<std::vector<float>>(), AnyTraits<float>())}, }; OUTPUT_MAP(BoundingBoxEncode) = {{0, OUTPUT_DESC(delats)}}; // BoundingBoxDecode INPUT_MAP(BoundingBoxDecode) = { {1, INPUT_DESC(rois)}, {2, INPUT_DESC(deltas)}, }; ATTR_MAP(BoundingBoxDecode) = { {"means", ATTR_DESC(means, AnyTraits<std::vector<float>>(), AnyTraits<float>())}, {"stds", ATTR_DESC(stds, AnyTraits<std::vector<float>>(), AnyTraits<float>())}, {"max_shape", ATTR_DESC(max_shape, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"wh_ratio_clip", ATTR_DESC(wh_ratio_clip, AnyTraits<float>())}, }; OUTPUT_MAP(BoundingBoxDecode) = {{0, OUTPUT_DESC(bboxes)}}; // TopK INPUT_MAP(TopK) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(k)}}; ATTR_MAP(TopK) = {{"sorted", ATTR_DESC(sorted, AnyTraits<bool>())}}; OUTPUT_MAP(TopK) = {{0, OUTPUT_DESC(values)}, {1, OUTPUT_DESC(indices)}}; // Multiply INPUT_MAP(Multiply) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(y)}}; ATTR_MAP(Multiply) = EMPTY_ATTR_MAP; OUTPUT_MAP(Multiply) = {{0, OUTPUT_DESC(z)}}; // TileD INPUT_MAP(TileD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(TileD) = {{2, ATTR_DESC(multiples, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(TileD) = EMPTY_ATTR_MAP; OUTPUT_MAP(TileD) = {{0, OUTPUT_DESC(y)}}; // OneHot INPUT_MAP(OneHot) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(depth)}, {3, INPUT_DESC(on_value)}, {4, INPUT_DESC(off_value)}}; ATTR_MAP(OneHot) = {{"axis", ATTR_DESC(axis, AnyTraits<int64_t>())}}; OUTPUT_MAP(OneHot) = {{0, OUTPUT_DESC(y)}}; // GatherV2D INPUT_MAP(GatherV2D) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(indices)}}; INPUT_ATTR_MAP(GatherV2D) = {{3, ATTR_DESC(axis, AnyTraits<int64_t>())}}; ATTR_MAP(GatherV2D) = EMPTY_ATTR_MAP; OUTPUT_MAP(GatherV2D) = {{0, OUTPUT_DESC(y)}}; // Reshape INPUT_MAP(Reshape) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(shape)}}; ATTR_MAP(Reshape) = EMPTY_ATTR_MAP; OUTPUT_MAP(Reshape) = {{0, OUTPUT_DESC(y)}}; // BiasAdd INPUT_MAP(BiasAdd) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(bias)}}; ATTR_MAP(BiasAdd) = {{"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}}; OUTPUT_MAP(BiasAdd) = {{0, OUTPUT_DESC(y)}}; // Iou INPUT_MAP(Iou) = {{1, INPUT_DESC(bboxes)}, {2, INPUT_DESC(gtboxes)}}; ATTR_MAP(Iou) = {{"mode", ATTR_DESC(mode, AnyTraits<std::string>())}}; OUTPUT_MAP(Iou) = {{0, OUTPUT_DESC(overlap)}}; // ResizeNearestNeighborV2D INPUT_MAP(ResizeNearestNeighborV2D) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ResizeNearestNeighborV2D) = { {"size", ATTR_DESC(size, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"align_corners", ATTR_DESC(align_corners, AnyTraits<bool>())}}; OUTPUT_MAP(ResizeNearestNeighborV2D) = {{0, OUTPUT_DESC(y)}}; // ResizeNearestNeighborV2Grad INPUT_MAP(ResizeNearestNeighborV2Grad) = {{1, INPUT_DESC(grads)}, {2, INPUT_DESC(size)}}; ATTR_MAP(ResizeNearestNeighborV2Grad) = {{"align_corners", ATTR_DESC(align_corners, AnyTraits<bool>())}}; OUTPUT_MAP(ResizeNearestNeighborV2Grad) = {{0, OUTPUT_DESC(y)}}; // ApplyAdam INPUT_MAP(ApplyAdam) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(m)}, {3, INPUT_DESC(v)}, {4, INPUT_DESC(beta1_power)}, {5, INPUT_DESC(beta2_power)}, {6, INPUT_DESC(lr)}, {7, INPUT_DESC(beta1)}, {8, INPUT_DESC(beta2)}, {9, INPUT_DESC(epsilon)}, {10, INPUT_DESC(grad)}}; ATTR_MAP(ApplyAdam) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}, {"use_nesterov", ATTR_DESC(use_nesterov, AnyTraits<bool>())}}; OUTPUT_MAP(ApplyAdam) = {{0, OUTPUT_DESC(var)}}; // ApplyAdamD INPUT_MAP(ApplyAdamD) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(m)}, {3, INPUT_DESC(v)}, {4, INPUT_DESC(beta1_power)}, {5, INPUT_DESC(beta2_power)}, {6, INPUT_DESC(lr)}, {7, INPUT_DESC(beta1)}, {8, INPUT_DESC(beta2)}, {9, INPUT_DESC(epsilon)}, {10, INPUT_DESC(grad)}}; ATTR_MAP(ApplyAdamD) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}, {"use_nesterov", ATTR_DESC(use_nesterov, AnyTraits<bool>())}}; OUTPUT_MAP(ApplyAdamD) = {{0, OUTPUT_DESC(var)}, {1, OUTPUT_DESC(m)}, {2, OUTPUT_DESC(v)}}; // Relu6 INPUT_MAP(Relu6) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Relu6) = EMPTY_ATTR_MAP; OUTPUT_MAP(Relu6) = {{0, OUTPUT_DESC(y)}}; // Relu6Grad INPUT_MAP(Relu6Grad) = {{1, INPUT_DESC(gradients)}, {2, INPUT_DESC(features)}}; ATTR_MAP(Relu6Grad) = EMPTY_ATTR_MAP; OUTPUT_MAP(Relu6Grad) = {{0, OUTPUT_DESC(backprops)}}; // ResizeBilinearV2Grad INPUT_MAP(ResizeBilinearV2Grad) = {{1, INPUT_DESC(grads)}, {2, INPUT_DESC(original_image)}}; ATTR_MAP(ResizeBilinearV2Grad) = {{"align_corners", ATTR_DESC(align_corners, AnyTraits<bool>())}}; OUTPUT_MAP(ResizeBilinearV2Grad) = {{0, OUTPUT_DESC(y)}}; // ResizeBilinearV2D INPUT_MAP(ResizeBilinearV2D) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ResizeBilinearV2D) = { {"size", ATTR_DESC(size, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"align_corners", ATTR_DESC(align_corners, AnyTraits<bool>())}}; OUTPUT_MAP(ResizeBilinearV2D) = {{0, OUTPUT_DESC(y)}}; // ZerosLike INPUT_MAP(ZerosLike) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ZerosLike) = EMPTY_ATTR_MAP; OUTPUT_MAP(ZerosLike) = {{0, OUTPUT_DESC(y)}}; // OnesLike INPUT_MAP(OnesLike) = {{1, INPUT_DESC(x)}}; ATTR_MAP(OnesLike) = EMPTY_ATTR_MAP; OUTPUT_MAP(OnesLike) = {{0, OUTPUT_DESC(y)}}; // NMSWithMask INPUT_MAP(NMSWithMask) = {{1, INPUT_DESC(box_scores)}}; ATTR_MAP(NMSWithMask) = {{"iou_threshold", ATTR_DESC(iou_threshold, AnyTraits<float>())}}; OUTPUT_MAP(NMSWithMask) = { {0, OUTPUT_DESC(selected_boxes)}, {1, OUTPUT_DESC(selected_idx)}, {2, OUTPUT_DESC(selected_mask)}}; // Unpack INPUT_MAP(Unpack) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Unpack) = {{"axis", ATTR_DESC(axis, AnyTraits<int>())}, {"num", ATTR_DESC(num, AnyTraits<int>())}}; DYN_OUTPUT_MAP(Unpack) = {{0, DYN_OUTPUT_DESC(y)}}; // ScatterNdUpdate INPUT_MAP(ScatterNdUpdate) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(indices)}, {3, INPUT_DESC(updates)}}; ATTR_MAP(ScatterNdUpdate) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}}; OUTPUT_MAP(ScatterNdUpdate) = {{0, OUTPUT_DESC(var)}}; // ScatterMax INPUT_MAP(ScatterMax) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(indices)}, {3, INPUT_DESC(updates)}}; ATTR_MAP(ScatterMax) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}}; OUTPUT_MAP(ScatterMax) = {{0, OUTPUT_DESC(var)}}; // CheckValid INPUT_MAP(CheckValid) = {{1, INPUT_DESC(bbox_tensor)}, {2, INPUT_DESC(img_metas)}}; ATTR_MAP(CheckValid) = EMPTY_ATTR_MAP; OUTPUT_MAP(CheckValid) = {{0, OUTPUT_DESC(valid_tensor)}}; // SmoothL1Loss INPUT_MAP(SmoothL1Loss) = {{1, INPUT_DESC(predict)}, {2, INPUT_DESC(label)}}; ATTR_MAP(SmoothL1Loss) = {{"sigma", ATTR_DESC(sigma, AnyTraits<float>())}}; OUTPUT_MAP(SmoothL1Loss) = {{0, OUTPUT_DESC(loss)}}; // SmoothL1LossGrad INPUT_MAP(SmoothL1LossGrad) = {{1, INPUT_DESC(predict)}, {2, INPUT_DESC(label)}, {3, INPUT_DESC(dout)}}; ATTR_MAP(SmoothL1LossGrad) = {{"sigma", ATTR_DESC(sigma, AnyTraits<float>())}}; OUTPUT_MAP(SmoothL1LossGrad) = {{0, OUTPUT_DESC(gradient)}}; // SigmoidCrossEntropyWithLogits INPUT_MAP(SigmoidCrossEntropyWithLogits) = {{1, INPUT_DESC(predict)}, {2, INPUT_DESC(target)}}; ATTR_MAP(SigmoidCrossEntropyWithLogits) = EMPTY_ATTR_MAP; OUTPUT_MAP(SigmoidCrossEntropyWithLogits) = {{0, OUTPUT_DESC(loss)}}; // SigmoidCrossEntropyWithLogitsGrad INPUT_MAP(SigmoidCrossEntropyWithLogitsGrad) = { {1, INPUT_DESC(predict)}, {2, INPUT_DESC(target)}, {3, INPUT_DESC(dout)}}; ATTR_MAP(SigmoidCrossEntropyWithLogitsGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(SigmoidCrossEntropyWithLogitsGrad) = {{0, OUTPUT_DESC(gradient)}}; // ScatterNdD INPUT_MAP(ScatterNdD) = {{1, INPUT_DESC(indices)}, {2, INPUT_DESC(x)}}; INPUT_ATTR_MAP(ScatterNdD) = { {3, ATTR_DESC(shape, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(ScatterNdD) = EMPTY_ATTR_MAP; OUTPUT_MAP(ScatterNdD) = {{0, OUTPUT_DESC(y)}}; // PadD INPUT_MAP(PadD) = {{1, INPUT_DESC(x)}}; ATTR_MAP(PadD) = {{"paddings", ATTR_DESC(paddings, AnyTraits<std::vector<std::vector<int64_t>>>())}}; OUTPUT_MAP(PadD) = {{0, OUTPUT_DESC(y)}}; // MirrorPad INPUT_MAP(MirrorPad) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(paddings)}}; ATTR_MAP(MirrorPad) = {{"mode", ATTR_DESC(mode, AnyTraits<std::string>())}}; OUTPUT_MAP(MirrorPad) = {{0, OUTPUT_DESC(y)}}; // MirrorPadGrad INPUT_MAP(MirrorPadGrad) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(paddings)}}; ATTR_MAP(MirrorPadGrad) = {{"mode", ATTR_DESC(mode, AnyTraits<std::string>())}}; OUTPUT_MAP(MirrorPadGrad) = {{0, OUTPUT_DESC(y)}}; // GatherNd INPUT_MAP(GatherNd) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(indices)}}; ATTR_MAP(GatherNd) = EMPTY_ATTR_MAP; OUTPUT_MAP(GatherNd) = {{0, OUTPUT_DESC(y)}}; // ROIAlign INPUT_MAP(ROIAlign) = {{1, INPUT_DESC(features)}, {2, INPUT_DESC(rois)}}; OUTPUT_MAP(ROIAlign) = {{0, OUTPUT_DESC(y)}}; ATTR_MAP(ROIAlign) = {{"pooled_height", ATTR_DESC(pooled_height, AnyTraits<int>())}, {"pooled_width", ATTR_DESC(pooled_width, AnyTraits<int>())}, {"spatial_scale", ATTR_DESC(spatial_scale, AnyTraits<float>())}, {"sample_num", ATTR_DESC(sample_num, AnyTraits<int>())}}; // ROIAlignGrad INPUT_MAP(ROIAlignGrad) = {{1, INPUT_DESC(ydiff)}, {2, INPUT_DESC(rois)}}; OUTPUT_MAP(ROIAlignGrad) = {{0, OUTPUT_DESC(xdiff)}}; ATTR_MAP(ROIAlignGrad) = { {"xdiff_shape", ATTR_DESC(xdiff_shape, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"pooled_height", ATTR_DESC(pooled_height, AnyTraits<int>())}, {"pooled_width", ATTR_DESC(pooled_width, AnyTraits<int>())}, {"spatial_scale", ATTR_DESC(spatial_scale, AnyTraits<float>())}, {"sample_num", ATTR_DESC(sample_num, AnyTraits<int>())}}; // ArgMaxD INPUT_MAP(ArgMaxD) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ArgMaxD) = {{"axis", ATTR_DESC(dimension, AnyTraits<int>())}, {"output_type", ATTR_DESC(dtype, AnyTraits<GEType>())}}; OUTPUT_MAP(ArgMaxD) = {{0, OUTPUT_DESC(y)}}; // ArgMinD INPUT_MAP(ArgMinD) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ArgMinD) = {{"axis", ATTR_DESC(dimension, AnyTraits<int>())}, {"output_type", ATTR_DESC(dtype, AnyTraits<GEType>())}}; OUTPUT_MAP(ArgMinD) = {{0, OUTPUT_DESC(y)}}; // ArgMaxWithValue INPUT_MAP(ArgMaxWithValue) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ArgMaxWithValue) = {{"axis", ATTR_DESC(dimension, AnyTraits<int>())}, {"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ArgMaxWithValue) = {{0, OUTPUT_DESC(indice)}, {1, OUTPUT_DESC(values)}}; // ArgMinWithValue INPUT_MAP(ArgMinWithValue) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ArgMinWithValue) = {{"axis", ATTR_DESC(dimension, AnyTraits<int>())}, {"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ArgMinWithValue) = {{0, OUTPUT_DESC(indice)}, {1, OUTPUT_DESC(values)}}; // ReduceAllD INPUT_MAP(ReduceAllD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(ReduceAllD) = { {2, ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(ReduceAllD) = {{"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ReduceAllD) = {{0, OUTPUT_DESC(y)}}; // ReduceMeanD INPUT_MAP(ReduceMeanD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(ReduceMeanD) = { {2, ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(ReduceMeanD) = {{"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ReduceMeanD) = {{0, OUTPUT_DESC(y)}}; // HCOMAllreduce INPUT_MAP(HcomAllReduce) = {{1, INPUT_DESC(x)}}; OUTPUT_MAP(HcomAllReduce) = {{0, OUTPUT_DESC(y)}}; ATTR_MAP(HcomAllReduce) = {{"op", ATTR_DESC(reduction, AnyTraits<std::string>())}, {"group", ATTR_DESC(group, AnyTraits<std::string>())}, {"fusion", ATTR_DESC(fusion, AnyTraits<int>())}}; // HCOMBraodcast INPUT_MAP(HcomBroadcast) = EMPTY_INPUT_MAP; DYN_INPUT_MAP(HcomBroadcast) = {{1, DYN_INPUT_DESC(x)}}; DYN_OUTPUT_MAP(HcomBroadcast) = {{0, DYN_OUTPUT_DESC(y)}}; ATTR_MAP(HcomBroadcast) = {{"root_rank", ATTR_DESC(root_rank, AnyTraits<int>())}, {"group", ATTR_DESC(group, AnyTraits<std::string>())}}; // HCOMAllreduce INPUT_MAP(HcomAllGather) = {{1, INPUT_DESC(x)}}; OUTPUT_MAP(HcomAllGather) = {{0, OUTPUT_DESC(y)}}; ATTR_MAP(HcomAllGather) = {{"group", ATTR_DESC(group, AnyTraits<std::string>())}, {"rank_size", ATTR_DESC(rank_size, AnyTraits<int>())}}; // HCOMReduceScatter INPUT_MAP(HcomReduceScatter) = {{1, INPUT_DESC(x)}}; OUTPUT_MAP(HcomReduceScatter) = {{0, OUTPUT_DESC(y)}}; ATTR_MAP(HcomReduceScatter) = {{"group", ATTR_DESC(group, AnyTraits<std::string>())}, {"op", ATTR_DESC(reduction, AnyTraits<std::string>())}, {"rank_size", ATTR_DESC(rank_size, AnyTraits<int>())}}; // Variable INPUT_MAP(Variable) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Variable) = EMPTY_ATTR_MAP; // ReluGrad INPUT_MAP(ReluGrad) = {{1, INPUT_DESC(gradients)}, {2, INPUT_DESC(features)}}; ATTR_MAP(ReluGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(ReluGrad) = {{0, OUTPUT_DESC(backprops)}}; // BiasAddGrad INPUT_MAP(BiasAddGrad) = {{1, INPUT_DESC(x)}}; ATTR_MAP(BiasAddGrad) = {{"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}}; OUTPUT_MAP(BiasAddGrad) = {{0, OUTPUT_DESC(y)}}; // MaxPoolGrad INPUT_MAP(MaxPoolGrad) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}, {3, INPUT_DESC(grad)}}; ATTR_MAP(MaxPoolGrad) = {{"ksize", ATTR_DESC(ksize, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"strides", ATTR_DESC(strides, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"padding", ATTR_DESC(padding, AnyTraits<std::string>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}}; OUTPUT_MAP(MaxPoolGrad) = {{0, OUTPUT_DESC(y)}}; // avgpoolgrad INPUT_MAP(AvgPoolGrad) = {{1, INPUT_DESC(orig_input_shape)}, {2, INPUT_DESC(input_grad)}}; ATTR_MAP(AvgPoolGrad) = {{"ksize", ATTR_DESC(ksize, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"strides", ATTR_DESC(strides, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"padding", ATTR_DESC(padding, AnyTraits<std::string>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}}; OUTPUT_MAP(AvgPoolGrad) = {{0, OUTPUT_DESC(out_grad)}}; // MaxPoolWithArgmax INPUT_MAP(MaxPoolWithArgmax) = {{1, INPUT_DESC(x)}}; ATTR_MAP(MaxPoolWithArgmax) = {{"ksize", ATTR_DESC(ksize, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"strides", ATTR_DESC(strides, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"padding", ATTR_DESC(padding, AnyTraits<std::string>())}}; OUTPUT_MAP(MaxPoolWithArgmax) = {{0, OUTPUT_DESC(y)}, {1, OUTPUT_DESC(argmax)}}; // MaxPoolGradWithArgmax INPUT_MAP(MaxPoolGradWithArgmax) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(grad)}, {3, INPUT_DESC(argmax)}}; ATTR_MAP(MaxPoolGradWithArgmax) = {{"ksize", ATTR_DESC(ksize, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"strides", ATTR_DESC(strides, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"padding", ATTR_DESC(padding, AnyTraits<std::string>())}}; OUTPUT_MAP(MaxPoolGradWithArgmax) = {{0, OUTPUT_DESC(y)}}; // ExtractImagePatches INPUT_MAP(ExtractImagePatches) = {{1, INPUT_DESC(x)}}; ATTR_MAP(ExtractImagePatches) = {{"ksizes", ATTR_DESC(ksizes, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"strides", ATTR_DESC(strides, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"rates", ATTR_DESC(rates, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}, {"padding", ATTR_DESC(padding, AnyTraits<std::string>())}}; OUTPUT_MAP(ExtractImagePatches) = {{0, OUTPUT_DESC(y)}}; // Conv2D INPUT_MAP(Conv2D) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(filter)}}; ATTR_MAP(Conv2D) = { {"stride", ATTR_DESC(strides, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"pad_list", ATTR_DESC(pads, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"dilation", ATTR_DESC(dilations, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}, {"group", ATTR_DESC(groups, AnyTraits<int>())}, }; OUTPUT_MAP(Conv2D) = {{0, OUTPUT_DESC(y)}}; // Conv2DBackpropInputD INPUT_MAP(Conv2DBackpropInputD) = {{1, INPUT_DESC(out_backprop)}, {2, INPUT_DESC(filter)}}; INPUT_ATTR_MAP(Conv2DBackpropInputD) = { {3, ATTR_DESC(input_size, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(Conv2DBackpropInputD) = { {"pad_list", ATTR_DESC(pads, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"stride", ATTR_DESC(strides, "pad", AnyTraits<std::vector<int64_t>>())}, {"dilation", ATTR_DESC(dilations, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}, {"group", ATTR_DESC(groups, AnyTraits<int>())}, }; OUTPUT_MAP(Conv2DBackpropInputD) = {{0, OUTPUT_DESC(y)}}; // Conv2DBackpropFilterD INPUT_MAP(Conv2DBackpropFilterD) = {{1, INPUT_DESC(out_backprop)}, {2, INPUT_DESC(x)}}; INPUT_ATTR_MAP(Conv2DBackpropFilterD) = { {3, ATTR_DESC(filter_size, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(Conv2DBackpropFilterD) = { {"pad_list", ATTR_DESC(pads, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"stride", ATTR_DESC(strides, "pad", AnyTraits<std::vector<int64_t>>())}, {"dilation", ATTR_DESC(dilations, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}, {"group", ATTR_DESC(groups, AnyTraits<int>())}, }; OUTPUT_MAP(Conv2DBackpropFilterD) = {{0, OUTPUT_DESC(y)}}; // DepthwiseConv2D INPUT_MAP(DepthwiseConv2D) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(filter)}}; ATTR_MAP(DepthwiseConv2D) = { {"stride", ATTR_DESC(strides, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"pads", ATTR_DESC(pads, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"dilation", ATTR_DESC(dilations, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"data_format", ATTR_DESC(data_format, AnyTraits<std::string>())}, }; OUTPUT_MAP(DepthwiseConv2D) = {{0, OUTPUT_DESC(y)}}; // DepthwiseConv2DBackpropInputD INPUT_MAP(DepthwiseConv2DBackpropInputD) = {{2, INPUT_DESC(filter)}, {3, INPUT_DESC(out_backprop)}}; INPUT_ATTR_MAP(DepthwiseConv2DBackpropInputD) = { {1, ATTR_DESC(input_size, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(DepthwiseConv2DBackpropInputD) = { {"stride", ATTR_DESC(strides, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"pads", ATTR_DESC(pads, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"dilation", ATTR_DESC(dilations, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, }; OUTPUT_MAP(DepthwiseConv2DBackpropInputD) = {{0, OUTPUT_DESC(input_grad)}}; // DepthwiseConv2DBackpropFilterD INPUT_MAP(DepthwiseConv2DBackpropFilterD) = {{1, INPUT_DESC(input)}, {3, INPUT_DESC(out_backprop)}}; INPUT_ATTR_MAP(DepthwiseConv2DBackpropFilterD) = { {2, ATTR_DESC(filter_size, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(DepthwiseConv2DBackpropFilterD) = { {"stride", ATTR_DESC(strides, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"pads", ATTR_DESC(pads, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, {"dilation", ATTR_DESC(dilations, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}, }; OUTPUT_MAP(DepthwiseConv2DBackpropFilterD) = {{0, OUTPUT_DESC(filter_grad)}}; // MatMul INPUT_MAP(MatMul) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(MatMul) = {{"transpose_a", ATTR_DESC(transpose_x1, AnyTraits<bool>())}, {"transpose_b", ATTR_DESC(transpose_x2, AnyTraits<bool>())}}; OUTPUT_MAP(MatMul) = {{0, OUTPUT_DESC(y)}}; // Merge INPUT_MAP(Merge) = EMPTY_INPUT_MAP; DYN_INPUT_MAP(Merge) = {{1, DYN_INPUT_DESC(x)}}; ATTR_MAP(Merge) = EMPTY_ATTR_MAP; OUTPUT_MAP(Merge) = {{0, OUTPUT_DESC(y)}, {1, OUTPUT_DESC(value_index)}}; // Switch INPUT_MAP(Switch) = {{1, INPUT_DESC(data)}, {2, INPUT_DESC(pred)}}; OUTPUT_MAP(Switch) = {{0, OUTPUT_DESC(output_false)}, {1, OUTPUT_DESC(output_true)}}; ATTR_MAP(Switch) = EMPTY_ATTR_MAP; // AddN INPUT_MAP(AddN) = EMPTY_INPUT_MAP; DYN_INPUT_MAP(AddN) = {{1, DYN_INPUT_DESC(x)}}; ATTR_MAP(AddN) = {{"n", ATTR_DESC(N, AnyTraits<int64_t>())}}; OUTPUT_MAP(AddN) = {{0, OUTPUT_DESC(y)}}; // Mul INPUT_MAP(Mul) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Mul) = EMPTY_ATTR_MAP; OUTPUT_MAP(Mul) = {{0, OUTPUT_DESC(y)}}; // RealDiv INPUT_MAP(RealDiv) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(RealDiv) = EMPTY_ATTR_MAP; OUTPUT_MAP(RealDiv) = {{0, OUTPUT_DESC(y)}}; // Cast INPUT_MAP(Cast) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(Cast) = {{2, ATTR_DESC(dst_type, AnyTraits<GEType>())}}; ATTR_MAP(Cast) = {{"Truncate", ATTR_DESC(truncate, AnyTraits<bool>())}}; OUTPUT_MAP(Cast) = {{0, OUTPUT_DESC(y)}}; // Reciprocal INPUT_MAP(Reciprocal) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Reciprocal) = EMPTY_ATTR_MAP; OUTPUT_MAP(Reciprocal) = {{0, OUTPUT_DESC(y)}}; // Sub INPUT_MAP(Sub) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Sub) = EMPTY_ATTR_MAP; OUTPUT_MAP(Sub) = {{0, OUTPUT_DESC(y)}}; // SplitD INPUT_MAP(SplitD) = {{1, INPUT_DESC(x)}}; ATTR_MAP(SplitD) = {{"axis", ATTR_DESC(split_dim, AnyTraits<int>())}, {"output_num", ATTR_DESC(num_split, AnyTraits<int>())}}; DYN_OUTPUT_MAP(SplitD) = {{0, DYN_OUTPUT_DESC(y)}}; // Neg INPUT_MAP(Neg) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Neg) = EMPTY_ATTR_MAP; OUTPUT_MAP(Neg) = {{0, OUTPUT_DESC(y)}}; // Transpose INPUT_MAP(TransposeD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(TransposeD) = {{2, ATTR_DESC(perm, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(TransposeD) = EMPTY_ATTR_MAP; // Do not set Transpose operator output descriptor // DropOutGenMask INPUT_MAP(DropOutGenMask) = {{1, INPUT_DESC(shape)}, {2, INPUT_DESC(prob)}}; ATTR_MAP(DropOutGenMask) = {{"Seed0", ATTR_DESC(seed, AnyTraits<int64_t>())}, {"Seed1", ATTR_DESC(seed2, AnyTraits<int64_t>())}}; OUTPUT_MAP(DropOutGenMask) = {{0, OUTPUT_DESC(y)}}; // Pack INPUT_MAP(Pack) = EMPTY_INPUT_MAP; DYN_INPUT_MAP(Pack) = {{1, DYN_INPUT_DESC(x)}}; ATTR_MAP(Pack) = {{"num", ATTR_DESC(N, AnyTraits<int>())}, {"axis", ATTR_DESC(axis, AnyTraits<int>())}}; OUTPUT_MAP(Pack) = {{0, OUTPUT_DESC(y)}}; // ConcatD INPUT_MAP(ConcatD) = EMPTY_INPUT_MAP; DYN_INPUT_MAP(ConcatD) = {{1, DYN_INPUT_DESC(x)}}; ATTR_MAP(ConcatD) = { {"axis", ATTR_DESC(concat_dim, AnyTraits<int>())}, {"inputNums", ATTR_DESC(N, AnyTraits<int>())}, }; OUTPUT_MAP(ConcatD) = {{0, OUTPUT_DESC(y)}}; // Less INPUT_MAP(Less) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Less) = EMPTY_ATTR_MAP; OUTPUT_MAP(Less) = {{0, OUTPUT_DESC(y)}}; // Rsqrt INPUT_MAP(Rsqrt) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Rsqrt) = EMPTY_ATTR_MAP; OUTPUT_MAP(Rsqrt) = {{0, OUTPUT_DESC(y)}}; // Sqrt INPUT_MAP(Sqrt) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Sqrt) = EMPTY_ATTR_MAP; OUTPUT_MAP(Sqrt) = {{0, OUTPUT_DESC(y)}}; // Square INPUT_MAP(Square) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Square) = EMPTY_ATTR_MAP; OUTPUT_MAP(Square) = {{0, OUTPUT_DESC(y)}}; // Tanh INPUT_MAP(Tanh) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Tanh) = EMPTY_ATTR_MAP; OUTPUT_MAP(Tanh) = {{0, OUTPUT_DESC(y)}}; // TanhGrad INPUT_MAP(TanhGrad) = {{1, INPUT_DESC(y)}, {2, INPUT_DESC(dy)}}; ATTR_MAP(TanhGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(TanhGrad) = {{0, OUTPUT_DESC(z)}}; // ReduceMinD INPUT_MAP(ReduceMinD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(ReduceMinD) = { {2, ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(ReduceMinD) = {{"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ReduceMinD) = {{0, OUTPUT_DESC(y)}}; // ReduceMaxD INPUT_MAP(ReduceMaxD) = {{1, INPUT_DESC(x)}}; INPUT_ATTR_MAP(ReduceMaxD) = { {2, ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; ATTR_MAP(ReduceMaxD) = {{"keep_dims", ATTR_DESC(keep_dims, AnyTraits<bool>())}}; OUTPUT_MAP(ReduceMaxD) = {{0, OUTPUT_DESC(y)}}; // Maximum INPUT_MAP(Maximum) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Maximum) = EMPTY_ATTR_MAP; OUTPUT_MAP(Maximum) = {{0, OUTPUT_DESC(y)}}; // Minimum INPUT_MAP(Minimum) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Minimum) = EMPTY_ATTR_MAP; OUTPUT_MAP(Minimum) = {{0, OUTPUT_DESC(y)}}; // MaximumGrad INPUT_MAP(MaximumGrad) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}, {3, INPUT_DESC(grads)}}; ATTR_MAP(MaximumGrad) = {{"grad_x", ATTR_DESC(grad_x, AnyTraits<bool>())}, {"grad_y", ATTR_DESC(grad_y, AnyTraits<bool>())}}; OUTPUT_MAP(MaximumGrad) = {{0, OUTPUT_DESC(y1)}, {1, OUTPUT_DESC(y2)}}; // MinimumGrad INPUT_MAP(MinimumGrad) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}, {3, INPUT_DESC(grads)}}; ATTR_MAP(MinimumGrad) = {{"grad_x", ATTR_DESC(grad_x, AnyTraits<bool>())}, {"grad_y", ATTR_DESC(grad_y, AnyTraits<bool>())}}; OUTPUT_MAP(MinimumGrad) = {{0, OUTPUT_DESC(y1)}, {1, OUTPUT_DESC(y2)}}; // Pow INPUT_MAP(Pow) = { {1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}, }; ATTR_MAP(Pow) = EMPTY_ATTR_MAP; OUTPUT_MAP(Pow) = {{0, OUTPUT_DESC(y)}}; // Equal INPUT_MAP(Equal) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Equal) = EMPTY_ATTR_MAP; OUTPUT_MAP(Equal) = {{0, OUTPUT_DESC(y)}}; // NotEqual INPUT_MAP(NotEqual) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(NotEqual) = EMPTY_ATTR_MAP; OUTPUT_MAP(NotEqual) = {{0, OUTPUT_DESC(y)}}; // Log INPUT_MAP(Log) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Log) = EMPTY_ATTR_MAP; OUTPUT_MAP(Log) = {{0, OUTPUT_DESC(y)}}; // LogicalAnd INPUT_MAP(LogicalAnd) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(LogicalAnd) = EMPTY_ATTR_MAP; OUTPUT_MAP(LogicalAnd) = {{0, OUTPUT_DESC(y)}}; // LogicalOr INPUT_MAP(LogicalOr) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(LogicalOr) = EMPTY_ATTR_MAP; OUTPUT_MAP(LogicalOr) = {{0, OUTPUT_DESC(y)}}; // LogicalNot INPUT_MAP(LogicalNot) = {{1, INPUT_DESC(x)}}; ATTR_MAP(LogicalNot) = EMPTY_ATTR_MAP; OUTPUT_MAP(LogicalNot) = {{0, OUTPUT_DESC(y)}}; // Greater INPUT_MAP(Greater) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Greater) = EMPTY_ATTR_MAP; OUTPUT_MAP(Greater) = {{0, OUTPUT_DESC(y)}}; // LogSoftmaxGrad INPUT_MAP(LogSoftmaxGrad) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(grad)}}; ATTR_MAP(LogSoftmaxGrad) = { {"axis", ATTR_DESC(axis, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; OUTPUT_MAP(LogSoftmaxGrad) = {{0, OUTPUT_DESC(y)}}; // Select INPUT_MAP(Select) = {{1, INPUT_DESC(condition)}, {2, INPUT_DESC(x1)}, {3, INPUT_DESC(x2)}}; ATTR_MAP(Select) = EMPTY_ATTR_MAP; OUTPUT_MAP(Select) = {{0, OUTPUT_DESC(y)}}; // LessEqual INPUT_MAP(LessEqual) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(LessEqual) = EMPTY_ATTR_MAP; OUTPUT_MAP(LessEqual) = {{0, OUTPUT_DESC(y)}}; // LogSoftmaxV2 INPUT_MAP(LogSoftmaxV2) = {{1, INPUT_DESC(logits)}}; ATTR_MAP(LogSoftmaxV2) = { {"axis", ATTR_DESC(axes, AnyTraits<std::vector<int64_t>>(), AnyTraits<std::vector<int64_t>>())}}; OUTPUT_MAP(LogSoftmaxV2) = {{0, OUTPUT_DESC(logsoftmax)}}; // RandomChoiceWithMask INPUT_MAP(RandomChoiceWithMask) = {{1, INPUT_DESC(x)}}; ATTR_MAP(RandomChoiceWithMask) = {{"count", ATTR_DESC(count, AnyTraits<int64_t>())}, {"seed", ATTR_DESC(seed, AnyTraits<int64_t>())}, {"seed2", ATTR_DESC(seed2, AnyTraits<int64_t>())}}; OUTPUT_MAP(RandomChoiceWithMask) = {{0, OUTPUT_DESC(y)}, {1, OUTPUT_DESC(mask)}}; // TruncatedNormal INPUT_MAP(TruncatedNormal) = {{1, INPUT_DESC(shape)}}; ATTR_MAP(TruncatedNormal) = {{"seed", ATTR_DESC(seed, AnyTraits<int64_t>())}, {"seed2", ATTR_DESC(seed2, AnyTraits<int64_t>())}}; OUTPUT_MAP(TruncatedNormal) = {{0, OUTPUT_DESC(y)}}; // StridedSliceGrad INPUT_MAP(StridedSliceGrad) = { {1, INPUT_DESC(dy)}, {2, INPUT_DESC(shape)}, {3, INPUT_DESC(begin)}, {4, INPUT_DESC(end)}, {5, INPUT_DESC(strides)}}; ATTR_MAP(StridedSliceGrad) = {{"begin_mask", ATTR_DESC(begin_mask, AnyTraits<int64_t>())}, {"end_mask", ATTR_DESC(end_mask, AnyTraits<int64_t>())}, {"ellipsis_mask", ATTR_DESC(ellipsis_mask, AnyTraits<int64_t>())}, {"new_axis_mask", ATTR_DESC(new_axis_mask, AnyTraits<int64_t>())}, {"shrink_axis_mask", ATTR_DESC(shrink_axis_mask, AnyTraits<int64_t>())}}; OUTPUT_MAP(StridedSliceGrad) = {{0, OUTPUT_DESC(output)}}; // Gelu INPUT_MAP(Gelu) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Gelu) = EMPTY_ATTR_MAP; OUTPUT_MAP(Gelu) = {{0, OUTPUT_DESC(y)}}; // GeluGrad INPUT_MAP(GeluGrad) = {{1, INPUT_DESC(dy)}, {2, INPUT_DESC(x)}, {3, INPUT_DESC(y)}}; ATTR_MAP(GeluGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(GeluGrad) = {{0, OUTPUT_DESC(z)}}; // StridedSlice INPUT_MAP(StridedSlice) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(begin)}, {3, INPUT_DESC(end)}, {4, INPUT_DESC(strides)}}; ATTR_MAP(StridedSlice) = {{"begin_mask", ATTR_DESC(begin_mask, AnyTraits<int64_t>())}, {"end_mask", ATTR_DESC(end_mask, AnyTraits<int64_t>())}, {"ellipsis_mask", ATTR_DESC(ellipsis_mask, AnyTraits<int64_t>())}, {"new_axis_mask", ATTR_DESC(new_axis_mask, AnyTraits<int64_t>())}, {"shrink_axis_mask", ATTR_DESC(shrink_axis_mask, AnyTraits<int64_t>())}}; OUTPUT_MAP(StridedSlice) = {{0, OUTPUT_DESC(y)}}; // UnsortedSegmentSum INPUT_MAP(UnsortedSegmentSumD) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(segment_ids)}}; INPUT_ATTR_MAP(UnsortedSegmentSumD) = {{3, ATTR_DESC(num_segments, AnyTraits<int64_t>())}}; ATTR_MAP(UnsortedSegmentSumD) = EMPTY_ATTR_MAP; OUTPUT_MAP(UnsortedSegmentSumD) = {{0, OUTPUT_DESC(y)}}; // ExpandDims INPUT_MAP(ExpandDims) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(axis)}}; ATTR_MAP(ExpandDims) = EMPTY_ATTR_MAP; OUTPUT_MAP(ExpandDims) = {{0, OUTPUT_DESC(y)}}; // Squeeze INPUT_MAP(Squeeze) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Squeeze) = {{"axis", ATTR_DESC(axis, AnyTraits<int>(), AnyTraits<std::vector<int64_t>>())}}; OUTPUT_MAP(Squeeze) = {{0, OUTPUT_DESC(y)}}; // SGD INPUT_MAP(SGD) = {{1, INPUT_DESC(parameters)}, {2, INPUT_DESC(gradient)}, {3, INPUT_DESC(learning_rate)}, {4, INPUT_DESC(accum)}, {5, INPUT_DESC(momentum)}, {6, INPUT_DESC(stat)}}; ATTR_MAP(SGD) = {{"dampening", ATTR_DESC(dampening, AnyTraits<float>())}, {"weight_decay", ATTR_DESC(weight_decay, AnyTraits<float>())}, {"nesterov", ATTR_DESC(nesterov, AnyTraits<bool>())}}; OUTPUT_MAP(SGD) = {{0, OUTPUT_DESC(parameters)}}; // LayerNorm INPUT_MAP(LayerNorm) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(gamma)}, {3, INPUT_DESC(beta)}}; ATTR_MAP(LayerNorm) = {{"begin_norm_axis", ATTR_DESC(begin_norm_axis, AnyTraits<int>())}, {"begin_params_axis", ATTR_DESC(begin_params_axis, AnyTraits<int>())}}; OUTPUT_MAP(LayerNorm) = {{0, OUTPUT_DESC(y)}, {1, OUTPUT_DESC(mean)}, {2, OUTPUT_DESC(variance)}}; // LayerNormGrad INPUT_MAP(LayerNormGrad) = { {1, INPUT_DESC(x)}, {2, INPUT_DESC(dy)}, {3, INPUT_DESC(variance)}, {4, INPUT_DESC(mean)}, {5, INPUT_DESC(gamma)}}; ATTR_MAP(LayerNormGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(LayerNormGrad) = {{0, OUTPUT_DESC(pd_x)}, {1, OUTPUT_DESC(pd_gamma)}, {2, OUTPUT_DESC(pd_beta)}}; // BatchMatMul INPUT_MAP(BatchMatMul) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(BatchMatMul) = {{"transpose_x1", ATTR_DESC(adj_x1, AnyTraits<bool>())}, {"transpose_x2", ATTR_DESC(adj_x2, AnyTraits<bool>())}}; OUTPUT_MAP(BatchMatMul) = {{0, OUTPUT_DESC(y)}}; // DropoutDoMask INPUT_MAP(DropOutDoMask) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(mask)}, {3, INPUT_DESC(keep_prob)}}; ATTR_MAP(DropOutDoMask) = EMPTY_ATTR_MAP; OUTPUT_MAP(DropOutDoMask) = {{0, OUTPUT_DESC(y)}}; // NPUGetFloatStatus INPUT_MAP(NPUGetFloatStatus) = {{1, INPUT_DESC(addr)}}; OUTPUT_MAP(NPUGetFloatStatus) = {{0, OUTPUT_DESC(data)}}; ATTR_MAP(NPUGetFloatStatus) = EMPTY_ATTR_MAP; // NPUAllocFloatStatus INPUT_MAP(NPUAllocFloatStatus) = EMPTY_INPUT_MAP; ATTR_MAP(NPUAllocFloatStatus) = EMPTY_ATTR_MAP; OUTPUT_MAP(NPUAllocFloatStatus) = {{0, OUTPUT_DESC(data)}}; // NPUClearFloatStatus INPUT_MAP(NPUClearFloatStatus) = {{1, INPUT_DESC(addr)}}; OUTPUT_MAP(NPUClearFloatStatus) = {{0, OUTPUT_DESC(data)}}; ATTR_MAP(NPUClearFloatStatus) = EMPTY_ATTR_MAP; // Abs INPUT_MAP(Abs) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Abs) = EMPTY_ATTR_MAP; OUTPUT_MAP(Abs) = {{0, OUTPUT_DESC(y)}}; // AbsGrad INPUT_MAP(AbsGrad) = {{1, INPUT_DESC(y)}, {2, INPUT_DESC(dy)}}; ATTR_MAP(AbsGrad) = EMPTY_ATTR_MAP; OUTPUT_MAP(AbsGrad) = {{0, OUTPUT_DESC(z)}}; // BinaryCrossEntropy INPUT_MAP(BinaryCrossEntropy) = {{1, INPUT_DESC(x)}, {2, INPUT_DESC(y)}, {3, INPUT_DESC(weight)}}; ATTR_MAP(BinaryCrossEntropy) = {{"reduction", ATTR_DESC(reduction, AnyTraits<std::string>())}}; OUTPUT_MAP(BinaryCrossEntropy) = {{0, OUTPUT_DESC(output)}}; // BinaryCrossEntropyGrad INPUT_MAP(BinaryCrossEntropyGrad) = { {1, INPUT_DESC(x)}, {2, INPUT_DESC(y)}, {3, INPUT_DESC(grad_output)}, {4, INPUT_DESC(weight)}}; ATTR_MAP(BinaryCrossEntropyGrad) = {{"reduction", ATTR_DESC(reduction, AnyTraits<std::string>())}}; OUTPUT_MAP(BinaryCrossEntropyGrad) = {{0, OUTPUT_DESC(output)}}; // SparseApplyAdagradD INPUT_MAP(SparseApplyAdagradD) = { {1, INPUT_DESC(var)}, {2, INPUT_DESC(accum)}, {3, INPUT_DESC(grad)}, {4, INPUT_DESC(indices)}}; ATTR_MAP(SparseApplyAdagradD) = {{"lr", ATTR_DESC(lr, AnyTraits<float>())}, {"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}}; OUTPUT_MAP(SparseApplyAdagradD) = {{0, OUTPUT_DESC(var)}, {1, OUTPUT_DESC(accum)}}; // SparseApplyFtrlD INPUT_MAP(SparseApplyFtrlD) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(accum)}, {3, INPUT_DESC(linear)}, {4, INPUT_DESC(grad)}, {5, INPUT_DESC(indices)}}; ATTR_MAP(SparseApplyFtrlD) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}, {"lr", ATTR_DESC(lr, AnyTraits<float>())}, {"l1", ATTR_DESC(l1, AnyTraits<float>())}, {"l2", ATTR_DESC(l2, AnyTraits<float>())}, {"lr_power", ATTR_DESC(lr_power, AnyTraits<float>())}}; OUTPUT_MAP(SparseApplyFtrlD) = {{0, OUTPUT_DESC(var)}}; // SpaceToDepth INPUT_MAP(SpaceToDepth) = {{1, INPUT_DESC(x)}}; ATTR_MAP(SpaceToDepth) = {{"block_size", ATTR_DESC(block_size, AnyTraits<int64_t>())}}; OUTPUT_MAP(SpaceToDepth) = {{0, OUTPUT_DESC(y)}}; // DepthToSpace INPUT_MAP(DepthToSpace) = {{1, INPUT_DESC(x)}}; ATTR_MAP(DepthToSpace) = {{"block_size", ATTR_DESC(block_size, AnyTraits<int64_t>())}}; OUTPUT_MAP(DepthToSpace) = {{0, OUTPUT_DESC(y)}}; // Sign INPUT_MAP(Sign) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Sign) = EMPTY_ATTR_MAP; OUTPUT_MAP(Sign) = {{0, OUTPUT_DESC(y)}}; // Round INPUT_MAP(Round) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Round) = EMPTY_ATTR_MAP; OUTPUT_MAP(Round) = {{0, OUTPUT_DESC(y)}}; // ApplyFtrl INPUT_MAP(ApplyFtrlD) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(accum)}, {3, INPUT_DESC(linear)}, {4, INPUT_DESC(grad)}, {5, INPUT_DESC(lr)}, {6, INPUT_DESC(l1)}, {7, INPUT_DESC(l2)}, {8, INPUT_DESC(lr_power)}}; ATTR_MAP(ApplyFtrlD) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}}; OUTPUT_MAP(ApplyFtrlD) = {{0, OUTPUT_DESC(var)}, {1, OUTPUT_DESC(accum)}, {2, OUTPUT_DESC(linear)}}; // Diag INPUT_MAP(Diag) = {{1, INPUT_DESC(x)}}; ATTR_MAP(Diag) = EMPTY_ATTR_MAP; OUTPUT_MAP(Diag) = {{0, OUTPUT_DESC(y)}}; // DiagPart INPUT_MAP(DiagPart) = {{1, INPUT_DESC(x)}}; ATTR_MAP(DiagPart) = EMPTY_ATTR_MAP; OUTPUT_MAP(DiagPart) = {{0, OUTPUT_DESC(y)}}; // SpaceToBatchD INPUT_MAP(SpaceToBatchD) = {{1, INPUT_DESC(x)}}; ATTR_MAP(SpaceToBatchD) = { {"block_size", ATTR_DESC(block_size, AnyTraits<int64_t>())}, {"paddings", ATTR_DESC(paddings, AnyTraits<std::vector<std::vector<int64_t>>>(), AnyTraits<std::vector<int64_t>>())}}; OUTPUT_MAP(SpaceToBatchD) = {{0, OUTPUT_DESC(y)}}; // BatchToSpaceD INPUT_MAP(BatchToSpaceD) = {{1, INPUT_DESC(x)}}; ATTR_MAP(BatchToSpaceD) = { {"block_size", ATTR_DESC(block_size, AnyTraits<int64_t>())}, {"crops", ATTR_DESC(crops, AnyTraits<std::vector<std::vector<int64_t>>>(), AnyTraits<std::vector<int64_t>>())}}; OUTPUT_MAP(BatchToSpaceD) = {{0, OUTPUT_DESC(y)}}; // Atan2 INPUT_MAP(Atan2) = {{1, INPUT_DESC(x1)}, {2, INPUT_DESC(x2)}}; ATTR_MAP(Atan2) = EMPTY_ATTR_MAP; OUTPUT_MAP(Atan2) = {{0, OUTPUT_DESC(y)}}; // ApplyRMSPropD INPUT_MAP(ApplyRMSPropD) = { {1, INPUT_DESC(var)}, {2, INPUT_DESC(ms)}, {3, INPUT_DESC(mom)}, {4, INPUT_DESC(grad)}, {5, INPUT_DESC(lr)}}; INPUT_ATTR_MAP(ApplyRMSPropD) = {{6, ATTR_DESC(rho, AnyTraits<float>())}, {7, ATTR_DESC(momentum, AnyTraits<float>())}, {8, ATTR_DESC(epsilon, AnyTraits<float>())}}; ATTR_MAP(ApplyRMSPropD) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}}; OUTPUT_MAP(ApplyRMSPropD) = {{0, OUTPUT_DESC(var)}}; // ApplyCenteredRMSProp INPUT_MAP(ApplyCenteredRMSProp) = {{1, INPUT_DESC(var)}, {2, INPUT_DESC(mg)}, {3, INPUT_DESC(ms)}, {4, INPUT_DESC(mom)}, {5, INPUT_DESC(grad)}, {6, INPUT_DESC(lr)}, {7, INPUT_DESC(rho)}, {8, INPUT_DESC(momentum)}, {9, INPUT_DESC(epsilon)}}; ATTR_MAP(ApplyCenteredRMSProp) = {{"use_locking", ATTR_DESC(use_locking, AnyTraits<bool>())}}; OUTPUT_MAP(ApplyCenteredRMSProp) = {{0, OUTPUT_DESC(var)}}; // L2Loss INPUT_MAP(L2Loss) = {{1, INPUT_DESC(x)}}; ATTR_MAP(L2Loss) = EMPTY_ATTR_MAP; OUTPUT_MAP(L2Loss) = {{0, OUTPUT_DESC(y)}}; // CTCLoss INPUT_MAP(CTCLoss) = {{1, INPUT_DESC(inputs)}, {2, INPUT_DESC(labels_indices)}, {3, INPUT_DESC(labels_values)}, {4, INPUT_DESC(sequence_length)}}; ATTR_MAP(CTCLoss) = { {"preprocess_collapse_repeated", ATTR_DESC(preprocess_collapse_repeated, AnyTraits<bool>())}, {"ctc_merge_repeated", ATTR_DESC(ctc_merge_repeated, AnyTraits<bool>())}, {"ignore_longer_outputs_than_inputs", ATTR_DESC(ignore_longer_outputs_than_inputs, AnyTraits<bool>())}}; OUTPUT_MAP(CTCLoss) = {{0, OUTPUT_DESC(loss)}, {1, OUTPUT_DESC(gradient)}}; #ifdef ENABLE_GE // Print INPUT_MAP(Print) = EMPTY_INPUT_MAP; DYN_INPUT_MAP(Print) = {{1, DYN_INPUT_DESC(x)}}; ATTR_MAP(Print) = EMPTY_ATTR_MAP; #endif } // namespace transform } // namespace mindspore
43.80622
120
0.659512
[ "shape", "vector", "transform" ]
281e19968d6fd1d138ba882d3ad26b1ae406c8d7
9,322
hpp
C++
coding/text_storage.hpp
dualword/organicmaps
c0a73aea4835517edef3b5a7d68a3a50d55a4471
[ "Apache-2.0" ]
null
null
null
coding/text_storage.hpp
dualword/organicmaps
c0a73aea4835517edef3b5a7d68a3a50d55a4471
[ "Apache-2.0" ]
null
null
null
coding/text_storage.hpp
dualword/organicmaps
c0a73aea4835517edef3b5a7d68a3a50d55a4471
[ "Apache-2.0" ]
null
null
null
#pragma once #include "coding/bwt_coder.hpp" #include "coding/reader.hpp" #include "coding/varint.hpp" #include "coding/write_to_sink.hpp" #include "base/assert.hpp" #include "base/lru_cache.hpp" #include <algorithm> #include <cstdint> #include <sstream> #include <string> #include <vector> namespace coding { // Writes a set of strings in a format that allows to efficiently // access blocks of strings. This means that access of individual // strings may be inefficient, but access to a block of strings can be // performed in O(length of all strings in the block + log(number of // blocks)). The size of each block roughly equals to the |blockSize|, // because the whole number of strings is packed into a single block. // // Format description: // * first 8 bytes - little endian-encoded offset of the index section // * data section - represents a catenated sequence of BWT-compressed blocks with // a sequence of individual string lengths in the block // * index section - represents a delta-encoded sequence of // BWT-compressed blocks offsets intermixed with the number of // strings inside each block. // // All numbers except the first offset are varints. template <typename Writer> class BlockedTextStorageWriter { public: BlockedTextStorageWriter(Writer & writer, uint64_t blockSize) : m_writer(writer), m_blockSize(blockSize), m_startOffset(writer.Pos()), m_blocks(1) { CHECK(m_blockSize != 0, ()); WriteToSink(m_writer, static_cast<uint64_t>(0)); m_dataOffset = m_writer.Pos(); } ~BlockedTextStorageWriter() { if (!m_lengths.empty()) FlushPool(m_lengths, m_pool); if (m_blocks.back().IsEmpty()) m_blocks.pop_back(); { auto const currentOffset = m_writer.Pos(); ASSERT_GREATER_OR_EQUAL(currentOffset, m_startOffset, ()); m_writer.Seek(m_startOffset); WriteToSink(m_writer, static_cast<uint64_t>(currentOffset - m_startOffset)); m_writer.Seek(currentOffset); } WriteVarUint(m_writer, m_blocks.size()); uint64_t prevOffset = 0; for (auto const & block : m_blocks) { ASSERT_GREATER_OR_EQUAL(block.m_offset, prevOffset, ()); WriteVarUint(m_writer, block.m_offset - prevOffset); ASSERT(!block.IsEmpty(), ()); WriteVarUint(m_writer, block.m_subs); prevOffset = block.m_offset; } } void Append(std::string const & s) { ASSERT(!m_blocks.empty(), ()); ASSERT_LESS(m_pool.size(), m_blockSize, ()); ++m_blocks.back().m_subs; m_pool.append(s); m_lengths.push_back(s.size()); if (m_pool.size() >= m_blockSize) { FlushPool(m_lengths, m_pool); m_pool.clear(); m_lengths.clear(); m_blocks.emplace_back(m_writer.Pos() - m_dataOffset /* offset */, 0 /* subs */); } } private: struct Block { Block() = default; Block(uint64_t offset, uint64_t subs) : m_offset(offset), m_subs(subs) {} bool IsEmpty() const { return m_subs == 0; } uint64_t m_offset = 0; // offset of the block inside the sequence of compressed blocks uint64_t m_subs = 0; // number of strings inside the block }; void FlushPool(std::vector<uint64_t> const & lengths, std::string const & pool) { for (auto const & length : lengths) WriteVarUint(m_writer, length); BWTCoder::EncodeAndWriteBlock(m_writer, pool.size(), reinterpret_cast<uint8_t const *>(pool.c_str())); } Writer & m_writer; uint64_t const m_blockSize; uint64_t m_startOffset = 0; uint64_t m_dataOffset = 0; std::vector<Block> m_blocks; std::string m_pool; // concatenated strings std::vector<uint64_t> m_lengths; // lengths of strings inside the |m_pool| }; class BlockedTextStorageIndex { public: struct BlockInfo { // Returns the index of the first string belonging to the block. uint64_t From() const { return m_from; } // Returns the index of the first string from the next block. uint64_t To() const { return m_from + m_subs; } uint64_t m_offset = 0; // offset of the block from the beginning of the section uint64_t m_from = 0; // index of the first string in the block uint64_t m_subs = 0; // number of strings in the block }; size_t GetNumBlockInfos() const { return m_blocks.size(); } size_t GetNumStrings() const { return m_blocks.empty() ? 0 : static_cast<size_t>(m_blocks.back().To()); } BlockInfo const & GetBlockInfo(size_t blockIx) const { ASSERT_LESS(blockIx, GetNumBlockInfos(), ()); return m_blocks[blockIx]; } // Returns the index of the block the |stringIx| belongs to. // Returns the number of blocks if there're no such block. size_t GetBlockIx(size_t stringIx) const { if (m_blocks.empty() || stringIx >= m_blocks.back().To()) return GetNumBlockInfos(); if (stringIx >= m_blocks.back().From()) return GetNumBlockInfos() - 1; size_t lo = 0, hi = GetNumBlockInfos() - 1; while (lo + 1 != hi) { ASSERT_GREATER_OR_EQUAL(stringIx, m_blocks[lo].From(), ()); ASSERT_LESS(stringIx, m_blocks[hi].From(), ()); auto const mi = lo + (hi - lo) / 2; if (stringIx >= m_blocks[mi].From()) lo = mi; else hi = mi; } ASSERT_GREATER_OR_EQUAL(stringIx, m_blocks[lo].From(), ()); ASSERT_LESS(stringIx, m_blocks[hi].From(), ()); return lo; } template <typename Reader> void Read(Reader & reader) { auto const indexOffset = ReadPrimitiveFromPos<uint64_t, Reader>(reader, 0); NonOwningReaderSource source(reader); source.Skip(indexOffset); auto const numBlocks = ReadVarUint<uint64_t, NonOwningReaderSource>(source); m_blocks.assign(static_cast<size_t>(numBlocks), {}); uint64_t prevOffset = 8; // 8 bytes for the offset of the data section for (uint64_t i = 0; i < numBlocks; ++i) { auto const delta = ReadVarUint<uint64_t, NonOwningReaderSource>(source); CHECK_GREATER_OR_EQUAL(prevOffset + delta, prevOffset, ()); prevOffset += delta; auto & block = m_blocks[static_cast<size_t>(i)]; block.m_offset = prevOffset; block.m_from = i == 0 ? 0 : m_blocks[static_cast<size_t>(i - 1)].To(); block.m_subs = ReadVarUint<uint64_t, NonOwningReaderSource>(source); CHECK_GREATER_OR_EQUAL(block.m_from + block.m_subs, block.m_from, ()); } } private: std::vector<BlockInfo> m_blocks; }; class BlockedTextStorageReader { public: inline static size_t const kDefaultCacheSize = 32; BlockedTextStorageReader() : m_cache(kDefaultCacheSize) {} explicit BlockedTextStorageReader(size_t cacheSize) : m_cache(cacheSize) {} template <typename Reader> void InitializeIfNeeded(Reader & reader) { if (m_initialized) return; m_index.Read(reader); m_initialized = true; } size_t GetNumStrings() const { CHECK(m_initialized, ()); return m_index.GetNumStrings(); } template <typename Reader> std::string ExtractString(Reader & reader, size_t stringIx) { InitializeIfNeeded(reader); auto const blockIx = m_index.GetBlockIx(stringIx); CHECK_LESS(blockIx, m_index.GetNumBlockInfos(), ()); auto const & bi = m_index.GetBlockInfo(blockIx); bool found; auto & entry = m_cache.Find(blockIx, found); if (!found) { NonOwningReaderSource source(reader); source.Skip(bi.m_offset); entry.m_value.clear(); entry.m_subs.resize(static_cast<size_t>(bi.m_subs)); uint64_t offset = 0; for (size_t i = 0; i < entry.m_subs.size(); ++i) { auto & sub = entry.m_subs[i]; sub.m_offset = offset; sub.m_length = ReadVarUint<uint64_t>(source); CHECK_GREATER_OR_EQUAL(sub.m_offset + sub.m_length, sub.m_offset, ()); offset += sub.m_length; } entry.m_value = BWTCoder::ReadAndDecodeBlock(source); } ASSERT_GREATER_OR_EQUAL(stringIx, bi.From(), ()); ASSERT_LESS(stringIx, bi.To(), ()); stringIx -= bi.From(); ASSERT_LESS(stringIx, entry.m_subs.size(), ()); auto const & si = entry.m_subs[stringIx]; auto const & value = entry.m_value; ASSERT_LESS_OR_EQUAL(si.m_offset + si.m_length, value.size(), ()); auto const beg = value.begin() + si.m_offset; return std::string(beg, beg + si.m_length); } private: struct StringInfo { StringInfo() = default; StringInfo(uint64_t offset, uint64_t length): m_offset(offset), m_length(length) {} uint64_t m_offset = 0; // offset of the string inside the decompressed block uint64_t m_length = 0; // length of the string }; struct CacheEntry { BWTCoder::BufferT m_value; // concatenation of the strings std::vector<StringInfo> m_subs; // indices of individual strings }; BlockedTextStorageIndex m_index; LruCache<size_t, CacheEntry> m_cache; bool m_initialized = false; }; template <typename Reader> class BlockedTextStorage { public: explicit BlockedTextStorage(Reader & reader) : m_reader(reader) { m_storage.InitializeIfNeeded(m_reader); } size_t GetNumStrings() const { return m_storage.GetNumStrings(); } std::string ExtractString(size_t stringIx) { return m_storage.ExtractString(m_reader, stringIx); } private: BlockedTextStorageReader m_storage; Reader & m_reader; }; } // namespace coding
29.222571
100
0.674748
[ "vector" ]
2822cd22162c7fb04c33b7ae2cffbca19df7e37e
31,315
cpp
C++
src/training/common/trainingsampleset.cpp
varmantusr/tesseract
94a3a70fda21c1e5a0e06ed5fcb887b86534d380
[ "Apache-2.0" ]
null
null
null
src/training/common/trainingsampleset.cpp
varmantusr/tesseract
94a3a70fda21c1e5a0e06ed5fcb887b86534d380
[ "Apache-2.0" ]
null
null
null
src/training/common/trainingsampleset.cpp
varmantusr/tesseract
94a3a70fda21c1e5a0e06ed5fcb887b86534d380
[ "Apache-2.0" ]
null
null
null
// Copyright 2010 Google Inc. All Rights Reserved. // Author: rays@google.com (Ray Smith) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifdef HAVE_CONFIG_H # include "config_auto.h" #endif #include <algorithm> #include <allheaders.h> #include "boxread.h" #include "fontinfo.h" #include "indexmapbidi.h" #include "intfeaturedist.h" #include "intfeaturemap.h" #include "intfeaturespace.h" #include "shapetable.h" #include "trainingsample.h" #include "trainingsampleset.h" #include "unicity_table.h" namespace tesseract { const int kTestChar = -1; // 37; // Max number of distances to compute the squared way const int kSquareLimit = 25; // Prime numbers for subsampling distances. const int kPrime1 = 17; const int kPrime2 = 13; TrainingSampleSet::FontClassInfo::FontClassInfo() : num_raw_samples(0), canonical_sample(-1), canonical_dist(0.0f) {} // Writes to the given file. Returns false in case of error. bool TrainingSampleSet::FontClassInfo::Serialize(FILE *fp) const { if (fwrite(&num_raw_samples, sizeof(num_raw_samples), 1, fp) != 1) return false; if (fwrite(&canonical_sample, sizeof(canonical_sample), 1, fp) != 1) return false; if (fwrite(&canonical_dist, sizeof(canonical_dist), 1, fp) != 1) return false; if (!::tesseract::Serialize(fp, samples)) return false; return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool TrainingSampleSet::FontClassInfo::DeSerialize(bool swap, FILE *fp) { if (fread(&num_raw_samples, sizeof(num_raw_samples), 1, fp) != 1) return false; if (fread(&canonical_sample, sizeof(canonical_sample), 1, fp) != 1) return false; if (fread(&canonical_dist, sizeof(canonical_dist), 1, fp) != 1) return false; if (!::tesseract::DeSerialize(swap, fp, samples)) return false; if (swap) { ReverseN(&num_raw_samples, sizeof(num_raw_samples)); ReverseN(&canonical_sample, sizeof(canonical_sample)); ReverseN(&canonical_dist, sizeof(canonical_dist)); } return true; } TrainingSampleSet::TrainingSampleSet(const FontInfoTable &font_table) : num_raw_samples_(0) , unicharset_size_(0) , font_class_array_(nullptr) , fontinfo_table_(font_table) {} TrainingSampleSet::~TrainingSampleSet() { delete font_class_array_; } // Writes to the given file. Returns false in case of error. bool TrainingSampleSet::Serialize(FILE *fp) const { if (!samples_.Serialize(fp)) return false; if (!unicharset_.save_to_file(fp)) return false; if (!font_id_map_.Serialize(fp)) return false; int8_t not_null = font_class_array_ != nullptr; if (fwrite(&not_null, sizeof(not_null), 1, fp) != 1) return false; if (not_null) { if (!font_class_array_->SerializeClasses(fp)) return false; } return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool TrainingSampleSet::DeSerialize(bool swap, FILE *fp) { if (!samples_.DeSerialize(swap, fp)) return false; num_raw_samples_ = samples_.size(); if (!unicharset_.load_from_file(fp)) return false; if (!font_id_map_.DeSerialize(swap, fp)) return false; delete font_class_array_; font_class_array_ = nullptr; int8_t not_null; if (fread(&not_null, sizeof(not_null), 1, fp) != 1) return false; if (not_null) { FontClassInfo empty; font_class_array_ = new GENERIC_2D_ARRAY<FontClassInfo>(1, 1, empty); if (!font_class_array_->DeSerializeClasses(swap, fp)) return false; } unicharset_size_ = unicharset_.size(); return true; } // Load an initial unicharset, or set one up if the file cannot be read. void TrainingSampleSet::LoadUnicharset(const char *filename) { if (!unicharset_.load_from_file(filename)) { tprintf( "Failed to load unicharset from file %s\n" "Building unicharset from scratch...\n", filename); unicharset_.clear(); // Add special characters as they were removed by the clear. UNICHARSET empty; unicharset_.AppendOtherUnicharset(empty); } unicharset_size_ = unicharset_.size(); } // Adds a character sample to this sample set. // If the unichar is not already in the local unicharset, it is added. // Returns the unichar_id of the added sample, from the local unicharset. int TrainingSampleSet::AddSample(const char *unichar, TrainingSample *sample) { if (!unicharset_.contains_unichar(unichar)) { unicharset_.unichar_insert(unichar); if (unicharset_.size() > MAX_NUM_CLASSES) { tprintf( "Error: Size of unicharset in TrainingSampleSet::AddSample is " "greater than MAX_NUM_CLASSES\n"); return -1; } } UNICHAR_ID char_id = unicharset_.unichar_to_id(unichar); AddSample(char_id, sample); return char_id; } // Adds a character sample to this sample set with the given unichar_id, // which must correspond to the local unicharset (in this). void TrainingSampleSet::AddSample(int unichar_id, TrainingSample *sample) { sample->set_class_id(unichar_id); samples_.push_back(sample); num_raw_samples_ = samples_.size(); unicharset_size_ = unicharset_.size(); } // Returns the number of samples for the given font,class pair. // If randomize is true, returns the number of samples accessible // with randomizing on. (Increases the number of samples if small.) // OrganizeByFontAndClass must have been already called. int TrainingSampleSet::NumClassSamples(int font_id, int class_id, bool randomize) const { ASSERT_HOST(font_class_array_ != nullptr); if (font_id < 0 || class_id < 0 || font_id >= font_id_map_.SparseSize() || class_id >= unicharset_size_) { // There are no samples because the font or class doesn't exist. return 0; } int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) return 0; // The font has no samples. if (randomize) return (*font_class_array_)(font_index, class_id).samples.size(); else return (*font_class_array_)(font_index, class_id).num_raw_samples; } // Gets a sample by its index. const TrainingSample *TrainingSampleSet::GetSample(int index) const { return samples_[index]; } // Gets a sample by its font, class, index. // OrganizeByFontAndClass must have been already called. const TrainingSample *TrainingSampleSet::GetSample(int font_id, int class_id, int index) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) return nullptr; int sample_index = (*font_class_array_)(font_index, class_id).samples[index]; return samples_[sample_index]; } // Get a sample by its font, class, index. Does not randomize. // OrganizeByFontAndClass must have been already called. TrainingSample *TrainingSampleSet::MutableSample(int font_id, int class_id, int index) { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) return nullptr; int sample_index = (*font_class_array_)(font_index, class_id).samples[index]; return samples_[sample_index]; } // Returns a string debug representation of the given sample: // font, unichar_str, bounding box, page. std::string TrainingSampleSet::SampleToString(const TrainingSample &sample) const { std::string boxfile_str; MakeBoxFileStr(unicharset_.id_to_unichar(sample.class_id()), sample.bounding_box(), sample.page_num(), boxfile_str); return std::string(fontinfo_table_.get(sample.font_id()).name) + " " + boxfile_str; } // Gets the combined set of features used by all the samples of the given // font/class combination. const BitVector &TrainingSampleSet::GetCloudFeatures(int font_id, int class_id) const { int font_index = font_id_map_.SparseToCompact(font_id); ASSERT_HOST(font_index >= 0); return (*font_class_array_)(font_index, class_id).cloud_features; } // Gets the indexed features of the canonical sample of the given // font/class combination. const std::vector<int> &TrainingSampleSet::GetCanonicalFeatures(int font_id, int class_id) const { int font_index = font_id_map_.SparseToCompact(font_id); ASSERT_HOST(font_index >= 0); return (*font_class_array_)(font_index, class_id).canonical_features; } // Returns the distance between the given UniCharAndFonts pair. // If matched_fonts, only matching fonts, are considered, unless that yields // the empty set. // OrganizeByFontAndClass must have been already called. float TrainingSampleSet::UnicharDistance(const UnicharAndFonts &uf1, const UnicharAndFonts &uf2, bool matched_fonts, const IntFeatureMap &feature_map) { int num_fonts1 = uf1.font_ids.size(); int c1 = uf1.unichar_id; int num_fonts2 = uf2.font_ids.size(); int c2 = uf2.unichar_id; double dist_sum = 0.0; int dist_count = 0; const bool debug = false; if (matched_fonts) { // Compute distances only where fonts match. for (int i = 0; i < num_fonts1; ++i) { int f1 = uf1.font_ids[i]; for (int j = 0; j < num_fonts2; ++j) { int f2 = uf2.font_ids[j]; if (f1 == f2) { dist_sum += ClusterDistance(f1, c1, f2, c2, feature_map); ++dist_count; } } } } else if (num_fonts1 * num_fonts2 <= kSquareLimit) { // Small enough sets to compute all the distances. for (int i = 0; i < num_fonts1; ++i) { int f1 = uf1.font_ids[i]; for (int j = 0; j < num_fonts2; ++j) { int f2 = uf2.font_ids[j]; dist_sum += ClusterDistance(f1, c1, f2, c2, feature_map); if (debug) { tprintf("Cluster dist %d %d %d %d = %g\n", f1, c1, f2, c2, ClusterDistance(f1, c1, f2, c2, feature_map)); } ++dist_count; } } } else { // Subsample distances, using the largest set once, and stepping through // the smaller set so as to ensure that all the pairs are different. int increment = kPrime1 != num_fonts2 ? kPrime1 : kPrime2; int index = 0; int num_samples = std::max(num_fonts1, num_fonts2); for (int i = 0; i < num_samples; ++i, index += increment) { int f1 = uf1.font_ids[i % num_fonts1]; int f2 = uf2.font_ids[index % num_fonts2]; if (debug) { tprintf("Cluster dist %d %d %d %d = %g\n", f1, c1, f2, c2, ClusterDistance(f1, c1, f2, c2, feature_map)); } dist_sum += ClusterDistance(f1, c1, f2, c2, feature_map); ++dist_count; } } if (dist_count == 0) { if (matched_fonts) return UnicharDistance(uf1, uf2, false, feature_map); return 0.0f; } return dist_sum / dist_count; } // Returns the distance between the given pair of font/class pairs. // Finds in cache or computes and caches. // OrganizeByFontAndClass must have been already called. float TrainingSampleSet::ClusterDistance(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map) { ASSERT_HOST(font_class_array_ != nullptr); int font_index1 = font_id_map_.SparseToCompact(font_id1); int font_index2 = font_id_map_.SparseToCompact(font_id2); if (font_index1 < 0 || font_index2 < 0) return 0.0f; FontClassInfo &fc_info = (*font_class_array_)(font_index1, class_id1); if (font_id1 == font_id2) { // Special case cache for speed. if (fc_info.unichar_distance_cache.size() == 0) fc_info.unichar_distance_cache.resize(unicharset_size_, -1.0f); if (fc_info.unichar_distance_cache[class_id2] < 0) { // Distance has to be calculated. float result = ComputeClusterDistance(font_id1, class_id1, font_id2, class_id2, feature_map); fc_info.unichar_distance_cache[class_id2] = result; // Copy to the symmetric cache entry. FontClassInfo &fc_info2 = (*font_class_array_)(font_index2, class_id2); if (fc_info2.unichar_distance_cache.size() == 0) fc_info2.unichar_distance_cache.resize(unicharset_size_, -1.0f); fc_info2.unichar_distance_cache[class_id1] = result; } return fc_info.unichar_distance_cache[class_id2]; } else if (class_id1 == class_id2) { // Another special-case cache for equal class-id. if (fc_info.font_distance_cache.size() == 0) fc_info.font_distance_cache.resize(font_id_map_.CompactSize(), -1.0f); if (fc_info.font_distance_cache[font_index2] < 0) { // Distance has to be calculated. float result = ComputeClusterDistance(font_id1, class_id1, font_id2, class_id2, feature_map); fc_info.font_distance_cache[font_index2] = result; // Copy to the symmetric cache entry. FontClassInfo &fc_info2 = (*font_class_array_)(font_index2, class_id2); if (fc_info2.font_distance_cache.size() == 0) fc_info2.font_distance_cache.resize(font_id_map_.CompactSize(), -1.0f); fc_info2.font_distance_cache[font_index1] = result; } return fc_info.font_distance_cache[font_index2]; } // Both font and class are different. Linear search for class_id2/font_id2 // in what is a hopefully short list of distances. int cache_index = 0; while (cache_index < fc_info.distance_cache.size() && (fc_info.distance_cache[cache_index].unichar_id != class_id2 || fc_info.distance_cache[cache_index].font_id != font_id2)) ++cache_index; if (cache_index == fc_info.distance_cache.size()) { // Distance has to be calculated. float result = ComputeClusterDistance(font_id1, class_id1, font_id2, class_id2, feature_map); FontClassDistance fc_dist = {class_id2, font_id2, result}; fc_info.distance_cache.push_back(fc_dist); // Copy to the symmetric cache entry. We know it isn't there already, as // we always copy to the symmetric entry. FontClassInfo &fc_info2 = (*font_class_array_)(font_index2, class_id2); fc_dist.unichar_id = class_id1; fc_dist.font_id = font_id1; fc_info2.distance_cache.push_back(fc_dist); } return fc_info.distance_cache[cache_index].distance; } // Computes the distance between the given pair of font/class pairs. float TrainingSampleSet::ComputeClusterDistance(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map) const { int dist = ReliablySeparable(font_id1, class_id1, font_id2, class_id2, feature_map, false); dist += ReliablySeparable(font_id2, class_id2, font_id1, class_id1, feature_map, false); int denominator = GetCanonicalFeatures(font_id1, class_id1).size(); denominator += GetCanonicalFeatures(font_id2, class_id2).size(); return static_cast<float>(dist) / denominator; } // Helper to add a feature and its near neighbors to the good_features. // levels indicates how many times to compute the offset features of what is // already there. This is done by iteration rather than recursion. static void AddNearFeatures(const IntFeatureMap &feature_map, int f, int levels, std::vector<int> *good_features) { int prev_num_features = 0; good_features->push_back(f); int num_features = 1; for (int level = 0; level < levels; ++level) { for (int i = prev_num_features; i < num_features; ++i) { int feature = (*good_features)[i]; for (int dir = -kNumOffsetMaps; dir <= kNumOffsetMaps; ++dir) { if (dir == 0) continue; int f1 = feature_map.OffsetFeature(feature, dir); if (f1 >= 0) { good_features->push_back(f1); } } } prev_num_features = num_features; num_features = good_features->size(); } } // Returns the number of canonical features of font/class 2 for which // neither the feature nor any of its near neighbors occurs in the cloud // of font/class 1. Each such feature is a reliable separation between // the classes, ASSUMING that the canonical sample is sufficiently // representative that every sample has a feature near that particular // feature. To check that this is so on the fly would be prohibitively // expensive, but it might be possible to pre-qualify the canonical features // to include only those for which this assumption is true. // ComputeCanonicalFeatures and ComputeCloudFeatures must have been called // first, or the results will be nonsense. int TrainingSampleSet::ReliablySeparable(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map, bool thorough) const { int result = 0; const TrainingSample *sample2 = GetCanonicalSample(font_id2, class_id2); if (sample2 == nullptr) return 0; // There are no canonical features. const std::vector<int> &canonical2 = GetCanonicalFeatures(font_id2, class_id2); const BitVector &cloud1 = GetCloudFeatures(font_id1, class_id1); if (cloud1.size() == 0) return canonical2.size(); // There are no cloud features. // Find a canonical2 feature that is not in cloud1. for (int f = 0; f < canonical2.size(); ++f) { const int feature = canonical2[f]; if (cloud1[feature]) continue; // Gather the near neighbours of f. std::vector<int> good_features; AddNearFeatures(feature_map, feature, 1, &good_features); // Check that none of the good_features are in the cloud. int i; for (i = 0; i < good_features.size(); ++i) { int good_f = good_features[i]; if (cloud1[good_f]) { break; } } if (i < good_features.size()) continue; // Found one in the cloud. ++result; } return result; } // Returns the total index of the requested sample. // OrganizeByFontAndClass must have been already called. int TrainingSampleSet::GlobalSampleIndex(int font_id, int class_id, int index) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) return -1; return (*font_class_array_)(font_index, class_id).samples[index]; } // Gets the canonical sample for the given font, class pair. // ComputeCanonicalSamples must have been called first. const TrainingSample *TrainingSampleSet::GetCanonicalSample(int font_id, int class_id) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) return nullptr; const int sample_index = (*font_class_array_)(font_index, class_id).canonical_sample; return sample_index >= 0 ? samples_[sample_index] : nullptr; } // Gets the max distance for the given canonical sample. // ComputeCanonicalSamples must have been called first. float TrainingSampleSet::GetCanonicalDist(int font_id, int class_id) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) return 0.0f; if ((*font_class_array_)(font_index, class_id).canonical_sample >= 0) return (*font_class_array_)(font_index, class_id).canonical_dist; else return 0.0f; } // Generates indexed features for all samples with the supplied feature_space. void TrainingSampleSet::IndexFeatures(const IntFeatureSpace &feature_space) { for (int s = 0; s < samples_.size(); ++s) samples_[s]->IndexFeatures(feature_space); } // Marks the given sample index for deletion. // Deletion is actually completed by DeleteDeadSamples. void TrainingSampleSet::KillSample(TrainingSample *sample) { sample->set_sample_index(-1); } // Deletes all samples with zero features marked by KillSample. void TrainingSampleSet::DeleteDeadSamples() { using namespace std::placeholders; // for _1 samples_.compact(std::bind(&TrainingSampleSet::DeleteableSample, this, _1)); num_raw_samples_ = samples_.size(); // Samples must be re-organized now we have deleted a few. } // Callback function returns true if the given sample is to be deleted, due // to having a negative classid. bool TrainingSampleSet::DeleteableSample(const TrainingSample *sample) { return sample == nullptr || sample->class_id() < 0; } // Construct an array to access the samples by font,class pair. void TrainingSampleSet::OrganizeByFontAndClass() { // Font indexes are sparse, so we used a map to compact them, so we can // have an efficient 2-d array of fonts and character classes. SetupFontIdMap(); int compact_font_size = font_id_map_.CompactSize(); // Get a 2-d array of generic vectors. delete font_class_array_; FontClassInfo empty; font_class_array_ = new GENERIC_2D_ARRAY<FontClassInfo>(compact_font_size, unicharset_size_, empty); for (int s = 0; s < samples_.size(); ++s) { int font_id = samples_[s]->font_id(); int class_id = samples_[s]->class_id(); if (font_id < 0 || font_id >= font_id_map_.SparseSize()) { tprintf("Font id = %d/%d, class id = %d/%d on sample %d\n", font_id, font_id_map_.SparseSize(), class_id, unicharset_size_, s); } ASSERT_HOST(font_id >= 0 && font_id < font_id_map_.SparseSize()); ASSERT_HOST(class_id >= 0 && class_id < unicharset_size_); int font_index = font_id_map_.SparseToCompact(font_id); (*font_class_array_)(font_index, class_id).samples.push_back(s); } // Set the num_raw_samples member of the FontClassInfo, to set the boundary // between the raw samples and the replicated ones. for (int f = 0; f < compact_font_size; ++f) { for (int c = 0; c < unicharset_size_; ++c) (*font_class_array_)(f, c).num_raw_samples = (*font_class_array_)(f, c).samples.size(); } // This is the global number of samples and also marks the boundary between // real and replicated samples. num_raw_samples_ = samples_.size(); } // Constructs the font_id_map_ which maps real font_ids (sparse) to a compact // index for the font_class_array_. void TrainingSampleSet::SetupFontIdMap() { // Number of samples for each font_id. std::vector<int> font_counts; for (int s = 0; s < samples_.size(); ++s) { const int font_id = samples_[s]->font_id(); while (font_id >= font_counts.size()) font_counts.push_back(0); ++font_counts[font_id]; } font_id_map_.Init(font_counts.size(), false); for (int f = 0; f < font_counts.size(); ++f) { font_id_map_.SetMap(f, font_counts[f] > 0); } font_id_map_.Setup(); } // Finds the sample for each font, class pair that has least maximum // distance to all the other samples of the same font, class. // OrganizeByFontAndClass must have been already called. void TrainingSampleSet::ComputeCanonicalSamples(const IntFeatureMap &map, bool debug) { ASSERT_HOST(font_class_array_ != nullptr); IntFeatureDist f_table; if (debug) tprintf("feature table size %d\n", map.sparse_size()); f_table.Init(&map); int worst_s1 = 0; int worst_s2 = 0; double global_worst_dist = 0.0; // Compute distances independently for each font and char index. int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { int font_id = font_id_map_.CompactToSparse(font_index); for (int c = 0; c < unicharset_size_; ++c) { int samples_found = 0; FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); if (fcinfo.samples.size() == 0 || (kTestChar >= 0 && c != kTestChar)) { fcinfo.canonical_sample = -1; fcinfo.canonical_dist = 0.0f; if (debug) tprintf("Skipping class %d\n", c); continue; } // The canonical sample will be the one with the min_max_dist, which // is the sample with the lowest maximum distance to all other samples. double min_max_dist = 2.0; // We keep track of the farthest apart pair (max_s1, max_s2) which // are max_max_dist apart, so we can see how bad the variability is. double max_max_dist = 0.0; int max_s1 = 0; int max_s2 = 0; fcinfo.canonical_sample = fcinfo.samples[0]; fcinfo.canonical_dist = 0.0f; for (int i = 0; i < fcinfo.samples.size(); ++i) { int s1 = fcinfo.samples[i]; const std::vector<int> &features1 = samples_[s1]->indexed_features(); f_table.Set(features1, features1.size(), true); double max_dist = 0.0; // Run the full squared-order search for similar samples. It is still // reasonably fast because f_table.FeatureDistance is fast, but we // may have to reconsider if we start playing with too many samples // of a single char/font. for (int j = 0; j < fcinfo.samples.size(); ++j) { int s2 = fcinfo.samples[j]; if (samples_[s2]->class_id() != c || samples_[s2]->font_id() != font_id || s2 == s1) continue; std::vector<int> features2 = samples_[s2]->indexed_features(); double dist = f_table.FeatureDistance(features2); if (dist > max_dist) { max_dist = dist; if (dist > max_max_dist) { max_max_dist = dist; max_s1 = s1; max_s2 = s2; } } } // Using Set(..., false) is far faster than re initializing, due to // the sparseness of the feature space. f_table.Set(features1, features1.size(), false); samples_[s1]->set_max_dist(max_dist); ++samples_found; if (max_dist < min_max_dist) { fcinfo.canonical_sample = s1; fcinfo.canonical_dist = max_dist; } UpdateRange(max_dist, &min_max_dist, &max_max_dist); } if (max_max_dist > global_worst_dist) { // Keep a record of the worst pair over all characters/fonts too. global_worst_dist = max_max_dist; worst_s1 = max_s1; worst_s2 = max_s2; } if (debug) { tprintf( "Found %d samples of class %d=%s, font %d, " "dist range [%g, %g], worst pair= %s, %s\n", samples_found, c, unicharset_.debug_str(c).c_str(), font_index, min_max_dist, max_max_dist, SampleToString(*samples_[max_s1]).c_str(), SampleToString(*samples_[max_s2]).c_str()); } } } if (debug) { tprintf("Global worst dist = %g, between sample %d and %d\n", global_worst_dist, worst_s1, worst_s2); } } // Replicates the samples to a minimum frequency defined by // 2 * kSampleRandomSize, or for larger counts duplicates all samples. // After replication, the replicated samples are perturbed slightly, but // in a predictable and repeatable way. // Use after OrganizeByFontAndClass(). void TrainingSampleSet::ReplicateAndRandomizeSamples() { ASSERT_HOST(font_class_array_ != nullptr); int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { for (int c = 0; c < unicharset_size_; ++c) { FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); int sample_count = fcinfo.samples.size(); int min_samples = 2 * std::max(kSampleRandomSize, sample_count); if (sample_count > 0 && sample_count < min_samples) { int base_count = sample_count; for (int base_index = 0; sample_count < min_samples; ++sample_count) { int src_index = fcinfo.samples[base_index++]; if (base_index >= base_count) base_index = 0; TrainingSample *sample = samples_[src_index]->RandomizedCopy(sample_count % kSampleRandomSize); int sample_index = samples_.size(); sample->set_sample_index(sample_index); samples_.push_back(sample); fcinfo.samples.push_back(sample_index); } } } } } // Caches the indexed features of the canonical samples. // ComputeCanonicalSamples must have been already called. // TODO(rays) see note on ReliablySeparable and try restricting the // canonical features to those that truly represent all samples. void TrainingSampleSet::ComputeCanonicalFeatures() { ASSERT_HOST(font_class_array_ != nullptr); const int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { const int font_id = font_id_map_.CompactToSparse(font_index); for (int c = 0; c < unicharset_size_; ++c) { int num_samples = NumClassSamples(font_id, c, false); if (num_samples == 0) continue; const TrainingSample *sample = GetCanonicalSample(font_id, c); FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); fcinfo.canonical_features = sample->indexed_features(); } } } // Computes the combined set of features used by all the samples of each // font/class combination. Use after ReplicateAndRandomizeSamples. void TrainingSampleSet::ComputeCloudFeatures(int feature_space_size) { ASSERT_HOST(font_class_array_ != nullptr); int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { int font_id = font_id_map_.CompactToSparse(font_index); for (int c = 0; c < unicharset_size_; ++c) { int num_samples = NumClassSamples(font_id, c, false); if (num_samples == 0) continue; FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); fcinfo.cloud_features.Init(feature_space_size); for (int s = 0; s < num_samples; ++s) { const TrainingSample *sample = GetSample(font_id, c, s); const std::vector<int> &sample_features = sample->indexed_features(); for (int i = 0; i < sample_features.size(); ++i) fcinfo.cloud_features.SetBit(sample_features[i]); } } } } // Adds all fonts of the given class to the shape. void TrainingSampleSet::AddAllFontsForClass(int class_id, Shape *shape) const { for (int f = 0; f < font_id_map_.CompactSize(); ++f) { const int font_id = font_id_map_.CompactToSparse(f); shape->AddToShape(class_id, font_id); } } #ifndef GRAPHICS_DISABLED // Display the samples with the given indexed feature that also match // the given shape. void TrainingSampleSet::DisplaySamplesWithFeature(int f_index, const Shape &shape, const IntFeatureSpace &space, ScrollView::Color color, ScrollView *window) const { for (int s = 0; s < num_raw_samples(); ++s) { const TrainingSample *sample = GetSample(s); if (shape.ContainsUnichar(sample->class_id())) { std::vector<int> indexed_features; space.IndexAndSortFeatures(sample->features(), sample->num_features(), &indexed_features); for (int f = 0; f < indexed_features.size(); ++f) { if (indexed_features[f] == f_index) { sample->DisplayFeatures(color, window); } } } } } #endif // !GRAPHICS_DISABLED } // namespace tesseract.
41.04194
99
0.688296
[ "shape", "vector" ]
2823c6f00e5ed290610a5588b84cc21a075c80e7
2,731
cpp
C++
dev/Gems/LyShine/Code/Tests/SerializationTest.cpp
BadDevCode/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/LyShine/Code/Tests/SerializationTest.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/LyShine/Code/Tests/SerializationTest.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "LyShine_precompiled.h" #include "LyShineTest.h" #include <UiSerialize.h> namespace UnitTest { class LyShineSerializationTest : public LyShineTest { protected: void SetupApplication() override { AZ::ComponentApplication::Descriptor appDesc; appDesc.m_memoryBlocksByteSize = 10 * 1024 * 1024; appDesc.m_recordingMode = AZ::Debug::AllocationRecords::RECORD_FULL; appDesc.m_stackRecordLevels = 20; AZ::ComponentApplication::StartupParameters appStartup; // Module needs to be created this way to create CryString allocator for test appStartup.m_createStaticModulesCallback = [](AZStd::vector<AZ::Module*>& modules) { modules.emplace_back(new LyShine::LyShineModule); }; m_systemEntity = m_application.Create(appDesc, appStartup); m_systemEntity->Init(); m_systemEntity->Activate(); } void SetupEnvironment() override { LyShineTest::SetupEnvironment(); } void TearDown() override { LyShineTest::TearDown(); } }; TEST_F(LyShineSerializationTest, Serialization_LayoutErrorsOnNullptr_FT) { AZ_TEST_START_TRACE_SUPPRESSION; UiSerialize::SetAnchorLeft(nullptr, .0f); UiSerialize::SetAnchorTop(nullptr, .0f); UiSerialize::SetAnchorRight(nullptr, .0f); UiSerialize::SetAnchorBottom(nullptr, .0f); UiSerialize::SetAnchors(nullptr, .0f, .0f, .0f, .0f); UiSerialize::SetOffsetLeft(nullptr, .0f); UiSerialize::SetOffsetTop(nullptr, .0f); UiSerialize::SetOffsetRight(nullptr, .0f); UiSerialize::SetOffsetBottom(nullptr, .0f); UiSerialize::SetOffsets(nullptr, .0f, .0f, .0f, .0f); UiSerialize::SetPaddingLeft(nullptr, 0); UiSerialize::SetPaddingTop(nullptr, 0); UiSerialize::SetPaddingRight(nullptr, 0); UiSerialize::SetPaddingBottom(nullptr, 0); UiSerialize::SetPadding(nullptr, 0, 0, 0, 0); AZ_TEST_STOP_TRACE_SUPPRESSION(15); } } //namespace UnitTest
33.716049
89
0.652508
[ "vector" ]
2826dcdb3ef1593dfa8b8bd177525e9c20e8a7a6
18,711
cc
C++
src/storage/lru_storage_test.cc
mcognetta/mozc
1f4fa17372bd196e87042738a16ab08bf904bcbf
[ "BSD-3-Clause" ]
null
null
null
src/storage/lru_storage_test.cc
mcognetta/mozc
1f4fa17372bd196e87042738a16ab08bf904bcbf
[ "BSD-3-Clause" ]
1
2021-06-30T14:59:51.000Z
2021-06-30T15:31:56.000Z
src/storage/lru_storage_test.cc
mcognetta/mozc
1f4fa17372bd196e87042738a16ab08bf904bcbf
[ "BSD-3-Clause" ]
1
2022-03-25T09:01:39.000Z
2022-03-25T09:01:39.000Z
// Copyright 2010-2020, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "storage/lru_storage.h" #include <algorithm> #include <set> #include <string> #include <utility> #include <vector> #include "base/clock_mock.h" #include "base/file_stream.h" #include "base/file_util.h" #include "base/logging.h" #include "base/port.h" #include "base/util.h" #include "storage/lru_cache.h" #include "testing/base/public/googletest.h" #include "testing/base/public/gunit.h" namespace mozc { namespace storage { namespace { const uint32 kSeed = 0x76fef; // Seed for fingerprint. std::string GenRandomString(int size) { std::string result; const size_t len = Util::Random(size) + 1; for (int i = 0; i < len; ++i) { const char32 l = Util::Random(0x1FFFF) + 1; Util::UCS4ToUTF8Append(l, &result); } return result; } void RunTest(LRUStorage *storage, uint32 size) { mozc::storage::LRUCache<std::string, uint32> cache(size); std::set<std::string> used; std::vector<std::pair<std::string, uint32> > values; for (int i = 0; i < size * 2; ++i) { const std::string key = GenRandomString(20); const uint32 value = static_cast<uint32>(Util::Random(10000000)); if (used.find(key) != used.end()) { continue; } used.insert(key); values.push_back(std::make_pair(key, value)); cache.Insert(key, value); storage->Insert(key, reinterpret_cast<const char *>(&value)); } std::reverse(values.begin(), values.end()); std::vector<std::string> value_list; storage->GetAllValues(&value_list); uint32 last_access_time; for (int i = 0; i < size; ++i) { const uint32 *v1 = cache.Lookup(values[i].first); const uint32 *v2 = reinterpret_cast<const uint32 *>( storage->Lookup(values[i].first, &last_access_time)); const uint32 *v3 = reinterpret_cast<const uint32 *>(value_list[i].data()); EXPECT_TRUE(v1 != nullptr); EXPECT_EQ(*v1, values[i].second); EXPECT_TRUE(v2 != nullptr); EXPECT_EQ(*v2, values[i].second); EXPECT_TRUE(v3 != nullptr); EXPECT_EQ(*v3, values[i].second); } for (int i = size; i < values.size(); ++i) { const uint32 *v1 = cache.Lookup(values[i].first); const uint32 *v2 = reinterpret_cast<const uint32 *>( storage->Lookup(values[i].first, &last_access_time)); EXPECT_TRUE(v1 == nullptr); EXPECT_TRUE(v2 == nullptr); } } std::vector<std::string> GetValuesInStorageOrder(const LRUStorage &storage) { std::vector<std::string> ret; for (size_t i = 0; i < storage.used_size(); ++i) { uint64 fp; std::string value; uint32 last_access_time; storage.Read(i, &fp, &value, &last_access_time); ret.push_back(value); } return ret; } } // namespace class LRUStorageTest : public ::testing::Test { protected: LRUStorageTest() {} void SetUp() override { UnlinkDBFileIfExists(); } void TearDown() override { UnlinkDBFileIfExists(); } static void UnlinkDBFileIfExists() { const std::string path = GetTemporaryFilePath(); if (FileUtil::FileExists(path)) { FileUtil::Unlink(path); } } static std::string GetTemporaryFilePath() { // This name should be unique to each test. return FileUtil::JoinPath(FLAGS_test_tmpdir, "LRUStorageTest_test.db"); } private: DISALLOW_COPY_AND_ASSIGN(LRUStorageTest); }; TEST_F(LRUStorageTest, LRUStorageTest) { const int kSize[] = {10, 100, 1000, 10000}; const std::string file = GetTemporaryFilePath(); for (int i = 0; i < arraysize(kSize); ++i) { LRUStorage::CreateStorageFile(file.c_str(), 4, kSize[i], kSeed); LRUStorage storage; EXPECT_TRUE(storage.Open(file.c_str())); EXPECT_EQ(file, storage.filename()); EXPECT_EQ(kSize[i], storage.size()); EXPECT_EQ(4, storage.value_size()); EXPECT_EQ(kSeed, storage.seed()); RunTest(&storage, kSize[i]); } } struct Entry { uint64 key; uint32 last_access_time; std::string value; }; TEST_F(LRUStorageTest, ReadWriteTest) { const int kSize[] = {10, 100, 1000, 10000}; const std::string file = GetTemporaryFilePath(); for (int i = 0; i < arraysize(kSize); ++i) { LRUStorage::CreateStorageFile(file.c_str(), 4, kSize[i], kSeed); LRUStorage storage; EXPECT_TRUE(storage.Open(file.c_str())); EXPECT_EQ(file, storage.filename()); EXPECT_EQ(kSize[i], storage.size()); EXPECT_EQ(4, storage.value_size()); EXPECT_EQ(kSeed, storage.seed()); std::vector<Entry> entries; const size_t size = kSize[i]; for (int j = 0; j < size; ++j) { Entry entry; entry.key = Util::Random(RAND_MAX); const int n = Util::Random(RAND_MAX); entry.value.assign(reinterpret_cast<const char *>(&n), 4); entry.last_access_time = Util::Random(100000); entries.push_back(entry); storage.Write(j, entry.key, entry.value, entry.last_access_time); } for (int j = 0; j < size; ++j) { uint64 key; std::string value; uint32 last_access_time; storage.Read(j, &key, &value, &last_access_time); EXPECT_EQ(entries[j].key, key); EXPECT_EQ(entries[j].value, value); EXPECT_EQ(entries[j].last_access_time, last_access_time); } } } TEST_F(LRUStorageTest, Merge) { const std::string file1 = GetTemporaryFilePath() + ".tmp1"; const std::string file2 = GetTemporaryFilePath() + ".tmp2"; // Can merge { LRUStorage::CreateStorageFile(file1.c_str(), 4, 100, kSeed); LRUStorage::CreateStorageFile(file2.c_str(), 4, 100, kSeed); LRUStorage storage; EXPECT_TRUE(storage.Open(file1.c_str())); EXPECT_TRUE(storage.Merge(file2.c_str())); } // different entry size { LRUStorage::CreateStorageFile(file1.c_str(), 4, 100, kSeed); LRUStorage::CreateStorageFile(file2.c_str(), 4, 200, kSeed); LRUStorage storage; EXPECT_TRUE(storage.Open(file1.c_str())); EXPECT_TRUE(storage.Merge(file2.c_str())); } // seed is different { LRUStorage::CreateStorageFile(file1.c_str(), 4, 100, kSeed); LRUStorage::CreateStorageFile(file2.c_str(), 4, 200, 0x76fee); LRUStorage storage; EXPECT_TRUE(storage.Open(file1.c_str())); EXPECT_FALSE(storage.Merge(file2.c_str())); } // value size is different { LRUStorage::CreateStorageFile(file1.c_str(), 4, 100, kSeed); LRUStorage::CreateStorageFile(file2.c_str(), 8, 200, kSeed); LRUStorage storage; EXPECT_TRUE(storage.Open(file1.c_str())); EXPECT_FALSE(storage.Merge(file2.c_str())); } { // Need to mock clock because old entries are removed on Open. The maximum // timestmap set below is 50, so set the current time to 100. ScopedClockMock clock(100, 0); LRUStorage::CreateStorageFile(file1.c_str(), 4, 8, kSeed); LRUStorage::CreateStorageFile(file2.c_str(), 4, 4, kSeed); LRUStorage storage1; EXPECT_TRUE(storage1.Open(file1.c_str())); storage1.Write(0, 0, "test", 1); storage1.Write(1, 1, "test", 10); storage1.Write(2, 2, "test", 20); storage1.Write(3, 3, "test", 30); LRUStorage storage2; EXPECT_TRUE(storage2.Open(file2.c_str())); storage2.Write(0, 4, "test", 2); storage2.Write(1, 5, "test", 50); EXPECT_TRUE(storage1.Merge(storage2)); uint64 fp; std::string value; uint32 last_access_time; storage1.Read(0, &fp, &value, &last_access_time); EXPECT_EQ(5, fp); EXPECT_EQ(50, last_access_time); storage1.Read(1, &fp, &value, &last_access_time); EXPECT_EQ(3, fp); EXPECT_EQ(30, last_access_time); storage1.Read(2, &fp, &value, &last_access_time); EXPECT_EQ(2, fp); EXPECT_EQ(20, last_access_time); storage1.Read(3, &fp, &value, &last_access_time); EXPECT_EQ(1, fp); EXPECT_EQ(10, last_access_time); } // same FP { // Need to mock clock because old entries are removed on Open. The maximum // timestmap set below is 50, so set the current time to 100. ScopedClockMock clock(100, 0); LRUStorage::CreateStorageFile(file1.c_str(), 4, 8, kSeed); LRUStorage::CreateStorageFile(file2.c_str(), 4, 4, kSeed); LRUStorage storage1; EXPECT_TRUE(storage1.Open(file1.c_str())); storage1.Write(0, 0, "test", 0); storage1.Write(1, 1, "test", 10); storage1.Write(2, 2, "test", 20); storage1.Write(3, 3, "test", 30); LRUStorage storage2; EXPECT_TRUE(storage2.Open(file2.c_str())); storage2.Write(0, 2, "new1", 0); storage2.Write(1, 3, "new2", 50); EXPECT_TRUE(storage1.Merge(storage2)); uint64 fp; std::string value; uint32 last_access_time; storage1.Read(0, &fp, &value, &last_access_time); EXPECT_EQ(3, fp); EXPECT_EQ(50, last_access_time); EXPECT_EQ("new2", value); storage1.Read(1, &fp, &value, &last_access_time); EXPECT_EQ(2, fp); EXPECT_EQ(20, last_access_time); EXPECT_EQ("test", value); storage1.Read(2, &fp, &value, &last_access_time); EXPECT_EQ(1, fp); EXPECT_EQ(10, last_access_time); storage1.Read(3, &fp, &value, &last_access_time); EXPECT_EQ(0, fp); EXPECT_EQ(0, last_access_time); } FileUtil::Unlink(file1); FileUtil::Unlink(file2); } TEST_F(LRUStorageTest, InvalidFileOpenTest) { LRUStorage storage; EXPECT_FALSE(storage.Insert("test", nullptr)); const std::string filename = GetTemporaryFilePath(); FileUtil::Unlink(filename); // cannot open EXPECT_FALSE(storage.Open(filename.c_str())); EXPECT_FALSE(storage.Insert("test", nullptr)); } TEST_F(LRUStorageTest, OpenOrCreateTest) { const std::string file = GetTemporaryFilePath(); { OutputFileStream ofs(file.c_str()); ofs << "test"; } { LRUStorage storage; EXPECT_FALSE(storage.Open(file.c_str())) << "Corrupted file should be detected as an error."; } { LRUStorage storage; EXPECT_TRUE(storage.OpenOrCreate(file.c_str(), 4, 10, kSeed)) << "Corrupted file should be replaced with new one."; uint32 v = 823; storage.Insert("test", reinterpret_cast<const char *>(&v)); const uint32 *result = reinterpret_cast<const uint32 *>(storage.Lookup("test")); CHECK_EQ(v, *result); } } TEST_F(LRUStorageTest, Delete) { ScopedClockMock clock(1, 0); clock->SetAutoPutClockForward(1, 0); const size_t kValueSize = 4; const size_t kNumElements = 4; LRUStorage storage; ASSERT_TRUE(storage.OpenOrCreate(GetTemporaryFilePath().c_str(), kValueSize, kNumElements, kSeed)); EXPECT_TRUE(storage.Delete("nothing to delete")); struct { const char *key; const char *value; } kElements[kNumElements] = { // Elements are inserted into the storage in this order. {"0000", "aaaa"}, {"1111", "bbbb"}, {"2222", "cccc"}, {"3333", "dddd"}, }; for (const auto &kv : kElements) { EXPECT_TRUE(storage.Insert(kv.key, kv.value)); } // Test the case where the element to be deleted is at the last slot of // mmapped region. EXPECT_TRUE(storage.Delete("3333")); std::vector<std::string> expected = {"aaaa", "bbbb", "cccc"}; EXPECT_EQ(expected, GetValuesInStorageOrder(storage)); EXPECT_EQ(3, storage.used_size()); EXPECT_EQ("aaaa", storage.LookupAsString("0000")); EXPECT_EQ("bbbb", storage.LookupAsString("1111")); EXPECT_EQ("cccc", storage.LookupAsString("2222")); EXPECT_TRUE(storage.Lookup("3333") == nullptr); // Remove the element ("1111", "bbbb") in the middle. The current // last element, ("2222", "cccc") should be moved to keep contiguity. EXPECT_TRUE(storage.Delete("1111")); EXPECT_EQ(2, storage.used_size()); EXPECT_EQ("aaaa", storage.LookupAsString("0000")); EXPECT_EQ("cccc", storage.LookupAsString("2222")); EXPECT_TRUE(storage.Lookup("1111") == nullptr); EXPECT_TRUE(storage.Lookup("3333") == nullptr); expected = {"aaaa", "cccc"}; EXPECT_EQ(expected, GetValuesInStorageOrder(storage)); // Insert a new element ("4444", "eeee"). EXPECT_TRUE(storage.Insert("4444", "eeee")); EXPECT_EQ(3, storage.used_size()); EXPECT_EQ("aaaa", storage.LookupAsString("0000")); EXPECT_EQ("cccc", storage.LookupAsString("2222")); EXPECT_EQ("eeee", storage.LookupAsString("4444")); EXPECT_TRUE(storage.Lookup("1111") == nullptr); EXPECT_TRUE(storage.Lookup("3333") == nullptr); expected = {"aaaa", "cccc", "eeee"}; EXPECT_EQ(expected, GetValuesInStorageOrder(storage)); // Remove the beginning ("0000", "aaaa"). EXPECT_TRUE(storage.Delete("0000")); EXPECT_EQ(2, storage.used_size()); EXPECT_EQ("cccc", storage.LookupAsString("2222")); EXPECT_EQ("eeee", storage.LookupAsString("4444")); EXPECT_TRUE(storage.Lookup("0000") == nullptr); EXPECT_TRUE(storage.Lookup("1111") == nullptr); EXPECT_TRUE(storage.Lookup("3333") == nullptr); expected = {"eeee", "cccc"}; // "eeee" was moved to the position of "aaaa". EXPECT_EQ(expected, GetValuesInStorageOrder(storage)); // Remove ("4444", "eeee") EXPECT_TRUE(storage.Delete("4444")); EXPECT_EQ(1, storage.used_size()); EXPECT_TRUE(storage.Lookup("0000") == nullptr); EXPECT_TRUE(storage.Lookup("1111") == nullptr); EXPECT_TRUE(storage.Lookup("3333") == nullptr); EXPECT_TRUE(storage.Lookup("4444") == nullptr); expected = {"cccc"}; EXPECT_EQ(expected, GetValuesInStorageOrder(storage)); EXPECT_TRUE(storage.Delete("2222")); EXPECT_EQ(0, storage.used_size()); EXPECT_TRUE(storage.Lookup("0000") == nullptr); EXPECT_TRUE(storage.Lookup("1111") == nullptr); EXPECT_TRUE(storage.Lookup("2222") == nullptr); EXPECT_TRUE(storage.Lookup("3333") == nullptr); EXPECT_TRUE(storage.Lookup("4444") == nullptr); } TEST_F(LRUStorageTest, DeleteElementsBefore) { ScopedClockMock clock(1, 0); const size_t kValueSize = 4; const size_t kNumElements = 4; LRUStorage storage; ASSERT_TRUE(storage.OpenOrCreate(GetTemporaryFilePath().c_str(), kValueSize, kNumElements, kSeed)); // Auto advance clock after opening the file; otherwise OpenOrCreate() // advances the clock. clock->SetAutoPutClockForward(1, 0); struct { const char *key; const char *value; } kElements[kNumElements] = { // Elements are inserted into the storage in this order. The above clock // mock gives timestamps 1 to 4. {"1111", "aaaa"}, // Timestamp 1 {"2222", "bbbb"}, // Timestamp 2 {"3333", "cccc"}, // Timestamp 3 {"4444", "dddd"}, // Timestamp 4 }; for (const auto &kv : kElements) { storage.Insert(kv.key, kv.value); } std::vector<std::string> values; storage.GetAllValues(&values); const std::vector<std::string> kExpectedAfterInsert = { "dddd", "cccc", "bbbb", "aaaa", }; EXPECT_EQ(kExpectedAfterInsert, values); // Should remove "1111" and "2222". EXPECT_EQ(2, storage.DeleteElementsBefore(3)); values.clear(); storage.GetAllValues(&values); const std::vector<std::string> kExpectedAfterDelete = { "dddd", "cccc", }; EXPECT_EQ(kExpectedAfterDelete, values); } TEST_F(LRUStorageTest, DeleteElementsUntouchedFor62Days) { ScopedClockMock clock(1, 0); const size_t kValueSize = 4; const size_t kNumElements = 4; LRUStorage storage; ASSERT_TRUE(storage.OpenOrCreate(GetTemporaryFilePath().c_str(), kValueSize, kNumElements, kSeed)); // Auto advance clock after opening the file; otherwise OpenOrCreate() // advances the clock. clock->SetAutoPutClockForward(1, 0); storage.Insert("1111", "aaaa"); storage.Insert("2222", "bbbb"); // Advance clock for 63 days. clock->PutClockForward(63 * 24 * 60 * 60, 0); // Insert newer elements. storage.Insert("3333", "cccc"); storage.Insert("4444", "dddd"); EXPECT_EQ(2, storage.DeleteElementsUntouchedFor62Days()); std::vector<std::string> values; storage.GetAllValues(&values); const std::vector<std::string> kExpectedAfterDelete = { "dddd", "cccc", }; EXPECT_EQ(kExpectedAfterDelete, values); } TEST_F(LRUStorageTest, OldDataAreNotLookedUp) { ScopedClockMock clock(1, 0); const size_t kValueSize = 4; const size_t kNumElements = 4; LRUStorage storage; ASSERT_TRUE(storage.OpenOrCreate(GetTemporaryFilePath().c_str(), kValueSize, kNumElements, kSeed)); EXPECT_TRUE(storage.Insert("1111", "aaaa")); EXPECT_TRUE(storage.Insert("2222", "bbbb")); // The two elements can be looked up as they are still not 62-day old. EXPECT_EQ("aaaa", storage.LookupAsString("1111")); EXPECT_EQ("bbbb", storage.LookupAsString("2222")); EXPECT_TRUE(storage.Touch("1111")); EXPECT_TRUE(storage.Touch("2222")); // Advance clock for 63 days. clock->PutClockForward(63 * 24 * 60 * 60, 0); // Insert new elements. EXPECT_TRUE(storage.Insert("3333", "cccc")); EXPECT_TRUE(storage.Insert("4444", "dddd")); // The old two cannot be looked up. EXPECT_TRUE(storage.Lookup("1111") == nullptr); EXPECT_TRUE(storage.Lookup("2222") == nullptr); EXPECT_FALSE(storage.Touch("1111")); EXPECT_FALSE(storage.Touch("2222")); // But the new ones are accessible. EXPECT_EQ("cccc", storage.LookupAsString("3333")); EXPECT_EQ("dddd", storage.LookupAsString("4444")); EXPECT_TRUE(storage.Touch("3333")); EXPECT_TRUE(storage.Touch("4444")); } } // namespace storage } // namespace mozc
31.984615
79
0.674256
[ "vector" ]
282713f9d59dcaae5fe6f71b5b23b9fe5e7e5bba
3,338
cpp
C++
pickup.cpp
matt360/PSVita-game
9dc4163c3256b0d3ee23a5c4730af4d4c11a9491
[ "MIT" ]
2
2019-11-18T09:12:44.000Z
2020-08-18T11:08:44.000Z
pickup.cpp
matt360/PSVita-game
9dc4163c3256b0d3ee23a5c4730af4d4c11a9491
[ "MIT" ]
null
null
null
pickup.cpp
matt360/PSVita-game
9dc4163c3256b0d3ee23a5c4730af4d4c11a9491
[ "MIT" ]
2
2019-06-28T16:44:42.000Z
2021-04-11T17:06:58.000Z
#include "pickup.h" Pickup::Pickup() { } Pickup::~Pickup() { //this->GetBody()->GetWorld()->DestroyBody(this->GetBody()); this->GetBody()->SetActive(false); } void Pickup::InitPickup( PrimitiveBuilder* primitive_builder, b2World* world, b2Vec2 position, float32 radius, gef::Mesh* mesh, uint16 category_bits, uint16 mask_bits, uint16 group_index, OBJECT_TYPE type) { // setup the mesh for the pickup // set from a model set_mesh(mesh); // create a physics body for the pickup b2BodyDef pickup_body_def; pickup_body_def.type = b2_staticBody; pickup_body_def.position = position; pickup_body_def.angle = 0.0f; SetBody(world->CreateBody(&pickup_body_def)); // create the shape for the pickup b2CircleShape pickup_shape; pickup_shape.m_radius = radius; // create the fixture b2FixtureDef pickup_fixture_def; pickup_fixture_def.shape = &pickup_shape; pickup_fixture_def.density = 1.0f; pickup_fixture_def.isSensor = true; // filter mask fixture definition // I am a ... (category_bits) pickup_fixture_def.filter.categoryBits = category_bits; // I collide with ... (mask_bits) pickup_fixture_def.filter.maskBits = mask_bits; // group index // if both groupIndex values are the same and positive, collide // if both groupIndex values are the same and negative, don't collide pickup_fixture_def.filter.groupIndex = group_index; SetGameObjectType(type); SetGameObjectColour(NO_COL); // create the fixture on the rigid body GetBody()->CreateFixture(&pickup_fixture_def); // update visuals from simulation data UpdateFromSimulation(GetBody()); // create a connection between the rigid body and GameObject GetBody()->SetUserData(this); } // !InitPickup void Pickup::InitPickup( PrimitiveBuilder* primitive_builder, b2World* world, b2Vec2 position, float32 radius, uint16 category_bits, uint16 mask_bits, uint16 group_index, OBJECT_TYPE type) { // set from the primitive builder set_mesh(primitive_builder->CreateSphereMesh(radius, 10, 10, gef::Vector4(0.0f, 0.0f, 0.0f), (gef::Material*)(&primitive_builder->green_material()))); // create a physics body for the pickup b2BodyDef pickup_body_def; pickup_body_def.type = b2_staticBody; pickup_body_def.position = position; pickup_body_def.angle = 0.0f; SetBody(world->CreateBody(&pickup_body_def)); // create the shape for the pickup b2CircleShape pickup_shape; pickup_shape.m_radius = radius; // create the fixture b2FixtureDef pickup_fixture_def; pickup_fixture_def.shape = &pickup_shape; pickup_fixture_def.density = 1.0f; pickup_fixture_def.isSensor = true; // filter mask fixture definition // I am a ... (category_bits) pickup_fixture_def.filter.categoryBits = category_bits; // I collide with ... (mask_bits) pickup_fixture_def.filter.maskBits = mask_bits; // group index // if both groupIndex values are the same and positive, collide // if both groupIndex values are the same and negative, don't collide pickup_fixture_def.filter.groupIndex = group_index; SetGameObjectType(type); SetGameObjectColour(NO_COL); // create the fixture on the rigid body GetBody()->CreateFixture(&pickup_fixture_def); // update visuals from simulation data UpdateFromSimulation(GetBody()); // create a connection between the rigid body and GameObject GetBody()->SetUserData(this); } // !InitPickup
27.816667
151
0.760336
[ "mesh", "shape", "model" ]
2829617afe0a2421431b7002bc78f85b495fb0e4
520
cpp
C++
CodeForces/Complete/500-599/525B-PashaAndString.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/500-599/525B-PashaAndString.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/500-599/525B-PashaAndString.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <iostream> #include <vector> int main(){ std::string s; getline(std::cin, s); long m; std::cin >> m; std::vector<long> rev(s.size() + 1, 0); for(int p = 0; p < m; p++){ long a; std::cin >> a; --a; ++rev[a]; --rev[s.size() - a]; } int reversals(0); std::string ans(s); for(int p = 0; p < s.size(); p++){ reversals += rev[p]; reversals %= 2; if(reversals){ans[p] = s[s.size() - p - 1];} } std::cout << ans << std::endl; return 0; }
20.8
52
0.465385
[ "vector" ]
2829b7fc3eebc179428a816460900ead42bd9848
6,645
cpp
C++
Silence/forest.cpp
wt-student-projects/games-technology-project
70790e26f087fd401b0211a59b7c2beaef9546c9
[ "Apache-2.0" ]
null
null
null
Silence/forest.cpp
wt-student-projects/games-technology-project
70790e26f087fd401b0211a59b7c2beaef9546c9
[ "Apache-2.0" ]
4
2016-07-15T21:23:08.000Z
2016-08-28T21:40:16.000Z
Silence/forest.cpp
wt-student-projects/games-technology-project
70790e26f087fd401b0211a59b7c2beaef9546c9
[ "Apache-2.0" ]
null
null
null
#include "Forest.h" #include "Silence.h" Forest::Forest(OperatingSystem * engine) : player(nullptr), alpha(0.0) { manager = engine->acquireSceneManager(); gamepad = engine->acquireGamepad(); package = engine->acquireAssetManager()->grabLocalManager(); package->grab({ "data/fonts/Calibri.ttf", "data/models/house/br_house1.md3", "data/textures/grass.png", "data/textures/dirt.png", "data/textures/pathways.png", "data/models/wall/wall.obj", "data/models/tree/tree1a_lod0.obj", "data/textures/ai_path2.png", "data/models/gate/SecurityGate.obj", "data/models/rocks/obj.obj" }); backgroundMusic.open(package->newAudio("data/media/main.wav", StreamLoop)); torchSound.open(package->newAudio("data/media/torch.mp3", Load)); } Forest::~Forest() { SAFE_RELEASE(package); } void Forest::onGamepadButton(int key, int state) { if (key == SDL_CONTROLLER_BUTTON_BACK && state == GamepadButtonPressed) { manager->exit(); } if (key == SDL_CONTROLLER_BUTTON_X && state == GamepadButtonPressed) { if (player->hasTorch()) { torchSound.reset(); torchSound.play(); torch.toggle(); } } player->onGamepadButton(static_cast<FirstPersonCamera *>(renderer3D.getCamera()), key, state); } void Forest::onGamepadAxis(int i, float x) { renderer3D.onGamepadAxis(i, x); } void Forest::onCreate() { matrices.makeProjection3D(60.0f, glm::vec2(0.1f, 300.0f)); terrain.create(package, world); monster.create(package); house.create(package); gate.create(package, world, manager); renderer3D.createRenderer(); renderer3D.changeCamera(CameraType::FirstPerson); renderer3D.setCameraDirection(180, 0); renderer3D.setCameraArea(glm::vec4(-7500.0f, -2500.0f, 7500.0, 2500.0f)); renderer3D.setCameraPosition(glm::vec3(0.0, 8.0, -35.0)); const auto lights = renderer3D.getLights(); nightLight.setDirection(vec3(0.0, -1.0, -0.3)); nightLight.setColour(vec3(1.4, 0.7, 0.7)); nightLight.turnOn(); torch.setDirection(vec3(0.0, 0.0, 1.0)); torch.setPosition(vec3(0.0, 0.0, 0.0)); torch.setColour(vec3(0.75, 0.75, 0.75)); torch.setAttribuation(0.02); torch.setConeAngle(25.0); player = static_cast<Indoors *>(manager->getScene(int(SceneID::Indoors)))->getPlayer(); if (player->hasTorch()) { torch.turnOn(); } else { torch.turnOff(); } point.setPosition(vec3(key.getPosition())); point.setColour(vec3(0.35, 0.2, 0.0)); point.setAttribuation(glm::vec4(0.1f, 0.3f, 0.007f, 0.0016f)); point.turnOn(); const auto callback = [&](Camera * c, SolidBox *) { c->cancelMovement(); }; world.onHit(new SolidBox(vec3(-78.0f, -1.0, -28.0f), vec3(78.0f, 1.0, 28.0f)), callback); world.onHit(new SolidBox(vec3(-75.0f, -1.0, 48.0f), vec3(-15.0f, 1.0, 53.0f)), callback); world.onHit(new SolidBox(vec3(12, -1.0, 48.0f), vec3(75, 1.0, 53.0f)), callback); world.setPlayerCamera(renderer3D.getCamera()); key.create(static_cast<Indoors *>(manager->getScene(int(SceneID::Indoors)))->getKey(), package); key.spawn(world, &point); pickups.create(package, world, player); pickups.getLights(lights); lights->pushDirectionalLight(&nightLight); lights->pushPointLight(&point); lights->pushSpotLight(&torch); footSteps.open(package->newAudio("data/media/footsteps.mp3", LoadLoop)); sign.open(package->newAudio("data/media/sign.mp3", Load)); roar.open(package->newAudio("data/media/roar.mp3", Load)); } void Forest::onGameEvent(SDL_Event& e) { renderer3D.updateCamera(e); terrain.event(e); if (e.key.keysym.sym == SDLK_f && e.type == SDL_KEYUP) { if (player->hasTorch()) { torchSound.reset(); torchSound.play(); torch.toggle(); } } player->onKeyEvent(static_cast<FirstPersonCamera *>(renderer3D.getCamera()), e.key.keysym.sym, e.type); } void Forest::onUpdate() { auto camera = static_cast<FirstPersonCamera *>(renderer3D.getCamera()); camera->prepareCamera(); terrain.update(renderer3D); gate.update(&key); house.update(); player->update(camera, &monster); if (alpha < 1.0f) { alpha += 0.005f; } monster.update(renderer3D.getCamera()); pickups.update(camera); if (monster.isCloseToPlayer(renderer3D.getCamera()->getPosition())) { sign.play(); } else { sign.reset(); } if (monster.getTravel() >= 1.0) { roar.play(); } if (monster.isActive()) { auto length = glm::length(glm::distance(monster.getPosition(), renderer3D.getCamera()->getPosition())); if (gamepad->isConnected() && timer.elapsed(Milliseconds) >= length) { gamepad->rumble(0.75, 100); timer.clear(); timer.start(); } } else { if (gamepad->isConnected() && timer.elapsed(Milliseconds) >= 1000) { gamepad->rumble(0.75, 100); timer.clear(); timer.start(); } } if (monster.hasKilledPlayer(renderer3D.getCamera()->getPosition())) { manager->switchScene(int(SceneID::Gameover)); } else { if (camera->getSpeed() < 0.01) { footSteps.pause(); } else { footSteps.play(); } } renderer3D.repositionCamera(); world.updateWorld(); } void Forest::onEnter(int i) { renderer3D.setCameraPosition(glm::vec3(0.0, 8.0, -35.0)); renderer3D.setCameraDirection(180, 0); backgroundMusic.play(); renderer3D.enableFog(); survivalTimer.start(); footSteps.reset(); alpha = 0.0f; timer.start(); monster.reset(); roar.reset(); } void Forest::onRender() { renderer3D.prepare(); renderer3D.setProjectionMatrix(matrices); renderer3D.setModelMatrix(matrices); renderer3D.setAlpha(alpha); terrain.render(renderer3D); monster.render(renderer3D); house.render(renderer3D); key.render(renderer3D); gate.render(renderer3D); pickups.render(renderer3D); renderer3D.present(); } void Forest::onExit(int i) { SDL_SetRelativeMouseMode(SDL_FALSE); backgroundMusic.stop(); footSteps.pause(); roar.reset(); roar.play(); player->reset(); gate.reset(); key.reset(); } HighPrecisionTimer * Forest::getForestTime() { return &survivalTimer; }
25.170455
111
0.60933
[ "render" ]
2829cdc1073ec20c03bbcde193de20ab1d0f8022
11,156
hpp
C++
lib/include/dcs/testbed/rain/sensors.hpp
sguazt/prometheus
03cdf3ccb283ed69c6fb84f18d89118abf95f837
[ "Apache-2.0" ]
null
null
null
lib/include/dcs/testbed/rain/sensors.hpp
sguazt/prometheus
03cdf3ccb283ed69c6fb84f18d89118abf95f837
[ "Apache-2.0" ]
null
null
null
lib/include/dcs/testbed/rain/sensors.hpp
sguazt/prometheus
03cdf3ccb283ed69c6fb84f18d89118abf95f837
[ "Apache-2.0" ]
null
null
null
/** * \file dcs/testbed/rain/sensors.hpp * * \brief Sensor for RAIN-driven applications. * * \author Marco Guazzone (marco.guazzone@gmail.com) * * <hr/> * * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DCS_TESTBED_RAIN_SENSORS_HPP #define DCS_TESTBED_RAIN_SENSORS_HPP #include <cctype> #include <cstddef> #include <ctime> #include <dcs/debug.hpp> #include <dcs/testbed/base_sensor.hpp> #include <fstream> #include <ios> #include <string> #include <vector> namespace dcs { namespace testbed { namespace rain { template <typename TraitsT> class response_time_sensor: public base_sensor<TraitsT> { private: typedef base_sensor<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::observation_type observation_type; public: response_time_sensor(std::string const& metrics_file_path) : metrics_file_(metrics_file_path), fpos_(0) // new_data_(false) { } private: void do_sense() { DCS_DEBUG_TRACE("BEGIN Do Sense"); // Available fields in a row (each field is separated by one or more white-spaces): // - '[' <generated-during> ']' // - <finished-timestamp> // - <operation name> // - <response time> // - '[' <operation request> ']' // - <total response time> // - <number of observations> const std::size_t timestamp_field(2); const std::size_t operation_field(3); const std::size_t response_time_field(4); //const std::size_t max_open_trials(50); // reset last sensing obs_.clear(); if (!ifs_.good() || !ifs_.is_open()) { // Found EOF. Two possible reasons: // 1. There is no data to read // 2. There is new data but we need to refresh input buffers // Investigate... if (ifs_.is_open()) { ifs_.close(); } ifs_.open(metrics_file_.c_str(), std::ios_base::ate); if (ifs_.good()) { ifs_.sync(); std::ifstream::pos_type new_fpos(ifs_.tellg()); //DCS_DEBUG_TRACE("REOPENED (good) -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_) << " - IN_AVAIL: " << ifs_.rdbuf()->in_avail()); if (fpos_ != new_fpos) { // The file has changed, we are in case #2 // Restart to read file from the old position ifs_.seekg(fpos_); // new_data_ = true; //DCS_DEBUG_TRACE("SOUGHT IFS STREAM -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); } else { ifs_.close(); } } } // Collect all available metrics entries while (ifs_.good() && ifs_.is_open()) { fpos_ = ifs_.tellg(); std::string line; std::getline(ifs_, line); //DCS_DEBUG_TRACE("IFS STREAM -- LINE: " << line << " - POS: " << fpos_ << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); const std::size_t n(line.size()); if (!ifs_.good() || n == 0) { continue; } std::time_t obs_ts = 0; // timestamp (in msecs from Epoch) std::string obs_op; // Operation label long obs_rtns = 0; // response time (in ns) std::size_t field = 0; for (std::size_t pos = 0; pos < n; ++pos) { // eat all heading space for (; pos < n && std::isspace(line[pos]); ++pos) { ; } if (pos < n) { ++field; switch (field) { case timestamp_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_ts; //DCS_DEBUG_TRACE("Timestamp: " << obs_ts); pos = pos2; break; } case operation_field: { std::size_t pos2(pos); //for (; pos2 < n && std::isalpha(line[pos2]); ++pos2) for (; pos2 < n && !std::isspace(line[pos2]); ++pos2) { ; } obs_op = line.substr(pos, pos2-pos); //DCS_DEBUG_TRACE("Operation: " << obs_op); pos = pos2; break; } case response_time_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_rtns; //DCS_DEBUG_TRACE("Response Time (nsecs): " << obs_rtns); pos = pos2; break; } default: // skip these fields for (; pos < n && !std::isspace(line[pos]); ++pos) { ; } break; } } } obs_.push_back(observation_type(obs_ts*1.0e-3, obs_op, obs_rtns*1.0e-9)); } DCS_DEBUG_TRACE("END Do Sense"); } private: void do_reset() { if (ifs_.is_open()) { ifs_.close(); } fpos_ = 0; //new_data_ = false; obs_.clear(); } private: bool do_has_observations() const { return obs_.size() > 0; } private: std::vector<observation_type> do_observations() const { return obs_; } private: std::string metrics_file_; private: std::ifstream ifs_; private: std::ifstream::pos_type fpos_; // private: bool new_data_; private: std::vector<observation_type> obs_; }; // response_time_sensor template <typename TraitsT> class throughput_sensor: public base_sensor<TraitsT> { private: typedef base_sensor<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::observation_type observation_type; public: throughput_sensor(std::string const& metrics_file_path) : metrics_file_(metrics_file_path), fpos_(0) // new_data_(false) { } private: void do_sense() { DCS_DEBUG_TRACE("BEGIN Do Sense"); // Available fields in a row (each field is separated by one or more white-spaces): // - '[' <generated-during> ']' // - <finished-timestamp> // - <operation name> // - <response time> // - '[' <operation request> ']' // - <total response time> // - <number of observations> const std::size_t timestamp_field(2); const std::size_t operation_field(3); const std::size_t num_observations_field(7); std::time_t first_obs_ts = -1; // timestamp (in secs from Epoch) of the first observation //const std::size_t max_open_trials(50); // reset last sensing obs_.clear(); if (!ifs_.good() || !ifs_.is_open()) { // Found EOF. Two possible reasons: // 1. There is no data to read // 2. There is new data but we need to refresh input buffers // Investigate... if (ifs_.is_open()) { ifs_.close(); } ifs_.open(metrics_file_.c_str(), std::ios_base::ate); if (ifs_.good()) { ifs_.sync(); std::ifstream::pos_type new_fpos(ifs_.tellg()); //DCS_DEBUG_TRACE("REOPENED (good) -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_) << " - IN_AVAIL: " << ifs_.rdbuf()->in_avail()); if (fpos_ != new_fpos) { // The file has changed, we are in case #2 // Restart to read file from the old position ifs_.seekg(fpos_); // new_data_ = true; //DCS_DEBUG_TRACE("SOUGHT IFS STREAM -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); } else { ifs_.close(); } } } // Collect all available metrics entries while (ifs_.good() && ifs_.is_open()) { fpos_ = ifs_.tellg(); std::string line; std::getline(ifs_, line); //DCS_DEBUG_TRACE("IFS STREAM -- LINE: " << line << " - POS: " << fpos_ << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); const std::size_t n = line.size(); if (!ifs_.good() || n == 0) { continue; } std::time_t obs_ts = -1; // timestamp (in secs from Epoch) std::string obs_op; // Operation label unsigned long num_obs = 0; // number of observations std::size_t field = 0; for (std::size_t pos = 0; pos < n; ++pos) { // eat all heading space for (; pos < n && std::isspace(line[pos]); ++pos) { ; } if (pos < n) { ++field; switch (field) { case timestamp_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_ts; //DCS_DEBUG_TRACE("Timestamp: " << obs_ts); pos = pos2; break; } case operation_field: { std::size_t pos2(pos); //for (; pos2 < n && std::isalpha(line[pos2]); ++pos2) for (; pos2 < n && !std::isspace(line[pos2]); ++pos2) { ; } obs_op = line.substr(pos, pos2-pos); //DCS_DEBUG_TRACE("Operation: " << obs_op); pos = pos2; break; } case num_observations_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> num_obs; //DCS_DEBUG_TRACE("Number of Observations: " << num_obs); pos = pos2; break; } default: // skip these fields for (; pos < n && !std::isspace(line[pos]); ++pos) { ; } break; } } } // Record this observation only if it is not the first observation if (first_obs_ts == -1) { first_obs_ts = obs_ts; } else { obs_.push_back(observation_type(obs_ts, obs_op, num_obs/((obs_ts-first_obs_ts)*1e-3))); } } DCS_DEBUG_TRACE("END Do Sense"); } private: void do_reset() { if (ifs_.is_open()) { ifs_.close(); } fpos_ = 0; //new_data_ = false; obs_.clear(); } private: bool do_has_observations() const { return obs_.size() > 0; } private: std::vector<observation_type> do_observations() const { return obs_; } private: std::string metrics_file_; private: std::ifstream ifs_; private: std::ifstream::pos_type fpos_; // private: bool new_data_; private: std::vector<observation_type> obs_; }; // response_time_sensor }}} // Namespace dcs::testbed::rain #endif // DCS_TESTBED_RAIN_SENSORS_HPP
25.824074
294
0.584797
[ "vector" ]
282de800fa7f0908837732bf2711bb57cd0ba711
2,489
cpp
C++
lesson01/src/main.cpp
QwintenParker/CPPExercises2021
dac568fd46fca2cf144cbe01551913deb133cef4
[ "MIT" ]
1
2021-09-22T08:48:24.000Z
2021-09-22T08:48:24.000Z
lesson01/src/main.cpp
QwintenParker/CPPExercises2021
dac568fd46fca2cf144cbe01551913deb133cef4
[ "MIT" ]
null
null
null
lesson01/src/main.cpp
QwintenParker/CPPExercises2021
dac568fd46fca2cf144cbe01551913deb133cef4
[ "MIT" ]
null
null
null
#include <iostream> // таким образом подключаются системные библиотеки (эта нужна для вывода в консоль) #include <vector> // подключаем библиотеку для поддержки вектора (массива динамического размера) // таким образом подключаются наши функции #include "simple_sum.h" #include "some_math.h" int main() { // таким образом выводятся сообщения в консоль // std::cout = "standard console output" = поток информации в консоль // std::endl = "standard end of line" = конец строчки (то же что и "\n") std::cout << "Hello World!" << std::endl; int a = 10; std::cout << "Please enter b="; int b; std::cin >> b; // считываем из консоли переменную std::cout << "b=" << b << std::endl; // TODO 01 чтобы телепортироваться внутрь функции - попробуйте удерживая CTRL кликнуть мышкой по функции, например по sum (она засветится как портал) int res = sum(a, b); std::cout << "a+b=" << a << "+" << b << "=" << res << std::endl; // TODO 06 выведите в консоль чему равно fibbonachiFast(b), не забудьте что нужно добавить не хватающий инклюд - some_math.h в которой объявлена эта функция std::cout << "fib(b)=" << fibbonachiFast(b) << std::endl; std::vector<double> values; std::cout << "values size: " << values.size() << std::endl; values.push_back(10); std::cout << "values size after push_back: " << values.size() << std::endl; values.push_back(20); values.push_back(35); values.push_back(4); std::cout << "values size after more push_back: " << values.size() << std::endl; // TODO 07 выведите в консоль каждый элемент из динамического массива for (int i = 0; i < values.size(); ++i) { double x = values[i]; if (i == values.size() - 1) { std::cout << x << std::endl; } else { std::cout << x << "," << std::ends; } } // TODO 08 считывайте числа из консоли (и добавляйте их в вектор) до тех пор пока не будет введен ноль, после чего просуммируйте считанные числа и выведите сумму //std::vector<double> val; int c; double sum = 0; std::cin >> c; while (c != 0) { values.push_back(c); sum = sum + c; std::cin >> c; if (c == 0) { std::cout << "sum=" << sum << std::endl; break; } } std::vector<double> xs = solveSquare(1.0, 4.0, -6.0); std::cout << xs.size() << std::endl; std::cout << xs[0] << ", " << xs[1] << std::endl; return 0; }
36.072464
165
0.588992
[ "vector" ]
28310d8ab7f7372d7575e9cd480445f90ad2caeb
45,615
cpp
C++
src/gausskernel/runtime/executor/execClusterResize.cpp
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
360
2020-06-30T14:47:34.000Z
2022-03-31T15:21:53.000Z
src/gausskernel/runtime/executor/execClusterResize.cpp
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
4
2020-06-30T15:09:16.000Z
2020-07-14T06:20:03.000Z
src/gausskernel/runtime/executor/execClusterResize.cpp
futurewei-cloud/chogori-opengauss
f43410e1643c887819e718d9baceb9e853ad9574
[ "MulanPSL-1.0" ]
133
2020-06-30T14:47:36.000Z
2022-03-25T15:29:00.000Z
/* ------------------------------------------------------------------------- * * execClusterResize.cpp * MPPDB ClusterResizing relevant routines * * Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd. * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/gausskernel/runtime/executor/execClusterResize.cpp * * ------------------------------------------------------------------------- */ #include "postgres.h" #include "knl/knl_variable.h" #include "access/tableam.h" #include "catalog/heap.h" #include "catalog/index.h" #include "catalog/namespace.h" #include "catalog/pg_namespace.h" #include "catalog/pgxc_group.h" #include "executor/executor.h" #include "executor/node/nodeModifyTable.h" #include "optimizer/clauses.h" #include "parser/analyze.h" #include "parser/parsetree.h" #include "pgxc/pgxc.h" #include "pgxc/redistrib.h" #include "tcop/utility.h" #include "utils/builtins.h" #include "utils/elog.h" #include "utils/guc.h" #include "utils/inval.h" #include "utils/lsyscache.h" #include "utils/rel.h" #include "utils/rel_gs.h" #include "utils/syscache.h" #include "utils/snapmgr.h" #include "storage/lmgr.h" #include "postgres_ext.h" /* * --------------------------------------------------------------------------------- * *Local functions/variables declaration fields* * --------------------------------------------------------------------------------- */ /* delete delta table definition */ #define Natts_pg_delete_delta 3 #define Anum_pg_delete_delta_xcnodeid_and_dntableoid 1 #define Anum_pg_delete_delta_tablebucketid_and_ctid 2 #define RANGE_SCAN_IN_REDIS "tidge+tid+pg_get_redis_rel_start_ctid+tidle+tid+pg_get_redis_rel_end_ctid+" static Node* eval_dnstable_func_mutator( Relation rel, Node* node, StringInfo qual_str, RangeScanInRedis *rangeScanInRedis, bool isRoot); static inline bool redis_tupleid_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs); static inline bool redis_blocknum_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs); static inline bool redis_offset_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs); #define REDIS_TUPLEID_RETRIVE_FUNCSIG(rettype, argstype, nargs) \ (((nargs) == 1 && (rettype) == TIDOID && (argstype)[0] == TEXTOID) || \ ((nargs) == 4 && (rettype) == TIDOID && (argstype)[0] == TEXTOID && (argstype)[1] == NAMEOID && \ (argstype)[2] == INT4OID && (argstype)[3] == INT4OID)) static inline bool redis_tupleid_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs) { if (pg_strcasecmp(funcname, "pg_get_redis_rel_start_ctid") == 0 && REDIS_TUPLEID_RETRIVE_FUNCSIG(rettype, argstype, nargs)) { return true; } if (pg_strcasecmp(funcname, "pg_get_redis_rel_end_ctid") == 0 && REDIS_TUPLEID_RETRIVE_FUNCSIG(rettype, argstype, nargs)) { return true; } return false; } static inline bool redis_offset_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs) { if (pg_strcasecmp(funcname, "pg_tupleid_get_offset") == 0 && (nargs == 1 && rettype == INT4OID && argstype[0] == TIDOID)) { return true; } return false; } static inline bool redis_blocknum_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs) { if (pg_strcasecmp(funcname, "pg_tupleid_get_blocknum") == 0 && (nargs == 1 && rettype == INT8OID && argstype[0] == TIDOID)) { return true; } return false; } static inline bool redis_ctid_retrive_function(const char* funcname, Oid rettype, const Oid* argstype, int nargs) { if (pg_strcasecmp(funcname, "pg_tupleid_get_ctid_to_bigint") == 0 && (nargs == 1 && rettype == INT8OID && argstype[0] == TIDOID)) { return true; } return false; } /* * - Brief: Record the given tuple's tupleid into pg_delete_delta table * - Parameter: * @rel: target relation of UPDATE/DELETE operation * @tupleid: tupleid that needs record * - Return: * no return value */ void RecordDeletedTuple(Oid relid, int2 bucketid, const ItemPointer tupleid, const Relation deldelta_rel) { Datum values[Natts_pg_delete_delta]; bool nulls[Natts_pg_delete_delta]; HeapTuple tup = NULL; Assert(deldelta_rel); /* In redistribution, table delete_delta has 3 or 2 column. */ Assert(RelationGetDescr(deldelta_rel)->natts <= 3); /* Iterate through attributes initializing nulls and values */ for (int i = 0; i < Natts_pg_delete_delta; i++) { nulls[i] = false; values[i] = (Datum)0; } values[Anum_pg_delete_delta_xcnodeid_and_dntableoid - 1] = UInt64GetDatum(((uint64)u_sess->pgxc_cxt.PGXCNodeIdentifier << 32) | relid); values[Anum_pg_delete_delta_tablebucketid_and_ctid - 1] = UInt64GetDatum(((uint64)ItemPointerGetBlockNumber(tupleid) << 16) | ItemPointerGetOffsetNumber(tupleid)); if (BUCKET_NODE_IS_VALID(bucketid)) { values[Anum_pg_delete_delta_tablebucketid_and_ctid - 1] |= ((uint64)bucketid << 48); } /* Record delta */ tup = heap_form_tuple(RelationGetDescr(deldelta_rel), values, nulls); (void)simple_heap_insert(deldelta_rel, tup); tableam_tops_free_tuple(tup); } /* * - Brief: get and open delete_delta rel * - Parameter: * @rel: target relation of UPDATE/DELETE/TRUNCATE operation * @lockmode: lock mode * @isMultiCatchup: multi catchup delta or not * - Return: * delete_delta rel */ /* * - Brief: Determine if the relation is under cluster resizing operation * - Parameter: * @rel: relation that needs to check * - Return: * @TRUE: relation is under cluster resizing * @FALSE: relation is not under cluster resizing */ bool RelationInClusterResizing(const Relation rel) { Assert(rel != NULL); /* Check relation's append_mode status */ if (!IsInitdb && RelationInRedistribute(rel)) return true; return false; } /* * - Brief: Determine if the relation is under cluster resizing read only operation * - Parameter: * @rel: relation that needs to check * - Return: * @TRUE: relation is under cluster resizing read only * @FALSE: relation is not under cluster resizing read only */ bool RelationInClusterResizingReadOnly(const Relation rel) { Assert(rel != NULL); /* Check relation's append_mode status */ if (!IsInitdb && RelationInRedistributeReadOnly(rel)) return true; return false; } /* * @Description: check whether relation is in redistribution though range variable. * @in range_var: range variable which stored relation info. * @return: true for in redistribution. */ bool CheckRangeVarInRedistribution(const RangeVar* range_var) { Relation relation; Oid relid; bool in_redis = false; relid = RangeVarGetRelid(range_var, AccessShareLock, true); if (OidIsValid(relid)) { relation = relation_open(relid, NoLock); /* If the relation is index, we should check the related table is resizing or not. */ if (RelationIsIndex(relation)) { Oid heapOid = IndexGetRelation(relid, false); Relation heapRelation = relation_open(heapOid, AccessShareLock); in_redis = RelationInClusterResizing(heapRelation); relation_close(heapRelation, AccessShareLock); } else { in_redis = RelationInClusterResizing(relation); } relation_close(relation, NoLock); UnlockRelationOid(relid, AccessShareLock); } return in_redis; } /* * - Brief: Determine if the table name is delete_delta table. * - Parameter: * @relname: name of target table * - Return: * @TRUE: the table is delete_delta table * @FALSE: the table is not delete_delta table */ bool RelationIsDeleteDeltaTable(char* delete_delta_name) { Oid relid; uint64 val; char* endptr = NULL; HeapTuple tuple; if (IsInitdb) { return false; } if (strncmp(delete_delta_name, "pg_delete_delta_", 16) != 0) { return false; } val = strtoull(delete_delta_name + 16, &endptr, 0); if ((errno == ERANGE) || (errno != 0 && val == 0)) { return false; } if (endptr == delete_delta_name + 16 || *endptr != '\0') { return false; } relid = (Oid)val; if (!OidIsValid(relid)) { return false; } tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); if (!HeapTupleIsValid(tuple)) { elog(WARNING, "Table %u related to %s does not exists.", relid, delete_delta_name); return false; } ReleaseSysCache(tuple); return true; } /* * - Brief: Determine if the Progress is under cluster resizing status * - Return: * @TRUE: Progress is under cluster resizing * @FALSE: Progress is not under cluster resizing */ bool ClusterResizingInProgress() { Relation pgxc_group_rel = NULL; TableScanDesc scan; HeapTuple tup = NULL; Datum datum; bool isNull = false; bool result = false; pgxc_group_rel = heap_open(PgxcGroupRelationId, AccessShareLock); if (!pgxc_group_rel) { ereport(PANIC, (errcode(ERRCODE_RELATION_OPEN_ERROR), errmsg("can not open pgxc_group"))); } scan = tableam_scan_begin(pgxc_group_rel, SnapshotNow, 0, NULL); while ((tup = (HeapTuple) tableam_scan_getnexttuple(scan, ForwardScanDirection)) != NULL) { datum = heap_getattr(tup, Anum_pgxc_group_in_redistribution, RelationGetDescr(pgxc_group_rel), &isNull); if ('y' == DatumGetChar(datum)) { result = true; break; } } tableam_scan_end(scan); heap_close(pgxc_group_rel, AccessShareLock); return result; } /* * - Brief: get the name of delete_delta table * - Parameter: * @relname: name of target table * @delta_delta_name: output value for delete_delta table name * @isMultiCatchup: multi catchup delta or not * - Return: * no return value */ static inline void RelationGetDeleteDeltaTableName(Relation rel, char* delete_delta_name, bool isMultiCatchup) { int rc = 0; /* Check if output parameter it not palloc()-ed from caller side */ if (delete_delta_name == NULL || rel == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid parameter in function '%s'", __FUNCTION__))); } /* * Look up Relation's reloptions to get table's cnoid to * form the name of delete_delta table */ if (!IsInitdb) { if (RelationInClusterResizing(rel) && !RelationInClusterResizingReadOnly(rel)) { if (isMultiCatchup) { rc = snprintf_s(delete_delta_name, NAMEDATALEN, NAMEDATALEN - 1, REDIS_MULTI_CATCHUP_DELETE_DELTA_TABLE_PREFIX "%u", RelationGetRelCnOid(rel)); } else { rc = snprintf_s(delete_delta_name, NAMEDATALEN, NAMEDATALEN - 1, REDIS_DELETE_DELTA_TABLE_PREFIX "%u", RelationGetRelCnOid(rel)); } securec_check_ss(rc, "\0", "\0"); } else { elog(LOG, "rel %s doesn't exist in redistributing", RelationGetRelationName(rel)); rc = snprintf_s(delete_delta_name, NAMEDATALEN, NAMEDATALEN - 1, REDIS_DELETE_DELTA_TABLE_PREFIX "%s", RelationGetRelationName(rel)); securec_check_ss(rc, "\0", "\0"); } } return; } Relation GetAndOpenDeleteDeltaRel(const Relation rel, LOCKMODE lockmode, bool isMultiCatchup) { Relation deldelta_rel; Oid deldelta_relid; char delete_delta_tablename[NAMEDATALEN]; Oid data_redis_namespace; errno_t errorno; errorno = memset_s(delete_delta_tablename, NAMEDATALEN, 0, NAMEDATALEN); securec_check_c(errorno, "\0", "\0"); RelationGetDeleteDeltaTableName(rel, (char*)delete_delta_tablename, isMultiCatchup); data_redis_namespace = get_namespace_oid("data_redis", false); /* We are going to fetch the delete delta relation under data_redis schema. */ deldelta_relid = get_relname_relid(delete_delta_tablename, data_redis_namespace); if (!OidIsValid(deldelta_relid)) { /* * If multi catchup delta table is not there, just return NULL. We should not * report error, because it is a valid case. Multi catchup delta table is * dropped in each catchup iteration. */ if (isMultiCatchup) { return NULL; } /* * To support Update or Delete during extension, we need to add 2 more columns. * more columns. Limited by MaxHeapAttributeNumber, if the table already contains too many columns, * we don't allow update or delete anymore, but insert statement can still proceed. */ if (((rel->rd_att->natts > (MaxHeapAttributeNumber - (Natts_pg_delete_delta - 1))) && !RELATION_IS_PARTITIONED(rel)) || ((rel->rd_att->natts > (MaxHeapAttributeNumber - Natts_pg_delete_delta)) && RELATION_IS_PARTITIONED(rel))) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("do not support update or delete on table %s, when do cluster resizing on it.", RelationGetRelationName(rel)), errdetail("Can not support online extension, if the table contains too many columns"))); } /* ERROR case, should never come here */ ereport(ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("delete delta table %s is not found when do cluster resizing table \"%s\"", delete_delta_tablename, RelationGetRelationName(rel)))); } deldelta_rel = relation_open(deldelta_relid, lockmode); elog(DEBUG1, "Delete_delta table %s for relation %s being under cluster resizing is valid.", delete_delta_tablename, RelationGetRelationName(rel)); return deldelta_rel; } /* * - Brief: Check the stmtment during online expansion, block unsupported ddl in cluster resizing. * - Parameter: * @rel: parsetree of DDL * - Return: * no return value */ void BlockUnsupportedDDL(const Node* parsetree) { if (IsInitdb) { return; } Relation rel = NULL; Oid relid = InvalidOid; List* relidlist = NULL; ListCell* lc = NULL; LOCKMODE lockmode_getrelid = AccessShareLock; LOCKMODE lockmode_openrel = AccessShareLock; /* * Check for shared-cache-inval messages before trying to access the * relation. This is needed to cover the case where the name * identifies a rel that has been dropped and recreated since the * start of our transaction: if we don't flush the old syscache entry, * then we'll latch onto that entry and suffer an error later. */ AcceptInvalidationMessages(); switch (nodeTag(parsetree)) { case T_CreatedbStmt: case T_AlterDatabaseStmt: case T_AlterDatabaseSetStmt: case T_CreateTableSpaceStmt: case T_DropTableSpaceStmt: case T_AlterTableSpaceOptionsStmt: case T_CreateGroupStmt: { if (ClusterResizingInProgress()) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion", CreateCommandTag((Node*)parsetree)))); } return; } break; case T_DropdbStmt: { if (ClusterResizingInProgress() && !u_sess->attr.attr_common.xc_maintenance_mode) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion", CreateCommandTag((Node*)parsetree)))); } else if (ClusterResizingInProgress()) { ereport(WARNING, (errmsg("Drop database during online expansion in maintenance mode!"))); } return; } break; /* Block CURSOR for while table in cluster resizing */ case T_PlannedStmt: { PlannedStmt* stmt = (PlannedStmt*)parsetree; relidlist = stmt->relationOids; } break; /* Block RENAME while table in cluster resizing */ case T_RenameStmt: { RenameStmt* stmt = (RenameStmt*)parsetree; switch (stmt->renameType) { case OBJECT_SCHEMA: { Oid nsOid = get_namespace_oid(stmt->subname, true); TRANSFER_DISABLE_DDL(nsOid); break; } case OBJECT_TABLE: { if (stmt->relation != NULL) { Oid relOid = RangeVarGetRelid(stmt->relation, AccessShareLock, true); if (OidIsValid(relOid)) { Oid nsOid = GetNamespaceIdbyRelId(relOid); UnlockRelationOid(relOid, AccessShareLock); TRANSFER_DISABLE_DDL(nsOid); } } break; } default: break; } if (stmt->relation && CheckRangeVarInRedistribution(stmt->relation)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), stmt->relation->relname))); } break; /* Block ALTER set schema while table in cluster resizing */ case T_AlterObjectSchemaStmt: { AlterObjectSchemaStmt* stmt = (AlterObjectSchemaStmt*)parsetree; /* disable alter table set schema when transfer */ if (stmt->relation != NULL) { Oid relOid = RangeVarGetRelid(stmt->relation, AccessShareLock, true); if (OidIsValid(relOid)) { Oid nsOid = GetNamespaceIdbyRelId(relOid); UnlockRelationOid(relOid, AccessShareLock); TRANSFER_DISABLE_DDL(nsOid); if (stmt->newschema) { nsOid = get_namespace_oid(stmt->newschema, true); TRANSFER_DISABLE_DDL(nsOid); } } } if (stmt->relation && CheckRangeVarInRedistribution(stmt->relation)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), stmt->relation->relname))); } break; /* Block CREATE index while table in cluster resizing(for row table only) */ case T_IndexStmt: { IndexStmt* stmt = (IndexStmt*)parsetree; if (stmt->relation) { relid = RangeVarGetRelid(stmt->relation, AccessShareLock, true); if (OidIsValid(relid)) { Relation relation = relation_open(relid, NoLock); bool inRedis = RelationIsRowFormat(relation) && RelationInClusterResizing(relation); relation_close(relation, NoLock); UnlockRelationOid(relid, AccessShareLock); if (inRedis) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), stmt->relation->relname))); } } } } break; /* Block REINDEX while table in cluster resizing(for row table only) */ case T_ReindexStmt: { ReindexStmt* stmt = (ReindexStmt*)parsetree; if (stmt->relation) { relid = RangeVarGetRelid(stmt->relation, AccessShareLock, true); if (OidIsValid(relid)) { Relation relation = relation_open(relid, NoLock); bool inRedis = false; if (RelationIsRelation(relation)) { inRedis = RelationIsRowFormat(relation) && RelationInClusterResizing(relation); } else if (RelationIsIndex(relation)) { Oid heapOid = IndexGetRelation(relid, false); Relation heapRelation = relation_open(heapOid, AccessShareLock); inRedis = RelationIsRowFormat(heapRelation) && RelationInClusterResizing(heapRelation); relation_close(heapRelation, AccessShareLock); } relation_close(relation, NoLock); UnlockRelationOid(relid, AccessShareLock); if (inRedis) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), stmt->relation->relname))); } } } } break; /* Block ALTER-Table while table in cluster resizing */ case T_AlterTableStmt: { AlterTableStmt* stmt = (AlterTableStmt*)parsetree; AlterTableCmd* cmd = NULL; foreach (lc, stmt->cmds) { cmd = (AlterTableCmd*)lfirst(lc); switch (cmd->subtype) { case AT_TruncatePartition: { /* * We do not allow truncate partition when the target is in read only * mode during online expansion time. */ if (stmt->relation) { relid = RangeVarGetRelid(stmt->relation, lockmode_getrelid, true); if (OidIsValid(relid)) { /* disable alter table truncate partition during transfer */ if (CheckRangeVarInRedistribution(stmt->relation)) { Oid nsOid = GetNamespaceIdbyRelId(relid); TRANSFER_DISABLE_DDL(nsOid); } rel = relation_open(relid, NoLock); if (RelationInClusterResizingReadOnly(rel)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command with '%s' option during online expansion on " "'%s' because the object is in read only mode.", CreateCommandTag((Node*)parsetree), CreateAlterTableCommandTag(cmd->subtype), RelationGetRelationName(rel)))); } relation_close(rel, NoLock); if (u_sess->attr.attr_sql.enable_parallel_ddl) UnlockRelationOid(relid, lockmode_getrelid); } } } break; case AT_AddNodeList: case AT_DeleteNodeList: break; case AT_UpdateSliceLike: { if (!ClusterResizingInProgress() && IS_PGXC_COORDINATOR) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Cannot alter table update slice like when it is not " "under redistribution"))); } } break; case AT_ResetRelOptions: case AT_SetRelOptions: if (cmd->def) { List* options = (List*)cmd->def; ListCell* opt = NULL; DefElem* def = NULL; foreach (opt, options) { def = (DefElem*)lfirst(opt); if (pg_strcasecmp(def->defname, "append_mode") == 0) { break; } } /* If rel option contain append_mode, then not check. */ if (opt != NULL) { break; } } /* fall through */ default: { if (stmt->relation && !u_sess->attr.attr_sql.enable_cluster_resize && CheckRangeVarInRedistribution(stmt->relation)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command with '%s' option during online expansion on '%s'", CreateCommandTag((Node*)parsetree), CreateAlterTableCommandTag(cmd->subtype), stmt->relation->relname))); } break; } } return; } break; /* Block CREATE-RULE statements while target table in cluster resizing */ case T_RuleStmt: { RuleStmt* stmt = (RuleStmt*)parsetree; if (stmt->relation) { relid = RangeVarGetRelid(stmt->relation, lockmode_getrelid, true); relidlist = list_make1_oid(relid); } } break; /* Block CREATE SEQUENCE set schema while owner table in cluster resizing */ case T_CreateSeqStmt: { CreateSeqStmt* stmt = (CreateSeqStmt*)parsetree; List* owned_by = NULL; DefElem* defel = NULL; foreach (lc, stmt->options) { defel = (DefElem*)lfirst(lc); if (pg_strcasecmp(defel->defname, "owned_by") == 0 && nodeTag(defel->arg) == T_List) { owned_by = (List*)defel->arg; } } if (owned_by != NULL) { int owned_len = list_length(owned_by); if (owned_len != 1) { List* relname = list_truncate(list_copy(owned_by), owned_len - 1); RangeVar* r = makeRangeVarFromNameList(relname); if (r && CheckRangeVarInRedistribution(r)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), r->relname))); } } } break; /* Block ALTER SEQUENCE while owner table in cluster resizing */ case T_AlterSeqStmt: { AlterSeqStmt* stmt = (AlterSeqStmt*)parsetree; List* owned_by = NIL; DefElem* defel = NULL; foreach (lc, stmt->options) { defel = (DefElem*)lfirst(lc); if (pg_strcasecmp(defel->defname, "owned_by") == 0 && nodeTag(defel->arg) == T_List) { owned_by = (List*)defel->arg; } } if (owned_by != NULL) { int owned_len = list_length(owned_by); if (owned_len != 1) { List* relname = list_truncate(list_copy(owned_by), owned_len - 1); RangeVar* r = makeRangeVarFromNameList(relname); if (r && CheckRangeVarInRedistribution(r)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), r->relname))); } } } break; /* Block CLUSTER while table in cluster resizing */ case T_ClusterStmt: { ClusterStmt* stmt = (ClusterStmt*)parsetree; if (stmt->relation && CheckRangeVarInRedistribution(stmt->relation)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), stmt->relation->relname))); } break; /* Block VACUUM FULL while table in cluster resizing */ case T_VacuumStmt: { VacuumStmt* stmt = (VacuumStmt*)parsetree; if ((stmt->options & VACOPT_VACUUM) || (stmt->options & VACOPT_MERGE)) { if (stmt->relation) { relid = RangeVarGetRelid(stmt->relation, lockmode_getrelid, true); relidlist = list_make1_oid(relid); } } if (stmt->options & VACOPT_FULL) { if (OidIsValid(relid)) { rel = relation_open(relid, lockmode_openrel); if (RelationInClusterResizing(rel)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport 'VACUUM FULL' command during online expansion on '%s'", RelationGetRelationName(rel)))); } relation_close(rel, lockmode_openrel); } } } break; /* Block truncate DDL when the target table is read only in cluster resizing */ case T_TruncateStmt: { ListCell* cell = NULL; TruncateStmt* stmt = (TruncateStmt*)parsetree; foreach (cell, stmt->relations) { RangeVar* rv = (RangeVar*)lfirst(cell); if (CheckRangeVarInRedistribution(rv)) { Oid relOid = RangeVarGetRelid(rv, lockmode_getrelid, true); if (OidIsValid(relOid)) { Oid nsOid = GetNamespaceIdbyRelId(relOid); UnlockRelationOid(relOid, lockmode_getrelid); TRANSFER_DISABLE_DDL(nsOid); } } rel = heap_openrv(rv, lockmode_openrel); if (RelationInClusterResizingReadOnly(rel)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s' because the object is in " "read only mode.", CreateCommandTag((Node*)parsetree), RelationGetRelationName(rel)))); } relation_close(rel, lockmode_openrel); } } break; case T_DropStmt: { DropStmt* stmt = (DropStmt*)parsetree; switch (stmt->removeType) { case OBJECT_TABLE: { /* disable drop table when transfer */ ListCell* cell = NULL; foreach (cell, stmt->objects) { RangeVar* rel = makeRangeVarFromNameList((List*)lfirst(cell)); Oid relOid = RangeVarGetRelid(rel, AccessShareLock, true); if (OidIsValid(relOid)) { Oid nsOid = GetNamespaceIdbyRelId(relOid); UnlockRelationOid(relOid, AccessShareLock); TRANSFER_DISABLE_DDL(nsOid); } } break; } case OBJECT_SCHEMA: { /* disable drop schema when transfer */ ListCell* cell = NULL; foreach (cell, stmt->objects) { List* objname = (List*)lfirst(cell); char* name = NameListToString(objname); Oid nsOid = get_namespace_oid(name, true); TRANSFER_DISABLE_DDL(nsOid); } break; } default: break; } } break; case T_CreateStmt: { /* disable create table when transfer */ CreateStmt* stmt = (CreateStmt*)parsetree; if (stmt->relation != NULL) { Oid nsOid = RangeVarGetCreationNamespace(stmt->relation); TRANSFER_DISABLE_DDL(nsOid); } } break; default: break; } foreach (lc, relidlist) { relid = lfirst_oid(lc); if (OidIsValid(relid) && get_rel_name(relid) != NULL) { rel = relation_open(relid, lockmode_openrel); if (RelationInClusterResizing(rel)) { ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("Unsupport '%s' command during online expansion on '%s'", CreateCommandTag((Node*)parsetree), RelationGetRelationName(rel)))); } relation_close(rel, lockmode_openrel); } } } /* * - Brief: For online expanions, the shippable function is evaluated here, the module * will be invoked in optimizer when do FQS evaluation, we have to define function * as STABLE * - Parameter: * @funcid: oid of user defined function which is createed/dropped in scope of gs_redis * - Return: * @true: shippable * @false: unshippable */ bool redis_func_shippable(Oid funcid) { const char* func_name = get_func_name(funcid); Oid* argstype = NULL; int nargs; Oid rettype = InvalidOid; bool result = false; if (func_name == NULL) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("function with OID %u does not exist", funcid))); } /* Fetch function signatures */ rettype = get_func_signature(funcid, &argstype, &nargs); if (redis_tupleid_retrive_function(func_name, rettype, argstype, nargs)) { /* tupleid retrive functions is shippable to datanodes */ result = true; } else if (redis_offset_retrive_function(func_name, rettype, argstype, nargs)) { result = true; } else if (redis_blocknum_retrive_function(func_name, rettype, argstype, nargs)) { result = true; } else if (redis_ctid_retrive_function(func_name, rettype, argstype, nargs)) { result = true; } /* pfree */ if (argstype != NULL) { pfree_ext(argstype); argstype = NULL; } return result; } /* * - Brief: determine if given funcid reflects a dn-stable function * - Parameter: * @funcid: function oid that to evaluate * - Return: * @result: true:dnstable false: not-dnstable function */ bool redis_func_dnstable(Oid funcid) { const char* func_name = get_func_name(funcid); Oid* argstype = NULL; int nargs; Oid rettype = InvalidOid; bool result = false; if (func_name == NULL) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("function with OID %u does not exist when checking function dnstable", funcid))); } /* Fetch function signatures */ rettype = get_func_signature(funcid, &argstype, &nargs); if (redis_tupleid_retrive_function(func_name, rettype, argstype, nargs)) { /* tupleid retrive functions is dnstable */ result = true; } return result; } /* * - Brief: evaluate ctid functions into a const value to avoid per-scanning * tuple invokation in seqscan. * - Parameter: * @rel: the rel being redistributing * @original_quals: the original quals possible contains ctid_funcs * @isRangeScanInRedis: if is a redis range scan * - Return: * @new_quals: quals which func call be replaced by a const */ List* eval_ctid_funcs(Relation rel, List* original_quals, RangeScanInRedis *rangeScanInRedis) { StringInfo qual_str = makeStringInfo(); /* * we have to make a copy of the original quals, since the eval_dnstable_func_mutator * will modify the it. the original qual will be needed again and again in later * to be re-eval in partition table scans. */ List* new_quals = (List*)copyObject((const void*)(original_quals)); rangeScanInRedis->isRangeScanInRedis = false; rangeScanInRedis->sliceTotal = 0; rangeScanInRedis->sliceIndex = 0; (void)eval_dnstable_func_mutator(rel, (Node*)new_quals, qual_str, rangeScanInRedis, true); pfree_ext(qual_str->data); pfree_ext(qual_str); return new_quals; } static int32 get_expr_const_val(Node *val){ if (IsA(val, Const) && !((Const*)val)->constisnull && ((Const*)val)->consttype == INT4OID) { return DatumGetInt32(((Const*)val)->constvalue); } else { return 0; } } /* * - Brief: working house for eval_dnstable_func() to evaluate dn stable function into a const * value to avoid per-scanning tuple invocation in seqscan * - Parameter: * @rel: the rel being redistributing * @node: expression node * @qual_str: predicate pattern * @isRangeScanInRedis: output to indicate if the predicate pattern is range scan in redis * @isRoot: we want to compare the predicate pattern only once at root level * - Return: * @result: expression tree with dn stable function const-evaluated */ static Node* eval_dnstable_func_mutator( Relation rel, Node* node, StringInfo qual_str, RangeScanInRedis *rangeScanInRedis, bool isRoot) { if (node == NULL) return NULL; if (IS_PGXC_COORDINATOR) return node; switch (nodeTag(node)) { case T_FuncExpr: { FuncExpr* expr = (FuncExpr*)node; /* flatten dn stable function into const value */ if (redis_func_dnstable(expr->funcid)) { Node* new_const = NULL; char* funcname = get_func_name(expr->funcid); if (funcname == NULL) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("operation expression function with OID %u does not exist.", expr->funcid))); } bool is_func_get_start_ctid = pg_strcasecmp(funcname, "pg_get_redis_rel_start_ctid") == 0; bool is_func_get_end_ctid = pg_strcasecmp(funcname, "pg_get_redis_rel_end_ctid") == 0; if (is_func_get_start_ctid || is_func_get_end_ctid){ int32 numSlices = get_expr_const_val((Node*)list_nth(expr->args, 2)); int32 idxSlices = get_expr_const_val((Node*)list_nth(expr->args, 3)); new_const = eval_redis_func_direct(rel, is_func_get_start_ctid, numSlices, idxSlices); rangeScanInRedis->sliceIndex = idxSlices; rangeScanInRedis->sliceTotal = numSlices; } else { new_const = eval_const_expressions(NULL, node); } appendStringInfoString(qual_str, get_func_name(expr->funcid)); appendStringInfoString(qual_str, "+"); return new_const; } break; } case T_List: { List* l = (List*)node; for (int i = 0; i < list_length(l); i++) { Node* expr = (Node*)list_nth(l, i); Node* new_expr = eval_dnstable_func_mutator(rel, expr, qual_str, rangeScanInRedis, false); /* * If a FuncExpr node is evalated into a T_Const value, we are hitting * the point so replace it in qual list. */ if (expr && IsA(expr, FuncExpr) && new_expr && IsA(new_expr, Const)) { l = list_delete_ptr(l, expr); l = lappend(l, new_expr); } } /* * If the predicate at root is something like "where ctid between pg_get_redis_rel_start_ctid('xx') * and pg_get_redis_rel_end_ctid('xx')" on DN, we will pushdown the predicate at scan node. */ if (isRoot && pg_strcasecmp(qual_str->data, RANGE_SCAN_IN_REDIS) == 0) { rangeScanInRedis->isRangeScanInRedis = true; } break; } case T_OpExpr: { OpExpr* opexpr = (OpExpr*)node; char* funcname = get_func_name(opexpr->opfuncid); if (funcname == NULL) { ereport(ERROR, (errcode(ERRCODE_UNDEFINED_FUNCTION), errmsg("operation expression function with OID %u does not exist.", opexpr->opfuncid))); } appendStringInfoString(qual_str, funcname); appendStringInfoString(qual_str, "+"); eval_dnstable_func_mutator(rel, (Node*)opexpr->args, qual_str, rangeScanInRedis, false); break; } case T_Var: { Var* var = (Var*)node; /* we only expect tid column in the predicate */ if (var->vartype == TIDOID) { appendStringInfoString(qual_str, "tid"); appendStringInfoString(qual_str, "+"); } break; } default: { appendStringInfoString(qual_str, nodeTagToString(nodeTag(node))); appendStringInfoString(qual_str, "+"); break; } } return NULL; } /* * - Brief: get and open new_table rel * - Parameter: * @rel: target relation of TRUNCATE operation * - Return: * new_table rel */ Relation GetAndOpenNewTableRel(const Relation rel, LOCKMODE lockmode) { Relation newtable_rel = NULL; Oid newtable_relid = InvalidOid; Oid data_redis_namespace; char new_tablename[NAMEDATALEN]; errno_t errorno = EOK; errorno = memset_s(new_tablename, NAMEDATALEN, 0, NAMEDATALEN); securec_check_c(errorno, "\0", "\0"); RelationGetNewTableName(rel, (char*)new_tablename); data_redis_namespace = get_namespace_oid("data_redis", false); newtable_relid = get_relname_relid(new_tablename, data_redis_namespace); if (!OidIsValid(newtable_relid)) { /* ERROR case, should never come here */ ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("new table %s is not found when do cluster resizing table \"%s\"", new_tablename, RelationGetRelationName(rel)))); } newtable_rel = relation_open(newtable_relid, lockmode); elog(LOG, "New temp table %s for relation %s under cluster resizing is valid.", new_tablename, RelationGetRelationName(rel)); return newtable_rel; } /* * - Brief: get the name of new table * - Parameter: * @relname: name of target table * @newtable_name: output value for new table name * - Return: * no return value */ void RelationGetNewTableName(Relation rel, char* newtable_name) { int rc = 0; /* Check if output parameter it not palloc()-ed from caller side */ if (newtable_name == NULL || rel == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("Invalid parameter in function '%s' when getting the name of new table", __FUNCTION__))); } /* * Look up relaion's reloptions to get table's cnoid to * form the name of new table */ if (!IsInitdb) { Oid rel_cn_oid = RelationGetRelCnOid(rel); if (OidIsValid(rel_cn_oid)) { rc = snprintf_s(newtable_name, NAMEDATALEN, NAMEDATALEN - 1, "data_redis_tmp_%u", rel_cn_oid); } else { elog(LOG, "rel %s doesn't exist in redistributing", RelationGetRelationName(rel)); rc = snprintf_s( newtable_name, NAMEDATALEN, NAMEDATALEN - 1, "data_redis_tmp_%s", RelationGetRelationName(rel)); } /* check the return value of security function */ securec_check_ss(rc, "\0", "\0"); } return; }
38.493671
120
0.562183
[ "object" ]
28343e1f3e625a05a8cb3b9f039cccd6d7e4cab5
1,947
cc
C++
dali/operators/generic/slice/slice_attr.cc
roclark/DALI
e44a212d89a5449bbe7f4bae3d0f55f11a262932
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-23T05:35:47.000Z
2020-09-23T05:35:47.000Z
dali/operators/generic/slice/slice_attr.cc
roclark/DALI
e44a212d89a5449bbe7f4bae3d0f55f11a262932
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
dali/operators/generic/slice/slice_attr.cc
roclark/DALI
e44a212d89a5449bbe7f4bae3d0f55f11a262932
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include "dali/core/tensor_layout.h" #include "dali/operators/generic/slice/slice_attr.h" namespace dali { DALI_SCHEMA(SliceAttr) .DocStr(R"code(Slice attributes placeholder)code") .AddOptionalArg("axes", R"code(Order of dimensions used for the anchor and shape slice inputs as dimension indices.)code", std::vector<int>{1, 0}) .AddOptionalArg("axis_names", R"code(Order of the dimensions used for the anchor and shape slice inputs, as described in layout. If a value is provided, ``axis_names`` will have a higher priority than ``axes``.)code", TensorLayout("WH")) .AddOptionalArg("normalized_anchor", R"code(Determines whether the anchor input should be interpreted as normalized (range [0.0, 1.0]) or as absolute coordinates. .. note:: This argument is only relevant when anchor data type is ``float``. For integer types, the coordinates are always absolute..)code", true) .AddOptionalArg("normalized_shape", R"code(Determines whether the shape input should be interpreted as normalized (range [0.0, 1.0]) or as absolute coordinates. .. note:: This argument is only relevant when anchor data type is ``float``. For integer types, the coordinates are always absolute.)code", true); } // namespace dali
37.442308
90
0.720596
[ "shape", "vector" ]
2836269e0c943dcb1b30760c07497984a458bf11
25,304
cpp
C++
plugin/pxr/maya/lib/usdMaya/adaptor.cpp
sopvop/maya-usd
c567a1661152ec2450359767fa2b0ca8cac4dc83
[ "Apache-2.0" ]
4
2019-11-19T14:58:17.000Z
2021-03-27T02:27:43.000Z
plugin/pxr/maya/lib/usdMaya/adaptor.cpp
ZhongLingXiao/maya-usd
c567a1661152ec2450359767fa2b0ca8cac4dc83
[ "Apache-2.0" ]
2
2019-08-14T20:44:09.000Z
2020-01-07T09:12:03.000Z
plugin/pxr/maya/lib/usdMaya/adaptor.cpp
ZhongLingXiao/maya-usd
c567a1661152ec2450359767fa2b0ca8cac4dc83
[ "Apache-2.0" ]
1
2019-08-14T14:33:41.000Z
2019-08-14T14:33:41.000Z
// // Copyright 2018 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "usdMaya/adaptor.h" #include "usdMaya/primWriterRegistry.h" #include "usdMaya/readUtil.h" #include "usdMaya/registryHelper.h" #include "usdMaya/util.h" #include "usdMaya/writeUtil.h" #include "pxr/usd/sdf/schema.h" #include "pxr/usd/usd/apiSchemaBase.h" #include "pxr/usd/usd/schemaBase.h" #include "pxr/usd/usd/tokens.h" #include <maya/MFnAttribute.h> #include <maya/MFnDependencyNode.h> #include <maya/MPlug.h> PXR_NAMESPACE_OPEN_SCOPE static std::string _GetMayaAttrNameForMetadataKey(const TfToken& key) { return TfStringPrintf("USD_%s", TfMakeValidIdentifier(key.GetString()).c_str()); } static std::string _GetMayaAttrNameForAttrName(const TfToken& attrName) { return TfStringPrintf("USD_ATTR_%s", TfMakeValidIdentifier(attrName.GetString()).c_str()); } static VtValue _GetListOpForTokenVector(const TfTokenVector& vector) { SdfTokenListOp op; op.SetPrependedItems(vector); return VtValue(op); } std::map<std::string, TfType> UsdMayaAdaptor::_schemaLookup; std::map<TfToken, std::vector<std::string>> UsdMayaAdaptor::_attributeAliases; UsdMayaAdaptor::UsdMayaAdaptor(const MObject& obj) : _handle(obj) { } UsdMayaAdaptor::operator bool() const { if (!_handle.isValid()) { return false; } MStatus status; MFnDependencyNode node(_handle.object(), &status); return status; } std::string UsdMayaAdaptor::GetMayaNodeName() const { if (!*this) { return std::string(); } if (_handle.object().hasFn(MFn::kDagNode)) { MFnDagNode dagNode(_handle.object()); return dagNode.fullPathName().asChar(); } else { MFnDependencyNode depNode(_handle.object()); return depNode.name().asChar(); } } TfToken UsdMayaAdaptor::GetUsdTypeName() const { if (!*this) { return TfToken(); } const TfType ty = GetUsdType(); const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() .GetPrimDefinition(ty); if (!primDef) { return TfToken(); } return primDef->GetNameToken(); } TfType UsdMayaAdaptor::GetUsdType() const { if (!*this) { return TfType(); } MObject object = _handle.object(); MFnDependencyNode depNode(object); // The adaptor type mapping might be registered externally in a prim writer // plugin. This simply pokes the prim writer registry to load the prim // writer plugin in order to pull in the adaptor mapping. UsdMayaPrimWriterRegistry::Find(depNode.typeName().asChar()); TfRegistryManager::GetInstance().SubscribeTo<UsdMayaAdaptor>(); const auto iter = _schemaLookup.find(depNode.typeName().asChar()); if (iter != _schemaLookup.end()) { return iter->second; } else { return TfType(); } } TfTokenVector UsdMayaAdaptor::GetAppliedSchemas() const { if (!*this) { return TfTokenVector(); } VtValue appliedSchemas; if (GetMetadata(UsdTokens->apiSchemas, &appliedSchemas)) { TfTokenVector result; appliedSchemas.Get<SdfTokenListOp>().ApplyOperations(&result); return result; } return TfTokenVector(); } UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::GetSchema(const TfType& ty) const { const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() .GetPrimDefinition(ty); if (!primDef) { return SchemaAdaptor(); } return GetSchemaByName(primDef->GetNameToken()); } UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const { if (!*this) { return SchemaAdaptor(); } // Get the schema definition. If it's registered, there should be a def. SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); if (!primDef) { return SchemaAdaptor(); } // Get the schema's TfType; its name should be registered as an alias. const TfType schemaType = TfType::Find<UsdSchemaBase>().FindDerivedByName(schemaName); // Is this an API schema? if (schemaType.IsA<UsdAPISchemaBase>()) { return SchemaAdaptor(_handle.object(), primDef); } // Is this a typed schema? else if (schemaType.IsA<UsdSchemaBase>()) { // XXX // We currently require an exact type match instead of the polymorphic // behavior that actual USD schema classes implement. This is because // we can't currently get the prim definition from the schema registry // for non-concrete schemas like Imageable (see bug 160436). Ideally, // once that's resolved, we would cache a mapping of Maya types to all // compatible USD type names based on schema inheritance. // (In that future world, we'll also want to special case some schemas // like UsdGeomImageable to be "compatible" with all Maya nodes.) const TfToken objectTypeName = GetUsdTypeName(); if (schemaName == objectTypeName) { // There's an exact MFn::Type match? Easy-peasy. return SchemaAdaptor(_handle.object(), primDef); } else { // If no match, do not allow usage of the typed-schema adaptor // mechanism. The importer/exporter have not declared that they // will use the adaptor mechanism to handle this type. return SchemaAdaptor(); } } // We shouldn't be able to reach this (everything is either typed or API). TF_CODING_ERROR("'%s' isn't a known API or typed schema", schemaName.GetText()); return SchemaAdaptor(); } UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::GetSchemaOrInheritedSchema(const TfType& ty) const { if (!*this) { return SchemaAdaptor(); } if (ty.IsA<UsdAPISchemaBase>()) { // No "promotion" for API schemas. return GetSchema(ty); } else if (ty.IsA<UsdSchemaBase>()) { // Can "promote" typed schemas based on inheritance. const TfType objectType = GetUsdType(); if (objectType.IsA(ty)) { return GetSchema(objectType); } } return SchemaAdaptor(); } UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::ApplySchema(const TfType& ty) { MDGModifier modifier; return ApplySchema(ty, modifier); } UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::ApplySchema(const TfType& ty, MDGModifier& modifier) { const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() .GetPrimDefinition(ty); if (!primDef) { TF_CODING_ERROR("Can't find schema definition for type '%s'", ty.GetTypeName().c_str()); return SchemaAdaptor(); } return ApplySchemaByName(primDef->GetNameToken(), modifier); } UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::ApplySchemaByName(const TfToken& schemaName) { MDGModifier modifier; return ApplySchemaByName(schemaName, modifier); } UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::ApplySchemaByName( const TfToken& schemaName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); return SchemaAdaptor(); } // Get the schema's TfType; its name should be registered as an alias. const TfType schemaType = TfType::Find<UsdSchemaBase>().FindDerivedByName(schemaName); // Make sure that this is an API schema. Only API schemas can be applied. if (!schemaType.IsA<UsdAPISchemaBase>()) { TF_CODING_ERROR("'%s' is not a registered API schema", schemaName.GetText()); return SchemaAdaptor(); } // Make sure that this is an "apply" schema. if (!UsdSchemaRegistry::GetInstance().IsAppliedAPISchema(schemaType)) { TF_CODING_ERROR("'%s' is not an applied API schema", schemaName.GetText()); return SchemaAdaptor(); } // Get the schema definition. If it's registered, there should be a def. SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); if (!primDef) { TF_CODING_ERROR("Can't find schema definition for name '%s'", schemaName.GetText()); return SchemaAdaptor(); } // Add to schema list (if not yet present). TfTokenVector currentSchemas = GetAppliedSchemas(); if (std::find(currentSchemas.begin(), currentSchemas.end(), schemaName) == currentSchemas.end()) { currentSchemas.push_back(schemaName); SetMetadata( UsdTokens->apiSchemas, _GetListOpForTokenVector(currentSchemas), modifier); } return SchemaAdaptor(_handle.object(), primDef); } void UsdMayaAdaptor::UnapplySchema(const TfType& ty) { MDGModifier modifier; UnapplySchema(ty, modifier); } void UsdMayaAdaptor::UnapplySchema(const TfType& ty, MDGModifier& modifier) { const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() .GetPrimDefinition(ty); if (!primDef) { TF_CODING_ERROR("Can't find schema definition for type '%s'", ty.GetTypeName().c_str()); return; } UnapplySchemaByName(primDef->GetNameToken(), modifier); } void UsdMayaAdaptor::UnapplySchemaByName(const TfToken& schemaName) { MDGModifier modifier; UnapplySchemaByName(schemaName, modifier); } void UsdMayaAdaptor::UnapplySchemaByName( const TfToken& schemaName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); return; } // Remove from schema list. TfTokenVector currentSchemas = GetAppliedSchemas(); currentSchemas.erase( std::remove( currentSchemas.begin(), currentSchemas.end(), schemaName), currentSchemas.end()); if (currentSchemas.empty()) { ClearMetadata(UsdTokens->apiSchemas, modifier); } else { SetMetadata( UsdTokens->apiSchemas, _GetListOpForTokenVector(currentSchemas), modifier); } } static bool _GetMetadataUnchecked( const MFnDependencyNode& node, const TfToken& key, VtValue* value) { VtValue fallback = SdfSchema::GetInstance().GetFallback(key); if (fallback.IsEmpty()) { return false; } std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); MPlug plug = node.findPlug(mayaAttrName.c_str()); if (plug.isNull()) { return false; } TfType ty = fallback.GetType(); VtValue result = UsdMayaWriteUtil::GetVtValue(plug, ty, TfToken()); if (result.IsEmpty()) { TF_RUNTIME_ERROR( "Cannot convert plug '%s' into metadata '%s' (%s)", plug.name().asChar(), key.GetText(), ty.GetTypeName().c_str()); return false; } *value = result; return true; } UsdMetadataValueMap UsdMayaAdaptor::GetAllAuthoredMetadata() const { if (!*this) { return UsdMetadataValueMap(); } MFnDependencyNode node(_handle.object()); UsdMetadataValueMap metaMap; for (const TfToken& key : GetPrimMetadataFields()) { VtValue value; if (_GetMetadataUnchecked(node, key, &value)) { metaMap[key] = value; } } return metaMap; } bool UsdMayaAdaptor::GetMetadata(const TfToken& key, VtValue* value) const { if (!*this) { return false; } if (!SdfSchema::GetInstance().IsRegistered(key)) { TF_CODING_ERROR("Metadata key '%s' is not registered", key.GetText()); return false; } MFnDependencyNode node(_handle.object()); return _GetMetadataUnchecked(node, key, value); } bool UsdMayaAdaptor::SetMetadata(const TfToken& key, const VtValue& value) { MDGModifier modifier; return SetMetadata(key, value, modifier); } bool UsdMayaAdaptor::SetMetadata( const TfToken& key, const VtValue& value, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); return false; } VtValue fallback; if (!SdfSchema::GetInstance().IsRegistered(key, &fallback)) { TF_CODING_ERROR("Metadata key '%s' is not registered", key.GetText()); return false; } if (fallback.IsEmpty()) { return false; } VtValue castValue = VtValue::CastToTypeOf(value, fallback); if (castValue.IsEmpty()) { TF_CODING_ERROR("Can't cast value to type '%s'", fallback.GetTypeName().c_str()); return false; } std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); std::string mayaNiceAttrName = key.GetText(); MFnDependencyNode node(_handle.object()); TfType ty = fallback.GetType(); MObject attrObj = UsdMayaReadUtil::FindOrCreateMayaAttr( ty, TfToken(), SdfVariabilityUniform, node, mayaAttrName, mayaNiceAttrName, modifier); if (attrObj.isNull()) { return false; } MPlug plug = node.findPlug(attrObj); if (!UsdMayaReadUtil::SetMayaAttr(plug, castValue, modifier)) { return false; } return true; } void UsdMayaAdaptor::ClearMetadata(const TfToken& key) { MDGModifier modifier; ClearMetadata(key, modifier); } void UsdMayaAdaptor::ClearMetadata(const TfToken& key, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); return; } MFnDependencyNode node(_handle.object()); std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); if (node.hasAttribute(mayaAttrName.c_str())) { MObject attr = node.attribute(mayaAttrName.c_str()); modifier.removeAttribute(_handle.object(), attr); modifier.doIt(); } } /* static */ TfTokenVector UsdMayaAdaptor::GetPrimMetadataFields() { return SdfSchema::GetInstance().GetMetadataFields(SdfSpecTypePrim); } template <typename T> static TfToken::Set _GetRegisteredSchemas() { TfToken::Set schemas; std::set<TfType> derivedTypes; TfType::Find<T>().GetAllDerivedTypes(&derivedTypes); UsdSchemaRegistry registry = UsdSchemaRegistry::GetInstance(); for (const TfType& ty : derivedTypes) { SdfPrimSpecHandle primDef = registry.GetPrimDefinition(ty); if (!primDef) { continue; } schemas.insert(primDef->GetNameToken()); } return schemas; } /* static */ TfToken::Set UsdMayaAdaptor::GetRegisteredAPISchemas() { return _GetRegisteredSchemas<UsdAPISchemaBase>(); } /* static */ TfToken::Set UsdMayaAdaptor::GetRegisteredTypedSchemas() { return _GetRegisteredSchemas<UsdSchemaBase>(); } /* static */ void UsdMayaAdaptor::RegisterTypedSchemaConversion( const std::string& nodeTypeName, const TfType& usdType) { const auto iterAndInserted = _schemaLookup.insert( std::make_pair(nodeTypeName, usdType)); if (iterAndInserted.second) { UsdMaya_RegistryHelper::AddUnloader([nodeTypeName]() { _schemaLookup.erase(nodeTypeName); }); } else { TF_CODING_ERROR("Typed schema conversion already registered for Maya " "type %s", nodeTypeName.c_str()); } } /* static */ void UsdMayaAdaptor::RegisterAttributeAlias( const TfToken& attributeName, const std::string& alias) { std::vector<std::string>& aliases = _attributeAliases[attributeName]; if (std::find(aliases.begin(), aliases.end(), alias) == aliases.end()) { aliases.push_back(alias); UsdMaya_RegistryHelper::AddUnloader([attributeName, alias]() { std::vector<std::string>& aliases = _attributeAliases[attributeName]; aliases.erase( std::remove(aliases.begin(), aliases.end(), alias), aliases.end()); }); } else { TF_CODING_ERROR("Attribute alias '%s' (='%s') already registered", alias.c_str(), attributeName.GetText()); } } /* static */ std::vector<std::string> UsdMayaAdaptor::GetAttributeAliases(const TfToken& attributeName) { TfRegistryManager::GetInstance().SubscribeTo<UsdMayaAdaptor>(); std::vector<std::string> result; result.push_back(_GetMayaAttrNameForAttrName(attributeName)); auto iter = _attributeAliases.find(attributeName); if (iter != _attributeAliases.end()) { const std::vector<std::string>& aliases = iter->second; result.insert(result.end(), aliases.begin(), aliases.end()); } return result; } UsdMayaAdaptor::SchemaAdaptor::SchemaAdaptor() : _handle(), _schemaDef(nullptr) { } UsdMayaAdaptor::SchemaAdaptor::SchemaAdaptor( const MObjectHandle& handle, SdfPrimSpecHandle schemaDef) : _handle(handle), _schemaDef(schemaDef) { } UsdMayaAdaptor::SchemaAdaptor::operator bool() const { if (!_handle.isValid() || !_schemaDef) { return false; } MStatus status; MFnDependencyNode node(_handle.object(), &status); return status; } std::string UsdMayaAdaptor::SchemaAdaptor::_GetMayaAttrNameOrAlias( const SdfAttributeSpecHandle& attrSpec) const { if (!*this) { TF_CODING_ERROR("Schema adaptor is not valid"); return std::string(); } TfRegistryManager::GetInstance().SubscribeTo<UsdMayaAdaptor>(); const MObject thisObject = _handle.object(); MFnDependencyNode depNode(thisObject); // If the generated name exists, it is the most preferred name, const TfToken name = attrSpec->GetNameToken(); const std::string genName = _GetMayaAttrNameForAttrName(name); if (depNode.hasAttribute(genName.c_str())) { return genName; } // Otherwise, search for any aliases that may already exist. auto iter = _attributeAliases.find(name); if (iter != _attributeAliases.end()) { const std::vector<std::string>& aliases = iter->second; for (const std::string& alias : aliases) { if (depNode.hasAttribute(alias.c_str())) { return alias; } } } // No attribute exists for this USD attribute. When creating, always use // the generated name. return genName; } UsdMayaAdaptor UsdMayaAdaptor::SchemaAdaptor::GetNodeAdaptor() const { if (!*this) { return UsdMayaAdaptor(MObject::kNullObj); } return UsdMayaAdaptor(_handle.object()); } TfToken UsdMayaAdaptor::SchemaAdaptor::GetName() const { if (!*this) { return TfToken(); } return _schemaDef->GetNameToken(); } UsdMayaAdaptor::AttributeAdaptor UsdMayaAdaptor::SchemaAdaptor::GetAttribute(const TfToken& attrName) const { if (!*this) { return AttributeAdaptor(); } SdfAttributeSpecHandle attrDef = _schemaDef->GetAttributes()[attrName]; if (!attrDef) { TF_CODING_ERROR("Attribute '%s' doesn't exist on schema '%s'", attrName.GetText(), _schemaDef->GetName().c_str()); return AttributeAdaptor(); } std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrDef); MFnDependencyNode node(_handle.object()); MPlug plug = node.findPlug(mayaAttrName.c_str()); if (plug.isNull()) { return AttributeAdaptor(); } return AttributeAdaptor(plug, attrDef); } UsdMayaAdaptor::AttributeAdaptor UsdMayaAdaptor::SchemaAdaptor::CreateAttribute(const TfToken& attrName) { MDGModifier modifier; return CreateAttribute(attrName, modifier); } UsdMayaAdaptor::AttributeAdaptor UsdMayaAdaptor::SchemaAdaptor::CreateAttribute( const TfToken& attrName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Schema adaptor is not valid"); return AttributeAdaptor(); } SdfAttributeSpecHandle attrDef = _schemaDef->GetAttributes()[attrName]; if (!attrDef) { TF_CODING_ERROR("Attribute '%s' doesn't exist on schema '%s'", attrName.GetText(), _schemaDef->GetName().c_str()); return AttributeAdaptor(); } std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrDef); std::string mayaNiceAttrName = attrDef->GetName(); MFnDependencyNode node(_handle.object()); bool newAttr = !node.hasAttribute(mayaAttrName.c_str()); MObject attrObj = UsdMayaReadUtil::FindOrCreateMayaAttr( attrDef->GetTypeName(), attrDef->GetVariability(), node, mayaAttrName, mayaNiceAttrName, modifier); if (attrObj.isNull()) { return AttributeAdaptor(); } MPlug plug = node.findPlug(attrObj); if (newAttr && attrDef->HasDefaultValue()) { // Set the fallback value as the initial value of the attribute, if // it exists. (There's not much point in setting the "default" value in // Maya, because it won't behave like the fallback value in USD.) UsdMayaReadUtil::SetMayaAttr( plug, attrDef->GetDefaultValue(), modifier); } return AttributeAdaptor(plug, attrDef); } void UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute(const TfToken& attrName) { MDGModifier modifier; RemoveAttribute(attrName, modifier); } void UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute( const TfToken& attrName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Schema adaptor is not valid"); return; } SdfAttributeSpecHandle attrDef = _schemaDef->GetAttributes()[attrName]; if (!attrDef) { TF_CODING_ERROR("Attribute '%s' doesn't exist on schema '%s'", attrName.GetText(), _schemaDef->GetName().c_str()); return; } std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrDef); MFnDependencyNode node(_handle.object()); if (node.hasAttribute(mayaAttrName.c_str())) { MObject attr = node.attribute(mayaAttrName.c_str()); modifier.removeAttribute(_handle.object(), attr); modifier.doIt(); } } TfTokenVector UsdMayaAdaptor::SchemaAdaptor::GetAuthoredAttributeNames() const { if (!*this) { return TfTokenVector(); } MFnDependencyNode node(_handle.object()); TfTokenVector result; for (const SdfAttributeSpecHandle& attr : _schemaDef->GetAttributes()) { std::string mayaAttrName = _GetMayaAttrNameOrAlias(attr); if (node.hasAttribute(mayaAttrName.c_str())) { result.push_back(attr->GetNameToken()); } } return result; } TfTokenVector UsdMayaAdaptor::SchemaAdaptor::GetAttributeNames() const { if (!*this) { return TfTokenVector(); } TfTokenVector attrNames; for (const SdfAttributeSpecHandle attr : _schemaDef->GetAttributes()) { attrNames.push_back(attr->GetNameToken()); } return attrNames; } const SdfPrimSpecHandle UsdMayaAdaptor::SchemaAdaptor::GetSchemaDefinition() const { return _schemaDef; } UsdMayaAdaptor::AttributeAdaptor::AttributeAdaptor() : _plug(), _node(), _attr(), _attrDef(nullptr) { } UsdMayaAdaptor::AttributeAdaptor::AttributeAdaptor( const MPlug& plug, SdfAttributeSpecHandle attrDef) : _plug(plug), _node(plug.node()), _attr(plug.attribute()), _attrDef(attrDef) { } UsdMayaAdaptor::AttributeAdaptor::operator bool() const { if (_plug.isNull() || !_node.isValid() || !_attr.isValid() || !_attrDef) { return false; } MStatus status; MFnDependencyNode depNode(_node.object(), &status); if (!status) { return false; } MFnAttribute attr(_attr.object(), &status); if (!status) { return false; } return depNode.hasAttribute(attr.name()); } UsdMayaAdaptor UsdMayaAdaptor::AttributeAdaptor::GetNodeAdaptor() const { if (!*this) { return UsdMayaAdaptor(MObject::kNullObj); } return UsdMayaAdaptor(_plug.node()); } TfToken UsdMayaAdaptor::AttributeAdaptor::GetName() const { if (!*this) { return TfToken(); } return _attrDef->GetNameToken(); } bool UsdMayaAdaptor::AttributeAdaptor::Get(VtValue* value) const { if (!*this) { return false; } VtValue result = UsdMayaWriteUtil::GetVtValue(_plug, _attrDef->GetTypeName()); if (result.IsEmpty()) { return false; } *value = result; return true; } bool UsdMayaAdaptor::AttributeAdaptor::Set(const VtValue& newValue) { MDGModifier modifier; return Set(newValue, modifier); } bool UsdMayaAdaptor::AttributeAdaptor::Set( const VtValue& newValue, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Attribute adaptor is not valid"); return false; } return UsdMayaReadUtil::SetMayaAttr(_plug, newValue, modifier); } const SdfAttributeSpecHandle UsdMayaAdaptor::AttributeAdaptor::GetAttributeDefinition() const { return _attrDef; } PXR_NAMESPACE_CLOSE_SCOPE
26.861996
79
0.661714
[ "object", "vector" ]
283885e5222e0533c21779c5e48636d57d53da18
106,620
cc
C++
android/art/runtime/interpreter/interpreter_switch_impl.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
206
2020-04-13T03:19:33.000Z
2022-03-27T13:52:25.000Z
android/art/runtime/interpreter/interpreter_switch_impl.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
9
2020-06-07T12:51:09.000Z
2022-03-28T23:55:09.000Z
android/art/runtime/interpreter/interpreter_switch_impl.cc
Solotov/deoptfuscator
8a54119e81517bcef73d2d6dfefba910ae2446e7
[ "MIT" ]
42
2020-04-13T03:37:58.000Z
2022-03-23T15:08:12.000Z
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "interpreter_switch_impl.h" #include "base/enums.h" #include "base/quasi_atomic.h" #include "dex/dex_file_types.h" #include "experimental_flags.h" #include "interpreter_common.h" #include "jit/jit.h" #include "jvalue-inl.h" #include "safe_math.h" namespace art { namespace interpreter { #define HANDLE_PENDING_EXCEPTION_WITH_INSTRUMENTATION(instr) \ do { \ DCHECK(self->IsExceptionPending()); \ self->AllowThreadSuspension(); \ if (!MoveToExceptionHandler(self, shadow_frame, instr)) { \ /* Structured locking is to be enforced for abnormal termination, too. */ \ DoMonitorCheckOnExit<do_assignability_check>(self, &shadow_frame); \ if (interpret_one_instruction) { \ /* Signal mterp to return to caller */ \ shadow_frame.SetDexPC(dex::kDexNoIndex); \ } \ ctx->result = JValue(); /* Handled in caller. */ \ return; \ } else { \ int32_t displacement = \ static_cast<int32_t>(shadow_frame.GetDexPC()) - static_cast<int32_t>(dex_pc); \ inst = inst->RelativeAt(displacement); \ } \ } while (false) #define HANDLE_PENDING_EXCEPTION() HANDLE_PENDING_EXCEPTION_WITH_INSTRUMENTATION(instrumentation) #define POSSIBLY_HANDLE_PENDING_EXCEPTION(_is_exception_pending, _next_function) \ do { \ if (UNLIKELY(_is_exception_pending)) { \ HANDLE_PENDING_EXCEPTION(); \ } else { \ inst = inst->_next_function(); \ } \ } while (false) #define HANDLE_MONITOR_CHECKS() \ if (!DoMonitorCheckOnExit<do_assignability_check>(self, &shadow_frame)) { \ HANDLE_PENDING_EXCEPTION(); \ } // Code to run before each dex instruction. #define PREAMBLE_SAVE(save_ref) \ { \ if (UNLIKELY(instrumentation->HasDexPcListeners()) && \ UNLIKELY(!DoDexPcMoveEvent(self, \ accessor, \ shadow_frame, \ dex_pc, \ instrumentation, \ save_ref))) { \ HANDLE_PENDING_EXCEPTION(); \ break; \ } \ } \ do {} while (false) #define PREAMBLE() PREAMBLE_SAVE(nullptr) #define BRANCH_INSTRUMENTATION(offset) \ do { \ if (UNLIKELY(instrumentation->HasBranchListeners())) { \ instrumentation->Branch(self, shadow_frame.GetMethod(), dex_pc, offset); \ } \ JValue result; \ if (jit::Jit::MaybeDoOnStackReplacement(self, \ shadow_frame.GetMethod(), \ dex_pc, \ offset, \ &result)) { \ if (interpret_one_instruction) { \ /* OSR has completed execution of the method. Signal mterp to return to caller */ \ shadow_frame.SetDexPC(dex::kDexNoIndex); \ } \ ctx->result = result; \ return; \ } \ } while (false) #define HOTNESS_UPDATE() \ do { \ if (jit != nullptr) { \ jit->AddSamples(self, shadow_frame.GetMethod(), 1, /*with_backedges*/ true); \ } \ } while (false) #define HANDLE_ASYNC_EXCEPTION() \ if (UNLIKELY(self->ObserveAsyncException())) { \ HANDLE_PENDING_EXCEPTION(); \ break; \ } \ do {} while (false) #define HANDLE_BACKWARD_BRANCH(offset) \ do { \ if (IsBackwardBranch(offset)) { \ HOTNESS_UPDATE(); \ /* Record new dex pc early to have consistent suspend point at loop header. */ \ shadow_frame.SetDexPC(inst->GetDexPc(insns)); \ self->AllowThreadSuspension(); \ } \ } while (false) // Unlike most other events the DexPcMovedEvent can be sent when there is a pending exception (if // the next instruction is MOVE_EXCEPTION). This means it needs to be handled carefully to be able // to detect exceptions thrown by the DexPcMovedEvent itself. These exceptions could be thrown by // jvmti-agents while handling breakpoint or single step events. We had to move this into its own // function because it was making ExecuteSwitchImpl have too large a stack. NO_INLINE static bool DoDexPcMoveEvent(Thread* self, const CodeItemDataAccessor& accessor, const ShadowFrame& shadow_frame, uint32_t dex_pc, const instrumentation::Instrumentation* instrumentation, JValue* save_ref) REQUIRES_SHARED(Locks::mutator_lock_) { DCHECK(instrumentation->HasDexPcListeners()); StackHandleScope<2> hs(self); Handle<mirror::Throwable> thr(hs.NewHandle(self->GetException())); mirror::Object* null_obj = nullptr; HandleWrapper<mirror::Object> h( hs.NewHandleWrapper(LIKELY(save_ref == nullptr) ? &null_obj : save_ref->GetGCRoot())); self->ClearException(); instrumentation->DexPcMovedEvent(self, shadow_frame.GetThisObject(accessor.InsSize()), shadow_frame.GetMethod(), dex_pc); if (UNLIKELY(self->IsExceptionPending())) { // We got a new exception in the dex-pc-moved event. We just let this exception replace the old // one. // TODO It would be good to add the old exception to the suppressed exceptions of the new one if // possible. return false; } else { if (UNLIKELY(!thr.IsNull())) { self->SetException(thr.Get()); } return true; } } static bool NeedsMethodExitEvent(const instrumentation::Instrumentation* ins) REQUIRES_SHARED(Locks::mutator_lock_) { return ins->HasMethodExitListeners() || ins->HasWatchedFramePopListeners(); } // Sends the normal method exit event. Returns true if the events succeeded and false if there is a // pending exception. NO_INLINE static bool SendMethodExitEvents(Thread* self, const instrumentation::Instrumentation* instrumentation, const ShadowFrame& frame, ObjPtr<mirror::Object> thiz, ArtMethod* method, uint32_t dex_pc, const JValue& result) REQUIRES_SHARED(Locks::mutator_lock_) { bool had_event = false; if (UNLIKELY(instrumentation->HasMethodExitListeners())) { had_event = true; instrumentation->MethodExitEvent(self, thiz.Ptr(), method, dex_pc, result); } if (UNLIKELY(frame.NeedsNotifyPop() && instrumentation->HasWatchedFramePopListeners())) { had_event = true; instrumentation->WatchedFramePopped(self, frame); } if (UNLIKELY(had_event)) { return !self->IsExceptionPending(); } else { return true; } } template<bool do_access_check, bool transaction_active> void ExecuteSwitchImplCpp(SwitchImplContext* ctx) { Thread* self = ctx->self; const CodeItemDataAccessor& accessor = ctx->accessor; ShadowFrame& shadow_frame = ctx->shadow_frame; JValue result_register = ctx->result_register; bool interpret_one_instruction = ctx->interpret_one_instruction; constexpr bool do_assignability_check = do_access_check; if (UNLIKELY(!shadow_frame.HasReferenceArray())) { LOG(FATAL) << "Invalid shadow frame for interpreter use"; ctx->result = JValue(); return; } self->VerifyStack(); uint32_t dex_pc = shadow_frame.GetDexPC(); const auto* const instrumentation = Runtime::Current()->GetInstrumentation(); const uint16_t* const insns = accessor.Insns(); const Instruction* inst = Instruction::At(insns + dex_pc); uint16_t inst_data; jit::Jit* jit = Runtime::Current()->GetJit(); do { dex_pc = inst->GetDexPc(insns); shadow_frame.SetDexPC(dex_pc); TraceExecution(shadow_frame, inst, dex_pc); inst_data = inst->Fetch16(0); switch (inst->Opcode(inst_data)) { case Instruction::NOP: PREAMBLE(); inst = inst->Next_1xx(); break; case Instruction::MOVE: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_12x(inst_data), shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::MOVE_FROM16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22x(inst_data), shadow_frame.GetVReg(inst->VRegB_22x())); inst = inst->Next_2xx(); break; case Instruction::MOVE_16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_32x(), shadow_frame.GetVReg(inst->VRegB_32x())); inst = inst->Next_3xx(); break; case Instruction::MOVE_WIDE: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_12x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::MOVE_WIDE_FROM16: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_22x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_22x())); inst = inst->Next_2xx(); break; case Instruction::MOVE_WIDE_16: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_32x(), shadow_frame.GetVRegLong(inst->VRegB_32x())); inst = inst->Next_3xx(); break; case Instruction::MOVE_OBJECT: PREAMBLE(); shadow_frame.SetVRegReference(inst->VRegA_12x(inst_data), shadow_frame.GetVRegReference(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::MOVE_OBJECT_FROM16: PREAMBLE(); shadow_frame.SetVRegReference(inst->VRegA_22x(inst_data), shadow_frame.GetVRegReference(inst->VRegB_22x())); inst = inst->Next_2xx(); break; case Instruction::MOVE_OBJECT_16: PREAMBLE(); shadow_frame.SetVRegReference(inst->VRegA_32x(), shadow_frame.GetVRegReference(inst->VRegB_32x())); inst = inst->Next_3xx(); break; case Instruction::MOVE_RESULT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_11x(inst_data), result_register.GetI()); inst = inst->Next_1xx(); break; case Instruction::MOVE_RESULT_WIDE: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_11x(inst_data), result_register.GetJ()); inst = inst->Next_1xx(); break; case Instruction::MOVE_RESULT_OBJECT: PREAMBLE_SAVE(&result_register); shadow_frame.SetVRegReference(inst->VRegA_11x(inst_data), result_register.GetL()); inst = inst->Next_1xx(); break; case Instruction::MOVE_EXCEPTION: { PREAMBLE(); ObjPtr<mirror::Throwable> exception = self->GetException(); DCHECK(exception != nullptr) << "No pending exception on MOVE_EXCEPTION instruction"; shadow_frame.SetVRegReference(inst->VRegA_11x(inst_data), exception.Ptr()); self->ClearException(); inst = inst->Next_1xx(); break; } case Instruction::RETURN_VOID_NO_BARRIER: { PREAMBLE(); JValue result; self->AllowThreadSuspension(); HANDLE_MONITOR_CHECKS(); if (UNLIKELY(NeedsMethodExitEvent(instrumentation) && !SendMethodExitEvents(self, instrumentation, shadow_frame, shadow_frame.GetThisObject(accessor.InsSize()), shadow_frame.GetMethod(), inst->GetDexPc(insns), result))) { HANDLE_PENDING_EXCEPTION_WITH_INSTRUMENTATION(nullptr); } if (interpret_one_instruction) { /* Signal mterp to return to caller */ shadow_frame.SetDexPC(dex::kDexNoIndex); } ctx->result = result; return; } case Instruction::RETURN_VOID: { PREAMBLE(); QuasiAtomic::ThreadFenceForConstructor(); JValue result; self->AllowThreadSuspension(); HANDLE_MONITOR_CHECKS(); if (UNLIKELY(NeedsMethodExitEvent(instrumentation) && !SendMethodExitEvents(self, instrumentation, shadow_frame, shadow_frame.GetThisObject(accessor.InsSize()), shadow_frame.GetMethod(), inst->GetDexPc(insns), result))) { HANDLE_PENDING_EXCEPTION_WITH_INSTRUMENTATION(nullptr); } if (interpret_one_instruction) { /* Signal mterp to return to caller */ shadow_frame.SetDexPC(dex::kDexNoIndex); } ctx->result = result; return; } case Instruction::RETURN: { PREAMBLE(); JValue result; result.SetJ(0); result.SetI(shadow_frame.GetVReg(inst->VRegA_11x(inst_data))); self->AllowThreadSuspension(); HANDLE_MONITOR_CHECKS(); if (UNLIKELY(NeedsMethodExitEvent(instrumentation) && !SendMethodExitEvents(self, instrumentation, shadow_frame, shadow_frame.GetThisObject(accessor.InsSize()), shadow_frame.GetMethod(), inst->GetDexPc(insns), result))) { HANDLE_PENDING_EXCEPTION_WITH_INSTRUMENTATION(nullptr); } if (interpret_one_instruction) { /* Signal mterp to return to caller */ shadow_frame.SetDexPC(dex::kDexNoIndex); } ctx->result = result; return; } case Instruction::RETURN_WIDE: { PREAMBLE(); JValue result; result.SetJ(shadow_frame.GetVRegLong(inst->VRegA_11x(inst_data))); self->AllowThreadSuspension(); HANDLE_MONITOR_CHECKS(); if (UNLIKELY(NeedsMethodExitEvent(instrumentation) && !SendMethodExitEvents(self, instrumentation, shadow_frame, shadow_frame.GetThisObject(accessor.InsSize()), shadow_frame.GetMethod(), inst->GetDexPc(insns), result))) { HANDLE_PENDING_EXCEPTION_WITH_INSTRUMENTATION(nullptr); } if (interpret_one_instruction) { /* Signal mterp to return to caller */ shadow_frame.SetDexPC(dex::kDexNoIndex); } ctx->result = result; return; } case Instruction::RETURN_OBJECT: { PREAMBLE(); JValue result; self->AllowThreadSuspension(); HANDLE_MONITOR_CHECKS(); const size_t ref_idx = inst->VRegA_11x(inst_data); ObjPtr<mirror::Object> obj_result = shadow_frame.GetVRegReference(ref_idx); if (do_assignability_check && obj_result != nullptr) { ObjPtr<mirror::Class> return_type = shadow_frame.GetMethod()->ResolveReturnType(); // Re-load since it might have moved. obj_result = shadow_frame.GetVRegReference(ref_idx); if (return_type == nullptr) { // Return the pending exception. HANDLE_PENDING_EXCEPTION(); } if (!obj_result->VerifierInstanceOf(return_type)) { // This should never happen. std::string temp1, temp2; self->ThrowNewExceptionF("Ljava/lang/InternalError;", "Returning '%s' that is not instance of return type '%s'", obj_result->GetClass()->GetDescriptor(&temp1), return_type->GetDescriptor(&temp2)); HANDLE_PENDING_EXCEPTION(); } } result.SetL(obj_result); if (UNLIKELY(NeedsMethodExitEvent(instrumentation) && !SendMethodExitEvents(self, instrumentation, shadow_frame, shadow_frame.GetThisObject(accessor.InsSize()), shadow_frame.GetMethod(), inst->GetDexPc(insns), result))) { HANDLE_PENDING_EXCEPTION_WITH_INSTRUMENTATION(nullptr); } // Re-load since it might have moved during the MethodExitEvent. result.SetL(shadow_frame.GetVRegReference(ref_idx)); if (interpret_one_instruction) { /* Signal mterp to return to caller */ shadow_frame.SetDexPC(dex::kDexNoIndex); } ctx->result = result; return; } case Instruction::CONST_4: { PREAMBLE(); uint4_t dst = inst->VRegA_11n(inst_data); int4_t val = inst->VRegB_11n(inst_data); shadow_frame.SetVReg(dst, val); if (val == 0) { shadow_frame.SetVRegReference(dst, nullptr); } inst = inst->Next_1xx(); break; } case Instruction::CONST_16: { PREAMBLE(); uint8_t dst = inst->VRegA_21s(inst_data); int16_t val = inst->VRegB_21s(); shadow_frame.SetVReg(dst, val); if (val == 0) { shadow_frame.SetVRegReference(dst, nullptr); } inst = inst->Next_2xx(); break; } case Instruction::CONST: { PREAMBLE(); uint8_t dst = inst->VRegA_31i(inst_data); int32_t val = inst->VRegB_31i(); shadow_frame.SetVReg(dst, val); if (val == 0) { shadow_frame.SetVRegReference(dst, nullptr); } inst = inst->Next_3xx(); break; } case Instruction::CONST_HIGH16: { PREAMBLE(); uint8_t dst = inst->VRegA_21h(inst_data); int32_t val = static_cast<int32_t>(inst->VRegB_21h() << 16); shadow_frame.SetVReg(dst, val); if (val == 0) { shadow_frame.SetVRegReference(dst, nullptr); } inst = inst->Next_2xx(); break; } case Instruction::CONST_WIDE_16: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_21s(inst_data), inst->VRegB_21s()); inst = inst->Next_2xx(); break; case Instruction::CONST_WIDE_32: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_31i(inst_data), inst->VRegB_31i()); inst = inst->Next_3xx(); break; case Instruction::CONST_WIDE: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_51l(inst_data), inst->VRegB_51l()); inst = inst->Next_51l(); break; case Instruction::CONST_WIDE_HIGH16: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_21h(inst_data), static_cast<uint64_t>(inst->VRegB_21h()) << 48); inst = inst->Next_2xx(); break; case Instruction::CONST_STRING: { PREAMBLE(); ObjPtr<mirror::String> s = ResolveString(self, shadow_frame, dex::StringIndex(inst->VRegB_21c())); if (UNLIKELY(s == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { shadow_frame.SetVRegReference(inst->VRegA_21c(inst_data), s.Ptr()); inst = inst->Next_2xx(); } break; } case Instruction::CONST_STRING_JUMBO: { PREAMBLE(); ObjPtr<mirror::String> s = ResolveString(self, shadow_frame, dex::StringIndex(inst->VRegB_31c())); if (UNLIKELY(s == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { shadow_frame.SetVRegReference(inst->VRegA_31c(inst_data), s.Ptr()); inst = inst->Next_3xx(); } break; } case Instruction::CONST_CLASS: { PREAMBLE(); ObjPtr<mirror::Class> c = ResolveVerifyAndClinit(dex::TypeIndex(inst->VRegB_21c()), shadow_frame.GetMethod(), self, false, do_access_check); if (UNLIKELY(c == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { shadow_frame.SetVRegReference(inst->VRegA_21c(inst_data), c.Ptr()); inst = inst->Next_2xx(); } break; } case Instruction::CONST_METHOD_HANDLE: { PREAMBLE(); ClassLinker* cl = Runtime::Current()->GetClassLinker(); ObjPtr<mirror::MethodHandle> mh = cl->ResolveMethodHandle(self, inst->VRegB_21c(), shadow_frame.GetMethod()); if (UNLIKELY(mh == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { shadow_frame.SetVRegReference(inst->VRegA_21c(inst_data), mh.Ptr()); inst = inst->Next_2xx(); } break; } case Instruction::CONST_METHOD_TYPE: { PREAMBLE(); ClassLinker* cl = Runtime::Current()->GetClassLinker(); ObjPtr<mirror::MethodType> mt = cl->ResolveMethodType(self, inst->VRegB_21c(), shadow_frame.GetMethod()); if (UNLIKELY(mt == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { shadow_frame.SetVRegReference(inst->VRegA_21c(inst_data), mt.Ptr()); inst = inst->Next_2xx(); } break; } case Instruction::MONITOR_ENTER: { PREAMBLE(); HANDLE_ASYNC_EXCEPTION(); ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(inst->VRegA_11x(inst_data)); if (UNLIKELY(obj == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); } else { DoMonitorEnter<do_assignability_check>(self, &shadow_frame, obj); POSSIBLY_HANDLE_PENDING_EXCEPTION(self->IsExceptionPending(), Next_1xx); } break; } case Instruction::MONITOR_EXIT: { PREAMBLE(); HANDLE_ASYNC_EXCEPTION(); ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(inst->VRegA_11x(inst_data)); if (UNLIKELY(obj == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); } else { DoMonitorExit<do_assignability_check>(self, &shadow_frame, obj); POSSIBLY_HANDLE_PENDING_EXCEPTION(self->IsExceptionPending(), Next_1xx); } break; } case Instruction::CHECK_CAST: { PREAMBLE(); ObjPtr<mirror::Class> c = ResolveVerifyAndClinit(dex::TypeIndex(inst->VRegB_21c()), shadow_frame.GetMethod(), self, false, do_access_check); if (UNLIKELY(c == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(inst->VRegA_21c(inst_data)); if (UNLIKELY(obj != nullptr && !obj->InstanceOf(c))) { ThrowClassCastException(c, obj->GetClass()); HANDLE_PENDING_EXCEPTION(); } else { inst = inst->Next_2xx(); } } break; } case Instruction::INSTANCE_OF: { PREAMBLE(); ObjPtr<mirror::Class> c = ResolveVerifyAndClinit(dex::TypeIndex(inst->VRegC_22c()), shadow_frame.GetMethod(), self, false, do_access_check); if (UNLIKELY(c == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(inst->VRegB_22c(inst_data)); shadow_frame.SetVReg(inst->VRegA_22c(inst_data), (obj != nullptr && obj->InstanceOf(c)) ? 1 : 0); inst = inst->Next_2xx(); } break; } case Instruction::ARRAY_LENGTH: { PREAMBLE(); ObjPtr<mirror::Object> array = shadow_frame.GetVRegReference(inst->VRegB_12x(inst_data)); if (UNLIKELY(array == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); } else { shadow_frame.SetVReg(inst->VRegA_12x(inst_data), array->AsArray()->GetLength()); inst = inst->Next_1xx(); } break; } case Instruction::NEW_INSTANCE: { PREAMBLE(); ObjPtr<mirror::Object> obj = nullptr; ObjPtr<mirror::Class> c = ResolveVerifyAndClinit(dex::TypeIndex(inst->VRegB_21c()), shadow_frame.GetMethod(), self, false, do_access_check); if (LIKELY(c != nullptr)) { if (UNLIKELY(c->IsStringClass())) { gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator(); obj = mirror::String::AllocEmptyString<true>(self, allocator_type); } else { obj = AllocObjectFromCode<true>( c.Ptr(), self, Runtime::Current()->GetHeap()->GetCurrentAllocator()); } } if (UNLIKELY(obj == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { obj->GetClass()->AssertInitializedOrInitializingInThread(self); // Don't allow finalizable objects to be allocated during a transaction since these can't // be finalized without a started runtime. if (transaction_active && obj->GetClass()->IsFinalizable()) { AbortTransactionF(self, "Allocating finalizable object in transaction: %s", obj->PrettyTypeOf().c_str()); HANDLE_PENDING_EXCEPTION(); break; } shadow_frame.SetVRegReference(inst->VRegA_21c(inst_data), obj.Ptr()); inst = inst->Next_2xx(); } break; } case Instruction::NEW_ARRAY: { PREAMBLE(); int32_t length = shadow_frame.GetVReg(inst->VRegB_22c(inst_data)); ObjPtr<mirror::Object> obj = AllocArrayFromCode<do_access_check, true>( dex::TypeIndex(inst->VRegC_22c()), length, shadow_frame.GetMethod(), self, Runtime::Current()->GetHeap()->GetCurrentAllocator()); if (UNLIKELY(obj == nullptr)) { HANDLE_PENDING_EXCEPTION(); } else { shadow_frame.SetVRegReference(inst->VRegA_22c(inst_data), obj.Ptr()); inst = inst->Next_2xx(); } break; } case Instruction::FILLED_NEW_ARRAY: { PREAMBLE(); bool success = DoFilledNewArray<false, do_access_check, transaction_active>(inst, shadow_frame, self, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::FILLED_NEW_ARRAY_RANGE: { PREAMBLE(); bool success = DoFilledNewArray<true, do_access_check, transaction_active>(inst, shadow_frame, self, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::FILL_ARRAY_DATA: { PREAMBLE(); const uint16_t* payload_addr = reinterpret_cast<const uint16_t*>(inst) + inst->VRegB_31t(); const Instruction::ArrayDataPayload* payload = reinterpret_cast<const Instruction::ArrayDataPayload*>(payload_addr); ObjPtr<mirror::Object> obj = shadow_frame.GetVRegReference(inst->VRegA_31t(inst_data)); bool success = FillArrayData(obj, payload); if (!success) { HANDLE_PENDING_EXCEPTION(); break; } if (transaction_active) { RecordArrayElementsInTransaction(obj->AsArray(), payload->element_count); } inst = inst->Next_3xx(); break; } case Instruction::THROW: { PREAMBLE(); HANDLE_ASYNC_EXCEPTION(); ObjPtr<mirror::Object> exception = shadow_frame.GetVRegReference(inst->VRegA_11x(inst_data)); if (UNLIKELY(exception == nullptr)) { ThrowNullPointerException("throw with null exception"); } else if (do_assignability_check && !exception->GetClass()->IsThrowableClass()) { // This should never happen. std::string temp; self->ThrowNewExceptionF("Ljava/lang/InternalError;", "Throwing '%s' that is not instance of Throwable", exception->GetClass()->GetDescriptor(&temp)); } else { self->SetException(exception->AsThrowable()); } HANDLE_PENDING_EXCEPTION(); break; } case Instruction::GOTO: { PREAMBLE(); HANDLE_ASYNC_EXCEPTION(); int8_t offset = inst->VRegA_10t(inst_data); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); break; } case Instruction::GOTO_16: { PREAMBLE(); HANDLE_ASYNC_EXCEPTION(); int16_t offset = inst->VRegA_20t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); break; } case Instruction::GOTO_32: { PREAMBLE(); HANDLE_ASYNC_EXCEPTION(); int32_t offset = inst->VRegA_30t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); break; } case Instruction::PACKED_SWITCH: { PREAMBLE(); int32_t offset = DoPackedSwitch(inst, shadow_frame, inst_data); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); break; } case Instruction::SPARSE_SWITCH: { PREAMBLE(); int32_t offset = DoSparseSwitch(inst, shadow_frame, inst_data); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); break; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wfloat-equal" case Instruction::CMPL_FLOAT: { PREAMBLE(); float val1 = shadow_frame.GetVRegFloat(inst->VRegB_23x()); float val2 = shadow_frame.GetVRegFloat(inst->VRegC_23x()); int32_t result; if (val1 > val2) { result = 1; } else if (val1 == val2) { result = 0; } else { result = -1; } shadow_frame.SetVReg(inst->VRegA_23x(inst_data), result); inst = inst->Next_2xx(); break; } case Instruction::CMPG_FLOAT: { PREAMBLE(); float val1 = shadow_frame.GetVRegFloat(inst->VRegB_23x()); float val2 = shadow_frame.GetVRegFloat(inst->VRegC_23x()); int32_t result; if (val1 < val2) { result = -1; } else if (val1 == val2) { result = 0; } else { result = 1; } shadow_frame.SetVReg(inst->VRegA_23x(inst_data), result); inst = inst->Next_2xx(); break; } case Instruction::CMPL_DOUBLE: { PREAMBLE(); double val1 = shadow_frame.GetVRegDouble(inst->VRegB_23x()); double val2 = shadow_frame.GetVRegDouble(inst->VRegC_23x()); int32_t result; if (val1 > val2) { result = 1; } else if (val1 == val2) { result = 0; } else { result = -1; } shadow_frame.SetVReg(inst->VRegA_23x(inst_data), result); inst = inst->Next_2xx(); break; } case Instruction::CMPG_DOUBLE: { PREAMBLE(); double val1 = shadow_frame.GetVRegDouble(inst->VRegB_23x()); double val2 = shadow_frame.GetVRegDouble(inst->VRegC_23x()); int32_t result; if (val1 < val2) { result = -1; } else if (val1 == val2) { result = 0; } else { result = 1; } shadow_frame.SetVReg(inst->VRegA_23x(inst_data), result); inst = inst->Next_2xx(); break; } #pragma clang diagnostic pop case Instruction::CMP_LONG: { PREAMBLE(); int64_t val1 = shadow_frame.GetVRegLong(inst->VRegB_23x()); int64_t val2 = shadow_frame.GetVRegLong(inst->VRegC_23x()); int32_t result; if (val1 > val2) { result = 1; } else if (val1 == val2) { result = 0; } else { result = -1; } shadow_frame.SetVReg(inst->VRegA_23x(inst_data), result); inst = inst->Next_2xx(); break; } case Instruction::IF_EQ: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_22t(inst_data)) == shadow_frame.GetVReg(inst->VRegB_22t(inst_data))) { int16_t offset = inst->VRegC_22t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_NE: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_22t(inst_data)) != shadow_frame.GetVReg(inst->VRegB_22t(inst_data))) { int16_t offset = inst->VRegC_22t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_LT: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_22t(inst_data)) < shadow_frame.GetVReg(inst->VRegB_22t(inst_data))) { int16_t offset = inst->VRegC_22t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_GE: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_22t(inst_data)) >= shadow_frame.GetVReg(inst->VRegB_22t(inst_data))) { int16_t offset = inst->VRegC_22t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_GT: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_22t(inst_data)) > shadow_frame.GetVReg(inst->VRegB_22t(inst_data))) { int16_t offset = inst->VRegC_22t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_LE: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_22t(inst_data)) <= shadow_frame.GetVReg(inst->VRegB_22t(inst_data))) { int16_t offset = inst->VRegC_22t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_EQZ: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_21t(inst_data)) == 0) { int16_t offset = inst->VRegB_21t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_NEZ: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_21t(inst_data)) != 0) { int16_t offset = inst->VRegB_21t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_LTZ: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_21t(inst_data)) < 0) { int16_t offset = inst->VRegB_21t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_GEZ: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_21t(inst_data)) >= 0) { int16_t offset = inst->VRegB_21t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_GTZ: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_21t(inst_data)) > 0) { int16_t offset = inst->VRegB_21t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::IF_LEZ: { PREAMBLE(); if (shadow_frame.GetVReg(inst->VRegA_21t(inst_data)) <= 0) { int16_t offset = inst->VRegB_21t(); BRANCH_INSTRUMENTATION(offset); inst = inst->RelativeAt(offset); HANDLE_BACKWARD_BRANCH(offset); } else { BRANCH_INSTRUMENTATION(2); inst = inst->Next_2xx(); } break; } case Instruction::AGET_BOOLEAN: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::BooleanArray> array = a->AsBooleanArray(); if (array->CheckIsValidIndex(index)) { shadow_frame.SetVReg(inst->VRegA_23x(inst_data), array->GetWithoutChecks(index)); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::AGET_BYTE: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::ByteArray> array = a->AsByteArray(); if (array->CheckIsValidIndex(index)) { shadow_frame.SetVReg(inst->VRegA_23x(inst_data), array->GetWithoutChecks(index)); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::AGET_CHAR: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::CharArray> array = a->AsCharArray(); if (array->CheckIsValidIndex(index)) { shadow_frame.SetVReg(inst->VRegA_23x(inst_data), array->GetWithoutChecks(index)); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::AGET_SHORT: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::ShortArray> array = a->AsShortArray(); if (array->CheckIsValidIndex(index)) { shadow_frame.SetVReg(inst->VRegA_23x(inst_data), array->GetWithoutChecks(index)); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::AGET: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); DCHECK(a->IsIntArray() || a->IsFloatArray()) << a->PrettyTypeOf(); ObjPtr<mirror::IntArray> array = ObjPtr<mirror::IntArray>::DownCast(a); if (array->CheckIsValidIndex(index)) { shadow_frame.SetVReg(inst->VRegA_23x(inst_data), array->GetWithoutChecks(index)); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::AGET_WIDE: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); DCHECK(a->IsLongArray() || a->IsDoubleArray()) << a->PrettyTypeOf(); ObjPtr<mirror::LongArray> array = ObjPtr<mirror::LongArray>::DownCast(a); if (array->CheckIsValidIndex(index)) { shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), array->GetWithoutChecks(index)); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::AGET_OBJECT: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::ObjectArray<mirror::Object>> array = a->AsObjectArray<mirror::Object>(); if (array->CheckIsValidIndex(index)) { shadow_frame.SetVRegReference(inst->VRegA_23x(inst_data), array->GetWithoutChecks(index)); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::APUT_BOOLEAN: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } uint8_t val = shadow_frame.GetVReg(inst->VRegA_23x(inst_data)); int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::BooleanArray> array = a->AsBooleanArray(); if (array->CheckIsValidIndex(index)) { array->SetWithoutChecks<transaction_active>(index, val); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::APUT_BYTE: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int8_t val = shadow_frame.GetVReg(inst->VRegA_23x(inst_data)); int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::ByteArray> array = a->AsByteArray(); if (array->CheckIsValidIndex(index)) { array->SetWithoutChecks<transaction_active>(index, val); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::APUT_CHAR: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } uint16_t val = shadow_frame.GetVReg(inst->VRegA_23x(inst_data)); int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::CharArray> array = a->AsCharArray(); if (array->CheckIsValidIndex(index)) { array->SetWithoutChecks<transaction_active>(index, val); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::APUT_SHORT: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int16_t val = shadow_frame.GetVReg(inst->VRegA_23x(inst_data)); int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::ShortArray> array = a->AsShortArray(); if (array->CheckIsValidIndex(index)) { array->SetWithoutChecks<transaction_active>(index, val); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::APUT: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t val = shadow_frame.GetVReg(inst->VRegA_23x(inst_data)); int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); DCHECK(a->IsIntArray() || a->IsFloatArray()) << a->PrettyTypeOf(); ObjPtr<mirror::IntArray> array = ObjPtr<mirror::IntArray>::DownCast(a); if (array->CheckIsValidIndex(index)) { array->SetWithoutChecks<transaction_active>(index, val); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::APUT_WIDE: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int64_t val = shadow_frame.GetVRegLong(inst->VRegA_23x(inst_data)); int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); DCHECK(a->IsLongArray() || a->IsDoubleArray()) << a->PrettyTypeOf(); ObjPtr<mirror::LongArray> array = ObjPtr<mirror::LongArray>::DownCast(a); if (array->CheckIsValidIndex(index)) { array->SetWithoutChecks<transaction_active>(index, val); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::APUT_OBJECT: { PREAMBLE(); ObjPtr<mirror::Object> a = shadow_frame.GetVRegReference(inst->VRegB_23x()); if (UNLIKELY(a == nullptr)) { ThrowNullPointerExceptionFromInterpreter(); HANDLE_PENDING_EXCEPTION(); break; } int32_t index = shadow_frame.GetVReg(inst->VRegC_23x()); ObjPtr<mirror::Object> val = shadow_frame.GetVRegReference(inst->VRegA_23x(inst_data)); ObjPtr<mirror::ObjectArray<mirror::Object>> array = a->AsObjectArray<mirror::Object>(); if (array->CheckIsValidIndex(index) && array->CheckAssignable(val)) { array->SetWithoutChecks<transaction_active>(index, val); inst = inst->Next_2xx(); } else { HANDLE_PENDING_EXCEPTION(); } break; } case Instruction::IGET_BOOLEAN: { PREAMBLE(); bool success = DoFieldGet<InstancePrimitiveRead, Primitive::kPrimBoolean, do_access_check>( self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_BYTE: { PREAMBLE(); bool success = DoFieldGet<InstancePrimitiveRead, Primitive::kPrimByte, do_access_check>( self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_CHAR: { PREAMBLE(); bool success = DoFieldGet<InstancePrimitiveRead, Primitive::kPrimChar, do_access_check>( self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_SHORT: { PREAMBLE(); bool success = DoFieldGet<InstancePrimitiveRead, Primitive::kPrimShort, do_access_check>( self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET: { PREAMBLE(); bool success = DoFieldGet<InstancePrimitiveRead, Primitive::kPrimInt, do_access_check>( self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_WIDE: { PREAMBLE(); bool success = DoFieldGet<InstancePrimitiveRead, Primitive::kPrimLong, do_access_check>( self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_OBJECT: { PREAMBLE(); bool success = DoFieldGet<InstanceObjectRead, Primitive::kPrimNot, do_access_check>( self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_QUICK: { PREAMBLE(); bool success = DoIGetQuick<Primitive::kPrimInt>(shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_WIDE_QUICK: { PREAMBLE(); bool success = DoIGetQuick<Primitive::kPrimLong>(shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_OBJECT_QUICK: { PREAMBLE(); bool success = DoIGetQuick<Primitive::kPrimNot>(shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_BOOLEAN_QUICK: { PREAMBLE(); bool success = DoIGetQuick<Primitive::kPrimBoolean>(shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_BYTE_QUICK: { PREAMBLE(); bool success = DoIGetQuick<Primitive::kPrimByte>(shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_CHAR_QUICK: { PREAMBLE(); bool success = DoIGetQuick<Primitive::kPrimChar>(shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IGET_SHORT_QUICK: { PREAMBLE(); bool success = DoIGetQuick<Primitive::kPrimShort>(shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SGET_BOOLEAN: { PREAMBLE(); bool success = DoFieldGet<StaticPrimitiveRead, Primitive::kPrimBoolean, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SGET_BYTE: { PREAMBLE(); bool success = DoFieldGet<StaticPrimitiveRead, Primitive::kPrimByte, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SGET_CHAR: { PREAMBLE(); bool success = DoFieldGet<StaticPrimitiveRead, Primitive::kPrimChar, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SGET_SHORT: { PREAMBLE(); bool success = DoFieldGet<StaticPrimitiveRead, Primitive::kPrimShort, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SGET: { PREAMBLE(); bool success = DoFieldGet<StaticPrimitiveRead, Primitive::kPrimInt, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SGET_WIDE: { PREAMBLE(); bool success = DoFieldGet<StaticPrimitiveRead, Primitive::kPrimLong, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SGET_OBJECT: { PREAMBLE(); bool success = DoFieldGet<StaticObjectRead, Primitive::kPrimNot, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_BOOLEAN: { PREAMBLE(); bool success = DoFieldPut<InstancePrimitiveWrite, Primitive::kPrimBoolean, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_BYTE: { PREAMBLE(); bool success = DoFieldPut<InstancePrimitiveWrite, Primitive::kPrimByte, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_CHAR: { PREAMBLE(); bool success = DoFieldPut<InstancePrimitiveWrite, Primitive::kPrimChar, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_SHORT: { PREAMBLE(); bool success = DoFieldPut<InstancePrimitiveWrite, Primitive::kPrimShort, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT: { PREAMBLE(); bool success = DoFieldPut<InstancePrimitiveWrite, Primitive::kPrimInt, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_WIDE: { PREAMBLE(); bool success = DoFieldPut<InstancePrimitiveWrite, Primitive::kPrimLong, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_OBJECT: { PREAMBLE(); bool success = DoFieldPut<InstanceObjectWrite, Primitive::kPrimNot, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_QUICK: { PREAMBLE(); bool success = DoIPutQuick<Primitive::kPrimInt, transaction_active>( shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_BOOLEAN_QUICK: { PREAMBLE(); bool success = DoIPutQuick<Primitive::kPrimBoolean, transaction_active>( shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_BYTE_QUICK: { PREAMBLE(); bool success = DoIPutQuick<Primitive::kPrimByte, transaction_active>( shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_CHAR_QUICK: { PREAMBLE(); bool success = DoIPutQuick<Primitive::kPrimChar, transaction_active>( shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_SHORT_QUICK: { PREAMBLE(); bool success = DoIPutQuick<Primitive::kPrimShort, transaction_active>( shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_WIDE_QUICK: { PREAMBLE(); bool success = DoIPutQuick<Primitive::kPrimLong, transaction_active>( shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::IPUT_OBJECT_QUICK: { PREAMBLE(); bool success = DoIPutQuick<Primitive::kPrimNot, transaction_active>( shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SPUT_BOOLEAN: { PREAMBLE(); bool success = DoFieldPut<StaticPrimitiveWrite, Primitive::kPrimBoolean, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SPUT_BYTE: { PREAMBLE(); bool success = DoFieldPut<StaticPrimitiveWrite, Primitive::kPrimByte, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SPUT_CHAR: { PREAMBLE(); bool success = DoFieldPut<StaticPrimitiveWrite, Primitive::kPrimChar, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SPUT_SHORT: { PREAMBLE(); bool success = DoFieldPut<StaticPrimitiveWrite, Primitive::kPrimShort, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SPUT: { PREAMBLE(); bool success = DoFieldPut<StaticPrimitiveWrite, Primitive::kPrimInt, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SPUT_WIDE: { PREAMBLE(); bool success = DoFieldPut<StaticPrimitiveWrite, Primitive::kPrimLong, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SPUT_OBJECT: { PREAMBLE(); bool success = DoFieldPut<StaticObjectWrite, Primitive::kPrimNot, do_access_check, transaction_active>(self, shadow_frame, inst, inst_data); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::INVOKE_VIRTUAL: { PREAMBLE(); bool success = DoInvoke<kVirtual, false, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_VIRTUAL_RANGE: { PREAMBLE(); bool success = DoInvoke<kVirtual, true, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_SUPER: { PREAMBLE(); bool success = DoInvoke<kSuper, false, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_SUPER_RANGE: { PREAMBLE(); bool success = DoInvoke<kSuper, true, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_DIRECT: { PREAMBLE(); bool success = DoInvoke<kDirect, false, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_DIRECT_RANGE: { PREAMBLE(); bool success = DoInvoke<kDirect, true, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_INTERFACE: { PREAMBLE(); bool success = DoInvoke<kInterface, false, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_INTERFACE_RANGE: { PREAMBLE(); bool success = DoInvoke<kInterface, true, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_STATIC: { PREAMBLE(); bool success = DoInvoke<kStatic, false, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_STATIC_RANGE: { PREAMBLE(); bool success = DoInvoke<kStatic, true, do_access_check>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_VIRTUAL_QUICK: { PREAMBLE(); bool success = DoInvokeVirtualQuick<false>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: { PREAMBLE(); bool success = DoInvokeVirtualQuick<true>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_POLYMORPHIC: { PREAMBLE(); DCHECK(Runtime::Current()->IsMethodHandlesEnabled()); bool success = DoInvokePolymorphic<false /* is_range */>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_4xx); break; } case Instruction::INVOKE_POLYMORPHIC_RANGE: { PREAMBLE(); DCHECK(Runtime::Current()->IsMethodHandlesEnabled()); bool success = DoInvokePolymorphic<true /* is_range */>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_4xx); break; } case Instruction::INVOKE_CUSTOM: { PREAMBLE(); DCHECK(Runtime::Current()->IsMethodHandlesEnabled()); bool success = DoInvokeCustom<false /* is_range */>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::INVOKE_CUSTOM_RANGE: { PREAMBLE(); DCHECK(Runtime::Current()->IsMethodHandlesEnabled()); bool success = DoInvokeCustom<true /* is_range */>( self, shadow_frame, inst, inst_data, &result_register); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_3xx); break; } case Instruction::NEG_INT: PREAMBLE(); shadow_frame.SetVReg( inst->VRegA_12x(inst_data), -shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::NOT_INT: PREAMBLE(); shadow_frame.SetVReg( inst->VRegA_12x(inst_data), ~shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::NEG_LONG: PREAMBLE(); shadow_frame.SetVRegLong( inst->VRegA_12x(inst_data), -shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::NOT_LONG: PREAMBLE(); shadow_frame.SetVRegLong( inst->VRegA_12x(inst_data), ~shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::NEG_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat( inst->VRegA_12x(inst_data), -shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::NEG_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble( inst->VRegA_12x(inst_data), -shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::INT_TO_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_12x(inst_data), shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::INT_TO_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_12x(inst_data), shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::INT_TO_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_12x(inst_data), shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::LONG_TO_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_12x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::LONG_TO_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_12x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::LONG_TO_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_12x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::FLOAT_TO_INT: { PREAMBLE(); float val = shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data)); int32_t result = art_float_to_integral<int32_t, float>(val); shadow_frame.SetVReg(inst->VRegA_12x(inst_data), result); inst = inst->Next_1xx(); break; } case Instruction::FLOAT_TO_LONG: { PREAMBLE(); float val = shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data)); int64_t result = art_float_to_integral<int64_t, float>(val); shadow_frame.SetVRegLong(inst->VRegA_12x(inst_data), result); inst = inst->Next_1xx(); break; } case Instruction::FLOAT_TO_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_12x(inst_data), shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::DOUBLE_TO_INT: { PREAMBLE(); double val = shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data)); int32_t result = art_float_to_integral<int32_t, double>(val); shadow_frame.SetVReg(inst->VRegA_12x(inst_data), result); inst = inst->Next_1xx(); break; } case Instruction::DOUBLE_TO_LONG: { PREAMBLE(); double val = shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data)); int64_t result = art_float_to_integral<int64_t, double>(val); shadow_frame.SetVRegLong(inst->VRegA_12x(inst_data), result); inst = inst->Next_1xx(); break; } case Instruction::DOUBLE_TO_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_12x(inst_data), shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; case Instruction::INT_TO_BYTE: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_12x(inst_data), static_cast<int8_t>( shadow_frame.GetVReg(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; case Instruction::INT_TO_CHAR: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_12x(inst_data), static_cast<uint16_t>( shadow_frame.GetVReg(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; case Instruction::INT_TO_SHORT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_12x(inst_data), static_cast<int16_t>( shadow_frame.GetVReg(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; case Instruction::ADD_INT: { PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), SafeAdd(shadow_frame.GetVReg(inst->VRegB_23x()), shadow_frame.GetVReg(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; } case Instruction::SUB_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), SafeSub(shadow_frame.GetVReg(inst->VRegB_23x()), shadow_frame.GetVReg(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; case Instruction::MUL_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), SafeMul(shadow_frame.GetVReg(inst->VRegB_23x()), shadow_frame.GetVReg(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; case Instruction::DIV_INT: { PREAMBLE(); bool success = DoIntDivide(shadow_frame, inst->VRegA_23x(inst_data), shadow_frame.GetVReg(inst->VRegB_23x()), shadow_frame.GetVReg(inst->VRegC_23x())); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::REM_INT: { PREAMBLE(); bool success = DoIntRemainder(shadow_frame, inst->VRegA_23x(inst_data), shadow_frame.GetVReg(inst->VRegB_23x()), shadow_frame.GetVReg(inst->VRegC_23x())); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::SHL_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), shadow_frame.GetVReg(inst->VRegB_23x()) << (shadow_frame.GetVReg(inst->VRegC_23x()) & 0x1f)); inst = inst->Next_2xx(); break; case Instruction::SHR_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), shadow_frame.GetVReg(inst->VRegB_23x()) >> (shadow_frame.GetVReg(inst->VRegC_23x()) & 0x1f)); inst = inst->Next_2xx(); break; case Instruction::USHR_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), static_cast<uint32_t>(shadow_frame.GetVReg(inst->VRegB_23x())) >> (shadow_frame.GetVReg(inst->VRegC_23x()) & 0x1f)); inst = inst->Next_2xx(); break; case Instruction::AND_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), shadow_frame.GetVReg(inst->VRegB_23x()) & shadow_frame.GetVReg(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::OR_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), shadow_frame.GetVReg(inst->VRegB_23x()) | shadow_frame.GetVReg(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::XOR_INT: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_23x(inst_data), shadow_frame.GetVReg(inst->VRegB_23x()) ^ shadow_frame.GetVReg(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::ADD_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), SafeAdd(shadow_frame.GetVRegLong(inst->VRegB_23x()), shadow_frame.GetVRegLong(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; case Instruction::SUB_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), SafeSub(shadow_frame.GetVRegLong(inst->VRegB_23x()), shadow_frame.GetVRegLong(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; case Instruction::MUL_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), SafeMul(shadow_frame.GetVRegLong(inst->VRegB_23x()), shadow_frame.GetVRegLong(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; case Instruction::DIV_LONG: PREAMBLE(); DoLongDivide(shadow_frame, inst->VRegA_23x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_23x()), shadow_frame.GetVRegLong(inst->VRegC_23x())); POSSIBLY_HANDLE_PENDING_EXCEPTION(self->IsExceptionPending(), Next_2xx); break; case Instruction::REM_LONG: PREAMBLE(); DoLongRemainder(shadow_frame, inst->VRegA_23x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_23x()), shadow_frame.GetVRegLong(inst->VRegC_23x())); POSSIBLY_HANDLE_PENDING_EXCEPTION(self->IsExceptionPending(), Next_2xx); break; case Instruction::AND_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_23x()) & shadow_frame.GetVRegLong(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::OR_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_23x()) | shadow_frame.GetVRegLong(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::XOR_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_23x()) ^ shadow_frame.GetVRegLong(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::SHL_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_23x()) << (shadow_frame.GetVReg(inst->VRegC_23x()) & 0x3f)); inst = inst->Next_2xx(); break; case Instruction::SHR_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), shadow_frame.GetVRegLong(inst->VRegB_23x()) >> (shadow_frame.GetVReg(inst->VRegC_23x()) & 0x3f)); inst = inst->Next_2xx(); break; case Instruction::USHR_LONG: PREAMBLE(); shadow_frame.SetVRegLong(inst->VRegA_23x(inst_data), static_cast<uint64_t>(shadow_frame.GetVRegLong(inst->VRegB_23x())) >> (shadow_frame.GetVReg(inst->VRegC_23x()) & 0x3f)); inst = inst->Next_2xx(); break; case Instruction::ADD_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_23x(inst_data), shadow_frame.GetVRegFloat(inst->VRegB_23x()) + shadow_frame.GetVRegFloat(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::SUB_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_23x(inst_data), shadow_frame.GetVRegFloat(inst->VRegB_23x()) - shadow_frame.GetVRegFloat(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::MUL_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_23x(inst_data), shadow_frame.GetVRegFloat(inst->VRegB_23x()) * shadow_frame.GetVRegFloat(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::DIV_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_23x(inst_data), shadow_frame.GetVRegFloat(inst->VRegB_23x()) / shadow_frame.GetVRegFloat(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::REM_FLOAT: PREAMBLE(); shadow_frame.SetVRegFloat(inst->VRegA_23x(inst_data), fmodf(shadow_frame.GetVRegFloat(inst->VRegB_23x()), shadow_frame.GetVRegFloat(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; case Instruction::ADD_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_23x(inst_data), shadow_frame.GetVRegDouble(inst->VRegB_23x()) + shadow_frame.GetVRegDouble(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::SUB_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_23x(inst_data), shadow_frame.GetVRegDouble(inst->VRegB_23x()) - shadow_frame.GetVRegDouble(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::MUL_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_23x(inst_data), shadow_frame.GetVRegDouble(inst->VRegB_23x()) * shadow_frame.GetVRegDouble(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::DIV_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_23x(inst_data), shadow_frame.GetVRegDouble(inst->VRegB_23x()) / shadow_frame.GetVRegDouble(inst->VRegC_23x())); inst = inst->Next_2xx(); break; case Instruction::REM_DOUBLE: PREAMBLE(); shadow_frame.SetVRegDouble(inst->VRegA_23x(inst_data), fmod(shadow_frame.GetVRegDouble(inst->VRegB_23x()), shadow_frame.GetVRegDouble(inst->VRegC_23x()))); inst = inst->Next_2xx(); break; case Instruction::ADD_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, SafeAdd(shadow_frame.GetVReg(vregA), shadow_frame.GetVReg(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::SUB_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, SafeSub(shadow_frame.GetVReg(vregA), shadow_frame.GetVReg(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::MUL_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, SafeMul(shadow_frame.GetVReg(vregA), shadow_frame.GetVReg(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::DIV_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); bool success = DoIntDivide(shadow_frame, vregA, shadow_frame.GetVReg(vregA), shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_1xx); break; } case Instruction::REM_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); bool success = DoIntRemainder(shadow_frame, vregA, shadow_frame.GetVReg(vregA), shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_1xx); break; } case Instruction::SHL_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, shadow_frame.GetVReg(vregA) << (shadow_frame.GetVReg(inst->VRegB_12x(inst_data)) & 0x1f)); inst = inst->Next_1xx(); break; } case Instruction::SHR_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, shadow_frame.GetVReg(vregA) >> (shadow_frame.GetVReg(inst->VRegB_12x(inst_data)) & 0x1f)); inst = inst->Next_1xx(); break; } case Instruction::USHR_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, static_cast<uint32_t>(shadow_frame.GetVReg(vregA)) >> (shadow_frame.GetVReg(inst->VRegB_12x(inst_data)) & 0x1f)); inst = inst->Next_1xx(); break; } case Instruction::AND_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, shadow_frame.GetVReg(vregA) & shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::OR_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, shadow_frame.GetVReg(vregA) | shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::XOR_INT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVReg(vregA, shadow_frame.GetVReg(vregA) ^ shadow_frame.GetVReg(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::ADD_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, SafeAdd(shadow_frame.GetVRegLong(vregA), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::SUB_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, SafeSub(shadow_frame.GetVRegLong(vregA), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::MUL_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, SafeMul(shadow_frame.GetVRegLong(vregA), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::DIV_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); DoLongDivide(shadow_frame, vregA, shadow_frame.GetVRegLong(vregA), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); POSSIBLY_HANDLE_PENDING_EXCEPTION(self->IsExceptionPending(), Next_1xx); break; } case Instruction::REM_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); DoLongRemainder(shadow_frame, vregA, shadow_frame.GetVRegLong(vregA), shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); POSSIBLY_HANDLE_PENDING_EXCEPTION(self->IsExceptionPending(), Next_1xx); break; } case Instruction::AND_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, shadow_frame.GetVRegLong(vregA) & shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::OR_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, shadow_frame.GetVRegLong(vregA) | shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::XOR_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, shadow_frame.GetVRegLong(vregA) ^ shadow_frame.GetVRegLong(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::SHL_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, shadow_frame.GetVRegLong(vregA) << (shadow_frame.GetVReg(inst->VRegB_12x(inst_data)) & 0x3f)); inst = inst->Next_1xx(); break; } case Instruction::SHR_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, shadow_frame.GetVRegLong(vregA) >> (shadow_frame.GetVReg(inst->VRegB_12x(inst_data)) & 0x3f)); inst = inst->Next_1xx(); break; } case Instruction::USHR_LONG_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegLong(vregA, static_cast<uint64_t>(shadow_frame.GetVRegLong(vregA)) >> (shadow_frame.GetVReg(inst->VRegB_12x(inst_data)) & 0x3f)); inst = inst->Next_1xx(); break; } case Instruction::ADD_FLOAT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegFloat(vregA, shadow_frame.GetVRegFloat(vregA) + shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::SUB_FLOAT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegFloat(vregA, shadow_frame.GetVRegFloat(vregA) - shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::MUL_FLOAT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegFloat(vregA, shadow_frame.GetVRegFloat(vregA) * shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::DIV_FLOAT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegFloat(vregA, shadow_frame.GetVRegFloat(vregA) / shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::REM_FLOAT_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegFloat(vregA, fmodf(shadow_frame.GetVRegFloat(vregA), shadow_frame.GetVRegFloat(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::ADD_DOUBLE_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegDouble(vregA, shadow_frame.GetVRegDouble(vregA) + shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::SUB_DOUBLE_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegDouble(vregA, shadow_frame.GetVRegDouble(vregA) - shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::MUL_DOUBLE_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegDouble(vregA, shadow_frame.GetVRegDouble(vregA) * shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::DIV_DOUBLE_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegDouble(vregA, shadow_frame.GetVRegDouble(vregA) / shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data))); inst = inst->Next_1xx(); break; } case Instruction::REM_DOUBLE_2ADDR: { PREAMBLE(); uint4_t vregA = inst->VRegA_12x(inst_data); shadow_frame.SetVRegDouble(vregA, fmod(shadow_frame.GetVRegDouble(vregA), shadow_frame.GetVRegDouble(inst->VRegB_12x(inst_data)))); inst = inst->Next_1xx(); break; } case Instruction::ADD_INT_LIT16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22s(inst_data), SafeAdd(shadow_frame.GetVReg(inst->VRegB_22s(inst_data)), inst->VRegC_22s())); inst = inst->Next_2xx(); break; case Instruction::RSUB_INT_LIT16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22s(inst_data), SafeSub(inst->VRegC_22s(), shadow_frame.GetVReg(inst->VRegB_22s(inst_data)))); inst = inst->Next_2xx(); break; case Instruction::MUL_INT_LIT16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22s(inst_data), SafeMul(shadow_frame.GetVReg(inst->VRegB_22s(inst_data)), inst->VRegC_22s())); inst = inst->Next_2xx(); break; case Instruction::DIV_INT_LIT16: { PREAMBLE(); bool success = DoIntDivide(shadow_frame, inst->VRegA_22s(inst_data), shadow_frame.GetVReg(inst->VRegB_22s(inst_data)), inst->VRegC_22s()); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::REM_INT_LIT16: { PREAMBLE(); bool success = DoIntRemainder(shadow_frame, inst->VRegA_22s(inst_data), shadow_frame.GetVReg(inst->VRegB_22s(inst_data)), inst->VRegC_22s()); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::AND_INT_LIT16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22s(inst_data), shadow_frame.GetVReg(inst->VRegB_22s(inst_data)) & inst->VRegC_22s()); inst = inst->Next_2xx(); break; case Instruction::OR_INT_LIT16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22s(inst_data), shadow_frame.GetVReg(inst->VRegB_22s(inst_data)) | inst->VRegC_22s()); inst = inst->Next_2xx(); break; case Instruction::XOR_INT_LIT16: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22s(inst_data), shadow_frame.GetVReg(inst->VRegB_22s(inst_data)) ^ inst->VRegC_22s()); inst = inst->Next_2xx(); break; case Instruction::ADD_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), SafeAdd(shadow_frame.GetVReg(inst->VRegB_22b()), inst->VRegC_22b())); inst = inst->Next_2xx(); break; case Instruction::RSUB_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), SafeSub(inst->VRegC_22b(), shadow_frame.GetVReg(inst->VRegB_22b()))); inst = inst->Next_2xx(); break; case Instruction::MUL_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), SafeMul(shadow_frame.GetVReg(inst->VRegB_22b()), inst->VRegC_22b())); inst = inst->Next_2xx(); break; case Instruction::DIV_INT_LIT8: { PREAMBLE(); bool success = DoIntDivide(shadow_frame, inst->VRegA_22b(inst_data), shadow_frame.GetVReg(inst->VRegB_22b()), inst->VRegC_22b()); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::REM_INT_LIT8: { PREAMBLE(); bool success = DoIntRemainder(shadow_frame, inst->VRegA_22b(inst_data), shadow_frame.GetVReg(inst->VRegB_22b()), inst->VRegC_22b()); POSSIBLY_HANDLE_PENDING_EXCEPTION(!success, Next_2xx); break; } case Instruction::AND_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), shadow_frame.GetVReg(inst->VRegB_22b()) & inst->VRegC_22b()); inst = inst->Next_2xx(); break; case Instruction::OR_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), shadow_frame.GetVReg(inst->VRegB_22b()) | inst->VRegC_22b()); inst = inst->Next_2xx(); break; case Instruction::XOR_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), shadow_frame.GetVReg(inst->VRegB_22b()) ^ inst->VRegC_22b()); inst = inst->Next_2xx(); break; case Instruction::SHL_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), shadow_frame.GetVReg(inst->VRegB_22b()) << (inst->VRegC_22b() & 0x1f)); inst = inst->Next_2xx(); break; case Instruction::SHR_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), shadow_frame.GetVReg(inst->VRegB_22b()) >> (inst->VRegC_22b() & 0x1f)); inst = inst->Next_2xx(); break; case Instruction::USHR_INT_LIT8: PREAMBLE(); shadow_frame.SetVReg(inst->VRegA_22b(inst_data), static_cast<uint32_t>(shadow_frame.GetVReg(inst->VRegB_22b())) >> (inst->VRegC_22b() & 0x1f)); inst = inst->Next_2xx(); break; case Instruction::UNUSED_3E ... Instruction::UNUSED_43: case Instruction::UNUSED_79 ... Instruction::UNUSED_7A: case Instruction::UNUSED_F3 ... Instruction::UNUSED_F9: UnexpectedOpcode(inst, shadow_frame); } } while (!interpret_one_instruction); // Record where we stopped. shadow_frame.SetDexPC(inst->GetDexPc(insns)); ctx->result = result_register; return; } // NOLINT(readability/fn_size) // Explicit definitions of ExecuteSwitchImplCpp. template HOT_ATTR void ExecuteSwitchImplCpp<true, false>(SwitchImplContext* ctx); template HOT_ATTR void ExecuteSwitchImplCpp<false, false>(SwitchImplContext* ctx); template void ExecuteSwitchImplCpp<true, true>(SwitchImplContext* ctx); template void ExecuteSwitchImplCpp<false, true>(SwitchImplContext* ctx); } // namespace interpreter } // namespace art
42.359952
102
0.550047
[ "object" ]
2838dbc287096b7f5241f15bcbca4d6989aca036
4,560
hpp
C++
include/OpenSpaceToolkit/Physics/Data/Vector.hpp
robinpdm/open-space-toolkit-physics
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
[ "Apache-2.0" ]
7
2020-03-30T11:51:11.000Z
2022-02-02T15:20:44.000Z
include/OpenSpaceToolkit/Physics/Data/Vector.hpp
robinpdm/open-space-toolkit-physics
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
[ "Apache-2.0" ]
24
2018-06-25T08:06:39.000Z
2020-01-05T20:34:02.000Z
include/OpenSpaceToolkit/Physics/Data/Vector.hpp
robinpdm/open-space-toolkit-physics
b53e5d4287fa6568d700cb8942c9a56d57b8d7cf
[ "Apache-2.0" ]
3
2020-03-05T18:18:38.000Z
2020-07-02T05:06:53.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Open Space Toolkit ▸ Physics /// @file OpenSpaceToolkit/Physics/Data/Vector.hpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __OpenSpaceToolkit_Physics_Data_Vector__ #define __OpenSpaceToolkit_Physics_Data_Vector__ #include <OpenSpaceToolkit/Physics/Coordinate/Frame.hpp> #include <OpenSpaceToolkit/Physics/Time/Instant.hpp> #include <OpenSpaceToolkit/Physics/Unit.hpp> #include <OpenSpaceToolkit/Mathematics/Objects/Vector.hpp> #include <OpenSpaceToolkit/Core/Types/Shared.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace ostk { namespace physics { namespace data { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using ostk::core::types::Shared ; using ostk::core::types::Integer ; using ostk::core::types::String ; using ostk::math::obj::Vector3d ; using ostk::physics::Unit ; using ostk::physics::time::Instant ; using ostk::physics::coord::Frame ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Vector quantity class Vector { public: Vector ( const Vector3d& aValue, const Unit& aUnit, const Shared<const Frame>& aFrameSPtr ) ; bool operator == ( const Vector& aVector ) const ; bool operator != ( const Vector& aVector ) const ; friend std::ostream& operator << ( std::ostream& anOutputStream, const Vector& aVector ) ; bool isDefined ( ) const ; Vector3d getValue ( ) const ; Unit getUnit ( ) const ; Shared<const Frame> getFrame ( ) const ; Vector inUnit ( const Unit& aUnit ) const ; Vector inFrame ( const Shared<const Frame>& aFrameSPtr, const Instant& anInstant ) const ; String toString ( const Integer& aPrecision = Integer::Undefined() ) const ; static Vector Undefined ( ) ; private: Vector3d value_ ; Unit unit_ ; Shared<const Frame> frameSPtr_ ; } ; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
46.530612
194
0.267325
[ "vector" ]
283aee8bd8a0cfa48491e4672a7d675afe692c7c
5,362
hpp
C++
plugin/html-overlay/include/android/dom/AndroidWebViewDOMEngine.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
null
null
null
plugin/html-overlay/include/android/dom/AndroidWebViewDOMEngine.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
null
null
null
plugin/html-overlay/include/android/dom/AndroidWebViewDOMEngine.hpp
undeadinu/minko
9171805751fb3a50c6fcab0b78892cdd4253ee11
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2013 Aerys Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "minko/Common.hpp" #include "minko/dom/AbstractDOM.hpp" #include "minko/dom/AbstractDOMEngine.hpp" #include "AndroidWebViewDOM.hpp" #include <jni.h> namespace android { namespace dom { class AndroidWebViewDOMEngine : public minko::dom::AbstractDOMEngine, public std::enable_shared_from_this<AndroidWebViewDOMEngine> { public: typedef std::shared_ptr<AndroidWebViewDOMEngine> Ptr; private: AndroidWebViewDOMEngine(); public: ~AndroidWebViewDOMEngine() { } void initialize(minko::AbstractCanvas::Ptr, minko::component::SceneManager::Ptr); void enterFrame(float); minko::dom::AbstractDOM::Ptr load(std::string uri); static Ptr create(); void clear(); minko::Signal<minko::dom::AbstractDOM::Ptr, std::string>::Ptr onload(); minko::Signal<minko::dom::AbstractDOM::Ptr, std::string>::Ptr onmessage(); minko::dom::AbstractDOM::Ptr mainDOM(); void visible(bool); bool visible(); inline AndroidWebViewDOM::Ptr currentDOM() { return _currentDOM; } std::string eval(const std::string&); inline bool isReady() { return _isReady; } inline void updateNextFrame() { _updateNextFrame = true; } inline void pollRate(int rate) { _pollRate = rate; } private: void createNewDom(); void registerDomEvents(); void updateWebViewResolution(int width, int height); void updateEvents(); public: static int _domUid; static std::vector<std::string> messages; static std::vector<minko::dom::AbstractDOMEvent::Ptr> events; // WebView Signals static minko::Signal<>::Ptr onWebViewInitialized; static minko::Signal<>::Ptr onWebViewPageLoaded; static std::mutex eventMutex; static std::mutex messageMutex; static Ptr currentEngine; static int numTouches; static int firstIdentifier; private: // WebView Slots minko::Signal<>::Slot _onWebViewInitializedSlot; minko::Signal<>::Slot _onWebViewPageLoadedSlot; // Inputs Slots minko::Signal<minko::dom::AbstractDOMMouseEvent::Ptr>::Slot _onmousemoveSlot; minko::Signal<minko::dom::AbstractDOMMouseEvent::Ptr>::Slot _onmousedownSlot; minko::Signal<minko::dom::AbstractDOMMouseEvent::Ptr>::Slot _onmouseupSlot; minko::Signal<minko::dom::AbstractDOMTouchEvent::Ptr>::Slot _ontouchstartSlot; minko::Signal<minko::dom::AbstractDOMTouchEvent::Ptr>::Slot _ontouchendSlot; minko::Signal<minko::dom::AbstractDOMTouchEvent::Ptr>::Slot _ontouchmoveSlot; AndroidWebViewDOM::Ptr _currentDOM; minko::AbstractCanvas::Ptr _canvas; minko::component::SceneManager::Ptr _sceneManager; minko::Signal<minko::AbstractCanvas::Ptr, minko::uint, minko::uint>::Slot _canvasResizedSlot; minko::Signal<minko::component::SceneManager::Ptr, float, float>::Slot _enterFrameSlot; minko::Signal<minko::dom::AbstractDOM::Ptr, std::string>::Ptr _onload; minko::Signal<minko::dom::AbstractDOM::Ptr, std::string>::Ptr _onmessage; bool _visible; bool _waitingForLoad; std::string _uriToLoad; bool _isReady; bool _webViewInitialized; bool _webViewPageLoaded; float _lastUpdateTime; int _pollRate; bool _updateNextFrame; // JNI part // Java Objects jobject _initWebViewTask = nullptr; // Java Method IDs jmethodID _evalJSMethod = nullptr; jmethodID _loadUrlMethod = nullptr; jmethodID _changeResolutionMethod = nullptr; jmethodID _hideMethod = nullptr; }; } }
26.544554
97
0.620291
[ "vector" ]
283b9a27616b1b1d8146f96c6789650fbf8a14a4
2,740
hpp
C++
include/crab/domains/term/simplify.hpp
seahorn/crab
82e3d9c94a3b112d4db344e34ae9f789b51d0ec0
[ "Apache-2.0" ]
152
2016-02-28T06:04:02.000Z
2022-03-30T10:44:56.000Z
include/crab/domains/term/simplify.hpp
seahorn/crab
82e3d9c94a3b112d4db344e34ae9f789b51d0ec0
[ "Apache-2.0" ]
43
2017-07-03T06:25:19.000Z
2022-03-23T21:09:32.000Z
include/crab/domains/term/simplify.hpp
seahorn/crab
82e3d9c94a3b112d4db344e34ae9f789b51d0ec0
[ "Apache-2.0" ]
28
2015-11-22T15:51:52.000Z
2022-01-30T00:46:57.000Z
#pragma once #include <boost/optional.hpp> #include <crab/domains/term/term_expr.hpp> #include <crab/domains/term/term_operators.hpp> /* Simplifiers for table terms after giving meaning to functors. */ namespace crab { namespace domains { namespace term { // Common API to simplifiers template <class Num, class Ftor> class Simplifier { protected: using term_table_t = term_table<Num, Ftor>; using term_id_t = typename term_table_t::term_id_t; term_table_t &_ttbl; public: Simplifier(term_table_t &term_table) : _ttbl(term_table) {} virtual ~Simplifier() {} virtual void simplify() = 0; // This should not modify the term table // FIXME: cannot make const the method without changing // constness of other methods. virtual boost::optional<term_id_t> simplify_term(term_id_t t) = 0; }; // Trivial simplifier by giving standard mathematical meaning // to arithmetic operators assuming that conmutativity, // associativity etc properties hold as expected. template <class Num> class NumSimplifier : Simplifier<Num, term_operator_t> { using simplifier_t = Simplifier<Num, term_operator_t>; using term_table_t = term_table<Num, term_operator_t>; using term_id_t = typename term_table_t::term_id_t; using term_t = typename term_table_t::term_t; // Simplify term f(left,right) boost::optional<term_id_t> simplify_term(term_operator_t f, term_id_t left, term_id_t right) { // Only consider these two rules: // '/'('*'(x,y),x) = y // '/'('*'(x,y),y) = x switch (f) { case TERM_OP_SDIV: case TERM_OP_UDIV: { term_t *tleft = this->_ttbl.get_term_ptr(left); term_t *tright = this->_ttbl.get_term_ptr(right); if ((tleft->kind() == TERM_APP) && term_ftor(tleft) == TERM_OP_MUL) { const std::vector<term_id_t> &args(term_args(tleft)); assert(args.size() == 2); term_t *tl = this->_ttbl.get_term_ptr(args[0]); term_t *tr = this->_ttbl.get_term_ptr(args[1]); if (tl == tright) return args[1]; if (tr == tright) return args[0]; } } default: return boost::optional<term_id_t>(); } } public: NumSimplifier(term_table_t &term_table) : simplifier_t(term_table) {} void simplify() {} boost::optional<term_id_t> simplify_term(term_id_t t) { if (term_t *tt = this->_ttbl.get_term_ptr(t)) { if (tt->kind() == TERM_APP) { const std::vector<term_id_t> &args(term_args(tt)); assert(args.size() == 2); return simplify_term(term_ftor(tt), args[0], args[1]); } } return boost::optional<term_id_t>(); } }; } // end namespace term } // end namespace domains } // end namespace crab
28.842105
77
0.659489
[ "vector" ]
283e1a17c0c86dfd38f73c691aa563fdc08b6c99
2,820
cpp
C++
windows.ui.xaml.input/code/Controls_WebView/cpp/Scenario7.xaml.cpp
gbaychev/winrt-api
25346cd51bc9d24c8c4371dc59768e039eaf02f1
[ "CC-BY-4.0", "MIT" ]
199
2017-02-09T23:13:51.000Z
2022-03-28T15:56:12.000Z
windows.ui.xaml.input/code/Controls_WebView/cpp/Scenario7.xaml.cpp
gbaychev/winrt-api
25346cd51bc9d24c8c4371dc59768e039eaf02f1
[ "CC-BY-4.0", "MIT" ]
2,093
2017-02-09T21:52:45.000Z
2022-03-25T22:23:18.000Z
windows.ui.xaml.input/code/Controls_WebView/cpp/Scenario7.xaml.cpp
gbaychev/winrt-api
25346cd51bc9d24c8c4371dc59768e039eaf02f1
[ "CC-BY-4.0", "MIT" ]
620
2017-02-08T19:19:44.000Z
2022-03-29T11:38:25.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario7.xaml.cpp // Implementation of the Scenario7 class // #include "pch.h" #include "Scenario7.xaml.h" using namespace SDKSample::WebViewControl; using namespace Windows::Foundation; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::ApplicationModel::DataTransfer; Scenario7::Scenario7() { InitializeComponent(); DataTransferManager^ dataTransferManager = nullptr; } // Invoked when this page is about to be displayed in a Frame. void Scenario7::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() rootPage = MainPage::Current; WebView7->LoadCompleted += ref new LoadCompletedEventHandler(this, &Scenario7::WebView7_LoadCompleted); WebView7->Navigate(ref new Uri("http://www.wsj.com")); } // Load completed handler for WebView7 void SDKSample::WebViewControl::Scenario7::WebView7_LoadCompleted(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) { WebView7->Visibility = Windows::UI::Xaml::Visibility::Visible; BlockingRect->Visibility = Windows::UI::Xaml::Visibility::Collapsed; ProgressRing1->IsActive = false; } // Click handler for 'Share' button //<snippetDataTransferPackage> void SDKSample::WebViewControl::Scenario7::Share_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) { dataTransferManager = DataTransferManager::GetForCurrentView(); dataRequestedToken = dataTransferManager->DataRequested += ref new TypedEventHandler<DataTransferManager^, DataRequestedEventArgs^>(this, &Scenario7::dataTransferManager_DataRequested); DataTransferManager::ShowShareUI(); } // Data requested handler void SDKSample::WebViewControl::Scenario7::dataTransferManager_DataRequested(DataTransferManager^ sender, DataRequestedEventArgs^ args) { DataRequest^ request = args->Request; DataPackage^ p = WebView7->DataTransferPackage; if (p->GetView()->Contains(StandardDataFormats::Text)) { p->Properties->Title = "WebView Sharing Excerpt"; p->Properties->Description = "This is a snippet from the content hosted in the WebView control"; request->Data = p; } else { request->FailWithDisplayText("Nothing to share"); } dataTransferManager->DataRequested -= dataRequestedToken; } //</snippetDataTransferPackage>
34.390244
186
0.732624
[ "object" ]
2849d4373f524b74987beb3f4d609540bc050f5c
12,360
cpp
C++
ARK2D/src/ARK2D/Tools/Packer.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
6
2015-08-25T19:16:20.000Z
2021-04-19T16:47:58.000Z
ARK2D/src/ARK2D/Tools/Packer.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
1
2015-09-17T14:03:12.000Z
2015-09-17T14:03:12.000Z
ARK2D/src/ARK2D/Tools/Packer.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
1
2018-10-02T19:59:47.000Z
2018-10-02T19:59:47.000Z
/* * Packer.cpp * * Created on: Sep 4, 2011 * Author: ashleygwinnell */ #include "Packer.h" #include <stdio.h> #include <iostream> #include <fstream> #include "../vendor/ogg130/ogg.h" #include "../vendor/vorbis132/vorbisfile.h" #include "../vendor/zlib123/zlib.h" #ifndef ARK2D_WINDOWS_PHONE_8 string getExtension(string s); string getExtension(string s) { unsigned int pos = s.find_last_of('.') + 1; return s.substr(pos); } bool is_big_endian(); bool is_big_endian() { static unsigned long x(1); static bool result(reinterpret_cast<unsigned char*>(&x)[0] == 0); return result; } const string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; string encodeBase64(const unsigned char* bytes_to_encode, unsigned int in_len); string encodeBase64(const unsigned char* bytes_to_encode, unsigned int in_len) { string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } char* file_get_contents(const char* fileName); char* file_get_contents(const char* fileName) { if (fileName != NULL) { std::cout << "Opening file: " << fileName << std::endl; std::fstream f(fileName, std::ios::in); if (!f.is_open()) { //std::cout << "File does not exist." << std::endl; string str = "Could not open file ["; str += fileName; str += "] as it does not exist."; //ErrorDialog::createAndShow(str); std::cout << str << std::endl; return NULL; } else { f.close(); char* text = NULL; FILE* file = NULL; #if defined(ARK2D_WINDOWS_PHONE_8) fopen_s(&file, fileName, "rt"); #else file = fopen(fileName, "rt"); #endif if (file == NULL) { string str = "Could not open file ["; str += fileName; str += "] as it does not exist."; std::cout << str << std::endl; return NULL; } fseek(file, 0, SEEK_END); int count = ftell(file); rewind(file); if (count > 0) { text = (char*)malloc(sizeof(char) * (count + 1)); count = fread(text, sizeof(char), count, file); text[count] = '\0'; } fclose(file); return text; } } return NULL; } void compress_memory(void *in_data, size_t in_data_size, std::vector<uint8_t> &out_data); void compress_memory(void *in_data, size_t in_data_size, std::vector<uint8_t> &out_data) { std::vector<uint8_t> buffer; const size_t BUFSIZE = 128 * 1024; uint8_t temp_buffer[BUFSIZE]; z_stream strm; strm.zalloc = 0; strm.zfree = 0; strm.next_in = reinterpret_cast<uint8_t *>(in_data); strm.avail_in = in_data_size; strm.next_out = temp_buffer; strm.avail_out = BUFSIZE; deflateInit(&strm, Z_BEST_COMPRESSION); while (strm.avail_in != 0) { //int res = deflate(&strm, Z_NO_FLUSH); //assert(res == Z_OK); if (strm.avail_out == 0) { buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE); strm.next_out = temp_buffer; strm.avail_out = BUFSIZE; } } int deflate_res = Z_OK; while (deflate_res == Z_OK) { if (strm.avail_out == 0) { buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE); strm.next_out = temp_buffer; strm.avail_out = BUFSIZE; } deflate_res = deflate(&strm, Z_FINISH); } //assert(deflate_res == Z_STREAM_END); buffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE - strm.avail_out); deflateEnd(&strm); out_data.swap(buffer); } Packer::Packer(): files() { } PackerFile* Packer::get(string file) { for (unsigned int i = 0; i < files.size(); i++) { PackerFile* pf = files.at(i); //std::cout << file.c_str() << " : " << pf->nameString << std::endl; if (strcmp(pf->nameString, file.c_str()) == 0) { return pf; } } std::cout << "File `" << file << "` not found in packer." << std::endl; return NULL; } void Packer::read(string inFile) { FILE* f = NULL; #if defined(ARK2D_WINDOWS_PHONE_8) fopen_s(&f, inFile.c_str(), "rb"); #else f = fopen(inFile.c_str(), "rb"); #endif int freadresult = 0; uint32_t numFiles; freadresult = fread(&numFiles, 4, 1, f); std::cout << "num files: " << numFiles << std::endl; for (unsigned int i = 0; i < numFiles; i++) { PackerFile* packerFile = new PackerFile(); freadresult = fread(&packerFile->type, 4, 1, f); std::cout << "type: " << packerFile->type << std::endl; freadresult = fread(&packerFile->nameLength, 4, 1, f); std::cout << "nameLength: " << packerFile->nameLength << std::endl; packerFile->nameString = (char*) malloc(packerFile->nameLength); freadresult = fread(packerFile->nameString, packerFile->nameLength, 1, f); //packerFile->nameString = "ASDASDASDAS"; //std::cout << "derp" << std::endl; //std::cout << packerFile->nameString[0] << std::endl; packerFile->nameString[packerFile->nameLength-1] = '\0'; //std::cout << "derp" << std::endl; std::cout << "nameString: " << packerFile->nameString << std::endl; freadresult = fread(&packerFile->size, 8, 1, f); std::cout << "size: " << packerFile->size << std::endl; if (packerFile->type == PackerFile::TYPE_AUDIO) { freadresult = fread(&packerFile->format, 4, 1, f); std::cout << "format: " << packerFile->format << std::endl; freadresult = fread(&packerFile->frequency, 4, 1, f); std::cout << "frequency: " << packerFile->frequency << std::endl; } packerFile->data = (char*) malloc(packerFile->size); freadresult = fread(packerFile->data, packerFile->size, 1, f); files.push_back(packerFile); } } void Packer::write(string outFile, vector<string> inFiles) { std::cout << "Reading input files..." << std::endl; for(unsigned int i = 0; i < inFiles.size(); i++) { string file = inFiles.at(i); std::ifstream thefile (file.c_str()); if (!thefile.is_open()) { std::cout << "Could not open file: " << file << std::endl; } else { thefile.close(); string ext = getExtension(file); if (ext == "ogg") { // Some vars! const unsigned int BUFFER_SIZE = 32768; // 32kb buffer int format; int frequency; int bitStream; long bytes; int endian = 0; // 0 for Little-Endian, 1 for Big-Endian if (is_big_endian()) { endian = 1; } char array[BUFFER_SIZE]; // Local fixed size array vorbis_info* oggInfo; OggVorbis_File oggFile; std::vector<char> bufferData; // Open for binary reading FILE* f = NULL; #if defined(ARK2D_WINDOWS_PHONE_8) fopen_s(&f, file.c_str(), "rb"); #else f = fopen(file.c_str(), "rb"); #endif if (f == NULL) { std::cout << "Could not open file:" << file << std::endl; return; } else { std::cout << "Opened file:" << file << std::endl; } // open using the SDK, no need to call fclose() now. ov_open(f, &oggFile, NULL, 0); // Get some info about the OGG and store it in oggInfo. oggInfo = ov_info(&oggFile, -1); // Check the number of channels... always use 16-bit samples if (oggInfo->channels == 1) { format = PACKER_AUDIO_MONO16; } else { format = PACKER_AUDIO_STEREO16; } frequency = oggInfo->rate; do { // Read up to a buffer's worth of decoded sound data bytes = ov_read(&oggFile, &array[0], BUFFER_SIZE, endian, 2, 1, &bitStream); // Append to end of buffer bufferData.insert(bufferData.end(), array, array + bytes); } while (bytes > 0); // Make mean AudioFile PackerFile* af = new PackerFile(); af->nameLength = strlen(file.c_str()) + 1; af->nameString = const_cast<char*>( file.c_str() ); std::cout << af->nameString << std::endl; af->format = format; af->frequency = frequency; af->size = bufferData.size(); af->data = malloc(af->size); memcpy(af->data, (void*) &bufferData[0], af->size); ov_clear(&oggFile); files.push_back(af); } } } std::cout << "Writing packed file..." << std::endl; FILE* out = NULL; #if defined(ARK2D_WINDOWS_PHONE_8) fopen_s(&out, outFile.c_str(), "w"); #else out = fopen(outFile.c_str(), "w"); #endif if (out == NULL) { std::cout << "Could not write packed file. " << outFile.c_str() << std::endl; return; } // find total size. uint64_t totalSize = 0; for(unsigned int i = 0; i < files.size(); i++) { int thisSize = 0; thisSize += files.at(i)->size; thisSize += 12; // 4 for type and 8 for length. thisSize += 4; // 4 for name length; thisSize += files.at(i)->nameLength; if (files.at(i)->type == PackerFile::TYPE_AUDIO) { thisSize += 8; // 4 for format and 4 for frequency. } totalSize += thisSize; std::cout << "file " << i << " was " << files.at(i)->size << " and " << thisSize << " size." << std::endl; } totalSize += 1; // for \0 char* space = (char*) malloc(totalSize); char* current = space; // write num of files uint32_t numFiles = files.size(); memcpy(current, &numFiles, 4); current += 4; // for each file for(unsigned int i = 0; i < files.size(); i++) { PackerFile* f = files.at(i); //write type (4 bytes) memcpy(current, &f->type, 4); current += 4; // write name length (4 bytes) memcpy(current, &f->nameLength, 4); current += 4; // write name string memcpy(current, f->nameString, f->nameLength); current += f->nameLength; // write length (8 bytes) memcpy(current, &f->size, 8); current += 8; if (f->type == PackerFile::TYPE_AUDIO) { //write format //fwrite(&f->format, 4, 1, out); memcpy(current, &f->format, 4); current += 4; // write freq //fwrite(&f->frequency, 4, 1, out); memcpy(current, &f->frequency, 4); current += 4; } //fwrite(&f->data, f->size, 1, out); memcpy(current, f->data, f->size); current += f->size; } char end = '\0'; memcpy(current, &end, 1); current += 1; //std::cout << ((char*) space) << std::endl; bool base64enabled = false; bool zlibEnabled = false; const char* newfcstr = NULL; int newflength = 0; if (base64enabled) { std::cout << "Base64 Encoding..." << std::endl; const unsigned char* blahh = (const unsigned char*) const_cast<const char*>(space); string newf = encodeBase64(blahh, totalSize); newfcstr = newf.c_str(); newflength = newf.length(); } else { newfcstr = const_cast<const char*>(space); newflength = totalSize; } if (zlibEnabled) { std::cout << "ZLib Compressing..." << std::endl; std::vector<unsigned char> woop; compress_memory((void*) newfcstr, newflength, woop); std::cout << "Writing packed file..." << std::endl; fwrite(&woop[0], woop.size(), 1, out); } else { std::cout << "Writing packed file..." << std::endl; fwrite((void*) newfcstr, newflength, 1, out); } fclose(out); //char* f = file_get_contents(outFile.c_str()); //std::cout << f << std::endl; /*out = fopen(outFile.c_str(), "r"); fseek(out, 0, SEEK_SET); int count = ftell(out); rewind(out); char* text = (char*) malloc(count+1); count = fread(text, sizeof(char), count, out); text[count] = '\0'; std::cout << count << std::endl;*/ } Packer::~Packer() { } PackerFile::PackerFile(): nameString(NULL), data(NULL) { } PackerFile::~PackerFile() { } #endif
24.769539
109
0.593447
[ "vector" ]
284bf6ced4bcdfe76e90dbbee29fc3b7f440017c
5,142
cpp
C++
test/src/line_test.cpp
kduske/vecmath
e6838c24b704a622e0fd85bc9d7ad2ccfb8c4522
[ "MIT" ]
3
2019-10-19T21:16:33.000Z
2020-03-04T06:32:52.000Z
test/src/line_test.cpp
kduske/vecmath
e6838c24b704a622e0fd85bc9d7ad2ccfb8c4522
[ "MIT" ]
21
2019-09-29T20:31:07.000Z
2020-08-15T18:23:42.000Z
test/src/line_test.cpp
TrenchBroom/vecmath
d4dd858a0b1d2d16aee4d572804e0cca26cee664
[ "MIT" ]
3
2020-12-06T05:32:05.000Z
2022-02-23T17:50:19.000Z
/* Copyright 2010-2019 Kristian Duske Copyright 2015-2019 Eric Wasylishen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "test_utils.h" #include <vecmath/approx.h> #include <vecmath/forward.h> #include <vecmath/line.h> #include <vecmath/line_io.h> #include <vecmath/mat.h> #include <vecmath/mat_ext.h> #include <vecmath/scalar.h> #include <sstream> #include <catch2/catch.hpp> namespace vm { TEST_CASE("line.constructor_default") { constexpr auto p = line3f(); CER_CHECK(p.point == vec3f::zero()); CER_CHECK(p.direction == vec3f::zero()); } TEST_CASE("line.constructor_convert") { constexpr auto l = line3d(vec3d::one(), vec3d::pos_z()); constexpr auto k = line3f(l); CER_CHECK(k.point == approx(vec3f::one())); CER_CHECK(k.direction == approx(vec3f::pos_z())); } TEST_CASE("line.constructor_with_point_and_direction") { constexpr auto p = vec3f(10, 20, 30); constexpr auto n = normalize_c(vec3f(1.0f, 2.0f, 3.0f)); constexpr auto l = line3f(p, n); CER_CHECK(l.point == approx(p)); CER_CHECK(l.direction == approx(n)); } TEST_CASE("line.get_origin") { constexpr auto l = line3d(vec3d::one(), vec3d::pos_z()); CER_CHECK(l.get_origin() == approx(l.point)); } TEST_CASE("line.get_direction") { constexpr auto l = line3d(vec3d::one(), vec3d::pos_z()); CER_CHECK(l.get_direction() == approx(l.direction)); } TEST_CASE("line.transform") { const auto l = line3d(vec3d::one(), vec3d::pos_z()); const auto rm = rotation_matrix(to_radians(15.0), to_radians(20.0), to_radians(-12.0)); const auto tm = translation_matrix(vec3d::one()); const auto lt = l.transform(rm * tm); CHECK(is_unit(l.direction, vm::Cd::almost_zero())); CHECK(lt.point == approx(rm * tm * l.point)); CHECK(lt.direction == approx(rm * l.direction)); } TEST_CASE("line.transform_c") { constexpr auto l = line3d(vec3d::one(), vec3d::pos_z()); constexpr auto sm = scaling_matrix(vec3d(2.0, 0.5, -2.0)); constexpr auto tm = translation_matrix(vec3d::one()); constexpr auto lt = l.transform_c(sm * tm); CHECK(is_unit(l.direction, vm::Cd::almost_zero())); CHECK(lt.point == approx(sm * tm * l.point)); CHECK(lt.direction == approx(normalize_c(sm * l.direction))); } TEST_CASE("line.make_canonical") { constexpr auto l1 = line3d(vec3d(-10, 0, 10), vec3d::pos_x()); constexpr auto l2 = line3d(vec3d(+10, 0, 10), vec3d::pos_x()); CER_CHECK(l2.make_canonical() == approx(l1.make_canonical())); } TEST_CASE("line.distance_to_projected_point") { constexpr auto l = line3f(vec3f(10, 0, 0), vec3f::pos_z()); CER_CHECK(distance_to_projected_point(l, vec3f(10, 0, 0)) == approx(0.0f)); CER_CHECK(distance_to_projected_point(l, vec3f(10, 0, 10)) == approx(10.0f)); CER_CHECK(distance_to_projected_point(l, vec3f(10, 10, 10)) == approx(10.0f)); } TEST_CASE("line.project_point") { constexpr auto l = line3f(vec3f(10, 0, 0), vec3f::pos_z()); CER_CHECK(project_point(l, vec3f(100, 100, 5)) == approx(vec3f(10, 0, 5))); } TEST_CASE("line.is_equal"){ CER_CHECK(is_equal(line3d(), line3d(), 0.0)) CER_CHECK( is_equal(line3d(vec3d::zero(), vec3d::pos_z()), line3d(vec3d::zero(), vec3d::pos_z()), 0.0)) CER_CHECK_FALSE( is_equal(line3d(vec3d(0, 0, 0), vec3d(0, 0, 1)), line3d(vec3d(1, 0, 0), vec3d(0, 0, 1)), 0.0)) CER_CHECK(is_equal( line3d(vec3d(0, 0, 0), vec3d(0, 0, 1)), line3d(vec3d(1, 0, 0), vec3d(0, 0, 1)), 2.0))} TEST_CASE("line.operator_equal"){ CER_CHECK(line3d() == line3d()) CER_CHECK(line3d(vec3d::zero(), vec3d::pos_z()) == line3d(vec3d::zero(), vec3d::pos_z())) CER_CHECK_FALSE( line3d(vec3d(0, 0, 0), vec3d(0, 0, 1)) == line3d(vec3d(1, 0, 0), vec3d(0, 0, 1)))} TEST_CASE("line.operator_not_equal"){ CER_CHECK_FALSE(line3d() != line3d()) CER_CHECK_FALSE(line3d(vec3d::zero(), vec3d::pos_z()) != line3d(vec3d::zero(), vec3d::pos_z())) CER_CHECK(line3d(vec3d(0, 0, 0), vec3d(0, 0, 1)) != line3d(vec3d(1, 0, 0), vec3d(0, 0, 1)))} TEST_CASE("line.stream_insertion") { std::stringstream str; str << line3d(line3d(vec3d::zero(), vec3d::pos_z())); CHECK(str.str() == "{ point: (0 0 0), direction: (0 0 1) }"); } } // namespace vm
38.954545
100
0.688059
[ "transform" ]
284cf2271efdf04b186180190669c3d91b19507d
2,982
cpp
C++
methods/slmm/slmm_c_compat.cpp
ambrad/COMPOSE
0bda7aeaf2b8494c7de8cd179c22e340b08eda6e
[ "BSD-3-Clause" ]
3
2018-12-30T20:01:25.000Z
2020-07-22T23:44:14.000Z
methods/slmm/slmm_c_compat.cpp
E3SM-Project/COMPOSE
0bda7aeaf2b8494c7de8cd179c22e340b08eda6e
[ "BSD-3-Clause" ]
8
2019-02-06T19:08:31.000Z
2020-04-24T03:40:49.000Z
methods/slmm/slmm_c_compat.cpp
ambrad/COMPOSE
0bda7aeaf2b8494c7de8cd179c22e340b08eda6e
[ "BSD-3-Clause" ]
2
2019-01-16T03:58:31.000Z
2019-02-06T22:45:43.000Z
#include <typeinfo> #include "slmm_c_compat.hpp" #include "slmm_spf.hpp" #include "slmm_gll.hpp" #include "slmm_mesh.hpp" #include "slmm_util.hpp" void init () { static bool inited = false; if ( ! inited) Kokkos::initialize(); inited = true; } void finalize () { static bool fin = false; if ( ! fin) Kokkos::finalize(); fin = true; } int solve_1eq_bc_qp_c ( const int n, const double* w, const double* a, const double b, const double* xlo, const double* xhi, const double* y, double* x, const int max_its) { return slmm::spf::solve_1eq_bc_qp( n, w, a, b, xlo, xhi, false, y, x, max_its); } void make_mesh (const int ne, const int np, const int nonuni, double* const p, int* const e) { slmm::AVec3s geo_p; slmm::AIdxs geo_c2n; slmm::mesh::make_cubedsphere_mesh(geo_p, geo_c2n, ne); if (nonuni) slmm::mesh::make_nonuniform(geo_p); if (np > 0) { slmm::AVec3s cgll_p; slmm::AIdxs cgll_c2n, cgll_io_c2n; slmm::mesh::make_cgll_from_geo(geo_p, geo_c2n, np, slmm::GLL(), cgll_p, cgll_c2n); slmm::mesh::make_io_cgll_from_internal_cgll(cgll_p, cgll_c2n, cgll_io_c2n); std::copy(cgll_p.data(), cgll_p.data() + cgll_p.size(), p); std::copy(cgll_io_c2n.data(), cgll_io_c2n.data() + cgll_io_c2n.size(), e); } else { std::copy(geo_p.data(), geo_p.data() + geo_p.size(), p); std::copy(geo_c2n.data(), geo_c2n.data() + geo_c2n.size(), e); } } static void wrap_lonlat (double* xs, double* ys, const int ne) { double min_lon, max_lon, min_lat, max_lat; const auto calc_ext = [&] () { min_lon = 1e30; max_lon = -1e30; min_lat = 1e30; max_lat = -1e30; for (int i = 0; i < ne; ++i) { min_lon = std::min(min_lon, xs[i]); max_lon = std::max(max_lon, xs[i]); min_lat = std::min(min_lat, ys[i]); max_lat = std::max(max_lat, ys[i]); } }; calc_ext(); if (max_lat < -0.95*M_PI/2 || min_lat > 0.95*M_PI/2) return; if (max_lat > 0 && min_lat < 0 && max_lat - min_lat > M_PI/2) for (int i = 0; i < ne; ++i) if (ys[i] < 0) ys[i] += M_PI; if (max_lon > 0 && min_lon < 0 && max_lon - min_lon > M_PI) { if (std::abs(max_lon) > std::abs(min_lon)) { for (int i = 0; i < ne; ++i) if (xs[i] > M_PI/2) xs[i] -= 2*M_PI; } else { for (int i = 0; i < ne; ++i) if (xs[i] < -M_PI/2) xs[i] += 2*M_PI; } } calc_ext(); if (max_lon > 2*M_PI - min_lon) for (int i = 0; i < ne; ++i) xs[i] -= 2*M_PI; if (-min_lon > 2*M_PI + max_lon) for (int i = 0; i < ne; ++i) xs[i] += 2*M_PI; } void make_latlon_quads (const int ncell, const double* ps, const int* es, double* lls) { static constexpr int nv = 4; for (int ie = 0; ie < ncell; ++ie) { const auto e = es + nv*ie; const auto lons = lls + 2*nv*ie; const auto lats = lons + 4; for (int iv = 0; iv < nv; ++iv) { const auto p = ps + 3*e[iv]; slmm::xyz2ll(p[0], p[1], p[2], lats[iv], lons[iv]); } wrap_lonlat(lons, lats, nv); } }
31.389474
88
0.585178
[ "mesh" ]
284e127ec405afeb8de409a45cc1c3a4ff33e45f
2,205
cpp
C++
Dynamic Programming/CSES Problem Set [ Dynamic Programming ]/Book Shop.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Dynamic Programming/CSES Problem Set [ Dynamic Programming ]/Book Shop.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Dynamic Programming/CSES Problem Set [ Dynamic Programming ]/Book Shop.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// Problem: Book Shop // Contest: CSES - CSES Problem Set // URL: https://cses.fi/problemset/task/1158 // Memory Limit: 512 MB // Time Limit: 1000 ms // Parsed on: 03-02-2021 12:24:12 IST (UTC+05:30) // Author: Kapil Choudhary // ******************************************************************** // कर्मण्येवाधिकारस्ते मा फलेषु कदाचन | // मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि || १.४७ || // ******************************************************************** #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; void solve() { int n, x; cin >> n >> x; int price[n+1], pages[n+1]; for(int i = 1; i <= n; i++) cin >> price[i]; for(int i = 1; i <= n; i++) cin >> pages[i]; int dp[n+1][x+1]; for(int i = 0; i <= n; i++) { for(int money = 0; money <= x; money++) { if(money == 0 || i == 0) dp[i][money] = 0; else { int op1 = dp[i-1][money]; int op2 = (price[i] > money) ? 0 : pages[i] + dp[i-1][money - price[i]]; dp[i][money] = max(op1, op2); } } } cout << dp[n][x] << "\n"; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; // cin >> t; while(t--) { solve(); } return 0; }
26.566265
81
0.543311
[ "vector" ]
28528474ec603711cf1f8f6cdb88b047d42fa6e8
9,259
cpp
C++
GpioTestTool/main.cpp
eportelli/samples
9a9fba8ce6f10fc9d7f7eb1f0519c874f21d9949
[ "MIT" ]
8
2016-06-01T16:27:20.000Z
2021-03-25T03:06:59.000Z
GpioTestTool/main.cpp
eportelli/samples
9a9fba8ce6f10fc9d7f7eb1f0519c874f21d9949
[ "MIT" ]
null
null
null
GpioTestTool/main.cpp
eportelli/samples
9a9fba8ce6f10fc9d7f7eb1f0519c874f21d9949
[ "MIT" ]
4
2016-07-15T03:04:10.000Z
2021-03-18T09:43:57.000Z
// Copyright (c) Microsoft. All rights reserved. // // GpioTestTool // // Utility to manipulate GPIO pins from the command line. // Demonstrates how to use the GPIO WinRT APIs from standard // C++ with WRL. // #include <windows.h> #include <strsafe.h> #include <wrl.h> #include <string> #include <vector> #include <sstream> #include <iostream> #include <cwctype> #include <windows.foundation.h> #include <windows.devices.gpio.h> using namespace ABI::Windows::Foundation; using namespace ABI::Windows::Devices::Gpio; using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; class wexception { public: explicit wexception (const std::wstring &msg) : msg_(msg) { } virtual ~wexception () { } virtual const wchar_t *wwhat () const { return msg_.c_str(); } private: std::wstring msg_; }; ComPtr<IGpioPin> MakePin (int PinNumber) { ComPtr<IGpioPin> pin; // get the activation factory ComPtr<IGpioControllerStatics> controllerStatics; HRESULT hr = GetActivationFactory( HStringReference(RuntimeClass_Windows_Devices_Gpio_GpioController).Get(), &controllerStatics); if (FAILED(hr)) { std::wostringstream msg; msg << L"Failed to get activation factory for GpioController. hr = 0x" << std::hex << hr; throw wexception(msg.str()); } ComPtr<IGpioController> controller; hr = controllerStatics->GetDefault(controller.GetAddressOf()); if (FAILED(hr)) { throw wexception(L"Failed to get instance of default GPIO controller"); } if (!controller) { throw wexception(L"GPIO is not available on this system"); } hr = controller->OpenPin(PinNumber, pin.GetAddressOf()); if (FAILED(hr)) { std::wostringstream msg; msg << L"Failed to open pin. hr = 0x" << std::hex << hr; throw wexception(msg.str()); } return pin; } GpioPinValue operator! (GpioPinValue Value) { return (Value == GpioPinValue_Low) ? GpioPinValue_High : GpioPinValue_Low; } std::wistream& operator>> (std::wistream& is, GpioPinValue& value) { int raw; is >> raw; if (is.fail()) { return is; } switch (raw) { case GpioPinValue_Low: case GpioPinValue_High: value = GpioPinValue(raw); break; default: is.clear(is.failbit); } return is; } std::wostream& operator<< (std::wostream& os, GpioPinValue value) { switch (value) { case GpioPinValue_Low: return os << L"Low"; case GpioPinValue_High: return os << L"High"; default: return os << L"[undefined]"; } } std::wistream& operator>> (std::wistream& is, GpioPinDriveMode& value) { is.clear(); std::wstring driveMode; is >> driveMode; if (!_wcsicmp(driveMode.c_str(), L"input")) { value = GpioPinDriveMode_Input; } else if (!_wcsicmp(driveMode.c_str(), L"output")) { value = GpioPinDriveMode_Output; } else if (!_wcsicmp(driveMode.c_str(), L"inputPullUp")) { value = GpioPinDriveMode_InputPullUp; } else if (!_wcsicmp(driveMode.c_str(), L"inputPullDown")) { value = GpioPinDriveMode_InputPullDown; } else { is.clear(is.failbit); } return is; } std::wostream& operator<< (std::wostream& os, GpioPinDriveMode value) { switch (value) { case GpioPinDriveMode_Input: return os << L"input"; case GpioPinDriveMode_Output: return os << L"output"; case GpioPinDriveMode_InputPullUp: return os << L"inputPullUp"; case GpioPinDriveMode_InputPullDown: return os << L"inputPullDown"; default: return os << L"[undefined]"; } } std::wostream& operator<< (std::wostream& os, GpioSharingMode value) { switch (value) { case GpioSharingMode_Exclusive: return os << L"Exclusive"; case GpioSharingMode_SharedReadOnly: return os << L"SharedReadOnly"; default: return os << L"[undefined]"; } } PCWSTR Help = L"Commands:\n" L" > write 0|1 Write pin low (0) or high (1)\n" L" > toggle Toggle the pin from its current state\n" L" > read Read pin\n" L" > setdrivemode drive_mode Set the pins's drive mode\n" L" where drive_mode = input|output|\n" L" inputPullUp|inputPullDown\n" L" > info Dump information about the pin\n" L" > help Display this help message\n" L" > quit Quit\n\n"; void ShowPrompt (_In_ IGpioPin* pin) { GpioPinValue outputLatch = GpioPinValue_High; while (std::wcin) { std::wcout << L"> "; std::wstring line; if (!std::getline(std::wcin, line)) { return; } std::wistringstream linestream(line); std::wstring command; linestream >> command; if ((command == L"q") || (command == L"quit")) { return; } else if ((command == L"h") || (command == L"help")) { std::wcout << Help; } else if ((command == L"w") || (command == L"write")) { GpioPinValue value; linestream >> value; if (linestream.fail()) { std::wcout << L"Syntax error: expecting 0 or 1\n"; std::wcout << L"Usage: write 0|1\n"; continue; } HRESULT hr = pin->Write(value); if (FAILED(hr)) { std::wcout << L"Failed to write pin. hr = 0x" << std::hex << hr << "\n"; continue; } } else if ((command == L"t") || (command == L"toggle")) { outputLatch = !outputLatch; HRESULT hr = pin->Write(outputLatch); if (FAILED(hr)) { std::wcout << L"Failed to write pin. hr = 0x" << std::hex << hr << "\n"; continue; } } else if ((command == L"r") || (command == L"read")) { GpioPinValue value; HRESULT hr = pin->Read(&value); if (FAILED(hr)) { std::wcout << L"Failed to read pin. hr = 0x" << std::hex << hr << "\n"; continue; } std::wcout << value << L"\n"; } else if (command == L"setdrivemode") { GpioPinDriveMode driveMode; linestream >> driveMode; if (linestream.fail()) { std::wcout << L"Syntax error: expecting valid drive mode\n"; continue; } HRESULT hr = pin->SetDriveMode(driveMode); if (FAILED(hr)) { std::wcout << L"Failed to set drive mode. hr = 0x" << std::hex << hr << "\n"; continue; } } else if ((command == L"i") || (command == L"info")) { int pinNumber; pin->get_PinNumber(&pinNumber); GpioSharingMode sharingMode; pin->get_SharingMode(&sharingMode); TimeSpan debounceTimeout; pin->get_DebounceTimeout(&debounceTimeout); GpioPinDriveMode driveMode; pin->GetDriveMode(&driveMode); std::wcout << L" Pin Number: " << std::dec << pinNumber << L"\n"; std::wcout << L" Sharing Mode: " << sharingMode << L"\n"; std::wcout << L" Debounce Timeout: " << debounceTimeout.Duration << L"\n"; std::wcout << L" Drive Mode: " << driveMode << L"\n"; } else if (command.empty()) { // ignore } else { std::wcout << L"Unrecognized command: " << command << L". Type 'help' for command usage.\n"; } } } void PrintUsage (PCWSTR name) { wprintf( L"%s: Command line GPIO testing utility\n" L"Usage: %s PinNumber\n" L"\n" L" PinNumber The pin number with which you wish to interact. This\n" L" parameter is required.\n" L"\n" L"Example:\n" L" %s 47\n", name, name, name); } int __cdecl wmain (_In_ int argc, _In_reads_(argc) wchar_t *argv[]) { int optind = 1; if (optind < argc) { if (!_wcsicmp(argv[optind], L"-h") || !wcscmp(argv[optind], L"-?")) { PrintUsage(argv[0]); return 0; } } else { std::wcerr << L"Missing required command line parameter PinNumber\n\n"; PrintUsage(argv[0]); return 1; } INT32 pinNumber; { PCWSTR arg = argv[optind++]; wchar_t *endptr; pinNumber = INT32(wcstoul(arg, &endptr, 0)); if (endptr != (arg + wcslen(arg))) { std::wcerr << L"Expecting integer: " << arg << L"\n"; std::wcerr << L"Type '" << argv[0] << " -h' for usage\n"; return 1; } } RoInitializeWrapper roInit(RO_INIT_MULTITHREADED); try { auto pin = MakePin(pinNumber); std::wcout << L"Type 'help' for a list of commands\n"; ShowPrompt(pin.Get()); } catch (const wexception& ex) { std::wcerr << L"Error: " << ex.wwhat() << L"\n"; return 1; } return 0; }
29.771704
93
0.542067
[ "vector" ]
285292500f37042070703e85d381b5d1c9a8ab58
14,332
cpp
C++
Prototype/src/libsbml-5.10.0/src/sbml/packages/spatial/sbml/CSGNode.cpp
Cosmo-Tech/biopredyn
0f5bcd4cb1f723bfdea07d4973e46e676f4175e8
[ "BSD-3-Clause" ]
null
null
null
Prototype/src/libsbml-5.10.0/src/sbml/packages/spatial/sbml/CSGNode.cpp
Cosmo-Tech/biopredyn
0f5bcd4cb1f723bfdea07d4973e46e676f4175e8
[ "BSD-3-Clause" ]
95
2015-03-06T12:14:06.000Z
2015-03-20T11:15:54.000Z
Prototype/src/libsbml-5.10.0/src/sbml/packages/spatial/sbml/CSGNode.cpp
Cosmo-Tech/biopredyn
0f5bcd4cb1f723bfdea07d4973e46e676f4175e8
[ "BSD-3-Clause" ]
null
null
null
/** * @file CSGNode.cpp * @brief Implementation of CSGNode, the SBase derived class of spatial package. * @author * * $Id: CSGNode.cpp $ * $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/branches/libsbml-5/src/packages/spatial/sbml/CSGNode.cpp $ * *<!--------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright 2009 California Institute of Technology. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html *------------------------------------------------------------------------- --> */ #include <iostream> #include <limits> #include <sbml/SBMLVisitor.h> #include <sbml/xml/XMLNode.h> #include <sbml/xml/XMLToken.h> #include <sbml/xml/XMLAttributes.h> #include <sbml/xml/XMLInputStream.h> #include <sbml/xml/XMLOutputStream.h> #include <sbml/packages/spatial/sbml/CSGPrimitive.h> #include <sbml/packages/spatial/sbml/CSGPseudoPrimitive.h> #include <sbml/packages/spatial/sbml/CSGSetOperator.h> #include <sbml/packages/spatial/sbml/CSGTranslation.h> #include <sbml/packages/spatial/sbml/CSGRotation.h> #include <sbml/packages/spatial/sbml/CSGScale.h> #include <sbml/packages/spatial/sbml/CSGHomogeneousTransformation.h> #include <sbml/packages/spatial/sbml/CSGNode.h> #include <sbml/packages/spatial/extension/SpatialExtension.h> using namespace std; LIBSBML_CPP_NAMESPACE_BEGIN /* * Only subclasses may create CSGNodes. */ CSGNode::CSGNode (SBMLSpatialTypeCode_t type, unsigned int level, unsigned int version) : SBase (level,version) , mSpatialId("") , mType (type) { } CSGNode::CSGNode(SBMLSpatialTypeCode_t type,SpatialPkgNamespaces* spatialns) : SBase(spatialns) , mSpatialId("") , mType (type) { } /* * Assignment operator. */ CSGNode& CSGNode::operator=(const CSGNode& source) { if(&source!=this) { this->SBase::operator=(source); this->mSpatialId = source.mSpatialId; this->mType = source.mType; } return *this; } /* * Destructor. */ CSGNode::~CSGNode () { } /* * Returns the value of the "spatialId" attribute of this CSGNode. */ const std::string& CSGNode::getSpatialId () const { return mSpatialId; } /* * Predicate returning @c true or @c false depending on whether this * CSGNode's "spatialId" attribute has been set. */ bool CSGNode::isSetSpatialId () const { return (mSpatialId.empty() == false); } /* * Sets the value of the "spatialId" attribute of this CSGNode. */ int CSGNode::setSpatialId (const std::string& spatialId) { return SyntaxChecker::checkAndSetSId(spatialId ,mSpatialId); } /* * Unsets the value of the "spatialId" attribute of this CSGNode. */ int CSGNode::unsetSpatialId () { mSpatialId.erase(); if (mSpatialId.empty()) { return LIBSBML_OPERATION_SUCCESS; } else { return LIBSBML_OPERATION_FAILED; } } /* * Creates a new CSGPrimitive for this CSGNode and returns it. */ CSGPrimitive* CSGNode::create_CSGPrimitive () { CSGPrimitive* n = new CSGPrimitive(static_cast<SpatialPkgNamespaces*>(mSBMLNamespaces)); return n; } /* * Creates a new CSGPseudoPrimitive for this CSGNode and returns it. */ CSGPseudoPrimitive* CSGNode::create_CSGPseudoPrimitive () { CSGPseudoPrimitive* n = new CSGPseudoPrimitive(static_cast<SpatialPkgNamespaces*>(mSBMLNamespaces)); return n; } /* * Creates a new CSGSetOperator for this CSGNode and returns it. */ CSGSetOperator* CSGNode::create_CSGSetOperator () { CSGSetOperator* n = new CSGSetOperator(static_cast<SpatialPkgNamespaces*>(mSBMLNamespaces)); return n; } /* * Creates a new CSGTranslation for this CSGNode and returns it. */ CSGTranslation* CSGNode::create_CSGTranslation () { CSGTranslation* n = new CSGTranslation(static_cast<SpatialPkgNamespaces*>(mSBMLNamespaces)); return n; } /* * Creates a new CSGRotation for this CSGNode and returns it. */ CSGRotation* CSGNode::create_CSGRotation () { CSGRotation* n = new CSGRotation(static_cast<SpatialPkgNamespaces*>(mSBMLNamespaces)); return n; } /* * Creates a new CSGScale for this CSGNode and returns it. */ CSGScale* CSGNode::create_CSGScale () { CSGScale* n = new CSGScale(static_cast<SpatialPkgNamespaces*>(mSBMLNamespaces)); return n; } /* * Creates a new CSGHomogeneousTransformation for this CSGNode and returns it. */ CSGHomogeneousTransformation* CSGNode::create_CSGHomogeneousTransformation () { CSGHomogeneousTransformation* n = new CSGHomogeneousTransformation(static_cast<SpatialPkgNamespaces*>(mSBMLNamespaces)); return n; } /* * Subclasses should override this method to return XML element name of * this SBML object. */ const std::string& CSGNode::getElementName () const { static const string csgTransformation = "csgTransformation"; static const string csgPrimitive = "csgPrimitive"; static const string csgPseudoPrimitive = "csgPseudoPrimitive"; static const string csgSetOperator = "csgSetOperator"; static const string invalid = "invalid"; if ( isCSGTransformation() ) { return csgTransformation; } else if ( isCSGPrimitive() ) { return csgPrimitive; } else if ( isCSGPseudoPrimitive() ) { return csgPseudoPrimitive; } else if ( isCSGSetOperator() ) { return csgSetOperator; } return invalid; } /* * Subclasses should override this method to get the list of * expected attributes. * This function is invoked from corresponding readAttributes() * function. */ void CSGNode::addExpectedAttributes(ExpectedAttributes& attributes) { SBase::addExpectedAttributes(attributes); attributes.add("spatialId"); } /* * Subclasses should override this method to read values from the given * XMLAttributes set into their specific fields. Be sure to call your * parents implementation of this method as well. */ void CSGNode::readAttributes (const XMLAttributes& attributes, const ExpectedAttributes& expectedAttributes) { SBase::readAttributes(attributes,expectedAttributes); const unsigned int sbmlLevel = getLevel (); const unsigned int sbmlVersion = getVersion(); bool assigned = attributes.readInto("spatialId", mSpatialId, getErrorLog(), true, getLine(), getColumn()); if (assigned && mSpatialId.empty()) { logEmptyString(mSpatialId, sbmlLevel, sbmlVersion, "<CSGNode>"); } if (!SyntaxChecker::isValidSBMLSId(mSpatialId)) logError(InvalidIdSyntax, getLevel(), getVersion(), "The syntax of the attribute spatialId='" + mSpatialId + "' does not conform."); } /* * Subclasses should override this method to write their XML attributes * to the XMLOutputStream. Be sure to call your parents implementation * of this method as well. */ void CSGNode::writeAttributes (XMLOutputStream& stream) const { SBase::writeAttributes(stream); stream.writeAttribute("spatialId", getPrefix(), mSpatialId); // // (EXTENSION) // SBase::writeExtensionAttributes(stream); } /* * @return the type of this CSGNode, CSGOBJ_TYPE_GEOMETRICPRIMITIVE or CSGOBJ_TYPE_CSGOPERATOR * or CSGOBJ_TYPE_AFFINETRANSFORMATION */ CSGNodeType_t CSGNode::getType () const { if (mType == SBML_SPATIAL_CSGTRANSFORMATION) return CSGNODE_TYPE_CSGTRANSFORMATION; if (mType == SBML_SPATIAL_CSGPRIMITIVE) return CSGNODE_TYPE_CSGPRIMITIVE; if (mType == SBML_SPATIAL_CSGPSEUDOPRIMITIVE) return CSGNODE_TYPE_CSGPSEUDOPRIMITIVE; if (mType == SBML_SPATIAL_CSGSETOPERATOR) return CSGNODE_TYPE_CSGSETOPERATOR; return CSGNODE_TYPE_INVALID; } /* * @return true if this CSGNode is a CSGTransformation, false otherwise. */ bool CSGNode::isCSGTransformation () const { return ((mType == SBML_SPATIAL_CSGTRANSFORMATION)); /* return ((mType == SBML_SPATIAL_CSGTRANSLATION) || (mType == SBML_SPATIAL_CSGROTATION) || (mType == SBML_SPATIAL_CSGSCALE) || (mType == SBML_SPATIAL_CSGHOMOGENEOUSTRANSFORMATION)) ; */ } /* * @return true if this CSGNode is a CSGPrimitive, false otherwise. */ bool CSGNode::isCSGPrimitive () const { return (mType == SBML_SPATIAL_CSGPRIMITIVE); } /* * @return true if this CSGNode is a CSGPseudoPrimitive, false otherwise. */ bool CSGNode::isCSGPseudoPrimitive () const { return (mType == SBML_SPATIAL_CSGPSEUDOPRIMITIVE); } /* * @return true if this CSGNode is an CSGNode, false otherwise. */ bool CSGNode::isCSGSetOperator () const { return (mType == SBML_SPATIAL_CSGSETOPERATOR); } /* * @return the typecode (int) of this SBML object or SBML_UNKNOWN * (default). * * @see getElementName() */ int CSGNode::getTypeCode () const { return mType; } CSGNode* CSGNode::clone() const { return new CSGNode(*this); } /* * Accepts the given SBMLVisitor. */ bool CSGNode::accept (SBMLVisitor& v) const { return v.visit(*this); } /* * Sets the parent SBMLDocument of this SBML object. */ void CSGNode::setSBMLDocument (SBMLDocument* d) { SBase::setSBMLDocument(d); } /* * Enables/Disables the given package with this element and child * elements (if any). * (This is an internal implementation for enablePakcage function) */ void CSGNode::enablePackageInternal(const std::string& pkgURI, const std::string& pkgPrefix, bool flag) { SBase::enablePackageInternal(pkgURI,pkgPrefix,flag); } /** @cond doxygenCOnly */ /** * Creates and returns a deep copy of a given CSGNode_t structure. * * @param g the CSGNode_t structure to copy * * @return a (deep) copy of this CSGNode_t structure. */ LIBSBML_EXTERN CSGNode_t * CSGNode_clone (const CSGNode_t *csg) { return static_cast<CSGNode*>( csg->clone() ); } /* * Ctor. */ ListOfCSGNodes::ListOfCSGNodes(SpatialPkgNamespaces* spatialns) : ListOf(spatialns) { // // set the element namespace of this object // setElementNamespace(spatialns->getURI()); } /* * Ctor. */ ListOfCSGNodes::ListOfCSGNodes(unsigned int level, unsigned int version, unsigned int pkgVersion) : ListOf(level,version) { setSBMLNamespacesAndOwn(new SpatialPkgNamespaces(level,version,pkgVersion)); }; /* * @return a (deep) copy of this ListOfCSGNodes. */ ListOfCSGNodes* ListOfCSGNodes::clone () const { return new ListOfCSGNodes(*this); } /** * @return the SBML object corresponding to next XMLToken in the * XMLInputStream or NULL if the token was not recognized. */ SBase* ListOfCSGNodes::createObject (XMLInputStream& stream) { const std::string& name = stream.peek().getName(); CSGNode* object = 0; SPATIAL_CREATE_NS(spatialns, this->getSBMLNamespaces()); if (name == "csgTranslation") { object = new CSGTranslation(spatialns); } if (name == "csgRotation") { object = new CSGRotation(spatialns); } if (name == "csgScale") { object = new CSGScale(spatialns); } if (name == "csgHomogeneousTransformation") { object = new CSGHomogeneousTransformation(spatialns); } if (name == "csgPrimitive") { object = new CSGPrimitive(spatialns); } if (name == "csgPseudoPrimitive") { object = new CSGPseudoPrimitive(spatialns); } if (name == "csgSetOperator") { object = new CSGSetOperator(spatialns); } delete spatialns; appendAndOwn(object); return object; } /* return nth item in list */ CSGNode * ListOfCSGNodes::get(unsigned int n) { return static_cast<CSGNode*>(ListOf::get(n)); } /* return nth item in list */ const CSGNode * ListOfCSGNodes::get(unsigned int n) const { return static_cast<const CSGNode*>(ListOf::get(n)); } /* return item by spatialId */ CSGNode* ListOfCSGNodes::get (const std::string& spatialId) { return const_cast<CSGNode*>( static_cast<const ListOfCSGNodes&>(*this).get(spatialId) ); } /* return item by spatialId */ const CSGNode* ListOfCSGNodes::get (const std::string& spatialId) const { vector<SBase*>::const_iterator result; result = find_if( mItems.begin(), mItems.end(), IdEq<CSGNode>(spatialId) ); return (result == mItems.end()) ? 0 : static_cast <CSGNode*> (*result); } /* Removes the nth item from this list */ CSGNode* ListOfCSGNodes::remove (unsigned int n) { return static_cast<CSGNode*>(ListOf::remove(n)); } /* Removes item in this list by spatialId */ CSGNode* ListOfCSGNodes::remove (const std::string& spatialId) { SBase* item = 0; vector<SBase*>::iterator result; result = find_if( mItems.begin(), mItems.end(), IdEq<CSGNode>(spatialId) ); if (result != mItems.end()) { item = *result; mItems.erase(result); } return static_cast <CSGNode*> (item); } /* * @return the typecode (int) of SBML objects contained in this ListOf or * SBML_UNKNOWN (default). */ int ListOfCSGNodes::getItemTypeCode () const { return SBML_SPATIAL_CSGNODE; } /* * Subclasses should override this method to return XML element name of * this SBML object. */ const std::string& ListOfCSGNodes::getElementName () const { static const std::string name = "listOfCSGNodes"; return name; } bool ListOfCSGNodes::isValidTypeForList(SBase * item) { int tc = item->getTypeCode(); return ((tc == SBML_SPATIAL_CSGTRANSLATION ) || (tc == SBML_SPATIAL_CSGROTATION ) || (tc == SBML_SPATIAL_CSGSCALE ) || (tc == SBML_SPATIAL_CSGHOMOGENEOUSTRANSFORMATION ) || (tc == SBML_SPATIAL_CSGPRIMITIVE ) || (tc == SBML_SPATIAL_CSGPSEUDOPRIMITIVE ) || (tc == SBML_SPATIAL_CSGSETOPERATOR )); } LIBSBML_CPP_NAMESPACE_END
23.456628
123
0.679528
[ "object", "vector" ]
28535f94d7e094f65a4116ff0d4d5d631ea0e576
2,827
hpp
C++
Explit/Explit/sdk/config/config.hpp
danielkrupinski/Expl
74124b67361cd29dd34389d692e43df86f83d072
[ "MIT" ]
12
2019-05-18T14:08:58.000Z
2021-06-13T01:22:53.000Z
Explit/Explit/sdk/config/config.hpp
danielkrupinski/Expl
74124b67361cd29dd34389d692e43df86f83d072
[ "MIT" ]
null
null
null
Explit/Explit/sdk/config/config.hpp
danielkrupinski/Expl
74124b67361cd29dd34389d692e43df86f83d072
[ "MIT" ]
3
2019-05-26T20:02:30.000Z
2020-02-17T20:26:47.000Z
#pragma once #include "../sdk.hpp" class c_config { public: c_config(const std::string path); void load(const std::string name); void save(const std::string name); void refresh(); struct { bool unhook = false; std::vector<std::string> config_list; std::string config_name; int config_id = 0; struct { struct { bool esp = true; bool box = true; int box_type = 1; bool fill_box = false; bool outline_box = true; int health = 0; bool distance = false; bool name = false; bool weapon = false; bool visible = false; bool ammo = false; bool skeletons = false; bool snaplines = false; bool vulnerability = false; int armor = 0; bool money = false; bool enemies = true; bool team = false; bool weapons = false; bool local = false; bool nades = false; bool chickens = false; struct { float team_invisible[3] = { 0,0,255 }; float team_visible[3] = { 0,255,0 }; float enemy_invisible[3] = { 255,255,0 }; float enemy_visible[3] = { 255,0,0 }; float weapons[3] = { 255,0,0 } ; float chickens[3] = { 255,0,0 }; float vulnerability[3] = {255,255,255}; float local[4] = { 54, 251, 43 , 255 }; }colors; }esp; struct { bool chams = false; bool local = false; bool enemy = false; bool team = false; bool wireframe = false; int material = 0; bool visible = false; bool arms = false; bool weapon = false; struct { float team_invisible[3] = { 0,0,255 }; float team_visible[3] = { 0,255,0 }; float enemy_invisible[3] = { 255,255,0 }; float enemy_visible[3] = { 255,0,0 }; float arms[3] = { 255,0,0 }; float weapon[3] = { 255,0,0 }; float local[3] = { 32,164,199 }; }colors; }chams; struct { bool glow = false; bool local = false; bool chickens = false; bool weapons = false; bool team = false; bool visible = false; bool enemy = false; bool vulnerability = false; int style = 0; struct { float team_invisible[3] = { 0,0,255 }; float team_visible[3] = { 0,255,0 }; float enemy_invisible[3] = { 255,255,0 }; float enemy_visible[3] = { 255,0,0 }; float weapons[3] = { 255,0,0 }; float chickens[3] = { 255,0,0 }; float local[3] = { 32,164,199 }; float vulnerability[3] = { 255,255,255 }; }colors; }glow; struct { bool enable = false; bool local = false; bool enemy = false; bool team = false; float radius = 50.f; }dlights; struct { bool watermark = true; }others; }visuals; struct { }misc; } settings; private: std::string directory_path; }; extern c_config g_config;
25.93578
47
0.559958
[ "vector" ]
28543377cfda6729d28d07ac1b8e9889737f09dc
3,789
hpp
C++
examples/flow/flow.hpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
null
null
null
examples/flow/flow.hpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
null
null
null
examples/flow/flow.hpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
null
null
null
// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com> // SPDX-License-Identifier: MIT #ifndef FLOW_FLOW_HPP #define FLOW_FLOW_HPP #include <cmath> #include "ads/executor/galois.hpp" #include "ads/output_manager.hpp" #include "ads/simulation.hpp" #include "environment.hpp" #include "pumps.hpp" namespace ads::problems { class flow : public simulation_3d { private: using Base = simulation_3d; vector_type u, u_prev; galois_executor executor{4}; environment env{1}; lin::tensor<double, 6> kq; output_manager<3> output; public: explicit flow(const config_3d& config) : Base{config} , u{shape()} , u_prev{shape()} , kq{{x.basis.elements, y.basis.elements, z.basis.elements, x.basis.quad_order + 1, y.basis.quad_order + 1, z.basis.quad_order + 1}} , output{x.B, y.B, z.B, 50} { } double init_state(double x, double y, double z) { double r = 0.1; double R = 0.5; return ads::bump(r, R, x, y, z); }; private: void before() override { fill_permeability_map(); prepare_matrices(); auto init = [this](double x, double y, double z) { return init_state(x, y, z); }; projection(u, init); solve(u); output.to_file(u, "out_%d.vti", 0); } void fill_permeability_map() { for (auto e : elements()) { for (auto q : quad_points()) { auto x = point(e, q); kq(e[0], e[1], e[2], q[0], q[1], q[2]) = env.permeability(x[0], x[1], x[2]); } } } void before_step(int /*iter*/, double /*t*/) override { using std::swap; swap(u, u_prev); } void step(int /*iter*/, double t) override { compute_rhs(t); solve(u); } void compute_rhs(double t) { auto& rhs = u; zero(rhs); executor.for_each(elements(), [&](index_type e) { auto U = element_rhs(); double J = jacobian(e); for (auto q : quad_points()) { double w = weight(q); auto x = point(e, q); double mi = 10; double k = permeability(e, q); value_type u = eval_fun(u_prev, e, q); double h = forcing(x, t); for (auto a : dofs_on_element(e)) { auto aa = dof_global_to_local(e, a); value_type v = eval_basis(e, q, a); double val = -k * std::exp(mi * u.val) * grad_dot(u, v) + h * v.val; U(aa[0], aa[1], aa[2]) += (u.val * v.val + steps.dt * val) * w * J; } } executor.synchronized([&] { update_global_rhs(rhs, U, e); }); }); } double energy(const vector_type& u) const { double E = 0; for (auto e : elements()) { double J = jacobian(e); for (auto q : quad_points()) { double w = weight(q); value_type a = eval_fun(u, e, q); E += a.val * a.val * w * J; } } return E; } void after_step(int iter, double /*t*/) override { if (iter % 10 == 0) { std::cout << "Step " << iter << ", energy: " << energy(u) << std::endl; } if ((iter + 1) % 100 == 0) { output.to_file(u, "out_%d.vti", iter + 1); } } double permeability(index_type e, index_type q) const { return kq(e[0], e[1], e[2], q[0], q[1], q[2]); } double forcing(point_type x, double /*t*/) const { using std::sin; double pi2 = 2 * M_PI; return 1 + sin(pi2 * x[0]) * sin(pi2 * x[1]) * sin(pi2 * x[2]); } }; } // namespace ads::problems #endif // FLOW_FLOW_HPP
27.456522
92
0.502507
[ "shape" ]
28597050160a73fdceb84e22fb323cdb1062532b
10,742
cpp
C++
Project1/matrix.cpp
ASSANDHOLE/CS205
2d27a75bb3c76cb76ac55442e514823b295c89a7
[ "MIT" ]
3
2020-09-21T10:58:05.000Z
2021-01-18T08:35:12.000Z
Project1/matrix.cpp
ASSANDHOLE/CS205
2d27a75bb3c76cb76ac55442e514823b295c89a7
[ "MIT" ]
null
null
null
Project1/matrix.cpp
ASSANDHOLE/CS205
2d27a75bb3c76cb76ac55442e514823b295c89a7
[ "MIT" ]
null
null
null
// // Created by AGY on 2020/10/21. // #include "matrix.h" #include <algorithm> #include <thread> #include <vector> #include <functional> #include "mul_mat.h" template<typename T> Matrix<T>::Matrix(const int row, const int column, bool to_zero_for_basic_types) { if (column > 0 && row > 0) { column_ = column; row_ = row; matrix_1d_ = new T[row_ * column_]; if (to_zero_for_basic_types) { initToZero(); } } else { row_ = 0; column_ = 0; matrix_1d_ = nullptr; } } template<typename T> Matrix<T>::Matrix(const Matrix<T> &temp) { row_ = temp.row_; column_ = temp.column_; const size_t kTotal = row_ * column_; matrix_1d_ = new T[kTotal]; for (int i = 0; i < kTotal; ++i) { matrix_1d_[i] = temp.matrix_1d_[i]; } } template<typename T> Matrix<T>::Matrix(int row, int column, T *matrix) { row_ = row; column_ = column; matrix_1d_ = matrix; } template<typename T> Matrix<T>::~Matrix<T>() { if (matrix_1d_) { delete[] matrix_1d_; } } template<typename T> Matrix<T> Matrix<T>::operator+(const Matrix<T> &mat2) const { if (row_ != mat2.row_ || column_ != mat2.column_) { throw MatrixNotFitException(); } Matrix<T> res(row_, column_); const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { res.matrix_1d_[i] = matrix_1d_[i] + mat2.matrix_1d_[i]; } return res; } template<typename T> Matrix<T> Matrix<T>::operator+(const T &t) const { Matrix<T> res(row_, column_); const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { res.matrix_1d_[i] = matrix_1d_[i] + t; } return res; } template<typename T> Matrix<T> Matrix<T>::operator-(const Matrix<T> &mat2) const { if (row_ != mat2.row_ || column_ != mat2.column_) { throw MatrixNotFitException(); } Matrix<T> res(row_, column_); const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { res.matrix_1d_[i] = matrix_1d_[i] - mat2.matrix_1d_[i]; } return res; } template<typename T> Matrix<T> Matrix<T>::operator-(const T &t) const { Matrix<T> res(row_, column_); const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { res.matrix_1d_[i] = matrix_1d_[i] - t; } return res; } template<class T> const T &Min(const T &a, const T &b) { return a < b ? a : b; } template<typename T> Matrix<T> Matrix<T>::operator*(const Matrix<T> &mat2) const { if (column_ != mat2.row_ || row_ == 0 || column_ == 0 || mat2.column_ == 0) { throw MatrixNotFitException(); } Matrix<T> res(row_, mat2.column_, true); if (typeid(T) == typeid(float)) { MulThrMat(row_, column_, mat2.column_, matrix_1d_, mat2.matrix_1d_, res.matrix_1d_); return res; } const auto calculate = [this, &res, &mat2](int start, int end) { for (int i = start; i < end; ++i) { for (int k = 0; k < column_; ++k) { for (int j = 0; j < res.column_; ++j) { res.matrix_1d_[i * res.column_ + j] = res.matrix_1d_[i * res.column_ + j] + matrix_1d_[i * column_ + k] * mat2.matrix_1d_[k * mat2.column_ + j]; } } } }; unsigned long const kMinVal = 200; unsigned long const kMaxThread = (res.row_ + kMinVal - 1) / kMinVal; unsigned long const kHardwareConcurrency = std::thread::hardware_concurrency(); unsigned long const kThreadNum = Min(kHardwareConcurrency != 0 ? kHardwareConcurrency : 2, kMaxThread); unsigned long const kBlockSize = res.row_ / kThreadNum; std::vector<std::thread> threads(kThreadNum - 1); for (int i = 0; i < (kThreadNum - 1); i++) { threads[i] = std::thread(calculate, i * kBlockSize, (i + 1) * kBlockSize); } calculate((kThreadNum - 1) * kBlockSize, res.row_); std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join)); return res; } template<typename T> Matrix<T> Matrix<T>::operator*(const T &t) const { Matrix<T> res(row_, column_); const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { res.matrix_1d_[i] = matrix_1d_[i] * t; } return res; } template<typename T> Matrix<T> Matrix<T>::operator/(const T &t) const { Matrix<T> res(row_, column_); const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { res.matrix_1d_[i] = matrix_1d_[i] / t; } return res; } template <typename T> Matrix<T> Matrix<T>::operator^(const int time) const { if (row_ != column_ || row_ == 0) { throw MatrixNotFitException(); } Matrix<T> res(*this); Matrix<T> base(*this); if (time <= 1) { return res; } int temp_time = time - 1; while (temp_time > 0) { if (temp_time & 1) { res = res * base; } base = base * base; temp_time /= 2; } return res; } template<typename T> Matrix<T> &Matrix<T>::operator=(const Matrix<T> &matrix) { if (this == &matrix) { return *this; } if (matrix_1d_) { delete[] matrix_1d_; } row_ = matrix.row_; column_ = matrix.column_; if (row_ > 0 && column_ > 0) { const size_t kTotal = row_ * column_; matrix_1d_ = new T[kTotal]; for (int i = 0; i < kTotal; ++i) { matrix_1d_[i] = matrix.matrix_1d_[i]; } } else { row_ = 0; column_ = 0; matrix_1d_ = nullptr; } return *this; } template<typename T> bool Matrix<T>::operator==(const Matrix<T> &mat2) const { if (row_ != mat2.row_ || column_ != mat2.column_) { return false; } if (row_ > 0 && column_ > 0) { const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { if (matrix_1d_[i] != mat2.matrix_1d_[i]) { return false; } } } return true; } template<typename T> bool Matrix<T>::operator!=(const Matrix<T> &mat2) const { if (row_ != mat2.row_ || column_ != mat2.column_) { return true; } if (row_ > 0 && column_ > 0) { const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { if (matrix_1d_[i] != mat2.matrix_1d_[i]) { return true; } } } return false; } template<typename T> Matrix<T> Matrix<T>::Transpose() const { if (column_ <= 0 || row_ <= 0) { throw MatrixNotFitException(); } Matrix<T> res(column_, row_); for (int i = 0; i < row_; ++i) { for (int j = 0; j < column_; ++j) { res.matrix_1d_[j * res.column_ + i] = matrix_1d_[i * column_ + j]; } } return res; } template<typename T> std::string Matrix<T>::Format(Matrix::OutputStyle output_style) const { std::stringstream string_stream; switch (output_style) { case kMatrixTypeNumOneLine: string_stream << "Matrix<" << typeid(T).name() << ">[" << row_ << "*" << column_ << "]("; for (int i = 0; i < row_; ++i) { for (int j = 0; j < column_; ++j) { string_stream << matrix_1d_[i * column_ + j]; if (j != column_ - 1) { string_stream << " "; } } string_stream << ((i == row_ - 1) ? ")" : "; "); } break; case kMatrixTypeNumMultipleLines: string_stream << "Matrix<" << typeid(T).name() << ">[" << row_ << "*" << column_ << "]\n("; for (int i = 0; i < row_; ++i) { for (int j = 0; j < column_; ++j) { string_stream << matrix_1d_[i * column_ + j]; if (j != column_ - 1) { string_stream << " "; } } string_stream << ((i == row_ - 1) ? ")" : ";\n "); } break; case kSimpleOneLine: string_stream << "("; for (int i = 0; i < row_; ++i) { for (int j = 0; j < column_; ++j) { string_stream << matrix_1d_[i * column_ + j]; if (j != column_ - 1) { string_stream << " "; } } string_stream << ((i == row_ - 1) ? ")" : "; "); } break; case kSimpleMultipleLines: string_stream << "("; for (int i = 0; i < row_; ++i) { for (int j = 0; j < column_; ++j) { string_stream << matrix_1d_[i * column_ + j]; if (j != column_ - 1) { string_stream << " "; } } string_stream << ((i == row_ - 1) ? ")" : ";\n "); } break; default:; } return string_stream.str(); } template<typename T> T *Matrix<T>::operator[](const int addr) const { if (addr >= row_ || addr < 0) { throw IndexOutOfMatrixException(); } T *res = &matrix_1d_[addr * column_]; return res; } template <typename T> T &Matrix<T>::operator()(int real_row, int real_column) const { return Get(real_row, real_column); } template<typename T> T &Matrix<T>::Get(int real_row, int real_column) const { if (real_row < 1 || real_column < 1 || real_row > row_ || real_column > column_) { throw IndexOutOfMatrixException(); } return matrix_1d_[(real_row - 1) * column_ + (real_column - 1)]; } template<typename T> std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix) { os << "Matrix<" << typeid(T).name() << ">[" << matrix.row_ << "*" << matrix.column_ << "]("; for (int i = 0; i < matrix.row_; ++i) { for (int j = 0; j < matrix.column_; ++j) { os << matrix.matrix_1d_[i * matrix.column_ + j]; if (j != matrix.column_ - 1) { os << " "; } } os << ((i == matrix.row_ - 1) ? ")" : "; "); } return os; } template<typename T> std::istream &operator>>(std::istream &is, const Matrix<T> &matrix) { if (matrix.row_ <= 0 || matrix.column_ <= 0) { throw MatrixNotFitException(); } for (int i = 0; i < matrix.row_; ++i) { for (int j = 0; j < matrix.column_; ++j) { is >> matrix.matrix_1d_[i * matrix.column_ + j]; } } return is; } template<typename T> void Matrix<T>::initToZero() { const size_t kTotal = row_ * column_; for (int i = 0; i < kTotal; ++i) { matrix_1d_[i] = T(); } }
29.510989
123
0.51415
[ "vector" ]
285e80958f0809a96c6e7f2dd18ac71e68b97b3f
8,609
cc
C++
chrome/browser/sync/glue/ui_model_worker_unittest.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
chrome/browser/sync/glue/ui_model_worker_unittest.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
chrome/browser/sync/glue/ui_model_worker_unittest.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "chrome/browser/sync/glue/ui_model_worker.h" #include "content/test/test_browser_thread.h" #include "testing/gtest/include/gtest/gtest.h" using browser_sync::UIModelWorker; using browser_sync::SyncerError; using content::BrowserThread; // Various boilerplate, primarily for the StopWithPendingWork test. class UIModelWorkerVisitor { public: UIModelWorkerVisitor(base::WaitableEvent* was_run, bool quit_loop) : quit_loop_when_run_(quit_loop), was_run_(was_run) { } virtual ~UIModelWorkerVisitor() { } virtual SyncerError DoWork() { EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI)); was_run_->Signal(); if (quit_loop_when_run_) MessageLoop::current()->Quit(); return browser_sync::SYNCER_OK; } private: bool quit_loop_when_run_; base::WaitableEvent* was_run_; DISALLOW_COPY_AND_ASSIGN(UIModelWorkerVisitor); }; // A faux-syncer that only interacts with its model safe worker. class Syncer { public: explicit Syncer(UIModelWorker* worker) : worker_(worker) {} ~Syncer() {} void SyncShare(UIModelWorkerVisitor* visitor) { // We wait until the callback is executed. So it is safe to use Unretained. browser_sync::WorkCallback c = base::Bind(&UIModelWorkerVisitor::DoWork, base::Unretained(visitor)); worker_->DoWorkAndWaitUntilDone(c); } private: scoped_refptr<UIModelWorker> worker_; DISALLOW_COPY_AND_ASSIGN(Syncer); }; // A callback run from the CoreThread to simulate terminating syncapi. void FakeSyncapiShutdownCallback(base::Thread* syncer_thread, UIModelWorker* worker, base::WaitableEvent** jobs, size_t job_count) { base::WaitableEvent all_jobs_done(false, false); // In real life, we would try and close a sync directory, which would // result in the syncer calling it's own destructor, which results in // the SyncerThread::HaltSyncer being called, which sets the // syncer in RequestEarlyExit mode and waits until the Syncer finishes // SyncShare to remove the syncer from its watch. Here we just manually // wait until all outstanding jobs are done to simulate what happens in // SyncerThread::HaltSyncer. all_jobs_done.WaitMany(jobs, job_count); // These two calls are made from SyncBackendHost::Core::DoShutdown. syncer_thread->Stop(); worker->OnSyncerShutdownComplete(); } class SyncUIModelWorkerTest : public testing::Test { public: SyncUIModelWorkerTest() : faux_syncer_thread_("FauxSyncerThread"), faux_core_thread_("FauxCoreThread") { } virtual void SetUp() { faux_syncer_thread_.Start(); ui_thread_.reset(new content::TestBrowserThread(BrowserThread::UI, &faux_ui_loop_)); bmw_ = new UIModelWorker(); syncer_.reset(new Syncer(bmw_.get())); } Syncer* syncer() { return syncer_.get(); } UIModelWorker* bmw() { return bmw_.get(); } base::Thread* core_thread() { return &faux_core_thread_; } base::Thread* syncer_thread() { return &faux_syncer_thread_; } private: MessageLoop faux_ui_loop_; scoped_ptr<content::TestBrowserThread> ui_thread_; base::Thread faux_syncer_thread_; base::Thread faux_core_thread_; scoped_refptr<UIModelWorker> bmw_; scoped_ptr<Syncer> syncer_; }; TEST_F(SyncUIModelWorkerTest, ScheduledWorkRunsOnUILoop) { base::WaitableEvent v_was_run(false, false); scoped_ptr<UIModelWorkerVisitor> v( new UIModelWorkerVisitor(&v_was_run, true)); syncer_thread()->message_loop()->PostTask(FROM_HERE, base::Bind(&Syncer::SyncShare, base::Unretained(syncer()), v.get())); // We are on the UI thread, so run our loop to process the // (hopefully) scheduled task from a SyncShare invocation. MessageLoop::current()->Run(); bmw()->OnSyncerShutdownComplete(); bmw()->Stop(); syncer_thread()->Stop(); } TEST_F(SyncUIModelWorkerTest, StopWithPendingWork) { // What we want to set up is the following: // ("ui_thread" is the thread we are currently executing on) // 1 - simulate the user shutting down the browser, and the ui thread needing // to terminate the core thread. // 2 - the core thread is where the syncapi is accessed from, and so it needs // to shut down the SyncerThread. // 3 - the syncer is waiting on the UIModelWorker to // perform a task for it. // The UIModelWorker's manual shutdown pump will save the day, as the // UI thread is not actually trying to join() the core thread, it is merely // waiting for the SyncerThread to give it work or to finish. After that, it // will join the core thread which should succeed as the SyncerThread has left // the building. Unfortunately this test as written is not provably decidable, // as it will always halt on success, but it may not on failure (namely if // the task scheduled by the Syncer is _never_ run). core_thread()->Start(); base::WaitableEvent v_ran(false, false); scoped_ptr<UIModelWorkerVisitor> v(new UIModelWorkerVisitor( &v_ran, false)); base::WaitableEvent* jobs[] = { &v_ran }; // The current message loop is not running, so queue a task to cause // UIModelWorker::Stop() to play a crucial role. See comment below. syncer_thread()->message_loop()->PostTask(FROM_HERE, base::Bind(&Syncer::SyncShare, base::Unretained(syncer()), v.get())); // This is what gets the core_thread blocked on the syncer_thread. core_thread()->message_loop()->PostTask(FROM_HERE, base::Bind(&FakeSyncapiShutdownCallback, syncer_thread(), base::Unretained(bmw()), static_cast<base::WaitableEvent**>(jobs), 1)); // This is what gets the UI thread blocked until NotifyExitRequested, // which is called when FakeSyncapiShutdownCallback runs and deletes the // syncer. bmw()->Stop(); EXPECT_FALSE(syncer_thread()->IsRunning()); core_thread()->Stop(); } TEST_F(SyncUIModelWorkerTest, HypotheticalManualPumpFlooding) { // This situation should not happen in real life because the Syncer should // never send more than one CallDoWork notification after early_exit_requested // has been set, but our UIModelWorker is built to handle this case // nonetheless. It may be needed in the future, and since we support it and // it is not actually exercised in the wild this test is essential. // It is identical to above except we schedule more than one visitor. core_thread()->Start(); // Our ammunition. base::WaitableEvent fox1_ran(false, false); scoped_ptr<UIModelWorkerVisitor> fox1(new UIModelWorkerVisitor( &fox1_ran, false)); base::WaitableEvent fox2_ran(false, false); scoped_ptr<UIModelWorkerVisitor> fox2(new UIModelWorkerVisitor( &fox2_ran, false)); base::WaitableEvent fox3_ran(false, false); scoped_ptr<UIModelWorkerVisitor> fox3(new UIModelWorkerVisitor( &fox3_ran, false)); base::WaitableEvent* jobs[] = { &fox1_ran, &fox2_ran, &fox3_ran }; // The current message loop is not running, so queue a task to cause // UIModelWorker::Stop() to play a crucial role. See comment below. syncer_thread()->message_loop()->PostTask(FROM_HERE, base::Bind(&Syncer::SyncShare, base::Unretained(syncer()), fox1.get())); syncer_thread()->message_loop()->PostTask(FROM_HERE, base::Bind(&Syncer::SyncShare, base::Unretained(syncer()), fox2.get())); // This is what gets the core_thread blocked on the syncer_thread. core_thread()->message_loop()->PostTask(FROM_HERE, base::Bind(&FakeSyncapiShutdownCallback, syncer_thread(), base::Unretained(bmw()), static_cast<base::WaitableEvent**>(jobs), 3)); syncer_thread()->message_loop()->PostTask(FROM_HERE, base::Bind(&Syncer::SyncShare, base::Unretained(syncer()), fox3.get())); // This is what gets the UI thread blocked until NotifyExitRequested, // which is called when FakeSyncapiShutdownCallback runs and deletes the // syncer. bmw()->Stop(); // Was the thread killed? EXPECT_FALSE(syncer_thread()->IsRunning()); core_thread()->Stop(); }
40.41784
80
0.709258
[ "model" ]
285f5c5ba965b32f021a92573ca92874e3dc2b7c
14,132
cpp
C++
external/webkit/Source/WebCore/plugins/PluginPackage.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Source/WebCore/plugins/PluginPackage.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
Source/WebCore/plugins/PluginPackage.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
/* * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 Collabora Ltd. All rights reserved. * Copyright (C) 2009 Holger Hans Peter Freyther * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "PluginPackage.h" #include "MIMETypeRegistry.h" #include "PluginDatabase.h" #include "PluginDebug.h" #include "Timer.h" #include "npruntime_impl.h" #include <string.h> #include <wtf/OwnArrayPtr.h> #include <wtf/text/CString.h> namespace WebCore { PluginPackage::~PluginPackage() { // This destructor gets called during refresh() if PluginDatabase's // PluginSet hash is already populated, as it removes items from // the hash table. Calling the destructor on a loaded plug-in of // course would cause a crash, so we check to call unload before we // ASSERT. // FIXME: There is probably a better way to fix this. if (!m_loadCount) unloadWithoutShutdown(); else unload(); ASSERT(!m_isLoaded); } void PluginPackage::freeLibrarySoon() { ASSERT(!m_freeLibraryTimer.isActive()); ASSERT(m_module); ASSERT(!m_loadCount); m_freeLibraryTimer.startOneShot(0); } void PluginPackage::freeLibraryTimerFired(Timer<PluginPackage>*) { ASSERT(m_module); ASSERT(!m_loadCount); unloadModule(m_module); m_module = 0; } int PluginPackage::compare(const PluginPackage& compareTo) const { // Sort plug-ins that allow multiple instances first. bool AallowsMultipleInstances = !quirks().contains(PluginQuirkDontAllowMultipleInstances); bool BallowsMultipleInstances = !compareTo.quirks().contains(PluginQuirkDontAllowMultipleInstances); if (AallowsMultipleInstances != BallowsMultipleInstances) return AallowsMultipleInstances ? -1 : 1; // Sort plug-ins in a preferred path first. bool AisInPreferredDirectory = PluginDatabase::isPreferredPluginDirectory(parentDirectory()); bool BisInPreferredDirectory = PluginDatabase::isPreferredPluginDirectory(compareTo.parentDirectory()); if (AisInPreferredDirectory != BisInPreferredDirectory) return AisInPreferredDirectory ? -1 : 1; int diff = strcmp(name().utf8().data(), compareTo.name().utf8().data()); if (diff) return diff; diff = compareFileVersion(compareTo.version()); if (diff) return diff; return strcmp(parentDirectory().utf8().data(), compareTo.parentDirectory().utf8().data()); } PluginPackage::PluginPackage(const String& path, const time_t& lastModified) : m_isEnabled(true) , m_isLoaded(false) , m_loadCount(0) , m_path(path) , m_moduleVersion(0) , m_module(0) , m_lastModified(lastModified) , m_freeLibraryTimer(this, &PluginPackage::freeLibraryTimerFired) #if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) , m_infoIsFromCache(true) #endif { m_fileName = pathGetFileName(m_path); m_parentDirectory = m_path.left(m_path.length() - m_fileName.length() - 1); } #if !OS(SYMBIAN) void PluginPackage::unload() { if (!m_isLoaded) return; if (--m_loadCount > 0) return; m_NPP_Shutdown(); unloadWithoutShutdown(); } #endif // !OS(SYMBIAN) void PluginPackage::unloadWithoutShutdown() { if (!m_isLoaded) return; ASSERT(!m_loadCount); ASSERT(m_module); // <rdar://5530519>: Crash when closing tab with pdf file (Reader 7 only) // If the plugin has subclassed its parent window, as with Reader 7, we may have // gotten here by way of the plugin's internal window proc forwarding a message to our // original window proc. If we free the plugin library from here, we will jump back // to code we just freed when we return, so delay calling FreeLibrary at least until // the next message loop freeLibrarySoon(); m_isLoaded = false; } void PluginPackage::setEnabled(bool enabled) { m_isEnabled = enabled; } PassRefPtr<PluginPackage> PluginPackage::createPackage(const String& path, const time_t& lastModified) { RefPtr<PluginPackage> package = adoptRef(new PluginPackage(path, lastModified)); if (!package->fetchInfo()) return 0; return package.release(); } #if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) PassRefPtr<PluginPackage> PluginPackage::createPackageFromCache(const String& path, const time_t& lastModified, const String& name, const String& description, const String& mimeDescription) { RefPtr<PluginPackage> package = adoptRef(new PluginPackage(path, lastModified)); package->m_name = name; package->m_description = description; package->determineModuleVersionFromDescription(); package->setMIMEDescription(mimeDescription); package->m_infoIsFromCache = true; return package.release(); } #endif #if defined(XP_UNIX) void PluginPackage::determineQuirks(const String& mimeType) { if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType)) { // Because a single process cannot create multiple VMs, and we cannot reliably unload a // Java VM, we cannot unload the Java plugin, or we'll lose reference to our only VM m_quirks.add(PluginQuirkDontUnloadPlugin); // Setting the window region to an empty region causes bad scrolling repaint problems // with the Java plug-in. m_quirks.add(PluginQuirkDontClipToZeroRectWhenScrolling); return; } if (mimeType == "application/x-shockwave-flash") { static const PlatformModuleVersion flashTenVersion(0x0a000000); if (compareFileVersion(flashTenVersion) >= 0) { // Flash 10.0 b218 doesn't like having a NULL window handle m_quirks.add(PluginQuirkDontSetNullWindowHandleOnDestroy); #if PLATFORM(QT) m_quirks.add(PluginQuirkRequiresGtkToolKit); #endif } else { // Flash 9 and older requests windowless plugins if we return a mozilla user agent m_quirks.add(PluginQuirkWantsMozillaUserAgent); } #if PLATFORM(QT) // Flash will crash on repeated calls to SetWindow in windowed mode m_quirks.add(PluginQuirkDontCallSetWindowMoreThanOnce); #if CPU(X86_64) // 64-bit Flash freezes if right-click is sent in windowless mode m_quirks.add(PluginQuirkIgnoreRightClickInWindowlessMode); #endif #endif m_quirks.add(PluginQuirkRequiresDefaultScreenDepth); m_quirks.add(PluginQuirkThrottleInvalidate); m_quirks.add(PluginQuirkThrottleWMUserPlusOneMessages); m_quirks.add(PluginQuirkFlashURLNotifyBug); } #if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6) // Passing a 32-bit depth pixmap to NPAPI plugins is too inefficient. Instead, pass a X Pixmap // that has same depth as the screen depth since graphics operations are optimized // for this depth. m_quirks.add(PluginQuirkRequiresDefaultScreenDepth); #endif } #endif #if !OS(WINDOWS) void PluginPackage::determineModuleVersionFromDescription() { // It's a bit lame to detect the plugin version by parsing it // from the plugin description string, but it doesn't seem that // version information is available in any standardized way at // the module level, like in Windows if (m_description.isEmpty()) return; if (m_description.startsWith("Shockwave Flash") && m_description.length() >= 19) { // The flash version as a PlatformModuleVersion differs on Unix from Windows // since the revision can be larger than a 8 bits, so we allow it 16 here and // push the major/minor up 8 bits. Thus on Unix, Flash's version may be // 0x0a000000 instead of 0x000a0000. Vector<String> versionParts; m_description.substring(16).split(' ', /*allowEmptyEntries =*/ false, versionParts); if (versionParts.isEmpty()) return; if (versionParts.size() >= 1) { Vector<String> majorMinorParts; versionParts[0].split('.', majorMinorParts); if (majorMinorParts.size() >= 1) { bool converted = false; unsigned major = majorMinorParts[0].toUInt(&converted); if (converted) m_moduleVersion = (major & 0xff) << 24; } if (majorMinorParts.size() == 2) { bool converted = false; unsigned minor = majorMinorParts[1].toUInt(&converted); if (converted) m_moduleVersion |= (minor & 0xff) << 16; } } if (versionParts.size() >= 2) { String revision = versionParts[1]; if (revision.length() > 1 && (revision[0] == 'r' || revision[0] == 'b')) { revision.remove(0, 1); m_moduleVersion |= revision.toInt() & 0xffff; } } } } #endif #if ENABLE(NETSCAPE_PLUGIN_API) void PluginPackage::initializeBrowserFuncs() { memset(&m_browserFuncs, 0, sizeof(m_browserFuncs)); m_browserFuncs.size = sizeof(m_browserFuncs); m_browserFuncs.version = NPVersion(); m_browserFuncs.geturl = NPN_GetURL; m_browserFuncs.posturl = NPN_PostURL; m_browserFuncs.requestread = NPN_RequestRead; m_browserFuncs.newstream = NPN_NewStream; m_browserFuncs.write = NPN_Write; m_browserFuncs.destroystream = NPN_DestroyStream; m_browserFuncs.status = NPN_Status; m_browserFuncs.uagent = NPN_UserAgent; m_browserFuncs.memalloc = NPN_MemAlloc; m_browserFuncs.memfree = NPN_MemFree; m_browserFuncs.memflush = NPN_MemFlush; m_browserFuncs.reloadplugins = NPN_ReloadPlugins; m_browserFuncs.geturlnotify = NPN_GetURLNotify; m_browserFuncs.posturlnotify = NPN_PostURLNotify; m_browserFuncs.getvalue = NPN_GetValue; m_browserFuncs.setvalue = NPN_SetValue; m_browserFuncs.invalidaterect = NPN_InvalidateRect; m_browserFuncs.invalidateregion = NPN_InvalidateRegion; m_browserFuncs.forceredraw = NPN_ForceRedraw; m_browserFuncs.getJavaEnv = NPN_GetJavaEnv; m_browserFuncs.getJavaPeer = NPN_GetJavaPeer; m_browserFuncs.pushpopupsenabledstate = NPN_PushPopupsEnabledState; m_browserFuncs.poppopupsenabledstate = NPN_PopPopupsEnabledState; m_browserFuncs.pluginthreadasynccall = NPN_PluginThreadAsyncCall; m_browserFuncs.releasevariantvalue = _NPN_ReleaseVariantValue; m_browserFuncs.getstringidentifier = _NPN_GetStringIdentifier; m_browserFuncs.getstringidentifiers = _NPN_GetStringIdentifiers; m_browserFuncs.getintidentifier = _NPN_GetIntIdentifier; m_browserFuncs.identifierisstring = _NPN_IdentifierIsString; m_browserFuncs.utf8fromidentifier = _NPN_UTF8FromIdentifier; m_browserFuncs.intfromidentifier = _NPN_IntFromIdentifier; m_browserFuncs.createobject = _NPN_CreateObject; m_browserFuncs.retainobject = _NPN_RetainObject; m_browserFuncs.releaseobject = _NPN_ReleaseObject; m_browserFuncs.invoke = _NPN_Invoke; m_browserFuncs.invokeDefault = _NPN_InvokeDefault; m_browserFuncs.evaluate = _NPN_Evaluate; m_browserFuncs.getproperty = _NPN_GetProperty; m_browserFuncs.setproperty = _NPN_SetProperty; m_browserFuncs.removeproperty = _NPN_RemoveProperty; m_browserFuncs.hasproperty = _NPN_HasProperty; m_browserFuncs.hasmethod = _NPN_HasMethod; m_browserFuncs.setexception = _NPN_SetException; m_browserFuncs.enumerate = _NPN_Enumerate; m_browserFuncs.construct = _NPN_Construct; m_browserFuncs.getvalueforurl = NPN_GetValueForURL; m_browserFuncs.setvalueforurl = NPN_SetValueForURL; m_browserFuncs.getauthenticationinfo = NPN_GetAuthenticationInfo; } #endif #if ENABLE(PLUGIN_PACKAGE_SIMPLE_HASH) unsigned PluginPackage::hash() const { unsigned hashCodes[] = { m_path.impl()->hash(), m_lastModified }; return StringHasher::hashMemory<sizeof(hashCodes)>(hashCodes); } bool PluginPackage::equal(const PluginPackage& a, const PluginPackage& b) { return a.m_description == b.m_description; } #endif int PluginPackage::compareFileVersion(const PlatformModuleVersion& compareVersion) const { // return -1, 0, or 1 if plug-in version is less than, equal to, or greater than // the passed version #if OS(WINDOWS) if (m_moduleVersion.mostSig != compareVersion.mostSig) return m_moduleVersion.mostSig > compareVersion.mostSig ? 1 : -1; if (m_moduleVersion.leastSig != compareVersion.leastSig) return m_moduleVersion.leastSig > compareVersion.leastSig ? 1 : -1; #else if (m_moduleVersion != compareVersion) return m_moduleVersion > compareVersion ? 1 : -1; #endif return 0; } #if ENABLE(NETSCAPE_PLUGIN_METADATA_CACHE) bool PluginPackage::ensurePluginLoaded() { if (!m_infoIsFromCache) return m_isLoaded; m_quirks = PluginQuirkSet(); m_name = String(); m_description = String(); m_fullMIMEDescription = String(); m_moduleVersion = 0; return fetchInfo(); } #endif }
35.777215
189
0.717167
[ "vector" ]
2862051c2dcda68fdd88f0ca4fab78234eb5ba5d
4,512
cpp
C++
Dev_RESTClient/CCallSharpTest/CCallSharpTestDlg.cpp
caochunsheng/AutoOrderSystem
8607380f16bbf47da0112d1e3403cb98f073ba6f
[ "Apache-2.0" ]
1
2017-12-18T17:11:43.000Z
2017-12-18T17:11:43.000Z
Dev_RESTClient/CCallSharpTest/CCallSharpTestDlg.cpp
caochunsheng/AutoOrderSystem
8607380f16bbf47da0112d1e3403cb98f073ba6f
[ "Apache-2.0" ]
null
null
null
Dev_RESTClient/CCallSharpTest/CCallSharpTestDlg.cpp
caochunsheng/AutoOrderSystem
8607380f16bbf47da0112d1e3403cb98f073ba6f
[ "Apache-2.0" ]
3
2019-05-31T21:02:33.000Z
2021-12-28T11:48:59.000Z
// CCallSharpTestDlg.cpp : implementation file // #include "stdafx.h" #include "CCallSharpTest.h" #include "CCallSharpTestDlg.h" #include "afxdialogex.h" #include "RegisterSharpCOM.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #import "RESTClient.tlb" raw_interfaces_only using namespace RESTClient; // CCCallSharpTestDlg dialog CCCallSharpTestDlg::CCCallSharpTestDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CCCallSharpTestDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CCCallSharpTestDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_LOG, m_strLog); } BEGIN_MESSAGE_MAP(CCCallSharpTestDlg, CDialogEx) ON_BN_CLICKED(IDOK, &CCCallSharpTestDlg::OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, &CCCallSharpTestDlg::OnBnClickedCancel) ON_BN_CLICKED(IDC_BUTTON_STOCK, &CCCallSharpTestDlg::OnBnClickedButtonStock) ON_BN_CLICKED(IDC_BUTTON_UPLOAD, &CCCallSharpTestDlg::OnBnClickedButtonUpload) ON_BN_CLICKED(IDC_BUTTON_DOWNLOAD, &CCCallSharpTestDlg::OnBnClickedButtonDownload) END_MESSAGE_MAP() // CCCallSharpTestDlg message handlers BOOL CCCallSharpTestDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CRegisterSharpCOM::RegisterDotNetAssembly("RESTClient.dll", 2); return TRUE; // return TRUE unless you set the focus to a control } void CCCallSharpTestDlg::OnBnClickedOk() { // Initialize COM. HRESULT hr = CoInitialize(NULL); // Create the interface pointer. CString resultMsg = "Error"; IHoleLayoutPtr pIHole(__uuidof(HoleLayoutPreview)); if (pIHole) { //VARIANT_BOOL result; CComBSTR bstr_put("D:\\gitArtisman\\Dev_RESTClient\\design_to_cam.xml"); //VARIANT_BOOL result = pIHole->CreateHoleLayoutImage(&bstr_put, &result); ::SysFreeString(bstr_put); } // Uninitialize COM. CoUninitialize(); } void CCCallSharpTestDlg::OnBnClickedCancel() { // TODO: Add your control notification handler code here CDialogEx::OnCancel(); } void CCCallSharpTestDlg::OnBnClickedButtonStock() { HRESULT hr = CoInitialize(NULL); CString resultMsg = "Error"; IArtCloudPtr pIArtCloud(__uuidof(ArtCloudClass)); if (pIArtCloud) { CComBSTR bstrCncType("cnc"); //cnc or saw CComBSTR bstrXmlFile("D:\\temp\\NestingData.xml"); BSTR bstr_msg; VARIANT_BOOL result = pIArtCloud->CuttingStock(bstrCncType, bstrXmlFile, &bstr_msg); CString errMsg(bstr_msg); resultMsg = errMsg; ::SysFreeString(bstr_msg); } CoUninitialize(); if (resultMsg.IsEmpty()) AfxMessageBox(_T("Success")); else AfxMessageBox(resultMsg); } void CCCallSharpTestDlg::OnBnClickedButtonUpload() { //upload.exe /ServerRelPath:"\drawLibs\app" /LocalFullPath:"D:\test" /ServerProcessor:"Raw Copy" HRESULT hr = CoInitialize(NULL); CString resultMsg = "Error"; IArtCloudPtr pIArtCloud(__uuidof(ArtCloudClass)); if (pIArtCloud) { CComBSTR bstr_srvPath("/ServerRelPath:\"\\drawLibs\\app\""); CComBSTR bstr_clnPath("/LocalFullPath:\"D:\\test\""); CComBSTR bstr_processor("/ServerProcessor:\"Raw Copy\""); BSTR bstr_msg; VARIANT_BOOL result = pIArtCloud->Upload(bstr_srvPath, bstr_clnPath, bstr_processor, &bstr_msg); CString errMsg(bstr_msg); resultMsg = errMsg; ::SysFreeString(bstr_msg); } CoUninitialize(); if (resultMsg.IsEmpty()) AfxMessageBox(_T("Success")); else AfxMessageBox(resultMsg); } void CCCallSharpTestDlg::OnBnClickedButtonDownload() { //download.exe /ServerRelPath:"\drawLibs\app" /LocalFullPath:"D:\test\app" /ServerProcessor:"Raw Copy" HRESULT hr = CoInitialize(NULL); CString resultMsg = "Error"; IArtCloudPtr pIArtCloud(__uuidof(ArtCloudClass)); if (pIArtCloud) { //CComBSTR bstr_srvPath("/ServerRelPath:\"\\drawLibs\\app\""); CComBSTR bstr_clnPath("/LocalFullPath:\"D:\\test\\models\\geometry\""); //CComBSTR bstr_processor("/ServerProcessor:\"Raw Copy\""); CComBSTR bstr_srvPath("/ServerRelPath:\"\\CADM\\SVG\\geometry\""); CComBSTR bstr_processor("/ServerProcessor:\"CADM Models\""); BSTR bstr_msg; VARIANT_BOOL result = pIArtCloud->Download(bstr_srvPath, bstr_clnPath, bstr_processor, &bstr_msg); CString errMsg(bstr_msg); resultMsg = errMsg; ::SysFreeString(bstr_msg); } CoUninitialize(); if (resultMsg.IsEmpty()) AfxMessageBox(_T("Success")); else AfxMessageBox(resultMsg); }
26.698225
105
0.755098
[ "geometry" ]
2863a72c68ba47bbeefbd272c41e1f280984e450
3,601
cpp
C++
4. Алгоритмы на графах/39. Сеть дорог #1586/[OK]228776.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
4. Алгоритмы на графах/39. Сеть дорог #1586/[OK]228776.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
4. Алгоритмы на графах/39. Сеть дорог #1586/[OK]228776.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include <iostream> #include <fstream> #include <vector> #include <queue> using namespace std; struct Edge { int x; int y; long long c; long long p; long long f = 0; Edge *r; Edge(int x, int y, long long c, long long p) : x(x), y(y), c(c), p(p) {}; }; vector<Edge*> a[111], b[111], res; int ms[111][111]; long long d[111]; Edge* p[111]; int n, m, sv, tv, x, y, c; Edge *edge; long long bfs(int s, int t) { long long mn = LLONG_MAX / 10; queue<int> q; Edge* path[111]; for (int i = 1; i <= n; i++) path[i] = 0; q.push(s); while (!q.empty()) { int v = q.front(); q.pop(); if (v == t) { res.clear(); while (v != s) { res.push_back(path[v]); mn = min(mn, path[v]->c - path[v]->f); v = path[v]->x; } for (Edge* edge : res) { edge->f += mn; edge->r->f -= mn; } return mn; } for (int i = 0; i < a[v].size(); i++) { edge = a[v][i]; if (!path[edge->y] && edge->c - edge->f > 0) { path[edge->y] = edge; q.push(edge->y); } } } return 0; } long long findFlow(int s, int t) { long long flow = 0; long long mn = bfs(s, t); while (mn) { flow += mn; mn = bfs(s, t); } return flow; } bool findCycle(int s) { for (int i = 1; i <= n; i++) { d[i] = 0; p[i] = 0; } int f; Edge* edge; for (int z = 1; z <= n; z++) { f = -1; for (int i = 1; i <= n; i++) for (int j = 0; j < a[i].size(); j++) { edge = a[i][j]; if (d[edge->y] > d[edge->x] + edge->p && edge->c - edge->f > 0) { d[edge->y] = max(d[edge->x] + edge->p, LLONG_MIN / 10); p[edge->y] = edge; f = edge->y; } } } res.clear(); if (f != -1) { int y = f; for (int i = 1; i <= n; i++) y = p[y]->x; for (int cur = y; ; cur = p[cur]->x) { res.push_back(p[cur]); if (cur == y && res.size() > 1) break; } if (res.size() > 0) res.pop_back(); long long addFlow = LLONG_MAX / 10; for (int i = 0; i < res.size(); i++) addFlow = min(addFlow, res[i]->c - res[i]->f); for (int i = 0; i < res.size(); i++) { res[i]->f += addFlow; res[i]->r->f -= addFlow; } return true; } return false; } long long minCostFlow(int s, int t) { while (findCycle(s)) {} long long minCost = 0; for (int i = 1; i <= n; i++) for (int j = 0; j < a[i].size(); j++) minCost += a[i][j]->p * a[i][j]->f; return minCost / 2; } int main() { ifstream cin("input.txt"); ofstream cout("output.txt"); int p; cin >> n >> m >> sv >> tv; for (int i = 0; i < m; i++) { cin >> x >> y >> c >> p; Edge *e1 = new Edge(x, y, c, p); Edge *e2 = new Edge(y, x, 0, -p); a[x].push_back(e1); a[y].push_back(e2); e1->r = e2; e2->r = e1; } long long flow = findFlow(sv, tv); long long minCost = minCostFlow(sv, tv); for (int i = 1; i <= n; i++) { for (int j = 0; j < a[i].size(); j++) { a[i][j]->f = 0; b[i].push_back(a[i][j]); } a[i].clear(); } int mm = m; m = 0; while (!cin.eof()) { cin >> x >> y; m++; ms[x][y] = 1; } for (int i = 1; i <= n; i++) { for (int j = 0; j < b[i].size(); j++) if (ms[i][b[i][j]->y] == 1 || ms[b[i][j]->y][i] == 1) { edge = b[i][j]; a[i].push_back(edge); } } long long sugFlow = findFlow(sv, tv); long long sugCost = minCostFlow(sv, tv); if (sugCost > minCost || sugFlow != flow) { cout << "No" << '\n' << flow << '\n' << minCost << '\n' << sugFlow << '\n' << sugCost << endl; } else { cout << "Yes" << '\n' << flow << '\n' << minCost << endl; } return 0; }
21.824242
97
0.452374
[ "vector" ]
286636d37f615c08ab0518154040702eb4329a7f
14,332
cc
C++
chainerx_cc/chainerx/cuda/cuda_device/batch_norm.cc
nishnik/chainer
03fc8a54b657f703855b25cbe53f56fda1295e76
[ "MIT" ]
1
2020-08-12T23:08:41.000Z
2020-08-12T23:08:41.000Z
chainerx_cc/chainerx/cuda/cuda_device/batch_norm.cc
nishnik/chainer
03fc8a54b657f703855b25cbe53f56fda1295e76
[ "MIT" ]
null
null
null
chainerx_cc/chainerx/cuda/cuda_device/batch_norm.cc
nishnik/chainer
03fc8a54b657f703855b25cbe53f56fda1295e76
[ "MIT" ]
null
null
null
#include "chainerx/cuda/cuda_device.h" #include <cstdint> #include <memory> #include <cudnn.h> #include "chainerx/array.h" #include "chainerx/axes.h" #include "chainerx/backend_util.h" #include "chainerx/cuda/cuda_set_device_scope.h" #include "chainerx/cuda/cudnn.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/error.h" #include "chainerx/macro.h" #include "chainerx/routines/creation.h" #include "chainerx/scalar.h" #include "chainerx/shape.h" namespace chainerx { namespace cuda { namespace { // TODO(sonots): Support other than 4, 5 dimensional arrays by reshaping into 4-dimensional arrays as Chainer does. cudnnBatchNormMode_t GetBatchNormMode(const Axes& axis) { if (axis.ndim() == 1 && axis[0] == 0) { // (1, channels, (depth, )height, width) return CUDNN_BATCHNORM_PER_ACTIVATION; } if ((axis.ndim() == 3 && axis[0] == 0 && axis[1] == 2 && axis[2] == 3) || (axis.ndim() == 4 && axis[0] == 0 && axis[1] == 2 && axis[2] == 3 && axis[3] == 4)) { // (1, channels, (1, )1, 1) // TODO(hvy): Consider CUDNN_BATCHNORM_SPATIAL_PERSISTENT if we can afford to check for overflow, with or without blocking. return CUDNN_BATCHNORM_SPATIAL; } throw DimensionError{"Invalid axis for BatchNorm using cuDNN ", axis, ". Expected 1, 3 or 4 dimensions."}; } // Helper function to update the running mean and running variance. void UpdateRunning(const Array& running, const Array& running_updated) { CHAINERX_ASSERT(running.IsContiguous()); CHAINERX_ASSERT(running_updated.IsContiguous()); CHAINERX_ASSERT(&running.device() == &running_updated.device()); CHAINERX_ASSERT( (running.dtype() == running_updated.dtype()) == (internal::GetRawOffsetData(running) == internal::GetRawOffsetData(running_updated))); if (running.dtype() == running_updated.dtype()) { // Assume that running already holds the updated values. return; } // The running values must be written back. const Array& running_casted_back = running_updated.AsType(running.dtype()); Device& device = running.device(); device.MemoryCopyFrom( internal::GetRawOffsetData(running), internal::GetRawOffsetData(running_casted_back), running.GetNBytes(), device); } // Derives a secondary tensor descriptor for the batch normalization parameters. cuda_internal::CudnnTensorDescriptor DeriveBatchNormTensorDescriptor( const cuda_internal::CudnnTensorDescriptor& x_desc, cudnnBatchNormMode_t mode) { cuda_internal::CudnnTensorDescriptor derive_desc{}; CheckCudnnError(cudnnDeriveBNTensorDescriptor(*derive_desc, *x_desc, mode)); return derive_desc; } class CudaBatchNormForwardBackward : public chainerx::GenericBatchNormForwardBackward { public: explicit CudaBatchNormForwardBackward( cuda_internal::CudnnHandle& cudnn_handle, const Array& running_mean, const Array& running_var, Scalar eps, Scalar decay, const Axes& axis) : GenericBatchNormForwardBackward{running_mean, running_var, eps, decay, axis}, cudnn_handle_{cudnn_handle} { if (static_cast<double>(eps) < CUDNN_BN_MIN_EPSILON) { throw CudnnError{"Minimum allowed epsilon is ", CUDNN_BN_MIN_EPSILON, " but found ", eps, "."}; } if (!running_mean.IsContiguous()) { throw DeviceError{"Running mean must to be contiguous for cuDNN to update it in-place."}; } if (!running_var.IsContiguous()) { throw DeviceError{"Running variance must to be contiguous for cuDNN to update it in-place."}; } } Array Forward(const Array& x, const Array& gamma, const Array& beta) override { if (CHAINERX_DEBUG) { Shape reduced_shape = internal::ReduceShape(x.shape(), axis(), true); CHAINERX_ASSERT(gamma.shape() == reduced_shape); CHAINERX_ASSERT(beta.shape() == reduced_shape); int64_t reduced_total_size = reduced_shape.GetTotalSize(); CHAINERX_ASSERT(running_mean().GetTotalSize() == reduced_total_size); CHAINERX_ASSERT(running_var().GetTotalSize() == reduced_total_size); CHAINERX_ASSERT(&x.device() == &gamma.device()); CHAINERX_ASSERT(&x.device() == &beta.device()); CHAINERX_ASSERT(&x.device() == &running_mean().device()); CHAINERX_ASSERT(&x.device() == &running_var().device()); CHAINERX_ASSERT(GetKind(x.dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(gamma.dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(beta.dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(running_mean().dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(running_var().dtype()) == DtypeKind::kFloat); } Device& device = x.device(); Dtype dtype = x.dtype(); CudaSetDeviceScope scope{device.index()}; Array x_cont = internal::AsContiguous(x); cuda_internal::CudnnTensorDescriptor x_desc{x_cont}; cudnnBatchNormMode_t mode = GetBatchNormMode(axis()); // Let cuDNN decide the parameter dtype based on the input and batch normalization mode. cuda_internal::CudnnTensorDescriptor gamma_beta_mean_var_desc = DeriveBatchNormTensorDescriptor(x_desc, mode); Dtype gamma_beta_mean_var_dtype = gamma_beta_mean_var_desc.GetDtype(); Array gamma_casted_cont = internal::AsContiguous(gamma, gamma_beta_mean_var_dtype); Array beta_casted_cont = internal::AsContiguous(beta, gamma_beta_mean_var_dtype); CHAINERX_ASSERT(running_mean().IsContiguous()); CHAINERX_ASSERT(running_var().IsContiguous()); // Convert parameter dtypes if they do not match the dtype expected by cuDNN. const Array& running_mean_casted = running_mean().dtype() != gamma_beta_mean_var_dtype ? running_mean().AsType(gamma_beta_mean_var_dtype) : running_mean(); const Array& running_var_casted = running_var().dtype() != gamma_beta_mean_var_dtype ? running_var().AsType(gamma_beta_mean_var_dtype) : running_var(); Array out = EmptyLike(x, device); Array x_mean = EmptyLike(gamma_casted_cont, device); Array x_inv_std = EmptyLike(gamma_casted_cont, device); cudnn_handle_.Call( cudnnBatchNormalizationForwardTraining, mode, cuda_internal::GetCudnnCoefficientPtr<1>(dtype), cuda_internal::GetCudnnCoefficientPtr<0>(dtype), *x_desc, internal::GetRawOffsetData(x_cont), *x_desc, internal::GetRawOffsetData(out), *gamma_beta_mean_var_desc, internal::GetRawOffsetData(gamma_casted_cont), internal::GetRawOffsetData(beta_casted_cont), 1.0 - static_cast<double>(decay()), internal::GetRawOffsetData(running_mean_casted), internal::GetRawOffsetData(running_var_casted), static_cast<double>(eps()), internal::GetRawOffsetData(x_mean), internal::GetRawOffsetData(x_inv_std)); // When data type of parameters is converted, say, from fp16 // to fp32, the values of fp32 arrays of running_mean and // running_var updated by batchNormalizationForwardTraining // must be explicitly written back to their original fp16 arrays. UpdateRunning(running_mean(), running_mean_casted); UpdateRunning(running_var(), running_var_casted); SetForwardResults(std::move(x_cont), gamma, std::move(x_mean), std::move(x_inv_std), beta.dtype()); return out; } std::array<Array, 3> Backward(const Array& gout) override { const Array& x_cont = this->x(); const Array& gamma = this->gamma(); const Array& x_mean = this->x_mean(); const Array& x_inv_std = this->x_inv_std(); if (CHAINERX_DEBUG) { Shape reduced_shape = internal::ReduceShape(x_cont.shape(), axis(), true); CHAINERX_ASSERT(reduced_shape == gamma.shape()); CHAINERX_ASSERT(x_cont.shape() == gout.shape()); CHAINERX_ASSERT(internal::GetArrayBody(x_mean) != nullptr); CHAINERX_ASSERT(internal::GetArrayBody(x_inv_std) != nullptr); CHAINERX_ASSERT(&x_cont.device() == &gamma.device()); CHAINERX_ASSERT(&x_cont.device() == &gout.device()); CHAINERX_ASSERT(&x_cont.device() == &x_mean.device()); CHAINERX_ASSERT(&x_cont.device() == &x_inv_std.device()); CHAINERX_ASSERT(x_cont.IsContiguous()); } Device& device = x_cont.device(); Dtype dtype = x_cont.dtype(); CudaSetDeviceScope scope{device.index()}; Array gout_cont = internal::AsContiguous(gout); Array gx = EmptyLike(x_cont, device); cuda_internal::CudnnTensorDescriptor x_desc{x_cont}; cudnnBatchNormMode_t mode = GetBatchNormMode(axis()); cuda_internal::CudnnTensorDescriptor gamma_beta_mean_var_desc = DeriveBatchNormTensorDescriptor(x_desc, mode); Dtype gamma_beta_mean_var_dtype = gamma_beta_mean_var_desc.GetDtype(); Shape gamma_beta_mean_var_shape = internal::ReduceShape(x_cont.shape(), axis(), true); Array gamma_casted_cont = internal::AsContiguous(gamma, gamma_beta_mean_var_dtype); Array ggamma = Empty(gamma_beta_mean_var_shape, gamma_beta_mean_var_dtype, device); Array gbeta = Empty(gamma_beta_mean_var_shape, gamma_beta_mean_var_dtype, device); CHAINERX_ASSERT(gamma_beta_mean_var_dtype == x_mean.dtype()); CHAINERX_ASSERT(gamma_beta_mean_var_dtype == x_inv_std.dtype()); CHAINERX_ASSERT(x_mean.IsContiguous()); CHAINERX_ASSERT(x_inv_std.IsContiguous()); cudnn_handle_.Call( cudnnBatchNormalizationBackward, mode, cuda_internal::GetCudnnCoefficientPtr<1>(dtype), cuda_internal::GetCudnnCoefficientPtr<0>(dtype), cuda_internal::GetCudnnCoefficientPtr<1>(dtype), cuda_internal::GetCudnnCoefficientPtr<0>(dtype), *x_desc, internal::GetRawOffsetData(x_cont), *x_desc, internal::GetRawOffsetData(gout_cont), *x_desc, internal::GetRawOffsetData(gx), *gamma_beta_mean_var_desc, internal::GetRawOffsetData(gamma_casted_cont), internal::GetRawOffsetData(ggamma), internal::GetRawOffsetData(gbeta), static_cast<double>(eps()), internal::GetRawOffsetData(x_mean), internal::GetRawOffsetData(x_inv_std)); if (ggamma.dtype() != gamma.dtype()) { ggamma = ggamma.AsType(gamma.dtype()); } if (gbeta.dtype() != beta_dtype()) { gbeta = gbeta.AsType(beta_dtype()); } return {std::move(gx), std::move(ggamma), std::move(gbeta)}; } private: cuda_internal::CudnnHandle& cudnn_handle_; }; } // namespace std::unique_ptr<BatchNormForwardBackward> CudaDevice::GetBatchNormForwardBackward( const Array& running_mean, const Array& running_var, Scalar eps, Scalar decay, const Axes& axis) { return std::make_unique<CudaBatchNormForwardBackward>(cudnn_handle(), running_mean, running_var, eps, decay, axis); } Array CudaDevice::FixedBatchNorm( const Array& x, const Array& gamma, const Array& beta, const Array& mean, const Array& var, Scalar eps, const Axes& axis) { if (static_cast<double>(eps) < CUDNN_BN_MIN_EPSILON) { throw CudnnError{"Minimum allowed epsilon is ", CUDNN_BN_MIN_EPSILON, " but found ", eps, "."}; } CudaSetDeviceScope scope{index()}; if (CHAINERX_DEBUG) { Shape reduced_shape = internal::ReduceShape(x.shape(), axis, true); CHAINERX_ASSERT(gamma.shape() == reduced_shape); CHAINERX_ASSERT(beta.shape() == reduced_shape); CHAINERX_ASSERT(mean.shape() == reduced_shape); CHAINERX_ASSERT(var.shape() == reduced_shape); CHAINERX_ASSERT(&x.device() == &gamma.device()); CHAINERX_ASSERT(&x.device() == &beta.device()); CHAINERX_ASSERT(&x.device() == &mean.device()); CHAINERX_ASSERT(&x.device() == &var.device()); CHAINERX_ASSERT(GetKind(x.dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(gamma.dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(beta.dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(mean.dtype()) == DtypeKind::kFloat); CHAINERX_ASSERT(GetKind(var.dtype()) == DtypeKind::kFloat); } Array x_cont = internal::AsContiguous(x); cuda_internal::CudnnTensorDescriptor x_desc{x_cont}; cudnnBatchNormMode_t mode = GetBatchNormMode(axis); cuda_internal::CudnnTensorDescriptor gamma_beta_mean_var_desc = DeriveBatchNormTensorDescriptor(x_desc, mode); Dtype gamma_beta_mean_var_dtype = gamma_beta_mean_var_desc.GetDtype(); Array gamma_casted_cont = internal::AsContiguous(gamma, gamma_beta_mean_var_dtype); Array beta_casted_cont = internal::AsContiguous(beta, gamma_beta_mean_var_dtype); Array mean_casted_cont = internal::AsContiguous(mean, gamma_beta_mean_var_dtype); Array var_casted_cont = internal::AsContiguous(var, gamma_beta_mean_var_dtype); Array out = EmptyLike(x, x.device()); cudnn_handle_.Call( cudnnBatchNormalizationForwardInference, GetBatchNormMode(axis), cuda_internal::GetCudnnCoefficientPtr<1>(x.dtype()), cuda_internal::GetCudnnCoefficientPtr<0>(x.dtype()), *x_desc, internal::GetRawOffsetData(x_cont), *x_desc, internal::GetRawOffsetData(out), *gamma_beta_mean_var_desc, internal::GetRawOffsetData(gamma_casted_cont), internal::GetRawOffsetData(beta_casted_cont), internal::GetRawOffsetData(mean_casted_cont), internal::GetRawOffsetData(var_casted_cont), static_cast<double>(eps)); return out; } } // namespace cuda } // namespace chainerx
45.069182
136
0.66369
[ "shape" ]
286673a5c122bfe39c76addd19d524b8328a2a55
16,931
hpp
C++
src/ttauri/text/editable_text.hpp
prollings/ttauri
51aa748eb52b72a06038ffa12952523cf3d4f9b6
[ "BSL-1.0" ]
null
null
null
src/ttauri/text/editable_text.hpp
prollings/ttauri
51aa748eb52b72a06038ffa12952523cf3d4f9b6
[ "BSL-1.0" ]
null
null
null
src/ttauri/text/editable_text.hpp
prollings/ttauri
51aa748eb52b72a06038ffa12952523cf3d4f9b6
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2019-2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #pragma once #include "attributed_grapheme.hpp" #include "shaped_text.hpp" #include "font.hpp" #include <string> #include <vector> namespace tt { class editable_text { std::vector<attributed_grapheme> text; shaped_text _shapedText; /** The maximum width when wrapping text. * For single line text editing, we should never wrap. */ float width = 0.0f; /** Insert-mode vs overwrite-mode. */ bool insertMode = true; /** The index into the text where the cursor is located. */ ssize_t cursorIndex = 0; /** The index into the text where the start of the selection is located. * When no text is selected the cursorIndex and selectionIndex are equal. */ ssize_t selectionIndex = 0; text_style currentStyle; /** Partial grapheme is inserted before cursorIndex. */ bool hasPartialgrapheme = false; public: editable_text(text_style style) : text(), _shapedText(), currentStyle(style) { } [[nodiscard]] operator std::string() const noexcept { auto r = std::string{}; for (ttlet &c : text) { r += to_string(c.grapheme.NFC()); } return r; } editable_text &operator=(std::string_view str) noexcept { cancelPartialgrapheme(); gstring gstr = to_gstring(str); text.clear(); text.reserve(std::ssize(gstr)); for (ttlet &g : gstr) { text.emplace_back(g, currentStyle); } selectionIndex = cursorIndex = 0; tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); updateshaped_text(); return *this; } /** Update the shaped text after changed to text. */ void updateshaped_text() noexcept { auto text_ = text; // Make sure there is an end-paragraph marker in the text. // This allows the shapedText to figure out the style of the text of an empty paragraph. if (std::ssize(text) == 0) { text_.emplace_back(grapheme::PS(), currentStyle, 0); } else { text_.emplace_back(grapheme::PS(), text_.back().style, 0); } _shapedText = shaped_text(text_, width, alignment::top_left, false); } [[nodiscard]] shaped_text shapedText() const noexcept { return _shapedText; } void setWidth(float _width) noexcept { width = _width; updateshaped_text(); } void setCurrentStyle(text_style style) noexcept { this->currentStyle = style; } /** Change the text style of all graphemes. */ void setStyleOfAll(text_style style) noexcept { setCurrentStyle(style); for (auto &c: text) { c.style = style; } updateshaped_text(); } size_t size() const noexcept { return text.size(); } /** Return the text iterator at index. */ decltype(auto) it(ssize_t index) noexcept { tt_axiom(index >= 0); // Index should never be at text.cend(); tt_axiom(index < std::ssize(text)); return text.begin() + index; } /** Return the text iterator at index. */ decltype(auto) cit(ssize_t index) const noexcept { tt_axiom(index >= 0); // Index should never be beyond text.cend(); tt_axiom(index <= std::ssize(text)); return text.cbegin() + index; } decltype(auto) it(ssize_t index) const noexcept { return cit(index); } /** Get carets at the cursor position. */ aarect partialgraphemeCaret() const noexcept { if (hasPartialgrapheme) { tt_axiom(cursorIndex != 0); return _shapedText.leftToRightCaret(cursorIndex - 1, false); } else { return {}; } } /** Get carets at the cursor position. */ aarect leftToRightCaret() const noexcept { return _shapedText.leftToRightCaret(cursorIndex, insertMode); } /** Get a set of rectangles for which text is selected. */ std::vector<aarect> selectionRectangles() const noexcept { auto r = std::vector<aarect>{}; if (selectionIndex < cursorIndex) { r = _shapedText.selectionRectangles(selectionIndex, cursorIndex); } else if (selectionIndex > cursorIndex) { r = _shapedText.selectionRectangles(cursorIndex, selectionIndex); } return r; } /** Delete a selection. * This function should be called when a selection is active while new text * is being inserted. */ void deleteSelection() noexcept { if (selectionIndex < cursorIndex) { text.erase(cit(selectionIndex), cit(cursorIndex)); cursorIndex = selectionIndex; updateshaped_text(); } else if (selectionIndex > cursorIndex) { text.erase(cit(cursorIndex), cit(selectionIndex)); selectionIndex = cursorIndex; updateshaped_text(); } } /*! Find the nearest character at position and return it's index. */ ssize_t characterIndexAtPosition(f32x4 position) const noexcept; void setmouse_cursorAtCoordinate(f32x4 coordinate) noexcept { if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharAtCoordinate(coordinate)) { selectionIndex = cursorIndex = *newmouse_cursorPosition; tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); } } void selectWordAtCoordinate(f32x4 coordinate) noexcept { if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharAtCoordinate(coordinate)) { std::tie(selectionIndex, cursorIndex) = _shapedText.indicesOfWord(*newmouse_cursorPosition); tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); } } void selectParagraphAtCoordinate(f32x4 coordinate) noexcept { if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharAtCoordinate(coordinate)) { std::tie(selectionIndex, cursorIndex) = _shapedText.indicesOfParagraph(*newmouse_cursorPosition); tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); } } void dragmouse_cursorAtCoordinate(f32x4 coordinate) noexcept { if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharAtCoordinate(coordinate)) { cursorIndex = *newmouse_cursorPosition; tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); } } void dragWordAtCoordinate(f32x4 coordinate) noexcept { if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharAtCoordinate(coordinate)) { ttlet [a, b] = _shapedText.indicesOfWord(*newmouse_cursorPosition); if (selectionIndex <= cursorIndex) { if (a < selectionIndex) { // Reverse selection selectionIndex = cursorIndex; cursorIndex = a; } else { cursorIndex = b; } } else { if (b > selectionIndex) { // Reverse selection selectionIndex = cursorIndex; cursorIndex = b; } else { cursorIndex = a; } } tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); } } void dragParagraphAtCoordinate(f32x4 coordinate) noexcept { if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharAtCoordinate(coordinate)) { ttlet [a, b] = _shapedText.indicesOfParagraph(*newmouse_cursorPosition); if (selectionIndex <= cursorIndex) { if (a < selectionIndex) { // Reverse selection selectionIndex = cursorIndex; cursorIndex = a; } else { cursorIndex = b; } } else { if (b > selectionIndex) { // Reverse selection selectionIndex = cursorIndex; cursorIndex = b; } else { cursorIndex = a; } } tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); } } void cancelPartialgrapheme() noexcept { if (hasPartialgrapheme) { tt_axiom(cursorIndex >= 1); selectionIndex = --cursorIndex; tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); text.erase(cit(cursorIndex)); hasPartialgrapheme = false; updateshaped_text(); } } /*! Insert a temporary partial character. * This partial character is currently being constructed by the operating system. * * Since the insertion has not been completed any selected text should not yet be deleted. */ void insertPartialgrapheme(grapheme character) noexcept { cancelPartialgrapheme(); deleteSelection(); text.emplace(cit(cursorIndex), character, currentStyle); selectionIndex = ++cursorIndex; tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); hasPartialgrapheme = true; updateshaped_text(); } /*! insert character at the cursor position. * Selected text will be deleted. */ void insertgrapheme(grapheme character) noexcept { cancelPartialgrapheme(); deleteSelection(); if (!insertMode) { handle_event(command::text_delete_char_next); } text.emplace(cit(cursorIndex), character, currentStyle); selectionIndex = ++cursorIndex; tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); updateshaped_text(); } void handlePaste(std::string str) noexcept { cancelPartialgrapheme(); deleteSelection(); gstring gstr = to_gstring(str); auto str_attr = std::vector<attributed_grapheme>{}; str_attr.reserve(std::ssize(gstr)); for (ttlet &g: gstr) { str_attr.emplace_back(g, currentStyle); } text.insert(cit(cursorIndex), str_attr.cbegin(), str_attr.cend()); selectionIndex = cursorIndex += std::ssize(str_attr); tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); updateshaped_text(); } std::string handleCopy() noexcept { auto r = std::string{}; if (selectionIndex < cursorIndex) { r.reserve(cursorIndex - selectionIndex); for (auto i = cit(selectionIndex); i != cit(cursorIndex); ++i) { r += to_string(i->grapheme); } } else if (selectionIndex > cursorIndex) { r.reserve(selectionIndex - cursorIndex); for (auto i = cit(cursorIndex); i != cit(selectionIndex); ++i) { r += to_string(i->grapheme); } } return r; } std::string handleCut() noexcept { auto r = handleCopy(); cancelPartialgrapheme(); deleteSelection(); return r; } bool handle_event(command command) noexcept { auto handled = false; tt_axiom(cursorIndex <= std::ssize(text)); cancelPartialgrapheme(); switch (command) { case command::text_cursor_char_left: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharOnTheLeft(cursorIndex)) { // XXX Change currentStyle based on the grapheme at the new cursor position. selectionIndex = cursorIndex = *newmouse_cursorPosition; } break; case command::text_cursor_char_right: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharOnTheRight(cursorIndex)) { selectionIndex = cursorIndex = *newmouse_cursorPosition; } break; case command::text_cursor_word_left: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfWordOnTheLeft(cursorIndex)) { selectionIndex = cursorIndex = *newmouse_cursorPosition; } break; case command::text_cursor_word_right: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfWordOnTheRight(cursorIndex)) { selectionIndex = cursorIndex = *newmouse_cursorPosition; } break; case command::text_cursor_line_end: handled = true; selectionIndex = cursorIndex = size() - 1; break; case command::text_cursor_line_begin: handled = true; selectionIndex = cursorIndex = 0; break; case command::text_select_char_left: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharOnTheLeft(cursorIndex)) { cursorIndex = *newmouse_cursorPosition; } break; case command::text_select_char_right: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfCharOnTheRight(cursorIndex)) { cursorIndex = *newmouse_cursorPosition; } break; case command::text_select_word_left: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfWordOnTheLeft(cursorIndex)) { cursorIndex = *newmouse_cursorPosition; } break; case command::text_select_word_right: handled = true; if (ttlet newmouse_cursorPosition = _shapedText.indexOfWordOnTheRight(cursorIndex)) { cursorIndex = *newmouse_cursorPosition; } break; case command::text_select_word: handled = true; std::tie(selectionIndex, cursorIndex) = _shapedText.indicesOfWord(cursorIndex); break; case command::text_select_line_end: handled = true; cursorIndex = size() - 1; break; case command::text_select_line_begin: handled = true; cursorIndex = 0; break; case command::text_select_document: handled = true; selectionIndex = 0; cursorIndex = size() - 1; // Upto end-of-paragraph marker. break; case command::text_mode_insert: handled = true; insertMode = !insertMode; break; case command::text_delete_char_prev: handled = true; if (cursorIndex != selectionIndex) { deleteSelection(); } else if (cursorIndex >= 1) { selectionIndex = --cursorIndex; text.erase(cit(cursorIndex)); updateshaped_text(); } break; case command::text_delete_char_next: handled = true; if (cursorIndex != selectionIndex) { deleteSelection(); } else if (cursorIndex < (std::ssize(text) - 1)) { // Don't delete the trailing paragraph separator. text.erase(cit(cursorIndex)); updateshaped_text(); } default:; } tt_axiom(selectionIndex >= 0); tt_axiom(selectionIndex <= std::ssize(text)); tt_axiom(cursorIndex >= 0); tt_axiom(cursorIndex <= std::ssize(text)); return handled; } }; }
31.885122
109
0.579588
[ "vector" ]
286807e50321e4659331fd3e2cbb4303b70b4be5
31,259
cc
C++
test/call_test.cc
na-g/webrtc-upstream-tracking
41b5296405e2cc37b838c2f7490d02130387b294
[ "BSD-3-Clause" ]
null
null
null
test/call_test.cc
na-g/webrtc-upstream-tracking
41b5296405e2cc37b838c2f7490d02130387b294
[ "BSD-3-Clause" ]
null
null
null
test/call_test.cc
na-g/webrtc-upstream-tracking
41b5296405e2cc37b838c2f7490d02130387b294
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/call_test.h" #include <algorithm> #include "absl/memory/memory.h" #include "api/audio_codecs/builtin_audio_decoder_factory.h" #include "api/audio_codecs/builtin_audio_encoder_factory.h" #include "api/video_codecs/video_encoder_config.h" #include "call/fake_network_pipe.h" #include "call/rtp_transport_controller_send.h" #include "call/simulated_network.h" #include "modules/audio_mixer/audio_mixer_impl.h" #include "modules/congestion_controller/bbr/bbr_factory.h" #include "rtc_base/checks.h" #include "rtc_base/event.h" #include "rtc_base/experiments/congestion_controller_experiment.h" #include "test/fake_encoder.h" #include "test/testsupport/fileutils.h" namespace webrtc { namespace test { namespace { const int kVideoRotationRtpExtensionId = 4; } CallTest::CallTest() : clock_(Clock::GetRealTimeClock()), send_event_log_(RtcEventLog::CreateNull()), recv_event_log_(RtcEventLog::CreateNull()), sender_call_transport_controller_(nullptr), audio_send_config_(/*send_transport=*/nullptr, /*media_transport=*/nullptr), audio_send_stream_(nullptr), bbr_network_controller_factory_(new BbrNetworkControllerFactory()), fake_encoder_factory_([this]() { std::unique_ptr<FakeEncoder> fake_encoder; if (video_encoder_configs_[0].codec_type == kVideoCodecVP8) { fake_encoder = absl::make_unique<FakeVP8Encoder>(clock_); } else { fake_encoder = absl::make_unique<FakeEncoder>(clock_); } fake_encoder->SetMaxBitrate(fake_encoder_max_bitrate_); return fake_encoder; }), fake_decoder_factory_([]() { return absl::make_unique<FakeDecoder>(); }), num_video_streams_(1), num_audio_streams_(0), num_flexfec_streams_(0), audio_decoder_factory_(CreateBuiltinAudioDecoderFactory()), audio_encoder_factory_(CreateBuiltinAudioEncoderFactory()), task_queue_("CallTestTaskQueue") {} CallTest::~CallTest() { task_queue_.SendTask([this]() { fake_send_audio_device_ = nullptr; fake_recv_audio_device_ = nullptr; video_capturers_.clear(); }); } void CallTest::RunBaseTest(BaseTest* test) { task_queue_.SendTask([this, test]() { num_video_streams_ = test->GetNumVideoStreams(); num_audio_streams_ = test->GetNumAudioStreams(); num_flexfec_streams_ = test->GetNumFlexfecStreams(); RTC_DCHECK(num_video_streams_ > 0 || num_audio_streams_ > 0); Call::Config send_config(send_event_log_.get()); test->ModifySenderCallConfig(&send_config); if (num_audio_streams_ > 0) { CreateFakeAudioDevices(test->CreateCapturer(), test->CreateRenderer()); test->OnFakeAudioDevicesCreated(fake_send_audio_device_.get(), fake_recv_audio_device_.get()); apm_send_ = AudioProcessingBuilder().Create(); apm_recv_ = AudioProcessingBuilder().Create(); EXPECT_EQ(0, fake_send_audio_device_->Init()); EXPECT_EQ(0, fake_recv_audio_device_->Init()); AudioState::Config audio_state_config; audio_state_config.audio_mixer = AudioMixerImpl::Create(); audio_state_config.audio_processing = apm_send_; audio_state_config.audio_device_module = fake_send_audio_device_; send_config.audio_state = AudioState::Create(audio_state_config); fake_send_audio_device_->RegisterAudioCallback( send_config.audio_state->audio_transport()); } CreateSenderCall(send_config); if (sender_call_transport_controller_ != nullptr) { test->OnRtpTransportControllerSendCreated( sender_call_transport_controller_); } if (test->ShouldCreateReceivers()) { Call::Config recv_config(recv_event_log_.get()); test->ModifyReceiverCallConfig(&recv_config); if (num_audio_streams_ > 0) { AudioState::Config audio_state_config; audio_state_config.audio_mixer = AudioMixerImpl::Create(); audio_state_config.audio_processing = apm_recv_; audio_state_config.audio_device_module = fake_recv_audio_device_; recv_config.audio_state = AudioState::Create(audio_state_config); fake_recv_audio_device_->RegisterAudioCallback( recv_config.audio_state->audio_transport()); } CreateReceiverCall(recv_config); } test->OnCallsCreated(sender_call_.get(), receiver_call_.get()); receive_transport_.reset(test->CreateReceiveTransport(&task_queue_)); send_transport_.reset( test->CreateSendTransport(&task_queue_, sender_call_.get())); if (test->ShouldCreateReceivers()) { send_transport_->SetReceiver(receiver_call_->Receiver()); receive_transport_->SetReceiver(sender_call_->Receiver()); if (num_video_streams_ > 0) receiver_call_->SignalChannelNetworkState(MediaType::VIDEO, kNetworkUp); if (num_audio_streams_ > 0) receiver_call_->SignalChannelNetworkState(MediaType::AUDIO, kNetworkUp); } else { // Sender-only call delivers to itself. send_transport_->SetReceiver(sender_call_->Receiver()); receive_transport_->SetReceiver(nullptr); } CreateSendConfig(num_video_streams_, num_audio_streams_, num_flexfec_streams_, send_transport_.get()); if (test->ShouldCreateReceivers()) { CreateMatchingReceiveConfigs(receive_transport_.get()); } if (num_video_streams_ > 0) { test->ModifyVideoConfigs(GetVideoSendConfig(), &video_receive_configs_, GetVideoEncoderConfig()); } if (num_audio_streams_ > 0) { test->ModifyAudioConfigs(&audio_send_config_, &audio_receive_configs_); } if (num_flexfec_streams_ > 0) { test->ModifyFlexfecConfigs(&flexfec_receive_configs_); } if (num_flexfec_streams_ > 0) { CreateFlexfecStreams(); test->OnFlexfecStreamsCreated(flexfec_receive_streams_); } if (num_video_streams_ > 0) { CreateVideoStreams(); test->OnVideoStreamsCreated(GetVideoSendStream(), video_receive_streams_); } if (num_audio_streams_ > 0) { CreateAudioStreams(); test->OnAudioStreamsCreated(audio_send_stream_, audio_receive_streams_); } if (num_video_streams_ > 0) { int width = kDefaultWidth; int height = kDefaultHeight; int frame_rate = kDefaultFramerate; test->ModifyVideoCaptureStartResolution(&width, &height, &frame_rate); CreateFrameGeneratorCapturer(frame_rate, width, height); test->OnFrameGeneratorCapturerCreated(frame_generator_capturer_); } Start(); }); test->PerformTest(); task_queue_.SendTask([this, test]() { Stop(); test->OnStreamsStopped(); DestroyStreams(); send_transport_.reset(); receive_transport_.reset(); DestroyCalls(); }); } void CallTest::CreateCalls() { CreateCalls(Call::Config(send_event_log_.get()), Call::Config(recv_event_log_.get())); } void CallTest::CreateCalls(const Call::Config& sender_config, const Call::Config& receiver_config) { CreateSenderCall(sender_config); CreateReceiverCall(receiver_config); } void CallTest::CreateSenderCall() { CreateSenderCall(Call::Config(send_event_log_.get())); } void CallTest::CreateSenderCall(const Call::Config& config) { NetworkControllerFactoryInterface* injected_factory = config.network_controller_factory; if (!injected_factory) { if (CongestionControllerExperiment::BbrControllerEnabled()) { RTC_LOG(LS_INFO) << "Using BBR network controller factory"; injected_factory = bbr_network_controller_factory_.get(); } else { RTC_LOG(LS_INFO) << "Using default network controller factory"; } } std::unique_ptr<RtpTransportControllerSend> controller_send = absl::make_unique<RtpTransportControllerSend>( Clock::GetRealTimeClock(), config.event_log, injected_factory, config.bitrate_config); sender_call_transport_controller_ = controller_send.get(); sender_call_.reset(Call::Create(config, std::move(controller_send))); } void CallTest::CreateReceiverCall(const Call::Config& config) { receiver_call_.reset(Call::Create(config)); } void CallTest::DestroyCalls() { sender_call_.reset(); receiver_call_.reset(); } void CallTest::CreateVideoSendConfig(VideoSendStream::Config* video_config, size_t num_video_streams, size_t num_used_ssrcs, Transport* send_transport) { RTC_DCHECK_LE(num_video_streams + num_used_ssrcs, kNumSsrcs); *video_config = VideoSendStream::Config(send_transport); video_config->encoder_settings.encoder_factory = &fake_encoder_factory_; video_config->rtp.payload_name = "FAKE"; video_config->rtp.payload_type = kFakeVideoSendPayloadType; video_config->rtp.extensions.push_back( RtpExtension(RtpExtension::kTransportSequenceNumberUri, kTransportSequenceNumberExtensionId)); video_config->rtp.extensions.push_back(RtpExtension( RtpExtension::kVideoContentTypeUri, kVideoContentTypeExtensionId)); video_config->rtp.extensions.push_back(RtpExtension( RtpExtension::kGenericFrameDescriptorUri, kGenericDescriptorExtensionId)); if (video_encoder_configs_.empty()) { video_encoder_configs_.emplace_back(); FillEncoderConfiguration(kVideoCodecGeneric, num_video_streams, &video_encoder_configs_.back()); } for (size_t i = 0; i < num_video_streams; ++i) video_config->rtp.ssrcs.push_back(kVideoSendSsrcs[num_used_ssrcs + i]); video_config->rtp.extensions.push_back(RtpExtension( RtpExtension::kVideoRotationUri, kVideoRotationRtpExtensionId)); } void CallTest::CreateAudioAndFecSendConfigs(size_t num_audio_streams, size_t num_flexfec_streams, Transport* send_transport) { RTC_DCHECK_LE(num_audio_streams, 1); RTC_DCHECK_LE(num_flexfec_streams, 1); if (num_audio_streams > 0) { AudioSendStream::Config audio_send_config(send_transport, /*media_transport=*/nullptr); audio_send_config.rtp.ssrc = kAudioSendSsrc; audio_send_config.send_codec_spec = AudioSendStream::Config::SendCodecSpec( kAudioSendPayloadType, {"opus", 48000, 2, {{"stereo", "1"}}}); audio_send_config.encoder_factory = audio_encoder_factory_; SetAudioConfig(audio_send_config); } // TODO(brandtr): Update this when we support multistream protection. if (num_flexfec_streams > 0) { SetSendFecConfig({kVideoSendSsrcs[0]}); } } void CallTest::SetAudioConfig(const AudioSendStream::Config& config) { audio_send_config_ = config; } void CallTest::SetSendFecConfig(std::vector<uint32_t> video_send_ssrcs) { GetVideoSendConfig()->rtp.flexfec.payload_type = kFlexfecPayloadType; GetVideoSendConfig()->rtp.flexfec.ssrc = kFlexfecSendSsrc; GetVideoSendConfig()->rtp.flexfec.protected_media_ssrcs = video_send_ssrcs; } void CallTest::SetSendUlpFecConfig(VideoSendStream::Config* send_config) { send_config->rtp.ulpfec.red_payload_type = kRedPayloadType; send_config->rtp.ulpfec.ulpfec_payload_type = kUlpfecPayloadType; send_config->rtp.ulpfec.red_rtx_payload_type = kRtxRedPayloadType; } void CallTest::SetReceiveUlpFecConfig( VideoReceiveStream::Config* receive_config) { receive_config->rtp.red_payload_type = kRedPayloadType; receive_config->rtp.ulpfec_payload_type = kUlpfecPayloadType; receive_config->rtp.rtx_associated_payload_types[kRtxRedPayloadType] = kRedPayloadType; } void CallTest::CreateSendConfig(size_t num_video_streams, size_t num_audio_streams, size_t num_flexfec_streams, Transport* send_transport) { if (num_video_streams > 0) { video_send_configs_.clear(); video_send_configs_.emplace_back(nullptr); CreateVideoSendConfig(&video_send_configs_.back(), num_video_streams, 0, send_transport); } CreateAudioAndFecSendConfigs(num_audio_streams, num_flexfec_streams, send_transport); } void CallTest::CreateMatchingVideoReceiveConfigs( const VideoSendStream::Config& video_send_config, Transport* rtcp_send_transport) { CreateMatchingVideoReceiveConfigs(video_send_config, rtcp_send_transport, true, &fake_decoder_factory_, absl::nullopt, false, 0); } void CallTest::CreateMatchingVideoReceiveConfigs( const VideoSendStream::Config& video_send_config, Transport* rtcp_send_transport, bool send_side_bwe, VideoDecoderFactory* decoder_factory, absl::optional<size_t> decode_sub_stream, bool receiver_reference_time_report, int rtp_history_ms) { AddMatchingVideoReceiveConfigs( &video_receive_configs_, video_send_config, rtcp_send_transport, send_side_bwe, decoder_factory, decode_sub_stream, receiver_reference_time_report, rtp_history_ms); } void CallTest::AddMatchingVideoReceiveConfigs( std::vector<VideoReceiveStream::Config>* receive_configs, const VideoSendStream::Config& video_send_config, Transport* rtcp_send_transport, bool send_side_bwe, VideoDecoderFactory* decoder_factory, absl::optional<size_t> decode_sub_stream, bool receiver_reference_time_report, int rtp_history_ms) { RTC_DCHECK(!video_send_config.rtp.ssrcs.empty()); VideoReceiveStream::Config default_config(rtcp_send_transport); default_config.rtp.remb = !send_side_bwe; default_config.rtp.transport_cc = send_side_bwe; default_config.rtp.local_ssrc = kReceiverLocalVideoSsrc; for (const RtpExtension& extension : video_send_config.rtp.extensions) default_config.rtp.extensions.push_back(extension); default_config.rtp.nack.rtp_history_ms = rtp_history_ms; // Enable RTT calculation so NTP time estimator will work. default_config.rtp.rtcp_xr.receiver_reference_time_report = receiver_reference_time_report; default_config.renderer = &fake_renderer_; for (size_t i = 0; i < video_send_config.rtp.ssrcs.size(); ++i) { VideoReceiveStream::Config video_recv_config(default_config.Copy()); video_recv_config.decoders.clear(); if (!video_send_config.rtp.rtx.ssrcs.empty()) { video_recv_config.rtp.rtx_ssrc = video_send_config.rtp.rtx.ssrcs[i]; video_recv_config.rtp.rtx_associated_payload_types[kSendRtxPayloadType] = video_send_config.rtp.payload_type; } video_recv_config.rtp.remote_ssrc = video_send_config.rtp.ssrcs[i]; VideoReceiveStream::Decoder decoder; decoder.payload_type = video_send_config.rtp.payload_type; decoder.video_format = SdpVideoFormat(video_send_config.rtp.payload_name); // Force fake decoders on non-selected simulcast streams. if (!decode_sub_stream || i == *decode_sub_stream) { decoder.decoder_factory = decoder_factory; } else { decoder.decoder_factory = &fake_decoder_factory_; } video_recv_config.decoders.push_back(decoder); receive_configs->emplace_back(std::move(video_recv_config)); } } void CallTest::CreateMatchingAudioAndFecConfigs( Transport* rtcp_send_transport) { RTC_DCHECK_GE(1, num_audio_streams_); if (num_audio_streams_ == 1) { CreateMatchingAudioConfigs(rtcp_send_transport, ""); } // TODO(brandtr): Update this when we support multistream protection. RTC_DCHECK(num_flexfec_streams_ <= 1); if (num_flexfec_streams_ == 1) { CreateMatchingFecConfig(rtcp_send_transport, *GetVideoSendConfig()); for (const RtpExtension& extension : GetVideoSendConfig()->rtp.extensions) GetFlexFecConfig()->rtp_header_extensions.push_back(extension); } } void CallTest::CreateMatchingAudioConfigs(Transport* transport, std::string sync_group) { audio_receive_configs_.push_back(CreateMatchingAudioConfig( audio_send_config_, audio_decoder_factory_, transport, sync_group)); } AudioReceiveStream::Config CallTest::CreateMatchingAudioConfig( const AudioSendStream::Config& send_config, rtc::scoped_refptr<AudioDecoderFactory> audio_decoder_factory, Transport* transport, std::string sync_group) { AudioReceiveStream::Config audio_config; audio_config.rtp.local_ssrc = kReceiverLocalAudioSsrc; audio_config.rtcp_send_transport = transport; audio_config.rtp.remote_ssrc = send_config.rtp.ssrc; audio_config.rtp.transport_cc = send_config.send_codec_spec ? send_config.send_codec_spec->transport_cc_enabled : false; audio_config.rtp.extensions = send_config.rtp.extensions; audio_config.decoder_factory = audio_decoder_factory; audio_config.decoder_map = {{kAudioSendPayloadType, {"opus", 48000, 2}}}; audio_config.sync_group = sync_group; return audio_config; } void CallTest::CreateMatchingFecConfig( Transport* transport, const VideoSendStream::Config& send_config) { FlexfecReceiveStream::Config config(transport); config.payload_type = send_config.rtp.flexfec.payload_type; config.remote_ssrc = send_config.rtp.flexfec.ssrc; config.protected_media_ssrcs = send_config.rtp.flexfec.protected_media_ssrcs; config.local_ssrc = kReceiverLocalVideoSsrc; if (!video_receive_configs_.empty()) video_receive_configs_[0].rtp.protected_by_flexfec = true; flexfec_receive_configs_.push_back(config); } void CallTest::CreateMatchingReceiveConfigs(Transport* rtcp_send_transport) { video_receive_configs_.clear(); for (VideoSendStream::Config& video_send_config : video_send_configs_) { CreateMatchingVideoReceiveConfigs(video_send_config, rtcp_send_transport); } CreateMatchingAudioAndFecConfigs(rtcp_send_transport); } void CallTest::CreateFrameGeneratorCapturerWithDrift(Clock* clock, float speed, int framerate, int width, int height) { video_sources_.clear(); video_capturers_.clear(); frame_generator_capturer_ = test::FrameGeneratorCapturer::Create( width, height, absl::nullopt, absl::nullopt, framerate * speed, clock); video_capturers_.emplace_back( std::unique_ptr<FrameGeneratorCapturer>(frame_generator_capturer_)); video_sources_.push_back(video_capturers_.back().get()); ConnectVideoSourcesToStreams(); } void CallTest::CreateFrameGeneratorCapturer(int framerate, int width, int height) { video_sources_.clear(); video_capturers_.clear(); frame_generator_capturer_ = test::FrameGeneratorCapturer::Create( width, height, absl::nullopt, absl::nullopt, framerate, clock_); video_capturers_.emplace_back( std::unique_ptr<FrameGeneratorCapturer>(frame_generator_capturer_)); video_sources_.push_back(video_capturers_.back().get()); ConnectVideoSourcesToStreams(); } void CallTest::CreateFakeAudioDevices( std::unique_ptr<TestAudioDeviceModule::Capturer> capturer, std::unique_ptr<TestAudioDeviceModule::Renderer> renderer) { fake_send_audio_device_ = TestAudioDeviceModule::CreateTestAudioDeviceModule( std::move(capturer), nullptr, 1.f); fake_recv_audio_device_ = TestAudioDeviceModule::CreateTestAudioDeviceModule( nullptr, std::move(renderer), 1.f); } void CallTest::CreateVideoStreams() { RTC_DCHECK(video_receive_streams_.empty()); CreateVideoSendStreams(); for (size_t i = 0; i < video_receive_configs_.size(); ++i) { video_receive_streams_.push_back(receiver_call_->CreateVideoReceiveStream( video_receive_configs_[i].Copy())); } AssociateFlexfecStreamsWithVideoStreams(); } void CallTest::CreateVideoSendStreams() { RTC_DCHECK(video_send_streams_.empty()); // We currently only support testing external fec controllers with a single // VideoSendStream. if (fec_controller_factory_.get()) { RTC_DCHECK_LE(video_send_configs_.size(), 1); } // TODO(http://crbug/818127): // Remove this workaround when ALR is not screenshare-specific. std::list<size_t> streams_creation_order; for (size_t i = 0; i < video_send_configs_.size(); ++i) { // If dual streams are created, add the screenshare stream last. if (video_encoder_configs_[i].content_type == VideoEncoderConfig::ContentType::kScreen) { streams_creation_order.push_back(i); } else { streams_creation_order.push_front(i); } } video_send_streams_.resize(video_send_configs_.size(), nullptr); for (size_t i : streams_creation_order) { if (fec_controller_factory_.get()) { video_send_streams_[i] = sender_call_->CreateVideoSendStream( video_send_configs_[i].Copy(), video_encoder_configs_[i].Copy(), fec_controller_factory_->CreateFecController()); } else { video_send_streams_[i] = sender_call_->CreateVideoSendStream( video_send_configs_[i].Copy(), video_encoder_configs_[i].Copy()); } } } void CallTest::CreateVideoSendStream(const VideoEncoderConfig& encoder_config) { RTC_DCHECK(video_send_streams_.empty()); video_send_streams_.push_back(sender_call_->CreateVideoSendStream( GetVideoSendConfig()->Copy(), encoder_config.Copy())); } void CallTest::CreateAudioStreams() { RTC_DCHECK(audio_send_stream_ == nullptr); RTC_DCHECK(audio_receive_streams_.empty()); audio_send_stream_ = sender_call_->CreateAudioSendStream(audio_send_config_); for (size_t i = 0; i < audio_receive_configs_.size(); ++i) { audio_receive_streams_.push_back( receiver_call_->CreateAudioReceiveStream(audio_receive_configs_[i])); } } void CallTest::CreateFlexfecStreams() { for (size_t i = 0; i < flexfec_receive_configs_.size(); ++i) { flexfec_receive_streams_.push_back( receiver_call_->CreateFlexfecReceiveStream( flexfec_receive_configs_[i])); } AssociateFlexfecStreamsWithVideoStreams(); } void CallTest::ConnectVideoSourcesToStreams() { for (size_t i = 0; i < video_sources_.size(); ++i) video_send_streams_[i]->SetSource(video_sources_[i], degradation_preference_); } void CallTest::AssociateFlexfecStreamsWithVideoStreams() { // All FlexFEC streams protect all of the video streams. for (FlexfecReceiveStream* flexfec_recv_stream : flexfec_receive_streams_) { for (VideoReceiveStream* video_recv_stream : video_receive_streams_) { video_recv_stream->AddSecondarySink(flexfec_recv_stream); } } } void CallTest::DissociateFlexfecStreamsFromVideoStreams() { for (FlexfecReceiveStream* flexfec_recv_stream : flexfec_receive_streams_) { for (VideoReceiveStream* video_recv_stream : video_receive_streams_) { video_recv_stream->RemoveSecondarySink(flexfec_recv_stream); } } } void CallTest::Start() { StartVideoStreams(); if (audio_send_stream_) { audio_send_stream_->Start(); } for (AudioReceiveStream* audio_recv_stream : audio_receive_streams_) audio_recv_stream->Start(); StartVideoCapture(); } void CallTest::StartVideoStreams() { for (VideoSendStream* video_send_stream : video_send_streams_) video_send_stream->Start(); for (VideoReceiveStream* video_recv_stream : video_receive_streams_) video_recv_stream->Start(); } void CallTest::StartVideoCapture() { for (auto& capturer : video_capturers_) capturer->Start(); } void CallTest::Stop() { StopVideoCapture(); for (AudioReceiveStream* audio_recv_stream : audio_receive_streams_) audio_recv_stream->Stop(); if (audio_send_stream_) { audio_send_stream_->Stop(); } StopVideoStreams(); } void CallTest::StopVideoCapture() { for (auto& capturer : video_capturers_) capturer->Stop(); } void CallTest::StopVideoStreams() { for (VideoSendStream* video_send_stream : video_send_streams_) video_send_stream->Stop(); for (VideoReceiveStream* video_recv_stream : video_receive_streams_) video_recv_stream->Stop(); } void CallTest::DestroyStreams() { DissociateFlexfecStreamsFromVideoStreams(); if (audio_send_stream_) sender_call_->DestroyAudioSendStream(audio_send_stream_); audio_send_stream_ = nullptr; for (AudioReceiveStream* audio_recv_stream : audio_receive_streams_) receiver_call_->DestroyAudioReceiveStream(audio_recv_stream); DestroyVideoSendStreams(); for (VideoReceiveStream* video_recv_stream : video_receive_streams_) receiver_call_->DestroyVideoReceiveStream(video_recv_stream); for (FlexfecReceiveStream* flexfec_recv_stream : flexfec_receive_streams_) receiver_call_->DestroyFlexfecReceiveStream(flexfec_recv_stream); video_receive_streams_.clear(); } void CallTest::DestroyVideoSendStreams() { for (VideoSendStream* video_send_stream : video_send_streams_) sender_call_->DestroyVideoSendStream(video_send_stream); video_send_streams_.clear(); } void CallTest::SetFakeVideoCaptureRotation(VideoRotation rotation) { frame_generator_capturer_->SetFakeRotation(rotation); } void CallTest::SetVideoDegradation(DegradationPreference preference) { GetVideoSendStream()->SetSource(frame_generator_capturer_, preference); } VideoSendStream::Config* CallTest::GetVideoSendConfig() { return &video_send_configs_[0]; } void CallTest::SetVideoSendConfig(const VideoSendStream::Config& config) { video_send_configs_.clear(); video_send_configs_.push_back(config.Copy()); } VideoEncoderConfig* CallTest::GetVideoEncoderConfig() { return &video_encoder_configs_[0]; } void CallTest::SetVideoEncoderConfig(const VideoEncoderConfig& config) { video_encoder_configs_.clear(); video_encoder_configs_.push_back(config.Copy()); } VideoSendStream* CallTest::GetVideoSendStream() { return video_send_streams_[0]; } FlexfecReceiveStream::Config* CallTest::GetFlexFecConfig() { return &flexfec_receive_configs_[0]; } constexpr size_t CallTest::kNumSsrcs; const int CallTest::kDefaultWidth; const int CallTest::kDefaultHeight; const int CallTest::kDefaultFramerate; const int CallTest::kDefaultTimeoutMs = 30 * 1000; const int CallTest::kLongTimeoutMs = 120 * 1000; const uint32_t CallTest::kSendRtxSsrcs[kNumSsrcs] = { 0xBADCAFD, 0xBADCAFE, 0xBADCAFF, 0xBADCB00, 0xBADCB01, 0xBADCB02}; const uint32_t CallTest::kVideoSendSsrcs[kNumSsrcs] = { 0xC0FFED, 0xC0FFEE, 0xC0FFEF, 0xC0FFF0, 0xC0FFF1, 0xC0FFF2}; const uint32_t CallTest::kAudioSendSsrc = 0xDEADBEEF; const uint32_t CallTest::kFlexfecSendSsrc = 0xBADBEEF; const uint32_t CallTest::kReceiverLocalVideoSsrc = 0x123456; const uint32_t CallTest::kReceiverLocalAudioSsrc = 0x1234567; const int CallTest::kNackRtpHistoryMs = 1000; const uint8_t CallTest::kDefaultKeepalivePayloadType = RtpKeepAliveConfig().payload_type; const std::map<uint8_t, MediaType> CallTest::payload_type_map_ = { {CallTest::kVideoSendPayloadType, MediaType::VIDEO}, {CallTest::kFakeVideoSendPayloadType, MediaType::VIDEO}, {CallTest::kSendRtxPayloadType, MediaType::VIDEO}, {CallTest::kRedPayloadType, MediaType::VIDEO}, {CallTest::kRtxRedPayloadType, MediaType::VIDEO}, {CallTest::kUlpfecPayloadType, MediaType::VIDEO}, {CallTest::kFlexfecPayloadType, MediaType::VIDEO}, {CallTest::kAudioSendPayloadType, MediaType::AUDIO}, {CallTest::kDefaultKeepalivePayloadType, MediaType::ANY}}; BaseTest::BaseTest() {} BaseTest::BaseTest(int timeout_ms) : RtpRtcpObserver(timeout_ms) {} BaseTest::~BaseTest() {} std::unique_ptr<TestAudioDeviceModule::Capturer> BaseTest::CreateCapturer() { return TestAudioDeviceModule::CreatePulsedNoiseCapturer(256, 48000); } std::unique_ptr<TestAudioDeviceModule::Renderer> BaseTest::CreateRenderer() { return TestAudioDeviceModule::CreateDiscardRenderer(48000); } void BaseTest::OnFakeAudioDevicesCreated( TestAudioDeviceModule* send_audio_device, TestAudioDeviceModule* recv_audio_device) {} void BaseTest::ModifySenderCallConfig(Call::Config* config) {} void BaseTest::ModifyReceiverCallConfig(Call::Config* config) {} void BaseTest::OnRtpTransportControllerSendCreated( RtpTransportControllerSend* controller) {} void BaseTest::OnCallsCreated(Call* sender_call, Call* receiver_call) {} test::PacketTransport* BaseTest::CreateSendTransport( SingleThreadedTaskQueueForTesting* task_queue, Call* sender_call) { return new PacketTransport( task_queue, sender_call, this, test::PacketTransport::kSender, CallTest::payload_type_map_, absl::make_unique<FakeNetworkPipe>( Clock::GetRealTimeClock(), absl::make_unique<SimulatedNetwork>(BuiltInNetworkBehaviorConfig()))); } test::PacketTransport* BaseTest::CreateReceiveTransport( SingleThreadedTaskQueueForTesting* task_queue) { return new PacketTransport( task_queue, nullptr, this, test::PacketTransport::kReceiver, CallTest::payload_type_map_, absl::make_unique<FakeNetworkPipe>( Clock::GetRealTimeClock(), absl::make_unique<SimulatedNetwork>(BuiltInNetworkBehaviorConfig()))); } size_t BaseTest::GetNumVideoStreams() const { return 1; } size_t BaseTest::GetNumAudioStreams() const { return 0; } size_t BaseTest::GetNumFlexfecStreams() const { return 0; } void BaseTest::ModifyVideoConfigs( VideoSendStream::Config* send_config, std::vector<VideoReceiveStream::Config>* receive_configs, VideoEncoderConfig* encoder_config) {} void BaseTest::ModifyVideoCaptureStartResolution(int* width, int* heigt, int* frame_rate) {} void BaseTest::OnVideoStreamsCreated( VideoSendStream* send_stream, const std::vector<VideoReceiveStream*>& receive_streams) {} void BaseTest::ModifyAudioConfigs( AudioSendStream::Config* send_config, std::vector<AudioReceiveStream::Config>* receive_configs) {} void BaseTest::OnAudioStreamsCreated( AudioSendStream* send_stream, const std::vector<AudioReceiveStream*>& receive_streams) {} void BaseTest::ModifyFlexfecConfigs( std::vector<FlexfecReceiveStream::Config>* receive_configs) {} void BaseTest::OnFlexfecStreamsCreated( const std::vector<FlexfecReceiveStream*>& receive_streams) {} void BaseTest::OnFrameGeneratorCapturerCreated( FrameGeneratorCapturer* frame_generator_capturer) {} void BaseTest::OnStreamsStopped() {} SendTest::SendTest(int timeout_ms) : BaseTest(timeout_ms) {} bool SendTest::ShouldCreateReceivers() const { return false; } EndToEndTest::EndToEndTest() {} EndToEndTest::EndToEndTest(int timeout_ms) : BaseTest(timeout_ms) {} bool EndToEndTest::ShouldCreateReceivers() const { return true; } } // namespace test } // namespace webrtc
38.0743
80
0.736428
[ "vector" ]
28695374e753070e38b50f41002eb431d47f5cf1
3,176
hpp
C++
cpp/src/gcylon/utils/util.hpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
229
2020-07-01T14:05:10.000Z
2022-03-25T12:26:58.000Z
cpp/src/gcylon/utils/util.hpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
261
2020-06-30T23:23:15.000Z
2022-03-16T09:55:40.000Z
cpp/src/gcylon/utils/util.hpp
deHasara/cylon
f5e31a1191d6a30c0a8c5778a7db4a07c5802da8
[ "Apache-2.0" ]
36
2020-06-30T23:14:52.000Z
2022-03-03T02:37:09.000Z
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GCYLON_ALL2ALL_UTIL_H #define GCYLON_ALL2ALL_UTIL_H #include <glog/logging.h> #include <cuda.h> #include <cudf/column/column.hpp> #include <cudf/table/table.hpp> namespace gcylon { /** * get one scalar value from device to host * @param buff * @return */ template <typename T> inline T getScalar(const T * buff) { T value; cudaMemcpy(&value, buff, sizeof(T), cudaMemcpyDeviceToHost); return value; } /** * get part of a constant-size-type column from gpu to cpu * @tparam T * @param cv * @param start * @param end * @return */ template <typename T> T * getColumnPart(const cudf::column_view &cv, int64_t start, int64_t end) { int64_t size = end - start; // data type size int dts = sizeof(T); uint8_t * host_array = new uint8_t[size * dts]; cudaMemcpy(host_array, cv.data<uint8_t>() + start * dts, size * dts, cudaMemcpyDeviceToHost); return (T *) host_array; } /** * get top N elements of a constant-size-type column * @tparam T * @param cv * @param topN * @return */ template <typename T> T * getColumnTop(const cudf::column_view &cv, int64_t topN = 5) { return getColumnPart<T>(cv, 0, topN); } /** * get tail N elements of a constant-size-type column * @tparam T * @param cv * @param tailN * @return */ template <typename T> T * getColumnTail(const cudf::column_view &cv, int64_t tailN = 5) { return getColumnPart<T>(cv, cv.size() - tailN, cv.size()); } /** * whether two cudf tables are equal with all elements in them * first sort both tables and compare then afterward * @param tv1 * @param tv2 * @return */ bool table_equal_with_sorting(cudf::table_view & tv1, cudf::table_view & tv2); /** * whether two cudf tables are equal with all elements in them * @param tv1 * @param tv2 * @return */ bool table_equal(const cudf::table_view & tv1, const cudf::table_view & tv2); /** * convert a vector of elements to a string with comma + space in between * @tparam T * @param vec * @return */ template<typename T> std::string vectorToString(const std::vector<T> &vec) { if (vec.empty()) { return std::string(); } std::ostringstream oss; // Convert all but the last element to avoid a trailing "," std::copy(vec.begin(), vec.end()-1, std::ostream_iterator<T>(oss, ", ")); // Now add the last element with no delimiter oss << vec.back(); return oss.str(); } /** * convert a vector of cudf tables to table_views * @param tables * @return */ std::vector<cudf::table_view> tablesToViews(const std::vector<std::unique_ptr<cudf::table>> &tables); } // end of namespace gcylon #endif //GCYLON_ALL2ALL_UTIL_H
24.8125
101
0.689232
[ "vector" ]
28771c4eaa854aa5bc02d03435fc240286c007c9
4,149
cpp
C++
src/plugins/robots/prototype/simulator/prototype_link_entity.cpp
wtrep/argos3
8c855408ca7d88be4ccf015ad93d7a6abd3c7f0b
[ "MIT" ]
null
null
null
src/plugins/robots/prototype/simulator/prototype_link_entity.cpp
wtrep/argos3
8c855408ca7d88be4ccf015ad93d7a6abd3c7f0b
[ "MIT" ]
1
2021-02-28T23:45:32.000Z
2021-02-28T23:45:32.000Z
src/plugins/robots/prototype/simulator/prototype_link_entity.cpp
wtrep/argos3
8c855408ca7d88be4ccf015ad93d7a6abd3c7f0b
[ "MIT" ]
7
2021-02-26T16:41:06.000Z
2022-01-19T21:36:31.000Z
/** * @file <argos3/plugins/robots/prototype/simulator/prototype_link_entity.cpp> * * @author Michael Allwright - <allsey87@gmail.com> * @author Weixu Zhu - <zhuweixu_harry@126.com> */ #include "prototype_link_entity.h" #include <argos3/core/simulator/entity/composable_entity.h> #include <argos3/plugins/robots/prototype/simulator/prototype_entity.h> namespace argos { /****************************************/ /****************************************/ CPrototypeLinkEntity::CPrototypeLinkEntity(CComposableEntity* pc_parent) : CEntity(pc_parent), m_eGeometry(EGeometry::BOX), m_cExtents(0.0f, 0.0f, 0.0f), m_fMass(0.0f), m_psAnchor(nullptr) {} /****************************************/ /****************************************/ void CPrototypeLinkEntity::Init(TConfigurationNode& t_tree) { try { /* Init parent */ CEntity::Init(t_tree); /* Parse link geometry and dimensions */ std::string strLinkGeometry; GetNodeAttribute(t_tree, "geometry", strLinkGeometry); if(strLinkGeometry == "box") { m_eGeometry = BOX; GetNodeAttribute(t_tree, "size", m_cExtents); } else if(strLinkGeometry == "cylinder") { m_eGeometry = CYLINDER; Real fRadius; Real fHeight; GetNodeAttribute(t_tree, "height", fHeight); GetNodeAttribute(t_tree, "radius", fRadius); m_cExtents.Set(fRadius * 2.0f, fRadius * 2.0f, fHeight); } else if(strLinkGeometry == "sphere") { m_eGeometry = SPHERE; Real fRadius; GetNodeAttribute(t_tree, "radius", fRadius); m_cExtents.Set(fRadius * 2.0f, fRadius * 2.0f, fRadius * 2.0f); } else if(strLinkGeometry == "convex_hull") { std::string strPoints; std::vector<std::string> vecPoints; CVector3 cPoint; m_eGeometry = CONVEX_HULL; m_cExtents.Set(0.0f, 0.0f, 0.0f); /* Parse the points of the convex hull */ GetNodeText(t_tree, strPoints); /* Remove any whitespace characters */ std::string::iterator itEraseBegin = std::remove_if(std::begin(strPoints), std::end(strPoints), ::isspace); strPoints.erase(itEraseBegin, std::end(strPoints)); /* Split into individual points */ Tokenize(strPoints, vecPoints, "()"); for(const std::string& str_point : vecPoints) { std::istringstream(str_point) >> cPoint; m_vecConvexHullPoints.push_back(cPoint); } CConvexHull cConvexHull(m_vecConvexHullPoints); /* store the faces in this object */ m_vecConvexHullFaces = cConvexHull.GetFaces(); } else { /* unknown geometry requested */ THROW_ARGOSEXCEPTION("Geometry \"" << strLinkGeometry << "\" is not implemented"); } /* Parse link geometry and dimensions */ GetNodeAttribute(t_tree, "mass", m_fMass); /* Get the offset position of the link */ CVector3 cOffsetPosition; GetNodeAttributeOrDefault(t_tree, "position", cOffsetPosition, cOffsetPosition); /* Get the offset orientation of the link */ CQuaternion cOffsetOrientation; GetNodeAttributeOrDefault(t_tree, "orientation", cOffsetOrientation, cOffsetOrientation); /* Create an anchor for this link */ CEmbodiedEntity& cBody = GetParent().GetParent().GetComponent<CEmbodiedEntity>("body"); m_psAnchor = &(cBody.AddAnchor(GetId(), cOffsetPosition, cOffsetOrientation)); /* Enable the anchor */ m_psAnchor->Enable(); } catch(CARGoSException& ex) { THROW_ARGOSEXCEPTION_NESTED("Error while initializing link entity", ex); } } /****************************************/ /****************************************/ REGISTER_STANDARD_SPACE_OPERATIONS_ON_ENTITY(CPrototypeLinkEntity); /****************************************/ /****************************************/ }
40.676471
98
0.566402
[ "geometry", "object", "vector" ]
287ab7f47dd4af62cdf6c18f1bf50f7aa96ce85a
71,285
cc
C++
src/nnet3/convolution.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
74
2017-01-10T21:27:24.000Z
2022-03-05T07:30:30.000Z
src/nnet3/convolution.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
49
2015-10-24T22:06:28.000Z
2019-12-24T11:13:34.000Z
src/nnet3/convolution.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
28
2017-01-23T10:49:04.000Z
2022-03-05T07:30:21.000Z
// nnet3/convolution.cc // Copyright 2017 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include <iterator> #include <sstream> #include <iomanip> #include "nnet3/convolution.h" #include "nnet3/nnet-parse.h" #include "nnet3/nnet-compile-utils.h" namespace kaldi { namespace nnet3 { namespace time_height_convolution { /** This function, used in ConvolutionComputation::ComputeDerived(), reverses a mapping that may not be unique. 'columns' is a column mapping where each member is either -1 (meaning, copy a zero), or a number between 0 and input_dim - 1. Its output, 'backward_columns', is the reverse mapping, but it's a vector of vectors instead of just a vector because the mapping may have been many-to-one. Each element of 'backward_columns' will be of dimension input_dim. For each columns[i] = j such that j != -1, for some k we will have (*backward_columns)[k][j] = i. */ static void ReverseColumnMapping( const std::vector<int32> &columns, int32 input_dim, std::vector<std::vector<int32> > *backward_columns) { int32 columns_dim = columns.size(); std::vector<std::vector<int32> > temp(input_dim); for (int32 i = 0; i < columns_dim; i++) { int32 j = columns[i]; KALDI_ASSERT(j >= -1 && j < input_dim); if (j != -1) temp[j].push_back(i); } // 'max_overlap' is the largest number of times that some j >= 0 appears in // 'columns'. int32 max_overlap = 0; for (int32 j = 0; j < input_dim; j++) max_overlap = std::max(max_overlap, static_cast<int32>(temp[j].size())); backward_columns->resize(max_overlap); for (int32 k = 0; k < max_overlap; k++) { (*backward_columns)[k].clear(); (*backward_columns)[k].resize(input_dim, -1); } for (int32 j = 0; j < input_dim; j++) { for (int32 k = 0; k < static_cast<int32>(temp[j].size()); k++) { int32 i = temp[j][k]; (*backward_columns)[k][j] = i; } } } // returns true if 'vec' is of the form // [ n, n+1, n+2, .... ]. static bool VectorIsContiguous(const std::vector<int32> &vec) { KALDI_ASSERT(!vec.empty()); int32 s = vec.size(); for (int32 i = 0; i + 1 < s; i++) if (vec[i+1] != vec[i] + 1) return false; return true; } std::string ConvolutionModel::Info() const { std::ostringstream os; os << "num-filters-in=" << num_filters_in << ", num-filters-out=" << num_filters_out << ", height-in=" << height_in << ", height-out=" << height_out << ", height-subsample-out=" << height_subsample_out << ", {time,height}-offsets=["; for (size_t i = 0; i < offsets.size(); i++) { if (i > 0) os << ' '; os << offsets[i].time_offset << ',' << offsets[i].height_offset; } os << "], required-time-offsets=["; for (std::set<int32>::const_iterator iter = required_time_offsets.begin(); iter != required_time_offsets.end(); ++iter) { if (iter != required_time_offsets.begin()) os << ','; os << *iter; } os << "], input-dim=" << InputDim() << ", output-dim=" << OutputDim(); return os.str(); } void ConvolutionModel::ComputeDerived() { { // compute all_time_offsets all_time_offsets.clear(); for (std::vector<Offset>::const_iterator iter = offsets.begin(); iter != offsets.end(); ++iter) all_time_offsets.insert(iter->time_offset); } { // compute time_offsets_modulus time_offsets_modulus = 0; std::set<int32>::iterator iter = all_time_offsets.begin(); int32 cur_offset = *iter; for (++iter; iter != all_time_offsets.end(); ++iter) { int32 this_offset = *iter; time_offsets_modulus = Gcd(time_offsets_modulus, this_offset - cur_offset); cur_offset = this_offset; } } } bool ConvolutionModel::Check(bool check_heights_used, bool allow_height_padding) const { if (num_filters_in <= 0 || num_filters_out <= 0 || height_in <= 0 || height_out <= 0 || height_subsample_out <= 0 || offsets.empty() || required_time_offsets.empty()) { KALDI_WARN << "Convolution model fails basic check."; return false; } ConvolutionModel temp(*this); temp.ComputeDerived(); if (!(temp == *this)) { KALDI_WARN << "Derived variables are incorrect."; return false; } // check that required_time_offsets is included in all_time_offsets. for (std::set<int32>::iterator iter = required_time_offsets.begin(); iter != required_time_offsets.end(); ++iter) { if (all_time_offsets.count(*iter) == 0) { KALDI_WARN << "Required time offsets not a subset of all_time_offsets."; return false; } } KALDI_ASSERT(IsSortedAndUniq(offsets)); std::vector<bool> h_in_used(height_in, false); std::vector<bool> offsets_used(offsets.size(), false); // check that in cases where we only have the minimum // required input (from required_time_offsets), each // height in the output is potentially nonzero. for (int32 h_out = 0; h_out < height_out * height_subsample_out; h_out += height_subsample_out) { bool some_input_available = false; for (size_t i = 0; i < offsets.size(); i++) { const Offset &offset = offsets[i]; int32 h_in = h_out + offset.height_offset; if (h_in >= 0 && h_in < height_in) { offsets_used[i] = true; h_in_used[h_in] = true; if (required_time_offsets.count(offset.time_offset) != 0) some_input_available = true; } else { if (!allow_height_padding) { KALDI_WARN << "height padding not allowed but is required."; return false; } } } if (!some_input_available) { // none of the // input pixels for this output pixel were available (at least in the case // where we only have the 'required' inputs on the time dimension). std::ostringstream os; Write(os, false); KALDI_WARN << "for the " << (h_out / height_out) << "'th output height, " "no input is available, if only required time-indexes " "are available."; // We could later change this part of the validation code to accept // such models, if there is a legitimate use-case. return false; } } if (check_heights_used) { for (int32 h = 0; h < height_in; h++) { if (!h_in_used[h]) { KALDI_WARN << "The input at the " << h << "'th height is never used."; return false; } } } for (size_t i = 0; i < offsets_used.size(); i++) { if (!offsets_used[i]) { KALDI_WARN << "(time,height) offset (" << offsets[i].time_offset << "," << offsets[i].height_offset << ") of this computation is never used."; return false; } } return true; } bool ConvolutionModel::operator == (const ConvolutionModel &other) const { return num_filters_in == other.num_filters_in && num_filters_out == other.num_filters_out && height_in == other.height_in && height_out == other.height_out && height_subsample_out == other.height_subsample_out && offsets == other.offsets && required_time_offsets == other.required_time_offsets && all_time_offsets == other.all_time_offsets && time_offsets_modulus == other.time_offsets_modulus; } void ConvolutionModel::Write(std::ostream &os, bool binary) const { WriteToken(os, binary, "<ConvolutionModel>"); WriteToken(os, binary, "<NumFiltersIn>"); WriteBasicType(os, binary, num_filters_in); WriteToken(os, binary, "<NumFiltersOut>"); WriteBasicType(os, binary, num_filters_out); WriteToken(os, binary, "<HeightIn>"); WriteBasicType(os, binary, height_in); WriteToken(os, binary, "<HeightOut>"); WriteBasicType(os, binary, height_out); WriteToken(os, binary, "<HeightSubsampleOut>"); WriteBasicType(os, binary, height_subsample_out); WriteToken(os, binary, "<Offsets>"); std::vector<std::pair<int32, int32> > pairs(offsets.size()); for (size_t i = 0; i < offsets.size(); i++) { pairs[i].first = offsets[i].time_offset; pairs[i].second = offsets[i].height_offset; } WriteIntegerPairVector(os, binary, pairs); std::vector<int32> required_time_offsets_list(required_time_offsets.begin(), required_time_offsets.end()); WriteToken(os, binary, "<RequiredTimeOffsets>"); WriteIntegerVector(os, binary, required_time_offsets_list); WriteToken(os, binary, "</ConvolutionModel>"); } void ConvolutionModel::Read(std::istream &is, bool binary) { ExpectOneOrTwoTokens(is, binary, "<ConvolutionModel>", "<NumFiltersIn>"); ReadBasicType(is, binary, &num_filters_in); ExpectToken(is, binary, "<NumFiltersOut>"); ReadBasicType(is, binary, &num_filters_out); ExpectToken(is, binary, "<HeightIn>"); ReadBasicType(is, binary, &height_in); ExpectToken(is, binary, "<HeightOut>"); ReadBasicType(is, binary, &height_out); ExpectToken(is, binary, "<HeightSubsampleOut>"); ReadBasicType(is, binary, &height_subsample_out); ExpectToken(is, binary, "<Offsets>"); std::vector<std::pair<int32, int32> > pairs; ReadIntegerPairVector(is, binary, &pairs); offsets.resize(pairs.size()); for (size_t i = 0; i < offsets.size(); i++) { offsets[i].time_offset = pairs[i].first; offsets[i].height_offset = pairs[i].second; } std::vector<int32> required_time_offsets_list; ExpectToken(is, binary, "<RequiredTimeOffsets>"); ReadIntegerVector(is, binary, &required_time_offsets_list); required_time_offsets.clear(); required_time_offsets.insert(required_time_offsets_list.begin(), required_time_offsets_list.end()); ExpectToken(is, binary, "</ConvolutionModel>"); ComputeDerived(); KALDI_ASSERT(Check(false, true)); } void ConvolutionComputation::Write(std::ostream &os, bool binary) const { WriteToken(os, binary, "<ConvComputation>"); WriteToken(os, binary, "<NumFiltersInOut>"); WriteBasicType(os, binary, num_filters_in); WriteBasicType(os, binary, num_filters_out); WriteToken(os, binary, "<HeightInOut>"); WriteBasicType(os, binary, height_in); WriteBasicType(os, binary, height_out); WriteToken(os, binary, "<NumTInOut>"); WriteBasicType(os, binary, num_t_in); WriteBasicType(os, binary, num_t_out); WriteToken(os, binary, "<NumImages>"); WriteBasicType(os, binary, num_images); WriteToken(os, binary, "<TempRowsCols>"); WriteBasicType(os, binary, temp_rows); WriteBasicType(os, binary, temp_cols); int32 num_steps = steps.size(); WriteToken(os, binary, "<NumSteps>"); WriteBasicType(os, binary, num_steps); for (int32 s = 0; s < num_steps; s++) { const ConvolutionStep &step = steps[s]; WriteToken(os, binary, "<TimeShift>"); WriteBasicType(os, binary, step.input_time_shift); WriteToken(os, binary, "<ParamsStartCol>"); WriteBasicType(os, binary, step.params_start_col); WriteToken(os, binary, "<HeightMap>"); WriteIntegerVector(os, binary, step.height_map); } WriteToken(os, binary, "</ConvComputation>"); } void ConvolutionComputation::Read(std::istream &is, bool binary) { ExpectOneOrTwoTokens(is, binary, "<ConvComputation>", "<NumFiltersInOut>"); ReadBasicType(is, binary, &num_filters_in); ReadBasicType(is, binary, &num_filters_out); ExpectToken(is, binary, "<HeightInOut>"); ReadBasicType(is, binary, &height_in); ReadBasicType(is, binary, &height_out); ExpectToken(is, binary, "<NumTInOut>"); ReadBasicType(is, binary, &num_t_in); ReadBasicType(is, binary, &num_t_out); ExpectToken(is, binary, "<NumImages>"); ReadBasicType(is, binary, &num_images); ExpectToken(is, binary, "<TempRowsCols>"); ReadBasicType(is, binary, &temp_rows); ReadBasicType(is, binary, &temp_cols); int32 num_steps; ExpectToken(is, binary, "<NumSteps>"); ReadBasicType(is, binary, &num_steps); steps.resize(num_steps); for (int32 s = 0; s < num_steps; s++) { ConvolutionStep &step = steps[s]; ExpectToken(is, binary, "<TimeShift>"); ReadBasicType(is, binary, &step.input_time_shift); ExpectToken(is, binary, "<ParamsStartCol>"); ReadBasicType(is, binary, &step.params_start_col); ExpectToken(is, binary, "<HeightMap>"); ReadIntegerVector(is, binary, &step.height_map); } ExpectToken(is, binary, "</ConvComputation>"); ComputeDerived(); Check(); } void ConvolutionComputation::Check() const { KALDI_ASSERT(num_filters_in > 0 && num_filters_out > 0 && height_in > 0 && height_out > 0); KALDI_ASSERT(num_t_in >= num_t_out && num_t_out > 0 && num_images > 0); KALDI_ASSERT((temp_rows == 0 && temp_cols == 0) || (temp_rows <= num_t_out * num_images && temp_cols > 0)); KALDI_ASSERT(temp_rows % num_images == 0); bool temp_mat_required = false; int32 num_steps = steps.size(); int32 num_extra_input_times = num_t_in - num_t_out, input_cols = num_filters_in * height_in, smallest_time_shift = 1000, largest_time_shift = 0; // check 'steps' for (int32 s = 0; s < num_steps; s++) { const ConvolutionStep &step = steps[s]; KALDI_ASSERT(step.input_time_shift >= 0 && step.input_time_shift <= num_extra_input_times); if (step.input_time_shift < smallest_time_shift) smallest_time_shift = step.input_time_shift; if (step.input_time_shift > largest_time_shift) largest_time_shift = step.input_time_shift; KALDI_ASSERT(step.params_start_col >= 0 && step.params_start_col % num_filters_in == 0); if (s != 0) { KALDI_ASSERT(step.input_time_shift != steps[s-1].input_time_shift); } std::vector<int32> columns; step.columns.CopyToVec(&columns); KALDI_ASSERT(step.first_column == columns[0]); KALDI_ASSERT(step.columns.Dim() == step.height_map.size() * num_filters_in); bool all_negative = true; int32 temp_height = step.height_map.size(); bool contiguous = true; for (int32 i = 0; i < temp_height; i++) { int32 h = step.height_map[i]; KALDI_ASSERT(h >= -1 && h < height_in); if (i > 0 && step.height_map[i-1] != h-1) contiguous = false; if (h == -1) { contiguous = false; for (int32 f = 0; f < num_filters_in; f++) { KALDI_ASSERT(columns[i * num_filters_in + f] == -1); } } else { all_negative = false; for (int32 f = 0; f < num_filters_in; f++) { KALDI_ASSERT(columns[i * num_filters_in + f] == h * num_filters_in + f); } } } KALDI_ASSERT(contiguous == step.columns_are_contiguous); if (!contiguous || columns.size() != input_cols) { // we would need the temporary matrix. Make sure the // temporary matrix is big enough. temp_mat_required = true; KALDI_ASSERT(columns.size() <= temp_cols); } KALDI_ASSERT(!all_negative); std::vector<int32> columns_reconstructed(columns.size(), -1); // reconstruct 'columns' from backward_columns as a way to // check that backward_columns is correct. // they are reverse-direction maps, but we may need // step.backward_columns.size() > 1 because of elements // in the input that are duplicated in the temp matrix. for (size_t k = 0; k < step.backward_columns.size(); k++) { std::vector<int32> backward_columns; step.backward_columns[k].CopyToVec(&backward_columns); KALDI_ASSERT(int32(backward_columns.size()) == num_filters_in * height_in); for (int32 l = 0; l < num_filters_in * height_in; l++) { int32 c = backward_columns[l]; KALDI_ASSERT(c < int32(columns.size())); if (c != -1) { KALDI_ASSERT(columns_reconstructed[c] == -1); columns_reconstructed[c] = l; } } } KALDI_ASSERT(columns_reconstructed == columns); } // check that all rows of the input were used. KALDI_ASSERT(smallest_time_shift == 0 && largest_time_shift == num_extra_input_times); // check that the temp matrix is only allocated if it is required. KALDI_ASSERT((temp_cols != 0) == temp_mat_required); } // Internal function called inside ConvolveForward. // Note: the number of time steps covered may be different // from that implied by cc.num_t_in and cc.num_t_out // if the matrices are very large and we've broken the // computation up into pieces to save memoiry. static void ConvolveForwardInternal( const ConvolutionComputation &cc, const CuMatrixBase<BaseFloat> &input, const CuMatrixBase<BaseFloat> &params, CuMatrixBase<BaseFloat> *temp_mat, CuMatrixBase<BaseFloat> *output) { KALDI_ASSERT(temp_mat->Stride() == temp_mat->NumCols()); // num_t_out supersedes cc.num_t_out (they'll only be different in // cases where we are doing the computation in pieces to save memory). int32 input_rows = input.NumRows(), output_rows = output->NumRows(); KALDI_ASSERT(output_rows <= input_rows && input_rows % cc.num_images == 0 && output_rows % cc.num_images == 0); int32 num_steps = cc.steps.size(); for (int32 s = 0; s < num_steps; s++) { const ConvolutionComputation::ConvolutionStep &step = cc.steps[s]; int32 input_row_start = step.input_time_shift * cc.num_images; // note: 'input_part' will normally be almost all of 'input', perhaps // minus one or two time steps at the start or end. CuSubMatrix<BaseFloat> input_part(input, input_row_start, output_rows, 0, input.NumCols()); int32 temp_num_cols = step.columns.Dim(), param_cols = temp_num_cols / cc.height_out; CuSubMatrix<BaseFloat> params_part(params, 0, params.NumRows(), step.params_start_col, param_cols); CuSubMatrix<BaseFloat> output_reshaped( output->Data(), output_rows * cc.height_out, cc.num_filters_out, cc.num_filters_out); if (!step.columns_are_contiguous || temp_num_cols != input.NumCols()) { // In most cases we will take this branch, where we have to copy the input // to a temporary matrix. (however, different steps may require different // num-cols of the temporary matrix, so we create sub-parts of 'temp_mat'. // We create the sub-matrix 'temp_mat_part' in a lower-level way, using // pointers, because we need to ensure that its num-cols and the stride // are the same (this is necessary so that we can do reshaping in // ConvolutionReshapedMultiply()). CuSubMatrix<BaseFloat> temp_mat_part(temp_mat->Data(), temp_mat->NumRows(), temp_num_cols, temp_num_cols); if (!step.columns_are_contiguous) { // we're doing a column mapping. temp_mat_part.CopyCols(input_part, step.columns); } else { // we're just taking a sub-matrix of the input matrix, but we still need // to make a copy because we need the stride == num-cols (so that the // reshaping will work). temp_mat_part.CopyFromMat(input_part.ColRange(step.first_column, step.columns.Dim())); } CuSubMatrix<BaseFloat> temp_mat_part_reshaped( temp_mat_part.Data(), temp_mat_part.NumRows() * cc.height_out, temp_num_cols / cc.height_out, temp_num_cols / cc.height_out); output_reshaped.AddMatMat(1.0, temp_mat_part_reshaped, kNoTrans, params_part, kTrans, 1.0); } else { CuSubMatrix<BaseFloat> input_reshaped( input_part.Data(), input_part.NumRows() * cc.height_out, input_part.NumCols() / cc.height_out, input_part.NumCols() / cc.height_out); output_reshaped.AddMatMat(1.0, input_reshaped, kNoTrans, params_part, kTrans, 1.0); } } } void ConvolveForward( const ConvolutionComputation &cc, const CuMatrixBase<BaseFloat> &input, const CuMatrixBase<BaseFloat> &params, CuMatrixBase<BaseFloat> *output) { KALDI_ASSERT(input.NumCols() == input.Stride() && output->NumCols() == output->Stride()); KALDI_ASSERT(params.NumRows() == cc.num_filters_out); KALDI_ASSERT(output->NumRows() == cc.num_t_out * cc.num_images && output->NumCols() == cc.height_out * cc.num_filters_out); // the input might need to be reshaped but we can check its total size. KALDI_ASSERT(input.NumRows() * input.NumCols() == cc.num_images * cc.num_t_in * cc.height_in * cc.num_filters_in); int32 input_rows = input.NumRows(), required_input_rows = cc.num_images * cc.num_t_in; // this if-statement handles reshaping the input and recursing if there // is subsampling. if (input_rows != required_input_rows) { if (input_rows % required_input_rows != 0) KALDI_ERR << "Input matrix has wrong size."; // error in calling code. // nr is a multiple of required_nr. Reshape the matrix. // we already checked that its Stride() == NumCols(); int32 num_cols = input.NumCols(), multiple = input_rows / required_input_rows, new_num_cols = num_cols * multiple, new_stride = new_num_cols; CuSubMatrix<BaseFloat> input_reshaped( input.Data(), required_input_rows, new_num_cols, new_stride); ConvolveForward(cc, input_reshaped, params, output); return; } CuMatrix<BaseFloat> temp_mat(cc.temp_rows, cc.temp_cols, kUndefined, kStrideEqualNumCols); // this if-statement handles breaking up the arguments // and the computation into row-ranges if the temporary // matrix would have been excessively large, and we've decided // to give it fewer rows than the output (this saves // memory). normally we won't take this if-statement // so ignore it if you're trying to understand the framework. if (cc.temp_rows != 0 && cc.temp_rows != input_rows) { KALDI_ASSERT(cc.temp_rows % cc.num_images == 0); int32 num_time_steps_per_chunk = cc.temp_rows / cc.num_images; int32 num_extra_in = cc.num_t_in - cc.num_t_out; for (int32 t_start = 0; t_start < cc.num_t_out; t_start += num_time_steps_per_chunk) { int32 num_t_left = cc.num_t_out - t_start, this_num_t_out = std::min<int32>(num_t_left, num_time_steps_per_chunk), this_num_t_in = this_num_t_out + num_extra_in; CuSubMatrix<BaseFloat> input_part(input, t_start * cc.num_images, this_num_t_in * cc.num_images, 0, input.NumCols()); CuSubMatrix<BaseFloat> output_part(*output, t_start * cc.num_images, this_num_t_out * cc.num_images, 0, output->NumCols()); CuSubMatrix<BaseFloat> temp_part(temp_mat, 0, this_num_t_out * cc.num_images, 0, temp_mat.NumCols()); ConvolveForwardInternal(cc, input_part, params, &temp_part, &output_part); } return; } ConvolveForwardInternal(cc, input, params, &temp_mat, output); } // Internal function called inside ConvolveBackwardData. // Note: the number of time steps covered may be different // from that implied by cc.num_t_in and cc.num_t_out // if the matrices are very large and we've broken the // computation up into pieces to save memory. // We require that temp_mat should not contain inf's // or nan's on entry. static void ConvolveBackwardDataInternal( const ConvolutionComputation &cc, const CuMatrixBase<BaseFloat> &params, const CuMatrixBase<BaseFloat> &output_deriv, CuMatrixBase<BaseFloat> *temp_mat, CuMatrixBase<BaseFloat> *input_deriv) { KALDI_ASSERT(temp_mat->Stride() == temp_mat->NumCols()); // num_t_out supersedes cc.num_t_out (they'll only be different in // cases where we are doing the computation in pieces to save memory). int32 input_rows = input_deriv->NumRows(), output_rows = output_deriv.NumRows(); KALDI_ASSERT(output_rows <= input_rows && input_rows % cc.num_images == 0 && output_rows % cc.num_images == 0); int32 num_steps = cc.steps.size(); for (int32 s = 0; s < num_steps; s++) { const ConvolutionComputation::ConvolutionStep &step = cc.steps[s]; int32 input_row_start = step.input_time_shift * cc.num_images; CuSubMatrix<BaseFloat> input_deriv_part(*input_deriv, input_row_start, output_rows, 0, input_deriv->NumCols()); int32 temp_num_cols = step.columns.Dim(), param_cols = temp_num_cols / cc.height_out; CuSubMatrix<BaseFloat> params_part(params, 0, params.NumRows(), step.params_start_col, param_cols); CuSubMatrix<BaseFloat> output_deriv_reshaped( output_deriv.Data(), output_rows * cc.height_out, cc.num_filters_out, cc.num_filters_out); if (!step.columns_are_contiguous || temp_num_cols != input_deriv->NumCols()) { // In most cases we will take this branch, where we have to propagate the // input-derivative via a temporary matrix. (however, different steps may // require different num-cols of the temporary matrix, so we create // sub-parts of 'temp_mat'. // We create the sub-matrix 'temp_mat_part' in a lower-level way, using // pointers, because we need to ensure that its num-cols and the stride // are the same (this is necessary so that we can do reshaping in // ConvolutionReshapedMultiply()). CuSubMatrix<BaseFloat> temp_mat_part(temp_mat->Data(), temp_mat->NumRows(), temp_num_cols, temp_num_cols), temp_mat_part_reshaped( temp_mat_part.Data(), temp_mat_part.NumRows() * cc.height_out, temp_num_cols / cc.height_out, temp_num_cols / cc.height_out); temp_mat_part_reshaped.AddMatMat(1.0, output_deriv_reshaped, kNoTrans, params_part, kNoTrans, 0.0); if (!step.columns_are_contiguous) { for (size_t i = 0; i < step.backward_columns.size(); i++) { input_deriv_part.AddCols(temp_mat_part, step.backward_columns[i]); } } else { // we're just taking a sub-matrix of the input matrix, but we still need // to make a copy because we need the stride == num-cols (so that the // reshaping will work). int32 num_cols = step.columns.Dim(); input_deriv_part.ColRange(step.first_column, num_cols).AddMat(1.0, temp_mat_part); } } else { CuSubMatrix<BaseFloat> input_deriv_reshaped( input_deriv_part.Data(), input_deriv_part.NumRows() * cc.height_out, input_deriv_part.NumCols() / cc.height_out, input_deriv_part.NumCols() / cc.height_out); input_deriv_reshaped.AddMatMat(1.0, output_deriv_reshaped, kNoTrans, params_part, kNoTrans, 1.0); } } } void ConvolveBackwardData( const ConvolutionComputation &cc, const CuMatrixBase<BaseFloat> &params, const CuMatrixBase<BaseFloat> &output_deriv, CuMatrixBase<BaseFloat> *input_deriv) { KALDI_ASSERT(input_deriv->NumCols() == input_deriv->Stride() && output_deriv.NumCols() == output_deriv.Stride()); KALDI_ASSERT(params.NumRows() == cc.num_filters_out); KALDI_ASSERT(output_deriv.NumRows() == cc.num_t_out * cc.num_images && output_deriv.NumCols() == cc.height_out * cc.num_filters_out); // the input might need to be reshaped but we can check its total size. KALDI_ASSERT(input_deriv->NumRows() * input_deriv->NumCols() == cc.num_images * cc.num_t_in * cc.height_in * cc.num_filters_in); int32 input_rows = input_deriv->NumRows(), required_input_rows = cc.num_images * cc.num_t_in; // this if-statement handles reshaping the input and recursing if there // is subsampling. if (input_rows != required_input_rows) { if (input_rows % required_input_rows != 0) KALDI_ERR << "Input matrix has wrong size."; // error in calling code. // nr is a multiple of required_nr. Reshape the matrix. // we already checked that its Stride() == NumCols(); int32 num_cols = input_deriv->NumCols(), multiple = input_rows / required_input_rows, new_num_cols = num_cols * multiple, new_stride = new_num_cols; CuSubMatrix<BaseFloat> input_deriv_reshaped( input_deriv->Data(), required_input_rows, new_num_cols, new_stride); ConvolveBackwardData(cc, params, output_deriv, &input_deriv_reshaped); return; } CuMatrix<BaseFloat> temp_mat(cc.temp_rows, cc.temp_cols, kSetZero, kStrideEqualNumCols); // this if-statement handles breaking up the arguments // and the computation into row-ranges if the temporary // matrix would have been excessively large, and we've decided // to give it fewer rows than the output (this saves // memory). normally we won't take this if-statement // so ignore it if you're trying to understand the framework. if (cc.temp_rows != 0 && cc.temp_rows != input_rows) { KALDI_ASSERT(cc.temp_rows % cc.num_images == 0); int32 num_time_steps_per_chunk = cc.temp_rows / cc.num_images; int32 num_extra_in = cc.num_t_in - cc.num_t_out; for (int32 t_start = 0; t_start < cc.num_t_out; t_start += num_time_steps_per_chunk) { int32 num_t_left = cc.num_t_out - t_start, this_num_t_out = std::min<int32>(num_t_left, num_time_steps_per_chunk), this_num_t_in = this_num_t_out + num_extra_in; CuSubMatrix<BaseFloat> input_deriv_part( *input_deriv, t_start * cc.num_images, this_num_t_in * cc.num_images, 0, input_deriv->NumCols()); CuSubMatrix<BaseFloat> output_deriv_part( output_deriv, t_start * cc.num_images, this_num_t_out * cc.num_images, 0, output_deriv.NumCols()); CuSubMatrix<BaseFloat> temp_part( temp_mat, 0, this_num_t_out * cc.num_images, 0, temp_mat.NumCols()); ConvolveBackwardDataInternal(cc, params, output_deriv_part, &temp_part, &input_deriv_part); } return; } ConvolveBackwardDataInternal(cc, params, output_deriv, &temp_mat, input_deriv); } // Internal function called inside ConvolveBackwardParams. // Note: the number of time steps covered may be different // from that implied by cc.num_t_in and cc.num_t_out // if the matrices are very large and we've broken the // computation up into pieces to save memoiry. static void ConvolveBackwardParamsInternal( const ConvolutionComputation &cc, const CuMatrixBase<BaseFloat> &input, const CuMatrixBase<BaseFloat> &output_deriv, BaseFloat alpha, CuMatrixBase<BaseFloat> *temp_mat, CuMatrixBase<BaseFloat> *params_deriv) { KALDI_ASSERT(temp_mat->Stride() == temp_mat->NumCols()); // num_t_out supersedes cc.num_t_out (they'll only be different in // cases where we are doing the computation in pieces to save memory). int32 input_rows = input.NumRows(), output_rows = output_deriv.NumRows(); KALDI_ASSERT(output_rows <= input_rows && input_rows % cc.num_images == 0 && output_rows % cc.num_images == 0); int32 num_steps = cc.steps.size(); for (int32 s = 0; s < num_steps; s++) { const ConvolutionComputation::ConvolutionStep &step = cc.steps[s]; int32 input_row_start = step.input_time_shift * cc.num_images; // note: 'input_part' will normally be almost all of 'input', perhaps // minus one or two time steps at the start or end. CuSubMatrix<BaseFloat> input_part(input, input_row_start, output_rows, 0, input.NumCols()); int32 temp_num_cols = step.columns.Dim(), param_cols = temp_num_cols / cc.height_out; CuSubMatrix<BaseFloat> params_deriv_part(*params_deriv, 0, params_deriv->NumRows(), step.params_start_col, param_cols); CuSubMatrix<BaseFloat> output_deriv_reshaped( output_deriv.Data(), output_rows * cc.height_out, cc.num_filters_out, cc.num_filters_out); if (!step.columns_are_contiguous || temp_num_cols != input.NumCols()) { // In most cases we will take this branch, where we have to copy the input // to a temporary matrix. (however, different steps may require different // num-cols of the temporary matrix, so we create sub-parts of 'temp_mat'. // We create the sub-matrix 'temp_mat_part' in a lower-level way, using // pointers, because we need to ensure that its num-cols and the stride // are the same (this is necessary so that we can do reshaping in // ConvolutionReshapedMultiply()). CuSubMatrix<BaseFloat> temp_mat_part(temp_mat->Data(), temp_mat->NumRows(), temp_num_cols, temp_num_cols); if (!step.columns_are_contiguous) { // we're doing a column mapping. temp_mat_part.CopyCols(input_part, step.columns); } else { // we're just taking a sub-matrix of the input matrix, but we still need // to make a copy because we need the stride == num-cols (so that the // reshaping will work). temp_mat_part.CopyFromMat(input_part.ColRange(step.first_column, step.columns.Dim())); } CuSubMatrix<BaseFloat> temp_mat_part_reshaped( temp_mat_part.Data(), temp_mat_part.NumRows() * cc.height_out, temp_num_cols / cc.height_out, temp_num_cols / cc.height_out); params_deriv_part.AddMatMat(alpha, output_deriv_reshaped, kTrans, temp_mat_part_reshaped, kNoTrans, 1.0); } else { CuSubMatrix<BaseFloat> input_reshaped( input_part.Data(), input_part.NumRows() * cc.height_out, input_part.NumCols() / cc.height_out, input_part.NumCols() / cc.height_out); params_deriv_part.AddMatMat(alpha, output_deriv_reshaped, kTrans, input_reshaped, kNoTrans, 1.0); } } } void ConvolveBackwardParams( const ConvolutionComputation &cc, const CuMatrixBase<BaseFloat> &input, const CuMatrixBase<BaseFloat> &output_deriv, BaseFloat alpha, CuMatrixBase<BaseFloat> *params_deriv) { KALDI_ASSERT(input.NumCols() == input.Stride() && output_deriv.NumCols() == output_deriv.Stride()); KALDI_ASSERT(params_deriv->NumRows() == cc.num_filters_out); KALDI_ASSERT(output_deriv.NumRows() == cc.num_t_out * cc.num_images && output_deriv.NumCols() == cc.height_out * cc.num_filters_out); // the input might need to be reshaped but we can check its total size. KALDI_ASSERT(input.NumRows() * input.NumCols() == cc.num_images * cc.num_t_in * cc.height_in * cc.num_filters_in); int32 input_rows = input.NumRows(), required_input_rows = cc.num_images * cc.num_t_in; // this if-statement handles reshaping the input and recursing if there // is subsampling. if (input_rows != required_input_rows) { if (input_rows % required_input_rows != 0) KALDI_ERR << "Input matrix has wrong size."; // error in calling code. // nr is a multiple of required_nr. Reshape the matrix. // we already checked that its Stride() == NumCols(); int32 num_cols = input.NumCols(), multiple = input_rows / required_input_rows, new_num_cols = num_cols * multiple, new_stride = new_num_cols; CuSubMatrix<BaseFloat> input_reshaped( input.Data(), required_input_rows, new_num_cols, new_stride); ConvolveBackwardParams(cc, input_reshaped, output_deriv, alpha, params_deriv); return; } CuMatrix<BaseFloat> temp_mat(cc.temp_rows, cc.temp_cols, kUndefined, kStrideEqualNumCols); // this if-statement handles breaking up the arguments // and the computation into row-ranges if the temporary // matrix would have been excessively large, and we've decided // to give it fewer rows than the output (this saves // memory). normally we won't take this if-statement // so ignore it if you're trying to understand the framework. if (cc.temp_rows != 0 && cc.temp_rows != input_rows) { KALDI_ASSERT(cc.temp_rows % cc.num_images == 0); int32 num_time_steps_per_chunk = cc.temp_rows / cc.num_images; int32 num_extra_in = cc.num_t_in - cc.num_t_out; for (int32 t_start = 0; t_start < cc.num_t_out; t_start += num_time_steps_per_chunk) { int32 num_t_left = cc.num_t_out - t_start, this_num_t_out = std::min<int32>(num_t_left, num_time_steps_per_chunk), this_num_t_in = this_num_t_out + num_extra_in; CuSubMatrix<BaseFloat> input_part( input, t_start * cc.num_images, this_num_t_in * cc.num_images, 0, input.NumCols()); CuSubMatrix<BaseFloat> output_deriv_part( output_deriv, t_start * cc.num_images, this_num_t_out * cc.num_images, 0, output_deriv.NumCols()); CuSubMatrix<BaseFloat> temp_part(temp_mat, 0, this_num_t_out * cc.num_images, 0, temp_mat.NumCols()); ConvolveBackwardParamsInternal(cc, input_part, output_deriv_part, alpha, &temp_part, params_deriv); } return; } ConvolveBackwardParamsInternal(cc, input, output_deriv, alpha, &temp_mat, params_deriv); } void PadModelHeight(const ConvolutionModel &model, ConvolutionModel *model_padded) { *model_padded = model; KALDI_ASSERT(!model.offsets.empty()); int32 min_height_offset = model.offsets[0].height_offset, max_height_offset = model.offsets[0].height_offset, num_offsets = model.offsets.size(); for (int32 i = 1; i < num_offsets; i++) { min_height_offset = std::min<int32>(min_height_offset, model.offsets[i].height_offset); max_height_offset = std::max<int32>(max_height_offset, model.offsets[i].height_offset); } int32 max_output_height = model.height_subsample_out * (model.height_out - 1), max_required_input = max_height_offset + max_output_height, min_required_input = min_height_offset + 0; int32 bottom_padding = -min_required_input, top_padding = max_required_input - (model.height_in - 1); if (bottom_padding < 0) bottom_padding = 0; if (top_padding < 0) top_padding = 0; model_padded->height_in += bottom_padding + top_padding; for (int32 i = 0; i < num_offsets; i++) model_padded->offsets[i].height_offset += bottom_padding; // The reason why we say 'allow_height_padding = false' below is obvious-- // we've 'manually' padded by changing the model, so this modified model // should not require height padding. The reason we set 'check_heights_used' // is a little more non-obvious. The very lowest and hightest heights // should always be used, but there may, in unusual models, be other heights // that are not used. We found this in random testing. KALDI_ASSERT(model_padded->Check(false, false)); } /** This function sets 'temp_rows' and 'temp_cols' in 'computation'. */ static void ComputeTempMatrixSize(const ConvolutionComputationOptions &opts, ConvolutionComputation *computation) { int32 temp_rows = 0, temp_cols = 0; for (size_t i = 0; i < computation->steps.size(); i++) { const ConvolutionComputation::ConvolutionStep &step = computation->steps[i]; int32 height_map_size = step.height_map.size(), this_num_cols = height_map_size * computation->num_filters_in; bool columns_are_contiguous = (step.height_map[0] != -1 && VectorIsContiguous(step.height_map)); bool need_temp_matrix = true; if (columns_are_contiguous && step.height_map[0] == 0 && this_num_cols == computation->num_filters_in * computation->height_in) { // the only situation in which we wouldn't need the temporary matrix // for this step, is where the columns are all of the input matrix. need_temp_matrix = false; } if (need_temp_matrix && this_num_cols > temp_cols) temp_cols = this_num_cols; } if (temp_cols > 0) { // work out how many rows the temporary matrix should have, taking // into account the specified memory limit. temp_rows = computation->num_t_out * computation->num_images; BaseFloat num_megabytes = (4 * temp_rows * temp_cols) / 1000000.0, megabyte_limit = opts.max_memory_mb; // C++ rounds down; here, we want to round up so we add one. int32 ratio = 1.0 + num_megabytes / megabyte_limit; // divide the number of time steps into 'ratio' pieces that are as equal as // possible; round up when dividing, to make sure that new_temp_rows * ratio // >= temp_rows so that we don't have a small leftover piece. int32 new_num_t_out = (computation->num_t_out + ratio - 1) / ratio; temp_rows = new_num_t_out * computation->num_images; BaseFloat new_num_megabytes = (4 * temp_rows * temp_cols) / 1000000.0; // make sure we're within the memory limit. if (new_num_megabytes > 1.01 * megabyte_limit) { KALDI_WARN << "Memory consumed in convolution is more than requested " << "(maybe very long time sequence?)"; } } computation->temp_rows = temp_rows; computation->temp_cols = temp_cols; } void UnPadModelHeight(const ConvolutionComputationOptions &opts, const ConvolutionModel &model, const ConvolutionModel &model_padded, ConvolutionComputation *computation) { // First work out how much padding was done in PadModelHeight(). int32 bottom_padding = (model_padded.offsets[0].height_offset - model.offsets[0].height_offset), total_padding = model_padded.height_in - model.height_in, top_padding = total_padding - bottom_padding; int32 old_computation_height_in = computation->height_in; // The computation may have been built for the input appended over // several frames. Check that it is for an input height that's a multiple of // the model input height. KALDI_ASSERT(old_computation_height_in % model_padded.height_in == 0 && computation->height_out == model.height_out); // 'ratio' is the same ratio from AppendInputFrames(), it's the number // of input frames in 'model' and 'model_padded' that get appended // to form a single frame in the computation. int32 num_steps = computation->steps.size(), unpadded_input_height = model.height_in, padded_input_height = model_padded.height_in, ratio = old_computation_height_in / padded_input_height; computation->height_in = ratio * unpadded_input_height; for (int32 s = 0; s < num_steps; s++) { ConvolutionComputation::ConvolutionStep &step = computation->steps[s]; int32 height_map_size = step.height_map.size(); for (int32 i = 0; i < height_map_size; i++) { int32 c = step.height_map[i]; KALDI_ASSERT(c >= 0); // there should be no -1's in the padded computation. // below, h is the actual height in terms of the padded computation, and m // is an index that goes from zero to (num-appended-frames - 1). int32 h = c % padded_input_height, m = c / padded_input_height; KALDI_ASSERT(m < ratio); if (h < bottom_padding || h >= padded_input_height - top_padding) { step.height_map[i] = -1; } else { step.height_map[i] = (h - bottom_padding) + m * unpadded_input_height; } } } ComputeTempMatrixSize(opts, computation); computation->ComputeDerived(); computation->Check(); } void PadComputationInputTime(const ConvolutionModel &model, ConvolutionComputationIo *io) { if (model.time_offsets_modulus == 0) { // this can only happen if model->all_time_offsets.size() == 1, // and no padding could be required here. W return to avoid // special cases below in Gcd(). return; } int32 min_time_offset = *model.all_time_offsets.begin(), max_time_offset = *model.all_time_offsets.rbegin(); // it makes everything much simpler if we just enforce that the stride of the // input divides model.time_offsets_modulus and also the output stride. // (enforcing this may make the input stride smaller). This may in certain // very odd cases cause us to require more inputs [actually 'blanks'] than // we really need, but it avoids a lot of careful thought. int32 old_t_step_in = io->t_step_in; io->t_step_in = Gcd(io->t_step_in, model.time_offsets_modulus); if (io->t_step_out != 0) io->t_step_in = Gcd(io->t_step_in, io->t_step_out); // to ensure that we cover all the original input points, now that // we changed the stride we may need to increase num_t_in. io->num_t_in = 1 + (old_t_step_in * (io->num_t_in - 1)) / io->t_step_in; // by 'desired' we mean usable as an input, not necessarily // required in the sense of 'required_time_offsets'. int32 first_desired_input_t = io->start_t_out + min_time_offset; if (first_desired_input_t < io->start_t_in) { KALDI_ASSERT((io->start_t_in - first_desired_input_t) % io->t_step_in == 0); io->num_t_in += (io->start_t_in - first_desired_input_t) / io->t_step_in; io->start_t_in = first_desired_input_t; } int32 last_desired_input_t = io->start_t_out + (io->num_t_out - 1) * io->t_step_out + max_time_offset, last_input_t = io->start_t_in + (io->num_t_in - 1) * io->t_step_in; // if the following assert fails, it means we had provided more input than was // needed, which is not expected. This could cause problems later, in // AppendInputFrames(). KALDI_ASSERT(last_desired_input_t >= last_input_t); if (last_desired_input_t > last_input_t) { KALDI_ASSERT((last_desired_input_t - last_input_t) % io->t_step_in == 0); io->num_t_in += (last_desired_input_t - last_input_t) / io->t_step_in; } } // returns i rounded down to a multiple of n, // e.g. RoundDownToMultipleOf(3, 2) = 2, // RoundDownToMultipleOf(-1, 3) = -3 static int32 RoundDownToMultipleOf(int32 i, int32 n) { return n * DivideRoundingDown(i, n); } // shifts all time-offsets in the model (in 'offsets[*].time_offset', // 'required_time_offsets', 'all_time_offsets') by adding 'shift' to them. static void ShiftAllTimeOffsets(int32 shift, ConvolutionModel *model) { { // shift 'offsets'. std::vector<ConvolutionModel::Offset>::iterator iter = model->offsets.begin(), end = model->offsets.end(); for (; iter != end; ++iter) iter->time_offset += shift; } std::set<int32> temp; std::set<int32>::const_iterator iter; for (iter = model->required_time_offsets.begin(); iter != model->required_time_offsets.end(); ++iter) temp.insert(*iter + shift); model->required_time_offsets.swap(temp); temp.clear(); for (iter = model->all_time_offsets.begin(); iter != model->all_time_offsets.end(); ++iter) temp.insert(*iter + shift); model->all_time_offsets.swap(temp); } /* \brief This function has been broken out of 'AppendInputFrames()' for clarity. It deals with appending input frames together, in cases where the input stride is smaller than the output stride. \param [in,out] io The input object representing the I/O of the convolution. It may be modified slightly by this function, in two respects. Firstly, if we are going to be reshaping the input into an input with fewer frames of larger dimension, we need to make sure the number of frames in the input of 'io' is a multiple of the relevant ratio, so we pad with zeros. Also, we may modify the stride of 'io' in cases where there is exactly one frame. This is for convenience of implementation and does not affect the frames represented. \param [out] io_appended The output object representing the I/O of the possibly-frame-appended computation. This may be the same as I/O, but it won't be if the input stride is smaller than the output stride-- in that case we need to append the frames. Note: at exit, 'io' and 'io_appended' will really represent two different 'views' of the same data, via a reshaping. \return Returns the integer ratio >= 1 between the num-cols of the 'appended' features and the original features; this also equals the number of frames we append together */ static int32 PrepareIoForAppending(ConvolutionComputationIo *io, ConvolutionComputationIo *io_appended) { // first make sure that the output has nonzero stride (it would only have zero // stride if there was only one output time index, which is unusual). if // there's only one output time index we can set the stride to whatever we // want without affecting the list of output indexes. int32 ratio; if (io->t_step_out == 0) { KALDI_ASSERT(io->num_t_out == 1); io->t_step_out = io->t_step_in; } if (io->t_step_out == io->t_step_in) { // there is nothing to do; the output and input strides are the same. *io_appended = *io; ratio = 1; return ratio; } // Now, we ensured in PadComputationInputTime that if the output stride is // nonzero, then the input stride must divide the output stride; and if the // output stride was zero then we would have set it to the input stride just // above; and if both were zero we would have returned above. So we can just // assert that the input stride divides the output stride. KALDI_ASSERT(io->t_step_out % io->t_step_in == 0); ratio = io->t_step_out / io->t_step_in; // ratio says how many input indexes we have for each output index, // ignoring end effects. It is the number of input indexes we will // append together and 'pretend' // record this ratio in the 'input' I/O object, which we are also // modifying to record the extra required padding. io->reorder_t_in = ratio; if (io->num_t_in % ratio != 0) { // Round up the number of input frames to the nearest multiple (via // zero-padding) so we get an whole number of appended input frames. io->num_t_in += ratio - (io->num_t_in % ratio); } // OK, from this point we create the output io object. *io_appended = *io; io_appended->reorder_t_in = 1; io_appended->t_step_in = io->t_step_out; io_appended->num_t_in /= ratio; return ratio; } void AppendInputFrames(const ConvolutionModel &model, ConvolutionComputationIo *io, ConvolutionModel *model_appended, ConvolutionComputationIo *io_appended) { int32 ratio = PrepareIoForAppending(io, io_appended); if (ratio == 1) { // we are not doing any appending of frames. *model_appended = model; return; } // we also need the time-step of the output (which is also now the // time-step of the appended input). // We know that the time step is not zero, because in that case we would // have ratio == 1 and would have returned above. int32 time_step_out = io_appended->t_step_out; KALDI_ASSERT(time_step_out == io_appended->t_step_in && time_step_out != 0); int32 orig_time_step_in = io->t_step_in; KALDI_ASSERT(orig_time_step_in * ratio == time_step_out); // make sure the difference between first input and output frames is what we // expect, else something could go wrong here. int32 first_time_offset = *(model.all_time_offsets.begin()); KALDI_ASSERT(io->start_t_in - io->start_t_out == first_time_offset); ConvolutionModel model_temp(model); // shift so that the first time offset is zero. this makes // the model conversion easier. ShiftAllTimeOffsets(-first_time_offset, &model_temp); model_appended->num_filters_in = model.num_filters_in; model_appended->num_filters_out = model.num_filters_out; model_appended->height_in = ratio * model.height_in; model_appended->height_out = model.height_out; model_appended->height_subsample_out = model.height_subsample_out; int32 num_offsets = model_temp.offsets.size(), old_height = model.height_in; model_appended->offsets.resize(num_offsets); model_appended->all_time_offsets.clear(); for (int32 i = 0; i < num_offsets; i++) { const ConvolutionModel::Offset &old_offset = model_temp.offsets[i]; ConvolutionModel::Offset &new_offset = model_appended->offsets[i]; // The following two lines are important!! They are the core of how // we handle subsampling in this framework. new_offset.time_offset = RoundDownToMultipleOf(old_offset.time_offset, time_step_out); KALDI_ASSERT((old_offset.time_offset - new_offset.time_offset) % orig_time_step_in == 0); int32 row_offset = (old_offset.time_offset - new_offset.time_offset) / orig_time_step_in; new_offset.height_offset = old_offset.height_offset + row_offset * old_height; model_appended->all_time_offsets.insert(new_offset.time_offset); } // Because the 'appended' model will always be used after zero-padding on the // time axis, we can just pretend that all desired time-offsets are required. // It's a kind of free error-checking. model_appended->required_time_offsets = model_appended->all_time_offsets; // Undo the time-shifting that we did before. ShiftAllTimeOffsets(first_time_offset, model_appended); model_appended->ComputeDerived(); KALDI_ASSERT(model_appended->Check(false, false)); } void ConvolutionComputation::ComputeDerived() { KALDI_ASSERT(!steps.empty()); int32 input_dim = height_in * num_filters_in; int32 largest_required_temp_cols = 0; for (std::vector<ConvolutionStep>::iterator iter = steps.begin(); iter != steps.end(); ++iter) { ConvolutionStep &step = *iter; std::vector<int32> columns; int32 temp_height = step.height_map.size(); columns.resize(temp_height * num_filters_in); for (int32 h = 0; h < temp_height; h++) { KALDI_ASSERT(step.height_map[h] >= -1 && step.height_map[h] < height_in); if (step.height_map[h] != -1) { for (int32 f = 0; f < num_filters_in; f++) columns[h * num_filters_in + f] = step.height_map[h] * num_filters_in + f; } else { for (int32 f = 0; f < num_filters_in; f++) columns[h * num_filters_in + f] = -1; } } step.columns.CopyFromVec(columns); std::vector<std::vector<int32> > backward_columns; ReverseColumnMapping(columns, input_dim, &backward_columns); step.backward_columns.resize(backward_columns.size()); for (size_t i = 0; i < backward_columns.size(); i++) step.backward_columns[i].CopyFromVec(backward_columns[i]); // we could replace height_map with columns in the line below and get the // same answer, but it would be a little slower. step.columns_are_contiguous = (step.height_map[0] != -1 && VectorIsContiguous(step.height_map)); step.first_column = columns[0]; bool need_temp_matrix = !(step.columns_are_contiguous && step.height_map[0] == 0 && step.height_map.size() == height_in); if (need_temp_matrix) { largest_required_temp_cols = std::max<int32>( largest_required_temp_cols, static_cast<int32>(columns.size())); } } KALDI_ASSERT(temp_cols == largest_required_temp_cols); } // returns true if the time value 't' is one of the // time values available on the input of 'io. static bool TimeValueInInput(const ConvolutionComputationIo &io, int32 t) { int32 t_step_in = std::max<int32>(1, io.t_step_in); return (t >= io.start_t_in && t < io.start_t_in + (t_step_in * io.num_t_in) && (t - io.start_t_in) % t_step_in == 0); } void CheckModelAndIo(const ConvolutionModel &model, const ConvolutionComputationIo &io, bool allow_extra_input) { KALDI_ASSERT(io.num_t_in > 0 && io.num_t_out > 0 && !model.required_time_offsets.empty() && !model.all_time_offsets.empty()); if (!allow_extra_input) { KALDI_ASSERT(io.start_t_in >= io.start_t_out + *model.all_time_offsets.begin()); int32 last_t_in = io.start_t_in + io.t_step_in * (io.num_t_in - 1), last_t_out = io.start_t_out + io.t_step_out * (io.num_t_out - 1); KALDI_ASSERT(last_t_in <= last_t_out + *model.all_time_offsets.rbegin()); } std::set<int32> input_times_to_check; for (int32 n = 0; n < std::min(5, io.num_t_out); n++) { int32 t_out = io.start_t_out + RandInt(0, io.num_t_out - 1) * io.t_step_out; for (std::set<int32>::const_iterator iter = model.required_time_offsets.begin(); iter != model.required_time_offsets.end(); ++iter) { int32 offset = *iter; input_times_to_check.insert(t_out + offset); } } for (std::set<int32>::const_iterator iter = input_times_to_check.begin(); iter != input_times_to_check.end(); ++iter) { int32 t = *iter; if (!TimeValueInInput(io, t)) { KALDI_ERR << "Error checking model and IO: time " << t << " is required but not in the input."; } } } void CompileConvolutionComputation( const ConvolutionModel &model, const std::vector<Index> &input_indexes, const std::vector<Index> &output_indexes, const ConvolutionComputationOptions &opts, ConvolutionComputation *computation, std::vector<Index> *input_indexes_modified, std::vector<Index> *output_indexes_modified) { // stage zero [preparing the input and output in a regular grid.] ConvolutionComputationIo io; GetComputationIo(input_indexes, output_indexes, &io); CheckModelAndIo(model, io, false); // stage 1. PadComputationInputTime(model, &io); CheckModelAndIo(model, io, false); // stage 2. ConvolutionModel model_padded; PadModelHeight(model, &model_padded); CheckModelAndIo(model_padded, io, false); // stage 3. ConvolutionModel model_appended; ConvolutionComputationIo io_appended; // make a 'fake' model and io for possibly-appended input frames. 'io' is // non-const because we may need to pad with a few extra frames. AppendInputFrames(model_padded, &io, &model_appended, &io_appended); CheckModelAndIo(model_appended, io_appended, true); // stage 4. MakeComputation(model_appended, io_appended, opts, computation); // 'reverse' of stage 2. [stage 3 kind of does its own // 'reverse' by modifying its input IO object.] // The computation is still specified for the appended input, // but the execution code can figure that out itself. UnPadModelHeight(opts, model, model_padded, computation); GetIndexesForComputation(io, input_indexes, output_indexes, input_indexes_modified, output_indexes_modified); } // Returns the greatest common divisor of the differences between the values in // 'vec', or zero if the vector has zero or one element. It is an error if // 'vec' has repeated elements (which could cause a crash in 'Gcd'). static int32 FindGcdOfDifferences(std::vector<int32> &vec) { size_t size = vec.size(); int32 ans = 0; for (size_t i = 0; i + 1 < size; i++) { int32 diff = vec[i+1] - vec[i]; // diff should not be zero. ans = Gcd(ans, diff); } return ans; } static void RegularizeTList(std::vector<int32> &t_values, int32 *start, int32 *step, int32 *num_values) { KALDI_ASSERT(!t_values.empty() && IsSortedAndUniq(t_values)); *start = t_values[0]; *step = FindGcdOfDifferences(t_values); if (*step == 0) { KALDI_ASSERT(t_values.size() == 1); *num_values = 1; } else { int32 last_value = t_values.back(); *num_values = 1 + (last_value - *start) / *step; KALDI_ASSERT((last_value - *start) % *step == 0); } } /** Creates a vector of indexes with a regular structure, according to these specifications. 'n_x_pairs' is the list of (n,x) pairs to include; they will appear in this order. 't_start', 't_step' and 'num_t_values' define the set of 't' values to include (note: t_step >= 0; they will appear in the natural order). If reorder_t == 1 (the normal case), then the order is simple: 't' has the higher stride, then (n, x). So we'll output first all (n, x) pairs for t_start, then all pairs for t_start + t_step, and so on. If instead reorder_t > 1, then the order is a little different [note: we expect that num_t_values % reorder_t == 0). Consider, for example, reorder_t == 2. In that case the first block has the first two t values, the second block has the next two t values, and so on. And within each block, the 't' values have the smallest stride (of 1). */ static void CreateIndexes(const std::vector<std::pair<int32, int32> > &n_x_pairs, int32 t_start, int32 t_step, int32 num_t_values, int32 reorder_t, std::vector<Index> *indexes) { KALDI_ASSERT(reorder_t >= 1 && num_t_values % reorder_t == 0 && t_step >= 0); if (t_step == 0) { KALDI_ASSERT(num_t_values == 1); t_step = 1; } int32 num_n_x_pairs = n_x_pairs.size(); indexes->clear(); indexes->reserve(num_n_x_pairs * num_t_values); int32 outer_t_step = t_step * reorder_t, t_end = t_start + (num_t_values * t_step); Index index; for (int32 t_block = t_start; t_block < t_end; t_block += outer_t_step) { for (int32 nx = 0; nx < num_n_x_pairs; nx++) { index.n = n_x_pairs[nx].first; index.x = n_x_pairs[nx].second; for (int32 t = t_block; t < t_block + outer_t_step; t += t_step) { index.t = t; indexes->push_back(index); } } } // we can remove the next assert after a while. KALDI_ASSERT(indexes->size() == num_n_x_pairs * num_t_values); } /** This function modifies 'indexes' by, for any Indexes which was not present in 'ref_indexes', setting the 't' value to kNoTime. This will cause the nnet3 framework to ignore such Indexes for certain purposes, it supresses certain error conditions that would otherwise happen from inserting unnecessary indexes into the input and output. */ static void SetSomeIndexesBlank(const std::vector<Index> &ref_indexes, std::vector<Index> *indexes) { std::unordered_set<Index, IndexHasher> ref_set; for (std::vector<Index>::const_iterator iter = ref_indexes.begin(); iter != ref_indexes.end(); ++iter) ref_set.insert(*iter); for (std::vector<Index>::iterator iter = indexes->begin(); iter != indexes->end(); ++iter) { if (ref_set.count(*iter) == 0) iter->t = kNoTime; } } void GetComputationIo( const std::vector<Index> &input_indexes, const std::vector<Index> &output_indexes, ConvolutionComputationIo *io) { std::vector<std::pair<int32, int32> > n_x_pairs; GetNxList(input_indexes, &n_x_pairs); KALDI_ASSERT(!n_x_pairs.empty()); io->num_images = n_x_pairs.size(); if (GetVerboseLevel() >= 3) { // a debugging step. std::vector<std::pair<int32, int32> > n_x_pairs_2; GetNxList(output_indexes, &n_x_pairs_2); KALDI_ASSERT(n_x_pairs_2 == n_x_pairs); } std::vector<int32> t_values; GetTList(input_indexes, &t_values); RegularizeTList(t_values, &(io->start_t_in), &(io->t_step_in), &(io->num_t_in)); GetTList(output_indexes, &t_values); RegularizeTList(t_values, &(io->start_t_out), &(io->t_step_out), &(io->num_t_out)); io->reorder_t_in = 1; } void GetIndexesForComputation( const ConvolutionComputationIo &io, const std::vector<Index> &orig_input_indexes, const std::vector<Index> &orig_output_indexes, std::vector<Index> *input_indexes, std::vector<Index> *output_indexes) { std::unordered_set<Index, IndexHasher> input_set, output_set; for (std::vector<Index>::const_iterator iter = orig_input_indexes.begin(); iter != orig_input_indexes.end(); ++iter) input_set.insert(*iter); for (std::vector<Index>::const_iterator iter = orig_output_indexes.begin(); iter != orig_output_indexes.end(); ++iter) output_set.insert(*iter); std::vector<std::pair<int32, int32> > n_x_pairs; GetNxList(orig_input_indexes, &n_x_pairs); KALDI_ASSERT(n_x_pairs.size() == io.num_images); CreateIndexes(n_x_pairs, io.start_t_in, io.t_step_in, io.num_t_in, io.reorder_t_in, input_indexes); SetSomeIndexesBlank(orig_input_indexes, input_indexes); CreateIndexes(n_x_pairs, io.start_t_out, io.t_step_out, io.num_t_out, 1, output_indexes); SetSomeIndexesBlank(orig_output_indexes, output_indexes); } void MakeComputation(const ConvolutionModel &model, ConvolutionComputationIo &io, const ConvolutionComputationOptions &opts, ConvolutionComputation *computation) { KALDI_ASSERT(io.t_step_in == io.t_step_out); computation->num_filters_in = model.num_filters_in; computation->num_filters_out = model.num_filters_out; computation->height_in = model.height_in; computation->height_out = model.height_out; computation->num_t_in = io.num_t_in; computation->num_t_out = io.num_t_out; computation->num_images = io.num_images; KALDI_ASSERT(io.reorder_t_in == 1); // first work out the steps of the computation, then // work out the dim of the temp matrix KALDI_ASSERT(IsSortedAndUniq(model.offsets)); // Each distinct value of 'time_offset' in model.offsets // becomes one step of the computation. // if io.t_step_in was zero, use 1 (so divisions and the like will work as // expected). int32 t_step = std::max<int32>(1, io.t_step_in), num_t_extra = io.num_t_in - io.num_t_out; computation->steps.clear(); int32 num_offsets = model.offsets.size(), cur_start_offset = 0, cur_end_offset = 0; for(; cur_start_offset < num_offsets; cur_start_offset = cur_end_offset) { cur_end_offset = cur_start_offset; while (cur_end_offset < num_offsets && model.offsets[cur_end_offset].time_offset == model.offsets[cur_start_offset].time_offset) cur_end_offset++; // we are processing the range of indexes into 'offsets' // from cur_start_offset to cur_end_offset - 1. int32 this_num_offsets = cur_end_offset - cur_start_offset; int32 time_offset = model.offsets[cur_start_offset].time_offset; ConvolutionComputation::ConvolutionStep step; // modified_time_offset will be used in working out the 'input_time_shift' // that determines which submatrix of the input matrix we'll use. // It equals the time-offset corrected for any time-difference between // the start of the output and of the input. int32 modified_time_offset = time_offset + io.start_t_out - io.start_t_in; KALDI_ASSERT(modified_time_offset >= 0 && modified_time_offset % t_step == 0); step.input_time_shift = modified_time_offset / t_step; KALDI_ASSERT(step.input_time_shift <= num_t_extra); step.params_start_col = model.num_filters_in * cur_start_offset; step.height_map.clear(); step.height_map.reserve(model.height_out * this_num_offsets); for (int32 h_out = 0; h_out < model.height_out * model.height_subsample_out; h_out += model.height_subsample_out) { for (int32 o = cur_start_offset; o < cur_end_offset; o++) { int32 this_height_offset = model.offsets[o].height_offset, h_in = h_out + this_height_offset; // by the time we call MakeComputation, the user should already have // called PadModelHeight, so there should be no need for zero padding on // the height axis, hence the following check. [we'll later modify the // resulting computation in UnPadModelHeight, and that's where // zero-padding gets taken account of.] KALDI_ASSERT(h_in >= 0 && h_in < model.height_in); step.height_map.push_back(h_in); } } computation->steps.push_back(step); } ComputeTempMatrixSize(opts, computation); } void ConvolutionComputationIo::Write(std::ostream &os, bool binary) const { WriteToken(os, binary, "<ConvCompIo>"); WriteBasicType(os, binary, num_images); WriteBasicType(os, binary, start_t_in); WriteBasicType(os, binary, t_step_in); WriteBasicType(os, binary, num_t_in); WriteBasicType(os, binary, start_t_out); WriteBasicType(os, binary, t_step_out); WriteBasicType(os, binary, num_t_out); WriteBasicType(os, binary, reorder_t_in); WriteToken(os, binary, "</ConvCompIo>"); } void ConvolutionComputationIo::Read(std::istream &is, bool binary) { ExpectToken(is, binary, "<ConvCompIo>"); ReadBasicType(is, binary, &num_images); ReadBasicType(is, binary, &start_t_in); ReadBasicType(is, binary, &t_step_in); ReadBasicType(is, binary, &num_t_in); ReadBasicType(is, binary, &start_t_out); ReadBasicType(is, binary, &t_step_out); ReadBasicType(is, binary, &num_t_out); ReadBasicType(is, binary, &reorder_t_in); ExpectToken(is, binary, "</ConvCompIo>"); } } // namespace time_height_convolution } // namespace nnet3 } // namespace kaldi
42.634569
85
0.660602
[ "object", "vector", "model" ]
287c7c1f8f1d4b3f1e921213e6b7143bd93a3f51
1,794
hh
C++
src/experience.hh
MaximilienNaveau/EnergyComputation
f9fdefcff197f7527a7c686f990ff496562ebc5e
[ "BSD-3-Clause" ]
null
null
null
src/experience.hh
MaximilienNaveau/EnergyComputation
f9fdefcff197f7527a7c686f990ff496562ebc5e
[ "BSD-3-Clause" ]
null
null
null
src/experience.hh
MaximilienNaveau/EnergyComputation
f9fdefcff197f7527a7c686f990ff496562ebc5e
[ "BSD-3-Clause" ]
null
null
null
#include "explorefolder.hh" #include "motors.hh" #include "commonTools.hh" #ifndef EXPERIENCE_HH #define EXPERIENCE_HH class Experience { public: // methods Experience(Motors * hrp2motors, path_t input_state_path, path_t input_ref_path, path_t rootFolder); // handle the data int handleData(); // getter & setter std::string name() {return experienceName_ ;} double walkedDistanced() {return walkedDistanced_ ;} double EnergyOfMotor() {return EnergyOfMotor_J_m_ ;} double EnergyOfWalking() {return EnergyOfWalking_J_m_ ;} double TimeTravelled() {return (0.005*(endData_-beginData_)) ;} private : // methods int setExperienceName(path_t rootFolder); int readData(); int filterTheData(); int defineBeginEndIndexes(); int computeTheEnergy(); int compareRefMeasure(); private : // attributes path_t input_astate_path_ ; path_t input_ref_path_ ; std::string experienceName_ ; int beginData_ ; int endData_ ; unsigned int ddl_ ; Motors * hrp2motors_ ; std::vector< std::string > titleRobotConfig_ ; std::vector< std::vector<double> > data_astate_ ; std::vector< std::vector<double> > data_ref_ ; std::vector< std::vector<double> > q_ ; std::vector< std::vector<double> > q_astate_ ; std::vector< std::vector<double> > q_ref_ ; std::vector< std::vector<double> > dq_ ; std::vector< std::vector<double> > torques_ ; std::vector< std::vector<double> > powerOutputMotors_ ; std::vector< std::vector<double> > powerOfWalk_ ; std::vector< std::vector<double> > errMeasureReference_ ; double walkedDistanced_ ; double EnergyOfMotor_J_m_ ; double EnergyOfWalking_J_m_ ; InfiniteImpendanceFilter IIF ; }; #endif // EXPERIENCE_HH
26.776119
103
0.686734
[ "vector" ]
287f59cc2f87149bbed81cae47185a0c088bcbf8
746
hpp
C++
Miracle/src/Miracle/Graphics/Implementations/Vulkan/ISurfaceTarget.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
Miracle/src/Miracle/Graphics/Implementations/Vulkan/ISurfaceTarget.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
3
2021-12-10T23:19:29.000Z
2022-03-27T05:04:14.000Z
Miracle/src/Miracle/Graphics/Implementations/Vulkan/ISurfaceTarget.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <variant> #include <Miracle/MiracleError.hpp> #include "Vulkan.hpp" namespace Miracle::Graphics::Implementations::Vulkan { class ISurfaceTarget { protected: bool m_extentChanged = false; public: virtual ~ISurfaceTarget() = default; virtual std::vector<const char*> getRequiredInstanceExtensions() const = 0; virtual vk::Extent2D getCurrentExtent() const = 0; virtual std::variant<MiracleError, vk::raii::SurfaceKHR> createSurface( const vk::raii::Instance& instance ) const = 0; inline bool isExtentChanged() { bool extentChanged = m_extentChanged; m_extentChanged = false; return extentChanged; } inline void markExtentChanged() { m_extentChanged = true; } }; }
21.941176
77
0.730563
[ "vector" ]
288a3529f479beda5fa8dd544968eb36f994d4cb
3,021
cpp
C++
Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/Text.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/Text.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Framework/AzQtComponents/AzQtComponents/Components/Widgets/Text.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzQtComponents/Components/Widgets/Text.h> #include <AzQtComponents/Components/ConfigHelpers.h> #include <AzQtComponents/Components/Style.h> #include <QLabel> #include <QSettings> #include <QString> namespace AzQtComponents { static QString g_headlineClass = QStringLiteral("Headline"); static QString g_titleClass = QStringLiteral("Title"); static QString g_subtitleClass = QStringLiteral("Subtitle"); static QString g_menuClass = QStringLiteral("Menu"); static QString g_labelClass = QStringLiteral("Label"); static QString g_paragraphClass = QStringLiteral("Paragraph"); static QString g_tooltipClass = QStringLiteral("Tooltip"); static QString g_buttonClass = QStringLiteral("Button"); static QString g_primaryTextClass = QStringLiteral("primaryText"); static QString g_secondaryTextClass = QStringLiteral("secondaryText"); static QString g_highlightedTextClass = QStringLiteral("highlightedText"); static QString g_blackTextClass = QStringLiteral("blackText"); Text::Config Text::loadConfig(QSettings& settings) { Config config = defaultConfig(); ConfigHelpers::GroupGuard guard(&settings, QStringLiteral("Hyperlink")); ConfigHelpers::read<QColor>(settings, QStringLiteral("Color"), config.hyperlinkColor); return config; } Text::Config Text::defaultConfig() { Config config; config.hyperlinkColor = QStringLiteral("#94D2FF"); return config; } void Text::addHeadlineStyle(QLabel* text) { Style::addClass(text, g_headlineClass); } void Text::addTitleStyle(QLabel* text) { Style::addClass(text, g_titleClass); } void Text::addSubtitleStyle(QLabel* text) { Style::addClass(text, g_subtitleClass); } void Text::addMenuStyle(QLabel* text) { Style::addClass(text, g_menuClass); } void Text::addLabelStyle(QLabel* text) { Style::addClass(text, g_labelClass); } void Text::addParagraphStyle(QLabel* text) { Style::addClass(text, g_paragraphClass); } void Text::addTooltipStyle(QLabel* text) { Style::addClass(text, g_tooltipClass); } void Text::addButtonStyle(QLabel* text) { Style::addClass(text, g_buttonClass); } void Text::addPrimaryStyle(QLabel* text) { Style::addClass(text, g_primaryTextClass); } void Text::addSecondaryStyle(QLabel* text) { Style::addClass(text, g_secondaryTextClass); } void Text::addHighlightedStyle(QLabel* text) { Style::addClass(text, g_highlightedTextClass); } void Text::addBlackStyle(QLabel* text) { Style::addClass(text, g_blackTextClass); } } // namespace AzQtComponents
27.463636
100
0.683548
[ "3d" ]
288a543505a878b837a2f16128a556360ca7fff8
895
cpp
C++
ProjectTile/src/SceneNode.cpp
andersonfr/TileEngineSFML
efb0685239208e6faa2519fdca318de086459fc4
[ "MIT" ]
null
null
null
ProjectTile/src/SceneNode.cpp
andersonfr/TileEngineSFML
efb0685239208e6faa2519fdca318de086459fc4
[ "MIT" ]
null
null
null
ProjectTile/src/SceneNode.cpp
andersonfr/TileEngineSFML
efb0685239208e6faa2519fdca318de086459fc4
[ "MIT" ]
null
null
null
#include "SceneNode.h" #include <assert.h> void SceneNode::AttachChild(Ptr child) { child->m_parent = this; child->OnStart(); m_children.push_back(std::move(child)); } SceneNode::Ptr SceneNode::DetachChild(const Ptr& node) { auto find = std::find_if(m_children.begin(), m_children.end(), [&](Ptr& p) { return p == node; }); assert(find != m_children.end()); Ptr p = std::move(*find); p->m_parent = nullptr; m_children.erase(find); p->OnDestroyed(); return p; } void SceneNode::DrawCurrent(sf::RenderTarget& target, sf::RenderStates states) const { } void SceneNode::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); DrawCurrent(target, states); for(const Ptr& c : m_children) { c->draw(target, states); } } void SceneNode::Update(float dt) { UpdateCurrent(dt); for(const Ptr& c : m_children) { c->Update(dt); } }
19.042553
99
0.683799
[ "transform" ]
288ba306b831daf419ef28499f7bf5053b388a95
11,115
hpp
C++
include/Firebase/Unity/UnitySynchronizationContext_SynchronizationContextBehavoir_-Start-c__Iterator0.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/Firebase/Unity/UnitySynchronizationContext_SynchronizationContextBehavoir_-Start-c__Iterator0.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/Firebase/Unity/UnitySynchronizationContext_SynchronizationContextBehavoir_-Start-c__Iterator0.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: Firebase.Unity.UnitySynchronizationContext/Firebase.Unity.SynchronizationContextBehavoir #include "Firebase/Unity/UnitySynchronizationContext_SynchronizationContextBehavoir.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Tuple`2<T1, T2> template<typename T1, typename T2> class Tuple_2; } // Forward declaring namespace: System::Threading namespace System::Threading { // Forward declaring type: SendOrPostCallback class SendOrPostCallback; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0); DEFINE_IL2CPP_ARG_TYPE(::Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0*, "Firebase.Unity", "UnitySynchronizationContext/SynchronizationContextBehavoir/<Start>c__Iterator0"); // Type namespace: Firebase.Unity namespace Firebase::Unity { // Size: 0x38 #pragma pack(push, 1) // Autogenerated type: Firebase.Unity.UnitySynchronizationContext/Firebase.Unity.SynchronizationContextBehavoir/Firebase.Unity.<Start>c__Iterator0 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0 : public ::Il2CppObject/*, public ::System::Collections::Generic::IEnumerator_1<::Il2CppObject*>*/ { public: public: // System.Tuple`2<System.Threading.SendOrPostCallback,System.Object> <entry>__0 // Size: 0x8 // Offset: 0x10 ::System::Tuple_2<::System::Threading::SendOrPostCallback*, ::Il2CppObject*>* $entry$__0; // Field size check static_assert(sizeof(::System::Tuple_2<::System::Threading::SendOrPostCallback*, ::Il2CppObject*>*) == 0x8); // System.Object $locvar0 // Size: 0x8 // Offset: 0x18 ::Il2CppObject* $locvar0; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // Firebase.Unity.UnitySynchronizationContext/Firebase.Unity.SynchronizationContextBehavoir $this // Size: 0x8 // Offset: 0x20 ::Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir* $this; // Field size check static_assert(sizeof(::Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir*) == 0x8); // System.Object $current // Size: 0x8 // Offset: 0x28 ::Il2CppObject* $current; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // System.Boolean $disposing // Size: 0x1 // Offset: 0x30 bool $disposing; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: $disposing and: $PC char __padding4[0x3] = {}; // System.Int32 $PC // Size: 0x4 // Offset: 0x34 int $PC; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating interface conversion operator: operator ::System::Collections::Generic::IEnumerator_1<::Il2CppObject*> operator ::System::Collections::Generic::IEnumerator_1<::Il2CppObject*>() noexcept { return *reinterpret_cast<::System::Collections::Generic::IEnumerator_1<::Il2CppObject*>*>(this); } // Get instance field reference: System.Tuple`2<System.Threading.SendOrPostCallback,System.Object> <entry>__0 [[deprecated("Use field access instead!")]] ::System::Tuple_2<::System::Threading::SendOrPostCallback*, ::Il2CppObject*>*& dyn_$entry$__0(); // Get instance field reference: System.Object $locvar0 [[deprecated("Use field access instead!")]] ::Il2CppObject*& dyn_$locvar0(); // Get instance field reference: Firebase.Unity.UnitySynchronizationContext/Firebase.Unity.SynchronizationContextBehavoir $this [[deprecated("Use field access instead!")]] ::Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir*& dyn_$this(); // Get instance field reference: System.Object $current [[deprecated("Use field access instead!")]] ::Il2CppObject*& dyn_$current(); // Get instance field reference: System.Boolean $disposing [[deprecated("Use field access instead!")]] bool& dyn_$disposing(); // Get instance field reference: System.Int32 $PC [[deprecated("Use field access instead!")]] int& dyn_$PC(); // private System.Object System.Collections.Generic.IEnumerator<object>.get_Current() // Offset: 0x18CBBE4 ::Il2CppObject* System_Collections_Generic_IEnumerator$object$_get_Current(); // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0x18CBBEC ::Il2CppObject* System_Collections_IEnumerator_get_Current(); // public System.Void .ctor() // Offset: 0x18CB99C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0*, creationType>())); } // public System.Boolean MoveNext() // Offset: 0x18CB9A4 bool MoveNext(); // public System.Void Dispose() // Offset: 0x18CBBF4 void Dispose(); // public System.Void Reset() // Offset: 0x18CBC08 void Reset(); }; // Firebase.Unity.UnitySynchronizationContext/Firebase.Unity.SynchronizationContextBehavoir/Firebase.Unity.<Start>c__Iterator0 #pragma pack(pop) static check_size<sizeof(UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0), 52 + sizeof(int)> __Firebase_Unity_UnitySynchronizationContext_SynchronizationContextBehavoir_$Start$c__Iterator0SizeCheck; static_assert(sizeof(UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0) == 0x38); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::System_Collections_Generic_IEnumerator$object$_get_Current // Il2CppName: System.Collections.Generic.IEnumerator<object>.get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::*)()>(&Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::System_Collections_Generic_IEnumerator$object$_get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0*), "System.Collections.Generic.IEnumerator<object>.get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::System_Collections_IEnumerator_get_Current // Il2CppName: System.Collections.IEnumerator.get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::*)()>(&Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::System_Collections_IEnumerator_get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0*), "System.Collections.IEnumerator.get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::*)()>(&Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0*), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::Dispose // Il2CppName: Dispose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::*)()>(&Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::Dispose)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0*), "Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::Reset // Il2CppName: Reset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::*)()>(&Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0::Reset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Firebase::Unity::UnitySynchronizationContext::SynchronizationContextBehavoir::$Start$c__Iterator0*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
65.382353
353
0.77031
[ "object", "vector" ]
288e10b4298f1c4d24489be7cb7c5698c0f8b982
10,514
cpp
C++
L1Trigger/Phase2L1ParticleFlow/src/newfirmware/regionizer/tdr/tdr_regionizer_ref.cpp
p2l1pfp/cmssw
9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9
[ "Apache-2.0" ]
2
2018-06-01T05:18:55.000Z
2021-04-08T21:44:06.000Z
L1Trigger/Phase2L1ParticleFlow/src/newfirmware/regionizer/tdr/tdr_regionizer_ref.cpp
p2l1pfp/cmssw
9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9
[ "Apache-2.0" ]
26
2018-10-30T12:47:58.000Z
2022-03-29T08:39:00.000Z
L1Trigger/Phase2L1ParticleFlow/src/newfirmware/regionizer/tdr/tdr_regionizer_ref.cpp
p2l1pfp/cmssw
9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9
[ "Apache-2.0" ]
null
null
null
#include "tdr_regionizer_ref.h" #include <iostream> #include "tdr_regionizer_elements_ref.icc" #ifdef CMSSW_GIT_HASH #include "FWCore/ParameterSet/interface/ParameterSet.h" l1ct::TDRRegionizerEmulator::TDRRegionizerEmulator(const edm::ParameterSet& iConfig) : TDRRegionizerEmulator( /*netaslices=*/3, iConfig.getParameter<uint32_t>("nTrack"), iConfig.getParameter<uint32_t>("nCalo"), iConfig.getParameter<uint32_t>("nEmCalo"), iConfig.getParameter<uint32_t>("nMu"), iConfig.getParameter<int32_t>("nClocks"), iConfig.getParameter<bool>("doSort")) { debug_ = iConfig.getUntrackedParameter<bool>("debug", false); } #endif l1ct::TDRRegionizerEmulator::TDRRegionizerEmulator(unsigned int netaslices, unsigned int ntk, unsigned int ncalo, unsigned int nem, unsigned int nmu, int nclocks, bool dosort) : RegionizerEmulator(), netaslices_(netaslices), ntk_(ntk), ncalo_(ncalo), nem_(nem), nmu_(nmu), nclocks_(nclocks), dosort_(dosort), init_(false) { assert(netaslices == 3); //the setup here only works for 3 barrel boards int etaoffsets[3] = {-228, 0, 228}; //this could be made generic perhaps, hardcoding for now for (unsigned int i = 0; i < netaslices_; i++) { tkRegionizers_.emplace_back( (unsigned int)NETA_SMALL, (unsigned int)NUMBER_OF_SMALL_REGIONS, ntk, etaoffsets[i], 115, nclocks); hadCaloRegionizers_.emplace_back( (unsigned int)NETA_SMALL, (unsigned int)NUMBER_OF_SMALL_REGIONS, ncalo, etaoffsets[i], 115, nclocks); emCaloRegionizers_.emplace_back( (unsigned int)NETA_SMALL, (unsigned int)NUMBER_OF_SMALL_REGIONS, nem, etaoffsets[i], 115, nclocks); muRegionizers_.emplace_back( (unsigned int)NETA_SMALL, (unsigned int)NUMBER_OF_SMALL_REGIONS, nmu, etaoffsets[i], 115, nclocks); } } l1ct::TDRRegionizerEmulator::~TDRRegionizerEmulator() {} void l1ct::TDRRegionizerEmulator::initSectorsAndRegions(const RegionizerDecodedInputs& in, const std::vector<PFInputRegion>& out) { assert(!init_); init_ = true; nregions_ = out.size(); if (ntk_) { for (unsigned int i = 0; i < netaslices_; i++) { tkRegionizers_[i].initSectors(in.track); tkRegionizers_[i].initRegions(out); } } if (ncalo_) { for (unsigned int i = 0; i < netaslices_; i++) { hadCaloRegionizers_[i].initSectors(in.hadcalo); hadCaloRegionizers_[i].initRegions(out); } } if (nem_) { for (unsigned int i = 0; i < netaslices_; i++) { emCaloRegionizers_[i].initSectors(in.emcalo); emCaloRegionizers_[i].initRegions(out); } } if (nmu_) { for (unsigned int i = 0; i < netaslices_; i++) { muRegionizers_[i].initSectors(in.muon); muRegionizers_[i].initRegions(out); } } } void l1ct::TDRRegionizerEmulator::fillLinks(const l1ct::RegionizerDecodedInputs& in, std::vector<std::vector<l1ct::TkObjEmu>>& links) { if (ntk_ == 0) return; links.clear(); links.resize(in.track.size()); //one link per sector for (unsigned int il = 0; il < in.track.size(); il++) { const l1ct::DetectorSector<l1ct::TkObjEmu>& sec = in.track[il]; for (unsigned int io = 0; io < sec.size(); io++) { links[il].push_back(sec[io]); if (links[il].size() == MAX_TK_EVT) { break; } } } } void l1ct::TDRRegionizerEmulator::fillLinks(const l1ct::RegionizerDecodedInputs& in, std::vector<std::vector<l1ct::HadCaloObjEmu>>& links) { if (ncalo_ == 0) return; links.clear(); links.resize(in.hadcalo.size()); //one link per sector for (unsigned int il = 0; il < in.hadcalo.size(); il++) { const l1ct::DetectorSector<l1ct::HadCaloObjEmu>& sec = in.hadcalo[il]; for (unsigned int io = 0; io < sec.size(); io++) { links[il].push_back(sec[io]); if (links[il].size() == MAX_CALO_EVT) { break; } } } } void l1ct::TDRRegionizerEmulator::fillLinks(const l1ct::RegionizerDecodedInputs& in, std::vector<std::vector<l1ct::EmCaloObjEmu>>& links) { if (nem_ == 0) return; links.clear(); links.resize(in.emcalo.size()); //one link per sector for (unsigned int il = 0; il < in.emcalo.size(); il++) { const l1ct::DetectorSector<l1ct::EmCaloObjEmu>& sec = in.emcalo[il]; for (unsigned int io = 0; io < sec.size(); io++) { links[il].push_back(sec[io]); if (links[il].size() == MAX_EMCALO_EVT) { break; } } } } void l1ct::TDRRegionizerEmulator::fillLinks(const l1ct::RegionizerDecodedInputs& in, std::vector<std::vector<l1ct::MuObjEmu>>& links) { if (nmu_ == 0) return; links.clear(); links.resize(1); //muons are global const l1ct::DetectorSector<l1ct::MuObjEmu>& sec = in.muon; for (unsigned int io = 0; io < sec.size(); io++) { links[0].push_back(sec[io]); if (links[0].size() == MAX_MU_EVT) { break; } } } void l1ct::TDRRegionizerEmulator::toFirmware(const std::vector<l1ct::TkObjEmu>& emu, TkObj fw[NTK_SECTORS][NTK_LINKS]) { if (ntk_ == 0) return; assert(emu.size() == NTK_SECTORS * NTK_LINKS * netaslices_); for (unsigned int is = 0, idx = 0; is < NTK_SECTORS * netaslices_; ++is) { // tf sectors for (unsigned int il = 0; il < NTK_LINKS; ++il, ++idx) { fw[is][il] = emu[idx]; } } } void l1ct::TDRRegionizerEmulator::toFirmware(const std::vector<l1ct::HadCaloObjEmu>& emu, HadCaloObj fw[NCALO_SECTORS][NCALO_LINKS]) { if (ncalo_ == 0) return; assert(emu.size() == NCALO_SECTORS * NCALO_LINKS * netaslices_); for (unsigned int is = 0, idx = 0; is < NCALO_SECTORS * netaslices_; ++is) { // tf sectors for (unsigned int il = 0; il < NCALO_LINKS; ++il, ++idx) { fw[is][il] = emu[idx]; } } } void l1ct::TDRRegionizerEmulator::toFirmware(const std::vector<l1ct::EmCaloObjEmu>& emu, EmCaloObj fw[NCALO_SECTORS][NCALO_LINKS]) { if (nem_ == 0) return; assert(emu.size() == NCALO_SECTORS * NCALO_LINKS * netaslices_); for (unsigned int is = 0, idx = 0; is < NCALO_SECTORS * netaslices_; ++is) { // tf sectors for (unsigned int il = 0; il < NCALO_LINKS; ++il, ++idx) { fw[is][il] = emu[idx]; } } } void l1ct::TDRRegionizerEmulator::toFirmware(const std::vector<l1ct::MuObjEmu>& emu, MuObj fw[NMU_LINKS]) { if (nmu_ == 0) return; assert(emu.size() == NMU_LINKS); for (unsigned int il = 0, idx = 0; il < NMU_LINKS; ++il, ++idx) { fw[il] = emu[idx]; } } void l1ct::TDRRegionizerEmulator::run(const RegionizerDecodedInputs& in, std::vector<PFInputRegion>& out) { if (!init_) initSectorsAndRegions(in, out); std::vector<std::vector<l1ct::TkObjEmu>> tk_links_in; std::vector<std::vector<l1ct::EmCaloObjEmu>> em_links_in; std::vector<std::vector<l1ct::HadCaloObjEmu>> calo_links_in; std::vector<std::vector<l1ct::MuObjEmu>> mu_links_in; // read the inputs fillLinks(in, tk_links_in); fillLinks(in, em_links_in); fillLinks(in, calo_links_in); fillLinks(in, mu_links_in); //this is overkill and could be improved, for now its ok (the sectors outside each board just wont do anything) for (unsigned int ie = 0; ie < netaslices_; ie++) { //add objects from link tkRegionizers_[ie].reset(); tkRegionizers_[ie].setPipes(tk_links_in); tkRegionizers_[ie].initTimes(); if (debug_) { dbgCout() << ie << "SECTORS/LINKS " << ie << std::endl; for (unsigned int i = 0; i < tk_links_in.size(); i++) { for (unsigned int j = 0; j < tk_links_in[i].size(); j++) { dbgCout() << "\t" << i << " " << j << "\t" << tk_links_in[i][j].hwPt.to_int() << "\t" << tk_links_in[i][j].hwEta.to_int() << "\t" << tk_links_in[i][j].hwPhi.to_int() << std::endl; } dbgCout() << "-------------------------------" << std::endl; } } tkRegionizers_[ie].run(debug_); emCaloRegionizers_[ie].reset(); emCaloRegionizers_[ie].setPipes(em_links_in); emCaloRegionizers_[ie].initTimes(); emCaloRegionizers_[ie].run(); hadCaloRegionizers_[ie].reset(); hadCaloRegionizers_[ie].setPipes(calo_links_in); hadCaloRegionizers_[ie].initTimes(); hadCaloRegionizers_[ie].run(); muRegionizers_[ie].reset(); muRegionizers_[ie].setPipes(mu_links_in); muRegionizers_[ie].initTimes(); muRegionizers_[ie].run(); } for (unsigned int ie = 0; ie < netaslices_; ie++) { for (unsigned int ireg = 0; ireg < nregions_; ireg++) { std::vector<l1ct::TkObjEmu> out_tks = tkRegionizers_[ie].getSmallRegion(ireg); if (!out_tks.empty()) { if (dosort_) { std::sort( out_tks.begin(), out_tks.end(), [](const l1ct::TkObjEmu a, const l1ct::TkObjEmu b) { return a > b; }); } out[ireg].track = out_tks; } std::vector<l1ct::EmCaloObjEmu> out_emcalos = emCaloRegionizers_[ie].getSmallRegion(ireg); if (!out_emcalos.empty()) { if (dosort_) { std::sort(out_emcalos.begin(), out_emcalos.end(), [](const l1ct::EmCaloObjEmu a, const l1ct::EmCaloObjEmu b) { return a > b; }); } out[ireg].emcalo = out_emcalos; } std::vector<l1ct::HadCaloObjEmu> out_hadcalos = hadCaloRegionizers_[ie].getSmallRegion(ireg); if (!out_hadcalos.empty()) { if (dosort_) { std::sort(out_hadcalos.begin(), out_hadcalos.end(), [](const l1ct::HadCaloObjEmu a, const l1ct::HadCaloObjEmu b) { return a > b; }); } out[ireg].hadcalo = out_hadcalos; } std::vector<l1ct::MuObjEmu> out_mus = muRegionizers_[ie].getSmallRegion(ireg); if (!out_mus.empty()) { if (dosort_) { std::sort( out_mus.begin(), out_mus.end(), [](const l1ct::MuObjEmu a, const l1ct::MuObjEmu b) { return a > b; }); } out[ireg].muon = out_mus; } } } }
35.761905
120
0.592353
[ "vector" ]
28947ec35c2b5c101ace10c427af0697ca159048
1,058
cc
C++
example/test-chars.cc
sebdeckers/cuckoofilter
b5170c326242693c8411e57975c6d885b06794e8
[ "Apache-2.0" ]
18
2018-03-20T12:31:43.000Z
2021-03-15T01:34:45.000Z
example/test-chars.cc
sebdeckers/cuckoofilter
b5170c326242693c8411e57975c6d885b06794e8
[ "Apache-2.0" ]
1
2018-03-20T14:25:11.000Z
2018-03-20T14:37:29.000Z
example/test-chars.cc
sebdeckers/cuckoofilter
b5170c326242693c8411e57975c6d885b06794e8
[ "Apache-2.0" ]
9
2018-03-20T14:14:27.000Z
2019-12-24T22:33:15.000Z
#include "cuckoofilter.h" #include <assert.h> #include <math.h> #include <iostream> #include <vector> using cuckoofilter::CuckooFilter; class MyObj { public: std::string str; MyObj(const std::string str) { this->str = str; } }; class MyHash { public: uint64_t operator()(MyObj* o) const { return cuckoofilter::HashUtil::BobHash(o->str); } }; int main(int argc, char **argv) { size_t total_items = 1000000; CuckooFilter<MyObj*, 12, cuckoofilter::SingleTable, MyHash> filter(total_items); if (filter.Add(new MyObj("hello")) != cuckoofilter::Ok) { std::cout << "unable to add"; return 0; } if (filter.Contain(new MyObj("hello")) == cuckoofilter::Ok) { std::cout << "ok"; } else { std::cout << "not ok"; } if (filter.Contain(new MyObj("not hello")) == cuckoofilter::Ok) { std::cout << "not ok"; } else { std::cout << "ok"; } if (filter.Contain(new MyObj("muaaha")) == cuckoofilter::Ok) { std::cout << "not ok"; } else { std::cout << "ok"; } return 0; }
18.561404
82
0.595463
[ "vector" ]
2895eef0fa4478f9174c459261f57196a0ca5710
748
cpp
C++
computer_science/algorithms/dynamic_programming/fibonacci.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
computer_science/algorithms/dynamic_programming/fibonacci.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
computer_science/algorithms/dynamic_programming/fibonacci.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
#include <iostream> #include <vector> #include <map> using namespace std; int fibonacci(int n) { // exponation time - T(n) = T(n - 1) + T(n - 2) + const(1) --> O(2^(n/2)) if (n <= 2) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int fibonacci_dp(int n) { if (n == 0) return 0; else if (n == 1) return 1; map<int, int> fib; fib[0] = 0; fib[1] = 1; for (int i = 2; i <= n; ++i) fib[i] = fib[i-1] + fib[i-2]; return fib[n]; } int main() { int n = 5, m = 5; // recursive algorithm without DP cout << fibonacci(n) << endl; // memoized DP algorithm: add in the map. If we have the element in the map, return the result for(int i = 0; i < 20; i++) cout << fibonacci_dp(i) << endl; return 0; }
18.243902
96
0.553476
[ "vector" ]
28971bcb9412bf9305b7254657a621eaac2eb2c5
2,343
hh
C++
src/window.hh
Geemili/kakoune
079b006cdab6f0ae594f80fff18ad61b71b0754d
[ "Unlicense" ]
1
2021-07-19T14:28:05.000Z
2021-07-19T14:28:05.000Z
src/window.hh
MilanVasko/kakoune
c939c30135930ebe6dbf963649e81a732e0830af
[ "Unlicense" ]
null
null
null
src/window.hh
MilanVasko/kakoune
c939c30135930ebe6dbf963649e81a732e0830af
[ "Unlicense" ]
null
null
null
#ifndef window_hh_INCLUDED #define window_hh_INCLUDED #include "client.hh" #include "display_buffer.hh" #include "highlighter_group.hh" #include "option_manager.hh" #include "optional.hh" #include "safe_ptr.hh" #include "scope.hh" namespace Kakoune { // A Window is a view onto a Buffer class Window : public SafeCountable, public OptionManagerWatcher, public Scope { public: Window(Buffer& buffer); ~Window(); const DisplayCoord& position() const { return m_position; } void set_position(DisplayCoord position); const DisplayCoord& range() const { return m_range; } const DisplayCoord& dimensions() const { return m_dimensions; } void set_dimensions(DisplayCoord dimensions); void scroll(LineCount offset); void center_line(LineCount buffer_line); void display_line_at(LineCount buffer_line, LineCount display_line); void scroll(ColumnCount offset); void center_column(ColumnCount buffer_column); void display_column_at(ColumnCount buffer_column, ColumnCount display_column); const DisplayBuffer& update_display_buffer(const Context& context); Optional<DisplayCoord> display_position(BufferCoord coord) const; BufferCoord buffer_coord(DisplayCoord coord) const; Buffer& buffer() const { return *m_buffer; } bool needs_redraw(const Context& context) const; void force_redraw() { m_last_setup = Setup{}; } void set_client(Client* client) { m_client = client; } void clear_display_buffer(); private: Window(const Window&) = delete; void on_option_changed(const Option& option) override; DisplaySetup compute_display_setup(const Context& context); void run_hook_in_own_context(StringView hook_name, StringView param, String client_name = ""); SafePtr<Buffer> m_buffer; SafePtr<Client> m_client; DisplayCoord m_position; DisplayCoord m_range; DisplayCoord m_dimensions; DisplayBuffer m_display_buffer; Highlighters m_builtin_highlighters; struct Setup { DisplayCoord position; DisplayCoord dimensions; size_t timestamp; size_t main_selection; Vector<BufferRange, MemoryDomain::Display> selections; }; Setup build_setup(const Context& context) const; Setup m_last_setup; }; } #endif // window_hh_INCLUDED
27.564706
82
0.729407
[ "vector" ]
28971e1953eae2a992e4a7ea9466c54a9f3829f8
25,679
cpp
C++
libraries/crosschain_privatekey_management/main.cpp
Whitecoin-Owner/Whitecoin-core
a48c1c229b9a311b10654ac79335890ca57aec4a
[ "MIT" ]
10
2020-09-26T12:00:03.000Z
2021-07-27T06:41:40.000Z
libraries/crosschain_privatekey_management/main.cpp
r8d8/Whitecoin-core
ba4438a0e41babde272c67a3b2048b4247a7dc4e
[ "MIT" ]
23
2020-05-31T13:08:03.000Z
2021-12-08T09:07:30.000Z
libraries/crosschain_privatekey_management/main.cpp
r8d8/Whitecoin-core
ba4438a0e41babde272c67a3b2048b4247a7dc4e
[ "MIT" ]
4
2019-12-05T15:32:08.000Z
2021-09-21T17:53:41.000Z
 #include <graphene/crosschain_privatekey_management/private_key.hpp> #include <graphene/crosschain_privatekey_management/database_privatekey.hpp> #include "fc/crypto/base58.hpp" #include <bitcoin/bitcoin.hpp> #include <graphene/crosschain_privatekey_management/util.hpp> #include <graphene/chain/protocol/address.hpp> #include <graphene/chain/protocol/types.hpp> #include <graphene/utilities/key_conversion.hpp> #include <fc/crypto/elliptic.hpp> #include <string> #include <vector> #include <iostream> #include <fc/thread/thread.hpp> #include <fc/crypto/hex.hpp> #include <fc/crypto/aes.hpp> #include <graphene/wallet/wallet.hpp> // // std::string key_to_compressed_wif(const fc::sha256& secret) // { // //one byte for prefix, one byte for compressed sentinel // const size_t size_of_data_to_hash = sizeof(secret) + 2; // const size_t size_of_hash_bytes = 4; // char data[size_of_data_to_hash + size_of_hash_bytes]; // data[0] = (char)0x80; // memcpy(&data[1], (char*)&secret, sizeof(secret)); // data[size_of_data_to_hash - 1] = (char)0x01; // fc::sha256 digest = fc::sha256::hash(data, size_of_data_to_hash); // digest = fc::sha256::hash(digest); // memcpy(data + size_of_data_to_hash, (char*)&digest, size_of_hash_bytes); // return fc::to_base58(data, sizeof(data)); // } // std::string key_to_compressed_wif(const fc::ecc::private_key& key) // { // return key_to_compressed_wif(key.get_secret()); // } namespace graphene { namespace privatekey_management { } } int main(int argc, char** argv) { using namespace graphene::privatekey_management; // // test private key generation // btc_privatekey btc_priv; // auto btc_wif_key = btc_priv.get_wif_key(); // printf("btc wif key: %s\n", btc_wif_key.c_str()); // auto btc_addr = btc_priv.get_address(); // printf("btc address: %s\n", btc_addr.c_str()); // // auto import_btc_priv_key = btc_priv.import_private_key(btc_wif_key); // btc_privatekey import_btc_priv(*import_btc_priv_key); // btc_wif_key = import_btc_priv.get_wif_key(); // printf("imported btc wif key: %s\n", btc_wif_key.c_str()); // // // ltc_privatekey ltc_priv; // auto ltc_wif_key = ltc_priv.get_wif_key(); // printf("ltc wif key: %s\n", ltc_wif_key.c_str()); // auto ltc_addr = ltc_priv.get_address(); // printf("ltc address: %s\n", ltc_addr.c_str()); // auto import_ltc_priv_key = ltc_priv.import_private_key(ltc_wif_key); // ltc_privatekey import_ltc_priv(*import_ltc_priv_key); // ltc_wif_key = import_ltc_priv.get_wif_key(); // printf("imported ltc wif key: %s\n", ltc_wif_key.c_str()); // database_privatekey db_priv; // std::string password = "123456"; // auto checksum = fc::sha512::hash(password.c_str(), password.size()); // // for (auto i = 0; i < 10; i++) // { // printf("current index: %d\n", i + 1); // // btc_privatekey btc_priv; // auto btc_wif_key = btc_priv.get_wif_key(btc_priv.get_private_key()); // printf("btc wif key: %s\n", btc_wif_key.c_str()); // auto btc_addr = btc_priv.get_address(btc_priv.get_private_key()); // printf("btc address: %s\n", btc_addr.c_str()); // auto import_btc_priv_key = btc_priv.import_private_key(btc_wif_key); // btc_wif_key = btc_priv.get_wif_key(*import_btc_priv_key); // printf("imported btc wif key: %s\n", btc_wif_key.c_str()); // // // // crosschain_privatekey_data data; // data.id = i+1; // data.addr = btc_priv.get_address(btc_priv.get_private_key()); // data.wif_key = btc_priv.get_wif_key(btc_priv.get_private_key()); // // // // db_priv.store(data, checksum); // } // // printf("\n"); // auto result = db_priv.fetch_by_id(3, checksum); // printf("%s\n", result->wif_key.c_str()); // // auto max_id = db_priv.fetch_current_max_id(); // printf("%d\n", max_id); //btc_privatekey priv; //std::string script = "OP_HASH160 97f0c041b556fbb141364790b596cd9b3b2b403b OP_EQUAL"; //std::string redeemscript = "552103045651fb6f856ce1b27fb173e44d8bd30842d4459fa586353a69cb276384e0522103caf30dcebba7c04e973b4afa394f0199e4c5a387faa5cec31b06dffe6592bd2e2103b5b29f6bba2c73fe7a3a0a2fa0f1aab23c5cf827686d605e9ab15cc281ac327221039a935048686f7bd83d8de10ec614b1b767ce74902e25c4a67632b225c64043162102b7730bb1aa8289f8028fe9315c5002860bc3578c87f26abb63c9ef2ca3fcfe5f210262b4fc622eb191a61f209cf890799fd141d003cc6ef721c192974120d5370a4e2102ca9c947b9a73f1819759aca131680aa0d0263c4130a2710d1a13b1d7755b9e9057ae"; //std::string raw_trx = "020000000117749ee7407b9a0511b742f9510d047a5edccef7d102377e573d3757ce509c540100000000ffffffff02000e2707000000001976a91428e13ec311b8b377288d069a489a0136ef967ca788ac603572340000000017a914537b76690c6d13d89ebe5d0e029c8f1c346a9fe38700000000"; //auto temp1 = graphene::privatekey_management::mutisign_trx("L2TtkoupXw4cYZebqUmSAEvnEh5K7pMAWEY9Tqih2CNdE7QcqR48",redeemscript, raw_trx); ////std::cout << "1:" << temp1<< std::endl; //auto temp2 = graphene::privatekey_management::mutisign_trx("KyJYWeAxYoxU5wCaGQKjqi73sK1QQBDsnvyGJB5LJP1XKahVj8mr", redeemscript, raw_trx); ////std::cout << "2:" << temp2 << std::endl; //if (temp1 == temp2) //{ // std::cout << "same signature" << std::endl; //} string password = "12345ssdlh"; vector<char> cipher_keys; string hex_string = "f623ebae490f6e72508ff950c3d462f274ce915aafdebd8d5c75b281975b2830df7e1af4b570ce3b03ab630b22613e6c33bbcfcced5cddecf6577ed196e5d1bbd368fa0ea48a59d467589125f9a92657515e6dad0a0893f2e682bdaf6923e3414144f6166bc9988276ffbbaba7ff56359ee0e02942dc9fc17d9479b8b00a0db02a32f95054b263b1e5722c41bd3b4970"; char cipher_key_char[144]; fc::from_hex(hex_string, cipher_key_char, 144); for (int i = 0; i < 144; i++) { cipher_keys.push_back(cipher_key_char[i]); } FC_ASSERT(password.size() > 0); auto pw = fc::sha512::hash(password.c_str(), password.size()); vector<char> decrypted = fc::aes_decrypt(pw, cipher_keys); std::cout << unsigned(decrypted[21]) << std::endl; auto pk = fc::raw::unpack<graphene::wallet::plain_keys>(decrypted); FC_ASSERT(pk.checksum == pw); for (auto iter = pk.keys.begin(); iter != pk.keys.end(); iter++) { std::cout << graphene::chain::address(iter->first).address_to_string() << " : " << iter->second << endl; } getchar(); fc::http::connection_sync conn; conn.connect_to(fc::ip::endpoint(fc::ip::address("112.5.37.213"),80)); //auto res = conn.parse_reply(); auto response = conn.request("GET", "http://1000896736104835.cn-hongkong.fc.aliyuncs.com/2016-08-15/proxy/query_XWC_middleware_endpoint/query_middleware_endpoint/", " "); std::cout << response.body << std::endl; getchar(); btc_privatekey priv1; std::string signature1 = "0x8d4583a002a1ee21c9fbc688c51c960508fe4d68dac16f571a3a50b460c38b9d2acffe29ac065670a178aab140a57cb7d47791896fd8111ebdeecffcdc8cb5be1c"; std::string message1 = "0x476e8cb6e378ae523d4016babf53569654ed2fcc"; auto res1 = priv1.verify_message(message1, message1, signature1); std::cout << "eth res: " << res1 << std::endl; fc::thread my_thread; fc::variant_object config = fc::json::from_string("{\"ip\":\"127.0.0.1\",\"port\":5005}").get_object(); my_thread.async([&]() { }); btc_privatekey priv_btc; std::vector<std::string> a = { "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4d020047304402202d4bcbfdf06682ef21a548ea89464ed765159c347ade5d9fb82ade29f8139d550220182012a25eb7e96cb652ac3f55050ac2353173637b2a87c80d1528267b0101a5014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4d0200473044022013ef261b997d9742a7b73b6f778e28456d3cb3e6de61307ffcc48e4feb55d615022056fd0e1563a38f261ce1908fec09dc5020b874c297594d07246efc98b1c77427014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4e0200483045022100d854ebbaf3c95521a53fccdc9a1df9c28114fbc215cf131febebe707d4c2e99d022004ff4f84900ade24c299aee22536d90fe82f997d1867952277621081fb9dd440014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4d0200473044022060147a0e14f7809fcc08714a592a35cbec84a9112aaee70a240185af9509f8700220103b446efc10802175801be7491c21bb0a22ed081fbeb3d202ab6be4b65d1ded014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4d0200473044022035c3c350b4493a99fcd51292303665dffc941c4206be9db2cff85bd89ec56d2e022023d822049349b8738b791d82c5329f1957270ee061f5cd2c7856bcc4f8b4e5d4014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4e0200483045022100f18deff6f32239ab11ba36910a9e0bdde7dc527acfc6143c7b3d4e65dc45ce1f02203801a77ab6a17a1f701390e4372da771b265803a3ff8e094956f850a4ad9bd86014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4e0200483045022100c918ecfdddbf2737cbda2461bfe38e0e852a403d0cffb7e7478c66cc42df5071022025a7d0b6284c647fa15e879057c03c04a518a5a6b50b1cdaa53243ad20dd031b014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4d020047304402201b096ec23b5a769b4244774c65a4977996f839314724703dc8850fd6a7ee097a0220410d125df7626faa350b0e42fe749e79f0a28667bee42a130b7cd575ed24a57c014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4e0200483045022100ce4f81d67d6103cd1f7254276034b45eee292a77a62bf004499ad6c454c551ac022029558549da389320a714f11bdf75a39fab6d5d2af45ad39d23b9d494a871841b014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4d0200473044022066db0983b11381d27f88d20ad7a03da52559364ea7d026df1b0d6c490ea36caa0220123ae0296601d94c0c72d6c78381b72c2543dd682b758a9a7a7d7e086967178e014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000", "0200000001f9f960f336656d7cb90463735a8516113f4493516d43b893e5338cff6d25179301000000fd4d02004730440220467817ee898265ad32edeb7659456565423e944539b2852e450e01867dbd312f0220723b360ee041e210dacf63030323d53c15b1c9fe10a53cd9ded29b49e589648f014d01025b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25faeffffffff02c8b654180000000017a91492fb55f5343846b6acfc269a615a82a800f5d6ad87a0fab8010000000017a9141592f4033152839c02b3716cc57dd02ad4bdb1ec8700000000"}; std::string redeemscript = "5b210209f45f7adb48d3a2bcc62ab49a29df822fdaf6b2c1e26afc48529a6a4272240c21023a37b1ec16f5d073ed4c1c435ac0dad2031f2d0188d439a5655b3bd1e8d9f0d72103a9e498958e3b816c89a6886adadc65a67e3658dfbc0c2a8d898536a64bb14ee22103d99a8ac95d78488394f0611bf3a654a726bb47b1453ed8ba93a26a868419c858210276447b1c51823c89359b64ae03ce23497caee8e4a3ce0b0616b18102c2f909122103b935a588f8d1f38af0926ba8b32fa4d2f549e97129544852922a45d4853b9a7e2103a154c3e59040df072d6a82a322a8cc48c142f85745749bb4147dfb0265a3c7382102bdbdb15ab4495025990f99edb7ab29f1fed3ae10b6631a7aa0a837053273cbb421039bf0b4f48b33456fca71f541143a5b4c0195e138ccc51ef71d1d4c25a8c3258a2102a7822cd38afae7a31cf8f5443c91c877d1931aeb58bd319fa7c95a7666bb07852102d23df29f6c723e0ea71b9841c010e18011462ec03a709e8fbd9c1e5ae89967e821026d80ea22ec04ac402a2056b6f10244956f51635825cb1c01f5ca0fe47e336d3321038da52155bb32fd7c835226c1aa8912eab50d214dea29e16a50625c624cc5747f21038a99963e63b998ebf3b02929927f0ab6220241c81589d97f41e6dadf1963f04b210235de1c98d9021cad75aaaf9ebd2a473e1ebf846d0c9d164b648782edacca10a25fae"; auto obj = priv_btc.combine_trxs(a); //fc::variant(obj).as_string(); // // btc_privatekey priv; // std::string wif = priv.get_wif_key(); // printf("the wif is %s\n", wif.c_str()); // // libbitcoin::wallet::ec_private libbitcoin_priv(wif); // libbitcoin::ec_secret secret = libbitcoin_priv.secret(); // // std::string hex_string = "394fcb53c3897424646f31361eedb6b0c159cbe2e72415b61a0cc776d8abf446"; // libbitcoin::data_chunk data; // libbitcoin::decode_base16(data, hex_string); // printf("the size is %d\n", data.size()); // libbitcoin::hash_digest hash; // std::copy(data.begin(), data.end(), hash.begin()); // // libbitcoin::ec_signature result; // // libbitcoin::sign(result, secret, hash); // printf("the result is %s\n", libbitcoin::encode_base16(result).c_str()); // // libbitcoin::der_signature out; // printf("the result is %s\n", libbitcoin::encode_base16(out).c_str()); //btc_privatekey pkey; //pkey.import_private_key("KwbYc3Vzs6d52Rz9UsEPMvAF8DLddthU2g8KpqQ2eHyUVTC1tPeq"); //std::string raw_transaction = "020000000101efc30cb46b3561d1ade9df3800ca560325beb92b15993b1078f53c73153be70000000000ffffffff026043993b000000001976a914bbad6509cda94ef4cc7735d41be492c2e9bab45488ac00286bee0000000017a9140f4d3a1d1b70386fe0846ef8432c8ebcc3c9ee058700000000"; //std::string redeemscript = "76a914a29932129ee913c92e40909e9a725195d600ab5f88ac"; ////auto str = pkey.sign_trx(raw_transaction,0); ////std::cout << str << std::endl; // //auto addr = pkey.get_address(); //fc::optional<fc::ecc::private_key> optional_private_key = graphene::utilities::wif_to_key("5KAffU3Pw7RNJAJ3d1qUrJ6QPVb6UFx6CJ4MhgfoHL7YwYspHhs"); //graphene::chain::public_key_type wif_pub_key = optional_private_key->get_public_key(); //std::cout << wif_pub_key.operator fc::string() << std::endl; //std::cout << graphene::chain::address(wif_pub_key).address_to_string() << std::endl; getchar(); return 0; }
106.551867
1,447
0.907746
[ "vector" ]
80bc5ce68ae3ac940945b00d2359521711ab7b3e
16,821
cpp
C++
packages/nextalign/src/align/alignPairwise.cpp
davidcroll/nextclade
f62d906034974c160eabb12ac9bf98a691646ee3
[ "MIT" ]
1
2021-07-01T05:07:32.000Z
2021-07-01T05:07:32.000Z
packages/nextalign/src/align/alignPairwise.cpp
amkram/nextclade
3703f4013f69407c9b91172997abc2e19b902b91
[ "MIT" ]
null
null
null
packages/nextalign/src/align/alignPairwise.cpp
amkram/nextclade
3703f4013f69407c9b91172997abc2e19b902b91
[ "MIT" ]
null
null
null
#include "alignPairwise.h" #include <cmath> #include <iostream> #include <string> #include <vector> #include "../match/matchAa.h" #include "../match/matchNuc.h" #include "../utils/safe_cast.h" namespace details { inline int round(double x) { return safe_cast<int>(std::round(x)); } }// namespace details class ErrorAlignmentNoSeedMatches : public std::runtime_error { public: explicit ErrorAlignmentNoSeedMatches() : std::runtime_error("Unable to align: no seed matches") {} }; class ErrorAlignmentSequenceTooShort : public std::runtime_error { public: explicit ErrorAlignmentSequenceTooShort() : std::runtime_error("Unable to align: sequence is too short") {} }; class ErrorAlignmentBadSeedMatches : public std::runtime_error { public: explicit ErrorAlignmentBadSeedMatches() : std::runtime_error("Unable to align: too many insertions, deletions, duplications, or ambiguous seed matches") { } }; // store direction info for backtrace as bits in paths matrix // these indicate the currently optimal move constexpr const int MATCH = 1 << 0; constexpr const int refGAPmatrix = 1 << 1; constexpr const int qryGAPmatrix = 1 << 2; // these are the override flags for gap extension constexpr const int refGAPextend = 1 << 3; constexpr const int qryGAPextend = 1 << 4; constexpr const int END_OF_SEQUENCE = -1; // determine the position where a particular kmer (string of length k) matches the reference sequence // TODO: this function accepts a start position and will not search for matches before this position. // This start position is set be the previous match. It is this sensitive to a seed matching in the wrong // part of the sequence and this is likely to produce errors for genomes with repeated sequence template<typename Letter> SeedMatch seedMatch( const Sequence<Letter>& kmer, const Sequence<Letter>& ref, const int start_pos, const int mismatchesAllowed) { const int refSize = safe_cast<int>(ref.size()); const int kmerSize = safe_cast<int>(kmer.size()); int tmpScore = 0; int maxScore = 0; int maxShift = -1; for (int shift = start_pos; shift < refSize - kmerSize; ++shift) { tmpScore = 0; for (int pos = 0; pos < kmerSize; ++pos) { if (kmer[pos] == ref[shift + pos]) { tmpScore++; } // TODO: this speeds up seed-matching by disregarding bad seeds. if (tmpScore + mismatchesAllowed < pos) { break; } } if (tmpScore > maxScore) { maxScore = tmpScore; maxShift = shift; // if maximal score is reached if (tmpScore == kmerSize) { break; } } } return {.shift = maxShift, .score = maxScore}; } template<typename Letter> inline bool isBadLetter(Letter letter); template<> [[maybe_unused]] inline bool isBadLetter(Nucleotide letter) { return letter == Nucleotide::N; } template<> [[maybe_unused]] inline bool isBadLetter(Aminoacid letter) { return letter == Aminoacid::X; } template<typename Letter> std::vector<int> getMapToGoodPositions(const Sequence<Letter>& query, int seedLength) { const int querySize = safe_cast<int>(query.size()); std::vector<int> mapToGoodPositions; mapToGoodPositions.reserve(querySize); int distanceToLastBadPos = 0; for (int i = 0; i < querySize; i++) { if (isBadLetter(query[i])) { distanceToLastBadPos = -1; } else if (distanceToLastBadPos > seedLength) { mapToGoodPositions.push_back(i - seedLength); } distanceToLastBadPos++; } return mapToGoodPositions; } template<typename Letter> SeedAlignment seedAlignment( const Sequence<Letter>& query, const Sequence<Letter>& ref, const NextalignSeedOptions& options) { const int querySize = safe_cast<int>(query.size()); const int refSize = safe_cast<int>(ref.size()); // clang-format off const int nSeeds = refSize > options.minSeeds * options.seedSpacing ? refSize / options.seedSpacing : options.minSeeds; const int margin = details::round(refSize / (nSeeds * 3.0)); const int bandWidth = details::round((refSize + querySize) * 0.5) - 3; // clang-format on int start_pos = 0; if (bandWidth < 2 * options.seedLength) { return { .meanShift = details::round((refSize - querySize) * 0.5),// NOLINT: cppcoreguidelines-avoid-magic-numbers .bandWidth = bandWidth // }; } const auto mapToGoodPositions = getMapToGoodPositions(query, options.seedLength); const int nGoodPositions = safe_cast<int>(mapToGoodPositions.size()); // TODO: Maybe use something other than array? A struct with named fields to make // the code in the end of the function less confusing? using Clamp = std::array<int, 4>; std::vector<Clamp> seedMatches; // generate kmers equally spaced on the query const auto seedCover = safe_cast<double>(nGoodPositions - 2 * margin); const double kmerSpacing = (seedCover - 1.0) / (nSeeds - 1.0); if (seedCover < 0.0 || kmerSpacing < 0.0) { throw ErrorAlignmentNoSeedMatches(); } for (int ni = 0; ni < nSeeds; ++ni) { const auto goodPositionIndex = details::round(margin + (kmerSpacing * ni)); invariant_less(goodPositionIndex, mapToGoodPositions.size()); const int qPos = mapToGoodPositions[goodPositionIndex]; // FIXME: query.substr() creates a new string. Use string view instead. const auto seed = query.substr(qPos, options.seedLength); const auto tmpMatch = seedMatch(seed, ref, start_pos, options.mismatchesAllowed); // only use seeds with at most allowed_mismatches if (tmpMatch.score >= options.seedLength - options.mismatchesAllowed) { seedMatches.push_back({qPos, tmpMatch.shift, tmpMatch.shift - qPos, tmpMatch.score}); start_pos = tmpMatch.shift; } } if (seedMatches.size() < 2) { throw ErrorAlignmentNoSeedMatches(); } // given the seed matches, determine the maximal and minimal shifts // this shift is the typical amount the query needs shifting to match ref // ref: ACTCTACTGC-TCAGAC // query: ----TCACTCATCT-ACACCGAT => shift = 4, then 3, 4 again int minShift = refSize; int maxShift = -refSize; for (auto& seedMatch : seedMatches) { if (seedMatch[2] < minShift) { minShift = seedMatch[2]; } if (seedMatch[2] > maxShift) { maxShift = seedMatch[2]; } } const int meanShift = details::round(0.5 * (minShift + maxShift)); const int bandWidthFinal = maxShift - minShift + 9; return {.meanShift = meanShift, .bandWidth = bandWidthFinal}; } template<typename Letter> ForwardTrace scoreMatrix(const Sequence<Letter>& query, const Sequence<Letter>& ref, const std::vector<int>& gapOpenClose, int bandWidth, int meanShift, const NextalignAlignmentOptions& alignmentOptions) { // allocate a matrix to record the matches const int querySize = safe_cast<int>(query.size()); const int refSize = safe_cast<int>(ref.size()); const int n_rows = bandWidth * 2 + 1; const int n_cols = refSize + 1; vector2d<int> paths(n_rows, n_cols); // TODO: these could be reduced to vectors vector2d<int> scores(n_rows, n_cols); std::vector<int> qryGaps(n_rows); // fill scores with alignment scores // The inner index scores[][ri] is the index of the reference sequence // the outer index si index the shift, together they define rPos=ri and qPos = ri-shift // if the colon marks the position in the sequence before rPos,qPos // R: ...ACT:X // Q: ...ACT:Y // 1) if X and Y are bases they either match or mismatch. shift doesn't change, rPos and qPos advance // -> right horizontal step in the matrix // 2) if X is '-' and Y is a base, rPos stays the same and the shift decreases // -> vertical step in the matrix from si+1 to si // 2) if X is a base and Y is '-', rPos advances the same and the shift increases // -> diagonal step in the matrix from (ri,si-1) to (ri+1,si) const auto NO_ALIGN = -(alignmentOptions.scoreMatch + alignmentOptions.penaltyMismatch) * refSize; for (int si = 2 * bandWidth; si > bandWidth; si--) { paths(si, 0) = qryGAPmatrix; } paths(bandWidth, 0) = MATCH; qryGaps[bandWidth] = -alignmentOptions.penaltyGapOpen; for (int si = bandWidth - 1; si >= 0; si--) { paths(si, 0) = refGAPmatrix; qryGaps[si] = -alignmentOptions.penaltyGapOpen; } for (int ri = 0; ri < refSize; ri++) { int qPos = ri - (bandWidth + meanShift); int refGaps = -gapOpenClose[ri]; for (int si = 2 * bandWidth; si >= 0; si--) { int tmpPath = 0, score = 0, origin = 0; int qGapExtend = 0, rGapExtend = 0, rGapOpen = 0, qGapOpen = 0; int tmpMatch = 0, tmpScore = 0; if (qPos < 0) { // precedes query sequence -- no score, origin is query gap // we could fill all of this at once score = 0; tmpPath += qryGAPextend; refGaps = -gapOpenClose[ri]; origin = qryGAPmatrix; } else if (qPos < querySize) { // if the shifted position is within the query sequence // no gap -- match case tmpMatch = lookupMatchScore(query[qPos], ref[ri]) > 0 ? alignmentOptions.scoreMatch : -alignmentOptions.penaltyMismatch; score = scores(si, ri) + tmpMatch; origin = MATCH; // check the scores of a reference gap if (si < 2 * bandWidth) { rGapExtend = refGaps - alignmentOptions.penaltyGapExtend; rGapOpen = scores(si + 1, ri + 1) - gapOpenClose[ri + 1]; if (rGapExtend > rGapOpen) { tmpScore = rGapExtend; tmpPath += refGAPextend; } else { tmpScore = rGapOpen; } refGaps = tmpScore; if (score < tmpScore) { score = tmpScore; origin = refGAPmatrix; } } else { refGaps = NO_ALIGN; } // check the scores of a reference gap if (si > 0) { qGapExtend = qryGaps[si - 1] - alignmentOptions.penaltyGapExtend; qGapOpen = scores(si - 1, ri) - gapOpenClose[ri]; tmpScore = qGapExtend > qGapOpen ? qGapExtend : qGapOpen; if (qGapExtend > qGapOpen) { tmpScore = qGapExtend; tmpPath += qryGAPextend; } else { tmpScore = qGapOpen; } qryGaps[si] = tmpScore; if (score < tmpScore) { score = tmpScore; origin = qryGAPmatrix; } } else { qryGaps[si] = NO_ALIGN; } } else { // past query sequence -- mark as sequence end score = END_OF_SEQUENCE; origin = END_OF_SEQUENCE; } tmpPath += origin; paths(si, ri + 1) = tmpPath; scores(si, ri + 1) = score; qPos++; } // std::cout <<"\n"; } return {.scores = scores, .paths = paths}; } template<typename Letter> AlignmentResult<Letter> backTrace(const Sequence<Letter>& query, const Sequence<Letter>& ref, const vector2d<int>& scores, const vector2d<int>& paths, int meanShift) { const int rowLength = safe_cast<int>(scores.num_cols()); const int scoresSize = safe_cast<int>(scores.num_rows()); const int querySize = safe_cast<int>(query.size()); const int refSize = safe_cast<int>(ref.size()); const int bandWidth = (scoresSize - 1) / 2; int currentMatrix = 0; // TODO: Avoid creating this lambda function const auto indexToShift = [&bandWidth, &meanShift]// (int si) { // return si - bandWidth + meanShift; }; std::vector<std::pair<char, char>> aln; Sequence<Letter> aln_ref; Sequence<Letter> aln_query; aln_ref.reserve(rowLength + 3 * bandWidth); aln_query.reserve(rowLength + 3 * bandWidth); // const lastIndexByShift = scores.map((d, i) = > Math.min(rowLength - 1, querySize + indexToShift(i))); // const lastScoreByShift = scores.map((d, i) = > d[lastIndexByShift[i]]); std::vector<int> lastScoreByShift; std::vector<int> lastIndexByShift; lastScoreByShift.resize(scores.num_rows()); lastIndexByShift.resize(scores.num_rows()); // Determine the best alignment by picking the optimal score at the end of the query int si = 0; int bestScore = 0; for (int i = 0; i < scoresSize; i++) { const auto is = indexToShift(i); lastIndexByShift[i] = rowLength - 1 < querySize + is ? rowLength - 1 : querySize + is; invariant_greater(lastIndexByShift[i], 0); invariant_less(lastIndexByShift[i], scores.num_cols()); lastScoreByShift[i] = scores(i, lastIndexByShift[i]); if (lastScoreByShift[i] > bestScore) { bestScore = lastScoreByShift[i]; si = i; } } const int shift = indexToShift(si); int origin;//NOLINT(cppcoreguidelines-init-variables) // determine position tuple qPos, rPos corresponding to the place it the matrix int rPos = lastIndexByShift[si] - 1; int qPos = rPos - shift; // add right overhang, i.e. unaligned parts of the query or reference the right end if (rPos < refSize - 1) { for (int ii = refSize - 1; ii > rPos; ii--) { aln_query += Letter::GAP; aln_ref += ref[ii]; } } else if (qPos < querySize - 1) { for (int ii = querySize - 1; ii > qPos; ii--) { aln_query += query[ii]; aln_ref += Letter::GAP; } } // do backtrace for aligned region while (rPos >= 0 && qPos >= 0) { origin = paths(si, rPos + 1); // std::cout<<si<<" "<<rPos<<" "<<origin<<" "<<currentMatrix<<"\n"; if (origin & MATCH && currentMatrix == 0) { // match -- decrement both strands and add match to alignment aln_query += query[qPos]; aln_ref += ref[rPos]; qPos--; rPos--; } else if ((origin & refGAPmatrix && currentMatrix == 0) || currentMatrix == refGAPmatrix) { // insertion in ref -- decrement query, increase shift aln_query += query[qPos]; aln_ref += Letter::GAP; qPos--; si++; if (origin & refGAPextend) { // remain in gap-extension mode and ignore best-overall score currentMatrix = refGAPmatrix; } else { // close gap, return to best-overall score currentMatrix = 0; } } else if ((origin & qryGAPmatrix && currentMatrix == 0) || currentMatrix == qryGAPmatrix) { // deletion in query -- decrement reference, reduce shift aln_query += Letter::GAP; aln_ref += ref[rPos]; rPos--; si--; if (origin & qryGAPextend) { // remain in gap-extension mode and ignore best-overall score currentMatrix = qryGAPmatrix; } else { // close gap, return to best-overall score currentMatrix = 0; } } else { break; } } // add left overhang if (rPos >= 0) { for (int ii = rPos; ii >= 0; ii--) { aln_query += Letter::GAP; aln_ref += ref[ii]; } } else if (qPos >= 0) { for (int ii = qPos; ii >= 0; ii--) { aln_query += query[ii]; aln_ref += Letter::GAP; } } // TODO: shrink to fit std::reverse(aln_query.begin(), aln_query.end()); std::reverse(aln_ref.begin(), aln_ref.end()); return { .query = aln_query, .ref = aln_ref, .alignmentScore = bestScore, }; } struct AlignPairwiseTag {}; template<typename Letter> AlignmentResult<Letter> alignPairwise(const Sequence<Letter>& query, const Sequence<Letter>& ref, const std::vector<int>& gapOpenClose, const NextalignAlignmentOptions& alignmentOptions, const NextalignSeedOptions& seedOptions, AlignPairwiseTag) { const SeedAlignment& seedAlignmentResult = seedAlignment(query, ref, seedOptions); const auto& bandWidth = seedAlignmentResult.bandWidth; const auto& meanShift = seedAlignmentResult.meanShift; if (bandWidth > alignmentOptions.maxIndel) { throw ErrorAlignmentBadSeedMatches(); } const ForwardTrace& forwardTrace = scoreMatrix(query, ref, gapOpenClose, bandWidth, meanShift, alignmentOptions); const auto& scores = forwardTrace.scores; const auto& paths = forwardTrace.paths; return backTrace(query, ref, scores, paths, meanShift); } NucleotideAlignmentResult alignPairwise(const NucleotideSequence& query, const NucleotideSequence& ref, const std::vector<int>& gapOpenClose, const NextalignAlignmentOptions& alignmentOptions, const NextalignSeedOptions& seedOptions) { const int querySize = safe_cast<int>(query.size()); if (querySize < alignmentOptions.minimalLength) { throw ErrorAlignmentSequenceTooShort(); } return alignPairwise(query, ref, gapOpenClose, alignmentOptions, seedOptions, AlignPairwiseTag{}); } AminoacidAlignmentResult alignPairwise(const AminoacidSequence& query, const AminoacidSequence& ref, const std::vector<int>& gapOpenClose, const NextalignAlignmentOptions& alignmentOptions, const NextalignSeedOptions& seedOptions) { return alignPairwise(query, ref, gapOpenClose, alignmentOptions, seedOptions, AlignPairwiseTag{}); }
35.11691
121
0.658225
[ "vector" ]
80bc69c2a6e915e6d0943a57c492495ebf9ea38d
14,348
cpp
C++
source/games/duke/src/player_w.cpp
madame-rachelle/Raze
67c8187d620e6cf9e99543cab5c5746dd31007af
[ "RSA-MD" ]
null
null
null
source/games/duke/src/player_w.cpp
madame-rachelle/Raze
67c8187d620e6cf9e99543cab5c5746dd31007af
[ "RSA-MD" ]
null
null
null
source/games/duke/src/player_w.cpp
madame-rachelle/Raze
67c8187d620e6cf9e99543cab5c5746dd31007af
[ "RSA-MD" ]
null
null
null
//------------------------------------------------------------------------- /* Copyright (C) 1996, 2003 - 3D Realms Entertainment Copyright (C) 2000, 2003 - Matt Saettler (EDuke Enhancements) Copyright (C) 2020 - Christoph Oelckers This file is part of Enhanced Duke Nukem 3D version 1.5 - Atomic Edition Duke Nukem 3D is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Original Source: 1996 - Todd Replogle Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms EDuke enhancements integrated: 04/13/2003 - Matt Saettler Note: EDuke source was in transition. Changes are in-progress in the source as it is released. */ //------------------------------------------------------------------------- #include "ns.h" #include "global.h" #include "gamevar.h" #include "names_d.h" BEGIN_DUKE_NS int operateTripbomb(int snum); //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- void DoFire(struct player_struct *p, short snum) { int i; if(aplWeaponWorksLike[p->curr_weapon][snum]!=KNEE_WEAPON) { p->ammo_amount[p->curr_weapon]--; } if(aplWeaponFireSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponFireSound[p->curr_weapon][snum],p->i); } SetGameVarID(g_iWeaponVarID,p->curr_weapon,p->i,snum); SetGameVarID(g_iWorksLikeVarID,aplWeaponWorksLike[p->curr_weapon][snum], p->i, snum); fi.shoot(p->i,aplWeaponShoots[p->curr_weapon][snum]); for(i=1;i<aplWeaponShotsPerBurst[p->curr_weapon][snum];i++) { fi.shoot(p->i,aplWeaponShoots[p->curr_weapon][snum]); if( aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_AMMOPERSHOT) { p->ammo_amount[p->curr_weapon]--; } } if(! (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_NOVISIBLE )) { // make them visible if not set... lastvisinc = ud.levelclock+32; p->visibility = 0; } if( //!(aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_CHECKATRELOAD) && aplWeaponReload[p->curr_weapon][snum] > aplWeaponTotalTime[p->curr_weapon][snum] && p->ammo_amount[p->curr_weapon] > 0 && (aplWeaponClip[p->curr_weapon][snum]) && ((p->ammo_amount[p->curr_weapon]%(aplWeaponClip[p->curr_weapon][snum]))==0) ) { // do clip check... p->kickback_pic=aplWeaponTotalTime[p->curr_weapon][snum]; // is same as p->kickback_pic.... } if(aplWeaponWorksLike[p->curr_weapon][snum]!=KNEE_WEAPON) { checkavailweapon(p); } } //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- void DoSpawn(struct player_struct *p, short snum) { int j; if(!aplWeaponSpawn[p->curr_weapon][snum]) return; j = fi.spawn(p->i, aplWeaponSpawn[p->curr_weapon][snum]); if((aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_SPAWNTYPE2 ) ) { // like shotgun shells sprite[j].ang += 1024; ssp(j,CLIPMASK0); sprite[j].ang += 1024; // p->kickback_pic++; } else if((aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_SPAWNTYPE3 ) ) { // like chaingun shells sprite[j].ang += 1024; sprite[j].ang &= 2047; sprite[j].xvel += 32; sprite[j].z += (3<<8); ssp(j,CLIPMASK0); } } //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- void fireweapon_ww(int snum) { auto p = &ps[snum]; int pi = p->i; p->crack_time = CRACK_TIME; if (p->holster_weapon == 1) { if (p->last_pissed_time <= (26 * 218) && p->weapon_pos == -9) { p->holster_weapon = 0; p->oweapon_pos = p->weapon_pos = 10; FTA(74, p); } } else { SetGameVarID(g_iReturnVarID, 0, pi, snum); SetGameVarID(g_iWeaponVarID, p->curr_weapon, pi, snum); SetGameVarID(g_iWorksLikeVarID, aplWeaponWorksLike[p->curr_weapon][snum], pi, snum); OnEvent(EVENT_FIRE, pi, snum, -1); if (GetGameVarID(g_iReturnVarID, pi, snum) == 0) { switch (aplWeaponWorksLike[p->curr_weapon][snum]) { case HANDBOMB_WEAPON: p->hbomb_hold_delay = 0; if (p->ammo_amount[p->curr_weapon] > 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case HANDREMOTE_WEAPON: p->hbomb_hold_delay = 0; p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } break; case PISTOL_WEAPON: if (p->ammo_amount[p->curr_weapon] > 0) { // p->ammo_amount[p->curr_weapon]--; p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case CHAINGUN_WEAPON: if (p->ammo_amount[p->curr_weapon] > 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case SHOTGUN_WEAPON: if (p->ammo_amount[p->curr_weapon] > 0 && p->random_club_frame == 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case TRIPBOMB_WEAPON: if (operateTripbomb(snum)) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case SHRINKER_WEAPON: if (p->ammo_amount[p->curr_weapon] > 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case GROW_WEAPON: if (p->ammo_amount[p->curr_weapon] > 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case FREEZE_WEAPON: if (p->ammo_amount[p->curr_weapon] > 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case DEVISTATOR_WEAPON: if (p->ammo_amount[p->curr_weapon] > 0) { p->kickback_pic = 1; p->hbomb_hold_delay = !p->hbomb_hold_delay; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case RPG_WEAPON: if (p->ammo_amount[RPG_WEAPON] > 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; case KNEE_WEAPON: if (p->quick_kick == 0) { p->kickback_pic = 1; if (aplWeaponInitialSound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponInitialSound[p->curr_weapon][snum], pi); } } break; } } } } //--------------------------------------------------------------------------- // // // //--------------------------------------------------------------------------- void operateweapon_ww(int snum, ESyncBits actions, int psect) { auto p = &ps[snum]; int pi = p->i; int i, j, k; int psectlotag = sector[psect].lotag; // already firing... if (aplWeaponWorksLike[p->curr_weapon][snum] == HANDBOMB_WEAPON) { if (aplWeaponHoldDelay[p->curr_weapon][snum] // there is a hold delay && (p->kickback_pic == aplWeaponFireDelay[p->curr_weapon][snum]) // and we are 'at' hold && (actions & SB_FIRE) // and 'fire' button is still down ) // just hold here... { p->rapid_fire_hold = 1; return; } p->kickback_pic++; if (p->kickback_pic == aplWeaponHoldDelay[p->curr_weapon][snum]) { p->ammo_amount[p->curr_weapon]--; if (p->on_ground && (actions & SB_CROUCH)) { k = 15; i = ((p->gethorizsum() - 100) * 20); } else { k = 140; i = -512 - ((p->gethorizsum() - 100) * 20); } j = EGS(p->cursectnum, p->posx + (sintable[(p->getang() + 512) & 2047] >> 6), p->posy + (sintable[p->getang() & 2047] >> 6), p->posz, HEAVYHBOMB, -16, 9, 9, p->getang(), (k + (p->hbomb_hold_delay << 5)), i, pi, 1); { long lGrenadeLifetime = GetGameVar("GRENADE_LIFETIME", NAM_GRENADE_LIFETIME, -1, snum); long lGrenadeLifetimeVar = GetGameVar("GRENADE_LIFETIME_VAR", NAM_GRENADE_LIFETIME_VAR, -1, snum); // set timer. blows up when at zero.... sprite[j].extra = lGrenadeLifetime + mulscale(krand(), lGrenadeLifetimeVar, 14) - lGrenadeLifetimeVar; } if (k == 15) { sprite[j].yvel = 3; sprite[j].z += (8 << 8); } k = hits(pi); if (k < 512) { sprite[j].ang += 1024; sprite[j].zvel /= 3; sprite[j].xvel /= 3; } p->hbomb_on = 1; } else if (p->kickback_pic < aplWeaponHoldDelay[p->curr_weapon][snum] && (actions & SB_CROUCH)) { p->hbomb_hold_delay++; } else if (p->kickback_pic > aplWeaponTotalTime[p->curr_weapon][snum]) { p->okickback_pic = p->kickback_pic = 0; // don't change to remote when in NAM: grenades are timed checkavailweapon(p); } } else if (aplWeaponWorksLike[p->curr_weapon][snum] == HANDREMOTE_WEAPON) { p->kickback_pic++; if (p->kickback_pic == aplWeaponFireDelay[p->curr_weapon][snum]) { if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_BOMB_TRIGGER) { p->hbomb_on = 0; } if (aplWeaponShoots[p->curr_weapon][snum] != 0) { if (!(aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_NOVISIBLE)) { // make them visible if not set... lastvisinc = ud.levelclock + 32; p->visibility = 0; } SetGameVarID(g_iWeaponVarID, p->curr_weapon, p->i, snum); SetGameVarID(g_iWorksLikeVarID, aplWeaponWorksLike[p->curr_weapon][snum], p->i, snum); fi.shoot(pi, aplWeaponShoots[p->curr_weapon][snum]); } } if (p->kickback_pic >= aplWeaponTotalTime[p->curr_weapon][snum]) { p->okickback_pic = p->kickback_pic = 0; /// WHAT THE HELL DOES THIS DO....????????????? if (p->ammo_amount[TRIPBOMB_WEAPON] > 0) fi.addweapon(p, TRIPBOMB_WEAPON); else checkavailweapon(p); } } else { // the basic weapon... p->kickback_pic++; if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_CHECKATRELOAD) { if (p->kickback_pic == aplWeaponReload[p->curr_weapon][snum]) { checkavailweapon(p); } } if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_STANDSTILL && p->kickback_pic < (aplWeaponFireDelay[p->curr_weapon][snum] + 1)) { p->posz = p->oposz; p->poszv = 0; } if (p->kickback_pic == aplWeaponSound2Time[p->curr_weapon][snum]) { if (aplWeaponSound2Sound[p->curr_weapon][snum]) { S_PlayActorSound(aplWeaponSound2Sound[p->curr_weapon][snum], pi); } } if (p->kickback_pic == aplWeaponSpawnTime[p->curr_weapon][snum]) { DoSpawn(p, snum); } if (p->kickback_pic == aplWeaponFireDelay[p->curr_weapon][snum]) { DoFire(p, snum); } if (p->kickback_pic > aplWeaponFireDelay[p->curr_weapon][snum] && p->kickback_pic < aplWeaponTotalTime[p->curr_weapon][snum]) { if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_AUTOMATIC) { // an 'automatic' if ((actions & SB_FIRE) == 0) { p->kickback_pic = aplWeaponTotalTime[p->curr_weapon][snum]; } if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_FIREEVERYTHIRD) { if (((p->kickback_pic) % 3) == 0) { DoFire(p, snum); DoSpawn(p, snum); } } if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_FIREEVERYOTHER) { // fire every other... DoFire(p, snum); DoSpawn(p, snum); } } // 'automatic } else if (p->kickback_pic >= aplWeaponTotalTime[p->curr_weapon][snum]) { if ( //!(aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_CHECKATRELOAD) && aplWeaponReload[p->curr_weapon][snum] > aplWeaponTotalTime[p->curr_weapon][snum] && p->ammo_amount[p->curr_weapon] > 0 && (aplWeaponClip[p->curr_weapon][snum]) && ((p->ammo_amount[p->curr_weapon] % (aplWeaponClip[p->curr_weapon][snum])) == 0) ) { // reload in progress... int i; i = aplWeaponReload[p->curr_weapon][snum] - aplWeaponTotalTime[p->curr_weapon][snum]; // time for 'reload' if (p->kickback_pic == (aplWeaponTotalTime[p->curr_weapon][snum] + 1)) { // eject shortly after 'total time' S_PlayActorSound(EJECT_CLIP, pi); } else if (p->kickback_pic == (aplWeaponReload[p->curr_weapon][snum] - (i / 3))) { // insert occurs 2/3 of way through reload delay S_PlayActorSound(INSERT_CLIP, pi); } if (p->kickback_pic >= (aplWeaponReload[p->curr_weapon][snum])) { p->okickback_pic = p->kickback_pic = 0; } } else { if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_AUTOMATIC) { // an 'automatic' if (actions & SB_FIRE) { // we are an AUTOMATIC. Fire again... if (aplWeaponFlags[p->curr_weapon][snum] & WEAPON_FLAG_RANDOMRESTART) { p->kickback_pic = 1 + (krand() & 3); } else { p->kickback_pic = 1; } } else { p->okickback_pic = p->kickback_pic = 0; } } else { // not 'automatic' and >totaltime p->okickback_pic = p->kickback_pic = 0; } } } } // process the event ourselves if no handler provided. } END_DUKE_NS
26.134791
102
0.601478
[ "3d" ]
80be637060b9e7e14a6a46f79c814ddf640de01d
7,580
cc
C++
components/precache/core/precache_database.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
components/precache/core/precache_database.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
components/precache/core/precache_database.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/precache/core/precache_database.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/time/time.h" #include "sql/connection.h" #include "sql/transaction.h" #include "url/gurl.h" namespace { // The number of days old that an entry in the precache URL table can be before // it is considered "old" and is removed from the table. const int kPrecacheHistoryExpiryPeriodDays = 60; } // namespace namespace precache { PrecacheDatabase::PrecacheDatabase() : is_flush_posted_(false) { // A PrecacheDatabase can be constructed on any thread. thread_checker_.DetachFromThread(); } PrecacheDatabase::~PrecacheDatabase() { // Since the PrecacheDatabase is refcounted, it will only be deleted if there // are no references remaining to it, meaning that it is not in use. Thus, it // is safe to delete it, regardless of what thread we are on. thread_checker_.DetachFromThread(); } bool PrecacheDatabase::Init(const base::FilePath& db_path) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!db_); // Init must only be called once. db_.reset(new sql::Connection()); db_->set_histogram_tag("Precache"); if (!db_->Open(db_path)) { // Don't initialize the URL table if unable to access // the database. return false; } if (!precache_url_table_.Init(db_.get())) { // Raze and close the database connection to indicate that it's not usable, // and so that the database will be created anew next time, in case it's // corrupted. db_->RazeAndClose(); return false; } return true; } void PrecacheDatabase::DeleteExpiredPrecacheHistory( const base::Time& current_time) { if (!IsDatabaseAccessible()) { // Do nothing if unable to access the database. return; } // Delete old precache history that has expired. base::Time delete_end = current_time - base::TimeDelta::FromDays( kPrecacheHistoryExpiryPeriodDays); buffered_writes_.push_back( base::Bind(&PrecacheURLTable::DeleteAllPrecachedBefore, base::Unretained(&precache_url_table_), delete_end)); Flush(); } void PrecacheDatabase::RecordURLPrecached(const GURL& url, const base::Time& fetch_time, int64 size, bool was_cached) { if (!IsDatabaseAccessible()) { // Don't track anything if unable to access the database. return; } if (buffered_urls_.find(url.spec()) != buffered_urls_.end()) { // If the URL for this fetch is in the write buffer, then flush the write // buffer. Flush(); } if (was_cached && !precache_url_table_.HasURL(url)) { // Since the precache came from the cache, and there's no entry in the URL // table for the URL, this means that the resource was already in the cache // because of user browsing. Thus, this precache had no effect, so ignore // it. return; } if (!was_cached) { // The precache only counts as overhead if it was downloaded over the // network. UMA_HISTOGRAM_COUNTS("Precache.DownloadedPrecacheMotivated", size); } // Use the URL table to keep track of URLs that are in the cache thanks to // precaching. If a row for the URL already exists, than update the timestamp // to |fetch_time|. buffered_writes_.push_back( base::Bind(&PrecacheURLTable::AddURL, base::Unretained(&precache_url_table_), url, fetch_time)); buffered_urls_.insert(url.spec()); MaybePostFlush(); } void PrecacheDatabase::RecordURLFetched(const GURL& url, const base::Time& fetch_time, int64 size, bool was_cached, bool is_connection_cellular) { if (!IsDatabaseAccessible()) { // Don't track anything if unable to access the database. return; } if (buffered_urls_.find(url.spec()) != buffered_urls_.end()) { // If the URL for this fetch is in the write buffer, then flush the write // buffer. Flush(); } if (was_cached && !precache_url_table_.HasURL(url)) { // Ignore cache hits that precache can't take credit for. return; } if (!was_cached) { // The fetch was served over the network during user browsing, so count it // as downloaded non-precache bytes. UMA_HISTOGRAM_COUNTS("Precache.DownloadedNonPrecache", size); if (is_connection_cellular) { UMA_HISTOGRAM_COUNTS("Precache.DownloadedNonPrecache.Cellular", size); } } else { // The fetch was served from the cache, and since there's an entry for this // URL in the URL table, this means that the resource was served from the // cache only because precaching put it there. Thus, precaching was helpful, // so count the fetch as saved bytes. UMA_HISTOGRAM_COUNTS("Precache.Saved", size); if (is_connection_cellular) { UMA_HISTOGRAM_COUNTS("Precache.Saved.Cellular", size); } } // Since the resource has been fetched during user browsing, remove any record // of that URL having been precached from the URL table, if any exists. // The current fetch would have put this resource in the cache regardless of // whether or not it was previously precached, so delete any record of that // URL having been precached from the URL table. buffered_writes_.push_back( base::Bind(&PrecacheURLTable::DeleteURL, base::Unretained(&precache_url_table_), url)); buffered_urls_.insert(url.spec()); MaybePostFlush(); } bool PrecacheDatabase::IsDatabaseAccessible() const { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(db_); return db_->is_open(); } void PrecacheDatabase::Flush() { DCHECK(thread_checker_.CalledOnValidThread()); if (buffered_writes_.empty()) { // Do nothing if there's nothing to flush. DCHECK(buffered_urls_.empty()); return; } if (IsDatabaseAccessible()) { sql::Transaction transaction(db_.get()); if (transaction.Begin()) { for (std::vector<base::Closure>::const_iterator it = buffered_writes_.begin(); it != buffered_writes_.end(); ++it) { it->Run(); } transaction.Commit(); } } // Clear the buffer, even if the database is inaccessible or unable to begin a // transaction. buffered_writes_.clear(); buffered_urls_.clear(); } void PrecacheDatabase::PostedFlush() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(is_flush_posted_); is_flush_posted_ = false; Flush(); } void PrecacheDatabase::MaybePostFlush() { DCHECK(thread_checker_.CalledOnValidThread()); if (buffered_writes_.empty() || is_flush_posted_) { // There's no point in posting a flush if there's nothing to be flushed or // if a flush has already been posted. return; } DCHECK(base::MessageLoop::current()); // Post a delayed task to flush the buffer in 1 second, so that multiple // database writes can be buffered up and flushed together in the same // transaction. base::MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PrecacheDatabase::PostedFlush, scoped_refptr<PrecacheDatabase>(this)), base::TimeDelta::FromSeconds(1)); is_flush_posted_ = true; } } // namespace precache
33.245614
80
0.679683
[ "vector" ]
80c2f2d6c4ccf4fe213ff4ba9b38beaac1a893f5
2,346
cpp
C++
Source/WebKit/UIProcess/Automation/cairo/WebAutomationSessionCairo.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
Source/WebKit/UIProcess/Automation/cairo/WebAutomationSessionCairo.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebKit/UIProcess/Automation/cairo/WebAutomationSessionCairo.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2017 Igalia S.L. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebAutomationSession.h" #include <WebCore/RefPtrCairo.h> #include <cairo/cairo.h> #include <wtf/text/Base64.h> using namespace WebCore; namespace WebKit { std::optional<String> WebAutomationSession::platformGetBase64EncodedPNGData(const ShareableBitmap::Handle& handle) { RefPtr<ShareableBitmap> bitmap = ShareableBitmap::create(handle, SharedMemory::Protection::ReadOnly); if (!bitmap) return std::nullopt; auto surface = bitmap->createCairoSurface(); if (!surface) return std::nullopt; Vector<unsigned char> pngData; cairo_surface_write_to_png_stream(surface.get(), [](void* userData, const unsigned char* data, unsigned length) -> cairo_status_t { auto* pngData = static_cast<Vector<unsigned char>*>(userData); pngData->append(data, length); return CAIRO_STATUS_SUCCESS; }, &pngData); if (pngData.isEmpty()) return std::nullopt; return base64Encode(pngData); } } // namespace WebKit
37.83871
135
0.739557
[ "vector" ]
80c45fadb8379012bc30cce26f16edf281093b50
14,514
cpp
C++
Runtime/World/CScriptEffect.cpp
jackoalan/urde
413483a996805a870f002324ee46cfc123f4df06
[ "MIT" ]
null
null
null
Runtime/World/CScriptEffect.cpp
jackoalan/urde
413483a996805a870f002324ee46cfc123f4df06
[ "MIT" ]
null
null
null
Runtime/World/CScriptEffect.cpp
jackoalan/urde
413483a996805a870f002324ee46cfc123f4df06
[ "MIT" ]
null
null
null
#include "Runtime/World/CScriptEffect.hpp" #include "Runtime/CPlayerState.hpp" #include "Runtime/CSimplePool.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/GameGlobalObjects.hpp" #include "Runtime/Camera/CGameCamera.hpp" #include "Runtime/Character/CModelData.hpp" #include "Runtime/Collision/CMaterialList.hpp" #include "Runtime/Particle/CElementGen.hpp" #include "Runtime/Particle/CParticleElectric.hpp" #include "Runtime/World/CActorParameters.hpp" #include "Runtime/World/CGameLight.hpp" #include "Runtime/World/CScriptTrigger.hpp" #include "Runtime/World/CWorld.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { u32 CScriptEffect::g_NumParticlesUpdating = 0; u32 CScriptEffect::g_NumParticlesRendered = 0; CScriptEffect::CScriptEffect(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, const zeus::CVector3f& scale, CAssetId partId, CAssetId elscId, bool hotInThermal, bool noTimerUnlessAreaOccluded, bool rebuildSystemsOnActivate, bool active, bool useRateInverseCamDist, float rateInverseCamDist, float rateInverseCamDistRate, float duration, float durationResetWhileVisible, bool useRateCamDistRange, float rateCamDistRangeMin, float rateCamDistRangeMax, float rateCamDistRangeFarRate, bool combatVisorVisible, bool thermalVisorVisible, bool xrayVisorVisible, const CLightParameters& lParms, bool dieWhenSystemsDone) : CActor(uid, active, name, info, xf, CModelData::CModelDataNull(), CMaterialList(), CActorParameters::None().HotInThermal(hotInThermal), kInvalidUniqueId) , x10c_partId(partId) , x114_rateInverseCamDist(rateInverseCamDist) , x118_rateInverseCamDistSq(rateInverseCamDist * rateInverseCamDist) , x11c_rateInverseCamDistRate(rateInverseCamDistRate) , x120_rateCamDistRangeMin(rateCamDistRangeMin) , x124_rateCamDistRangeMax(rateCamDistRangeMax) , x128_rateCamDistRangeFarRate(rateCamDistRangeFarRate) , x12c_remTime(duration) , x130_duration(duration) , x134_durationResetWhileVisible(durationResetWhileVisible) , x138_actorLights(lParms.MakeActorLights()) { x110_24_enable = active; x110_25_noTimerUnlessAreaOccluded = noTimerUnlessAreaOccluded; x110_26_rebuildSystemsOnActivate = rebuildSystemsOnActivate; x110_27_useRateInverseCamDist = useRateInverseCamDist; x110_28_combatVisorVisible = combatVisorVisible; x110_29_thermalVisorVisible = thermalVisorVisible; x110_30_xrayVisorVisible = xrayVisorVisible; x110_31_anyVisorVisible = xrayVisorVisible && thermalVisorVisible && combatVisorVisible; x111_24_useRateCamDistRange = useRateCamDistRange; x111_25_dieWhenSystemsDone = dieWhenSystemsDone; x111_26_canRender = false; if (partId.IsValid()) { xf8_particleSystemToken = g_SimplePool->GetObj({FOURCC('PART'), partId}); x104_particleSystem = std::make_unique<CElementGen>(xf8_particleSystemToken); zeus::CTransform newXf = xf; newXf.origin = zeus::skZero3f; x104_particleSystem->SetOrientation(newXf); x104_particleSystem->SetGlobalTranslation(xf.origin); x104_particleSystem->SetGlobalScale(scale); x104_particleSystem->SetParticleEmission(active); x104_particleSystem->SetModulationColor(lParms.GetNoLightsAmbient()); x104_particleSystem->SetModelsUseLights(x138_actorLights != nullptr); } if (elscId.IsValid()) { xe8_electricToken = g_SimplePool->GetObj({FOURCC('ELSC'), elscId}); xf4_electric = std::make_unique<CParticleElectric>(xe8_electricToken); zeus::CTransform newXf = xf; newXf.origin = zeus::skZero3f; xf4_electric->SetOrientation(newXf); xf4_electric->SetGlobalTranslation(xf.origin); xf4_electric->SetGlobalScale(scale); xf4_electric->SetParticleEmission(active); } xe7_29_drawEnabled = true; } void CScriptEffect::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptEffect::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) { bool oldActive = GetActive(); switch (msg) { case EScriptObjectMessage::Activate: if (x110_26_rebuildSystemsOnActivate) { if (x104_particleSystem) { const zeus::CVector3f scale = x104_particleSystem->GetGlobalScale(); const zeus::CColor color = x104_particleSystem->GetModulationColor(); x104_particleSystem = std::make_unique<CElementGen>(xf8_particleSystemToken); zeus::CTransform newXf = GetTransform(); newXf.origin = zeus::skZero3f; x104_particleSystem->SetOrientation(newXf); x104_particleSystem->SetGlobalTranslation(GetTranslation()); x104_particleSystem->SetGlobalScale(scale); x104_particleSystem->SetParticleEmission(oldActive); x104_particleSystem->SetModulationColor(color); x104_particleSystem->SetModelsUseLights(x138_actorLights != nullptr); } if (xf4_electric) { const zeus::CVector3f scale = xf4_electric->GetGlobalScale(); const zeus::CColor color = xf4_electric->GetModulationColor(); xf4_electric = std::make_unique<CParticleElectric>(xe8_electricToken); zeus::CTransform newXf = GetTransform(); newXf.origin = zeus::skZero3f; xf4_electric->SetOrientation(newXf); xf4_electric->SetGlobalTranslation(GetTranslation()); xf4_electric->SetGlobalScale(scale); xf4_electric->SetParticleEmission(oldActive); xf4_electric->SetModulationColor(color); } } break; case EScriptObjectMessage::Registered: if (x104_particleSystem && x104_particleSystem->SystemHasLight()) { x108_lightId = mgr.AllocateUniqueId(); mgr.AddObject(new CGameLight(x108_lightId, GetAreaIdAlways(), GetActive(), std::string("EffectPLight_") + GetName().data(), x34_transform, GetUniqueId(), x104_particleSystem->GetLight(), x10c_partId.Value(), 1, 0.f)); } break; case EScriptObjectMessage::Deleted: if (x108_lightId != kInvalidUniqueId) { mgr.FreeScriptObject(x108_lightId); x108_lightId = kInvalidUniqueId; } break; case EScriptObjectMessage::InitializedInArea: for (const SConnection& conn : x20_conns) { if ((conn.x0_state == EScriptObjectState::Modify && conn.x4_msg == EScriptObjectMessage::Follow) || (conn.x0_state == EScriptObjectState::InheritBounds && conn.x4_msg == EScriptObjectMessage::Activate)) { auto search = mgr.GetIdListForScript(conn.x8_objId); for (auto it = search.first; it != search.second; ++it) { if (TCastToConstPtr<CScriptTrigger>(mgr.GetObjectById(it->second))) x13c_triggerId = it->second; } } } break; default: break; } CActor::AcceptScriptMsg(msg, uid, mgr); TCastToPtr<CActor> light = mgr.ObjectById(x108_lightId); mgr.SendScriptMsg(light, uid, msg); if (oldActive != GetActive()) { std::vector<TUniqueId> playIds; for (const SConnection& conn : x20_conns) { if (conn.x0_state != EScriptObjectState::Play || conn.x4_msg != EScriptObjectMessage::Activate) continue; TUniqueId uid = mgr.GetIdForScript(conn.x8_objId); if (uid != kInvalidUniqueId) playIds.push_back(uid); } if (playIds.size() > 0) { TCastToConstPtr<CActor> otherAct = mgr.GetObjectById(playIds[u32(0.99f * playIds.size() * mgr.GetActiveRandom()->Float())]); if (otherAct) { if (light) light->SetTransform(otherAct->GetTransform()); else SetTransform(otherAct->GetTransform()); } } x110_24_enable = true; if (x104_particleSystem) x104_particleSystem->SetParticleEmission(GetActive()); if (xf4_electric) xf4_electric->SetParticleEmission(GetActive()); if (GetActive()) x12c_remTime = zeus::max(x12c_remTime, x130_duration); } } void CScriptEffect::PreRender(CStateManager& mgr, const zeus::CFrustum&) { if (x110_27_useRateInverseCamDist || x111_24_useRateCamDistRange) { float genRate = 1.f; const CGameCamera* cam = mgr.GetCameraManager()->GetCurrentCamera(mgr); float camMagSq = (cam->GetTranslation() - GetTranslation()).magSquared(); float camMag = 0.f; if (camMagSq > 0.001f) camMag = std::sqrt(camMagSq); if (x110_27_useRateInverseCamDist && camMagSq < x118_rateInverseCamDistSq) genRate = (1.f - x11c_rateInverseCamDistRate) * (camMag / x114_rateInverseCamDist) + x11c_rateInverseCamDistRate; if (x111_24_useRateCamDistRange) { float t = zeus::min(1.f, zeus::max(0.f, camMag - x120_rateCamDistRangeMin) / (x124_rateCamDistRangeMax - x120_rateCamDistRangeMin)); genRate = (1.f - t) * genRate + t * x128_rateCamDistRangeFarRate; } x104_particleSystem->SetGeneratorRate(genRate); } if (!mgr.GetObjectById(x13c_triggerId)) x13c_triggerId = kInvalidUniqueId; } void CScriptEffect::AddToRenderer(const zeus::CFrustum& frustum, const CStateManager& mgr) const { if (!x111_26_canRender) { const_cast<CScriptEffect&>(*this).x12c_remTime = zeus::max(x12c_remTime, x134_durationResetWhileVisible); return; } if (!frustum.aabbFrustumTest(x9c_renderBounds)) return; const_cast<CScriptEffect&>(*this).x12c_remTime = zeus::max(x12c_remTime, x134_durationResetWhileVisible); if (x110_31_anyVisorVisible) { bool visible = false; const CPlayerState::EPlayerVisor visor = mgr.GetPlayerState()->GetActiveVisor(mgr); if (visor == CPlayerState::EPlayerVisor::Combat || visor == CPlayerState::EPlayerVisor::Scan) visible = x110_28_combatVisorVisible; else if (visor == CPlayerState::EPlayerVisor::XRay) visible = x110_30_xrayVisorVisible; else if (visor == CPlayerState::EPlayerVisor::Thermal) visible = x110_29_thermalVisorVisible; if (visible && x138_actorLights) { const CGameArea* area = mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways()); const_cast<CScriptEffect&>(*this).x138_actorLights->BuildAreaLightList( mgr, *area, zeus::CAABox{x9c_renderBounds.center(), x9c_renderBounds.center()}); const_cast<CScriptEffect&>(*this).x138_actorLights->BuildDynamicLightList(mgr, x9c_renderBounds); } EnsureRendered(mgr); } } void CScriptEffect::Render(const CStateManager& mgr) const { /* The following code is kept for reference, this is now performed in CElementGen if (x138_actorLights) x138_actorLights->ActivateLights(); */ if (x104_particleSystem && x104_particleSystem->GetParticleCountAll() > 0) { g_NumParticlesRendered += x104_particleSystem->GetParticleCountAll(); x104_particleSystem->Render(x138_actorLights.get()); } if (xf4_electric && xf4_electric->GetParticleCount() > 0) { g_NumParticlesRendered += xf4_electric->GetParticleCount(); xf4_electric->Render(x138_actorLights.get()); } } void CScriptEffect::Think(float dt, CStateManager& mgr) { if (xe4_28_transformDirty) { if (x104_particleSystem) { zeus::CTransform newXf = x34_transform; newXf.origin = zeus::skZero3f; x104_particleSystem->SetOrientation(newXf); x104_particleSystem->SetGlobalTranslation(x34_transform.origin); } if (xf4_electric) { zeus::CTransform newXf = x34_transform; newXf.origin = zeus::skZero3f; xf4_electric->SetOrientation(newXf); xf4_electric->SetGlobalTranslation(x34_transform.origin); } if (TCastToPtr<CActor> act = mgr.ObjectById(x108_lightId)) act->SetTransform(GetTransform()); xe4_28_transformDirty = false; } if (x110_25_noTimerUnlessAreaOccluded) { const CGameArea* area = mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways()); CGameArea::EOcclusionState visible = area->IsPostConstructed() ? area->GetOcclusionState() : CGameArea::EOcclusionState::Occluded; if (visible == CGameArea::EOcclusionState::Occluded && x12c_remTime <= 0.f) return; } else if (x12c_remTime <= 0.f) return; x12c_remTime -= dt; if (x110_24_enable) { if (x104_particleSystem) { x104_particleSystem->Update(dt); g_NumParticlesUpdating += x104_particleSystem->GetParticleCountAll(); } if (xf4_electric) { xf4_electric->Update(dt); g_NumParticlesUpdating += xf4_electric->GetParticleCount(); } if (x108_lightId != kInvalidUniqueId) { if (TCastToPtr<CGameLight> light = mgr.ObjectById(x108_lightId)) { if (x30_24_active) light->SetLight(x104_particleSystem->GetLight()); } } if (x111_25_dieWhenSystemsDone) { x140_destroyDelayTimer += dt; if (x140_destroyDelayTimer > 15.f || AreBothSystemsDeleteable()) { mgr.FreeScriptObject(GetUniqueId()); return; } } } if (x104_particleSystem) { if (xb4_drawFlags.x0_blendMode != 0) x104_particleSystem->SetModulationColor(xb4_drawFlags.x4_color); else x104_particleSystem->SetModulationColor(zeus::skWhite); } } void CScriptEffect::CalculateRenderBounds() { std::optional<zeus::CAABox> particleBounds; if (x104_particleSystem) particleBounds = x104_particleSystem->GetBounds(); std::optional<zeus::CAABox> electricBounds; if (xf4_electric) electricBounds = xf4_electric->GetBounds(); if (particleBounds || electricBounds) { zeus::CAABox renderBounds = zeus::CAABox(); if (particleBounds) { renderBounds.accumulateBounds(particleBounds->min); renderBounds.accumulateBounds(particleBounds->max); } if (electricBounds) { renderBounds.accumulateBounds(electricBounds->min); renderBounds.accumulateBounds(electricBounds->max); } x9c_renderBounds = renderBounds; x111_26_canRender = true; } else { x9c_renderBounds = {GetTranslation(), GetTranslation()}; x111_26_canRender = false; } } zeus::CAABox CScriptEffect::GetSortingBounds(const CStateManager& mgr) const { if (x13c_triggerId == kInvalidUniqueId) return x9c_renderBounds; else return static_cast<const CScriptTrigger*>(mgr.GetObjectById(x13c_triggerId))->GetTriggerBoundsWR(); } bool CScriptEffect::AreBothSystemsDeleteable() const { bool ret = true; if (x104_particleSystem && !x104_particleSystem->IsSystemDeletable()) ret = false; if (xf4_electric && !xf4_electric->IsSystemDeletable()) ret = false; return ret; } } // namespace urde
39.333333
119
0.716274
[ "render", "vector" ]
80c79d105472d89e1e358229395b3932d1cdf1b0
37,918
cpp
C++
PrimitivesTest/Game.cpp
walbourn/directxtk12test
c94ab20d30e94475198dc1420d592435aa19dd58
[ "MIT" ]
5
2019-05-23T14:25:41.000Z
2022-03-07T13:41:59.000Z
PrimitivesTest/Game.cpp
walbourn/directxtk12test
c94ab20d30e94475198dc1420d592435aa19dd58
[ "MIT" ]
3
2016-09-29T03:06:56.000Z
2020-09-26T19:38:37.000Z
PrimitivesTest/Game.cpp
walbourn/directxtk12test
c94ab20d30e94475198dc1420d592435aa19dd58
[ "MIT" ]
1
2022-03-07T13:42:00.000Z
2022-03-07T13:42:00.000Z
//-------------------------------------------------------------------------------------- // File: Game.cpp // // Developer unit test for DirectXTK Geometric Primitives // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615561 //-------------------------------------------------------------------------------------- #include "pch.h" #include "Game.h" #define GAMMA_CORRECT_RENDERING #define USE_COPY_QUEUE #define USE_COMPUTE_QUEUE // Build for LH vs. RH coords //#define LH_COORDS #define REVERSEZ namespace { constexpr float rowtop = 4.f; constexpr float row0 = 2.7f; constexpr float row1 = 1.f; constexpr float row2 = -0.7f; constexpr float row3 = -2.5f; constexpr float col0 = -7.5f; constexpr float col1 = -5.75f; constexpr float col2 = -4.25f; constexpr float col3 = -2.7f; constexpr float col4 = -1.25f; constexpr float col5 = 0.f; constexpr float col6 = 1.25f; constexpr float col7 = 2.5f; constexpr float col8 = 4.25f; constexpr float col9 = 5.75f; constexpr float col10 = 7.5f; } extern void ExitGame() noexcept; using namespace DirectX; using Microsoft::WRL::ComPtr; static_assert(std::is_nothrow_move_constructible<GeometricPrimitive>::value, "Move Ctor."); static_assert(std::is_nothrow_move_assignable<GeometricPrimitive>::value, "Move Assign."); Game::Game() noexcept(false) : m_instanceCount(0), m_spinning(true), m_firstFrame(false), m_pitch(0), m_yaw(0) { #ifdef GAMMA_CORRECT_RENDERING const DXGI_FORMAT c_RenderFormat = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; #else const DXGI_FORMAT c_RenderFormat = DXGI_FORMAT_B8G8R8A8_UNORM; #endif #ifdef XBOX m_deviceResources = std::make_unique<DX::DeviceResources>( c_RenderFormat, DXGI_FORMAT_D32_FLOAT, 2, DX::DeviceResources::c_Enable4K_UHD #ifdef _GAMING_XBOX | DX::DeviceResources::c_EnableQHD #endif ); #elif defined(UWP) m_deviceResources = std::make_unique<DX::DeviceResources>( c_RenderFormat, DXGI_FORMAT_D32_FLOAT, 2, D3D_FEATURE_LEVEL_11_0, DX::DeviceResources::c_Enable4K_Xbox ); #else m_deviceResources = std::make_unique<DX::DeviceResources>(c_RenderFormat); #endif #ifdef LOSTDEVICE m_deviceResources->RegisterDeviceNotify(this); #endif } Game::~Game() { if (m_deviceResources) { m_deviceResources->WaitForGpu(); } } // Initialize the Direct3D resources required to run. void Game::Initialize( #ifdef COREWINDOW IUnknown* window, #else HWND window, #endif int width, int height, DXGI_MODE_ROTATION rotation) { m_gamePad = std::make_unique<GamePad>(); m_keyboard = std::make_unique<Keyboard>(); #ifdef XBOX UNREFERENCED_PARAMETER(rotation); UNREFERENCED_PARAMETER(width); UNREFERENCED_PARAMETER(height); m_deviceResources->SetWindow(window); #ifdef COREWINDOW m_keyboard->SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window)); #endif #elif defined(UWP) m_deviceResources->SetWindow(window, width, height, rotation); m_keyboard->SetWindow(reinterpret_cast<ABI::Windows::UI::Core::ICoreWindow*>(window)); #else UNREFERENCED_PARAMETER(rotation); m_deviceResources->SetWindow(window, width, height); #endif m_deviceResources->CreateDeviceResources(); CreateDeviceDependentResources(); m_deviceResources->CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources(); } #pragma region Frame Update // Executes the basic game loop. void Game::Tick() { m_timer.Tick([&]() { Update(m_timer); }); Render(); } // Updates the world. void Game::Update(DX::StepTimer const&) { PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update"); auto kb = m_keyboard->GetState(); m_keyboardButtons.Update(kb); auto pad = m_gamePad->GetState(0); if (pad.IsConnected()) { m_gamePadButtons.Update(pad); if (pad.IsViewPressed()) { ExitGame(); } if (m_gamePadButtons.a == GamePad::ButtonStateTracker::PRESSED) { m_spinning = !m_spinning; } if (pad.IsLeftStickPressed()) { m_spinning = false; m_yaw = m_pitch = 0.f; } else { m_yaw += pad.thumbSticks.leftX * 0.1f; m_pitch -= pad.thumbSticks.leftY * 0.1f; } } else { m_gamePadButtons.Reset(); if (kb.A || kb.D) { m_spinning = false; m_yaw += (kb.D ? 0.1f : -0.1f); } if (kb.W || kb.S) { m_spinning = false; m_pitch += (kb.W ? 0.1f : -0.1f); } if (kb.Home) { m_spinning = false; m_yaw = m_pitch = 0.f; } } if (m_yaw > XM_PI) { m_yaw -= XM_PI * 2.f; } else if (m_yaw < -XM_PI) { m_yaw += XM_PI * 2.f; } if (kb.Escape) { ExitGame(); } if (m_keyboardButtons.IsKeyPressed(Keyboard::Space)) { m_spinning = !m_spinning; } PIXEndEvent(); } #pragma endregion #pragma region Frame Render // Draws the scene. void Game::Render() { // Don't try to render anything before the first Update. if (m_timer.GetFrameCount() == 0) { return; } auto time = static_cast<float>(m_timer.GetTotalSeconds()); float alphaFade = (sin(time * 2) + 1) / 2; if (alphaFade >= 1) alphaFade = 1 - FLT_EPSILON; float yaw = time * 0.4f; float pitch = time * 0.7f; float roll = time * 1.1f; XMMATRIX world; if (m_spinning) { world = XMMatrixRotationRollPitchYaw(pitch, yaw, roll); } else { world = XMMatrixRotationRollPitchYaw(m_pitch, m_yaw, 0); } // Prepare the command list to render a new frame. m_deviceResources->Prepare(); Clear(); auto commandList = m_deviceResources->GetCommandList(); PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Render"); if (m_firstFrame) { // // This is not strictly needed on Windows due to common state promotion, but this behavior is optional on Xbox // // Copy queue resources are left in D3D12_RESOURCE_STATE_COPY_DEST state #ifdef USE_COPY_QUEUE m_torus->Transition(commandList, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER); #endif // Compute queue IBs are in D3D12_RESOURCE_STATE_COPY_DEST state #ifdef USE_COMPUTE_QUEUE m_teapot->Transition(commandList, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER); #endif m_firstFrame = false; } // Set the descriptor heaps ID3D12DescriptorHeap* heaps[] = { m_resourceDescriptors->Heap(), m_states->Heap() }; commandList->SetDescriptorHeaps(static_cast<UINT>(std::size(heaps)), heaps); XMVECTORF32 red, green, blue, yellow, cyan, magenta, cornflower, lime, gray; #ifdef GAMMA_CORRECT_RENDERING red.v = XMColorSRGBToRGB(Colors::Red); green.v = XMColorSRGBToRGB(Colors::Green); blue.v = XMColorSRGBToRGB(Colors::Blue); yellow.v = XMColorSRGBToRGB(Colors::Yellow); cyan.v = XMColorSRGBToRGB(Colors::Cyan); magenta.v = XMColorSRGBToRGB(Colors::Magenta); cornflower.v = XMColorSRGBToRGB(Colors::CornflowerBlue); lime.v = XMColorSRGBToRGB(Colors::Lime); gray.v = XMColorSRGBToRGB(Colors::Gray); #else red.v = Colors::Red; green.v = Colors::Green; blue.v = Colors::Blue; yellow.v = Colors::Yellow; cyan.v = Colors::Cyan; magenta.v = Colors::Magenta; cornflower.v = Colors::CornflowerBlue; lime.v = Colors::Lime; gray.v = Colors::Gray; #endif SimpleMath::Vector4 white = Colors::White.v; //--- Draw shapes ---------------------------------------------------------------------- m_effect->SetWorld(world * XMMatrixTranslation(col0, row0, 0)); m_effect->SetDiffuseColor(Colors::White); m_effect->Apply(commandList); m_cube->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col1, row0, 0)); m_effect->SetDiffuseColor(red); m_effect->Apply(commandList); m_sphere->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col2, row0, 0)); m_effect->SetDiffuseColor(green); m_effect->Apply(commandList); m_geosphere->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col3, row0, 0)); m_effect->SetDiffuseColor(lime); m_effect->Apply(commandList); m_cylinder->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col4, row0, 0)); m_effect->SetDiffuseColor(yellow); m_effect->Apply(commandList); m_cone->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col5, row0, 0)); m_effect->SetDiffuseColor(blue); m_effect->Apply(commandList); m_torus->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col6, row0, 0)); m_effect->SetDiffuseColor(cornflower); m_effect->Apply(commandList); m_teapot->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col7, row0, 0)); m_effect->SetDiffuseColor(red); m_effect->Apply(commandList); m_tetra->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col8, row0, 0)); m_effect->SetDiffuseColor(lime); m_effect->Apply(commandList); m_octa->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col9, row0, 0)); m_effect->SetDiffuseColor(blue); m_effect->Apply(commandList); m_dodec->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col10, row0, 0)); m_effect->SetDiffuseColor(cyan); m_effect->Apply(commandList); m_iso->Draw(commandList); m_effect->SetWorld(world * XMMatrixTranslation(col8, row3, 0)); m_effect->SetDiffuseColor(magenta); m_effect->Apply(commandList); m_box->Draw(commandList); //--- Draw textured shapes ------------------------------------------------------------- m_effectTexture->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::RefTexture), m_states->AnisotropicWrap()); m_effectTexture->SetWorld(world * XMMatrixTranslation(col0, row1, 0)); m_effectTexture->SetDiffuseColor(Colors::White); m_effectTexture->Apply(commandList); m_cube->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col1, row1, 0)); m_effectTexture->SetDiffuseColor(red); m_effectTexture->Apply(commandList); m_sphere->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col2, row1, 0)); m_effectTexture->SetDiffuseColor(green); m_effectTexture->Apply(commandList); m_geosphere->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col3, row1, 0)); m_effectTexture->SetDiffuseColor(lime); m_effectTexture->Apply(commandList); m_cylinder->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col4, row1, 0)); m_effectTexture->SetDiffuseColor(yellow); m_effectTexture->Apply(commandList); m_cone->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col5, row1, 0)); m_effectTexture->SetDiffuseColor(blue); m_effectTexture->Apply(commandList); m_torus->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col6, row1, 0)); m_effectTexture->SetDiffuseColor(cornflower); m_effectTexture->Apply(commandList); m_teapot->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col7, row1, 0)); m_effectTexture->SetDiffuseColor(red); m_effectTexture->Apply(commandList); m_tetra->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col8, row1, 0)); m_effectTexture->SetDiffuseColor(lime); m_effectTexture->Apply(commandList); m_octa->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col9, row1, 0)); m_effectTexture->SetDiffuseColor(blue); m_effectTexture->Apply(commandList); m_dodec->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col10, row1, 0)); m_effectTexture->SetDiffuseColor(cyan); m_effectTexture->Apply(commandList); m_iso->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col9, row3, 0)); m_effectTexture->SetDiffuseColor(magenta); m_effectTexture->Apply(commandList); m_box->Draw(commandList); m_effectTexture->SetWorld(world * XMMatrixTranslation(col7, row3, 0)); m_effectTexture->SetDiffuseColor(Colors::White); m_effectTexture->Apply(commandList); m_customBox->Draw(commandList); //--- Draw shapes in wireframe --------------------------------------------------------- m_effectWireframe->SetDiffuseColor(gray); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col0, row2, 0)); m_effectWireframe->Apply(commandList); m_cube->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col1, row2, 0)); m_effectWireframe->Apply(commandList); m_sphere->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col2, row2, 0)); m_effectWireframe->Apply(commandList); m_geosphere->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col3, row2, 0)); m_effectWireframe->Apply(commandList); m_cylinder->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col4, row2, 0)); m_effectWireframe->Apply(commandList); m_cone->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col5, row2, 0)); m_effectWireframe->Apply(commandList); m_torus->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col6, row2, 0)); m_effectWireframe->Apply(commandList); m_teapot->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col7, row2, 0)); m_effectWireframe->Apply(commandList); m_tetra->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col8, row2, 0)); m_effectWireframe->Apply(commandList); m_octa->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col9, row2, 0)); m_effectWireframe->Apply(commandList); m_dodec->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col10, row2, 0)); m_effectWireframe->Apply(commandList); m_iso->Draw(commandList); m_effectWireframe->SetWorld(world * XMMatrixTranslation(col10, row3, 0)); m_effectWireframe->Apply(commandList); m_box->Draw(commandList); //--- Draw shapes with alpha blending -------------------------------------------------- m_effectAlpha->SetWorld(world * XMMatrixTranslation(col0, row3, 0)); m_effectAlpha->SetDiffuseColor(white * alphaFade); m_effectAlpha->SetAlpha(alphaFade); m_effectAlpha->Apply(commandList); m_cube->Draw(commandList); m_effectPMAlphaTexture->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::Cat), m_states->AnisotropicWrap()); m_effectPMAlphaTexture->SetWorld(world * XMMatrixTranslation(col1, row3, 0)); m_effectPMAlphaTexture->SetDiffuseColor(white * alphaFade); m_effectPMAlphaTexture->SetAlpha(alphaFade); m_effectPMAlphaTexture->Apply(commandList); m_cube->Draw(commandList); m_effectAlphaTexture->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::Cat), m_states->AnisotropicWrap()); m_effectAlphaTexture->SetWorld(world * XMMatrixTranslation(col2, row3, 0)); m_effectAlphaTexture->SetDiffuseColor(white * alphaFade); m_effectAlphaTexture->SetAlpha(alphaFade); m_effectAlphaTexture->Apply(commandList); m_cube->Draw(commandList); //--- Draw dynamic light --------------------------------------------------------------- XMVECTOR quat = XMQuaternionRotationRollPitchYaw(pitch, yaw, roll); XMVECTOR dir = XMVector3Rotate(g_XMOne, quat); m_effectLights->SetLightDirection(0, dir); m_effectLights->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::DirectXLogo), m_states->AnisotropicWrap()); m_effectLights->SetWorld(XMMatrixTranslation(col3, row3, 0)); m_effectLights->Apply(commandList); m_cube->Draw(commandList); //--- Draw dynamic light and fog ------------------------------------------------------- XMMATRIX fbworld = XMMatrixTranslation(0, 0, cos(time) * 2.f); m_effectFog->SetWorld(fbworld * XMMatrixTranslation(col5, row3, 0)); m_effectFog->SetLightDirection(0, dir); m_effectFog->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::DirectXLogo), m_states->AnisotropicWrap()); m_effectFog->Apply(commandList); m_cube->Draw(commandList); //--- Draw shapes with instancing ------------------------------------------------------ { size_t j = 0; for (float x = -8.f; x <= 8.f; x += 3.f) { XMMATRIX m = world * XMMatrixTranslation(x, 0.f, cos(time + float(j) * XM_PIDIV4)); XMStoreFloat3x4(&m_instanceTransforms[j], m); ++j; } assert(j == m_instanceCount); const size_t instBytes = j * sizeof(XMFLOAT3X4); GraphicsResource inst = m_graphicsMemory->Allocate(instBytes); memcpy(inst.Memory(), m_instanceTransforms.get(), instBytes); D3D12_VERTEX_BUFFER_VIEW vertexBufferInst = {}; vertexBufferInst.BufferLocation = inst.GpuAddress(); vertexBufferInst.SizeInBytes = static_cast<UINT>(instBytes); vertexBufferInst.StrideInBytes = sizeof(XMFLOAT3X4); commandList->IASetVertexBuffers(1, 1, &vertexBufferInst); m_instancedEffect->SetTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::DirectXLogo), m_states->AnisotropicWrap()); m_instancedEffect->SetNormalTexture(m_resourceDescriptors->GetGpuHandle(Descriptors::NormalMap)); m_instancedEffect->SetWorld(XMMatrixTranslation(0.f, rowtop, 0.f)); m_instancedEffect->Apply(commandList); m_teapot->DrawInstanced(commandList, m_instanceCount); } PIXEndEvent(commandList); // Show the new frame. PIXBeginEvent(m_deviceResources->GetCommandQueue(), PIX_COLOR_DEFAULT, L"Present"); m_deviceResources->Present(); m_graphicsMemory->Commit(m_deviceResources->GetCommandQueue()); // Sample stats to update peak values std::ignore = m_graphicsMemory->GetStatistics(); PIXEndEvent(m_deviceResources->GetCommandQueue()); } // Helper method to clear the back buffers. void Game::Clear() { auto commandList = m_deviceResources->GetCommandList(); PIXBeginEvent(commandList, PIX_COLOR_DEFAULT, L"Clear"); // Clear the views. auto rtvDescriptor = m_deviceResources->GetRenderTargetView(); auto dsvDescriptor = m_deviceResources->GetDepthStencilView(); XMVECTORF32 color; #ifdef GAMMA_CORRECT_RENDERING color.v = XMColorSRGBToRGB(Colors::CornflowerBlue); #else color.v = Colors::CornflowerBlue; #endif #ifdef REVERSEZ constexpr float c_zclear = 0.f; #else constexpr float c_zclear = 1.f; #endif commandList->OMSetRenderTargets(1, &rtvDescriptor, FALSE, &dsvDescriptor); commandList->ClearRenderTargetView(rtvDescriptor, color, 0, nullptr); commandList->ClearDepthStencilView(dsvDescriptor, D3D12_CLEAR_FLAG_DEPTH, c_zclear, 0, 0, nullptr); // Set the viewport and scissor rect. auto viewport = m_deviceResources->GetScreenViewport(); auto scissorRect = m_deviceResources->GetScissorRect(); commandList->RSSetViewports(1, &viewport); commandList->RSSetScissorRects(1, &scissorRect); PIXEndEvent(commandList); } #pragma endregion #pragma region Message Handlers // Message handlers void Game::OnActivated() { } void Game::OnDeactivated() { } void Game::OnSuspending() { m_deviceResources->Suspend(); } void Game::OnResuming() { m_deviceResources->Resume(); m_timer.ResetElapsedTime(); m_gamePadButtons.Reset(); m_keyboardButtons.Reset(); } #ifdef PC void Game::OnWindowMoved() { auto r = m_deviceResources->GetOutputSize(); m_deviceResources->WindowSizeChanged(r.right, r.bottom); } #endif #ifndef XBOX void Game::OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation) { #ifdef UWP if (!m_deviceResources->WindowSizeChanged(width, height, rotation)) return; #else UNREFERENCED_PARAMETER(rotation); if (!m_deviceResources->WindowSizeChanged(width, height)) return; #endif CreateWindowSizeDependentResources(); } #endif #ifdef UWP void Game::ValidateDevice() { m_deviceResources->ValidateDevice(); } #endif // Properties void Game::GetDefaultSize(int& width, int& height) const { width = 1600; height = 720; } #pragma endregion #pragma region Direct3D Resources // These are the resources that depend on the device. void Game::CreateDeviceDependentResources() { auto device = m_deviceResources->GetD3DDevice(); m_graphicsMemory = std::make_unique<GraphicsMemory>(device); m_states = std::make_unique<CommonStates>(device); // Create effects. RenderTargetState rtState(m_deviceResources->GetBackBufferFormat(), m_deviceResources->GetDepthBufferFormat()); #ifdef REVERSEZ const auto& c_depthState = CommonStates::DepthReverseZ; #else const auto& c_depthState = CommonStates::DepthDefault; #endif { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::Opaque, c_depthState, CommonStates::CullCounterClockwise, rtState); m_effect = std::make_unique<BasicEffect>(device, EffectFlags::Lighting, pd); m_effect->EnableDefaultLighting(); } { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::Opaque, c_depthState, CommonStates::Wireframe, rtState); m_effectWireframe = std::make_unique<BasicEffect>(device, EffectFlags::PerPixelLighting, pd); m_effectWireframe->EnableDefaultLighting(); } { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::Opaque, c_depthState, CommonStates::CullCounterClockwise, rtState); m_effectTexture = std::make_unique<BasicEffect>(device, EffectFlags::Texture | EffectFlags::PerPixelLighting, pd); m_effectTexture->EnableDefaultLighting(); } { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::AlphaBlend, c_depthState, CommonStates::CullCounterClockwise, rtState); m_effectAlpha = std::make_unique<BasicEffect>(device, EffectFlags::PerPixelLighting, pd); m_effectAlpha->EnableDefaultLighting(); } { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::AlphaBlend, c_depthState, CommonStates::CullCounterClockwise, rtState); m_effectPMAlphaTexture = std::make_unique<BasicEffect>(device, EffectFlags::Texture | EffectFlags::PerPixelLighting, pd); m_effectPMAlphaTexture->EnableDefaultLighting(); } { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::NonPremultiplied, c_depthState, CommonStates::CullCounterClockwise, rtState); m_effectAlphaTexture = std::make_unique<BasicEffect>(device, EffectFlags::Texture | EffectFlags::PerPixelLighting, pd); m_effectAlphaTexture->EnableDefaultLighting(); } { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::Opaque, c_depthState, CommonStates::CullCounterClockwise, rtState); m_effectLights = std::make_unique<BasicEffect>(device, EffectFlags::Texture | EffectFlags::PerPixelLighting, pd); m_effectLights->EnableDefaultLighting(); } { EffectPipelineStateDescription pd( &GeometricPrimitive::VertexType::InputLayout, CommonStates::Opaque, c_depthState, CommonStates::CullCounterClockwise, rtState); m_effectFog = std::make_unique<BasicEffect>(device, EffectFlags::Texture | EffectFlags::Fog | EffectFlags::PerPixelLighting, pd); m_effectFog->EnableDefaultLighting(); #ifdef LH_COORDS m_effectFog->SetFogStart(-6); m_effectFog->SetFogEnd(-8); #else m_effectFog->SetFogStart(6); m_effectFog->SetFogEnd(8); #endif XMVECTORF32 color; #ifdef GAMMA_CORRECT_RENDERING color.v = XMColorSRGBToRGB(Colors::CornflowerBlue); #else color.v = Colors::CornflowerBlue; #endif m_effectFog->SetFogColor(color); } { static const D3D12_INPUT_ELEMENT_DESC s_InputElements[] = { // GeometricPrimitive::VertexType { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, // XMFLOAT3X4 { "InstMatrix", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 }, { "InstMatrix", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 }, { "InstMatrix", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1 }, }; static const D3D12_INPUT_LAYOUT_DESC s_layout = { s_InputElements, static_cast<UINT>(std::size(s_InputElements)) }; EffectPipelineStateDescription pd( &s_layout, CommonStates::Opaque, c_depthState, CommonStates::CullCounterClockwise, rtState); m_instancedEffect = std::make_unique<NormalMapEffect>(device, EffectFlags::Fog | EffectFlags::Instancing, pd); m_instancedEffect->EnableDefaultLighting(); #ifdef LH_COORDS m_instancedEffect->SetFogStart(-9); m_instancedEffect->SetFogEnd(-10); #else m_instancedEffect->SetFogStart(9); m_instancedEffect->SetFogEnd(10); #endif XMVECTORF32 color; #ifdef GAMMA_CORRECT_RENDERING color.v = XMColorSRGBToRGB(Colors::CornflowerBlue); #else color.v = Colors::CornflowerBlue; #endif m_instancedEffect->SetFogColor(color); // Create instance transforms. size_t j = 0; for (float x = -8.f; x <= 8.f; x += 3.f) { ++j; } m_instanceCount = static_cast<UINT>(j); m_instanceTransforms = std::make_unique<XMFLOAT3X4[]>(j); constexpr XMFLOAT3X4 s_identity = { 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f }; j = 0; for (float x = -8.f; x <= 8.f; x += 3.f) { m_instanceTransforms[j] = s_identity; m_instanceTransforms[j]._14 = x; ++j; } } // Create shapes. #ifdef LH_COORDS bool rhcoords = false; #else bool rhcoords = true; #endif m_cube = GeometricPrimitive::CreateCube(1.f, rhcoords); m_box = GeometricPrimitive::CreateBox(XMFLOAT3(1.f / 2.f, 2.f / 2.f, 3.f / 2.f), rhcoords); m_sphere = GeometricPrimitive::CreateSphere(1.f, 16, rhcoords); m_geosphere = GeometricPrimitive::CreateGeoSphere(1.f, 3, rhcoords); m_cylinder = GeometricPrimitive::CreateCylinder(1.f, 1.f, 32, rhcoords); m_cone = GeometricPrimitive::CreateCone(1.f, 1.f, 32, rhcoords); m_torus = GeometricPrimitive::CreateTorus(1.f, 0.333f, 32, rhcoords); m_teapot = GeometricPrimitive::CreateTeapot(1.f, 8, rhcoords); m_tetra = GeometricPrimitive::CreateTetrahedron(0.75f, rhcoords); m_octa = GeometricPrimitive::CreateOctahedron(0.75f, rhcoords); m_dodec = GeometricPrimitive::CreateDodecahedron(0.5f, rhcoords); m_iso = GeometricPrimitive::CreateIcosahedron(0.5f, rhcoords); { GeometricPrimitive::VertexCollection customVerts; GeometricPrimitive::IndexCollection customIndices; GeometricPrimitive::CreateBox(customVerts, customIndices, XMFLOAT3(1.f / 2.f, 2.f / 2.f, 3.f / 2.f), rhcoords); assert(customVerts.size() == 24); assert(customIndices.size() == 36); for (auto& it : customVerts) { it.textureCoordinate.x *= 5.f; it.textureCoordinate.y *= 5.f; } m_customBox = GeometricPrimitive::CreateCustom(customVerts, customIndices); } { // Ensure VertexType alias is consistent with alternative client usage GeometricPrimitive::VertexCollection customVerts; GeometricPrimitive::IndexCollection customIndices; GeometricPrimitive::CreateBox(customVerts, customIndices, XMFLOAT3(1.f / 2.f, 2.f / 2.f, 3.f / 2.f), rhcoords); assert(customVerts.size() == 24); assert(customIndices.size() == 36); for (auto& it : customVerts) { it.textureCoordinate.x *= 5.f; it.textureCoordinate.y *= 5.f; } m_customBox2 = GeometricPrimitive::CreateCustom(customVerts, customIndices); } // Load textures. m_resourceDescriptors = std::make_unique<DescriptorHeap>(device, Descriptors::Count); { ResourceUploadBatch resourceUpload(device); resourceUpload.Begin(); // Convert some primitives to using static VB/IBs m_geosphere->LoadStaticBuffers(device, resourceUpload); m_cylinder->LoadStaticBuffers(device, resourceUpload); m_cone->LoadStaticBuffers(device, resourceUpload); #ifndef USE_COPY_QUEUE m_torus->LoadStaticBuffers(device, resourceUpload); #endif #ifndef USE_COMPUTE_QUEUE m_teapot->LoadStaticBuffers(device, resourceUpload); #endif #ifdef GAMMA_CORRECT_RENDERING constexpr DDS_LOADER_FLAGS loadFlags = DDS_LOADER_FORCE_SRGB; #else constexpr DDS_LOADER_FLAGS loadFlags = DDS_LOADER_DEFAULT; #endif DX::ThrowIfFailed( CreateDDSTextureFromFileEx(device, resourceUpload, L"cat.dds", 0, D3D12_RESOURCE_FLAG_NONE, loadFlags, m_cat.ReleaseAndGetAddressOf())); CreateShaderResourceView(device, m_cat.Get(), m_resourceDescriptors->GetCpuHandle(Descriptors::Cat)); DX::ThrowIfFailed( CreateDDSTextureFromFileEx(device, resourceUpload, L"dx5_logo.dds", 0, D3D12_RESOURCE_FLAG_NONE, loadFlags, m_dxLogo.ReleaseAndGetAddressOf())); CreateShaderResourceView(device, m_dxLogo.Get(), m_resourceDescriptors->GetCpuHandle(Descriptors::DirectXLogo)); DX::ThrowIfFailed( CreateDDSTextureFromFileEx(device, resourceUpload, L"reftexture.dds", 0, D3D12_RESOURCE_FLAG_NONE, loadFlags, m_refTexture.ReleaseAndGetAddressOf())); CreateShaderResourceView(device, m_refTexture.Get(), m_resourceDescriptors->GetCpuHandle(Descriptors::RefTexture)); DX::ThrowIfFailed( CreateDDSTextureFromFileEx(device, resourceUpload, L"normalMap.dds", 0, D3D12_RESOURCE_FLAG_NONE, DDS_LOADER_DEFAULT, m_normalMap.ReleaseAndGetAddressOf())); CreateShaderResourceView(device, m_normalMap.Get(), m_resourceDescriptors->GetCpuHandle(Descriptors::NormalMap)); auto uploadResourcesFinished = resourceUpload.End(m_deviceResources->GetCommandQueue()); uploadResourcesFinished.wait(); } // Copy Queue test #ifdef USE_COPY_QUEUE { ResourceUploadBatch resourceUpload(device); D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COPY; resourceUpload.Begin(queueDesc.Type); DX::ThrowIfFailed(device->CreateCommandQueue(&queueDesc, IID_GRAPHICS_PPV_ARGS(m_copyQueue.ReleaseAndGetAddressOf()))); m_copyQueue->SetName(L"CopyTest"); m_torus->LoadStaticBuffers(device, resourceUpload); auto uploadResourcesFinished = resourceUpload.End(m_copyQueue.Get()); uploadResourcesFinished.wait(); m_firstFrame = true; } #endif // USE_COPY_QUEUE // Compute Queue test #ifdef USE_COMPUTE_QUEUE { ResourceUploadBatch resourceUpload(device); D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE; resourceUpload.Begin(queueDesc.Type); DX::ThrowIfFailed(device->CreateCommandQueue(&queueDesc, IID_GRAPHICS_PPV_ARGS(m_computeQueue.ReleaseAndGetAddressOf()))); m_computeQueue->SetName(L"ComputeTest"); m_teapot->LoadStaticBuffers(device, resourceUpload); auto uploadResourcesFinished = resourceUpload.End(m_computeQueue.Get()); uploadResourcesFinished.wait(); m_firstFrame = true; } #endif // USE_COMPUTE_QUEUE m_deviceResources->WaitForGpu(); } // Allocate all memory resources that change on a window SizeChanged event. void Game::CreateWindowSizeDependentResources() { static const XMVECTORF32 cameraPosition = { { { 0.f, 0.f, 9.f, 0.f } } }; auto size = m_deviceResources->GetOutputSize(); float aspect = (float)size.right / (float)size.bottom; #ifdef REVERSEZ constexpr float c_nearz = 10.f; constexpr float c_farz = 1.f; #else constexpr float c_nearz = 1.f; constexpr float c_farz = 10.f; #endif #ifdef LH_COORDS XMMATRIX view = XMMatrixLookAtLH(cameraPosition, g_XMZero, XMVectorSet(0, 1, 0, 0)); XMMATRIX projection = XMMatrixPerspectiveFovLH(1, aspect, c_nearz, c_farz); #else XMMATRIX view = XMMatrixLookAtRH(cameraPosition, g_XMZero, XMVectorSet(0, 1, 0, 0)); XMMATRIX projection = XMMatrixPerspectiveFovRH(1, aspect, c_nearz, c_farz); #endif #ifdef UWP { auto orient3d = m_deviceResources->GetOrientationTransform3D(); XMMATRIX orient = XMLoadFloat4x4(&orient3d); projection *= orient; } #endif m_effect->SetView(view); m_effectWireframe->SetView(view); m_effectTexture->SetView(view); m_effectAlpha->SetView(view); m_effectPMAlphaTexture->SetView(view); m_effectAlphaTexture->SetView(view); m_effectLights->SetView(view); m_effectFog->SetView(view); m_instancedEffect->SetView(view); m_effect->SetProjection(projection); m_effectWireframe->SetProjection(projection); m_effectTexture->SetProjection(projection); m_effectAlpha->SetProjection(projection); m_effectPMAlphaTexture->SetProjection(projection); m_effectAlphaTexture->SetProjection(projection); m_effectLights->SetProjection(projection); m_effectFog->SetProjection(projection); m_instancedEffect->SetProjection(projection); } #ifdef LOSTDEVICE void Game::OnDeviceLost() { m_cube.reset(); m_box.reset(); m_sphere.reset(); m_geosphere.reset(); m_cylinder.reset(); m_cone.reset(); m_torus.reset(); m_teapot.reset(); m_tetra.reset(); m_octa.reset(); m_dodec.reset(); m_iso.reset(); m_customBox.reset(); m_customBox2.reset(); m_effect.reset(); m_effectWireframe.reset(); m_effectTexture.reset(); m_effectAlpha.reset(); m_effectPMAlphaTexture.reset(); m_effectAlphaTexture.reset(); m_effectLights.reset(); m_effectFog.reset(); m_instancedEffect.reset(); m_cat.Reset(); m_dxLogo.Reset(); m_refTexture.Reset(); m_normalMap.Reset(); m_resourceDescriptors.reset(); m_states.reset(); m_graphicsMemory.reset(); m_copyQueue.Reset(); m_computeQueue.Reset(); } void Game::OnDeviceRestored() { CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } #endif #pragma endregion
33.319859
148
0.657814
[ "render" ]
80ca1ef06af9cd08b80f9fa8869da0cca8096053
975
cpp
C++
HeightCalibrator/SimpleTest.cpp
dohxehapo/HeightCalibrator
1f129bd6e5a593425ae125309b05002ff087e30f
[ "MIT" ]
2
2019-05-06T06:58:54.000Z
2019-05-06T14:23:29.000Z
HeightCalibrator/SimpleTest.cpp
dohxehapo/HeightCalibrator
1f129bd6e5a593425ae125309b05002ff087e30f
[ "MIT" ]
null
null
null
HeightCalibrator/SimpleTest.cpp
dohxehapo/HeightCalibrator
1f129bd6e5a593425ae125309b05002ff087e30f
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "SimpleTest.h" void SimpleTest::Run(std::string pImagePath, std::vector<Post> &pPosts, PostImage pTestPost) { // Initialization HeightCalibrator calibr; LineF skyline; calibr.Initialize(pPosts, &skyline); // Processing float height; calibr.GetHeight(pTestPost, height); std::cout << "Height: " << height << "\n"; // Output results cv::namedWindow("output"); cv::Mat img = cv::imread(pImagePath); if (img.empty()) return; for (unsigned int i = 0; i < pPosts.size(); ++i) cv::line(img, cv::Point(pPosts[i].BaseX, pPosts[i].BaseY), cv::Point(pPosts[i].BaseX, pPosts[i].TopY), cv::Scalar(0, 0, 255), 2); cv::line(img, cv::Point(pTestPost.BaseX, pTestPost.BaseY), cv::Point(pTestPost.BaseX, pTestPost.TopY), cv::Scalar(0, 255, 0), 2); cv::line(img, cv::Point((int)skyline.Pt1.X, (int)skyline.Pt1.Y), cv::Point((int)skyline.Pt2.X, (int)skyline.Pt2.Y), cv::Scalar(255, 0, 0), 2); cv::imshow("output", img); cv::waitKey(0); }
29.545455
143
0.667692
[ "vector" ]
80ce0bda4dbad4253c981db320feaae037f4cee9
1,890
cpp
C++
samples/CaptureCube/src/CaptureCubeApp.cpp
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
3,494
2015-01-02T08:42:09.000Z
2022-03-31T14:16:23.000Z
samples/CaptureCube/src/CaptureCubeApp.cpp
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
1,284
2015-01-02T07:31:47.000Z
2022-03-30T02:06:43.000Z
samples/CaptureCube/src/CaptureCubeApp.cpp
rsh/Cinder-Emscripten
4a08250c56656865c7c3a52fb9380980908b1439
[ "BSD-2-Clause" ]
780
2015-01-02T22:14:29.000Z
2022-03-30T00:16:56.000Z
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/Surface.h" #include "cinder/Capture.h" #include "cinder/Camera.h" #include "cinder/Text.h" #include "cinder/Log.h" using namespace ci; using namespace ci::app; class CaptureCubeApp : public App { public: void setup() override; void resize() override; void update() override; void draw() override; CameraPersp mCam; CaptureRef mCapture; gl::Texture2dRef mTexture; mat4 mCubeRotation; }; void CaptureCubeApp::setup() { try { mCapture = Capture::create( 320, 240 ); mCapture->start(); } catch( CaptureExc &exc ) { CI_LOG_EXCEPTION( "failed to initialize the Capture: ", exc ); // create a warning texture TextLayout layout; layout.clear( Color( 0.3f, 0.3f, 0.3f ) ); layout.setColor( Color( 1, 1, 1 ) ); layout.setFont( Font( "Arial", 96 ) ); layout.addCenteredLine( "No Webcam" ); layout.addCenteredLine( "Detected" ); mTexture = gl::Texture2d::create( layout.render() ); } mCam.lookAt( vec3( 3, 2, -3 ), vec3( 0 ) ); gl::enableDepthRead(); gl::enableDepthWrite(); } void CaptureCubeApp::resize() { mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 ); gl::setMatrices( mCam ); } void CaptureCubeApp::update() { if( mCapture && mCapture->checkNewFrame() ) mTexture = gl::Texture2d::create( *mCapture->getSurface() ); // Rotate the cube by .03 radians around an arbitrary axis mCubeRotation *= rotate( 0.03f, vec3( 1 ) ); } void CaptureCubeApp::draw() { gl::clear( Color::black() ); if( ! mTexture ) return; gl::bindStockShader( gl::ShaderDef().texture() ); gl::ScopedTextureBind texScope( mTexture ); gl::ScopedModelMatrix modelScope; gl::multModelMatrix( mCubeRotation ); gl::drawCube( vec3( 0 ), vec3( 2, 2, 2 ) ); } CINDER_APP( CaptureCubeApp, RendererGl( RendererGl::Options().msaa( 4 ) ) )
23.333333
75
0.678307
[ "render" ]
80cf455769f68822d7dc186c38c37e1b67c438dc
19,546
cpp
C++
src/Pipeline/SpirvShaderControlFlow.cpp
springmeyer/swiftshader
d2046d34f651c6ef1426b48f6280df2464094c18
[ "Apache-2.0" ]
null
null
null
src/Pipeline/SpirvShaderControlFlow.cpp
springmeyer/swiftshader
d2046d34f651c6ef1426b48f6280df2464094c18
[ "Apache-2.0" ]
null
null
null
src/Pipeline/SpirvShaderControlFlow.cpp
springmeyer/swiftshader
d2046d34f651c6ef1426b48f6280df2464094c18
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SpirvShader.hpp" #include "Reactor/Coroutine.hpp" // rr::Yield #include "ShaderCore.hpp" #include <spirv/unified1/spirv.hpp> #include <queue> namespace sw { SpirvShader::Block::Block(InsnIterator begin, InsnIterator end) : begin_(begin) , end_(end) { // Default to a Simple, this may change later. kind = Block::Simple; // Walk the instructions to find the last two of the block. InsnIterator insns[2]; for(auto insn : *this) { insns[0] = insns[1]; insns[1] = insn; } switch(insns[1].opcode()) { case spv::OpBranch: branchInstruction = insns[1]; outs.emplace(Block::ID(branchInstruction.word(1))); switch(insns[0].opcode()) { case spv::OpLoopMerge: kind = Loop; mergeInstruction = insns[0]; mergeBlock = Block::ID(mergeInstruction.word(1)); continueTarget = Block::ID(mergeInstruction.word(2)); break; default: kind = Block::Simple; break; } break; case spv::OpBranchConditional: branchInstruction = insns[1]; outs.emplace(Block::ID(branchInstruction.word(2))); outs.emplace(Block::ID(branchInstruction.word(3))); switch(insns[0].opcode()) { case spv::OpSelectionMerge: kind = StructuredBranchConditional; mergeInstruction = insns[0]; mergeBlock = Block::ID(mergeInstruction.word(1)); break; case spv::OpLoopMerge: kind = Loop; mergeInstruction = insns[0]; mergeBlock = Block::ID(mergeInstruction.word(1)); continueTarget = Block::ID(mergeInstruction.word(2)); break; default: kind = UnstructuredBranchConditional; break; } break; case spv::OpSwitch: branchInstruction = insns[1]; outs.emplace(Block::ID(branchInstruction.word(2))); for(uint32_t w = 4; w < branchInstruction.wordCount(); w += 2) { outs.emplace(Block::ID(branchInstruction.word(w))); } switch(insns[0].opcode()) { case spv::OpSelectionMerge: kind = StructuredSwitch; mergeInstruction = insns[0]; mergeBlock = Block::ID(mergeInstruction.word(1)); break; default: kind = UnstructuredSwitch; break; } break; default: break; } } void SpirvShader::Function::TraverseReachableBlocks(Block::ID id, SpirvShader::Block::Set &reachable) const { if(reachable.count(id) == 0) { reachable.emplace(id); for(auto out : getBlock(id).outs) { TraverseReachableBlocks(out, reachable); } } } void SpirvShader::Function::AssignBlockFields() { Block::Set reachable; TraverseReachableBlocks(entry, reachable); for(auto &it : blocks) { auto &blockId = it.first; auto &block = it.second; if(reachable.count(blockId) > 0) { for(auto &outId : it.second.outs) { auto outIt = blocks.find(outId); ASSERT_MSG(outIt != blocks.end(), "Block %d has a non-existent out %d", blockId.value(), outId.value()); auto &out = outIt->second; out.ins.emplace(blockId); } if(block.kind == Block::Loop) { auto mergeIt = blocks.find(block.mergeBlock); ASSERT_MSG(mergeIt != blocks.end(), "Loop block %d has a non-existent merge block %d", blockId.value(), block.mergeBlock.value()); mergeIt->second.isLoopMerge = true; } } } } void SpirvShader::Function::ForeachBlockDependency(Block::ID blockId, std::function<void(Block::ID)> f) const { auto block = getBlock(blockId); for(auto dep : block.ins) { if(block.kind != Block::Loop || // if not a loop... !ExistsPath(blockId, dep, block.mergeBlock)) // or a loop and not a loop back edge { f(dep); } } } bool SpirvShader::Function::ExistsPath(Block::ID from, Block::ID to, Block::ID notPassingThrough) const { // TODO: Optimize: This can be cached on the block. Block::Set seen; seen.emplace(notPassingThrough); std::queue<Block::ID> pending; pending.emplace(from); while(pending.size() > 0) { auto id = pending.front(); pending.pop(); for(auto out : getBlock(id).outs) { if(seen.count(out) != 0) { continue; } if(out == to) { return true; } pending.emplace(out); } seen.emplace(id); } return false; } void SpirvShader::EmitState::addOutputActiveLaneMaskEdge(Block::ID to, RValue<SIMD::Int> mask) { addActiveLaneMaskEdge(block, to, mask & activeLaneMask()); } void SpirvShader::EmitState::addActiveLaneMaskEdge(Block::ID from, Block::ID to, RValue<SIMD::Int> mask) { auto edge = Block::Edge{ from, to }; auto it = edgeActiveLaneMasks.find(edge); if(it == edgeActiveLaneMasks.end()) { edgeActiveLaneMasks.emplace(edge, mask); } else { auto combined = it->second | mask; edgeActiveLaneMasks.erase(edge); edgeActiveLaneMasks.emplace(edge, combined); } } RValue<SIMD::Int> SpirvShader::GetActiveLaneMaskEdge(EmitState *state, Block::ID from, Block::ID to) const { auto edge = Block::Edge{ from, to }; auto it = state->edgeActiveLaneMasks.find(edge); ASSERT_MSG(it != state->edgeActiveLaneMasks.end(), "Could not find edge %d -> %d", from.value(), to.value()); return it->second; } void SpirvShader::EmitBlocks(Block::ID id, EmitState *state, Block::ID ignore /* = 0 */) const { auto oldPending = state->pending; auto &function = getFunction(state->function); std::deque<Block::ID> pending; state->pending = &pending; pending.push_front(id); while(pending.size() > 0) { auto id = pending.front(); auto const &block = function.getBlock(id); if(id == ignore) { pending.pop_front(); continue; } // Ensure all dependency blocks have been generated. auto depsDone = true; function.ForeachBlockDependency(id, [&](Block::ID dep) { if(state->visited.count(dep) == 0) { state->pending->push_front(dep); depsDone = false; } }); if(!depsDone) { continue; } pending.pop_front(); state->block = id; switch(block.kind) { case Block::Simple: case Block::StructuredBranchConditional: case Block::UnstructuredBranchConditional: case Block::StructuredSwitch: case Block::UnstructuredSwitch: EmitNonLoop(state); break; case Block::Loop: EmitLoop(state); break; default: UNREACHABLE("Unexpected Block Kind: %d", int(block.kind)); } } state->pending = oldPending; } void SpirvShader::EmitNonLoop(EmitState *state) const { auto &function = getFunction(state->function); auto blockId = state->block; auto block = function.getBlock(blockId); if(!state->visited.emplace(blockId).second) { return; // Already generated this block. } if(blockId != function.entry) { // Set the activeLaneMask. SIMD::Int activeLaneMask(0); for(auto in : block.ins) { auto inMask = GetActiveLaneMaskEdge(state, in, blockId); activeLaneMask |= inMask; } SetActiveLaneMask(activeLaneMask, state); } EmitInstructions(block.begin(), block.end(), state); for(auto out : block.outs) { if(state->visited.count(out) == 0) { state->pending->push_back(out); } } } void SpirvShader::EmitLoop(EmitState *state) const { auto &function = getFunction(state->function); auto blockId = state->block; auto &block = function.getBlock(blockId); auto mergeBlockId = block.mergeBlock; auto &mergeBlock = function.getBlock(mergeBlockId); if(!state->visited.emplace(blockId).second) { return; // Already emitted this loop. } // Gather all the blocks that make up the loop. std::unordered_set<Block::ID> loopBlocks; loopBlocks.emplace(block.mergeBlock); function.TraverseReachableBlocks(blockId, loopBlocks); // incomingBlocks are block ins that are not back-edges. std::unordered_set<Block::ID> incomingBlocks; for(auto in : block.ins) { if(loopBlocks.count(in) == 0) { incomingBlocks.emplace(in); } } // Emit the loop phi instructions, and initialize them with a value from // the incoming blocks. for(auto insn = block.begin(); insn != block.mergeInstruction; insn++) { if(insn.opcode() == spv::OpPhi) { StorePhi(blockId, insn, state, incomingBlocks); } } // loopActiveLaneMask is the mask of lanes that are continuing to loop. // This is initialized with the incoming active lane masks. SIMD::Int loopActiveLaneMask = SIMD::Int(0); for(auto in : incomingBlocks) { loopActiveLaneMask |= GetActiveLaneMaskEdge(state, in, blockId); } // mergeActiveLaneMasks contains edge lane masks for the merge block. // This is the union of all edge masks across all iterations of the loop. std::unordered_map<Block::ID, SIMD::Int> mergeActiveLaneMasks; for(auto in : function.getBlock(mergeBlockId).ins) { mergeActiveLaneMasks.emplace(in, SIMD::Int(0)); } // Create the loop basic blocks auto headerBasicBlock = Nucleus::createBasicBlock(); auto mergeBasicBlock = Nucleus::createBasicBlock(); // Start emitting code inside the loop. Nucleus::createBr(headerBasicBlock); Nucleus::setInsertBlock(headerBasicBlock); // Load the active lane mask. SetActiveLaneMask(loopActiveLaneMask, state); // Emit the non-phi loop header block's instructions. for(auto insn = block.begin(); insn != block.end(); insn++) { if(insn.opcode() == spv::OpPhi) { LoadPhi(insn, state); } else { EmitInstruction(insn, state); } } // Emit all blocks between the loop header and the merge block, but // don't emit the merge block yet. for(auto out : block.outs) { EmitBlocks(out, state, mergeBlockId); } // Restore current block id after emitting loop blocks. state->block = blockId; // Rebuild the loopActiveLaneMask from the loop back edges. loopActiveLaneMask = SIMD::Int(0); for(auto in : block.ins) { if(function.ExistsPath(blockId, in, mergeBlockId)) { loopActiveLaneMask |= GetActiveLaneMaskEdge(state, in, blockId); } } // Add active lanes to the merge lane mask. for(auto in : function.getBlock(mergeBlockId).ins) { auto edge = Block::Edge{ in, mergeBlockId }; auto it = state->edgeActiveLaneMasks.find(edge); if(it != state->edgeActiveLaneMasks.end()) { mergeActiveLaneMasks[in] |= it->second; } } // Update loop phi values. for(auto insn = block.begin(); insn != block.mergeInstruction; insn++) { if(insn.opcode() == spv::OpPhi) { StorePhi(blockId, insn, state, loopBlocks); } } // Use the [loop -> merge] active lane masks to update the phi values in // the merge block. We need to do this to handle divergent control flow // in the loop. // // Consider the following: // // int phi_source = 0; // for(uint i = 0; i < 4; i++) // { // phi_source = 0; // if(gl_GlobalInvocationID.x % 4 == i) // divergent control flow // { // phi_source = 42; // single lane assignment. // break; // activeLaneMask for [loop->merge] is active for a single lane. // } // // -- we are here -- // } // // merge block // int phi = phi_source; // OpPhi // // In this example, with each iteration of the loop, phi_source will // only have a single lane assigned. However by 'phi' value in the merge // block needs to be assigned the union of all the per-lane assignments // of phi_source when that lane exited the loop. for(auto insn = mergeBlock.begin(); insn != mergeBlock.end(); insn++) { if(insn.opcode() == spv::OpPhi) { StorePhi(mergeBlockId, insn, state, loopBlocks); } } // Loop body now done. // If any lanes are still active, jump back to the loop header, // otherwise jump to the merge block. Nucleus::createCondBr(AnyTrue(loopActiveLaneMask).value, headerBasicBlock, mergeBasicBlock); // Continue emitting from the merge block. Nucleus::setInsertBlock(mergeBasicBlock); state->pending->push_back(mergeBlockId); for(const auto &it : mergeActiveLaneMasks) { state->addActiveLaneMaskEdge(it.first, mergeBlockId, it.second); } } SpirvShader::EmitResult SpirvShader::EmitBranch(InsnIterator insn, EmitState *state) const { auto target = Block::ID(insn.word(1)); state->addActiveLaneMaskEdge(state->block, target, state->activeLaneMask()); return EmitResult::Terminator; } SpirvShader::EmitResult SpirvShader::EmitBranchConditional(InsnIterator insn, EmitState *state) const { auto &function = getFunction(state->function); auto block = function.getBlock(state->block); ASSERT(block.branchInstruction == insn); auto condId = Object::ID(block.branchInstruction.word(1)); auto trueBlockId = Block::ID(block.branchInstruction.word(2)); auto falseBlockId = Block::ID(block.branchInstruction.word(3)); auto cond = Operand(this, state, condId); ASSERT_MSG(getType(getObject(condId)).componentCount == 1, "Condition must be a Boolean type scalar"); // TODO: Optimize for case where all lanes take same path. state->addOutputActiveLaneMaskEdge(trueBlockId, cond.Int(0)); state->addOutputActiveLaneMaskEdge(falseBlockId, ~cond.Int(0)); return EmitResult::Terminator; } SpirvShader::EmitResult SpirvShader::EmitSwitch(InsnIterator insn, EmitState *state) const { auto &function = getFunction(state->function); auto block = function.getBlock(state->block); ASSERT(block.branchInstruction == insn); auto selId = Object::ID(block.branchInstruction.word(1)); auto sel = Operand(this, state, selId); ASSERT_MSG(sel.componentCount == 1, "Selector must be a scalar"); auto numCases = (block.branchInstruction.wordCount() - 3) / 2; // TODO: Optimize for case where all lanes take same path. SIMD::Int defaultLaneMask = state->activeLaneMask(); // Gather up the case label matches and calculate defaultLaneMask. std::vector<RValue<SIMD::Int>> caseLabelMatches; caseLabelMatches.reserve(numCases); for(uint32_t i = 0; i < numCases; i++) { auto label = block.branchInstruction.word(i * 2 + 3); auto caseBlockId = Block::ID(block.branchInstruction.word(i * 2 + 4)); auto caseLabelMatch = CmpEQ(sel.Int(0), SIMD::Int(label)); state->addOutputActiveLaneMaskEdge(caseBlockId, caseLabelMatch); defaultLaneMask &= ~caseLabelMatch; } auto defaultBlockId = Block::ID(block.branchInstruction.word(2)); state->addOutputActiveLaneMaskEdge(defaultBlockId, defaultLaneMask); return EmitResult::Terminator; } SpirvShader::EmitResult SpirvShader::EmitUnreachable(InsnIterator insn, EmitState *state) const { // TODO: Log something in this case? SetActiveLaneMask(SIMD::Int(0), state); return EmitResult::Terminator; } SpirvShader::EmitResult SpirvShader::EmitReturn(InsnIterator insn, EmitState *state) const { SetActiveLaneMask(SIMD::Int(0), state); return EmitResult::Terminator; } SpirvShader::EmitResult SpirvShader::EmitKill(InsnIterator insn, EmitState *state) const { state->routine->killMask |= SignMask(state->activeLaneMask()); SetActiveLaneMask(SIMD::Int(0), state); return EmitResult::Terminator; } SpirvShader::EmitResult SpirvShader::EmitFunctionCall(InsnIterator insn, EmitState *state) const { auto functionId = Function::ID(insn.word(3)); const auto &functionIt = functions.find(functionId); ASSERT(functionIt != functions.end()); auto &function = functionIt->second; // TODO(b/141246700): Add full support for spv::OpFunctionCall // The only supported function is a single OpKill wrapped in a // function, as a result of the "wrap OpKill" SPIRV-Tools pass ASSERT(function.blocks.size() == 1); spv::Op wrapOpKill[] = { spv::OpLabel, spv::OpKill }; for(const auto &block : function.blocks) { int insnNumber = 0; for(auto blockInsn : block.second) { if(insnNumber > 1) { UNIMPLEMENTED("b/141246700: Function block number of instructions: %d", insnNumber); // FIXME(b/141246700) return EmitResult::Continue; } if(blockInsn.opcode() != wrapOpKill[insnNumber++]) { UNIMPLEMENTED("b/141246700: Function block instruction %d : %s", insnNumber - 1, OpcodeName(blockInsn.opcode()).c_str()); // FIXME(b/141246700) return EmitResult::Continue; } if(blockInsn.opcode() == spv::OpKill) { EmitInstruction(blockInsn, state); } } } return EmitResult::Continue; } SpirvShader::EmitResult SpirvShader::EmitControlBarrier(InsnIterator insn, EmitState *state) const { auto executionScope = spv::Scope(GetConstScalarInt(insn.word(1))); auto semantics = spv::MemorySemanticsMask(GetConstScalarInt(insn.word(3))); // TODO: We probably want to consider the memory scope here. For now, // just always emit the full fence. Fence(semantics); switch(executionScope) { case spv::ScopeWorkgroup: Yield(YieldResult::ControlBarrier); break; case spv::ScopeSubgroup: break; default: // See Vulkan 1.1 spec, Appendix A, Validation Rules within a Module. UNREACHABLE("Scope for execution must be limited to Workgroup or Subgroup"); break; } return EmitResult::Continue; } SpirvShader::EmitResult SpirvShader::EmitPhi(InsnIterator insn, EmitState *state) const { auto &function = getFunction(state->function); auto currentBlock = function.getBlock(state->block); if(!currentBlock.isLoopMerge) { // If this is a loop merge block, then don't attempt to update the // phi values from the ins. EmitLoop() has had to take special care // of this phi in order to correctly deal with divergent lanes. StorePhi(state->block, insn, state, currentBlock.ins); } LoadPhi(insn, state); return EmitResult::Continue; } void SpirvShader::LoadPhi(InsnIterator insn, EmitState *state) const { auto typeId = Type::ID(insn.word(1)); auto type = getType(typeId); auto objectId = Object::ID(insn.word(2)); auto storageIt = state->routine->phis.find(objectId); ASSERT(storageIt != state->routine->phis.end()); auto &storage = storageIt->second; auto &dst = state->createIntermediate(objectId, type.componentCount); for(uint32_t i = 0; i < type.componentCount; i++) { dst.move(i, storage[i]); } } void SpirvShader::StorePhi(Block::ID currentBlock, InsnIterator insn, EmitState *state, std::unordered_set<SpirvShader::Block::ID> const &filter) const { auto typeId = Type::ID(insn.word(1)); auto type = getType(typeId); auto objectId = Object::ID(insn.word(2)); auto storageIt = state->routine->phis.find(objectId); ASSERT(storageIt != state->routine->phis.end()); auto &storage = storageIt->second; for(uint32_t w = 3; w < insn.wordCount(); w += 2) { auto varId = Object::ID(insn.word(w + 0)); auto blockId = Block::ID(insn.word(w + 1)); if(filter.count(blockId) == 0) { continue; } auto mask = GetActiveLaneMaskEdge(state, blockId, currentBlock); auto in = Operand(this, state, varId); for(uint32_t i = 0; i < type.componentCount; i++) { storage[i] = As<SIMD::Float>((As<SIMD::Int>(storage[i]) & ~mask) | (in.Int(i) & mask)); } } } void SpirvShader::Fence(spv::MemorySemanticsMask semantics) const { if(semantics == spv::MemorySemanticsMaskNone) { return; //no-op } rr::Fence(MemoryOrder(semantics)); } void SpirvShader::Yield(YieldResult res) const { rr::Yield(RValue<Int>(int(res))); } void SpirvShader::SetActiveLaneMask(RValue<SIMD::Int> mask, EmitState *state) const { state->activeLaneMaskValue = mask.value; dbgUpdateActiveLaneMask(mask, state); } } // namespace sw
27.529577
151
0.696562
[ "object", "vector" ]
80cff375b1d40f31d75259335bb23fa072912673
2,938
cpp
C++
eval/src/benchmarkOnlyDS.cpp
xaedes/GNSS-Shadowing
a748e3063fb76272005b6430a844a53644cca9b0
[ "MIT" ]
29
2017-10-13T12:14:13.000Z
2022-02-25T16:39:05.000Z
eval/src/benchmarkOnlyDS.cpp
xaedes/GNSS-Shadowing
a748e3063fb76272005b6430a844a53644cca9b0
[ "MIT" ]
null
null
null
eval/src/benchmarkOnlyDS.cpp
xaedes/GNSS-Shadowing
a748e3063fb76272005b6430a844a53644cca9b0
[ "MIT" ]
8
2018-04-21T14:52:26.000Z
2022-02-14T13:51:10.000Z
#include <iostream> #include <sstream> #include <memory> #include <iomanip> // std::setprecision #include <ios> // std::fixed #include "eval/version.h" #include "mapping/mapProperties.h" #include "mapping/mapper.h" #include "mapping/dopMap.h" #include "world/world.h" #include "common/timing.h" using namespace gnssShadowing::eval; using namespace gnssShadowing::common; using namespace gnssShadowing; using namespace std; int main(int argc, char* argv[]) { // cout << "version " << Version::getString() << endl; // cout << "revision " << Version::getRevision() << endl; world::World world("data/2017-03-28.tle",0,"data/uni.obj","Building"); int numParameter=7; if (argc < numParameter+1) return -1; istringstream isss[numParameter]; for (int k=0; k<numParameter; k++) { isss[k] = istringstream(argv[1+k]); } double basePlaneLevel; double interval; int numPlaneLevels; double width; double height; double resolution; double maxDuration; int k=0; isss[k++] >> basePlaneLevel; isss[k++] >> interval; isss[k++] >> numPlaneLevels; isss[k++] >> width; isss[k++] >> height; isss[k++] >> resolution; isss[k++] >> maxDuration; double startTime = now_seconds(); int numIterations = 0; int numRows,numCols; while((numIterations == 0) || (now_seconds() - startTime < maxDuration)) { std::vector<double> planeLevels; for (int k=0; k<numPlaneLevels; k++) { planeLevels.push_back(basePlaneLevel + k*interval); } float w = width; float h = height; mapping::MapProperties mapProperties(-w/2,-h/2,w/resolution,h/resolution,resolution,resolution,planeLevels); numCols = mapProperties.m_num_cols; numRows = mapProperties.m_num_rows; mapping::Mapper mapper(world, mapProperties, 5*D2R); mapper.updateSats(startTime); mapper.m_visibilityMap.clear(); mapper.m_visibilityMap.populateWithAll(); mapper.m_dopMap.populate(mapper.m_visibilityMap); numIterations++; } double endTime = now_seconds(); double totalDuration = endTime - startTime; double meanDuration = totalDuration / (numIterations?numIterations:1); int numCells = numCols*numRows; int numCellsTotal = numCells*numPlaneLevels; cout << basePlaneLevel << "\t" << interval << "\t" << numPlaneLevels << "\t" << width << "\t" << height << "\t" << resolution << "\t" << numCols << "\t" << numRows << "\t" << numCells << "\t" << numCellsTotal << "\t" << maxDuration << "\t" << numIterations << "\t" << meanDuration << "\t" << totalDuration << "\t" << endl; }
28.803922
116
0.576923
[ "vector" ]
80d3ab6c11f6755dfd0b96daaa636923dae80626
12,455
cpp
C++
src/Context.cpp
CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan
08803777a20a010015958af8bd841147fc6b7fd6
[ "MIT" ]
3
2020-06-24T07:13:59.000Z
2020-10-22T03:49:15.000Z
src/Context.cpp
CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan
08803777a20a010015958af8bd841147fc6b7fd6
[ "MIT" ]
null
null
null
src/Context.cpp
CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan
08803777a20a010015958af8bd841147fc6b7fd6
[ "MIT" ]
null
null
null
/** * @file 'Context.cpp' * @brief Graphic context holder * @copyright The MIT license * @author Matej Karas */ #include "Context.h" #include <GLFW/glfw3.h> #include <unordered_set> #include <iostream> #include <vulkan/vulkan.hpp> #ifndef DEBUG #define ENABLE_VALIDATION_LAYERS #endif namespace { const std::vector<const char*> VALIDATION_LAYERS = { "VK_LAYER_LUNARG_standard_validation", }; const std::vector<const char*> DEVICE_EXTENSIONS = { VK_KHR_SWAPCHAIN_EXTENSION_NAME, }; bool checkDeviceExtensionSupport(vk::PhysicalDevice device) { std::unordered_set<std::string> requiredExtensions(DEVICE_EXTENSIONS.begin(), DEVICE_EXTENSIONS.end()); for (const auto& extension : device.enumerateDeviceExtensionProperties()) requiredExtensions.erase(extension.extensionName); return requiredExtensions.empty(); } bool isDeviceSuitable(vk::PhysicalDevice device, vk::SurfaceKHR windowSurface) { QueueFamilyIndices indices = QueueFamilyIndices::findQueueFamilies(device, windowSurface); bool extensionsSupported = checkDeviceExtensionSupport(device); auto formats = device.getSurfaceFormatsKHR(windowSurface); auto presentModes = device.getSurfacePresentModesKHR(windowSurface); return indices.isComplete() && extensionsSupported && (!formats.empty() && !presentModes.empty()); } VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT msgType, const VkDebugUtilsMessengerCallbackDataEXT* callback, void* userData) { vk::DebugUtilsMessageSeverityFlagsEXT messageSeverity(severity); vk::DebugUtilsMessageTypeFlagsEXT messageType(msgType); vk::DebugUtilsMessengerCallbackDataEXT callbackData(*callback); if (messageSeverity & vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose) std::cerr << "VERBOSE: "; else if (messageSeverity & vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo) std::cerr << "INFO: "; else if (messageSeverity & vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning) std::cerr << "WARNING: "; else if (messageSeverity & vk::DebugUtilsMessageSeverityFlagBitsEXT::eError) std::cerr << "ERROR: "; if (messageType & vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral) std::cerr << "GENERAL"; else { if (messageType & vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation) std::cerr << "VALIDATION"; if (messageType & vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance) { if (messageType & vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation) std::cerr << " | "; std::cerr << "PERFORMANCE"; } } { auto name = (callbackData.pMessageIdName) ? callbackData.pMessageIdName : ""; std::cerr << " - Message ID Number " << callbackData.messageIdNumber << ", Message ID Name: " << name << "\n\t" << callbackData.pMessage; } if (callbackData.objectCount > 0) { std::cerr << "\n\n\tObjects - " << callbackData.objectCount << "\n"; for (size_t object = 0; object < callbackData.objectCount; object++) { auto name = (callbackData.pObjects[object].pObjectName) ? callbackData.pObjects[object].pObjectName : ""; std::cerr << "\t\tObject[" << object << "] - Type " << vk::to_string(callbackData.pObjects[object].objectType) << ", Handle " << std::hex << std::showbase << callbackData.pObjects[object].objectHandle << std::dec << ", Name \"" << name << "\"\n"; } } if (callbackData.cmdBufLabelCount > 0) { std::cerr << "\n\tCommand Buffer Labels - " << callbackData.cmdBufLabelCount << "\n"; for (size_t label = 0; label < callbackData.cmdBufLabelCount; label++) { std::cerr << "\t\tLabel[" << label << "] - " << callbackData.pCmdBufLabels[label].pLabelName << " { " << callbackData.pCmdBufLabels[label].color[0] << ", " << callbackData.pCmdBufLabels[label].color[1] << ", " << callbackData.pCmdBufLabels[label].color[2] << ", " << callbackData.pCmdBufLabels[label].color[3] << " }\n\n"; } } std::cerr << std::endl; return VK_FALSE; } } bool QueueFamilyIndices::isComplete() const { return generalFamily >= 0 && computeFamily >= 0; } bool QueueFamilyIndices::isSingleQueue() const { return generalFamily == computeFamily; } QueueFamilyIndices QueueFamilyIndices::findQueueFamilies(vk::PhysicalDevice device, vk::SurfaceKHR surface) { QueueFamilyIndices indices; auto queueFamilies = device.getQueueFamilyProperties(); // try to find queue for compute, graphics and present - standard says that there should be 1 universal queue on every device auto flag = vk::QueueFlagBits::eGraphics | vk::QueueFlagBits::eCompute; for (int i = 0; i < static_cast<int>(queueFamilies.size()) && indices.generalFamily < 0; i++) if (queueFamilies[i].queueFlags & flag && device.getSurfaceSupportKHR(static_cast<uint32_t>(i), surface)) indices.generalFamily = i; // try to pick async for (int i = 0; i < static_cast<int>(queueFamilies.size()); i++) { if (queueFamilies[i].queueFlags & vk::QueueFlagBits::eCompute) { const auto lastQueue = indices.computeFamily; indices.computeFamily = i; if (i != indices.generalFamily) { indices.computeQueueIndex = 0; break; } if (queueFamilies[i].queueCount > 1) indices.computeQueueIndex = 1; else if (indices.computeQueueIndex == 1) // try to pick another queue in family, which could be async too indices.computeFamily = lastQueue; } } if (!indices.isComplete()) throw std::runtime_error("Failed to pick appropriate queue families"); return indices; } Context::Context(GLFWwindow* window) : mWindow(window) { if (!window) throw std::runtime_error("Invalid window"); createInstance(); setupDebugCallback(); createWindowSurface(); pickPhysicalDevice(); findQueueFamilyIndices(); createLogicalDevice(); createCommandPools(); } void Context::createInstance() { #ifdef ENABLE_VALIDATION_LAYERS auto availableLayers = vk::enumerateInstanceLayerProperties(); for (const char* layerName : VALIDATION_LAYERS) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) throw std::runtime_error("Validation layer not found"); } #endif vk::ApplicationInfo appInfo; appInfo.pApplicationName = "Vulkan Hello World"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "No Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_1; vk::InstanceCreateInfo instanceInfo; instanceInfo.pApplicationInfo = &appInfo; // Getting Vulkan instance extensions required by GLFW std::vector<const char*> extensions; unsigned int glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); for (unsigned int i = 0; i < glfwExtensionCount; i++) extensions.push_back(glfwExtensions[i]); #ifdef ENABLE_VALIDATION_LAYERS extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); #endif // Getting Vulkan supported extensions std::unordered_set<std::string> supportedExtensionNames; for (const auto& extension : vk::enumerateInstanceExtensionProperties()) supportedExtensionNames.insert(std::string(extension.extensionName)); // Check for and print any unsupported extension for (const auto& eName : extensions) if (supportedExtensionNames.count(eName) <= 0) std::cerr << "Unsupported extension required by GLFW: " << eName << std::endl; // Enable required extensions instanceInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); instanceInfo.ppEnabledExtensionNames = extensions.data(); #ifdef ENABLE_VALIDATION_LAYERS instanceInfo.enabledLayerCount = static_cast<uint32_t>(VALIDATION_LAYERS.size()); instanceInfo.ppEnabledLayerNames = VALIDATION_LAYERS.data(); #endif mInstance = createInstanceUnique(instanceInfo); } void Context::setupDebugCallback() { #ifdef ENABLE_VALIDATION_LAYERS vk::DebugUtilsMessengerCreateInfoEXT createInfo; createInfo.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError; createInfo.messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance; createInfo.pfnUserCallback = debugCallback; static auto dldi = vk::DispatchLoaderDynamic(*mInstance, reinterpret_cast<PFN_vkGetInstanceProcAddr>(mInstance->getProcAddr("vkGetInstanceProcAddr"))); mMessenger = mInstance->createDebugUtilsMessengerEXTUnique(createInfo, nullptr, dldi); #endif } void Context::createWindowSurface() { VkSurfaceKHR surface; if (auto result = glfwCreateWindowSurface(*mInstance, mWindow, nullptr, &surface); result != VK_SUCCESS) throw std::runtime_error("Failed to create window surface"); mSurface = vk::UniqueSurfaceKHR(surface, vk::ObjectDestroy<vk::Instance, vk::DispatchLoaderStatic>(*mInstance)); } void Context::pickPhysicalDevice() { auto devices = mInstance->enumeratePhysicalDevices(); if (devices.empty()) throw std::runtime_error("Failed to find GPUs with Vulkan support"); for (const auto& device : devices) { if (isDeviceSuitable(device, *mSurface)) { mPhysicalDevice = device; break; } } if (!mPhysicalDevice) throw std::runtime_error("Failed to find a suitable GPU!"); #ifndef NDEBUG std::cout << "Current Device: " << mPhysicalDevice.getProperties().deviceName << std::endl; #endif // NDEBUG //mPhyisicalDeviceProperties = static_cast<vk::PhysicalDevice>(physicalDevice).getProperties(); } void Context::findQueueFamilyIndices() { mQueueFamilyIndices = QueueFamilyIndices::findQueueFamilies(mPhysicalDevice, *mSurface); if (!mQueueFamilyIndices.isComplete()) throw std::runtime_error("Queue family indices is not complete"); } void Context::createLogicalDevice() { std::vector<vk::DeviceQueueCreateInfo> queueInfo; std::vector<int> queueFamilies; std::vector<std::vector<float>> queuePriorities; if (mQueueFamilyIndices.isSingleQueue()) { queueFamilies.emplace_back(mQueueFamilyIndices.generalFamily); if (mQueueFamilyIndices.computeQueueIndex > 0) queuePriorities.emplace_back(std::vector<float>{1.0f, 1.0f}); else queuePriorities.emplace_back(std::vector<float>{1.0f}); } else { queueFamilies.emplace_back(mQueueFamilyIndices.generalFamily); queuePriorities.emplace_back(std::vector<float>{1.0f}); queueFamilies.emplace_back(mQueueFamilyIndices.computeFamily); queuePriorities.emplace_back(std::vector<float>{1.0f}); } for (size_t i = 0; i < queueFamilies.size(); i++) { vk::DeviceQueueCreateInfo info; info.queueFamilyIndex = queueFamilies[i]; info.queueCount = static_cast<uint32_t>(queuePriorities[i].size()); info.pQueuePriorities = queuePriorities[i].data(); queueInfo.emplace_back(info); } vk::PhysicalDeviceFeatures deviceFeatures; deviceFeatures.samplerAnisotropy = VK_TRUE; deviceFeatures.fragmentStoresAndAtomics = VK_TRUE; // Create the logical device vk::DeviceCreateInfo deviceInfo; deviceInfo.pQueueCreateInfos = queueInfo.data(); deviceInfo.queueCreateInfoCount = static_cast<uint32_t>(queueInfo.size()); deviceInfo.pEnabledFeatures = &deviceFeatures; #ifdef ENABLE_VALIDATION_LAYERS deviceInfo.enabledLayerCount = static_cast<uint32_t>(VALIDATION_LAYERS.size()); deviceInfo.ppEnabledLayerNames = VALIDATION_LAYERS.data(); #endif deviceInfo.enabledExtensionCount = static_cast<uint32_t>(DEVICE_EXTENSIONS.size()); deviceInfo.ppEnabledExtensionNames = DEVICE_EXTENSIONS.data(); mDevice = mPhysicalDevice.createDeviceUnique(deviceInfo); mGeneralQueue = mDevice->getQueue(mQueueFamilyIndices.generalFamily, 0); mComputeQueue = mDevice->getQueue(mQueueFamilyIndices.computeFamily, mQueueFamilyIndices.computeQueueIndex); } void Context::createCommandPools() { vk::CommandPoolCreateInfo poolInfo; poolInfo.queueFamilyIndex = mQueueFamilyIndices.generalFamily; poolInfo.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer; mStaticCommandPool = mDevice->createCommandPoolUnique(poolInfo); poolInfo.flags |= vk::CommandPoolCreateFlagBits::eTransient; mDynamicCommandPool = mDevice->createCommandPoolUnique(poolInfo); poolInfo.queueFamilyIndex = mQueueFamilyIndices.computeFamily; mComputeCommandPool = mDevice->createCommandPoolUnique(poolInfo); }
31.29397
178
0.749659
[ "object", "vector" ]
80d567c9e34ed4128c70aaf87e798c12110acd92
15,537
cpp
C++
libraries/fc/src/network/http/http_connection.cpp
hbchain/hbcore
649c67d91cf950e0fc4102a6e0ea82e5f7abd17f
[ "MIT" ]
2
2020-07-22T02:08:49.000Z
2020-12-04T08:20:40.000Z
libraries/fc/src/network/http/http_connection.cpp
hbchain/hbcore
649c67d91cf950e0fc4102a6e0ea82e5f7abd17f
[ "MIT" ]
null
null
null
libraries/fc/src/network/http/http_connection.cpp
hbchain/hbcore
649c67d91cf950e0fc4102a6e0ea82e5f7abd17f
[ "MIT" ]
1
2020-12-01T07:50:29.000Z
2020-12-01T07:50:29.000Z
#include <fc/network/http/connection.hpp> #include <fc/network/tcp_socket.hpp> #include <fc/io/sstream.hpp> #include <fc/io/iostream.hpp> #include <fc/exception/exception.hpp> #include <fc/network/ip.hpp> #include <fc/crypto/hex.hpp> #include <fc/log/logger.hpp> #include <fc/io/stdio.hpp> #include <fc/network/url.hpp> #include <boost/algorithm/string.hpp> #include <fc/asio.hpp> #include <iostream> #include <boost/shared_ptr.hpp> class fc::http::connection::impl { public: fc::tcp_socket sock; fc::ip::endpoint ep; impl() { } int read_until(char* buffer, char* end, char c = '\n') { char* p = buffer; // try { while (p < end && 1 == sock.readsome(p, 1)) { if (*p == c) { *p = '\0'; return (p - buffer) - 1; } ++p; } // } catch ( ... ) { // elog("%s", fc::current_exception().diagnostic_information().c_str() ); //elog( "%s", fc::except_str().c_str() ); // } return (p - buffer); } fc::http::reply parse_reply() { fc::http::reply rep; try { std::vector<char> line(1024 * 8); int s = read_until(line.data(), line.data() + line.size(), ' '); // HTTP/1.1 s = read_until(line.data(), line.data() + line.size(), ' '); // CODE rep.status = static_cast<int>(to_int64(fc::string(line.data()))); s = read_until(line.data(), line.data() + line.size(), '\n'); // DESCRIPTION while ((s = read_until(line.data(), line.data() + line.size(), '\n')) > 1) { fc::http::header h; char* end = line.data(); while (*end != ':')++end; h.key = fc::string(line.data(), end); ++end; // skip ':' ++end; // skip space char* skey = end; while (*end != '\r') ++end; h.val = fc::string(skey, end); rep.headers.push_back(h); if (boost::iequals(h.key, "Content-Length")) { rep.body.resize(static_cast<size_t>(to_uint64(fc::string(h.val)))); } } if (rep.body.size()) { sock.read(rep.body.data(), rep.body.size()); } return rep; } catch (fc::exception& e) { elog("${exception}", ("exception", e.to_detail_string())); sock.close(); rep.status = http::reply::InternalServerError; return rep; } } }; namespace fc { namespace http { connection::connection() :my(new connection::impl()) {} connection::~connection() {} // used for clients void connection::connect_to(const fc::ip::endpoint& ep) { my->sock.close(); my->sock.connect_to(my->ep = ep); } http::reply connection::request(const fc::string& method, const fc::string& url, const fc::string& body, const headers& he) { fc::url parsed_url(url); if (!my->sock.is_open()) { wlog("Re-open socket!"); my->sock.connect_to(my->ep); } try { fc::stringstream req; req << method << " " << parsed_url.path()->generic_string() << " HTTP/1.1\r\n"; req << "Host: " << *parsed_url.host() << "\r\n"; req << "Content-Type: application/json\r\n"; for (auto i = he.begin(); i != he.end(); ++i) { req << i->key << ": " << i->val << "\r\n"; } if (body.size()) req << "Content-Length: " << body.size() << "\r\n"; req << "\r\n"; fc::string head = req.str(); my->sock.write(head.c_str(), head.size()); // fc::cerr.write( head.c_str() ); if (body.size()) { my->sock.write(body.c_str(), body.size()); // fc::cerr.write( body.c_str() ); } // fc::cerr.flush(); return my->parse_reply(); } catch (...) { my->sock.close(); FC_THROW_EXCEPTION(exception, "Error Sending HTTP Request"); // TODO: provide more info // return http::reply( http::reply::InternalServerError ); // TODO: replace with connection error } } // used for servers fc::tcp_socket& connection::get_socket()const { return my->sock; } http::request connection::read_request()const { http::request req; req.remote_endpoint = fc::variant(get_socket().remote_endpoint()).as_string(); std::vector<char> line(1024 * 8); int s = my->read_until(line.data(), line.data() + line.size(), ' '); // METHOD req.method = line.data(); s = my->read_until(line.data(), line.data() + line.size(), ' '); // PATH req.path = line.data(); s = my->read_until(line.data(), line.data() + line.size(), '\n'); // HTTP/1.0 while ((s = my->read_until(line.data(), line.data() + line.size(), '\n')) > 1) { fc::http::header h; char* end = line.data(); while (*end != ':')++end; h.key = fc::string(line.data(), end); ++end; // skip ':' ++end; // skip space char* skey = end; while (*end != '\r') ++end; h.val = fc::string(skey, end); req.headers.push_back(h); if (boost::iequals(h.key, "Content-Length")) { auto s = static_cast<size_t>(to_uint64(fc::string(h.val))); FC_ASSERT(s < 1024 * 1024); req.body.resize(static_cast<size_t>(to_uint64(fc::string(h.val)))); } if (boost::iequals(h.key, "Host")) { req.domain = h.val; } } // TODO: some common servers won't give a Content-Length, they'll use // Transfer-Encoding: chunked. handle that here. if (req.body.size()) { my->sock.read(req.body.data(), req.body.size()); } return req; } fc::string request::get_header(const fc::string& key)const { for (auto itr = headers.begin(); itr != headers.end(); ++itr) { if (boost::iequals(itr->key, key)) { return itr->val; } } return fc::string(); } std::vector<header> parse_urlencoded_params(const fc::string& f) { int num_args = 0; for (size_t i = 0; i < f.size(); ++i) { if (f[i] == '=') ++num_args; } std::vector<header> h(num_args); int arg = 0; for (size_t i = 0; i < f.size(); ++i) { while (f[i] != '=' && i < f.size()) { if (f[i] == '%') { h[arg].key += char((fc::from_hex(f[i + 1]) << 4) | fc::from_hex(f[i + 2])); i += 3; } else { h[arg].key += f[i]; ++i; } } ++i; while (i < f.size() && f[i] != '&') { if (f[i] == '%') { h[arg].val += char((fc::from_hex(f[i + 1]) << 4) | fc::from_hex(f[i + 2])); i += 3; } else { h[arg].val += f[i] == '+' ? ' ' : f[i]; ++i; } } ++arg; } return h; } connection_sync::connection_sync() : _socket(fc::asio::default_io_service()), _deadline(fc::asio::default_io_service()) { } connection_sync::~connection_sync() { close_socket(); } int connection_sync::connect_to_servers(const std::vector<fc::ip::endpoint>& eps, std::vector<int>& res) { int ep_count = eps.size(); res.resize(ep_count,0); for (int i = 0; i < ep_count; i++) { try { auto& ep = eps[i]; boost::asio::ip::tcp::endpoint p(boost::asio::ip::address_v4(ep.get_address()), ep.port()); _socket.close(); _socket.connect(p); return i; } catch (...) { res[i]++; } } FC_THROW_EXCEPTION(exception, "Error Connecting HTTP Server."); } void connection_sync::connect_to(const fc::ip::endpoint& ep) { for (int i = 0; i < 3; i++) { try { boost::asio::ip::tcp::endpoint p(boost::asio::ip::address_v4(ep.get_address()), ep.port()); _socket.close(); _socket.connect(p); return; } catch (...) { std::cout << "retry connection to" << std::endl; } } try { boost::asio::ip::tcp::endpoint p(boost::asio::ip::address_v4(ep.get_address()), ep.port()); _socket.close(); _socket.connect(p); } catch (fc::exception& e) { FC_THROW_EXCEPTION(exception, "Error Connecting HTTP Server."); } } void connection_sync::handle_reply(const boost::system::error_code & error) { if (error&&error.value() != 2) { std::cout << "handle_reply error" << error.value() << error.message() << std::endl; return; } std::lock_guard<std::mutex> lk(read_lock); if (is_timeout) return; if (is_release) return; //is_timeout = false; is_done = true; if (!is_release) { is_release = true; _deadline.get_io_service().dispatch([&]() { try { _deadline.cancel(); } catch (...) {} }); } m_cond.notify_all(); } void connection_sync::handle_reply(const boost::system::error_code & error, size_t bytes_transferred) { if (error) { std::cout << "handle_reply error" << error.message() << std::endl; return; } std::lock_guard<std::mutex> lk(read_lock); if (is_timeout) return; //is_timeout = false; //std::cout << error.message() << " " << bytes_transferred << std::endl; is_done = true; if (!is_release) { is_release = true; _deadline.get_io_service().dispatch([&]() { try { _deadline.cancel(); } catch (...) {} }); } m_cond.notify_all(); } http::reply connection_sync::request(const fc::string& method, const fc::string& url, const fc::string& body, const headers& he) { try { fc::url parsed_url(url); fc::stringstream req; req << method << " " << parsed_url.path()->generic_string() << " HTTP/1.1\r\n"; req << "Host: " << *parsed_url.host() << "\r\n"; req << "Content-Type: application/json\r\n"; req << "Accept: */*\r\n"; for (auto i = he.begin(); i != he.end(); ++i) { req << i->key << ": " << i->val << "\r\n"; } boost::system::error_code ec; if (body.size()) req << "Content-Length: " << body.size() << "\r\n"; req << "\r\n"; fc::string head = req.str(); _socket.write_some(boost::asio::buffer(head), ec); // fc::cerr.write( head.c_str() ); if (body.size()) { _socket.write_some(boost::asio::buffer(body), ec); // fc::cerr.write( body.c_str() ); } // fc::cerr.flush(); const auto& ret = parse_reply(); return ret; //return parse_reply(); } catch (...) { FC_THROW_EXCEPTION(exception, "Error Sending HTTP Request"); // TODO: provide more info } } void connection_sync::close_socket() { is_release = true; try { _socket.cancel(); } catch (...) { } try { _socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both); } catch (...) { } try { _socket.close(); } catch (...) { } } void connection_sync::check_deadline(const boost::system::error_code & error) { if (error) { //std::cout << "check_deadline error" << error.value() << " " << error.message() << std::endl; return; } if (is_timeout || is_done || is_release) { return; } if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now()) { std::lock_guard<std::mutex> lk(read_lock); if (is_timeout || is_done || is_release) { return; } close_socket(); boost::this_thread::sleep(boost::posix_time::seconds(3)); is_timeout = true; //close_socket(); m_cond.notify_all(); } } http::reply connection_sync::parse_reply() { fc::http::reply rep; try { { std::unique_lock<std::mutex> lk(read_lock); _deadline.expires_from_now(boost::posix_time::seconds(50)); _deadline.async_wait(boost::bind(&connection_sync::check_deadline, this, boost::asio::placeholders::error)); boost::asio::async_read_until(_socket, line, "\r\n\r\n", boost::bind(&connection_sync::handle_reply, this, boost::asio::placeholders::error)); while (!(is_done || is_timeout)) { auto now = std::chrono::system_clock::now(); m_cond.wait_until(lk, now+ std::chrono::seconds(2)); //m_cond.wait(lk); } if (is_timeout) { std::cout << "query timeout1" << std::endl; rep.status = reply::status_code::InternalServerError; return rep; } } is_release = false; is_done = false; is_timeout = false; //line.consume(s); //s = boost::asio::read_until(_socket, line, ' '); // COD std::istream response_stream(&line); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); rep.status = status_code; std::string head; uint64_t content_length = 0; while (std::getline(response_stream, head) && head != "\r") { auto pos = head.find(':'); string key; key.assign(head.c_str(), pos); string val; val.assign(head.c_str(), pos + 1, std::string::npos); val.erase(0, val.find_first_not_of(" ")); val.erase(val.find_last_not_of("\r") + 1); header h(key, val); if (boost::iequals(h.key, "Content-Length")) { rep.body.resize(static_cast<size_t>(to_uint64(fc::string(h.val)))); content_length = to_uint64(fc::string(h.val)); } ///rep.headers.push_back(); rep.headers.push_back(h); } content_length -= line.size(); boost::system::error_code error; { std::unique_lock<std::mutex> lk(read_lock); if (content_length > 0) { _deadline.expires_from_now(boost::posix_time::seconds(50)); _deadline.async_wait(boost::bind(&connection_sync::check_deadline, this, boost::asio::placeholders::error)); boost::asio::async_read(_socket, line, boost::asio::transfer_at_least(content_length), boost::bind(&connection_sync::handle_reply, this, boost::asio::placeholders::error)); //, boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred } while (!(is_done || is_timeout) && content_length>0) { auto now = std::chrono::system_clock::now(); m_cond.wait_until(lk, now + std::chrono::seconds(2)); } if (is_timeout) { rep.status = reply::status_code::InternalServerError; return rep; } if (line.size()) { std::istream response_stream1(&line); std::istreambuf_iterator<char> eos; auto reponse_data = string(std::istreambuf_iterator<char>(response_stream1), eos); rep.body.assign(reponse_data.begin(), reponse_data.end()); } } return rep; /* //response_stream>> status ; line.consume(s); rep.status = static_cast<int>(to_int64("200")); std::cout << rep.status << std::endl; s = boost::asio::read_until(_socket, line, '\n'); // DESCRIPTION line.consume(s); while ((s = boost::asio::read_until(_socket, line, '\n')) > 1) { fc::http::header h; string line_str; std::istream line_stream(&line); line_stream >> line_str; std::cout << line_str << std::endl; line.consume(s); const char* begin = line_str.c_str(); const char* end = begin; while (*end != ':')++end; h.key = fc::string(begin, end); ++end; // skip ':' ++end; // skip space const char* skey = end; while (*end != '\r') ++end; h.val = fc::string(skey, end); rep.headers.push_back(h); if (boost::iequals(h.key, "Content-Length")) { rep.body.resize(static_cast<size_t>(to_uint64(fc::string(h.val)))); } } if (rep.body.size()) { //sock.read(rep.body.data(), rep.body.size()); _socket.read_some(boost::asio::buffer( rep.body.data(), rep.body.size())); } return rep; */ } catch (std::exception& ex) { std::cout << ex.what() << std::endl; } catch (fc::exception& e) { elog("${exception}", ("exception", e.to_detail_string())); } is_done = true; is_timeout = true; if (!is_release) { is_release = true; _deadline.get_io_service().dispatch([&]() {try { _deadline.cancel(); } catch (...) {} }); } rep.status = http::reply::InternalServerError; std::lock_guard<std::mutex> lk_end2(read_lock); return rep; } } // fc::http }
27.645907
178
0.57598
[ "vector" ]
80d58067ca97085cad3abfbaf6eafb3d9eaba76f
334
cpp
C++
vectors.c++.cpp
Prachimandavee/Hactoberfest2020
0de395fa976723949f2ed20e290a679bede26b3d
[ "MIT" ]
null
null
null
vectors.c++.cpp
Prachimandavee/Hactoberfest2020
0de395fa976723949f2ed20e290a679bede26b3d
[ "MIT" ]
null
null
null
vectors.c++.cpp
Prachimandavee/Hactoberfest2020
0de395fa976723949f2ed20e290a679bede26b3d
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec; while(1) { int a; cout<< "enter the number which is not negative "; cin >> a; if(a<0) { break; } vec.push_back(a); } for(int i=0;i<vec.size();i++) { cout<<vec[i]<<endl; } return 0; }
11.517241
54
0.51497
[ "vector" ]
80de8d1325d39debc556c3e08c38ac183ddea38a
4,369
cpp
C++
examples/multiple_buttons/main.cpp
mscofield0/cui-sfml
f70dfdf977958eb2b37162d474873c75df4dadc5
[ "MIT" ]
null
null
null
examples/multiple_buttons/main.cpp
mscofield0/cui-sfml
f70dfdf977958eb2b37162d474873c75df4dadc5
[ "MIT" ]
null
null
null
examples/multiple_buttons/main.cpp
mscofield0/cui-sfml
f70dfdf977958eb2b37162d474873c75df4dadc5
[ "MIT" ]
null
null
null
#include <any> #include <iostream> #include <print_stuff.hpp> #include <random> #include <string> #include <type_traits> #include <utility> #include <cui/compile_time/scene.hpp> #include <cui/compile_time/scenes/parse_scenes.hpp> #include <cui/compile_time/style.hpp> #include <cui/compile_time/styles/parse_styles.hpp> #include <cui/compile_time/value_data.hpp> #include <cui/utils/print.hpp> #include <cui/visual/node.hpp> #include <cui/visual/scene_graph.hpp> #include <cursors.hpp> #include <detail/intermediaries/color.hpp> #include <detail/templates/on_click.hpp> #include <detail/templates/on_resize.hpp> #include <detail/templates/switch_schematic.hpp> #include <visual_element.hpp> #include <window.hpp> #include <window_options.hpp> #define STATIC_STRING_HOLDER(name) static constexpr const char name[] = #define END_STATIC_STRING_HOLDER ; int main() { using namespace cui; STATIC_STRING_HOLDER(style__) #include "file.styles" END_STATIC_STRING_HOLDER STATIC_STRING_HOLDER(scene__) #include "file.scene" END_STATIC_STRING_HOLDER // Typedefs for easy use using win_t = Window; using node_t = Node; using event_data_t = EventData<node_t>; std::unique_ptr<win_t> window; // Create a scope so it destructs at the end { // Parse the .scene file constexpr auto scenes_variant = ct::scenes::parse_scenes<scene__>(); // Handle if error if constexpr (scenes_variant.is_type_b()) { println(scenes_variant.type_b()); return 0; } // Parse the .styles file constexpr auto styles_variant = ct::styles::parse_styles<style__>(); // Handle if error if constexpr (styles_variant.is_type_b()) { println(styles_variant.type_b()); return 0; } // Populate the Window with the parsed data else { std::vector<ct::Style> sty; sty.reserve(styles_variant.type_a().size()); for (const auto& el : styles_variant.type_a()) { const auto parsed_variant = ct::Style::create(el); if (parsed_variant.is_type_b()) { println(parsed_variant.type_b()); return 0; } const auto& parsed = parsed_variant.type_a(); sty.push_back(parsed); } // Create the Window window = std::make_unique<win_t>(std::move(sty), std::move(scenes_variant.type_a())); } } // Create a typedef for the event types using EventType = sf::Event::EventType; // Register the on_close event [OBLIGATORY, otherwise you cannot close via conventional methods] window->register_global_event(EventType::Closed, "on_close", [&window](auto event_data) { window->close(); }); // Register the on_resize event [OPTIONAL, but a resize event is one of the events that should update the scene graph] window->register_global_event(EventType::Resized, "on_resize", [&window](auto event_data) { templates::OnResize((*window), event_data); }); // Get the text_box node auto& graph = window->active_scene().graph(); auto text_box = std::find_if(graph.begin(), graph.end(), [](const auto& node) { return node.data().name() == "text_box"; }); // Register the on_click_btn event [OPTIONAL, defines functionality on button click] window->register_event(EventType::MouseButtonPressed, "on_click_btn", [&window, &text_box](event_data_t event_data) { // Uses CUI's GUI helper template `OnClick` to provide functionality on click templates::OnClick((*window), event_data, [&text_box](Window& window, event_data_t& event_data) { constexpr cui::Color colors[] = {cui::Color(255, 0, 0), cui::Color(0, 255, 0), cui::Color(0, 0, 255)}; constexpr cui::ct::StringView texts[] = {"Red text", "Green text", "Blue text"}; auto& graph = window.active_scene().graph(); auto& scheme = text_box->data().active_schematic().get(); // Get the last char of the node name indicating the id const auto id = event_data.caller()->name().back() - '0' - 1; // Set the text_box color and text scheme.text_color() = colors[id]; text_box->data().text() = texts[id].data(); // Schedule the render cache to be updated window.schedule_to_update_cache(); }); }); // Attaches the registered event `on_click_btn` to the button nodes window->attach_event_to_node("button1", "on_click_btn"); window->attach_event_to_node("button2", "on_click_btn"); window->attach_event_to_node("button3", "on_click_btn"); // Initialize the window window->init({800, 600, "Title", sf::Style::Default, sf::ContextSettings{}, 60}); }
34.952
140
0.719158
[ "render", "vector" ]
80dea87699836e251958aaaa26ee720a1315cf7e
129,752
cpp
C++
src/modules/processes/ImageIntegration/ImageIntegrationInterface.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/ImageIntegration/ImageIntegrationInterface.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
src/modules/processes/ImageIntegration/ImageIntegrationInterface.cpp
fmeschia/pixinsight-class-library
11b956e27d6eee3e119a7b1c337d090d7a03f436
[ "JasPer-2.0", "libtiff" ]
null
null
null
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 2.4.9 // ---------------------------------------------------------------------------- // Standard ImageIntegration Process Module Version 1.2.33 // ---------------------------------------------------------------------------- // ImageIntegrationInterface.cpp - Released 2021-04-09T19:41:48Z // ---------------------------------------------------------------------------- // This file is part of the standard ImageIntegration PixInsight module. // // Copyright (c) 2003-2021 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (https://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ---------------------------------------------------------------------------- #include "ImageIntegrationInterface.h" #include "ImageIntegrationProcess.h" #include "IntegrationCache.h" #include <pcl/DrizzleData.h> #include <pcl/FileDataCachePreferencesDialog.h> #include <pcl/FileDialog.h> #include <pcl/FileFormat.h> #include <pcl/LocalNormalizationData.h> #include <pcl/MessageBox.h> #include <pcl/PreviewSelectionDialog.h> #define IMAGELIST_MINHEIGHT( fnt ) RoundInt( 8.125*fnt.Height() ) namespace pcl { // ---------------------------------------------------------------------------- ImageIntegrationInterface* TheImageIntegrationInterface = nullptr; // ---------------------------------------------------------------------------- ImageIntegrationInterface::ImageIntegrationInterface() : m_instance( TheImageIntegrationProcess ) { TheImageIntegrationInterface = this; /* * The auto save geometry feature is of no good to interfaces that include * both auto-expanding controls (e.g. TreeBox) and collapsible sections * (e.g. SectionBar). */ DisableAutoSaveGeometry(); } // ---------------------------------------------------------------------------- ImageIntegrationInterface::~ImageIntegrationInterface() { if ( GUI != nullptr ) delete GUI, GUI = nullptr; } // ---------------------------------------------------------------------------- IsoString ImageIntegrationInterface::Id() const { return "ImageIntegration"; } // ---------------------------------------------------------------------------- MetaProcess* ImageIntegrationInterface::Process() const { return TheImageIntegrationProcess; } // ---------------------------------------------------------------------------- String ImageIntegrationInterface::IconImageSVGFile() const { return "@module_icons_dir/ImageIntegration.svg"; } // ---------------------------------------------------------------------------- InterfaceFeatures ImageIntegrationInterface::Features() const { return InterfaceFeature::DefaultGlobal | InterfaceFeature::PreferencesButton; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::EditPreferences() { if ( TheIntegrationCache == nullptr ) new IntegrationCache; // loads upon construction FileDataCachePreferencesDialog dlg( TheIntegrationCache ); dlg.Execute(); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::ResetInstance() { ImageIntegrationInstance defaultInstance( TheImageIntegrationProcess ); ImportProcess( defaultInstance ); } // ---------------------------------------------------------------------------- bool ImageIntegrationInterface::Launch( const MetaProcess& P, const ProcessImplementation*, bool& dynamic, unsigned& /*flags*/ ) { if ( GUI == nullptr ) { GUI = new GUIData( *this ); SetWindowTitle( "ImageIntegration" ); UpdateControls(); // Restore position only if ( !RestoreGeometry() ) SetDefaultPosition(); AdjustToContents(); } dynamic = false; return &P == TheImageIntegrationProcess; } // ---------------------------------------------------------------------------- ProcessImplementation* ImageIntegrationInterface::NewProcess() const { return new ImageIntegrationInstance( m_instance ); } // ---------------------------------------------------------------------------- bool ImageIntegrationInterface::ValidateProcess( const ProcessImplementation& p, pcl::String& whyNot ) const { if ( dynamic_cast<const ImageIntegrationInstance*>( &p ) != nullptr ) return true; whyNot = "Not an ImageIntegration instance."; return false; } // ---------------------------------------------------------------------------- bool ImageIntegrationInterface::RequiresInstanceValidation() const { return true; } // ---------------------------------------------------------------------------- bool ImageIntegrationInterface::ImportProcess( const ProcessImplementation& p ) { m_instance.Assign( p ); UpdateControls(); return true; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::SaveSettings() const { SaveGeometry(); } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateControls() { UpdateInputImagesList(); UpdateImageSelectionButtons(); UpdateFormatHintsControls(); UpdateIntegrationControls(); UpdateRejectionControls(); UpdateROIControls(); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateInputImagesItem( size_type i ) { TreeBox::Node* node = GUI->InputImages_TreeBox[i]; if ( node == nullptr ) return; const ImageIntegrationInstance::ImageItem& item = m_instance.p_images[i]; node->SetText( 0, String( i+1 ) ); node->SetAlignment( 0, TextAlign::Right ); node->SetIcon( 1, ScaledResource( item.enabled ? ":/browser/enabled.png" : ":/browser/disabled.png" ) ); node->SetAlignment( 1, TextAlign::Left ); String fileText; if ( !item.nmlPath.IsEmpty() ) fileText << "<n> "; if ( !item.drzPath.IsEmpty() ) fileText << "<d> "; if ( GUI->FullPaths_CheckBox.IsChecked() ) fileText << item.path; else fileText << File::ExtractNameAndSuffix( item.path ); node->SetText( 2, fileText ); node->SetAlignment( 2, TextAlign::Left ); String toolTip = item.path; if ( !item.nmlPath.IsEmpty() ) toolTip << '\n' << item.nmlPath; if ( !item.drzPath.IsEmpty() ) toolTip << '\n' << item.drzPath; node->SetToolTip( 2, toolTip ); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateInputImagesList() { int currentIdx = GUI->InputImages_TreeBox.ChildIndex( GUI->InputImages_TreeBox.CurrentNode() ); GUI->InputImages_TreeBox.DisableUpdates(); GUI->InputImages_TreeBox.Clear(); for ( size_type i = 0; i < m_instance.p_images.Length(); ++i ) { new TreeBox::Node( GUI->InputImages_TreeBox ); UpdateInputImagesItem( i ); } GUI->InputImages_TreeBox.AdjustColumnWidthToContents( 0 ); GUI->InputImages_TreeBox.AdjustColumnWidthToContents( 1 ); GUI->InputImages_TreeBox.AdjustColumnWidthToContents( 2 ); if ( !m_instance.p_images.IsEmpty() ) if ( currentIdx >= 0 && currentIdx < GUI->InputImages_TreeBox.NumberOfChildren() ) GUI->InputImages_TreeBox.SetCurrentNode( GUI->InputImages_TreeBox[currentIdx] ); GUI->InputImages_TreeBox.EnableUpdates(); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateImageSelectionButtons() { bool hasItems = GUI->InputImages_TreeBox.NumberOfChildren() > 0; bool hasSelection = hasItems && GUI->InputImages_TreeBox.HasSelectedTopLevelNodes(); GUI->AddDrizzleFiles_PushButton.Enable( hasItems ); GUI->ClearDrizzleFiles_PushButton.Enable( hasItems ); GUI->AddLocalNormalizationFiles_PushButton.Enable( hasItems ); GUI->ClearLocalNormalizationFiles_PushButton.Enable( hasItems ); GUI->SetReference_PushButton.Enable( GUI->InputImages_TreeBox.CurrentNode() != 0 ); GUI->SelectAll_PushButton.Enable( hasItems ); GUI->InvertSelection_PushButton.Enable( hasItems ); GUI->ToggleSelected_PushButton.Enable( hasSelection ); GUI->RemoveSelected_PushButton.Enable( hasSelection ); GUI->Clear_PushButton.Enable( hasItems ); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateFormatHintsControls() { GUI->InputHints_Edit.SetText( m_instance.p_inputHints ); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateIntegrationControls() { bool isAverage = m_instance.p_generateIntegratedImage && m_instance.p_combination == IICombination::Average; bool isKeywordWeight = m_instance.p_weightMode == IIWeightMode::KeywordWeight; GUI->Combination_Label.Enable( m_instance.p_generateIntegratedImage ); GUI->Combination_ComboBox.SetCurrentItem( m_instance.p_combination ); GUI->Combination_ComboBox.Enable( m_instance.p_generateIntegratedImage ); GUI->Normalization_ComboBox.SetCurrentItem( m_instance.p_normalization ); GUI->AdaptiveGridSize_SpinBox.SetValue( m_instance.p_adaptiveGridSize ); GUI->AdaptiveNoScale_CheckBox.SetChecked( m_instance.p_adaptiveNoScale ); GUI->WeightMode_Label.Enable( isAverage ); GUI->WeightMode_ComboBox.Enable( isAverage ); GUI->WeightMode_ComboBox.SetCurrentItem( m_instance.p_weightMode ); GUI->WeightKeyword_Label.Enable( isAverage && isKeywordWeight ); GUI->WeightScale_ComboBox.Enable( isAverage ); GUI->WeightScale_ComboBox.SetCurrentItem( m_instance.p_weightScale ); GUI->WeightKeyword_Edit.Enable( isAverage && isKeywordWeight ); GUI->WeightKeyword_Edit.SetText( m_instance.p_weightKeyword ); GUI->IgnoreNoiseKeywords_CheckBox.SetChecked( m_instance.p_ignoreNoiseKeywords ); GUI->GenerateIntegratedImage_CheckBox.SetChecked( m_instance.p_generateIntegratedImage ); GUI->Generate64BitResult_CheckBox.SetChecked( m_instance.p_generate64BitResult ); GUI->Generate64BitResult_CheckBox.Enable( m_instance.p_generateIntegratedImage ); GUI->GenerateDrizzleData_CheckBox.SetChecked( m_instance.p_generateDrizzleData ); GUI->SubtractPedestals_CheckBox.SetChecked( m_instance.p_subtractPedestals ); GUI->TruncateOnOutOfRange_CheckBox.SetChecked( m_instance.p_truncateOnOutOfRange ); GUI->TruncateOnOutOfRange_CheckBox.Enable( m_instance.p_generateIntegratedImage ); GUI->EvaluateNoise_CheckBox.SetChecked( m_instance.p_evaluateNoise ); GUI->EvaluateNoise_CheckBox.Enable( m_instance.p_generateIntegratedImage ); GUI->ClosePreviousImages_CheckBox.SetChecked( m_instance.p_closePreviousImages ); GUI->AutoMemorySize_CheckBox.SetChecked( m_instance.p_autoMemorySize ); GUI->BufferSize_SpinBox.SetValue( m_instance.p_bufferSizeMB ); GUI->BufferSize_Label.Enable( !m_instance.p_autoMemorySize ); GUI->BufferSize_SpinBox.Enable( !m_instance.p_autoMemorySize ); GUI->StackSize_SpinBox.SetValue( m_instance.p_stackSizeMB ); GUI->StackSize_Label.Enable( !m_instance.p_autoMemorySize ); GUI->StackSize_SpinBox.Enable( !m_instance.p_autoMemorySize ); GUI->UseCache_CheckBox.SetChecked( m_instance.p_useCache ); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateRejectionControls() { bool doesRejection = m_instance.p_rejection != IIRejection::NoRejection; bool doesRangeRejection = m_instance.p_rangeClipLow || m_instance.p_rangeClipHigh; bool doesMinMaxRejection = m_instance.p_rejection == IIRejection::MinMax; bool doesPercentileClipRejection = m_instance.p_rejection == IIRejection::PercentileClip; bool doesSigmaClipRejection = m_instance.p_rejection == IIRejection::SigmaClip || m_instance.p_rejection == IIRejection::WinsorizedSigmaClip || m_instance.p_rejection == IIRejection::AveragedSigmaClip; bool doesLinearFitRejection = m_instance.p_rejection == IIRejection::LinearFit; bool doesESDRejection = m_instance.p_rejection == IIRejection::ESD; bool doesCCDClipRejection = m_instance.p_rejection == IIRejection::CCDClip; GUI->RejectionAlgorithm_ComboBox.SetCurrentItem( m_instance.p_rejection ); GUI->RejectionNormalization_ComboBox.Enable( doesRejection ); GUI->RejectionNormalization_ComboBox.SetCurrentItem( m_instance.p_rejectionNormalization ); GUI->GenerateRejectionMaps_CheckBox.Enable( doesRejection || doesRangeRejection ); GUI->GenerateRejectionMaps_CheckBox.SetChecked( m_instance.p_generateRejectionMaps ); GUI->ClipLow_CheckBox.Enable( doesRejection ); GUI->ClipLow_CheckBox.SetChecked( m_instance.p_clipLow ); GUI->ClipHigh_CheckBox.Enable( doesRejection ); GUI->ClipHigh_CheckBox.SetChecked( m_instance.p_clipHigh ); GUI->ClipLowRange_CheckBox.SetChecked( m_instance.p_rangeClipLow ); GUI->ClipHighRange_CheckBox.SetChecked( m_instance.p_rangeClipHigh ); GUI->ReportRangeRejection_CheckBox.Enable( doesRangeRejection ); GUI->ReportRangeRejection_CheckBox.SetChecked( m_instance.p_reportRangeRejection ); GUI->MapRangeRejection_CheckBox.Enable( m_instance.p_generateRejectionMaps && doesRangeRejection ); GUI->MapRangeRejection_CheckBox.SetChecked( m_instance.p_mapRangeRejection ); GUI->MinMaxLow_Label.Enable( doesMinMaxRejection && m_instance.p_clipLow ); GUI->MinMaxLow_SpinBox.Enable( doesMinMaxRejection && m_instance.p_clipLow ); GUI->MinMaxLow_SpinBox.SetValue( m_instance.p_minMaxLow ); GUI->MinMaxHigh_Label.Enable( doesMinMaxRejection && m_instance.p_clipHigh ); GUI->MinMaxHigh_SpinBox.Enable( doesMinMaxRejection && m_instance.p_clipHigh ); GUI->MinMaxHigh_SpinBox.SetValue( m_instance.p_minMaxHigh ); GUI->PercentileLow_NumericControl.Enable( doesPercentileClipRejection && m_instance.p_clipLow ); GUI->PercentileLow_NumericControl.SetValue( m_instance.p_pcClipLow ); GUI->PercentileHigh_NumericControl.Enable( doesPercentileClipRejection && m_instance.p_clipHigh ); GUI->PercentileHigh_NumericControl.SetValue( m_instance.p_pcClipHigh ); GUI->SigmaLow_NumericControl.Enable( doesSigmaClipRejection && m_instance.p_clipLow ); GUI->SigmaLow_NumericControl.SetValue( m_instance.p_sigmaLow ); GUI->SigmaHigh_NumericControl.Enable( doesSigmaClipRejection && m_instance.p_clipHigh ); GUI->SigmaHigh_NumericControl.SetValue( m_instance.p_sigmaHigh ); GUI->WinsorizationCutoff_NumericControl.Enable( m_instance.p_rejection == IIRejection::WinsorizedSigmaClip ); GUI->WinsorizationCutoff_NumericControl.SetValue( m_instance.p_winsorizationCutoff ); GUI->LinearFitLow_NumericControl.Enable( doesLinearFitRejection ); GUI->LinearFitLow_NumericControl.SetValue( m_instance.p_linearFitLow ); GUI->LinearFitHigh_NumericControl.Enable( doesLinearFitRejection ); GUI->LinearFitHigh_NumericControl.SetValue( m_instance.p_linearFitHigh ); GUI->ESDOutliersFraction_NumericControl.Enable( doesESDRejection ); GUI->ESDOutliersFraction_NumericControl.SetValue( m_instance.p_esdOutliersFraction ); GUI->ESDAlpha_NumericControl.Enable( doesESDRejection ); GUI->ESDAlpha_NumericControl.SetValue( m_instance.p_esdAlpha ); GUI->ESDLowRelaxation_NumericControl.Enable( doesESDRejection ); GUI->ESDLowRelaxation_NumericControl.SetValue( m_instance.p_esdLowRelaxation ); GUI->CCDGain_NumericControl.Enable( doesCCDClipRejection ); GUI->CCDGain_NumericControl.SetValue( m_instance.p_ccdGain ); GUI->CCDReadNoise_NumericControl.Enable( doesCCDClipRejection ); GUI->CCDReadNoise_NumericControl.SetValue( m_instance.p_ccdReadNoise ); GUI->CCDScaleNoise_NumericControl.Enable( doesCCDClipRejection ); GUI->CCDScaleNoise_NumericControl.SetValue( m_instance.p_ccdScaleNoise ); GUI->RangeLow_NumericControl.Enable( m_instance.p_rangeClipLow ); GUI->RangeLow_NumericControl.SetValue( m_instance.p_rangeLow ); GUI->RangeHigh_NumericControl.Enable( m_instance.p_rangeClipHigh ); GUI->RangeHigh_NumericControl.SetValue( m_instance.p_rangeHigh ); GUI->LargeScaleRejection_Control.Enable( doesRejection ); GUI->RejectLargeScaleLow_CheckBox.SetChecked( m_instance.p_largeScaleClipLow ); GUI->RejectLargeScaleLow_CheckBox.Enable( m_instance.p_clipLow ); GUI->SmallScaleLayersLow_Label.Enable( m_instance.p_clipLow && m_instance.p_largeScaleClipLow ); GUI->SmallScaleLayersLow_SpinBox.SetValue( m_instance.p_largeScaleClipLowProtectedLayers ); GUI->SmallScaleLayersLow_SpinBox.Enable( m_instance.p_clipLow && m_instance.p_largeScaleClipLow ); GUI->GrowthLow_Label.Enable( m_instance.p_clipLow && m_instance.p_largeScaleClipLow ); GUI->GrowthLow_SpinBox.SetValue( m_instance.p_largeScaleClipLowGrowth ); GUI->GrowthLow_SpinBox.Enable( m_instance.p_clipLow && m_instance.p_largeScaleClipLow ); GUI->RejectLargeScaleHigh_CheckBox.SetChecked( m_instance.p_largeScaleClipHigh ); GUI->RejectLargeScaleHigh_CheckBox.Enable( m_instance.p_clipHigh ); GUI->SmallScaleLayersHigh_Label.Enable( m_instance.p_clipHigh && m_instance.p_largeScaleClipHigh ); GUI->SmallScaleLayersHigh_SpinBox.SetValue( m_instance.p_largeScaleClipHighProtectedLayers ); GUI->SmallScaleLayersHigh_SpinBox.Enable( m_instance.p_clipHigh && m_instance.p_largeScaleClipHigh ); GUI->GrowthHigh_Label.Enable( m_instance.p_clipHigh && m_instance.p_largeScaleClipHigh ); GUI->GrowthHigh_SpinBox.SetValue( m_instance.p_largeScaleClipHighGrowth ); GUI->GrowthHigh_SpinBox.Enable( m_instance.p_clipHigh && m_instance.p_largeScaleClipHigh ); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::UpdateROIControls() { GUI->ROI_SectionBar.SetChecked( m_instance.p_useROI ); GUI->ROIX0_SpinBox.SetValue( m_instance.p_roi.x0 ); GUI->ROIY0_SpinBox.SetValue( m_instance.p_roi.y0 ); GUI->ROIWidth_SpinBox.SetValue( m_instance.p_roi.Width() ); GUI->ROIHeight_SpinBox.SetValue( m_instance.p_roi.Height() ); } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_InputImages_CurrentNodeUpdated( TreeBox& sender, TreeBox::Node& current, TreeBox::Node& oldCurrent ) { int index = sender.ChildIndex( &current ); if ( index < 0 || size_type( index ) >= m_instance.p_images.Length() ) throw Error( "ImageIntegrationInterface: *Warning* Corrupted interface structures" ); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_InputImages_NodeActivated( TreeBox& sender, TreeBox::Node& node, int col ) { int index = sender.ChildIndex( &node ); if ( index < 0 || size_type( index ) >= m_instance.p_images.Length() ) throw Error( "ImageIntegrationInterface: *Warning* Corrupted interface structures" ); ImageIntegrationInstance::ImageItem& item = m_instance.p_images[index]; switch ( col ) { case 0: break; case 1: item.enabled = !item.enabled; UpdateInputImagesItem( index ); break; case 2: { Array<ImageWindow> windows = ImageWindow::Open( item.path, IsoString()/*id*/, m_instance.p_inputHints ); for ( ImageWindow& window : windows ) window.Show(); } break; } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_InputImages_NodeSelectionUpdated( TreeBox& sender ) { UpdateImageSelectionButtons(); } // ---------------------------------------------------------------------------- String ImageIntegrationInterface::LocalNormalizationTargetName( const String& filePath ) { LocalNormalizationData nml( filePath, true/*ignoreNormalizationData*/ ); /* * If the XNML file includes a target normalization path, use it. Otherwise * the target should have the same name as the .xnml file. */ String targetfilePath = nml.TargetFilePath(); if ( targetfilePath.IsEmpty() ) targetfilePath = filePath; if ( GUI->StaticDataTargets_CheckBox.IsChecked() ) return File::ChangeExtension( targetfilePath, String() ); return File::ExtractName( targetfilePath ); } // ---------------------------------------------------------------------------- String ImageIntegrationInterface::DrizzleTargetName( const String& filePath ) { DrizzleData drz( filePath, true/*ignoreIntegrationData*/ ); /* * If the XDRZ file includes a target alignment path, use it. Otherwise * the target should have the same name as the .xdrz file. */ String targetfilePath = drz.AlignmentTargetFilePath(); if ( targetfilePath.IsEmpty() ) targetfilePath = filePath; if ( GUI->StaticDataTargets_CheckBox.IsChecked() ) return File::ChangeExtension( targetfilePath, String() ); return File::ExtractName( targetfilePath ); } // ---------------------------------------------------------------------------- static size_type TreeInsertionIndex( const TreeBox& tree ) { const TreeBox::Node* n = tree.CurrentNode(); return (n != nullptr) ? tree.ChildIndex( n ) + 1 : tree.NumberOfChildren(); } void ImageIntegrationInterface::e_InputImages_Click( Button& sender, bool checked ) { if ( sender == GUI->AddFiles_PushButton ) { OpenFileDialog d; d.SetCaption( "ImageIntegration: Select Input Images" ); d.LoadImageFilters(); d.EnableMultipleSelections(); if ( d.Execute() ) { size_type i0 = TreeInsertionIndex( GUI->InputImages_TreeBox ); ImageIntegrationInstance::image_list newImages; for ( size_type i = 0; i < i0; ++i ) newImages << m_instance.p_images[i]; for ( const String& path : d.FileNames() ) newImages << ImageIntegrationInstance::ImageItem( path ); for ( size_type i = i0; i < m_instance.p_images.Length(); ++i ) newImages << m_instance.p_images[i]; m_instance.p_images = newImages; // for ( const String& path : d.FileNames() ) // m_instance.p_images.Insert( m_instance.p_images.At( i0++ ), ImageIntegrationInstance::ImageItem( path ) ); UpdateInputImagesList(); UpdateImageSelectionButtons(); } } else if ( sender == GUI->AddDrizzleFiles_PushButton ) { OpenFileDialog d; d.SetCaption( "ImageIntegration: Select Drizzle Data Files" ); d.SetFilter( FileFilter( "Drizzle Data Files", StringList() << ".xdrz" << ".drz" ) ); d.EnableMultipleSelections(); if ( d.Execute() ) { IVector assigned( 0, int( m_instance.p_images.Length() ) ); for ( const String& path : d.FileNames() ) { String targetName = DrizzleTargetName( path ); IVector::iterator n = assigned.Begin(); for ( ImageIntegrationInstance::ImageItem& item : m_instance.p_images ) { String name = GUI->StaticDataTargets_CheckBox.IsChecked() ? File::ChangeExtension( item.path, String() ) : File::ExtractName( item.path ); if ( name == targetName ) { item.drzPath = path; ++*n; break; } ++n; } } UpdateInputImagesList(); int total = 0; int duplicates = 0; for ( int i = 0; i < assigned.Length(); ++i ) if ( assigned[i] > 0 ) { ++total; if ( assigned[i] > 1 ) ++duplicates; } if ( total == 0 ) { MessageBox( "<p>No drizzle data files have been assigned to integration source images.</p>", "ImageIntegration", StdIcon::Error, StdButton::Ok ).Execute(); } else { if ( total < assigned.Length() || duplicates ) MessageBox( String().Format( "<p>%d of %d drizzle data files have been assigned.<br/>" "%d duplicate assignment(s)</p>", total, assigned.Length(), duplicates ), "ImageIntegration", StdIcon::Warning, StdButton::Ok ).Execute(); if ( !m_instance.p_generateDrizzleData ) { m_instance.p_generateDrizzleData = true; UpdateIntegrationControls(); } } } } else if ( sender == GUI->ClearDrizzleFiles_PushButton ) { for ( ImageIntegrationInstance::ImageItem& item : m_instance.p_images ) item.drzPath.Clear(); UpdateInputImagesList(); if ( m_instance.p_generateDrizzleData ) { m_instance.p_generateDrizzleData = false; UpdateIntegrationControls(); } } else if ( sender == GUI->AddLocalNormalizationFiles_PushButton ) { OpenFileDialog d; d.SetCaption( "ImageIntegration: Select Local Normalization Data Files" ); d.SetFilter( FileFilter( "Local Normalization Data Files", ".xnml" ) ); d.EnableMultipleSelections(); if ( d.Execute() ) { IVector assigned( 0, int( m_instance.p_images.Length() ) ); for ( const String& path : d.FileNames() ) { String targetName = LocalNormalizationTargetName( path ); IVector::iterator n = assigned.Begin(); for ( ImageIntegrationInstance::ImageItem& item : m_instance.p_images ) { String name = GUI->StaticDataTargets_CheckBox.IsChecked() ? File::ChangeExtension( item.path, String() ) : File::ExtractName( item.path ); if ( name == targetName ) { item.nmlPath = path; ++*n; break; } ++n; } } UpdateInputImagesList(); int total = 0; int duplicates = 0; for ( int i = 0; i < assigned.Length(); ++i ) if ( assigned[i] > 0 ) { ++total; if ( assigned[i] > 1 ) ++duplicates; } if ( total == 0 ) { MessageBox( "<p>No local normalization data files have been assigned to integration source images.</p>", "ImageIntegration", StdIcon::Error, StdButton::Ok ).Execute(); } else { if ( total < assigned.Length() || duplicates ) MessageBox( String().Format( "<p>%d of %d local normalization data files have been assigned.<br/>" "%d duplicate assignment(s)</p>", total, assigned.Length(), duplicates ), "ImageIntegration", StdIcon::Warning, StdButton::Ok ).Execute(); } } } else if ( sender == GUI->ClearLocalNormalizationFiles_PushButton ) { for ( ImageIntegrationInstance::ImageItem& item : m_instance.p_images ) item.nmlPath.Clear(); UpdateInputImagesList(); } else if ( sender == GUI->SelectAll_PushButton ) { GUI->InputImages_TreeBox.SelectAllNodes(); UpdateImageSelectionButtons(); } else if ( sender == GUI->SetReference_PushButton ) { TreeBox::Node* node = GUI->InputImages_TreeBox.CurrentNode(); if ( node != nullptr ) { int idx = GUI->InputImages_TreeBox.ChildIndex( node ); if ( idx > 0 ) { ImageIntegrationInstance::ImageItem item = m_instance.p_images[idx]; m_instance.p_images.Remove( m_instance.p_images.At( idx ) ); item.enabled = true; m_instance.p_images.Insert( m_instance.p_images.Begin(), item ); UpdateInputImagesList(); GUI->InputImages_TreeBox.SetCurrentNode( GUI->InputImages_TreeBox[0] ); UpdateImageSelectionButtons(); } } } else if ( sender == GUI->InvertSelection_PushButton ) { for ( int i = 0, n = GUI->InputImages_TreeBox.NumberOfChildren(); i < n; ++i ) GUI->InputImages_TreeBox[i]->Select( !GUI->InputImages_TreeBox[i]->IsSelected() ); UpdateImageSelectionButtons(); } else if ( sender == GUI->ToggleSelected_PushButton ) { for ( int i = 0, n = GUI->InputImages_TreeBox.NumberOfChildren(); i < n; ++i ) if ( GUI->InputImages_TreeBox[i]->IsSelected() ) m_instance.p_images[i].enabled = !m_instance.p_images[i].enabled; UpdateInputImagesList(); UpdateImageSelectionButtons(); } else if ( sender == GUI->RemoveSelected_PushButton ) { ImageIntegrationInstance::image_list newImages; for ( int i = 0, n = GUI->InputImages_TreeBox.NumberOfChildren(); i < n; ++i ) if ( !GUI->InputImages_TreeBox[i]->IsSelected() ) newImages << m_instance.p_images[i]; m_instance.p_images = newImages; UpdateInputImagesList(); UpdateImageSelectionButtons(); } else if ( sender == GUI->Clear_PushButton ) { m_instance.p_images.Clear(); UpdateInputImagesList(); UpdateImageSelectionButtons(); } else if ( sender == GUI->FullPaths_CheckBox ) { UpdateInputImagesList(); UpdateImageSelectionButtons(); } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_FormatHints_EditCompleted( Edit& sender ) { String hints = sender.Text().Trimmed(); if ( sender == GUI->InputHints_Edit ) m_instance.p_inputHints = hints; sender.SetText( hints ); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Integration_ItemSelected( ComboBox& sender, int itemIndex ) { if ( sender == GUI->Combination_ComboBox ) { m_instance.p_combination = itemIndex; UpdateIntegrationControls(); } else if ( sender == GUI->Normalization_ComboBox ) { m_instance.p_normalization = itemIndex; } else if ( sender == GUI->WeightMode_ComboBox ) { m_instance.p_weightMode = itemIndex; UpdateIntegrationControls(); } else if ( sender == GUI->WeightScale_ComboBox ) { m_instance.p_weightScale = itemIndex; UpdateIntegrationControls(); } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Integration_EditCompleted( Edit& sender ) { if ( sender == GUI->WeightKeyword_Edit ) { m_instance.p_weightKeyword = sender.Text(); m_instance.p_weightKeyword.Trim(); m_instance.p_weightKeyword.ToUppercase(); sender.SetText( m_instance.p_weightKeyword ); } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Integration_SpinValueUpdated( SpinBox& sender, int value ) { if ( sender == GUI->AdaptiveGridSize_SpinBox ) m_instance.p_adaptiveGridSize = value; else if ( sender == GUI->BufferSize_SpinBox ) m_instance.p_bufferSizeMB = value; else if ( sender == GUI->StackSize_SpinBox ) m_instance.p_stackSizeMB = value; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Integration_Click( Button& sender, bool checked ) { if ( sender == GUI->GenerateIntegratedImage_CheckBox ) { m_instance.p_generateIntegratedImage = checked; UpdateIntegrationControls(); } else if ( sender == GUI->Generate64BitResult_CheckBox ) m_instance.p_generate64BitResult = checked; else if ( sender == GUI->GenerateDrizzleData_CheckBox ) m_instance.p_generateDrizzleData = checked; else if ( sender == GUI->IgnoreNoiseKeywords_CheckBox ) m_instance.p_ignoreNoiseKeywords = checked; else if ( sender == GUI->AdaptiveNoScale_CheckBox ) m_instance.p_adaptiveNoScale = checked; else if ( sender == GUI->SubtractPedestals_CheckBox ) m_instance.p_subtractPedestals = checked; else if ( sender == GUI->TruncateOnOutOfRange_CheckBox ) m_instance.p_truncateOnOutOfRange = checked; else if ( sender == GUI->EvaluateNoise_CheckBox ) m_instance.p_evaluateNoise = checked; else if ( sender == GUI->ClosePreviousImages_CheckBox ) m_instance.p_closePreviousImages = checked; else if ( sender == GUI->AutoMemorySize_CheckBox ) { m_instance.p_autoMemorySize = checked; UpdateIntegrationControls(); } else if ( sender == GUI->UseCache_CheckBox ) m_instance.p_useCache = checked; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Rejection_ItemSelected( ComboBox& sender, int itemIndex ) { if ( sender == GUI->RejectionAlgorithm_ComboBox ) { m_instance.p_rejection = itemIndex; UpdateRejectionControls(); } else if ( sender == GUI->RejectionNormalization_ComboBox ) { m_instance.p_rejectionNormalization = itemIndex; UpdateRejectionControls(); } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Rejection_SpinValueUpdated( SpinBox& sender, int value ) { if ( sender == GUI->MinMaxLow_SpinBox ) m_instance.p_minMaxLow = value; else if ( sender == GUI->MinMaxHigh_SpinBox ) m_instance.p_minMaxHigh = value; else if ( sender == GUI->SmallScaleLayersLow_SpinBox ) m_instance.p_largeScaleClipLowProtectedLayers = value; else if ( sender == GUI->GrowthLow_SpinBox ) m_instance.p_largeScaleClipLowGrowth = value; else if ( sender == GUI->SmallScaleLayersHigh_SpinBox ) m_instance.p_largeScaleClipHighProtectedLayers = value; else if ( sender == GUI->GrowthHigh_SpinBox ) m_instance.p_largeScaleClipHighGrowth = value; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Rejection_EditValueUpdated( NumericEdit& sender, double value ) { if ( sender == GUI->PercentileLow_NumericControl ) m_instance.p_pcClipLow = value; else if ( sender == GUI->PercentileHigh_NumericControl ) m_instance.p_pcClipHigh = value; else if ( sender == GUI->SigmaLow_NumericControl ) m_instance.p_sigmaLow = value; else if ( sender == GUI->SigmaHigh_NumericControl ) m_instance.p_sigmaHigh = value; else if ( sender == GUI->WinsorizationCutoff_NumericControl ) m_instance.p_winsorizationCutoff = value; else if ( sender == GUI->LinearFitLow_NumericControl ) m_instance.p_linearFitLow = value; else if ( sender == GUI->LinearFitHigh_NumericControl ) m_instance.p_linearFitHigh = value; else if ( sender == GUI->ESDOutliersFraction_NumericControl ) m_instance.p_esdOutliersFraction = value; else if ( sender == GUI->ESDAlpha_NumericControl ) m_instance.p_esdAlpha = value; else if ( sender == GUI->ESDLowRelaxation_NumericControl ) m_instance.p_esdLowRelaxation = value; else if ( sender == GUI->CCDGain_NumericControl ) m_instance.p_ccdGain = value; else if ( sender == GUI->CCDReadNoise_NumericControl ) m_instance.p_ccdReadNoise = value; else if ( sender == GUI->CCDScaleNoise_NumericControl ) m_instance.p_ccdScaleNoise = value; else if ( sender == GUI->RangeLow_NumericControl ) m_instance.p_rangeLow = value; else if ( sender == GUI->RangeHigh_NumericControl ) m_instance.p_rangeHigh = value; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_Rejection_Click( Button& sender, bool checked ) { if ( sender == GUI->GenerateRejectionMaps_CheckBox ) { m_instance.p_generateRejectionMaps = checked; UpdateRejectionControls(); } else if ( sender == GUI->ClipLow_CheckBox ) { m_instance.p_clipLow = checked; UpdateRejectionControls(); } else if ( sender == GUI->ClipHigh_CheckBox ) { m_instance.p_clipHigh = checked; UpdateRejectionControls(); } else if ( sender == GUI->ClipLowRange_CheckBox ) { m_instance.p_rangeClipLow = checked; UpdateRejectionControls(); } else if ( sender == GUI->ClipHighRange_CheckBox ) { m_instance.p_rangeClipHigh = checked; UpdateRejectionControls(); } else if ( sender == GUI->ReportRangeRejection_CheckBox ) m_instance.p_reportRangeRejection = checked; else if ( sender == GUI->MapRangeRejection_CheckBox ) m_instance.p_mapRangeRejection = checked; else if ( sender == GUI->RejectLargeScaleLow_CheckBox ) { m_instance.p_largeScaleClipLow = checked; UpdateRejectionControls(); } else if ( sender == GUI->RejectLargeScaleHigh_CheckBox ) { m_instance.p_largeScaleClipHigh = checked; UpdateRejectionControls(); } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_ROI_Check( SectionBar& sender, bool checked ) { if ( sender == GUI->ROI_SectionBar ) m_instance.p_useROI = checked; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_ROI_SpinValueUpdated( SpinBox& sender, int value ) { if ( sender == GUI->ROIX0_SpinBox ) m_instance.p_roi.x0 = value; else if ( sender == GUI->ROIY0_SpinBox ) m_instance.p_roi.y0 = value; else if ( sender == GUI->ROIWidth_SpinBox ) m_instance.p_roi.x1 = m_instance.p_roi.x0 + value; else if ( sender == GUI->ROIHeight_SpinBox ) m_instance.p_roi.y1 = m_instance.p_roi.y0 + value; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_ROI_Click( Button& sender, bool checked ) { if ( sender == GUI->SelectPreview_Button ) { PreviewSelectionDialog d; d.SetWindowTitle( "Select ROI Preview" ); if ( d.Execute() ) if ( !d.Id().IsEmpty() ) { View view = View::ViewById( d.Id() ); if ( !view.IsNull() ) { m_instance.p_roi = view.Window().PreviewRect( view.Id() ); UpdateROIControls(); } } } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_ToggleSection( SectionBar& sender, Control& section, bool start ) { if ( start ) GUI->InputImages_TreeBox.SetFixedHeight(); else { GUI->InputImages_TreeBox.SetMinHeight( IMAGELIST_MINHEIGHT( Font() ) ); GUI->InputImages_TreeBox.SetMaxHeight( int_max ); if ( GUI->InputImages_Control.IsVisible() ) SetVariableHeight(); else SetFixedHeight(); } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_FileDrag( Control& sender, const Point& pos, const StringList& files, unsigned modifiers, bool& wantsFiles ) { if ( sender == GUI->InputImages_TreeBox.Viewport() ) wantsFiles = true; } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_FileDrop( Control& sender, const Point& pos, const StringList& files, unsigned modifiers ) { if ( sender == GUI->InputImages_TreeBox.Viewport() ) { StringList localNormalizationFiles, drizzleFiles; bool recursive = IsControlOrCmdPressed(); size_type i0 = TreeInsertionIndex( GUI->InputImages_TreeBox ); for ( const String& item : files ) { StringList inputFiles; if ( File::Exists( item ) ) { String ext = File::ExtractSuffix( item ).CaseFolded(); if ( ext == ".xnml" ) localNormalizationFiles << item; else if ( ext == ".xdrz" || ext == ".drz" ) drizzleFiles << item; else inputFiles << item; } else if ( File::DirectoryExists( item ) ) { inputFiles << FileFormat::SupportedImageFiles( item, true/*toRead*/, false/*toWrite*/, recursive ); localNormalizationFiles << FileFormat::LocalNormalizationFiles( item, recursive ); drizzleFiles << FileFormat::DrizzleFiles( item, recursive ); } inputFiles.Sort(); for ( const String& file : inputFiles ) { String ext = File::ExtractSuffix( file ).CaseFolded(); if ( ext == ".xnml" ) localNormalizationFiles << file; else if ( ext == ".xdrz" || ext == ".drz" ) drizzleFiles << file; else m_instance.p_images.Insert( m_instance.p_images.At( i0++ ), ImageIntegrationInstance::ImageItem( file ) ); } } for ( const String& file : localNormalizationFiles ) { String targetName = LocalNormalizationTargetName( file ); for ( ImageIntegrationInstance::ImageItem& item : m_instance.p_images ) { String name = GUI->StaticDataTargets_CheckBox.IsChecked() ? File::ChangeExtension( item.path, String() ) : File::ExtractName( item.path ); if ( name == targetName ) { item.nmlPath = file; break; } } } for ( const String& file : drizzleFiles ) { String targetName = DrizzleTargetName( file ); for ( ImageIntegrationInstance::ImageItem& item : m_instance.p_images ) { String name = GUI->StaticDataTargets_CheckBox.IsChecked() ? File::ChangeExtension( item.path, String() ) : File::ExtractName( item.path ); if ( name == targetName ) { item.drzPath = file; break; } } } UpdateInputImagesList(); UpdateImageSelectionButtons(); if ( !drizzleFiles.IsEmpty() ) if ( !m_instance.p_generateDrizzleData ) { m_instance.p_generateDrizzleData = true; UpdateIntegrationControls(); } } } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_ViewDrag( Control& sender, const Point& pos, const View& view, unsigned modifiers, bool& wantsView ) { if ( sender == GUI->ROI_SectionBar || sender == GUI->ROI_Control || sender == GUI->SelectPreview_Button ) wantsView = view.IsPreview(); } // ---------------------------------------------------------------------------- void ImageIntegrationInterface::e_ViewDrop( Control& sender, const Point& pos, const View& view, unsigned modifiers ) { if ( sender == GUI->ROI_SectionBar || sender == GUI->ROI_Control || sender == GUI->SelectPreview_Button ) if ( view.IsPreview() ) { m_instance.p_useROI = true; m_instance.p_roi = view.Window().PreviewRect( view.Id() ); GUI->ROI_SectionBar.ShowSection(); UpdateROIControls(); } } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- ImageIntegrationInterface::GUIData::GUIData( ImageIntegrationInterface& w ) { pcl::Font fnt = w.Font(); int labelWidth1 = fnt.Width( String( "Winsorization cutoff:" ) + 'M' ); int editWidth1 = fnt.Width( String( 'M', 16 ) ); int editWidth2 = fnt.Width( String( '0', 11 ) ); //int spinWidth1 = fnt.Width( String( '0', 11 ) ); int ui4 = w.LogicalPixelsToPhysical( 4 ); // InputImages_SectionBar.SetTitle( "Input Images" ); InputImages_SectionBar.SetSection( InputImages_Control ); InputImages_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); InputImages_TreeBox.SetMinHeight( IMAGELIST_MINHEIGHT( fnt ) ); InputImages_TreeBox.SetNumberOfColumns( 3 ); InputImages_TreeBox.HideHeader(); InputImages_TreeBox.EnableMultipleSelections(); InputImages_TreeBox.DisableRootDecoration(); InputImages_TreeBox.EnableAlternateRowColor(); InputImages_TreeBox.OnCurrentNodeUpdated( (TreeBox::node_navigation_event_handler)&ImageIntegrationInterface::e_InputImages_CurrentNodeUpdated, w ); InputImages_TreeBox.OnNodeActivated( (TreeBox::node_event_handler)&ImageIntegrationInterface::e_InputImages_NodeActivated, w ); InputImages_TreeBox.OnNodeSelectionUpdated( (TreeBox::tree_event_handler)&ImageIntegrationInterface::e_InputImages_NodeSelectionUpdated, w ); InputImages_TreeBox.Viewport().OnFileDrag( (Control::file_drag_event_handler)&ImageIntegrationInterface::e_FileDrag, w ); InputImages_TreeBox.Viewport().OnFileDrop( (Control::file_drop_event_handler)&ImageIntegrationInterface::e_FileDrop, w ); AddFiles_PushButton.SetText( "Add Files" ); AddFiles_PushButton.SetToolTip( "<p>Add existing image files to the list of input images.</p>" ); AddFiles_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); AddLocalNormalizationFiles_PushButton.SetText( "Add L.Norm. Files" ); AddLocalNormalizationFiles_PushButton.SetToolTip( "<p>Associate existing local normalization data files with input images.</p>" "<p>Local normalization data files carry the .xnml suffix. Normally you should select .xnml files generated by " "the LocalNormalization tool for the same files that you are integrating.</p>" ); AddLocalNormalizationFiles_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); ClearLocalNormalizationFiles_PushButton.SetText( "Clear L.Norm. Files" ); ClearLocalNormalizationFiles_PushButton.SetToolTip( "<p>Remove all local normalization data files currently associated with " "input images.</p>" "<p>This removes just file associations, not the actual local normalization data files.</p>" ); ClearLocalNormalizationFiles_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); AddDrizzleFiles_PushButton.SetText( "Add Drizzle Files" ); AddDrizzleFiles_PushButton.SetToolTip( "<p>Associate existing drizzle data files with input images.</p>" "<p>Drizzle data files carry the .xdrz suffix. Normally you should select .xdrz files generated by " "the StarAlignment tool for the same files that you are integrating.</p>" ); AddDrizzleFiles_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); ClearDrizzleFiles_PushButton.SetText( "Clear Drizzle Files" ); ClearDrizzleFiles_PushButton.SetToolTip( "<p>Remove all drizzle data files currently associated with input images.</p>" "<p>This removes just file associations, not the actual drizzle data files.</p>" ); ClearDrizzleFiles_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); SetReference_PushButton.SetText( "Set Reference" ); SetReference_PushButton.SetToolTip( "<p>Make the currently selected file on the list the reference image.</p>" "<p>The reference image is the first one in the list of images to integrate. Its statistical properties " "will be taken as the basis to calculate normalization parameters and relative combination weights for the " "rest of integrated images.</p>" ); SetReference_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); SelectAll_PushButton.SetText( "Select All" ); SelectAll_PushButton.SetToolTip( "<p>Select all input images.</p>" ); SelectAll_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); InvertSelection_PushButton.SetText( "Invert Selection" ); InvertSelection_PushButton.SetToolTip( "<p>Invert the current selection of input images.</p>" ); InvertSelection_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); ToggleSelected_PushButton.SetText( "Toggle Selected" ); ToggleSelected_PushButton.SetToolTip( "<p>Toggle the enabled/disabled state of currently selected input images.</p>" "<p>Disabled input images will be ignored during the integration process.</p>" ); ToggleSelected_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); RemoveSelected_PushButton.SetText( "Remove Selected" ); RemoveSelected_PushButton.SetToolTip( "<p>Remove all currently selected input images.</p>" ); RemoveSelected_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); Clear_PushButton.SetText( "Clear" ); Clear_PushButton.SetToolTip( "<p>Clear the list of input images.</p>" ); Clear_PushButton.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); StaticDataTargets_CheckBox.SetText( "Static data targets" ); StaticDataTargets_CheckBox.SetToolTip( "<p>When assigning drizzle and/or local normalization data files to target " "images, take into account full file paths stored in .xdrz and .xnml files. This allows you to integrate images " "with duplicate file names on different directories. However, by enabling this option your data set gets tied to " "specific locations on the local filesystem. When this option is disabled (the default state), only file names are " "used to associate target images with .xdrz and .xnml files, which allows you to move your images freely throughout " "the filesystem, including the possibility to migrate them to different machines.</p>" "<p>Changes to this option will come into play the next time you associate .xdrz and/or .xnml files with target " "images. Existing file associations are not affected.</p>"); //StaticDataTargets_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); FullPaths_CheckBox.SetText( "Full paths" ); FullPaths_CheckBox.SetToolTip( "<p>Show full paths for input image files.</p>" ); FullPaths_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_InputImages_Click, w ); InputButtons_Sizer.SetSpacing( 4 ); InputButtons_Sizer.Add( AddFiles_PushButton ); InputButtons_Sizer.Add( AddLocalNormalizationFiles_PushButton ); InputButtons_Sizer.Add( ClearLocalNormalizationFiles_PushButton ); InputButtons_Sizer.Add( AddDrizzleFiles_PushButton ); InputButtons_Sizer.Add( ClearDrizzleFiles_PushButton ); InputButtons_Sizer.Add( SetReference_PushButton ); InputButtons_Sizer.Add( SelectAll_PushButton ); InputButtons_Sizer.Add( InvertSelection_PushButton ); InputButtons_Sizer.Add( ToggleSelected_PushButton ); InputButtons_Sizer.Add( RemoveSelected_PushButton ); InputButtons_Sizer.Add( Clear_PushButton ); InputButtons_Sizer.Add( StaticDataTargets_CheckBox ); InputButtons_Sizer.Add( FullPaths_CheckBox ); InputButtons_Sizer.AddStretch(); InputImages_Sizer.SetSpacing( 4 ); InputImages_Sizer.Add( InputImages_TreeBox, 100 ); InputImages_Sizer.Add( InputButtons_Sizer ); InputImages_Control.SetSizer( InputImages_Sizer ); // FormatHints_SectionBar.SetTitle( "Format Hints" ); FormatHints_SectionBar.SetSection( FormatHints_Control ); FormatHints_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); const char* hintsToolTip = "<p><i>Format hints</i> allow you to override global file format settings " "for image files used by specific processes. In ImageIntegration, input hints change the way input images " "of some particular file formats are loaded during the integration process. There are no output hints in " "ImageIntegration since this process does not write images to disk files.</p>" "<p>For example, you can use the \"raw cfa\" hints to force the RAW format to load pure raw images without " "applying any demosaicing, interpolation, white balance, or black point correction. You can also specify the " "\"lower-range\" and \"upper-range\" hints to load floating point FITS and TIFF files generated by other " "applications that don't use PixInsight's normalized [0,1] range. Most standard file format modules support " "hints; each format supports a number of input and/or output hints that you can use for different purposes " "with tools that give you access to format hints.</p>"; InputHints_Label.SetText( "Input hints:" ); InputHints_Label.SetFixedWidth( labelWidth1 ); InputHints_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); InputHints_Label.SetToolTip( hintsToolTip ); InputHints_Edit.SetToolTip( hintsToolTip ); InputHints_Edit.OnEditCompleted( (Edit::edit_event_handler)&ImageIntegrationInterface::e_FormatHints_EditCompleted, w ); InputHints_Sizer.SetSpacing( 4 ); InputHints_Sizer.Add( InputHints_Label ); InputHints_Sizer.Add( InputHints_Edit, 100 ); FormatHints_Sizer.SetSpacing( 4 ); FormatHints_Sizer.Add( InputHints_Sizer ); FormatHints_Control.SetSizer( FormatHints_Sizer ); // Integration_SectionBar.SetTitle( "Image Integration" ); Integration_SectionBar.SetSection( Integration_Control ); Integration_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); const char* combinationToolTip = "<p>Select a pixel combination operation.</p>" "<p><b>Average</b> combination provides the best signal-to-noise ratio in the integrated result.</p>" "<p><b>Median</b> combination provides implicit robust rejection of outliers, but at the cost of more noise.</p>"; Combination_Label.SetText( "Combination:" ); Combination_Label.SetFixedWidth( labelWidth1 ); Combination_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); Combination_Label.SetToolTip( combinationToolTip ); Combination_ComboBox.AddItem( "Average" ); Combination_ComboBox.AddItem( "Median" ); Combination_ComboBox.AddItem( "Minimum" ); Combination_ComboBox.AddItem( "Maximum" ); Combination_ComboBox.SetToolTip( combinationToolTip ); Combination_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&ImageIntegrationInterface::e_Integration_ItemSelected, w ); Combination_Sizer.SetSpacing( 4 ); Combination_Sizer.Add( Combination_Label ); Combination_Sizer.Add( Combination_ComboBox ); Combination_Sizer.AddStretch(); const char* normalizationToolTip = "<p>Image normalization for combination.</p>" "<p>If one of these options is selected, ImageIntegration will normalize and scale all the input images " "before combining them to generate the output image. Note that these normalization and scaling operations " "are independent from the similar operations performed before pixel rejection.</p>" "<p>Normalization matches mean background values. This can be done either as an <b>additive</b> or as a " "<b>multiplicative</b> process. In general, both ways lead to very similar results, but multiplicative " "normalization should be used to integrate images that are to be further combined or applied by " "multiplication or division, such as flat fields.</p>" "<p><b>Scaling</b> matches dispersion. This works as a sort of <i>automatic weighting</i> to combine the input " "images, and tends to improve the SNR of the result, especially for images with different overall illumination.</p>" "<p><b>Local normalization</b> applies per-pixel linear normalization functions previously calculated and stored " "in XNML files (.xnml file name suffix) by the LocalNormalization process. To apply this option, existing XNML " "files must be associated with input integration files. This option should normally be used when local normalization " "is also used for pixel rejection.</p>" "<p><b>Adaptive normalization</b> applies per-pixel additive/scaling normalization functions, computed by surface " "spline interpolation from matrices of location and two-sided scale estimates calculated for each integrated image. " "This algorithm is an alternative to local normalization that does not require auxiliary files. See also the " "information provided for adaptive rejection normalization.</p>" "<p>The default option is additive normalization with scaling.</p>"; Normalization_Label.SetText( "Normalization:" ); Normalization_Label.SetFixedWidth( labelWidth1 ); Normalization_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); Normalization_Label.SetToolTip( normalizationToolTip ); Normalization_ComboBox.AddItem( "No normalization" ); Normalization_ComboBox.AddItem( "Additive" ); Normalization_ComboBox.AddItem( "Multiplicative" ); Normalization_ComboBox.AddItem( "Additive with scaling" ); Normalization_ComboBox.AddItem( "Multiplicative with scaling" ); Normalization_ComboBox.AddItem( "Local normalization" ); Normalization_ComboBox.AddItem( "Adaptive normalization" ); Normalization_ComboBox.SetToolTip( normalizationToolTip ); Normalization_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&ImageIntegrationInterface::e_Integration_ItemSelected, w ); Normalization_Sizer.SetSpacing( 4 ); Normalization_Sizer.Add( Normalization_Label ); Normalization_Sizer.Add( Normalization_ComboBox ); Normalization_Sizer.AddStretch(); const char* adaptiveGridToolTip = "<p>This parameter defines the number of samples used to interpolate per-pixel statistical location and scale " "estimates for adaptive normalization. The more samples, the more locally adaptive the normalization will be.</p>" "<p>A more adaptive normalization attempts to compensate for additive and multiplicative differences between " "integrated subframes at a smaller scale. A less adaptive normalization acts at a larger scale; for example, the " "default <i>additive with scaling</i> output normalization (or the <i>scale + zero offset</i> normalization for " "rejection) uses a single sample of location and scale, and hence can be regarded as a special case of adaptive " "normalization working at the scale of the entire image.</p>" "<p>The value specified with this parameter determines the number of columns or rows (according to the largest " "dimension of the image) in the matrix of regularly distributed samples of location and scale computed from pixels " "of each integrated subframe. This value will be used equally for rejection and output adaptive normalizations.</p>" "<p><b>Warning:</b> Specifying a value that is too high for this parameter may lead to generation of artifacts in " "the integrated image. This is because too small sampling regions tend to map small-scale local variations that may " "not be representative of significant statistical variations in the image. Always watch rejection maps closely when " "using adaptive normalization. <b>Local normalizations must <i>never</i> be applied blindly without analyzing the " "results.</b></p>"; AdaptiveGridSize_Label.SetText( "Adaptive grid size:" ); AdaptiveGridSize_Label.SetFixedWidth( labelWidth1 ); AdaptiveGridSize_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); AdaptiveGridSize_Label.SetToolTip( adaptiveGridToolTip ); AdaptiveGridSize_SpinBox.SetRange( int( TheIIAdaptiveGridSizeParameter->MinimumValue() ), int( TheIIAdaptiveGridSizeParameter->MaximumValue() ) ); AdaptiveGridSize_SpinBox.SetToolTip( adaptiveGridToolTip ); AdaptiveGridSize_SpinBox.SetFixedWidth( editWidth2 ); AdaptiveGridSize_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Integration_SpinValueUpdated, w ); AdaptiveGridSize_Sizer.SetSpacing( 4 ); AdaptiveGridSize_Sizer.Add( AdaptiveGridSize_Label ); AdaptiveGridSize_Sizer.Add( AdaptiveGridSize_SpinBox ); AdaptiveGridSize_Sizer.AddStretch(); AdaptiveNoScale_CheckBox.SetText( "No adaptive scale components" ); AdaptiveNoScale_CheckBox.SetToolTip( "<p>Apply only the location (additive) components of adaptive normalization " "functions, and use global two-sided scale estimates instead of adaptive ones.</p>" "<p>This option can be used to limit adaptive normalization to correction of purely additive gradients. Without " "multiplicative components, adaptive normalization can be more tolerant of excessive grid size parameter values. " "However, in difficult cases with strong gradients, scale components can be necessary to achieve a sufficiently " "accurate normalization.</p>" ); AdaptiveNoScale_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); AdaptiveNoScale_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); AdaptiveNoScale_Sizer.Add( AdaptiveNoScale_CheckBox ); AdaptiveNoScale_Sizer.AddStretch(); const char* weightModeToolTip = "<p>Image weighting criterion.</p>" "<p>Exposure times will be retrieved from standard EXPTIME and EXPOSURE FITS keywords (in that order).</p>" "<p>The <b>noise evaluation</b> option uses multiscale noise evaluation techniques to compute relative " "SNR values that tend to minimize mean squared error in the integrated image. This is usually the most " "robust approach for automatic image weighting, and therefore the default option.</p>" "<p>Noise estimates are obtained either from cached data, if available, or from NOISExx FITS keywords, if " "they are present in the images. Otherwise ImageIntegration will compute Gaussian noise estimates using the " "multiresolution support (MRS) noise evaluation algorithm.</p>" "<p>The <b>average signal strength</b> option attempts to derive relative exposures directly from statistical " "properties of the data. This option is less robust and may not work if some images have additive " "illumination variations, such as sky gradients.</p>" "<p>If you select the <b>FITS keyword</b> option, please specify the name of a FITS keyword to retrieve " "image weights. The specified keyword must be present in all input images and its value must be of numeric " "type and positive.</p>"; WeightMode_Label.SetText( "Weights:" ); WeightMode_Label.SetFixedWidth( labelWidth1 ); WeightMode_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); WeightMode_Label.SetToolTip( weightModeToolTip ); WeightMode_ComboBox.AddItem( "Don't care (all weights = 1)" ); WeightMode_ComboBox.AddItem( "Exposure time" ); WeightMode_ComboBox.AddItem( "Noise evaluation" ); WeightMode_ComboBox.AddItem( "Average signal strength" ); WeightMode_ComboBox.AddItem( "Median value" ); WeightMode_ComboBox.AddItem( "Average value" ); WeightMode_ComboBox.AddItem( "FITS keyword" ); WeightMode_ComboBox.SetToolTip( weightModeToolTip ); WeightMode_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&ImageIntegrationInterface::e_Integration_ItemSelected, w ); WeightMode_Sizer.SetSpacing( 4 ); WeightMode_Sizer.Add( WeightMode_Label ); WeightMode_Sizer.Add( WeightMode_ComboBox ); WeightMode_Sizer.AddStretch(); const char* weightKeywordToolTip = "<p>Custom FITS keyword to retrieve image weights.</p>" "<p>This is the name of a FITS keyword that will be used to retrieve image weights, if the " "<i>FITS keyword</i> option has been selected as the weighting criterion.</p>"; WeightKeyword_Label.SetText( "Weight keyword:" ); WeightKeyword_Label.SetFixedWidth( labelWidth1 ); WeightKeyword_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); WeightKeyword_Label.SetToolTip( weightKeywordToolTip ); WeightKeyword_Edit.SetMinWidth( editWidth1 ); WeightKeyword_Edit.SetToolTip( weightKeywordToolTip ); WeightKeyword_Edit.OnEditCompleted( (Edit::edit_event_handler)&ImageIntegrationInterface::e_Integration_EditCompleted, w ); WeightKeyword_Sizer.SetSpacing( 4 ); WeightKeyword_Sizer.Add( WeightKeyword_Label ); WeightKeyword_Sizer.Add( WeightKeyword_Edit ); WeightKeyword_Sizer.AddStretch(); const char* weightScaleToolTip = "<p>Estimator of scale used for image weighting and normalization.</p>" "<p>Statistical estimates of scale, or dispersion, are necessary for most image weighting, output and " "rejection normalization/scaling algorithms. Robust and efficient scale estimators are crucial to make the data " "from different images statistically compatible.</p>" "<p>The <b>average absolute deviation from the median</b> is robustified by trimming all pixel samples outside " "the [0.00002,0.99998] range, which excludes cold and hot pixels, as well as saturated pixels and bright spurious " "features (cosmics, etc).</p>" "<p>The <b>median absolute deviation from the median (MAD)</b> is a well-known robust estimator of scale. Although " "it has the best possible breakdown point (50%), its Gaussian efficiency is rather low (37%).</p>" "<p>The square root of the <b>biweight midvariance</b> is a robust estimator of scale with a 50% breakdown point " "(as good as MAD) and high efficiency with respect to several distributions (about 87%). This is the default scale " "estimator in current versions of the ImageIntegration tool.</p>" "<p>All scale estimators have been implemented as two-sided or bilateral algorithms, where estimates of scale are " "computed separately for low and high pixel samples, which are samples with values less than or equal and greater " "than the computed estimate of location, respectively, for each image channel. This helps to achieve a more robust " "and efficient normalization for pixel rejection, especially for input images with asymmetric or skewed " "distributions.</p>" "<p>In all cases the median is used as a robust estimator of location. This makes sense for deep-sky images " "because the median closely represents the mean background of the image in most cases.</p>"; WeightScale_Label.SetText( "Scale estimator:" ); WeightScale_Label.SetFixedWidth( labelWidth1 ); WeightScale_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); WeightScale_Label.SetToolTip( weightScaleToolTip ); WeightScale_ComboBox.AddItem( "Average absolute deviation from the median" ); WeightScale_ComboBox.AddItem( "Median absolute deviation from the median (MAD)" ); WeightScale_ComboBox.AddItem( "Biweight midvariance (BWMV)" ); WeightScale_ComboBox.SetToolTip( weightScaleToolTip ); WeightScale_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&ImageIntegrationInterface::e_Integration_ItemSelected, w ); WeightScale_Sizer.SetSpacing( 4 ); WeightScale_Sizer.Add( WeightScale_Label ); WeightScale_Sizer.Add( WeightScale_ComboBox ); WeightScale_Sizer.AddStretch(); IgnoreNoiseKeywords_CheckBox.SetText( "Ignore noise keywords" ); IgnoreNoiseKeywords_CheckBox.SetToolTip( "<p>Ignore NOISExx keywords. Always compute new noise estimates for " "input images, or retrieve them from the cache (if the cache is enabled and valid cached noise estimates are " "available).</p>" ); IgnoreNoiseKeywords_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); IgnoreNoiseKeywords_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); IgnoreNoiseKeywords_Sizer.Add( IgnoreNoiseKeywords_CheckBox ); IgnoreNoiseKeywords_Sizer.AddStretch(); GenerateIntegratedImage_CheckBox.SetText( "Generate integrated image" ); GenerateIntegratedImage_CheckBox.SetToolTip( "<p>Generate the result of the integration process as a new " "image window.</p>" "<p>This option should be enabled for normal use. If you disable it, the integrated image won't be " "generated at the end of the process. You can disable this option to save a relatively modest amount of " "computation time and resources while you are trying out rejection parameters. To evaluate the quality " "of pixel rejection, you normally are only interested in rejection pixel counts and/or rejection maps.</p>" ); GenerateIntegratedImage_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); GenerateIntegratedImage_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); GenerateIntegratedImage_Sizer.Add( GenerateIntegratedImage_CheckBox ); GenerateIntegratedImage_Sizer.AddStretch(); Generate64BitResult_CheckBox.SetText( "Generate a 64-bit result image" ); Generate64BitResult_CheckBox.SetToolTip( "<p>If this option is selected, ImageIntegration will generate a " "64-bit floating point result image. Otherwise the integration result will be generated as a 32-bit " "floating point image.</p>" ); Generate64BitResult_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); Generate64BitResult_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); Generate64BitResult_Sizer.Add( Generate64BitResult_CheckBox ); Generate64BitResult_Sizer.AddStretch(); GenerateDrizzleData_CheckBox.SetText( "Generate drizzle data" ); GenerateDrizzleData_CheckBox.SetToolTip( "<p>Generate an XML drizzle data file for each integrated image.</p>" "<p>Drizzle data files contain geometrical projection parameters, pixel rejection maps, statistical data " "and metadata for the DrizzleIntegration tool. StarAlignment creates drizzle files with projection data, " "and the ImageIntegration tool appends rejection and statistical data to the same files. Drizzle files carry " "the .xdrz file suffix.</p>" ); GenerateDrizzleData_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); GenerateDrizzleData_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); GenerateDrizzleData_Sizer.Add( GenerateDrizzleData_CheckBox ); GenerateDrizzleData_Sizer.AddStretch(); SubtractPedestals_CheckBox.SetText( "Subtract pedestals" ); SubtractPedestals_CheckBox.SetToolTip( "<p>Subtract PEDESTAL keyword values, if present in input images.</p>" "<p>Some applications add small positive values (typically about 100 DN) systematically to calibrated light frames. " "<p>These small <i>pedestals</i> should be subtracted from source integration pixels to refer all input data to the " "same zero point consistently.</p>" "<p>This option should only be enabled for integration of calibrated light frames with PEDESTAL keywords. This is " "typically the case if you have no access to uncalibrated raw data, and are forced to work with data already " "calibrated in other applications.</p>" "<p>This option should be <i>disabled</i> for integration of raw bias and dark frames, since in these cases existing " "PEDESTAL keywords should be preserved in the generated master bias and dark frames. These pedestals will be " "subtracted automatically by the ImageCalibration process for calibration of flat and light frames.</p>" ); SubtractPedestals_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); SubtractPedestals_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); SubtractPedestals_Sizer.Add( SubtractPedestals_CheckBox ); SubtractPedestals_Sizer.AddStretch(); TruncateOnOutOfRange_CheckBox.SetText( "Truncate on out-of-range" ); TruncateOnOutOfRange_CheckBox.SetToolTip( "<p>If the output integrated image has saturated pixel samples out of " "the nominal [0,1] range, truncate them instead of rescaling the whole image.</p>" "<p>No out-of-range values should occur after integration of a well-calibrated data set under normal conditions. " "However, sometimes saturated pixels may lead to out-of-range values after output normalization, depending on " "the frame selected as integration reference.</p>" "<p>When this happens, the best option for integration of light or science frames is a linear rescaling, which " "preserves all of the integrated data. However, in some cases altering all pixel values is not admissible, so a " "rescaling operation is not applicable. This is the case for integration of flat frames, where truncation is the " "only option available to preserve the correct illumination profile in the integrated master flat frame.</p>" ); TruncateOnOutOfRange_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); TruncateOnOutOfRange_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); TruncateOnOutOfRange_Sizer.Add( TruncateOnOutOfRange_CheckBox ); TruncateOnOutOfRange_Sizer.AddStretch(); EvaluateNoise_CheckBox.SetText( "Evaluate noise" ); EvaluateNoise_CheckBox.SetToolTip( "<p>Evaluate the standard deviation of Gaussian noise for the final " "integrated image.</p>" "<p>Noise evaluation uses wavelet-based techniques and provides estimates to within 1% accuracy. " "This option is useful to compare the results of different integration procedures. For example, by " "comparing noise estimates you can know which image normalization and weighting criteria lead to the " "best result in terms of signal-to-noise ratio improvement.</p>" ); EvaluateNoise_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); EvaluateNoise_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); EvaluateNoise_Sizer.Add( EvaluateNoise_CheckBox ); EvaluateNoise_Sizer.AddStretch(); ClosePreviousImages_CheckBox.SetText( "Close previous images" ); ClosePreviousImages_CheckBox.SetToolTip( "<p>Select this option to close existing integration and rejection " "map images before running a new integration process. This is useful to avoid accumulation of multiple " "results on the workspace, when the same integration is being tested repeatedly.</p>" ); ClosePreviousImages_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); ClosePreviousImages_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); ClosePreviousImages_Sizer.Add( ClosePreviousImages_CheckBox ); ClosePreviousImages_Sizer.AddStretch(); AutoMemorySize_CheckBox.SetText( "Automatic buffer sizes" ); AutoMemorySize_CheckBox.SetToolTip( "<p>Use the largest possible buffer and stack sizes, calculated " "automatically from the amount of physical memory currently available to PixInsight.</p>" "<p>Usually this is the best option to optimize image integration performance, but be aware that for large " "data sets and low-memory machines (relative to the total size of the data) the process may use too many " "system resources. If you want finer control on system resources usage, disable this option and tweak the " "values of the <i>buffer size</i> and <i>stack size</i> parameters.</p>" ); AutoMemorySize_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); AutoMemorySize_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); AutoMemorySize_Sizer.Add( AutoMemorySize_CheckBox ); AutoMemorySize_Sizer.AddStretch(); const char* bufferSizeToolTip = "<p>This parameter defines the size of the working buffers used to read pixel rows. There is an " "independent buffer per input image. A reasonably large buffer size will improve performance by " "minimizing disk reading operations. The default value of 16 MiB is usually quite appropriate.</p>" "<p>Decrease this parameter if you experience out-of-memory errors during integration. This may " "be necessary for integration of large image sets on systems with low memory resources. The " "minimum value is zero, which will use a single row of pixels per input image.</p>"; BufferSize_Label.SetText( "Buffer size (MiB):" ); BufferSize_Label.SetFixedWidth( labelWidth1 ); BufferSize_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); BufferSize_Label.SetToolTip( bufferSizeToolTip ); BufferSize_SpinBox.SetRange( int( TheIIBufferSizeParameter->MinimumValue() ), int( TheIIBufferSizeParameter->MaximumValue() ) ); BufferSize_SpinBox.SetToolTip( bufferSizeToolTip ); BufferSize_SpinBox.SetFixedWidth( editWidth2 ); BufferSize_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Integration_SpinValueUpdated, w ); BufferSize_Sizer.SetSpacing( 4 ); BufferSize_Sizer.Add( BufferSize_Label ); BufferSize_Sizer.Add( BufferSize_SpinBox ); BufferSize_Sizer.AddStretch(); const char* stackSizeToolTip = "<p>This is the size of the working integration stack structure. In general, the larger this " "parameter, the better the performance, especially on multiprocessor/multicore systems.</p>" "<p>The best performance is achieved when the whole set of integrated pixels can be loaded at " "once in the integration stack. For this to happen, the following conditions must be true:</p>" "<ul>" "<li><b>Buffer size</b> must be large enough as to allow loading an input file in 32-bit floating " "point format completely with a single file read operation.</li>" "<li><b>Stack size</b> must be larger than or equal to W*H*(12*N + 4), where W and H are the image " "width and height in pixels, respectively, and N is the number of integrated images. For linear fit " "clipping rejection, replace 4 with 8 in the above equation.</li>" "</ul>" "<p>Note that this may require a large amount of RAM available for relatively large image sets. " "As an example, the default stack size of 1024 (1 GiB) is sufficient to integrate 20 2048x2048 monochrome " "images optimally with the default buffer size of 16 MiB. With a stack size of 4 GiB and a buffer size of " "64 MiB you could integrate 20 4Kx4K monochrome images with optimum performance.</p>"; StackSize_Label.SetText( "Stack size (MiB):" ); StackSize_Label.SetFixedWidth( labelWidth1 ); StackSize_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); StackSize_Label.SetToolTip( stackSizeToolTip ); // Limit to one half the parameter's maximum (500 GiB) to keep the SpinBox size within editWidth2. StackSize_SpinBox.SetRange( int( TheIIStackSizeParameter->MinimumValue() ), int( TheIIStackSizeParameter->MaximumValue() ) >> 1 ); StackSize_SpinBox.SetToolTip( stackSizeToolTip ); StackSize_SpinBox.SetFixedWidth( editWidth2 ); StackSize_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Integration_SpinValueUpdated, w ); StackSize_Sizer.SetSpacing( 4 ); StackSize_Sizer.Add( StackSize_Label ); StackSize_Sizer.Add( StackSize_SpinBox ); StackSize_Sizer.AddStretch(); UseCache_CheckBox.SetText( "Use file cache" ); UseCache_CheckBox.SetToolTip( "<p>By default, ImageIntegration generates and uses a dynamic cache of " "working image parameters, including pixel statistics and normalization data. This cache greatly " "improves performance when the same images are being integrated several times, for example to find " "optimal pixel rejection parameters.</p>" "<p>Disable this option if for some reason you don't want to use the cache. This will force " "recalculation of all statistical data required for normalization, which involves loading all " "integrated image files from disk.</p>" "<p>The file cache can also be <i>persistent</i> across PixInsight core application executions. The " "persistent cache and its options can be controlled with the ImageIntegration Preferences dialog.</p>"); UseCache_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Integration_Click, w ); Cache_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); Cache_Sizer.Add( UseCache_CheckBox ); Cache_Sizer.AddStretch(); Integration_Sizer.SetSpacing( 4 ); Integration_Sizer.Add( Combination_Sizer ); Integration_Sizer.Add( Normalization_Sizer ); Integration_Sizer.Add( AdaptiveGridSize_Sizer ); Integration_Sizer.Add( AdaptiveNoScale_Sizer ); Integration_Sizer.Add( WeightMode_Sizer ); Integration_Sizer.Add( WeightKeyword_Sizer ); Integration_Sizer.Add( WeightScale_Sizer ); Integration_Sizer.Add( IgnoreNoiseKeywords_Sizer ); Integration_Sizer.Add( GenerateIntegratedImage_Sizer ); Integration_Sizer.Add( Generate64BitResult_Sizer ); Integration_Sizer.Add( GenerateDrizzleData_Sizer ); Integration_Sizer.Add( SubtractPedestals_Sizer ); Integration_Sizer.Add( TruncateOnOutOfRange_Sizer ); Integration_Sizer.Add( EvaluateNoise_Sizer ); Integration_Sizer.Add( ClosePreviousImages_Sizer ); Integration_Sizer.Add( AutoMemorySize_Sizer ); Integration_Sizer.Add( BufferSize_Sizer ); Integration_Sizer.Add( StackSize_Sizer ); Integration_Sizer.Add( Cache_Sizer ); Integration_Control.SetSizer( Integration_Sizer ); // Rejection1_SectionBar.SetTitle( "Pixel Rejection (1)" ); Rejection1_SectionBar.SetSection( Rejection1_Control ); Rejection1_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); const char* rejectionAlgorithmToolTip = "<p>Pixel rejection algorithm</p>" "<p>The <b>iterative sigma clipping</b> algorithm is usually a good option to integrate more than " "10 or 15 images. Keep in mind that for sigma clipping to work, the standard deviation must be a good " "estimate of dispersion, which requires a sufficient number of pixels per stack (the more images the " "better).</p>" "<p><b>Winsorized sigma clipping</b> is similar to the normal sigma clipping algorithm, but uses a " "special iterative procedure based on Huber's method of robust estimation of parameters through " "<i>Winsorization</i>. This algorithm can yield superior rejection of outliers with better preservation " "of significant data for large sets of images.</p>" "<p><b>Linear fit clipping</b> fits each pixel stack to a straigtht line. The linear fit is optimized " "in the twofold sense of minimizing average absolute deviation and maximizing inliers. This rejection " "algorithm is more robust than sigma clipping for large sets of images, especially in presence of " "additive sky gradients of varying intensity and spatial distribution. For the best performance, use " "this algorithm for large sets of at least 15 images. Five images is the minimum required.</p>" "<p>The <b>Generalized Extreme Studentized Deviate (ESD) Test</b> rejection algorithm is an implementation " "of the method described by Bernard Rosner in his 1983 paper <i>Percentage Points for a Generalized ESD " "Many-Outlier procedure</i>, adapted to the image integration task. The ESD algorithm assumes that each " "pixel stack, in absence of outliers, follows an approximately normal (Gaussian) distribution. It aims at " "avoiding <i>masking</i>, a serious issue that occurs when an outlier goes undetected because its value is " "similar to another outlier. The performance of this algorithm can be excellent for large data sets of 25 " "or more images, and especially for very large sets of 50 or more frames. The minimum required is 3 images.</p>" "<p><b>Percentile clipping</b> rejection is excellent to integrate reduced sets of images, such as " "3 to 6 images. This is a single-pass algorithm that rejects pixels outside a fixed range of values " "relative to the median of each pixel stack.</p>" "<p><b>Averaged iterative sigma clipping</b> is intended for sets of 10 or more images. This algorithm " "tries to derive the gain of an ideal CCD detector from existing pixel data, assuming zero readout noise, " "then uses a Poisson noise model to perform rejection. For large sets of images however, sigma clipping " "tends to be superior.</p>" "<p>The <b>min/max</b> method can be used to ensure rejection of extreme values. Min/max performs an " "unconditional rejection of a fixed number of pixels from each stack, without any statistical basis. " "Rejection methods based on robust statistics, such as percentile, Winsorized sigma clipping, linear " "fitting and averaged sigma clipping are in general preferable.</p>" "<p>Finally, the <b>CCD noise model</b> algorithm requires unmodified (uncalibrated) data and accurate " "sensor parameters. This rejection algorithm can only be useful to integrate calibration images (bias " "frames, dark frames and flat fields).</p>"; RejectionAlgorithm_Label.SetText( "Rejection algorithm:" ); RejectionAlgorithm_Label.SetFixedWidth( labelWidth1 ); RejectionAlgorithm_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); RejectionAlgorithm_Label.SetToolTip( rejectionAlgorithmToolTip ); RejectionAlgorithm_ComboBox.AddItem( "No rejection" ); RejectionAlgorithm_ComboBox.AddItem( "Min/Max" ); RejectionAlgorithm_ComboBox.AddItem( "Percentile Clipping" ); RejectionAlgorithm_ComboBox.AddItem( "Sigma Clipping" ); RejectionAlgorithm_ComboBox.AddItem( "Winsorized Sigma Clipping" ); RejectionAlgorithm_ComboBox.AddItem( "Averaged Sigma Clipping" ); RejectionAlgorithm_ComboBox.AddItem( "Linear Fit Clipping" ); RejectionAlgorithm_ComboBox.AddItem( "CCD Noise Model" ); RejectionAlgorithm_ComboBox.AddItem( "Generalized Extreme Studentized Deviate (ESD) Test" ); RejectionAlgorithm_ComboBox.SetToolTip( rejectionAlgorithmToolTip ); RejectionAlgorithm_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&ImageIntegrationInterface::e_Rejection_ItemSelected, w ); RejectionAlgorithm_Sizer.SetSpacing( 4 ); RejectionAlgorithm_Sizer.Add( RejectionAlgorithm_Label ); RejectionAlgorithm_Sizer.Add( RejectionAlgorithm_ComboBox ); RejectionAlgorithm_Sizer.AddStretch(); const char* rejectionNormalizationToolTip = "<p>Image normalization for pixel rejection.</p>" "<p>Normalization is essential to perform a correct pixel rejection, since it ensures that the data " "from all integrated images are compatible in terms of their statistical distribution (mean background " "values and dispersion).</p>" "<p><b>Scale + zero offset</b> matches mean background values and dispersion. This involves " "multiplicative and additive transformations. This is the default rejection normalization method that " "should be used to integrate calibrated images.</p>" "<p><b>Equalize fluxes</b> simply matches the main histogram peaks of all images prior to pixel rejection. " "This is done by multiplication with the ratio of the reference median to the median of each integrated image. " "This is the method of choice to integrate sky flat fields, since in this case trying to match dispersion " "does not make sense, due to the irregular illumination distribution. For the same reason, this type of " "rejection normalization can also be useful to integrate uncalibrated images, or images suffering from " "strong gradients.</p>" "<p><b>Local normalization</b> applies per-pixel linear normalization functions previously calculated and stored " "in XNML files (.xnml file name suffix) by the LocalNormalization process. To apply this option, existing XNML " "files must be associated with input integration files. Local normalization can be the most accurate and robust " "option for rejection normalization of data sets with large variations, such as those caused by varying " "acquisition conditions, strong gradients with different orientations and intensities, or data acquired with " "different instruments. In such cases, global normalization techniques based on statistical properties of the " "whole image may be unable to make the data statistically compatible with the required locality, leading to " "inaccurate pixel rejection.</p>" "<p><b>Adaptive normalization</b> applies per-pixel additive/scaling normalization functions, computed by surface " "spline interpolation from matrices of location and two-sided scale estimates calculated for each integrated image. " "This algorithm is an alternative to local normalization that does not require auxiliary files. Adaptive " "normalization is intended to solve the same problems described for local normalization: data with strong local " "variations, especially strong gradients of varying orientations and intensities. Although local normalization is " "much more accurate and can be necessary to solve difficult problems, adaptive normalization is much easier to use " "and works well in most practical cases.</p>"; RejectionNormalization_Label.SetText( "Normalization:" ); RejectionNormalization_Label.SetFixedWidth( labelWidth1 ); RejectionNormalization_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); RejectionNormalization_Label.SetToolTip( rejectionNormalizationToolTip ); RejectionNormalization_ComboBox.AddItem( "No normalization" ); RejectionNormalization_ComboBox.AddItem( "Scale + zero offset" ); RejectionNormalization_ComboBox.AddItem( "Equalize fluxes" ); RejectionNormalization_ComboBox.AddItem( "Local normalization" ); RejectionNormalization_ComboBox.AddItem( "Adaptive normalization" ); RejectionNormalization_ComboBox.SetToolTip( rejectionNormalizationToolTip ); RejectionNormalization_ComboBox.OnItemSelected( (ComboBox::item_event_handler)&ImageIntegrationInterface::e_Rejection_ItemSelected, w ); RejectionNormalization_Sizer.SetSpacing( 4 ); RejectionNormalization_Sizer.Add( RejectionNormalization_Label ); RejectionNormalization_Sizer.Add( RejectionNormalization_ComboBox ); RejectionNormalization_Sizer.AddStretch(); GenerateRejectionMaps_CheckBox.SetText( "Generate rejection maps" ); GenerateRejectionMaps_CheckBox.SetToolTip( "<p>Rejection maps have pixel values proportional to the " "number of rejected pixels for each output pixel. Low and high rejected pixels are represented as two " "separate rejection maps, which are generated as 32-bit floating point images.</p>" "<p>Use rejection maps along with console rejection statistics to evaluate performance of pixel " "rejection parameters.</p>" ); GenerateRejectionMaps_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); GenerateRejectionMaps_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); GenerateRejectionMaps_Sizer.Add( GenerateRejectionMaps_CheckBox ); GenerateRejectionMaps_Sizer.AddStretch(); ClipLow_CheckBox.SetText( "Clip low pixels" ); ClipLow_CheckBox.SetToolTip( "<p>Enable rejection of low pixels. Low pixels have values below the median of " "a pixel stack.</p>" "<p>If this option is disabled, rejection algorithms can only reject high pixels, i.e. pixels above the median.</p>" ); ClipLow_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); ClipLow_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); ClipLow_Sizer.Add( ClipLow_CheckBox ); ClipLow_Sizer.AddStretch(); ClipHigh_CheckBox.SetText( "Clip high pixels" ); ClipHigh_CheckBox.SetToolTip( "<p>Enable rejection of high pixels. High pixels have values above the median of " "a pixel stack.</p>" "<p>If this option is disabled, rejection algorithms can only reject low pixels, i.e. pixels below the median.</p>" ); ClipHigh_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); ClipHigh_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); ClipHigh_Sizer.Add( ClipHigh_CheckBox ); ClipHigh_Sizer.AddStretch(); ClipLowRange_CheckBox.SetText( "Clip low range" ); ClipLowRange_CheckBox.SetToolTip( "<p>Enable rejection of pixels with values less than or equal to the " "<i>low rejection range</i> parameter.</p>" ); ClipLowRange_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); ClipLowRange_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); ClipLowRange_Sizer.Add( ClipLowRange_CheckBox ); ClipLowRange_Sizer.AddStretch(); ClipHighRange_CheckBox.SetText( "Clip high range" ); ClipHighRange_CheckBox.SetToolTip( "<p>Enable rejection of pixels with values greater than or equal to the " "<i>high rejection range</i> parameter.</p>" ); ClipHighRange_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); ClipHighRange_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); ClipHighRange_Sizer.Add( ClipHighRange_CheckBox ); ClipHighRange_Sizer.AddStretch(); ReportRangeRejection_CheckBox.SetText( "Report range rejection" ); ReportRangeRejection_CheckBox.SetToolTip( "<p>Include range rejected pixels in rejected pixel counts " "reported on console summaries.</p>" ); ReportRangeRejection_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); ReportRangeRejection_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); ReportRangeRejection_Sizer.Add( ReportRangeRejection_CheckBox ); ReportRangeRejection_Sizer.AddStretch(); MapRangeRejection_CheckBox.SetText( "Map range rejection" ); MapRangeRejection_CheckBox.SetToolTip( "<p>Include range rejected pixels in pixel rejection maps.</p>" ); MapRangeRejection_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); MapRangeRejection_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); MapRangeRejection_Sizer.Add( MapRangeRejection_CheckBox ); MapRangeRejection_Sizer.AddStretch(); Rejection1_Sizer.SetSpacing( 4 ); Rejection1_Sizer.Add( RejectionAlgorithm_Sizer ); Rejection1_Sizer.Add( RejectionNormalization_Sizer ); Rejection1_Sizer.Add( GenerateRejectionMaps_Sizer ); Rejection1_Sizer.Add( ClipLow_Sizer ); Rejection1_Sizer.Add( ClipHigh_Sizer ); Rejection1_Sizer.Add( ClipLowRange_Sizer ); Rejection1_Sizer.Add( ClipHighRange_Sizer ); Rejection1_Sizer.Add( ReportRangeRejection_Sizer ); Rejection1_Sizer.Add( MapRangeRejection_Sizer ); Rejection1_Control.SetSizer( Rejection1_Sizer ); // Rejection2_SectionBar.SetTitle( "Pixel Rejection (2)" ); Rejection2_SectionBar.SetSection( Rejection2_Control ); Rejection2_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); const char* minMaxLowToolTip = "<p>Number of low (dark) pixels to be rejected by the min/max algorithm.</p>"; MinMaxLow_Label.SetText( "Min/Max low:" ); MinMaxLow_Label.SetFixedWidth( labelWidth1 ); MinMaxLow_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); MinMaxLow_Label.SetToolTip( minMaxLowToolTip ); MinMaxLow_SpinBox.SetRange( int( TheIIMinMaxLowParameter->MinimumValue() ), 65536 ); MinMaxLow_SpinBox.SetToolTip( minMaxLowToolTip ); MinMaxLow_SpinBox.SetFixedWidth( editWidth2 ); MinMaxLow_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Rejection_SpinValueUpdated, w ); MinMaxLow_Sizer.SetSpacing( 4 ); MinMaxLow_Sizer.Add( MinMaxLow_Label ); MinMaxLow_Sizer.Add( MinMaxLow_SpinBox ); MinMaxLow_Sizer.AddStretch(); const char* minMaxHighToolTip = "<p>Number of high (bright) pixels to be rejected by the min/max algorithm.</p>"; MinMaxHigh_Label.SetText( "Min/Max high:" ); MinMaxHigh_Label.SetFixedWidth( labelWidth1 ); MinMaxHigh_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); MinMaxHigh_Label.SetToolTip( minMaxHighToolTip ); MinMaxHigh_SpinBox.SetRange( int( TheIIMinMaxHighParameter->MinimumValue() ), 65536 ); MinMaxHigh_SpinBox.SetToolTip( minMaxHighToolTip ); MinMaxHigh_SpinBox.SetFixedWidth( editWidth2 ); MinMaxHigh_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Rejection_SpinValueUpdated, w ); MinMaxHigh_Sizer.SetSpacing( 4 ); MinMaxHigh_Sizer.Add( MinMaxHigh_Label ); MinMaxHigh_Sizer.Add( MinMaxHigh_SpinBox ); MinMaxHigh_Sizer.AddStretch(); PercentileLow_NumericControl.label.SetText( "Percentile low:" ); PercentileLow_NumericControl.label.SetFixedWidth( labelWidth1 ); PercentileLow_NumericControl.slider.SetRange( 0, 100 ); PercentileLow_NumericControl.slider.SetScaledMinWidth( 250 ); PercentileLow_NumericControl.SetReal(); PercentileLow_NumericControl.SetRange( TheIIPercentileLowParameter->MinimumValue(), TheIIPercentileLowParameter->MaximumValue() ); PercentileLow_NumericControl.SetPrecision( TheIIPercentileLowParameter->Precision() ); PercentileLow_NumericControl.edit.SetFixedWidth( editWidth2 ); PercentileLow_NumericControl.SetToolTip( "<p>Low clipping factor for the percentile clipping rejection algorithm.</p>" ); PercentileLow_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); PercentileHigh_NumericControl.label.SetText( "Percentile high:" ); PercentileHigh_NumericControl.label.SetFixedWidth( labelWidth1 ); PercentileHigh_NumericControl.slider.SetRange( 0, 100 ); PercentileHigh_NumericControl.slider.SetScaledMinWidth( 250 ); PercentileHigh_NumericControl.SetReal(); PercentileHigh_NumericControl.SetRange( TheIIPercentileHighParameter->MinimumValue(), TheIIPercentileHighParameter->MaximumValue() ); PercentileHigh_NumericControl.SetPrecision( TheIIPercentileHighParameter->Precision() ); PercentileHigh_NumericControl.edit.SetFixedWidth( editWidth2 ); PercentileHigh_NumericControl.SetToolTip( "<p>High clipping factor for the percentile clipping rejection algorithm.</p>" ); PercentileHigh_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); SigmaLow_NumericControl.label.SetText( "Sigma low:" ); SigmaLow_NumericControl.label.SetFixedWidth( labelWidth1 ); SigmaLow_NumericControl.slider.SetRange( 0, 100 ); SigmaLow_NumericControl.slider.SetScaledMinWidth( 250 ); SigmaLow_NumericControl.SetReal(); SigmaLow_NumericControl.SetRange( TheIISigmaLowParameter->MinimumValue(), TheIISigmaLowParameter->MaximumValue() ); SigmaLow_NumericControl.SetPrecision( TheIISigmaLowParameter->Precision() ); SigmaLow_NumericControl.edit.SetFixedWidth( editWidth2 ); SigmaLow_NumericControl.SetToolTip( "<p>Low sigma clipping factor for the sigma clipping and averaged sigma clipping " "rejection algorithms.</p>" ); SigmaLow_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); SigmaHigh_NumericControl.label.SetText( "Sigma high:" ); SigmaHigh_NumericControl.label.SetFixedWidth( labelWidth1 ); SigmaHigh_NumericControl.slider.SetRange( 0, 100 ); SigmaHigh_NumericControl.slider.SetScaledMinWidth( 250 ); SigmaHigh_NumericControl.SetReal(); SigmaHigh_NumericControl.SetRange( TheIISigmaHighParameter->MinimumValue(), TheIISigmaHighParameter->MaximumValue() ); SigmaHigh_NumericControl.SetPrecision( TheIISigmaHighParameter->Precision() ); SigmaHigh_NumericControl.edit.SetFixedWidth( editWidth2 ); SigmaHigh_NumericControl.SetToolTip( "<p>High sigma clipping factor for the sigma clipping and averaged sigma clipping " "rejection algorithms.</p>" ); SigmaHigh_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); WinsorizationCutoff_NumericControl.label.SetText( "Winsorization cutoff:" ); WinsorizationCutoff_NumericControl.label.SetFixedWidth( labelWidth1 ); WinsorizationCutoff_NumericControl.slider.SetRange( 30, 100 ); WinsorizationCutoff_NumericControl.slider.SetScaledMinWidth( 250 ); WinsorizationCutoff_NumericControl.SetReal(); WinsorizationCutoff_NumericControl.SetRange( TheIIWinsorizationCutoffParameter->MinimumValue(), TheIIWinsorizationCutoffParameter->MaximumValue() ); WinsorizationCutoff_NumericControl.SetPrecision( TheIIWinsorizationCutoffParameter->Precision() ); WinsorizationCutoff_NumericControl.edit.SetFixedWidth( editWidth2 ); WinsorizationCutoff_NumericControl.SetToolTip( "<p>Cutoff point for the Winsorized sigma clipping rejection algorithm, " "in sigma units.</p>" "<p>All pixel samples with absolute differences from the median larger than this parameter will be set equal to the median " "of the pixel stack in the first rejection iteration. This replaces extreme outliers, such as cosmics, hot and cold pixels, " "with plausible values instead of their nearest neighbors.</p>" ); WinsorizationCutoff_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); LinearFitLow_NumericControl.label.SetText( "Linear fit low:" ); LinearFitLow_NumericControl.label.SetFixedWidth( labelWidth1 ); LinearFitLow_NumericControl.slider.SetRange( 0, 100 ); LinearFitLow_NumericControl.slider.SetScaledMinWidth( 250 ); LinearFitLow_NumericControl.SetReal(); LinearFitLow_NumericControl.SetRange( TheIILinearFitLowParameter->MinimumValue(), TheIILinearFitLowParameter->MaximumValue() ); LinearFitLow_NumericControl.SetPrecision( TheIILinearFitLowParameter->Precision() ); LinearFitLow_NumericControl.edit.SetFixedWidth( editWidth2 ); LinearFitLow_NumericControl.SetToolTip( "<p>Tolerance of the linear fit clipping algorithm for low pixel values, in sigma units.</p>" ); LinearFitLow_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); LinearFitHigh_NumericControl.label.SetText( "Linear fit high:" ); LinearFitHigh_NumericControl.label.SetFixedWidth( labelWidth1 ); LinearFitHigh_NumericControl.slider.SetRange( 0, 100 ); LinearFitHigh_NumericControl.slider.SetScaledMinWidth( 250 ); LinearFitHigh_NumericControl.SetReal(); LinearFitHigh_NumericControl.SetRange( TheIILinearFitHighParameter->MinimumValue(), TheIILinearFitHighParameter->MaximumValue() ); LinearFitHigh_NumericControl.SetPrecision( TheIILinearFitHighParameter->Precision() ); LinearFitHigh_NumericControl.edit.SetFixedWidth( editWidth2 ); LinearFitHigh_NumericControl.SetToolTip( "<p>Tolerance of the linear fit clipping algorithm for high pixel values, in sigma units.</p>" ); LinearFitHigh_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); ESDOutliersFraction_NumericControl.label.SetText( "ESD outliers:" ); ESDOutliersFraction_NumericControl.label.SetFixedWidth( labelWidth1 ); ESDOutliersFraction_NumericControl.slider.SetRange( 0, 100 ); ESDOutliersFraction_NumericControl.slider.SetScaledMinWidth( 250 ); ESDOutliersFraction_NumericControl.SetReal(); ESDOutliersFraction_NumericControl.SetRange( TheIIESDOutliersFractionParameter->MinimumValue(), TheIIESDOutliersFractionParameter->MaximumValue() ); ESDOutliersFraction_NumericControl.SetPrecision( TheIIESDOutliersFractionParameter->Precision() ); ESDOutliersFraction_NumericControl.edit.SetFixedWidth( editWidth2 ); ESDOutliersFraction_NumericControl.SetToolTip( "<p>Expected maximum fraction of outliers for the generalized " "ESD rejection algorithm.</p>" "<p>For example, a value of 0.2 applied to a stack of 10 pixels means that the ESD algorithm will be limited " "to detect a maximum of two outlier pixels, or in other words, only 0, 1 or 2 outliers will be detectable in " "such case. The default value is 0.3, which allows the algorithm to detect up to a 30% of outlier pixels in " "each pixel stack.</p>" ); ESDOutliersFraction_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); ESDAlpha_NumericControl.label.SetText( "ESD significance:" ); ESDAlpha_NumericControl.label.SetFixedWidth( labelWidth1 ); ESDAlpha_NumericControl.slider.SetRange( 0, 100 ); ESDAlpha_NumericControl.slider.SetScaledMinWidth( 250 ); ESDAlpha_NumericControl.SetReal(); ESDAlpha_NumericControl.SetRange( TheIIESDAlphaParameter->MinimumValue(), TheIIESDAlphaParameter->MaximumValue() ); ESDAlpha_NumericControl.SetPrecision( TheIIESDAlphaParameter->Precision() ); ESDAlpha_NumericControl.edit.SetFixedWidth( editWidth2 ); ESDAlpha_NumericControl.SetToolTip( "<p>Probability of making a type I error (false positive) in the generalized " "ESD rejection algorithm.</p>" "<p>This is the significance level of the outlier detection hypothesis test. For example, a significance level " "of 0.01 means that a 1% chance of being wrong when rejecting the null hypothesis (that there are no outliers in " "a given pixel stack) is acceptable. The default value is 0.05 (5% significance level).</p>" "<p>By increasing this parameter the ESD algorithm will tend to reject more pixels in each stack. The effect of " "increasing this parameter is similar to reducing the threshold of a sigma clipping algorithm (although the " "underlying mechanism is very different).</p>" ); ESDAlpha_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); ESDLowRelaxation_NumericControl.label.SetText( "ESD low relaxation:" ); ESDLowRelaxation_NumericControl.label.SetFixedWidth( labelWidth1 ); ESDLowRelaxation_NumericControl.slider.SetRange( 0, 50 ); ESDLowRelaxation_NumericControl.slider.SetScaledMinWidth( 250 ); ESDLowRelaxation_NumericControl.SetReal(); ESDLowRelaxation_NumericControl.SetRange( TheIIESDLowRelaxationParameter->MinimumValue(), TheIIESDLowRelaxationParameter->MaximumValue() ); ESDLowRelaxation_NumericControl.SetPrecision( TheIIESDLowRelaxationParameter->Precision() ); ESDLowRelaxation_NumericControl.edit.SetFixedWidth( editWidth2 ); ESDLowRelaxation_NumericControl.SetToolTip( "<p>Relaxation factor for ESD rejection of low pixels.</p>" "<p>The larger the value of this parameter, the more permissive the ESD algorithm will be for rejection of pixels " "with values below the median of each stack. This can be useful to reject less dark pixels on sky background areas " "and extended nebular regions, where high dispersion induced by noise may lead to excessive detection of false " "outliers.</p>" ); ESDLowRelaxation_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); RangeLow_NumericControl.label.SetText( "Range low:" ); RangeLow_NumericControl.label.SetFixedWidth( labelWidth1 ); RangeLow_NumericControl.slider.SetRange( 0, 100 ); RangeLow_NumericControl.slider.SetScaledMinWidth( 250 ); RangeLow_NumericControl.SetReal(); RangeLow_NumericControl.SetRange( TheIIRangeLowParameter->MinimumValue(), TheIIRangeLowParameter->MaximumValue() ); RangeLow_NumericControl.SetPrecision( TheIIRangeLowParameter->Precision() ); RangeLow_NumericControl.edit.SetFixedWidth( editWidth2 ); RangeLow_NumericControl.SetToolTip( "<p>Low rejection range. If the <i>clip low range</i> option is enabled, " "all pixels with values less than or equal to this low rejection range parameter will be rejected.</p>" ); RangeLow_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); RangeHigh_NumericControl.label.SetText( "Range high:" ); RangeHigh_NumericControl.label.SetFixedWidth( labelWidth1 ); RangeHigh_NumericControl.slider.SetRange( 0, 100 ); RangeHigh_NumericControl.slider.SetScaledMinWidth( 250 ); RangeHigh_NumericControl.SetReal(); RangeHigh_NumericControl.SetRange( TheIIRangeHighParameter->MinimumValue(), TheIIRangeHighParameter->MaximumValue() ); RangeHigh_NumericControl.SetPrecision( TheIIRangeHighParameter->Precision() ); RangeHigh_NumericControl.edit.SetFixedWidth( editWidth2 ); RangeHigh_NumericControl.SetToolTip( "<p>High rejection range. If the <i>clip high range</i> option is enabled, " "all pixels with values greater than or equal to this high rejection range parameter will be rejected.</p>" ); RangeHigh_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); Rejection2_Sizer.SetSpacing( 4 ); Rejection2_Sizer.Add( MinMaxLow_Sizer ); Rejection2_Sizer.Add( MinMaxHigh_Sizer ); Rejection2_Sizer.Add( PercentileLow_NumericControl ); Rejection2_Sizer.Add( PercentileHigh_NumericControl ); Rejection2_Sizer.Add( SigmaLow_NumericControl ); Rejection2_Sizer.Add( SigmaHigh_NumericControl ); Rejection2_Sizer.Add( WinsorizationCutoff_NumericControl ); Rejection2_Sizer.Add( LinearFitLow_NumericControl ); Rejection2_Sizer.Add( LinearFitHigh_NumericControl ); Rejection2_Sizer.Add( ESDOutliersFraction_NumericControl ); Rejection2_Sizer.Add( ESDAlpha_NumericControl ); Rejection2_Sizer.Add( ESDLowRelaxation_NumericControl ); Rejection2_Sizer.Add( RangeLow_NumericControl ); Rejection2_Sizer.Add( RangeHigh_NumericControl ); Rejection2_Control.SetSizer( Rejection2_Sizer ); // Rejection3_SectionBar.SetTitle( "Pixel Rejection (3)" ); Rejection3_SectionBar.SetSection( Rejection3_Control ); Rejection3_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); CCDGain_NumericControl.label.SetText( "CCD gain:" ); CCDGain_NumericControl.label.SetFixedWidth( labelWidth1 ); CCDGain_NumericControl.slider.SetRange( 0, 100 ); CCDGain_NumericControl.slider.SetScaledMinWidth( 250 ); CCDGain_NumericControl.SetReal(); CCDGain_NumericControl.SetRange( TheIICCDGainParameter->MinimumValue(), TheIICCDGainParameter->MaximumValue() ); CCDGain_NumericControl.SetPrecision( TheIICCDGainParameter->Precision() ); CCDGain_NumericControl.edit.SetFixedWidth( editWidth2 ); CCDGain_NumericControl.SetToolTip( "<p>CCD sensor gain in electrons per data number (e-/ADU). Only used by the CCD noise " "clipping rejection algorithm.</p>" ); CCDGain_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); CCDReadNoise_NumericControl.label.SetText( "CCD readout noise:" ); CCDReadNoise_NumericControl.label.SetFixedWidth( labelWidth1 ); CCDReadNoise_NumericControl.slider.SetRange( 0, 100 ); CCDReadNoise_NumericControl.slider.SetScaledMinWidth( 250 ); CCDReadNoise_NumericControl.SetReal(); CCDReadNoise_NumericControl.SetRange( TheIICCDReadNoiseParameter->MinimumValue(), TheIICCDReadNoiseParameter->MaximumValue() ); CCDReadNoise_NumericControl.SetPrecision( TheIICCDReadNoiseParameter->Precision() ); CCDReadNoise_NumericControl.edit.SetFixedWidth( editWidth2 ); CCDReadNoise_NumericControl.SetToolTip( "<p>CCD readout noise in electrons. Only used by the CCD noise " "clipping rejection algorithm.</p>" ); CCDReadNoise_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); CCDScaleNoise_NumericControl.label.SetText( "CCD scale noise:" ); CCDScaleNoise_NumericControl.label.SetFixedWidth( labelWidth1 ); CCDScaleNoise_NumericControl.slider.SetRange( 0, 100 ); CCDScaleNoise_NumericControl.slider.SetScaledMinWidth( 250 ); CCDScaleNoise_NumericControl.SetReal(); CCDScaleNoise_NumericControl.SetRange( TheIICCDScaleNoiseParameter->MinimumValue(), TheIICCDScaleNoiseParameter->MaximumValue() ); CCDScaleNoise_NumericControl.SetPrecision( TheIICCDScaleNoiseParameter->Precision() ); CCDScaleNoise_NumericControl.edit.SetFixedWidth( editWidth2 ); CCDScaleNoise_NumericControl.SetToolTip( "<p>CCD <i>scale noise</i> (AKA <i>sensitivity noise</i>). This is a " "dimensionless factor, only used by the CCD noise clipping rejection algorithm. Scale noise typically comes " "from noise introduced during flat fielding.</p>" ); CCDScaleNoise_NumericControl.OnValueUpdated( (NumericEdit::value_event_handler)&ImageIntegrationInterface::e_Rejection_EditValueUpdated, w ); Rejection3_Sizer.SetSpacing( 4 ); Rejection3_Sizer.Add( CCDGain_NumericControl ); Rejection3_Sizer.Add( CCDReadNoise_NumericControl ); Rejection3_Sizer.Add( CCDScaleNoise_NumericControl ); Rejection3_Control.SetSizer( Rejection3_Sizer ); // LargeScaleRejection_SectionBar.SetTitle( "Large-Scale Pixel Rejection" ); LargeScaleRejection_SectionBar.SetSection( LargeScaleRejection_Control ); LargeScaleRejection_SectionBar.SetToolTip( "<p>Large-scale pixel rejection uses multiscale analysis techniques to detect structures " "of rejected pixels. These structures are grown to cover borderline regions where high uncertainty may lead to insufficient rejection " "by statistical pixel rejection algorithms.</p>" "<p>This feature is very efficient to improve rejection of plane and satellite trails and flashes. With large-scale high pixel rejection " "enabled, you can be sure these artifacts will be correctly rejected without needing to reduce clipping factors, which in turn allows " "for more accurate rejection with inclusion of more signal in the integrated result. Large-scale low rejection may be useful to remove " "dust motes and other relatively large dark artifacts.</p>" ); LargeScaleRejection_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); RejectLargeScaleLow_CheckBox.SetText( "Reject low large-scale structures" ); RejectLargeScaleLow_CheckBox.SetToolTip( "<p>Enable large-scale rejection for low pixels. A low pixel sample has a value below the " "estimated central value of its pixel stack.</p>" ); RejectLargeScaleLow_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); RejectLargeScaleLow_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); RejectLargeScaleLow_Sizer.Add( RejectLargeScaleLow_CheckBox ); RejectLargeScaleLow_Sizer.AddStretch(); const char* smallScaleLayersLowToolTip = "<p>Number of small-scale layers that will be excluded from large-scale low pixel " "rejection maps. Increase this value to detect larger groups of contiguous rejected pixels. Excluding too few layers may lead to " "excessive (unnecessary) large-scale rejection. Excluding too many layers may lead to insufficient large-scale rejection. The " "default value of two layers is generally a good compromise.</p>"; SmallScaleLayersLow_Label.SetText( "Layers (low):" ); SmallScaleLayersLow_Label.SetFixedWidth( labelWidth1 ); SmallScaleLayersLow_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); SmallScaleLayersLow_Label.SetToolTip( smallScaleLayersLowToolTip ); SmallScaleLayersLow_SpinBox.SetRange( int( TheIILargeScaleClipHighProtectedLayersParameter->MinimumValue() ), int( TheIILargeScaleClipHighProtectedLayersParameter->MaximumValue() ) ); SmallScaleLayersLow_SpinBox.SetToolTip( smallScaleLayersLowToolTip ); SmallScaleLayersLow_SpinBox.SetFixedWidth( editWidth2 ); SmallScaleLayersLow_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Rejection_SpinValueUpdated, w ); SmallScaleLayersLow_Sizer.SetSpacing( 4 ); SmallScaleLayersLow_Sizer.Add( SmallScaleLayersLow_Label ); SmallScaleLayersLow_Sizer.Add( SmallScaleLayersLow_SpinBox ); SmallScaleLayersLow_Sizer.AddStretch(); const char* growthLowToolTip = "<p>Growth of large-scale pixel rejection structures. Increase to extend rejection to more " "adjacent pixels. Excessive growth will reject too many pixels unnecessarily around large-scale structures, such as plane trails. " "Insufficient growth will leave unrejected pixels on high-uncertainty regions. The default value of two pixels is generally a " "good option.</p>"; GrowthLow_Label.SetText( "Growth (low):" ); GrowthLow_Label.SetFixedWidth( labelWidth1 ); GrowthLow_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); GrowthLow_Label.SetToolTip( growthLowToolTip ); GrowthLow_SpinBox.SetRange( int( TheIILargeScaleClipHighGrowthParameter->MinimumValue() ), int( TheIILargeScaleClipHighGrowthParameter->MaximumValue() ) ); GrowthLow_SpinBox.SetToolTip( growthLowToolTip ); GrowthLow_SpinBox.SetFixedWidth( editWidth2 ); GrowthLow_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Rejection_SpinValueUpdated, w ); GrowthLow_Sizer.SetSpacing( 4 ); GrowthLow_Sizer.Add( GrowthLow_Label ); GrowthLow_Sizer.Add( GrowthLow_SpinBox ); GrowthLow_Sizer.AddStretch(); RejectLargeScaleHigh_CheckBox.SetText( "Reject high large-scale structures" ); RejectLargeScaleHigh_CheckBox.SetToolTip( "<p>Enable large-scale rejection for high pixels. A high pixel sample has a value above the " "estimated central value of its pixel stack.</p>" ); RejectLargeScaleHigh_CheckBox.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_Rejection_Click, w ); RejectLargeScaleHigh_Sizer.AddUnscaledSpacing( labelWidth1 + ui4 ); RejectLargeScaleHigh_Sizer.Add( RejectLargeScaleHigh_CheckBox ); RejectLargeScaleHigh_Sizer.AddStretch(); const char* smallScaleLayersHighToolTip = "<p>Number of small-scale layers that will be excluded from large-scale high pixel " "rejection maps. Increase this value to detect larger groups of contiguous rejected pixels. Excluding too few layers may lead to " "excessive (unnecessary) large-scale rejection. Excluding too many layers may lead to insufficient large-scale rejection. The " "default value of two layers is generally a good compromise.</p>"; SmallScaleLayersHigh_Label.SetText( "Layers (high):" ); SmallScaleLayersHigh_Label.SetFixedWidth( labelWidth1 ); SmallScaleLayersHigh_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); SmallScaleLayersHigh_Label.SetToolTip( smallScaleLayersHighToolTip ); SmallScaleLayersHigh_SpinBox.SetRange( int( TheIILargeScaleClipHighProtectedLayersParameter->MinimumValue() ), int( TheIILargeScaleClipHighProtectedLayersParameter->MaximumValue() ) ); SmallScaleLayersHigh_SpinBox.SetToolTip( smallScaleLayersHighToolTip ); SmallScaleLayersHigh_SpinBox.SetFixedWidth( editWidth2 ); SmallScaleLayersHigh_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Rejection_SpinValueUpdated, w ); SmallScaleLayersHigh_Sizer.SetSpacing( 4 ); SmallScaleLayersHigh_Sizer.Add( SmallScaleLayersHigh_Label ); SmallScaleLayersHigh_Sizer.Add( SmallScaleLayersHigh_SpinBox ); SmallScaleLayersHigh_Sizer.AddStretch(); const char* growthHighToolTip = "<p>Growth of large-scale pixel rejection structures. Increase to extend rejection to more " "adjacent pixels. Excessive growth will reject too many pixels unnecessarily around large-scale structures, such as plane trails. " "Insufficient growth will leave unrejected pixels on high-uncertainty regions. The default value of two pixels is generally a " "good option.</p>"; GrowthHigh_Label.SetText( "Growth (high):" ); GrowthHigh_Label.SetFixedWidth( labelWidth1 ); GrowthHigh_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); GrowthHigh_Label.SetToolTip( growthHighToolTip ); GrowthHigh_SpinBox.SetRange( int( TheIILargeScaleClipHighGrowthParameter->MinimumValue() ), int( TheIILargeScaleClipHighGrowthParameter->MaximumValue() ) ); GrowthHigh_SpinBox.SetToolTip( growthHighToolTip ); GrowthHigh_SpinBox.SetFixedWidth( editWidth2 ); GrowthHigh_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_Rejection_SpinValueUpdated, w ); GrowthHigh_Sizer.SetSpacing( 4 ); GrowthHigh_Sizer.Add( GrowthHigh_Label ); GrowthHigh_Sizer.Add( GrowthHigh_SpinBox ); GrowthHigh_Sizer.AddStretch(); LargeScaleRejection_Sizer.SetSpacing( 4 ); LargeScaleRejection_Sizer.Add( RejectLargeScaleLow_Sizer ); LargeScaleRejection_Sizer.Add( SmallScaleLayersLow_Sizer ); LargeScaleRejection_Sizer.Add( GrowthLow_Sizer ); LargeScaleRejection_Sizer.Add( RejectLargeScaleHigh_Sizer ); LargeScaleRejection_Sizer.Add( SmallScaleLayersHigh_Sizer ); LargeScaleRejection_Sizer.Add( GrowthHigh_Sizer ); LargeScaleRejection_Control.SetSizer( LargeScaleRejection_Sizer ); // ROI_SectionBar.SetTitle( "Region of Interest" ); ROI_SectionBar.EnableTitleCheckBox(); ROI_SectionBar.SetSection( ROI_Control ); ROI_SectionBar.OnCheck( (SectionBar::check_event_handler)&ImageIntegrationInterface::e_ROI_Check, w ); ROI_SectionBar.OnToggleSection( (SectionBar::section_event_handler)&ImageIntegrationInterface::e_ToggleSection, w ); ROI_SectionBar.OnViewDrag( (Control::view_drag_event_handler)&ImageIntegrationInterface::e_ViewDrag, w ); ROI_SectionBar.OnViewDrop( (Control::view_drop_event_handler)&ImageIntegrationInterface::e_ViewDrop, w ); const char* roiX0ToolTip = "<p>X pixel coordinate of the upper-left corner of the ROI.</p>"; ROIX0_Label.SetText( "Left:" ); ROIX0_Label.SetFixedWidth( labelWidth1 ); ROIX0_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIX0_Label.SetToolTip( roiX0ToolTip ); ROIX0_SpinBox.SetRange( 0, int_max ); //ROIX0_SpinBox.SetFixedWidth( spinWidth1 ); ROIX0_SpinBox.SetToolTip( roiX0ToolTip ); ROIX0_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_ROI_SpinValueUpdated, w ); ROIX0_Sizer.SetSpacing( 4 ); ROIX0_Sizer.Add( ROIX0_Label ); ROIX0_Sizer.Add( ROIX0_SpinBox ); ROIX0_Sizer.AddStretch(); const char* roiY0ToolTip = "<p>Y pixel coordinate of the upper-left corner of the ROI.</p>"; ROIY0_Label.SetText( "Top:" ); ROIY0_Label.SetFixedWidth( labelWidth1 ); ROIY0_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIY0_Label.SetToolTip( roiY0ToolTip ); ROIY0_SpinBox.SetRange( 0, int_max ); //ROIY0_SpinBox.SetFixedWidth( spinWidth1 ); ROIY0_SpinBox.SetToolTip( roiY0ToolTip ); ROIY0_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_ROI_SpinValueUpdated, w ); ROIY0_Sizer.SetSpacing( 4 ); ROIY0_Sizer.Add( ROIY0_Label ); ROIY0_Sizer.Add( ROIY0_SpinBox ); ROIY0_Sizer.AddStretch(); const char* roiWidthToolTip = "<p>Width of the ROI in pixels.</p>"; ROIWidth_Label.SetText( "Width:" ); ROIWidth_Label.SetFixedWidth( labelWidth1 ); ROIWidth_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIWidth_Label.SetToolTip( roiWidthToolTip ); ROIWidth_SpinBox.SetRange( 0, int_max ); //ROIWidth_SpinBox.SetFixedWidth( spinWidth1 ); ROIWidth_SpinBox.SetToolTip( roiWidthToolTip ); ROIWidth_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_ROI_SpinValueUpdated, w ); ROIWidth_Sizer.SetSpacing( 4 ); ROIWidth_Sizer.Add( ROIWidth_Label ); ROIWidth_Sizer.Add( ROIWidth_SpinBox ); ROIWidth_Sizer.AddStretch(); const char* roiHeightToolTip = "<p>Height of the ROI in pixels.</p>"; ROIHeight_Label.SetText( "Height:" ); ROIHeight_Label.SetFixedWidth( labelWidth1 ); ROIHeight_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ROIHeight_Label.SetToolTip( roiHeightToolTip ); ROIHeight_SpinBox.SetRange( 0, int_max ); //ROIHeight_SpinBox.SetFixedWidth( spinWidth1 ); ROIHeight_SpinBox.SetToolTip( roiHeightToolTip ); ROIHeight_SpinBox.OnValueUpdated( (SpinBox::value_event_handler)&ImageIntegrationInterface::e_ROI_SpinValueUpdated, w ); SelectPreview_Button.SetText( "From Preview" ); SelectPreview_Button.SetToolTip( "<p>Import ROI coordinates from an existing preview.</p>" ); SelectPreview_Button.OnClick( (Button::click_event_handler)&ImageIntegrationInterface::e_ROI_Click, w ); SelectPreview_Button.OnViewDrag( (Control::view_drag_event_handler)&ImageIntegrationInterface::e_ViewDrag, w ); SelectPreview_Button.OnViewDrop( (Control::view_drop_event_handler)&ImageIntegrationInterface::e_ViewDrop, w ); ROIHeight_Sizer.SetSpacing( 4 ); ROIHeight_Sizer.Add( ROIHeight_Label ); ROIHeight_Sizer.Add( ROIHeight_SpinBox ); ROIHeight_Sizer.AddStretch(); ROIHeight_Sizer.Add( SelectPreview_Button ); ROI_Sizer.SetSpacing( 4 ); ROI_Sizer.Add( ROIX0_Sizer ); ROI_Sizer.Add( ROIY0_Sizer ); ROI_Sizer.Add( ROIWidth_Sizer ); ROI_Sizer.Add( ROIHeight_Sizer ); ROI_Control.SetSizer( ROI_Sizer ); ROI_Control.OnViewDrag( (Control::view_drag_event_handler)&ImageIntegrationInterface::e_ViewDrag, w ); ROI_Control.OnViewDrop( (Control::view_drop_event_handler)&ImageIntegrationInterface::e_ViewDrop, w ); // Global_Sizer.SetMargin( 8 ); Global_Sizer.SetSpacing( 6 ); Global_Sizer.Add( InputImages_SectionBar ); Global_Sizer.Add( InputImages_Control ); Global_Sizer.Add( FormatHints_SectionBar ); Global_Sizer.Add( FormatHints_Control ); Global_Sizer.Add( Integration_SectionBar ); Global_Sizer.Add( Integration_Control ); Global_Sizer.Add( Rejection1_SectionBar ); Global_Sizer.Add( Rejection1_Control ); Global_Sizer.Add( Rejection2_SectionBar ); Global_Sizer.Add( Rejection2_Control ); Global_Sizer.Add( Rejection3_SectionBar ); Global_Sizer.Add( Rejection3_Control ); Global_Sizer.Add( LargeScaleRejection_SectionBar ); Global_Sizer.Add( LargeScaleRejection_Control ); Global_Sizer.Add( ROI_SectionBar ); Global_Sizer.Add( ROI_Control ); w.SetSizer( Global_Sizer ); w.EnsureLayoutUpdated(); w.AdjustToContents(); w.SetFixedWidth(); FormatHints_Control.Hide(); Rejection1_Control.Hide(); Rejection2_Control.Hide(); Rejection3_Control.Hide(); LargeScaleRejection_Control.Hide(); ROI_Control.Hide(); w.AdjustToContents(); } // ---------------------------------------------------------------------------- } // pcl // ---------------------------------------------------------------------------- // EOF ImageIntegrationInterface.cpp - Released 2021-04-09T19:41:48Z
51.265113
151
0.721137
[ "geometry", "model" ]
80e1591d4de27fa4e1ecf0d4907b912e799ea49c
6,045
cpp
C++
main.cpp
duzenko/opengl_sky
4137da35b205c292267a4b1a39b400632dd57008
[ "MIT" ]
null
null
null
main.cpp
duzenko/opengl_sky
4137da35b205c292267a4b1a39b400632dd57008
[ "MIT" ]
null
null
null
main.cpp
duzenko/opengl_sky
4137da35b205c292267a4b1a39b400632dd57008
[ "MIT" ]
null
null
null
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string> #include "utils.h" #include "glsl.h" // OpenGL Helpers void glAssert( unsigned int obj, GLenum statusType, void ( APIENTRY* ivFun )( GLuint, GLenum, GLint* ), void ( APIENTRY* infoLogFun )( GLuint, GLsizei, GLsizei*, GLchar* ) ) { GLint statusCode = GL_FALSE; ivFun( obj, statusType, &statusCode ); if ( statusCode == GL_TRUE ) { return; } GLint length = 0; ivFun( obj, GL_INFO_LOG_LENGTH, &length ); char* error_log = (char*) alloca( length ); infoLogFun( obj, length, &length, &error_log[0] ); fprintf( stderr, "%s\n", error_log ); //free( error_log ); exit( 0 ); } // Structures typedef struct { float x, y, z, r, r2; double px, py; } gamestate; typedef struct { unsigned int program; int P, RX, RY, M, aspectRatio, time; } entity; typedef struct { entity* entities; unsigned int entity_count; gamestate state; bool paused; } scene; std::string title = "Loading..."; unsigned int makeShader( const char* code, GLenum shaderType ) { unsigned int shader = glCreateShader( shaderType ); glShaderSource( shader, 1, &code, NULL ); glCompileShader( shader ); glAssert( shader, GL_COMPILE_STATUS, glGetShaderiv, glGetShaderInfoLog ); return shader; } unsigned int makeProgram( const char* vertexShaderSource, const char* fragmentShaderSource ) { unsigned int vertexShader = vertexShaderSource ? makeShader( vertexShaderSource, GL_VERTEX_SHADER ) : 0; unsigned int fragmentShader = fragmentShaderSource ? makeShader( fragmentShaderSource, GL_FRAGMENT_SHADER ) : 0; unsigned int program = glCreateProgram(); if ( vertexShader ) { glAttachShader( program, vertexShader ); } if ( fragmentShader ) { glAttachShader( program, fragmentShader ); } glLinkProgram( program ); glAssert( program, GL_LINK_STATUS, glGetProgramiv, glGetProgramInfoLog ); if ( vertexShader ) { glDetachShader( program, vertexShader ); } if ( vertexShader ) { glDeleteShader( vertexShader ); } if ( fragmentShader ) { glDetachShader( program, fragmentShader ); } if ( fragmentShader ) { glDeleteShader( fragmentShader ); } return program; } // Entities entity makeEntity( scene* s, const char* vs, const char* fs ) { entity e; // Load Program e.program = makeProgram( vs, fs ); e.P = glGetUniformLocation( e.program, "P" ); e.RX = glGetUniformLocation( e.program, "RX" ); e.RY = glGetUniformLocation( e.program, "RY" ); e.M = glGetUniformLocation( e.program, "M" ); e.aspectRatio = glGetUniformLocation( e.program, "aspectRatio" ); e.time = glGetUniformLocation( e.program, "time" ); s->entities = (entity*) realloc( s->entities, ++s->entity_count * sizeof( entity ) ); memcpy( &s->entities[s->entity_count - 1], &e, sizeof( entity ) ); return e; } void renderEntity( entity e, matrix P, matrix RX, matrix RY, float time, float aspectRatio ) { glUseProgram( e.program ); glUniformMatrix4fv( e.P, 1, GL_FALSE, P.m ); glUniformMatrix4fv( e.RX, 1, GL_FALSE, RX.m ); glUniformMatrix4fv( e.RY, 1, GL_FALSE, RY.m ); glUniform1f( e.time, time ); glUniform1f( e.aspectRatio, aspectRatio ); glBegin( GL_TRIANGLE_STRIP ); glVertex2f( -1.0, 1.0 ); glVertex2f( -1.0, -1.0 ); glVertex2f( 1.0, 1.0 ); glVertex2f( 1.0, -1.0 ); glEnd(); } void deleteEntity( entity e ) { glDeleteProgram( e.program ); } // Scene scene s = { .entities = 0, .entity_count = 0, .state = {.x = 0.0f, .y = 0, .z = 0, .r = 0, .r2 = 0.0f } }; void renderScene( scene s, int w, int h ) { matrix p = getProjectionMatrix( w, h ); matrix rx = getRotationMatrix( 0, s.state.r2 ); matrix ry = getRotationMatrix( 1, s.state.r ); static double lastTime = 0, time = -1e1f; title = std::to_string( time ); if ( !s.paused ) time += ( glfwGetTime() - lastTime ) * 1e1f; lastTime = glfwGetTime(); for ( unsigned int i = 0; i < s.entity_count; i++ ) renderEntity( s.entities[i], p, rx, ry, (float)time, (float) w / h ); } void deleteScene( scene s ) { for ( unsigned int i = 0; i < s.entity_count; i++ ) deleteEntity( s.entities[i] ); free( s.entities ); } void keyCallback( GLFWwindow* window, int key, int scancode, int action, int mods ) { if ( action != GLFW_PRESS ) return; if ( key == GLFW_KEY_ESCAPE ) glfwSetWindowShouldClose( window, 1 ); if ( key == GLFW_KEY_SPACE ) s.paused = !s.paused; } // Main Loop int main() { glfwInit(); glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 2 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 1 ); glfwWindowHint( GLFW_MAXIMIZED, GLFW_TRUE ); GLFWwindow* window = glfwCreateWindow( 800, 600, "Test", NULL, NULL ); glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_DISABLED ); glfwMakeContextCurrent( window ); glfwSetKeyCallback( window, keyCallback ); gladLoadGL(); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LESS ); glEnable( GL_CULL_FACE ); glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); makeEntity( &s, skyVertShader, skyFragShader ); glfwGetCursorPos( window, &s.state.px, &s.state.py ); while ( !glfwWindowShouldClose( window ) ) { // Move Cursor double mx, my; glfwGetCursorPos( window, &mx, &my ); s.state.r -= -(float) ( mx - s.state.px ) * 2e-3f; s.state.r2 -= (float) ( my - s.state.py ) * 2e-3f; s.state.px = (float) mx; s.state.py = (float) my; // Clear Framebuffer glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Render the Scene int w, h; glfwGetWindowSize( window, &w, &h ); renderScene( s, w, h ); glfwSetWindowTitle( window, title.c_str() ); // Swap glfwSwapBuffers( window ); glfwPollEvents(); } deleteScene( s ); glfwTerminate(); return 0; }
30.376884
116
0.633747
[ "render" ]
80e1850a7ac2c8458b6cc251c8341fb540272d1c
156,704
cpp
C++
CWE-119/source_files/CVE-2010-3765/Firefox_3.5.13_CVE_2010_3765_content_base_src_nsGenericElement.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
185
2017-12-14T08:18:15.000Z
2022-03-30T02:58:36.000Z
CWE-119/source_files/CVE-2010-3765/Firefox_3.5.13_CVE_2010_3765_content_base_src_nsGenericElement.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
11
2018-01-30T23:31:20.000Z
2022-01-17T05:03:56.000Z
CWE-119/source_files/CVE-2010-3765/Firefox_3.5.13_CVE_2010_3765_content_base_src_nsGenericElement.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
87
2018-01-10T08:12:32.000Z
2022-02-19T10:29:31.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=2 sw=2 et tw=79: */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * Base class for all element classes; this provides an implementation * of DOM Core's nsIDOMElement, implements nsIContent, provides * utility methods for subclasses, and so forth. */ #include "nsGenericElement.h" #include "nsDOMAttribute.h" #include "nsDOMAttributeMap.h" #include "nsIAtom.h" #include "nsINodeInfo.h" #include "nsIDocument.h" #include "nsIDOMNodeList.h" #include "nsIDOMDocument.h" #include "nsIDOMText.h" #include "nsIContentIterator.h" #include "nsIEventListenerManager.h" #include "nsIFocusController.h" #include "nsILinkHandler.h" #include "nsIScriptGlobalObject.h" #include "nsIURL.h" #include "nsNetUtil.h" #include "nsIFrame.h" #include "nsIPresShell.h" #include "nsPresContext.h" #include "nsStyleConsts.h" #include "nsString.h" #include "nsUnicharUtils.h" #include "nsIEventStateManager.h" #include "nsIDOMEvent.h" #include "nsIPrivateDOMEvent.h" #include "nsDOMCID.h" #include "nsIServiceManager.h" #include "nsIDOMCSSStyleDeclaration.h" #include "nsDOMCSSDeclaration.h" #include "nsINameSpaceManager.h" #include "nsContentList.h" #include "nsDOMError.h" #include "nsDOMString.h" #include "nsIScriptSecurityManager.h" #include "nsIDOMMutationEvent.h" #include "nsMutationEvent.h" #include "nsNodeUtils.h" #include "nsDocument.h" #ifdef MOZ_XUL #include "nsXULElement.h" #endif /* MOZ_XUL */ #include "nsFrameManager.h" #include "nsFrameSelection.h" #include "nsBindingManager.h" #include "nsXBLBinding.h" #include "nsIDOMCSSStyleDeclaration.h" #include "nsIDOMViewCSS.h" #include "nsIXBLService.h" #include "nsPIDOMWindow.h" #include "nsIBoxObject.h" #include "nsPIBoxObject.h" #include "nsIDOMNSDocument.h" #include "nsIDOMNSElement.h" #include "nsClientRect.h" #ifdef MOZ_SVG #include "nsSVGUtils.h" #endif #include "nsLayoutUtils.h" #include "nsGkAtoms.h" #include "nsContentUtils.h" #include "nsIJSContextStack.h" #include "nsIServiceManager.h" #include "nsIDOMEventListener.h" #include "nsIWebNavigation.h" #include "nsIBaseWindow.h" #include "jsapi.h" #include "nsNodeInfoManager.h" #include "nsICategoryManager.h" #include "nsIDOMNSFeatureFactory.h" #include "nsIDOMDocumentType.h" #include "nsIDOMUserDataHandler.h" #include "nsIDOMNSEditableElement.h" #include "nsIEditor.h" #include "nsIEditorDocShell.h" #include "nsEventDispatcher.h" #include "nsContentCreatorFunctions.h" #include "nsIFocusController.h" #include "nsIControllers.h" #include "nsLayoutUtils.h" #include "nsIView.h" #include "nsIViewManager.h" #include "nsIScrollableFrame.h" #include "nsIScrollableView.h" #include "nsIScrollableViewProvider.h" #include "nsXBLInsertionPoint.h" #include "nsICSSStyleRule.h" /* For nsCSSSelectorList */ #include "nsCSSRuleProcessor.h" #ifdef MOZ_XUL #include "nsIXULDocument.h" #endif /* MOZ_XUL */ #ifdef ACCESSIBILITY #include "nsIAccessibilityService.h" #include "nsIAccessibleEvent.h" #endif /* ACCESSIBILITY */ #include "nsCycleCollectionParticipant.h" #include "nsCCUncollectableMarker.h" #include "mozAutoDocUpdate.h" #include "nsICSSParser.h" #ifdef MOZ_SVG PRBool NS_SVG_HaveFeature(const nsAString &aFeature); #endif /* MOZ_SVG */ #ifdef DEBUG_waterson /** * List a content tree to stdout. Meant to be called from gdb. */ void DebugListContentTree(nsIContent* aElement) { aElement->List(stdout, 0); printf("\n"); } #endif NS_DEFINE_IID(kThisPtrOffsetsSID, NS_THISPTROFFSETS_SID); PRInt32 nsIContent::sTabFocusModel = eTabFocus_any; PRBool nsIContent::sTabFocusModelAppliesToXUL = PR_FALSE; nsresult NS_NewContentIterator(nsIContentIterator** aInstancePtrResult); //---------------------------------------------------------------------- nsINode::nsSlots::~nsSlots() { if (mChildNodes) { mChildNodes->DropReference(); NS_RELEASE(mChildNodes); } if (mWeakReference) { mWeakReference->NoticeNodeDestruction(); } } //---------------------------------------------------------------------- nsINode::~nsINode() { NS_ASSERTION(!HasSlots(), "nsNodeUtils::LastRelease was not called?"); } void* nsINode::GetProperty(PRUint16 aCategory, nsIAtom *aPropertyName, nsresult *aStatus) const { nsIDocument *doc = GetOwnerDoc(); if (!doc) return nsnull; return doc->PropertyTable()->GetProperty(this, aCategory, aPropertyName, aStatus); } nsresult nsINode::SetProperty(PRUint16 aCategory, nsIAtom *aPropertyName, void *aValue, NSPropertyDtorFunc aDtor, PRBool aTransfer, void **aOldValue) { nsIDocument *doc = GetOwnerDoc(); if (!doc) return NS_ERROR_FAILURE; nsresult rv = doc->PropertyTable()->SetProperty(this, aCategory, aPropertyName, aValue, aDtor, nsnull, aTransfer, aOldValue); if (NS_SUCCEEDED(rv)) { SetFlags(NODE_HAS_PROPERTIES); } return rv; } nsresult nsINode::DeleteProperty(PRUint16 aCategory, nsIAtom *aPropertyName) { nsIDocument *doc = GetOwnerDoc(); if (!doc) return nsnull; return doc->PropertyTable()->DeleteProperty(this, aCategory, aPropertyName); } void* nsINode::UnsetProperty(PRUint16 aCategory, nsIAtom *aPropertyName, nsresult *aStatus) { nsIDocument *doc = GetOwnerDoc(); if (!doc) return nsnull; return doc->PropertyTable()->UnsetProperty(this, aCategory, aPropertyName, aStatus); } nsresult nsGenericElement::GetListenerManager(PRBool aCreateIfNotFound, nsIEventListenerManager** aResult) { return nsContentUtils::GetListenerManager(this, aCreateIfNotFound, aResult); } nsresult nsGenericElement::AddEventListenerByIID(nsIDOMEventListener *aListener, const nsIID& aIID) { nsCOMPtr<nsIEventListenerManager> elm; nsresult rv = GetListenerManager(PR_TRUE, getter_AddRefs(elm)); if (elm) { return elm->AddEventListenerByIID(aListener, aIID, NS_EVENT_FLAG_BUBBLE); } return rv; } nsresult nsGenericElement::RemoveEventListenerByIID(nsIDOMEventListener *aListener, const nsIID& aIID) { nsCOMPtr<nsIEventListenerManager> elm; GetListenerManager(PR_FALSE, getter_AddRefs(elm)); if (elm) { return elm->RemoveEventListenerByIID(aListener, aIID, NS_EVENT_FLAG_BUBBLE); } return NS_OK; } nsresult nsGenericElement::GetSystemEventGroup(nsIDOMEventGroup** aGroup) { nsCOMPtr<nsIEventListenerManager> elm; nsresult rv = GetListenerManager(PR_TRUE, getter_AddRefs(elm)); if (elm) { return elm->GetSystemEventGroupLM(aGroup); } return rv; } nsINode::nsSlots* nsINode::CreateSlots() { return new nsSlots(mFlagsOrSlots); } void nsINode::AddMutationObserver(nsIMutationObserver* aMutationObserver) { nsSlots* slots = GetSlots(); if (slots) { slots->mMutationObservers.AppendElementUnlessExists(aMutationObserver); } } void nsINode::RemoveMutationObserver(nsIMutationObserver* aMutationObserver) { nsSlots* slots = GetExistingSlots(); if (slots) { slots->mMutationObservers.RemoveElement(aMutationObserver); } } PRBool nsINode::IsEditableInternal() const { if (HasFlag(NODE_IS_EDITABLE)) { // The node is in an editable contentEditable subtree. return PR_TRUE; } nsIDocument *doc = GetCurrentDoc(); // Check if the node is in a document and the document is in designMode. return doc && doc->HasFlag(NODE_IS_EDITABLE); } static nsIContent* GetEditorRootContent(nsIEditor* aEditor) { nsCOMPtr<nsIDOMElement> rootElement; aEditor->GetRootElement(getter_AddRefs(rootElement)); nsCOMPtr<nsIContent> rootContent(do_QueryInterface(rootElement)); return rootContent; } nsIContent* nsINode::GetTextEditorRootContent(nsIEditor** aEditor) { if (aEditor) *aEditor = nsnull; for (nsINode* node = this; node; node = node->GetNodeParent()) { nsCOMPtr<nsIDOMNSEditableElement> editableElement(do_QueryInterface(node)); if (!editableElement) continue; nsCOMPtr<nsIEditor> editor; editableElement->GetEditor(getter_AddRefs(editor)); NS_ENSURE_TRUE(editor, nsnull); nsIContent* rootContent = GetEditorRootContent(editor); if (aEditor) editor.swap(*aEditor); return rootContent; } return nsnull; } static nsIEditor* GetHTMLEditor(nsPresContext* aPresContext) { nsCOMPtr<nsISupports> container = aPresContext->GetContainer(); nsCOMPtr<nsIEditorDocShell> editorDocShell(do_QueryInterface(container)); PRBool isEditable; if (!editorDocShell || NS_FAILED(editorDocShell->GetEditable(&isEditable)) || !isEditable) return nsnull; nsCOMPtr<nsIEditor> editor; editorDocShell->GetEditor(getter_AddRefs(editor)); return editor; } nsIContent* nsINode::GetSelectionRootContent(nsIPresShell* aPresShell) { NS_ENSURE_TRUE(aPresShell, nsnull); if (IsNodeOfType(eDOCUMENT)) return static_cast<nsIDocument*>(this)->GetRootContent(); if (!IsNodeOfType(eCONTENT)) return nsnull; nsIFrame* frame = aPresShell->GetPrimaryFrameFor(static_cast<nsIContent*>(this)); if (frame && frame->GetStateBits() & NS_FRAME_INDEPENDENT_SELECTION) { // This node should be a descendant of input/textarea editor. nsIContent* content = GetTextEditorRootContent(); if (content) return content; NS_ERROR("Editor is not found!"); } nsPresContext* presContext = aPresShell->GetPresContext(); if (presContext) { nsIEditor* editor = GetHTMLEditor(presContext); if (editor) { // This node is in HTML editor. nsIDocument* doc = GetCurrentDoc(); if (!doc || doc->HasFlag(NODE_IS_EDITABLE) || !HasFlag(NODE_IS_EDITABLE)) return GetEditorRootContent(editor); // If the current document is not editable, but current content is // editable, we should assume that the child of the nearest non-editable // ancestor is selection root. nsIContent* content = static_cast<nsIContent*>(this); for (nsIContent* parent = GetParent(); parent && parent->HasFlag(NODE_IS_EDITABLE); parent = content->GetParent()) content = parent; return content; } } nsCOMPtr<nsFrameSelection> fs = aPresShell->FrameSelection(); nsIContent* content = fs->GetLimiter(); if (content) return content; content = fs->GetAncestorLimiter(); if (content) return content; nsIDocument* doc = aPresShell->GetDocument(); NS_ENSURE_TRUE(doc, nsnull); return doc->GetRootContent(); } nsIDOMNodeList* nsINode::GetChildNodesList() { nsSlots *slots = GetSlots(); if (!slots) { return nsnull; } if (!slots->mChildNodes) { slots->mChildNodes = new nsChildContentList(this); if (slots->mChildNodes) { NS_ADDREF(slots->mChildNodes); } } return slots->mChildNodes; } #ifdef DEBUG void nsINode::CheckNotNativeAnonymous() const { if (!IsNodeOfType(eCONTENT)) return; nsIContent* content = static_cast<const nsIContent *>(this)->GetBindingParent(); while (content) { if (content->IsRootOfNativeAnonymousSubtree()) { NS_ERROR("Element not marked to be in native anonymous subtree!"); break; } content = content->GetBindingParent(); } } #endif nsresult nsINode::GetParentNode(nsIDOMNode** aParentNode) { *aParentNode = nsnull; nsINode *parent = GetNodeParent(); return parent ? CallQueryInterface(parent, aParentNode) : NS_OK; } nsresult nsINode::GetChildNodes(nsIDOMNodeList** aChildNodes) { *aChildNodes = GetChildNodesList(); if (!*aChildNodes) { return NS_ERROR_OUT_OF_MEMORY; } NS_ADDREF(*aChildNodes); return NS_OK; } nsresult nsINode::GetFirstChild(nsIDOMNode** aNode) { nsIContent* child = GetChildAt(0); if (child) { return CallQueryInterface(child, aNode); } *aNode = nsnull; return NS_OK; } nsresult nsINode::GetLastChild(nsIDOMNode** aNode) { nsIContent* child = GetLastChild(); if (child) { return CallQueryInterface(child, aNode); } *aNode = nsnull; return NS_OK; } nsresult nsINode::GetPreviousSibling(nsIDOMNode** aPrevSibling) { *aPrevSibling = nsnull; nsIContent *sibling = GetSibling(-1); return sibling ? CallQueryInterface(sibling, aPrevSibling) : NS_OK; } nsresult nsINode::GetNextSibling(nsIDOMNode** aNextSibling) { *aNextSibling = nsnull; nsIContent *sibling = GetSibling(1); return sibling ? CallQueryInterface(sibling, aNextSibling) : NS_OK; } nsresult nsINode::GetOwnerDocument(nsIDOMDocument** aOwnerDocument) { *aOwnerDocument = nsnull; nsIDocument *ownerDoc = GetOwnerDocument(); return ownerDoc ? CallQueryInterface(ownerDoc, aOwnerDocument) : NS_OK; } //---------------------------------------------------------------------- PRInt32 nsIContent::IntrinsicState() const { return IsEditable() ? NS_EVENT_STATE_MOZ_READWRITE : NS_EVENT_STATE_MOZ_READONLY; } void nsIContent::UpdateEditableState() { nsIContent *parent = GetParent(); SetEditableFlag(parent && parent->HasFlag(NODE_IS_EDITABLE)); } nsIContent* nsIContent::FindFirstNonNativeAnonymous() const { // This handles also nested native anonymous content. for (const nsIContent *content = this; content; content = content->GetBindingParent()) { if (!content->IsInNativeAnonymousSubtree()) { // Oops, this function signature allows casting const to // non-const. (Then again, so does GetChildAt(0)->GetParent().) return const_cast<nsIContent*>(content); } } return nsnull; } //---------------------------------------------------------------------- NS_IMPL_ADDREF(nsChildContentList) NS_IMPL_RELEASE(nsChildContentList) NS_INTERFACE_TABLE_HEAD(nsChildContentList) NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY NS_NODELIST_OFFSET_AND_INTERFACE_TABLE_BEGIN(nsChildContentList) NS_INTERFACE_TABLE_ENTRY(nsChildContentList, nsINodeList) NS_INTERFACE_TABLE_ENTRY(nsChildContentList, nsIDOMNodeList) NS_OFFSET_AND_INTERFACE_TABLE_END NS_OFFSET_AND_INTERFACE_TABLE_TO_MAP_SEGUE NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(NodeList) NS_INTERFACE_MAP_END NS_IMETHODIMP nsChildContentList::GetLength(PRUint32* aLength) { *aLength = mNode ? mNode->GetChildCount() : 0; return NS_OK; } NS_IMETHODIMP nsChildContentList::Item(PRUint32 aIndex, nsIDOMNode** aReturn) { nsINode* node = GetNodeAt(aIndex); if (!node) { *aReturn = nsnull; return NS_OK; } return CallQueryInterface(node, aReturn); } nsINode* nsChildContentList::GetNodeAt(PRUint32 aIndex) { if (mNode) { return mNode->GetChildAt(aIndex); } return nsnull; } //---------------------------------------------------------------------- NS_IMPL_CYCLE_COLLECTION_1(nsNode3Tearoff, mContent) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNode3Tearoff) NS_INTERFACE_MAP_ENTRY(nsIDOM3Node) NS_INTERFACE_MAP_END_AGGREGATED(mContent) NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNode3Tearoff) NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNode3Tearoff) NS_IMETHODIMP nsNode3Tearoff::GetBaseURI(nsAString& aURI) { nsCOMPtr<nsIURI> baseURI = mContent->GetBaseURI(); nsCAutoString spec; if (baseURI) { baseURI->GetSpec(spec); } CopyUTF8toUTF16(spec, aURI); return NS_OK; } NS_IMETHODIMP nsNode3Tearoff::GetTextContent(nsAString &aTextContent) { nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mContent)); NS_ASSERTION(node, "We have an nsIContent which doesn't support nsIDOMNode"); PRUint16 nodeType; node->GetNodeType(&nodeType); if (nodeType == nsIDOMNode::DOCUMENT_TYPE_NODE || nodeType == nsIDOMNode::NOTATION_NODE) { SetDOMStringToNull(aTextContent); return NS_OK; } if (nodeType == nsIDOMNode::TEXT_NODE || nodeType == nsIDOMNode::CDATA_SECTION_NODE || nodeType == nsIDOMNode::COMMENT_NODE || nodeType == nsIDOMNode::PROCESSING_INSTRUCTION_NODE) { return node->GetNodeValue(aTextContent); } nsContentUtils::GetNodeTextContent(mContent, PR_TRUE, aTextContent); return NS_OK; } NS_IMETHODIMP nsNode3Tearoff::SetTextContent(const nsAString &aTextContent) { // Batch possible DOMSubtreeModified events. mozAutoSubtreeModified subtree(mContent->GetOwnerDoc(), nsnull); nsCOMPtr<nsIDOMNode> node(do_QueryInterface(mContent)); NS_ASSERTION(node, "We have an nsIContent which doesn't support nsIDOMNode"); PRUint16 nodeType; node->GetNodeType(&nodeType); if (nodeType == nsIDOMNode::DOCUMENT_TYPE_NODE || nodeType == nsIDOMNode::NOTATION_NODE) { return NS_OK; } if (nodeType == nsIDOMNode::TEXT_NODE || nodeType == nsIDOMNode::CDATA_SECTION_NODE || nodeType == nsIDOMNode::COMMENT_NODE || nodeType == nsIDOMNode::PROCESSING_INSTRUCTION_NODE) { return node->SetNodeValue(aTextContent); } return nsContentUtils::SetNodeTextContent(mContent, aTextContent, PR_FALSE); } NS_IMETHODIMP nsNode3Tearoff::CompareDocumentPosition(nsIDOMNode* aOther, PRUint16* aReturn) { NS_ENSURE_ARG_POINTER(aOther); nsCOMPtr<nsINode> other = do_QueryInterface(aOther); NS_ENSURE_TRUE(other, NS_ERROR_DOM_NOT_SUPPORTED_ERR); *aReturn = nsContentUtils::ComparePosition(other, mContent); return NS_OK; } NS_IMETHODIMP nsNode3Tearoff::IsSameNode(nsIDOMNode* aOther, PRBool* aReturn) { nsCOMPtr<nsIContent> other(do_QueryInterface(aOther)); *aReturn = mContent == other; return NS_OK; } PRBool nsNode3Tearoff::AreNodesEqual(nsIContent* aContent1, nsIContent* aContent2) { // We use nsIContent instead of nsINode for the attributes of elements. NS_PRECONDITION(aContent1 && aContent2, "Who called AreNodesEqual?"); nsAutoString string1, string2; // Prefix, namespace URI, local name, node name check. if (!aContent1->NodeInfo()->Equals(aContent2->NodeInfo())) { return PR_FALSE; } if (aContent1->Tag() == nsGkAtoms::documentTypeNodeName) { nsCOMPtr<nsIDOMDocumentType> docType1 = do_QueryInterface(aContent1); nsCOMPtr<nsIDOMDocumentType> docType2 = do_QueryInterface(aContent2); NS_ASSERTION(docType1 && docType2, "Why don't we have a document type node?"); // Public ID docType1->GetPublicId(string1); docType2->GetPublicId(string2); if (!string1.Equals(string2)) { return PR_FALSE; } // System ID docType1->GetSystemId(string1); docType2->GetSystemId(string2); if (!string1.Equals(string2)) { return PR_FALSE; } // Internal subset docType1->GetInternalSubset(string1); docType2->GetInternalSubset(string2); if (!string1.Equals(string2)) { return PR_FALSE; } } if (aContent1->IsNodeOfType(nsINode::eELEMENT)) { // aContent1 is an element. Do the check on attributes. PRUint32 attrCount = aContent1->GetAttrCount(); if (attrCount != aContent2->GetAttrCount()) { return PR_FALSE; } // Iterate over attributes. for (PRUint32 i = 0; i < attrCount; ++i) { const nsAttrName* attrName1 = aContent1->GetAttrNameAt(i); #ifdef DEBUG PRBool hasAttr = #endif aContent1->GetAttr(attrName1->NamespaceID(), attrName1->LocalName(), string1); NS_ASSERTION(hasAttr, "Why don't we have an attr?"); if (!aContent2->AttrValueIs(attrName1->NamespaceID(), attrName1->LocalName(), string1, eCaseMatters)) { return PR_FALSE; } } } else { // aContent1 is not an element. Node value check. nsCOMPtr<nsIDOMNode> domNode1 = do_QueryInterface(aContent1); nsCOMPtr<nsIDOMNode> domNode2 = do_QueryInterface(aContent2); NS_ASSERTION(domNode1 && domNode2, "How'd we get nsIContent without nsIDOMNode?"); domNode1->GetNodeValue(string1); domNode2->GetNodeValue(string2); if (!string1.Equals(string2)) { return PR_FALSE; } } // Child nodes count. PRUint32 childCount = aContent1->GetChildCount(); if (childCount != aContent2->GetChildCount()) { return PR_FALSE; } // Iterate over child nodes. for (PRUint32 i = 0; i < childCount; ++i) { nsIContent* child1 = aContent1->GetChildAt(i); nsIContent* child2 = aContent2->GetChildAt(i); if (!AreNodesEqual(child1, child2)) { return PR_FALSE; } } return PR_TRUE; } NS_IMETHODIMP nsNode3Tearoff::IsEqualNode(nsIDOMNode* aOther, PRBool* aReturn) { NS_ENSURE_ARG_POINTER(aOther); *aReturn = PR_FALSE; // Since we implement nsIContent, aOther must as well. nsCOMPtr<nsIContent> aOtherContent = do_QueryInterface(aOther); // Documents and attributes don't implement nsIContent. if (!aOtherContent) { return NS_OK; } *aReturn = nsNode3Tearoff::AreNodesEqual(mContent, aOtherContent); return NS_OK; } NS_IMETHODIMP nsNode3Tearoff::GetFeature(const nsAString& aFeature, const nsAString& aVersion, nsISupports** aReturn) { return nsGenericElement::InternalGetFeature(this, aFeature, aVersion, aReturn); } NS_IMETHODIMP nsNode3Tearoff::SetUserData(const nsAString& aKey, nsIVariant* aData, nsIDOMUserDataHandler* aHandler, nsIVariant** aResult) { return nsNodeUtils::SetUserData(mContent, aKey, aData, aHandler, aResult); } NS_IMETHODIMP nsNode3Tearoff::GetUserData(const nsAString& aKey, nsIVariant** aResult) { return nsNodeUtils::GetUserData(mContent, aKey, aResult); } NS_IMETHODIMP nsNode3Tearoff::LookupPrefix(const nsAString& aNamespaceURI, nsAString& aPrefix) { SetDOMStringToNull(aPrefix); // XXX Waiting for DOM spec to list error codes. // Trace up the content parent chain looking for the namespace // declaration that defines the aNamespaceURI namespace. Once found, // return the prefix (i.e. the attribute localName). for (nsIContent* content = mContent; content; content = content->GetParent()) { PRUint32 attrCount = content->GetAttrCount(); for (PRUint32 i = 0; i < attrCount; ++i) { const nsAttrName* name = content->GetAttrNameAt(i); if (name->NamespaceEquals(kNameSpaceID_XMLNS) && content->AttrValueIs(kNameSpaceID_XMLNS, name->LocalName(), aNamespaceURI, eCaseMatters)) { // If the localName is "xmlns", the prefix we output should be // null. if (name->LocalName() != nsGkAtoms::xmlns) { name->LocalName()->ToString(aPrefix); } return NS_OK; } } } return NS_OK; } NS_IMETHODIMP nsNode3Tearoff::LookupNamespaceURI(const nsAString& aNamespacePrefix, nsAString& aNamespaceURI) { if (NS_FAILED(nsContentUtils::LookupNamespaceURI(mContent, aNamespacePrefix, aNamespaceURI))) { SetDOMStringToNull(aNamespaceURI); } return NS_OK; } NS_IMETHODIMP nsNode3Tearoff::IsDefaultNamespace(const nsAString& aNamespaceURI, PRBool* aReturn) { nsAutoString defaultNamespace; LookupNamespaceURI(EmptyString(), defaultNamespace); *aReturn = aNamespaceURI.Equals(defaultNamespace); return NS_OK; } NS_IMETHODIMP nsNSElementTearoff::GetFirstElementChild(nsIDOMElement** aResult) { *aResult = nsnull; nsAttrAndChildArray& children = mContent->mAttrsAndChildren; PRUint32 i, count = children.ChildCount(); for (i = 0; i < count; ++i) { nsIContent* child = children.ChildAt(i); if (child->IsNodeOfType(nsINode::eELEMENT)) { return CallQueryInterface(child, aResult); } } return NS_OK; } NS_IMETHODIMP nsNSElementTearoff::GetLastElementChild(nsIDOMElement** aResult) { *aResult = nsnull; nsAttrAndChildArray& children = mContent->mAttrsAndChildren; PRUint32 i = children.ChildCount(); while (i > 0) { nsIContent* child = children.ChildAt(--i); if (child->IsNodeOfType(nsINode::eELEMENT)) { return CallQueryInterface(child, aResult); } } return NS_OK; } NS_IMETHODIMP nsNSElementTearoff::GetPreviousElementSibling(nsIDOMElement** aResult) { *aResult = nsnull; nsIContent* parent = mContent->GetParent(); if (!parent) { return NS_OK; } NS_ASSERTION(parent->IsNodeOfType(nsINode::eELEMENT) || parent->IsNodeOfType(nsINode::eDOCUMENT_FRAGMENT), "Parent content must be an element or a doc fragment"); nsAttrAndChildArray& children = static_cast<nsGenericElement*>(parent)->mAttrsAndChildren; PRInt32 index = children.IndexOfChild(mContent); if (index < 0) { return NS_OK; } PRUint32 i = index; while (i > 0) { nsIContent* child = children.ChildAt((PRUint32)--i); if (child->IsNodeOfType(nsINode::eELEMENT)) { return CallQueryInterface(child, aResult); } } return NS_OK; } NS_IMETHODIMP nsNSElementTearoff::GetNextElementSibling(nsIDOMElement** aResult) { *aResult = nsnull; nsIContent* parent = mContent->GetParent(); if (!parent) { return NS_OK; } NS_ASSERTION(parent->IsNodeOfType(nsINode::eELEMENT) || parent->IsNodeOfType(nsINode::eDOCUMENT_FRAGMENT), "Parent content must be an element or a doc fragment"); nsAttrAndChildArray& children = static_cast<nsGenericElement*>(parent)->mAttrsAndChildren; PRInt32 index = children.IndexOfChild(mContent); if (index < 0) { return NS_OK; } PRUint32 i, count = children.ChildCount(); for (i = (PRUint32)index + 1; i < count; ++i) { nsIContent* child = children.ChildAt(i); if (child->IsNodeOfType(nsINode::eELEMENT)) { return CallQueryInterface(child, aResult); } } return NS_OK; } nsContentList* nsNSElementTearoff::GetChildrenList() { nsGenericElement::nsDOMSlots *slots = mContent->GetDOMSlots(); NS_ENSURE_TRUE(slots, nsnull); if (!slots->mChildrenList) { slots->mChildrenList = new nsContentList(mContent, nsGkAtoms::_asterix, kNameSpaceID_Wildcard, PR_FALSE); } return slots->mChildrenList; } NS_IMETHODIMP nsNSElementTearoff::GetChildElementCount(PRUint32* aResult) { *aResult = 0; nsContentList* list = GetChildrenList(); NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY); *aResult = list->Length(PR_TRUE); return NS_OK; } NS_IMETHODIMP nsNSElementTearoff::GetChildren(nsIDOMNodeList** aResult) { *aResult = nsnull; nsContentList* list = GetChildrenList(); NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY); NS_ADDREF(*aResult = list); return NS_OK; } //---------------------------------------------------------------------- NS_IMPL_CYCLE_COLLECTION_1(nsNSElementTearoff, mContent) NS_INTERFACE_MAP_BEGIN(nsNSElementTearoff) NS_INTERFACE_MAP_ENTRY(nsIDOMNSElement) NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsNSElementTearoff) NS_INTERFACE_MAP_END_AGGREGATED(mContent) NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNSElementTearoff) NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNSElementTearoff) NS_IMETHODIMP nsNSElementTearoff::GetElementsByClassName(const nsAString& aClasses, nsIDOMNodeList** aReturn) { return nsDocument::GetElementsByClassNameHelper(mContent, aClasses, aReturn); } nsIFrame* nsGenericElement::GetStyledFrame() { nsIFrame *frame = GetPrimaryFrame(Flush_Layout); return (frame && frame->GetType() == nsGkAtoms::tableOuterFrame) ? frame->GetFirstChild(nsnull) : frame; } void nsGenericElement::GetOffsetRect(nsRect& aRect, nsIContent** aOffsetParent) { *aOffsetParent = nsnull; aRect = nsRect(); nsIFrame* frame = GetStyledFrame(); if (!frame) { return; } nsPoint origin = frame->GetPosition(); aRect.x = nsPresContext::AppUnitsToIntCSSPixels(origin.x); aRect.y = nsPresContext::AppUnitsToIntCSSPixels(origin.y); // Get the union of all rectangles in this and continuation frames. // It doesn't really matter what we use as aRelativeTo here, since // we only care about the size. Using 'parent' might make things // a bit faster by speeding up the internal GetOffsetTo operations. nsIFrame* parent = frame->GetParent() ? frame->GetParent() : frame; nsRect rcFrame = nsLayoutUtils::GetAllInFlowRectsUnion(frame, parent); aRect.width = nsPresContext::AppUnitsToIntCSSPixels(rcFrame.width); aRect.height = nsPresContext::AppUnitsToIntCSSPixels(rcFrame.height); } void nsNSElementTearoff::GetScrollInfo(nsIScrollableView **aScrollableView, nsIFrame **aFrame) { *aScrollableView = nsnull; // it isn't clear what to return for SVG nodes, so just return nothing if (mContent->IsNodeOfType(nsINode::eSVG)) { if (aFrame) *aFrame = nsnull; return; } nsIFrame* frame = (static_cast<nsGenericElement*>(mContent))->GetStyledFrame(); if (aFrame) { *aFrame = frame; } if (!frame) { return; } // Get the scrollable frame nsIScrollableFrame *scrollFrame = nsnull; CallQueryInterface(frame, &scrollFrame); if (!scrollFrame) { nsIScrollableViewProvider *scrollProvider = nsnull; CallQueryInterface(frame, &scrollProvider); // menu frames implement nsIScrollableViewProvider but we don't want // to use it here. if (scrollProvider && frame->GetType() != nsGkAtoms::menuFrame) { *aScrollableView = scrollProvider->GetScrollableView(); if (*aScrollableView) { return; } } nsIDocument* doc = mContent->GetCurrentDoc(); PRBool quirksMode = doc && doc->GetCompatibilityMode() == eCompatibility_NavQuirks; if ((quirksMode && mContent->NodeInfo()->Equals(nsGkAtoms::body)) || (!quirksMode && mContent->NodeInfo()->Equals(nsGkAtoms::html))) { // In quirks mode, the scroll info for the body element should map to the // scroll info for the nearest scrollable frame above the body element // (i.e. the root scrollable frame). This is what IE6 does in quirks // mode. In strict mode the root scrollable frame corresponds to the // html element in IE6, so we map the scroll info for the html element to // the root scrollable frame. do { frame = frame->GetParent(); if (!frame) { break; } CallQueryInterface(frame, &scrollFrame); } while (!scrollFrame); } if (!scrollFrame) { return; } } // Get the scrollable view *aScrollableView = scrollFrame->GetScrollableView(); } nsresult nsNSElementTearoff::GetScrollTop(PRInt32* aScrollTop) { NS_ENSURE_ARG_POINTER(aScrollTop); *aScrollTop = 0; nsIScrollableView *view; nsresult rv = NS_OK; GetScrollInfo(&view); if (view) { nscoord xPos, yPos; rv = view->GetScrollPosition(xPos, yPos); *aScrollTop = nsPresContext::AppUnitsToIntCSSPixels(yPos); } return rv; } nsresult nsNSElementTearoff::SetScrollTop(PRInt32 aScrollTop) { nsIScrollableView *view; nsresult rv = NS_OK; GetScrollInfo(&view); if (view) { nscoord xPos, yPos; rv = view->GetScrollPosition(xPos, yPos); if (NS_SUCCEEDED(rv)) { rv = view->ScrollTo(xPos, nsPresContext::CSSPixelsToAppUnits(aScrollTop), 0); } } return rv; } nsresult nsNSElementTearoff::GetScrollLeft(PRInt32* aScrollLeft) { NS_ENSURE_ARG_POINTER(aScrollLeft); *aScrollLeft = 0; nsIScrollableView *view; nsresult rv = NS_OK; GetScrollInfo(&view); if (view) { nscoord xPos, yPos; rv = view->GetScrollPosition(xPos, yPos); *aScrollLeft = nsPresContext::AppUnitsToIntCSSPixels(xPos); } return rv; } nsresult nsNSElementTearoff::SetScrollLeft(PRInt32 aScrollLeft) { nsIScrollableView *view; nsresult rv = NS_OK; GetScrollInfo(&view); if (view) { nscoord xPos, yPos; rv = view->GetScrollPosition(xPos, yPos); if (NS_SUCCEEDED(rv)) { rv = view->ScrollTo(nsPresContext::CSSPixelsToAppUnits(aScrollLeft), yPos, 0); } } return rv; } nsresult nsNSElementTearoff::GetScrollHeight(PRInt32* aScrollHeight) { NS_ENSURE_ARG_POINTER(aScrollHeight); *aScrollHeight = 0; if (mContent->IsNodeOfType(nsINode::eSVG)) return NS_OK; nsIScrollableView *scrollView; nsresult rv = NS_OK; GetScrollInfo(&scrollView); if (!scrollView) { nsRect rcFrame; nsCOMPtr<nsIContent> parent; (static_cast<nsGenericElement *>(mContent))->GetOffsetRect(rcFrame, getter_AddRefs(parent)); *aScrollHeight = rcFrame.height; return NS_OK; } // xMax and yMax is the total length of our container nscoord xMax, yMax; rv = scrollView->GetContainerSize(&xMax, &yMax); *aScrollHeight = nsPresContext::AppUnitsToIntCSSPixels(yMax); return rv; } nsresult nsNSElementTearoff::GetScrollWidth(PRInt32* aScrollWidth) { NS_ENSURE_ARG_POINTER(aScrollWidth); *aScrollWidth = 0; if (mContent->IsNodeOfType(nsINode::eSVG)) return NS_OK; nsIScrollableView *scrollView; nsresult rv = NS_OK; GetScrollInfo(&scrollView); if (!scrollView) { nsRect rcFrame; nsCOMPtr<nsIContent> parent; (static_cast<nsGenericElement *>(mContent))->GetOffsetRect(rcFrame, getter_AddRefs(parent)); *aScrollWidth = rcFrame.width; return NS_OK; } nscoord xMax, yMax; rv = scrollView->GetContainerSize(&xMax, &yMax); *aScrollWidth = nsPresContext::AppUnitsToIntCSSPixels(xMax); return rv; } nsRect nsNSElementTearoff::GetClientAreaRect() { nsIScrollableView *scrollView; nsIFrame *frame; // it isn't clear what to return for SVG nodes, so just return 0 if (mContent->IsNodeOfType(nsINode::eSVG)) return nsRect(0, 0, 0, 0); GetScrollInfo(&scrollView, &frame); if (scrollView) { return scrollView->View()->GetBounds(); } if (frame && (frame->GetStyleDisplay()->mDisplay != NS_STYLE_DISPLAY_INLINE || frame->IsFrameOfType(nsIFrame::eReplaced))) { // Special case code to make client area work even when there isn't // a scroll view, see bug 180552, bug 227567. return frame->GetPaddingRect() - frame->GetPositionIgnoringScrolling(); } return nsRect(0, 0, 0, 0); } nsresult nsNSElementTearoff::GetClientTop(PRInt32* aLength) { NS_ENSURE_ARG_POINTER(aLength); *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().y); return NS_OK; } nsresult nsNSElementTearoff::GetClientLeft(PRInt32* aLength) { NS_ENSURE_ARG_POINTER(aLength); *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().x); return NS_OK; } nsresult nsNSElementTearoff::GetClientHeight(PRInt32* aLength) { NS_ENSURE_ARG_POINTER(aLength); *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().height); return NS_OK; } nsresult nsNSElementTearoff::GetClientWidth(PRInt32* aLength) { NS_ENSURE_ARG_POINTER(aLength); *aLength = nsPresContext::AppUnitsToIntCSSPixels(GetClientAreaRect().width); return NS_OK; } static nsIFrame* GetContainingBlockForClientRect(nsIFrame* aFrame) { // get the nearest enclosing SVG foreign object frame or the root frame while (aFrame->GetParent() && !aFrame->IsFrameOfType(nsIFrame::eSVGForeignObject)) { aFrame = aFrame->GetParent(); } return aFrame; } NS_IMETHODIMP nsNSElementTearoff::GetBoundingClientRect(nsIDOMClientRect** aResult) { // Weak ref, since we addref it below nsClientRect* rect = new nsClientRect(); if (!rect) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(*aResult = rect); nsIFrame* frame = mContent->GetPrimaryFrame(Flush_Layout); if (!frame) { // display:none, perhaps? Return the empty rect return NS_OK; } nsPresContext* presContext = frame->PresContext(); nsRect r = nsLayoutUtils::GetAllInFlowRectsUnion(frame, GetContainingBlockForClientRect(frame)); rect->SetLayoutRect(r, presContext); return NS_OK; } struct RectListBuilder : public nsLayoutUtils::RectCallback { nsPresContext* mPresContext; nsClientRectList* mRectList; nsresult mRV; RectListBuilder(nsPresContext* aPresContext, nsClientRectList* aList) : mPresContext(aPresContext), mRectList(aList), mRV(NS_OK) {} virtual void AddRect(const nsRect& aRect) { nsRefPtr<nsClientRect> rect = new nsClientRect(); if (!rect) { mRV = NS_ERROR_OUT_OF_MEMORY; return; } rect->SetLayoutRect(aRect, mPresContext); mRectList->Append(rect); } }; NS_IMETHODIMP nsNSElementTearoff::GetClientRects(nsIDOMClientRectList** aResult) { *aResult = nsnull; nsRefPtr<nsClientRectList> rectList = new nsClientRectList(); if (!rectList) return NS_ERROR_OUT_OF_MEMORY; nsIFrame* frame = mContent->GetPrimaryFrame(Flush_Layout); if (!frame) { // display:none, perhaps? Return an empty list *aResult = rectList.forget().get(); return NS_OK; } RectListBuilder builder(frame->PresContext(), rectList); nsLayoutUtils::GetAllInFlowRects(frame, GetContainingBlockForClientRect(frame), &builder); if (NS_FAILED(builder.mRV)) return builder.mRV; *aResult = rectList.forget().get(); return NS_OK; } //---------------------------------------------------------------------- NS_IMPL_ISUPPORTS1(nsNodeWeakReference, nsIWeakReference) nsNodeWeakReference::~nsNodeWeakReference() { if (mNode) { NS_ASSERTION(mNode->GetSlots() && mNode->GetSlots()->mWeakReference == this, "Weak reference has wrong value"); mNode->GetSlots()->mWeakReference = nsnull; } } NS_IMETHODIMP nsNodeWeakReference::QueryReferent(const nsIID& aIID, void** aInstancePtr) { return mNode ? mNode->QueryInterface(aIID, aInstancePtr) : NS_ERROR_NULL_POINTER; } NS_IMPL_CYCLE_COLLECTION_1(nsNodeSupportsWeakRefTearoff, mNode) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNodeSupportsWeakRefTearoff) NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) NS_INTERFACE_MAP_END_AGGREGATED(mNode) NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNodeSupportsWeakRefTearoff) NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNodeSupportsWeakRefTearoff) NS_IMETHODIMP nsNodeSupportsWeakRefTearoff::GetWeakReference(nsIWeakReference** aInstancePtr) { nsINode::nsSlots* slots = mNode->GetSlots(); NS_ENSURE_TRUE(slots, NS_ERROR_OUT_OF_MEMORY); if (!slots->mWeakReference) { slots->mWeakReference = new nsNodeWeakReference(mNode); NS_ENSURE_TRUE(slots->mWeakReference, NS_ERROR_OUT_OF_MEMORY); } NS_ADDREF(*aInstancePtr = slots->mWeakReference); return NS_OK; } //---------------------------------------------------------------------- nsDOMEventRTTearoff * nsDOMEventRTTearoff::mCachedEventTearoff[NS_EVENT_TEAROFF_CACHE_SIZE]; PRUint32 nsDOMEventRTTearoff::mCachedEventTearoffCount = 0; nsDOMEventRTTearoff::nsDOMEventRTTearoff(nsIContent *aContent) : mContent(aContent) { } nsDOMEventRTTearoff::~nsDOMEventRTTearoff() { } NS_IMPL_CYCLE_COLLECTION_1(nsDOMEventRTTearoff, mContent) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMEventRTTearoff) NS_INTERFACE_MAP_ENTRY(nsIDOMEventTarget) NS_INTERFACE_MAP_ENTRY(nsIDOM3EventTarget) NS_INTERFACE_MAP_ENTRY(nsIDOMNSEventTarget) NS_INTERFACE_MAP_END_AGGREGATED(mContent) NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsDOMEventRTTearoff, nsIDOMEventTarget) NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS_WITH_DESTROY(nsDOMEventRTTearoff, nsIDOMEventTarget, LastRelease()) nsDOMEventRTTearoff * nsDOMEventRTTearoff::Create(nsIContent *aContent) { if (mCachedEventTearoffCount) { // We have cached unused instances of this class, return a cached // instance in stead of always creating a new one. nsDOMEventRTTearoff *tearoff = mCachedEventTearoff[--mCachedEventTearoffCount]; // Set the back pointer to the content object tearoff->mContent = aContent; return tearoff; } // The cache is empty, this means we haveto create a new instance. return new nsDOMEventRTTearoff(aContent); } // static void nsDOMEventRTTearoff::Shutdown() { // Clear our cache. while (mCachedEventTearoffCount) { delete mCachedEventTearoff[--mCachedEventTearoffCount]; } } void nsDOMEventRTTearoff::LastRelease() { if (mCachedEventTearoffCount < NS_EVENT_TEAROFF_CACHE_SIZE) { // There's still space in the cache for one more instance, put // this instance in the cache in stead of deleting it. mCachedEventTearoff[mCachedEventTearoffCount++] = this; // Don't set mContent to null directly since setting mContent to null // could result in code that grabs a tearoff from the cache and we don't // want to get reused while still being torn down. // See bug 330526. nsCOMPtr<nsIContent> kungFuDeathGrip; kungFuDeathGrip.swap(mContent); // The refcount balancing and destructor re-entrancy protection // code in Release() sets mRefCnt to 1 so we have to set it to 0 // here to prevent leaks mRefCnt = 0; return; } delete this; } nsresult nsDOMEventRTTearoff::GetDOM3EventTarget(nsIDOM3EventTarget **aTarget) { nsCOMPtr<nsIEventListenerManager> listener_manager; nsresult rv = mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager)); NS_ENSURE_SUCCESS(rv, rv); return CallQueryInterface(listener_manager, aTarget); } NS_IMETHODIMP nsDOMEventRTTearoff::GetScriptTypeID(PRUint32 *aLang) { *aLang = mContent->GetScriptTypeID(); return NS_OK; } NS_IMETHODIMP nsDOMEventRTTearoff::SetScriptTypeID(PRUint32 aLang) { return mContent->SetScriptTypeID(aLang); } // nsIDOMEventTarget NS_IMETHODIMP nsDOMEventRTTearoff::AddEventListener(const nsAString& aType, nsIDOMEventListener *aListener, PRBool useCapture) { return AddEventListener(aType, aListener, useCapture, !nsContentUtils::IsChromeDoc(mContent->GetOwnerDoc())); } NS_IMETHODIMP nsDOMEventRTTearoff::RemoveEventListener(const nsAString& aType, nsIDOMEventListener* aListener, PRBool aUseCapture) { return RemoveGroupedEventListener(aType, aListener, aUseCapture, nsnull); } NS_IMETHODIMP nsDOMEventRTTearoff::DispatchEvent(nsIDOMEvent *aEvt, PRBool* _retval) { nsCOMPtr<nsIEventListenerManager> listener_manager; nsresult rv = mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(listener_manager); NS_ENSURE_STATE(target); return target->DispatchEvent(aEvt, _retval); } // nsIDOM3EventTarget NS_IMETHODIMP nsDOMEventRTTearoff::AddGroupedEventListener(const nsAString& aType, nsIDOMEventListener *aListener, PRBool aUseCapture, nsIDOMEventGroup *aEvtGrp) { nsCOMPtr<nsIDOM3EventTarget> event_target; nsresult rv = GetDOM3EventTarget(getter_AddRefs(event_target)); NS_ENSURE_SUCCESS(rv, rv); return event_target->AddGroupedEventListener(aType, aListener, aUseCapture, aEvtGrp); } NS_IMETHODIMP nsDOMEventRTTearoff::RemoveGroupedEventListener(const nsAString& aType, nsIDOMEventListener *aListener, PRBool aUseCapture, nsIDOMEventGroup *aEvtGrp) { nsCOMPtr<nsIDOM3EventTarget> event_target; nsresult rv = GetDOM3EventTarget(getter_AddRefs(event_target)); NS_ENSURE_SUCCESS(rv, rv); return event_target->RemoveGroupedEventListener(aType, aListener, aUseCapture, aEvtGrp); } NS_IMETHODIMP nsDOMEventRTTearoff::CanTrigger(const nsAString & type, PRBool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsDOMEventRTTearoff::IsRegisteredHere(const nsAString & type, PRBool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } // nsIDOMNSEventTarget NS_IMETHODIMP nsDOMEventRTTearoff::AddEventListener(const nsAString& aType, nsIDOMEventListener *aListener, PRBool aUseCapture, PRBool aWantsUntrusted) { nsCOMPtr<nsIEventListenerManager> listener_manager; nsresult rv = mContent->GetListenerManager(PR_TRUE, getter_AddRefs(listener_manager)); NS_ENSURE_SUCCESS(rv, rv); PRInt32 flags = aUseCapture ? NS_EVENT_FLAG_CAPTURE : NS_EVENT_FLAG_BUBBLE; if (aWantsUntrusted) { flags |= NS_PRIV_EVENT_UNTRUSTED_PERMITTED; } return listener_manager->AddEventListenerByType(aListener, aType, flags, nsnull); } //---------------------------------------------------------------------- NS_IMPL_CYCLE_COLLECTION_1(nsNodeSelectorTearoff, mContent) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsNodeSelectorTearoff) NS_INTERFACE_MAP_ENTRY(nsIDOMNodeSelector) NS_INTERFACE_MAP_END_AGGREGATED(mContent) NS_IMPL_CYCLE_COLLECTING_ADDREF(nsNodeSelectorTearoff) NS_IMPL_CYCLE_COLLECTING_RELEASE(nsNodeSelectorTearoff) NS_IMETHODIMP nsNodeSelectorTearoff::QuerySelector(const nsAString& aSelector, nsIDOMElement **aReturn) { return nsGenericElement::doQuerySelector(mContent, aSelector, aReturn); } NS_IMETHODIMP nsNodeSelectorTearoff::QuerySelectorAll(const nsAString& aSelector, nsIDOMNodeList **aReturn) { return nsGenericElement::doQuerySelectorAll(mContent, aSelector, aReturn); } //---------------------------------------------------------------------- nsGenericElement::nsDOMSlots::nsDOMSlots(PtrBits aFlags) : nsINode::nsSlots(aFlags), mBindingParent(nsnull) { } nsGenericElement::nsDOMSlots::~nsDOMSlots() { if (mStyle) { mStyle->DropReference(); } if (mAttributeMap) { mAttributeMap->DropReference(); } } nsGenericElement::nsGenericElement(nsINodeInfo *aNodeInfo) : nsIContent(aNodeInfo) { // Set the default scriptID to JS - but skip SetScriptTypeID as it // does extra work we know isn't necessary here... SetFlags(nsIProgrammingLanguage::JAVASCRIPT << NODE_SCRIPT_TYPE_OFFSET); } nsGenericElement::~nsGenericElement() { NS_PRECONDITION(!IsInDoc(), "Please remove this from the document properly"); } NS_IMETHODIMP nsGenericElement::GetNodeName(nsAString& aNodeName) { mNodeInfo->GetQualifiedName(aNodeName); return NS_OK; } NS_IMETHODIMP nsGenericElement::GetLocalName(nsAString& aLocalName) { mNodeInfo->GetLocalName(aLocalName); return NS_OK; } NS_IMETHODIMP nsGenericElement::GetNodeValue(nsAString& aNodeValue) { SetDOMStringToNull(aNodeValue); return NS_OK; } NS_IMETHODIMP nsGenericElement::SetNodeValue(const nsAString& aNodeValue) { // The DOM spec says that when nodeValue is defined to be null "setting it // has no effect", so we don't throw an exception. return NS_OK; } NS_IMETHODIMP nsGenericElement::GetNodeType(PRUint16* aNodeType) { *aNodeType = (PRUint16)nsIDOMNode::ELEMENT_NODE; return NS_OK; } NS_IMETHODIMP nsGenericElement::GetNamespaceURI(nsAString& aNamespaceURI) { return mNodeInfo->GetNamespaceURI(aNamespaceURI); } NS_IMETHODIMP nsGenericElement::GetPrefix(nsAString& aPrefix) { mNodeInfo->GetPrefix(aPrefix); return NS_OK; } NS_IMETHODIMP nsGenericElement::SetPrefix(const nsAString& aPrefix) { // XXX: Validate the prefix string! nsCOMPtr<nsIAtom> prefix; if (!aPrefix.IsEmpty()) { prefix = do_GetAtom(aPrefix); NS_ENSURE_TRUE(prefix, NS_ERROR_OUT_OF_MEMORY); } if (!nsContentUtils::IsValidNodeName(mNodeInfo->NameAtom(), prefix, mNodeInfo->NamespaceID())) { return NS_ERROR_DOM_NAMESPACE_ERR; } nsCOMPtr<nsINodeInfo> newNodeInfo; nsresult rv = nsContentUtils::PrefixChanged(mNodeInfo, prefix, getter_AddRefs(newNodeInfo)); NS_ENSURE_SUCCESS(rv, rv); mNodeInfo = newNodeInfo; return NS_OK; } nsresult nsGenericElement::InternalIsSupported(nsISupports* aObject, const nsAString& aFeature, const nsAString& aVersion, PRBool* aReturn) { NS_ENSURE_ARG_POINTER(aReturn); *aReturn = PR_FALSE; // Convert the incoming UTF16 strings to raw char*'s to save us some // code when doing all those string compares. NS_ConvertUTF16toUTF8 feature(aFeature); NS_ConvertUTF16toUTF8 version(aVersion); const char *f = feature.get(); const char *v = version.get(); if (PL_strcasecmp(f, "XML") == 0 || PL_strcasecmp(f, "HTML") == 0) { if (aVersion.IsEmpty() || PL_strcmp(v, "1.0") == 0 || PL_strcmp(v, "2.0") == 0) { *aReturn = PR_TRUE; } } else if (PL_strcasecmp(f, "Views") == 0 || PL_strcasecmp(f, "StyleSheets") == 0 || PL_strcasecmp(f, "Core") == 0 || PL_strcasecmp(f, "CSS") == 0 || PL_strcasecmp(f, "CSS2") == 0 || PL_strcasecmp(f, "Events") == 0 || PL_strcasecmp(f, "UIEvents") == 0 || PL_strcasecmp(f, "MouseEvents") == 0 || // Non-standard! PL_strcasecmp(f, "MouseScrollEvents") == 0 || PL_strcasecmp(f, "HTMLEvents") == 0 || PL_strcasecmp(f, "Range") == 0 || PL_strcasecmp(f, "XHTML") == 0) { if (aVersion.IsEmpty() || PL_strcmp(v, "2.0") == 0) { *aReturn = PR_TRUE; } } else if (PL_strcasecmp(f, "XPath") == 0) { if (aVersion.IsEmpty() || PL_strcmp(v, "3.0") == 0) { *aReturn = PR_TRUE; } } #ifdef MOZ_SVG else if (PL_strcasecmp(f, "SVGEvents") == 0 || PL_strcasecmp(f, "SVGZoomEvents") == 0 || NS_SVG_HaveFeature(aFeature)) { if (aVersion.IsEmpty() || PL_strcmp(v, "1.0") == 0 || PL_strcmp(v, "1.1") == 0) { *aReturn = PR_TRUE; } } #endif /* MOZ_SVG */ else { nsCOMPtr<nsIDOMNSFeatureFactory> factory = GetDOMFeatureFactory(aFeature, aVersion); if (factory) { factory->HasFeature(aObject, aFeature, aVersion, aReturn); } } return NS_OK; } nsresult nsGenericElement::InternalGetFeature(nsISupports* aObject, const nsAString& aFeature, const nsAString& aVersion, nsISupports** aReturn) { *aReturn = nsnull; nsCOMPtr<nsIDOMNSFeatureFactory> factory = GetDOMFeatureFactory(aFeature, aVersion); if (factory) { factory->GetFeature(aObject, aFeature, aVersion, aReturn); } return NS_OK; } already_AddRefed<nsIDOMNSFeatureFactory> nsGenericElement::GetDOMFeatureFactory(const nsAString& aFeature, const nsAString& aVersion) { nsIDOMNSFeatureFactory *factory = nsnull; nsCOMPtr<nsICategoryManager> categoryManager = do_GetService(NS_CATEGORYMANAGER_CONTRACTID); if (categoryManager) { nsCAutoString featureCategory(NS_DOMNS_FEATURE_PREFIX); AppendUTF16toUTF8(aFeature, featureCategory); nsXPIDLCString contractID; nsresult rv = categoryManager->GetCategoryEntry(featureCategory.get(), NS_ConvertUTF16toUTF8(aVersion).get(), getter_Copies(contractID)); if (NS_SUCCEEDED(rv)) { CallGetService(contractID.get(), &factory); // addrefs } } return factory; } NS_IMETHODIMP nsGenericElement::IsSupported(const nsAString& aFeature, const nsAString& aVersion, PRBool* aReturn) { return InternalIsSupported(this, aFeature, aVersion, aReturn); } NS_IMETHODIMP nsGenericElement::HasAttributes(PRBool* aReturn) { NS_ENSURE_ARG_POINTER(aReturn); *aReturn = GetAttrCount() > 0; return NS_OK; } NS_IMETHODIMP nsGenericElement::GetAttributes(nsIDOMNamedNodeMap** aAttributes) { NS_ENSURE_ARG_POINTER(aAttributes); nsDOMSlots *slots = GetDOMSlots(); if (!slots) { return NS_ERROR_OUT_OF_MEMORY; } if (!slots->mAttributeMap) { slots->mAttributeMap = new nsDOMAttributeMap(this); if (!slots->mAttributeMap) { return NS_ERROR_OUT_OF_MEMORY; } if (!slots->mAttributeMap->Init()) { slots->mAttributeMap = nsnull; return NS_ERROR_FAILURE; } } NS_ADDREF(*aAttributes = slots->mAttributeMap); return NS_OK; } nsresult nsGenericElement::HasChildNodes(PRBool* aReturn) { *aReturn = mAttrsAndChildren.ChildCount() > 0; return NS_OK; } NS_IMETHODIMP nsGenericElement::GetTagName(nsAString& aTagName) { mNodeInfo->GetQualifiedName(aTagName); return NS_OK; } nsresult nsGenericElement::GetAttribute(const nsAString& aName, nsAString& aReturn) { const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName); if (!name) { if (mNodeInfo->NamespaceID() == kNameSpaceID_XUL) { // XXX should be SetDOMStringToNull(aReturn); // See bug 232598 aReturn.Truncate(); } else { SetDOMStringToNull(aReturn); } return NS_OK; } GetAttr(name->NamespaceID(), name->LocalName(), aReturn); return NS_OK; } nsresult nsGenericElement::SetAttribute(const nsAString& aName, const nsAString& aValue) { const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName); if (!name) { nsresult rv = nsContentUtils::CheckQName(aName, PR_FALSE); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aName); NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY); return SetAttr(kNameSpaceID_None, nameAtom, aValue, PR_TRUE); } return SetAttr(name->NamespaceID(), name->LocalName(), name->GetPrefix(), aValue, PR_TRUE); } nsresult nsGenericElement::RemoveAttribute(const nsAString& aName) { const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName); if (!name) { return NS_OK; } // Hold a strong reference here so that the atom or nodeinfo doesn't go // away during UnsetAttr. If it did UnsetAttr would be left with a // dangling pointer as argument without knowing it. nsAttrName tmp(*name); return UnsetAttr(name->NamespaceID(), name->LocalName(), PR_TRUE); } nsresult nsGenericElement::GetAttributeNode(const nsAString& aName, nsIDOMAttr** aReturn) { NS_ENSURE_ARG_POINTER(aReturn); *aReturn = nsnull; nsCOMPtr<nsIDOMNamedNodeMap> map; nsresult rv = GetAttributes(getter_AddRefs(map)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMNode> node; rv = map->GetNamedItem(aName, getter_AddRefs(node)); if (NS_SUCCEEDED(rv) && node) { rv = CallQueryInterface(node, aReturn); } return rv; } nsresult nsGenericElement::SetAttributeNode(nsIDOMAttr* aAttribute, nsIDOMAttr** aReturn) { NS_ENSURE_ARG_POINTER(aReturn); NS_ENSURE_ARG_POINTER(aAttribute); *aReturn = nsnull; nsCOMPtr<nsIDOMNamedNodeMap> map; nsresult rv = GetAttributes(getter_AddRefs(map)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMNode> returnNode; rv = map->SetNamedItem(aAttribute, getter_AddRefs(returnNode)); NS_ENSURE_SUCCESS(rv, rv); if (returnNode) { rv = CallQueryInterface(returnNode, aReturn); } return rv; } nsresult nsGenericElement::RemoveAttributeNode(nsIDOMAttr* aAttribute, nsIDOMAttr** aReturn) { NS_ENSURE_ARG_POINTER(aReturn); NS_ENSURE_ARG_POINTER(aAttribute); *aReturn = nsnull; nsCOMPtr<nsIDOMNamedNodeMap> map; nsresult rv = GetAttributes(getter_AddRefs(map)); NS_ENSURE_SUCCESS(rv, rv); nsAutoString name; rv = aAttribute->GetName(name); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIDOMNode> node; rv = map->RemoveNamedItem(name, getter_AddRefs(node)); if (NS_SUCCEEDED(rv) && node) { rv = CallQueryInterface(node, aReturn); } } return rv; } nsresult nsGenericElement::GetElementsByTagName(const nsAString& aTagname, nsIDOMNodeList** aReturn) { nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aTagname); NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY); nsContentList *list = NS_GetContentList(this, nameAtom, kNameSpaceID_Unknown).get(); NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY); // transfer ref to aReturn *aReturn = list; return NS_OK; } nsresult nsGenericElement::GetAttributeNS(const nsAString& aNamespaceURI, const nsAString& aLocalName, nsAString& aReturn) { PRInt32 nsid = nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI); if (nsid == kNameSpaceID_Unknown) { // Unknown namespace means no attr... aReturn.Truncate(); return NS_OK; } nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName); GetAttr(nsid, name, aReturn); return NS_OK; } nsresult nsGenericElement::SetAttributeNS(const nsAString& aNamespaceURI, const nsAString& aQualifiedName, const nsAString& aValue) { nsCOMPtr<nsINodeInfo> ni; nsresult rv = nsContentUtils::GetNodeInfoFromQName(aNamespaceURI, aQualifiedName, mNodeInfo->NodeInfoManager(), getter_AddRefs(ni)); NS_ENSURE_SUCCESS(rv, rv); return SetAttr(ni->NamespaceID(), ni->NameAtom(), ni->GetPrefixAtom(), aValue, PR_TRUE); } nsresult nsGenericElement::RemoveAttributeNS(const nsAString& aNamespaceURI, const nsAString& aLocalName) { nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName); PRInt32 nsid = nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI); if (nsid == kNameSpaceID_Unknown) { // Unknown namespace means no attr... return NS_OK; } nsAutoString tmp; UnsetAttr(nsid, name, PR_TRUE); return NS_OK; } nsresult nsGenericElement::GetAttributeNodeNS(const nsAString& aNamespaceURI, const nsAString& aLocalName, nsIDOMAttr** aReturn) { NS_ENSURE_ARG_POINTER(aReturn); *aReturn = nsnull; nsCOMPtr<nsIDOMNamedNodeMap> map; nsresult rv = GetAttributes(getter_AddRefs(map)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMNode> node; rv = map->GetNamedItemNS(aNamespaceURI, aLocalName, getter_AddRefs(node)); if (NS_SUCCEEDED(rv) && node) { rv = CallQueryInterface(node, aReturn); } return rv; } nsresult nsGenericElement::SetAttributeNodeNS(nsIDOMAttr* aNewAttr, nsIDOMAttr** aReturn) { NS_ENSURE_ARG_POINTER(aReturn); NS_ENSURE_ARG_POINTER(aNewAttr); *aReturn = nsnull; nsCOMPtr<nsIDOMNamedNodeMap> map; nsresult rv = GetAttributes(getter_AddRefs(map)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMNode> returnNode; rv = map->SetNamedItemNS(aNewAttr, getter_AddRefs(returnNode)); NS_ENSURE_SUCCESS(rv, rv); if (returnNode) { rv = CallQueryInterface(returnNode, aReturn); } return rv; } nsresult nsGenericElement::GetElementsByTagNameNS(const nsAString& aNamespaceURI, const nsAString& aLocalName, nsIDOMNodeList** aReturn) { PRInt32 nameSpaceId = kNameSpaceID_Wildcard; if (!aNamespaceURI.EqualsLiteral("*")) { nsresult rv = nsContentUtils::NameSpaceManager()->RegisterNameSpace(aNamespaceURI, nameSpaceId); NS_ENSURE_SUCCESS(rv, rv); } nsCOMPtr<nsIAtom> nameAtom = do_GetAtom(aLocalName); NS_ENSURE_TRUE(nameAtom, NS_ERROR_OUT_OF_MEMORY); nsContentList *list = NS_GetContentList(this, nameAtom, nameSpaceId).get(); NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY); // transfer ref to aReturn *aReturn = list; return NS_OK; } nsresult nsGenericElement::HasAttribute(const nsAString& aName, PRBool* aReturn) { NS_ENSURE_ARG_POINTER(aReturn); const nsAttrName* name = InternalGetExistingAttrNameFromQName(aName); *aReturn = (name != nsnull); return NS_OK; } nsresult nsGenericElement::HasAttributeNS(const nsAString& aNamespaceURI, const nsAString& aLocalName, PRBool* aReturn) { NS_ENSURE_ARG_POINTER(aReturn); PRInt32 nsid = nsContentUtils::NameSpaceManager()->GetNameSpaceID(aNamespaceURI); if (nsid == kNameSpaceID_Unknown) { // Unknown namespace means no attr... *aReturn = PR_FALSE; return NS_OK; } nsCOMPtr<nsIAtom> name = do_GetAtom(aLocalName); *aReturn = HasAttr(nsid, name); return NS_OK; } nsresult nsGenericElement::JoinTextNodes(nsIContent* aFirst, nsIContent* aSecond) { nsresult rv = NS_OK; nsCOMPtr<nsIDOMText> firstText(do_QueryInterface(aFirst, &rv)); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIDOMText> secondText(do_QueryInterface(aSecond, &rv)); if (NS_SUCCEEDED(rv)) { nsAutoString str; rv = secondText->GetData(str); if (NS_SUCCEEDED(rv)) { rv = firstText->AppendData(str); } } } return rv; } nsresult nsGenericElement::Normalize() { // Batch possible DOMSubtreeModified events. mozAutoSubtreeModified subtree(GetOwnerDoc(), nsnull); nsresult result = NS_OK; PRUint32 index, count = GetChildCount(); for (index = 0; (index < count) && (NS_OK == result); index++) { nsIContent *child = GetChildAt(index); nsCOMPtr<nsIDOMNode> node = do_QueryInterface(child); if (node) { PRUint16 nodeType; node->GetNodeType(&nodeType); switch (nodeType) { case nsIDOMNode::TEXT_NODE: // ensure that if the text node is empty, it is removed if (0 == child->TextLength()) { result = RemoveChildAt(index, PR_TRUE); if (NS_FAILED(result)) { return result; } count--; index--; break; } if (index+1 < count) { // Get the sibling. If it's also a text node, then // remove it from the tree and join the two text // nodes. nsIContent *sibling = GetChildAt(index + 1); nsCOMPtr<nsIDOMNode> siblingNode = do_QueryInterface(sibling); if (siblingNode) { PRUint16 siblingNodeType; siblingNode->GetNodeType(&siblingNodeType); if (siblingNodeType == nsIDOMNode::TEXT_NODE) { result = RemoveChildAt(index+1, PR_TRUE); if (NS_FAILED(result)) { return result; } result = JoinTextNodes(child, sibling); if (NS_FAILED(result)) { return result; } count--; index--; } } } break; case nsIDOMNode::ELEMENT_NODE: nsCOMPtr<nsIDOMElement> element = do_QueryInterface(child); if (element) { result = element->Normalize(); } break; } } } return result; } static nsXBLBinding* GetFirstBindingWithContent(nsBindingManager* aBmgr, nsIContent* aBoundElem) { nsXBLBinding* binding = aBmgr->GetBinding(aBoundElem); while (binding) { if (binding->GetAnonymousContent()) { return binding; } binding = binding->GetBaseBinding(); } return nsnull; } static nsresult BindNodesInInsertPoints(nsXBLBinding* aBinding, nsIContent* aInsertParent, nsIDocument* aDocument) { NS_PRECONDITION(aBinding && aInsertParent, "Missing arguments"); nsresult rv; // These should be refcounted or otherwise protectable. nsInsertionPointList* inserts = aBinding->GetExistingInsertionPointsFor(aInsertParent); if (inserts) { PRBool allowScripts = aBinding->AllowScripts(); #ifdef MOZ_XUL nsCOMPtr<nsIXULDocument> xulDoc = do_QueryInterface(aDocument); #endif PRUint32 i; for (i = 0; i < inserts->Length(); ++i) { nsCOMPtr<nsIContent> insertRoot = inserts->ElementAt(i)->GetDefaultContent(); if (insertRoot) { PRUint32 j; for (j = 0; j < insertRoot->GetChildCount(); ++j) { nsCOMPtr<nsIContent> child = insertRoot->GetChildAt(j); rv = child->BindToTree(aDocument, aInsertParent, aBinding->GetBoundElement(), allowScripts); NS_ENSURE_SUCCESS(rv, rv); #ifdef MOZ_XUL if (xulDoc) { xulDoc->AddSubtreeToDocument(child); } #endif } } } } return NS_OK; } nsresult nsGenericElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent, nsIContent* aBindingParent, PRBool aCompileEventHandlers) { NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!"); NS_PRECONDITION(HasSameOwnerDoc(NODE_FROM(aParent, aDocument)), "Must have the same owner document"); NS_PRECONDITION(!aParent || aDocument == aParent->GetCurrentDoc(), "aDocument must be current doc of aParent"); NS_PRECONDITION(!GetCurrentDoc(), "Already have a document. Unbind first!"); // Note that as we recurse into the kids, they'll have a non-null parent. So // only assert if our parent is _changing_ while we have a parent. NS_PRECONDITION(!GetParent() || aParent == GetParent(), "Already have a parent. Unbind first!"); NS_PRECONDITION(!GetBindingParent() || aBindingParent == GetBindingParent() || (!aBindingParent && aParent && aParent->GetBindingParent() == GetBindingParent()), "Already have a binding parent. Unbind first!"); NS_PRECONDITION(!aParent || !aDocument || !aParent->HasFlag(NODE_FORCE_XBL_BINDINGS), "Parent in document but flagged as forcing XBL"); NS_PRECONDITION(aBindingParent != this, "Content must not be its own binding parent"); NS_PRECONDITION(!IsRootOfNativeAnonymousSubtree() || aBindingParent == aParent, "Native anonymous content must have its parent as its " "own binding parent"); if (!aBindingParent && aParent) { aBindingParent = aParent->GetBindingParent(); } #ifdef MOZ_XUL // First set the binding parent nsXULElement* xulElem = nsXULElement::FromContent(this); if (xulElem) { xulElem->SetXULBindingParent(aBindingParent); } else #endif { if (aBindingParent) { nsDOMSlots *slots = GetDOMSlots(); if (!slots) { return NS_ERROR_OUT_OF_MEMORY; } slots->mBindingParent = aBindingParent; // Weak, so no addref happens. } } NS_ASSERTION(!aBindingParent || IsRootOfNativeAnonymousSubtree() || !HasFlag(NODE_IS_IN_ANONYMOUS_SUBTREE) || (aParent && aParent->IsInNativeAnonymousSubtree()), "Trying to re-bind content from native anonymous subtree to " "non-native anonymous parent!"); if (aParent && aParent->IsInNativeAnonymousSubtree()) { SetFlags(NODE_IS_IN_ANONYMOUS_SUBTREE); } PRBool hadForceXBL = HasFlag(NODE_FORCE_XBL_BINDINGS); // Now set the parent and set the "Force attach xbl" flag if needed. if (aParent) { mParentPtrBits = reinterpret_cast<PtrBits>(aParent) | PARENT_BIT_PARENT_IS_CONTENT; if (aParent->HasFlag(NODE_FORCE_XBL_BINDINGS)) { SetFlags(NODE_FORCE_XBL_BINDINGS); } } else { mParentPtrBits = reinterpret_cast<PtrBits>(aDocument); } // XXXbz sXBL/XBL2 issue! // Finally, set the document if (aDocument) { // Notify XBL- & nsIAnonymousContentCreator-generated // anonymous content that the document is changing. // XXXbz ordering issues here? Probably not, since ChangeDocumentFor is // just pretty broken anyway.... Need to get it working. // XXXbz XBL doesn't handle this (asserts), and we don't really want // to be doing this during parsing anyway... sort this out. // aDocument->BindingManager()->ChangeDocumentFor(this, nsnull, // aDocument); // Being added to a document. mParentPtrBits |= PARENT_BIT_INDOCUMENT; // Unset this flag since we now really are in a document. UnsetFlags(NODE_FORCE_XBL_BINDINGS); } // If NODE_FORCE_XBL_BINDINGS was set we might have anonymous children // that also need to be told that they are moving. nsresult rv; if (hadForceXBL) { nsIDocument* ownerDoc = GetOwnerDoc(); if (ownerDoc) { nsBindingManager* bmgr = ownerDoc->BindingManager(); // First check if we have a binding... nsXBLBinding* contBinding = GetFirstBindingWithContent(bmgr, this); if (contBinding) { nsCOMPtr<nsIContent> anonRoot = contBinding->GetAnonymousContent(); PRBool allowScripts = contBinding->AllowScripts(); PRUint32 i; for (i = 0; i < anonRoot->GetChildCount(); ++i) { nsCOMPtr<nsIContent> child = anonRoot->GetChildAt(i); rv = child->BindToTree(aDocument, this, this, allowScripts); NS_ENSURE_SUCCESS(rv, rv); } // ...then check if we have content in insertion points that are // direct children of the <content> rv = BindNodesInInsertPoints(contBinding, this, aDocument); NS_ENSURE_SUCCESS(rv, rv); } // ...and finally check if we're in a binding where we have content in // insertion points. if (aBindingParent) { nsXBLBinding* binding = bmgr->GetBinding(aBindingParent); if (binding) { rv = BindNodesInInsertPoints(binding, this, aDocument); NS_ENSURE_SUCCESS(rv, rv); } } } } UpdateEditableState(); // Now recurse into our kids PRUint32 i; // Don't call GetChildCount() here since that'll make XUL generate // template children, which we're not in a consistent enough state for. // Additionally, there's not really a need to generate the children here. for (i = 0; i < mAttrsAndChildren.ChildCount(); ++i) { // The child can remove itself from the parent in BindToTree. nsCOMPtr<nsIContent> child = mAttrsAndChildren.ChildAt(i); rv = child->BindToTree(aDocument, this, aBindingParent, aCompileEventHandlers); NS_ENSURE_SUCCESS(rv, rv); } nsNodeUtils::ParentChainChanged(this); // XXXbz script execution during binding can trigger some of these // postcondition asserts.... But we do want that, since things will // generally be quite broken when that happens. NS_POSTCONDITION(aDocument == GetCurrentDoc(), "Bound to wrong document"); NS_POSTCONDITION(aParent == GetParent(), "Bound to wrong parent"); NS_POSTCONDITION(aBindingParent == GetBindingParent(), "Bound to wrong binding parent"); return NS_OK; } void nsGenericElement::UnbindFromTree(PRBool aDeep, PRBool aNullParent) { NS_PRECONDITION(aDeep || (!GetCurrentDoc() && !GetBindingParent()), "Shallow unbind won't clear document and binding parent on " "kids!"); // Make sure to unbind this node before doing the kids nsIDocument *document = HasFlag(NODE_FORCE_XBL_BINDINGS) ? GetOwnerDoc() : GetCurrentDoc(); mParentPtrBits = aNullParent ? 0 : mParentPtrBits & ~PARENT_BIT_INDOCUMENT; if (document) { // Notify XBL- & nsIAnonymousContentCreator-generated // anonymous content that the document is changing. document->BindingManager()->ChangeDocumentFor(this, document, nsnull); if (HasAttr(kNameSpaceID_XLink, nsGkAtoms::href)) { document->ForgetLink(this); } document->ClearBoxObjectFor(this); } // Unset this since that's what the old code effectively did. UnsetFlags(NODE_FORCE_XBL_BINDINGS); #ifdef MOZ_XUL nsXULElement* xulElem = nsXULElement::FromContent(this); if (xulElem) { xulElem->SetXULBindingParent(nsnull); } else #endif { nsDOMSlots *slots = GetExistingDOMSlots(); if (slots) { slots->mBindingParent = nsnull; } } if (aDeep) { // Do the kids. Don't call GetChildCount() here since that'll force // XUL to generate template children, which there is no need for since // all we're going to do is unbind them anyway. PRUint32 i, n = mAttrsAndChildren.ChildCount(); for (i = 0; i < n; ++i) { // Note that we pass PR_FALSE for aNullParent here, since we don't want // the kids to forget us. We _do_ want them to forget their binding // parent, though, since this only walks non-anonymous kids. mAttrsAndChildren.ChildAt(i)->UnbindFromTree(PR_TRUE, PR_FALSE); } } nsNodeUtils::ParentChainChanged(this); } nsresult nsGenericElement::PreHandleEvent(nsEventChainPreVisitor& aVisitor) { return nsGenericElement::doPreHandleEvent(this, aVisitor); } static nsIContent* FindNativeAnonymousSubtreeOwner(nsIContent* aContent) { if (aContent->IsInNativeAnonymousSubtree()) { PRBool isNativeAnon = PR_FALSE; while (aContent && !isNativeAnon) { isNativeAnon = aContent->IsRootOfNativeAnonymousSubtree(); aContent = aContent->GetParent(); } } return aContent; } nsresult nsGenericElement::doPreHandleEvent(nsIContent* aContent, nsEventChainPreVisitor& aVisitor) { //FIXME! Document how this event retargeting works, Bug 329124. aVisitor.mCanHandle = PR_TRUE; // Don't propagate mouseover and mouseout events when mouse is moving // inside native anonymous content. PRBool isAnonForEvents = aContent->IsRootOfNativeAnonymousSubtree(); if ((aVisitor.mEvent->message == NS_MOUSE_ENTER_SYNTH || aVisitor.mEvent->message == NS_MOUSE_EXIT_SYNTH) && // Check if we should stop event propagation when event has just been // dispatched or when we're about to propagate from // native anonymous subtree. ((static_cast<nsISupports*>(aContent) == aVisitor.mEvent->originalTarget && !aContent->IsInNativeAnonymousSubtree()) || isAnonForEvents)) { nsCOMPtr<nsIContent> relatedTarget = do_QueryInterface(static_cast<nsMouseEvent*> (aVisitor.mEvent)->relatedTarget); if (relatedTarget && relatedTarget->GetOwnerDoc() == aContent->GetOwnerDoc()) { // If current target is anonymous for events or we know that related // target is descendant of an element which is anonymous for events, // we may want to stop event propagation. // If aContent is the original target, aVisitor.mRelatedTargetIsInAnon // must be updated. if (isAnonForEvents || aVisitor.mRelatedTargetIsInAnon || (aVisitor.mEvent->originalTarget == aContent && (aVisitor.mRelatedTargetIsInAnon = relatedTarget->IsInNativeAnonymousSubtree()))) { nsIContent* anonOwner = FindNativeAnonymousSubtreeOwner(aContent); if (anonOwner) { nsIContent* anonOwnerRelated = FindNativeAnonymousSubtreeOwner(relatedTarget); if (anonOwnerRelated) { // Note, anonOwnerRelated may still be inside some other // native anonymous subtree. The case where anonOwner is still // inside native anonymous subtree will be handled when event // propagates up in the DOM tree. while (anonOwner != anonOwnerRelated && anonOwnerRelated->IsInNativeAnonymousSubtree()) { anonOwnerRelated = FindNativeAnonymousSubtreeOwner(anonOwnerRelated); } if (anonOwner == anonOwnerRelated) { #ifdef DEBUG_smaug nsCOMPtr<nsIContent> originalTarget = do_QueryInterface(aVisitor.mEvent->originalTarget); nsAutoString ot, ct, rt; if (originalTarget) { originalTarget->Tag()->ToString(ot); } aContent->Tag()->ToString(ct); relatedTarget->Tag()->ToString(rt); printf("Stopping %s propagation:" "\n\toriginalTarget=%s \n\tcurrentTarget=%s %s" "\n\trelatedTarget=%s %s \n%s", (aVisitor.mEvent->message == NS_MOUSE_ENTER_SYNTH) ? "mouseover" : "mouseout", NS_ConvertUTF16toUTF8(ot).get(), NS_ConvertUTF16toUTF8(ct).get(), isAnonForEvents ? "(is native anonymous)" : (aContent->IsInNativeAnonymousSubtree() ? "(is in native anonymous subtree)" : ""), NS_ConvertUTF16toUTF8(rt).get(), relatedTarget->IsInNativeAnonymousSubtree() ? "(is in native anonymous subtree)" : "", (originalTarget && relatedTarget->FindFirstNonNativeAnonymous() == originalTarget->FindFirstNonNativeAnonymous()) ? "" : "Wrong event propagation!?!\n"); #endif aVisitor.mParentTarget = nsnull; // Event should not propagate to non-anon content. aVisitor.mCanHandle = isAnonForEvents; return NS_OK; } } } } } } nsCOMPtr<nsIContent> parent = aContent->GetParent(); if (isAnonForEvents) { // If a DOM event is explicitly dispatched using node.dispatchEvent(), then // all the events are allowed even in the native anonymous content.. NS_ASSERTION(aVisitor.mEvent->eventStructType != NS_MUTATION_EVENT || aVisitor.mDOMEvent, "Mutation event dispatched in native anonymous content!?!"); aVisitor.mEventTargetAtParent = parent; } else if (parent) { nsCOMPtr<nsIContent> content(do_QueryInterface(aVisitor.mEvent->target)); if (content && content->GetBindingParent() == parent) { aVisitor.mEventTargetAtParent = parent; } } // check for an anonymous parent // XXX XBL2/sXBL issue nsIDocument* ownerDoc = aContent->GetOwnerDoc(); if (ownerDoc) { nsIContent* insertionParent = ownerDoc->BindingManager()-> GetInsertionParent(aContent); NS_ASSERTION(!(aVisitor.mEventTargetAtParent && insertionParent && aVisitor.mEventTargetAtParent != insertionParent), "Retargeting and having insertion parent!"); if (insertionParent) { parent = insertionParent; } } if (parent) { aVisitor.mParentTarget = parent; } else { aVisitor.mParentTarget = aContent->GetCurrentDoc(); } return NS_OK; } nsresult nsGenericElement::PostHandleEvent(nsEventChainPostVisitor& /*aVisitor*/) { return NS_OK; } nsresult nsGenericElement::DispatchDOMEvent(nsEvent* aEvent, nsIDOMEvent* aDOMEvent, nsPresContext* aPresContext, nsEventStatus* aEventStatus) { return nsEventDispatcher::DispatchDOMEvent(static_cast<nsIContent*>(this), aEvent, aDOMEvent, aPresContext, aEventStatus); } nsIAtom* nsGenericElement::GetID() const { if (!HasFlag(NODE_MAY_HAVE_ID)) { return nsnull; } nsIAtom* IDName = GetIDAttributeName(); if (IDName) { const nsAttrValue* attrVal = mAttrsAndChildren.GetAttr(IDName); if (attrVal){ if (attrVal->Type() == nsAttrValue::eAtom) { return attrVal->GetAtomValue(); } if(attrVal->IsEmptyString()){ return nsnull; } // Check if the ID has been stored as a string. // This would occur if the ID attribute name changed after // the ID was parsed. if (attrVal->Type() == nsAttrValue::eString) { nsAutoString idVal(attrVal->GetStringValue()); // Create an atom from the value and set it into the attribute list. const_cast<nsAttrValue*>(attrVal)->ParseAtom(idVal); return attrVal->GetAtomValue(); } } } return nsnull; } const nsAttrValue* nsGenericElement::DoGetClasses() const { NS_NOTREACHED("Shouldn't ever be called"); return nsnull; } NS_IMETHODIMP nsGenericElement::WalkContentStyleRules(nsRuleWalker* aRuleWalker) { return NS_OK; } nsICSSStyleRule* nsGenericElement::GetInlineStyleRule() { return nsnull; } NS_IMETHODIMP nsGenericElement::SetInlineStyleRule(nsICSSStyleRule* aStyleRule, PRBool aNotify) { NS_NOTYETIMPLEMENTED("nsGenericElement::SetInlineStyleRule"); return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP_(PRBool) nsGenericElement::IsAttributeMapped(const nsIAtom* aAttribute) const { return PR_FALSE; } nsChangeHint nsGenericElement::GetAttributeChangeHint(const nsIAtom* aAttribute, PRInt32 aModType) const { return nsChangeHint(0); } nsIAtom * nsGenericElement::GetIDAttributeName() const { return mNodeInfo->GetIDAttributeAtom(); } nsIAtom * nsGenericElement::GetClassAttributeName() const { return nsnull; } PRBool nsGenericElement::FindAttributeDependence(const nsIAtom* aAttribute, const MappedAttributeEntry* const aMaps[], PRUint32 aMapCount) { for (PRUint32 mapindex = 0; mapindex < aMapCount; ++mapindex) { for (const MappedAttributeEntry* map = aMaps[mapindex]; map->attribute; ++map) { if (aAttribute == *map->attribute) { return PR_TRUE; } } } return PR_FALSE; } already_AddRefed<nsINodeInfo> nsGenericElement::GetExistingAttrNameFromQName(const nsAString& aStr) const { const nsAttrName* name = InternalGetExistingAttrNameFromQName(aStr); if (!name) { return nsnull; } nsINodeInfo* nodeInfo; if (name->IsAtom()) { nodeInfo = mNodeInfo->NodeInfoManager()->GetNodeInfo(name->Atom(), nsnull, kNameSpaceID_None).get(); } else { NS_ADDREF(nodeInfo = name->NodeInfo()); } return nodeInfo; } already_AddRefed<nsIURI> nsGenericElement::GetBaseURI() const { nsIDocument* doc = GetOwnerDoc(); if (!doc) { // We won't be able to do security checks, etc. So don't go any // further. That said, this really shouldn't happen... NS_ERROR("Element without owner document"); return nsnull; } // Our base URL depends on whether we have an xml:base attribute, as // well as on whether any of our ancestors do. nsCOMPtr<nsIURI> parentBase; nsIContent *parent = GetParent(); if (parent) { parentBase = parent->GetBaseURI(); } else { // No parent, so just use the document (we must be the root or not in the // tree). parentBase = doc->GetBaseURI(); } // Now check for an xml:base attr nsAutoString value; GetAttr(kNameSpaceID_XML, nsGkAtoms::base, value); if (value.IsEmpty()) { // No xml:base, so we just use the parent's base URL nsIURI *base = nsnull; parentBase.swap(base); return base; } nsCOMPtr<nsIURI> ourBase; nsresult rv = NS_NewURI(getter_AddRefs(ourBase), value, doc->GetDocumentCharacterSet().get(), parentBase); if (NS_SUCCEEDED(rv)) { // do a security check, almost the same as nsDocument::SetBaseURL() rv = nsContentUtils::GetSecurityManager()-> CheckLoadURIWithPrincipal(NodePrincipal(), ourBase, nsIScriptSecurityManager::STANDARD); } nsIURI *base; if (NS_FAILED(rv)) { base = parentBase; } else { base = ourBase; } NS_IF_ADDREF(base); return base; } PRBool nsGenericElement::IsLink(nsIURI** aURI) const { *aURI = nsnull; return PR_FALSE; } void nsGenericElement::SetFocus(nsPresContext* aPresContext) { // Traditionally focusable elements can take focus as long as they don't set // the disabled attribute nsCOMPtr<nsIPresShell> presShell = aPresContext->PresShell(); if (!presShell) { return; } nsIFrame* frame = presShell->GetPrimaryFrameFor(this); if (frame && frame->IsFocusable() && aPresContext->EventStateManager()->SetContentState(this, NS_EVENT_STATE_FOCUS)) { presShell->ScrollContentIntoView(this, NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE, NS_PRESSHELL_SCROLL_IF_NOT_VISIBLE); } } // static PRBool nsGenericElement::ShouldFocus(nsIContent *aContent) { // Default to false, since if the document is not attached to a window, // we should not focus any of its content. PRBool visible = PR_FALSE; // Figure out if we're focusing an element in an inactive (hidden) // tab (whose docshell is not visible), if so, drop this focus // request on the floor nsIDocument *document = aContent->GetDocument(); if (document) { nsIScriptGlobalObject *sgo = document->GetScriptGlobalObject(); if (sgo) { nsCOMPtr<nsIWebNavigation> webNav(do_GetInterface(sgo)); nsCOMPtr<nsIBaseWindow> baseWin(do_QueryInterface(webNav)); if (baseWin) { baseWin->GetVisibility(&visible); } } } return visible; } // static PRBool nsGenericElement::ShouldBlur(nsIContent *aContent) { // Determine if the current element is focused, if it is not focused // then we should not try to blur PRBool isFocused = PR_FALSE; nsIDocument *document = aContent->GetDocument(); if (document) { nsPIDOMWindow *win = document->GetWindow(); if (win) { nsCOMPtr<nsIFocusController> focusController = win->GetRootFocusController(); if (focusController) { nsCOMPtr<nsIDOMElement> focusedElement; focusController->GetFocusedElement(getter_AddRefs(focusedElement)); nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(aContent); //when the element is the same as the focused element, blur it if (domElement == focusedElement) isFocused = PR_TRUE; } } } return isFocused; } nsIContent* nsGenericElement::GetBindingParent() const { nsDOMSlots *slots = GetExistingDOMSlots(); if (slots) { return slots->mBindingParent; } return nsnull; } PRBool nsGenericElement::IsNodeOfType(PRUint32 aFlags) const { return !(aFlags & ~(eCONTENT | eELEMENT)); } //---------------------------------------------------------------------- // virtual void nsGenericElement::SetMayHaveFrame(PRBool aMayHaveFrame) { if (aMayHaveFrame) { SetFlags(NODE_MAY_HAVE_FRAME); } else { UnsetFlags(NODE_MAY_HAVE_FRAME); } } // virtual PRBool nsGenericElement::MayHaveFrame() const { return HasFlag(NODE_MAY_HAVE_FRAME); } PRUint32 nsGenericElement::GetScriptTypeID() const { PtrBits flags = GetFlags(); /* 4 bits reserved for script-type ID. */ return (flags >> NODE_SCRIPT_TYPE_OFFSET) & 0x000F; } nsresult nsGenericElement::SetScriptTypeID(PRUint32 aLang) { if ((aLang & 0x000F) != aLang) { NS_ERROR("script ID too large!"); return NS_ERROR_FAILURE; } /* SetFlags will just mask in the specific flags set, leaving existing ones alone. So we must clear all the bits first */ UnsetFlags(0x000FU << NODE_SCRIPT_TYPE_OFFSET); SetFlags(aLang << NODE_SCRIPT_TYPE_OFFSET); return NS_OK; } nsresult nsGenericElement::InsertChildAt(nsIContent* aKid, PRUint32 aIndex, PRBool aNotify) { NS_PRECONDITION(aKid, "null ptr"); return doInsertChildAt(aKid, aIndex, aNotify, this, GetCurrentDoc(), mAttrsAndChildren); } /* static */ nsresult nsGenericElement::doInsertChildAt(nsIContent* aKid, PRUint32 aIndex, PRBool aNotify, nsIContent* aParent, nsIDocument* aDocument, nsAttrAndChildArray& aChildArray) { NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!"); NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument, "Incorrect aDocument"); nsresult rv; nsINode* container = NODE_FROM(aParent, aDocument); if (!container->HasSameOwnerDoc(aKid)) { nsCOMPtr<nsIDOMNode> kid = do_QueryInterface(aKid, &rv); NS_ENSURE_SUCCESS(rv, rv); PRUint16 nodeType = 0; rv = kid->GetNodeType(&nodeType); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOM3Document> domDoc = do_QueryInterface(container->GetOwnerDoc()); // DocumentType nodes are the only nodes that can have a null // ownerDocument according to the DOM spec, and we need to allow // inserting them w/o calling AdoptNode(). if (domDoc && (nodeType != nsIDOMNode::DOCUMENT_TYPE_NODE || aKid->GetOwnerDoc())) { nsCOMPtr<nsIDOMNode> adoptedKid; rv = domDoc->AdoptNode(kid, getter_AddRefs(adoptedKid)); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(adoptedKid == kid, "Uh, adopt node changed nodes?"); } } PRUint32 childCount = aChildArray.ChildCount(); NS_ENSURE_TRUE(aIndex <= childCount, NS_ERROR_ILLEGAL_VALUE); nsMutationGuard::DidMutate(); PRBool isAppend = (aIndex == childCount); mozAutoDocUpdate updateBatch(aDocument, UPDATE_CONTENT_MODEL, aNotify); rv = aChildArray.InsertChildAt(aKid, aIndex); NS_ENSURE_SUCCESS(rv, rv); rv = aKid->BindToTree(aDocument, aParent, nsnull, PR_TRUE); if (NS_FAILED(rv)) { aChildArray.RemoveChildAt(aIndex); aKid->UnbindFromTree(); return rv; } // The kid may have removed its parent from the document, so recheck that // that's still in the document before proceeding. Also, the kid may have // just removed itself, in which case we don't really want to fire // ContentAppended or a mutation event. // XXXbz What if the kid just moved us in the document? Scripts suck. We // really need to stop running them while we're in the middle of modifying // the DOM.... if (aNotify && aKid->GetNodeParent() == container) { // Note that we always want to call ContentInserted when things are added // as kids to documents if (aParent && isAppend) { nsNodeUtils::ContentAppended(aParent, aIndex); } else { nsNodeUtils::ContentInserted(container, aKid, aIndex); } if (nsContentUtils::HasMutationListeners(aKid, NS_EVENT_BITS_MUTATION_NODEINSERTED, container)) { mozAutoRemovableBlockerRemover blockerRemover(container->GetOwnerDoc()); nsMutationEvent mutation(PR_TRUE, NS_MUTATION_NODEINSERTED); mutation.mRelatedNode = do_QueryInterface(container); mozAutoSubtreeModified subtree(container->GetOwnerDoc(), container); nsEventDispatcher::Dispatch(aKid, nsnull, &mutation); } } return NS_OK; } nsresult nsGenericElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify) { nsCOMPtr<nsIContent> oldKid = mAttrsAndChildren.GetSafeChildAt(aIndex); NS_ASSERTION(oldKid == GetChildAt(aIndex), "Unexpected child in RemoveChildAt"); if (oldKid) { return doRemoveChildAt(aIndex, aNotify, oldKid, this, GetCurrentDoc(), mAttrsAndChildren); } return NS_OK; } /* static */ nsresult nsGenericElement::doRemoveChildAt(PRUint32 aIndex, PRBool aNotify, nsIContent* aKid, nsIContent* aParent, nsIDocument* aDocument, nsAttrAndChildArray& aChildArray) { NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!"); NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument, "Incorrect aDocument"); #ifdef ACCESSIBILITY // A11y needs to be notified of content removals first, so accessibility // events can be fired before any changes occur if (aNotify && aDocument) { nsIPresShell *presShell = aDocument->GetPrimaryShell(); if (presShell && presShell->IsAccessibilityActive()) { nsCOMPtr<nsIAccessibilityService> accService = do_GetService("@mozilla.org/accessibilityService;1"); if (accService) { accService->InvalidateSubtreeFor(presShell, aKid, nsIAccessibleEvent::EVENT_DOM_DESTROY); } } } #endif nsMutationGuard::DidMutate(); nsINode* container = NODE_FROM(aParent, aDocument); NS_PRECONDITION(aKid && aKid->GetParent() == aParent && aKid == container->GetChildAt(aIndex) && container->IndexOf(aKid) == (PRInt32)aIndex, "Bogus aKid"); mozAutoDocUpdate updateBatch(aDocument, UPDATE_CONTENT_MODEL, aNotify); nsMutationGuard guard; mozAutoSubtreeModified subtree(nsnull, nsnull); if (aNotify && nsContentUtils::HasMutationListeners(aKid, NS_EVENT_BITS_MUTATION_NODEREMOVED, container)) { mozAutoRemovableBlockerRemover blockerRemover(container->GetOwnerDoc()); nsMutationEvent mutation(PR_TRUE, NS_MUTATION_NODEREMOVED); mutation.mRelatedNode = do_QueryInterface(container); subtree.UpdateTarget(container->GetOwnerDoc(), container); nsEventDispatcher::Dispatch(aKid, nsnull, &mutation); } // Someone may have removed the kid or any of its siblings while that event // was processing. if (guard.Mutated(0)) { aIndex = container->IndexOf(aKid); if (static_cast<PRInt32>(aIndex) < 0) { return NS_OK; } } aChildArray.RemoveChildAt(aIndex); if (aNotify) { nsNodeUtils::ContentRemoved(container, aKid, aIndex); } aKid->UnbindFromTree(); return NS_OK; } /* static */ nsresult nsGenericElement::DispatchEvent(nsPresContext* aPresContext, nsEvent* aEvent, nsIContent* aTarget, PRBool aFullDispatch, nsEventStatus* aStatus) { NS_PRECONDITION(aTarget, "Must have target"); NS_PRECONDITION(aEvent, "Must have source event"); NS_PRECONDITION(aStatus, "Null out param?"); if (!aPresContext) { return NS_OK; } nsCOMPtr<nsIPresShell> shell = aPresContext->GetPresShell(); if (!shell) { return NS_OK; } if (aFullDispatch) { return shell->HandleEventWithTarget(aEvent, nsnull, aTarget, aStatus); } return shell->HandleDOMEventWithTarget(aTarget, aEvent, aStatus); } /* static */ nsresult nsGenericElement::DispatchClickEvent(nsPresContext* aPresContext, nsInputEvent* aSourceEvent, nsIContent* aTarget, PRBool aFullDispatch, nsEventStatus* aStatus) { NS_PRECONDITION(aTarget, "Must have target"); NS_PRECONDITION(aSourceEvent, "Must have source event"); NS_PRECONDITION(aStatus, "Null out param?"); nsMouseEvent event(NS_IS_TRUSTED_EVENT(aSourceEvent), NS_MOUSE_CLICK, aSourceEvent->widget, nsMouseEvent::eReal); event.refPoint = aSourceEvent->refPoint; PRUint32 clickCount = 1; if (aSourceEvent->eventStructType == NS_MOUSE_EVENT) { clickCount = static_cast<nsMouseEvent*>(aSourceEvent)->clickCount; } event.clickCount = clickCount; event.isShift = aSourceEvent->isShift; event.isControl = aSourceEvent->isControl; event.isAlt = aSourceEvent->isAlt; event.isMeta = aSourceEvent->isMeta; return DispatchEvent(aPresContext, &event, aTarget, aFullDispatch, aStatus); } nsIFrame* nsGenericElement::GetPrimaryFrame() { nsIDocument* doc = GetCurrentDoc(); if (!doc) { return nsnull; } return GetPrimaryFrameFor(this, doc); } nsIFrame* nsGenericElement::GetPrimaryFrame(mozFlushType aType) { nsIDocument* doc = GetCurrentDoc(); if (!doc) { return nsnull; } // Cause a flush, so we get up-to-date frame // information doc->FlushPendingNotifications(aType); return GetPrimaryFrameFor(this, doc); } /* static */ nsIFrame* nsGenericElement::GetPrimaryFrameFor(nsIContent* aContent, nsIDocument* aDocument) { // Get presentation shell 0 nsIPresShell *presShell = aDocument->GetPrimaryShell(); if (!presShell) { return nsnull; } return presShell->GetPrimaryFrameFor(aContent); } void nsGenericElement::DestroyContent() { nsIDocument *document = GetOwnerDoc(); if (document) { document->BindingManager()->ChangeDocumentFor(this, document, nsnull); document->ClearBoxObjectFor(this); } // XXX We really should let cycle collection do this, but that currently still // leaks (see https://bugzilla.mozilla.org/show_bug.cgi?id=406684). ReleaseWrapper(); PRUint32 i, count = mAttrsAndChildren.ChildCount(); for (i = 0; i < count; ++i) { // The child can remove itself from the parent in BindToTree. mAttrsAndChildren.ChildAt(i)->DestroyContent(); } } void nsGenericElement::SaveSubtreeState() { PRUint32 i, count = mAttrsAndChildren.ChildCount(); for (i = 0; i < count; ++i) { mAttrsAndChildren.ChildAt(i)->SaveSubtreeState(); } } //---------------------------------------------------------------------- // Generic DOMNode implementations /* * This helper function checks if aChild is the same as aNode or if * aChild is one of aNode's ancestors. -- jst@citec.fi */ NS_IMETHODIMP nsGenericElement::InsertBefore(nsIDOMNode *aNewChild, nsIDOMNode *aRefChild, nsIDOMNode **aReturn) { return doReplaceOrInsertBefore(PR_FALSE, aNewChild, aRefChild, this, GetCurrentDoc(), aReturn); } NS_IMETHODIMP nsGenericElement::ReplaceChild(nsIDOMNode* aNewChild, nsIDOMNode* aOldChild, nsIDOMNode** aReturn) { return doReplaceOrInsertBefore(PR_TRUE, aNewChild, aOldChild, this, GetCurrentDoc(), aReturn); } NS_IMETHODIMP nsGenericElement::RemoveChild(nsIDOMNode *aOldChild, nsIDOMNode **aReturn) { return doRemoveChild(aOldChild, this, GetCurrentDoc(), aReturn); } // When replacing, aRefContent is the content being replaced; when // inserting it's the content before which we're inserting. In the // latter case it may be null. static PRBool IsAllowedAsChild(nsIContent* aNewChild, PRUint16 aNewNodeType, nsIContent* aParent, nsIDocument* aDocument, PRBool aIsReplace, nsIContent* aRefContent) { NS_PRECONDITION(aNewChild, "Must have new child"); NS_PRECONDITION(!aIsReplace || aRefContent, "Must have ref content for replace"); #ifdef DEBUG PRUint16 debugNodeType = 0; nsCOMPtr<nsIDOMNode> debugNode(do_QueryInterface(aNewChild)); nsresult debugRv = debugNode->GetNodeType(&debugNodeType); NS_PRECONDITION(NS_SUCCEEDED(debugRv) && debugNodeType == aNewNodeType, "Bogus node type passed"); #endif if (aParent && nsContentUtils::ContentIsDescendantOf(aParent, aNewChild)) { return PR_FALSE; } // The allowed child nodes differ for documents and elements switch (aNewNodeType) { case nsIDOMNode::COMMENT_NODE : case nsIDOMNode::PROCESSING_INSTRUCTION_NODE : // OK in both cases return PR_TRUE; case nsIDOMNode::TEXT_NODE : case nsIDOMNode::CDATA_SECTION_NODE : case nsIDOMNode::ENTITY_REFERENCE_NODE : // Only allowed under elements return aParent != nsnull; case nsIDOMNode::ELEMENT_NODE : { if (aParent) { // Always ok to have elements under other elements return PR_TRUE; } nsIContent* rootContent = aDocument->GetRootContent(); if (rootContent) { // Already have a documentElement, so this is only OK if we're // replacing it. return aIsReplace && rootContent == aRefContent; } // We don't have a documentElement yet. Our one remaining constraint is // that the documentElement must come after the doctype. if (!aRefContent) { // Appending is just fine. return PR_TRUE; } // Now grovel for a doctype nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDocument); NS_ASSERTION(doc, "Shouldn't happen"); nsCOMPtr<nsIDOMDocumentType> docType; doc->GetDoctype(getter_AddRefs(docType)); nsCOMPtr<nsIContent> docTypeContent = do_QueryInterface(docType); if (!docTypeContent) { // It's all good. return PR_TRUE; } PRInt32 doctypeIndex = aDocument->IndexOf(docTypeContent); PRInt32 insertIndex = aDocument->IndexOf(aRefContent); // Now we're OK in the following two cases only: // 1) We're replacing something that's not before the doctype // 2) We're inserting before something that comes after the doctype return aIsReplace ? (insertIndex >= doctypeIndex) : insertIndex > doctypeIndex; } case nsIDOMNode::DOCUMENT_TYPE_NODE : { if (aParent) { // no doctypes allowed under elements return PR_FALSE; } nsCOMPtr<nsIDOMDocument> doc = do_QueryInterface(aDocument); NS_ASSERTION(doc, "Shouldn't happen"); nsCOMPtr<nsIDOMDocumentType> docType; doc->GetDoctype(getter_AddRefs(docType)); nsCOMPtr<nsIContent> docTypeContent = do_QueryInterface(docType); if (docTypeContent) { // Already have a doctype, so this is only OK if we're replacing it return aIsReplace && docTypeContent == aRefContent; } // We don't have a doctype yet. Our one remaining constraint is // that the doctype must come before the documentElement. nsIContent* rootContent = aDocument->GetRootContent(); if (!rootContent) { // It's all good return PR_TRUE; } if (!aRefContent) { // Trying to append a doctype, but have a documentElement return PR_FALSE; } PRInt32 rootIndex = aDocument->IndexOf(rootContent); PRInt32 insertIndex = aDocument->IndexOf(aRefContent); // Now we're OK if and only if insertIndex <= rootIndex. Indeed, either // we end up replacing aRefContent or we end up before it. Either one is // ok as long as aRefContent is not after rootContent. return insertIndex <= rootIndex; } case nsIDOMNode::DOCUMENT_FRAGMENT_NODE : { // Note that for now we only allow nodes inside document fragments if // they're allowed inside elements. If we ever change this to allow // doctype nodes in document fragments, we'll need to update this code if (aParent) { // All good here return PR_TRUE; } PRBool sawElement = PR_FALSE; PRUint32 count = aNewChild->GetChildCount(); for (PRUint32 index = 0; index < count; ++index) { nsIContent* childContent = aNewChild->GetChildAt(index); NS_ASSERTION(childContent, "Something went wrong"); if (childContent->IsNodeOfType(nsINode::eELEMENT)) { if (sawElement) { // Can't put two elements into a document return PR_FALSE; } sawElement = PR_TRUE; } // If we can put this content at the the right place, we might be ok; // if not, we bail out. nsCOMPtr<nsIDOMNode> childNode(do_QueryInterface(childContent)); PRUint16 type; childNode->GetNodeType(&type); if (!IsAllowedAsChild(childContent, type, aParent, aDocument, aIsReplace, aRefContent)) { return PR_FALSE; } } // Everything in the fragment checked out ok, so we can stick it in here return PR_TRUE; } default: /* * aNewChild is of invalid type. */ break; } return PR_FALSE; } /* static */ nsresult nsGenericElement::doReplaceOrInsertBefore(PRBool aReplace, nsIDOMNode* aNewChild, nsIDOMNode* aRefChild, nsIContent* aParent, nsIDocument* aDocument, nsIDOMNode** aReturn) { NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!"); NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument, "Incorrect aDocument"); *aReturn = nsnull; if (!aNewChild || (aReplace && !aRefChild)) { return NS_ERROR_NULL_POINTER; } // Keep a strong reference to the node that we'll return to ensure it // doesn't go away. nsCOMPtr<nsIDOMNode> returnVal = aReplace ? aRefChild : aNewChild; nsCOMPtr<nsIContent> refContent; nsresult res = NS_OK; PRInt32 insPos; nsINode* container = NODE_FROM(aParent, aDocument); // Figure out which index to insert at if (aRefChild) { refContent = do_QueryInterface(aRefChild); insPos = container->IndexOf(refContent); if (insPos < 0) { return NS_ERROR_DOM_NOT_FOUND_ERR; } if (aRefChild == aNewChild) { NS_ADDREF(*aReturn = aNewChild); return NS_OK; } } else { insPos = container->GetChildCount(); } nsCOMPtr<nsIContent> newContent = do_QueryInterface(aNewChild); if (!newContent) { return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR; } PRUint16 nodeType = 0; res = aNewChild->GetNodeType(&nodeType); NS_ENSURE_SUCCESS(res, res); // Make sure that the inserted node is allowed as a child of its new parent. if (!IsAllowedAsChild(newContent, nodeType, aParent, aDocument, aReplace, refContent)) { return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR; } // DocumentType nodes are the only nodes that can have a null // ownerDocument according to the DOM spec, and we need to allow // inserting them w/o calling AdoptNode(). if (!container->HasSameOwnerDoc(newContent) && (nodeType != nsIDOMNode::DOCUMENT_TYPE_NODE || newContent->GetOwnerDoc())) { nsCOMPtr<nsIDOM3Document> domDoc = do_QueryInterface(aDocument); if (domDoc) { nsCOMPtr<nsIDOMNode> adoptedKid; nsresult rv = domDoc->AdoptNode(aNewChild, getter_AddRefs(adoptedKid)); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(adoptedKid == aNewChild, "Uh, adopt node changed nodes?"); } } // We want an update batch when we expect several mutations to be performed, // which is when we're replacing a node, or when we're inserting a fragment. mozAutoDocConditionalContentUpdateBatch(aDocument, aReplace || nodeType == nsIDOMNode::DOCUMENT_FRAGMENT_NODE); // If we're replacing if (aReplace) { // Getting (and addrefing) the following child here is sort of wasteful // in the common case, but really, it's not that expensive. Get over it. refContent = container->GetChildAt(insPos + 1); nsMutationGuard guard; res = container->RemoveChildAt(insPos, PR_TRUE); NS_ENSURE_SUCCESS(res, res); if (guard.Mutated(1)) { insPos = refContent ? container->IndexOf(refContent) : container->GetChildCount(); if (insPos < 0) { return NS_ERROR_DOM_NOT_FOUND_ERR; } // Passing PR_FALSE for aIsReplace since we now have removed the node // to be replaced. if (!IsAllowedAsChild(newContent, nodeType, aParent, aDocument, PR_FALSE, refContent)) { return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR; } } } /* * Check if we're inserting a document fragment. If we are, we need * to remove the children of the document fragment and add them * individually (i.e. we don't add the actual document fragment). */ if (nodeType == nsIDOMNode::DOCUMENT_FRAGMENT_NODE) { PRUint32 count = newContent->GetChildCount(); // Copy the children into a separate array to avoid having to deal with // mutations to the fragment while we're inserting. nsCOMArray<nsIContent> fragChildren; if (!fragChildren.SetCapacity(count)) { return NS_ERROR_OUT_OF_MEMORY; } PRUint32 i; for (i = 0; i < count; i++) { nsIContent* child = newContent->GetChildAt(i); NS_ASSERTION(child->GetCurrentDoc() == nsnull, "How did we get a child with a current doc?"); fragChildren.AppendObject(child); } // Remove the children from the fragment and flag for possible mutations. PRBool mutated = PR_FALSE; for (i = count; i > 0;) { // We don't need to update i if someone mutates the DOM. The only thing // that'd happen is that the resulting child list might be unexpected, // but we should never crash since RemoveChildAt is out-of-bounds safe. nsMutationGuard guard; newContent->RemoveChildAt(--i, PR_TRUE); mutated = mutated || guard.Mutated(1); } // Iterate through the fragment's children, and insert them in the new // parent for (i = 0; i < count; ++i) { // Get the n:th child from the array. nsIContent* childContent = fragChildren[i]; // If we've had any unexpeted mutations so far we need to recheck that // the child can still be inserted. if (mutated) { // We really only need to update insPos if we *just* got an unexpected // mutation as opposed to 3 insertions ago. But this is an edgecase so // no need to over optimize. insPos = refContent ? container->IndexOf(refContent) : container->GetChildCount(); if (insPos < 0) { // Someone seriously messed up the childlist. We have no idea // where to insert the remaining children, so just bail. return NS_ERROR_DOM_NOT_FOUND_ERR; } nsCOMPtr<nsIDOMNode> tmpNode = do_QueryInterface(childContent); PRUint16 tmpType = 0; tmpNode->GetNodeType(&tmpType); if (childContent->GetNodeParent() || !IsAllowedAsChild(childContent, tmpType, aParent, aDocument, PR_FALSE, refContent)) { return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR; } } nsMutationGuard guard; // XXXbz how come no reparenting here? That seems odd... // Insert the child. res = container->InsertChildAt(childContent, insPos, PR_TRUE); NS_ENSURE_SUCCESS(res, res); // Check to see if any evil mutation events mucked around with the // child list. mutated = mutated || guard.Mutated(1); ++insPos; } } else { // Not inserting a fragment but rather a single node. if (newContent->IsRootOfAnonymousSubtree()) { // This is anonymous content. Don't allow its insertion // anywhere, since it might have UnbindFromTree calls coming // its way. return NS_ERROR_DOM_NOT_SUPPORTED_ERR; } // Remove the element from the old parent if one exists nsINode* oldParent = newContent->GetNodeParent(); if (oldParent) { PRInt32 removeIndex = oldParent->IndexOf(newContent); if (removeIndex < 0) { // newContent is anonymous. We can't deal with this, so just bail NS_ERROR("How come our flags didn't catch this?"); return NS_ERROR_DOM_NOT_SUPPORTED_ERR; } NS_ASSERTION(!(oldParent == container && removeIndex == insPos), "invalid removeIndex"); nsMutationGuard guard; res = oldParent->RemoveChildAt(removeIndex, PR_TRUE); NS_ENSURE_SUCCESS(res, res); // Adjust insert index if the node we ripped out was a sibling // of the node we're inserting before if (oldParent == container && removeIndex < insPos) { --insPos; } if (guard.Mutated(1)) { insPos = refContent ? container->IndexOf(refContent) : container->GetChildCount(); if (insPos < 0) { // Someone seriously messed up the childlist. We have no idea // where to insert the new child, so just bail. return NS_ERROR_DOM_NOT_FOUND_ERR; } if (newContent->GetNodeParent() || !IsAllowedAsChild(newContent, nodeType, aParent, aDocument, PR_FALSE, refContent)) { return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR; } } } if (!newContent->IsNodeOfType(eXUL)) { nsContentUtils::ReparentContentWrapper(newContent, aParent, container->GetOwnerDoc(), container->GetOwnerDoc()); } res = container->InsertChildAt(newContent, insPos, PR_TRUE); NS_ENSURE_SUCCESS(res, res); } returnVal.swap(*aReturn); return res; } /* static */ nsresult nsGenericElement::doRemoveChild(nsIDOMNode* aOldChild, nsIContent* aParent, nsIDocument* aDocument, nsIDOMNode** aReturn) { NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!"); NS_PRECONDITION(!aParent || aParent->GetCurrentDoc() == aDocument, "Incorrect aDocument"); *aReturn = nsnull; NS_ENSURE_TRUE(aOldChild, NS_ERROR_NULL_POINTER); nsINode* container = NODE_FROM(aParent, aDocument); nsCOMPtr<nsIContent> content = do_QueryInterface(aOldChild); // fix children to be a passed argument PRInt32 index = container->IndexOf(content); if (index == -1) { // aOldChild isn't one of our children. return NS_ERROR_DOM_NOT_FOUND_ERR; } nsresult rv = container->RemoveChildAt(index, PR_TRUE); *aReturn = aOldChild; NS_ADDREF(aOldChild); return rv; } //---------------------------------------------------------------------- // nsISupports implementation NS_IMPL_CYCLE_COLLECTION_CLASS(nsGenericElement) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGenericElement) NS_IMPL_CYCLE_COLLECTION_UNLINK_LISTENERMANAGER NS_IMPL_CYCLE_COLLECTION_UNLINK_USERDATA NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER if (tmp->HasProperties() && tmp->IsNodeOfType(nsINode::eXUL)) { tmp->DeleteProperty(nsGkAtoms::contextmenulistener); tmp->DeleteProperty(nsGkAtoms::popuplistener); } // Unlink child content (and unbind our subtree). { PRUint32 childCount = tmp->mAttrsAndChildren.ChildCount(); if (childCount) { // Don't allow script to run while we're unbinding everything. nsAutoScriptBlocker scriptBlocker; while (childCount-- > 0) { // Once we have XPCOMGC we shouldn't need to call UnbindFromTree. // We could probably do a non-deep unbind here when IsInDoc is false // for better performance. tmp->mAttrsAndChildren.ChildAt(childCount)->UnbindFromTree(); tmp->mAttrsAndChildren.RemoveChildAt(childCount); } } } // Unlink any DOM slots of interest. { nsDOMSlots *slots = tmp->GetExistingDOMSlots(); if (slots) { if (slots->mAttributeMap) { slots->mAttributeMap->DropReference(); slots->mAttributeMap = nsnull; } if (tmp->IsNodeOfType(nsINode::eXUL)) NS_IF_RELEASE(slots->mControllers); slots->mChildrenList = nsnull; } } NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsGenericElement) nsIDocument* currentDoc = tmp->GetCurrentDoc(); if (currentDoc && nsCCUncollectableMarker::InGeneration( currentDoc->GetMarkedCCGeneration())) { return NS_SUCCESS_INTERRUPTED_TRAVERSE; } nsIDocument* ownerDoc = tmp->GetOwnerDoc(); if (ownerDoc) { ownerDoc->BindingManager()->Traverse(tmp, cb); } NS_IMPL_CYCLE_COLLECTION_TRAVERSE_LISTENERMANAGER NS_IMPL_CYCLE_COLLECTION_TRAVERSE_USERDATA NS_IMPL_CYCLE_COLLECTION_TRAVERSE_PRESERVED_WRAPPER if (tmp->HasProperties() && tmp->IsNodeOfType(nsINode::eXUL)) { nsISupports* property = static_cast<nsISupports*> (tmp->GetProperty(nsGkAtoms::contextmenulistener)); cb.NoteXPCOMChild(property); property = static_cast<nsISupports*> (tmp->GetProperty(nsGkAtoms::popuplistener)); cb.NoteXPCOMChild(property); } // Traverse attribute names and child content. { PRUint32 i; PRUint32 attrs = tmp->mAttrsAndChildren.AttrCount(); for (i = 0; i < attrs; i++) { const nsAttrName* name = tmp->mAttrsAndChildren.AttrNameAt(i); if (!name->IsAtom()) { NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mAttrsAndChildren[i]->NodeInfo()"); cb.NoteXPCOMChild(name->NodeInfo()); } } PRUint32 kids = tmp->mAttrsAndChildren.ChildCount(); for (i = 0; i < kids; i++) { NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mAttrsAndChildren[i]"); cb.NoteXPCOMChild(tmp->mAttrsAndChildren.GetSafeChildAt(i)); } } NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mNodeInfo) // Traverse any DOM slots of interest. { nsDOMSlots *slots = tmp->GetExistingDOMSlots(); if (slots) { cb.NoteXPCOMChild(slots->mAttributeMap.get()); if (tmp->IsNodeOfType(nsINode::eXUL)) cb.NoteXPCOMChild(slots->mControllers); cb.NoteXPCOMChild( static_cast<nsIDOMNodeList*>(slots->mChildrenList.get())); } } NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_INTERFACE_MAP_BEGIN(nsGenericElement) NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsGenericElement) NS_INTERFACE_MAP_ENTRY(nsIContent) NS_INTERFACE_MAP_ENTRY(nsINode) NS_INTERFACE_MAP_ENTRY(nsPIDOMEventTarget) NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOM3Node, new nsNode3Tearoff(this)) NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMNSElement, new nsNSElementTearoff(this)) NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMEventTarget, nsDOMEventRTTearoff::Create(this)) NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOM3EventTarget, nsDOMEventRTTearoff::Create(this)) NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMNSEventTarget, nsDOMEventRTTearoff::Create(this)) NS_INTERFACE_MAP_ENTRY_TEAROFF(nsISupportsWeakReference, new nsNodeSupportsWeakRefTearoff(this)) NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMNodeSelector, new nsNodeSelectorTearoff(this)) // nsNodeSH::PreCreate() depends on the identity pointer being the // same as nsINode (which nsIContent inherits), so if you change the // below line, make sure nsNodeSH::PreCreate() still does the right // thing! NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIContent) NS_INTERFACE_MAP_END NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsGenericElement, nsIContent) NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS_WITH_DESTROY(nsGenericElement, nsIContent, nsNodeUtils::LastRelease(this)) nsresult nsGenericElement::PostQueryInterface(REFNSIID aIID, void** aInstancePtr) { nsIDocument *document = GetOwnerDoc(); if (document) { return document->BindingManager()->GetBindingImplementation(this, aIID, aInstancePtr); } *aInstancePtr = nsnull; return NS_ERROR_NO_INTERFACE; } //---------------------------------------------------------------------- nsresult nsGenericElement::LeaveLink(nsPresContext* aPresContext) { nsILinkHandler *handler = aPresContext->GetLinkHandler(); if (!handler) { return NS_OK; } return handler->OnLeaveLink(); } nsresult nsGenericElement::AddScriptEventListener(nsIAtom* aEventName, const nsAString& aValue, PRBool aDefer) { nsIDocument *ownerDoc = GetOwnerDoc(); if (!ownerDoc || ownerDoc->IsLoadedAsData()) { // Make this a no-op rather than throwing an error to avoid // the error causing problems setting the attribute. return NS_OK; } NS_PRECONDITION(aEventName, "Must have event name!"); nsCOMPtr<nsISupports> target; PRBool defer = PR_TRUE; nsCOMPtr<nsIEventListenerManager> manager; nsresult rv = GetEventListenerManagerForAttr(getter_AddRefs(manager), getter_AddRefs(target), &defer); NS_ENSURE_SUCCESS(rv, rv); if (manager) { defer = defer && aDefer; // only defer if everyone agrees... PRUint32 lang = GetScriptTypeID(); rv = manager->AddScriptEventListener(target, aEventName, aValue, lang, defer, !nsContentUtils::IsChromeDoc(ownerDoc)); } return rv; } //---------------------------------------------------------------------- const nsAttrName* nsGenericElement::InternalGetExistingAttrNameFromQName(const nsAString& aStr) const { return mAttrsAndChildren.GetExistingAttrNameFromQName( NS_ConvertUTF16toUTF8(aStr)); } nsresult nsGenericElement::CopyInnerTo(nsGenericElement* aDst) const { PRUint32 i, count = mAttrsAndChildren.AttrCount(); for (i = 0; i < count; ++i) { const nsAttrName* name = mAttrsAndChildren.AttrNameAt(i); const nsAttrValue* value = mAttrsAndChildren.AttrAt(i); nsAutoString valStr; value->ToString(valStr); nsresult rv = aDst->SetAttr(name->NamespaceID(), name->LocalName(), name->GetPrefix(), valStr, PR_FALSE); NS_ENSURE_SUCCESS(rv, rv); } return NS_OK; } nsresult nsGenericElement::SetAttr(PRInt32 aNamespaceID, nsIAtom* aName, nsIAtom* aPrefix, const nsAString& aValue, PRBool aNotify) { NS_ENSURE_ARG_POINTER(aName); NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown, "Don't call SetAttr with unknown namespace"); nsIDocument* doc = GetCurrentDoc(); if (kNameSpaceID_XLink == aNamespaceID && nsGkAtoms::href == aName) { // XLink URI(s) might be changing. Drop the link from the map. If it // is still style relevant it will be re-added by // nsStyleUtil::IsLink. Make sure to keep the style system // consistent so this remains true! In particular if the style system // were to get smarter and not restyling an XLink element if the href // doesn't change in a "significant" way, we'd need to do the same // significance check here. if (doc) { doc->ForgetLink(this); } } nsAutoString oldValue; PRBool modification = PR_FALSE; PRBool hasListeners = aNotify && nsContentUtils::HasMutationListeners(this, NS_EVENT_BITS_MUTATION_ATTRMODIFIED, this); // If we have no listeners and aNotify is false, we are almost certainly // coming from the content sink and will almost certainly have no previous // value. Even if we do, setting the value is cheap when we have no // listeners and don't plan to notify. The check for aNotify here is an // optimization, the check for haveListeners is a correctness issue. if (hasListeners || aNotify) { nsAttrInfo info(GetAttrInfo(aNamespaceID, aName)); if (info.mValue) { // Check whether the old value is the same as the new one. Note that we // only need to actually _get_ the old value if we have listeners. PRBool valueMatches; if (hasListeners) { // Need to store the old value info.mValue->ToString(oldValue); valueMatches = aValue.Equals(oldValue); } else if (aNotify) { valueMatches = info.mValue->Equals(aValue, eCaseMatters); } if (valueMatches && aPrefix == info.mName->GetPrefix()) { return NS_OK; } modification = PR_TRUE; } } nsresult rv = BeforeSetAttr(aNamespaceID, aName, &aValue, aNotify); NS_ENSURE_SUCCESS(rv, rv); nsAttrValue attrValue; if (!ParseAttribute(aNamespaceID, aName, aValue, attrValue)) { attrValue.SetTo(aValue); } return SetAttrAndNotify(aNamespaceID, aName, aPrefix, oldValue, attrValue, modification, hasListeners, aNotify, &aValue); } nsresult nsGenericElement::SetAttrAndNotify(PRInt32 aNamespaceID, nsIAtom* aName, nsIAtom* aPrefix, const nsAString& aOldValue, nsAttrValue& aParsedValue, PRBool aModification, PRBool aFireMutation, PRBool aNotify, const nsAString* aValueForAfterSetAttr) { nsresult rv; PRUint8 modType = aModification ? static_cast<PRUint8>(nsIDOMMutationEvent::MODIFICATION) : static_cast<PRUint8>(nsIDOMMutationEvent::ADDITION); nsIDocument* document = GetCurrentDoc(); mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, aNotify); // When notifying, make sure to keep track of states whose value // depends solely on the value of an attribute. PRUint32 stateMask; if (aNotify) { stateMask = PRUint32(IntrinsicState()); if (document) { document->AttributeWillChange(this, aNamespaceID, aName); } } if (aNamespaceID == kNameSpaceID_None) { // XXXbz Perhaps we should push up the attribute mapping function // stuff to nsGenericElement? if (!IsAttributeMapped(aName) || !SetMappedAttribute(document, aName, aParsedValue, &rv)) { rv = mAttrsAndChildren.SetAndTakeAttr(aName, aParsedValue); } } else { nsCOMPtr<nsINodeInfo> ni; ni = mNodeInfo->NodeInfoManager()->GetNodeInfo(aName, aPrefix, aNamespaceID); NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY); rv = mAttrsAndChildren.SetAndTakeAttr(ni, aParsedValue); } NS_ENSURE_SUCCESS(rv, rv); if (document || HasFlag(NODE_FORCE_XBL_BINDINGS)) { nsIDocument* ownerDoc = GetOwnerDoc(); if (ownerDoc) { nsRefPtr<nsXBLBinding> binding = ownerDoc->BindingManager()->GetBinding(this); if (binding) { binding->AttributeChanged(aName, aNamespaceID, PR_FALSE, aNotify); } } } if (aNotify) { stateMask = stateMask ^ PRUint32(IntrinsicState()); if (stateMask && document) { MOZ_AUTO_DOC_UPDATE(document, UPDATE_CONTENT_STATE, aNotify); document->ContentStatesChanged(this, nsnull, stateMask); } nsNodeUtils::AttributeChanged(this, aNamespaceID, aName, modType, stateMask); } if (aNamespaceID == kNameSpaceID_XMLEvents && aName == nsGkAtoms::event && mNodeInfo->GetDocument()) { mNodeInfo->GetDocument()->AddXMLEventsContent(this); } if (aValueForAfterSetAttr) { rv = AfterSetAttr(aNamespaceID, aName, aValueForAfterSetAttr, aNotify); NS_ENSURE_SUCCESS(rv, rv); } if (aFireMutation) { mozAutoRemovableBlockerRemover blockerRemover(GetOwnerDoc()); nsMutationEvent mutation(PR_TRUE, NS_MUTATION_ATTRMODIFIED); nsAutoString attrName; aName->ToString(attrName); nsCOMPtr<nsIDOMAttr> attrNode; nsAutoString ns; nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNamespaceID, ns); GetAttributeNodeNS(ns, attrName, getter_AddRefs(attrNode)); mutation.mRelatedNode = attrNode; mutation.mAttrName = aName; nsAutoString newValue; GetAttr(aNamespaceID, aName, newValue); if (!newValue.IsEmpty()) { mutation.mNewAttrValue = do_GetAtom(newValue); } if (!aOldValue.IsEmpty()) { mutation.mPrevAttrValue = do_GetAtom(aOldValue); } mutation.mAttrChange = modType; mozAutoSubtreeModified subtree(GetOwnerDoc(), this); nsEventDispatcher::Dispatch(this, nsnull, &mutation); } return NS_OK; } PRBool nsGenericElement::ParseAttribute(PRInt32 aNamespaceID, nsIAtom* aAttribute, const nsAString& aValue, nsAttrValue& aResult) { if (aNamespaceID == kNameSpaceID_None && aAttribute == GetIDAttributeName() && !aValue.IsEmpty()) { SetFlags(NODE_MAY_HAVE_ID); // Store id as an atom. id="" means that the element has no id, // not that it has an emptystring as the id. aResult.ParseAtom(aValue); return PR_TRUE; } return PR_FALSE; } PRBool nsGenericElement::SetMappedAttribute(nsIDocument* aDocument, nsIAtom* aName, nsAttrValue& aValue, nsresult* aRetval) { *aRetval = NS_OK; return PR_FALSE; } nsresult nsGenericElement::GetEventListenerManagerForAttr(nsIEventListenerManager** aManager, nsISupports** aTarget, PRBool* aDefer) { nsresult rv = GetListenerManager(PR_TRUE, aManager); if (NS_SUCCEEDED(rv)) { NS_ADDREF(*aTarget = static_cast<nsIContent*>(this)); } *aDefer = PR_TRUE; return rv; } nsGenericElement::nsAttrInfo nsGenericElement::GetAttrInfo(PRInt32 aNamespaceID, nsIAtom* aName) const { NS_ASSERTION(nsnull != aName, "must have attribute name"); NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown, "must have a real namespace ID!"); PRInt32 index = mAttrsAndChildren.IndexOfAttr(aName, aNamespaceID); if (index >= 0) { return nsAttrInfo(mAttrsAndChildren.AttrNameAt(index), mAttrsAndChildren.AttrAt(index)); } return nsAttrInfo(nsnull, nsnull); } PRBool nsGenericElement::GetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, nsAString& aResult) const { NS_ASSERTION(nsnull != aName, "must have attribute name"); NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "must have a real namespace ID!"); const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID); if (!val) { // Since we are returning a success code we'd better do // something about the out parameters (someone may have // given us a non-empty string). aResult.Truncate(); return PR_FALSE; } val->ToString(aResult); return PR_TRUE; } PRBool nsGenericElement::HasAttr(PRInt32 aNameSpaceID, nsIAtom* aName) const { NS_ASSERTION(nsnull != aName, "must have attribute name"); NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "must have a real namespace ID!"); return mAttrsAndChildren.IndexOfAttr(aName, aNameSpaceID) >= 0; } PRBool nsGenericElement::AttrValueIs(PRInt32 aNameSpaceID, nsIAtom* aName, const nsAString& aValue, nsCaseTreatment aCaseSensitive) const { NS_ASSERTION(aName, "Must have attr name"); NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "Must have namespace"); const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID); return val && val->Equals(aValue, aCaseSensitive); } PRBool nsGenericElement::AttrValueIs(PRInt32 aNameSpaceID, nsIAtom* aName, nsIAtom* aValue, nsCaseTreatment aCaseSensitive) const { NS_ASSERTION(aName, "Must have attr name"); NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "Must have namespace"); NS_ASSERTION(aValue, "Null value atom"); const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID); return val && val->Equals(aValue, aCaseSensitive); } PRInt32 nsGenericElement::FindAttrValueIn(PRInt32 aNameSpaceID, nsIAtom* aName, AttrValuesArray* aValues, nsCaseTreatment aCaseSensitive) const { NS_ASSERTION(aName, "Must have attr name"); NS_ASSERTION(aNameSpaceID != kNameSpaceID_Unknown, "Must have namespace"); NS_ASSERTION(aValues, "Null value array"); const nsAttrValue* val = mAttrsAndChildren.GetAttr(aName, aNameSpaceID); if (val) { for (PRInt32 i = 0; aValues[i]; ++i) { if (val->Equals(*aValues[i], aCaseSensitive)) { return i; } } return ATTR_VALUE_NO_MATCH; } return ATTR_MISSING; } nsresult nsGenericElement::UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, PRBool aNotify) { NS_ASSERTION(nsnull != aName, "must have attribute name"); PRInt32 index = mAttrsAndChildren.IndexOfAttr(aName, aNameSpaceID); if (index < 0) { return NS_OK; } nsresult rv = BeforeSetAttr(aNameSpaceID, aName, nsnull, aNotify); NS_ENSURE_SUCCESS(rv, rv); nsIDocument *document = GetCurrentDoc(); mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, aNotify); if (document) { if (kNameSpaceID_XLink == aNameSpaceID && nsGkAtoms::href == aName) { // XLink URI might be changing. document->ForgetLink(this); } if (aNotify) { document->AttributeWillChange(this, aNameSpaceID, aName); } } // When notifying, make sure to keep track of states whose value // depends solely on the value of an attribute. PRUint32 stateMask; if (aNotify) { stateMask = PRUint32(IntrinsicState()); } PRBool hasMutationListeners = aNotify && nsContentUtils::HasMutationListeners(this, NS_EVENT_BITS_MUTATION_ATTRMODIFIED, this); // Grab the attr node if needed before we remove it from the attr map nsCOMPtr<nsIDOMAttr> attrNode; if (hasMutationListeners) { nsAutoString attrName; aName->ToString(attrName); nsAutoString ns; nsContentUtils::NameSpaceManager()->GetNameSpaceURI(aNameSpaceID, ns); GetAttributeNodeNS(ns, attrName, getter_AddRefs(attrNode)); } // Clear binding to nsIDOMNamedNodeMap nsDOMSlots *slots = GetExistingDOMSlots(); if (slots && slots->mAttributeMap) { slots->mAttributeMap->DropAttribute(aNameSpaceID, aName); } nsAttrValue oldValue; rv = mAttrsAndChildren.RemoveAttrAt(index, oldValue); NS_ENSURE_SUCCESS(rv, rv); if (document || HasFlag(NODE_FORCE_XBL_BINDINGS)) { nsIDocument* ownerDoc = GetOwnerDoc(); if (ownerDoc) { nsRefPtr<nsXBLBinding> binding = ownerDoc->BindingManager()->GetBinding(this); if (binding) { binding->AttributeChanged(aName, aNameSpaceID, PR_TRUE, aNotify); } } } if (aNotify) { stateMask = stateMask ^ PRUint32(IntrinsicState()); if (stateMask && document) { MOZ_AUTO_DOC_UPDATE(document, UPDATE_CONTENT_STATE, aNotify); document->ContentStatesChanged(this, nsnull, stateMask); } nsNodeUtils::AttributeChanged(this, aNameSpaceID, aName, nsIDOMMutationEvent::REMOVAL, stateMask); } rv = AfterSetAttr(aNameSpaceID, aName, nsnull, aNotify); NS_ENSURE_SUCCESS(rv, rv); if (hasMutationListeners) { mozAutoRemovableBlockerRemover blockerRemover(GetOwnerDoc()); nsCOMPtr<nsIDOMEventTarget> node = do_QueryInterface(static_cast<nsIContent *>(this)); nsMutationEvent mutation(PR_TRUE, NS_MUTATION_ATTRMODIFIED); mutation.mRelatedNode = attrNode; mutation.mAttrName = aName; nsAutoString value; oldValue.ToString(value); if (!value.IsEmpty()) mutation.mPrevAttrValue = do_GetAtom(value); mutation.mAttrChange = nsIDOMMutationEvent::REMOVAL; mozAutoSubtreeModified subtree(GetOwnerDoc(), this); nsEventDispatcher::Dispatch(this, nsnull, &mutation); } return NS_OK; } const nsAttrName* nsGenericElement::GetAttrNameAt(PRUint32 aIndex) const { return mAttrsAndChildren.GetSafeAttrNameAt(aIndex); } PRUint32 nsGenericElement::GetAttrCount() const { return mAttrsAndChildren.AttrCount(); } const nsTextFragment* nsGenericElement::GetText() { return nsnull; } PRUint32 nsGenericElement::TextLength() { // We can remove this assertion if it turns out to be useful to be able // to depend on this returning 0 NS_NOTREACHED("called nsGenericElement::TextLength"); return 0; } nsresult nsGenericElement::SetText(const PRUnichar* aBuffer, PRUint32 aLength, PRBool aNotify) { NS_ERROR("called nsGenericElement::SetText"); return NS_ERROR_FAILURE; } nsresult nsGenericElement::AppendText(const PRUnichar* aBuffer, PRUint32 aLength, PRBool aNotify) { NS_ERROR("called nsGenericElement::AppendText"); return NS_ERROR_FAILURE; } PRBool nsGenericElement::TextIsOnlyWhitespace() { return PR_FALSE; } void nsGenericElement::AppendTextTo(nsAString& aResult) { // We can remove this assertion if it turns out to be useful to be able // to depend on this appending nothing. NS_NOTREACHED("called nsGenericElement::TextLength"); } #ifdef DEBUG void nsGenericElement::ListAttributes(FILE* out) const { PRUint32 index, count = mAttrsAndChildren.AttrCount(); for (index = 0; index < count; index++) { nsAutoString buffer; // name mAttrsAndChildren.AttrNameAt(index)->GetQualifiedName(buffer); // value buffer.AppendLiteral("=\""); nsAutoString value; mAttrsAndChildren.AttrAt(index)->ToString(value); for (int i = value.Length(); i >= 0; --i) { if (value[i] == PRUnichar('"')) value.Insert(PRUnichar('\\'), PRUint32(i)); } buffer.Append(value); buffer.AppendLiteral("\""); fputs(" ", out); fputs(NS_LossyConvertUTF16toASCII(buffer).get(), out); } } void nsGenericElement::List(FILE* out, PRInt32 aIndent, const nsCString& aPrefix) const { PRInt32 indent; for (indent = aIndent; --indent >= 0; ) fputs(" ", out); fputs(aPrefix.get(), out); nsAutoString buf; mNodeInfo->GetQualifiedName(buf); fputs(NS_LossyConvertUTF16toASCII(buf).get(), out); fprintf(out, "@%p", (void *)this); ListAttributes(out); fprintf(out, " intrinsicstate=[%08x]", IntrinsicState()); fprintf(out, " refcount=%d<", mRefCnt.get()); PRUint32 i, length = GetChildCount(); if (length > 0) { fputs("\n", out); for (i = 0; i < length; ++i) { nsIContent *kid = GetChildAt(i); kid->List(out, aIndent + 1); } for (indent = aIndent; --indent >= 0; ) fputs(" ", out); } fputs(">\n", out); nsGenericElement* nonConstThis = const_cast<nsGenericElement*>(this); // XXX sXBL/XBL2 issue! Owner or current document? nsIDocument *document = GetOwnerDoc(); if (document) { // Note: not listing nsIAnonymousContentCreator-created content... nsBindingManager* bindingManager = document->BindingManager(); nsCOMPtr<nsIDOMNodeList> anonymousChildren; bindingManager->GetAnonymousNodesFor(nonConstThis, getter_AddRefs(anonymousChildren)); if (anonymousChildren) { anonymousChildren->GetLength(&length); if (length > 0) { for (indent = aIndent; --indent >= 0; ) fputs(" ", out); fputs("anonymous-children<\n", out); for (i = 0; i < length; ++i) { nsCOMPtr<nsIDOMNode> node; anonymousChildren->Item(i, getter_AddRefs(node)); nsCOMPtr<nsIContent> child = do_QueryInterface(node); child->List(out, aIndent + 1); } for (indent = aIndent; --indent >= 0; ) fputs(" ", out); fputs(">\n", out); } } if (bindingManager->HasContentListFor(nonConstThis)) { nsCOMPtr<nsIDOMNodeList> contentList; bindingManager->GetContentListFor(nonConstThis, getter_AddRefs(contentList)); NS_ASSERTION(contentList != nsnull, "oops, binding manager lied"); contentList->GetLength(&length); if (length > 0) { for (indent = aIndent; --indent >= 0; ) fputs(" ", out); fputs("content-list<\n", out); for (i = 0; i < length; ++i) { nsCOMPtr<nsIDOMNode> node; contentList->Item(i, getter_AddRefs(node)); nsCOMPtr<nsIContent> child = do_QueryInterface(node); child->List(out, aIndent + 1); } for (indent = aIndent; --indent >= 0; ) fputs(" ", out); fputs(">\n", out); } } } } void nsGenericElement::DumpContent(FILE* out, PRInt32 aIndent, PRBool aDumpAll) const { PRInt32 indent; for (indent = aIndent; --indent >= 0; ) fputs(" ", out); nsAutoString buf; mNodeInfo->GetQualifiedName(buf); fputs("<", out); fputs(NS_LossyConvertUTF16toASCII(buf).get(), out); if(aDumpAll) ListAttributes(out); fputs(">", out); if(aIndent) fputs("\n", out); PRInt32 index, kids = GetChildCount(); for (index = 0; index < kids; index++) { nsIContent *kid = GetChildAt(index); PRInt32 indent = aIndent ? aIndent + 1 : 0; kid->DumpContent(out, indent, aDumpAll); } for (indent = aIndent; --indent >= 0; ) fputs(" ", out); fputs("</", out); fputs(NS_LossyConvertUTF16toASCII(buf).get(), out); fputs(">", out); if(aIndent) fputs("\n", out); } #endif PRUint32 nsGenericElement::GetChildCount() const { return mAttrsAndChildren.ChildCount(); } nsIContent * nsGenericElement::GetChildAt(PRUint32 aIndex) const { return mAttrsAndChildren.GetSafeChildAt(aIndex); } nsIContent * const * nsGenericElement::GetChildArray() const { return mAttrsAndChildren.GetChildArray(); } PRInt32 nsGenericElement::IndexOf(nsINode* aPossibleChild) const { return mAttrsAndChildren.IndexOfChild(aPossibleChild); } nsINode::nsSlots* nsGenericElement::CreateSlots() { return new nsDOMSlots(mFlagsOrSlots); } PRBool nsGenericElement::CheckHandleEventForLinksPrecondition(nsEventChainVisitor& aVisitor, nsIURI** aURI) const { if (aVisitor.mEventStatus == nsEventStatus_eConsumeNoDefault || !NS_IS_TRUSTED_EVENT(aVisitor.mEvent) || !aVisitor.mPresContext) { return PR_FALSE; } // Make sure we actually are a link return IsLink(aURI); } nsresult nsGenericElement::PreHandleEventForLinks(nsEventChainPreVisitor& aVisitor) { // Optimisation: return early if this event doesn't interest us. // IMPORTANT: this switch and the switch below it must be kept in sync! switch (aVisitor.mEvent->message) { case NS_MOUSE_ENTER_SYNTH: case NS_FOCUS_CONTENT: case NS_MOUSE_EXIT_SYNTH: case NS_BLUR_CONTENT: break; default: return NS_OK; } // Make sure we meet the preconditions before continuing nsCOMPtr<nsIURI> absURI; if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) { return NS_OK; } nsresult rv = NS_OK; // We do the status bar updates in PreHandleEvent so that the status bar gets // updated even if the event is consumed before we have a chance to set it. switch (aVisitor.mEvent->message) { // Set the status bar the same for focus and mouseover case NS_MOUSE_ENTER_SYNTH: aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; // FALL THROUGH case NS_FOCUS_CONTENT: { nsAutoString target; GetLinkTarget(target); nsContentUtils::TriggerLink(this, aVisitor.mPresContext, absURI, target, PR_FALSE, PR_TRUE); } break; case NS_MOUSE_EXIT_SYNTH: aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; // FALL THROUGH case NS_BLUR_CONTENT: rv = LeaveLink(aVisitor.mPresContext); break; default: // switch not in sync with the optimization switch earlier in this function NS_NOTREACHED("switch statements not in sync"); return NS_ERROR_UNEXPECTED; } return rv; } nsresult nsGenericElement::PostHandleEventForLinks(nsEventChainPostVisitor& aVisitor) { // Optimisation: return early if this event doesn't interest us. // IMPORTANT: this switch and the switch below it must be kept in sync! switch (aVisitor.mEvent->message) { case NS_MOUSE_BUTTON_DOWN: case NS_MOUSE_CLICK: case NS_UI_ACTIVATE: case NS_KEY_PRESS: break; default: return NS_OK; } // Make sure we meet the preconditions before continuing nsCOMPtr<nsIURI> absURI; if (!CheckHandleEventForLinksPrecondition(aVisitor, getter_AddRefs(absURI))) { return NS_OK; } nsresult rv = NS_OK; switch (aVisitor.mEvent->message) { case NS_MOUSE_BUTTON_DOWN: { if (aVisitor.mEvent->eventStructType == NS_MOUSE_EVENT && static_cast<nsMouseEvent*>(aVisitor.mEvent)->button == nsMouseEvent::eLeftButton) { // don't make the link grab the focus if there is no link handler nsILinkHandler *handler = aVisitor.mPresContext->GetLinkHandler(); nsIDocument *document = GetCurrentDoc(); if (handler && document && ShouldFocus(this)) { // If the window is not active, do not allow the focus to bring the // window to the front. We update the focus controller, but do nothing // else. nsPIDOMWindow *win = document->GetWindow(); if (win) { nsIFocusController *focusController = win->GetRootFocusController(); if (focusController) { PRBool isActive = PR_FALSE; focusController->GetActive(&isActive); if (!isActive) { nsCOMPtr<nsIDOMElement> domElement = do_QueryInterface(this); if(domElement) focusController->SetFocusedElement(domElement); break; } } } aVisitor.mPresContext->EventStateManager()-> SetContentState(this, NS_EVENT_STATE_ACTIVE | NS_EVENT_STATE_FOCUS); } } } break; case NS_MOUSE_CLICK: if (NS_IS_MOUSE_LEFT_CLICK(aVisitor.mEvent)) { nsInputEvent* inputEvent = static_cast<nsInputEvent*>(aVisitor.mEvent); if (inputEvent->isControl || inputEvent->isMeta || inputEvent->isAlt ||inputEvent->isShift) { break; } // The default action is simply to dispatch DOMActivate nsCOMPtr<nsIPresShell> shell = aVisitor.mPresContext->GetPresShell(); if (shell) { // single-click nsEventStatus status = nsEventStatus_eIgnore; nsUIEvent actEvent(NS_IS_TRUSTED_EVENT(aVisitor.mEvent), NS_UI_ACTIVATE, 1); rv = shell->HandleDOMEventWithTarget(this, &actEvent, &status); } } break; case NS_UI_ACTIVATE: { nsAutoString target; GetLinkTarget(target); nsContentUtils::TriggerLink(this, aVisitor.mPresContext, absURI, target, PR_TRUE, PR_TRUE); } break; case NS_KEY_PRESS: { if (aVisitor.mEvent->eventStructType == NS_KEY_EVENT) { nsKeyEvent* keyEvent = static_cast<nsKeyEvent*>(aVisitor.mEvent); if (keyEvent->keyCode == NS_VK_RETURN) { nsEventStatus status = nsEventStatus_eIgnore; rv = DispatchClickEvent(aVisitor.mPresContext, keyEvent, this, PR_FALSE, &status); if (NS_SUCCEEDED(rv)) { aVisitor.mEventStatus = nsEventStatus_eConsumeNoDefault; } } } } break; default: // switch not in sync with the optimization switch earlier in this function NS_NOTREACHED("switch statements not in sync"); return NS_ERROR_UNEXPECTED; } return rv; } void nsGenericElement::GetLinkTarget(nsAString& aTarget) { aTarget.Truncate(); } // NOTE: The aPresContext pointer is NOT addrefed. static nsresult ParseSelectorList(nsINode* aNode, const nsAString& aSelectorString, nsCSSSelectorList** aSelectorList, nsPresContext** aPresContext) { NS_ENSURE_ARG(aNode); nsIDocument* doc = aNode->GetOwnerDoc(); NS_ENSURE_STATE(doc); nsCOMPtr<nsICSSParser> parser; nsresult rv = doc->CSSLoader()->GetParserFor(nsnull, getter_AddRefs(parser)); NS_ENSURE_SUCCESS(rv, rv); rv = parser->ParseSelectorString(aSelectorString, doc->GetDocumentURI(), 0, // XXXbz get the right line number! aSelectorList); doc->CSSLoader()->RecycleParser(parser); NS_ENSURE_SUCCESS(rv, rv); // It's not strictly necessary to have a prescontext here, but it's // a bit of an optimization for various stuff. *aPresContext = nsnull; nsIPresShell* shell = doc->GetPrimaryShell(); if (shell) { *aPresContext = shell->GetPresContext(); } return NS_OK; } /* * Callback to be called as we iterate over the tree and match elements. If * the callbacks returns false, the iteration should be stopped. */ typedef PRBool (* ElementMatchedCallback)(nsIContent* aMatchingElement, void* aClosure); // returning false means stop iteration static PRBool TryMatchingElementsInSubtree(nsINode* aRoot, RuleProcessorData* aParentData, nsPresContext* aPresContext, nsCSSSelectorList* aSelectorList, ElementMatchedCallback aCallback, void* aClosure) { PRUint32 count = aRoot->GetChildCount(); /* To improve the performance of '+' and '~' combinators and the :nth-* * selectors, we keep track of the immediately previous sibling data. That's * cheaper than heap-allocating all the datas and keeping track of them all, * and helps a good bit in the common cases. We also keep track of the whole * parent data chain, since we have those Around anyway */ char databuf[2 * sizeof(RuleProcessorData)]; RuleProcessorData* prevSibling = nsnull; RuleProcessorData* data = reinterpret_cast<RuleProcessorData*>(databuf); nsIContent * const * kidSlot = aRoot->GetChildArray(); nsIContent * const * end = kidSlot + count; #ifdef DEBUG nsMutationGuard debugMutationGuard; #endif PRBool continueIteration = PR_TRUE; for (; kidSlot != end; ++kidSlot) { nsIContent* kid = *kidSlot; if (!kid->IsNodeOfType(nsINode::eELEMENT)) { continue; } /* See whether we match */ new (data) RuleProcessorData(aPresContext, kid, nsnull); NS_ASSERTION(!data->mParentData, "Shouldn't happen"); NS_ASSERTION(!data->mPreviousSiblingData, "Shouldn't happen"); data->mParentData = aParentData; data->mPreviousSiblingData = prevSibling; if (nsCSSRuleProcessor::SelectorListMatches(*data, aSelectorList)) { continueIteration = (*aCallback)(kid, aClosure); } if (continueIteration) { continueIteration = TryMatchingElementsInSubtree(kid, data, aPresContext, aSelectorList, aCallback, aClosure); } /* Clear out the parent and previous sibling data if we set them, so that * ~RuleProcessorData won't try to delete a placement-new'd object. Make * sure this happens before our possible early break. Note that we can * have null aParentData but non-null data->mParentData if we're scoped to * an element. However, prevSibling and data->mPreviousSiblingData must * always match. */ NS_ASSERTION(!aParentData || data->mParentData == aParentData, "Unexpected parent"); NS_ASSERTION(data->mPreviousSiblingData == prevSibling, "Unexpected prev sibling"); data->mPreviousSiblingData = nsnull; if (prevSibling) { if (aParentData) { prevSibling->mParentData = nsnull; } prevSibling->~RuleProcessorData(); } else { /* This is the first time through, so point |prevSibling| to the location we want to have |data| end up pointing to. */ prevSibling = data + 1; } /* Now swap |prevSibling| and |data|. Again, before the early break */ RuleProcessorData* temp = prevSibling; prevSibling = data; data = temp; if (!continueIteration) { break; } } if (prevSibling) { if (aParentData) { prevSibling->mParentData = nsnull; } /* Make sure to clean this up */ prevSibling->~RuleProcessorData(); } #ifdef DEBUG NS_ASSERTION(!debugMutationGuard.Mutated(0), "Unexpected mutations happened"); #endif return continueIteration; } static PRBool FindFirstMatchingElement(nsIContent* aMatchingElement, void* aClosure) { NS_PRECONDITION(aMatchingElement && aClosure, "How did that happen?"); nsIContent** slot = static_cast<nsIContent**>(aClosure); *slot = aMatchingElement; return PR_FALSE; } /* static */ nsresult nsGenericElement::doQuerySelector(nsINode* aRoot, const nsAString& aSelector, nsIDOMElement **aReturn) { NS_PRECONDITION(aReturn, "Null out param?"); nsAutoPtr<nsCSSSelectorList> selectorList; nsPresContext* presContext; nsresult rv = ParseSelectorList(aRoot, aSelector, getter_Transfers(selectorList), &presContext); NS_ENSURE_SUCCESS(rv, rv); nsIContent* foundElement = nsnull; TryMatchingElementsInSubtree(aRoot, nsnull, presContext, selectorList, FindFirstMatchingElement, &foundElement); if (foundElement) { return CallQueryInterface(foundElement, aReturn); } *aReturn = nsnull; return NS_OK; } static PRBool AppendAllMatchingElements(nsIContent* aMatchingElement, void* aClosure) { NS_PRECONDITION(aMatchingElement && aClosure, "How did that happen?"); static_cast<nsBaseContentList*>(aClosure)->AppendElement(aMatchingElement); return PR_TRUE; } /* static */ nsresult nsGenericElement::doQuerySelectorAll(nsINode* aRoot, const nsAString& aSelector, nsIDOMNodeList **aReturn) { NS_PRECONDITION(aReturn, "Null out param?"); nsBaseContentList* contentList = new nsBaseContentList(); NS_ENSURE_TRUE(contentList, NS_ERROR_OUT_OF_MEMORY); NS_ADDREF(*aReturn = contentList); nsAutoPtr<nsCSSSelectorList> selectorList; nsPresContext* presContext; nsresult rv = ParseSelectorList(aRoot, aSelector, getter_Transfers(selectorList), &presContext); NS_ENSURE_SUCCESS(rv, rv); TryMatchingElementsInSubtree(aRoot, nsnull, presContext, selectorList, AppendAllMatchingElements, contentList); return NS_OK; }
29.746393
96
0.662121
[ "object" ]
80e333ff33618f291731c13743e1eceacc24a63c
3,242
cpp
C++
C++/nuts-bolts-problem.cpp
xenron/sandbox-dev-lintcode
114145723af43eafc84ff602ad3ac7b353a9fc38
[ "MIT" ]
695
2015-04-18T16:11:56.000Z
2022-03-11T13:28:44.000Z
C++/nuts-bolts-problem.cpp
Abd-Elrazek/LintCode
8f6ee0ff38cb7cf8bf9fca800243823931604155
[ "MIT" ]
4
2015-07-04T13:07:35.000Z
2020-08-11T11:32:29.000Z
C++/nuts-bolts-problem.cpp
Abd-Elrazek/LintCode
8f6ee0ff38cb7cf8bf9fca800243823931604155
[ "MIT" ]
338
2015-04-28T04:39:03.000Z
2022-03-16T03:00:15.000Z
// Time: O(nlogn) on average // Space: O(logn) on average /** * class Comparator { * public: * int cmp(string a, string b); * }; * You can use compare.cmp(a, b) to compare nuts "a" and bolts "b", * if "a" is bigger than "b", it will return 1, else if they are equal, * it will return 0, else if "a" is smaller than "b", it will return -1. * When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid. */ class Solution { public: using CompareResult = enum { SMALLER = -1, EQUAL = 0, BIGGER = 1, REVERSE = 2 }; /** * @param nuts: a vector of integers * @param bolts: a vector of integers * @param compare: a instance of Comparator * @return: nothing */ void sortNutsAndBolts(vector<string> &nuts, vector<string> &bolts, Comparator compare) { quickSort(nuts, bolts, 0, nuts.size() - 1, compare); } // Method which works just like quick sort void quickSort(vector<string>& nuts, vector<string>& bolts, int left, int right, Comparator& compare) { if (left < right) { // Randomly choose a bolt as a pivot for nuts partition. default_random_engine gen((random_device())()); uniform_int_distribution<int> dis(left, right); int pivot = dis(gen); // Use the pivot bolt to make a partition of nuts. // The we could know the index where the pivot (bolt, nut) // pair should be in sorted order. pivot = partition(nuts, left, right, bolts[pivot], compare); // Using the nut in the pivot bolt to make a partition of bolts. partition(bolts, left, right, nuts[pivot], compare); // Now, both nuts and bolts are partitioned by the pivot nut-bolt pair. // The pivot nut-bolt pair is also in the correct index of the sorted order. // Recursively do the same thing in the left and right side of the pivot. quickSort(nuts, bolts, left, pivot - 1, compare); quickSort(nuts, bolts, pivot + 1, right, compare); } } // All the smaller elements should be in the left side of the pivot, // and all the bigger elements should in the right side of the pivot. int partition(vector<string>& arr, int left, int right, const string& pivot, Comparator& compare) { for (int i = left; i < right; ) { if (compare.cmp(arr[i], pivot) == SMALLER || // Smaller. (compare.cmp(arr[i], pivot) == REVERSE && compare.cmp(pivot, arr[i]) == BIGGER)) { swap(arr[left++], arr[i++]); } else if (compare.cmp(arr[i], pivot) == BIGGER || // Bigger. (compare.cmp(arr[i], pivot) == REVERSE && compare.cmp(pivot, arr[i]) == SMALLER)) { ++i; } else { // Equal. swap(arr[i], arr[right]); } } // Put the pivot to the partition index. swap(arr[left], arr[right]); // Return the partition index of an array. return left; } };
40.024691
88
0.548735
[ "vector" ]
80e5b61cbd5f3c10be303fa887ed3e979e535091
3,677
hpp
C++
packages/monte_carlo/core/src/MonteCarlo_SimulationProperties.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/core/src/MonteCarlo_SimulationProperties.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/core/src/MonteCarlo_SimulationProperties.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_SimulationProperties.hpp //! \author Alex Robinson //! \brief Simulation properties class declaration //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_SIMULATION_PROPERTIES_HPP #define MONTE_CARLO_SIMULATION_PROPERTIES_HPP // Boost Includes #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/split_member.hpp> #include <boost/serialization/version.hpp> #include <boost/serialization/export.hpp> // FRENSIE Includes #include "MonteCarlo_SimulationGeneralProperties.hpp" #include "MonteCarlo_SimulationNeutronProperties.hpp" #include "MonteCarlo_SimulationPhotonProperties.hpp" #include "MonteCarlo_SimulationAdjointPhotonProperties.hpp" #include "MonteCarlo_SimulationElectronProperties.hpp" #include "MonteCarlo_SimulationAdjointElectronProperties.hpp" #include "MonteCarlo_ParticleType.hpp" namespace MonteCarlo{ /*! The simulation properties class * * This class has been designed as a mix-in class. It can be used as the * control point for all runtime configuration options used in a Monte Carlo * simulation. */ class SimulationProperties : public SimulationGeneralProperties, public SimulationNeutronProperties, public SimulationPhotonProperties, public SimulationAdjointPhotonProperties, public SimulationElectronProperties, public SimulationAdjointElectronProperties { public: //! Constructor SimulationProperties() { /* ... */ } //! Destructor ~SimulationProperties() { /* ... */ } //! Return the min particle energy template<typename ParticleType> double getMinParticleEnergy() const; //! Return the max particle energy template<typename ParticleType> double getMaxParticleEnergy() const; //! Set atomic relaxation mode to off void setAtomicRelaxationModeOff( const ParticleType particle ); //! Set atomic relaxation mode to on void setAtomicRelaxationModeOn( const ParticleType particle ); //! Return if atomic relaxation mode is on bool isAtomicRelaxationModeOn( const ParticleType particle ) const; //! Return the cutoff roulette threshold weight template<typename ParticleType> double getRouletteThresholdWeight() const; //! Return the cutoff roulette survival weight template<typename ParticleType> double getRouletteSurvivalWeight() const; private: // Save/load the state to an archive template<typename Archive> void serialize( Archive& ar, const unsigned version ); // Declare the boost serialization access object as a friend friend class boost::serialization::access; }; } // end MonteCarlo namespace #if !defined SWIG BOOST_CLASS_VERSION( MonteCarlo::SimulationProperties, 0 ); BOOST_CLASS_EXPORT_KEY2( MonteCarlo::SimulationProperties, "SimulationProperties" ); EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, SimulationProperties ); #endif // end !defined SWIG //---------------------------------------------------------------------------// // Template Includes. //---------------------------------------------------------------------------// #include "MonteCarlo_SimulationProperties_def.hpp" //---------------------------------------------------------------------------// #endif // end MONTE_CARLO_SIMULATION_PROPERTIES_HPP //---------------------------------------------------------------------------// // end MonteCarlo_SimulationProperties.hpp //---------------------------------------------------------------------------//
33.126126
84
0.643459
[ "object" ]
80e9a9118b034d8f778cbceaa4ea8e00cf4ac859
10,002
cpp
C++
project/HeightmapTerrain.cpp
Linzee/opengl-forest
9e8f49568449247cc627c4481785c4431a1e37a3
[ "MIT" ]
null
null
null
project/HeightmapTerrain.cpp
Linzee/opengl-forest
9e8f49568449247cc627c4481785c4431a1e37a3
[ "MIT" ]
1
2018-09-05T13:41:47.000Z
2018-09-08T13:50:26.000Z
project/HeightmapTerrain.cpp
Linzee/opengl-forest
9e8f49568449247cc627c4481785c4431a1e37a3
[ "MIT" ]
null
null
null
#include "HeightmapTerrain.h" //----------------------------------------- //---- TERRAIN ---- //----------------------------------------- Terrain LoadHeightmapTerrain(const maybewchar* filename, GLint position_location, GLint normal_location, GLint tex_coord_location) { /* Load texture data */ Terrain terrain; // Create IL image ILuint IL_tex; ilGenImages(1, &IL_tex); ilBindImage(IL_tex); // Solve upside down textures ilEnable(IL_ORIGIN_SET); ilOriginFunc(IL_ORIGIN_LOWER_LEFT); // Load IL image ILboolean success = ilLoadImage(filename); if (!success) { ilBindImage(0); ilDeleteImages(1, &IL_tex); throw std::invalid_argument("Cannot load heightmap!"); } // Get IL image parameters int img_width = ilGetInteger(IL_IMAGE_WIDTH); int img_height = ilGetInteger(IL_IMAGE_HEIGHT); int img_format = ilGetInteger(IL_IMAGE_FORMAT); int img_type = ilGetInteger(IL_IMAGE_TYPE); /* Load vectors */ std::vector< std::vector< glm::vec3> > vertexes(img_width, std::vector<glm::vec3>(img_height)); std::vector< std::vector< glm::vec2> > coords(img_width, std::vector<glm::vec2>(img_height)); terrain.height = std::vector< std::vector<float> >(img_width, std::vector<float>(img_height)); ILubyte * imageData = ilGetData(); for (int x = 0; x < img_width; x++) { for (int y = 0; y < img_height; y++) { float s = float(x) / float(img_width); float t = float(y) / float(img_height); int bl; switch (img_format) { case IL_RGB: bl = 3; break; case IL_RGBA: bl = 4; break; default: // Unsupported format ilBindImage(0); ilDeleteImages(1, &IL_tex); throw std::invalid_argument("Cannot load heightmap, invalid format!"); } float height = float(imageData[(x*img_width + y) * bl]) / 255.0f; vertexes[x][y] = glm::vec3(-0.5f + s, height, -0.5f + t); coords[x][y] = glm::vec2(s, t); terrain.height[x][y] = height; } } ilBindImage(0); ilDeleteImages(1, &IL_tex); /* Calculate normals */ std::vector< std::vector<glm::vec3> > normals[2]; for (int i = 0; i < 2; i++) { normals[i] = std::vector< std::vector<glm::vec3> >(img_width - 1, std::vector<glm::vec3>(img_height - 1)); } for (int x = 0; x < img_width - 1; x++) { for (int y = 0; y < img_height - 1; y++) { glm::vec3 triangle0[] = { vertexes[x + 1][y + 1], vertexes[x + 1][y], vertexes[x][y] }; glm::vec3 triangle1[] = { vertexes[x][y], vertexes[x][y + 1], vertexes[x + 1][y + 1], }; glm::vec3 triangleNorm0 = glm::cross(triangle0[0] - triangle0[1], triangle0[1] - triangle0[2]); glm::vec3 triangleNorm1 = glm::cross(triangle1[0] - triangle1[1], triangle1[1] - triangle1[2]); normals[0][x][y] = glm::normalize(triangleNorm0); normals[1][x][y] = glm::normalize(triangleNorm1); } } std::vector< std::vector<glm::vec3> > finalNormals(img_width, std::vector<glm::vec3>(img_height)); for (int x = 0; x < img_width; x++) { for (int y = 0; y < img_height; y++) { glm::vec3 finalNormal = glm::vec3(0.0f, 0.0f, 0.0f); // Look for bottom-right triangles if (x < img_width - 1 && y < img_height - 1) { finalNormal += normals[0][x][y]; finalNormal += normals[1][x][y]; } // Look for upper-left triangles if (x - 1 >= 0 && y - 1 >= 0) { finalNormal += normals[0][x - 1][y - 1]; finalNormal += normals[1][x - 1][y - 1]; } // Look for upper-right triangles if (x < img_width - 1 && y - 1 >= 0) { finalNormal += normals[0][x][y - 1]; } // Look for bottom-left triangles if (x - 1 >= 0 && y < img_height - 1) { finalNormal += normals[1][x - 1][y]; } finalNormals[x][y] = glm::normalize(finalNormal); } } /* Indices */ std::vector<unsigned int> indices; for (int y = 0; y < img_height - 1; y++) { for (int x = 0; x < img_width - 1; x++) { for (int r = 0; r < 2; r++) { int row = y + (1 - r); int index = row * img_width + x; indices.push_back(index); } } // Restart triangle strips indices.push_back(4294967295U); } /* Normalize data */ std::vector<float> vertexData(img_width * img_height * 8); for (int x = 0; x < img_width; x++) { for (int y = 0; y < img_height; y++) { vertexData[(x + y * img_width) * 8 + 0] = vertexes[x][y].x; vertexData[(x + y * img_width) * 8 + 1] = vertexes[x][y].y; vertexData[(x + y * img_width) * 8 + 2] = vertexes[x][y].z; vertexData[(x + y * img_width) * 8 + 3] = finalNormals[x][y].x; vertexData[(x + y * img_width) * 8 + 4] = finalNormals[x][y].y; vertexData[(x + y * img_width) * 8 + 5] = finalNormals[x][y].z; vertexData[(x + y * img_width) * 8 + 6] = coords[x][y].x; vertexData[(x + y * img_width) * 8 + 7] = coords[x][y].y; } } /* Load to opengl */ // Create a single buffer for vertex data glGenBuffers(1, &terrain.VertexBuffers[0]); glBindBuffer(GL_ARRAY_BUFFER, terrain.VertexBuffers[0]); glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), &vertexData[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // Create a buffer for indices glGenBuffers(1, &terrain.IndexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, terrain.IndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Create a vertex array object for the geometry glGenVertexArrays(1, &terrain.VAO); // Set the parameters of the geometry glBindVertexArray(terrain.VAO); glBindBuffer(GL_ARRAY_BUFFER, terrain.VertexBuffers[0]); if (position_location >= 0) { glEnableVertexAttribArray(position_location); glVertexAttribPointer(position_location, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, 0); } if (normal_location >= 0) { glEnableVertexAttribArray(normal_location); glVertexAttribPointer(normal_location, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *)(sizeof(float) * 3)); } if (tex_coord_location >= 0) { glEnableVertexAttribArray(tex_coord_location); glVertexAttribPointer(tex_coord_location, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *)(sizeof(float) * 6)); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, terrain.IndexBuffer); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); terrain.Mode = GL_TRIANGLE_STRIP; terrain.DrawArraysCount = 0; terrain.DrawElementsCount = indices.size(); return terrain; } //----------------------------------------- //---- Random trees planting ---- //----------------------------------------- void RandomTrees(const Terrain& terrain_geometry, glm::mat4* tree_model_matrixes, int tree_count, std::function<float(float, float, float)> callable) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> disArea(-50.0f, 50.0f - 1.0f); std::uniform_real_distribution<> disAngle(0.0f, 6.28f); std::uniform_real_distribution<> disGeneral(0.0f, 1.0f); for (size_t i = 0; i < tree_count; i++) { float x = disArea(gen); int xdata = static_cast<int>((x + 50) * 256 / 100); float z = disArea(gen); int zdata = static_cast<int>((z + 50) * 256 / 100); float y1 = terrain_geometry.height[xdata][zdata]; float y2 = terrain_geometry.height[xdata + 1][zdata + 1]; float dx = x - static_cast<int>(x); float dz = z - static_cast<int>(z); float t = sqrt(dx * dx + dz * dz) / sqrt(2.0f); float y = (1 - t) * y1 + t * y2; if (disGeneral(gen) > callable(x, y, z)) { i -= 1; continue; } glm::mat4 mat(1.0); mat = glm::translate(mat, glm::vec3(x, y * TERRAIN_HEIGHT, z)); mat = glm::rotate(mat, -tan(y1 - terrain_geometry.height[xdata + 1][zdata]), glm::vec3(0.0, 0.0, 1.0)); mat = glm::rotate(mat, -tan(y1 - terrain_geometry.height[xdata][zdata + 1]), glm::vec3(1.0, 0.0, 0.0)); mat = glm::rotate(mat, static_cast<float>(disAngle(gen)), glm::vec3(0.0, 1.0, 0.0)); tree_model_matrixes[i] = mat; } } //----------------------------------------- //---- BLINKING CAMERA CLASS ---- //----------------------------------------- const float BlinkCamera::min_elevation = -1.5f; const float BlinkCamera::max_elevation = 1.5f; const float BlinkCamera::angle_sensitivity = 0.008f; const float BlinkCamera::move_speed = 0.2f; BlinkCamera::BlinkCamera(Terrain* terrain, float x, float z) : terrain(terrain), angle_direction(0.0f), angle_elevation(0.0f) { eye_position.x = x; eye_position.z = z; eye_position.y = get_height(x, z); update_look_pos(); } void BlinkCamera::OnMouseButtonChanged(int button, int state, int x, int y) { } void BlinkCamera::update_look_pos() { look_position.x = eye_position.x + cosf(angle_elevation) * cosf(angle_direction); look_position.y = eye_position.y + -sinf(angle_elevation); look_position.z = eye_position.z + cosf(angle_elevation) * sinf(angle_direction); } float BlinkCamera::get_height(float x, float z) { int xi = static_cast<int>(round((eye_position.x / 50) * 128)) + 128; int zi = static_cast<int>(round((eye_position.z / 50) * 128)) + 128; xi = std::max(std::min(xi, 255), 0); zi = std::max(std::min(zi, 255), 0); return terrain->height[xi][zi] * TERRAIN_HEIGHT; } void BlinkCamera::OnMouseMoved(int dx, int dy) { angle_direction += dx * angle_sensitivity; angle_elevation += dy * angle_sensitivity; // Clamp the results if (angle_elevation > max_elevation) angle_elevation = max_elevation; if (angle_elevation < min_elevation) angle_elevation = min_elevation; update_look_pos(); } void BlinkCamera::Move() { float vv = vel_w ? 1.0 : 0.0 + vel_s ? -1.0 : 0.0; float vu = vel_d ? 1.0 : 0.0 + vel_a ? -1.0 : 0.0; if (vv + vu == 0) return; float inAngle = atan2(vu, vv); eye_position.x += move_speed * cosf(angle_direction + inAngle); eye_position.z += move_speed * sinf(angle_direction + inAngle); eye_position.y = get_height(eye_position.x, eye_position.z); update_look_pos(); } glm::vec3 BlinkCamera::GetEyePosition() const { return eye_position; } glm::vec3 BlinkCamera::GetLookPosition() const { return look_position; }
29.856716
151
0.635773
[ "geometry", "object", "vector" ]
80eb15f966d016c7b069beb32039f516eab15865
3,249
cpp
C++
String/385. Mini Parser/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
String/385. Mini Parser/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
String/385. Mini Parser/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 385. Mini Parser // // Created by 边俊林 on 2019/8/11. // Copyright © 2019 Minecode.Link. All rights reserved. // /* ------------------------------------------------------ *\ https://leetcode.com/problems/mini-parser/ \* ------------------------------------------------------ */ #include <map> #include <set> #include <queue> #include <stack> #include <string> #include <vector> #include <cstdio> #include <cstdlib> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // //class NestedInteger { // public: // // Constructor initializes an empty nested list. // NestedInteger(); // // // Constructor initializes a single integer. // NestedInteger(int value); // // // Return true if this NestedInteger holds a single integer, rather than a nested list. // bool isInteger() const; // // // Return the single integer that this NestedInteger holds, if it holds a single integer // // The result is undefined if this NestedInteger holds a nested list // int getInteger() const; // // // Set this NestedInteger to hold a single integer. // void setInteger(int value); // // // Set this NestedInteger to hold a nested list and adds a nested integer to it. // void add(const NestedInteger &ni); // // // Return the nested list that this NestedInteger holds, if it holds a nested list // // The result is undefined if this NestedInteger holds a single integer // const vector<NestedInteger> &getList() const; //}; class NestedInteger { public: NestedInteger() { } NestedInteger(int value) { this->val = value; } bool isInteger() const { return true; } int getInteger() const { return val; } void setInteger(int value) { val = value; } void add(const NestedInteger &ni) { vec.push_back(ni); } const vector<NestedInteger> &getList() const { return vec; } private: int val = 0; vector<NestedInteger> vec; }; class Solution { public: NestedInteger deserialize(string s) { int idx = 0; return deserializeCore(s, idx); } private: NestedInteger deserializeCore(string& s, int& idx) { if (s[idx] == '[') return deserializeList(s, idx); return deserializeNumber(s, idx); } NestedInteger deserializeNumber(string& s, int& idx) { int p = idx; while (p < s.length() && (isdigit(s[p]) || s[p] == '-')) ++p; if (p > idx) { string tmp = s.substr(idx, p-idx); idx = p; return NestedInteger(stoi(tmp)); } idx = p; return NestedInteger(0); } NestedInteger deserializeList(string& s, int& idx) { NestedInteger ni; while (s[idx] != ']') { ++idx; if (s[idx] == ']') break; ni.add(deserializeCore(s, idx)); } ++idx; return ni; } }; int main() { Solution sol = Solution(); // string s = "[324]"; // string s = "324"; string s = "[123,[456,[789]]]"; // string s = "[]"; auto res = sol.deserialize(s); cout << res.getInteger() << endl; return 0; }
23.715328
94
0.566328
[ "vector" ]
80ee6446c4c48d2973526a4d5021783e501cb78a
2,478
cc
C++
mysql-server/router/src/http/src/http_auth_backend_metadata_cache.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/src/http/src/http_auth_backend_metadata_cache.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/src/http/src/http_auth_backend_metadata_cache.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "http_auth_backend_metadata_cache.h" #include <algorithm> #include <fstream> #include <istream> #include <string> #include <vector> #include <sys/stat.h> #include <sys/types.h> #include <cerrno> #include "http_auth_error.h" #include "kdf_pbkdf2.h" #include "kdf_sha_crypt.h" #include "mysqlrouter/metadata_cache.h" std::error_code HttpAuthBackendMetadataCache::authorize( const rapidjson::Document &privileges) { if (!privileges.IsNull()) return make_error_code(HttpAuthErrc::kAuthorizationNotSupported); return {}; } std::error_code HttpAuthBackendMetadataCache::authenticate( const std::string &username, const std::string &password) { if (!metadata_cache::MetadataCacheAPI::instance()->is_initialized()) return make_error_code(McfErrc::kMetadataNotInitialized); const auto auth_data_maybe = metadata_cache::MetadataCacheAPI::instance()->get_rest_user_auth_data( username); if (!auth_data_maybe.first) return make_error_code(McfErrc::kUserNotFound); const auto &auth_data = auth_data_maybe.second; const auto &encoded_hash = auth_data.first; const auto &privileges = auth_data.second; if (encoded_hash.empty() && password.empty()) return {}; const auto &ec = authorize(privileges); if (ec) return ec; return ShaCryptMcfAdaptor::validate(encoded_hash, password); }
34.901408
77
0.76473
[ "vector" ]