repo
stringlengths
3
91
file
stringlengths
16
152
code
stringlengths
0
3.77M
file_length
int64
0
3.77M
avg_line_length
float64
0
16k
max_line_length
int64
0
273k
extension_type
stringclasses
1 value
RGB-N
RGB-N-master/lib/compact_bilinear_pooling/compact_bilinear_pooling_test.py
from __future__ import absolute_import, division, print_function import numpy as np import tensorflow as tf from compact_bilinear_pooling import compact_bilinear_pooling_layer def bp(bottom1, bottom2, sum_pool=True): assert(np.all(bottom1.shape[:3] == bottom2.shape[:3])) batch_size, height, width = bottom1.shape[:3] output_dim = bottom1.shape[-1] * bottom2.shape[-1] bottom1_flat = bottom1.reshape((-1, bottom1.shape[-1])) bottom2_flat = bottom2.reshape((-1, bottom2.shape[-1])) output = np.empty((batch_size*height*width, output_dim), np.float32) for n in range(len(output)): output[n, ...] = np.outer(bottom1_flat[n], bottom2_flat[n]).reshape(-1) output = output.reshape((batch_size, height, width, output_dim)) if sum_pool: output = np.sum(output, axis=(1, 2)) return output # Input and output tensors # Input channels need to be specified for shape inference input_dim1 = 2048 input_dim2 = 2048 output_dim = 16000 bottom1 = tf.placeholder(tf.float32, [None, None, None, input_dim1]) bottom2 = tf.placeholder(tf.float32, [None, None, None, input_dim2]) top = compact_bilinear_pooling_layer(bottom1, bottom2, output_dim, sum_pool=True) grad = tf.gradients(top, [bottom1, bottom2]) def cbp(bottom1_value, bottom2_value): sess = tf.get_default_session() return sess.run(top, feed_dict={bottom1: bottom1_value, bottom2: bottom2_value}) def cbp_with_grad(bottom1_value, bottom2_value): sess = tf.get_default_session() return sess.run([top]+grad, feed_dict={bottom1: bottom1_value, bottom2: bottom2_value}) def test_kernel_approximation(batch_size, height, width): print("Testing kernel approximation...") # Input values x = np.random.rand(batch_size, height, width, input_dim1).astype(np.float32) y = np.random.rand(batch_size, height, width, input_dim2).astype(np.float32) z = np.random.rand(batch_size, height, width, input_dim1).astype(np.float32) w = np.random.rand(batch_size, height, width, input_dim2).astype(np.float32) # Compact Bilinear Pooling results cbp_xy = cbp(x, y) cbp_zw = cbp(z, w) # (Original) Bilinear Pooling results bp_xy = bp(x, y) bp_zw = bp(z, w) # Check the kernel results of Compact Bilinear Pooling # against Bilinear Pooling cbp_kernel = np.sum(cbp_xy*cbp_zw, axis=1) bp_kernel = np.sum(bp_xy*bp_zw, axis=1) ratio = cbp_kernel / bp_kernel print("ratio between Compact Bilinear Pooling (CBP) and Bilinear Pooling (BP):") print(ratio) assert(np.all(np.abs(ratio - 1) < 2e-2)) print("Passed.") def test_large_input(batch_size, height, width): print("Testing large input...") # Input values x = np.random.rand(batch_size, height, width, input_dim1).astype(np.float32) y = np.random.rand(batch_size, height, width, input_dim2).astype(np.float32) # Compact Bilinear Pooling results _ = cbp_with_grad(x, y) # Test passes iff no exception occurs. print("Passed.") def main(): sess = tf.InteractiveSession() test_kernel_approximation(batch_size=2, height=3, width=4) test_large_input(batch_size=64, height=14, width=14) sess.close() if __name__ == '__main__': main()
3,295
34.44086
84
py
RGB-N
RGB-N-master/lib/compact_bilinear_pooling/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # --------------------------------------------------------
248
34.571429
58
py
RGB-N
RGB-N-master/lib/compact_bilinear_pooling/sequential_fft/sequential_batch_fft_test.py
from __future__ import absolute_import, division, print_function import tensorflow as tf import numpy as np from sequential_batch_fft_ops import sequential_batch_fft, sequential_batch_ifft compute_size = 128 x = tf.placeholder(tf.complex64, [None, None]) x_128 = tf.placeholder(tf.complex128, [None, None]) # FFT x_fft = sequential_batch_fft(x, compute_size) x_fft_128 = sequential_batch_fft(x_128, compute_size) x_fft_tf = tf.fft(x) # IFFT x_ifft = sequential_batch_ifft(x, compute_size) x_ifft_128 = sequential_batch_ifft(x_128, compute_size) x_ifft_tf = tf.ifft(x) # Grads gx_fft = tf.gradients(x_fft, x)[0] gx_fft_128 = tf.gradients(x_fft_128, x_128)[0] gx_fft_tf = tf.gradients(x_fft_tf, x)[0] gx_ifft = tf.gradients(x_ifft, x)[0] gx_ifft_128 = tf.gradients(x_ifft_128, x_128)[0] gx_ifft_tf = tf.gradients(x_ifft_tf, x)[0] def test_shape(): print("Testing shape...") # Test Shape inference. Output shape should be # the same as input shape input_pl = tf.placeholder(tf.complex64, [1000, 16000]) output_fft = sequential_batch_fft(input_pl) output_ifft = sequential_batch_ifft(input_pl) g_fft = tf.gradients(output_fft, input_pl)[0] g_ifft = tf.gradients(output_ifft, input_pl)[0] assert(output_fft.get_shape() == input_pl.get_shape()) assert(output_ifft.get_shape() == input_pl.get_shape()) assert(g_fft.get_shape() == input_pl.get_shape()) assert(g_ifft.get_shape() == input_pl.get_shape()) print("Passed.") def test_forward(): # Test forward and compare with tf.batch_fft and tf.batch_ifft print("Testing forward...") sess = tf.Session() for dim in range(1000, 5000, 1000): for batch_size in range(1, 10): x_val = (np.random.randn(batch_size, dim) + np.random.randn(batch_size, dim) * 1j).astype(np.complex64) # Forward complex64 x_fft_val, x_ifft_tf_val = sess.run([x_fft, x_ifft], {x: x_val}) # Forward complex128 x_fft_128_val, x_ifft_128_val = sess.run([x_fft_128, x_ifft_128], {x_128: x_val.astype(np.complex128)}) # Forward with reference tf.batch_fft and tf.batch_ifft x_fft_tf_val, x_ifft_val = sess.run([x_fft_tf, x_ifft_tf], {x: x_val}) ref_sum_fft = np.sum(np.abs(x_fft_tf_val)) ref_sum_ifft = np.sum(np.abs(x_ifft_tf_val)) relative_diff_fft = np.sum(np.abs(x_fft_val - x_fft_tf_val)) / ref_sum_fft relative_diff_ifft = np.sum(np.abs(x_ifft_val - x_ifft_tf_val)) / ref_sum_ifft relative_diff_fft128 = np.sum(np.abs(x_fft_128_val - x_fft_tf_val)) / ref_sum_fft relative_diff_ifft128 = np.sum(np.abs(x_ifft_128_val - x_ifft_tf_val)) / ref_sum_ifft assert(relative_diff_fft < 1e-5) assert(relative_diff_fft128 < 1e-5) assert(relative_diff_ifft < 1e-5) assert(relative_diff_ifft128 < 1e-5) sess.close() print("Passed.") def test_gradient(): # Test Backward and compare with tf.batch_fft and tf.batch_ifft print("Testing gradient...") sess = tf.Session() for dim in range(1000, 5000, 1000): for batch_size in range(1, 10): x_val = (np.random.randn(batch_size, dim) + np.random.randn(batch_size, dim) * 1j).astype(np.complex64) # Backward complex64 gx_fft_val, gx_ifft_tf_val = sess.run([gx_fft, gx_ifft], {x: x_val}) # Backward complex128 gx_fft_128_val, gx_ifft_128_val = sess.run([gx_fft_128, gx_ifft_128], {x_128: x_val.astype(np.complex128)}) # Backward with reference tf.batch_fft and tf.batch_ifft gx_fft_tf_val, gx_ifft_val = sess.run([gx_fft_tf, gx_ifft_tf], {x: x_val}) ref_sum_fft = np.sum(np.abs(gx_fft_tf_val)) ref_sum_ifft = np.sum(np.abs(gx_ifft_tf_val)) relative_diff_fft = np.sum(np.abs(gx_fft_val - gx_fft_tf_val)) / ref_sum_fft relative_diff_ifft = np.sum(np.abs(gx_ifft_val - gx_ifft_tf_val)) / ref_sum_ifft relative_diff_fft128 = np.sum(np.abs(gx_fft_128_val - gx_fft_tf_val)) / ref_sum_fft relative_diff_ifft128 = np.sum(np.abs(gx_ifft_128_val - gx_ifft_tf_val)) / ref_sum_ifft assert(relative_diff_fft < 1e-5) assert(relative_diff_fft128 < 1e-5) assert(relative_diff_ifft < 1e-5) assert(relative_diff_ifft128 < 1e-5) sess.close() print("Passed.") def test_large_input(): # Very large input size, where tf.batch_fft and tf.batch_ifft # will run OOM print("Testing large input...") sess = tf.Session() batch_size, dim = 64*16*16, 16000 print("Forwarding and Backwarding with input shape", [batch_size, dim], "This may take a while...") x_val = (np.random.randn(batch_size, dim) + np.random.randn(batch_size, dim) * 1j).astype(np.complex64) sess.run(tf.group(x_fft, x_ifft, gx_fft, gx_ifft), {x: x_val}) sess.close() # Test passes iff no exception occurs. print("Passed.") if __name__ == "__main__": test_shape() test_forward() test_gradient() test_large_input()
5,280
38.706767
99
py
RGB-N
RGB-N-master/lib/compact_bilinear_pooling/sequential_fft/sequential_batch_fft_ops.py
from __future__ import absolute_import, division, print_function import os.path as osp import tensorflow as tf from tensorflow.python.framework import ops # load module module = tf.load_op_library(osp.join(osp.dirname(__file__), 'build/sequential_batch_fft.so')) sequential_batch_fft = module.sequential_batch_fft sequential_batch_ifft = module.sequential_batch_ifft # Shape registration is moved to C++ to be compatible with TensorFlow 1.0 API # @tf.RegisterShape("SequentialBatchFFT") # def _SequentialBatchFFTShape(op): # return [op.inputs[0].get_shape()] # # @tf.RegisterShape("SequentialBatchIFFT") # def _SequentialBatchIFFTShape(op): # return [op.inputs[0].get_shape()] @ops.RegisterGradient("SequentialBatchFFT") def _SequentialBatchFFTGrad(op, grad): if (grad.dtype == tf.complex64): size = tf.cast(tf.shape(grad)[1], tf.float32) return (sequential_batch_ifft(grad, op.get_attr("compute_size")) * tf.complex(size, 0.)) else: size = tf.cast(tf.shape(grad)[1], tf.float64) return (sequential_batch_ifft(grad, op.get_attr("compute_size")) * tf.complex(size, tf.zeros([], tf.float64))) @ops.RegisterGradient("SequentialBatchIFFT") def _SequentialBatchIFFTGrad(op, grad): if (grad.dtype == tf.complex64): rsize = 1. / tf.cast(tf.shape(grad)[1], tf.float32) return (sequential_batch_fft(grad, op.get_attr("compute_size")) * tf.complex(rsize, 0.)) else: rsize = 1. / tf.cast(tf.shape(grad)[1], tf.float64) return (sequential_batch_fft(grad, op.get_attr("compute_size")) * tf.complex(rsize, tf.zeros([], tf.float64)))
1,700
36.8
77
py
RGB-N
RGB-N-master/lib/compact_bilinear_pooling/sequential_fft/__init__.py
from .sequential_batch_fft_ops import sequential_batch_fft, sequential_batch_ifft
82
40.5
81
py
RGB-N
RGB-N-master/lib/datasets/voc_eval.py
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import xml.etree.ElementTree as ET import os import pickle import numpy as np import pdb def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.find('truncated').text) obj_struct['difficult'] = int(obj.find('difficult').text) bbox = obj.find('bndbox') obj_struct['bbox'] = [int(bbox.find('xmin').text), int(bbox.find('ymin').text), int(bbox.find('xmax').text), int(bbox.find('ymax').text)] objects.append(obj_struct) return objects def voc_ap(rec, prec, use_07_metric=False): """ ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11. else: # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def parse_txt(fileline,classname): #classes=('__background__','person_au','person_tp','airplane_tp','airplane_au','dog_tp','dog_au', #'train_tp','train_au','bed_tp','bed_au','refrigerator_tp','refrigerator_au') #classes=('__background__','person_au','person_tp','tv_tp','tv_au','airplane_tp','airplane_au','dog_tp','dog_au', #'bench_tp','bench_au','train_tp','train_au','broccoli_tp','broccoli_au','kite_tp','kite_au','bed_tp','bed_au','refrigerator_tp','refrigerator_au','bowl_tp','bowl_au') classes=('__background__', 'tamper','authentic') classes=('authentic', 'tamper') #classes=('__background__', # always index 0 #'splicing','removal','manipulation') #classes=('__background__','person_au','tv_au','airplane_au','dog_au', #'bench_au','train_au','broccoli_au','kite_au','bed_au','refrigerator_au','bowl_au') class_to_ind = dict(list(zip(classes, list(range(len(classes)))))) num_objs = int(len(fileline.split(' ')[1:])/5) objects=[] obj={} #print(fileline.split()) #pdb.set_trace() #object['name']=fileline.split(" ")[0] for i in range(num_objs): obj['bbox']=[float(fileline.split(' ')[5*i+1]), float(fileline.split(' ')[5*i+2]), float(fileline.split(' ')[5*i+3]), float(fileline.split(' ')[5*i+4])] try: obj['cls']=class_to_ind[fileline.split(' ')[5*i+5]] except: #pdb.set_trace() obj['cls']=int(fileline.split(' ')[5*i+5]) #obj['bbox']=[int(fileline.split(' ')[(classname-1)*5+1]), #int(fileline.split(' ')[(classname-1)*5+2]), #int(fileline.split(' ')[(classname-1)*5+3]), #int(fileline.split(' ')[(classname-1)*5+4])] #obj['cls']=int(fileline.split(' ')[(classname-1)*5+5]) objects.append(obj.copy()) return objects def voc_eval(detpath, detpath2, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=False, fuse=False): """rec, prec, ap = voc_eval(detpath, annopath, imagesetfile, classname, [ovthresh], [use_07_metric]) Top level function that does the PASCAL VOC evaluation. detpath: Path to detections detpath.format(classname) should produce the detection results file. annopath: Path to annotations annopath.format(imagename) should be the xml annotations file. imagesetfile: Text file containing the list of images, one image per line. classname: Category name (duh) cachedir: Directory for caching the annotations [ovthresh]: Overlap threshold (default = 0.5) [use_07_metric]: Whether to use VOC07's 11 point AP computation (default False) """ # assumes detections are in detpath.format(classname) # assumes annotations are in annopath.format(imagename) # assumes imagesetfile is a text file with each line an image name # cachedir caches the annotations in a pickle file # first load gt if not os.path.isdir(cachedir): os.mkdir(cachedir) cachefile = os.path.join(cachedir, 'annots.pkl') # read list of images with open(imagesetfile, 'r') as f: lines = f.readlines() imagenames = [x.strip() for x in lines] if not os.path.isfile(cachefile): # load annots recs = {} for i, imagename in enumerate(imagenames): name=imagename.split(' ')[0] recs[name] = parse_txt(imagename,classname) #recs[imagename] = parse_rec(annopath.format(imagename)) if i % 100 == 0: print('Reading annotation for {:d}/{:d}'.format( i + 1, len(imagenames))) # save print('Saving cached annotations to {:s}'.format(cachefile)) #with open(cachefile, 'w') as f: #pickle.dump(recs, f) else: # load with open(cachefile, 'rb') as f: try: recs = pickle.load(f) except: recs = pickle.load(f, encoding='bytes') # extract gt objects for this class class_recs = {} npos = 0 #pdb.set_trace() for imagename in imagenames: name=imagename.split(' ')[0] R = [obj for obj in recs[name] if obj['cls'] == classname] npos=npos+len(R) bbox = np.array([x['bbox'] for x in R]) #difficult = np.array([x['difficult'] for x in R]).astype(np.bool) det = [False] * len(R) class_recs[name] = {'bbox': bbox, #'difficult': difficult, 'det': det} # read dets detfile = detpath.format(classname) detfile_n = detpath2.format(classname) #print(detfile) with open(detfile, 'r') as f: lines = f.readlines() if os.path.isfile(detfile_n): with open(detfile_n, 'r') as f_n: n_lines = f_n.readlines() n_splitlines = [x.strip().split(' ') for x in n_lines] #print(n_splitlines) image_n = [x[0] for x in n_splitlines] confidence_n = np.array([float(x[1]) for x in n_splitlines]) BB_n = np.array([[float(z) for z in x[2:]] for x in n_splitlines]) splitlines = [x.strip().split(' ') for x in lines] image_ids = [x[0] for x in splitlines] confidence = np.array([float(x[1]) for x in splitlines]) BB = np.array([[float(z) for z in x[2:]] for x in splitlines]) count=np.zeros(10) noise_ct=0 select_final=np.array([True]*len(image_ids)) image_select=[] if BB.shape[0] > 0 and fuse: for k in range(len(image_ids)): if image_ids[k] in image_select: select_final[k]=False continue if image_ids[k] in image_n: bb = BB[k, :].astype(float) index=[i for i,ex in enumerate(image_n) if ex==image_ids[k]] bb1 = BB_n[index, :].astype(float) #print(index,bb1) #pdb.set_trace() c_n=confidence_n[index] ix_min = np.maximum(bb1[:, 0], bb[0]) iy_min = np.maximum(bb1[:, 1], bb[1]) ix_max = np.minimum(bb1[:, 2], bb[2]) iy_max = np.minimum(bb1[:, 3], bb[3]) iw = np.maximum(ix_max - ix_min + 1., 0.) ih = np.maximum(iy_max - iy_min + 1., 0.) inters = iw * ih # union uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + (bb1[:, 2] - bb1[:, 0] + 1.) * (bb1[:, 3] - bb1[:, 1] + 1.) - inters) overlaps = inters / uni ov_max = np.max(overlaps) jmax = np.argmax(overlaps) if ov_max>=0.5: count[int(ov_max*10)]=count[int(ov_max*10)]+1 #print(confidence[k],c_n) #confidence[k]=np.maximum(confidence[k],c_n[jmax]) confidence[k]=(confidence[k]+c_n[jmax])/2 #pdb.set_trace() BB[k,:]=(confidence[k]*BB[k,:]+c_n[jmax]*bb1[jmax,:])/np.maximum(confidence[k]+c_n[jmax], np.finfo(np.float64).eps) image_select.append(image_ids[k]) #if confidence[k]<c_n[jmax]-0.5: #BB[k,:]=bb1[jmax,:] #print(image_ids[k],confidence[k],c_n[jmax]) elif ov_max<0.5 and ov_max>0.1: count[int(ov_max*10)]=count[int(ov_max*10)]+1 image_select.append(image_ids[k]) #select_final[k]=False #BB[k,:]=(confidence[k]*BB[k,:]+c_n[jmax]*bb1[jmax,:])/(confidence[k]+c_n[jmax]) #pass #select_final[k]=False #confidence[k]=0.7*confidence[k]+0.3*c_n[jmax] #if confidence[k]<c_n[jmax]: #BB[k,:]=bb1[jmax,:] #print(image_ids[k],confidence[k],c_n[jmax]) #confidence[k]=confidence[k]*max(ov_max+0.2,0.6) else: count[int(ov_max*10)]=count[int(ov_max*10)]+1 select_final[k]=False #confidence[k]=confidence[k]*0.9 #if confidence[k]<c_n[jmax]: #BB[k,:]=bb1[jmax,:] #confidence[k]=c_n[jmax]*0.9 for nk in range(len(image_n)): if image_n[nk] not in image_ids: noise_ct=noise_ct+1 #image_ids.append(image_n[nk]) #select_final.append(select_final,True) #confidence=np.append(confidence,confidence_n[nk]) #BB=np.vstack((BB,BB_n[nk,:])) print('rgb no overlap: {:s}'.format(count)) print('noise no overlap: {:d}'.format(noise_ct)) image_ids=np.extract(select_final,image_ids) confidence=np.extract(select_final,confidence) BB=BB[select_final,:] nd = len(image_ids) #print(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) bb=[] bb1=[] #pdb.set_trace() if BB.shape[0] > 0: # sort by confidence sorted_ind = np.argsort(-confidence) sorted_scores = np.sort(-confidence) BB = BB[sorted_ind, :] image_ids = [image_ids[x] for x in sorted_ind] #print(class_recs) #print(sorted_ind) # go down dets and mark TPs and FPs for d in range(nd): #print(bb1) R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) if fuse: if image_ids[d] in image_n: index=[i for i,ex in enumerate(image_n) if ex==image_ids[d]] bb1 = BB_n[index, :].astype(float) ix_min = np.maximum(bb1[:, 0], bb[0]) iy_min = np.maximum(bb1[:, 1], bb[1]) ix_max = np.minimum(bb1[:, 2], bb[2]) iy_max = np.minimum(bb1[:, 3], bb[3]) iw_n = np.maximum(ix_max - ix_min + 1., 0.) ih_n = np.maximum(iy_max - iy_min + 1., 0.) inters_n = iw_n * ih_n # union un = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + (bb1[:, 2] - bb1[:, 0] + 1.) * (bb1[:, 3] - bb1[:, 1] + 1.) - inters_n) overlaps_n = inters_n / un ov_max_n = np.max(overlaps_n) ovmax = -np.inf BBGT = R['bbox'].astype(float) #print(BBGT) #pdb.set_trace() if BBGT.size > 0: # compute overlaps # intersection #print(BBGT) #print(bb) ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) ixmax = np.minimum(BBGT[:, 2], bb[2]) iymax = np.minimum(BBGT[:, 3], bb[3]) iw = np.maximum(ixmax - ixmin + 1., 0.) ih = np.maximum(iymax - iymin + 1., 0.) inters = iw * ih # union uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + (BBGT[:, 2] - BBGT[:, 0] + 1.) * (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) print("overlap:") print(overlaps) if ovmax > ovthresh: #print(R['det'][jmax]) #if not R['difficult'][jmax]: if not R['det'][jmax]: #print(R['det'][jmax]) tp[d] = 1. R['det'][jmax] = 1 else: fp[d] = 1. else: print('fp:{:s}'.format(image_ids[d])) if fuse: print('score:{:f}, ovmax:{:f}'.format(-sorted_scores[d],ov_max_n)) fp[d] = 1. # compute precision recall fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / float(npos) # avoid divide by zero in case the first detection matches a difficult # ground truth prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = voc_ap(rec, prec, use_07_metric) return rec, prec, ap
13,267
34.100529
173
py
RGB-N
RGB-N-master/lib/datasets/dist_fake.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import pickle import subprocess import uuid import pdb from .voc_eval import voc_eval from model.config import cfg import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class dist_fake(imdb): def __init__(self, image_set, year, dist_path=None): imdb.__init__(self, image_set) self._year = year self._image_set = image_set.split('dist_')[1] self._dist_path = self._get_default_path() if dist_path is None \ else dist_path self._data_path=self._dist_path self._classes = ('__background__', # always index 0 'tamper','authentic') self._classes = ('authentic', # always index 0 'tamper') #self.classes =('authentic', # always index 0 #'splicing','removal') self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes))))) self._image_ext = {'.png','.jpg','.tif','.bmp','.JPG'} self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(os.path.splitext(self._image_index[i].split(' ')[0])[0]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ for ext in self._image_ext: #image_path = os.path.join('/home-3/[email protected]/work/xintong/medifor/portrait/test_data', #index + ext) image_path = os.path.join(self._data_path, index + ext) image_path1=os.path.join('/home-3/[email protected]/work/pengzhou/dataset/NC2016_Test0613', index + ext) if os.path.isfile(image_path): return image_path elif os.path.isfile(image_path1): return image_path1 else: continue assert os.path.isfile(image_path) and os.path.isfile(image_path1), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join(self._data_path, self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] #print(image_index) return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ return os.path.join(cfg.DATA_DIR, 'NC2016_Test0613') def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: try: roidb = pickle.load(fid) except: roidb = pickle.load(fid, encoding='bytes') print('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self.roidb_gt(index) for index in self.image_index] with open(cache_file, 'wb') as fid: pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL) print('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def roidb_gt(self,image_id): num_objs = int(len(image_id.split(' ')[1:])/5) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix in range(num_objs): bbox = image_id.split(' ')[ix*5+1:ix*5+5] # Make pixel indexes 0-based x1 = float(bbox[0]) y1 = float(bbox[1]) x2 = float(bbox[2]) y2 = float(bbox[3]) if x1<0: x1=0 if y1<0: y1=0 try: cls=self._class_to_ind[image_id.split(' ')[ix*5+5]] except: if int(image_id.split(' ')[ix*5+5])==0: print('authentic') cls=2 else: cls = int(image_id.split(' ')[ix*5+5]) boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 ) * (y2 - y1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'JPGed':False, 'noised':False, 'seg_areas': seg_areas} def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print('loading {}'.format(filename)) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = pickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'nist_' + self._image_set + '_{:s}.txt' path = os.path.join( '.', filename) return path def _get_voc_noise_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'nist_' + self._image_set + '_{:s}_noise.txt' path = os.path.join( '.', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print('Writing {} VOC results file'.format(cls)) filename = self._get_voc_results_file_template().format(cls) print(filename) with open(filename, 'w') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): #pdb.set_trace() f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.format(index.split(' ')[0], dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) #pdb.set_trace() def _do_python_eval(self, output_dir='output'): annopath = os.path.join( self._dist_path, 'coco_multi' , 'Annotations', '{:s}.xml') imagesetfile = os.path.join( self._dist_path, self._image_set + '.txt') cachedir = os.path.join(self._dist_path, 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 #use_07_metric = True if int(self._year) < 2010 else False use_07_metric = False print('dist metric? ' + ('Yes' if use_07_metric else 'No')) if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__' or cls == self.classes[0]: cls_ind=0 continue else: cls_ind=self._class_to_ind[cls] #elif cls=='median_filtering': #cls_ind=3 #continue filename = self._get_voc_results_file_template().format(cls) filename2 = self._get_voc_noise_results_file_template().format(cls) print(cls_ind) rec, prec, ap = voc_eval( filename,filename2, annopath, imagesetfile, cls_ind, cachedir, ovthresh=0.5, use_07_metric=use_07_metric,fuse=False) aps += [ap] print(('AP for {} = {:.4f},recall = {:.4f}, precision = {:.4f}'.format(cls, ap,rec[-1],prec[-1]))) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f: pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) fig=plt.figure() plt.plot(rec,prec) fig.suptitle('PR curve for {} detection'.format(cls),fontsize=20) plt.xlabel('recall',fontsize=15) plt.xlim((0,1.0)) plt.ylim((0,1.0)) plt.ylabel('precision',fontsize=15) fig.savefig('{}.jpg'.format(cls)) print(('Mean AP = {:.4f}'.format(np.mean(aps)))) print('~~~~~~~~') print('Results:') for ap in aps: print(('{:.3f}'.format(ap))) print(('{:.3f}'.format(np.mean(aps)))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print('-----------------------------------------------------') print('Computing results with the official MATLAB eval code.') print('-----------------------------------------------------') path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._devkit_path, self._get_comp_id(), self._image_set, output_dir) print(('Running:\n{}'.format(cmd))) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) #if self.config['matlab_eval']: #self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) #os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.dist_fake import dist_fake d = dist_fake('trainval', '2007') res = d.roidb from IPython import embed; embed()
13,392
34.619681
104
py
RGB-N
RGB-N-master/lib/datasets/pascal_voc.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import xml.etree.ElementTree as ET import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import pickle import subprocess import uuid from .voc_eval import voc_eval from model.config import cfg class pascal_voc(imdb): def __init__(self, image_set, year, devkit_path=None): imdb.__init__(self, 'voc_' + year + '_' + image_set) self._year = year self._image_set = image_set self._devkit_path = self._get_default_path() if devkit_path is None \ else devkit_path self._data_path = os.path.join(self._devkit_path, 'VOC' + self._year) self._classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor') self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes))))) self._image_ext = '.jpg' self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb self._salt = str(uuid.uuid4()) self._comp_id = 'comp4' # PASCAL specific config options self.config = {'cleanup': True, 'use_salt': True, 'use_diff': False, 'matlab_eval': False, 'rpn_file': None} assert os.path.exists(self._devkit_path), \ 'VOCdevkit path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_index[i]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ image_path = os.path.join(self._data_path, 'JPEGImages', index + self._image_ext) assert os.path.exists(image_path), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join(self._data_path, 'ImageSets', 'Main', self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ return os.path.join(cfg.DATA_DIR, 'VOCdevkit' + self._year) def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: try: roidb = pickle.load(fid) except: roidb = pickle.load(fid, encoding='bytes') print('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self._load_pascal_annotation(index) for index in self.image_index] with open(cache_file, 'wb') as fid: pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL) print('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print('loading {}'.format(filename)) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = pickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = self._get_comp_id() + '_det_' + self._image_set + '_{:s}.txt' path = os.path.join( self._devkit_path, 'results', 'VOC' + self._year, 'Main', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print('Writing {} VOC results file'.format(cls)) filename = self._get_voc_results_file_template().format(cls) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index, dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) def _do_python_eval(self, output_dir='output'): annopath = os.path.join( self._devkit_path, 'VOC' + self._year, 'Annotations', '{:s}.xml') imagesetfile = os.path.join( self._devkit_path, 'VOC' + self._year, 'ImageSets', 'Main', self._image_set + '.txt') cachedir = os.path.join(self._devkit_path, 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 use_07_metric = True if int(self._year) < 2010 else False print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No')) if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) rec, prec, ap = voc_eval( filename, annopath, imagesetfile, cls, cachedir, ovthresh=0.5, use_07_metric=use_07_metric) aps += [ap] print(('AP for {} = {:.4f}'.format(cls, ap))) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f: pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) print(('Mean AP = {:.4f}'.format(np.mean(aps)))) print('~~~~~~~~') print('Results:') for ap in aps: print(('{:.3f}'.format(ap))) print(('{:.3f}'.format(np.mean(aps)))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print('-----------------------------------------------------') print('Computing results with the official MATLAB eval code.') print('-----------------------------------------------------') path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._devkit_path, self._get_comp_id(), self._image_set, output_dir) print(('Running:\n{}'.format(cmd))) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) if self.config['matlab_eval']: self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.pascal_voc import pascal_voc d = pascal_voc('trainval', '2007') res = d.roidb from IPython import embed; embed()
11,180
35.301948
85
py
RGB-N
RGB-N-master/lib/datasets/imdb.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import os.path as osp import PIL from utils.cython_bbox import bbox_overlaps import numpy as np import scipy.sparse from model.config import cfg class imdb(object): """Image database.""" def __init__(self, name, classes=None): self._name = name self._num_classes = 0 if not classes: self._classes = [] else: self._classes = classes self._image_index = [] self._obj_proposer = 'gt' self._roidb = None self._roidb_handler = self.default_roidb # Use this dict for storing dataset specific config options self.config = {} @property def name(self): return self._name @property def num_classes(self): return len(self._classes) @property def classes(self): return self._classes @property def image_index(self): return self._image_index @property def roidb_handler(self): return self._roidb_handler @roidb_handler.setter def roidb_handler(self, val): self._roidb_handler = val def set_proposal_method(self, method): method = eval('self.' + method + '_roidb') self.roidb_handler = method @property def roidb(self): # A roidb is a list of dictionaries, each with the following keys: # boxes # gt_overlaps # gt_classes # flipped if self._roidb is not None: return self._roidb self._roidb = self.roidb_handler() return self._roidb @property def cache_path(self): cache_path = osp.abspath(osp.join(cfg.DATA_DIR, 'cache')) if not os.path.exists(cache_path): os.makedirs(cache_path) return cache_path @property def num_images(self): return len(self.image_index) def image_path_at(self, i): raise NotImplementedError def default_roidb(self): raise NotImplementedError def evaluate_detections(self, all_boxes, output_dir=None): """ all_boxes is a list of length number-of-classes. Each list element is a list of length number-of-images. Each of those list elements is either an empty list [] or a numpy array of detection. all_boxes[class][image] = [] or np.array of shape #dets x 5 """ raise NotImplementedError def _get_widths(self): return [PIL.Image.open(self.image_path_at(i)).size[0] for i in range(self.num_images)] def append_flipped_images(self): num_images = self.num_images widths = self._get_widths() for i in range(num_images): boxes = self.roidb[i]['boxes'].copy() oldx1 = boxes[:, 0].copy() oldx2 = boxes[:, 2].copy() #print(oldx2,oldx1,widths[i]) if oldx2>=widths[i]: oldx2=widths[i]-1 boxes[:, 0] = widths[i] - oldx2 - 1 boxes[:, 2] = widths[i] - oldx1 - 1 #print(boxes) assert (boxes[:, 2] >= boxes[:, 0]).all() entry = {'boxes': boxes, 'gt_overlaps': self.roidb[i]['gt_overlaps'], 'gt_classes': self.roidb[i]['gt_classes'], 'flipped': True, 'JPGed':False, 'noised':False} self.roidb.append(entry) self._image_index = self._image_index * 2 def append_noise_images(self): num_images = self.num_images widths = self._get_widths() for i in range(num_images): boxes = self.roidb[i]['boxes'].copy() flipped= self.roidb[i]['flipped'] jpg= self.roidb[i]['JPGed'] entry = {'boxes': boxes, 'gt_overlaps': self.roidb[i]['gt_overlaps'], 'gt_classes': self.roidb[i]['gt_classes'], 'flipped':flipped, 'JPGed':jpg, 'noised': True} self.roidb.append(entry) self._image_index = self._image_index * 2 def append_jpg_images(self): num_images = self.num_images widths = self._get_widths() for i in range(num_images): boxes = self.roidb[i]['boxes'].copy() flipped= self.roidb[i]['flipped'] noised= self.roidb[i]['noised'] entry = {'boxes': boxes, 'gt_overlaps': self.roidb[i]['gt_overlaps'], 'gt_classes': self.roidb[i]['gt_classes'], 'flipped':flipped, 'JPGed':True, 'noised':noised} self.roidb.append(entry) self._image_index = self._image_index * 2 def evaluate_recall(self, candidate_boxes=None, thresholds=None, area='all', limit=None): """Evaluate detection proposal recall metrics. Returns: results: dictionary of results with keys 'ar': average recall 'recalls': vector recalls at each IoU overlap threshold 'thresholds': vector of IoU overlap thresholds 'gt_overlaps': vector of all ground-truth overlaps """ # Record max overlap value for each gt box # Return vector of overlap values areas = {'all': 0, 'small': 1, 'medium': 2, 'large': 3, '96-128': 4, '128-256': 5, '256-512': 6, '512-inf': 7} area_ranges = [[0 ** 2, 1e5 ** 2], # all [0 ** 2, 32 ** 2], # small [32 ** 2, 96 ** 2], # medium [96 ** 2, 1e5 ** 2], # large [96 ** 2, 128 ** 2], # 96-128 [128 ** 2, 256 ** 2], # 128-256 [256 ** 2, 512 ** 2], # 256-512 [512 ** 2, 1e5 ** 2], # 512-inf ] assert area in areas, 'unknown area range: {}'.format(area) area_range = area_ranges[areas[area]] gt_overlaps = np.zeros(0) num_pos = 0 for i in range(self.num_images): # Checking for max_overlaps == 1 avoids including crowd annotations # (...pretty hacking :/) max_gt_overlaps = self.roidb[i]['gt_overlaps'].toarray().max(axis=1) gt_inds = np.where((self.roidb[i]['gt_classes'] > 0) & (max_gt_overlaps == 1))[0] gt_boxes = self.roidb[i]['boxes'][gt_inds, :] gt_areas = self.roidb[i]['seg_areas'][gt_inds] valid_gt_inds = np.where((gt_areas >= area_range[0]) & (gt_areas <= area_range[1]))[0] gt_boxes = gt_boxes[valid_gt_inds, :] num_pos += len(valid_gt_inds) if candidate_boxes is None: # If candidate_boxes is not supplied, the default is to use the # non-ground-truth boxes from this roidb non_gt_inds = np.where(self.roidb[i]['gt_classes'] == 0)[0] boxes = self.roidb[i]['boxes'][non_gt_inds, :] else: boxes = candidate_boxes[i] if boxes.shape[0] == 0: continue if limit is not None and boxes.shape[0] > limit: boxes = boxes[:limit, :] overlaps = bbox_overlaps(boxes.astype(np.float), gt_boxes.astype(np.float)) _gt_overlaps = np.zeros((gt_boxes.shape[0])) for j in range(gt_boxes.shape[0]): # find which proposal box maximally covers each gt box argmax_overlaps = overlaps.argmax(axis=0) # and get the iou amount of coverage for each gt box max_overlaps = overlaps.max(axis=0) # find which gt box is 'best' covered (i.e. 'best' = most iou) gt_ind = max_overlaps.argmax() gt_ovr = max_overlaps.max() assert (gt_ovr >= 0) # find the proposal box that covers the best covered gt box box_ind = argmax_overlaps[gt_ind] # record the iou coverage of this gt box _gt_overlaps[j] = overlaps[box_ind, gt_ind] assert (_gt_overlaps[j] == gt_ovr) # mark the proposal box and the gt box as used overlaps[box_ind, :] = -1 overlaps[:, gt_ind] = -1 # append recorded iou coverage level gt_overlaps = np.hstack((gt_overlaps, _gt_overlaps)) gt_overlaps = np.sort(gt_overlaps) if thresholds is None: step = 0.05 thresholds = np.arange(0.5, 0.95 + 1e-5, step) recalls = np.zeros_like(thresholds) # compute recall for each iou threshold for i, t in enumerate(thresholds): recalls[i] = (gt_overlaps >= t).sum() / float(num_pos) # ar = 2 * np.trapz(recalls, thresholds) ar = recalls.mean() return {'ar': ar, 'recalls': recalls, 'thresholds': thresholds, 'gt_overlaps': gt_overlaps} def create_roidb_from_box_list(self, box_list, gt_roidb): assert len(box_list) == self.num_images, \ 'Number of boxes must match number of ground-truth images' roidb = [] for i in range(self.num_images): boxes = box_list[i] num_boxes = boxes.shape[0] overlaps = np.zeros((num_boxes, self.num_classes), dtype=np.float32) if gt_roidb is not None and gt_roidb[i]['boxes'].size > 0: gt_boxes = gt_roidb[i]['boxes'] gt_classes = gt_roidb[i]['gt_classes'] gt_overlaps = bbox_overlaps(boxes.astype(np.float), gt_boxes.astype(np.float)) argmaxes = gt_overlaps.argmax(axis=1) maxes = gt_overlaps.max(axis=1) I = np.where(maxes > 0)[0] overlaps[I, gt_classes[argmaxes[I]]] = maxes[I] overlaps = scipy.sparse.csr_matrix(overlaps) roidb.append({ 'boxes': boxes, 'gt_classes': np.zeros((num_boxes,), dtype=np.int32), 'gt_overlaps': overlaps, 'flipped': False, 'JPGed':False, 'noised':False #'seg_areas': np.zeros((num_boxes,), dtype=np.float32), }) return roidb @staticmethod def merge_roidbs(a, b): assert len(a) == len(b) for i in range(len(a)): a[i]['boxes'] = np.vstack((a[i]['boxes'], b[i]['boxes'])) a[i]['gt_classes'] = np.hstack((a[i]['gt_classes'], b[i]['gt_classes'])) a[i]['gt_overlaps'] = scipy.sparse.vstack([a[i]['gt_overlaps'], b[i]['gt_overlaps']]) # a[i]['seg_areas'] = np.hstack((a[i]['seg_areas'], #b[i]['seg_areas'])) return a def competition_mode(self, on): """Turn competition mode on or off.""" pass
10,309
33.481605
74
py
RGB-N
RGB-N-master/lib/datasets/factory.py
# -------------------------------------------------------- # Tensorflow RGB-N # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- """Factory method for easily getting imdbs by name.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function __sets = {} from datasets.pascal_voc import pascal_voc from datasets.coco import coco from datasets.casia import casia from datasets.dist_fake import dist_fake from datasets.nist import nist from datasets.dvmm import dvmm from datasets.swapme import swapme import numpy as np # Set up voc_<year>_<split> for year in ['2007', '2012']: for split in ['train', 'val', 'trainval', 'test']: name = 'voc_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: pascal_voc(split, year)) # Set up coco_2014_<split> for year in ['2014']: for split in ['train', 'val', 'minival', 'valminusminival', 'trainval']: name = 'coco_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: coco(split, year)) # Set up coco_2015_<split> for year in ['2015']: for split in ['test', 'test-dev']: name = 'COCO_{}_{}'.format(year, split) __sets[name] = (lambda split=split, year=year: coco(split, year)) dvmm_path='/vulcan/scratch/pengzhou/dataset/4cam_splc' for split in ['dist_train', 'dist_test']: name = split __sets[name] = (lambda split=split: dvmm(split,2007,dvmm_path)) dso_path='/vulcan/scratch/pengzhou/dataset/COVERAGE' for split in ['dist_cover_train_single', 'dist_cover_test_single']: name = split __sets[name] = (lambda split=split: dist_fake(split,2007,dso_path)) nist_path='/vulcan/scratch/pengzhou/dataset/NC2016_Test0613' for split in ['dist_NIST_train_new_2', 'dist_NIST_test_new_2']: name = split __sets[name] = (lambda split=split: nist(split,2007,nist_path)) casia_path='/vulcan/scratch/pengzhou/dataset/CASIA2' #for split in ['casia_train_all_single', 'casia_test_all_1']: for split in ['casia_train_all_single', 'casia_test_all_single']: name = split __sets[name] = (lambda split=split: casia(split,2007,casia_path)) coco_path='/vulcan/scratch/pengzhou/dataset/filter_tamper' for split in ['coco_train_filter_single', 'coco_test_filter_single']: name = split __sets[name] = (lambda split=split: coco(split,2007,coco_path)) swapme_path='/home-3/[email protected]/work/xintong/medifor/images/dataset_1k_final' for split in ['face_faceswap_rcnn_train_only', 'face_faceswap_rcnn_test']: name = split __sets[name] = (lambda split=split: swapme(split,2007,swapme_path)) def get_imdb(name): """Get an imdb (image database) by name.""" if name not in __sets: raise KeyError('Unknown dataset: {}'.format(name)) return __sets[name]() def list_imdbs(): """List all registered imdbs.""" return list(__sets.keys())
2,928
34.719512
83
py
RGB-N
RGB-N-master/lib/datasets/casia.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import pickle import subprocess import uuid from .voc_eval import voc_eval from model.config import cfg import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class casia(imdb): def __init__(self, image_set, year, dist_path=None): imdb.__init__(self, image_set) self._year = year self._image_set = image_set.split('casia_')[1] self._dist_path = self._get_default_path() if dist_path is None \ else dist_path self._data_path=self._dist_path self._classes = ('__background__', # always index 0 'tamper','authentic') self._classes = ('authentic', # always index 0 'tamper') self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes))))) self._image_ext = {'.png','.jpg','.tif','.bmp','.JPG'} self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(os.path.splitext(self._image_index[i].split(' ')[0])[0]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ for ext in self._image_ext: #image_path = os.path.join('/home-3/[email protected]/work/xintong/medifor/portrait/test_data', #index + ext) image_path = os.path.join(self._data_path, index + ext) image_path1=os.path.join('/home-3/[email protected]/work/pengzhou/dataset/cocostuff/coco/train2014', index + ext) if os.path.isfile(image_path): return image_path elif os.path.isfile(image_path1): return image_path1 else: continue assert os.path.isfile(image_path) and os.path.isfile(image_path1), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join(self._data_path, self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] #print(image_index) return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ return os.path.join(cfg.DATA_DIR, 'CASIA1') def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: try: roidb = pickle.load(fid) except: roidb = pickle.load(fid, encoding='bytes') print('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self.roidb_gt(index) for index in self.image_index] with open(cache_file, 'wb') as fid: pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL) print('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def roidb_gt(self,image_id): num_objs = int(len(image_id.split(' ')[1:])/5) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix in range(num_objs): bbox = image_id.split(' ')[ix*5+1:ix*5+5] # Make pixel indexes 0-based x1 = float(bbox[0]) -1 y1 = float(bbox[1]) -1 x2 = float(bbox[2]) -1 y2 = float(bbox[3]) -1 if x1<0: x1=0 if y1<0: y1=0 try: cls=self._class_to_ind[image_id.split(' ')[ix*5+5]] except: if int(image_id.split(' ')[ix*5+5])==0: print('authentic') #cls=2 else: cls = int(image_id.split(' ')[ix*5+5]) boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 ) * (y2 - y1) #print(image_id) #print(boxes) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'JPGed': False, 'noised': False, 'seg_areas': seg_areas} def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print('loading {}'.format(filename)) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = pickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'JPGed':False, 'noised':False, 'seg_areas': seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'casia_' + self._image_set + '_{:s}.txt' path = os.path.join( '.', filename) return path def _get_voc_noise_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'casia_' + self._image_set + '_{:s}_noise.txt' path = os.path.join( '.', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print('Writing {} VOC results file'.format(cls)) filename = self._get_voc_results_file_template().format(cls) print(filename) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index.split(' ')[0], dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) def _do_python_eval(self, output_dir='output'): annopath = os.path.join( self._dist_path, 'coco_multi' , 'Annotations', '{:s}.xml') imagesetfile = os.path.join( self._dist_path, self._image_set + '.txt') cachedir = os.path.join(self._dist_path, 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 #use_07_metric = True if int(self._year) < 2010 else False use_07_metric = False print('dist metric? ' + ('Yes' if use_07_metric else 'No')) if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__' or cls == self.classes[0]: cls_ind=0 continue else: cls_ind=self._class_to_ind[cls] #elif cls=='median_filtering': #cls_ind=3 #continue filename = self._get_voc_results_file_template().format(cls) filename2 = self._get_voc_noise_results_file_template().format(cls) print(cls_ind) rec, prec, ap = voc_eval( filename,filename2, annopath, imagesetfile, cls_ind, cachedir, ovthresh=0.5, use_07_metric=use_07_metric,fuse=False) aps += [ap] print(('AP for {} = {:.4f},recall = {:.4f}, precision = {:.4f}'.format(cls, ap,rec[-1],prec[-1]))) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f: pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) fig=plt.figure() plt.plot(rec,prec) fig.suptitle('PR curve for {} detection'.format(cls),fontsize=20) plt.xlabel('recall',fontsize=15) plt.xlim((0,1.0)) plt.ylim((0,1.0)) plt.ylabel('precision',fontsize=15) fig.savefig('{}.jpg'.format(cls)) print(('Mean AP = {:.4f}'.format(np.mean(aps)))) print('~~~~~~~~') print('Results:') for ap in aps: print(('{:.3f}'.format(ap))) print(('{:.3f}'.format(np.mean(aps)))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print('-----------------------------------------------------') print('Computing results with the official MATLAB eval code.') print('-----------------------------------------------------') path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._devkit_path, self._get_comp_id(), self._image_set, output_dir) print(('Running:\n{}'.format(cmd))) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) #if self.config['matlab_eval']: #self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) #os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.casia import casia d = casia('trainval', '2007') res = d.roidb from IPython import embed; embed()
13,348
34.597333
105
py
RGB-N
RGB-N-master/lib/datasets/swapme.py
# -------------------------------------------------------- # Tensorflow RGB-N # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import pickle import subprocess import uuid from .voc_eval import voc_eval from model.config import cfg import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class swapme(imdb): def __init__(self, image_set, year, dist_path=None): imdb.__init__(self, image_set) self._year = year self._image_set = image_set.split('face_')[1] self._dist_path = self._get_default_path() if dist_path is None \ else dist_path self._data_path=self._dist_path self._classes = ('__background__', # always index 0 'tamper','authentic') #self._classes = ('authentic', # always index 0 #'tamper') self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes))))) self._image_ext = {'.png','.jpg','.tif','.bmp','.JPG'} self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(os.path.splitext(self._image_index[i].split(' ')[0])[0]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ for ext in self._image_ext: #image_path = os.path.join('/home-3/[email protected]/work/xintong/medifor/portrait/test_data', #index + ext) image_path = os.path.join(self._data_path, index + ext) image_path1=os.path.join('/home-3/[email protected]/work/pengzhou/dataset/DATA2', index.split('/')[1] + ext) if os.path.isfile(image_path): return image_path elif os.path.isfile(image_path1): return image_path1 else: continue assert os.path.isfile(image_path) and os.path.isfile(image_path1), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join('/home-3/[email protected]/work/pengzhou/dataset', self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] #print(image_index) return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ return os.path.join(cfg.DATA_DIR, 'swapme') def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: try: roidb = pickle.load(fid) except: roidb = pickle.load(fid, encoding='bytes') print('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self.roidb_gt(index) for index in self.image_index] with open(cache_file, 'wb') as fid: pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL) print('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def roidb_gt(self,image_id): num_objs = int(len(image_id.split(' ')[1:])/5) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix in range(num_objs): bbox = image_id.split(' ')[ix*5+1:ix*5+5] # Make pixel indexes 0-based x1 = float(bbox[0]) -1 y1 = float(bbox[1]) -1 x2 = float(bbox[2]) -1 y2 = float(bbox[3]) -1 if x1<0: x1=0 if y1<0: y1=0 try: cls=self._class_to_ind[image_id.split(' ')[ix*5+5]] except: if int(image_id.split(' ')[ix*5+5])==0: print('authentic') cls=2 else: cls = int(image_id.split(' ')[ix*5+5]) boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 ) * (y2 - y1) #print(image_id) #print(boxes) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print('loading {}'.format(filename)) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = pickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'casia_' + self._image_set + '_{:s}.txt' path = os.path.join( '.', filename) return path def _get_voc_noise_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'casia_' + self._image_set + '_{:s}_noise.txt' path = os.path.join( '.', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print('Writing {} VOC results file'.format(cls)) filename = self._get_voc_results_file_template().format(cls) print(filename) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index.split(' ')[0], dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) def _do_python_eval(self, output_dir='output'): annopath = os.path.join( '/home-3/[email protected]/work/pengzhou/dataset', 'coco_multi' , 'Annotations', '{:s}.xml') imagesetfile = os.path.join( '/home-3/[email protected]/work/pengzhou/dataset', self._image_set + '.txt') cachedir = os.path.join('/home-3/[email protected]/work/pengzhou/dataset', 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 #use_07_metric = True if int(self._year) < 2010 else False use_07_metric = False print('dist metric? ' + ('Yes' if use_07_metric else 'No')) if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__' or cls == self.classes[0]: cls_ind=0 continue else: cls_ind=self._class_to_ind[cls] #elif cls=='median_filtering': #cls_ind=3 #continue filename = self._get_voc_results_file_template().format(cls) filename2 = self._get_voc_noise_results_file_template().format(cls) print(cls_ind) rec, prec, ap = voc_eval( filename,filename2, annopath, imagesetfile, cls_ind, cachedir, ovthresh=0.5, use_07_metric=use_07_metric,fuse=False) aps += [ap] print(('AP for {} = {:.4f},recall = {:.4f}, precision = {:.4f}'.format(cls, ap,rec[-1],prec[-1]))) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f: pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) fig=plt.figure() plt.plot(rec,prec) fig.suptitle('PR curve for {} detection'.format(cls),fontsize=20) plt.xlabel('recall',fontsize=15) plt.xlim((0,1.0)) plt.ylim((0,1.0)) plt.ylabel('precision',fontsize=15) fig.savefig('{}.jpg'.format(cls)) print(('Mean AP = {:.4f}'.format(np.mean(aps)))) print('~~~~~~~~') print('Results:') for ap in aps: print(('{:.3f}'.format(ap))) print(('{:.3f}'.format(np.mean(aps)))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print('-----------------------------------------------------') print('Computing results with the official MATLAB eval code.') print('-----------------------------------------------------') path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._devkit_path, self._get_comp_id(), self._image_set, output_dir) print(('Running:\n{}'.format(cmd))) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) #if self.config['matlab_eval']: #self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) #os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.swapme import swapme d = swapme('trainval', '2007') res = d.roidb from IPython import embed; embed()
13,342
35.062162
104
py
RGB-N
RGB-N-master/lib/datasets/ds_utils.py
# -------------------------------------------------------- # Fast/er R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def unique_boxes(boxes, scale=1.0): """Return indices of unique boxes.""" v = np.array([1, 1e3, 1e6, 1e9]) hashes = np.round(boxes * scale).dot(v) _, index = np.unique(hashes, return_index=True) return np.sort(index) def xywh_to_xyxy(boxes): """Convert [x y w h] box format to [x1 y1 x2 y2] format.""" return np.hstack((boxes[:, 0:2], boxes[:, 0:2] + boxes[:, 2:4] - 1)) def xyxy_to_xywh(boxes): """Convert [x1 y1 x2 y2] box format to [x y w h] format.""" return np.hstack((boxes[:, 0:2], boxes[:, 2:4] - boxes[:, 0:2] + 1)) def validate_boxes(boxes, width=0, height=0): """Check that a set of boxes are valid.""" x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] assert (x1 >= 0).all() assert (y1 >= 0).all() assert (x2 >= x1).all() assert (y2 >= y1).all() assert (x2 < width).all() assert (y2 < height).all() def filter_small_boxes(boxes, min_size): w = boxes[:, 2] - boxes[:, 0] h = boxes[:, 3] - boxes[:, 1] keep = np.where((w >= min_size) & (h > min_size))[0] return keep
1,402
27.06
70
py
RGB-N
RGB-N-master/lib/datasets/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # --------------------------------------------------------
248
34.571429
58
py
RGB-N
RGB-N-master/lib/datasets/coco.py
# -------------------------------------------------------- # Tensorflow RGB-N # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou, based on the code of Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import pickle import subprocess import uuid from .voc_eval import voc_eval from model.config import cfg import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class coco(imdb): def __init__(self, image_set, year, dist_path=None): imdb.__init__(self, image_set) self._year = year self._image_set = image_set.split('coco_')[1] self._dist_path = self._get_default_path() if dist_path is None \ else dist_path self._data_path=self._dist_path #self._data_path = os.path.join(self._dist_path, image_set) self._classes = ('__background__', # always index 0 'tamper','authentic') self._classes = ('authentic', # always index 0 'tamper') self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes))))) #self._image_ext = {'.jpg','.tif'} self._image_ext = {'.png','.jpg','.tif','.bmp','.JPG'} self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(os.path.splitext(self._image_index[i].split(' ')[0])[0]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ for ext in self._image_ext: #image_path = os.path.join('/home-3/[email protected]/work/xintong/medifor/portrait/test_data', #index + ext) image_path = os.path.join(self._data_path, index + ext) image_path1=os.path.join('../dataset/train2014', index + ext) if os.path.isfile(image_path): return image_path elif os.path.isfile(image_path1): return image_path1 else: continue assert os.path.isfile(image_path) and os.path.isfile(image_path1), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join(self._data_path, self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ #return os.path.join(cfg.DATA_DIR, 'CASIA2') return os.path.join(cfg.DATA_DIR, 'cocostuff/coco/splicing') def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: try: roidb = pickle.load(fid) except: roidb = pickle.load(fid, encoding='bytes') print('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self.roidb_gt(index) for index in self.image_index] with open(cache_file, 'wb') as fid: pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL) print('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def roidb_gt(self,image_id): num_objs = int(len(image_id.split(' ')[1:])/5) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix in range(num_objs): bbox = image_id.split(' ')[ix*5+1:ix*5+5] #print(bbox) # Make pixel indexes 0-based x1 = float(bbox[0]) -1 y1 = float(bbox[1]) -1 x2 = float(bbox[2]) -1 y2 = float(bbox[3]) -1 if x1<0: x1=0 if y1<0: y1=0 try: cls=self._class_to_ind[image_id.split(' ')[ix*5+5]] except: cls = int(image_id.split(' ')[ix*5+5]) boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 ) * (y2 - y1) #print(image_id) #print(boxes) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'JPGed': False, 'noised':False, 'seg_areas': seg_areas} def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print('loading {}'.format(filename)) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = pickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'coco_' + self._image_set + '_{:s}.txt' path = os.path.join( '.', filename) return path def _get_voc_noise_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'coco_' + self._image_set + '_{:s}_noise.txt' path = os.path.join( '.', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print('Writing {} det results file'.format(cls)) filename = self._get_voc_results_file_template().format(cls) print(filename) with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] #print(dets) #print(index) if dets == []: continue # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index.split(' ')[0], dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) def _do_python_eval(self, output_dir='output'): annopath = os.path.join( self._dist_path, 'coco_multi' , 'Annotations', '{:s}.xml') imagesetfile = os.path.join( self._dist_path, self._image_set + '.txt') cachedir = os.path.join(self._dist_path, 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 #use_07_metric = True if int(self._year) < 2010 else False use_07_metric = False print('dist metric? ' + ('Yes' if use_07_metric else 'No')) if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__' or cls == self.classes[0]: cls_ind=0 continue else: cls_ind=self._class_to_ind[cls] #elif cls=='median_filtering': #cls_ind=3 #continue filename = self._get_voc_results_file_template().format(cls) filename2 = self._get_voc_noise_results_file_template().format(cls) #print(cls_ind) rec, prec, ap = voc_eval( filename,filename2, annopath, imagesetfile, cls_ind, cachedir, ovthresh=0.5, use_07_metric=use_07_metric,fuse=False) aps += [ap] print(('AP for {} = {:.4f},recall = {:.4f}, precision = {:.4f}'.format(cls, ap,rec[-1],prec[-1]))) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f: pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) fig=plt.figure() plt.plot(rec,prec) fig.suptitle('PR curve for {} detection'.format(cls),fontsize=20) plt.xlabel('recall',fontsize=15) plt.xlim((0,1.0)) plt.ylim((0,1.0)) plt.ylabel('precision',fontsize=15) fig.savefig('{}.png'.format(cls)) print(('Mean AP = {:.4f}'.format(np.mean(aps)))) print('~~~~~~~~') print('Results:') for ap in aps: print(('{:.3f}'.format(ap))) print(('{:.3f}'.format(np.mean(aps)))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print('-----------------------------------------------------') print('Computing results with the official MATLAB eval code.') print('-----------------------------------------------------') path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._dist_path, self._image_set, output_dir) print(('Running:\n{}'.format(cmd))) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) #if self.config['matlab_eval']: #self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__' or cls == self.classes[0]: continue filename = self._get_voc_results_file_template().format(cls) #os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.coco import coco d = coco('train', '2007') res = d.roidb from IPython import embed; embed()
13,334
34.65508
104
py
RGB-N
RGB-N-master/lib/datasets/nist.py
# -------------------------------------------------------- # Tensorflow RGB-N # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import pickle import subprocess import uuid import pdb from .voc_eval import voc_eval from model.config import cfg import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class nist(imdb): def __init__(self, image_set, year, dist_path=None): imdb.__init__(self, image_set) self._year = year self._image_set = image_set.split('dist_')[1] self._dist_path = self._get_default_path() if dist_path is None \ else dist_path self._data_path=self._dist_path self._classes = ('__background__', # always index 0 'tamper','authentic') self._classes = ('__background__', # always index 0 'splicing','removal','manipulation') self._classes = ('authentic', # always index 0 'tamper') self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes))))) self._image_ext = {'.png','.jpg','.tif','.bmp','.JPG'} self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(os.path.splitext(self._image_index[i].split(' ')[0])[0]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ for ext in self._image_ext: #image_path = os.path.join('/home-3/[email protected]/work/xintong/medifor/portrait/test_data', #index + ext) image_path = os.path.join(self._data_path, index + ext) image_path1=os.path.join('/home-3/[email protected]/work/pengzhou/dataset/NC2016_Test0613', index + ext) if os.path.isfile(image_path): return image_path elif os.path.isfile(image_path1): return image_path1 else: continue assert os.path.isfile(image_path) and os.path.isfile(image_path1), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join(self._data_path, self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] #print(image_index) return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ return os.path.join(cfg.DATA_DIR, 'NC2016_Test0613') def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: try: roidb = pickle.load(fid) except: roidb = pickle.load(fid, encoding='bytes') print('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self.roidb_gt(index) for index in self.image_index] with open(cache_file, 'wb') as fid: pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL) print('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def roidb_gt(self,image_id): num_objs = int(len(image_id.split(' ')[1:])/5) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix in range(num_objs): bbox = image_id.split(' ')[ix*5+1:ix*5+5] # Make pixel indexes 0-based x1 = float(bbox[0]) y1 = float(bbox[1]) x2 = float(bbox[2]) y2 = float(bbox[3]) if x1<0: x1=0 if y1<0: y1=0 try: cls=self._class_to_ind[image_id.split(' ')[ix*5+5]] except: if int(image_id.split(' ')[ix*5+5])==0: print('authentic') cls=2 else: cls = int(image_id.split(' ')[ix*5+5]) boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 ) * (y2 - y1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'JPGed': False, 'noised':False, 'seg_areas': seg_areas} def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print('loading {}'.format(filename)) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = pickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'nist_' + self._image_set + '_{:s}.txt' path = os.path.join( '.', filename) return path def _get_voc_noise_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'nist_' + self._image_set + '_{:s}_noise.txt' path = os.path.join( '.', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__' or cls == self.classes[0]: continue print('Writing {} VOC results file'.format(cls)) filename = self._get_voc_results_file_template().format(cls) print(filename) with open(filename, 'w') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): #pdb.set_trace() f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.format(index.split(' ')[0], dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) #pdb.set_trace() def _do_python_eval(self, output_dir='output'): annopath = os.path.join( self._dist_path, 'coco_multi' , 'Annotations', '{:s}.xml') imagesetfile = os.path.join( self._dist_path, self._image_set + '.txt') cachedir = os.path.join(self._dist_path, 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 #use_07_metric = True if int(self._year) < 2010 else False use_07_metric = False print('dist metric? ' + ('Yes' if use_07_metric else 'No')) if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__' or cls == self.classes[0]: cls_ind=0 continue else: cls_ind=self._class_to_ind[cls] #elif cls=='median_filtering': #cls_ind=3 #continue filename = self._get_voc_results_file_template().format(cls) filename2 = self._get_voc_noise_results_file_template().format(cls) print(cls_ind) rec, prec, ap = voc_eval( filename,filename2, annopath, imagesetfile, cls_ind, cachedir, ovthresh=0.5, use_07_metric=use_07_metric,fuse=False) aps += [ap] print(('AP for {} = {:.4f},recall = {:.4f}, precision = {:.4f}'.format(cls, ap,rec[-1],prec[-1]))) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f: pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) fig=plt.figure() plt.plot(rec,prec) fig.suptitle('PR curve for {} detection'.format(cls),fontsize=20) plt.xlabel('recall',fontsize=15) plt.xlim((0,1.0)) plt.ylim((0,1.0)) plt.ylabel('precision',fontsize=15) fig.savefig('{}.png'.format(cls)) print(('Mean AP = {:.4f}'.format(np.mean(aps)))) print('~~~~~~~~') print('Results:') for ap in aps: print(('{:.3f}'.format(ap))) print(('{:.3f}'.format(np.mean(aps)))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print('-----------------------------------------------------') print('Computing results with the official MATLAB eval code.') print('-----------------------------------------------------') path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._devkit_path, self._get_comp_id(), self._image_set, output_dir) print(('Running:\n{}'.format(cmd))) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) #if self.config['matlab_eval']: #self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__' or cls == self.classes[0]: continue filename = self._get_voc_results_file_template().format(cls) #os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.dist_fake import dist_fake d = nist('trainval', '2007') res = d.roidb from IPython import embed; embed()
13,431
34.818667
104
py
RGB-N
RGB-N-master/lib/datasets/dvmm.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from datasets.imdb import imdb import datasets.ds_utils as ds_utils import numpy as np import scipy.sparse import scipy.io as sio import utils.cython_bbox import pickle import subprocess import uuid import pdb from .voc_eval import voc_eval from model.config import cfg import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt class dvmm(imdb): def __init__(self, image_set, year, dist_path=None): imdb.__init__(self, image_set) self._year = year self._image_set = image_set.split('dist_')[1] self._dist_path = self._get_default_path() if dist_path is None \ else dist_path self._data_path=self._dist_path self._classes = ('__background__', # always index 0 'tamper','authentic') self._classes = ('authentic', # always index 0 'tamper') #self.classes =('authentic', # always index 0 #'splicing','removal') self._class_to_ind = dict(list(zip(self.classes, list(range(self.num_classes))))) self._image_ext = {'.png','.jpg','.tif','.bmp','.JPG'} self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.gt_roidb assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(os.path.splitext(self._image_index[i].split(' ')[0])[0]) def image_path_from_index(self, index): """ Construct an image path from the image's "index" identifier. """ for ext in self._image_ext: #image_path = os.path.join('/home-3/[email protected]/work/xintong/medifor/portrait/test_data', #index + ext) image_path = os.path.join(self._data_path, index + ext) image_path1=os.path.join('/home-3/[email protected]/work/pengzhou/dataset/NC2016_Test0613', index + ext) if os.path.isfile(image_path): return image_path elif os.path.isfile(image_path1): return image_path1 else: continue assert os.path.isfile(image_path) and os.path.isfile(image_path1), \ 'Path does not exist: {}'.format(image_path) return image_path def _load_image_set_index(self): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt image_set_file = os.path.join(self._data_path, self._image_set + '.txt') assert os.path.exists(image_set_file), \ 'Path does not exist: {}'.format(image_set_file) with open(image_set_file) as f: image_index = [x.strip() for x in f.readlines()] #print(image_index) return image_index def _get_default_path(self): """ Return the default path where PASCAL VOC is expected to be installed. """ return os.path.join(cfg.DATA_DIR, 'NC2016_Test0613') def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: try: roidb = pickle.load(fid) except: roidb = pickle.load(fid, encoding='bytes') print('{} gt roidb loaded from {}'.format(self.name, cache_file)) return roidb gt_roidb = [self.roidb_gt(index) for index in self.image_index] with open(cache_file, 'wb') as fid: pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL) print('wrote gt roidb to {}'.format(cache_file)) return gt_roidb def rpn_roidb(self): if int(self._year) == 2007 or self._image_set != 'test': gt_roidb = self.gt_roidb() rpn_roidb = self._load_rpn_roidb(gt_roidb) roidb = imdb.merge_roidbs(gt_roidb, rpn_roidb) else: roidb = self._load_rpn_roidb(None) return roidb def roidb_gt(self,image_id): num_objs = int(len(image_id.split(' ')[1:])/5) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix in range(num_objs): bbox = image_id.split(' ')[ix*5+1:ix*5+5] # Make pixel indexes 0-based x1 = float(bbox[0]) y1 = float(bbox[1]) x2 = float(bbox[2]) y2 = float(bbox[3]) if x1<0: x1=0 if y1<0: y1=0 try: cls=self._class_to_ind[image_id.split(' ')[ix*5+5]] except: if int(image_id.split(' ')[ix*5+5])==0: print('authentic') #cls=2 else: cls = int(image_id.split(' ')[ix*5+5]) boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 ) * (y2 - y1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _load_rpn_roidb(self, gt_roidb): filename = self.config['rpn_file'] print('loading {}'.format(filename)) assert os.path.exists(filename), \ 'rpn data not found at: {}'.format(filename) with open(filename, 'rb') as f: box_list = pickle.load(f) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_pascal_annotation(self, index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ filename = os.path.join(self._data_path, 'Annotations', index + '.xml') tree = ET.parse(filename) objs = tree.findall('object') if not self.config['use_diff']: # Exclude the samples labeled as difficult non_diff_objs = [ obj for obj in objs if int(obj.find('difficult').text) == 0] # if len(non_diff_objs) != len(objs): # print 'Removed {} difficult objects'.format( # len(objs) - len(non_diff_objs)) objs = non_diff_objs num_objs = len(objs) boxes = np.zeros((num_objs, 4), dtype=np.uint16) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) # "Seg" area for pascal is just the box area seg_areas = np.zeros((num_objs), dtype=np.float32) # Load object bounding boxes into a data frame. for ix, obj in enumerate(objs): bbox = obj.find('bndbox') # Make pixel indexes 0-based x1 = float(bbox.find('xmin').text) - 1 y1 = float(bbox.find('ymin').text) - 1 x2 = float(bbox.find('xmax').text) - 1 y2 = float(bbox.find('ymax').text) - 1 cls = self._class_to_ind[obj.find('name').text.lower().strip()] boxes[ix, :] = [x1, y1, x2, y2] gt_classes[ix] = cls overlaps[ix, cls] = 1.0 seg_areas[ix] = (x2 - x1 + 1) * (y2 - y1 + 1) overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes': boxes, 'gt_classes': gt_classes, 'gt_overlaps': overlaps, 'flipped': False, 'seg_areas': seg_areas} def _get_comp_id(self): comp_id = (self._comp_id + '_' + self._salt if self.config['use_salt'] else self._comp_id) return comp_id def _get_voc_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'dvmm_' + self._image_set + '_{:s}.txt' path = os.path.join( '.', filename) return path def _get_voc_noise_results_file_template(self): # VOCdevkit/results/VOC2007/Main/<comp_id>_det_test_aeroplane.txt filename = 'dvmm_' + self._image_set + '_{:s}_noise.txt' path = os.path.join( '.', filename) return path def _write_voc_results_file(self, all_boxes): for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print('Writing {} VOC results file'.format(cls)) filename = self._get_voc_results_file_template().format(cls) print(filename) with open(filename, 'w') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in range(dets.shape[0]): #pdb.set_trace() f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'.format(index.split(' ')[0], dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) #pdb.set_trace() def _do_python_eval(self, output_dir='output'): annopath = os.path.join( self._dist_path, 'coco_multi' , 'Annotations', '{:s}.xml') imagesetfile = os.path.join( self._dist_path, self._image_set + '.txt') cachedir = os.path.join(self._dist_path, 'annotations_cache') aps = [] # The PASCAL VOC metric changed in 2010 #use_07_metric = True if int(self._year) < 2010 else False use_07_metric = False print('dist metric? ' + ('Yes' if use_07_metric else 'No')) if not os.path.isdir(output_dir): os.mkdir(output_dir) for i, cls in enumerate(self._classes): if cls == '__background__' or cls == self.classes[0]: cls_ind=0 continue else: cls_ind=self._class_to_ind[cls] #elif cls=='median_filtering': #cls_ind=3 #continue filename = self._get_voc_results_file_template().format(cls) filename2 = self._get_voc_noise_results_file_template().format(cls) print(cls_ind) rec, prec, ap = voc_eval( filename,filename2, annopath, imagesetfile, cls_ind, cachedir, ovthresh=0.5, use_07_metric=use_07_metric,fuse=False) aps += [ap] print(('AP for {} = {:.4f},recall = {:.4f}, precision = {:.4f}'.format(cls, ap,rec[-1],prec[-1]))) with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f: pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f) fig=plt.figure() plt.plot(rec,prec) fig.suptitle('PR curve for {} detection'.format(cls),fontsize=20) plt.xlabel('recall',fontsize=15) plt.xlim((0,1.0)) plt.ylim((0,1.0)) plt.ylabel('precision',fontsize=15) fig.savefig('{}.jpg'.format(cls)) print(('Mean AP = {:.4f}'.format(np.mean(aps)))) print('~~~~~~~~') print('Results:') for ap in aps: print(('{:.3f}'.format(ap))) print(('{:.3f}'.format(np.mean(aps)))) print('~~~~~~~~') print('') print('--------------------------------------------------------------') print('Results computed with the **unofficial** Python eval code.') print('Results should be very close to the official MATLAB eval code.') print('Recompute with `./tools/reval.py --matlab ...` for your paper.') print('-- Thanks, The Management') print('--------------------------------------------------------------') def _do_matlab_eval(self, output_dir='output'): print('-----------------------------------------------------') print('Computing results with the official MATLAB eval code.') print('-----------------------------------------------------') path = os.path.join(cfg.ROOT_DIR, 'lib', 'datasets', 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\'); quit;"' \ .format(self._devkit_path, self._get_comp_id(), self._image_set, output_dir) print(('Running:\n{}'.format(cmd))) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): self._write_voc_results_file(all_boxes) self._do_python_eval(output_dir) #if self.config['matlab_eval']: #self._do_matlab_eval(output_dir) if self.config['cleanup']: for cls in self._classes: if cls == '__background__': continue filename = self._get_voc_results_file_template().format(cls) #os.remove(filename) def competition_mode(self, on): if on: self.config['use_salt'] = False self.config['cleanup'] = False else: self.config['use_salt'] = True self.config['cleanup'] = True if __name__ == '__main__': from datasets.dvmm import dvmm d = dvmm('trainval', '2007') res = d.roidb from IPython import embed; embed()
13,318
34.612299
104
py
RGB-N
RGB-N-master/lib/datasets/tools/mcg_munge.py
import os import sys """Hacky tool to convert file system layout of MCG boxes downloaded from http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/mcg/ so that it's consistent with those computed by Jan Hosang (see: http://www.mpi-inf.mpg.de/departments/computer-vision-and-multimodal- computing/research/object-recognition-and-scene-understanding/how- good-are-detection-proposals-really/) NB: Boxes from the MCG website are in (y1, x1, y2, x2) order. Boxes from Hosang et al. are in (x1, y1, x2, y2) order. """ def munge(src_dir): # stored as: ./MCG-COCO-val2014-boxes/COCO_val2014_000000193401.mat # want: ./MCG/mat/COCO_val2014_0/COCO_val2014_000000141/COCO_val2014_000000141334.mat files = os.listdir(src_dir) for fn in files: base, ext = os.path.splitext(fn) # first 14 chars / first 22 chars / all chars + .mat # COCO_val2014_0/COCO_val2014_000000447/COCO_val2014_000000447991.mat first = base[:14] second = base[:22] dst_dir = os.path.join('MCG', 'mat', first, second) if not os.path.exists(dst_dir): os.makedirs(dst_dir) src = os.path.join(src_dir, fn) dst = os.path.join(dst_dir, fn) print 'MV: {} -> {}'.format(src, dst) os.rename(src, dst) if __name__ == '__main__': # src_dir should look something like: # src_dir = 'MCG-COCO-val2014-boxes' src_dir = sys.argv[1] munge(src_dir)
1,451
36.230769
94
py
RGB-N
RGB-N-master/lib/layer_utils/proposal_layer.py
# -------------------------------------------------------- # Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from model.config import cfg from model.bbox_transform import bbox_transform_inv, clip_boxes from model.nms_wrapper import nms def proposal_layer(rpn_cls_prob, rpn_bbox_pred, im_info, cfg_key, _feat_stride, anchors, num_anchors): """A simplified version compared to fast/er RCNN For details please see the technical report """ if type(cfg_key) == bytes: cfg_key = cfg_key.decode('utf-8') pre_nms_topN = cfg[cfg_key].RPN_PRE_NMS_TOP_N post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N nms_thresh = cfg[cfg_key].RPN_NMS_THRESH im_info = im_info[0] # Get the scores and bounding boxes scores = rpn_cls_prob[:, :, :, num_anchors:] rpn_bbox_pred = rpn_bbox_pred.reshape((-1, 4)) scores = scores.reshape((-1, 1)) proposals = bbox_transform_inv(anchors, rpn_bbox_pred) proposals = clip_boxes(proposals, im_info[:2]) # Pick the top region proposals order = scores.ravel().argsort()[::-1] if pre_nms_topN > 0: order = order[:pre_nms_topN] proposals = proposals[order, :] scores = scores[order] # Non-maximal suppression keep = nms(np.hstack((proposals, scores)), nms_thresh) # Pick th top region proposals after NMS if post_nms_topN > 0: keep = keep[:post_nms_topN] proposals = proposals[keep, :] scores = scores[keep] # Only support single image as input batch_inds = np.zeros((proposals.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False))) return blob, scores
1,850
32.654545
102
py
RGB-N
RGB-N-master/lib/layer_utils/proposal_top_layer.py
# -------------------------------------------------------- # Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from model.config import cfg from model.bbox_transform import bbox_transform_inv, clip_boxes import numpy.random as npr def proposal_top_layer(rpn_cls_prob, rpn_bbox_pred, im_info, _feat_stride, anchors, num_anchors): """A layer that just selects the top region proposals without using non-maximal suppression, For details please see the technical report """ rpn_top_n = cfg.TEST.RPN_TOP_N im_info = im_info[0] scores = rpn_cls_prob[:, :, :, num_anchors:] rpn_bbox_pred = rpn_bbox_pred.reshape((-1, 4)) scores = scores.reshape((-1, 1)) length = scores.shape[0] if length < rpn_top_n: # Random selection, maybe unnecessary and loses good proposals # But such case rarely happens top_inds = npr.choice(length, size=rpn_top_n, replace=True) else: top_inds = scores.argsort(0)[::-1] top_inds = top_inds[:rpn_top_n] top_inds = top_inds.reshape(rpn_top_n, ) # Do the selection here anchors = anchors[top_inds, :] rpn_bbox_pred = rpn_bbox_pred[top_inds, :] scores = scores[top_inds] # Convert anchors into proposals via bbox transformations proposals = bbox_transform_inv(anchors, rpn_bbox_pred) # Clip predicted boxes to image proposals = clip_boxes(proposals, im_info[:2]) # Output rois blob # Our RPN implementation only supports a single input image, so all # batch inds are 0 batch_inds = np.zeros((proposals.shape[0], 1), dtype=np.float32) blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False))) return blob, scores
1,868
32.981818
97
py
RGB-N
RGB-N-master/lib/layer_utils/generate_anchors.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np # Verify that we compute the same anchors as Shaoqing's matlab implementation: # # >> load output/rpn_cachedir/faster_rcnn_VOC2007_ZF_stage1_rpn/anchors.mat # >> anchors # # anchors = # # -83 -39 100 56 # -175 -87 192 104 # -359 -183 376 200 # -55 -55 72 72 # -119 -119 136 136 # -247 -247 264 264 # -35 -79 52 96 # -79 -167 96 184 # -167 -343 184 360 # array([[ -83., -39., 100., 56.], # [-175., -87., 192., 104.], # [-359., -183., 376., 200.], # [ -55., -55., 72., 72.], # [-119., -119., 136., 136.], # [-247., -247., 264., 264.], # [ -35., -79., 52., 96.], # [ -79., -167., 96., 184.], # [-167., -343., 184., 360.]]) def generate_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2 ** np.arange(3, 6)): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size]) - 1 ratio_anchors = _ratio_enum(base_anchor, ratios) anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in range(ratio_anchors.shape[0])]) return anchors def _whctrs(anchor): """ Return width, height, x center, and y center for an anchor (window). """ w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr def _mkanchors(ws, hs, x_ctr, y_ctr): """ Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack((x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1))) return anchors def _ratio_enum(anchor, ratios): """ Enumerate a set of anchors for each aspect ratio wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) size = w * h size_ratios = size / ratios ws = np.round(np.sqrt(size_ratios)) hs = np.round(ws * ratios) anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors def _scale_enum(anchor, scales): """ Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) ws = w * scales hs = h * scales anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors if __name__ == '__main__': import time t = time.time() a = generate_anchors() print(time.time() - t) print(a) from IPython import embed; embed()
3,129
25.525424
78
py
RGB-N
RGB-N-master/lib/layer_utils/proposal_target_layer.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick, Sean Bell and Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import numpy.random as npr from model.config import cfg from model.bbox_transform import bbox_transform from utils.cython_bbox import bbox_overlaps def proposal_target_layer(rpn_rois, rpn_scores, gt_boxes, _num_classes): """ Assign object detection proposals to ground-truth targets. Produces proposal classification labels and bounding-box regression targets. """ # Proposal ROIs (0, x1, y1, x2, y2) coming from RPN # (i.e., rpn.proposal_layer.ProposalLayer), or any other source all_rois = rpn_rois all_scores = rpn_scores # Include ground-truth boxes in the set of candidate rois if cfg.TRAIN.USE_GT: zeros = np.zeros((gt_boxes.shape[0], 1), dtype=gt_boxes.dtype) all_rois = np.vstack( (all_rois, np.hstack((zeros, gt_boxes[:, :-1]))) ) # not sure if it a wise appending, but anyway i am not using it all_scores = np.vstack((all_scores, zeros)) num_images = 1 rois_per_image = cfg.TRAIN.BATCH_SIZE / num_images fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image) # Sample rois with classification labels and bounding box regression # targets labels, rois, roi_scores, bbox_targets, bbox_inside_weights = _sample_rois( all_rois, all_scores, gt_boxes, fg_rois_per_image, rois_per_image, _num_classes) rois = rois.reshape(-1, 5) roi_scores = roi_scores.reshape(-1) labels = labels.reshape(-1, 1) bbox_targets = bbox_targets.reshape(-1, _num_classes * 4) bbox_inside_weights = bbox_inside_weights.reshape(-1, _num_classes * 4) bbox_outside_weights = np.array(bbox_inside_weights > 0).astype(np.float32) return rois, roi_scores, labels, bbox_targets, bbox_inside_weights, bbox_outside_weights def _get_bbox_regression_labels(bbox_target_data, num_classes): """Bounding-box regression targets (bbox_target_data) are stored in a compact form N x (class, tx, ty, tw, th) This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). Returns: bbox_target (ndarray): N x 4K blob of regression targets bbox_inside_weights (ndarray): N x 4K blob of loss weights """ clss = bbox_target_data[:, 0] bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32) bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32) if num_classes<=2: inds = np.where(clss > 0)[0] else: inds = np.where(clss > 0)[0] for ind in inds: cls = clss[ind] start = int(4 * cls) end = start + 4 bbox_targets[ind, start:end] = bbox_target_data[ind, 1:] bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS return bbox_targets, bbox_inside_weights def _compute_targets(ex_rois, gt_rois, labels): """Compute bounding-box regression targets for an image.""" assert ex_rois.shape[0] == gt_rois.shape[0] assert ex_rois.shape[1] == 4 assert gt_rois.shape[1] == 4 targets = bbox_transform(ex_rois, gt_rois) if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED: # Optionally normalize targets by a precomputed mean and stdev targets = ((targets - np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS)) / np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS)) return np.hstack( (labels[:, np.newaxis], targets)).astype(np.float32, copy=False) def _sample_rois(all_rois, all_scores, gt_boxes, fg_rois_per_image, rois_per_image, num_classes): """Generate a random sample of RoIs comprising foreground and background examples. """ # overlaps: (rois x gt_boxes) overlaps = bbox_overlaps( np.ascontiguousarray(all_rois[:, 1:5], dtype=np.float), np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float)) gt_assignment = overlaps.argmax(axis=1) max_overlaps = overlaps.max(axis=1) labels = gt_boxes[gt_assignment, 4] # Select foreground RoIs as those with >= FG_THRESH overlap fg_inds = np.where(max_overlaps >= cfg.TRAIN.FG_THRESH)[0] # Guard against the case when an image has fewer than fg_rois_per_image # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((max_overlaps < cfg.TRAIN.BG_THRESH_HI) & (max_overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # Small modification to the original version where we ensure a fixed number of regions are sampled if fg_inds.size > 0 and bg_inds.size > 0: fg_rois_per_image = min(fg_rois_per_image, fg_inds.size) fg_inds = npr.choice(fg_inds, size=int(fg_rois_per_image), replace=False) bg_rois_per_image = rois_per_image - fg_rois_per_image to_replace = bg_inds.size < bg_rois_per_image bg_inds = npr.choice(bg_inds, size=int(bg_rois_per_image), replace=to_replace) elif fg_inds.size > 0: to_replace = fg_inds.size < rois_per_image fg_inds = npr.choice(fg_inds, size=int(rois_per_image), replace=to_replace) fg_rois_per_image = rois_per_image elif bg_inds.size > 0: to_replace = bg_inds.size < rois_per_image bg_inds = npr.choice(bg_inds, size=int(rois_per_image), replace=to_replace) fg_rois_per_image = 0 else: import pdb pdb.set_trace() # The indices that we're selecting (both fg and bg) keep_inds = np.append(fg_inds, bg_inds) # Select sampled values from various arrays: labels = labels[keep_inds] # Clamp labels for the background RoIs to 0 labels[int(fg_rois_per_image):] = 0 rois = all_rois[keep_inds] roi_scores = all_scores[keep_inds] bbox_target_data = _compute_targets( rois[:, 1:5], gt_boxes[gt_assignment[keep_inds], :4], labels) bbox_targets, bbox_inside_weights = \ _get_bbox_regression_labels(bbox_target_data, num_classes) return labels, rois, roi_scores, bbox_targets, bbox_inside_weights
6,081
37.987179
100
py
RGB-N
RGB-N-master/lib/layer_utils/snippets.py
# -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import numpy.random as npr from model.config import cfg from layer_utils.generate_anchors import generate_anchors from model.bbox_transform import bbox_transform_inv, clip_boxes from utils.cython_bbox import bbox_overlaps def generate_anchors_pre(height, width, feat_stride, anchor_scales=(8,16,32), anchor_ratios=(0.5,1,2)): """ A wrapper function to generate anchors given different scales Also return the number of anchors in variable 'length' """ anchors = generate_anchors(ratios=np.array(anchor_ratios), scales=np.array(anchor_scales)) A = anchors.shape[0] shift_x = np.arange(0, width) * feat_stride shift_y = np.arange(0, height) * feat_stride shift_x, shift_y = np.meshgrid(shift_x, shift_y) shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() K = shifts.shape[0] # width changes faster, so here it is H, W, C anchors = anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2)) anchors = anchors.reshape((K * A, 4)).astype(np.float32, copy=False) length = np.int32(anchors.shape[0]) return anchors, length
1,473
42.352941
103
py
RGB-N
RGB-N-master/lib/layer_utils/anchor_target_layer.py
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from model.config import cfg import numpy as np import numpy.random as npr from utils.cython_bbox import bbox_overlaps from model.bbox_transform import bbox_transform def anchor_target_layer(rpn_cls_score, gt_boxes, im_info, _feat_stride, all_anchors, num_anchors): """Same as the anchor target layer in original Fast/er RCNN """ A = num_anchors total_anchors = all_anchors.shape[0] K = total_anchors / num_anchors im_info = im_info[0] # allow boxes to sit over the edge by a small amount _allowed_border = 0 # map of shape (..., H, W) height, width = rpn_cls_score.shape[1:3] # only keep anchors inside the image inds_inside = np.where( (all_anchors[:, 0] >= -_allowed_border) & (all_anchors[:, 1] >= -_allowed_border) & (all_anchors[:, 2] < im_info[1] + _allowed_border) & # width (all_anchors[:, 3] < im_info[0] + _allowed_border) # height )[0] # keep only inside anchors anchors = all_anchors[inds_inside, :] # label: 1 is positive, 0 is negative, -1 is dont care labels = np.empty((len(inds_inside),), dtype=np.float32) labels.fill(-1) # overlaps between the anchors and the gt boxes # overlaps (ex, gt) overlaps = bbox_overlaps( np.ascontiguousarray(anchors, dtype=np.float), np.ascontiguousarray(gt_boxes, dtype=np.float)) argmax_overlaps = overlaps.argmax(axis=1) max_overlaps = overlaps[np.arange(len(inds_inside)), argmax_overlaps] gt_argmax_overlaps = overlaps.argmax(axis=0) gt_max_overlaps = overlaps[gt_argmax_overlaps, np.arange(overlaps.shape[1])] gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] if not cfg.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels first so that positive labels can clobber them # first set the negatives labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 # fg label: for each gt, anchor with highest overlap labels[gt_argmax_overlaps] = 1 # fg label: above threshold IOU labels[max_overlaps >= cfg.TRAIN.RPN_POSITIVE_OVERLAP] = 1 if cfg.TRAIN.RPN_CLOBBER_POSITIVES: # assign bg labels last so that negative labels can clobber positives labels[max_overlaps < cfg.TRAIN.RPN_NEGATIVE_OVERLAP] = 0 # subsample positive labels if we have too many num_fg = int(cfg.TRAIN.RPN_FG_FRACTION * cfg.TRAIN.RPN_BATCHSIZE) fg_inds = np.where(labels == 1)[0] if len(fg_inds) > num_fg: disable_inds = npr.choice( fg_inds, size=(len(fg_inds) - num_fg), replace=False) labels[disable_inds] = -1 # subsample negative labels if we have too many num_bg = cfg.TRAIN.RPN_BATCHSIZE - np.sum(labels == 1) bg_inds = np.where(labels == 0)[0] if len(bg_inds) > num_bg: disable_inds = npr.choice( bg_inds, size=(len(bg_inds) - num_bg), replace=False) labels[disable_inds] = -1 bbox_targets = np.zeros((len(inds_inside), 4), dtype=np.float32) bbox_targets = _compute_targets(anchors, gt_boxes[argmax_overlaps, :]) bbox_inside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) # only the positive ones have regression targets bbox_inside_weights[labels == 1, :] = np.array(cfg.TRAIN.RPN_BBOX_INSIDE_WEIGHTS) bbox_outside_weights = np.zeros((len(inds_inside), 4), dtype=np.float32) if cfg.TRAIN.RPN_POSITIVE_WEIGHT < 0: # uniform weighting of examples (given non-uniform sampling) num_examples = np.sum(labels >= 0) positive_weights = np.ones((1, 4)) * 1.0 / num_examples negative_weights = np.ones((1, 4)) * 1.0 / num_examples else: assert ((cfg.TRAIN.RPN_POSITIVE_WEIGHT > 0) & (cfg.TRAIN.RPN_POSITIVE_WEIGHT < 1)) positive_weights = (cfg.TRAIN.RPN_POSITIVE_WEIGHT / np.sum(labels == 1)) negative_weights = ((1.0 - cfg.TRAIN.RPN_POSITIVE_WEIGHT) / np.sum(labels == 0)) bbox_outside_weights[labels == 1, :] = positive_weights bbox_outside_weights[labels == 0, :] = negative_weights # map up to original set of anchors labels = _unmap(labels, total_anchors, inds_inside, fill=-1) bbox_targets = _unmap(bbox_targets, total_anchors, inds_inside, fill=0) bbox_inside_weights = _unmap(bbox_inside_weights, total_anchors, inds_inside, fill=0) bbox_outside_weights = _unmap(bbox_outside_weights, total_anchors, inds_inside, fill=0) # labels labels = labels.reshape((1, height, width, A)).transpose(0, 3, 1, 2) labels = labels.reshape((1, 1, A * height, width)) rpn_labels = labels # bbox_targets bbox_targets = bbox_targets \ .reshape((1, height, width, A * 4)) rpn_bbox_targets = bbox_targets # bbox_inside_weights bbox_inside_weights = bbox_inside_weights \ .reshape((1, height, width, A * 4)) rpn_bbox_inside_weights = bbox_inside_weights # bbox_outside_weights bbox_outside_weights = bbox_outside_weights \ .reshape((1, height, width, A * 4)) rpn_bbox_outside_weights = bbox_outside_weights return rpn_labels, rpn_bbox_targets, rpn_bbox_inside_weights, rpn_bbox_outside_weights def _unmap(data, count, inds, fill=0): """ Unmap a subset of item (data) back to the original set of items (of size count) """ if len(data.shape) == 1: ret = np.empty((count,), dtype=np.float32) ret.fill(fill) ret[inds] = data else: ret = np.empty((count,) + data.shape[1:], dtype=np.float32) ret.fill(fill) ret[inds, :] = data return ret def _compute_targets(ex_rois, gt_rois): """Compute bounding-box regression targets for an image.""" assert ex_rois.shape[0] == gt_rois.shape[0] assert ex_rois.shape[1] == 4 assert gt_rois.shape[1] == 5 return bbox_transform(ex_rois, gt_rois[:, :4]).astype(np.float32, copy=False)
6,031
35.780488
98
py
RGB-N
RGB-N-master/lib/layer_utils/__init__.py
0
0
0
py
RGB-N
RGB-N-master/lib/utils/nms.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import numpy as np def nms(dets, thresh): x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep
1,008
25.552632
59
py
RGB-N
RGB-N-master/lib/utils/timer.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import time class Timer(object): """A simple timer.""" def __init__(self): self.total_time = 0. self.calls = 0 self.start_time = 0. self.diff = 0. self.average_time = 0. def tic(self): # using time.time instead of time.clock because time time.clock # does not normalize for multithreading self.start_time = time.time() def toc(self, average=True): self.diff = time.time() - self.start_time self.total_time += self.diff self.calls += 1 self.average_time = self.total_time / self.calls if average: return self.average_time else: return self.diff
948
27.757576
71
py
RGB-N
RGB-N-master/lib/utils/boxes_grid.py
# -------------------------------------------------------- # Subcategory CNN # Copyright (c) 2015 CVGL Stanford # Licensed under The MIT License [see LICENSE for details] # Written by Yu Xiang # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import math from model.config import cfg def get_boxes_grid(image_height, image_width): """ Return the boxes on image grid. """ # height and width of the heatmap if cfg.NET_NAME == 'CaffeNet': height = np.floor((image_height * max(cfg.TRAIN.SCALES) - 1) / 4.0 + 1) height = np.floor((height - 1) / 2.0 + 1 + 0.5) height = np.floor((height - 1) / 2.0 + 1 + 0.5) width = np.floor((image_width * max(cfg.TRAIN.SCALES) - 1) / 4.0 + 1) width = np.floor((width - 1) / 2.0 + 1 + 0.5) width = np.floor((width - 1) / 2.0 + 1 + 0.5) elif cfg.NET_NAME == 'VGGnet': height = np.floor(image_height * max(cfg.TRAIN.SCALES) / 2.0 + 0.5) height = np.floor(height / 2.0 + 0.5) height = np.floor(height / 2.0 + 0.5) height = np.floor(height / 2.0 + 0.5) width = np.floor(image_width * max(cfg.TRAIN.SCALES) / 2.0 + 0.5) width = np.floor(width / 2.0 + 0.5) width = np.floor(width / 2.0 + 0.5) width = np.floor(width / 2.0 + 0.5) else: assert (1), 'The network architecture is not supported in utils.get_boxes_grid!' # compute the grid box centers h = np.arange(height) w = np.arange(width) y, x = np.meshgrid(h, w, indexing='ij') centers = np.dstack((x, y)) centers = np.reshape(centers, (-1, 2)) num = centers.shape[0] # compute width and height of grid box area = cfg.TRAIN.KERNEL_SIZE * cfg.TRAIN.KERNEL_SIZE aspect = cfg.TRAIN.ASPECTS # height / width num_aspect = len(aspect) widths = np.zeros((1, num_aspect), dtype=np.float32) heights = np.zeros((1, num_aspect), dtype=np.float32) for i in range(num_aspect): widths[0, i] = math.sqrt(area / aspect[i]) heights[0, i] = widths[0, i] * aspect[i] # construct grid boxes centers = np.repeat(centers, num_aspect, axis=0) widths = np.tile(widths, num).transpose() heights = np.tile(heights, num).transpose() x1 = np.reshape(centers[:, 0], (-1, 1)) - widths * 0.5 x2 = np.reshape(centers[:, 0], (-1, 1)) + widths * 0.5 y1 = np.reshape(centers[:, 1], (-1, 1)) - heights * 0.5 y2 = np.reshape(centers[:, 1], (-1, 1)) + heights * 0.5 boxes_grid = np.hstack((x1, y1, x2, y2)) / cfg.TRAIN.SPATIAL_SCALE return boxes_grid, centers[:, 0], centers[:, 1]
2,599
34.135135
84
py
RGB-N
RGB-N-master/lib/utils/blob.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Blob helper functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import cv2 def im_list_to_blob(ims): """Convert a list of images into a network input. Assumes images are already prepared (means subtracted, BGR order, ...). """ max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) blob = np.zeros((num_images, max_shape[0], max_shape[1], 3), dtype=np.float32) for i in range(num_images): im = ims[i] blob[i, 0:im.shape[0], 0:im.shape[1], :] = im return blob def prep_im_for_blob(im, pixel_means, target_size, max_size): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE if np.round(im_scale * im_size_max) > max_size: im_scale = float(max_size) / float(im_size_max) im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) return im, im_scale def prep_noise_for_blob(im, pixel_means, target_size, max_size): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE if np.round(im_scale * im_size_max) > max_size: im_scale = float(max_size) / float(im_size_max) im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) return im, im_scale
2,135
32.904762
73
py
RGB-N
RGB-N-master/lib/utils/__init__.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # --------------------------------------------------------
248
34.571429
58
py
RGB-N
RGB-N-master/lib/model/test.py
# -------------------------------------------------------- # Tensorflow Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import cv2 try: import cPickle as pickle except ImportError: import pickle import os import math from utils.timer import Timer from utils.cython_nms import nms, nms_new from utils.boxes_grid import get_boxes_grid from utils.blob import im_list_to_blob import pdb from model.config import cfg, get_output_dir from model.bbox_transform import clip_boxes, bbox_transform_inv def _get_image_blob(im): """Converts an image into a network input. Arguments: im (ndarray): a color image in BGR order Returns: blob (ndarray): a data blob holding an image pyramid im_scale_factors (list): list of image scales (relative to im) used in the image pyramid """ row,col,ch= im.shape mean = 0 var = 10 sigma = var**0.5 gauss = np.random.normal(mean,sigma,(row,col,ch)) gauss = gauss.reshape(row,col,ch) # jpeg #cv2.imwrite('b.jpg',im,[cv2.IMWRITE_JPEG_QUALITY, 70]) #pdb.set_trace() #im=cv2.imread('b.jpg') im_orig = im.astype(np.float32, copy=True) #im_orig = im_orig + gauss im_orig -= cfg.PIXEL_MEANS im_shape = im_orig.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) processed_ims = [] processed_noise = [] im_scale_factors = [] for target_size in cfg.TEST.SCALES: im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE if np.round(im_scale * im_size_max) > cfg.TEST.MAX_SIZE: im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max) im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) noise=im im_scale_factors.append(im_scale) processed_ims.append(im) processed_noise.append(noise) # Create a blob to hold the input images blob = im_list_to_blob(processed_ims) noise_blob = im_list_to_blob(processed_noise) return blob,noise_blob, np.array(im_scale_factors) def _get_blobs(im): """Convert an image and RoIs within that image into network inputs.""" blobs = {} blobs['data'],blobs['noise'], im_scale_factors = _get_image_blob(im) return blobs, im_scale_factors def _clip_boxes(boxes, im_shape): """Clip boxes to image boundaries.""" # x1 >= 0 boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0) # y1 >= 0 boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0) # x2 < im_shape[1] boxes[:, 2::4] = np.minimum(boxes[:, 2::4], im_shape[1] - 1) # y2 < im_shape[0] boxes[:, 3::4] = np.minimum(boxes[:, 3::4], im_shape[0] - 1) return boxes def _rescale_boxes(boxes, inds, scales): """Rescale boxes according to image rescaling.""" for i in range(boxes.shape[0]): boxes[i,:] = boxes[i,:] / scales[int(inds[i])] return boxes def im_detect(sess, net, im): blobs, im_scales = _get_blobs(im) assert len(im_scales) == 1, "Only single-image batch implemented" im_blob = blobs['data'] # seems to have height, width, and image scales # still not sure about the scale, maybe full image it is 1. blobs['im_info'] = np.array([[im_blob.shape[1], im_blob.shape[2], im_scales[0]]], dtype=np.float32) try: scores1, scores, bbox_pred, rois,feat,s = net.test_image(sess, blobs['data'], blobs['im_info']) except: scores1, scores, bbox_pred, rois,feat,s = net.test_image(sess, blobs['data'],blobs['noise'], blobs['im_info']) boxes = rois[:, 1:5] / im_scales[0] # print(scores.shape, bbox_pred.shape, rois.shape, boxes.shape) scores = np.reshape(scores, [scores.shape[0], -1]) bbox_pred = np.reshape(bbox_pred, [bbox_pred.shape[0], -1]) if cfg.TEST.BBOX_REG: # Apply bounding-box regression deltas box_deltas = bbox_pred pred_boxes = bbox_transform_inv(boxes, box_deltas) pred_boxes = _clip_boxes(pred_boxes, im.shape) else: # Simply repeat the boxes, once for each class pred_boxes = np.tile(boxes, (1, scores.shape[1])) return scores, pred_boxes,feat,s def apply_nms(all_boxes, thresh): """Apply non-maximum suppression to all predicted boxes output by the test_net method. """ num_classes = len(all_boxes) num_images = len(all_boxes[0]) nms_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)] for cls_ind in range(num_classes): for im_ind in range(num_images): dets = all_boxes[cls_ind][im_ind] if dets == []: continue x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] inds = np.where((x2 > x1) & (y2 > y1) & (scores > cfg.TEST.DET_THRESHOLD))[0] dets = dets[inds,:] if dets == []: continue keep = nms(dets, thresh) if len(keep) == 0: continue nms_boxes[cls_ind][im_ind] = dets[keep, :].copy() return nms_boxes def test_net(sess, net, imdb, weights_filename, max_per_image=100, thresh=0.0): np.random.seed(cfg.RNG_SEED) """Test a Fast R-CNN network on an image database.""" num_images = len(imdb.image_index) # all detections are collected into: # all_boxes[cls][image] = N x 5 array of detections in # (x1, y1, x2, y2, score) all_boxes = [[[] for _ in range(num_images)] for _ in range(imdb.num_classes)] output_dir = get_output_dir(imdb, weights_filename) if os.path.isfile(os.path.join(output_dir, 'detections.pkl')): all_boxes=pickle.load(open(os.path.join(output_dir, 'detections.pkl'),'r')) else: # timers _t = {'im_detect' : Timer(), 'misc' : Timer()} for i in range(num_images): im = cv2.imread(imdb.image_path_at(i)) _t['im_detect'].tic() scores, boxes,_ ,_ = im_detect(sess, net, im) _t['im_detect'].toc() _t['misc'].tic() # skip j = 0, because it's the background class for j in range(1, imdb.num_classes): inds = np.where(scores[:, j] > thresh)[0] cls_scores = scores[inds, j] cls_boxes = boxes[inds, j*4:(j+1)*4] cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \ .astype(np.float32, copy=False) keep = nms(cls_dets, cfg.TEST.NMS) cls_dets = cls_dets[keep, :] all_boxes[j][i] = cls_dets # Limit to max_per_image detections *over all classes* if max_per_image > 0: image_scores = np.hstack([all_boxes[j][i][:, -1] for j in range(1, imdb.num_classes)]) if len(image_scores) > max_per_image: image_thresh = np.sort(image_scores)[-max_per_image] for j in range(1, imdb.num_classes): keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0] all_boxes[j][i] = all_boxes[j][i][keep, :] _t['misc'].toc() print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \ .format(i + 1, num_images, _t['im_detect'].average_time, _t['misc'].average_time)) det_file = os.path.join(output_dir, 'detections_{:f}.pkl'.format(10)) with open(det_file, 'wb') as f: pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL) print('Evaluating detections') imdb.evaluate_detections(all_boxes, output_dir)
7,355
32.589041
114
py
RGB-N
RGB-N-master/lib/model/bbox_transform.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pdb from decimal import Decimal def bbox_transform(ex_rois, gt_rois): ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0 ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0 ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0 gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0 gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights targets_dw = np.log(gt_widths / ex_widths) targets_dh = np.log(gt_heights / ex_heights) targets = np.vstack( (targets_dx, targets_dy, targets_dw, targets_dh)).transpose() return targets def bbox_transform_inv(boxes, deltas): if boxes.shape[0] == 0: return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype) boxes = boxes.astype(deltas.dtype, copy=False) widths = boxes[:, 2] - boxes[:, 0] + 1.0 heights = boxes[:, 3] - boxes[:, 1] + 1.0 ctr_x = boxes[:, 0] + 0.5 * widths ctr_y = boxes[:, 1] + 0.5 * heights dx = deltas[:, 0::4] dy = deltas[:, 1::4] dw = deltas[:, 2::4] dh = deltas[:, 3::4] dh.astype(Decimal) dw.astype(Decimal) pred_ctr_x = dx * widths[:, np.newaxis] + ctr_x[:, np.newaxis] pred_ctr_y = dy * heights[:, np.newaxis] + ctr_y[:, np.newaxis] pred_w = np.exp(dw) * widths[:, np.newaxis] pred_h = np.exp(dh) * heights[:, np.newaxis] pred_boxes = np.zeros(deltas.shape, dtype=deltas.dtype) # x1 pred_boxes[:, 0::4] = pred_ctr_x - 0.5 * pred_w # y1 pred_boxes[:, 1::4] = pred_ctr_y - 0.5 * pred_h # x2 pred_boxes[:, 2::4] = pred_ctr_x + 0.5 * pred_w # y2 pred_boxes[:, 3::4] = pred_ctr_y + 0.5 * pred_h return pred_boxes def clip_boxes(boxes, im_shape): """ Clip boxes to image boundaries. """ # x1 >= 0 boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0) # y1 >= 0 boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0) # x2 < im_shape[1] boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0) # y2 < im_shape[0] boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0) return boxes
2,622
30.22619
77
py
RGB-N
RGB-N-master/lib/model/nms_wrapper.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function from model.config import cfg from nms.gpu_nms import gpu_nms from nms.cpu_nms import cpu_nms from nms.py_cpu_nms import py_cpu_nms def nms(dets, thresh, force_cpu=False): """Dispatch to either CPU or GPU NMS implementations.""" if dets.shape[0] == 0: return [] if cfg.USE_GPU_NMS and not force_cpu: return gpu_nms(dets, thresh, device_id=cfg.GPU_ID) else: return cpu_nms(dets, thresh)
764
30.875
58
py
RGB-N
RGB-N-master/lib/model/config.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import os.path as osp import numpy as np # `pip install easydict` if you don't have it from easydict import EasyDict as edict __C = edict() # Consumers can get config by: # from fast_rcnn_config import cfg cfg = __C # # Training options # __C.TRAIN = edict() # Initial learning rate __C.TRAIN.LEARNING_RATE = 0.001 # Momentum __C.TRAIN.MOMENTUM = 0.9 # Weight decay, for regularization __C.TRAIN.WEIGHT_DECAY = 0.0005 # Factor for reducing the learning rate __C.TRAIN.GAMMA = 0.1 # Step size for reducing the learning rate, currently only support one step __C.TRAIN.STEPSIZE = 30000 # Iteration intervals for showing the loss during training, on command line interface __C.TRAIN.DISPLAY = 10 # Whether to double the learning rate for bias __C.TRAIN.DOUBLE_BIAS = True # Whether to initialize the weights with truncated normal distribution __C.TRAIN.TRUNCATED = False # Whether to have weight decay on bias as well __C.TRAIN.BIAS_DECAY = False # Whether to add ground truth boxes to the pool when sampling regions __C.TRAIN.USE_GT = False # Whether to use aspect-ratio grouping of training images, introduced merely for saving # GPU memory __C.TRAIN.ASPECT_GROUPING = False # The number of snapshots kept, older ones are deleted to save space __C.TRAIN.SNAPSHOT_KEPT = 10 # The time interval for saving tensorflow summaries __C.TRAIN.SUMMARY_INTERVAL = 180 # Scale to use during training (can NOT list multiple scales) # The scale is the pixel size of an image's shortest side __C.TRAIN.SCALES = (600,) # Max pixel size of the longest side of a scaled input image __C.TRAIN.MAX_SIZE = 1000 # Images to use per minibatch __C.TRAIN.IMS_PER_BATCH = 1 # Minibatch size (number of regions of interest [ROIs]) __C.TRAIN.BATCH_SIZE = 128 # Fraction of minibatch that is labeled foreground (i.e. class > 0) __C.TRAIN.FG_FRACTION = 0.25 # Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) __C.TRAIN.FG_THRESH = 0.5 # Overlap threshold for a ROI to be considered background (class = 0 if # overlap in [LO, HI)) __C.TRAIN.BG_THRESH_HI = 0.5 __C.TRAIN.BG_THRESH_LO = 0.1 # Use horizontally-flipped images during training? __C.TRAIN.USE_FLIPPED = True # Train bounding-box regressors __C.TRAIN.BBOX_REG = True # Overlap required between a ROI and ground-truth box in order for that ROI to # be used as a bounding-box regression training example __C.TRAIN.BBOX_THRESH = 0.5 # Iterations between snapshots __C.TRAIN.SNAPSHOT_ITERS = 4000 # solver.prototxt specifies the snapshot path prefix, this adds an optional # infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel __C.TRAIN.SNAPSHOT_PREFIX = 'res101_faster_rcnn' # __C.TRAIN.SNAPSHOT_INFIX = '' # Use a prefetch thread in roi_data_layer.layer # So far I haven't found this useful; likely more engineering work is required # __C.TRAIN.USE_PREFETCH = False # Normalize the targets (subtract empirical mean, divide by empirical stddev) __C.TRAIN.BBOX_NORMALIZE_TARGETS = True # Deprecated (inside weights) __C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Normalize the targets using "precomputed" (or made up) means and stdevs # (BBOX_NORMALIZE_TARGETS must also be True) __C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = True __C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0) __C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2) # Train using these proposals __C.TRAIN.PROPOSAL_METHOD = 'gt' # Make minibatches from images that have similar aspect ratios (i.e. both # tall and thin or both short and wide) in order to avoid wasting computation # on zero-padding. # Use RPN to detect objects __C.TRAIN.HAS_RPN = True # IOU >= thresh: positive example __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # If an anchor statisfied by positive and negative conditions set to negative __C.TRAIN.RPN_CLOBBER_POSITIVES = False # Max number of foreground examples __C.TRAIN.RPN_FG_FRACTION = 0.5 # Total number of examples __C.TRAIN.RPN_BATCHSIZE = 256 # NMS threshold used on RPN proposals __C.TRAIN.RPN_NMS_THRESH = 0.7 # Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) # __C.TRAIN.RPN_MIN_SIZE = 16 # Deprecated (outside weights) __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Give the positive RPN examples weight of p * 1 / {num positives} # and give negatives a weight of (1 - p) # Set to -1.0 to use uniform example weighting __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 # Whether to use all ground truth bounding boxes for training, # For COCO, setting USE_ALL_GT to False will exclude boxes that are flagged as ''iscrowd'' __C.TRAIN.USE_ALL_GT = True __C.TRAIN.FUSE = True __C.TRAIN.USE_NOISE = False __C.TRAIN.USE_NOISE_AUG = False __C.TRAIN.USE_JPG_AUG = False __C.TRAIN.HNM = False # # Testing options # __C.TEST = edict() # Scale to use during testing (can NOT list multiple scales) # The scale is the pixel size of an image's shortest side __C.TEST.SCALES = (600,) # Max pixel size of the longest side of a scaled input image __C.TEST.MAX_SIZE = 1000 # Overlap threshold used for non-maximum suppression (suppress boxes with # IoU >= this threshold) __C.TEST.NMS = 0.2 # Experimental: treat the (K+1) units in the cls_score layer as linear # predictors (trained, eg, with one-vs-rest SVMs). __C.TEST.SVM = False # Test using bounding-box regressors __C.TEST.BBOX_REG = True # Propose boxes __C.TEST.HAS_RPN = False # Test using these proposals __C.TEST.PROPOSAL_METHOD = 'gt' ## NMS threshold used on RPN proposals __C.TEST.RPN_NMS_THRESH = 0.7 ## Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TEST.RPN_PRE_NMS_TOP_N = 6000 ## Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TEST.RPN_POST_NMS_TOP_N = 100 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) # __C.TEST.RPN_MIN_SIZE = 16 # Testing mode, default to be 'nms', 'top' is slower but better # See report for details __C.TEST.MODE = 'nms' # Only useful when TEST.MODE is 'top', specifies the number of top proposals to select __C.TEST.RPN_TOP_N = 5000 # # ResNet options # __C.RESNET = edict() # Option to set if max-pooling is appended after crop_and_resize. # if true, the region will be resized to a squre of 2xPOOLING_SIZE, # then 2x2 max-pooling is applied; otherwise the region will be directly # resized to a square of POOLING_SIZE __C.RESNET.MAX_POOL = False # Number of fixed blocks during finetuning, by default the first of all 4 blocks is fixed # Range: 0 (none) to 3 (all) __C.RESNET.FIXED_BLOCKS = 1 # Whether to tune the batch nomalization parameters during training __C.RESNET.BN_TRAIN = False # # MISC # # The mapping from image coordinates to feature map coordinates might cause # some boxes that are distinct in image space to become identical in feature # coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor # for identifying duplicate boxes. # 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16 __C.DEDUP_BOXES = 1. / 16. # Pixel mean values (BGR order) as a (1, 1, 3) array # We use the same pixel mean for all networks even though it's not exactly what # they were trained with __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # For reproducibility __C.RNG_SEED = 3 # A small number that's used many times __C.EPS = 1e-14 # Root directory of project __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # Data directory __C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data')) # Name (or path to) the matlab executable __C.MATLAB = 'matlab' # Place outputs under an experiments directory __C.EXP_DIR = 'default' # Use GPU implementation of non-maximum suppression __C.USE_GPU_NMS = True # Default GPU device id __C.GPU_ID = 0 # Default pooling mode, only 'crop' is available __C.POOLING_MODE = 'crop' # Size of the pooled region after RoI pooling __C.POOLING_SIZE = 7 # Anchor scales for RPN __C.ANCHOR_SCALES = [8,16,32] # Anchor ratios for RPN __C.ANCHOR_RATIOS = [0.5,1,2] def get_output_dir(imdb, weights_filename): """Return the directory where experimental artifacts are placed. If the directory does not exist, it is created. A canonical path is built using the name from an imdb and a network (if not None). """ outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name)) if weights_filename is None: weights_filename = 'default' outdir = osp.join(outdir, weights_filename) if not os.path.exists(outdir): os.makedirs(outdir) return outdir def get_output_tb_dir(imdb, weights_filename): """Return the directory where tensorflow summaries are placed. If the directory does not exist, it is created. A canonical path is built using the name from an imdb and a network (if not None). """ outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'tensorboard', __C.EXP_DIR, imdb.name)) if weights_filename is None: weights_filename = 'default' outdir = osp.join(outdir, weights_filename) if not os.path.exists(outdir): os.makedirs(outdir) return outdir def _merge_a_into_b(a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.items(): # a must specify keys that are in b if k not in b: raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too old_type = type(b[k]) if old_type is not type(v): if isinstance(b[k], np.ndarray): v = np.array(v, dtype=b[k].dtype) else: raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k], b[k]) except: print(('Error under config key: {}'.format(k))) raise else: b[k] = v def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C) def cfg_from_list(cfg_list): """Set config keys via list (e.g., from command line).""" from ast import literal_eval assert len(cfg_list) % 2 == 0 for k, v in zip(cfg_list[0::2], cfg_list[1::2]): key_list = k.split('.') d = __C for subkey in key_list[:-1]: assert subkey in d d = d[subkey] subkey = key_list[-1] assert subkey in d try: value = literal_eval(v) except: # handle the case when v is a string literal value = v assert type(value) == type(d[subkey]), \ 'type {} does not match original type {}'.format( type(value), type(d[subkey])) d[subkey] = value
11,267
29.209115
91
py
RGB-N
RGB-N-master/lib/model/__init__.py
from . import config
21
10
20
py
RGB-N
RGB-N-master/lib/model/train_val.py
# -------------------------------------------------------- # Tensorflow RGB-N # Licensed under The MIT License [see LICENSE for details] # Written by Peng Zhou , based on code from Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future__ import print_function from model.config import cfg import roi_data_layer.roidb as rdl_roidb from roi_data_layer.layer import RoIDataLayer from utils.timer import Timer try: import cPickle as pickle except ImportError: import pickle import numpy as np import os import sys import glob import time import pdb import tensorflow as tf from tensorflow.python import pywrap_tensorflow class SolverWrapper(object): """ A wrapper class for the training process """ def __init__(self, sess, network, imdb, roidb, valroidb, output_dir, tbdir, pretrained_model=None): self.net = network self.imdb = imdb self.roidb = roidb self.valroidb = valroidb self.output_dir = output_dir self.tbdir = tbdir # Simply put '_val' at the end to save the summaries from the validation set self.tbvaldir = tbdir + '_val' if not os.path.exists(self.tbvaldir): os.makedirs(self.tbvaldir) self.pretrained_model = pretrained_model def snapshot(self, sess, iter): net = self.net if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) # Store the model snapshot filename = cfg.TRAIN.SNAPSHOT_PREFIX + '_iter_{:d}'.format(iter) + '.ckpt' filename = os.path.join(self.output_dir, filename) self.saver.save(sess, filename) print('Wrote snapshot to: {:s}'.format(filename)) # Also store some meta information, random state, etc. nfilename = cfg.TRAIN.SNAPSHOT_PREFIX + '_iter_{:d}'.format(iter) + '.pkl' nfilename = os.path.join(self.output_dir, nfilename) # current state of numpy random st0 = np.random.get_state() # current position in the database cur = self.data_layer._cur # current shuffled indeces of the database perm = self.data_layer._perm # current position in the validation database cur_val = self.data_layer_val._cur # current shuffled indeces of the validation database perm_val = self.data_layer_val._perm # Dump the meta info with open(nfilename, 'wb') as fid: pickle.dump(st0, fid, pickle.HIGHEST_PROTOCOL) pickle.dump(cur, fid, pickle.HIGHEST_PROTOCOL) pickle.dump(perm, fid, pickle.HIGHEST_PROTOCOL) pickle.dump(cur_val, fid, pickle.HIGHEST_PROTOCOL) pickle.dump(perm_val, fid, pickle.HIGHEST_PROTOCOL) pickle.dump(iter, fid, pickle.HIGHEST_PROTOCOL) return filename, nfilename def get_variables_in_checkpoint_file(self, file_name): try: reader = pywrap_tensorflow.NewCheckpointReader(file_name) var_to_shape_map = reader.get_variable_to_shape_map() return var_to_shape_map except Exception as e: # pylint: disable=broad-except print(str(e)) if "corrupted compressed block contents" in str(e): print("It's likely that your checkpoint file has been compressed " "with SNAPPY.") def train_model(self, sess, max_iters): # Build data layers for both training and validation set self.data_layer = RoIDataLayer(self.roidb, self.imdb.num_classes) self.data_layer_val = RoIDataLayer(self.valroidb, self.imdb.num_classes, random=True) # Determine different scales for anchors, see paper with sess.graph.as_default(): # Set the random seed for tensorflow tf.set_random_seed(cfg.RNG_SEED) # Build the main computation graph layers = self.net.create_architecture(sess, 'TRAIN', self.imdb.num_classes, tag='default', anchor_scales=cfg.ANCHOR_SCALES, anchor_ratios=cfg.ANCHOR_RATIOS) # Define the loss loss = layers['total_loss'] # Set learning rate and momentum lr = tf.Variable(cfg.TRAIN.LEARNING_RATE, trainable=False) momentum = cfg.TRAIN.MOMENTUM self.optimizer = tf.train.MomentumOptimizer(lr, momentum) # Compute the gradients wrt the loss gvs = self.optimizer.compute_gradients(loss) # Double the gradient of the bias if set if cfg.TRAIN.DOUBLE_BIAS: final_gvs = [] with tf.variable_scope('Gradient_Mult') as scope: for grad, var in gvs: scale = 1. if cfg.TRAIN.DOUBLE_BIAS and '/biases:' in var.name: scale *= 2. if not np.allclose(scale, 1.0): grad = tf.multiply(grad, scale) final_gvs.append((tf.clip_by_value(grad,-5.0,5.0), var)) train_op = self.optimizer.apply_gradients(final_gvs) else: train_op = self.optimizer.apply_gradients(gvs) # We will handle the snapshots ourselves self.saver = tf.train.Saver(max_to_keep=100000) # Write the train and validation information to tensorboard self.writer = tf.summary.FileWriter(self.tbdir, sess.graph) self.valwriter = tf.summary.FileWriter(self.tbvaldir) # Find previous snapshots if there is any to restore from sfiles = os.path.join(self.output_dir, cfg.TRAIN.SNAPSHOT_PREFIX + '_iter_*.ckpt.meta') sfiles = glob.glob(sfiles) sfiles.sort(key=os.path.getmtime) # Get the snapshot name in TensorFlow redstr = '_iter_{:d}.'.format(cfg.TRAIN.STEPSIZE+1) sfiles = [ss.replace('.meta', '') for ss in sfiles] sfiles = [ss for ss in sfiles if redstr not in ss] nfiles = os.path.join(self.output_dir, cfg.TRAIN.SNAPSHOT_PREFIX + '_iter_*.pkl') nfiles = glob.glob(nfiles) nfiles.sort(key=os.path.getmtime) nfiles = [nn for nn in nfiles if redstr not in nn] lsf = len(sfiles) assert len(nfiles) == lsf np_paths = nfiles ss_paths = sfiles if lsf == 0: # Fresh train directly from ImageNet weights print('Loading initial model weights from {:s}'.format(self.pretrained_model)) variables = tf.global_variables() # Initialize all variables first sess.run(tf.variables_initializer(variables, name='init')) var_keep_dic = self.get_variables_in_checkpoint_file(self.pretrained_model) # Get the variables to restore, ignorizing the variables to fix variables_to_restore = self.net.get_variables_to_restore(variables, var_keep_dic) restorer = tf.train.Saver(variables_to_restore) restorer.restore(sess, self.pretrained_model) print('Loaded.') if cfg.TRAIN.FUSE: noise_vars={} for v in variables: if v.name.split('/')[0]=='noise' and v.name.split(':')[0].replace('noise','resnet_v1_101',1) in var_keep_dic: noise_vars[v.name.split(':')[0].replace('noise','resnet_v1_101',1)]=v noise_restorer = tf.train.Saver(noise_vars) noise_restorer.restore(sess, self.pretrained_model) # Need to fix the variables before loading, so that the RGB weights are changed to BGR # For VGG16 it also changes the convolutional weights fc6 and fc7 to # fully connected weights self.net.fix_variables(sess, self.pretrained_model) print('Fixed.') sess.run(tf.assign(lr, cfg.TRAIN.LEARNING_RATE)) last_snapshot_iter = 0 else: # Get the most recent snapshot and restore ss_paths = [ss_paths[-1]] np_paths = [np_paths[-1]] print('Restorining model snapshots from {:s}'.format(sfiles[-1])) self.saver.restore(sess, str(sfiles[-1])) print('Restored.') # Needs to restore the other hyperparameters/states for training, (TODO xinlei) I have # tried my best to find the random states so that it can be recovered exactly # However the Tensorflow state is currently not available with open(str(nfiles[-1]), 'rb') as fid: st0 = pickle.load(fid) cur = pickle.load(fid) perm = pickle.load(fid) cur_val = pickle.load(fid) perm_val = pickle.load(fid) last_snapshot_iter = pickle.load(fid) np.random.set_state(st0) self.data_layer._cur = cur self.data_layer._perm = perm self.data_layer_val._cur = cur_val self.data_layer_val._perm = perm_val # Set the learning rate, only reduce once if last_snapshot_iter > cfg.TRAIN.STEPSIZE: sess.run(tf.assign(lr, cfg.TRAIN.LEARNING_RATE * cfg.TRAIN.GAMMA)) else: sess.run(tf.assign(lr, cfg.TRAIN.LEARNING_RATE)) timer = Timer() iter = last_snapshot_iter + 1 last_summary_time = time.time() while iter < max_iters + 1: # Learning rate if iter == cfg.TRAIN.STEPSIZE + 1: # Add snapshot here before reducing the learning rate self.snapshot(sess, iter) sess.run(tf.assign(lr, cfg.TRAIN.LEARNING_RATE * cfg.TRAIN.GAMMA)) timer.tic() # Get training data, one batch at a time blobs = self.data_layer.forward() now = time.time() if now - last_summary_time > cfg.TRAIN.SUMMARY_INTERVAL: # Compute the graph with summary rpn_loss_cls, rpn_loss_box, loss_cls, loss_box, total_loss, summary = \ self.net.train_step_with_summary(sess, blobs, train_op) self.writer.add_summary(summary, float(iter)) # Also check the summary on the validation set blobs_val = self.data_layer_val.forward() summary_val = self.net.get_summary(sess, blobs_val) self.valwriter.add_summary(summary_val, float(iter)) last_summary_time = now else: # Compute the graph without summary rpn_loss_cls, rpn_loss_box, loss_cls, loss_box, total_loss = \ self.net.train_step(sess, blobs, train_op) timer.toc() # Display training information if iter % (cfg.TRAIN.DISPLAY) == 0: print('iter: %d / %d, total loss: %.6f\n >>> rpn_loss_cls: %.6f\n ' '>>> rpn_loss_box: %.6f\n >>> loss_cls: %.6f\n >>> loss_box: %.6f\n >>> lr: %f' % \ (iter, max_iters, total_loss, rpn_loss_cls, rpn_loss_box, loss_cls, loss_box, lr.eval())) print('speed: {:.3f}s / iter'.format(timer.average_time)) if iter % cfg.TRAIN.SNAPSHOT_ITERS == 0: last_snapshot_iter = iter snapshot_path, np_path = self.snapshot(sess, iter) np_paths.append(np_path) ss_paths.append(snapshot_path) # Remove the old snapshots if there are too many if len(np_paths) > cfg.TRAIN.SNAPSHOT_KEPT: to_remove = len(np_paths) - cfg.TRAIN.SNAPSHOT_KEPT for c in range(to_remove): nfile = np_paths[0] os.remove(str(nfile)) np_paths.remove(nfile) if len(ss_paths) > cfg.TRAIN.SNAPSHOT_KEPT: to_remove = len(ss_paths) - cfg.TRAIN.SNAPSHOT_KEPT for c in range(to_remove): sfile = ss_paths[0] # To make the code compatible to earlier versions of Tensorflow, # where the naming tradition for checkpoints are different if os.path.exists(str(sfile)): os.remove(str(sfile)) else: os.remove(str(sfile + '.data-00000-of-00001')) os.remove(str(sfile + '.index')) sfile_meta = sfile + '.meta' os.remove(str(sfile_meta)) ss_paths.remove(sfile) iter += 1 if last_snapshot_iter != iter - 1: self.snapshot(sess, iter - 1) self.writer.close() self.valwriter.close() def get_training_roidb(imdb): """Returns a roidb (Region of Interest database) for use in training.""" if cfg.TRAIN.USE_FLIPPED: print('Appending horizontally-flipped training examples...') imdb.append_flipped_images() print('done') if cfg.TRAIN.USE_NOISE_AUG: print('Appending noise to training examples...') imdb.append_noise_images() print('done') if cfg.TRAIN.USE_JPG_AUG: print('Appending jpg compression to training examples...') imdb.append_jpg_images() print('done') print('Preparing training data...') rdl_roidb.prepare_roidb(imdb) print('done') return imdb.roidb def filter_roidb(roidb): """Remove roidb entries that have no usable RoIs.""" def is_valid(entry): # Valid images have: # (1) At least one foreground RoI OR # (2) At least one background RoI overlaps = entry['max_overlaps'] # find boxes with sufficient overlap fg_inds = np.where(overlaps >= cfg.TRAIN.FG_THRESH)[0] # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO))[0] # image is only valid if such boxes exist valid = len(fg_inds) > 0 or len(bg_inds) > 0 return valid num = len(roidb) filtered_roidb = [entry for entry in roidb if is_valid(entry)] num_after = len(filtered_roidb) print('Filtered {} roidb entries: {} -> {}'.format(num - num_after, num, num_after)) return filtered_roidb def train_net(network, imdb, roidb, valroidb, output_dir, tb_dir, pretrained_model=None, max_iters=40000): """Train a Fast R-CNN network.""" roidb = filter_roidb(roidb) valroidb = filter_roidb(valroidb) tfconfig = tf.ConfigProto(allow_soft_placement=True) tfconfig.gpu_options.allow_growth = True with tf.Session(config=tfconfig) as sess: sw = SolverWrapper(sess, network, imdb, roidb, valroidb, output_dir, tb_dir, pretrained_model=pretrained_model) print('Solving...') sw.train_model(sess, max_iters) print('done solving')
13,708
37.835694
119
py
RGB-N
RGB-N-master/lib/nms/py_cpu_nms.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import numpy as np def py_cpu_nms(dets, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep
1,051
25.974359
59
py
RGB-N
RGB-N-master/lib/nms/__init__.py
0
0
0
py
RGB-N
RGB-N-master/coco_synthetic/split_train_test.py
import networkx as nx import numpy as np import os from glob import glob import sys import skimage.io as io import pdb def contain_node(Graph_list,node): for g in Graph_list: if g.has_node(node): return True return False data_dir='../../dataset/filter_tamper' #FIXME ext='Tp*' dataDir='../../dataset' #FIXME dataType='train2014' #COCO2014 train directory #cls=['person','tv','airplane','dog','bench','train','kite','bed','refrigerator','bowl'] cls=['person','airplane','dog','train','bed','refrigerator'] filenames=glob(os.path.join(data_dir,ext)) G=nx.Graph() print(len(filenames)) for file in filenames: content=os.path.splitext(os.path.basename(file))[0].split("_") if content[-1] in cls: target_name=content[1] source_name=content[2] G.add_edge(target_name,source_name) train = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0:950] test=sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[950:] with open('train_filter.txt','w') as f: for file in filenames: content=os.path.splitext(os.path.basename(a))[0].split("_") if content[-1] in cls: target_name=content[1] source_name=content[2] if target_name!= source_name and contain_node(train,target_name) and contain_node(train,source_name): x1=float(content[3]) y1=float(content[4]) x2=float(content[5]) y2=float(content[6]) source_img=io.imread(os.path.join(dataDir,dataType,'COCO_train2014_{:012d}.jpg'.format(int(source_name)))) target_img=io.imread(os.path.join(dataDir,dataType,'COCO_train2014_{:012d}.jpg'.format(int(target_name)))) s_w,s_h = source_img.shape[:2] t_w,t_h = target_img.shape[:2] f.write('%s %.5f %.5f %.5f %.5f\n' % (file,x1*s_h/t_h,y1*s_w/t_w,x2*s_h/t_h,y2*s_w/t_w) ) with open('test_filter.txt','w') as f: for file in filenames: content=os.path.splitext(os.path.basename(file))[0].split("_") if content[-1] in cls: target_name=content[1] source_name=content[2] if target_name!= source_name and contain_node(test,target_name) and contain_node(test,source_name): x1=float(content[3]) y1=float(content[4]) x2=float(content[5]) y2=float(content[6]) source_img=io.imread(os.path.join(dataDir,dataType,'COCO_train2014_{:012d}.jpg'.format(int(source_name)))) target_img=io.imread(os.path.join(dataDir,dataType,'COCO_train2014_{:012d}.jpg'.format(int(target_name)))) s_w,s_h = source_img.shape[:2] t_w,t_h = target_img.shape[:2] f.write('%s %.5f %.5f %.5f %.5f\n' % (file,x1*s_h/t_h,y1*s_w/t_w,x2*s_h/t_h,y2*s_w/t_w))
2,551
33.486486
110
py
RGB-N
RGB-N-master/coco_synthetic/demo.py
from pycocotools.coco import COCO import numpy as np import cv2 import skimage.io as io import matplotlib.pyplot as plt import pylab import os from PIL import Image from PIL import ImageFilter import argparse import sys import pdb def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='input begin and end category') parser.add_argument('--begin', dest='begin', help='begin type of cat', default=None, type=int) parser.add_argument('--end', dest='end', help='begin type of cat', default=None, type=int) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args args=parse_args() print(args.begin) pylab.rcParams['figure.figsize'] = (10.0, 8.0) dataDir='..' dataType='train2014' annFile='%s/annotations/instances_%s.json'%(dataDir,dataType) coco=COCO(annFile) cats = coco.loadCats(coco.getCatIds()) for cat in cats[args.begin:args.end]: for num in range(2000): try: catIds = coco.getCatIds(catNms=[cat['name']]); imgIds = coco.getImgIds(catIds=catIds ); img = coco.loadImgs(imgIds[np.random.randint(0,len(imgIds))])[0] #I = io.imread('http://mscoco.org/images/%d'%(img['id'])) #I = io.imread(img['coco_url']) I=io.imread(os.path.join(dataDir,dataType,'COCO_train2014_{:012d}.jpg'.format(img['id']))) #plt.imshow(I); plt.axis('off') annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) anns = coco.loadAnns(annIds) #coco.showAnns(anns) bbx=anns[0]['bbox'] mask=np.array(coco.annToMask(anns[0])) print(np.shape(mask)) print(np.shape(I)) #pdb.set_trace() I1=I #row,col=np.where(mask>0) #print(row) #print(col) #I1=I[row,col,0] #print(np.shape(I1)) I1[:,:,0]=np.array(I[:,:,0] * mask ) I1[:,:,1]=np.array(I[:,:,1] * mask ) I1[:,:,2]=np.array(I[:,:,2] * mask ) #pdb.set_trace() rand=np.random.randint(100,size=1)[0] #flag=0 #I1=cv2.GaussianBlur(I1,(5,5),0) #flag=1 img1 = coco.loadImgs(imgIds[np.random.randint(0,len(imgIds))])[0] #b1 = io.imread('http://mscoco.org/images/%d'%(img1['id'])) #b1 = io.imread(img1['coco_url']) b1=io.imread(os.path.join(dataDir,dataType,'COCO_train2014_{:012d}.jpg'.format(img1['id']))) text_img = Image.new('RGBA', (np.shape(b1)[0],np.shape(b1)[1]), (0, 0, 0, 0)) background=Image.fromarray(b1,'RGB') foreground=Image.fromarray(I1,'RGB').convert('RGBA') datas=foreground.getdata() #pdb.set_trace() newData = [] for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: newData.append((0, 0, 0, 0)) else: newData.append(item) foreground.putdata(newData) foreground=foreground.resize((background.size[0],background.size[1]),Image.ANTIALIAS) background.paste(foreground,(0,0),mask=foreground.split()[3]) if rand%3<2: background=background.filter(ImageFilter.GaussianBlur(radius=1.5)) #pdb.set_trace() if not os.path.isfile('../filter_tamper/Tp_'+str(img['id'])+'_'+str(img1['id'])+'_'+str(bbx[0])+'_'+str(bbx[1])+'_'+str(bbx[0]+bbx[2])+'_'+str(bbx[1]+bbx[3])+'_'+cat['name']+'.png'): io.imsave('../filter_tamper/Tp_'+str(img['id'])+'_'+str(img1['id'])+'_'+str(bbx[0])+'_'+str(bbx[1])+'_'+str(bbx[0]+bbx[2])+'_'+str(bbx[1]+bbx[3])+'_'+cat['name']+'.png',background) except Exception as e: print(e) print('finished') #I1=np.array([[I[i,j,:] for j in range(len(I[i,:,0])) if mask[i,j]]for i in range(len(I[:,:,0]))])
3,500
34.363636
185
py
SOCC
SOCC-master/scripts/socc_comment_profilling.py
import pandas as pd import ast import datetime import numpy as np """ Note: This script file is specific designed for SOCC_DATA/raw/gnm_comment_threads.csv, which can be find in "https://github.com/sfu-discourse-lab/SOCC" """ def posted_comments(df): """ count the posted comments of each user Args: df: pandas dataframe (for gnm_comment_threads.csv only) Returns: a dataframe with two columns ['comment_author', 'count'] """ return df[['comment_author','comment_id']].drop_duplicates().\ groupby(['comment_author']).agg(['count']) def thread_participated(df): """ count the number of threads that each user participated in Args: df: pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with two columns ['comment_author', 'count_thread_participated'] """ df['articleID_threadID'] = pd.Series(df.comment_counter.\ apply(lambda x: "_".join(x.split('_')[1:3]))) return df[['comment_author', 'articleID_threadID']].\ drop_duplicates().groupby(['comment_author']).count() def threads_initiated(df): """ count the number of threads that each user initiated Args: df: pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with two columns ['comment_author', 'count_thread_initiated'] """ df['is_initiated_threads'] = df['comment_counter'].apply(lambda x:len(x.split('_'))==3) return df[['comment_author', 'is_initiated_threads']].groupby(['comment_author']).sum() def pos_votes_count(df): """ count the number of positive votes that each user gained Args: df: pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with two columns ['comment_author', 'pos_votes_count'] """ return df[['comment_author', 'posVotes']].groupby('comment_author').sum() def neg_votes_count(df): """ count the number of positive votes that each user gained Args: df: pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with two columns ['comment_author', 'neg_votes_count'] """ return df[['comment_author', 'negVotes']].groupby('comment_author').sum() def _find_all_reactions_types(df): """ This is the helper function from all the reactions, find all kind of reactions types Args: df_reactions: reaction_list column in pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with two columns ['comment_author', 'reaction_types_count'] """ reaction_is_null = df.reactions.isnull() reactions = [] for i in range(len(df.reactions)): if not reaction_is_null[i] and len(df.reactions[i]) > 2: reaction_list = ast.literal_eval(df.reactions[i])['reaction_list'] for rlist in reaction_list: reactions.append(rlist['reaction']) return list(set(reactions)) def _find_all_reactions_count(reaction_list): """ This is the helper function for each reaction list, find the reaction count Args: df: pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with two columns ['comment_author', 'reaction_types_count'] """ reactions_count = {} for rlist in reaction_list: if rlist['reaction'] in reactions_count: reactions_count[rlist['reaction']] += 1 else: reactions_count[rlist['reaction']] = 1 return reactions_count def reactions_count(df): """ count the reactions that each user gained among the reaction lists Args: df: pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with two columns ['comment_author', 'reaction_types_count'] """ result = pd.DataFrame(df.comment_author.drop_duplicates().reset_index(drop=True)) reaction_types = _find_all_reactions_types(df) #print(reaction_types) for i in reaction_types: df[i] = 0 df['reaction_counts'] = 0 reaction_is_null = df.reactions.isnull() for i in range(len(df.reactions)): if not reaction_is_null[i] and df.reactions[i] != '{}': reactions = ast.literal_eval(df.iloc[i]['reactions']) df.loc[i, 'reaction_counts'] = int(reactions['reaction_counts'][-1].split()[-1]) reaction_list = _find_all_reactions_count(reactions['reaction_list']) for k in reaction_list.keys(): #print(k) TEST PURPOSE df.loc[i, k] = int(reaction_list[k]) for t in reaction_types: raction_type_sum = df[['comment_author', t]].groupby('comment_author').sum() result = result.join(raction_type_sum, on = 'comment_author') raction_count_sum = df[['comment_author', 'reaction_counts']].groupby('comment_author').sum() result = result.join(raction_count_sum, on = 'comment_author') return result def yearly_count(df): """ for each user, count the number of posted comment every year Args: df: pandas dataframe (for gnm_comment_threads.csv only) Return: a dataframe with few columns ['comment_author', 'comments_posted_in_years', 'yearly_frequency'] """ timestamp_df = df[['comment_author','timestamp']].dropna() timestamp_df['year'] = timestamp_df['timestamp'].dropna().\ apply(lambda x: datetime.datetime.fromtimestamp(int(x)/1000).year) #timestamp_df['thread_year'] = timestamp_df['threadTimestamp'].dropna().apply(lambda x: datetime.datetime.fromtimestamp(int(x)/1000).year) counts = timestamp_df[['comment_author', 'year']].dropna()\ .groupby(['comment_author', 'year']).size() counts = pd.DataFrame(counts, columns = ['count']) yearly_counts = pd.pivot_table(counts, values='count', \ index=['comment_author'], columns=['year'], aggfunc=np.sum) yearly_counts.columns = ['comments_posted_in_' + str(n) for n in yearly_counts.columns] yearly_counts['yearly_frequency'] = yearly_counts.sum(axis=1)/len(yearly_counts.columns) return yearly_counts def main(path): df = pd.read_csv('Data/raw/gnm_comment_threads.csv').drop_duplicates() result = pd.DataFrame(df.comment_author.drop_duplicates().reset_index(drop=True)) result = result.join(posted_comments(df), on = 'comment_author') result = result.join(thread_participated(df), on = 'comment_author') result = result.join(threads_initiated(df), on = 'comment_author') result = result.join(pos_votes_count(df), on = 'comment_author') result = result.join(neg_votes_count(df), on = 'comment_author') result = result.join(reactions_count(df).set_index('comment_author'), on = 'comment_author') result = result.join(yearly_count(df), on = 'comment_author') result.columns = ['comment_author','posted_comments_count', \ 'participated_threads_count', 'initiated_thread_count', \ 'posVotes_num', 'negVotes_num'] + list(result.columns[6:]) result.to_csv('commenter_profiles.csv', index=False) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='count the comment profilling') parser.add_argument('gnm_comment_threads_file_path', type=str, help='the path to ICE folder') args = parser.parse_args() main(args.gnm_comment_threads_file_path)
6,776
35.435484
139
py
SOCC
SOCC-master/scripts/clean_comments.py
import glob import re from smart_open import smart_open # set the directory of your exported project webanno_project = input("Path to exported WebAnno project: (e.g. 'C:/.../curation')") write_directory = input("Path to folder to write new TSVs to: (e.g. 'C:/.../clean_TSVs')") # note that if the folder you write to does not already exist, this may cause an error def getcontents(directory): """ Returns the file paths for all files in the specified path. Basically the same as glob.glob, but adds a slash to the path and changes backslashes to forward slashes. :param directory: the path to a folder (without a '/' at the end) :return: a list of the contents of that folder """ return [name.replace('\\', '/') for name in glob.glob(directory + '/*')] # find the folders in your project folders = getcontents(webanno_project) # get the paths to each file in the project files1 = [getcontents(doc) for doc in folders] files = [] for i in range(len(files1)): try: files.append(files1[i][0]) except: continue # clean the files so they can be read as tsv's # generate new names for cleaned files commonsource = webanno_project + '/' commonname = '/CURATION_USER.tsv' cleannames = [name[-(len(name) - len(commonsource)):] for name in files] # get folder/CURATION_USER.tsv cleannames = [name[:len(name) - len(commonname)] for name in cleannames] # cut out the /CURATION_USER.tsv part cleannames = [re.sub(r"\..*", "", name) for name in cleannames] # strip the file extension cleannames = [name + '_cleaned.tsv' for name in cleannames] # generate new directories for cleaned files cleandirs = [write_directory.replace('\\', '/') + '/' + name for name in cleannames] # actually clean those comments def cleancomment(path): """ Cleans a file of any lines beginning with '#' - these lines prevent the file from being read properly into a Pandas dataframe. :param path: the path to a file :return: the contents of the file, with any lines starting with '#' removed """ newfile = [] with smart_open(path, 'r') as f: for line in f.readlines(): if re.match('#', line) is None: newfile.append(line) newfile2 = '' for line in newfile: for char in line: newfile2 = newfile2 + char return newfile2 def cleancomments(readdirs, writedirs, readnames=[]): """ Cleans the comments in readdirs and writes them to writedirs. Be sure the two lists are the same length and order, or it will return an error. :param readdirs: a list of files to clean :param writedirs: a list of files to write to; i.e. paths to the new, clean files :param readnames: a list of names used to report which file has been cleaned. If unspecified, will not report that any files have been cleaned (but will still clean them) :return: """ for i in range(max(len(readdirs), len(writedirs))): with smart_open(writedirs[i], 'w') as f: f.write(cleancomment(readdirs[i])) if readnames: print(readnames[i] + ' cleaned') # Write cleaned comments to assigned folder cleancomments(files, cleandirs, readnames=cleannames)
3,244
35.055556
119
py
SOCC
SOCC-master/scripts/rename_webanno.py
import glob import os import pandas as pd # This script can be used to rename the Appraisal or Negation annotated files from their idiosyncratic names to those # generated by the comment counter. You will need the unzipped, exported project directory, as well as a mapping of # WebAnno to comment counter names. (The mapping and zipped project are available on GitHub.) # path to your unzipped exported project: maindir = input("path to your unzipped exported project e.g. 'C:/.../project_name'") # path to your mapping of names: mapping_csv = input("path to your mapping of names e.g. 'C:/.../comment_counter_appraisal_mapping.csv'") # get the subfolders where annotations are annotations1dir = maindir + '/annotation' annotations2dir = maindir + '/annotation_ser' curations1dir = maindir + '/curation' curations2dir = maindir + '/curation_ser' sourcedir = maindir + '/source' # then the files for each annotation def getcontents(directory): """ Returns the file paths for all files in the specified path (directory). """ return [name.replace('\\', '/') for name in glob.glob(directory + '/*')] annotations1 = getcontents(annotations1dir) annotations2 = getcontents(annotations2dir) curations1 = getcontents(curations1dir) curations2 = getcontents(curations2dir) sources = getcontents(sourcedir) # make sure all files end in .txt (some may have been .tsv) def ziplist(oldlist, newlist): """ :param oldlist: an iterable :param newlist: another iterable :return: list from two iterables oldlist and newlist, where the ith element of oldlist is the first element of the ith sub-list and the ith element of newlist is the second element of the ith sub-list. """ return [[oldlist[i], newlist[i]] for i in range(max(len(oldlist), len(newlist)))] def cleanfilenames(files, directory): """ :param files: a list of paths to files :param directory: the directory common to those files (used to rename them) :return: a ziplist where each sublist's first element is the original filename and the second element is that name with a .txt extension instead. This function will not work if file extensions are more than 3 characters. """ sourcenames = [name[(len(directory) + 1):] for name in files] cleannames = [name[(len(directory) + 1):-3] + 'txt' for name in files] return ziplist(sourcenames, cleannames) cleanann1 = cleanfilenames(annotations1, annotations1dir) cleanann2 = cleanfilenames(annotations2, annotations2dir) cleancur1 = cleanfilenames(curations1, curations1dir) cleancur2 = cleanfilenames(curations2, curations2dir) cleansources = cleanfilenames(sources, sourcedir) # prepare to rename those files so they end in .txt def rename_file(directory, pattern, titlepattern): for pathAndFilename in glob.iglob(os.path.join(directory, pattern)): os.rename(pathAndFilename, os.path.join(directory, titlepattern)) def massrename(directory, dictionary, confirmation='Done!', check=0): for i in range(len(dictionary)): if check == 1: print([dictionary[i][0], dictionary[i][1]]) rename_file(directory, dictionary[i][0], dictionary[i][1]) print(confirmation) # execute massrename to change file extensions massrename(annotations1dir, cleanann1, confirmation='ann1') massrename(annotations2dir, cleanann2, confirmation='ann2') massrename(curations1dir, cleancur1, confirmation='cur1') massrename(curations2dir, cleancur2, confirmation='cur2') massrename(sourcedir, cleansources, confirmation='source') # get mapping mappings into Python from csv mapping1 = pd.read_csv(mapping_csv) list1 = mapping1['appraisal_negation_annotation_file_name'].tolist() list2 = mapping1['comment_counter'].tolist() mapping = ziplist(list1, list2) # rename files according to mapping (e.g. source_....) massrename(annotations1dir, mapping, confirmation='ann1') massrename(annotations2dir, mapping, confirmation='ann2') massrename(curations1dir, mapping, confirmation='cur1') massrename(curations2dir, mapping, confirmation='cur2') massrename(sourcedir, mapping, confirmation='source')
4,125
38.673077
118
py
SOCC
SOCC-master/scripts/webanno_to_sentence.py
from smart_open import smart_open import pandas as pd import re from io import StringIO # find the comments appraisal_comments_path = input('Path to combined Appraisal WebAnno formatted comments tsv' '(e.g. C:\\...\\combined_appraisal_webanno.tsv): ') negation_comments_path = input('Path to combined negation WebAnno formatted comments tsv' '(e.g. C:\\...\\combined_negation_webanno.tsv): ') mapping_csv = input("Path to your mapping of names e.g. 'C:\\...\\comment_counter_appraisal_mapping.csv'") contox_path = input("Path to constructiveness and toxicity annotations e.g." "'C:\\...\\SFU_constructiveness_toxicity_corpus.csv'") writename = input('Name for the file that will be created (e.g. all_socc_annotations): ') + '.csv' writepath = input('Folder to write the new file to (e.g. C:\\...\\Documents\\): ') + writename # what to put for blank entries: blank_entry = 'None' # split the comments so that we can iterate over each individual one if appraisal_comments_path: with smart_open(appraisal_comments_path, 'r') as f: comments_str = f.read() appraisal_comments_list = comments_str.split('#end of comment\n\n') else: print("Not using Appraisal annotations as no path was provided.") if negation_comments_path: with smart_open(negation_comments_path, 'r') as f: comments_str = f.read() negation_comments_list = comments_str.split('#end of comment\n\n') else: print("Not using negation annotations as no path was provided.") # go through the comments, extract the sentences, clean the comments so pandas can read them later, then build a # pandas data frame combining each comment as it is done # these are the actual column headers for the TSV files # some Appraisal TSVs do not have graduation, hence the need for two lists of names appraisal_longheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol', 'gralab', 'grapol'] appraisal_shortheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol'] negation_headers = ['sentpos', 'charpos', 'word', 'negation'] # some comments have no annotations no_annotation = ['sentpos', 'charpos', 'word'] appraisal_possnames = [no_annotation, appraisal_shortheaders, appraisal_longheaders] negation_possnames = [no_annotation, negation_headers] # labels that can be found in different columns attlabs = ('Appreciation', 'Affect', 'Judgment') attpols = ('pos', 'neu', 'neg') gralabs = ('Force', 'Focus') grapols = ('up', 'down') neglabs = ('NEG', 'SCOPE', 'FOCUS', 'XSCOPE') # create some tuples to show which columns go with which labels # doesn't include polarity because we'll pull that out based on the label # (each instance of Attitude should have both label and polarity) appraisal_collabels = ((appraisal_longheaders[3], attlabs), (appraisal_longheaders[5], gralabs),) # this next tuple is within another tuple so that the same commands we need later will iterate correctly negation_collabels = (('negation', neglabs),) # use the mapping csv to provide comment counter names in addition to old names if mapping_csv: mapping1 = pd.read_csv(mapping_csv) list1 = mapping1['appraisal_negation_annotation_file_name'].tolist() list2 = mapping1['comment_counter'].tolist() # dictionary of original to comment counter names mappingdict1 = {} for i in range(max(len(list1), len(list2))): mappingdict1[list1[i]] = list2[i] # same dictionary in reverse mappingdict2 = {} for i in range(max(len(list1), len(list2))): mappingdict2[list2[i]] = list1[i] def readprojfile(source, project): """ Reads a WebAnno TSV into a pandas dataframe. One column is often read as full of NaN's due to the TSVs' original formatting, so this function drops any columns with NaN's. :param source: the path to a WebAnno TSV :param possnames: the headers that may occur in the TSV, as a list of lists of headers. The function will check each list within possnames to see if its length is equal to the number of columns :param project: 'app' if Appraisal, 'neg' if negation. :return: a pandas dataframe containing the information in the original TSV """ # set possnames if project == "neg" or project.lower() == "negation": possnames = negation_possnames project = "neg" elif project == "app" or project.lower() == "appraisal": possnames = appraisal_possnames project = "app" else: print("Project type not recognized. Use 'neg' or 'att'.") possnames = None newdf = pd.read_csv(source, sep='\t', header=None) newdf = newdf.dropna(axis=1, how='all') if (project == "neg" or project.lower() == "negation") \ and len(newdf.columns) == 5: # Neg annotations with arrows have an extra column we won't use newdf = newdf.loc[:, 0:3] # so we'll just delete it for headers in possnames: if len(newdf.columns) == len(headers): newdf.columns = headers if all([len(newdf.columns) != i for i in [len(headers) for headers in possnames]]): print("No correct number of columns in", source) return newdf def getlabinds_df(dataframe, correspondences, dfname="dataframe", verbose=False): """ Gets the unique labels, including indices, that appear in a dataframe so that they can be searched later. :param dataframe: a pandas dataframe :param correspondences: a list or tuple of columns and labels like collabels :param dfname: a name for the dataframe, used for reporting when one or more columns doesn't show up :param verbose: a boolean; if True, tells you when a dataframe is missing a column :return: a list of the form [(index of column),(list of unique labels including index of that label, e.g. ['Appreciation','Appreciation[1]','Appreciation[2]']) """ newdict = {} for entry in range(len(correspondences)): if correspondences[entry][0] in dataframe.columns: searchedlist = dataframe[correspondences[entry][0]].tolist() splitlist = [i.split('|') for i in searchedlist] foundlist = [] for e in splitlist: # each element in splitlist is currently a list for i in e: # so i is a string foundlist.append(i) # so now foundlist is a list of strings foundlist = set(foundlist) # convert to set so we have uniques only foundlist = [label for label in foundlist] # convert foundlist back to a list newdict[correspondences[entry][0]] = foundlist else: if verbose: print(dfname, "does not include column", correspondences[entry][0]) return newdict def lookup_label(dataframe, column, label, commentid="dataframe", not_applicable=None, verbose=False): """ Looks in the dataframe for rows matching the label and returns them. :param dataframe: A pandas dataframe :param column: which column in the dataframe to look in for the labels :param label: which label to look for in the column :param commentid: the name of the comment; the new row will have this as its first entry :param bothids: whether to include both comment names (e.g. aboriginal_1 and source_xx_xx) :param not_applicable: what to put in a cell if there is no data (e.g. something un-annotated) :param verbose: whether to tell you when it's done :param clean_suffix: the suffix appended to clean files. Default assumes you cleaned them with clean_comments.py :return: a list that can be used as a new row or rows. If the label has no index (e.g. 'Appreciation' or '_'), then all rows with those labels will be returned. If it has an index (e.g. 'Appreciation[3]'), then one row representing that annotated span will be returned. The fields in the list are, by column: - the comment ID - which sentence the span starts in - which sentence it ends in - which character it starts on - which character it ends on - which words are in the span - the Attitude label for the span - the Attitude polarity for the span - the graduation label for the span - the graduation polarity for the span """ # determine if we're looking at attitude, graduation, or negation if 'att' in column: layer = 'att' elif 'gra' in column: layer = 'gra' elif column == 'negation': layer = 'neg' else: layer = 'unknown' # Check that both label and polarity columns are present if ('attlab' in dataframe.columns) ^ ('attpol' in dataframe.columns): if 'attlab' in dataframe.columns: print(commentid, 'has attlab column but no attpol column') if 'attpol' in dataframe.columns: print(commentid, 'has attpol column but no attlab column') if ('gralab' in dataframe.columns) ^ ('grapol' in dataframe.columns): if 'gralab' in dataframe.columns: print(commentid, 'has gralab column but no grapol column') if 'grapol' in dataframe.columns: print(commentid, 'has grapol column but no gralab column') # look for labels with brackets (e.g. 'Appreciation[3]') if '[' in label: mask = [(label in i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # get the sentence(s) of the label foundsentstart = int(re.search(r'^.*-', founddf['sentpos'].tolist()[0]).group()[:-1]) foundsentend = int(re.search(r'^.*-', founddf['sentpos'].tolist()[-1]).group()[:-1]) # get the character positions for the new row # look at which character the label starts in foundcharstart = int(re.search(r'^.*-', founddf['charpos'].tolist()[0]).group()[:-1]) # look at which character the label ends in foundcharend = int(re.search(r'-.*$', founddf['charpos'].tolist()[-1]).group()[1:]) # concatenate the words for the new row foundwords = '' for word in founddf['word']: foundwords = foundwords + word + ' ' foundwords = foundwords[:-1] # get the labels for the new row # in case of pipes, figure out which one is the real label posslabels = founddf[column].tolist() posslabels = posslabels[0] posslabels = posslabels.split('|') labelindex = posslabels.index(label) # now look through the columns and find the appropriate labels # Each column is converted to a list. The first item in the list is used to find the label. # This item is split by '|' in case of stacked annotations. # Before, we found the index of the label we want. We get the found label from this index. if layer == 'att': if 'attlab' in founddf.columns: foundattlab = founddf['attlab'].tolist()[0].split('|')[labelindex] # We want to cut off the index (e.g. 'Appreciation[3]' -> 'Appreciation') # search() finds everything up to the '[', and .group()[:-1] returns what it found, minus the '[' foundattlab = re.search(r'^.*\[', foundattlab).group()[:-1] else: foundattlab = not_applicable if 'attpol' in founddf.columns: foundattpol = founddf['attpol'].tolist()[0].split('|')[labelindex] foundattpol = re.search(r'^.*\[', foundattpol).group()[:-1] else: foundattpol = not_applicable foundgralab = not_applicable foundgrapol = not_applicable elif layer == 'gra': if 'gralab' in founddf.columns: foundgralab = founddf['gralab'].tolist()[0].split('|')[labelindex] foundgralab = re.search(r'^.*\[', foundgralab).group()[:-1] else: foundgralab = not_applicable if 'grapol' in founddf.columns: foundgrapol = founddf['grapol'].tolist()[0].split('|')[labelindex] foundgrapol = re.search(r'^.*\[', foundgrapol).group()[:-1] else: foundgrapol = not_applicable foundattlab = not_applicable foundattpol = not_applicable elif layer == 'neg': if 'negation' in founddf.columns: foundneglab = founddf['negation'].tolist()[0].split('|')[labelindex] foundneglab = re.search(r'^.*\[', foundneglab).group()[:-1] else: foundneglab = not_applicable else: print(label, "I can't tell which label this is.") # put all that together into a list for a new row if layer == 'att' or layer == 'gra': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundattlab, foundattpol, foundgralab, foundgrapol] elif layer == 'neg': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundneglab] else: print("I couldn't make a new row because I don't know which label this is") if verbose: print('Done with comment', commentid, "label", label) return foundrow # look for unlabelled spans (i.e. label '_') elif label == '_': if layer == 'neg': mask = [(label in i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # If the layer is Attitude or Graduation, check for spans with a label but no polarity or vice versa # and be sure that any spans returned as unlabelled have no label or polarity elif layer == 'att' or layer == 'gra': attmask = [] gramask = [] if 'attlab' in dataframe.columns and 'attpol' in dataframe.columns: mask1 = [(label in i) for i in dataframe['attlab'].tolist()] mask2 = [(label in i) for i in dataframe['attpol'].tolist()] for i in range(len(mask1)): if mask1[i] is not mask2[i]: print('row', i, 'has mismatched Attitude labels') attmask = [a and b for a, b in zip(mask1, mask2)] if 'gralab' in dataframe.columns and 'grapol' in dataframe.columns: mask3 = [(label in i) for i in dataframe['gralab'].tolist()] mask4 = [(label in i) for i in dataframe['grapol'].tolist()] for i in range(len(mask3)): if mask3[i] is not mask4[i]: print('row', i, 'has mismatched Graduation labels') gramask = [a and b for a, b in zip(mask3, mask4)] if attmask and not gramask: mask = attmask elif gramask and not attmask: mask = gramask elif attmask and gramask: mask = [a and b for a, b in zip(attmask, gramask)] elif not attmask and not gramask: # this will return all rows if there's no attlab or mask = [True for i in range(len(dataframe))] # gralab, since there's no annotations at all. founddf = dataframe[mask] else: print("Layer unrecognized when looking for unlabelled spans") # find the sentences sentences = [] for i in range(len(founddf['sentpos'])): sentences.append( int( # we want to do math on this later re.search( r'^.*-', founddf['sentpos'].tolist()[i] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found )) # find the character positions charpositions = [] for i in range(len(founddf['charpos'])): charpositions.append( (int(re.search(r'^.*-', founddf['charpos'].tolist()[i]).group()[:-1]), int(re.search(r'-.*$', founddf['charpos'].tolist()[i]).group()[1:])) ) # find all the words allfoundwords = founddf['word'].tolist() # find consecutive unlabelled words foundspans = [] span_number = -1 last_match = False for i in range(len(allfoundwords)): if i - 1 in range(len(allfoundwords)): # if this isn't the first word # check if this word came right after the last one if sentences[i - 1] == sentences[i] and \ (charpositions[i - 1][-1] == (charpositions[i][0] - 1) or \ charpositions[i - 1][-1] == (charpositions[i][0])): if not last_match: # if this is not a continuation of the previous span span_number += 1 # keep track of the number we're on (index of foundspans) # add the row for this span to foundspans if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i - 1], # sentence start sentences[i], # sentence end charpositions[i - 1][0], # character start charpositions[i][-1], # character end allfoundwords[i - 1] + ' ' + allfoundwords[i], # words not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i - 1], # sentence start sentences[i], # sentence end charpositions[i - 1][0], # character start charpositions[i][-1], # character end allfoundwords[i - 1] + ' ' + allfoundwords[i], # words not_applicable]) last_match = True # record these two i's as contiguous else: # (this word is a continuation of the previous span) foundspans[span_number].pop(4) # remove the ending char position so we can replace it oldwords = foundspans[span_number].pop(4) # remove the words from the span to replace it foundspans[span_number].insert(4, charpositions[i][-1]) # add the last character of this word foundspans[span_number].insert(5, oldwords + ' ' + allfoundwords[i]) # add the words together else: last_match = False # record these two i's as non-contiguous # check if this is the first pair of words we're looking at if i == 1: # i would equal 1 bc we skip i=0 (since we looked backwards) # if i=1 and the first and second words are non-contiguous, we need to add # the first word to foundspans. if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i - 1], # sentence start sentences[i - 1], # sentence end charpositions[i - 1][0], # character start charpositions[i - 1][-1], # character end allfoundwords[i - 1], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i - 1], # sentence start sentences[i - 1], # sentence end charpositions[i - 1][0], # character start charpositions[i - 1][-1], # character end allfoundwords[i - 1], # word not_applicable]) # look ahead to see if the next word is a continuation of this span: if i + 1 in range(len(sentences)): if sentences[i + 1] != sentences[i] and charpositions[i + 1][-1] != (charpositions[i][0] + 1): span_number = span_number + 1 # if so, keep track of the index if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable]) # else: the loop continues else: # if there is no following word and this one isn't a continuation, it's its own word. span_number = span_number + 1 if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable]) # no negation if verbose: print('Done with comment', commentid, "label", label) return foundspans # look for one-word annotated spans (e.g. 'Appreciation' elif ((label in attlabs) or (label in attpols) or (label in gralabs) or (label in grapols) or (label in neglabs)): # create subset dataframe - stricter than other conditions mask = [(label == i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # find the sentences sentences = [] for i in range(len(founddf['sentpos'])): sentences.append( int( # we want to do math on this later re.search( r'^.*-', founddf['sentpos'].tolist()[i] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found, minus 1 character from the end )) # find the character positions charpositions = [] for i in range(len(founddf['charpos'])): charpositions.append( (int(re.search(r'^.*-', founddf['charpos'].tolist()[i]).group()[:-1]), int(re.search(r'-.*$', founddf['charpos'].tolist()[i]).group()[1:])) ) # find the words allfoundwords = founddf['word'].tolist() # in case of pipes, figure out which one is the real label posslabels = founddf[column].tolist() posslabels = posslabels[0] posslabels = posslabels.split('|') labelindex = posslabels.index(label) # now look through the columns and find the appropriate labels # Each column is converted to a list. The first item in the list is used to find the label. # This item is split by '|' in case of stacked annotations. # Before, we found the index of the label we want. We get the found label from this index. foundspans = [] for i in range(len(founddf)): # since these are one word long, the starting and ending sentences are the same. foundsentstart = sentences[i] foundsentend = foundsentstart # find the characters the word starts and ends with foundcharstart = charpositions[i][0] foundcharend = charpositions[i][1] # find the word foundwords = allfoundwords[i] if layer == 'att': if 'attlab' in founddf.columns: foundattlab = founddf['attlab'].tolist()[0].split('|')[labelindex] else: foundattlab = not_applicable if 'attpol' in founddf.columns: foundattpol = founddf['attpol'].tolist()[0].split('|')[labelindex] else: foundattpol = not_applicable foundgralab = not_applicable foundgrapol = not_applicable elif layer == 'gra': if 'gralab' in founddf.columns: foundgralab = founddf['gralab'].tolist()[0].split('|')[labelindex] else: foundgralab = not_applicable if 'grapol' in founddf.columns: foundgrapol = founddf['grapol'].tolist()[0].split('|')[labelindex] else: foundgrapol = not_applicable foundattlab = not_applicable foundattpol = not_applicable elif layer == 'neg': if 'negation' in founddf.columns: foundneglab = founddf['negation'].tolist()[0].split('|')[labelindex] else: foundneglab = not_applicable else: print(label, "I can't tell which label this is.") # put all that together into a list for a new row if layer == 'att' or layer == 'gra': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundattlab, foundattpol, foundgralab, foundgrapol] elif layer == 'neg': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundneglab] else: print("I couldn't make a new row because I don't know which label this is") # add that row to foundspans foundspans.append(foundrow) if verbose: print('Done with comment', commentid, "label", label) return foundspans else: print('Your label was not recognized') # more info to help process the TSVs sentence_indicator = '#Text=' # what WebAnno TSVs have written to indicate the full text of a sentence sent_startpos = len(sentence_indicator) # where the text for a sentence would actually start name_indicator = '#comment: ' # text added to the combined tsv to indicate the name of each comment name_startpos = len(name_indicator) # where the text for the comment name would actually start # set up the data frame to be filled in new_df_columns = ('comment', 'comment_counter', 'sentstart', 'sentend', 'charstart', 'charend', 'span', 'attlab', 'attpol', 'gralab', 'grapol', 'neglab',) new_df = pd.DataFrame(columns=new_df_columns) # combine negation and Appraisal annotations if appraisal_comments_path and negation_comments_path: # Do stuff with appraisal print('Processing appraisal comments') new_appraisal_df = new_df sentences_df = pd.DataFrame() for comment in appraisal_comments_list: if comment: # due to how the comments list is made, it ends in a '' which can't be read properly # extract sentences and clean them linelist = comment.split('\n') clean_comment_lines = [] sentences = [] for line in linelist: # get the sentences and comment names and discard other commented lines if re.match('#', line): # if WebAnno commented out the line if re.match(sentence_indicator, line): # if the line has the text for a sentence # add that sentence to the sentences list if not lastmatch_sent: # Normally, each line with '#Text=' is a new sentence. Add the relevant part to the list: sentences.append(line[sent_startpos:]) else: # for some reason aboriginal_11 has 2 '#Text=' lines, but only one sentence. # This conditional addresses that sentences[-1] = sentences[-1] + line[sent_startpos:] lastmatch_sent = True else: lastmatch_sent=False if re.match(name_indicator, line): # if the line has the text for a comment name # set the names oldname = line[name_startpos:] if mappingdict1 or mappingdict2: # get the comment_counter name - note that file extensions may vary between .txt and .tsv # because of how files were managed in WebAnno, hence the replacement of the extension newname = oldname[:-4] + '.txt' if newname in mappingdict1: newname = mappingdict1[newname] elif newname in mappingdict2: newname = mappingdict2[newname] # if the line was not commented out, put it in the new "clean" list: else: clean_comment_lines.append(line) # put the sentences into a df and add them to the existing df new_sentences_df = pd.DataFrame() new_sentences_df['span'] = sentences print('Processing comment', oldname) # put the comment into a pandas df clean_comment = '\n'.join(clean_comment_lines) clean_comment_buffer = StringIO(clean_comment) clean_df = readprojfile(clean_comment_buffer, 'app') # Find which labels occur in the sentence labinds = getlabinds_df(clean_df, appraisal_collabels) foundrows = [] for i in range(len(appraisal_collabels)): searchcolumn = appraisal_collabels[i][0] # which column to look in if searchcolumn in clean_df.columns: searchlabels = labinds[searchcolumn] # which labels to look for in that column for searchlabel in searchlabels: if searchlabel != '_': # don't include blank spans foundstuff = lookup_label(clean_df, searchcolumn, searchlabel, commentid=oldname, not_applicable=blank_entry, verbose=False) if '[' in searchlabel: # in this case, foundstuff is one row of data foundrows.append(foundstuff) else: # in this case, foundstuff is many rows of data for row in foundstuff: foundrows.append(row) # make a dataframe with all the info we just added so that we can add it to the master df foundrows_df = pd.DataFrame(foundrows, columns=('comment', 'sentstart', 'sentend', 'charstart', 'charend', 'span', 'attlab', 'attpol', 'gralab', 'grapol',)) # add in the comment_counter name if mappingdict1 or mappingdict2: foundrows_df['comment_counter'] = newname # flesh out the new sentences df for column in new_df_columns: if column in ('charstart', 'charend', 'attlab', 'attpol', 'gralab', 'grapol', 'neglab'): new_sentences_df[column] = blank_entry elif column in ('sentstart', 'sentend'): # fill in the sentence positions new_sentences_df[column] = [i for i in range(1, len(sentences) + 1)] elif column == 'comment': new_sentences_df[column] = oldname elif column == 'comment_counter': new_sentences_df[column] = newname # we want to include character positions # read the TSV and make a new quick DF of sentences and characters # this will let us find which character #'s a sentence starts and ends with sentchar_df = pd.DataFrame(columns=('sentence', 'charstart', 'charend')) # prepare "sentence" column sentence_numbers = [] for i in clean_df['sentpos'].tolist(): # find the number before a hyphen, return that number, then coerce it into an integer and add it to # sentence_numbers sentence_numbers.append(int(re.search(r'^.*-', i).group()[:-1])) sentchar_df['sentence'] = sentence_numbers # prepare "charstart" and "charend" columns charstarts = [] charends = [] for i in clean_df['charpos'].tolist(): charstarts.append(int(re.search(r'^.*-', i).group()[:-1])) charends.append(int(re.search(r'-.*$', i).group()[1:])) sentchar_df['charstart'] = charstarts sentchar_df['charend'] = charends # add in character position info to the dataframe new_sents_charstarts = [] new_sents_charends = [] for i in new_sentences_df['sentstart']: startlist = sentchar_df.loc[sentchar_df.sentence == i, 'charstart'].tolist() endlist = sentchar_df.loc[sentchar_df.sentence == i, 'charend'].tolist() new_sentences_df.loc[new_sentences_df.sentstart == i, 'charstart'] = min(startlist) new_sentences_df.loc[new_sentences_df.sentstart == i, 'charend'] = max(endlist) sentences_df = sentences_df.append(new_sentences_df) # add this comment's information to the Appraisal df foundrows_df['neglab'] = blank_entry new_appraisal_df = new_appraisal_df.append(foundrows_df) # Do the same for negation print('Processing negation comments') new_negation_df = new_df for comment in negation_comments_list: if comment: # due to how the comments list is made, it ends in a '' which can't be read properly # extract sentences and clean them linelist = comment.split('\n') clean_comment_lines = [] # sentences list not needed since we have this from Appraisal for line in linelist: # get the sentences and comment names and discard other commented lines if re.match('#', line): # if WebAnno commented out the line if re.match(name_indicator, line): # if the line has the text for a comment name # set the name oldname = line[name_startpos:] # if the line was not commented out, put it in the new "clean" list: else: clean_comment_lines.append(line) print('Processing comment', oldname) # put the comment into a pandas df clean_comment = '\n'.join(clean_comment_lines) clean_comment_buffer = StringIO(clean_comment) clean_df = readprojfile(clean_comment_buffer, 'neg') # Find which labels occur in the sentence labinds = getlabinds_df(clean_df, negation_collabels) foundrows = [] for i in range(len(negation_collabels)): searchcolumn = negation_collabels[i][0] # which column to look in if searchcolumn in clean_df.columns: searchlabels = labinds[searchcolumn] # which labels to look for in that column for searchlabel in searchlabels: if searchlabel != '_': # don't include blank spans foundstuff = lookup_label(clean_df, searchcolumn, searchlabel, commentid=oldname, not_applicable=blank_entry, verbose=False) if '[' in searchlabel: # in this case, foundstuff is one row of data foundrows.append(foundstuff) else: # in this case, foundstuff is many rows of data for row in foundstuff: foundrows.append(row) # make a dataframe with all the info we just added so that we can add it to the master df foundrows_df = pd.DataFrame(foundrows, columns=('comment', 'sentstart', 'sentend', 'charstart', 'charend', 'span', 'neglab',)) # add in the comment_counter name if mappingdict1 or mappingdict2: foundrows_df['comment_counter'] = newname # make blank columns to smooth the appending process for column in ('attlab', 'attpol', 'gralab', 'grapol',): foundrows_df[column] = blank_entry new_negation_df = new_df.append(foundrows_df) # combine all those dataframes new_df = new_df.append(new_appraisal_df) new_df = new_df.append(new_negation_df) new_df = new_df.append(sentences_df) # sort by which character the row starts with, then which character it ends at # this means that it will read chronologically, with longer spans appearing first new_df = new_df.sort_values(by=['comment', 'charstart', 'charend'], ascending=[True, True, False]) else: print("Can't combine only one project.") # add in the constructiveness and toxicity annotations if contox_path: # make empty columns in new_df contox_columns = ('is_constructive', 'is_constructive:confidence', 'toxicity_level', 'toxicity_level:confidence') for column in contox_columns: new_df[column] = 'error' contox_df = pd.read_csv(contox_path) length_error = [] # in case there are any duplicate rows in the contox_df for column in contox_columns: for comment in contox_df['comment_counter']: if len(contox_df.loc[contox_df.comment_counter == comment, column]) > 1: length_error.append(comment) print('Length error for', comment) print('Adding', column, 'to', comment) new_df.loc[new_df.comment_counter == comment, column] = \ contox_df.loc[contox_df.comment_counter == comment, column].tolist()[0] # .tolist()[0] was added to get a straightforward string out of the relevant entry if length_error: print('Duplicate rows found. You may want to check these comments:') for i in length_error: print(i) else: print('Not adding constructiveness and toxicity as no path to it was given.') # write the df if writepath: new_df.to_csv(writepath) print('New dataframe written to', writepath) else: print('Not writing to file as no file path was specified.')
43,711
54.261694
119
py
SOCC
SOCC-master/scripts/old_combine_comments.py
from glob import glob import pandas as pd import re # where to find your cleaned TSVs: appraisal_projectpath = input('Path to appraisal project folder: (e.g. C:/.../Appraisal/clean_TSVs)') # where to write a new CSV appraisal_writepath = input('Path to write a new appraisal CSV to: (e.g. C:/.../combined_appraisal_comments.csv)') # same for negation negation_projectpath = input('Path to negation project folder: (e.g. C:/.../Negation/clean_TSVs)') negation_writepath = input('Path to write a new negation CSV to: (e.g. C:/.../combined_negation_comments.csv)') # where to find the mapping CSV so that names like source_x_x and aboriginal_1 are both used: mapping_csv = input("path to your mapping of names e.g. 'C:/.../comment_counter_appraisal_mapping.csv'") # change these variables if you are not using appraisal annotations # they are the actual column headers for the TSV files # some Appraisal TSVs do not have graduation, hence the need for two lists of names appraisal_longheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol', 'gralab', 'grapol'] appraisal_shortheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol'] negation_headers = ['sentpos', 'charpos', 'word', 'negation'] # some comments have no annotations no_annotation = ['sentpos', 'charpos', 'word'] appraisal_possnames = [no_annotation, appraisal_shortheaders, appraisal_longheaders] negation_possnames = [no_annotation, negation_headers] def getcontents(directory): """ Returns the file paths for all files in the specified path (directory). Identical to glob.glob() except that it converts '\\' to '/' """ return [name.replace('\\', '/') for name in glob(directory + '/*')] appraisal_projectdirs = getcontents(appraisal_projectpath) negation_projectdirs = getcontents(negation_projectpath) def readprojfile(path, project): """ Reads a cleaned WebAnno TSV into a pandas dataframe. One column is often read as full of NaN's due to the TSVs' original formatting, so this function drops any columns with NaN's. :param path: the path to the TSV :param possnames: the headers that may occur in the TSV, as a list of lists of headers. The function will check each list within possnames to see if its length is equal to the number of columns :param project: 'app' if Appraisal, 'neg' if negation. :return: a pandas dataframe containing the information in the original TSV """ # set possnames if project == "neg" or project.lower() == "negation": possnames = negation_possnames project = "neg" elif project == "app" or project.lower() == "appraisal": possnames = appraisal_possnames project = "app" else: print("Project type not recognized. Use 'neg' or 'att'.") possnames = None newdf = pd.read_csv(path, sep='\t', header=None) newdf = newdf.dropna(axis=1, how='all') if (project == "neg" or project.lower() == "negation")\ and len(newdf.columns) == 5: # Neg annotations with arrows have an extra column we won't use newdf = newdf.loc[:, 0:3] # so we'll just delete it for headers in possnames: if len(newdf.columns) == len(headers): newdf.columns = headers if all([len(newdf.columns) != i for i in [len(headers) for headers in possnames]]): print("No correct number of columns in", path) return newdf attlabs = ('Appreciation', 'Affect', 'Judgment') attpols = ('pos', 'neu', 'neg') gralabs = ('Force', 'Focus') grapols = ('up', 'down') neglabs = ('NEG', 'SCOPE', 'FOCUS', 'XSCOPE') # create a list to show which column to look in and which labels to look for in that column appraisal_collabels = ((appraisal_longheaders[3], attlabs), (appraisal_longheaders[4], attpols), (appraisal_longheaders[5], gralabs), (appraisal_longheaders[6], grapols)) # this next tuple is within another tuple so that the same commands we need later will iterate correctly negation_collabels = (('negation', neglabs),) # create a dictionary matching old comment names to comment counter ones if mapping_csv: mapping1 = pd.read_csv(mapping_csv) list1 = mapping1['appraisal_negation_annotation_file_name'].tolist() list2 = mapping1['comment_counter'].tolist() # dictionary of original to comment counter names mappingdict1 = {} for i in range(max(len(list1), len(list2))): mappingdict1[list1[i]] = list2[i] # same dictionary in reverse mappingdict2 = {} for i in range(max(len(list1), len(list2))): mappingdict2[list2[i]] = list1[i] def getlabinds(dataframe, correspondences, dfname="dataframe", verbose=False): """ Gets the unique labels, including indices, that appear in a dataframe so that they can be searched later. :param dataframe: a pandas dataframe :param correspondences: a list or tuple of columns and labels like collabels :param dfname: a name for the dataframe, used for reporting when one or more columns doesn't show up :param verbose: a boolean; if True, tells you when a dataframe is missing a column :return: a list of the form [(index of column),(list of unique labels including index of that label, e.g. ['Appreciation','Appreciation[1]','Appreciation[2]']) """ newdict = {} for entry in range(len(correspondences)): if correspondences[entry][0] in dataframe.columns: searchedlist = dataframe[correspondences[entry][0]].tolist() splitlist = [i.split('|') for i in searchedlist] foundlist = [] for e in splitlist: # each element in splitlist is currently a list for i in e: # so i is a string foundlist.append(i) # so now foundlist is a list of strings foundlist = set(foundlist) # convert to set so we have uniques only foundlist = [label for label in foundlist] # convert foundlist back to a list newdict[correspondences[entry][0]] = foundlist else: if verbose: print(dfname, "does not include column", correspondences[entry][0]) return newdict def listand(list1, list2): """ Returns a new list, applying the "and" operation to each item pairwise in list 1 and 2 :param list1: A list :param list2: A second list :return: A list of booleans """ return [a and b for a, b in zip(list1, list2)] def lookup_label(dataframe, column, label, commentid="dataframe", not_applicable=None, verbose=False, clean_suffix='_cleaned.tsv'): """ Looks in the dataframe for rows matching the label and returns them. :param dataframe: A pandas dataframe :param column: which column in the dataframe to look in for the labels :param label: which label to look for in the column :param commentid: the name of the comment; the new row will have this as its first entry :param bothids: whether to include both comment names (e.g. aboriginal_1 and source_xx_xx) :param not_applicable: what to put in a cell if there is no data (e.g. something un-annotated) :param verbose: whether to tell you when it's done :param clean_suffix: the suffix appended to clean files. Default assumes you cleaned them with clean_comments.py :return: a list that can be used as a new row or rows. If the label has no index (e.g. 'Appreciation' or '_'), then all rows with those labels will be returned. If it has an index (e.g. 'Appreciation[3]'), then one row representing that annotated span will be returned. The fields in the list are, by column: - the comment ID - which sentence the span starts in - which sentence it ends in - which character it starts on - which character it ends on - which words are in the span - the Attitude label for the span - the Attitude polarity for the span - the graduation label for the span - the graduation polarity for the span """ # determine if we're looking at attitude, graduation, or negation if 'att' in column: layer = 'att' elif 'gra' in column: layer = 'gra' elif column == 'negation': layer = 'neg' else: layer = 'unknown' # Check that both label and polarity columns are present if ('attlab' in dataframe.columns) ^ ('attpol' in dataframe.columns): if 'attlab' in dataframe.columns: print(commentid, 'has attlab column but no attpol column') if 'attpol' in dataframe.columns: print(commentid, 'has attpol column but no attlab column') if ('gralab' in dataframe.columns) ^ ('grapol' in dataframe.columns): if 'gralab' in dataframe.columns: print(commentid, 'has gralab column but no grapol column') if 'grapol' in dataframe.columns: print(commentid, 'has grapol column but no gralab column') # look for labels with brackets (e.g. 'Appreciation[3]') if '[' in label: mask = [(label in i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # get the sentence(s) of the label foundsentstart = int(re.search(r'^.*-', founddf['sentpos'].tolist()[0]).group()[:-1]) foundsentend = int(re.search(r'^.*-', founddf['sentpos'].tolist()[-1]).group()[:-1]) # get the character positions for the new row # look at which character the label starts in foundcharstart = int(re.search(r'^.*-', founddf['charpos'].tolist()[0]).group()[:-1]) # look at which character the label ends in foundcharend = int(re.search(r'-.*$', founddf['charpos'].tolist()[-1]).group()[1:]) # concatenate the words for the new row foundwords = '' for word in founddf['word']: foundwords = foundwords + word + ' ' foundwords = foundwords[:-1] # get the labels for the new row # in case of pipes, figure out which one is the real label posslabels = founddf[column].tolist() posslabels = posslabels[0] posslabels = posslabels.split('|') labelindex = posslabels.index(label) # now look through the columns and find the appropriate labels # Each column is converted to a list. The first item in the list is used to find the label. # This item is split by '|' in case of stacked annotations. # Before, we found the index of the label we want. We get the found label from this index. if layer == 'att': if 'attlab' in founddf.columns: foundattlab = founddf['attlab'].tolist()[0].split('|')[labelindex] # We want to cut off the index (e.g. 'Appreciation[3]' -> 'Appreciation') # search() finds everything up to the '[', and .group()[:-1] returns what it found, minus the '[' foundattlab = re.search(r'^.*\[', foundattlab).group()[:-1] else: foundattlab = not_applicable if 'attpol' in founddf.columns: foundattpol = founddf['attpol'].tolist()[0].split('|')[labelindex] foundattpol = re.search(r'^.*\[', foundattpol).group()[:-1] else: foundattpol = not_applicable foundgralab = not_applicable foundgrapol = not_applicable elif layer == 'gra': if 'gralab' in founddf.columns: foundgralab = founddf['gralab'].tolist()[0].split('|')[labelindex] foundgralab = re.search(r'^.*\[', foundgralab).group()[:-1] else: foundgralab = not_applicable if 'grapol' in founddf.columns: foundgrapol = founddf['grapol'].tolist()[0].split('|')[labelindex] foundgrapol = re.search(r'^.*\[', foundgrapol).group()[:-1] else: foundgrapol = not_applicable foundattlab = not_applicable foundattpol = not_applicable elif layer == 'neg': if 'negation' in founddf.columns: foundneglab = founddf['negation'].tolist()[0].split('|')[labelindex] foundneglab = re.search(r'^.*\[', foundneglab).group()[:-1] else: foundneglab = not_applicable else: print(label, "I can't tell which label this is.") # put all that together into a list for a new row if layer == 'att' or layer == 'gra': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundattlab, foundattpol, foundgralab, foundgrapol] elif layer == 'neg': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundneglab] else: print("I couldn't make a new row because I don't know which label this is") if verbose: print('Done with comment', commentid, "label", label) return foundrow # look for unlabelled spans (i.e. label '_') elif label == '_': if layer == 'neg': mask = [(label in i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # If the layer is Attitude or Graduation, check for spans with a label but no polarity or vice versa # and be sure that any spans returned as unlabelled have no label or polarity elif layer == 'att' or layer == 'gra': attmask = [] gramask = [] if 'attlab' in dataframe.columns and 'attpol' in dataframe.columns: mask1 = [(label in i) for i in dataframe['attlab'].tolist()] mask2 = [(label in i) for i in dataframe['attpol'].tolist()] for i in range(len(mask1)): if mask1[i] is not mask2[i]: print('row', i, 'has mismatched Attitude labels') attmask = [a and b for a, b in zip(mask1, mask2)] if 'gralab' in dataframe.columns and 'grapol' in dataframe.columns: mask3 = [(label in i) for i in dataframe['gralab'].tolist()] mask4 = [(label in i) for i in dataframe['grapol'].tolist()] for i in range(len(mask3)): if mask3[i] is not mask4[i]: print('row', i, 'has mismatched Graduation labels') gramask = [a and b for a, b in zip(mask3, mask4)] if attmask and not gramask: mask = attmask elif gramask and not attmask: mask = gramask elif attmask and gramask: mask = [a and b for a, b in zip(attmask, gramask)] elif not attmask and not gramask: # this will return all rows if there's no attlab or mask = [True for i in range(len(dataframe))] # gralab, since there's no annotations at all. founddf = dataframe[mask] else: print("Layer unrecognized when looking for unlabelled spans") # find the sentences sentences = [] for i in range(len(founddf['sentpos'])): sentences.append( int( # we want to do math on this later re.search( r'^.*-', founddf['sentpos'].tolist()[i] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found )) # find the character positions charpositions = [] for i in range(len(founddf['charpos'])): charpositions.append( (int(re.search(r'^.*-', founddf['charpos'].tolist()[i]).group()[:-1]), int(re.search(r'-.*$', founddf['charpos'].tolist()[i]).group()[1:])) ) # find all the words allfoundwords = founddf['word'].tolist() # find consecutive unlabelled words foundspans = [] span_number = -1 last_match = False for i in range(len(allfoundwords)): if i - 1 in range(len(allfoundwords)): # if this isn't the first word # check if this word came right after the last one if sentences[i - 1] == sentences[i] and\ (charpositions[i - 1][-1] == (charpositions[i][0] - 1) or\ charpositions[i - 1][-1] == (charpositions[i][0])): if not last_match: # if this is not a continuation of the previous span span_number += 1 # keep track of the number we're on (index of foundspans) # add the row for this span to foundspans if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i], # sentence end charpositions[i-1][0], # character start charpositions[i][-1], # character end allfoundwords[i - 1] + ' ' + allfoundwords[i], # words not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i], # sentence end charpositions[i-1][0], # character start charpositions[i][-1], # character end allfoundwords[i - 1] + ' ' + allfoundwords[i], # words not_applicable]) last_match = True # record these two i's as contiguous else: # (this word is a continuation of the previous span) foundspans[span_number].pop(4) # remove the ending char position so we can replace it oldwords = foundspans[span_number].pop(4) # remove the words from the span to replace it foundspans[span_number].insert(4, charpositions[i][-1]) # add the last character of this word foundspans[span_number].insert(5, oldwords + ' ' + allfoundwords[i]) # add the words together else: last_match = False # record these two i's as non-contiguous # check if this is the first pair of words we're looking at if i == 1: # i would equal 1 bc we skip i=0 (since we looked backwards) # if i=1 and the first and second words are non-contiguous, we need to add # the first word to foundspans. if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i-1], # sentence end charpositions[i-1][0], # character start charpositions[i-1][-1], # character end allfoundwords[i-1], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i-1], # sentence end charpositions[i-1][0], # character start charpositions[i-1][-1], # character end allfoundwords[i-1], # word not_applicable]) # look ahead to see if the next word is a continuation of this span: if i + 1 in range(len(sentences)): if sentences[i + 1] != sentences[i] and charpositions[i + 1][-1] != (charpositions[i][0] + 1): span_number = span_number + 1 # if so, keep track of the index if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable]) # else: the loop continues else: # if there is no following word and this one isn't a continuation, it's its own word. span_number = span_number + 1 if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable]) # no negation if verbose: print('Done with comment', commentid, "label", label) return foundspans # look for one-word annotated spans (e.g. 'Appreciation' elif ((label in attlabs) or (label in attpols) or (label in gralabs) or (label in grapols) or (label in neglabs)): # create subset dataframe - stricter than other conditions mask = [(label == i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # find the sentences sentences = [] for i in range(len(founddf['sentpos'])): sentences.append( int( # we want to do math on this later re.search( r'^.*-', founddf['sentpos'].tolist()[i] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found, minus 1 character from the end )) # find the character positions charpositions = [] for i in range(len(founddf['charpos'])): charpositions.append( (int(re.search(r'^.*-', founddf['charpos'].tolist()[i]).group()[:-1]), int(re.search(r'-.*$', founddf['charpos'].tolist()[i]).group()[1:])) ) # find the words allfoundwords = founddf['word'].tolist() # in case of pipes, figure out which one is the real label posslabels = founddf[column].tolist() posslabels = posslabels[0] posslabels = posslabels.split('|') labelindex = posslabels.index(label) # now look through the columns and find the appropriate labels # Each column is converted to a list. The first item in the list is used to find the label. # This item is split by '|' in case of stacked annotations. # Before, we found the index of the label we want. We get the found label from this index. foundspans = [] for i in range(len(founddf)): # since these are one word long, the starting and ending sentences are the same. foundsentstart = sentences[i] foundsentend = foundsentstart # find the characters the word starts and ends with foundcharstart = charpositions[i][0] foundcharend = charpositions[i][1] # find the word foundwords = allfoundwords[i] if layer == 'att': if 'attlab' in founddf.columns: foundattlab = founddf['attlab'].tolist()[0].split('|')[labelindex] else: foundattlab = not_applicable if 'attpol' in founddf.columns: foundattpol = founddf['attpol'].tolist()[0].split('|')[labelindex] else: foundattpol = not_applicable foundgralab = not_applicable foundgrapol = not_applicable elif layer == 'gra': if 'gralab' in founddf.columns: foundgralab = founddf['gralab'].tolist()[0].split('|')[labelindex] else: foundgralab = not_applicable if 'grapol' in founddf.columns: foundgrapol = founddf['grapol'].tolist()[0].split('|')[labelindex] else: foundgrapol = not_applicable foundattlab = not_applicable foundattpol = not_applicable elif layer == 'neg': if 'negation' in founddf.columns: foundneglab = founddf['negation'].tolist()[0].split('|')[labelindex] else: foundneglab = not_applicable else: print(label, "I can't tell which label this is.") # put all that together into a list for a new row if layer == 'att' or layer == 'gra': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundattlab, foundattpol, foundgralab, foundgrapol] elif layer == 'neg': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundneglab] else: print("I couldn't make a new row because I don't know which label this is") # add that row to foundspans foundspans.append(foundrow) if verbose: print('Done with comment', commentid, "label", label) return foundspans else: print('Your label was not recognized') # you can try commands like: """ testdf1 = readprojfile(appraisal_projectdirs[3], 'app') lookup_label(testdf1,'attlab','_', commentid='testdf1') lookup_label(testdf1,'attlab','Judgment[4]', commentid='testdf1') lookup_label(testdf1,'attlab','Appreciation', commentid='testdf1') lookup_label(testdf1, 'gralab', 'Force', commentid='testdf1') testdf2 = readprojfile(negation_projectdirs[3], 'neg') lookup_label(testdf2, 'negation', 'NEG', commentid='testdf2') lookup_label(testdf2, 'negation', 'SCOPE[2]', commentid='testdf2') lookup_label(testdf2, 'negation', '_', commentid='testdf2') """ # this variable will be used in a moment; it's the same as collabels, keeping only the 'label' parts # it's used so that we don't search polarity redundantly appraisal_search_correspondences = (appraisal_collabels[0], appraisal_collabels[2]) # column names for new dataframes: appraisal_newheads = ['comment', 'sentstart', 'sentend', 'charstart', 'charend', 'span', 'attlab', 'attpol', 'gralab', 'grapol'] negation_newheads = ['comment', 'sentstart', 'sentend', 'charstart', 'charend', 'span', 'label'] def simplify_dataframe(dataframe, project, commentid="Dataframe", not_applicable=None, bothids=True, clean_suffix='_cleaned.tsv', verbose=()): """ Uses all the labels in correspondences to create a new dataframe organized by span rather than by word. :param dataframe: the dataframe to search and re-create :param project: 'neg' for a negation project, 'app' for an appraisal project :param commentid: the name of the comment; the new row will have this as its first entry :param not_applicable: what to put in a cell if there is no data (e.g. something un-annotated) :param bothids: whether to add in a column with the other id (e.g. aboriginal_1 or source_01...) :param clean_suffix: the suffix added to clean files (this will be removed from commentid to find the other id) :param verbose: an iterable containing one or more of the following strings: missingcol: reports whenever a comment lacks an annotation for one or more columns label_done: reports when each label has been searched for (same as verbose for lookup_label) comment_done: reports when the function has finished running :return: a new dataframe with the same content as the one given in the first place, but reorganized by span rather than by word """ # set verbosity if 'missingcol' in verbose: verbose_missingcol = True else: verbose_missingcol = False # set newcols and correspondences if project == "neg" or project.lower() == "negation": newcols = negation_newheads correspondences = negation_collabels project = "neg" elif project == "app" or project.lower() == "appraisal": newcols = appraisal_newheads correspondences = appraisal_search_correspondences project = "app" else: print("Project type not recognized. Use 'neg' or 'app'.") newcols = None correspondences = None # find the labels to look for labinds = getlabinds(dataframe, correspondences=correspondences, dfname=commentid, verbose=verbose_missingcol) # search the old dataframe and create a list to later add as rows to the empty one if 'label_done' in verbose: v_label_done = True else: v_label_done = False foundrows = [] for i in range(len(correspondences)): searchcolumn = correspondences[i][0] # which column to look in if searchcolumn in dataframe.columns: searchlabels = labinds[searchcolumn] # which labels to look for in that column for searchlabel in searchlabels: foundstuff = lookup_label(dataframe, searchcolumn, searchlabel, commentid=commentid, not_applicable=not_applicable, verbose=v_label_done) if '[' in searchlabel: # in this case, foundstuff is one row of data foundrows.append(foundstuff) else: # in this case, foundstuff is many rows of data for row in foundstuff: foundrows.append(row) # if foundrows is empty, then instead of returning an empty df, return a df with a None-annotated row. if not foundrows: # find the sentences sentences = [] # add the first sentence number to sentences sentences.append( int( re.search( r'^.*-', dataframe['sentpos'].tolist()[0] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found )) # add the last sentence number to sentences sentences.append( int( re.search( r'^.*-', dataframe['sentpos'].tolist()[-1] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found )) # find the character positions charpositions = (int(re.search(r'^.*-', dataframe['charpos'].tolist()[0]).group()[:-1]), int(re.search(r'-.*$', dataframe['charpos'].tolist()[-1]).group()[1:])) # find all the words allfoundwords = dataframe['word'].tolist() allfoundwords = " ".join(allfoundwords) if project == "app": foundrows.append([commentid, # comment ID sentences[0], # sentence start sentences[1], # sentence end charpositions[0], # character start charpositions[1], # character end allfoundwords, # word not_applicable, # Labels are all assumed to be absent. not_applicable, not_applicable, not_applicable, ]) elif project == "neg": foundrows.append([commentid, # comment ID sentences[0], # sentence start sentences[1], # sentence end charpositions[0], # character start charpositions[1], # character end allfoundwords, # word not_applicable]) # no negation # make the rows into a new df newdf = pd.DataFrame(foundrows, columns=newcols) # sort by which character the row starts with in ascending order, then which character it ends with descending # this means that it will read chronologically, with longer spans appearing first newdf = newdf.sort_values(by=['charstart', 'charend'], ascending=[True, False]) # lookup_label will return duplicate rows when there is a span annotated only for Attitude or only for Graduation. newdf = newdf.drop_duplicates() # now, if necessary, add a column for the other comment id if bothids: commentid = commentid[:-len(clean_suffix)] + '.txt' if commentid in mappingdict1: otherid = mappingdict1[commentid] elif commentid in mappingdict2: otherid = mappingdict2[commentid] else: otherid='' print("No other comment id found for", commentid + '.') if otherid: newdf['comment_counter'] = otherid if 'comment_done' in verbose: print(commentid, "processed") return newdf # try simplify_dataframe(testdf1, appraisal_newheads, appraisal_search_correspondences, commentid="testdf1") def combine_annotations(paths, project, not_applicable=None, bothids=True, clean_suffix='_cleaned.tsv', verbose=()): """ Takes cleaned WebAnno TSVs from given paths and reorganizes them into one single dataframe, with each row representing a span (not a word, as original TSV rows do). :param paths: where your cleaned WebAnno TSVs can be found :param project: 'neg' for a negation project, 'app' for an appraisal project :param not_applicable: what to put in a cell if there is no data (e.g. something un-annotated) :param bothids: whether to include a column with the other form of identification (see simplify_dataframe()) :param clean_suffix: the suffix for cleaned files (this is removed if bothids is True, so that the mapping dictionaries work.) (see simplify_dataframe()). :param verbose: an iterable containing one or more of the following strings: missingcol: reports whenever a comment lacks an annotation for one or more columns label_done: reports when each label has been searched for (same as verbose for lookup_label) comment_start: before processing a comment, reports which commentid it is about to process comment_done: reports when the function has finished with each comment all_done: reports when the function is finished running :return: A new dataframe incorporating the information of all the TSVs in paths. Each row of the dataframe is one span. """ # set newcols and correspondences if project.lower() == "neg" or project.lower() == "negation": newcols = negation_newheads project = "neg" elif project.lower() == "app" or project.lower() == "appraisal": newcols = appraisal_newheads project = "app" else: print("Project type not recognized. Use 'neg' or 'app'.") newcols = None newdf = pd.DataFrame(columns=newcols) for path in paths: commentid = path.split('/')[-1] if 'comment_start' in verbose: print("Processing comment", commentid) originaldf = readprojfile(path, project) founddf = simplify_dataframe(originaldf, project, commentid=commentid, bothids=bothids, clean_suffix=clean_suffix, not_applicable=not_applicable, verbose=verbose) newdf = newdf.append(founddf) if 'all_done' in verbose: print("New dataframe created.") return newdf # try combine_annotations(testdirs, 'app') if appraisal_projectpath: if mapping_csv: combined_appraisal_dataframe = combine_annotations(appraisal_projectdirs, 'app', not_applicable='None', # a string works better for R than verbose=('comment_start',)) # an empty cell if appraisal_writepath: combined_appraisal_dataframe.to_csv(appraisal_writepath) print("Appraisal dataframe exported.") else: print("Not exporting Appraisal project as no path was specified.") else: combined_appraisal_dataframe = combine_annotations(appraisal_projectdirs, 'app', not_applicable='None', bothids=False, verbose=('comment_start',)) if appraisal_writepath: combined_appraisal_dataframe.to_csv(appraisal_writepath) print("Appraisal dataframe exported.") else: print("Not exporting Appraisal project as no path was specified.") else: print("Not combining Appraisal project as no path was specified.") if negation_projectpath: combined_negation_dataframe = combine_annotations(negation_projectdirs, 'neg', not_applicable='None', verbose=('comment_start',)) if negation_writepath: combined_negation_dataframe.to_csv(negation_writepath) print("Negation dataframe exported.") else: print("Not exporting Negation project as no path was specified.") else: print("Not combining Negation project as no path was specified.")
42,165
50.992602
119
py
SOCC
SOCC-master/scripts/combine_webanno.py
# This script operates directly on the "annotation" folder output by exporting a WebAnno project # for SOCC, this folder is SOCC\annotated\Appraisal\curation # Each of \annotation's sub-folders contains a TSV that contains the annotations for the given comment. # This script puts all of those TSVs into one long file, appending one after the other. In that file, # commented lines using '#' indicate when the source TSVs begin and end. import os from smart_open import smart_open import re # path to a folder containing only the WebAnno TSVs projectpath = input('Path to project folder: (e.g. C:\\...\\curation)') # directory to output outputpath = input("Path to write new TSV to: (e.g. 'C:\\...\\newfile.tsv')") # get the subfolders of /curation folders = os.listdir(projectpath) # since all TSVs should be named CURATION_USER.tsv, we need to record the folder name to know which comment is being annotated. # I use an embedded list for this. files = [[f, os.listdir(os.path.join(projectpath, f))] for f in folders] # so for each file 'f' in files, f[0] is the folder that f is contained in, and f[1] is the name of f # check that each folder contains exactly one CURATION_USER.tsv file if any([len(f[1]) for f in files]) > 1: bad_folders = [f[0] for f in files if len(f[1]) > 1] raise Exception('Some folders have more than one file:', bad_folders) else: # since they have exactly one entry each, there's no point in keeping the filename in a list files = [[f[0], f[1][0]] for f in files] # check that that file is CURATION_USER.tsv if any([f[1] != 'CURATION_USER.tsv' for f in files]): bad_names = [f[1] for f in files if f[1] != 'CURATION_USER.tsv'] raise Exception('Expected files named CURATION_USER.tsv; unexpected file names found:', bad_names) for f in files: if f != 'CURATION_USER.tsv': print(f) else: print('Found curated annotations') # start combining the files verbose = False # setting this to True may help troubleshooting newfile = '' for f in files: name = f[0] f_path = os.path.join(projectpath, f[0], f[1]) # indicate the beginning and end of a comment, and what that comment's name is newfile = newfile + '#comment: ' + name + '\n' with smart_open(f_path, 'r', encoding='utf-8') as f_io: newfile = newfile + f_io.read() + '#end of comment\n\n' if verbose: print('processed', name) # output print('All files processed, writing to', outputpath) with smart_open(outputpath, 'w') as output: output.write(newfile) print('Finished writing.')
2,604
45.517857
127
py
SOCC
SOCC-master/scripts/webanno_to_span.py
from glob import glob import pandas as pd import re # where to find your cleaned TSVs: appraisal_projectpath = input('Path to appraisal project folder: (e.g. C:/.../Appraisal/clean_TSVs)') # where to write a new CSV appraisal_writepath = input('Path to write a new appraisal CSV to: (e.g. C:/.../combined_appraisal_comments.csv)') # same for negation negation_projectpath = input('Path to negation project folder: (e.g. C:/.../Negation/clean_TSVs)') negation_writepath = input('Path to write a new negation CSV to: (e.g. C:/.../combined_negation_comments.csv)') # where to find the mapping CSV so that names like source_x_x and aboriginal_1 are both used: mapping_csv = input("Path to your mapping of names e.g. 'C:/.../comment_counter_appraisal_mapping.csv'") # these are the actual column headers for the TSV files # some Appraisal TSVs do not have graduation, hence the need for two lists of names appraisal_longheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol', 'gralab', 'grapol'] appraisal_shortheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol'] negation_headers = ['sentpos', 'charpos', 'word', 'negation'] # some comments have no annotations no_annotation = ['sentpos', 'charpos', 'word'] appraisal_possnames = [no_annotation, appraisal_shortheaders, appraisal_longheaders] negation_possnames = [no_annotation, negation_headers] def getcontents(directory): """ Returns the file paths for all files in the specified path (directory). Identical to glob.glob() except that it converts '\\' to '/' """ return [name.replace('\\', '/') for name in glob(directory + '/*')] appraisal_projectdirs = getcontents(appraisal_projectpath) negation_projectdirs = getcontents(negation_projectpath) def readprojfile(source, project): """ Reads a cleaned WebAnno TSV into a pandas dataframe. One column is often read as full of NaN's due to the TSVs' original formatting, so this function drops any columns with NaN's. :param source: the path to the TSV :param possnames: the headers that may occur in the TSV, as a list of lists of headers. The function will check each list within possnames to see if its length is equal to the number of columns :param project: 'app' if Appraisal, 'neg' if negation. :return: a pandas dataframe containing the information in the original TSV """ # set possnames if project == "neg" or project.lower() == "negation": possnames = negation_possnames project = "neg" elif project == "app" or project.lower() == "appraisal": possnames = appraisal_possnames project = "app" else: print("Project type not recognized. Use 'neg' or 'att'.") possnames = None newdf = pd.read_csv(source, sep='\t', header=None) newdf = newdf.dropna(axis=1, how='all') if (project == "neg" or project.lower() == "negation")\ and len(newdf.columns) == 5: # Neg annotations with arrows have an extra column we won't use newdf = newdf.loc[:, 0:3] # so we'll just delete it for headers in possnames: if len(newdf.columns) == len(headers): newdf.columns = headers if all([len(newdf.columns) != i for i in [len(headers) for headers in possnames]]): print("No correct number of columns in", source) return newdf # the labels that can show up in different columns attlabs = ('Appreciation', 'Affect', 'Judgment') attpols = ('pos', 'neu', 'neg') gralabs = ('Force', 'Focus') grapols = ('up', 'down') neglabs = ('NEG', 'SCOPE', 'FOCUS', 'XSCOPE') # create some tuples to show which columns go with which labels appraisal_collabels = ((appraisal_longheaders[3], attlabs), (appraisal_longheaders[4], attpols), (appraisal_longheaders[5], gralabs), (appraisal_longheaders[6], grapols)) # this next tuple is within another tuple so that the same commands we need later will iterate correctly negation_collabels = (('negation', neglabs),) # create a dictionary matching old comment names to comment counter ones if mapping_csv: mapping1 = pd.read_csv(mapping_csv) list1 = mapping1['appraisal_negation_annotation_file_name'].tolist() list2 = mapping1['comment_counter'].tolist() # dictionary of original to comment counter names mappingdict1 = {} for i in range(max(len(list1), len(list2))): mappingdict1[list1[i]] = list2[i] # same dictionary in reverse mappingdict2 = {} for i in range(max(len(list1), len(list2))): mappingdict2[list2[i]] = list1[i] def getlabinds_df(dataframe, correspondences, dfname="dataframe", verbose=False): """ Gets the unique labels, including indices, that appear in a dataframe so that they can be searched later. :param dataframe: a pandas dataframe :param correspondences: a list or tuple of columns and labels like collabels :param dfname: a name for the dataframe, used for reporting when one or more columns doesn't show up :param verbose: a boolean; if True, tells you when a dataframe is missing a column :return: a list of the form [(index of column),(list of unique labels including index of that label, e.g. ['Appreciation','Appreciation[1]','Appreciation[2]']) """ newdict = {} for entry in range(len(correspondences)): if correspondences[entry][0] in dataframe.columns: searchedlist = dataframe[correspondences[entry][0]].tolist() splitlist = [i.split('|') for i in searchedlist] foundlist = [] for e in splitlist: # each element in splitlist is currently a list for i in e: # so i is a string foundlist.append(i) # so now foundlist is a list of strings foundlist = set(foundlist) # convert to set so we have uniques only foundlist = [label for label in foundlist] # convert foundlist back to a list newdict[correspondences[entry][0]] = foundlist else: if verbose: print(dfname, "does not include column", correspondences[entry][0]) return newdict def lookup_label(dataframe, column, label, commentid="dataframe", not_applicable=None, verbose=False, clean_suffix='_cleaned.tsv'): """ Looks in the dataframe for rows matching the label and returns them. :param dataframe: A pandas dataframe :param column: which column in the dataframe to look in for the labels :param label: which label to look for in the column :param commentid: the name of the comment; the new row will have this as its first entry :param bothids: whether to include both comment names (e.g. aboriginal_1 and source_xx_xx) :param not_applicable: what to put in a cell if there is no data (e.g. something un-annotated) :param verbose: whether to tell you when it's done :param clean_suffix: the suffix appended to clean files. Default assumes you cleaned them with clean_comments.py :return: a list that can be used as a new row or rows. If the label has no index (e.g. 'Appreciation' or '_'), then all rows with those labels will be returned. If it has an index (e.g. 'Appreciation[3]'), then one row representing that annotated span will be returned. The fields in the list are, by column: - the comment ID - which sentence the span starts in - which sentence it ends in - which character it starts on - which character it ends on - which words are in the span - the Attitude label for the span - the Attitude polarity for the span - the graduation label for the span - the graduation polarity for the span """ # determine if we're looking at attitude, graduation, or negation if 'att' in column: layer = 'att' elif 'gra' in column: layer = 'gra' elif column == 'negation': layer = 'neg' else: layer = 'unknown' # Check that both label and polarity columns are present if ('attlab' in dataframe.columns) ^ ('attpol' in dataframe.columns): if 'attlab' in dataframe.columns: print(commentid, 'has attlab column but no attpol column') if 'attpol' in dataframe.columns: print(commentid, 'has attpol column but no attlab column') if ('gralab' in dataframe.columns) ^ ('grapol' in dataframe.columns): if 'gralab' in dataframe.columns: print(commentid, 'has gralab column but no grapol column') if 'grapol' in dataframe.columns: print(commentid, 'has grapol column but no gralab column') # look for labels with brackets (e.g. 'Appreciation[3]') if '[' in label: mask = [(label in i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # get the sentence(s) of the label foundsentstart = int(re.search(r'^.*-', founddf['sentpos'].tolist()[0]).group()[:-1]) foundsentend = int(re.search(r'^.*-', founddf['sentpos'].tolist()[-1]).group()[:-1]) # get the character positions for the new row # look at which character the label starts in foundcharstart = int(re.search(r'^.*-', founddf['charpos'].tolist()[0]).group()[:-1]) # look at which character the label ends in foundcharend = int(re.search(r'-.*$', founddf['charpos'].tolist()[-1]).group()[1:]) # concatenate the words for the new row foundwords = '' for word in founddf['word']: foundwords = foundwords + word + ' ' foundwords = foundwords[:-1] # get the labels for the new row # in case of pipes, figure out which one is the real label posslabels = founddf[column].tolist() posslabels = posslabels[0] posslabels = posslabels.split('|') labelindex = posslabels.index(label) # now look through the columns and find the appropriate labels # Each column is converted to a list. The first item in the list is used to find the label. # This item is split by '|' in case of stacked annotations. # Before, we found the index of the label we want. We get the found label from this index. if layer == 'att': if 'attlab' in founddf.columns: foundattlab = founddf['attlab'].tolist()[0].split('|')[labelindex] # We want to cut off the index (e.g. 'Appreciation[3]' -> 'Appreciation') # search() finds everything up to the '[', and .group()[:-1] returns what it found, minus the '[' foundattlab = re.search(r'^.*\[', foundattlab).group()[:-1] else: foundattlab = not_applicable if 'attpol' in founddf.columns: foundattpol = founddf['attpol'].tolist()[0].split('|')[labelindex] foundattpol = re.search(r'^.*\[', foundattpol).group()[:-1] else: foundattpol = not_applicable foundgralab = not_applicable foundgrapol = not_applicable elif layer == 'gra': if 'gralab' in founddf.columns: foundgralab = founddf['gralab'].tolist()[0].split('|')[labelindex] foundgralab = re.search(r'^.*\[', foundgralab).group()[:-1] else: foundgralab = not_applicable if 'grapol' in founddf.columns: foundgrapol = founddf['grapol'].tolist()[0].split('|')[labelindex] foundgrapol = re.search(r'^.*\[', foundgrapol).group()[:-1] else: foundgrapol = not_applicable foundattlab = not_applicable foundattpol = not_applicable elif layer == 'neg': if 'negation' in founddf.columns: foundneglab = founddf['negation'].tolist()[0].split('|')[labelindex] foundneglab = re.search(r'^.*\[', foundneglab).group()[:-1] else: foundneglab = not_applicable else: print(label, "I can't tell which label this is.") # put all that together into a list for a new row if layer == 'att' or layer == 'gra': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundattlab, foundattpol, foundgralab, foundgrapol] elif layer == 'neg': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundneglab] else: print("I couldn't make a new row because I don't know which label this is") if verbose: print('Done with comment', commentid, "label", label) return foundrow # look for unlabelled spans (i.e. label '_') elif label == '_': if layer == 'neg': mask = [(label in i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # If the layer is Attitude or Graduation, check for spans with a label but no polarity or vice versa # and be sure that any spans returned as unlabelled have no label or polarity elif layer == 'att' or layer == 'gra': attmask = [] gramask = [] if 'attlab' in dataframe.columns and 'attpol' in dataframe.columns: mask1 = [(label in i) for i in dataframe['attlab'].tolist()] mask2 = [(label in i) for i in dataframe['attpol'].tolist()] for i in range(len(mask1)): if mask1[i] is not mask2[i]: print('row', i, 'has mismatched Attitude labels') attmask = [a and b for a, b in zip(mask1, mask2)] if 'gralab' in dataframe.columns and 'grapol' in dataframe.columns: mask3 = [(label in i) for i in dataframe['gralab'].tolist()] mask4 = [(label in i) for i in dataframe['grapol'].tolist()] for i in range(len(mask3)): if mask3[i] is not mask4[i]: print('row', i, 'has mismatched Graduation labels') gramask = [a and b for a, b in zip(mask3, mask4)] if attmask and not gramask: mask = attmask elif gramask and not attmask: mask = gramask elif attmask and gramask: mask = [a and b for a, b in zip(attmask, gramask)] elif not attmask and not gramask: # this will return all rows if there's no attlab or mask = [True for i in range(len(dataframe))] # gralab, since there's no annotations at all. founddf = dataframe[mask] else: print("Layer unrecognized when looking for unlabelled spans") # find the sentences sentences = [] for i in range(len(founddf['sentpos'])): sentences.append( int( # we want to do math on this later re.search( r'^.*-', founddf['sentpos'].tolist()[i] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found )) # find the character positions charpositions = [] for i in range(len(founddf['charpos'])): charpositions.append( (int(re.search(r'^.*-', founddf['charpos'].tolist()[i]).group()[:-1]), int(re.search(r'-.*$', founddf['charpos'].tolist()[i]).group()[1:])) ) # find all the words allfoundwords = founddf['word'].tolist() # find consecutive unlabelled words foundspans = [] span_number = -1 last_match = False for i in range(len(allfoundwords)): if i - 1 in range(len(allfoundwords)): # if this isn't the first word # check if this word came right after the last one if sentences[i - 1] == sentences[i] and\ (charpositions[i - 1][-1] == (charpositions[i][0] - 1) or\ charpositions[i - 1][-1] == (charpositions[i][0])): if not last_match: # if this is not a continuation of the previous span span_number += 1 # keep track of the number we're on (index of foundspans) # add the row for this span to foundspans if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i], # sentence end charpositions[i-1][0], # character start charpositions[i][-1], # character end allfoundwords[i - 1] + ' ' + allfoundwords[i], # words not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i], # sentence end charpositions[i-1][0], # character start charpositions[i][-1], # character end allfoundwords[i - 1] + ' ' + allfoundwords[i], # words not_applicable]) last_match = True # record these two i's as contiguous else: # (this word is a continuation of the previous span) foundspans[span_number].pop(4) # remove the ending char position so we can replace it oldwords = foundspans[span_number].pop(4) # remove the words from the span to replace it foundspans[span_number].insert(4, charpositions[i][-1]) # add the last character of this word foundspans[span_number].insert(5, oldwords + ' ' + allfoundwords[i]) # add the words together else: last_match = False # record these two i's as non-contiguous # check if this is the first pair of words we're looking at if i == 1: # i would equal 1 bc we skip i=0 (since we looked backwards) # if i=1 and the first and second words are non-contiguous, we need to add # the first word to foundspans. if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i-1], # sentence end charpositions[i-1][0], # character start charpositions[i-1][-1], # character end allfoundwords[i-1], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i-1], # sentence start sentences[i-1], # sentence end charpositions[i-1][0], # character start charpositions[i-1][-1], # character end allfoundwords[i-1], # word not_applicable]) # look ahead to see if the next word is a continuation of this span: if i + 1 in range(len(sentences)): if sentences[i + 1] != sentences[i] and charpositions[i + 1][-1] != (charpositions[i][0] + 1): span_number = span_number + 1 # if so, keep track of the index if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable]) # else: the loop continues else: # if there is no following word and this one isn't a continuation, it's its own word. span_number = span_number + 1 if layer == 'att' or layer == 'gra': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable, # Labels are all assumed to be absent. not_applicable, # Per earlier code, it should tell you if that is not_applicable, # not actually the case. not_applicable, ]) elif layer == 'neg': foundspans.append([commentid, # comment ID sentences[i], # sentence start sentences[i], # sentence end charpositions[i][0], # character start charpositions[i][-1], # character end allfoundwords[i], # word not_applicable]) # no negation if verbose: print('Done with comment', commentid, "label", label) return foundspans # look for one-word annotated spans (e.g. 'Appreciation' elif ((label in attlabs) or (label in attpols) or (label in gralabs) or (label in grapols) or (label in neglabs)): # create subset dataframe - stricter than other conditions mask = [(label == i) for i in dataframe[column].tolist()] founddf = dataframe[mask] # find the sentences sentences = [] for i in range(len(founddf['sentpos'])): sentences.append( int( # we want to do math on this later re.search( r'^.*-', founddf['sentpos'].tolist()[i] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found, minus 1 character from the end )) # find the character positions charpositions = [] for i in range(len(founddf['charpos'])): charpositions.append( (int(re.search(r'^.*-', founddf['charpos'].tolist()[i]).group()[:-1]), int(re.search(r'-.*$', founddf['charpos'].tolist()[i]).group()[1:])) ) # find the words allfoundwords = founddf['word'].tolist() # in case of pipes, figure out which one is the real label posslabels = founddf[column].tolist() posslabels = posslabels[0] posslabels = posslabels.split('|') labelindex = posslabels.index(label) # now look through the columns and find the appropriate labels # Each column is converted to a list. The first item in the list is used to find the label. # This item is split by '|' in case of stacked annotations. # Before, we found the index of the label we want. We get the found label from this index. foundspans = [] for i in range(len(founddf)): # since these are one word long, the starting and ending sentences are the same. foundsentstart = sentences[i] foundsentend = foundsentstart # find the characters the word starts and ends with foundcharstart = charpositions[i][0] foundcharend = charpositions[i][1] # find the word foundwords = allfoundwords[i] if layer == 'att': if 'attlab' in founddf.columns: foundattlab = founddf['attlab'].tolist()[0].split('|')[labelindex] else: foundattlab = not_applicable if 'attpol' in founddf.columns: foundattpol = founddf['attpol'].tolist()[0].split('|')[labelindex] else: foundattpol = not_applicable foundgralab = not_applicable foundgrapol = not_applicable elif layer == 'gra': if 'gralab' in founddf.columns: foundgralab = founddf['gralab'].tolist()[0].split('|')[labelindex] else: foundgralab = not_applicable if 'grapol' in founddf.columns: foundgrapol = founddf['grapol'].tolist()[0].split('|')[labelindex] else: foundgrapol = not_applicable foundattlab = not_applicable foundattpol = not_applicable elif layer == 'neg': if 'negation' in founddf.columns: foundneglab = founddf['negation'].tolist()[0].split('|')[labelindex] else: foundneglab = not_applicable else: print(label, "I can't tell which label this is.") # put all that together into a list for a new row if layer == 'att' or layer == 'gra': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundattlab, foundattpol, foundgralab, foundgrapol] elif layer == 'neg': foundrow = [commentid, foundsentstart, foundsentend, foundcharstart, foundcharend, foundwords, foundneglab] else: print("I couldn't make a new row because I don't know which label this is") # add that row to foundspans foundspans.append(foundrow) if verbose: print('Done with comment', commentid, "label", label) return foundspans else: print('Your label was not recognized') # you can try commands like: """ testdf1 = readprojfile(appraisal_projectdirs[3], 'app') lookup_label(testdf1,'attlab','_', commentid='testdf1') lookup_label(testdf1,'attlab','Judgment[4]', commentid='testdf1') lookup_label(testdf1,'attlab','Appreciation', commentid='testdf1') lookup_label(testdf1, 'gralab', 'Force', commentid='testdf1') testdf2 = readprojfile(negation_projectdirs[3], 'neg') lookup_label(testdf2, 'negation', 'NEG', commentid='testdf2') lookup_label(testdf2, 'negation', 'SCOPE[2]', commentid='testdf2') lookup_label(testdf2, 'negation', '_', commentid='testdf2') """ # this variable will be used in a moment; it's the same as collabels, keeping only the 'label' parts # it's used so that we don't search polarity redundantly appraisal_search_correspondences = (appraisal_collabels[0], appraisal_collabels[2]) # column names for new dataframes: appraisal_newheads = ['comment', 'sentstart', 'sentend', 'charstart', 'charend', 'span', 'attlab', 'attpol', 'gralab', 'grapol'] negation_newheads = ['comment', 'sentstart', 'sentend', 'charstart', 'charend', 'span', 'label'] def simplify_dataframe(dataframe, project, commentid="Dataframe", not_applicable=None, bothids=True, clean_suffix='_cleaned.tsv', verbose=()): """ Uses all the labels in correspondences to create a new dataframe organized by span rather than by word. :param dataframe: the dataframe to search and re-create :param project: 'neg' for a negation project, 'app' for an appraisal project :param commentid: the name of the comment; the new row will have this as its first entry :param not_applicable: what to put in a cell if there is no data (e.g. something un-annotated) :param bothids: whether to add in a column with the other id (e.g. aboriginal_1 or source_01...) :param clean_suffix: the suffix added to clean files (this will be removed from commentid to find the other id) :param verbose: an iterable containing one or more of the following strings: missingcol: reports whenever a comment lacks an annotation for one or more columns label_done: reports when each label has been searched for (same as verbose for lookup_label) comment_done: reports when the function has finished running :return: a new dataframe with the same content as the one given in the first place, but reorganized by span rather than by word """ # set verbosity if 'missingcol' in verbose: verbose_missingcol = True else: verbose_missingcol = False # set newcols and correspondences if project == "neg" or project.lower() == "negation": newcols = negation_newheads correspondences = negation_collabels project = "neg" elif project == "app" or project.lower() == "appraisal": newcols = appraisal_newheads correspondences = appraisal_search_correspondences project = "app" else: print("Project type not recognized. Use 'neg' or 'app'.") newcols = None correspondences = None # find the labels to look for labinds = getlabinds_df(dataframe, correspondences=correspondences, dfname=commentid, verbose=verbose_missingcol) # search the old dataframe and create a list to later add as rows to the empty one if 'label_done' in verbose: v_label_done = True else: v_label_done = False foundrows = [] for i in range(len(correspondences)): searchcolumn = correspondences[i][0] # which column to look in if searchcolumn in dataframe.columns: searchlabels = labinds[searchcolumn] # which labels to look for in that column for searchlabel in searchlabels: foundstuff = lookup_label(dataframe, searchcolumn, searchlabel, commentid=commentid, not_applicable=not_applicable, verbose=v_label_done) if '[' in searchlabel: # in this case, foundstuff is one row of data foundrows.append(foundstuff) else: # in this case, foundstuff is many rows of data for row in foundstuff: foundrows.append(row) # if foundrows is empty, then instead of returning an empty df, return a df with a None-annotated row. if not foundrows: # find the sentences sentences = [] # add the first sentence number to sentences sentences.append( int( re.search( r'^.*-', dataframe['sentpos'].tolist()[0] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found )) # add the last sentence number to sentences sentences.append( int( re.search( r'^.*-', dataframe['sentpos'].tolist()[-1] # finds whatever comes before a '-' ).group()[:-1] # returns the string it found )) # find the character positions charpositions = (int(re.search(r'^.*-', dataframe['charpos'].tolist()[0]).group()[:-1]), int(re.search(r'-.*$', dataframe['charpos'].tolist()[-1]).group()[1:])) # find all the words allfoundwords = dataframe['word'].tolist() allfoundwords = " ".join(allfoundwords) if project == "app": foundrows.append([commentid, # comment ID sentences[0], # sentence start sentences[1], # sentence end charpositions[0], # character start charpositions[1], # character end allfoundwords, # word not_applicable, # Labels are all assumed to be absent. not_applicable, not_applicable, not_applicable, ]) elif project == "neg": foundrows.append([commentid, # comment ID sentences[0], # sentence start sentences[1], # sentence end charpositions[0], # character start charpositions[1], # character end allfoundwords, # word not_applicable]) # no negation # make the rows into a new df newdf = pd.DataFrame(foundrows, columns=newcols) # sort by which character the row starts with in ascending order, then which character it ends with descending # this means that it will read chronologically, with longer spans appearing first newdf = newdf.sort_values(by=['charstart', 'charend'], ascending=[True, False]) # lookup_label will return duplicate rows when there is a span annotated only for Attitude or only for Graduation. newdf = newdf.drop_duplicates() # now, if necessary, add a column for the other comment id if bothids: commentid = commentid[:-len(clean_suffix)] + '.txt' if commentid in mappingdict1: otherid = mappingdict1[commentid] elif commentid in mappingdict2: otherid = mappingdict2[commentid] else: otherid='' print("No other comment id found for", commentid + '.') if otherid: newdf['comment_counter'] = otherid if 'comment_done' in verbose: print(commentid, "processed") return newdf # try simplify_dataframe(testdf1, appraisal_newheads, appraisal_search_correspondences, commentid="testdf1") def combine_annotations(paths, project, not_applicable=None, bothids=True, clean_suffix='_cleaned.tsv', verbose=()): """ Takes cleaned WebAnno TSVs from given paths and reorganizes them into one single dataframe, with each row representing a span (not a word, as original TSV rows do). :param paths: where your cleaned WebAnno TSVs can be found :param project: 'neg' for a negation project, 'app' for an appraisal project :param not_applicable: what to put in a cell if there is no data (e.g. something un-annotated) :param bothids: whether to include a column with the other form of identification (see simplify_dataframe()) :param clean_suffix: the suffix for cleaned files (this is removed if bothids is True, so that the mapping dictionaries work.) (see simplify_dataframe()). :param verbose: an iterable containing one or more of the following strings: missingcol: reports whenever a comment lacks an annotation for one or more columns label_done: reports when each label has been searched for (same as verbose for lookup_label) comment_start: before processing a comment, reports which commentid it is about to process comment_done: reports when the function has finished with each comment all_done: reports when the function is finished running :return: A new dataframe incorporating the information of all the TSVs in paths. Each row of the dataframe is one span. """ # set newcols and correspondences if project.lower() == "neg" or project.lower() == "negation": newcols = negation_newheads project = "neg" elif project.lower() == "app" or project.lower() == "appraisal": newcols = appraisal_newheads project = "app" else: print("Project type not recognized. Use 'neg' or 'app'.") newcols = None newdf = pd.DataFrame(columns=newcols) for path in paths: commentid = path.split('/')[-1] if 'comment_start' in verbose: print("Processing comment", commentid) originaldf = readprojfile(path, project) founddf = simplify_dataframe(originaldf, project, commentid=commentid, bothids=bothids, clean_suffix=clean_suffix, not_applicable=not_applicable, verbose=verbose) newdf = newdf.append(founddf) if 'all_done' in verbose: print("New dataframe created.") return newdf # try combine_annotations(testdirs, 'app') if appraisal_projectpath: if mapping_csv: combined_appraisal_dataframe = combine_annotations(appraisal_projectdirs, 'app', not_applicable='None', # a string works better for R verbose=('comment_start',)) if appraisal_writepath: combined_appraisal_dataframe.to_csv(appraisal_writepath) print("Appraisal dataframe exported.") else: print("Not exporting Appraisal project as no path was specified.") else: combined_appraisal_dataframe = combine_annotations(appraisal_projectdirs, 'app', not_applicable='None', bothids=False, verbose=('comment_start',)) if appraisal_writepath: combined_appraisal_dataframe.to_csv(appraisal_writepath) print("Appraisal dataframe exported.") else: print("Not exporting Appraisal project as no path was specified.") else: print("Not combining Appraisal project as no path was specified.") if negation_projectpath: combined_negation_dataframe = combine_annotations(negation_projectdirs, 'neg', not_applicable='None', verbose=('comment_start',)) if negation_writepath: combined_negation_dataframe.to_csv(negation_writepath) print("Negation dataframe exported.") else: print("Not exporting Negation project as no path was specified.") else: print("Not combining Negation project as no path was specified.")
41,827
51.285
119
py
SOCC
SOCC-master/scripts/projects_to_tsv.py
from smart_open import smart_open import pandas as pd import re from io import StringIO # find the comments appraisal_comments_path = input('Path to combined Appraisal WebAnno formatted comments tsv' '(e.g. C:\\...\\combined_appraisal_webanno.tsv): ') negation_comments_path = input('Path to combined negation WebAnno formatted comments tsv' '(e.g. C:\\...\\combined_negation_webanno.tsv): ') mapping_csv = input("Path to your mapping of names e.g. 'C:\\...\\comment_counter_appraisal_mapping.csv'") contox_path = input("Path to constructiveness and toxicity annotations e.g." "'C:\\...\\SFU_constructiveness_toxicity_corpus.csv'") writename = input('Name for the file that will be created (e.g. all_socc_annotations): ') + '.tsv' writepath = input('Folder to write the new file to (e.g. C:\\...\\Documents\\): ') + writename # what to put for blank entries: blank_entry = '_' # split the comments so that we can iterate over each individual one if appraisal_comments_path: with smart_open(appraisal_comments_path, 'r') as f: comments_str = f.read() appraisal_comments_list = comments_str.split('#end of comment\n\n') else: print("Not using Appraisal annotations as no path was provided.") if negation_comments_path: with smart_open(negation_comments_path, 'r') as f: comments_str = f.read() negation_comments_list = comments_str.split('#end of comment\n\n') else: print("Not using negation annotations as no path was provided.") # these are the actual column headers for the TSV files # some Appraisal TSVs do not have graduation, hence the need for two lists of names appraisal_longheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol', 'gralab', 'grapol'] appraisal_shortheaders = ['sentpos', 'charpos', 'word', 'attlab', 'attpol'] negation_shortheaders = ['sentpos', 'charpos', 'word', 'negation'] negation_longheaders = ['sentpos', 'charpos', 'word', 'negation', 'XNEG'] # some comments have no annotations no_annotation = ['sentpos', 'charpos', 'word'] appraisal_possnames = [no_annotation, appraisal_shortheaders, appraisal_longheaders] negation_possnames = [no_annotation, negation_shortheaders, negation_longheaders] # labels that can be found in different columns attlabs = ('Appreciation', 'Affect', 'Judgment') attpols = ('pos', 'neu', 'neg') gralabs = ('Force', 'Focus') grapols = ('up', 'down') neglabs = ('NEG', 'SCOPE', 'FOCUS', 'XSCOPE') # create some tuples to show which columns go with which labels # doesn't include polarity because we'll pull that out based on the label # (each instance of Attitude should have both label and polarity) appraisal_collabels = ((appraisal_longheaders[3], attlabs), (appraisal_longheaders[5], gralabs),) # this next tuple is within another tuple so that the same commands we need later will iterate correctly negation_collabels = (('negation', neglabs),) # more info to help process the TSVs sentence_indicator = '#Text=' # what WebAnno TSVs have written to indicate the full text of a sentence sent_startpos = len(sentence_indicator) # where the text for a sentence would actually start name_indicator = '#comment: ' # text added to the combined tsv to indicate the name of each comment name_startpos = len(name_indicator) # where the text for the comment name would actually start def readprojfile_withblanks(source, project, neg_possnames=negation_possnames, app_possnames=appraisal_possnames, not_applicable=blank_entry): """ Reads a WebAnno TSV into a pandas dataframe. One column is often read as full of NaN's due to the TSVs' original formatting, so this function drops any columns with NaN's. This function also adds blanks for any columns which are not included in the original TSV. :param source: the path to a WebAnno TSV :param possnames: the headers that may occur in the TSV, as a list of lists of headers. The function will check each list within possnames to see if its length is equal to the number of columns :param project: 'app' if Appraisal, 'neg' if negation. :param neg_possnames: a list of lists of possible headers for the negation TSVs :param app_possnames: a list of lists of possible headers for the Appraisal TSVs :param not_applicable: what to put for entries that are empty :return: a pandas dataframe containing the information in the original TSV """ # set possnames if project == "neg" or project.lower() == "negation": possnames = neg_possnames project = "neg" elif project == "app" or project.lower() == "appraisal": possnames = app_possnames project = "app" else: print("Project type not recognized. Use 'neg' or 'att'.") possnames = None newdf = pd.read_csv(source, sep='\t', header=None) newdf = newdf.dropna(axis=1, how='all') for headers in possnames: if len(newdf.columns) == len(headers): newdf.columns = headers if all([len(newdf.columns) != i for i in [len(headers) for headers in possnames]]): print("No correct number of columns in", source) # add in missing columns if len(newdf.columns) != len(possnames[-1]): for column in possnames[-1]: if column not in newdf.columns: newdf[column] = not_applicable return newdf # We will want the names to match accross annotations, so let's get the mapping in if mapping_csv: mapping1 = pd.read_csv(mapping_csv) list1 = mapping1['appraisal_negation_annotation_file_name'].tolist() list2 = mapping1['comment_counter'].tolist() # dictionary of original to comment counter names mappingdict1 = {} for i in range(max(len(list1), len(list2))): mappingdict1[list1[i]] = list2[i] # same dictionary in reverse mappingdict2 = {} for i in range(max(len(list1), len(list2))): mappingdict2[list2[i]] = list1[i] # go through the comments, extract the sentences, clean the comments so pandas can read them later, then build a # pandas data frame combining each comment as it is done if appraisal_comments_path and negation_comments_path: # Prepare a combined df appdf = pd.DataFrame() combined_sentences = pd.DataFrame(columns=('comment', 'sent')) # Do stuff with appraisal print('Processing appraisal comments') for comment in appraisal_comments_list: if comment: # due to how the comments list is made, it ends in a '' which can't be read properly # extract sentences and clean them linelist = comment.split('\n') clean_comment_lines = [] sentences = [] lastmatch_sent = False # whether the last line had the sentence text in it for line in linelist: # get the sentences and comment names and discard other commented lines if re.match('#', line): # if WebAnno commented out the line if re.match(sentence_indicator, line): # if the line has the text for a sentence # add that sentence to the sentences list if not lastmatch_sent: # Normally, each line with '#Text=' is a new sentence. Add the relevant part to the list: sentences.append(line[sent_startpos:]) else: # for some reason aboriginal_11 has 2 '#Text=' lines, but only one sentence. # This conditional addresses that sentences[-1] = sentences[-1] + line[sent_startpos:] lastmatch_sent = True else: lastmatch_sent = False if re.match(name_indicator, line): # if the line has the text for a comment name # set the name # file extensions may vary between .txt and .tsv because of how files were managed in WebAnno. # The extension is replaced so that names match across projects. oldname = line[name_startpos:] oldname = oldname[:-4] + '.txt' # if the line was not commented out, put it in the new "clean" list: else: clean_comment_lines.append(line) lastmatch_sent = False # Now that we have the sentences and comment name, get them into the combined sentences df # one file was misnamed in an earlier version of the Appraisal files. Let's fix that here: if oldname == 'aboriginal_16.txt': oldname = 'aboriginal_17.txt' # let's also add the comment counter name comment_counter = mappingdict1[oldname] sentences_df = pd.DataFrame() sentences_df['sent'] = sentences sentences_df['oldname'] = oldname sentences_df['comment_counter'] = comment_counter combined_sentences = combined_sentences.append(sentences_df) print('Processing comment', str(appraisal_comments_list.index(comment)) + ':', oldname) # put the comment into a pandas df clean_comment = '\n'.join(clean_comment_lines) clean_comment_buffer = StringIO(clean_comment) clean_df = readprojfile_withblanks(clean_comment_buffer, 'app') clean_df['oldname'] = oldname clean_df['comment_counter'] = comment_counter appdf = appdf.append(clean_df) # get the negation columns negdf = pd.DataFrame() for comment in negation_comments_list: if comment: # due to how the comments list is made, it ends in a '' which can't be read properly # extract sentences and clean them linelist = comment.split('\n') clean_comment_lines = [] # sentences list not needed since we have this from Appraisal for line in linelist: # get the sentences and comment names and discard other commented lines if re.match('#', line): # if WebAnno commented out the line if re.match(name_indicator, line): # if the line has the text for a comment name # set the name oldname = line[name_startpos:] # file extensions may vary between .txt and .tsv because of how files were managed in WebAnno. # The extension is replaced so that names match across projects. oldname = oldname[:-4] + '.txt' # if the line was not commented out, put it in the new "clean" list: else: clean_comment_lines.append(line) print('Processing comment', str(negation_comments_list.index(comment)) + ':', oldname) # let's also add the comment counter name comment_counter = mappingdict1[oldname] # put the comment into a pandas df clean_comment = '\n'.join(clean_comment_lines) clean_comment_buffer = StringIO(clean_comment) clean_df = readprojfile_withblanks(clean_comment_buffer, 'neg') clean_df['oldname'] = oldname clean_df['comment_counter'] = comment_counter negdf = negdf.append(clean_df) # Combine appraisal and negation annotations app_commentlist = set(appdf['oldname'].tolist()) # list of unique comment names for App neg_commentlist = set(negdf['oldname'].tolist()) # and for neg # check that the same comments are in both if neg_commentlist != app_commentlist: if not all([i in neg_commentlist for i in app_commentlist]): for comment in neg_commentlist: if comment not in app_commentlist: print(comment, 'is in negation but not Appraisal') if not all([i in app_commentlist for i in neg_commentlist]): for comment in app_commentlist: if comment not in neg_commentlist: print(comment, 'is in Appraisal but not negation') combined_df = appdf combined_df['negation'] = blank_entry combined_df['XNEG'] = blank_entry for comment in app_commentlist: print('Combining Appraisal and negation annotations for', comment) combined_df.loc[combined_df.oldname == oldname, 'negation'] = negdf.loc[negdf.oldname == oldname, 'negation'] combined_df.loc[combined_df.oldname == oldname, 'XNEG'] = negdf.loc[negdf.oldname == oldname, 'XNEG'] # Separate the sentence numbers in combined_df sentence_numbers = [] for i in combined_df['sentpos'].tolist(): # find the number before a hyphen, return that number, then coerce it into an integer and add it to # sentence_numbers sentence_numbers.append(int(re.search(r'^.*-', i).group()[:-1])) combined_df['sentence'] = sentence_numbers # Read the constructiveness and toxicity df if contox_path: contox_columns = ('comment', 'is_constructive', 'is_constructive:confidence', 'toxicity_level', 'toxicity_level:confidence') contox_df = pd.read_csv(contox_path) # Sort the comment list so that the TSV is more easily navigable comment_counter_list = [mappingdict1[i] for i in app_commentlist] comment_counter_list.sort() # Put all the information together newstring = '' for comment in comment_counter_list: print('Adding constructiveness and toxicity to', comment) comment_slice = combined_df.loc[combined_df.comment_counter == comment] contox_slice = contox_df.loc[contox_df.comment_counter == comment] # .tolist()[0] is added to get a straightforward string out of the relevant entry comment_oldname = comment_slice['oldname'].tolist()[0] comment_is_constructive = contox_slice['is_constructive'].tolist()[0] comment_is_const_conf = contox_slice['is_constructive:confidence'].tolist()[0] comment_toxicity = contox_slice['toxicity_level'].tolist()[0] comment_tox_conf = contox_slice['toxicity_level:confidence'].tolist()[0] # Put the data describing the whole comment into one string # \n is replaced with | to make things more human-readable comment_prefix = '# comment= ' + comment_oldname + ' / ' + comment + '\n' + \ '# is_constructive= ' + comment_is_constructive.replace('\n', '|') + '\tconfidence= ' + \ str(comment_is_const_conf).replace('\n', '|') + '\n' + \ '# toxicity_level= ' + comment_toxicity.replace('\n', '|') + '\tconfidence= ' + \ str(comment_tox_conf).replace('\n', '|') # get the sentences for this comment sentences_slice = combined_sentences.loc[combined_sentences.comment_counter == comment] sentences = sentences_slice['sent'].tolist() # go through each sentence, get a slice for the rows of that sentence, put a header containing the sentence, # then put the annotated words after that comment_body = '' for i in set(comment_slice['sentence'].tolist()): small_slice = comment_slice.loc[comment_slice.sentence == i] small_slice = small_slice.drop(columns=['oldname', 'comment_counter', 'sentence']) comment_body = comment_body + '\n\n#text = ' + sentences[i-1] + '\n' + \ small_slice.to_string(index=False) # (i-1 because WebAnno starts counting at 1 but Python starts at 0) newstring = newstring + comment_prefix + comment_body + '\n\n\n' if writepath: with smart_open(writepath, 'w') as f: print('Writing new file...') f.write(newstring) print('New file written!') else: print('No write path was given, so no file will be generated.') else: print('No constructiveness/toxicity path was given, so this information won\'t show up') else: print('Either Appraisal or negation path was missing. What can I do?')
16,422
54.296296
120
py
robogym
robogym-master/setup.py
#!/usr/bin/env python3 from setuptools import find_packages, setup def setup_robogym(): setup( name="robogym", version=open("ROBOGYM_VERSION").read(), packages=find_packages(), install_requires=[ # Fixed versions "click==7.0", "collision==1.2.2", "gym==0.15.3", "kociemba==1.2.1", "mujoco-py==2.0.2.13", "pycuber==0.2.2", "matplotlib==3.1.2", "transforms3d==0.3.1", # Minimum versions "jsonnet>=0.14.0", "pytest>=4.6.9", "scikit-learn>=0.21.3", "trimesh>=3.5.23", "mock>=4.0.2", ], python_requires=">=3.7.4", description="OpenAI Robogym Robotics Environments", include_package_data=True, ) setup_robogym()
862
24.382353
59
py
robogym
robogym-master/robogym/robot_exception.py
"""Module with custom exception code for robots.""" class RobotException(Exception): """Base class for custom exceptions relative to or raised by robots.""" pass
173
20.75
75
py
robogym
robogym-master/robogym/robot_env.py
import abc import logging import random import time from collections import OrderedDict from copy import deepcopy from typing import Any, Callable, Dict, Generic, List, Optional, Tuple, Type, TypeVar import attr import gym import gym.spaces as spaces import numpy as np from robogym.goal.goal_generator import GoalGenerator from robogym.mujoco.modifiers.base import Modifier from robogym.mujoco.simulation_interface import SimulationInterface from robogym.mujoco.warning_buffer import MjWarningBuffer from robogym.observation.common import Observation, ObservationProvider, SyncType from robogym.randomization.action import ActionRandomizer from robogym.randomization.env import ( EnvActionRandomizer, EnvObservationRandomizer, EnvParameterRandomizer, EnvRandomization, EnvSimulationRandomizer, ) from robogym.randomization.observation import ObservationRandomizer from robogym.randomization.sim import SimulationRandomizer from robogym.robot.robot_interface import Robot from robogym.robot_exception import RobotException from robogym.utils.env_utils import gym_space_from_arrays from robogym.utils.multi_goal_tracker import MultiGoalTracker logger = logging.getLogger(__name__) T = TypeVar("T") def build_nested_attr(t: Callable[..., T], default: Optional[Dict] = None) -> T: """ Build attr.attrib for given user defined attr type which can be nested into another attr.attrib class. This is to overcome that issue that nested dict won't be automatically deserialized into nested attrib class. For example directly define the following attrib hierarchy @attrs.s() class B: name: str @attrs.s() class A: b: B and create a instance via A(b={'name': 'foo'}) doesn't work because {'name': 'foo'} won't be deserialized into class B. If you create a nested attrib using this function as @attrs.s() class A: b: build_nested_attr(B) The nested serialization will work correctly. """ if default is None: default = {} def converter(val): new_val = default.copy() if isinstance(val, t): return val else: assert isinstance(val, dict) new_val.update(val) return t(**new_val) return attr.ib(converter=converter, default=t(**default)) def get_generic_param_type(type_: Type, i: int, expected_type: Type): """ Get i-th generic type parameter for given class. For example if type_ extends Generic[A, B, C] then get_generic_param_type(type_, 0) -> A get_generic_param_type(type_, 1) -> B An error will be raised if the generic type is not a subclass of expected type. """ type_param = type_.__orig_bases__[0].__args__[i] if isinstance(type_param, TypeVar): # type: ignore type_param = type_param.__bound__ assert issubclass(type_param, expected_type), ( f"Parameter class {type_param} is not a subclass of {expected_type}" f"Please make sure type arguments for {type_} is correctly specified." ) return type_param @attr.s(auto_attribs=True) class RobotEnvParameters: # How many steps with random action do we take when the environment is initialized. # This should be nonzero for sim2real training configs. n_random_initial_steps: int = 10 @attr.s(auto_attribs=True) class RobotEnvConstants: """ Parameters of the env - set once and for all """ # How many mujoco warnings we store max per episode mujoco_warning_capacity: int = 5 # Whether policy actions represent target position of the fingers or change in positions of # the fingers relative_action: bool = True # Number of bins for discrete action. n_action_bins: int = 11 # If this environment is used by physical robot. physical: bool = False ##################### # Curriculum settings # Number of mujoco simulation steps per environment step mujoco_substeps: int = 10 # timestep for each mujoco simulation step. mujoco_timestep: float = 0.002 #################### # Observation related constants. # All enabled observation providers. Note that mujoco and goal doesn't # need to be specified here because they are assumed to exist for all # environments. observation_providers: list = [] # Map between observation key to observation provider. This can used to # override predefined default_observation_map to support different # provider for each observation. observation_configs: dict = {} ##################### # Wrapper settings. # Below are constants for commonly used wrappers e.g. recording wrapper. # If randomize the environment. randomize: bool = True ##################### # Multiple successes settings # Threshold for success conditions success_threshold: dict = {} # How many successes needed to stop the episode. successes_needed: int = 5 # Reward for a single success if all the distances are within the `success_threshold` success_reward: float = 5.0 # Number of seconds to sample the amount of time (in seconds) that success needs to # stay in successful state to be counted. This defines the range (in seconds) and the # actual pause time is sampled uniformly from within this range. success_pause_range_s: Tuple[float, float] = (0.0, 0.0) # Max timesteps for each goal until timeout. max_timesteps_per_goal: Optional[int] = None # If true, check if goal is reachable from current state after each step. check_goal_reachable: bool = False # How many gym steps we can make before considering the goal is unreachable. max_steps_goal_unreachable: int = 10 # If yes, include `goal_distance_reward` into the final env reward. # How `goal_distance_reward` is calculated depends on the specific env. use_goal_distance_reward: bool = True ##################### # Randomizer settings # Path for all enabled randomizers. Randomizer path is defined as # dot separated list of randomizer names along the chain e.g. # parameters # Top level parameters randomizer # observation.observation_delay # Observation delay randomizer # under top level observation randomizer randomizers: List[str] = [] class ObservationMapValue(Dict[str, Type[Observation]]): """ Value type for observation map. Example ways to instantiate this type are: ObservationMapValue({'mujoco': 'MujocoCubePosObservation'}) ObservationMapValue({ 'mujoco': MujocoCubePosObservation, 'phasespace': PhasespaceCubePosObservation, }, default='phasespace') If there is only one provider available for given observation, default doesn't need to be explicitly specified. default provider will be used if no provider is explicitly specified for this observation key in RobotEnvConstants.observation_configs. """ def __init__( self, providers_to_obs_class: Dict[str, Type[Observation]], default: Optional[str] = None, ): """ :param providers_to_obs_class: Map between provider name to observation class. :param default: Name of default observation provider. """ super().__init__(**providers_to_obs_class) self._default = default def update(self, target: "ObservationMapValue", **kwargs): # type: ignore super().update(target, **kwargs) self._default = target._default or self._default def get_default(self): if self._default is None: assert len(self) == 1, ( f"There are multiple providers available for this observation: " f"{self.keys()}, but no default." ) return list(self.keys())[0] else: assert self._default in self, f"Invalid default provider {self._default}" return self._default class RobotEnvObserver: """ Class to encapsulate observation related logic. """ def __init__( self, mujoco_simulation: SimulationInterface, providers: Dict[str, ObservationProvider], observations: Dict[str, Observation], ): self.mujoco_simulation = mujoco_simulation self.providers = providers self.observations = observations self._observation_space = None self.reset() def reset(self): """ Reset providers and observations. """ for provider in self.providers.values(): provider.reset() for observation in self.observations.values(): observation.reset() def sync(self, sync_type=SyncType.STEP): """ Sync all observation providers. Ideally this should only be called once every step. """ # Sync observation providers to make sure they return latest # information. for provider in self.providers.values(): if provider.SYNC_TYPE.value <= sync_type.value: provider.sync() def observe(self) -> dict: """ Return read only view of current observation of the environment. Calling this method multiple times in a row should yield same result without any side effect. """ return OrderedDict((key, o.get()) for key, o in self.observations.items()) def record_data(self) -> dict: """ Return data for recording wrapper. """ data = {} for provider in self.providers.values(): data.update(provider.record_data()) for obs in self.observations.values(): data.update(obs.record_data()) return data class EnvMeta(abc.ABCMeta): """ Metaclass for the environment to properly initialize environment after "basic" init has been done. This can ensure initialize() is called after __init__ of this class and all subclasses have finished. To follow the pattern please make sure: - Put logic in __init__ if it should be called before __init__of all subclasses are called. - Put logic in initialize if it should be called after __init__ of all subclasses are called. """ def __call__(cls, *args, **kwargs): """Called when you call MyNewClass() """ obj = type.__call__(cls, *args, **kwargs) obj.initialize() return obj PType = TypeVar("PType", bound=RobotEnvParameters) CType = TypeVar("CType", bound=RobotEnvConstants) SType = TypeVar("SType", bound=SimulationInterface) class RobotEnv(gym.Env, Generic[PType, CType, SType], metaclass=EnvMeta): """ Base class for robot environments. """ metadata = { "render.modes": ["human", "rgb_array"], } def __init__( self, parameters: PType, constants: CType, mujoco_simulation: SType, mujoco_modifiers: Dict[str, Modifier], robot: Robot, goal_generation: GoalGenerator, randomization: EnvRandomization, starting_seed: Optional[int] = None, ): self.parameters = parameters self.constants = constants self.mujoco_simulation = mujoco_simulation self._cached_robot = robot self.randomization = randomization self.latest_action_metadata: Dict[str, object] = {} # Container for potential mujoco errors/warnings self.warning_buffer = MjWarningBuffer( maxlen=self.constants.mujoco_warning_capacity ) self.warning_buffer.enter() # Random seed state self._last_seed = ( starting_seed if starting_seed is not None else random.randint(0, 2 ** 32 - 1) ) self._random_state = np.random.RandomState(self._last_seed) # Episode step counter self.t = 0 # "Goal" information self._previous_goal_distance = None self._goal = None # type: ignore self._goal_info_cache = None self.goal_generation = goal_generation # Environment observation/action spaces self.action_space = spaces.Box( low=-1.0, high=1.0, shape=(len(robot.zero_control()),), dtype=np.float32 ) self.action_space.seed(self._last_seed) # Will be initialized later self.observer: Optional[RobotEnvObserver] = None self._observation_space = None # List of mujoco modifiers self.modifiers: List[Tuple[str, Any]] = [] self.reward_names = ["env", "goal", "success"] self.last_update_time = time.time() self.mujoco_simulation.mj_sim.render_callback = self._render_callback for parameter_name, modifier in mujoco_modifiers.items(): self.register_modifier(parameter_name, modifier) # Set up trackers for multi-successes goals self.multi_goal_tracker = MultiGoalTracker( mujoco_simulation=self.mujoco_simulation, reset_goal_generation_fn=self.reset_goal_generation, reset_goal_fn=self.reset_goal, max_timesteps_per_goal=self.constants.max_timesteps_per_goal, success_reward=self.constants.success_reward, successes_needed=self.constants.successes_needed, success_pause_range_s=self.constants.success_pause_range_s, max_steps_goal_unreachable=self.constants.max_steps_goal_unreachable, check_goal_reachable=self.constants.check_goal_reachable, use_goal_distance_reward=self.constants.use_goal_distance_reward, goal_types=self.goal_generation.goal_types(), random_state=self._random_state, ) def initialize(self): """ Initialization to be ran after __init__ of this class and all the subclasses is finished """ self._setup_simulation_from_parameters() if "orrb" in self.constants.observation_providers: self._reset() self._goal = self._next_goal() self.update_goal_info() self.observer = self._build_observer() ############################################################################################### # Initialize observation related stuff. def _build_observer(self): """ Initialize observation providers for the environment. """ providers = self._build_observation_providers() observations = self._build_observations(providers) return RobotEnvObserver(self.mujoco_simulation, providers, observations) def _build_observations(self, providers: Dict[str, ObservationProvider]): observation_map = self._default_observation_map() observations: Dict[str, Observation] = {} for obs_key, obs_map in observation_map.items(): provider_name = self.constants.observation_configs.get( obs_key, obs_map.get_default() ) assert provider_name in providers, ( f"Observation {obs_key} is configured to use provider {provider_name} " f"which is not enabled. Enabled providers are: " f"{providers.keys()}" ) obs_class = obs_map[provider_name] provider = providers[provider_name] observations[obs_key] = obs_class(provider) return observations ############################################################################################### # Internal API - must be overridden - observation @abc.abstractmethod def _build_observation_providers(self) -> Dict[str, ObservationProvider]: """ Build all observation providers for this environment. """ pass @abc.abstractmethod def _default_observation_map(self) -> Dict[str, ObservationMapValue]: """ Return map between observation key and map between observation provider and observation class. This map should only contain simulation based observations. See implementation of other environments for example. """ pass ############################################################################################### # Internal API - may be overridden - mujoco simulation interface def _get_simulation_reward_with_done(self, info: dict) -> Tuple[float, bool]: """ Return current reward and whether episode is finished :param info: Current info dict for this env step. """ return 0.0, False def _get_simulation_info(self) -> dict: """ Return extra information about the environment """ # Just a stub for now return {} def _set_action(self, action): """ Set action for the hand""" action = np.asarray(action) action = np.clip(action, self.action_space.low, self.action_space.high) ctrl = self.robot.denormalize_position_control( position_control=action, relative_action=self.constants.relative_action, ) self.robot.set_position_control(ctrl) ############################################################################################### # Internal API - To be exposed to the child classes and wrappers def register_modifier(self, parameter_name: str, modifier_object: Modifier): """ Register given modifier for a given parameter value """ modifier_object.initialize(self.sim) self.modifiers.append((parameter_name, modifier_object)) def _setup_simulation_from_parameters(self): """ Set all the simulation parameters from the current settings. You may override it or just leave it as it is for a very basic setup. """ for param_name, modifier in self.modifiers: modifier(getattr(self.parameters, param_name)) def _render_callback(self, _sim, _viewer): """A custom callback that is called before rendering. Can be used to implement custom visualizations. """ pass def _reset(self): """ Custom reset logic that can be overloaded by subclasses. """ pass def _act(self, action): """Perform a gym environment action on the simulation. By default, this just passes the action through to the simulation, but it can be overridden by subclasses for more complicated logic.""" self._set_action(action) ############################################################################################### # Internal API - goal interface def _next_goal(self): """ Return next goal for the robot. Return a dictionary representing that goal """ current_state = self.goal_generation.current_state() return self.goal_generation.next_goal(self._random_state, current_state) def _calculate_goal_distance_reward( self, previous_goal_distance, goal_distance ) -> float: dist_reward = sum( [ previous_goal_distance[k] - goal_distance[k] for k in self.constants.success_threshold ] ) return dist_reward def _calculate_goal_distance(self, current_state): goal_distance = self.goal_generation.goal_distance(self._goal, current_state) return goal_distance def _is_successful_state(self, current_state): goal_distance = self._calculate_goal_distance(current_state) return self._is_successful(goal_distance) def _is_successful(self, goal_distance): return all( [ np.all(goal_distance[k] < self.constants.success_threshold[k]) for k in self.constants.success_threshold ] ) def _get_goal_info(self): """ Calculate information about current state of the goal """ current_state = self.goal_generation.current_state() goal_distance = self._calculate_goal_distance(current_state) relative_goal = goal_distance.pop("relative_goal", None) goal_reachable = self.goal_generation.goal_reachable(self._goal, current_state) # In case it's the first time, just set it to current goal distance if self._previous_goal_distance is None: self._previous_goal_distance = goal_distance goal_distance_reward = self._calculate_goal_distance_reward( self._previous_goal_distance, goal_distance ) self._previous_goal_distance = goal_distance optional_keys = {} is_successful = ( self._is_successful(goal_distance) or self.goal_generation.reached_terminal_state ) optional_keys["goal_max_dist"] = { k: np.max(goal_distance[k]) for k in self.constants.success_threshold } optional_keys["goal_failures"] = { k: np.sum(goal_distance[k] > self.constants.success_threshold[k]) for k in self.constants.success_threshold } goal_info = { "current_state": current_state, "goal_dist": {key: np.sum(dist) for key, dist in goal_distance.items()}, "goal_achieved": is_successful, "goal": self._goal, "penalty": current_state.get("penalty", 0.0), "goal_reachable": goal_reachable, "solved": self.goal_generation.reached_terminal_state, } goal_info.update(optional_keys) if relative_goal is not None: for key, val in relative_goal.items(): goal_info[f"rel_goal_{key}"] = val.copy() return goal_distance_reward, is_successful, deepcopy(goal_info) @property def _is_goal_achieved(self) -> bool: """ Return if current goal is achieved. """ assert self._goal_info_cache return self._goal_info_cache[1] @property def _goal_info_dict(self) -> dict: """ Return dict containing info e.g. goal state, relative goal state etc. for current goal """ assert self._goal_info_cache return self._goal_info_cache[2] ############################################################################################### # Fully internal methods. def _synchronize_step_time(self): """ Synchronize step time based on current threshold. """ # Figure out the frequency with which we would step the underlying simulation (in seconds). delta_threshold_s = self._get_wall_clock_step_time_threshold() # Sleep until we hit the time step (delta threshold) current_time = time.time() wait_time = max(0.0, delta_threshold_s - (current_time - self.last_update_time)) time.sleep(wait_time) update_time = time.time() self.last_update_time = update_time def _get_wall_clock_step_time_threshold(self): """ Return the minimum threshold wall clock step time. """ if self.constants.physical: sim = self.mujoco_simulation.mj_sim return float(sim.nsubsteps) * sim.model.opt.timestep else: # No minimum threshold for simulation. return 0 def _observe_sync(self, sync_type=SyncType.STEP): """ Sync all observation providers and return latest observation. Ideally this should only be called once every step. """ self.mujoco_simulation.forward() self.update_goal_info() self.observer.sync(sync_type=sync_type) observations = self.observe() # Notify each robot of the new observations. # This path allows robots to do whatever they need with this observations update. For example, certain arms # that use sub-simulations can sync them with the new observations. self.robot.on_observations_updated(observations) return observations ############################################################################################### # External API - to establish communication with other parts of the system @property def observation_space(self): if self._observation_space is None: obs = self._observe_sync(sync_type=SyncType.RESET) self._observation_space = gym_space_from_arrays(obs) return self._observation_space @property def robot(self): return self._cached_robot @property def warnings(self): """ List of MuJoCo warnings """ return self.warning_buffer.warnings @property def sim(self): """ Define this property so that it plays nicely with other parts of the system """ return self.mujoco_simulation.sim def observe(self) -> dict: """ Return read only view of current observation of the environment. Calling this method multiple times in a row should yield same result without any side effect. There are two ways to provide environment observations: 1. Via _observe_simple(): You can return observation using classic style gym observe method where you can directly return data associate with each observation. The downside of this approach it's not easy to change the observation based on different environment configuration e.g. sim vs physical. It's recommended to only return observations which are cheap to fetch and consistent across all environment configurations in _observe_simple(). 2. Via observer.observe(): This comes with a bit extra overhead as it requires creating observation provider and observation classes. But it has better structured support for observations can vary based on environment configuration or needs to be updated not at every step. It's recommended to handle all polymorphic observations in observer. """ assert self.observer obs = self._observe_simple() obs.update(self.observer.observe()) return self.randomization.observation_randomizer.randomize( obs, self._random_state ) def _observe_simple(self): """ Returns simple observations which can always be fetched regardless of which observation providers are specified. This function is called every time observe is called so everything here needs to cheap to fetch. Good candidates to be included here are mujoco simulation state, info from goal dict etc. """ return {} ############################################################################################### # External API - gym Env def reset(self): """Resets the state of the environment and returns an initial observation. Warning: Do not overload this method! It ensures operations happen in certain order. please add custom reset logic to _reset. Returns: observation (object): the initial observation of the space. """ # Reset time counter self.t = 0 # Reset randomization self.randomization.reset() # Randomize parameters. self.parameters = self.randomization.parameter_randomizer.randomize( self.parameters, self._random_state ) self._reset() # Randomize simulation. Because sim is recreated in self._reset(), # simulation_randomizer.randomize should be called after the _reset. self.randomization.simulation_randomizer.randomize( self.mujoco_simulation.mj_sim, self._random_state ) # reset observer. self.observer.reset() # Reset multi goal tracker for a new episode. self.multi_goal_tracker.reset() # Reset state of goal generation. return self.reset_goal_generation(sync_type=SyncType.RESET) def step_finalize(self, obs, env_reward, done, info): # Process the output by multiple goal tracker. goal_distance_reward, is_successful, goal_info = self.goal_info() obs, reward, done, info = self.multi_goal_tracker.process( obs, env_reward, done, info, goal_distance_reward, is_successful, goal_info ) info.update(goal_info) return obs, reward, done, info def step(self, action): """Run one timestep of the environment's dynamics. When end of episode is reached, you are responsible for calling `reset()` to reset this environment's state. Accepts an action and returns a tuple (observation, reward, done, info). Args: action (object): an action provided by the environment Returns: observation (object): agent's observation of the current environment reward (float) : amount of reward returned after previous action done (boolean): whether the episode has ended, in which case further step() calls will return undefined results info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning) """ action = self.randomization.action_randomizer.randomize( action, self._random_state ) robot_exception = None try: self._act(action) except RobotException as re: logger.error( f"Robot raised exception: {str(re)}. This will finish the current episode." ) robot_exception = re if not self.constants.physical: # We don't need to do stepping for physical roll out. self.mujoco_simulation.step() self._synchronize_step_time() self.t += 1 obs, reward, done, info = self.get_observation(robot_exception=robot_exception) obs, reward, done, info = self.step_finalize(obs, reward, done, info) return obs, reward, done, info def get_info_finalize(self, info: dict) -> dict: """This is called to append more info into the original `info` dict, including stats from multi-goal tracker or self-play tracker. This should neither affect observation nor trigger any tracker process calls. Multiple calls without step() in-between should yield same results. """ _, _, goal_info = self.goal_info() info = self.multi_goal_tracker.update_info(info, goal_info) info.update(goal_info) return info def get_observation(self, robot_exception=None): # Get current state to return to the user obs = self._observe_sync() if robot_exception is None: info, env_reward, done = self.get_simulation_info_reward_with_done() else: # Robot raised an exception, we can't continue with this tick, since we can't assume that the robot # performed the action. info = {"robot_raised_exception": True} done = True env_reward = 0.0 # TBD consider adding a penalty if useful info = self.get_info_finalize(info) return obs, env_reward, done, info def get_info(self): obs, reward, done, info = self.get_observation() return info def get_simulation_info_reward_with_done(self): info = self._get_simulation_info() env_reward, done = self._get_simulation_reward_with_done(info) assert isinstance(env_reward, float) return info, env_reward, done def update_goal_info(self): """ Re-computes and caches the current goal_info. Usually you do not have to call this since `step` will automatically do so. However, if you manipulate the state externally, you will have to call this method after. """ self._goal_info_cache = self._get_goal_info() def reset_goal(self, update_seed=False, sync_type=SyncType.RESET_GOAL): """ Reset the goal of the environment """ # Reset stats for one goal in the same episode. self.multi_goal_tracker.reset_goal_steps() # Randomize a target for the robot self._goal = self._next_goal() self._previous_goal_distance = None return self._observe_sync(sync_type=sync_type) def reset_goal_generation(self, sync_type=SyncType.RESET_GOAL): """ Reset state of goal generation. """ self.goal_generation.reset(self._random_state) return self.reset_goal(sync_type=sync_type) def goal_info(self): """ Return info about the goal """ return self._goal_info_cache def render(self, mode="human", width=500, height=500): """Renders the environment. The set of supported modes varies per environment. (And some environments do not support rendering at all.) By convention, if mode is: - human: render to the current display or terminal and return nothing. Usually for human consumption. - rgb_array: Return an numpy.ndarray with shape (x, y, 3), representing RGB values for an x-by-y pixel image, suitable for turning into a video. - ansi: Return a string (str) or StringIO.StringIO containing a terminal-style text representation. The text can include newlines and ANSI escape sequences (e.g. for colors). Note: Make sure that your class's metadata 'render.modes' key includes the list of supported modes. It's recommended to call super() in implementations to use the functionality of this method. Args: mode (str): the mode to render with width (int): Width of the rendered image. height (int): Height of the rendered image. Example: class MyEnv(Env): metadata = {'render.modes': ['human', 'rgb_array']} def render(self, mode='human'): if mode == 'rgb_array': return np.array(...) # return RGB frame suitable for video elif mode is 'human': ... # pop up a window and render else: super(MyEnv, self).render(mode=mode) # just raise an exception """ if mode == "human": return self.mujoco_simulation.mujoco_viewer.render() elif mode == "rgb_array": return self.mujoco_simulation.render(width=width, height=height) else: raise ValueError("Unsupported mode %s" % mode) def seed(self, seed=None): """Sets the seed for this env's random number generator(s). Note: Some environments use multiple pseudorandom number generators. We want to capture all such seeds used in order to ensure that there aren't accidental correlations between multiple generators. Returns: list<bigint>: Returns the list of seeds used in this env's random number generators. The first value in the list should be the "main" seed, or the value which a reproducer should pass to 'seed'. Often, the main seed equals the provided 'seed', but this won't be true if seed=None, for example. """ if isinstance(seed, list): # Support list of seeds as required by Gym. seed = seed[0] elif isinstance(seed, int): pass elif seed is not None: # If seed is None, we just return current seed. raise ValueError("Seed must be an integer.") if seed is not None: self._last_seed = seed self._random_state.seed(seed) self.action_space.seed(seed) # Return list of seeds to conform to Gym specs return [self._last_seed] def apply_wrappers(self, **wrapper_params): """ Apply wrappers to the environment. """ return self @classmethod @abc.abstractmethod def build_robot(cls, mujoco_simulation: SType, physical: bool) -> Robot: """ Build robot for this environment. """ pass @classmethod @abc.abstractmethod def build_goal_generation( cls, constants: CType, mujoco_simulation: SType ) -> GoalGenerator: """ Build goal generation for this environment. """ pass @classmethod @abc.abstractmethod def build_simulation(cls, constants: CType, parameters: PType) -> SType: """ Build simulation for this environment. """ pass @classmethod def build_mujoco_modifiers(cls) -> Dict[str, Modifier]: """ Build mujoco modifiers for this environment. """ return OrderedDict() @classmethod def build_randomization( cls, constants: CType, parameters: PType ) -> EnvRandomization: """ Build simulation for this environment. """ return EnvRandomization( parameter_randomizer=cls.build_parameter_randomizer(constants, parameters), observation_randomizer=EnvObservationRandomizer( cls.build_observation_randomizers(constants) ), action_randomizer=EnvActionRandomizer( cls.build_action_randomizers(constants) ), simulation_randomizer=EnvSimulationRandomizer( cls.build_simulation_randomizers(constants) ), ) @classmethod def build_parameter_randomizer( cls, constants: CType, parameters: PType ) -> EnvParameterRandomizer: """ Build parameter randomizer for the environment. """ return EnvParameterRandomizer(parameters) @classmethod def build_observation_randomizers(cls, constants) -> List[ObservationRandomizer]: """ Build observation randomizers for the environment. """ return [] @classmethod def build_action_randomizers(cls, constants) -> List[ActionRandomizer]: """ Build action randomizers for the environment. """ return [] @classmethod def build_simulation_randomizers(cls, constants) -> List[SimulationRandomizer]: """ Build simulation randomizers for the environment. """ return [] @classmethod def build( cls, parameters=None, constants=None, wrapper_params=None, starting_seed=None, apply_wrappers=True, ): """ Construct a dactyl environment together with a set of common wrappers. """ if parameters is None: parameters = {} if constants is None: constants = {} if wrapper_params is None: wrapper_params = {} parameter_class = get_generic_param_type(cls, 0, RobotEnvParameters) constant_class = get_generic_param_type(cls, 1, RobotEnvConstants) if isinstance(parameters, dict): parameters = parameter_class(**parameters) if isinstance(constants, dict): constants = constant_class(**constants) mujoco_simulation = cls.build_simulation(constants, parameters,) mujoco_modifiers = cls.build_mujoco_modifiers() goal_generation = cls.build_goal_generation(constants, mujoco_simulation) randomization = cls.build_randomization(constants, parameters) for name in constants.randomizers: randomization.get_randomizer(name).enable() robot = cls.build_robot( mujoco_simulation=mujoco_simulation, physical=constants.physical ) env = cls( parameters=parameters, constants=constants, mujoco_simulation=mujoco_simulation, mujoco_modifiers=mujoco_modifiers, robot=robot, goal_generation=goal_generation, randomization=randomization, starting_seed=starting_seed, ) if apply_wrappers: env = env.apply_wrappers(**wrapper_params) return env @classmethod def _get_default_wrappers(cls): return None
40,152
34.098776
115
py
robogym
robogym-master/robogym/mujoco/constants.py
from enum import Enum OPT_FIELDS = { "apirate", "collision", "cone", "density", "disableflags", "enableflags", "gravity", "impedance", "impratio", "integrator", "iterations", "jacobian", "magnetic", "mpr_iterations", "mpr_tolerance", "noslip_iterations", "noslip_tolerance", "o_margin", "o_solimp", "o_solref", "reference", "solver", "timestep", "tolerance", "uintptr", "viscosity", "wind", } """ follow mujoco-py order: cdef enum USER_DEFINED_ACTUATOR_PARAMS: IDX_PROPORTIONAL_GAIN = 0, IDX_INTEGRAL_TIME_CONSTANT = 1, IDX_INTEGRAL_MAX_CLAMP = 2, IDX_DERIVATIVE_TIME_CONSTANT = 3, IDX_DERIVATIVE_GAIN_SMOOTHING = 4, IDX_ERROR_DEADBAND = 5, """ PID_GAIN_PARAMS = [ "pid_kp", "pid_ti", "pid_imax_clamp", "pid_td", "pid_dsmooth", "pid_error_deadband", ] class MujocoEquality(Enum): mjEQ_CONNECT = 0 # connect two bodies at a point (ball joint) mjEQ_WELD = 1 # fix relative position and orientation of two bodies mjEQ_JOINT = 2 # couple the values of two scalar joints with cubic mjEQ_TENDON = 3 # couple the lengths of two tendons with cubic mjEQ_DISTANCE = 4 # fix the contact distance betweent two geoms
1,292
19.854839
72
py
robogym
robogym-master/robogym/mujoco/simulation_interface.py
import itertools as it from typing import Dict, List import attr from mujoco_py import MjSimState, cymj from robogym.mujoco.helpers import ( joint_qpos_ids, joint_qpos_ids_from_prefix, joint_qvel_ids, joint_qvel_ids_from_prefix, ) from robogym.mujoco.mujoco_xml import MjSim @attr.s(auto_attribs=True) class SimulationParameters: """ Containing all parameters needed to build the mujoco simulation. """ pass class SimulationInterface: """ Base class for domain-specific simulation interfaces tied to particular XML. Goal is to transform code interfacing with generic `MjSim` that looks like that: hand_angles = sim.data.qpos[hand_angle_idx] cube_pos = sim.data.qpos[cube_pos_idx] sim.model.actuator_gainprm[actuator_idx] = actuator_kps sim.model.actuator_biasprm[actuator_idx] = actuator_kps Into more high-level and domain-specific version: hand_angles = sim.hand.get_angles() cube_pos = sim.get_cube_pos() sim.set_actuator_kp(actuator_kps) Etc. This is a base class that just exposes a few generic utilities to help the subclasses implement the abovementioned functionality. By convention, the subclasses should be named <Something>Simulation. """ __slots__ = [ "sim", "qpos_idxs", "qvel_idxs", "synchronization_points", "_mujoco_viewer", ] def __init__(self, sim: MjSim): self.sim = sim self.qpos_idxs: Dict[str, List[int]] = {} self.qvel_idxs: Dict[str, List[int]] = {} self.synchronization_points = [] # type: ignore self._mujoco_viewer = None @property def mj_sim(self): """ MuJoCo simulation object - alias to make it clearer """ return self.sim @property def mujoco_viewer(self): """ Get a nicely-interactive version of the mujoco viewer """ if self._mujoco_viewer is None: # Inline import since this is only relevant on platforms # which have GLFW support. from mujoco_py.mjviewer import MjViewer # noqa self._mujoco_viewer = MjViewer(self.sim) return self._mujoco_viewer def enable_pid(self): """ Enable our custom PID controller code for the actuators with 'user' type """ cymj.set_pid_control(self.sim.model, self.sim.data) ############################################################################################### # SUBCLASS REGISTRATION def register_joint_group(self, group_name, prefix): """ Finds and collect joint ids for given joint name prefix or a list of prefixes. """ if isinstance(prefix, str): self.qpos_idxs[group_name] = joint_qpos_ids_from_prefix( self.sim.model, prefix ) self.qvel_idxs[group_name] = joint_qvel_ids_from_prefix( self.sim.model, prefix ) elif isinstance(prefix, list): self.qpos_idxs[group_name] = list( it.chain.from_iterable( joint_qpos_ids_from_prefix(self.sim.model, p) for p in prefix ) ) self.qvel_idxs[group_name] = list( it.chain.from_iterable( joint_qvel_ids_from_prefix(self.sim.model, p) for p in prefix ) ) def register_joint_group_by_name(self, group_name, name): """ Finds and collect joint ids for given joint name or list of names. """ if isinstance(name, str): self.qpos_idxs[group_name] = joint_qpos_ids(self.sim.model, name) self.qvel_idxs[group_name] = joint_qvel_ids(self.sim.model, name) elif isinstance(name, list): self.qpos_idxs[group_name] = list( it.chain.from_iterable(joint_qpos_ids(self.sim.model, n) for n in name) ) self.qvel_idxs[group_name] = list( it.chain.from_iterable(joint_qvel_ids(self.sim.model, n) for n in name) ) ############################################################################################### # GET DATA OUT OF SIM def get_qpos(self, group_name): """ Gets qpos for a particular group. """ return self.sim.data.qpos[self.qpos_idxs[group_name]] def get_qpos_dict(self, group_names): """ Gets qpos dictionary for multiple groups. """ return {k: self.get_qpos(k) for k in group_names} def get_qvel(self, group_name): """ Gets qvel for a particular group. """ return self.sim.data.qvel[self.qvel_idxs[group_name]] def get_qvel_dict(self, group_names): """ Gets qpos dictionary for multiple groups. """ return {k: self.get_qvel(k) for k in group_names} @property def qpos(self): """ Returns. copy of full sim qpos. """ return self.sim.data.qpos.copy() @property def qvel(self): """ Returns copy of full sim qvel. """ return self.sim.data.qvel.copy() def get_state(self) -> MjSimState: return self.sim.get_state() ############################################################################################### # SET DATA IN SIM def set_qpos(self, group_name, value): """ Sets qpos for a given group. """ self.sim.data.qpos[self.qpos_idxs[group_name]] = value def set_qvel(self, group_name, value): """ Sets qpos for a given group. """ self.sim.data.qvel[self.qvel_idxs[group_name]] = value def add_qpos(self, group_name, value): """ Sets qpos for a given group. """ self.sim.data.qpos[self.qpos_idxs[group_name]] += value def set_state(self, state: MjSimState): self.sim.set_state(state) ############################################################################################### # INTERFACE TO UNDERLYING SIM def step(self, with_udd=True): """ Advances the simulation by calling ``mj_step``. If ``qpos`` or ``qvel`` have been modified directly, the user is required to call :meth:`.forward` before :meth:`.step` if their ``udd_callback`` requires access to MuJoCo state set during the forward dynamics. """ self.sim.step(with_udd=with_udd) self.sim.forward() # To potentially communicate with other processes for point in self.synchronization_points: point.synchronize() def reset(self): """ Resets the simulation data and clears buffers. """ self.sim.reset() def set_constants(self): """ Sets the derived constants of the mujoco simulation. """ self.sim.set_constants() def forward(self): """ Computes the forward kinematics. Calls ``mj_forward`` internally. """ self.sim.forward() def render( self, width=None, height=None, *, camera_name=None, depth=False, mode="offscreen", device_id=-1 ): """ Renders view from a camera and returns image as an `numpy.ndarray`. Args: - width (int): desired image width. - height (int): desired image height. - camera_name (str): name of camera in model. If None, the free camera will be used. - depth (bool): if True, also return depth buffer - device (int): device to use for rendering (only for GPU-backed rendering). Returns: - rgb (uint8 array): image buffer from camera - depth (float array): depth buffer from camera (only returned if depth=True) """ return self.sim.render( width=width, height=height, camera_name=camera_name, depth=depth, mode=mode, device_id=device_id, ) ############################################################################################### # PROPERTIES @property def n_substeps(self): """ Number of substeps in the mujoco sim """ return self.sim.nsubsteps
8,178
31.585657
99
py
robogym
robogym-master/robogym/mujoco/mujoco_xml.py
import os.path import typing import xml.etree.ElementTree as et import mujoco_py import numpy as np ASSETS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../assets")) XML_DIR = os.path.join(ASSETS_DIR, "xmls") def _format_array(np_array, precision=6): """ Format numpy array into a nice string suitable for mujoco XML """ if not isinstance(np_array, np.ndarray): np_array = np.array(np_array, dtype=float) # Make sure it's flattened if len(np_array.shape) > 1: np_array = np_array.reshape(-1) if np.min(np.abs(np_array)) > 0.001: format_str = "{:.%df}" % precision else: format_str = "{:.%de}" % precision # Finally format a string out of numpy array return " ".join(format_str.format(x) for x in np_array) class StaleMjSimError(Exception): """ Exception indicating the MjSim instance is stale and should no longer be used. """ pass class MjSim(mujoco_py.MjSim): """ There are environments e.g. rearrange environment which recreates sim after reach env reset. This can cause potential bugs caused by other components still caching instance of old sim. These bugs are usually quite tricky to find. This class makes it easier to find these bugs by allowing invalidating the sim instance so any access to properties of stale sim instance will cause error. """ __slots__ = ("_stale", "_xml") def __init__(self, model, **kwargs): # Note: we don't need to call super.__init__ because MjSim use __cinit__ # for initialization which happens automatically before subclass __init__ # is called. self._stale: bool = False self._xml = model.get_xml() def get_xml(self): """ Mujoco's internal get_xml() is unreliable as it seems to override the internal memory buffer when more than one sim is instantiated. We therefore cache the model xml on creation. :return: """ return self._xml def set_stale(self): """ Set this sim instance as stale so further access to properties of this instance will raise error. """ self._stale = True def is_stale(self): return self._stale @property def data(self): self._ensure_not_stale() return super().data @property def model(self): self._ensure_not_stale() return super().model def _ensure_not_stale(self): if self._stale: raise StaleMjSimError( "You are accessing property of a stale sim instance which is no longer used" "by the environment." ) class MujocoXML: """ Class that combines multiple MuJoCo XML files into a single one. """ meshdir = os.path.join(ASSETS_DIR, "stls") texturedir = os.path.join(ASSETS_DIR, "textures") TEXTURE_ATTRIBUTES = [ "file", "fileback" "filedown", "filefront", "fileleft", "fileright", "fileup", ] NAMED_FIELDS = { "actuator", "body1", "body2", "childclass", "class", "geom", "geom1", "geom2", "joint", "joint1", "joint2", "jointparent", "material", "mesh", "name", "sidesite", "site", "source", "target", "tendon", "texture", } ############################################################################################### # CONSTRUCTION @classmethod def parse(cls, xml_filename: str): """ Parse given xml filename into the MujocoXML model """ xml_full_path = os.path.join(XML_DIR, xml_filename) if not os.path.exists(xml_full_path): raise Exception(xml_full_path) with open(xml_full_path) as f: xml_root = et.parse(f).getroot() xml = cls(xml_root) xml.load_includes(os.path.dirname(os.path.abspath(xml_full_path))) return xml @classmethod def from_string(cls, contents: str): """ Construct MujocoXML from string """ xml_root = et.XML(contents) xml = cls(xml_root) xml.load_includes() return xml def __init__(self, root_element: typing.Optional[et.Element] = None): """ Create new MujocoXML class """ # This is the root element of the XML document we'll be modifying if root_element is None: # Create empty root element self.root_element = et.Element("mujoco") else: # Initialize it from the existing thing self.root_element = root_element ############################################################################################### # COMBINING MUJOCO ELEMENTS def add_default_compiler_directive(self): """ Add a default compiler directive """ self.root_element.append( et.Element( "compiler", { "meshdir": self.meshdir, "texturedir": self.texturedir, "angle": "radian", "coordinate": "local", }, ) ) return self def append(self, other: "MujocoXML"): """ Append another XML object to this object """ self.root_element.extend(other.root_element) return self def xml_string(self): """ Return combined XML as a string """ return et.tostring(self.root_element, encoding="unicode", method="xml") def load_includes(self, include_root=""): """ Some mujoco files contain includes that need to be process on our side of the system Find all elements that have an 'include' child """ for element in self.root_element.findall(".//include/.."): # Remove in a second pass to avoid modifying list while iterating it elements_to_remove_insert = [] for idx, subelement in enumerate(element): if subelement.tag == "include": # Branch off initial filename include_path = os.path.join(include_root, subelement.get("file")) include_element = MujocoXML.parse(include_path) elements_to_remove_insert.append( (idx, subelement, include_element.root_element) ) # Iterate in reversed order to make sure indices are not screwed up for idx, to_remove, to_insert in reversed(elements_to_remove_insert): element.remove(to_remove) to_insert_list = list(to_insert) # Insert multiple elements for i in range(len(to_insert)): element.insert(idx + i, to_insert_list[i]) return self def _resolve_asset_paths(self, meshdir, texturedir): """Resolve relative asset path in xml to local file path.""" for mesh in self.root_element.findall(".//mesh"): fname = mesh.get("file") if fname is not None: if fname[0] != "/": fname = os.path.join(meshdir or self.meshdir, fname) mesh.set("file", fname) for texture in self.root_element.findall(".//texture"): for attribute in self.TEXTURE_ATTRIBUTES: fname = texture.get(attribute) if fname is not None: if fname[0] != "/": fname = os.path.join(texturedir or self.texturedir, fname) texture.set(attribute, fname) def build(self, output_filename=None, meshdir=None, texturedir=None, **kwargs): """ Build and return a mujoco simulation """ self._resolve_asset_paths(meshdir, texturedir) xml_string = self.xml_string() if output_filename is not None: with open(output_filename, "wt") as f: f.write(xml_string) mj_model = mujoco_py.load_model_from_xml(xml_string) return MjSim(mj_model, **kwargs) ############################################################################################### # MODIFICATIONS def set_objects_attr(self, tag: str = "*", **kwargs): """ Set given attribute to all instances of given tag within the tree """ for element in self.root_element.findall(".//{}".format(tag)): for name, value in kwargs.items(): if isinstance(value, (list, np.ndarray)): value = _format_array(value) element.set(name, str(value)) return self def set_objects_attrs(self, tag_args: dict): """ Batch version of set_objects_attr where args for multiple tags can be specified as a dict. """ for tag, args in tag_args.items(): self.set_objects_attr(tag=tag, **args) def set_named_objects_attr(self, name: str, tag: str = "*", **kwargs): """ Sets xml attributes of all objects with given name """ for element in self.root_element.findall(".//{}[@name='{}']".format(tag, name)): for name, value in kwargs.items(): if isinstance(value, (list, np.ndarray)): value = _format_array(value) element.set(name, str(value)) return self def set_prefixed_objects_attr(self, prefix: str, tag: str = "*", **kwargs): """ Sets xml attributes of all objects with given name prefix """ for element in self.root_element.findall(".//{}[@name]".format(tag)): if element.get("name").startswith(prefix): # type: ignore for name, value in kwargs.items(): if isinstance(value, (list, np.ndarray)): value = _format_array(value) element.set(name, str(value)) return self def add_name_prefix(self, name_prefix: str, exclude_attribs=[]): """ Add a given name prefix to all elements with "name" attribute. Additionally, once we changed all "name" attributes we also have to change all attribute fields that refer to those names. """ for element in self.root_element.iter(): for attrib_name in element.keys(): if ( attrib_name not in self.NAMED_FIELDS or attrib_name in exclude_attribs ): continue element.set(attrib_name, name_prefix + element.get(attrib_name)) # type: ignore return self def replace_name(self, old_name: str, new_name: str, exclude_attribs=[]): """ Replace an old name string with an new name string in "name" attribute. """ for element in self.root_element.iter(): for attrib_name in element.keys(): if ( attrib_name not in self.NAMED_FIELDS or attrib_name in exclude_attribs ): continue element.set(attrib_name, element.get(attrib_name).replace(old_name, new_name)) # type: ignore return self def remove_objects_by_tag(self, tag: str): """ Remove objects with given tag from XML """ for element in self.root_element.findall(".//{}/..".format(tag)): for subelement in list(element): if subelement.tag != tag: continue assert subelement.tag == tag element.remove(subelement) return self def remove_objects_by_prefix(self, prefix: str, tag: str = "*"): """ Remove objects with given name prefix from XML """ for element in self.root_element.findall(".//{}[@name]/..".format(tag)): for subelement in list(element): if subelement.get("name").startswith(prefix): # type: ignore element.remove(subelement) return self def remove_objects_by_name( self, names: typing.Union[typing.List[str], str], tag: str = "*" ): """ Remove object with given name from XML """ if isinstance(names, str): names = [names] for name in names: for element in self.root_element.findall( ".//{}[@name='{}']/..".format(tag, name) ): for subelement in list(element): if subelement.get("name") == name: element.remove(subelement) return self
12,646
32.635638
110
py
robogym
robogym-master/robogym/mujoco/warning_buffer.py
import collections import logging import mujoco_py.cymj as cymj logger = logging.getLogger(__name__) class MujocoErrorException(Exception): """ Exception raised when mujoco error is called. """ pass def error_callback(message): """ Mujoco error callback """ message = message.decode() full_message = f"MUJOCO ERROR: {message}" logger.error(full_message) raise MujocoErrorException(full_message) # Set it once for all the processes cymj.set_error_callback(error_callback) class MjWarningBuffer: """ Buffering MuJoCo warnings. That way they don't cause an exception being thrown which crashes the process, but at the same time we store them in memory and can process. One can potentially specify buffer capacity if one wants to use a circular buffer. """ def __init__(self, maxlen=None): self.maxlen = maxlen self._buffer = collections.deque(maxlen=self.maxlen) self._prev_user_callback = None def _intercept_warning(self, warn_bytes): """ Intercept a warning """ warn = warn_bytes.decode() # Convert bytes to string logger.warning("MUJOCO WARNING: %s", str(warn)) self._buffer.append(warn) @property def warnings(self): """ Return a list of warnings to the user """ return list(self._buffer) def enter(self): """ Enable collecting warnings """ if self._prev_user_callback is None: self._prev_user_callback = cymj.get_warning_callback() cymj.set_warning_callback(self._intercept_warning) def clear(self): """ Reset warning buffer """ self._buffer.clear() def exit(self): """ Stop collecting warnings """ if self._prev_user_callback is not None: cymj.set_warning_callback(self._prev_user_callback) self._prev_user_callback = None def __enter__(self): """ Enter - context manager magic method """ self.enter() def __exit__(self, exc_type, exc_val, exc_tb): """ Exit - context manager magic method """ self.exit() def __repr__(self): """ Text representation""" return "<{} warnings:{}>".format(self.__class__.__name__, len(self.warnings))
2,265
25.97619
86
py
robogym
robogym-master/robogym/mujoco/forward_kinematics.py
import xml.etree.ElementTree as et from typing import Any, Dict, List, Optional, Tuple import numpy as np import robogym.utils.rotation as rot from robogym.mujoco.mujoco_xml import MujocoXML def homogeneous_matrix_from_pos_mat(pos, mat): m = np.eye(4) m[:3, :3] = mat m[:3, 3] = pos return m def get_joint_matrix(pos, angle, axis): def transform_rot_x_matrix(pos, angle): """ Optimization - create a homogeneous matrix where rotation submatrix rotates around the X axis by given angle in radians """ m = np.eye(4) m[1, 1] = m[2, 2] = np.cos(angle) s = np.sin(angle) m[1, 2] = -s m[2, 1] = s m[:3, 3] = pos return m def transform_rot_y_matrix(pos, angle): """ Optimization - create a homogeneous matrix where rotation submatrix rotates around the Y axis by given angle in radians """ m = np.eye(4) m[0, 0] = m[2, 2] = np.cos(angle) s = np.sin(angle) m[0, 2] = s m[2, 0] = -s m[:3, 3] = pos return m def transform_rot_z_matrix(pos, angle): """ Optimization - create a homogeneous matrix where rotation submatrix rotates around the Z axis by given angle in radians """ m = np.eye(4) m[0, 0] = m[1, 1] = np.cos(angle) s = np.sin(angle) m[0, 1] = -s m[1, 0] = s m[:3, 3] = pos return m if abs(axis[0]) == 1.0 and axis[1] == 0.0 and axis[2] == 0.0: return transform_rot_x_matrix(pos, angle * axis[0]) elif axis[0] == 0.0 and abs(axis[1]) == 1.0 and axis[2] == 0.0: return transform_rot_y_matrix(pos, angle * axis[1]) elif axis[0] == 0.0 and axis[1] == 0.0 and abs(axis[2]) == 1.0: return transform_rot_z_matrix(pos, angle * axis[2]) else: return homogeneous_matrix_from_pos_mat( pos, rot.quat2mat(rot.quat_from_angle_and_axis(angle, axis)) ) class ForwardKinematics: """ Generic forward kinematics calculator for open chain rigid systems. """ def __init__(self, site_computations, joint_info): self.site_computations = site_computations self.joint_info = joint_info def compute(self, qpos, return_joint_pos=False): """ given joint positions, calculate the endpoint positions. currently only return positions, but orientation also computed but just not returned. later could be useful for other end effectors. currently only support hinge joints. """ num_sites = len(self.site_computations) site_positions = [] joint_positions = [None] * len(self.joint_info) def cached_joint_calculator(computations, cidx): joint_idx = computations[cidx] assert isinstance( joint_idx, int ), "computation should be body interweaving with joints." if joint_positions[joint_idx] is not None: return joint_positions[joint_idx] else: (joint_pos, joint_axis) = self.joint_info[joint_idx] joint_matrix = get_joint_matrix(joint_pos, qpos[joint_idx], joint_axis) if cidx == len(computations) - 2: joint_pos = computations[-1] @ joint_matrix else: joint_pos = ( cached_joint_calculator(computations, cidx + 2) @ computations[cidx + 1] @ joint_matrix ) joint_positions[joint_idx] = joint_pos return joint_pos for i in range(num_sites): computations = self.site_computations[i] m = computations[0] if len(computations) > 1: m = cached_joint_calculator(computations, 1) @ m # only return position for now site_positions.append(m[:3, 3]) if return_joint_pos: joint_xpos = list(map(lambda v: v[:3, 3], joint_positions)) return np.array(site_positions + joint_xpos) else: return np.array(site_positions) @classmethod def prepare( cls, mxml: MujocoXML, root_body_name: str, root_body_pos: np.array, root_body_euler: np.array, target_sites: List[str], joint_names: List[str], ): """ parse mujoco xml to build up the kinematic tree, also does some static computations (e.g. fixed body/body connection). target_sites are the endpoints to compute later joint_names are sequence of joints passed at runtime for the endpoint position calculations. """ IDENTITY_QUAT = rot.quat_identity() ROOT_BODY_PARENT = "NONE" target_sites_idx: Dict[str, int] = { v: idx for idx, v in enumerate(target_sites) } joint_names_idx: Dict[str, int] = {v: idx for idx, v in enumerate(joint_names)} num_sites = len(target_sites) site_info: List[Optional[Tuple]] = [None] * num_sites # (4d matrix, parentBody) joint_info: List[Optional[Tuple]] = [None] * len(joint_names) # (axis, pos) body_info: Dict[ str, Any ] = dict() # name => (4d homegeneous matrix, parentbody) body_joints: Dict[str, str] = dict() # body => joints def get_matrix(x: et.Element): pos = np.fromstring(x.attrib.get("pos"), sep=" ") if "euler" in x.attrib: euler = np.fromstring(x.attrib.get("euler"), sep=" ") return homogeneous_matrix_from_pos_mat(pos, rot.euler2mat(euler)) elif "axisangle" in x.attrib: axis_angle = np.fromstring(x.attrib.get("axisangle"), sep=" ") quat = rot.quat_from_angle_and_axis( axis_angle[-1], np.array(axis_angle[:-1]) ) return homogeneous_matrix_from_pos_mat(pos, rot.quat2mat(quat)) elif "quat" in x.attrib: quat = np.fromstring(x.attrib.get("quat"), sep=" ") return homogeneous_matrix_from_pos_mat(pos, rot.quat2mat(quat)) else: quat = IDENTITY_QUAT return homogeneous_matrix_from_pos_mat(pos, rot.quat2mat(quat)) def traverse(rt: et.Element, parent_body: str): assert rt.tag == "body", "only start from body tag in xml" matrix = get_matrix(rt) name = rt.attrib.get("name", "noname_body_%d" % len(body_info)) body_info[name] = (matrix, parent_body) for x in rt.findall("joint"): joint_name = x.attrib.get("name", "") joint_idx: int = joint_names_idx.get(joint_name, -1) if joint_idx == -1: continue assert ( x.attrib.get("type", "hinge") == "hinge" ), "currently only support hinge joints" pos = np.fromstring(x.attrib.get("pos"), sep=" ") axis = np.fromstring(x.attrib.get("axis"), sep=" ") joint_info[joint_idx] = (pos, axis) assert ( joint_name not in body_joints ), "Only support open chain system, unsupported rigid bodies" body_joints[name] = joint_name for x in rt.findall("site"): site_idx = target_sites_idx.get(x.attrib.get("name", ""), -1) if site_idx != -1: matrix = get_matrix(x) site_info[site_idx] = (matrix, name) for x in rt.findall("body"): # recursive scan through body parts traverse(x, name) rt = None for child in mxml.root_element.find("worldbody").findall("body"): # type: ignore if child.attrib.get("name", "") == root_body_name: rt = child break assert rt is not None, "no root body found in xml" traverse(rt, ROOT_BODY_PARENT) root_matrix = homogeneous_matrix_from_pos_mat( root_body_pos, rot.euler2mat(root_body_euler) ) # build the computation flow site_computations = [[] for i in range(num_sites)] # type: ignore for i in range(num_sites): (matrix, parent_body) = site_info[i] # type: ignore # Just have to trust the code while parent_body != ROOT_BODY_PARENT: parent_matrix, new_parent_body = body_info[parent_body] joint_name = body_joints.get(parent_body, "") if joint_name: site_computations[i].append(matrix) site_computations[i].append(joint_names_idx[joint_name]) matrix = parent_matrix else: matrix = parent_matrix @ matrix parent_body = new_parent_body site_computations[i].append(root_matrix @ matrix) return cls(site_computations, joint_info)
9,205
35.387352
94
py
robogym
robogym-master/robogym/mujoco/helpers.py
import itertools import typing import mujoco_py import mujoco_py.generated.const def joint_qpos_ids(model, joint_name: str) -> typing.List[int]: addr = model.get_joint_qpos_addr(joint_name) if isinstance(addr, tuple): return list(range(addr[0], addr[1])) else: return [addr] def joint_qpos_ids_from_prefix(model, joint_prefix): qpos_ids_list = [ joint_qpos_ids(model, name) for name in model.joint_names if name.startswith(joint_prefix) ] return list(itertools.chain.from_iterable(qpos_ids_list)) def joint_qvel_ids(model, joint_name: str) -> typing.List[int]: addr = model.get_joint_qvel_addr(joint_name) if isinstance(addr, tuple): return list(range(addr[0], addr[1])) else: return [addr] def joint_qvel_ids_from_prefix(model, joint_prefix): qvel_ids_list = [ joint_qvel_ids(model, name) for name in model.joint_names if name.startswith(joint_prefix) ] return list(itertools.chain.from_iterable(qvel_ids_list)) def joint_type_name(joint_type: int) -> str: if joint_type == mujoco_py.generated.const.JNT_FREE: return "free" if joint_type == mujoco_py.generated.const.JNT_BALL: return "ball" if joint_type == mujoco_py.generated.const.JNT_SLIDE: return "slide" if joint_type == mujoco_py.generated.const.JNT_HINGE: return "hinge" raise AssertionError(f"unsupported joint type: {joint_type}")
1,484
27.018868
65
py
robogym
robogym-master/robogym/mujoco/test/test_mujoco_utils.py
import random import numpy as np from mujoco_py import cymj, functions from numpy.random.mtrand import _rand as global_randstate from robogym.mujoco.forward_kinematics import ForwardKinematics from robogym.mujoco.mujoco_xml import MujocoXML from robogym.mujoco.simulation_interface import SimulationInterface from robogym.utils.rotation import uniform_quat XML_BALL = """ <mujoco> <worldbody> <body name="ball"> <freejoint name="ball_joint"/> <geom name="sphere" pos="0.00 0.00 0.00" type="sphere" size="0.1 0.1 0.1"/> </body> </worldbody> </mujoco> """ XML_ARM = """ <mujoco> <worldbody> <body name="arm"> <joint type="hinge" name="hinge_joint" axis="0 0 1"/> <geom name="sphere" pos="0.00 0.00 0.00" type="sphere" size="0.1 0.1 0.1"/> <body name="forearm" pos="1 0 0"> <joint type="slide" axis="1 0 0" name="slide_joint"/> <geom name="box" pos="0.00 0.00 0.00" type="box" size="0.1 0.1 0.1"/> </body> </body> </worldbody> </mujoco> """ def test_simple_mujoco_setup(): ball_one = ( MujocoXML.from_string(XML_BALL) .add_name_prefix("ball_one:") .set_named_objects_attr("ball_one:ball", pos=[1, 0, 0]) ) ball_two = ( MujocoXML.from_string(XML_BALL) .add_name_prefix("ball_two:") .set_named_objects_attr("ball_two:ball", pos=[-1, 0, 0]) ) main = ( MujocoXML().add_default_compiler_directive().append(ball_one).append(ball_two) ) simulation = SimulationInterface(main.build()) simulation.register_joint_group("ball_one", "ball_one:ball_joint") simulation.register_joint_group("ball_two", "ball_two:ball_joint") assert simulation.get_qpos("ball_one").shape == (7,) assert simulation.get_qpos("ball_two").shape == (7,) assert simulation.get_qvel("ball_one").shape == (6,) assert simulation.get_qvel("ball_two").shape == (6,) qpos1 = np.random.randn(3) qrot1 = uniform_quat(global_randstate) qpos1_combined = np.concatenate([qpos1, qrot1]) qpos2 = np.random.randn(3) qrot2 = uniform_quat(global_randstate) qpos2_combined = np.concatenate([qpos2, qrot2]) simulation.set_qpos("ball_one", qpos1_combined) simulation.set_qpos("ball_two", qpos2_combined) assert np.linalg.norm(simulation.get_qpos("ball_one") - qpos1_combined) < 1e-6 assert np.linalg.norm(simulation.get_qpos("ball_two") - qpos2_combined) < 1e-6 def test_more_complex_mujoco_setup(): xml = ( MujocoXML() .add_default_compiler_directive() .append( MujocoXML.from_string(XML_ARM) .add_name_prefix("arm_one:") .set_named_objects_attr("arm_one:ball", pos=[0, 1, 0]) ) .append( MujocoXML.from_string(XML_ARM) .add_name_prefix("arm_two:") .set_named_objects_attr("arm_two:ball", pos=[0, -1, 0]) ) ) simulation = SimulationInterface(xml.build()) simulation.register_joint_group("arm_one", "arm_one:") simulation.register_joint_group("arm_one_hinge", "arm_one:hinge_joint") simulation.register_joint_group("arm_two", "arm_two:") simulation.register_joint_group("arm_two_hinge", "arm_two:hinge_joint") assert simulation.get_qpos("arm_one").shape == (2,) assert simulation.get_qvel("arm_one").shape == (2,) assert simulation.get_qpos("arm_two").shape == (2,) assert simulation.get_qvel("arm_two").shape == (2,) assert simulation.get_qpos("arm_one_hinge").shape == (1,) assert simulation.get_qvel("arm_one_hinge").shape == (1,) assert simulation.get_qpos("arm_two_hinge").shape == (1,) assert simulation.get_qvel("arm_two_hinge").shape == (1,) initial_qpos_one = simulation.get_qpos("arm_one") initial_qpos_two = simulation.get_qpos("arm_two") simulation.set_qpos("arm_one_hinge", 0.1) # Chech that we are setting the right hinge joint assert np.linalg.norm(simulation.get_qpos("arm_one") - initial_qpos_one) > 0.09 assert np.linalg.norm(simulation.get_qpos("arm_two") - initial_qpos_two) < 1e-6 def test_set_attributes_mixed_precision(): main = ( MujocoXML() .add_default_compiler_directive() .append( MujocoXML.from_string(XML_BALL).set_named_objects_attr( "ball", pos=[1, 1e-8, 1e-12] ) ) ) simulation = SimulationInterface(main.build()) ball_id = simulation.sim.model.body_name2id("ball") ball_pos = simulation.sim.model.body_pos[ball_id] target_pos = np.array([1, 1e-8, 1e-12]) # test relative error cause absolute error can be quite small either way assert np.linalg.norm((ball_pos / target_pos) - 1) < 1e-6 def test_forward_kinematics_on_inverted_pendulum(): mxml = MujocoXML.parse( "test/inverted_pendulum/inverted_double_pendulum.xml" ).add_name_prefix("ivp:") simulation = SimulationInterface(mxml.build()) simulation.register_joint_group("pendulum", "ivp:") joint_names = list(map(lambda x: "ivp:%s" % x, ["hinge", "hinge2"])) site_names = list(map(lambda x: "ivp:%s" % x, ["hinge2_site", "tip"])) KIN = ForwardKinematics.prepare( mxml, "ivp:cart", np.zeros(3), np.zeros(3), site_names, joint_names ) for _ in range(5): simulation.mj_sim.data.ctrl[0] = random.random() for _ in range(100): simulation.step() simulation.forward() site_positions = np.array( [simulation.mj_sim.data.get_site_xpos(site) for site in site_names] ) joint_pos = simulation.get_qpos("pendulum") kinemetics_positions = KIN.compute(joint_pos, return_joint_pos=True) assert (np.abs(site_positions - kinemetics_positions[:2]) < 1e-6).all() assert (np.abs(site_positions[0] - kinemetics_positions[-1]) < 1e-6).all() def test_remove_elem(): ball_without_joint = MujocoXML.from_string(XML_BALL).remove_objects_by_tag( "freejoint" ) ref_xml = """ <mujoco> <worldbody> <body name="ball"> <geom name="sphere" pos="0.00 0.00 0.00" size="0.1 0.1 0.1" type="sphere" /> </body> </worldbody> </mujoco> """ assert ref_xml.strip() == ball_without_joint.xml_string().strip() def test_mj_error_callback(): message = None called = False def callback(msg): nonlocal message message = msg.decode() raise RuntimeError(message) cymj.set_error_callback(callback) try: with cymj.wrap_mujoco_warning(): functions.mju_error("error") except RuntimeError as e: assert e.args[0] == "error" assert message == "error" called = True assert called
6,728
29.726027
86
py
robogym
robogym-master/robogym/mujoco/modifiers/base.py
class Modifier: """ Base class for various MuJoCo modifiers """ def __init__(self): self.sim = None def initialize(self, sim): self.sim = sim def __call__(self, parameter_value): """ Apply given parameter to the sim """ raise NotImplementedError
297
21.923077
51
py
robogym
robogym-master/robogym/mujoco/modifiers/timestep.py
from robogym.mujoco.modifiers.base import Modifier class TimestepModifier(Modifier): """ Modify simulation timestep """ def __call__(self, timestep): self.sim.model.opt.timestep = timestep
208
22.222222
50
py
robogym
robogym-master/robogym/envs/dactyl/full_perpendicular.py
import functools import typing import attr import numpy as np import pycuber import robogym.utils.rotation as rotation from robogym.envs.dactyl.common.cube_env import ( CubeEnv, CubeSimulationInterface, DactylCubeEnvConstants, DactylCubeEnvParameters, ) from robogym.envs.dactyl.common.cube_manipulator import CubeManipulator from robogym.envs.dactyl.common.mujoco_modifiers import PerpendicularCubeSizeModifier from robogym.envs.dactyl.goals.face_cube_solver import FaceCubeSolverGoal from robogym.envs.dactyl.goals.face_curriculum import FaceCurriculumGoal from robogym.envs.dactyl.goals.face_free import FaceFreeGoal from robogym.envs.dactyl.goals.fixed_fair_scramble import FixedFairScrambleGoal from robogym.envs.dactyl.goals.full_unconstrained import FullUnconstrainedGoal from robogym.envs.dactyl.goals.release_cube_solver import ReleaseCubeSolverGoal from robogym.envs.dactyl.goals.unconstrained_cube_solver import UnconstrainedCubeSolver from robogym.envs.dactyl.observation.cube import ( GoalCubeRotObservation, MujocoCubePosObservation, MujocoCubeRotObservation, ) from robogym.envs.dactyl.observation.full_perpendicular import ( GoalCubePosObservation, GoalFaceAngleObservation, MujocoFaceAngleObservation, ) from robogym.envs.dactyl.observation.shadow_hand import ( MujocoShadowhandAngleObservation, MujocoShadowhandRelativeFingertipsObservation, ) from robogym.goal.goal_generator import GoalGenerator from robogym.mujoco.mujoco_xml import MujocoXML from robogym.observation.mujoco import MujocoQposObservation, MujocoQvelObservation from robogym.robot_env import ObservationMapValue as omv @attr.s(auto_attribs=True) class FullPerpendicularEnvParameters(DactylCubeEnvParameters): """ Parameters of the Dactyl Perpendicular env - possible to change for each episode """ # How many steps with random action do we take when the environment is initialized n_random_initial_steps: int = 10 # Multiplier of the cube size cube_size_multiplier: float = 1.0 @attr.s(auto_attribs=True) class FullPerpendicularEnvConstants(DactylCubeEnvConstants): """ Parameters of the Dactyl Perpendicular env - set once and for all """ # Number of mujoco simulation steps per environment step mujoco_substeps: int = 10 # How many steps with zero action to take on env reset reset_initial_steps: int = 20 # Threshold for success conditions success_threshold: dict = {"cube_quat": 0.4, "cube_face_angle": 0.2} max_timesteps_per_goal: int = 1600 # What kind of goal generation we want for the environment goal_generation: str = "face_free" # Which directions do we rotate the faces goal_directions: typing.List[str] = ["cw", "ccw"] # Are faces always rotated to round angles round_target_face: bool = True # Probability of cube reorient vs face rotation p_face_flip: float = 0.5 # How many times to scramble cube initially num_scramble_steps: int = 50 # Whether to scramble face angles at the beginning of each episode scramble_face_angles: bool = True # Whether to randomize face angles at the beginning of each episode. randomize_face_angles: bool = True class FullPerpendicularSimulation(CubeSimulationInterface): """ Simulation of a shadow hand manipulating full perpendicular cube """ @classmethod def _build_mujoco_cube_xml(cls, xml, cube_xml_path): xml.append( MujocoXML.parse(cube_xml_path) .add_name_prefix("cube:") .set_named_objects_attr("cube:middle", tag="body", pos=[1.0, 0.87, 0.2]) # Delete springs for now .remove_objects_by_prefix(prefix="cube:cubelet:spring:", tag="joint") ) # Target xml.append( MujocoXML.parse(cube_xml_path) .add_name_prefix("target:") .set_named_objects_attr("target:middle", tag="body", pos=[1.0, 0.87, 0.2]) # Delete springs for now .remove_objects_by_prefix(prefix="target:cubelet:spring:", tag="joint") # Disable collisions .set_objects_attr(tag="geom", group="2", conaffinity="0", contype="0") ) def __init__(self, sim): super().__init__(sim) self.cube_model = CubeManipulator(prefix="cube:", sim=sim) self.target_model = CubeManipulator(prefix="target:", sim=sim) self.register_joint_group("cube_position", prefix="cube:cube:t") self.register_joint_group("cube_rotation", prefix="cube:cube:rot") self.register_joint_group("cube_drivers", prefix="cube:cubelet:driver:") self.register_joint_group("cube_cubelets", prefix="cube:cubelet:") self.register_joint_group("target_position", prefix="target:cube:t") self.register_joint_group("target_rotation", prefix="target:cube:rot") self.register_joint_group("target_drivers", prefix="target:cubelet:driver:") self.register_joint_group("target_cubelets", prefix="target:cubelet:") self.register_joint_group("cube_all_joints", prefix="cube:") self.register_joint_group("target_all_joints", prefix="target:") self.register_joint_group("hand_angle", prefix="robot0:") def clone_target_from_cube(self): """ Clone target internal state from cube state """ self.set_qpos("target_cubelets", self.get_qpos("cube_cubelets")) def get_face_angles(self, target): """ Return "face angles" either from cube or from the target """ assert target in {"cube", "target"} return self.get_qpos("{}_drivers".format(target)) def align_target_faces(self): """ Align target orientation to given set of **straight** angles """ self.target_model.soft_align_faces() def rotate_target_face(self, axis, side, angle): """ Rotate given face of the target by given angle """ self.target_model.rotate_face(axis, side, angle) class FullPerpendicularEnv( CubeEnv[ FullPerpendicularEnvParameters, FullPerpendicularEnvConstants, FullPerpendicularSimulation, ] ): """ A dactyl Rubik's cube environment that aims to replicate physically accurately perpendicular rotations """ # Face angle is six numbers: one number for each cube face TARGET_ANGLE_SHAPE = 6 FACE_GEOM_NAMES = [ "cube:cubelet:neg_x", "cube:cubelet:pos_x", "cube:cubelet:neg_y", "cube:cubelet:pos_y", "cube:cubelet:neg_z", "cube:cubelet:pos_z", ] PYCUBER_ACTIONS = ["L", "L'", "R", "R'", "F", "F'", "B", "B'", "D", "D'", "U", "U'"] def _default_observation_map(self): return { "cube_pos": omv({"mujoco": MujocoCubePosObservation}), "cube_quat": omv({"mujoco": MujocoCubeRotObservation}), "cube_face_angle": omv({"mujoco": MujocoFaceAngleObservation}), "qpos": omv({"mujoco": MujocoQposObservation}), "qvel": omv({"mujoco": MujocoQvelObservation}), "perp_qpos": omv({"mujoco": MujocoQposObservation}), # Duplicate of qpos. "perp_qvel": omv({"mujoco": MujocoQvelObservation}), # Duplicate of qvel. "hand_angle": omv({"mujoco": MujocoShadowhandAngleObservation}), "fingertip_pos": omv( {"mujoco": MujocoShadowhandRelativeFingertipsObservation} ), "goal_pos": omv({"goal": GoalCubePosObservation}), "goal_quat": omv({"goal": GoalCubeRotObservation}), "goal_face_angle": omv({"goal": GoalFaceAngleObservation}), } @classmethod def build_goal_generation( cls, constants: FullPerpendicularEnvConstants, mujoco_simulation: CubeSimulationInterface, ) -> GoalGenerator: """ Construct a goal generation object """ if constants.goal_generation == "face_curr": return FaceCurriculumGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, goal_directions=constants.goal_directions, round_target_face=constants.round_target_face, p_face_flip=constants.p_face_flip, ) elif constants.goal_generation == "face_free": return FaceFreeGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, goal_directions=constants.goal_directions, round_target_face=constants.round_target_face, p_face_flip=constants.p_face_flip, ) elif constants.goal_generation == "face_cube_solver": return FaceCubeSolverGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, num_scramble_steps=constants.num_scramble_steps, ) elif constants.goal_generation == "release_cube_solver": return ReleaseCubeSolverGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, num_scramble_steps=constants.num_scramble_steps, ) elif constants.goal_generation == "full_unconstrained": return FullUnconstrainedGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, goal_directions=constants.goal_directions, round_target_face=constants.round_target_face, ) elif constants.goal_generation == "unconstrained_cube_solver": return UnconstrainedCubeSolver( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, num_scramble_steps=constants.num_scramble_steps, ) elif constants.goal_generation == "fixed_fair_scramble": return FixedFairScrambleGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, num_scramble_steps=constants.num_scramble_steps, ) else: raise RuntimeError( "Invalid 'goal_generation' constant '{}'".format( constants.goal_generation ) ) @classmethod def build_simulation(cls, constants, parameters): return FullPerpendicularSimulation.build( n_substeps=constants.mujoco_substeps, simulation_params=parameters.simulation_params, ) @classmethod def build_mujoco_modifiers(cls): modifiers = super().build_mujoco_modifiers() modifiers["cube_size_multiplier"] = PerpendicularCubeSizeModifier("cube:") return modifiers ############################################################################################### # Internal API - to be overridden - environment randomization def _scramble_cube(self): """ Scramble a cube randomly at the beginning of an episode """ cube = pycuber.Cube() for i in range(self.constants.num_scramble_steps): action = self._random_state.choice(self.PYCUBER_ACTIONS) cube.perform_step(action) self.mujoco_simulation.cube_model.from_pycuber(cube) def _scramble_face_angles(self): """ Scramble face angles randomly without moving cubelets in any way """ random_angles = self._random_state.choice([-2, -1, 0, 1, 2], size=6) * np.pi / 2 self.mujoco_simulation.set_qpos("cube_drivers", random_angles) def _randomize_cube_initial_position(self): """ Draw a random initial position for a cube """ # Original env had this, but I'm not really sure it's needed for i in range(self.constants.reset_initial_steps): ctrl = self.mujoco_simulation.shadow_hand.denormalize_position_control( self.mujoco_simulation.shadow_hand.zero_control() ) self.mujoco_simulation.shadow_hand.set_position_control(ctrl) self.mujoco_simulation.step() cube_translation = ( self._random_state.randn(3) * self.parameters.cube_position_wiggle_std ) self.mujoco_simulation.add_qpos("cube_position", cube_translation) cube_orientation = rotation.uniform_quat(self._random_state) self.mujoco_simulation.set_qpos("cube_rotation", cube_orientation) self._scramble_cube() if self.constants.scramble_face_angles: self._scramble_face_angles() if self.constants.randomize_face_angles: # Face angles random_face_angle = self._random_state.uniform( -np.pi / 4, np.pi / 4, size=2 ) # Face axes random_axis = self._random_state.randint(3) self.mujoco_simulation.cube_model.rotate_face( random_axis, 0, random_face_angle[0] ) self.mujoco_simulation.cube_model.rotate_face( random_axis, 1, random_face_angle[1] ) # Need to call this after the qpos is modified self.mujoco_simulation.forward() action = self._random_state.uniform(-1.0, 1.0, self.action_space.shape[0]) for _ in range(self.parameters.n_random_initial_steps): ctrl = self.mujoco_simulation.shadow_hand.denormalize_position_control( action ) self.mujoco_simulation.shadow_hand.set_position_control(ctrl) self.mujoco_simulation.step() ############################################################################################### # External API - to establish communication with other parts of the system @property def cube_type(self): """ Type of cube """ return "full-perpendicular" @property def face_joint_names(self): # Needed by some wrappers return [ # Need to drop 'cube:' prefix x[5:] for x in self.mujoco_simulation.cube_model.joints ] ############################################################################################### # Fully internal methods def _render_callback(self, _sim, _viewer): """ Set a render callback """ self.mujoco_simulation.set_qpos("target_position", np.array([0.15, 0, -0.03])) self.mujoco_simulation.set_qpos("target_rotation", self._goal["cube_quat"]) self.mujoco_simulation.set_qpos("target_drivers", self._goal["cube_face_angle"]) self.mujoco_simulation.set_qvel("target_all_joints", 0.0) self.mujoco_simulation.forward() @classmethod def _get_default_wrappers(cls): default_wrappers = super()._get_default_wrappers() default_wrappers.update( { "default_observation_noise_levels": { "fingertip_pos": {"uncorrelated": 0.002, "additive": 0.001}, "hand_angle": {"additive": 0.1, "uncorrelated": 0.1}, "cube_pos": {"additive": 0.005, "uncorrelated": 0.001}, "cube_quat": {"additive": 0.1, "uncorrelated": 0.09}, "cube_face_angle": {"additive": 0.1, "uncorrelated": 0.1}, }, "default_no_noise_levels": { "fingertip_pos": {}, "hand_angle": {}, "cube_pos": {}, "cube_quat": {}, "cube_face_angle": {}, }, "default_observation_delay_levels": { "interpolators": { "cube_quat": "QuatInterpolator", "cube_face_angle": "RadianInterpolator", }, "groups": { # Uncomment below to enable observation delay randomization. # "vision": { # "obs_names": ["cube_pos", "cube_quat"], # "mean": 3, # "std": 0.5, # }, # "giiker": { # "obs_names": ["cube_face_angle"], # "mean": 1, # "std": 0.2, # }, # "phasespace": { # "obs_names": ["fingertip_pos"], # "mean": 0.5, # "std": 0.1, # } }, }, "default_no_observation_delay_levels": { "interpolators": {}, "groups": {}, }, "pre_obsnoise_randomizations": [ ["RandomizedActionLatency"], ["RandomizedPerpendicularCubeSizeWrapper"], ["RandomizedBodyInertiaWrapper"], ["RandomizedTimestepWrapper"], ["RandomizedRobotFrictionWrapper"], ["RandomizedCubeFrictionWrapper"], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ["RandomizedPhasespaceFingersWrapper"], ["RandomizedRobotDampingWrapper"], ["RandomizedRobotKpWrapper"], ["RandomizedFaceDampingWrapper"], ["RandomizedJointLimitWrapper"], ["RandomizedTendonRangeWrapper"], ], } ) return default_wrappers make_simple_env = functools.partial(FullPerpendicularEnv.build, apply_wrappers=False) make_env = FullPerpendicularEnv.build
18,202
39.541203
99
py
robogym
robogym-master/robogym/envs/dactyl/reach.py
import functools import typing import attr import numpy as np from robogym.envs.dactyl.observation.reach import ( GoalFingertipPosObservation, GoalIsAchievedObservation, ) from robogym.envs.dactyl.observation.shadow_hand import ( MujocoShadowhandAbsoluteFingertipsObservation, MujocoShadowHandJointPosObservation, MujocoShadowHandJointVelocityObservation, ) from robogym.goal.goal_generator import GoalGenerator from robogym.mujoco.mujoco_xml import MujocoXML from robogym.mujoco.simulation_interface import SimulationInterface from robogym.observation.goal import GoalObservationProvider from robogym.observation.mujoco import MujocoObservationProvider, ObservationProvider from robogym.robot.shadow_hand.hand_forward_kinematics import FINGERTIP_SITE_NAMES from robogym.robot.shadow_hand.mujoco.mujoco_shadow_hand import MuJoCoShadowHand from robogym.robot_env import ObservationMapValue as omv from robogym.robot_env import RobotEnv, RobotEnvConstants, RobotEnvParameters from robogym.wrappers import dactyl, randomizations, util DEFAULT_NOISE_LEVELS: typing.Dict[str, dict] = { "fingertip_pos": {"uncorrelated": 0.001, "additive": 0.001}, } NO_NOISE_LEVELS: typing.Dict[str, dict] = { key: {} for key in DEFAULT_NOISE_LEVELS.keys() } @attr.s(auto_attribs=True) class ReachEnvParameters(RobotEnvParameters): """ Parameters of the shadow hand reach env - possible to change for each episode. """ pass @attr.s(auto_attribs=True) class ReachEnvConstants(RobotEnvConstants): """ Parameters of the shadow hand reach env - same for all episodes. """ success_threshold: dict = {"fingertip_pos": 0.025} # If specified, freeze all other fingers. active_finger: typing.Optional[str] = None # Overwrite the following constants regarding rewards. successes_needed: int = 50 max_timesteps_per_goal: int = 150 class ReachSimulation(SimulationInterface): """ Simulation interface for shadow hand reach env. """ # Just a floor FLOOR_XML = "floor/basic_floor.xml" # Target fingertip sites. TARGET_XML = "shadowhand_reach/target.xml" # Robot hand xml HAND_XML = "robot/shadowhand/main.xml" # XML with default light LIGHT_XML = "light/default.xml" def __init__(self, sim): super().__init__(sim) self.enable_pid() self.shadow_hand = MuJoCoShadowHand(self) @classmethod def build(cls, n_substeps: int = 10): """Construct a ShadowHandReachSimulation object. :param n_substeps: (int) sim.nsubsteps, num of substeps :return: a ShadowHandReachSimulation object with properly constructed sim. """ xml = MujocoXML() xml.add_default_compiler_directive() xml.append( MujocoXML.parse(cls.FLOOR_XML).set_named_objects_attr( "floor", tag="body", pos=[1, 1, 0] ) ) target = MujocoXML.parse(cls.TARGET_XML) colors = [ [1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 0.0, 1.0, 1.0], ] for site, color in zip(FINGERTIP_SITE_NAMES, colors): target.set_named_objects_attr( f"target_{site}", pos=[0.5, 0.5, 0.0], type="sphere", rgba=color, size=0.005, ) xml.append(target) xml.append( MujocoXML.parse(cls.HAND_XML) .add_name_prefix("robot0:") .set_named_objects_attr( "robot0:hand_mount", tag="body", pos=[1.0, 1.25, 0.15], euler=[np.pi / 2, 0, np.pi], ) .remove_objects_by_name("robot0:annotation:outer_bound") # Remove hand base free joint so that hand is immovable .remove_objects_by_name("robot0:hand_base") ) xml.append(MujocoXML.parse(cls.LIGHT_XML)) simulation = cls(xml.build(nsubsteps=n_substeps)) # Move fingers out of the way. simulation.shadow_hand.set_position_control( simulation.shadow_hand.denormalize_position_control( simulation.shadow_hand.zero_control() ) ) for _ in range(20): simulation.step() return simulation class ReachEnv(RobotEnv[ReachEnvParameters, ReachEnvConstants, ReachSimulation]): """ Environment with the ShadowHand and a locked cube (i.e. no moving pieces, just a solid block). """ def _build_observation_providers(self): """ Initialize observation providers for the environment. """ providers: typing.Dict[str, ObservationProvider] = { "mujoco": MujocoObservationProvider(self.mujoco_simulation), "goal": GoalObservationProvider(lambda: self.goal_info()), } return providers def _default_observation_map(self): return { "qpos": omv({"mujoco": MujocoShadowHandJointPosObservation}), "qvel": omv({"mujoco": MujocoShadowHandJointVelocityObservation}), "fingertip_pos": omv( {"mujoco": MujocoShadowhandAbsoluteFingertipsObservation} ), "goal_fingertip_pos": omv({"goal": GoalFingertipPosObservation}), "is_goal_achieved": omv({"goal": GoalIsAchievedObservation}), } @classmethod def build_goal_generation( cls, constants, mujoco_simulation: ReachSimulation ) -> GoalGenerator: """ Construct a goal generation object """ goal_simulation = ReachSimulation.build(n_substeps=mujoco_simulation.n_substeps) sim = goal_simulation.mj_sim # Make sure fingers are separated. # For transfer, want to make sure post-noise locations are achievable. sim.model.geom_margin[:] = sim.model.geom_margin + 0.002 from robogym.envs.dactyl.goals.shadow_hand_reach_fingertip_pos import ( FingertipPosGoal, ) return FingertipPosGoal(mujoco_simulation, goal_simulation) @classmethod def build_simulation(cls, constants, parameters): return ReachSimulation.build(n_substeps=constants.mujoco_substeps) @classmethod def build_robot(cls, mujoco_simulation, physical): return mujoco_simulation.shadow_hand def _render_callback(self, _sim, _viewer): """ Set a render callback """ goal_fingertip_pos = self._goal["fingertip_pos"].reshape(-1, 3) for finger_idx, site in enumerate(FINGERTIP_SITE_NAMES): goal_pos = goal_fingertip_pos[finger_idx] site_id = _sim.model.site_name2id(f"target_{site}") _sim.data.site_xpos[site_id] = goal_pos def _reset(self): super()._reset() self.constants.success_pause_range_s = (0.0, 0.5) def apply_wrappers(self, **wrapper_params): """ Apply wrappers to the environment. """ self.constants: ReachEnvConstants env = util.ClipActionWrapper(self) if self.constants.active_finger is not None: env = dactyl.FingerSeparationWrapper( env, active_finger=self.constants.active_finger ) if self.constants.randomize: env = randomizations.RandomizedActionLatency(env) env = randomizations.RandomizedBodyInertiaWrapper(env) env = randomizations.RandomizedTimestepWrapper(env) env = randomizations.RandomizedRobotFrictionWrapper(env) env = randomizations.RandomizedGravityWrapper(env) env = dactyl.RandomizedPhasespaceFingersWrapper(env) env = dactyl.RandomizedRobotDampingWrapper(env) env = dactyl.RandomizedRobotKpWrapper(env) noise_levels = DEFAULT_NOISE_LEVELS else: noise_levels = NO_NOISE_LEVELS # must happen before angle observation wrapper env = randomizations.RandomizeObservationWrapper(env, levels=noise_levels) if self.constants.randomize: env = dactyl.FingersFreezingPhasespaceMarkers(env) env = randomizations.ActionNoiseWrapper(env) env = util.SmoothActionWrapper( env ) # this get's applied before noise is added (important) env = util.RelativeGoalWrapper(env) env = util.UnifiedGoalObservationWrapper(env, goal_parts=["fingertip_pos"]) env = util.ClipObservationWrapper(env) env = util.ClipRewardWrapper(env) env = util.PreviousActionObservationWrapper(env) env = util.DiscretizeActionWrapper( env, n_action_bins=self.constants.n_action_bins ) # Note: Recording wrapper is removed here to favor simplicity. return env make_simple_env = functools.partial(ReachEnv.build, apply_wrappers=False) make_env = ReachEnv.build
8,954
32.920455
90
py
robogym
robogym-master/robogym/envs/dactyl/face_perpendicular.py
import functools import logging from typing import List import attr import numpy as np import robogym.utils.rotation as rotation from robogym.envs.dactyl.common.cube_env import ( CubeEnv, CubeSimulationInterface, DactylCubeEnvConstants, DactylCubeEnvParameters, ) from robogym.envs.dactyl.common.mujoco_modifiers import PerpendicularCubeSizeModifier from robogym.envs.dactyl.goals.face_curriculum import FaceCurriculumGoal from robogym.envs.dactyl.goals.face_free import FaceFreeGoal from robogym.envs.dactyl.observation.cube import ( GoalCubeRotObservation, MujocoCubePosObservation, MujocoCubeRotObservation, ) from robogym.envs.dactyl.observation.face_perpendicular import ( GoalCubePosObservation, GoalFaceAngleObservation, MujocoFaceAngleObservation, ) from robogym.envs.dactyl.observation.shadow_hand import ( MujocoShadowhandAngleObservation, MujocoShadowhandRelativeFingertipsObservation, ) from robogym.goal.goal_generator import GoalGenerator from robogym.mujoco.mujoco_xml import MujocoXML from robogym.observation.mujoco import MujocoQposObservation, MujocoQvelObservation from robogym.robot_env import ObservationMapValue as omv logger = logging.getLogger(__name__) @attr.s(auto_attribs=True) class FacePerpendicularEnvParameters(DactylCubeEnvParameters): """ Parameters of the Dactyl Face Perpendicular env - possible to change for each episode""" pass @attr.s(auto_attribs=True) class FacePerpendicularEnvConstants(DactylCubeEnvConstants): """ Parameters of the Dactyl Perpendicular env - set once and for all """ # Threshold for success conditions success_threshold: dict = {"cube_quat": 0.4, "cube_face_angle": 0.2} # What kind of goal generation we want for the environment goal_generation: str = "face_curr" ##################### # Curriculum settings # Which directions do we rotate the faces goal_directions: List[str] = ["cw", "ccw"] # Are faces always rotated to round angles round_target_face: bool = True # Probability of cube reorient vs face rotation p_face_flip: float = 0.25 class FacePerpendicularSimulation(CubeSimulationInterface): """ Simulation of a shadow hand manipulating a face cube """ @classmethod def _build_mujoco_cube_xml(cls, xml, cube_xml_path): xml.append( MujocoXML.parse(cube_xml_path) .add_name_prefix("cube:") .set_named_objects_attr("cube:middle", tag="body", pos=[1.0, 0.87, 0.2]) # Leave +/- z driver joints .remove_objects_by_name(names="cube:cubelet:driver:neg_x", tag="joint") .remove_objects_by_name(names="cube:cubelet:driver:pos_x", tag="joint") .remove_objects_by_name(names="cube:cubelet:driver:neg_y", tag="joint") .remove_objects_by_name(names="cube:cubelet:driver:pos_y", tag="joint") # Remove x/y cubelet hinge joints .remove_objects_by_prefix(prefix="cube:cubelet:rotx:", tag="joint") .remove_objects_by_prefix(prefix="cube:cubelet:roty:", tag="joint") # Delete springs for now .remove_objects_by_prefix(prefix="cube:cubelet:spring:", tag="joint") # Remove remaining cubelet joints we're not interested in .remove_objects_by_name( names=[ "cube:cubelet:rotz:neg_x_pos_y", "cube:cubelet:rotz:neg_x_neg_y", "cube:cubelet:rotz:pos_x_pos_y", "cube:cubelet:rotz:pos_x_neg_y", ], tag="joint", ) ) # Target xml.append( MujocoXML.parse(cube_xml_path) .add_name_prefix("target:") .set_named_objects_attr("target:middle", tag="body", pos=[1.0, 0.87, 0.2]) # Disable collisions .set_objects_attr(tag="geom", group="2", conaffinity="0", contype="0") # Leave +/- z driver joints .remove_objects_by_name(names="target:cubelet:driver:neg_x", tag="joint") .remove_objects_by_name(names="target:cubelet:driver:pos_x", tag="joint") .remove_objects_by_name(names="target:cubelet:driver:neg_y", tag="joint") .remove_objects_by_name(names="target:cubelet:driver:pos_y", tag="joint") # Remove x/y cubelet hinge joints .remove_objects_by_prefix(prefix="target:cubelet:rotx:", tag="joint") .remove_objects_by_prefix(prefix="target:cubelet:roty:", tag="joint") .remove_objects_by_prefix(prefix="target:cubelet:spring:", tag="joint") # Remove remaining cubelet joints we're not interested in .remove_objects_by_name( names=[ "target:cubelet:rotz:neg_x_pos_y", "target:cubelet:rotz:neg_x_neg_y", "target:cubelet:rotz:pos_x_pos_y", "target:cubelet:rotz:pos_x_neg_y", ], tag="joint", ) ) def __init__(self, mujoco_simulation): super().__init__(mujoco_simulation) self.register_joint_group("cube_position", prefix="cube:cube:t") self.register_joint_group("cube_rotation", prefix="cube:cube:rot") self.register_joint_group_by_name( "cube_top_face_driver", name="cube:cubelet:driver:pos_z" ) self.register_joint_group_by_name( "cube_bottom_face_driver", name="cube:cubelet:driver:neg_z" ) self.register_joint_group_by_name( "cube_drivers", name=["cube:cubelet:driver:pos_z", "cube:cubelet:driver:neg_z"], ) self.register_joint_group_by_name( "cube_top_face", name=[ "cube:cubelet:driver:pos_z", "cube:cubelet:rotz:neg_x_pos_y_pos_z", "cube:cubelet:rotz:neg_x_neg_y_pos_z", "cube:cubelet:rotz:neg_x_pos_z", "cube:cubelet:rotz:pos_x_pos_z", "cube:cubelet:rotz:pos_x_neg_y_pos_z", "cube:cubelet:rotz:pos_x_pos_y_pos_z", "cube:cubelet:rotz:neg_y_pos_z", "cube:cubelet:rotz:pos_y_pos_z", ], ) self.register_joint_group_by_name( "cube_bottom_face", name=[ "cube:cubelet:driver:neg_z", "cube:cubelet:rotz:neg_x_pos_y_neg_z", "cube:cubelet:rotz:neg_x_neg_y_neg_z", "cube:cubelet:rotz:neg_x_neg_z", "cube:cubelet:rotz:pos_x_neg_z", "cube:cubelet:rotz:pos_x_neg_y_neg_z", "cube:cubelet:rotz:pos_x_pos_y_neg_z", "cube:cubelet:rotz:neg_y_neg_z", "cube:cubelet:rotz:pos_y_neg_z", ], ) self.register_joint_group("cube_springs", prefix="cube:cubelet:spring:") self.register_joint_group("target_position", prefix="target:cube:t") self.register_joint_group("target_rotation", prefix="target:cube:rot") self.register_joint_group_by_name( "target_top_face_driver", name="target:cubelet:driver:pos_z" ) self.register_joint_group_by_name( "target_bottom_face_driver", name="target:cubelet:driver:neg_z" ) self.register_joint_group_by_name( "target_drivers", name=["target:cubelet:driver:pos_z", "target:cubelet:driver:neg_z"], ) self.register_joint_group_by_name( "target_top_face", name=[ "target:cubelet:driver:pos_z", "target:cubelet:rotz:neg_x_pos_y_pos_z", "target:cubelet:rotz:neg_x_neg_y_pos_z", "target:cubelet:rotz:neg_x_pos_z", "target:cubelet:rotz:pos_x_pos_z", "target:cubelet:rotz:pos_x_neg_y_pos_z", "target:cubelet:rotz:pos_x_pos_y_pos_z", "target:cubelet:rotz:neg_y_pos_z", "target:cubelet:rotz:pos_y_pos_z", ], ) self.register_joint_group_by_name( "target_bottom_face", name=[ "target:cubelet:driver:neg_z", "target:cubelet:rotz:neg_x_pos_y_neg_z", "target:cubelet:rotz:neg_x_neg_y_neg_z", "target:cubelet:rotz:neg_x_neg_z", "target:cubelet:rotz:pos_x_neg_z", "target:cubelet:rotz:pos_x_neg_y_neg_z", "target:cubelet:rotz:pos_x_pos_y_neg_z", "target:cubelet:rotz:neg_y_neg_z", "target:cubelet:rotz:pos_y_neg_z", ], ) self.register_joint_group("target_springs", prefix="target:cubelet:spring:") self.register_joint_group("target_all_joints", prefix="target:") self.register_joint_group("hand_angle", prefix="robot0:") def set_face_angles(self, target, angles): assert target in {"cube", "target"} self.set_qpos("{}_top_face".format(target), angles[0]) self.set_qpos("{}_bottom_face".format(target), angles[1]) def get_face_angles(self, target): assert target in {"cube", "target"} return self.get_qpos("{}_drivers".format(target)) def rotate_target_face(self, side, angle): """ Rotate given face of the target by given angle """ qpos = self.get_face_angles("target") qpos[side] += angle self.set_face_angles("target", qpos) def clone_target_from_cube(self): """ Clone target internal state from cube state """ self.set_face_angles("target", self.get_face_angles("cube")) def align_target_faces(self): """ Align target orientation to straight orientation of the cube """ self.set_face_angles( "target", rotation.round_to_straight_angles(self.get_face_angles("target")) ) class FacePerpendicularEnv( CubeEnv[ FacePerpendicularEnvParameters, FacePerpendicularEnvConstants, FacePerpendicularSimulation, ] ): """ A dactyl Rubik's cube environment that aims to replicate dactyl face env using simpler code """ # Target angle is two numbers: top face angle and bottom face angle TARGET_ANGLE_SHAPE = 2 FACE_GEOM_NAMES = ["cube:cubelet:pos_z", "cube:cubelet:neg_z"] FACE_JOINT_NAMES = [ "cubelet:driver:pos_z", "cubelet:rotz:neg_x_pos_y_pos_z", "cubelet:rotz:neg_x_neg_y_pos_z", "cubelet:rotz:neg_x_pos_z", "cubelet:rotz:pos_x_pos_z", "cubelet:rotz:pos_x_neg_y_pos_z", "cubelet:rotz:pos_x_pos_y_pos_z", "cubelet:rotz:neg_y_pos_z", "cubelet:rotz:pos_y_pos_z", "cubelet:driver:neg_z", "cubelet:rotz:neg_x_pos_y_neg_z", "cubelet:rotz:neg_x_neg_y_neg_z", "cubelet:rotz:neg_x_neg_z", "cubelet:rotz:pos_x_neg_z", "cubelet:rotz:pos_x_neg_y_neg_z", "cubelet:rotz:pos_x_pos_y_neg_z", "cubelet:rotz:neg_y_neg_z", "cubelet:rotz:pos_y_neg_z", ] def _default_observation_map(self): return { "cube_pos": omv({"mujoco": MujocoCubePosObservation}), "cube_quat": omv({"mujoco": MujocoCubeRotObservation}), "cube_face_angle": omv({"mujoco": MujocoFaceAngleObservation}), "qpos": omv({"mujoco": MujocoQposObservation}), "qvel": omv({"mujoco": MujocoQvelObservation}), "perp_qpos": omv({"mujoco": MujocoQposObservation}), # Duplicate of qpos. "perp_qvel": omv({"mujoco": MujocoQvelObservation}), # Duplicate of qvel. "hand_angle": omv({"mujoco": MujocoShadowhandAngleObservation}), "fingertip_pos": omv( {"mujoco": MujocoShadowhandRelativeFingertipsObservation} ), "goal_pos": omv({"goal": GoalCubePosObservation}), "goal_quat": omv({"goal": GoalCubeRotObservation}), "goal_face_angle": omv({"goal": GoalFaceAngleObservation}), } @classmethod def build_goal_generation( cls, constants: FacePerpendicularEnvConstants, mujoco_simulation: FacePerpendicularSimulation, ) -> GoalGenerator: """ Construct a goal generation object """ if constants.goal_generation == "face_curr": return FaceCurriculumGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, goal_directions=constants.goal_directions, round_target_face=constants.round_target_face, p_face_flip=constants.p_face_flip, ) elif constants.goal_generation == "face_free": return FaceFreeGoal( mujoco_simulation=mujoco_simulation, success_threshold=constants.success_threshold, face_geom_names=cls.FACE_GEOM_NAMES, goal_directions=constants.goal_directions, round_target_face=constants.round_target_face, p_face_flip=constants.p_face_flip, ) else: raise RuntimeError( "Invalid 'goal_generation' constant '{}'".format( constants.goal_generation ) ) @classmethod def build_simulation(cls, constants, parameters): return FacePerpendicularSimulation.build( n_substeps=constants.mujoco_substeps, simulation_params=parameters.simulation_params, ) @classmethod def build_mujoco_modifiers(cls): modifiers = super().build_mujoco_modifiers() modifiers["cube_size_multiplier"] = PerpendicularCubeSizeModifier("cube:") return modifiers ############################################################################################### # Internal API - to be overridden - environment randomization def _randomize_cube_initial_position(self): """ Draw a random initial position for a cube """ # Original env had this, but I'm not really sure it's needed for i in range(self.constants.reset_initial_steps): ctrl = self.mujoco_simulation.shadow_hand.denormalize_position_control( self.mujoco_simulation.shadow_hand.zero_control() ) self.mujoco_simulation.shadow_hand.set_position_control(ctrl) self.mujoco_simulation.step() cube_translation = ( self._random_state.randn(3) * self.parameters.cube_position_wiggle_std ) self.mujoco_simulation.add_qpos("cube_position", cube_translation) cube_orientation = rotation.uniform_quat(self._random_state) self.mujoco_simulation.set_qpos("cube_rotation", cube_orientation) random_face_angle = self._random_state.uniform(-np.pi / 4, np.pi / 4, 2) self.mujoco_simulation.set_face_angles("cube", random_face_angle) # Need to call this after the qpos is modified self.mujoco_simulation.forward() action = self._random_state.uniform(-1.0, 1.0, self.action_space.shape[0]) for _ in range(self.parameters.n_random_initial_steps): ctrl = self.mujoco_simulation.shadow_hand.denormalize_position_control( action ) self.mujoco_simulation.shadow_hand.set_position_control(ctrl) self.mujoco_simulation.step() ############################################################################################### # External API - to establish communication with other parts of the system @property def cube_type(self): """ Type of cube """ return "face-perpendicular" @property def face_joint_names(self): """ Used by some wrapper """ return self.FACE_JOINT_NAMES ############################################################################################### # Fully internal methods def _render_callback(self, _sim, _viewer): """ Set a render callback """ self.mujoco_simulation.set_qpos("target_position", np.array([0.15, 0, -0.03])) self.mujoco_simulation.set_qpos("target_rotation", self._goal["cube_quat"]) self.mujoco_simulation.set_face_angles("target", self._goal["cube_face_angle"]) self.mujoco_simulation.set_qvel("target_position", 0.0) self.mujoco_simulation.set_qvel("target_rotation", 0.0) self.mujoco_simulation.set_qvel("target_top_face", 0.0) self.mujoco_simulation.set_qvel("target_bottom_face", 0.0) self.mujoco_simulation.forward() @classmethod def _get_default_wrappers(cls): default_wrappers = super()._get_default_wrappers() default_wrappers.update( { "default_observation_noise_levels": { "fingertip_pos": {"uncorrelated": 0.002, "additive": 0.001}, "hand_angle": {"additive": 0.1, "uncorrelated": 0.1}, "cube_pos": {"additive": 0.005, "uncorrelated": 0.001}, "cube_quat": {"additive": 0.1, "uncorrelated": 0.09}, "cube_face_angle": {"additive": 0.1, "uncorrelated": 0.1}, }, "default_no_noise_levels": { "fingertip_pos": {}, "hand_angle": {}, "cube_pos": {}, "cube_quat": {}, "cube_face_angle": {}, }, "default_observation_delay_levels": { "interpolators": { "cube_quat": "QuatInterpolator", "cube_face_angle": "RadianInterpolator", }, "groups": { # Uncomment below to enable observation delay randomization. # "vision": { # "obs_names": ["cube_pos", "cube_quat"], # "mean": 3, # "std": 0.5, # }, # "giiker": { # "obs_names": ["cube_face_angle"], # "mean": 1, # "std": 0.2, # }, # "phasespace": { # "obs_names": ["fingertip_pos"], # "mean": 0.5, # "std": 0.1, # } }, }, "default_no_observation_delay_levels": { "interpolators": {}, "groups": {}, }, "pre_obsnoise_randomizations": [ ["RandomizedActionLatency"], ["RandomizedPerpendicularCubeSizeWrapper"], ["RandomizedBodyInertiaWrapper"], ["RandomizedTimestepWrapper"], ["RandomizedRobotFrictionWrapper"], ["RandomizedCubeFrictionWrapper"], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ["RandomizedPhasespaceFingersWrapper"], ["RandomizedRobotDampingWrapper"], ["RandomizedRobotKpWrapper"], ["RandomizedFaceDampingWrapper"], ["RandomizedJointLimitWrapper"], ["RandomizedTendonRangeWrapper"], ], } ) return default_wrappers make_simple_env = functools.partial(FacePerpendicularEnv.build, apply_wrappers=False) make_env = FacePerpendicularEnv.build
19,795
39.154158
99
py
robogym
robogym-master/robogym/envs/dactyl/locked.py
import functools import attr import numpy as np import robogym.utils.rotation as rotation from robogym.envs.dactyl.common.cube_env import ( CubeEnv, CubeSimulationInterface, CubeSimulationParameters, DactylCubeEnvConstants, DactylCubeEnvParameters, ) from robogym.envs.dactyl.common.mujoco_modifiers import LockedCubeSizeModifier from robogym.envs.dactyl.goals.locked_parallel import LockedParallelGoal from robogym.envs.dactyl.observation.cube import ( GoalCubeRotObservation, GoalIsAchievedObservation, GoalQposObservation, MujocoCubePosObservation, MujocoCubeRotObservation, ) from robogym.envs.dactyl.observation.locked import GoalCubePosObservation from robogym.envs.dactyl.observation.shadow_hand import ( MujocoShadowhandAngleObservation, MujocoShadowhandRelativeFingertipsObservation, ) from robogym.goal.goal_generator import GoalGenerator from robogym.mujoco.mujoco_xml import MujocoXML from robogym.observation.image import ImageObservation from robogym.observation.mujoco import MujocoQposObservation, MujocoQvelObservation from robogym.robot_env import ObservationMapValue as omv from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class LockedSimulationParameters(CubeSimulationParameters): cube_appearance: str = "texture" @attr.s(auto_attribs=True) class LockedEnvParameters(DactylCubeEnvParameters): """ Parameters of the Dactyl Locked env - possible to change for each episode. """ simulation_params: LockedSimulationParameters = build_nested_attr( LockedSimulationParameters ) @attr.s(auto_attribs=True) class LockedEnvConstants(DactylCubeEnvConstants): """ Parameters of the Dactyl Locked env - same for all episodes. """ # Max number of steps before considering goal is unreachable. max_steps_goal_unreachable: int = 10 # Threshold for success conditions success_threshold: dict = {"cube_quat": 0.4} # Goal generation. goal_generation: str = "state" # If use vision base observations. vision_observations: bool = False # If use vision base goal observation. vision_goal: bool = False class LockedSimulation(CubeSimulationInterface): """ Simulation of ShadowHand manipulating the locked cube. """ # Perpendicular cube model CUBE_XML_PATH_PATTERN = "rubik/rubik_locked{suffix}.xml" @classmethod def _build_mujoco_cube_xml(cls, xml, cube_xml_path): xml.append( MujocoXML.parse(cube_xml_path) .remove_objects_by_name("annotation:outer_bound") .add_name_prefix("cube:") .set_named_objects_attr("cube:middle", tag="body", pos=[1.0, 0.87, 0.2]) .set_named_objects_attr("cube:middle", tag="geom", density=421.0) ) # Target cube xml.append( MujocoXML.parse(cube_xml_path) .remove_objects_by_name("annotation:outer_bound") .add_name_prefix("target:") .set_named_objects_attr("target:middle", tag="body", pos=[1.0, 0.87, 0.2]) # Disable collisions .set_objects_attr(tag="geom", group="2", conaffinity="0", contype="0") ) @classmethod def _get_model_xml_path_and_params(cls, cube_appearance): if cube_appearance == "texture": cube_xml_path = cls.CUBE_XML_PATH_PATTERN.format(suffix="") elif cube_appearance == "material": cube_xml_path = cls.CUBE_XML_PATH_PATTERN.format(suffix="_material_cells") elif cube_appearance == "obstacles": cube_xml_path = cls.CUBE_XML_PATH_PATTERN.format(suffix="_with_obstacles") elif cube_appearance == "openai": cube_xml_path = cls.CUBE_XML_PATH_PATTERN.format(suffix="_openai") else: raise ValueError(f"Unrecognized cube appearance: {cube_appearance}") return cube_xml_path, {} def __init__(self, mujoco_simulation): super().__init__(mujoco_simulation) self.register_joint_group("cube_position", prefix="cube:cube_t") self.register_joint_group("cube_rotation", prefix="cube:cube_rot") self.register_joint_group("target_position", prefix="target:cube_t") self.register_joint_group("target_rotation", prefix="target:cube_rot") self.register_joint_group("target_all_joints", prefix="target:") self.register_joint_group("hand_angle", prefix="robot0:") class LockedEnv(CubeEnv[LockedEnvParameters, LockedEnvConstants, LockedSimulation]): """ Environment with the ShadowHand and a locked cube (i.e. no moving pieces, just a solid block). """ def _default_observation_map(self): obs_map = { "cube_pos": omv({"mujoco": MujocoCubePosObservation}), "cube_quat": omv({"mujoco": MujocoCubeRotObservation}), "qpos": omv({"mujoco": MujocoQposObservation}), "qvel": omv({"mujoco": MujocoQvelObservation}), "hand_angle": omv({"mujoco": MujocoShadowhandAngleObservation}), "fingertip_pos": omv( {"mujoco": MujocoShadowhandRelativeFingertipsObservation} ), "goal_pos": omv({"goal": GoalCubePosObservation}), "goal_quat": omv({"goal": GoalCubeRotObservation}), "qpos_goal": omv({"goal": GoalQposObservation}), "is_goal_achieved": omv({"goal": GoalIsAchievedObservation}), } if self.constants.vision_observations: # Add image observations for vision based policy rollout. obs_map.update( { "vision": omv( {"dummy_vision": ImageObservation}, default="dummy_vision" ) } ) if self.constants.vision_goal: obs_map.update( { "vision_goal": omv( { "goal": ImageObservation, "goal_render_image": ImageObservation, "goal_dummy_vision": ImageObservation, }, default="goal_dummy_vision", ), } ) return obs_map @classmethod def build_goal_generation(cls, constants, mujoco_simulation) -> GoalGenerator: """ Construct a goal generation object """ assert ( constants.goal_generation == "state" ), "Only state based goal generation is supported" return LockedParallelGoal(mujoco_simulation) @classmethod def build_simulation(cls, constants, parameters): return LockedSimulation.build( n_substeps=constants.mujoco_substeps, simulation_params=parameters.simulation_params, ) @classmethod def build_mujoco_modifiers(cls): modifiers = super().build_mujoco_modifiers() modifiers["cube_size_multiplier"] = LockedCubeSizeModifier("cube:") return modifiers ############################################################################################### # Internal API def _randomize_cube_initial_position(self): """ Draw a random initial position for a cube """ # Original env had this, but I'm not really sure it's needed for i in range(self.constants.reset_initial_steps): ctrl = self.mujoco_simulation.shadow_hand.denormalize_position_control( self.mujoco_simulation.shadow_hand.zero_control() ) self.mujoco_simulation.shadow_hand.set_position_control(ctrl) self.mujoco_simulation.step() cube_translation = ( self._random_state.randn(3) * self.parameters.cube_position_wiggle_std ) self.mujoco_simulation.add_qpos("cube_position", cube_translation) cube_orientation = rotation.uniform_quat(self._random_state) self.mujoco_simulation.set_qpos("cube_rotation", cube_orientation) # Need to call this after the qpos is modified self.mujoco_simulation.forward() action = self._random_state.uniform(-1.0, 1.0, self.action_space.shape[0]) for _ in range(self.parameters.n_random_initial_steps): ctrl = self.mujoco_simulation.shadow_hand.denormalize_position_control( action ) self.mujoco_simulation.shadow_hand.set_position_control(ctrl) self.mujoco_simulation.step() @classmethod def _get_default_wrappers(cls): default_wrappers = super()._get_default_wrappers() default_wrappers.update( { "default_observation_noise_levels": { "fingertip_pos": {"uncorrelated": 0.002, "additive": 0.001}, "hand_angle": {"additive": 0.1, "uncorrelated": 0.1}, "cube_pos": {"additive": 0.005, "uncorrelated": 0.001}, "cube_quat": {"additive": 0.1, "uncorrelated": 0.09}, }, "default_no_noise_levels": { "fingertip_pos": {}, "hand_angle": {}, "cube_pos": {}, "cube_quat": {}, }, "default_observation_delay_levels": { "interpolators": {"cube_quat": "QuatInterpolator"}, "groups": { # Uncomment below to enable observation delay randomization. # "vision": { # "obs_names": ["cube_pos", "cube_quat"], # "mean": 3, # "std": 0.5, # }, # "phasespace": { # "obs_names": ["fingertip_pos"], # "mean": 0.5, # "std": 0.1, # } }, }, "default_no_observation_delay_levels": { "interpolators": {}, "groups": {}, }, "pre_obsnoise_randomizations": [ ["RandomizedActionLatency"], ["RandomizedCubeSizeWrapper"], ["RandomizedBodyInertiaWrapper"], ["RandomizedTimestepWrapper"], ["RandomizedRobotFrictionWrapper"], ["RandomizedCubeFrictionWrapper"], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ["RandomizedPhasespaceFingersWrapper"], ["RandomizedRobotDampingWrapper"], ["RandomizedRobotKpWrapper"], ["RandomizedJointLimitWrapper"], ["RandomizedTendonRangeWrapper"], ], } ) return default_wrappers ############################################################################################### # External API - to establish communication with other parts of the system @property def cube_type(self): """ Type of cube """ return "locked" ############################################################################################### # Fully internal methods def _render_callback(self, _sim, _viewer): """ Set a render callback """ self.mujoco_simulation.set_qpos("target_position", np.array([0.15, 0, -0.03])) self.mujoco_simulation.set_qpos("target_rotation", self._goal["cube_quat"]) self.mujoco_simulation.set_qvel("target_all_joints", 0.0) self.mujoco_simulation.forward() make_simple_env = functools.partial(LockedEnv.build, apply_wrappers=False) make_env = LockedEnv.build
11,793
37.542484
99
py
robogym
robogym-master/robogym/envs/dactyl/common/cube_env.py
import abc from contextlib import contextmanager from typing import Dict, List, Optional, Tuple, TypeVar import attr import numpy as np from robogym.envs.dactyl.common import cube_utils from robogym.envs.dactyl.common.cube_utils import DEFAULT_CAMERA_NAMES from robogym.envs.dactyl.common.dactyl_cube_wrappers import apply_wrappers from robogym.mujoco.mujoco_xml import MujocoXML from robogym.mujoco.simulation_interface import ( SimulationInterface, SimulationParameters, ) from robogym.observation.dummy_vision import ( DummyVisionGoalObservationProvider, DummyVisionObservationProvider, ) from robogym.observation.goal import GoalObservationProvider from robogym.observation.mujoco import MujocoObservationProvider, ObservationProvider from robogym.robot.shadow_hand.mujoco.mujoco_shadow_hand import MuJoCoShadowHand from robogym.robot_env import ( RobotEnv, RobotEnvConstants, RobotEnvParameters, build_nested_attr, ) @attr.s(auto_attribs=True) class CubeSimulationParameters(SimulationParameters): """Simulation parameters for cube env.""" # Cube appearance for mujoco and vision rendering. cube_appearance: str = "policy" # If True, hide target in simulation. hide_target: bool = False @attr.s(auto_attribs=True) class DactylCubeEnvParameters(RobotEnvParameters): """ Parameters of the Dactyl cube env - possible to change between episodes """ # Standard deviation of initial cube position cube_position_wiggle_std: float = 0.005 # Multiplier of the cube size cube_size_multiplier: float = 1.0 simulation_params: CubeSimulationParameters = build_nested_attr( CubeSimulationParameters ) @attr.s(auto_attribs=True) class DactylCubeEnvConstants(RobotEnvConstants): """ Parameters of the Dactyl cube env - set once and for all """ # Maximum number of tries to place cube randomly before we give up for given episode max_pose_resets: int = 50 ##################### # Multi success related settings # How many successes needed to stop roll out. successes_needed: int = 50 max_timesteps_per_goal: int = 400 # Check if current goal is reachable in each step. This is disabled by default # as to get more reliably performance metrics. However, this should be enabled # for demos or when recording a video. check_goal_reachable: bool = False # Max number of steps before considering goal is unreachable. max_steps_goal_unreachable: int = 100 success_pause_range_s: Tuple[float, float] = (0.0, 0.0) # Currently supported providers are: # # phasespace: Enable phasespace tracking for hand only. # phasespace/cube: Enable phasespace tracking for both hand and locked cube. # giiker: Enable giiker. # vision: Enable vision. # shadowhand: Enable shadowhand sensor. # # Example for observation_configs below. # # Locked cube: # {'cube_pos': 'phasespace', 'cube_quat': 'phasespace', 'fingertip_pos': 'phasespace'} # # Full cube: # { # 'cube_pos': 'vision', # 'cube_quat': 'vision', # 'cube_face_angle': 'giiker', # 'fingertip_pos': 'phasespace' # } # # How many steps with zero action to take on env reset reset_initial_steps: int = 20 ##################### # Wrapper settings # Args for vision wrapper. vision_args: Optional[dict] = None # If fix wrist joint position fixed_wrist: bool = False # If use relative goal wrapper. relative_goal_wrapper: bool = True # Reward for dropping the cube. drop_reward: float = -20.0 # Minimum episode length. min_episode_length: int = -1 # The cameras to be used when providing vision observations and/or goals. camera_names: List[str] = DEFAULT_CAMERA_NAMES # Width and height of images (only relevant for vision policies). image_size: int = 200 class CubeSimulationInterface(SimulationInterface): """ Simulation interface for shadow hand manipulating some version of a cube. Should be subclassed to implement particular version of a cube that simulation will manipulate. """ # Perpendicular cube model CUBE_XML = "rubik/rubik_perpendicular.xml" # XML with slightly different cube model for vision rendering VISION_CUBE_XML = "rubik/rubik_perpendicular_vision.xml" # XML for vision rendering with corner cutoff for center piece. VISION_CUBE_CORNER_CUTOFF_XML = "rubik/rubik_perpendicular_vision_corner_cutoff.xml" # Just a floor FLOOR_XML = "floor/basic_floor.xml" # Robot hand xml HAND_XML = "robot/shadowhand/main.xml" # XML with default light LIGHT_XML = "light/default.xml" # XML with default camera CAMERA_XML = "camera/default.xml" def __init__(self, sim): super().__init__(sim) self.enable_pid() self.shadow_hand = MuJoCoShadowHand(self) def is_cube_on_palm(self): """ Determines if cube is on palm """ return cube_utils.on_palm(self.sim) @classmethod def _build_mujoco_cube_xml(cls, xml, cube_xml_path): """ Builc xml for the cube simulation """ raise NotImplementedError @classmethod def build( cls, n_substeps: int = 10, simulation_params: CubeSimulationParameters = CubeSimulationParameters(), ): """ Construct a CubeSimulationInterface object with perpendicular cube. """ cube_xml_path, size_params = cls._get_model_xml_path_and_params( simulation_params.cube_appearance ) xml = MujocoXML() xml.add_default_compiler_directive() cls._build_mujoco_cube_xml(xml, cube_xml_path) xml.append( MujocoXML.parse(cls.FLOOR_XML).set_named_objects_attr( "floor", tag="body", pos=[1, 1, 0] ) ) xml.append( MujocoXML.parse(cls.HAND_XML) .add_name_prefix("robot0:") .set_objects_attr(tag="size", **size_params) .set_named_objects_attr( "robot0:hand_mount", tag="body", pos=[1.0, 1.25, 0.15], euler=[np.pi / 2, 0, np.pi], ) .remove_objects_by_name("robot0:annotation:outer_bound") # Remove hand base free joint so that hand is immovable .remove_objects_by_name("robot0:hand_base") ) xml.append(MujocoXML.parse(cls.LIGHT_XML)) simulation = cls(xml.build(nsubsteps=n_substeps)) if simulation_params.hide_target: simulation.hide_target() return simulation @classmethod def _get_model_xml_path_and_params(cls, cube_appearance): assert cube_appearance in ( "policy", "vision", "vision_corner_cutoff", ), f"Unexpected cube type: {cube_appearance}" if cube_appearance == "vision": cube_xml_path = cls.VISION_CUBE_XML max_contacts_params = dict( njmax=6000, nconmax=600, nuserdata=100, nuser_actuator=20 ) elif cube_appearance == "vision_corner_cutoff": cube_xml_path = cls.VISION_CUBE_CORNER_CUTOFF_XML max_contacts_params = dict( njmax=6000, nconmax=600, nuserdata=100, nuser_actuator=20 ) else: cube_xml_path = cls.CUBE_XML max_contacts_params = dict( njmax=2000, nconmax=200, nuserdata=100, nuser_actuator=20 ) return cube_xml_path, max_contacts_params @contextmanager def hide_target(self): """ Make target transparent (or invisible if we want to hide_target) """ target_geom_ids = [ self.sim.model.geom_name2id(name) for name in self.sim.model.geom_names if name.startswith("target") ] target_mat_ids = [self.sim.model.geom_matid[gid] for gid in target_geom_ids] target_site_ids = [ self.sim.model.site_name2id(name) for name in self.sim.model.site_names if name.startswith("target") ] old_mat_rgba = self.sim.model.mat_rgba.copy() old_geom_rgba = self.sim.model.geom_rgba.copy() old_site_rgba = self.sim.model.site_rgba.copy() self.sim.model.mat_rgba[target_mat_ids, -1] = 0 self.sim.model.geom_rgba[target_geom_ids, -1] = 0 self.sim.model.site_rgba[target_site_ids, -1] = 0 yield # Make target visible again. self.sim.model.mat_rgba[:] = old_mat_rgba self.sim.model.geom_rgba[:] = old_geom_rgba self.sim.model.site_rgba[:] = old_site_rgba PType = TypeVar("PType", bound=DactylCubeEnvParameters) CType = TypeVar("CType", bound=DactylCubeEnvConstants) SType = TypeVar("SType", bound=CubeSimulationInterface) class CubeEnv(RobotEnv[PType, CType, SType], abc.ABC): """ Base class for dactyl cube environments. Locked, Face, Full, Perpendicular, with right subclass should handle all of them """ def _build_observation_providers(self): """ Initialize observation providers for the environment. """ providers: Dict[str, ObservationProvider] = { "mujoco": MujocoObservationProvider(self.mujoco_simulation), "goal": GoalObservationProvider(self.goal_info), } if "dummy_vision" in self.constants.observation_providers: providers["dummy_vision"] = DummyVisionObservationProvider( camera_names=self.constants.camera_names, image_size=self.constants.image_size, ) providers["goal_dummy_vision"] = DummyVisionGoalObservationProvider( get_goal=self.goal_info, goal_qpos_key="qpos_goal", camera_names=self.constants.camera_names, image_size=self.constants.image_size, ) return providers def _has_episode_ended(self): """ Check if simulation is in state good enough to continue training """ return not self.mujoco_simulation.is_cube_on_palm() def _setup_simulation_from_parameters(self): """ Set all the simulation parameters from the current settings. You may override it or just leave it as it is for a very basic setup. """ for param_name, modifier in self.modifiers: modifier(getattr(self.parameters, param_name)) ############################################################################################### # Internal API - to be overridden - environment randomization def _randomize_cube_initial_position(self): """ Draw a random initial position for a cube """ raise NotImplementedError("Override _randomize_cube_initial_position") def _reset(self): """Resets the state of the environment and returns an initial observation. Returns: observation (object): the initial observation of the space. """ # Basically randomize cube position, until we get some random state where cube is still on # the palm of the hand for _ in range(self.constants.max_pose_resets): # Reset accumulated warnings self.warning_buffer.clear() # Reset to the initial state self.mujoco_simulation.reset() # Set all the simulation parameters self._setup_simulation_from_parameters() # Set derived constants of the simulation self.mujoco_simulation.set_constants() # Randomize cube position. self._randomize_cube_initial_position() if not self._has_episode_ended(): break @classmethod def build_robot(cls, mujoco_simulation, physical): return mujoco_simulation.shadow_hand def apply_wrappers(self, **wrapper_params): """ Apply wrappers to the environment. """ self.constants: DactylCubeEnvConstants return apply_wrappers( self, randomize=self.constants.randomize, n_action_bins=self.constants.n_action_bins, fixed_wrist=self.constants.fixed_wrist, relative_goal_wrapper=self.constants.relative_goal_wrapper, drop_reward=self.constants.drop_reward, default_wrappers=self._get_default_wrappers(), min_episode_length=self.constants.min_episode_length, **wrapper_params, ) @classmethod def _get_default_wrappers(cls): return { "post_obsnoise_randomizations": [ ["FingersOccludedPhasespaceMarkers"], ["FingersFreezingPhasespaceMarkers"], ["CubeFreezingPhasespaceBody"], ["ActionNoiseWrapper"], ], }
12,925
32.228792
99
py
robogym
robogym-master/robogym/envs/dactyl/common/cube_manipulator.py
import collections from typing import Dict, Tuple import numpy as np import pycuber from robogym.utils import rotation PYCUBER_LOCATION_AXES: Dict[str, np.array] = { "L": np.array([-1, 0, 0]), "R": np.array([1, 0, 0]), "F": np.array([0, -1, 0]), "B": np.array([0, 1, 0]), "D": np.array([0, 0, -1]), "U": np.array([0, 0, 1]), } PYCUBER_COLOR_AXES: Dict[str, np.array] = { "red": np.array([-1, 0, 0]), "orange": np.array([1, 0, 0]), "blue": np.array([0, 1, 0]), "green": np.array([0, -1, 0]), "yellow": np.array([0, 0, 1]), "white": np.array([0, 0, -1]), } # Below mappings are represented as pairs (axis nr, sign) # e.g. (0, -1) means -X and (2, 1) means +Z PYCUBER_COLOR_AXES_DESCRIPTIONS: Dict[str, Tuple] = { "red": (0, -1), "orange": (0, 1), "blue": (1, 1), "green": (1, -1), "yellow": (2, 1), "white": (2, -1), } PYCUBER_REVERSE_LOCATIONS: Dict[Tuple, str] = { (0, -1): "L", (0, 1): "R", (1, -1): "F", (1, 1): "B", (2, -1): "D", (2, 1): "U", } PYCUBER_REVERSE_COLORS: Dict[Tuple, str] = { (0, -1): "red", (0, 1): "orange", (1, 1): "blue", (1, -1): "green", (2, 1): "yellow", (2, -1): "white", } class CubeManipulator: """ Class for manipulating the perpendicular rubik's cube model in mujoco simulation. Translates face rotation commands into angle representation that can be input into mujoco qpos array """ def __init__(self, prefix, sim): self.prefix = prefix self.sim = sim self.drivers = [ x for x in self.sim.model.joint_names if x.startswith("{}cubelet:driver:".format(self.prefix)) ] self.rotators = [ x for x in self.sim.model.joint_names if x.startswith("{}cubelet:rot".format(self.prefix)) ] self.joints = self.drivers + self.rotators self.joints_qpos_map = {} self.joints_qpos_idx = [] for j in self.joints: current_index = self.sim.model.get_joint_qpos_addr(j) self.joints_qpos_map[j] = current_index self.joints_qpos_idx.append(current_index) # Info about the cubelets - indexed by cubelet index self.cubelet_meta_info = [] # Populate cubelet meta information for i in range(3): for j in range(3): for k in range(3): indicators = collections.OrderedDict( [("x", i - 1), ("y", j - 1), ("z", k - 1)] ) # Build cubelet nam name_pieces = [] keys = [] for key, value in indicators.items(): if value == -1: keys.append(key) name_pieces.append("neg_{}".format(key)) elif value == 1: keys.append(key) name_pieces.append("pos_{}".format(key)) name = "_".join(name_pieces) data = {"name": name, "coords": np.array([i - 1, j - 1, k - 1])} if len(name_pieces) > 1: # Not a driver just a normal cubelet idxs = [ self.joints.index( "{}cubelet:rot{}:{}".format(prefix, key, name) ) for key in indicators ] data["type"] = "cubelet" data["euler_qpos"] = [self.joints_qpos_idx[i] for i in idxs] elif len(name_pieces) == 1: data["driver"] = self.drivers.index( "{}cubelet:driver:{}".format(prefix, name) ) data["type"] = "driver" else: data["type"] = "null" self.cubelet_meta_info.append(data) def _cubelet_rotation_matrix(self, cubelet_meta_info, qpos_array): """ Find local coordinate axes for the cubelet """ euler_angles = qpos_array[cubelet_meta_info["euler_qpos"]] return rotation.euler2mat(euler_angles) def rotate_face(self, axis, side, angle): """ Rotate given face (identified by axis and side) by given angle. Cube should be in a reasonably aligned state for this to work well. """ assert 0 <= axis <= 2 assert 0 <= side <= 1 angle = rotation.normalize_angles(np.array(angle)) if np.abs(angle) < 1e-4: # No need to do anything, the angle is too small to care return side = side * 2 - 1 qpos_copy = self.sim.data.qpos.copy() # For each cubelet for i in range(27): cubelet_meta = self.cubelet_meta_info[i] if cubelet_meta["type"] == "cubelet": mtx = self._cubelet_rotation_matrix(cubelet_meta, qpos_copy) current_coords = mtx @ cubelet_meta["coords"].astype(float) is_selected = np.take(current_coords, axis) * side > 0.5 if is_selected: euler = np.zeros(3) euler[axis] = angle combined_matrix = rotation.euler2mat(euler) @ mtx new_euler = rotation.mat2euler(combined_matrix) self.sim.data.qpos[cubelet_meta["euler_qpos"]] = new_euler elif cubelet_meta["type"] == "driver": # No transformation matrix really here current_coords = cubelet_meta["coords"] is_selected = np.take(current_coords, axis) * side > 0.5 if is_selected: joint_idx = self.joints_qpos_idx[cubelet_meta["driver"]] self.sim.data.qpos[joint_idx] += angle def from_pycuber(self, cube: pycuber.Cube): """ Set cubelet positions based on the pycuber cube state Image copied from rubik_utils.py Z(+) Up (Yellow) Faces: | +X: Right (Orange) | / Y(+) Back (Blue) -X: Left (Red) _____________ / +Y: Back (Blue) / /| -Y: Front (Green) / / | +Z: Up (Yellow) / / | -Z: Down (White) /____________/ | | | |____ X(+) Right (Orange) Left | | / (Red) | Front | / | (Green) | / |____________|/ Down (White) """ # First, we zero out the cubelet positions to reset all of the cube state self.sim.data.qpos[self.joints_qpos_idx] = 0.0 for cubelet in cube.children: if isinstance(cubelet, pycuber.cube.Corner): mtx = np.zeros((3, 3)) for element in cubelet.location: # Example: Corner(B: [r], U: [y], L: [g]) # Original location: red, yellow, green: -X, +Z, -Y # Current location back, up, left: +Y, +Z, -X # Mapping: -X -> +Y, +Z -> +Z, -Y -> -X axis, sign = PYCUBER_COLOR_AXES_DESCRIPTIONS[ cubelet[element].colour ] vector = PYCUBER_LOCATION_AXES[element] mtx[:, axis] = sign * vector euler_angles = rotation.mat2euler(mtx) original_location: np.array = sum( PYCUBER_COLOR_AXES[x.colour] for x in cubelet.children ) idx = ( (original_location[0] + 1) * 9 + (original_location[1] + 1) * 3 + original_location[2] + 1 ) # Set the euler angles self.sim.data.qpos[ self.cubelet_meta_info[idx]["euler_qpos"] ] = euler_angles elif isinstance(cubelet, pycuber.cube.Edge): # Example: # Edge(R: [o], B: [g]) # original location: orange-green +X, -Y, (1, -1, 0) # current location: right-back, +X, +Y (1, 1, 0) original_location = sum( PYCUBER_COLOR_AXES[x.colour] for x in cubelet.children ) mtx = np.zeros((3, 3)) axes = {0, 1, 2} for element in cubelet.location: axis, sign = PYCUBER_COLOR_AXES_DESCRIPTIONS[ cubelet[element].colour ] vector = PYCUBER_LOCATION_AXES[element] mtx[:, axis] = sign * vector axes.remove(axis) remaining_axis = axes.pop() # Antisymmetric tensor if remaining_axis == 0: mtx[:, 0] = np.cross(mtx[:, 1], mtx[:, 2]) elif remaining_axis == 1: mtx[:, 1] = -np.cross(mtx[:, 0], mtx[:, 2]) elif remaining_axis == 2: mtx[:, 2] = np.cross(mtx[:, 0], mtx[:, 1]) euler_angles = rotation.mat2euler(mtx) idx = ( (original_location[0] + 1) * 9 + (original_location[1] + 1) * 3 + original_location[2] + 1 ) # Set the euler angles self.sim.data.qpos[ self.cubelet_meta_info[idx]["euler_qpos"] ] = euler_angles def to_pycuber(self) -> pycuber.Cube: """ Return current cubelet state as a pycuber state """ self.soft_align_faces() qpos_copy = self.sim.data.qpos.copy() cubies = [] for i in range(27): cubelet_meta = self.cubelet_meta_info[i] if cubelet_meta["type"] == "cubelet": mtx = self._cubelet_rotation_matrix(cubelet_meta, qpos_copy) original_coords = cubelet_meta["coords"] # current_coords = (mtx @ cubelet_meta['coords'].astype(float)).round().astype(int) cubie_desc = {} for prev_axis, sign in enumerate(original_coords): if sign != 0: vec = mtx[:, prev_axis] * sign new_axis = np.abs(vec).argmax() new_sign = vec[new_axis] color = PYCUBER_REVERSE_COLORS[prev_axis, sign] loc = PYCUBER_REVERSE_LOCATIONS[new_axis, new_sign] cubie_desc[loc] = pycuber.Square(color) if len(cubie_desc) == 3: cubies.append(pycuber.Corner(**cubie_desc)) elif len(cubie_desc) == 2: cubies.append(pycuber.Edge(**cubie_desc)) if cubelet_meta["type"] == "driver": original_coords = cubelet_meta["coords"] axis = np.abs(original_coords).argmax() sign = original_coords[axis] color = PYCUBER_REVERSE_COLORS[axis, sign] loc = PYCUBER_REVERSE_LOCATIONS[axis, sign] cubie_desc = {loc: pycuber.Square(color)} cubies.append(pycuber.Centre(**cubie_desc)) return pycuber.Cube(cubies=cubies) def snap_rotate_face_with_threshold(self, axis, side, angle, threshold=0.1): """ Rotate face of a cube in a "snapping" fashion, correcting the cube along the way. Underlying assumption: cube is already in a "snapped", physically-aligned state Threshold is threshold in radians which decides maximum angle we want to snap over. If the angle required to move the face to be snapped is larger than that, the cube will remain locked and won't rotate. """ qpos = self.sim.data.qpos drivers = rotation.normalize_angles( qpos[[self.joints_qpos_map[x] for x in self.drivers]] ) perpendicular_axes = sorted({0, 1, 2} - {axis}) transaction = [] abort = False for other_axis in perpendicular_axes: for other_side in range(2): other_driver_idx = other_axis * 2 + other_side other_angle = drivers[other_driver_idx] other_angle_aligned = rotation.round_to_straight_angles(other_angle) other_angle_diff = rotation.normalize_angles( other_angle_aligned - other_angle ) if ( np.abs(other_angle_diff) < np.abs(angle) and np.abs(other_angle_diff) < threshold ): transaction.append((other_axis, other_side, other_angle_diff)) else: abort = True if not abort: # Snap other faces for other_axis, other_side, angle_diff in transaction: self.rotate_face(other_axis, other_side, angle_diff) # rotate the actual face self.rotate_face(axis, side, angle) def soft_align_faces(self): """ Align cube configuration to nearest set of straight angles. Should handle more corner cases than naive implementation """ drivers_idx = [self.joints_qpos_map[x] for x in self.drivers] current_angles = self.sim.data.qpos[drivers_idx] straight_angles = rotation.round_to_straight_angles(current_angles) normalized_diff = rotation.normalize_angles(straight_angles - current_angles) # From the largest angle to the smallest for _, idx in reversed( sorted(zip(np.abs(normalized_diff), range(len(normalized_diff)))) ): self.rotate_face(idx // 2, idx % 2, normalized_diff[idx]) # Align all little cubelets at the end for i in range(27): info = self.cubelet_meta_info[i] if "euler_qpos" in info: mtx = self._cubelet_rotation_matrix(info, self.sim.data.qpos) # Much better alignment than in the euler angle representation # If the cube is close enough to the aligned state it should work mtx = mtx.round() self.sim.data.qpos[info["euler_qpos"]] = rotation.mat2euler(mtx) def align_angles(self): """ Round all cube angles to the nearest straight angle Naive implementation that may easily cause the cube to end up in an incorrect state due to "gimbal lock" singularity in the euler angle representation """ self.sim.data.qpos[self.joints_qpos_idx] = rotation.round_to_straight_angles( self.sim.data.qpos[self.joints_qpos_idx] )
15,260
34.992925
99
py
robogym
robogym-master/robogym/envs/dactyl/common/cube_utils.py
import math import numpy as np from robogym.mujoco.helpers import joint_qpos_ids_from_prefix from robogym.utils import rotation PARALLEL_QUATS = [ rotation.quat_normalize(rotation.euler2quat(r)) for r in rotation.get_parallel_rotations() ] DEFAULT_CAMERA_NAMES = ["vision_cam_top", "vision_cam_right", "vision_cam_left"] def on_palm(sim): """ Determines if the cube is on the palm of the hand.""" sim.forward() cube_middle_idx = sim.model.site_name2id("cube:center") cube_middle_pos = sim.data.site_xpos[cube_middle_idx] is_on_palm = cube_middle_pos[2] > 0.04 return is_on_palm def uniform_z_aligned_quat(random): """ Produces a random quaternion with the red face on top. """ axis = np.asarray([0.0, 0.0, 1.0]) angle = random.uniform(-np.pi, np.pi) quat = rotation.quat_from_angle_and_axis(angle, axis) return rotation.quat_normalize(quat) def face_up(sim, geom_names): """ Return the index of the face which is oriented up. """ face_geom_z = [sim.data.get_geom_xpos(name)[2] for name in geom_names] return np.argmax(face_geom_z) def face_up_quats(sim, ball_joint, geom_names): """ Returns a dict of parallel quats in which the given faces are up. """ goal_quat = {} cube_quat_idxs = joint_qpos_ids_from_prefix(sim.model, ball_joint) initial_quat = sim.data.qpos[cube_quat_idxs] sim.data.qpos[cube_quat_idxs] = rotation.quat_identity() for i, geom in enumerate(geom_names): geom_z = [] for p in PARALLEL_QUATS: sim.data.qpos[cube_quat_idxs] = p sim.forward() geom_z.append(sim.data.get_geom_xpos(geom)[2]) goal_quat[i] = PARALLEL_QUATS[np.argmax(geom_z)] assert len(goal_quat.keys()) == len(geom_names) sim.data.qpos[cube_quat_idxs] = initial_quat sim.forward() return goal_quat def rotated_face( face_angles, face_to_shift, random, round_target_face, directions=["cw", "ccw"] ): """ Return a new set of face angles, which correspond to the original but with the given face rotated. """ clockwise = math.pow(-1, face_to_shift) rotation_directions = { "cw": clockwise, "ccw": -clockwise, } directions = [math.pi / 2 * rotation_directions[d] for d in directions] rotated_face = face_angles.copy() if random.uniform() < float(round_target_face): rotated_face[face_to_shift] += random.choice(directions) rotated_face = rotation.normalize_angles(rotated_face) rotated_face = rotation.round_to_straight_angles(rotated_face) else: directions += [0.0] rotated_face[face_to_shift] += random.uniform(min(directions), max(directions)) rotated_face = rotation.normalize_angles(rotated_face) return rotated_face def rotated_face_with_angle( face_angles, face_to_shift, random, round_target_face, directions=["cw", "ccw"] ): """ Return a new set of face angles, which correspond to the original but with the given face rotated. :param face_angles: Numpy array of current angles of cube faces :param face_to_shift: Index of the face that we are about to rotate :param random: Random state used to sample pseudorandom numbers :param round_target_face: Boolean of floating point probability if the face should be rotated by 90 degrees or by any uniform angle within range :param directions: Specify which direction rotations are allowed, supported values are 'cw' and 'ccw' """ clockwise = math.pow(-1, face_to_shift) rotation_directions = { "cw": clockwise, "ccw": -clockwise, } directions = [math.pi / 2 * rotation_directions[d] for d in directions] rotated_face = face_angles.copy() if random.uniform() < float(round_target_face): rotation_angle = random.choice(directions) rotated_face[face_to_shift] += rotation_angle rotated_face = rotation.normalize_angles(rotated_face) rotated_face = rotation.round_to_straight_angles(rotated_face) else: directions += [0.0] rotation_angle = random.uniform(min(directions), max(directions)) rotated_face[face_to_shift] += rotation_angle rotated_face = rotation.normalize_angles(rotated_face) return rotated_face, rotation_angle def align_quat_up(cube_quat, normalize=True): """ Align quaternion so that the closest face to being up is actually up """ z_up = np.array([0, 0, 1]).reshape(3, 1) mtx = rotation.quat2mat(cube_quat) # Axis that is the closest (by dotproduct) to z-up axis_nr = np.abs((z_up.T @ mtx)).argmax() # Axis of the cube pointing the closest to the top axis = mtx[:, axis_nr] axis = axis * np.sign(axis @ z_up) # Quaternion representing the rotation from "axis" that is almost up to # the actual "up" direction difference_quat = rotation.vectors2quat(axis, z_up[:, 0]) angle = rotation.quat_mul(difference_quat, cube_quat) return rotation.quat_normalize(angle) if normalize else angle def up_axis_with_sign(cube_quat): """ Return an axis number + sign of the cube that is the closest to pointing up """ z_up = np.array([0, 0, 1]).reshape(3, 1) mtx = rotation.quat2mat(cube_quat) # Axis that is the closest (by dotproduct) to z-up axis_nr = np.abs((z_up.T @ mtx)).argmax() axis = mtx[:, axis_nr] sign = np.sign(axis @ z_up) return axis_nr, sign def distance_quat_from_being_up(cube_quat, axis_nr, sign): """ How far is the cube from having given axis pointing upwards """ mtx = rotation.quat2mat(cube_quat) axis = mtx[:, axis_nr] axis = axis * sign z_up = np.array([0, 0, 1]).reshape(3, 1) # Quaternion representing the rotation from "axis" that is almost up to # the actual "up" direction difference_quat = rotation.vectors2quat(axis, z_up[:, 0]) return rotation.quat_normalize(difference_quat)
5,962
31.763736
97
py
robogym
robogym-master/robogym/envs/dactyl/common/dactyl_cube_wrappers.py
import logging from robogym.wrappers.named_wrappers import apply_named_wrappers, edit_wrappers logger = logging.getLogger(__name__) def construct_default_wrappers( *, randomize: bool, n_action_bins: int, fixed_wrist: bool, adr_wrapper, relative_goal_wrapper: bool = False, drop_reward: float = -20.0, default_wrappers=None, min_episode_length: int = -1 ): """ Construct default list of wrappers. Args: - randomize (bool): use randomizations. See default-wrapper-base.jsonnet for default randomization blocks - vision_args (dict): see base-vision.jsonnet for examples - n_action_bins (int or None=DiscretizeActionWrapper.DEFAULT_BINS): number of discrete bins - min_episode_length: If positive, a dropped cube at a timestep below min_epsiode_length will not trigger a 'done'. A penalty for cube dropping is only returned on the first frame. Returns: list of wrappers """ wrappers = [] # actions should be clipped immediately before sending to env if fixed_wrist: wrappers.append(["FixedWristWrapper"]) # must be inside clipping wrappers.append(["ClipActionWrapper"]) wrappers.append( [ "StopOnFallWrapper", dict(min_episode_length=min_episode_length, drop_reward=drop_reward,), ] ) if randomize: wrappers.append(["BacklashWrapper"]) if adr_wrapper is not None: wrappers.append(adr_wrapper) wrappers += default_wrappers["pre_obsnoise_randomizations"] noise_levels = default_wrappers["default_observation_noise_levels"] observation_delay_levels = default_wrappers["default_observation_delay_levels"] else: noise_levels = default_wrappers["default_no_noise_levels"] observation_delay_levels = default_wrappers[ "default_no_observation_delay_levels" ] wrappers.append(["ObservationDelayWrapper", dict(levels=observation_delay_levels)]) wrappers.append( ["RandomizeObservationWrapper", dict(levels=noise_levels)] ) # must happen before angle observation wrapper wrappers.append( ["SmoothActionWrapper"] ) # it is important that this gets applied before noise is added if relative_goal_wrapper: wrappers.append(["RelativeGoalWrapper", dict(obs_prefix="cube_")]) if randomize: wrappers += default_wrappers["post_obsnoise_randomizations"] wrappers.append(["AngleObservationWrapper"]) wrappers.append( [ "UnifiedGoalObservationWrapper", dict(goal_parts=["pos", "quat", "face_angle"]), ] ) wrappers.append(["ClipObservationWrapper"]) wrappers.append(["ClipRewardWrapper"]) wrappers.append(["PreviousActionObservationWrapper"]) wrappers.append(["RewardObservationWrapper", {"reward_inds": [1, 2]}]) wrappers.append(["DiscretizeActionWrapper", {"n_action_bins": n_action_bins}]) return wrappers def apply_wrappers( env, randomize, wrappers=None, n_action_bins=None, fixed_wrist=False, insert_above=[], insert_below=[], replace=[], delete=[], adr_wrapper=None, relative_goal_wrapper=False, drop_reward=-20.0, default_wrappers=None, min_episode_length=-1, ): if wrappers is None: wrappers = construct_default_wrappers( randomize=randomize, n_action_bins=n_action_bins, fixed_wrist=fixed_wrist, drop_reward=drop_reward, adr_wrapper=adr_wrapper, relative_goal_wrapper=relative_goal_wrapper, default_wrappers=default_wrappers, min_episode_length=min_episode_length, ) wrappers = edit_wrappers( wrappers=wrappers, insert_above=insert_above, insert_below=insert_below, replace=replace, delete=delete, ) env = apply_named_wrappers(env, wrappers) return env def get_vision_wrapper_args(input_vision_args, cube_type): vision_args = (input_vision_args or {}).copy() if "vision_env_args" not in vision_args: vision_args["vision_env_args"] = {} if cube_type == "full-perpendicular": vision_env_args = { "hide_target": True, "cube_appearance": "vision", } elif cube_type in "face-perpendicular": vision_env_args = { "hide_target": True, "randomize": False, "n_random_initial_steps": 0, } elif cube_type == "locked": vision_env_args = { "hide_target": True, "cube_appearance": "material", "randomize": False, "n_random_initial_steps": 0, } else: vision_env_args = {} vision_args["vision_env_args"].update(vision_env_args) return vision_args
4,867
29.049383
97
py
robogym
robogym-master/robogym/envs/dactyl/common/mujoco_modifiers.py
import numpy as np # noinspection PyUnresolvedReferences from robogym.mujoco.modifiers.timestep import Modifier # noinspection PyAttributeOutsideInit class PerpendicularCubeSizeModifier(Modifier): """ Modify size of a "perpendicular cube" """ def __init__(self, prefix): super().__init__() self.body_name_prefix = f"{prefix}cubelet:" self.mesh_name = f"{prefix}rounded_cube" def initialize(self, sim): super().initialize(sim) cubelet_body_names = [ x for x in self.sim.model.body_names if x.startswith(self.body_name_prefix) ] self.cubelet_body_ids = np.array( [self.sim.model.body_name2id(x) for x in cubelet_body_names] ) cubelet_geom_names = [ x for x in self.sim.model.geom_names if x.startswith(self.body_name_prefix) ] self.cubelet_geom_ids = np.array( [self.sim.model.geom_name2id(x) for x in cubelet_geom_names] ) cube_mesh_id = self.sim.model.mesh_name2id(self.mesh_name) self.cube_vert_adr = self.sim.model.mesh_vertadr[cube_mesh_id] self.cube_vert_num = self.sim.model.mesh_vertnum[cube_mesh_id] self.original_cube_body_pos = self.sim.model.body_pos[ self.cubelet_body_ids ].copy() self.original_mesh_verts = ( self.sim.model.mesh_vert[ self.cube_vert_adr: self.cube_vert_adr + self.cube_vert_num ] ).copy() self.original_geom_rbound = self.sim.model.geom_rbound[ self.cubelet_geom_ids ].copy() def __call__(self, cube_size_multiplier): self.sim.model.body_pos[self.cubelet_body_ids] = ( self.original_cube_body_pos * cube_size_multiplier ) self.sim.model.mesh_vert[ self.cube_vert_adr: self.cube_vert_adr + self.cube_vert_num ] = (self.original_mesh_verts * cube_size_multiplier) self.sim.model.geom_rbound[self.cubelet_geom_ids] = ( self.original_geom_rbound * cube_size_multiplier ) # noinspection PyAttributeOutsideInit class LockedCubeSizeModifier(Modifier): """ Modify size of a "locked cube" """ def __init__(self, prefix): super().__init__() self.prefix = prefix def initialize(self, sim): super().initialize(sim) self.body_ids = [ self.sim.model.body_name2id(x) for x in self.sim.model.body_names if x.startswith(self.prefix) ] self.original_body_pos = self.sim.model.body_pos[self.body_ids].copy() self.geom_ids = [ self.sim.model.geom_name2id(x) for x in self.sim.model.geom_names if x.startswith(self.prefix) ] self.original_geom_size = self.sim.model.geom_size[self.geom_ids].copy() def __call__(self, cube_size_multiplier): self.sim.model.body_pos[self.body_ids] = ( self.original_body_pos * cube_size_multiplier ) self.sim.model.geom_size[self.geom_ids] = ( self.original_geom_size * cube_size_multiplier )
3,155
29.941176
87
py
robogym
robogym-master/robogym/envs/dactyl/observation/cube.py
import numpy as np from robogym.observation.goal import GoalObservation from robogym.observation.mujoco import MujocoObservation from robogym.utils.rotation import quat_normalize class MujocoCubePosObservation(MujocoObservation): """ Implement mujoco base cube position observation. """ def get(self) -> np.ndarray: """ Get cube position. """ return self.provider.mujoco_simulation.get_qpos("cube_position") class MujocoCubeRotObservation(MujocoObservation): """ Implement mujoco base cube rotation observation. """ def get(self) -> np.ndarray: """ Get cube position. """ return quat_normalize(self.provider.mujoco_simulation.get_qpos("cube_rotation")) class GoalCubeRotObservation(GoalObservation): """ Implement goal cube rotation observation. """ def get(self) -> np.ndarray: """ Get cube position. """ assert self.provider.goal return quat_normalize(self.provider.goal["cube_quat"]) class GoalQposObservation(GoalObservation): """ Retrieves the qpos corresponding to the goal state. """ def get(self) -> np.ndarray: """ Get goal qpos. """ assert self.provider.goal return self.provider.goal["qpos_goal"] class GoalIsAchievedObservation(GoalObservation): """ Implement observation indicating if we've achieved the current goal. """ def get(self) -> np.ndarray: """ Get the flag indicating if we've achieved the current goal. """ return self.provider.is_successful
1,639
23.117647
88
py
robogym
robogym-master/robogym/envs/dactyl/observation/shadow_hand.py
import abc import numpy as np from robogym.observation.mujoco import MujocoObservation from robogym.robot.shadow_hand.hand_forward_kinematics import FINGERTIP_SITE_NAMES from robogym.robot.shadow_hand.hand_interface import JOINTS from robogym.robot.shadow_hand.mujoco.mujoco_shadow_hand import MuJoCoShadowHand def _update_qpos_and_qvel(sim, qpos=None, qvel=None): for i, joint_name in enumerate(JOINTS): name = "robot0:" + joint_name if name in sim.model.joint_names: if qpos is not None: sim.data.qpos[sim.model.get_joint_qpos_addr(name)] = qpos[i] if qvel is not None: sim.data.qvel[sim.model.get_joint_qvel_addr(name)] = qvel[i] class MujocoShadowHandObservation(MujocoObservation, abc.ABC): def __init__(self, provider): super().__init__(provider) self.hand = MuJoCoShadowHand(self.provider.mujoco_simulation) class MujocoShadowhandRelativeFingertipsObservation(MujocoShadowHandObservation): """ Mujoco based relative fingertip position observation. """ def get(self) -> np.ndarray: """ Get relative fingertip positions. """ return self.hand.observe().fingertip_positions().flatten() class MujocoShadowhandAbsoluteFingertipsObservation(MujocoShadowHandObservation): """ Mujoco based absolute fingertip position observation. """ def get(self) -> np.ndarray: """ Get relative fingertip positions. """ fingertip_pos = np.array( [ self.provider.mujoco_simulation.mj_sim.data.get_site_xpos( f"robot0:{site}" ) for site in FINGERTIP_SITE_NAMES ] ) return fingertip_pos.flatten() class MujocoShadowHandJointPosObservation(MujocoShadowHandObservation): """ Mujoco based observation for shadowhand joint positions. """ def get(self) -> np.ndarray: """ Get shadowhand joint positions. """ return self.hand.observe().joint_positions() class MujocoShadowHandJointVelocityObservation(MujocoShadowHandObservation): """ Mujoco based observation for shadowhand joint velocities. """ def get(self) -> np.ndarray: """ Get shadowhand joint velocities. """ return self.hand.observe().joint_velocities() class MujocoShadowhandAngleObservation(MujocoShadowHandObservation): """ Mujoco based observation for shadowhand hand angle. """ def get(self) -> np.ndarray: """ Get shadowhand joint velocities. """ return self.provider.mujoco_simulation.get_qpos("hand_angle")
2,716
27.6
82
py
robogym
robogym-master/robogym/envs/dactyl/observation/full_perpendicular.py
import numpy as np from robogym.observation.goal import GoalObservation from robogym.observation.mujoco import MujocoObservation from robogym.utils.rotation import normalize_angles MYPY = False if MYPY: from robogym.envs.dactyl.full_perpendicular import FullPerpendicularSimulation BaseObservationType = MujocoObservation[FullPerpendicularSimulation] else: BaseObservationType = MujocoObservation class MujocoFaceAngleObservation(BaseObservationType): """ Implement mujoco base cube face angles. """ def get(self) -> np.ndarray: """ Get cube position. """ return normalize_angles(self.provider.mujoco_simulation.get_face_angles("cube")) class GoalCubePosObservation(GoalObservation): """ Implement goal cube position observation. """ def get(self) -> np.ndarray: """ Get cube position. """ assert self.provider.goal return self.provider.goal["cube_pos"] class GoalFaceAngleObservation(GoalObservation): """ Implement goal cube face angle observation. """ def get(self) -> np.ndarray: """ Get cube position. """ assert self.provider.goal return self.provider.goal["cube_face_angle"]
1,267
22.924528
88
py
robogym
robogym-master/robogym/envs/dactyl/observation/reach.py
import numpy as np from robogym.observation.goal import GoalObservation class GoalFingertipPosObservation(GoalObservation): """ Implement goal fingertip pos observation. """ def get(self) -> np.ndarray: assert self.provider.goal return self.provider.goal["fingertip_pos"] class GoalIsAchievedObservation(GoalObservation): """ Implement observation indicating if we've achieved the current goal. """ def get(self) -> np.ndarray: """ Get the flag indicating if we've achieved the current goal. """ return self.provider.is_successful
618
22.807692
72
py
robogym
robogym-master/robogym/envs/dactyl/observation/face_perpendicular.py
import numpy as np from robogym.observation.goal import GoalObservation from robogym.observation.mujoco import MujocoObservation MYPY = False if MYPY: from robogym.envs.dactyl.face_perpendicular import FacePerpendicularSimulation BaseObservationType = MujocoObservation[FacePerpendicularSimulation] else: BaseObservationType = MujocoObservation class MujocoFaceAngleObservation(BaseObservationType): """ Implement mujoco base cube face angles. """ def get(self) -> np.ndarray: """ Get cube position. """ return self.provider.mujoco_simulation.get_face_angles("cube") class GoalCubePosObservation(GoalObservation): """ Implement goal cube position observation. """ def get(self) -> np.ndarray: """ Get cube position. """ assert self.provider.goal return self.provider.goal["cube_pos"] class GoalFaceAngleObservation(GoalObservation): """ Implement goal cube face angle observation. """ def get(self) -> np.ndarray: """ Get cube position. """ assert self.provider.goal return self.provider.goal["cube_face_angle"]
1,197
22.038462
82
py
robogym
robogym-master/robogym/envs/dactyl/observation/locked.py
import numpy as np from robogym.observation.goal import GoalObservation class GoalCubePosObservation(GoalObservation): """ Implement goal cube position observation. """ def get(self) -> np.ndarray: """ Locked cube doesn't take position as part of goal. """ return np.zeros(3)
328
19.5625
58
py
robogym
robogym-master/robogym/envs/dactyl/tests/test_rubik_solvers.py
import unittest import numpy as np import pytest from numpy.testing import assert_allclose from robogym.envs.dactyl.full_perpendicular import make_env from robogym.utils import rotation class TestRubikSolvers(unittest.TestCase): X_AXIS = 0 Y_AXIS = 1 Z_AXIS = 2 NEGATIVE_SIDE = 0 POSITIVE_SIDE = 1 CW = 1 CCW = -1 # Apply B R U rotations to solved cube scrambles = [ { "rotation": { "axis": Z_AXIS, "side": POSITIVE_SIDE, "angle": CW * np.pi / 2, }, "recovery_flips": np.array([[1, 1, 1]]), }, { "rotation": { "axis": X_AXIS, "side": POSITIVE_SIDE, "angle": CW * np.pi / 2, }, "recovery_flips": np.array([[0, 0, 1]]), }, { "rotation": { "axis": Y_AXIS, "side": POSITIVE_SIDE, "angle": CW * np.pi / 2, }, "recovery_flips": np.array([[0, 1, 1]]), }, ] def test_face_cube_solver(self): constants = { "goal_generation": "face_cube_solver", "num_scramble_steps": 3, "randomize_face_angles": False, "randomize": False, } env = make_env(constants=constants) unwrapped = env.unwrapped # start from deterministic straight qpos unwrapped.mujoco_simulation.set_qpos("cube_rotation", [1.0, 0.0, 0.0, 0.0]) assert_allclose( unwrapped.mujoco_simulation.get_qpos("cube_rotation"), [1.0, 0.0, 0.0, 0.0] ) current_face_rotations = np.zeros(6) for step in self.scrambles: rot = step["rotation"] unwrapped.mujoco_simulation.cube_model.rotate_face( rot["axis"], rot["side"], rot["angle"] ) current_face_rotations[rot["axis"] * 2 + rot["side"]] += rot["angle"] # track remaining face rotations on cube assert_allclose( current_face_rotations, [0, np.pi / 2, 0, np.pi / 2, 0, np.pi / 2] ) unwrapped.reset_goal_generation() steps_left = len(self.scrambles) for step in reversed(self.scrambles): # assert state before recovery flip _, reached, goal_info = env.unwrapped.goal_info() assert not reached assert goal_info["goal_reachable"] assert goal_info["goal_dist"]["steps_to_solve"] == steps_left goal = goal_info["goal"] assert goal["goal_type"] == "flip" # check if expected quat goal is met recovery_quat = rotation.apply_euler_rotations( unwrapped.mujoco_simulation.get_qpos("cube_rotation"), step["recovery_flips"], ) assert_allclose(goal["cube_quat"], recovery_quat, atol=1e-8) assert_allclose(goal["cube_face_angle"], current_face_rotations) # apply target quat rotation to cube and recompute goal unwrapped.mujoco_simulation.set_qpos("cube_rotation", recovery_quat) unwrapped.update_goal_info() _, reached, info = unwrapped.goal_info() assert reached unwrapped.mujoco_simulation.forward() unwrapped.reset_goal() solution = step["rotation"] _, reached, goal_info = env.unwrapped.goal_info() assert not reached assert goal_info["goal_reachable"] assert goal_info["goal_dist"]["steps_to_solve"] == steps_left goal = goal_info["goal"] assert goal["goal_type"] == "rotation" assert goal["axis_nr"] == solution["axis"] assert goal["axis_sign"][0] == solution["side"] current_face_rotations[solution["axis"] * 2 + solution["side"]] -= solution[ "angle" ] assert_allclose(goal["cube_face_angle"], current_face_rotations) # actually rotate cube in the opposite direction of the original rotation unwrapped.mujoco_simulation.cube_model.rotate_face( solution["axis"], solution["side"], -solution["angle"] ) unwrapped.update_goal_info() _, reached, info = unwrapped.goal_info() assert reached unwrapped.mujoco_simulation.forward() unwrapped.reset_goal() steps_left -= 1 assert steps_left == 0 def test_release_cube_solver(self): constants = { "goal_generation": "release_cube_solver", "num_scramble_steps": 3, "randomize_face_angles": False, "randomize": False, } env = make_env(constants=constants) unwrapped = env.unwrapped # start from deterministic straight qpos unwrapped.mujoco_simulation.set_qpos("cube_rotation", [1.0, 0.0, 0.0, 0.0]) assert_allclose( unwrapped.mujoco_simulation.get_qpos("cube_rotation"), [1.0, 0.0, 0.0, 0.0] ) current_face_rotations = np.zeros(6) for step in self.scrambles: rot = step["rotation"] unwrapped.mujoco_simulation.cube_model.rotate_face( rot["axis"], rot["side"], rot["angle"] ) current_face_rotations[rot["axis"] * 2 + rot["side"]] += rot["angle"] # track remaining face rotations on cube assert_allclose( current_face_rotations, [0, np.pi / 2, 0, np.pi / 2, 0, np.pi / 2] ) unwrapped.reset_goal_generation() steps_left = len(self.scrambles) for step in reversed(self.scrambles): # assert state before recovery flip _, reached, goal_info = env.unwrapped.goal_info() assert not reached assert goal_info["goal_reachable"] assert goal_info["goal_dist"]["steps_to_solve"] == steps_left goal = goal_info["goal"] assert goal["goal_type"] == "flip" # check if expected quat goal is met recovery_quat = rotation.apply_euler_rotations( unwrapped.mujoco_simulation.get_qpos("cube_rotation"), step["recovery_flips"], ) assert_allclose(goal["cube_quat"], recovery_quat, atol=1e-8) assert_allclose(goal["cube_face_angle"], current_face_rotations) # apply target quat rotation to cube and recompute goal unwrapped.mujoco_simulation.set_qpos("cube_rotation", recovery_quat) unwrapped.update_goal_info() _, reached, info = unwrapped.goal_info() assert reached unwrapped.mujoco_simulation.forward() unwrapped.reset_goal() solution = step["rotation"] _, reached, goal_info = env.unwrapped.goal_info() assert not reached assert goal_info["goal_reachable"] assert goal_info["goal_dist"]["steps_to_solve"] == steps_left goal = goal_info["goal"] assert goal["goal_type"] == "rotation" assert goal["axis_nr"] == solution["axis"] assert goal["axis_sign"][0] == solution["side"] current_face_rotations[solution["axis"] * 2 + solution["side"]] -= solution[ "angle" ] assert_allclose(goal["cube_face_angle"], current_face_rotations) # actually rotate cube in the opposite direction of the original rotation unwrapped.mujoco_simulation.cube_model.rotate_face( solution["axis"], solution["side"], -solution["angle"] ) unwrapped.update_goal_info() _, reached, info = unwrapped.goal_info() assert reached unwrapped.mujoco_simulation.forward() unwrapped.reset_goal() steps_left -= 1 assert steps_left == 0 _, _, info = unwrapped.goal_info() assert info["solved"] unwrapped.mujoco_simulation.forward() assert info["solved"] def test_unconstrained_cube_solver(self): constants = { "goal_generation": "unconstrained_cube_solver", "num_scramble_steps": 3, "randomize_face_angles": False, "randomize": False, } env = make_env(constants=constants) unwrapped = env.unwrapped # start from deterministic straight qpos unwrapped.mujoco_simulation.set_qpos("cube_rotation", [1.0, 0.0, 0.0, 0.0]) assert_allclose( unwrapped.mujoco_simulation.get_qpos("cube_rotation"), [1.0, 0.0, 0.0, 0.0] ) current_face_rotations = np.zeros(6) for step in self.scrambles: rot = step["rotation"] unwrapped.mujoco_simulation.cube_model.rotate_face( rot["axis"], rot["side"], rot["angle"] ) current_face_rotations[rot["axis"] * 2 + rot["side"]] += rot["angle"] # track remaining face rotations on cube assert_allclose( current_face_rotations, [0, np.pi / 2, 0, np.pi / 2, 0, np.pi / 2] ) unwrapped.reset_goal_generation() steps_left = len(self.scrambles) for step in reversed(self.scrambles): solution = step["rotation"] _, reached, goal_info = env.unwrapped.goal_info() assert not reached assert goal_info["goal_reachable"] assert goal_info["goal_dist"]["steps_to_solve"] == steps_left goal = goal_info["goal"] assert goal["goal_type"] == "rotation" current_face_rotations[solution["axis"] * 2 + solution["side"]] -= solution[ "angle" ] assert_allclose(goal["cube_face_angle"], current_face_rotations) # actually rotate cube in the opposite direction of the original rotation unwrapped.mujoco_simulation.cube_model.rotate_face( solution["axis"], solution["side"], -solution["angle"] ) unwrapped.update_goal_info() _, reached, info = unwrapped.goal_info() assert reached unwrapped.mujoco_simulation.forward() unwrapped.reset_goal() steps_left -= 1 assert steps_left == 0 @pytest.mark.parametrize("axis", [0, 1, 2]) @pytest.mark.parametrize("side", [0, 1]) @pytest.mark.parametrize("rot_direction", [-1, 1]) def test_unconstrained_cube_solver(axis, side, rot_direction): constants = { "goal_generation": "unconstrained_cube_solver", "num_scramble_steps": 0, "randomize_face_angles": False, "randomize": False, } env = make_env(constants=constants) unwrapped = env.unwrapped # Rotate each face and make sure goal generator is able to solve the cube in one step unwrapped.mujoco_simulation.cube_model.rotate_face( axis, side, np.pi / 2 * rot_direction ) unwrapped.reset_goal_generation() _, _, goal_info = env.unwrapped.goal_info() assert goal_info["goal_reachable"] assert goal_info["goal_dist"]["steps_to_solve"] == 1 goal = goal_info["goal"] assert goal["goal_type"] == "rotation" assert_allclose(goal["cube_face_angle"], np.zeros(6))
11,388
34.369565
89
py
robogym
robogym-master/robogym/envs/dactyl/tests/test_locked.py
import numpy as np from mujoco_py import ignore_mujoco_warnings from numpy.testing import assert_allclose from robogym.envs.dactyl.common.cube_utils import on_palm from robogym.envs.dactyl.locked import make_env, make_simple_env from robogym.utils import rotation def test_locked_cube(): env = make_env(starting_seed=0) is_on_palm = [] for idx in range(20): env.reset() expected_joints = ( "cube:cube_tx", "cube:cube_ty", "cube:cube_tz", "cube:cube_rot", "target:cube_tx", "target:cube_ty", "target:cube_tz", "target:cube_rot", "robot0:WRJ1", "robot0:WRJ0", "robot0:FFJ3", "robot0:FFJ2", "robot0:FFJ1", "robot0:FFJ0", "robot0:MFJ3", "robot0:MFJ2", "robot0:MFJ1", "robot0:MFJ0", "robot0:RFJ3", "robot0:RFJ2", "robot0:RFJ1", "robot0:RFJ0", "robot0:LFJ4", "robot0:LFJ3", "robot0:LFJ2", "robot0:LFJ1", "robot0:LFJ0", "robot0:THJ4", "robot0:THJ3", "robot0:THJ2", "robot0:THJ1", "robot0:THJ0", ) assert env.unwrapped.sim.model.joint_names == expected_joints with ignore_mujoco_warnings(): for _ in range(20): obs, _, _, _ = env.step(env.action_space.nvec // 2) is_on_palm.append(on_palm(env.unwrapped.sim)) # Make sure the mass is right. cube_body_idx = env.unwrapped.sim.model.body_name2id("cube:middle") assert_allclose( env.unwrapped.sim.model.body_subtreemass[cube_body_idx], 0.078, atol=1e-3 ) assert ( np.mean(is_on_palm) >= 0.8 ), "Cube should stay in hand (most of the time) when zero action is sent." def test_observe(): # Test observation matches simulation state. env = make_simple_env() env.reset() simulation = env.mujoco_simulation obs = env.observe() qpos = simulation.qpos qpos[simulation.qpos_idxs["target_all_joints"]] = 0.0 qvel = simulation.qvel qvel[simulation.qvel_idxs["target_all_joints"]] = 0.0 true_obs = { "cube_pos": simulation.get_qpos("cube_position"), "cube_quat": rotation.quat_normalize(simulation.get_qpos("cube_rotation")), "hand_angle": simulation.get_qpos("hand_angle"), "fingertip_pos": simulation.shadow_hand.observe() .fingertip_positions() .flatten(), "qpos": qpos, "qvel": qvel, } for obs_key, true_val in true_obs.items(): assert np.allclose( obs[obs_key], true_val ), f"Value for obs {obs_key} {obs[obs_key]} doesn't match true value {true_val}." def test_informative_obs(): WHITELIST = [ # The position of the goal is zeroed "relative_goal_pos", "noisy_relative_goal_pos", "goal_pos", # Not all episodes end with a fall, i.e. it might be all zeros "fell_down", "is_goal_achieved", ] env = make_env(constants=dict(randomize=False, max_timesteps_per_goal=50)) obs = env.reset() done = False all_obs = [obs] while not done: obs, reward, done, info = env.step(env.action_space.sample()) all_obs.append(obs) all_obs.append(env.reset()) # one more reset at the end # Collect all obs and index by key. keys = set(all_obs[0].keys()) assert len(keys) > 0 combined_obs_by_keys = {key: [] for key in keys} for obs in all_obs: assert set(obs.keys()) == keys for key in keys: combined_obs_by_keys[key].append(obs[key]) # Make sure that none of the keys has all-constant obs. for key, obs in combined_obs_by_keys.items(): assert len(obs) == len(all_obs) if key in WHITELIST: continue obs0 = obs[0] equals = [np.array_equal(obs0, obs_i) for obs_i in obs] # If ob0 is equal to all other obs, all obs are equal, i.e. the observation # contains no information whatsoever. This is usually bad (e.g. we had an issue # in the past where qpos was aways set to all-zeros). assert not np.all(equals), "observations for {} are all equal to {}".format( key, obs0 ) def test_relative_action(): for relative_action in [True, False]: # NOTE - this seed choice is very important, since starting states affect the test. # The test could be updated to be robust in the future. env = make_env( starting_seed=586895, constants={"relative_action": relative_action} ) env.reset() zeros = np.zeros(env.unwrapped.sim.model.nu) not_zeros = np.ones(env.unwrapped.sim.model.nu) * 0.5 num_robot_joints = len( [x for x in env.unwrapped.sim.model.joint_names if "robot0" in x] ) qpos_shape = env.unwrapped.sim.data.qpos.shape num_cube_joints = qpos_shape[0] - num_robot_joints for action in [zeros, not_zeros]: env.unwrapped.sim.data.qvel[:] = 0 env.unwrapped.sim.data.qpos[:] = np.random.randn(*qpos_shape) * 0.1 env.unwrapped.sim.data.qpos[:num_cube_joints] = -10.0 for _ in range(10): env.unwrapped.step(action) qvel = np.sum(np.square(env.unwrapped.sim.data.qvel[num_cube_joints:])) if (action == zeros).all() and relative_action: assert qvel < 0.09 else: assert qvel > 0.09 def helper_test_two_deterministic_envs(env1, env2): env1.reset() env2.reset() env1.unwrapped.reset_goal() env2.unwrapped.reset_goal() action = env2.action_space.sample() env1_obs, env1_reward = env1.step(action)[:2] env2_obs, env2_reward = env2.step(action)[:2] for key in env1_obs.keys(): assert np.all( np.isclose(env1_obs[key], env2_obs[key]) ), "Key: %s -- Diff:\n%s" % (key, env1_obs[key] - env2_obs[key]) assert np.allclose(env1_reward, env2_reward) def test_rand_locked_consistent(): seed = 12345 helper_test_two_deterministic_envs( make_env(starting_seed=seed), make_env(starting_seed=seed) ) def test_det_locked_consistent(): seed = 12345 helper_test_two_deterministic_envs( make_env(constants=dict(randomize=False), starting_seed=seed), make_env(constants=dict(randomize=False), starting_seed=seed), )
6,618
30.975845
91
py
robogym
robogym-master/robogym/envs/dactyl/tests/test_full.py
import numpy as np import pytest from numpy.testing import assert_allclose from robogym.envs.dactyl.full_perpendicular import make_env, make_simple_env from robogym.utils import rotation def test_cube_mass(): env = make_env(constants=dict(randomize=False)) sim = env.unwrapped.sim cube_id = sim.model.body_name2id("cube:middle") # The mass of the giiker cube is 90g assert_allclose(sim.model.body_subtreemass[cube_id], 0.09, atol=0.005) @pytest.mark.parametrize( "goal_generation", [ "face_curr", "face_free", "face_cube_solver", "unconstrained_cube_solver", "full_unconstrained", "release_cube_solver", ], ) def test_goal_info(goal_generation): constants = { "goal_generation": goal_generation, "randomize_face_angles": False, "randomize": False, } # There is some small chance that cube can get into invalid state in simulation # which will cause cube solver to fail. Fixing the seed here to mitigate this # issue. env = make_env(constants=constants, starting_seed=12312) env.reset() _, _, goal_info = env.unwrapped.goal_info() assert "goal" in goal_info assert "goal_type" in goal_info["goal"] def test_make_simple_env(): env = make_simple_env( parameters={ "simulation_params": dict(cube_appearance="vision", hide_target=True) } ) env.reset() sim = env.sim # there is no wrapper. sticker_geoms = [g for g in sim.model.geom_names if g.startswith("cube:sticker:")] assert len(sticker_geoms) == 9 * 6 def test_observe(): # Test observation matches simulation state. env = make_simple_env() env.reset() simulation = env.mujoco_simulation obs = env.observe() qpos = simulation.qpos qpos[simulation.qpos_idxs["target_all_joints"]] = 0.0 qvel = simulation.qvel qvel[simulation.qvel_idxs["target_all_joints"]] = 0.0 true_obs = { "cube_pos": simulation.get_qpos("cube_position"), "cube_quat": rotation.quat_normalize(simulation.get_qpos("cube_rotation")), "hand_angle": simulation.get_qpos("hand_angle"), "fingertip_pos": simulation.shadow_hand.observe() .fingertip_positions() .flatten(), "qpos": qpos, "qvel": qvel, } for obs_key, true_val in true_obs.items(): assert np.allclose( obs[obs_key], true_val ), f"Value for obs {obs_key} {obs[obs_key]} doesn't match true value {true_val}." def test_informative_obs(): WHITELIST = [ # The position of the goal is zeroed "relative_goal_pos", "noisy_relative_goal_pos", "goal_pos", # Not all episodes end with a fall, i.e. it might be all zeros "fell_down", ] env = make_env(constants=dict(randomize=False, max_timesteps_per_goal=50)) obs = env.reset() done = False all_obs = [obs] while not done: obs, reward, done, info = env.step(env.action_space.sample()) all_obs.append(obs) all_obs.append(env.reset()) # one more reset at the end # Collect all obs and index by key. keys = set(all_obs[0].keys()) assert len(keys) > 0 combined_obs_by_keys = {key: [] for key in keys} for obs in all_obs: assert set(obs.keys()) == keys for key in keys: combined_obs_by_keys[key].append(obs[key]) # Make sure that none of the keys has all-constant obs. for key, obs in combined_obs_by_keys.items(): assert len(obs) == len(all_obs) if key in WHITELIST: continue obs0 = obs[0] equals = [np.array_equal(obs0, obs_i) for obs_i in obs] # If ob0 is equal to all other obs, all obs are equal, i.e. the observation # contains no information whatsoever. This is usually bad (e.g. we had an issue # in the past where qpos was aways set to all-zeros). assert not np.all(equals), "observations for {} are all equal to {}".format( key, obs0 ) def test_min_episode_length(): min_steps = 1000 env_1 = make_env(constants=dict(min_episode_length=min_steps), starting_seed=12312) env_1.reset() # fix seed to avoid stochastic tests num_fallen = 0 for _ in range(min_steps): o, r, d, i = env_1.step(env_1.action_space.sample()) assert not d if i["fell_down"]: num_fallen += 1 assert num_fallen > 0 env_2 = make_env(constants=dict(min_episode_length=-1), starting_seed=12312) env_2.reset() # fix seed to avoid stochastic tests for t in range(min_steps): o, r, d, i = env_2.step(env_2.action_space.sample()) if d: break assert t < min_steps - 1
4,773
29.8
89
py
robogym
robogym-master/robogym/envs/dactyl/tests/test_cube_utils.py
import numpy as np import robogym.envs.dactyl.common.cube_utils as cube_utils import robogym.utils.rotation as rotation def test_align_quat_up(): """ Test function 'align_quat_up' """ identity_quat = np.array([1.0, 0.0, 0.0, 0.0]) assert ( np.linalg.norm(cube_utils.align_quat_up(identity_quat) - identity_quat) < 1e-8 ) # Rotate along each axis but only slightly transformations = np.eye(3) * 0.4 for i in range(3): quat = rotation.euler2quat(transformations[i]) # For axes 0, 1 identity rotation is the proper rotation if i in [0, 1]: assert np.linalg.norm(cube_utils.align_quat_up(quat) - identity_quat) < 1e-8 else: # For axis 2 cube is already aligned assert np.linalg.norm(cube_utils.align_quat_up(quat) - quat) < 1e-8 # Rotate along each axis so much that another face is now on top transformations = np.eye(3) * (np.pi / 2 - 0.3) full_transformations = np.eye(3) * (np.pi / 2) for i in range(3): quat = rotation.euler2quat(transformations[i]) aligned = cube_utils.align_quat_up(quat) if i in [0, 1]: new_euler_angles = rotation.quat2euler(aligned) assert np.linalg.norm(new_euler_angles - full_transformations[i]) < 1e-8 else: # For axis 2 cube is already aligned assert np.linalg.norm(cube_utils.align_quat_up(quat) - quat) < 1e-8 def test_up_axis_with_sign(): """ Test function 'up_axis_with_sign' """ identity_quat = np.array([1.0, 0.0, 0.0, 0.0]) assert cube_utils.up_axis_with_sign(identity_quat) == (2, 1) # Rotate along each axis so much that another face is now on top transformations = np.eye(3) * (np.pi / 2 - 0.3) for i in range(3): quat = rotation.euler2quat(transformations[i]) axis, sign = cube_utils.up_axis_with_sign(quat) if i == 0: assert axis == 1 assert sign == 1 elif i == 1: assert axis == 0 assert sign == -1 else: assert axis == 2 assert sign == 1 transformations = -np.eye(3) * (np.pi / 2 - 0.3) for i in range(3): quat = rotation.euler2quat(transformations[i]) axis, sign = cube_utils.up_axis_with_sign(quat) if i == 0: assert axis == 1 assert sign == -1 elif i == 1: assert axis == 0 assert sign == 1 else: assert axis == 2 assert sign == 1 def test_distance_quat_from_being_up(): """ Test function 'distance_quat_from_being_up' """ initial_configuration = np.array([1.0, 0.0, 0.0, 0.0]) assert ( np.linalg.norm( cube_utils.distance_quat_from_being_up(initial_configuration, 2, 1) - initial_configuration ) < 1e-8 ) assert ( np.abs( rotation.quat_magnitude( cube_utils.distance_quat_from_being_up(initial_configuration, 2, -1) ) - np.pi ) < 1e-8 ) assert ( np.abs( rotation.quat_magnitude( cube_utils.distance_quat_from_being_up(initial_configuration, 0, 1) ) - np.pi / 2 ) < 1e-8 ) assert ( np.abs( rotation.quat_magnitude( cube_utils.distance_quat_from_being_up(initial_configuration, 0, -1) ) - np.pi / 2 ) < 1e-8 ) assert ( np.abs( rotation.quat_magnitude( cube_utils.distance_quat_from_being_up(initial_configuration, 1, 1) ) - np.pi / 2 ) < 1e-8 ) assert ( np.abs( rotation.quat_magnitude( cube_utils.distance_quat_from_being_up(initial_configuration, 1, -1) ) - np.pi / 2 ) < 1e-8 ) # Rotate along each axis but only slightly transformations = np.eye(3) * 0.4 for i in range(3): quat = rotation.euler2quat(transformations[i]) distance_quat = cube_utils.distance_quat_from_being_up(quat, 2, 1) if i in [0, 1]: result = rotation.quat_mul(quat, distance_quat) assert np.linalg.norm(result - initial_configuration) < 1e-8 else: assert np.linalg.norm(distance_quat - initial_configuration) < 1e-8 transformations = np.eye(3) * (np.pi / 2 - 0.3) for i in range(3): quat = rotation.euler2quat(transformations[i]) if i == 0: distance_quat = cube_utils.distance_quat_from_being_up(quat, 1, 1) assert np.abs(rotation.quat_magnitude(distance_quat) - 0.3) < 1e-8 elif i == 1: distance_quat = cube_utils.distance_quat_from_being_up(quat, 0, -1) assert np.abs(rotation.quat_magnitude(distance_quat) - 0.3) < 1e-8 else: distance_quat = cube_utils.distance_quat_from_being_up(quat, 2, 1) assert np.linalg.norm(distance_quat - initial_configuration) < 1e-8
5,150
28.267045
88
py
robogym
robogym-master/robogym/envs/dactyl/tests/test_cube_manipulator.py
import numpy as np import pycuber import robogym.utils.rotation as rotation from robogym.envs.dactyl.full_perpendicular import FullPerpendicularSimulation X_AXIS = 0 Y_AXIS = 1 Z_AXIS = 2 NEGATIVE_SIDE = 0 POSITIVE_SIDE = 1 def _full_side_idx(axis, side): # DRIVER ORDER IS: # -x, +x, -y, +y, -z, +z return axis * 2 + side def test_cube_manipulator_drivers(): """ Test CubeManipulator class if it manages to manipulates cubelets properly """ mujoco_simulation = FullPerpendicularSimulation.build(n_substeps=10) for axis in [X_AXIS, Y_AXIS, Z_AXIS]: for side in [NEGATIVE_SIDE, POSITIVE_SIDE]: # Reset simulation mujoco_simulation.set_qpos("cube_all_joints", 0.0) mujoco_simulation.cube_model.rotate_face(axis, side, np.pi / 2) target_angle = np.zeros(6, dtype=float) target_angle[_full_side_idx(axis, side)] = np.pi / 2 assert ( np.linalg.norm( mujoco_simulation.get_qpos("cube_drivers") - target_angle ) < 1e-6 ) def test_cube_manipulator_drivers_sequence(): """ Test CubeManipulator class if it manages to manipulate cubelets properly """ mujoco_simulation = FullPerpendicularSimulation.build(n_substeps=10) mujoco_simulation.cube_model.rotate_face(X_AXIS, POSITIVE_SIDE, np.pi / 2) mujoco_simulation.cube_model.rotate_face(Y_AXIS, POSITIVE_SIDE, np.pi / 2) mujoco_simulation.cube_model.rotate_face(Z_AXIS, POSITIVE_SIDE, np.pi / 2) mujoco_simulation.cube_model.rotate_face(Y_AXIS, POSITIVE_SIDE, np.pi / 2) mujoco_simulation.cube_model.rotate_face(X_AXIS, POSITIVE_SIDE, np.pi / 2) target_angle = np.array([0.0, np.pi, 0.0, np.pi, 0.0, np.pi / 2]) assert ( np.linalg.norm(mujoco_simulation.get_qpos("cube_drivers") - target_angle) < 1e-6 ) POSSIBLE_COORDS = [-1, 0, 1] def _assert_cubelet_coords(manipulator, original_coords, current_coords): """ Check if given cubelet is present at given coords""" indexes = original_coords.round().astype(int) + 1 coord_idx = indexes[0] * 9 + indexes[1] * 3 + indexes[2] meta_info = manipulator.cubelet_meta_info[coord_idx] assert np.linalg.norm(meta_info["coords"] - original_coords) < 1e-6 if meta_info["type"] == "cubelet": mtx = manipulator._cubelet_rotation_matrix(meta_info, manipulator.sim.data.qpos) actual_current_coords = mtx @ original_coords.astype(float) assert np.linalg.norm(actual_current_coords - current_coords) < 1e-6 def test_cube_manipulator_cubelet_positions(): """ Test CubeManipulator class if it manages to manipulates cubelets properly """ mujoco_simulation = FullPerpendicularSimulation.build(n_substeps=10) for x_coord in POSSIBLE_COORDS: for y_coord in POSSIBLE_COORDS: for z_coord in POSSIBLE_COORDS: coords = np.array([x_coord, y_coord, z_coord]) _assert_cubelet_coords(mujoco_simulation.cube_model, coords, coords) mujoco_simulation.cube_model.rotate_face(X_AXIS, POSITIVE_SIDE, np.pi / 2) # These are not touched for x_coord in [0, -1]: for y_coord in POSSIBLE_COORDS: for z_coord in POSSIBLE_COORDS: coords = np.array([x_coord, y_coord, z_coord]) _assert_cubelet_coords(mujoco_simulation.cube_model, coords, coords) # Let's check four corner cubelets just to be sure _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, 1, 1]), np.array([1, -1, 1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, -1, 1]), np.array([1, -1, -1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, -1, -1]), np.array([1, 1, -1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, 1, -1]), np.array([1, 1, 1]) ) mujoco_simulation.cube_model.rotate_face(Y_AXIS, POSITIVE_SIDE, np.pi / 2) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([-1, 1, -1]), np.array([-1, 1, 1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([-1, 1, 1]), np.array([1, 1, 1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, 1, -1]), np.array([1, 1, -1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, -1, -1]), np.array([-1, 1, -1]) ) def test_snap_rotate_face_with_threshold(): from robogym.envs.dactyl.full_perpendicular import FullPerpendicularSimulation mujoco_simulation = FullPerpendicularSimulation.build(n_substeps=10) mujoco_simulation.cube_model.snap_rotate_face_with_threshold( X_AXIS, POSITIVE_SIDE, np.pi / 2 ) # These are not touched for x_coord in [0, -1]: for y_coord in POSSIBLE_COORDS: for z_coord in POSSIBLE_COORDS: coords = np.array([x_coord, y_coord, z_coord]) _assert_cubelet_coords(mujoco_simulation.cube_model, coords, coords) # Let's check four corner cubelets just to be sure _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, 1, 1]), np.array([1, -1, 1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, -1, 1]), np.array([1, -1, -1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, -1, -1]), np.array([1, 1, -1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, 1, -1]), np.array([1, 1, 1]) ) # Rotate this face again by 45 degrees mujoco_simulation.cube_model.snap_rotate_face_with_threshold( X_AXIS, POSITIVE_SIDE, np.pi / 4 ) cubelets_before = mujoco_simulation.get_qpos("cube_cubelets").copy() # None of these should do anything mujoco_simulation.cube_model.snap_rotate_face_with_threshold( Y_AXIS, POSITIVE_SIDE, np.pi / 8 ) mujoco_simulation.cube_model.snap_rotate_face_with_threshold( Y_AXIS, NEGATIVE_SIDE, np.pi / 8 ) mujoco_simulation.cube_model.snap_rotate_face_with_threshold( Z_AXIS, POSITIVE_SIDE, np.pi / 8 ) mujoco_simulation.cube_model.snap_rotate_face_with_threshold( Z_AXIS, NEGATIVE_SIDE, np.pi / 8 ) cubelets_after = mujoco_simulation.get_qpos("cube_cubelets").copy() assert np.linalg.norm(cubelets_before - cubelets_after) < 1e-6 # Revert mujoco_simulation.cube_model.snap_rotate_face_with_threshold( X_AXIS, POSITIVE_SIDE, -np.pi / 4 ) # Move a little mujoco_simulation.cube_model.snap_rotate_face_with_threshold( X_AXIS, POSITIVE_SIDE, 0.05 ) # Make sure cube gets realigned mujoco_simulation.cube_model.snap_rotate_face_with_threshold( Y_AXIS, POSITIVE_SIDE, np.pi / 2 ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([-1, 1, -1]), np.array([-1, 1, 1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([-1, 1, 1]), np.array([1, 1, 1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, 1, -1]), np.array([1, 1, -1]) ) _assert_cubelet_coords( mujoco_simulation.cube_model, np.array([1, -1, -1]), np.array([-1, 1, -1]) ) cubelets_final = rotation.normalize_angles( mujoco_simulation.get_qpos("cube_cubelets").copy() ) assert ( np.linalg.norm( cubelets_final - rotation.round_to_straight_angles(cubelets_final) ) < 1e-8 ) def test_pycuber_conversion(): from robogym.envs.dactyl.full_perpendicular import FullPerpendicularSimulation mujoco_simulation = FullPerpendicularSimulation.build() for i in range(5): cube = pycuber.Cube() for action in np.random.choice(list("LRFBDU"), size=20, replace=True): cube(str(action)) mujoco_simulation.cube_model.from_pycuber(cube) cube2 = mujoco_simulation.cube_model.to_pycuber() assert cube == cube2
8,123
30.984252
88
py
robogym
robogym-master/robogym/envs/dactyl/tests/test_reach.py
from robogym.envs.dactyl.reach import make_env def test_dactyl_reach(): env = make_env() obs = env.reset() expected_joints = ( "robot0:WRJ1", "robot0:WRJ0", "robot0:FFJ3", "robot0:FFJ2", "robot0:FFJ1", "robot0:FFJ0", "robot0:MFJ3", "robot0:MFJ2", "robot0:MFJ1", "robot0:MFJ0", "robot0:RFJ3", "robot0:RFJ2", "robot0:RFJ1", "robot0:RFJ0", "robot0:LFJ4", "robot0:LFJ3", "robot0:LFJ2", "robot0:LFJ1", "robot0:LFJ0", "robot0:THJ4", "robot0:THJ3", "robot0:THJ2", "robot0:THJ1", "robot0:THJ0", ) assert env.unwrapped.sim.model.joint_names == expected_joints for k, ob in obs.items(): assert ob.shape[0] > 0
826
21.972222
65
py
robogym
robogym-master/robogym/envs/dactyl/goals/full_unconstrained.py
import typing import numpy as np from robogym.envs.dactyl.common import cube_utils from robogym.goal.goal_generator import GoalGenerator from robogym.utils import rotation class FullUnconstrainedGoal(GoalGenerator): """ Rotate any face, no orientation objectives for the Z axis. """ def __init__( self, mujoco_simulation, success_threshold: dict, face_geom_names: typing.List[str], goal_directions: typing.Optional[typing.List[str]] = None, round_target_face: bool = True, ): """ Create new FullUnconstrainedGoal object :param mujoco_simulation: A SimulationInterface object for a mujoco simulation considered :param success_threshold: Dictionary of threshold levels for cube orientation and face rotation, for which we consider the cube "aligned" with the goal :param face_geom_names: Names of 6 face geoms of the cube for which we measure the rotation :param goal_directions: Whether to rotate faces only clockwise, counterclockwise or both :param round_target_face: Whether target face rotations should be only round angles (multiplies of pi/2) or not :param p_face_flip: If the cube is aligned, what is the probability of flipping the cube vs rotating the face """ super().__init__() assert len(face_geom_names) == 6, "Only supports full cube for now" self.mujoco_simulation = mujoco_simulation self.success_threshold = success_threshold self.face_geom_names = face_geom_names if goal_directions is None: self.goal_directions = ["cw", "ccw"] else: self.goal_directions = goal_directions self.round_target_face = round_target_face self.goal_candidates = list(range(len(self.face_geom_names))) def next_goal(self, random_state, current_state): """ Generate a new goal from current cube goal state """ cube_face = current_state["cube_face_angle"] self.mujoco_simulation.clone_target_from_cube() self.mujoco_simulation.target_model.soft_align_faces() # Make the goal so that any face is rotated at random face_to_shift = random_state.choice(self.goal_candidates) # Rotate given face by a random angle and return both, new rotations and an angle goal_face, delta_angle = cube_utils.rotated_face_with_angle( cube_face, face_to_shift, random_state, self.round_target_face, directions=self.goal_directions, ) self.mujoco_simulation.target_model.rotate_face( face_to_shift // 2, face_to_shift % 2, delta_angle ) return { "cube_pos": np.zeros(3), "cube_quat": np.zeros(4), "cube_face_angle": goal_face, "goal_type": "rotation", } def current_state(self): """ Extract current cube goal state """ return { "cube_pos": self.mujoco_simulation.get_qpos("cube_position"), "cube_quat": self.mujoco_simulation.get_qpos("cube_rotation"), "cube_face_angle": self.mujoco_simulation.get_face_angles("cube"), } def relative_goal(self, goal_state, current_state): """ Calculate a difference in the 'goal space' between current state and the target goal """ assert goal_state["goal_type"] == "rotation" return { # Cube pos does not count "cube_pos": np.zeros(goal_state["cube_pos"].shape), # Quaternion difference of a rotation "cube_quat": np.zeros(goal_state["cube_quat"].shape), # Angle differences "cube_face_angle": rotation.normalize_angles( goal_state["cube_face_angle"] - current_state["cube_face_angle"] ), } def goal_distance(self, goal_state, current_state): """ Distance from the current goal to the target state. """ relative_goal = self.relative_goal(goal_state, current_state) goal_distance = { "cube_pos": 0.0, "cube_quat": 0.0, "cube_face_angle": np.linalg.norm(relative_goal["cube_face_angle"]), } return goal_distance def goal_types(self) -> typing.Set[str]: return {"rotation"}
4,409
35.147541
99
py
robogym
robogym-master/robogym/envs/dactyl/goals/unconstrained_cube_solver.py
import logging import typing import numpy as np from robogym.envs.dactyl.goals.rubik_cube_solver import RubikCubeSolver from robogym.utils import rotation logger = logging.getLogger(__name__) class UnconstrainedCubeSolver(RubikCubeSolver): """ Generates a series of goals to solve a Rubik's cube. Goals are not constrained to apply to a particular face. """ def __init__( self, mujoco_simulation, success_threshold: typing.Dict[str, float], face_geom_names: typing.List[str], num_scramble_steps: int, ): """ Creates new UnconstrainedCubeSolver object """ self.success_threshold = success_threshold super().__init__( mujoco_simulation=mujoco_simulation, face_geom_names=face_geom_names, num_scramble_steps=num_scramble_steps, ) def _is_goal_met(self, current_face_state, threshold): """ Check if current face state matches current goal state. """ face_diff = rotation.normalize_angles(current_face_state - self.goal_face_state) return np.linalg.norm(face_diff, axis=-1) < threshold def next_goal(self, random_state, current_state): """ Generates a new goal from current cube goal state """ cube_pos = current_state["cube_pos"] cube_quat = current_state["cube_quat"] cube_face = current_state["cube_face_angle"] # Success threshold parameters face_threshold = self.success_threshold["cube_face_angle"] # Check if current state already meets goal state. if self._is_goal_met(cube_face, face_threshold): # Step forward in goal sequence to get next goal. self._step_goal() # Directly rotate the face indicated by the goal action. goal_action = self._get_goal_action() face_to_shift = goal_action.face_idx self.mujoco_simulation.target_model.rotate_face( face_to_shift // 2, face_to_shift % 2, goal_action.face_angle ) # align cube quat for visualization purposes, has no effect on goal being met cube_quat = rotation.quat_normalize(rotation.round_to_straight_quat(cube_quat)) return { "cube_pos": cube_pos, "cube_quat": cube_quat, "cube_face_angle": self.goal_face_state, "goal_type": "rotation", } def relative_goal(self, goal_state, current_state): """ Calculate a difference in the 'goal space' between current state and the target goal """ goal_type = goal_state["goal_type"] assert goal_type == "rotation", 'unknown goal_type "{}"'.format(goal_type) return { # Cube pos does not count "cube_pos": np.zeros(goal_state["cube_pos"].shape), # Quaternion difference of a rotation "cube_quat": np.zeros(goal_state["cube_quat"].shape), # Angle differences "cube_face_angle": rotation.normalize_angles( goal_state["cube_face_angle"] - current_state["cube_face_angle"] ), } def goal_distance(self, goal_state, current_state): """ Distance from the current goal to the target state. """ relative_goal = self.relative_goal(goal_state, current_state) goal_distance = { "cube_pos": 0.0, "cube_quat": 0.0, # qpos has no effect on whether we consider goal achieved "cube_face_angle": np.linalg.norm(relative_goal["cube_face_angle"]), "steps_to_solve": len(self.goal_sequence) - (self.goal_step % len(self.goal_sequence)), } return goal_distance def goal_reachable(self, goal_state, current_state): """ Check if goal is in reach from current state.""" relative_goal = self.relative_goal(goal_state, current_state) face_rotation_angles = relative_goal["cube_face_angle"] goal_type = goal_state["goal_type"] assert goal_type == "rotation", 'unknown goal_type "{}"'.format(goal_type) eps = 1e-6 rounded_rotation_angles = rotation.round_to_straight_angles( np.abs(rotation.normalize_angles(face_rotation_angles)) ) rotated_faces = list(np.where(rounded_rotation_angles > eps)[0]) goal_face_idx = self._get_goal_action().face_idx return rounded_rotation_angles[ goal_face_idx ] < np.pi / 2 + eps and rotated_faces in ([], [goal_face_idx])
4,548
35.103175
92
py
robogym
robogym-master/robogym/envs/dactyl/goals/face_curriculum.py
import typing import numpy as np from robogym.envs.dactyl.common import cube_utils from robogym.goal.goal_generator import GoalGenerator from robogym.utils import rotation class FaceCurriculumGoal(GoalGenerator): """ 'Face curriculum' goal generation. Generate goals that specify a fully aligned cube at a desired orientation with the specified face being up. """ def __init__( self, mujoco_simulation, success_threshold: dict, face_geom_names: typing.List[str], goal_directions: typing.Optional[typing.List[str]] = None, round_target_face: bool = True, p_face_flip: float = 0.25, ): """ Create new FaceCurriculumGoal object :param mujoco_simulation: A SimulationInterface object for a mujoco simulation considered :param success_threshold: Dictionary of threshold levels for cube orientation and face rotation, for which we consider the cube "aligned" with the goal :param face_geom_names: Names of 6 face geoms of the cube for which we measure the rotation :param goal_directions: Whether to rotate faces only clockwise, counterclockwise or both :param round_target_face: Whether target face rotations should be only round angles (multiplies of pi/2) or not :param p_face_flip: If the cube is aligned, what is the probability of flipping the cube vs rotating the face """ super().__init__() assert len(face_geom_names) in {2, 6}, "Only supports full cube or face cube" self.mujoco_simulation = mujoco_simulation self.success_threshold = success_threshold self.face_geom_names = face_geom_names if goal_directions is None: self.goal_directions = ["cw", "ccw"] else: self.goal_directions = goal_directions self.round_target_face = round_target_face self.p_face_flip = p_face_flip self.goal_quat_for_face = cube_utils.face_up_quats( mujoco_simulation.sim, "cube:cube:rot", self.face_geom_names ) def next_goal(self, random_state, current_state): """ Generate a new goal from current cube goal state """ cube_pos = current_state["cube_pos"] cube_quat = current_state["cube_quat"] cube_face = current_state["cube_face_angle"] # Success threshold parameters face_threshold = self.success_threshold["cube_face_angle"] rot_threshold = self.success_threshold["cube_quat"] self.mujoco_simulation.clone_target_from_cube() self.mujoco_simulation.align_target_faces() rounded_current_face = rotation.round_to_straight_angles(cube_face) # Face aligned - are faces in the current cube aligned within the threshold current_face_diff = rotation.normalize_angles(cube_face - rounded_current_face) face_aligned = np.linalg.norm(current_face_diff, axis=-1) < face_threshold # Z aligned - is there a cube face looking up within the rotation threshold if len(self.face_geom_names) == 2: z_aligned = rotation.rot_z_aligned(cube_quat, rot_threshold) else: # len(self.face_geom_names) == 6 z_aligned = rotation.rot_xyz_aligned(cube_quat, rot_threshold) # Do reorientation - with some probability, just reorient the cube do_reorientation = random_state.uniform() < self.p_face_flip # Rotate face - should we rotate face or reorient the cube rotate_face = face_aligned and z_aligned and not do_reorientation if rotate_face: # Chose index from the geoms that is highest on the z axis face_to_shift = cube_utils.face_up( self.mujoco_simulation.sim, self.face_geom_names ) # Rotate given face by a random angle and return both, new rotations and an angle goal_face, delta_angle = cube_utils.rotated_face_with_angle( cube_face, face_to_shift, random_state, self.round_target_face, directions=self.goal_directions, ) if len(self.face_geom_names) == 2: self.mujoco_simulation.rotate_target_face(face_to_shift, delta_angle) else: self.mujoco_simulation.rotate_target_face( face_to_shift // 2, face_to_shift % 2, delta_angle ) goal_quat = rotation.round_to_straight_quat(cube_quat) else: # need to flip cube # Gaol for face rotations is just aligning them goal_face = rounded_current_face # Make the goal so that a given face is straight up candidates = list(range(len(self.face_geom_names))) face_to_shift = random_state.choice(candidates) z_quat = cube_utils.uniform_z_aligned_quat(random_state) face_up_quat = self.goal_quat_for_face[face_to_shift] goal_quat = rotation.quat_mul(z_quat, face_up_quat) goal_quat = rotation.quat_normalize(goal_quat) return { "cube_pos": cube_pos, "cube_quat": goal_quat, "cube_face_angle": goal_face, "goal_type": "rotation" if rotate_face else "flip", } def current_state(self): """ Extract current cube goal state """ cube_pos = np.zeros(3) return { "cube_pos": cube_pos, "cube_quat": self.mujoco_simulation.get_qpos("cube_rotation"), "cube_face_angle": self.mujoco_simulation.get_face_angles("cube"), } def relative_goal(self, goal_state, current_state): """ Calculate a difference in the 'goal space' between current state and the target goal """ return { # Cube pos does not count "cube_pos": np.zeros(goal_state["cube_pos"].shape), # Quaternion difference of a rotation "cube_quat": rotation.quat_difference( goal_state["cube_quat"], current_state["cube_quat"] ), # Angle differences "cube_face_angle": rotation.normalize_angles( goal_state["cube_face_angle"] - current_state["cube_face_angle"] ), } def goal_distance(self, goal_state, current_state): """ Distance from the current goal to the target state. """ relative_goal = self.relative_goal(goal_state, current_state) goal_distance = { "cube_pos": 0.0, "cube_quat": rotation.quat_magnitude(relative_goal["cube_quat"]), "cube_face_angle": np.linalg.norm(relative_goal["cube_face_angle"]), } return goal_distance def goal_types(self) -> typing.Set[str]: return {"rotation", "flip"}
6,870
38.262857
99
py
robogym
robogym-master/robogym/envs/dactyl/goals/release_cube_solver.py
import logging from robogym.envs.dactyl.goals.face_cube_solver import FaceCubeSolverGoal logger = logging.getLogger(__name__) class ReleaseCubeSolverGoal(FaceCubeSolverGoal): def face_threshold(self): """ Dynamic face threshold to use a custom success threshold that is lower than the typical threshold to assess face alignment once the cube has been fully solved :return: """ if self.goal_step < len(self.goal_sequence): return self.success_threshold["cube_face_angle"] return 0.05 def _get_goal_action(self): """ Get the required action to achieve current goal state. """ # We solve the cube once and stop generating goals. if self.goal_step < len(self.goal_sequence): goal = self.goal_sequence[self.goal_step] else: goal = self.goal_sequence[-1] self.reached_terminal_state = True return goal
977
30.548387
73
py
robogym
robogym-master/robogym/envs/dactyl/goals/locked_parallel.py
from typing import Set import numpy as np from numpy.random import RandomState from robogym.envs.dactyl.common import cube_utils from robogym.envs.dactyl.common.cube_env import CubeSimulationInterface from robogym.goal.goal_generator import GoalGenerator from robogym.utils import rotation class LockedParallelGoal(GoalGenerator): """ Generates random orientation goals for the locked cube. Specifically, the goal orientation always has the sides aligned with, or "parallel" with, the x-y-z axes. Hence the name "Parallel" for this goal generator. Note: historically, we've also called this goal generator "XYZ," so you might see that name mentioned in docs etc. """ def __init__(self, mujoco_simulation: CubeSimulationInterface): """ Create new FaceCubeSolverGoalGenerator object :param success_threshold: Dictionary of threshold levels for cube orientation and face rotation, for which we consider the cube "aligned" with the goal """ self.mujoco_simulation = mujoco_simulation super().__init__() def next_goal(self, random_state: RandomState, current_state: dict) -> dict: """ Generate a new goal from current cube goal state """ # we just sample a random orientation, so current goal_state isn't used z_quat = cube_utils.uniform_z_aligned_quat(random_state) quat_choice = random_state.randint(len(cube_utils.PARALLEL_QUATS)) parallel_quat = cube_utils.PARALLEL_QUATS[quat_choice] goal_quat = rotation.quat_mul(z_quat, parallel_quat) # Create qpos for goal state (with just cube quat set) for rendering purposes. qpos_goal = np.zeros_like(self.mujoco_simulation.qpos) qpos_inds = self.mujoco_simulation.qpos_idxs["cube_rotation"] qpos_goal[qpos_inds] = goal_quat qpos_pos_inds = self.mujoco_simulation.qpos_idxs["cube_position"] qpos_goal[qpos_pos_inds] = np.array([0.0, 0.0, -0.025]) return {"cube_quat": goal_quat, "qpos_goal": qpos_goal, "goal_type": "flip"} def current_state(self) -> dict: """ Extract current cube goal state """ return { "cube_quat": self.mujoco_simulation.get_qpos("cube_rotation"), } def relative_goal(self, goal_state: dict, current_state: dict) -> dict: """ Calculate a difference in the 'goal space' between current state and the target goal """ return { # We don't care about pos in goal. But we have to include it here because # we need cube pos to be present in relative_goal observation. "cube_pos": np.zeros(3), # Quaternion difference of a rotation "cube_quat": rotation.quat_difference( goal_state["cube_quat"], current_state["cube_quat"] ), } def goal_distance(self, goal_state: dict, current_state: dict) -> dict: """ Distance from the current goal to the target state. """ relative_goal = self.relative_goal(goal_state, current_state) goal_distance = { "cube_quat": rotation.quat_magnitude(relative_goal["cube_quat"]), } return goal_distance def goal_types(self) -> Set[str]: return {"flip"}
3,288
40.1125
94
py
robogym
robogym-master/robogym/envs/dactyl/goals/face_free.py
import typing import numpy as np from robogym.envs.dactyl.common import cube_utils from robogym.goal.goal_generator import GoalGenerator from robogym.utils import rotation class FaceFreeGoal(GoalGenerator): """ Rotate the top face of the cube and make sure it's still a top face, but don't constrain the rotation of the "up" (Z) axis, allowing the cube to have any orientation with the desired top face. """ def __init__( self, mujoco_simulation, success_threshold: dict, face_geom_names: typing.List[str], goal_directions: typing.Optional[typing.List[str]] = None, round_target_face: bool = True, p_face_flip: float = 0.25, ): """ Create new FaceFreeGoal object :param mujoco_simulation: A SimulationInterface object for a mujoco simulation considered :param success_threshold: Dictionary of threshold levels for cube orientation and face rotation, for which we consider the cube "aligned" with the goal :param face_geom_names: Names of 6 face geoms of the cube for which we measure the rotation :param goal_directions: Whether to rotate faces only clockwise, counterclockwise or both :param round_target_face: Whether target face rotations should be only round angles (multiplies of pi/2) or not :param p_face_flip: If the cube is aligned, what is the probability of flipping the cube vs rotating the face """ super().__init__() assert len(face_geom_names) in {2, 6}, "Only supports full cube or face cube" self.mujoco_simulation = mujoco_simulation self.success_threshold = success_threshold self.face_geom_names = face_geom_names if goal_directions is None: self.goal_directions = ["cw", "ccw"] else: self.goal_directions = goal_directions self.round_target_face = round_target_face self.p_face_flip = p_face_flip self.goal_quat_for_face = cube_utils.face_up_quats( mujoco_simulation.sim, "cube:cube:rot", self.face_geom_names ) def next_goal(self, random_state, current_state): """ Generate a new goal from current cube goal state """ cube_quat = current_state["cube_quat"] cube_face = current_state["cube_face_angle"] # Success threshold parameters face_threshold = self.success_threshold["cube_face_angle"] rot_threshold = self.success_threshold["cube_quat"] self.mujoco_simulation.clone_target_from_cube() self.mujoco_simulation.align_target_faces() rounded_current_face = rotation.round_to_straight_angles(cube_face) # Face aligned - are faces in the current cube aligned within the threshold current_face_diff = rotation.normalize_angles(cube_face - rounded_current_face) face_aligned = np.linalg.norm(current_face_diff) < face_threshold # Z aligned - is there a cube face looking up within the rotation threshold if len(self.face_geom_names) == 2: z_aligned = rotation.rot_z_aligned(cube_quat, rot_threshold) else: # len(self.face_geom_names) == 6 z_aligned = rotation.rot_xyz_aligned(cube_quat, rot_threshold) axis_nr, axis_sign = cube_utils.up_axis_with_sign(cube_quat) # Do reorientation - with some probability, just reorient the cube do_reorientation = random_state.uniform() < self.p_face_flip # Rotate face - should we rotate face or reorient the cube rotate_face = face_aligned and z_aligned and not do_reorientation if rotate_face: # Chose index from the geoms that is highest on the z axis face_to_shift = cube_utils.face_up( self.mujoco_simulation.sim, self.face_geom_names ) # Rotate given face by a random angle and return both, new rotations and an angle goal_face, delta_angle = cube_utils.rotated_face_with_angle( cube_face, face_to_shift, random_state, self.round_target_face, directions=self.goal_directions, ) if len(self.face_geom_names) == 2: self.mujoco_simulation.rotate_target_face(face_to_shift, delta_angle) else: self.mujoco_simulation.rotate_target_face( face_to_shift // 2, face_to_shift % 2, delta_angle ) goal_quat = cube_utils.align_quat_up(cube_quat) else: # need to flip cube # Gaol for face rotations is just aligning them goal_face = rounded_current_face # Make the goal so that a given face is straight up candidates = list(range(len(self.face_geom_names))) face_to_shift = random_state.choice(candidates) z_quat = cube_utils.uniform_z_aligned_quat(random_state) face_up_quat = self.goal_quat_for_face[face_to_shift] goal_quat = rotation.quat_mul(z_quat, face_up_quat) goal_quat = rotation.quat_normalize(goal_quat) return { "cube_pos": np.zeros(3), "cube_quat": goal_quat, "cube_face_angle": goal_face, "goal_type": "rotation" if rotate_face else "flip", "axis_nr": axis_nr, "axis_sign": axis_sign, } def current_state(self): """ Extract current cube goal state """ return { "cube_pos": self.mujoco_simulation.get_qpos("cube_position"), "cube_quat": self.mujoco_simulation.get_qpos("cube_rotation"), "cube_face_angle": self.mujoco_simulation.get_face_angles("cube"), } def relative_goal(self, goal_state, current_state): """ Calculate a difference in the 'goal space' between current state and the target goal """ if goal_state["goal_type"] == "rotation": orientation_distance = cube_utils.distance_quat_from_being_up( current_state["cube_quat"], goal_state["axis_nr"], goal_state["axis_sign"], ) elif goal_state["goal_type"] == "flip": orientation_distance = rotation.quat_difference( goal_state["cube_quat"], current_state["cube_quat"] ) else: raise ValueError('unknown goal_type "{}"'.format(goal_state["goal_type"])) return { # Cube pos does not count "cube_pos": np.zeros(goal_state["cube_pos"].shape), # Quaternion difference of a rotation "cube_quat": orientation_distance, # Angle differences "cube_face_angle": rotation.normalize_angles( goal_state["cube_face_angle"] - current_state["cube_face_angle"] ), } def goal_distance(self, goal_state, current_state): """ Distance from the current goal to the target state. """ relative_goal = self.relative_goal(goal_state, current_state) goal_distance = { "cube_pos": 0.0, "cube_quat": rotation.quat_magnitude(relative_goal["cube_quat"]), "cube_face_angle": np.linalg.norm(relative_goal["cube_face_angle"]), } return goal_distance def goal_types(self) -> typing.Set[str]: """See parent for documentation.""" return {"rotation", "flip"}
7,517
38.568421
99
py
robogym
robogym-master/robogym/envs/dactyl/goals/locked_real_image.py
import numpy as np from numpy.random import RandomState from robogym.envs.dactyl.common.cube_env import CubeSimulationInterface from robogym.envs.dactyl.common.cube_utils import DEFAULT_CAMERA_NAMES from robogym.envs.dactyl.goals.locked_parallel import LockedParallelGoal class LockedRealImageGoal(LockedParallelGoal): """ Goal generation which uses iterate through a sequence of goal images loaded from disk. """ def __init__(self, mujoco_simulation: CubeSimulationInterface, goal_data_path: str): super().__init__(mujoco_simulation) self.goals = np.load(goal_data_path) self.goal_idx = 0 def next_goal(self, random_state: RandomState, goal_state: dict) -> dict: """ Load next goal image. """ num_goals = len(self.goals["quats"]) goal_image = np.concatenate( [ self.goals[cam][self.goal_idx % num_goals] for cam in DEFAULT_CAMERA_NAMES ], axis=0, ) goal = { "cube_quat": self.goals["quats"][self.goal_idx % num_goals], "qpos_goal": np.zeros_like(self.mujoco_simulation.qpos), "vision_goal": goal_image, "goal_type": "flip", } self.goal_idx += 1 return goal
1,309
30.190476
88
py
robogym
robogym-master/robogym/envs/dactyl/goals/shadow_hand_reach_fingertip_pos.py
import numpy as np from numpy.random import RandomState from robogym.envs.dactyl.reach import ReachSimulation from robogym.goal.goal_generator import GoalGenerator from robogym.robot.shadow_hand.hand_forward_kinematics import FINGERTIP_SITE_NAMES from robogym.utils.dactyl_utils import actuated_joint_range class FingertipPosGoal(GoalGenerator): """ Goal generation to sample random qpos within actuator control range. """ def __init__( self, mujoco_simulation: ReachSimulation, goal_simulation: ReachSimulation ): """ Create new FingertipPosGoal object """ self.mujoco_simulation = mujoco_simulation self.goal_simulation = goal_simulation self.goal_joint_pos = mujoco_simulation.shadow_hand.observe().joint_positions() super().__init__() def next_goal(self, random_state: RandomState, current_state: dict) -> dict: """ Goal is defined as fingertip position. We sample next goal by sampling actuator control within control range then use forward kinematic to calculate fingertip position. """ sim = self.mujoco_simulation.mj_sim goal_sim = self.goal_simulation.mj_sim # We need to update control range and joint range for goal simulation because # they can be changed by randomizers. goal_sim.model.jnt_range[:] = sim.model.jnt_range goal_sim.model.actuator_ctrlrange[:] = sim.model.actuator_ctrlrange # Sample around current pose of the fingers in joint space. joint_limits = actuated_joint_range(sim) joint_range = joint_limits[:, 1] - joint_limits[:, 0] goal_joint_pos = random_state.normal( loc=self.goal_joint_pos, scale=0.1 * joint_range ) goal_joint_pos = np.clip(goal_joint_pos, joint_limits[:, 0], joint_limits[:, 1]) # replace state to ensure reachability with current model self.goal_simulation.set_qpos("robot0:hand_joint_angles", goal_joint_pos) self.goal_simulation.forward() # take a few steps to avoid goals that are impossible due to contacts for steps in range(2): self.goal_simulation.shadow_hand.set_position_control( self.goal_simulation.shadow_hand.denormalize_position_control( self.goal_simulation.shadow_hand.zero_control(), relative_action=True, ) ) self.goal_simulation.step() self.goal_joint_pos = ( self.goal_simulation.shadow_hand.observe().joint_positions() ) return { "fingertip_pos": self._get_fingertip_position(self.goal_simulation), } def current_state(self) -> dict: """ Extract current cube goal state """ return {"fingertip_pos": self._get_fingertip_position(self.mujoco_simulation)} def relative_goal(self, goal_state: dict, current_state: dict) -> dict: return { "fingertip_pos": goal_state["fingertip_pos"] - current_state["fingertip_pos"] } def goal_distance(self, goal_state: dict, current_state: dict) -> dict: relative_goal = self.relative_goal(goal_state, current_state) return {"fingertip_pos": np.linalg.norm(relative_goal["fingertip_pos"])} @staticmethod def _get_fingertip_position(simulation: ReachSimulation): """ Get absolute fingertip positions in mujoco frame. """ fingertip_pos = np.array( [ simulation.mj_sim.data.get_site_xpos(f"robot0:{site}") for site in FINGERTIP_SITE_NAMES ] ) fingertip_pos = fingertip_pos.flatten() return fingertip_pos
3,768
35.240385
88
py
robogym
robogym-master/robogym/envs/dactyl/goals/face_cube_solver.py
import logging import typing import numpy as np from robogym.envs.dactyl.common import cube_utils from robogym.envs.dactyl.goals.rubik_cube_solver import RubikCubeSolver from robogym.utils import rotation logger = logging.getLogger(__name__) class FaceCubeSolverGoal(RubikCubeSolver): """ Generates a series of goals to solve a Rubik's cube. Goals are generated in a way to always rotate the top face. """ def __init__( self, mujoco_simulation, success_threshold: typing.Dict[str, float], face_geom_names: typing.List[str], num_scramble_steps: int, ): """ Create new FaceCubeSolverGoalGenerator object :param success_threshold: Dictionary of threshold levels for cube orientation and face rotation, for which we consider the cube "aligned" with the goal """ self.success_threshold = success_threshold super().__init__( mujoco_simulation=mujoco_simulation, face_geom_names=face_geom_names, num_scramble_steps=num_scramble_steps, ) def _is_goal_met(self, current_face_state, threshold): """ Check if current face state matches current goal state. """ face_up = cube_utils.face_up(self.mujoco_simulation.sim, self.face_geom_names) goal_face_idx = self._get_goal_action().face_idx face_diff = rotation.normalize_angles(current_face_state - self.goal_face_state) return ( face_up == goal_face_idx and np.linalg.norm(face_diff, axis=-1) < threshold ) def face_threshold(self): return self.success_threshold["cube_face_angle"] def next_goal(self, random_state, current_state): """ Generate a new goal from current cube goal state """ cube_pos = current_state["cube_pos"] cube_quat = current_state["cube_quat"] cube_face = current_state["cube_face_angle"] # Success threshold parameters face_threshold = self.face_threshold() rot_threshold = self.success_threshold["cube_quat"] rounded_current_face = rotation.round_to_straight_angles(cube_face) # Face aligned - are faces in the current cube aligned within the threshold current_face_diff = rotation.normalize_angles(cube_face - rounded_current_face) face_aligned = np.linalg.norm(current_face_diff, axis=-1) < face_threshold # Z aligned - is there a cube face looking up within the rotation threshold z_aligned = rotation.rot_xyz_aligned(cube_quat, rot_threshold) axis_nr, axis_sign = cube_utils.up_axis_with_sign(cube_quat) cube_aligned = face_aligned and z_aligned # Check if current state already meets goal state. if cube_aligned and self._is_goal_met(cube_face, face_threshold): # Step forward in goal sequence to get next goal. self._step_goal() goal_action = self._get_goal_action() if cube_aligned: # Choose index from the geoms that is highest on the z axis face_to_shift = cube_utils.face_up( self.mujoco_simulation.sim, self.face_geom_names ) # Rotate face if the face to rotate for next goal is facing up. rotate_face = face_to_shift == goal_action.face_idx else: rotate_face = False if rotate_face: self.mujoco_simulation.target_model.rotate_face( face_to_shift // 2, face_to_shift % 2, goal_action.face_angle ) goal_quat = cube_utils.align_quat_up(cube_quat) goal_face = self.goal_face_state else: # need to flip cube # Rotate cube so that goal face is on the top. We currently apply # a deterministic transformation here that would get the goal face to the top, # which is _not_ the minimal possible orientation change, which may be # worth addressing in the future. goal_quat = self.goal_quat_for_face[goal_action.face_idx] # No need to rotate face, just align them. goal_face = rounded_current_face goal_quat = rotation.quat_normalize(goal_quat) return { "cube_pos": cube_pos, "cube_quat": goal_quat, "cube_face_angle": goal_face, "goal_type": "rotation" if rotate_face else "flip", "axis_nr": axis_nr, "axis_sign": axis_sign, } def relative_goal(self, goal_state, current_state): """ Calculate a difference in the 'goal space' between current state and the target goal """ if goal_state["goal_type"] == "rotation": orientation_distance = cube_utils.distance_quat_from_being_up( current_state["cube_quat"], goal_state["axis_nr"], goal_state["axis_sign"], ) elif goal_state["goal_type"] == "flip": orientation_distance = rotation.quat_difference( goal_state["cube_quat"], current_state["cube_quat"] ) else: raise ValueError('unknown goal_type "{}"'.format(goal_state["goal_type"])) return { # Cube pos does not count "cube_pos": np.zeros(goal_state["cube_pos"].shape), # Quaternion difference of a rotation "cube_quat": orientation_distance, # Angle differences "cube_face_angle": rotation.normalize_angles( goal_state["cube_face_angle"] - current_state["cube_face_angle"] ), } def goal_distance(self, goal_state, current_state): """ Distance from the current goal to the target state. """ relative_goal = self.relative_goal(goal_state, current_state) goal_distance = { "cube_pos": 0.0, "cube_quat": rotation.quat_magnitude(relative_goal["cube_quat"]), "cube_face_angle": np.linalg.norm(relative_goal["cube_face_angle"]), "steps_to_solve": len(self.goal_sequence) - (self.goal_step % len(self.goal_sequence)), "goal_step": self.goal_step, } return goal_distance def goal_reachable(self, goal_state, current_state): """ Check if goal is in reach from current state.""" relative_goal = self.relative_goal(goal_state, current_state) face_rotation_angles = relative_goal["cube_face_angle"] goal_type = goal_state["goal_type"] eps = 1e-6 rounded_rotation_angles = rotation.round_to_straight_angles( np.abs(rotation.normalize_angles(face_rotation_angles)) ) rotated_faces = list(np.where(rounded_rotation_angles > eps)[0]) if goal_type == "rotation": # When doing face rotation, three conditions should met: # 1. Goal face should face up # 2. Rounded rotation angle for goal face should be at most 90 degree. # 3. Rounded rotation angle for other faces should be 0. goal_face_idx = self._get_goal_action().face_idx face_up = cube_utils.face_up( self.mujoco_simulation.sim, self.face_geom_names ) return ( goal_face_idx == face_up and rounded_rotation_angles[goal_face_idx] < np.pi / 2 + eps and rotated_faces in ([], [goal_face_idx]) ) elif goal_type == "flip": # When doing flipping, rounded rotation angles should be 0. return len(rotated_faces) == 0 else: raise ValueError('unknown goal_type "{}"'.format(goal_type))
7,728
37.645
94
py
robogym
robogym-master/robogym/envs/dactyl/goals/rubik_cube_solver.py
import logging import typing import numpy as np import pycuber from robogym.envs.dactyl.common import cube_utils from robogym.goal.goal_generator import GoalGenerator from robogym.utils import rotation from robogym.utils.rubik_utils import solve_fast logger = logging.getLogger(__name__) class GoalAction(typing.NamedTuple): face_idx: int face_angle: float pycuber_action: str num_remaining_actions: int class RubikCubeSolver(GoalGenerator): """ Solve the cube using the kociemba rubik cube solver """ # Mapping from Mujoco face id to pycuber action. FACE_ACTIONS = tuple("LRFBDU") # Mapping from Mujoco face id to cube color. FACE_COLORS = tuple("ROGBWY") # Mapping from Mujoco face id to rotation sign. Note that pycuber # rotation angle needs to be flipped for certain faces. FACE_SIGNS = [1, -1, 1, -1, 1, -1] def __init__( self, mujoco_simulation, face_geom_names: typing.List[str], num_scramble_steps: int, ): """ Create new FaceCubeSolverGoalGenerator object :param mujoco_simulation: A SimulationInterface object for a mujoco simulation considered :param success_threshold: Dictionary of threshold levels for cube orientation and face rotation, for which we consider the cube "aligned" with the goal """ super().__init__() assert len(face_geom_names) == 6, "Only full cube can be solved" self.mujoco_simulation = mujoco_simulation self.face_geom_names = face_geom_names self.num_scramble_steps = num_scramble_steps self.goal_quat_for_face = cube_utils.face_up_quats( mujoco_simulation.sim, "cube:cube:rot", self.face_geom_names ) self._reset_goal_state(pycuber.Cube()) def _generate_solution_sequence(self, cube): """ Returns an action sequence to solve the cube. """ # Try to find a reasonable length solution. step = 0 solution = None while step < 5: try: max_depth = self.num_scramble_steps + 2 ** step - 1 solution = solve_fast(cube, max_depth=max_depth) break except ValueError: logging.info(f"Cannot solve cube within {max_depth} steps.") step += 1 assert solution is not None, f"Could not find solution in {max_depth} steps" return self._normalize_actions(solution.split()) @classmethod def _normalize_actions(cls, actions): """ Normalize Singmaster Notation to tuple of action in'UDLRFB' and angle in (pi/2, -pi/2). """ normalized_actions = [] for i, action in enumerate(actions): # We track to number of remaining pycuber actions so we can use it to generate # optimal solution sequence during goal regeneration. num_actions = 1 num_remaining_actions = len(actions) - i if action.endswith("2"): num_actions = 2 action = action[:-1] if action.endswith("'"): angle = -np.pi / 2 else: angle = np.pi / 2 face_idx = cls.FACE_ACTIONS.index(action[0]) angle *= cls.FACE_SIGNS[face_idx] normalized_actions.extend( [ GoalAction( face_idx=face_idx, face_angle=angle, pycuber_action=action, num_remaining_actions=num_remaining_actions, ) ] * num_actions ) return normalized_actions def _step_goal(self): """ Move one step forward in the goal sequence. Also update current goal state. """ self.goal_step += 1 goal_action = self._get_goal_action() self.goal_face_state[goal_action.face_idx] += goal_action.face_angle def _get_goal_action(self): """ Get the required action to achieve current goal state. """ # We solve the cube first and then reverse this sequence, then solve again, and # so on until we run out of time. solve_forward = (self.goal_step // len(self.goal_sequence)) % 2 == 0 if solve_forward: goal_idx = self.goal_step % len(self.goal_sequence) goal = self.goal_sequence[goal_idx] else: goal_idx = ( len(self.goal_sequence) - 1 - (self.goal_step % len(self.goal_sequence)) ) goal = self.goal_sequence[goal_idx] # flip direction on face rotation goal = GoalAction( face_idx=goal.face_idx, face_angle=-goal.face_angle, pycuber_action=goal.pycuber_action, num_remaining_actions=goal.num_remaining_actions, ) return goal def current_state(self): """ Extract current cube goal state """ cube_pos = self.mujoco_simulation.get_qpos("cube_position") return { "cube_pos": cube_pos, "cube_quat": self.mujoco_simulation.get_qpos("cube_rotation"), "cube_face_angle": self.mujoco_simulation.get_face_angles("cube"), } def reset(self, random_state): """ Reset state of the goal generator. """ cube = self.mujoco_simulation.cube_model.to_pycuber() self._reset_goal_state(cube) def _reset_goal_state(self, cube): self.reached_terminal_state = False initial_goal_state = self.current_state()["cube_face_angle"] initial_goal_state = rotation.round_to_straight_angles(initial_goal_state) logger.info("Reset goal generation state with pycuber state") logger.info(cube) self.mujoco_simulation.clone_target_from_cube() self.mujoco_simulation.align_target_faces() self.goal_sequence = self._generate_solution_sequence(cube) logger.info("Goal Sequence:") self._print_goal_sequence() self.goal_face_state = initial_goal_state self.goal_step = -1 self._step_goal() def _print_goal_sequence(self): sequence = " ".join(a.pycuber_action for a in self.goal_sequence) logging.info(f"Solution Sequence: {sequence}") def goal_types(self) -> typing.Set[str]: return {"rotation", "flip"}
6,493
31.964467
97
py
robogym
robogym-master/robogym/envs/dactyl/goals/fixed_fair_scramble.py
import logging from robogym.envs.dactyl.goals.face_cube_solver import FaceCubeSolverGoal logger = logging.getLogger(__name__) class FixedFairScrambleGoal(FaceCubeSolverGoal): """ Generates a series of goals to apply a "fair scramble" to a fully solved Rubik's cube. The fair scramble was generated using the WCA app and was not cherry-picked: https://www.worldcubeassociation.org/regulations/scrambles/ Goals are generated in a way to always rotate the top face. """ def _generate_solution_sequence(self, cube): solution = "L2 U2 R2 B D2 B2 D2 L2 F' D' R B F L U' F D' L2" return self._normalize_actions(solution.split())
675
34.578947
90
py
robogym
robogym-master/robogym/envs/rearrange/composer.py
import attr from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.goals.object_state import GoalArgs from robogym.envs.rearrange.simulation.composer import ( ComposerRearrangeSim, ComposerRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class ComposerRearrangeEnvParameters(RearrangeEnvParameters): simulation_params: ComposerRearrangeSimParameters = build_nested_attr( ComposerRearrangeSimParameters ) @attr.s(auto_attribs=True) class ComposerRearrangeEnvConstants(RearrangeEnvConstants): goal_args: GoalArgs = build_nested_attr(GoalArgs, default={"stabilize_goal": True}) goal_generation: str = "train" class ComposerRearrangeEnv( RearrangeEnv[ ComposerRearrangeEnvParameters, ComposerRearrangeEnvConstants, ComposerRearrangeSim, ] ): def _sample_group_attributes(self, num_groups: int): attrs_dict = super()._sample_group_attributes(num_groups) attrs_dict["num_geoms"] = self._random_state.randint( low=1, high=self.parameters.simulation_params.num_max_geoms + 1, size=num_groups, ) return attrs_dict make_env = ComposerRearrangeEnv.build
1,338
26.895833
87
py
robogym
robogym-master/robogym/envs/rearrange/chessboard.py
import logging from typing import List import attr import numpy as np from robogym.envs.rearrange.common.mesh import ( MeshRearrangeEnv, MeshRearrangeEnvConstants, MeshRearrangeEnvParameters, MeshRearrangeSimParameters, ) from robogym.envs.rearrange.common.utils import find_meshes_by_dirname from robogym.envs.rearrange.goals.object_state_fixed import ObjectFixedStateGoal from robogym.envs.rearrange.simulation.base import ObjectGroupConfig from robogym.envs.rearrange.simulation.chessboard import ChessboardRearrangeSim from robogym.robot_env import build_nested_attr logger = logging.getLogger(__name__) CHESS_CHARS = ["rook", "queen", "bishop", "knight"] @attr.s(auto_attribs=True) class ChessboardRearrangeEnvParameters(MeshRearrangeEnvParameters): simulation_params: MeshRearrangeSimParameters = build_nested_attr( MeshRearrangeSimParameters, default=dict(num_objects=len(CHESS_CHARS), mesh_scale=0.4), ) class ChessboardRearrangeEnv( MeshRearrangeEnv[ ChessboardRearrangeEnvParameters, MeshRearrangeEnvConstants, ChessboardRearrangeSim, ] ): MESH_FILES = find_meshes_by_dirname("chess") def _sample_random_object_groups( self, dedupe_objects: bool = False ) -> List[ObjectGroupConfig]: return super()._sample_random_object_groups(dedupe_objects=True) def _sample_object_colors(self, num_groups: int): assert num_groups == 4 return [[0.267, 0.165, 0.133, 1.0]] * num_groups def _sample_object_meshes(self, num_groups: int): assert num_groups == 4 return [self.MESH_FILES[name] for name in CHESS_CHARS[:num_groups]] def _reset(self): super()._reset() # Scale chessboard properly (x, y, _), (w, h, _), z = self.mujoco_simulation.get_table_dimensions() placement_area = self.mujoco_simulation.get_placement_area() px = placement_area.offset[0] py = placement_area.offset[1] pw = placement_area.size[0] ph = placement_area.size[1] # Move board to center of placement area. sim = self.mujoco_simulation.mj_sim body_id = sim.model.body_name2id("chessboard") sim.model.body_pos[body_id][:] = [x - w + px + pw / 2, y - h + py + ph / 2, z] self.mujoco_simulation.forward() @classmethod def build_goal_generation(cls, constants, mujoco_simulation): pw, ph, _ = mujoco_simulation.get_placement_area().size sim = mujoco_simulation.mj_sim geom_id = sim.model.geom_name2id("chessboard") cw, ch = sim.model.geom_size[geom_id, :2] num_objects = mujoco_simulation.num_objects placements = np.zeros((num_objects, 2)) placements[:, 0] = 1 - 1.0 / num_objects / 2 placements[:, 1] = ( np.linspace( ph / 2 - ch + ch / num_objects, ph / 2 + ch - ch / num_objects, num_objects, ) / ph ) return ObjectFixedStateGoal( mujoco_simulation, args=constants.goal_args, relative_placements=placements ) make_env = ChessboardRearrangeEnv.build
3,177
32.104167
87
py
robogym
robogym-master/robogym/envs/rearrange/ycb_pickandplace.py
from robogym.envs.rearrange.common.base import RearrangeEnvConstants from robogym.envs.rearrange.goals.pickandplace import PickAndPlaceGoal from robogym.envs.rearrange.simulation.mesh import MeshRearrangeSim from robogym.envs.rearrange.ycb import YcbRearrangeEnv class YcbPickAndPlaceEnv(YcbRearrangeEnv): @classmethod def build_goal_generation( cls, constants: RearrangeEnvConstants, mujoco_simulation: MeshRearrangeSim ): return PickAndPlaceGoal(mujoco_simulation, constants.goal_args) make_env = YcbPickAndPlaceEnv.build
556
33.8125
82
py
robogym
robogym-master/robogym/envs/rearrange/table_setting.py
import logging from typing import List import attr import numpy as np from robogym.envs.rearrange.common.mesh import ( MeshRearrangeEnv, MeshRearrangeEnvConstants, MeshRearrangeEnvParameters, MeshRearrangeSimParameters, ) from robogym.envs.rearrange.goals.object_state_fixed import ObjectFixedStateGoal from robogym.envs.rearrange.simulation.base import ObjectGroupConfig from robogym.envs.rearrange.simulation.mesh import MeshRearrangeSim from robogym.envs.rearrange.ycb import find_ycb_meshes from robogym.robot_env import build_nested_attr from robogym.utils.rotation import quat_from_angle_and_axis logger = logging.getLogger(__name__) @attr.s(auto_attribs=True) class TableSettingRearrangeEnvParameters(MeshRearrangeEnvParameters): simulation_params: MeshRearrangeSimParameters = build_nested_attr( MeshRearrangeSimParameters, default=dict(num_objects=5) ) class TableSettingRearrangeEnv( MeshRearrangeEnv[ TableSettingRearrangeEnvParameters, MeshRearrangeEnvConstants, MeshRearrangeSim, ] ): MESH_FILES = find_ycb_meshes() def _sample_random_object_groups( self, dedupe_objects: bool = False ) -> List[ObjectGroupConfig]: return super()._sample_random_object_groups(dedupe_objects=True) def _sample_object_colors(self, num_groups: int): assert num_groups == 5 return [[0.99, 0.44, 0.35, 1.0]] + [[0.506, 0.675, 0.75, 1.0]] * 4 def _sample_object_size_scales(self, num_groups: int): assert num_groups == 5 return [0.6, 0.53, 0.63, 0.6, 0.6] def _sample_object_meshes(self, num_groups: int): """Add one plate, 2 forks, 1 spoon and 1 knife.""" return [ self.MESH_FILES[name] for name in ["029_plate", "030_fork", "030_fork", "032_knife", "031_spoon"] ] @classmethod def build_goal_generation(cls, constants, mujoco_simulation): return ObjectFixedStateGoal( mujoco_simulation, args=constants.goal_args, relative_placements=np.array( [ [0.6, 0.5], # "029_plate" [0.6, 0.68], # "030_fork" [0.6, 0.75], # "030_fork" [0.6, 0.36], # "032_knife" [0.6, 0.28], # "031_spoon" ] ), init_quats=np.array( [ [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], # We need to rotate the spoon a little bit counter-clock-wise to be aligned with others. quat_from_angle_and_axis(0.38, np.array([0, 0, 1.0])), ] ), ) make_env = TableSettingRearrangeEnv.build
2,813
32.105882
108
py
robogym
robogym-master/robogym/envs/rearrange/holdout.py
import os from typing import Dict, List, Optional, cast import attr import numpy as np from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.goals.holdout_object_state import ( HoldoutGoalArgs, HoldoutObjectStateGoal, ) from robogym.envs.rearrange.holdouts import STATE_DIR from robogym.envs.rearrange.simulation.base import ObjectGroupConfig from robogym.envs.rearrange.simulation.holdout import ( HoldoutRearrangeSim, HoldoutRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class HoldoutRearrangeEnvConstants(RearrangeEnvConstants): # Path to file storing initial state of objects. # If not specified, initial state will be randomly sampled. initial_state_path: Optional[str] = None goal_args: HoldoutGoalArgs = build_nested_attr(HoldoutGoalArgs) randomize_target: bool = False @attr.s(auto_attribs=True) class HoldoutRearrangeEnvParameters(RearrangeEnvParameters): simulation_params: HoldoutRearrangeSimParameters = build_nested_attr( HoldoutRearrangeSimParameters ) # Hold out arg should use explicitly defined material without randomization. material_names: Optional[List[str]] = attr.ib(default=cast(List[str], [])) @material_names.validator def validate_material_names(self, _, value): assert not value, ( "Specifying material names for holdout in parameters is not supported. " "Please specify material in jsonnet config directly." ) class HoldoutRearrangeEnv( RearrangeEnv[ HoldoutRearrangeEnvParameters, HoldoutRearrangeEnvConstants, HoldoutRearrangeSim, ] ): def _sample_random_object_groups( self, dedupe_objects: bool = False ) -> List[ObjectGroupConfig]: # Create dummy object groups based on task object config so that reward # function can take duplicated objects in holdouts into consideration. object_groups = [] num_objects = self.parameters.simulation_params.num_objects object_id = 0 for c in self.parameters.simulation_params.task_object_configs[:num_objects]: object_group = ObjectGroupConfig(count=c.count) # Set up object ids object_group.object_ids = list(range(object_id, object_id + c.count)) object_id += c.count object_groups.append(object_group) return object_groups def _sample_group_attributes(self, num_groups: int) -> Dict[str, list]: # We don't set random attributes for object groups return {} def _apply_object_colors(self): # We don't apply customized object colors. pass def _apply_object_size_scales(self): # We don't apply customized object size scaling. pass def _randomize_object_initial_states(self): if self.constants.initial_state_path: initial_state = np.load( os.path.join(STATE_DIR, self.constants.initial_state_path) ) self.mujoco_simulation.set_object_pos( initial_state["obj_pos"][: self.mujoco_simulation.num_objects] ) self.mujoco_simulation.set_object_quat( initial_state["obj_quat"][: self.mujoco_simulation.num_objects] ) self.mujoco_simulation.forward() else: super()._randomize_object_initial_states() @classmethod def build_goal_generation(cls, constants, mujoco_simulation): if constants.randomize_target: return super().build_goal_generation(constants, mujoco_simulation) else: return HoldoutObjectStateGoal(mujoco_simulation, args=constants.goal_args) make_env = HoldoutRearrangeEnv.build
3,871
32.094017
86
py
robogym
robogym-master/robogym/envs/rearrange/mixture.py
from typing import Any, Dict, List import attr from robogym.envs.rearrange.common.mesh import ( MeshRearrangeEnv, MeshRearrangeEnvConstants, MeshRearrangeEnvParameters, ) from robogym.envs.rearrange.datasets.envstates.utils import get_envstate_datasets from robogym.envs.rearrange.datasets.objects.utils import get_object_datasets from robogym.envs.rearrange.simulation.base import ObjectGroupConfig from robogym.envs.rearrange.simulation.mesh import MeshRearrangeSim @attr.s(auto_attribs=True) class MixtureRearrangeEnvConstants(MeshRearrangeEnvConstants): # Set of object datasets used for constructing environment states. # {object dataset name: object dataset config} object_config: Dict[str, Dict[str, Any]] = { "ycb": { "function": "robogym.envs.rearrange.datasets.objects.local_mesh:create", "args": {"mesh_dirname": "ycb"}, }, "geom": { "function": "robogym.envs.rearrange.datasets.objects.local_mesh:create", "args": {"mesh_dirname": "geom"}, }, } # Sef of environment state datasets that are used to sample environment states. The # environment state datasets use object datasets defined by object_config. # {envstate dataset name: dataset config} dataset_config: Dict[str, Dict[str, Any]] = { "ycb_dataset": { "function": "robogym.envs.rearrange.datasets.envstates.random:create", "args": {"object_sample_prob": {"ycb": 1.0}}, }, "geom_dataset": { "function": "robogym.envs.rearrange.datasets.envstates.random:create", "args": {"object_sample_prob": {"geom": 1.0}}, }, "mixed_dataset": { "function": "robogym.envs.rearrange.datasets.envstates.random:create", "args": {"object_sample_prob": {"ycb": 0.5, "geom": 0.5}}, }, } # environment state dataset level sampling probability. # {envstate dataset name: probability of sampling from this dataset} dataset_sampling_config: dict = { "ycb_dataset": 0.3, "geom_dataset": 0.3, "mixed_dataset": 0.4, } class MixtureRearrangeEnv( MeshRearrangeEnv[ MeshRearrangeEnvParameters, MixtureRearrangeEnvConstants, MeshRearrangeSim ] ): """ Rearrange environment using mixture of dataset to define an initial state distribution. """ def initialize(self): super().initialize() self.object_datasets = get_object_datasets( self.constants.object_config, self._random_state ) self.datasets = get_envstate_datasets( self.constants.dataset_config, self.object_datasets, self._random_state ) # Name of environment state datasets self.dataset_ids = sorted(list(self.constants.dataset_sampling_config)) # Probability for sampling from each environment state datasets self.dataset_prob = [ self.constants.dataset_sampling_config[dataset_id] for dataset_id in self.dataset_ids ] # Dataset that will be used for sampling an environment state self.cur_dataset = self._sample_dataset() def _sample_dataset(self): """ Sample an environment state dataset """ dataset_id = self.dataset_ids[ self._random_state.choice(len(self.dataset_ids), p=self.dataset_prob) ] return self.datasets[dataset_id] def _reset(self): """ Reset environment state This function resets envstate dataset and then use the dataset state for resetting the environment. environment state dataset may randomize on the fly or load previously saved environment states from storage. """ self.cur_dataset = self._sample_dataset() self.cur_dataset.reset(self) super()._reset() ####################################################################################### # Override envstate randomization function in environment to make the dataset fully # determine the environment states def _sample_attributed_object_groups( self, dedupe_objects: bool = False ) -> List[ObjectGroupConfig]: """ This function includes sampling mesh, scales, and colors """ assert not dedupe_objects, "Mixture dataset always supports duplicated objects" return self.cur_dataset.envstate.object_groups def _sample_object_meshes(self, num_groups: int) -> List[List[str]]: # This function is not necessary because we will directly return object groups pass def _generate_object_placements(self): self.cur_dataset.check_initialized() return self.cur_dataset.envstate.init_pos, self.cur_dataset.envstate.is_valid def _sample_object_initial_rotations(self): self.cur_dataset.check_initialized() return self.cur_dataset.envstate.init_quats make_env = MixtureRearrangeEnv.build
4,957
36.560606
96
py
robogym
robogym-master/robogym/envs/rearrange/blocks_reach.py
import attr import numpy as np from robogym.envs.rearrange.blocks import BlockRearrangeEnvParameters, BlockRearrangeSim from robogym.envs.rearrange.common.base import RearrangeEnv, RearrangeEnvConstants from robogym.envs.rearrange.goals.object_reach_goal import ( DeterministicReachGoal, ObjectReachGoal, ) @attr.s(auto_attribs=True) class BlocksReachEnvConstants(RearrangeEnvConstants): # Goal generation for env. # det-state: Use deterministic goals # state: Use random state goals goal_generation: str = attr.ib( default="state", validator=attr.validators.in_(["state", "det-state"]) ) class BlocksReachEnv( RearrangeEnv[ BlockRearrangeEnvParameters, BlocksReachEnvConstants, BlockRearrangeSim, ] ): @classmethod def build_goal_generation(cls, constants, mujoco_simulation): if constants.goal_generation == "det-state": return DeterministicReachGoal(mujoco_simulation, args=constants.goal_args) else: return ObjectReachGoal(mujoco_simulation, args=constants.goal_args) def _calculate_goal_distance_reward(self, previous_goal_distance, goal_distance): return np.sum(previous_goal_distance["obj_pos"] - goal_distance["obj_pos"]) make_env = BlocksReachEnv.build
1,282
31.897436
88
py
robogym
robogym-master/robogym/envs/rearrange/blocks_stack.py
import logging import attr from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.goals.object_stack_goal import ObjectStackGoal from robogym.envs.rearrange.simulation.base import RearrangeSimParameters from robogym.envs.rearrange.simulation.blocks import ( BlockRearrangeSim, BlockRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr logger = logging.getLogger(__name__) @attr.s(auto_attribs=True) class BlockStackEnvConstants(RearrangeEnvConstants): # whether block stacked in the fixed order or random order. fixed_order: bool = False @attr.s(auto_attribs=True) class BlockStackEnvParameters(RearrangeEnvParameters): simulation_params: RearrangeSimParameters = build_nested_attr( BlockRearrangeSimParameters, default=dict(num_objects=2) ) class BlockStackEnv( RearrangeEnv[BlockStackEnvParameters, BlockStackEnvConstants, BlockRearrangeSim] ): @classmethod def build_goal_generation(cls, constants, mujoco_simulation): return ObjectStackGoal( mujoco_simulation, constants.goal_args, constants.fixed_order ) make_env = BlockStackEnv.build
1,242
26.622222
84
py