| 19 | namespace sdk_cpp { |
| 20 | |
| 21 | int WeightedRandomRender::initialize(const google::protobuf::Message& conf) { |
| 22 | srand((unsigned)time(NULL)); |
| 23 | try { |
| 24 | const configure::WeightedRandomRenderConf& weighted_random_render_conf = |
| 25 | dynamic_cast<const configure::WeightedRandomRenderConf&>(conf); |
| 26 | |
| 27 | std::string weights = weighted_random_render_conf.variant_weight_list(); |
| 28 | |
| 29 | std::vector<std::string> splits; |
| 30 | if (str_split(weights, WEIGHT_SEPERATOR, &splits) != 0) { |
| 31 | LOG(ERROR) << "Failed split string:" << weights; |
| 32 | return -1; |
| 33 | } |
| 34 | |
| 35 | uint32_t weight_size = splits.size(); |
| 36 | _normalized_sum = 0; |
| 37 | for (uint32_t wi = 0; wi < weight_size; ++wi) { |
| 38 | char* end_pos = NULL; |
| 39 | uint32_t ratio = strtoul(splits[wi].c_str(), &end_pos, 10); |
| 40 | if (end_pos == splits[wi].c_str()) { |
| 41 | LOG(ERROR) << "Error ratio(uint32) format:" << splits[wi] << " at " |
| 42 | << wi; |
| 43 | return -1; |
| 44 | } |
| 45 | |
| 46 | _variant_weight_list.push_back(ratio); |
| 47 | _normalized_sum += ratio; |
| 48 | } |
| 49 | |
| 50 | if (_normalized_sum <= 0) { |
| 51 | LOG(ERROR) << "Zero normalized weight sum"; |
| 52 | return -1; |
| 53 | } |
| 54 | |
| 55 | VLOG(2) << "Succ read weights list: " << weights |
| 56 | << ", count: " << _variant_weight_list.size() |
| 57 | << ", normalized: " << _normalized_sum; |
| 58 | } catch (std::bad_cast& e) { |
| 59 | LOG(ERROR) << "Failed init WeightedRandomRender" |
| 60 | << "from configure, err:" << e.what(); |
| 61 | return -1; |
| 62 | } catch (...) { |
| 63 | LOG(ERROR) << "Failed init WeightedRandomRender" |
| 64 | << "from configure, err message is unkown."; |
| 65 | return -1; |
| 66 | } |
| 67 | |
| 68 | return 0; |
| 69 | } |
| 70 | |
| 71 | Variant* WeightedRandomRender::route(const VariantList& variants, |
| 72 | const void* params) { |