def as_r_vector(o, val_type): if isinstance(o, dict): keys = o.keys() vals = [o[k] for k in keys] robj = as_r_vector(vals, val_type=val_type) robj.setnames(keys) else: if val_type == int: robj = robjects.IntVector(o) elif val_type == float: robj = robjects.FloatVector(o) elif val_type == bool: robj = robjects.BoolVector(o) else: robj = robjects.RVector(o) return robj
def create_vector(v_list, desired_type=None): is_bool = True is_int = True is_float = True is_str = True for elt in v_list: if type(elt) == str: is_bool = False is_int = False is_float = False elif type(elt) == float: is_bool = False is_int = False elif type(elt) == int: is_bool = False else: is_bool = False is_int = False is_float = False is_str = False break if is_bool and (desired_type is None or desired_type == bool): return robjects.BoolVector(v_list) elif is_int and (desired_type is None or desired_type == int): res = [int(elt) for elt in v_list] return robjects.IntVector(res) elif is_float and (desired_type is None or desired_type == float): res = [float(elt) for elt in v_list] return robjects.FloatVector(res) elif is_str and (desired_type is None or desired_type == str): res = [str(elt) for elt in v_list] return robjects.StrVector(res) if desired_type is not None: raise TypeException("Cannot coerce vector to type '%s'" % desired_type) return robjects.RVector(v_list)
res = [float(elt) for elt in v_list] return robjects.FloatVector(res) elif is_str and (desired_type is None or desired_type == str): res = [str(elt) for elt in v_list] return robjects.StrVector(res) if desired_type is not None: raise TypeException("Cannot coerce vector to type '%s'" % desired_type) return robjects.RVector(v_list) def vector_conv(v, desired_type=None): v_list = eval(v) return create_vector(v_list, desired_type) RVector = new_constant('RVector', staticmethod(vector_conv), robjects.RVector([]), staticmethod(lambda x: isinstance(x, robjects.RVector))) def bool_vector_conv(v): return vector_conv(v, bool) RBoolVector = new_constant('RBoolVector' , staticmethod(bool_vector_conv), robjects.BoolVector([]), staticmethod(lambda x: isinstance(x, robjects.RVector)), base_class=RVector) def int_vector_conv(v): return vector_conv(v, int) RIntVector = new_constant('RIntVector' , staticmethod(int_vector_conv), robjects.IntVector([]),
def smooth_ratios(support=supports): tuple_lists = [] ratio_dicts = [] for s in support: print "*"*50 + s tuples = prof_tuples(prof_maxes[s]) weights, r_bar = raw_ratios(s) if 0: #len(prof_maxes[s]) > 1: wdict = dict(zip(tuples, weights)) rdict = dict(zip(tuples, r_bar)) obs = [tuples[i] for i in range(len(tuples)) if r_bar[i] > 0] print obs pre_R = flatten(obs) #obs = [tuples[i] for i in range(len(tuples)) if r_bar[i] > 0] #print "rdict: " + str(rdict[(5,5,4,2)]) pre_R_vec = ro.RVector(pre_R) ro.r['assign']("obs", pre_R_vec) obs_mat = ro.r("obs_mat <- matrix(as.numeric(obs), nc=%d, byrow=T)"%len(prof_maxes[s])) ro.r("library(geometry)") hull_idx = [int(k) for k in ro.r("print(unique(as.vector(convhulln(obs_mat, \"QJ\"))))")] hull = [obs[i-1] for i in hull_idx] print hull constr = [[1,]+list(i) for i in hull] print constr constr_mat = co.matrix(constr, tc='d') print constr_mat #in_hull = filter(lambda t: in_cvx_hull(t, constr_mat), tuples) #out_hull = list(set(tuples).difference(in_hull)) #print "Difference: " + str(len(in_hull)-len(tuples)) #in_hull = obs in_hull=tuples in_weights = [wdict[t] for t in in_hull] in_rbar = [rdict[t] for t in in_hull] print set(tuples).difference(in_hull) #print in_cvx_hull((5,5,4,2), obs_mat) else: in_weights = weights in_rbar = r_bar in_hull = tuples init = co.matrix(in_rbar, tc='d') w = co.matrix(in_weights, tc='d') P = co.spmatrix(w, range(len(in_weights)), range(len(in_weights)), tc='d') q = co.matrix(-P * init, tc='d') #objfun = objective_factory(len(in_hull), init, w, P, q) #print objfun.args #if s == "loc":#"dist": r = r_bar t = in_hull #print q G = G_mat(in_hull) f = open("G_file.p", 'w') pickle.dump(G, f) f.close() #print G h = co.matrix((0,)*G.size[0], tc='d') sol = co.solvers.coneqp(P, q, G, h, dims={'l':G.size[0],'q':[],'s':[]}) #sol = co.solvers.cp(objfun, G, h) res = dict(zip(in_hull, sol['x'])) #print [(k,v) for k,v in rdict.iteritems() if v == max(rdict.values())] #print [(k,v) for k,v in res.iteritems() if v == max(res.values())] #print [(k,res[k],rdict[k]) for k in [in_hull[x] for x in investigate(0, G)]] #print [(k,res[k],rdict[k]) for k in [in_hull[x] for x in investigate(1, G)]] #print [(k,res[k],rdict[k]) for k in [in_hull[x] for x in investigate(11, G)]] #print [(k,res[k],rdict[k]) for k in [in_hull[x] for x in investigate(19, G)]] #print [(k,res[k],rdict[k]) for k in [in_hull[x] for x in investigate(66, G)]] #print [(k,res[k],rdict[k]) for k in [in_hull[x] for x in investigate(143, G)]] tuple_lists.append(tuples) ratio_dicts.append(dict(zip(in_hull, list(sol['x'])))) # print w # print r # r2 = [2929666.7390237185, 0.70787580866602073, 0.1314312027126355, 0.015006581860636961, 0.005, 0.0045703943247474149] #print rg # print ratio_dicts[0] #d = [(tup, r[i], ratio_dicts[0][tup]) for i,tup in enumerate(t) if tup[1]>=6] # f = open("ratioChange.txt",'w') # f.write('\n'.join(["%s: %g -> %g"%(str(l[0]), l[1], l[2]) for l in d])) # f.close() full_tuples = [x for x in product(*tuple_lists)] return dict([(flatten(t), reduce(operator.mul, [ratio_dicts[i][t[i]] for i in range(len(support))], 1)) for t in full_tuples])