Predicate Value::makePredicate() const { switch (kind()) { case CONSTANT: assert(constant().kind() == Constant::BOOLEAN); return constant().boolValue() ? Predicate::True() : Predicate::False(); case ALIAS: { TemplateVarMap assignments(alias().templateVariables().copy(), aliasTemplateArguments().copy()); return alias().value().substitute(assignments, /*selfconst=*/Predicate::SelfConst()).makePredicate(); } case PREDICATE: return predicate().copy(); case TEMPLATEVARREF: { return Predicate::Variable(const_cast<TemplateVar*>(templateVar())); } case TERNARY: { // TODO: Remove this, because it isn't entirely correct. return Predicate::Or(Predicate::And(ternaryCondition().makePredicate(), ternaryIfTrue().makePredicate()), ternaryIfFalse().makePredicate()); } case CAPABILITYTEST: { return Predicate::Satisfies(capabilityTestCheckType(), capabilityTestCapabilityType()); } default: locic_unreachable("Invalid value kind for makePredicate()."); } }
void FormulaCreationMenu::create_max_formula(CNFFormula & f) { ask_k(); ask_n(); int numassg; while(1){ try{ numassg = ui->getint("How many satisfying assignments does this formula have?"); break; } catch(UserInputException e){ std::cout << e.what() << std::endl; } } //now we get the assignments one by one std::vector<Assignment> assignments(numassg,Assignment(n)); for(int i = 0; i<numassg; i++){ while(1){ try{ std::string assg = ui->getstring(std::string("Assignment #").append(std::to_string(i+1)).append("?")); assignments[i].set_assignment(assg); break; } catch(UserInputException e){ std::cout << e.what() << std::endl; } } } MaxSatGenerator mg(n, k, assignments); mg.generate_sat(f); }
void Parser::assignments(MethodGenerationContext* mgenc, list<StdString>& l) { if (symIsIdentifier()) { l.push_back(assignment(mgenc)); Peek(); if (nextSym == Assign) assignments(mgenc, l); } }
// List all assignments common to students in the gradebook void EditAllAssignmentsDialog::populateAssignments() { assignmentList->clear(); std::vector<Assignment> assignments(gradebook->getCommonAssignments()); for(std::vector<Assignment>::const_iterator i = assignments.begin(); i != assignments.end(); ++i) { assignmentList->addItem(QString(i->getName().c_str())); } }
void show_defs( const goto_functionst::goto_functiont &goto_function, const namespacet &ns, std::ostream &out) { ssa_objectst ssa_objects(goto_function, ns); assignmentst assignments(goto_function.body, ns, ssa_objects); ssa_ait ssa_analysis(assignments); ssa_analysis(goto_function, ns); ssa_analysis.output(ns, goto_function.body, out); }
void Parser::assignation(MethodGenerationContext* mgenc) { list<StdString> l; assignments(mgenc, l); evaluation(mgenc); list<StdString>::iterator i; for (i = l.begin(); i != l.end(); ++i) bcGen->EmitDUP(mgenc); for (i = l.begin(); i != l.end(); ++i) genPopVariable(mgenc, (*i)); }
void BipartiteWeightedMatchingBinding::bindFunctUnitInState(raw_ostream &out, State* state, std::string funcUnitType, int numFuncUnitsAvail, AssignmentInfo &assigned) { // create a numFuncUnitsAvail x numFuncUnitsAvail matrix of integer weights // and assignments for solving the bipartite weighted matching problem Table weights(numFuncUnitsAvail, std::vector<int>(numFuncUnitsAvail)); Table assignments(numFuncUnitsAvail, std::vector<int>(numFuncUnitsAvail)); std::string tmp; raw_string_ostream weights_stream(tmp); // loop over all operations in this state int operationIdx = 0; for (State::iterator instr = state->begin(), ie = state->end(); instr != ie; ++instr) { Instruction *I = *instr; if (shareInstructionWithFU(I, funcUnitType)) { constructWeights(weights_stream, I, operationIdx, funcUnitType, numFuncUnitsAvail, assigned, weights); opInstr[operationIdx] = I; operationIdx++; } } // only share if there is more than one operation using // this functional unit int numOperationsToShare = operationIdx; if (numOperationsToShare >= 1) { out << "State: " << state->getName() << "\n"; out << "Binding functional unit type: " << funcUnitType << "\n"; out << "Weight matrix for operation/function unit matching:\n"; weights_stream.flush(); out << weights_stream.str(); printTable(out, funcUnitType, numOperationsToShare, numFuncUnitsAvail, weights); out << "Solving Bipartite Weighted Matching (minimize weights)...\n"; solveBipartiteWeightedMatching(weights, assignments); out << "Assignment matrix after operation/function unit matching:\n"; printTable(out, funcUnitType, numOperationsToShare, numFuncUnitsAvail, assignments); out << "Checking that every operator was assigned to a functional unit..."; CheckAllWereAssigned(numOperationsToShare, numFuncUnitsAvail, assignments); out << "yes\n"; out << "Binding operator -> functional unit assignments:\n"; UpdateAssignments(out, numOperationsToShare, funcUnitType, numFuncUnitsAvail, assigned, assignments); } }
bool controller::export_ptr_list(const arguments &args_, std::string &) const { std::ofstream pointers("sqf_pointers_declaration.hpp"); std::ofstream pointers_def("sqf_pointers_definitions.hpp"); std::ofstream assignments("sqf_assignments.hpp"); pointers << "//Exported Pointer Definitions For: " << args_.as_string(0) << "\n\n"; assignments << "//Exported Pointer Assignments For: " << args_.as_string(0) << "\n\n"; pointers << "\n// Unary Functions\n"; pointers_def << "\n// Unary Functions\n"; assignments << "\n// Unary Functions\n"; auto unary_list = loader::get().unary(); std::list<std::string> sorted_unary_list; for (auto unary : unary_list) { sorted_unary_list.push_back(unary.first); } sorted_unary_list.sort(); for (auto unary_entry : sorted_unary_list) { std::string op_name = unary_entry; std::regex name_test = std::regex("[a-z]+?.*"); if (std::regex_match(op_name, name_test)) { for (auto op : unary_list[unary_entry]) { std::string arg_types = op.op->arg_type.type_str(); std::transform(arg_types.begin(), arg_types.end(), arg_types.begin(), ::tolower); std::string return_type = op.op->return_type.type_str(); std::transform(return_type.begin(), return_type.end(), return_type.begin(), ::tolower); std::string first_arg_type = *op.op->arg_type.type().begin(); std::string pointer_name = "unary__" + op_name + "__" + arg_types + "__ret__" + return_type; pointers_def << "unary_function __sqf::" << pointer_name << ";\n"; pointers << "static unary_function " << pointer_name << ";\n"; //__sqf::unary_random_scalar_raw = (unary_function)functions.get_unary_function_typed("random", "SCALAR"); assignments << "__sqf::" << pointer_name << " = " << "(unary_function)host::functions.get_unary_function_typed(\"" << op_name << "\"_sv, \"" << first_arg_type << "\"_sv);\n"; } } } pointers << "\n// Binary Functions\n"; pointers_def << "\n// Binary Functions\n"; assignments << "\n// Binary Functions\n"; auto binary_list = loader::get().binary(); std::list<std::string> sorted_binary_list; for (auto binary : binary_list) { sorted_binary_list.push_back(binary.first); }; sorted_binary_list.sort(); for (auto binary_entry : sorted_binary_list) { std::string op_name = binary_entry; std::regex name_test = std::regex("[a-z]+?.*"); if (std::regex_match(op_name, name_test)) { for (auto op : binary_list[binary_entry]) { std::string arg1_types = op.op->arg1_type.type_str(); std::transform(arg1_types.begin(), arg1_types.end(), arg1_types.begin(), ::tolower); std::string arg2_types = op.op->arg2_type.type_str(); std::transform(arg2_types.begin(), arg2_types.end(), arg2_types.begin(), ::tolower); std::string return_type = op.op->return_type.type_str(); std::transform(return_type.begin(), return_type.end(), return_type.begin(), ::tolower); std::string first_arg1_type = *op.op->arg1_type.type().begin(); std::string first_arg2_type = *op.op->arg2_type.type().begin(); std::string pointer_name = "binary__" + op_name + "__" + arg1_types + "__" + arg2_types + "__ret__" + return_type; pointers_def << "binary_function __sqf::" << pointer_name << ";\n"; pointers << "static binary_function " << pointer_name << ";\n"; assignments << "__sqf::" << pointer_name << " = " << "(binary_function)host::functions.get_binary_function_typed(\"" << op_name << "\"_sv, \"" << first_arg1_type << "\"_sv, \"" << first_arg2_type << "\"_sv);\n"; } } } pointers << "\n// Nular Functions\n"; pointers_def << "\n// Nular Functions\n"; assignments << "\n// Nular Functions\n"; auto nular_list = loader::get().nular(); std::list<std::string> sorted_nular_list; for (auto nular : nular_list) { sorted_nular_list.push_back(nular.first); }; sorted_nular_list.sort(); for (auto nular_entry : sorted_nular_list) { std::string op_name = nular_entry; std::regex name_test = std::regex("[a-z]+?.*"); if (std::regex_match(op_name, name_test)) { for (auto op : nular_list[nular_entry]) { std::string return_type = op.op->return_type.type_str(); std::transform(return_type.begin(), return_type.end(), return_type.begin(), ::tolower); std::string pointer_name = "nular__" + op_name + "__ret__" + return_type; pointers_def << "nular_function __sqf::" << pointer_name << ";\n"; pointers << "static nular_function " << pointer_name << ";\n"; //__sqf::unary_random_scalar_raw = (unary_function)functions.get_unary_function_typed("random", "SCALAR"); assignments << "__sqf::" << pointer_name << " = " << "(nular_function)host::functions.get_nular_function(\"" << op_name << "\"_sv);\n"; } } } return true; }
bool VLFeat::CalculateCommon(int f, bool all, int l) { string msg = "VLFeat::CalculateCommon("+ToStr(f)+","+ToStr(all)+","+ ToStr(l)+") : "; // if (!do_fisher && !do_vlad) { // cerr << msg // << "either encoding=fisher or encoding=vlad should be specified" // << endl; // return false; // } if (!gmm && !kmeans) { cerr << msg << "either gmm=xxx or kmeans=xxx option should be given" << endl; return false; } cox::tictac::func tt(tics, "VLFeat::CalculateCommon"); // obs! only some parameters here, should be in ProcessOptionsAndRemove() // too, also scales and geometry should be made specifiable... bool normalizeSift = false, renormalize = true, flat_window = true; size_t step = 3, binsize = 8; EnsureImage(); int width = Width(true), height = Height(true); if (FrameVerbose()) cout << msg+"wxh=" << width << "x" << height << "=" << width*height << endl; vector<float> rgbcoeff { 0.2989, 0.5870, 0.1140 }; imagedata idata = CurrentFrame(); idata.convert(imagedata::pixeldata_float); idata.force_one_channel(rgbcoeff); vector<float> dsift; size_t descr_size_orig = 0, descr_size_final = 0; vector<float> scales { 1.0000, 0.7071, 0.5000, 0.3536, 0.2500 }; // vector<float> scales { 1.0000 }; for (size_t i=0; i<scales.size(); i++) { if (KeyPointVerbose()) cout << "Starting vl_dsift_process() in scale " << scales[i] << endl; imagedata simg = idata; if (scales[i]!=1) { scalinginfo si(simg.width(), simg.height(), (int)floor(scales[i]*simg.width()+0.5), (int)floor(scales[i]*simg.height()+0.5)); simg.rescale(si, 1); } // VlDsiftFilter *sf = vl_dsift_new(simg.width(), simg.height()); VlDsiftFilter *sf = vl_dsift_new_basic(simg.width(), simg.height(), step, binsize); // opts.scales = logspace(log10(1), log10(.25), 5) ; // void vl_dsift_set_bounds ( VlDsiftFilter * self, // int minX, // int minY, // int maxX, // int maxY // ); // VlDsiftDescriptorGeometry geom = { 8, 4, 4, 0, 0 }; // vl_dsift_set_geometry(sf, &geom); //vl_dsift_set_steps(sf, 3, 3); //vl_dsift_set_window_size(sf, 8); vl_dsift_set_flat_window(sf, flat_window); // aka fast in matlab vector<float> imgvec = simg.get_float(); const float *img_fp = &imgvec[0]; // cout << "IMAGE = " << img_fp[0] << " " << img_fp[1] << " " // << img_fp[2] << " ... " << img_fp[41] << endl; vl_dsift_process(sf, img_fp); // if opts.rootSift // false // descrs{si} = sqrt(descrs{si}) ; // end // if opts.normalizeSift //true // descrs{si} = snorm(descrs{si}) ; // end descr_size_orig = sf->descrSize; size_t nf = sf->numFrames; const VlDsiftKeypoint *k = sf->frames; float *d = sf->descrs; if (KeyPointVerbose()) cout << " found " << sf->numFrames << " 'frames' in " << simg.info() << endl << " descriptor dim " << descr_size_orig << endl; if (PixelVerbose()) for (size_t i=0; i<nf; i++) { cout << " i=" << i << " x=" << k[i].x << " y=" << k[i].y << " s=" << k[i].s << " norm=" << k[i].norm; if (FullVerbose()) { cout << " RAW"; for (size_t j=0; j<descr_size_orig; j++) cout << " " << d[i*descr_size_orig+j]; } cout << endl; } if (normalizeSift) { for (size_t i=0; i<nf; i++) { if (PixelVerbose()) cout << " i=" << i << " x=" << k[i].x << " y=" << k[i].y << " s=" << k[i].s << " norm=" << k[i].norm; double mul = 0.0; for (size_t j=0; j<descr_size_orig; j++) mul += d[i*descr_size_orig+j]*d[i*descr_size_orig+j]; if (mul) mul = 1.0/sqrt(mul); if (FullVerbose()) cout << " NORM"; for (size_t j=0; j<descr_size_orig; j++) { d[i*descr_size_orig+j] *= mul; if (FullVerbose()) cout << " " << d[i*descr_size_orig+j]; } if (PixelVerbose()) cout << endl; } } if (!pca.vector_length()) { dsift.insert(dsift.end(), d, d+nf*descr_size_orig); descr_size_final = descr_size_orig; } else { for (size_t i=0; i<nf; i++) { vector<float> vin(d+i*descr_size_orig, d+(i+1)*descr_size_orig); vector<float> vout = pca.projection_coeff(vin); dsift.insert(dsift.end(), vout.begin(), vout.end()); } descr_size_final = pca.base_size(); } vl_dsift_delete(sf); } size_t numdata = dsift.size()/descr_size_final; const float *datain = &dsift[0]; vector<float> enc((do_fisher?2:1)*descriptor_dim()*nclusters()); float *dataout = &enc[0]; if (do_fisher) { if (FrameVerbose()) cout << msg << "fisher encoding " << numdata << " descriptors of size " << descr_size_orig << " => " << descr_size_final << " with gmm dimensionality " << descriptor_dim() << endl; if (descr_size_final!=descriptor_dim()) { cerr << msg << "dimensionality mismatch descr_size_final=" << descr_size_final << " descriptor_dim()=" << descriptor_dim() << endl; return false; } vl_fisher_encode(dataout, VL_TYPE_FLOAT, means(), descriptor_dim(), nclusters(), covariances(), priors(), datain, numdata, VL_FISHER_FLAG_IMPROVED) ; } if (do_vlad) { //obs! correct use of pca? if (FrameVerbose()) cout << msg << "vlad encoding " << numdata << " descriptors of size " << descr_size_final << endl; vector<vl_uint32> indexes(numdata); vector<float> distances(numdata); if (kdtree) vl_kdforest_query_with_array(kdtree, &indexes[0], 1, numdata, &distances[0], datain); else vl_kmeans_quantize(kmeans, &indexes[0], &distances[0], datain, numdata); vector<float> assignments(numdata*nclusters()); for (size_t i=0; i<numdata; i++) assignments[i * nclusters() + indexes[i]] = 1; int vlad_flags = VL_VLAD_FLAG_SQUARE_ROOT|VL_VLAD_FLAG_NORMALIZE_COMPONENTS; vl_vlad_encode(dataout, VL_TYPE_FLOAT, means(), descriptor_dim(), nclusters(), datain, numdata, &assignments[0], vlad_flags); } if (renormalize) { if (PixelVerbose()) cout << " RENORM:"; double mul = 0.0; for (size_t j=0; j<enc.size(); j++) mul += enc[j]*enc[j]; if (mul) mul = 1.0/sqrt(mul); for (size_t j=0; j<enc.size(); j++) { if (PixelVerbose()) cout << " " << enc[j]; enc[j] *= mul; if (PixelVerbose()) cout << "->" << enc[j]; } if (PixelVerbose()) cout << endl; } ((VectorData*)GetData(0))->setVector(enc); return true; }
void primitive(void) { int ptr = 0; if(tokeq("call")) { byte * b = m; int l; int c; int v; int a = 0; int i; scan(); boolexpr(); if(tokeq("(")) { scan(); a++; boolexpr(); g_pop_ax(); g_pop_bx(); g_push_ax(); g_push_bx(); while (tokeq(",")) { scan(); a++; boolexpr(); g_pop_ax(); g_pop_bx(); g_push_ax(); g_push_bx(); } if(tokeq(")")) { scan(); } else { error("Missing )"); } } g_pop_bx(); g_push_bp(); g_mov_ax_sp(); g_add_ax(a << 1); g_mov_bp_ax(); g_call_bx(); g_pop_dx(); g_pop_bp(); for(i=0;i<a;i++) { g_pop_ax(); } g_push_dx(); return; } if(tokeq("poll")) { scan(); if(tokeq("tty")) { scan(); g_mov_ah(11); g_int(0x21); g_xor_ah_ah(); g_push_ax(); return; } error("You can only poll the tty"); return; } if(tokeq("Ypush")) { scan(); if(tokeq("(")) { scan(); boolexpr(); if(tokeq(")")) { g_xor_ax_ax(); g_push_ax(); scan(); return; } if(tokeq(",")) { scan(); boolexpr(); if(tokeq(")")) { scan(); return; } } } error("Usage is Ypush(boolexpr[,boolexpr]) in function"); return; } if(tokeq("Ypop")) { scan(); if(tokeq("(")) { scan(); if(tokeq(")")) { scan(); return; } } error("Usage would be Ypop() in function"); return; } if(tokeq("eof")) { scan(); g_mov_bx(caddr(eofflag)); g_push_BX(); g_xor_ax_ax(); g_mov_BX_ax(); return; } if(tokeq("gpos")) { scan(); if(tokeq("(")) { scan(); boolexpr(); if (tokeq(",")) { scan(); boolexpr(); g_xor_cx_cx(); g_pop_dx(); g_mov_ax(0x4201); g_pop_bx(); g_int(0x21); g_push_ax(); if (tokeq(")")) { scan(); return; } } } error("Malformed way to use 'gpos'"); } if(tokeq("sin")) { runtime_trig(); scan(); boolexpr(); g_pop_ax(); g_mov_bx(caddr(sin_routine)); g_call_bx(); g_push_cx(); return; } if(tokeq("cos")) { runtime_trig(); scan(); boolexpr(); g_pop_ax(); g_mov_bx(caddr(cos_routine)); g_call_bx(); g_push_cx(); return; } if(tokeq("abs")) { scan(); boolexpr(); g_pop_ax(); g_and_ax(0x7fff); g_push_ax(); return; } if(tokeq("asc")) { scan(); boolexpr(); g_pop_ax(); g_and_ax(0x007f); g_push_ax(); return; } if(tokeq("low")) { scan(); boolexpr(); g_pop_ax(); g_and_ax(0x00ff); g_push_ax(); return; } if(tokeq("med")) { scan(); boolexpr(); g_pop_ax(); g_mov_cl(4); g_shr_ax_cl(); g_and_ax(0x00ff); g_push_ax(); return; } if(tokeq("fix")) { scan(); boolexpr(); g_pop_ax(); g_mov_ah_al(); g_xor_al_al(); g_push_ax(); return; } if(tokeq("int") || tokeq("hig")) { scan(); boolexpr(); g_pop_ax(); g_mov_al_ah(); g_xor_ah_ah(); g_push_ax(); return; } if(tokeq("fre")) { scan(); boolexpr(); g_pop_ax(); g_mov_ax_I(caddr(d)-2); g_neg_ax(); g_push_ax(); return; } if(tokeq("rnd")) { symbol * q = NULL; scan(); if(tokeq("(")) { scan(); q = name(0); if(tokeq(")")) { scan(); } else error("Missing )"); } else { error("Need identifier in rnd()"); } g_pop_bx(); g_mov_ax_BX(); g_mov_dx(58653U); g_imul_dx(); g_mov_dx(13849U); g_add_ax_dx(); g_mov_BX_ax(); g_push_ax(); if (q != NULL && q->hook_addr != NULL) { g_mov_ax(caddr(q->hook_addr)); g_call_ax(); } return; } if(tokeq("stu")) { scan(); boolexpr(); g_pop_ax(); g_mov_bx(caddr(sbuffer + 14)); g_label(); g_xor_dx_dx(); g_mov_cx(10); g_idiv_cx(); g_add_dx('0'); g_mov_BX_dl(); g_dec_bx(); g_or_ax_ax(); g_jnz(-18); g_inc_bx(); g_push_bx(); return; } if(tokeq("str")) { scan(); boolexpr(); g_pop_ax(); g_push_ax(); g_cmp_ax(0); g_jg(+2); g_neg_ax(); g_label(); g_mov_bx(caddr(sbuffer + 14)); g_label(); g_xor_dx_dx(); g_mov_cx(10); g_idiv_cx(); g_add_dx('0'); g_mov_BX_dl(); g_dec_bx(); g_or_ax_ax(); g_jnz(-18); g_pop_ax(); g_cmp_ax(0); g_jge(+5); g_mov_al('-'); g_mov_BX_al(); g_dec_bx(); g_label(); g_inc_bx(); g_push_bx(); return; } if(tokeq("sif")) { scan(); boolexpr(); g_pop_ax(); g_push_ax(); g_xor_ah_ah(); g_mov_dx(39); g_imul_dx(); /* g_mov_al_ah(); g_mov_ah_dl(); */ g_mov_bx(caddr(sbuffer + 14)); g_mov_cx(10); g_label(); g_xor_dx_dx(); g_idiv_cx(); g_add_dx('0'); g_mov_BX_dl(); g_dec_bx(); g_cmp_bx(caddr(sbuffer + 10)); g_jnz(-17); g_mov_dx('.'); g_mov_BX_dl(); g_dec_bx(); g_pop_ax(); g_mov_al_ah(); g_xor_ah_ah(); g_label(); g_xor_dx_dx(); g_idiv_cx(); g_add_dx('0'); g_mov_BX_dl(); g_dec_bx(); g_or_ax_ax(); g_jnz(-15); g_inc_bx(); g_push_bx(); return; } if(tokeq("nameof")) { char * q; byte * b; scan(); if(tokeq("(")) { scan(); q = (token+1); b = stalloc(strlen(q)+1); name(0); if(tokeq(")")) { scan(); strcpy((char *)b, q); g_mov_ax(caddr(b)); g_push_ax(); } else error("Missing ("); } else error("Missing )"); return; } if(tokeq("^")) { scan(); ptr = 1; } if(tokeq("#")) { scan(); if (tokeq("(")) { scan(); boolexpr(); if (tokeq(")")) { scan(); g_pop_ax(); g_shl_ax_1(); g_neg_ax(); g_xchg_si_ax(); g_mov_ax_BP_SI(); g_push_ax(); return; } error("Missing )"); return; } g_mov_ax_BP(-2 * member()); g_push_ax(); return; } if(sym_exists(token)) { symbol * q = NULL; q = name(0); if (!ptr) { g_pop_bx(); g_push_BX(); if (tokeq("++")) { scan(); g_mov_ax_BX(); g_inc_ax(); g_mov_BX_ax(); if (q != NULL && q->hook_addr != NULL) { g_mov_ax(caddr(q->hook_addr)); g_call_ax(); } } if (tokeq("--")) { scan(); g_mov_ax_BX(); g_dec_ax(); g_mov_BX_ax(); if (q != NULL && q->hook_addr != NULL) { g_mov_ax(caddr(q->hook_addr)); g_call_ax(); } } } return; } if (ptr) { error("Identifier should follow ^"); } if(token[0] >= '0' && token[0] <= '9') { int v = atoi(token); g_mov_ax(v); g_push_ax(); scan(); if (tokeq(".")) { scan(); while(strlen(token) < 4) { strcat(token, "0"); } v = atoi(token) / 39; scan(); if (v > 255) v = 255; g_pop_ax(); g_mov_ah_al(); g_mov_al(v & 0xff); g_push_ax(); } return; } if(token[0] == '"') { char * q = (token+1); byte * b = stalloc(strlen(q)+1); strcpy((char *)b, q); g_mov_ax(caddr(b)); g_push_ax(); scan(); while(token[0] == '"') { char * q = (token+1); byte * b; stretract(); b = stalloc(strlen(q)+1); strcpy((char *)b, q); scan(); } return; } if(tokeq("{")) { byte * l; byte * q; int c=0; int v=0; int lc; scan(); l = m; g_label(); g_nop(); assignments(); if (tokeq("}")) { scan(); g_ret(); q = stalloc(m - l); memcpy(q, l, m - l); m = l; g_mov_ax(caddr(q)); g_push_ax(); return; } error("Missing }"); return; } if(tokeq("INLINE")) { byte * l; byte * q; int c=0; int v=0; int lc; scan(); if(tokeq("{")) scan(); l = m; g_label(); g_nop(); while(tokne("}")) { GEN(atoi(token)); scan(); } scan(); g_ret(); q = stalloc(m - l); memcpy(q, l, m - l); m = l; g_mov_ax(caddr(q)); g_push_ax(); return; } if(tokeq("(")) { scan(); boolexpr(); if (tokeq(")")) { scan(); return; } error("Missing )"); return; } if(tokeq("*")) { scan(); boolexpr(); g_mov_bx(260); g_mov_ax_BX(); g_pop_dx(); g_push_ax(); g_add_ax_dx(); g_mov_BX_ax(); return; } error("Unrecognized primitive"); }
size_t MaxVarianceNewCluster::EmptyCluster(const MatType& data, const size_t emptyCluster, arma::mat& centroids, arma::Col<size_t>& clusterCounts, MetricType& metric) { // First, we need to find the cluster with maximum variance (by which I mean // the sum of the covariance matrices). arma::vec variances; variances.zeros(clusterCounts.n_elem); // Start with 0. arma::Col<size_t> assignments(data.n_cols); // Add the variance of each point's distance away from the cluster. I think // this is the sensible thing to do. for (size_t i = 0; i < data.n_cols; ++i) { // Find the closest centroid to this point. double minDistance = std::numeric_limits<double>::infinity(); size_t closestCluster = centroids.n_cols; // Invalid value. for (size_t j = 0; j < centroids.n_cols; j++) { const double distance = metric.Evaluate(data.col(i), centroids.col(j)); if (distance < minDistance) { minDistance = distance; closestCluster = j; } } assignments[i] = closestCluster; variances[closestCluster] += metric.Evaluate(data.col(i), centroids.col(closestCluster)); } // Divide by the number of points in the cluster to produce the variance. // Although a -nan will occur here for the empty cluster(s), this doesn't // matter because variances.max() won't pick it up. If the number of points // in the cluster is 1, we ensure that cluster is not selected by forcing the // variance to 0. for (size_t i = 0; i < clusterCounts.n_elem; ++i) variances[i] /= (clusterCounts[i] == 1) ? DBL_MAX : clusterCounts[i]; // Now find the cluster with maximum variance. arma::uword maxVarCluster; variances.max(maxVarCluster); // Now, inside this cluster, find the point which is furthest away. size_t furthestPoint = data.n_cols; double maxDistance = -DBL_MAX; for (size_t i = 0; i < data.n_cols; ++i) { if (assignments[i] == maxVarCluster) { const double distance = metric.Evaluate(data.col(i), centroids.col(maxVarCluster)); if (distance > maxDistance) { maxDistance = distance; furthestPoint = i; } } } // Take that point and add it to the empty cluster. centroids.col(maxVarCluster) *= (double(clusterCounts[maxVarCluster]) / double(clusterCounts[maxVarCluster] - 1)); centroids.col(maxVarCluster) -= (1.0 / (clusterCounts[maxVarCluster] - 1.0)) * arma::vec(data.col(furthestPoint)); clusterCounts[maxVarCluster]--; clusterCounts[emptyCluster]++; centroids.col(emptyCluster) = arma::vec(data.col(furthestPoint)); assignments[furthestPoint] = emptyCluster; // Output some debugging information. Log::Debug << "Point " << furthestPoint << " assigned to empty cluster " << emptyCluster << ".\n"; return 1; // We only changed one point. }
void TempMotifCounter::Count3TEdgeTriads(double delta, Counter3D& counts) { counts = Counter3D(2, 2, 2); // Get the counts on each undirected edge TVec< THash<TInt, TInt> > edge_counts(static_graph_->GetMxNId()); TVec< THash<TInt, TIntV> > assignments(static_graph_->GetMxNId()); for (TNGraph::TEdgeI it = static_graph_->BegEI(); it < static_graph_->EndEI(); it++) { int src = it.GetSrcNId(); int dst = it.GetDstNId(); int min_node = MIN(src, dst); int max_node = MAX(src, dst); edge_counts[min_node](max_node) += temporal_data_[src](dst).Len(); assignments[min_node](max_node) = TIntV(); } // Assign triangles to the edge with the most events TIntV Us, Vs, Ws; GetAllStaticTriangles(Us, Vs, Ws); #pragma omp parallel for schedule(dynamic) for (int i = 0; i < Us.Len(); i++) { int u = Us[i]; int v = Vs[i]; int w = Ws[i]; int counts_uv = edge_counts[MIN(u, v)].GetDat(MAX(u, v)); int counts_uw = edge_counts[MIN(u, w)].GetDat(MAX(u, w)); int counts_vw = edge_counts[MIN(v, w)].GetDat(MAX(v, w)); if (counts_uv >= MAX(counts_uw, counts_vw)) { #pragma omp critical { TIntV& assignment = assignments[MIN(u, v)].GetDat(MAX(u, v)); assignment.Add(w); } } else if (counts_uw >= MAX(counts_uv, counts_vw)) { #pragma omp critical { TIntV& assignment = assignments[MIN(u, w)].GetDat(MAX(u, w)); assignment.Add(v); } } else if (counts_vw >= MAX(counts_uv, counts_uw)) { #pragma omp critical { TIntV& assignment = assignments[MIN(v, w)].GetDat(MAX(v, w)); assignment.Add(u); } } } TVec<TIntPair> all_edges; TIntV all_nodes; GetAllNodes(all_nodes); for (int node_id = 0; node_id < all_nodes.Len(); node_id++) { int u = all_nodes[node_id]; TIntV nbrs; GetAllNeighbors(u, nbrs); for (int nbr_id = 0; nbr_id < nbrs.Len(); nbr_id++) { int v = nbrs[nbr_id]; if (assignments[u].IsKey(v) && assignments[u].GetDat(v).Len() > 0) { all_edges.Add(TIntPair(u, v)); } } } // Count triangles on edges with the assigned neighbors #pragma omp parallel for schedule(dynamic) for (int edge_id = 0; edge_id < all_edges.Len(); edge_id++) { TIntPair edge = all_edges[edge_id]; int u = edge.Key; int v = edge.Dat; // Continue if no assignment if (!assignments[u].IsKey(v)) { continue; } TIntV& uv_assignment = assignments[u].GetDat(v); // Continue if no data if (uv_assignment.Len() == 0) { continue; } // Get all events on (u, v) TVec<TriadEdgeData> events; TVec<TIntPair> ts_indices; int index = 0; int nbr_index = 0; // Assign indices from 0, 1, ..., num_nbrs + 2 AddTriadEdgeData(events, ts_indices, index, u, v, nbr_index, 0, 1); nbr_index++; AddTriadEdgeData(events, ts_indices, index, v, u, nbr_index, 0, 0); nbr_index++; // Get all events on triangles assigned to (u, v) for (int w_id = 0; w_id < uv_assignment.Len(); w_id++) { int w = uv_assignment[w_id]; AddTriadEdgeData(events, ts_indices, index, w, u, nbr_index, 0, 0); AddTriadEdgeData(events, ts_indices, index, w, v, nbr_index, 0, 1); AddTriadEdgeData(events, ts_indices, index, u, w, nbr_index, 1, 0); AddTriadEdgeData(events, ts_indices, index, v, w, nbr_index, 1, 1); nbr_index++; } // Put events in sorted order ts_indices.Sort(); TIntV timestamps(ts_indices.Len()); TVec<TriadEdgeData> sorted_events(ts_indices.Len()); for (int i = 0; i < ts_indices.Len(); i++) { timestamps[i] = ts_indices[i].Key; sorted_events[i] = events[ts_indices[i].Dat]; } // Get the counts and update the counter ThreeTEdgeTriadCounter tetc(nbr_index, 0, 1); tetc.Count(sorted_events, timestamps, delta); #pragma omp critical { for (int dir1 = 0; dir1 < 2; dir1++) { for (int dir2 = 0; dir2 < 2; dir2++) { for (int dir3 = 0; dir3 < 2; dir3++) { counts(dir1, dir2, dir3) += tetc.Counts(dir1, dir2, dir3); } } } } } }