#include "rogueviz.h" // SAG visualizer (e.g. Reddit roguelikes, GitHub languages) //----------------------------------------------------------- // see: https://www.youtube.com/watch?v=mDG3_f8R2Ns (SAG boardgames) // see: https://www.youtube.com/watch?v=WSyygk_3j9o (SAG roguelikes) // see: https://www.youtube.com/watch?v=HWQkDkeEUeM (SAG programming languages) #include "dhrg/dhrg.h" #include #include "leastsquare.cpp" namespace rogueviz { namespace sag { int threads = 1; int informat; /* format ID */ bool turn(int delta); int sagpar = 0; bool angular = false; bool report_tempi = false; int best_cost = 1000000000; enum eSagmode { sagOff, sagHC, sagSA }; eSagmode sagmode; // 0 - off, 1 - hillclimbing, 2 - SA const char *sagmodes[3] = {"off", "HC", "SA"}; ld temperature = -4; const char *loadfname; string auto_save; bool auto_visualize = true; int vizsa_start; int vizsa_len; /** all the SAG cells */ vector sagcells; /** table of distances between SAG cells */ vector> sagdist; /** what node is on sagcells[i] */ vector sagnode; /** node i is on sagcells[sagid[i]] */ vector sagid; /** sagcells[ids[c]]] == c */ map ids; /** if i in neighbors[j], sagcells[i] is a neighbor of sagcells[j] */ vector> neighbors; ld pdist(hyperpoint hi, hyperpoint hj); /** matrix for every sagcell */ vector cell_matrix; /** precision of geometric distances */ int gdist_prec; /** max edge for dijkstra */ int dijkstra_maxedge; /** the maximum value in sagdist +1 */ int max_sag_dist; vector sagedges; vector> edges_yes, edges_no; enum eSagMethod { smClosest, smLogistic, smMatch }; eSagMethod method; bool loglik_repeat; /* parameters for smMatch */ ld match_a = 1, match_b = 0; /* parameters for smLogistic */ dhrg::logistic lgsag(1, 1); vector loglik_tab_y, loglik_tab_n; int ipturn = 100; long long numiter = 0; int hightemp = 10; int lowtemp = -15; /* for the embedding method: */ bool embedding; dhrg::logistic lgemb(1, 1); vector placement; string distance_file; void compute_dists() { int N = isize(sagcells); neighbors.clear(); neighbors.resize(N); for(int i=0; i visited; auto visit = [&] (int id, const transmatrix& T) { if(cell_matrix[id][0][0] != ERRORV) return; cell_matrix[id] = T; visited.push_back(id); }; visit(0, Id); for(int i=0; itype; d++) if(ids.count(c0->move(d))) visit(ids[c0->move(d)], T0 * currentmap->adj(c0, d)); } sagdist.clear(); sagdist.resize(N); for(int i=0; i>> dijkstra_edges(N); for(int i=0; i distances(N); for(int i=a; i> pq; auto visit = [&] (int i, ld dist) { if(distances[i] <= dist) return; distances[i] = dist; pq.emplace(-dist, i); }; visit(i, 0); while(!pq.empty()) { ld d = -pq.top().first; int at = pq.top().second; pq.pop(); for(auto e: dijkstra_edges[at]) visit(e.first, d + e.second); } for(int j=0; j q; auto visit = [&] (int j, int dist) { if(sdi[j] < N) return; sdi[j] = dist; q.push_back(j); }; visit(i, 0); for(int j=0; j(max_sag_dist, x); max_sag_dist++; } bool legacy; /* legacy method */ void init_snake(int n) { sagcells.clear(); ids.clear(); auto enlist = [&] (cellwalker cw) { ids[cw.at] = isize(sagcells); sagcells.push_back(cw.at); }; cellwalker cw = cwt; enlist(cw); cw += wstep; enlist(cw); for(int i=2; iallcells(); int N = isize(sagcells); ids.clear(); for(int i=0; i hubval; double costat(int vid, int sid) { if(vid < 0) return 0; double cost = 0; if(method == smLogistic) { auto &s = sagdist[sid]; for(auto j: edges_yes[vid]) cost += loglik_tab_y[s[sagid[j]]]; for(auto j: edges_no[vid]) cost += loglik_tab_n[s[sagid[j]]]; return -cost; } if(method == smMatch) { vertexdata& vd = vdata[vid]; for(int j=0; jweight2 + match_b; ld dist = cdist - expect; cost += dist * dist; } } return cost; } vertexdata& vd = vdata[vid]; for(int j=0; jweight2; } if(!hubval.empty()) { for(auto sid2: neighbors[sid]) { int vid2 = sagnode[sid2]; if(vid2 >= 0 && (hubval[vid] & hubval[vid]) == 0) cost += hub_penalty; } } return cost; } // std::mt19937 los; double cost; vector chgs; edgetype *sag_edge; void forgetedges(int id) { for(int i=0; iorig = NULL; } bool chance(double p) { p *= double(hrngen.max()) + 1; auto l = hrngen(); auto pv = (decltype(l)) p; if(l < pv) return true; if(l == pv) return chance(p-pv); return false; } void saiter() { int DN = isize(sagid); int t1 = hrand(DN); int sid1 = sagid[t1]; int sid2; int s = hrand(4)+1; if(s == 4) sid2 = hrand(isize(sagcells)); else { sid2 = sid1; for(int ii=0; ii= 0) sagid[t2] = -1; double change = costat(t1,sid2) + costat(t2,sid1) - costat(t1,sid1) - costat(t2,sid2); sagnode[sid1] = t1; sagid[t1] = sid1; sagnode[sid2] = t2; if(t2 >= 0) sagid[t2] = sid2; if(change > 0 && (sagmode == sagHC || !chance(exp(-change * exp(-temperature))))) return; sagnode[sid1] = t2; sagnode[sid2] = t1; sagid[t1] = sid2; if(t2 >= 0) sagid[t2] = sid1; cost += change; } void prepare_graph() { int DN = isize(sagid); set> alledges; for(auto e: sagedges) { if(e.i == e.j) continue; alledges.emplace(e.i, e.j); alledges.emplace(e.j, e.i); } edges_yes.clear(); edges_yes.resize(DN); edges_no.clear(); edges_no.resize(DN); for(int i=0; ibase = sagcells[sag::sagid[i]]; forgetedges(i); } shmup::fixStorage(); } void load_sag_solution(const string& fname) { printf("Loading the sag from: %s\n", fname.c_str()); FILE *sf = fopen(fname.c_str(), "rt"); if(!sf) { printf("Failed to open file.\n"); exit(1); } int SN = isize(sagcells); if(sf) while(true) { string lab; while(true) { int c = fgetc(sf); if(c == EOF) goto afterload; else if(c == ',' || c == ';') break; else if(rv_ignore(c)) ; else lab += c; } int sid = -1; int err = fscanf(sf, "%d", &sid); if(sid < 0 || sid >= SN || err < 1) sid = -1; if(!labeler.count(lab)) { printf("unknown vertex: %s\n", lab.c_str()); } else { int id = getid(lab); sagid[id] = sid; } } afterload: if(sf) fclose(sf); prepare_graph(); reassign(); } void dofullsa(int satime) { sagmode = sagSA; int t1 = SDL_GetTicks(); int tl = -999999; while(true) { int t2 = SDL_GetTicks(); double d = (t2-t1) / (1000. * satime); if(d > 1) break; temperature = hightemp - (d*(hightemp-lowtemp)); for(int i=0; i<10000; i++) { numiter++; sag::saiter(); } if(t2 - tl > 980) { tl = t2; println(hlog, format("it %12Ld temp %6.4f [1/e at %13.6f] cost = %f ", numiter, double(sag::temperature), (double) exp(sag::temperature), double(sag::cost))); } } temperature = -5; sagmode = sagOff; reassign(); } void dofullsa_iterations(long long saiter) { sagmode = sagSA; decltype(SDL_GetTicks()) t1 = -999999; for(int i=0; i 1000) { t1 = t2; println(hlog, format("it %12Ld temp %6.4f [1/e at %13.6f] cost = %f ", numiter, double(sag::temperature), (double) exp(sag::temperature), double(sag::cost))); } } } temperature = -5; sagmode = sagOff; reassign(); } void iterate() { if(!sagmode) return; int t1 = SDL_GetTicks(); for(int i=0; i 200) ipturn /= 2; else ipturn = ipturn * 100 / t; print(hlog, format("it %12Ld temp %6.4f [2:%8.6f,10:%8.6f,50:%8.6f] cost = %f\n", numiter, double(sag::temperature), (double) exp(-2 * exp(-sag::temperature)), (double) exp(-10 * exp(-sag::temperature)), (double) exp(-50 * exp(-sag::temperature)), (double) sag::cost)); if(auto_visualize) reassign(); } void save_sag_solution(const string& fname) { FILE *f = fopen(fname.c_str(), "wt"); for(int i=0; i= sag_edge->visible_from) pedge[sagdist[sagid[ei.i]][sagid[ei.j]] * mul]++; } for(int d=0; d(f); int id; if(!labeler.count(lab)) { printf("unknown vertex: %s\n", lab.c_str()); continue; } else id = getid(lab); ld alpha, r; if(1) { dynamicval g(geometry, gNormal); hyperpoint h; for(int d=0; d(f); alpha = atan2(h); r = hdist0(h); println(hlog, "read ", lab, " as ", h, " which is ", tie(alpha, r)); } placement[id] = direct_exp(cspin(0, 2, alpha) * ctangent(0, r)); println(hlog, "dist = ", pdist(placement[id], C0), " expected: ", r); } } else if(informat == 3) { /* BFKL */ string ignore; if(!scan(f, ignore, ignore, ignore, ignore, ignore, ignore, ignore, ignore)) { printf("Error: incorrect format of the first line\n"); exit(1); } while(true) { string lab = scan(f); if(lab == "" || lab == "#ROGUEVIZ_ENDOFDATA") break; ld r, alpha; if(!scan(f, r, alpha)) { printf("Error: incorrect format of r/alpha\n"); exit(1); } hyperpoint h = spin(alpha * degree) * xpush0(r); if(!labeler.count(lab)) { printf("unknown vertex: %s\n", lab.c_str()); } else { int id = getid(lab); placement[id] = h; } } } else if(informat == 4) { while(true) { string lab = scan(f); if(lab == "") break; ld r, alpha; if(!scan(f, r, alpha)) { printf("Error: incorrect format of r/alpha\n"); exit(1); } hyperpoint h = spin(alpha) * xpush0(r); if(!labeler.count(lab)) { printf("unknown vertex: %s\n", lab.c_str()); } else { int id = getid(lab); placement[id] = h; } } } else { while(!feof(f.f)) { string lab = scan(f); int id; if(!labeler.count(lab)) { printf("unknown vertex: %s\n", lab.c_str()); continue; } else id = getid(lab); hyperpoint h; for(int d=0; d(f); placement[id] = h; } } reassign_embedding(); compute_loglik(); } void read_hubs(const string& fname) { hubval.resize(isize(vdata), -1); fhstream f(fname, "rt"); if(!f.f) { printf("Failed to open hub file: %s\n", fname.c_str()); exit(1); } println(hlog, "loading hubs: ", fname); while(!feof(f.f)) { string l1, l2; while(true) { int c = fgetc(f.f); if(c == EOF) return; else if(c == ';') break; else if(rv_ignore(c)) ; else l1 += c; } while(true) { int c = fgetc(f.f); if(c == EOF) return; else if(c == ';') return; else if(rv_ignore(c)) break; else l2 += c; } if(!id_known(l1)) { printf("label unknown: %s\n", l1.c_str()); exit(1); } hubval[getid(l1)] = atoi(l2.c_str()); } } void readsag(const char *fname) { maxweight = 0; sag_edge = add_edgetype("SAG edge"); fhstream f(fname, "rt"); if(!f.f) { printf("Failed to open SAG file: %s\n", fname); throw "failed to open SAG file"; } if(informat == 1) { scanline(f); set > edges; int all = 0, good = 0; while(!feof(f.f)) { string l1 = scan(f); string l2 = scan(f); if(l1 == "") continue; if(l2 == "") continue; edgeinfo ei(sag_edge); ei.i = getid(l1); ei.j = getid(l2); if(ei.i > ei.j) swap(ei.i, ei.j); all++; if(edges.count({ei.i, ei.j})) continue; good++; edges.emplace(ei.i, ei.j); ei.weight = 1; sagedges.push_back(ei); } println(hlog, "N = ", isize(vdata), " edges = ", good, "/", all); return; } while(!feof(f.f)) { string l1, l2; while(true) { int c = fgetc(f.f); if(c == EOF) return; else if(c == ';') break; else if(rv_ignore(c)) ; else l1 += c; } while(true) { int c = fgetc(f.f); if(c == EOF) return; else if(c == ';') break; else if(rv_ignore(c)) ; else l2 += c; } ld wei; if(!scan(f, wei)) continue; edgeinfo ei(sag_edge); ei.i = getid(l1); ei.j = getid(l2); ei.weight = wei; sagedges.push_back(ei); } } ld edgepower=1, edgemul=1; void init() { rogueviz::init(RV_GRAPH | RV_WHICHWEIGHT | RV_AUTO_MAXWEIGHT | RV_HAVE_WEIGHT); rv_hook(rogueviz::hooks_close, 100, [] { sag::sagedges.clear(); }); rv_hook(shmup::hooks_turn, 100, turn); rv_hook(rogueviz::hooks_rvmenu, 100, [] { dialog::addSelItem(XLAT("temperature"), fts(sag::temperature), 't'); dialog::add_action([] { dialog::editNumber(sag::temperature, sag::lowtemp, sag::hightemp, 1, 0, XLAT("temperature"), ""); }); dialog::addSelItem(XLAT("SAG mode"), sag::sagmodes[sag::sagmode], 'm'); dialog::add_action([] { sag::sagmode = sag::eSagmode( (1+sag::sagmode) % 3 ); }); dialog::addSelItem(XLAT("min temperature"), fts(sag::lowtemp), 'i'); dialog::add_action([] { dialog::editNumber(sag::lowtemp, -20, 20, 1, 0, XLAT("min temperature"), ""); }); dialog::addSelItem(XLAT("max temperature"), fts(sag::hightemp), 'i'); dialog::add_action([] { dialog::editNumber(sag::hightemp, -20, 20, 1, 0, XLAT("high temperature"), ""); }); dialog::addSelItem(XLAT("automatic cycle"), fts(sag::vizsa_len), 'c'); dialog::add_action([] { dialog::editNumber(sag::vizsa_len, 5, 1800, 1, 0, XLAT("automatic cycle"), ""); }); dialog::addBoolItem(XLAT("automatic"), sag::vizsa_start, 'a'); dialog::add_action([] { sag::vizsa_start = sag::vizsa_start ? 0 : SDL_GetTicks(); sag::sagmode = sagOff; }); dialog::addBoolItem_action(XLAT("auto-visualize"), sag::auto_visualize, 'b'); dialog::addBoolItem_action(XLAT("continuous embedding"), sag::embedding, 'e'); }); weight_label = "min weight"; temperature = 0; sagmode = sagOff; } void create_viz() { int DN = isize(vdata); for(int i=0; i n || m < 0) throw hr_exception("generate_fake_data parameters incorrect"); sagid.resize(m); int SN = isize(sagcells); int DN = isize(sagid); vdata.resize(DN); for(int i=0; i alldist; for(int j=0; j sorted_sagdist; for(auto& a: sagdist) for(auto b: a) sorted_sagdist.push_back(b); sort(sorted_sagdist.begin(), sorted_sagdist.end()); vector d(5, 0); for(auto a: sagdist[0]) if(a < 5) d[a]++; for(int i=0; i<3; i++) { bool first = false; #define out(x, y) if(i == 0) println(hlog, x, " = ", y); else if(first) print(hlog, ";"); first = true; if(i == 1) print(hlog, x); if(i == 2) print(hlog, y); out("nodes", isize(sagcells)); out("maxsagdist", max_sag_dist); out("dim", (euclid && WDIM == 2 && euc::eu.user_axes[1][1] == 1) ? 1 : WDIM); out("geometry", S3 >= OINF ? "tree" : hyperbolic ? "hyperbolic" : sphere ? "sphere" : euclid ? "euclid" : nil ? "nil" : sol ? "solv" : prod ? "product" : "other"); out("closed", max_sag_dist == isize(sagcells) ? 0 : closed_manifold ? 1 : 0); out("angular", angular); for(int p: {1, 10, 50}) { out(format("sagdist%02d", p), sorted_sagdist[(p * sorted_sagdist.size()) / 100]); } for(int p: {1, 2, 3, 4}) { out(format("d%d", p), d[p]); } println(hlog); #undef out } } void output_stats() { if(auto_save != "" && cost < best_cost) { println(hlog, "cost ", cost, " beats ", best_cost); best_cost = cost; sag::save_sag_solution(auto_save); } println(hlog, "solution: ", sagid); int DN = isize(sagid); ld mAP = compute_mAP(); dhrg::iddata routing_result; dhrg::prepare_pairs(DN, [] (int i) { return edges_yes[i]; }); dhrg::greedy_routing(routing_result, [] (int i, int j) { return sagdist[sagid[i]][sagid[j]]; }); print(hlog, "CSV;", logid++, ";", isize(sagnode), ";", DN, ";", isize(sagedges), ";", lgsag.R, ";", lgsag.T, ";", cost, ";", mAP, ";", routing_result.suc / routing_result.tot, ";", routing_result.routedist / routing_result.bestdist); if(report_tempi) print(hlog, ";", hightemp,";",lowtemp,";",format("%lld", numiter)); println(hlog); } int readArgs() { #if CAP_COMMANDLINE using namespace arg; if(0) ; else if(argis("-sagmin")) { shift_arg_formula(default_edgetype.visible_from); default_edgetype.visible_from_hi = default_edgetype.visible_from; default_edgetype.visible_from_help = default_edgetype.visible_from; } else if(argis("-sagminhi")) { shift_arg_formula(default_edgetype.visible_from_hi); } else if(argis("-sag_gdist")) { shift(); sag::gdist_prec = argi(); } else if(argis("-sag_gdist_dijkstra")) { shift(); sag::dijkstra_maxedge = argi(); } else if(argis("-sag_gdist_save")) { shift(); fhstream f(args(), "wt"); f.write(sagdist); } else if(argis("-sag_gdist_load")) { shift(); distance_file = args(); } else if(argis("-sagrt")) { shift(); sag::lgsag.R = argf(); shift(); sag::lgsag.T = argf(); if(method == smLogistic) compute_loglik_tab(); } else if(argis("-sagmatch-ab")) { shift(); sag::match_a = argf(); shift(); sag::match_b = argf(); if(method == smMatch) prepare_graph(); } else if(argis("-sagrt-auto")) { compute_auto_rt(); } else if(argis("-sag_use_loglik")) { shift(); int mtd = argi(); if(mtd == 0) method = smClosest, loglik_repeat = false; if(mtd == 1) method = smLogistic, loglik_repeat = false; if(mtd == 2) method = smLogistic, loglik_repeat = true; if(mtd == 3) method = smMatch, loglik_repeat = false; if(mtd == 4) method = smMatch, loglik_repeat = true; if(method == smLogistic) compute_loglik_tab(); if(method == smMatch) prepare_graph(); } else if(argis("-sagminhelp")) { shift_arg_formula(default_edgetype.visible_from_help); } else if(argis("-sagformat")) { shift(); informat = argi(); } // (1) configure edge weights else if(argis("-sag-edgepower")) { shift_arg_formula(sag::edgepower); shift_arg_formula(sag::edgemul); } // (1) configure temperature (high, low) else if(argis("-sagtemp")) { shift(); sag::hightemp = argi(); shift(); sag::lowtemp = argi(); } // (2) read the edge data else if(argis("-sagpar")) { PHASE(3); shift(); sag::sagpar = argi(); } else if(argis("-sag")) { PHASE(3); shift(); sag::read(args()); } else if(argis("-sagfake")) { PHASE(3); shift(); int n = argi(); shift(); int m = argi(); sag::generate_fake_data(n, m); } else if(argis("-sagaviz")) { PHASE(3); shift(); sag::auto_visualize = argi(); } else if(argis("-saghubs")) { println(hlog, "HUBS"); PHASE(3); shift_arg_formula(sag::hub_penalty); shift(); hub_filename = args(); } // (3) load the initial positioning else if(argis("-sagload")) { PHASE(3); shift(); sag::load_sag_solution(args()); } // (4) perform simulated annealing: -fullsa