def __init__(self, agent_name, model, weights=None, t_horizon=10, num_basis=5, capacity=100000, batch_size=20): self._agent_name = agent_name self._model = model self._t_horizon = t_horizon self._replay_buffer = ReplayBuffer(capacity) self._batch_size = batch_size self._basis = Basis(self._model.explr_space, num_basis=num_basis) self._lamk = np.exp(-0.8*np.linalg.norm(self._basis.k, axis=1)) self._barr = Barrier(self._model.explr_space) self._targ_dist = TargetDist(basis=self._basis) self._u = [0.0*np.zeros(self._model.action_space.shape[0]) for _ in range(t_horizon)] # TODO: implement more weights if weights is None: weights = {'R' : np.eye(self._model.action_space.shape[0])} self._Rinv = np.linalg.inv(weights['R']) self._phik = None self._ck_mean = None self._ck_msg = Ck() self._ck_msg.name = self._agent_name self._ck_dict = {} self.pred_path = [] # set up the eos stuff last rospy.Subscriber('ck_link', Ck, self._ck_link_callback) self._ck_pub = rospy.Publisher('ck_link', Ck, queue_size=1)
def QSdaily(download=False,plotting=False,store=False): logging.basicConfig(filename=LOG_PATH,level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.info('rubyqs periodic task started.') if download: logging.debug('Download started.') RT = RescueTime(store=True) r = RT.get_rescuetime_log() Basis BC = Basis(store=True,store_raw=True) b = BC.get_all() # Plotting if plotting: logging.debug('Plotting in main task started.') #rollingtable_plotly() dayssince_plotly() activitydaily_plotly() prodhours_plotly() heatmap_plotly() sleepdetailed_plotly() sleeptimes_plotly() if 'r' not in locals(): r = None if 'b' not in locals(): b = None return (r,b)
def __init__(self, model, target_dist, weights=None, horizon=100, num_basis=5, capacity=100000, batch_size=20): self.model = model self.target_dist = target_dist self.horizon = horizon self.replay_buffer = ReplayBuffer(capacity) self.batch_size = batch_size self.basis = Basis(self.model.explr_space, num_basis=num_basis) # self.lamk = 1.0/(np.linalg.norm(self.basis.k, axis=1) + 1)**(3.0/2.0) self.lamk = np.exp(-0.8 * np.linalg.norm(self.basis.k, axis=1)) self.barr = Barrier(self.model.explr_space) # initialize the control sequence # self.u_seq = [np.zeros(self.model.action_space.shape) # for _ in range(horizon)] self.u_seq = [ 0.0 * self.model.action_space.sample() for _ in range(horizon) ] if weights is None: weights = {'R': np.eye(self.model.action_space.shape[0])} self.Rinv = np.linalg.inv(weights['R']) self._phik = None self.ck = None
def __init__(self,mol,bas_file,do_print=0): print 'Hf module started' self.mol = mol bas = Basis() atom_functions = bas.read_basis(bas_file) self.atom_functions = atom_functions self.do_print=do_print
def reset_basis(self): centroid = numpy.array((0, 0, 0)) for atom in self.atoms: centroid += atom.get_coord() centroid /= len(self.atoms) self.set_basis(Basis().translate(centroid)) self.recalculate_positions()
def basis(self) -> Matrix: """Returns a basis for the subspace""" result = copy(self.generators) for i, v in enumerate(result): if is_consistent(Matrix(cols=result[:i] + result[i + 1:]), v): result.pop(i) return Basis(result)
def vandermonde(eta, p): """ Internal function to variable_projection Calculates the Vandermonde matrix using polynomial basis functions :param eta: ndarray, the affine transformed projected values of inputs in active subspace :param p: int, the maximum degree of polynomials :return: * **V (numpy array)**: The resulting Vandermode matrix * **Polybasis (Poly object)**: An instance of Poly object containing the polynomial basis derived """ _, n = eta.shape listing = [] for i in range(0, n): listing.append(p) Object = Basis('Total order', listing) #Establish n Parameter objects params = [] P = Parameter(order=p, lower=-1, upper=1, param_type='Uniform') for i in range(0, n): params.append(P) #Use the params list to establish the Poly object Polybasis = Poly(params, Object) V = Polybasis.getPolynomial(eta) V = V.T return V, Polybasis
def __init__(self, D=None, R=None): if D is None: raise(ValueError, 'Distributions must be given') else: self.D = D if R is None: raise(ValueError, 'Correlation matrix must be specified') else: self.R = R self.std = Parameter(order=5, distribution='normal',shape_parameter_A = 0.0, shape_parameter_B = 1.0) # # R0 = fictive matrix of correlated normal intermediate variables # # 1) Check the type of correlated marginals # 2) Use Effective Quadrature for solving Legendre # 3) Calculate the fictive matrix inf_lim = -8.0 sup_lim = - inf_lim p1 = Parameter(distribution = 'uniform', lower = inf_lim, upper = sup_lim, order = 31) myBasis = Basis('Tensor grid') Pols = Polyint([p1, p1], myBasis) p = Pols.quadraturePoints w = Pols.quadratureWeights * (sup_lim - inf_lim)**2 p1 = p[:,0] p2 = p[:,1] R0 = np.eye((len(self.D))) for i in range(len(self.D)): for j in range(i+1, len(self.D), 1): if self.R[i,j] == 0: R0[i,j] = 0.0 else: tp11 = -(np.array(self.D[i].getiCDF(self.std.getCDF(points=p1))) - self.D[i].mean ) / np.sqrt( self.D[i].variance ) tp22 = -(np.array(self.D[j].getiCDF(self.std.getCDF(points=p2))) - self.D[j].mean)/np.sqrt( self.D[j].variance ) rho_ij = self.R[i,j] bivariateNormalPDF = (1.0 / (2.0 * np.pi * np.sqrt(1.0-rho_ij**2)) * np.exp(-1.0/(2.0*(1.0 - rho_ij**2)) * (p1**2 - 2.0 * rho_ij * p1 * p2 + p2**2 ))) coefficientsIntegral = np.flipud(tp11*tp22 * w) def check_difference(rho_ij): bivariateNormalPDF = (1.0 / (2.0 * np.pi * np.sqrt(1.0-rho_ij**2)) * np.exp(-1.0/(2.0*(1.0 - rho_ij**2)) * (p1**2 - 2.0 * rho_ij * p1 * p2 + p2**2 ))) diff = np.dot(coefficientsIntegral, bivariateNormalPDF) return diff - self.R[i,j] rho = optimize.newton(check_difference, self.R[i,j]) R0[i,j] = rho R0[j,i] = R0[i,j] self.A = np.linalg.cholesky(R0) print 'The Cholesky decomposition of fictive matrix R0 is:' print self.A print 'The fictive matrix is:' print R0
def __init__(self): # basic config self.pose = np.array([0.1, 0.1, 0.]) self.obsv = [] # ts = message_filters.ApproximateTimeSynchronizer([self.odom_sub, self.scan_sub], 10, 0.01) # ts.registerCallback(self.callback) self.bearings = np.linspace(0, 2 * pi, 360) self.start_time = time.time() # ergodic control config self.size = 4.0 self.explr_space = Box(np.array([0.0, 0.0]), np.array([self.size, self.size]), dtype=np.float64) self.basis = Basis(explr_space=self.explr_space, num_basis=10) # self.t_dist = TargetDist() self.t_dist = TargetDist(means=[[1.0, 1.0], [3.0, 3.0]], cov=0.1, size=self.size) self.phik = convert_phi2phik(self.basis, self.t_dist.grid_vals, self.t_dist.grid, self.size) self.weights = {'R': np.diag([10, 1])} self.model = TurtlebotDyn(size=self.size, dt=0.1) self.erg_ctrl = RTErgodicControl(self.model, self.t_dist, weights=self.weights, horizon=80, num_basis=10, batch_size=500) self.obstacles = np.array([[1., 2.], [2., 1.], [2., 2.], [3., 1.], [1., 3.], [2., 3.], [3., 2.]]) self.erg_ctrl.barr.update_obstacles(self.obstacles) self.erg_ctrl.phik = self.phik self.log = {'traj': [], 'ctrls': [], 'ctrl_seq': [], 'count': 0} # self.odom_sub = message_filters.Subscriber('/odom', Odometry)#, self.odom_callback) # self.scan_sub = message_filters.Subscriber('/scan', LaserScan)#, self.scan_callback) self.odom_sub = rospy.Subscriber('/odom', Odometry, self.odom_callback) self.scan_sub = rospy.Subscriber('/scan', LaserScan, self.scan_callback) self.ctrl_sub = rospy.Subscriber('/ctrl_flag', Bool, self.ctrl_callback) self.obsv_pub = rospy.Publisher('/landmarks', Marker, queue_size=1) self.ctrl_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
def __init__(self, matrix: Optional[Matrix] = None, **kwargs): """ Parameters: matrix (Optional[Matrix]): A matrix representing the transformation **kwargs: points (Dict[VectorType, VectorType]): A map of pairs of input and output points of the transformation """ if matrix is not None: self.matrix = Matrix(matrix) if type( matrix) is not Matrix else matrix elif "points" in kwargs: inputs = [ Vector(v) if type(v) is not Vector else v for v in kwargs["points"].keys() ] outputs = [ Vector(v) if type(v) is not Vector else v for v in kwargs["points"].values() ] self.matrix = Matrix(cols=outputs) @ inverse(Basis(*inputs).matrix)
def __init__(self): # basic config self.pose = np.array([0.1, 0.1, 0.]) self.obsv = [] self.bearings = np.linspace(0, 2*pi, 360) self.start_time = time.time() # ergodic control config self.size = 4.0 self.explr_space = Box(np.array([0.0,0.0]), np.array([self.size,self.size]), dtype=np.float64) self.basis = Basis(explr_space=self.explr_space, num_basis=10) # self.t_dist = TargetDist() self.t_dist = TargetDist(means=[[1.0,1.0],[3.0,3.0]], cov=0.1, size=self.size) self.phik = convert_phi2phik(self.basis, self.t_dist.grid_vals, self.t_dist.grid, self.size) self.weights = {'R': np.diag([10, 1])} self.model = TurtlebotDyn(size=self.size, dt=0.1) self.erg_ctrl = RTErgodicControl(self.model, self.t_dist, weights=self.weights, horizon=80, num_basis=10, batch_size=500) self.obstacles = np.array([[1.,2.], [2.,1.], [2.,2.], [3.,1.], [1.,3.], [2.,3.], [3.,2.]]) self.erg_ctrl.barr.update_obstacles(self.obstacles) self.erg_ctrl.phik = self.phik self.log = {'traj':[], 'ctrls':[], 'ctrl_seq':[], 'count':0} self.odom_sub = rospy.Subscriber('/odom', Odometry, self.odom_callback) self.scan_sub = rospy.Subscriber('/scan', LaserScan, self.scan_callback) self.ctrl_sub = rospy.Subscriber('/ctrl_flag', Bool, self.ctrl_callback) self.obsv_pub = rospy.Publisher('/landmarks', Marker, queue_size=1) self.ctrl_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1) self.path_pub = rospy.Publisher('/test_path', Path, queue_size=1) self.map_pub = rospy.Publisher('/landmarks_map', Marker, queue_size=1) self.path_msg = Path() self.odom_header = None ####### # for test only self.old_obsv = [] self.curr_obsv = [] self.lm_table = []
def getPseudospectralCoefficients(self, function, override_orders=None): if override_orders is None: pts, wts = super(Polyint, self).getTensorQuadratureRule() tensor_elements = self.basis.elements P = super(Polyint, self).getPolynomial(pts) else: pts, wts = super(Polyint, self).getTensorQuadratureRule(override_orders) tensor_basis = Basis('Tensor grid', override_orders) tensor_elements = tensor_basis.elements P = super(Polyint, self).getPolynomial(pts, tensor_elements) m = len(wts) W = np.mat(np.diag(np.sqrt(wts))) A = np.mat(W * P.T) if callable(function): y = evalfunction(points=pts, function=function) else: y = function b = np.dot(W, np.reshape(y, (m, 1))) coefficients = np.dot(A.T, b) return coefficients, tensor_elements, pts, wts
def __init__(self): # basic config self.pose = np.array([0.1, 0.1, 0.]) self.obsv = [] self.bearings = np.linspace(0, 2 * pi, 360) self.start_time = time.time() # ergodic control config self.size = 4.0 self.explr_space = Box(np.array([0.0, 0.0]), np.array([self.size, self.size]), dtype=np.float64) self.basis = Basis(explr_space=self.explr_space, num_basis=10) # self.t_dist = TargetDist() self.t_dist = TargetDist(means=[[1.0, 1.0], [3.0, 3.0]], cov=0.1, size=self.size) self.weights = {'R': np.diag([10, 1])} self.model = TurtlebotDyn(size=self.size, dt=0.1) self.erg_ctrl = RTErgodicControl(self.model, self.t_dist, weights=self.weights, horizon=80, num_basis=10, batch_size=500) self.obstacles = np.array([[1., 2.], [2., 1.], [2., 2.], [3., 1.], [1., 3.], [2., 3.], [3., 2.]]) self.erg_ctrl.barr.update_obstacles(self.obstacles) self.phik = convert_phi2phik(self.basis, self.t_dist.grid_vals, self.t_dist.grid, self.size) self.erg_ctrl.phik = self.phik self.log = {'traj': [], 'ctrls': [], 'ctrl_seq': [], 'count': 0} self.odom_sub = rospy.Subscriber('/odom', Odometry, self.odom_callback) self.scan_sub = rospy.Subscriber('/scan', LaserScan, self.scan_callback) self.ctrl_sub = rospy.Subscriber('/ctrl_flag', Bool, self.ctrl_callback) self.obsv_pub = rospy.Publisher('/landmarks', Marker, queue_size=1) self.ctrl_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1) self.path_pub = rospy.Publisher('/test_path', Path, queue_size=1) self.map_pub = rospy.Publisher('/landmarks_map', Marker, queue_size=1) self.ekf_pub = rospy.Publisher('/ekf_odom', Odometry, queue_size=1) self.path_msg = Path() self.odom_header = None ####### # for test only self.old_obsv = [] self.curr_obsv = [] self.lm_table = [] cube_list = Marker() cube_list.header.frame_id = 'odom' cube_list.header.stamp = rospy.Time.now() cube_list.ns = 'landmark_map' cube_list.action = Marker.ADD cube_list.pose.orientation.w = 1.0 cube_list.id = 0 cube_list.type = Marker.CUBE_LIST cube_list.scale.x = 0.05 cube_list.scale.y = 0.05 cube_list.scale.z = 0.5 cube_list.color.b = 1.0 cube_list.color.a = 1.0 self.cube_list = cube_list self.real_landmarks = np.array([ [2.34, 2.13], # id: 0 [0.60, 0.60], # id: 1 [0.60, 3.40], # id: 2 [3.40, 0.60], # id: 3 [3.40, 3.40] ]) # id: 4 self.init_pose = np.zeros(3) self.raw_odom_traj = [] self.lm_id = [] ####### # ekf self.ekf_mean = np.array([0.0, 0.0, 0.0]) self.ekf_cov = np.diag([1e-09 for _ in range(3)]) self.ekf_R = np.diag([0.01, 0.01, 0.01]) self.ekf_Q = np.diag([0.03, 0.03]) self.init_flag = False
def main(): # make environment t1 = time.time() pot_region = (2 / np.sqrt(3), 2 / np.sqrt(3), 2 / np.sqrt(3)) radius = np.sqrt(pot_region[0]**2 + pot_region[1]**2 + pot_region[2]**2) region = (radius, radius, radius) nr = 201 gridpx = 200 gridpy = 200 gridpz = 200 x, y, z = grid(gridpx, gridpy, gridpz, region) xx, yy, zz = np.meshgrid(x, y, z) #make mesh #linear mesh #r =np.linspace(0.0001,region,nr) #log mesh #a = np.log(2) / (nr - 1) a = 0.03 b = radius / (np.e**(a * (nr - 1)) - 1) rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)]) # make potential V = makepotential(xx, yy, zz, pot_region, pottype="cubic", potbottom=-1, potshow_f=False) # surface integral V_radial = surfaceintegral(x, y, z, rofi, V, method="lebedev_py", potshow_f=False) vofi = np.array(V_radial) # select method of surface integral """ #test 20191029 V_test = np.zeros(nr,dtype=np.float64) for i in range(nr): ri = rofi[i] if ri < pot_region[0]: V_test[i] = -1 elif ri >= pot_region[0] and ri < pot_region[0] * np.sqrt(2) : V_test[i] = -1 * ( 1 - 12 * np.pi * ri * ( ri - 0.5 * radius )/(4 * np.pi * ri**2)) elif ri >= pot_region[0] * np.sqrt(2) and ri <=radius: V_test[i] = -1 * ( ri - 0.5 * np.sqrt(3) * radius ) * ( 2 - 3 * np.sqrt(2) * ( np.sqrt(2) - 1 ) ) / ( ri**2 * (np.sqrt(2) - np.sqrt(3))**2) #plt.plot(rofi,V_test,marker=".") #plt.show() V_radial = V_test vofi = V_test """ # make basis node_open = 1 node_close = 2 node = node_open + node_close LMAX = 3 nstates = node * LMAX**2 all_basis = [] for lvalsh in range(LMAX): l_basis = [] # for open channel val = 1. slo = 0. for no in range(node_open): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, no, nr, rofi, slo, vofi, val) l_basis.append(basis) # for close channel val = 0. slo = -1. for nc in range(node_close): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, nc, nr, rofi, slo, vofi, val) l_basis.append(basis) all_basis.append(l_basis) with open("wavefunc_2.dat", mode="w") as fw_w: fw_w.write("#r, l, node, open or close = ") for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write(str(nyu_basis.l)) fw_w.write(str(nyu_basis.node)) if nyu_basis.open: fw_w.write("open") else: fw_w.write("close") fw_w.write(" ") fw_w.write("\n") for i in range(nr): fw_w.write("{:>13.8f}".format(rofi[i])) for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write("{:>13.8f}".format(nyu_basis.g[i])) fw_w.write("\n") Smat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) hsmat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) lmat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) qmat = np.zeros((LMAX, LMAX, node, node), dtype=np.float64) """ for l1 in range (LMAX): for n1 in range (node_open + node_close): print("l1 = ",l1,"n1 = ",n1,all_basis[l1][n1].val,all_basis[l1][n1].g[nr-1]) sys.exit() """ for l1 in range(LMAX): for l2 in range(LMAX): if l1 != l2: continue for n1 in range(node): for n2 in range(node): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() Smat[l1][l2][n1][n2] = integrate( all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr], rofi, nr) hsmat[l1][l2][n1][ n2] = Smat[l1][l2][n1][n2] * all_basis[l2][n2].e lmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nSmat") print(Smat) print("\nhsmat") print(hsmat) print("\nlmat") print(lmat) print("\nqmat") print(qmat) hs_L = np.zeros((LMAX, LMAX, node, node)) """ for l1 in range(LMAX): for n1 in range(node): for l2 in range(LMAX): for n2 in range(node): print("{:>8.4f}".format(lmat[l1][l2][n1][n2]),end="") print("") print("") """ print("hs_L") for l1 in range(LMAX): for n1 in range(node): for l2 in range(LMAX): for n2 in range(node): hs_L[l1][l2][n1][ n2] = hsmat[l1][l2][n1][n2] + lmat[l1][l2][n1][n2] print("{:>8.4f}".format(hs_L[l1][l2][n1][n2]), end="") print("") #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial) V_ang = np.where( np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1], V - my_radial_interfunc(np.sqrt(xx**2 + yy**2 + zz**2)), 0.) """ for i in range(gridpx): for j in range(gridpy): for k in range(gridpz): print(V_ang[i][j][k],end=" ") print("") print("\n") sys.exit() """ #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! """ with open ("V_ang.dat",mode = "w") as fw_a: for i in range(len(V_ang)): fw_a.write("{:>13.8f}".format(xx[50][i][50])) fw_a.write("{:>13.8f}\n".format(V_ang[i][50][50])) """ #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() umat_av = np.zeros((node, node, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) gridstart = 50 gridend = 60 gridrange = gridend - gridstart + 1 for ngrid in range(gridstart, gridend + 1): t1 = time.time() fw_u = open("umat_grid" + str(ngrid) + ".dat", mode="w") umat = np.zeros((node, node, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) igridpx = ngrid igridpy = ngrid igridpz = ngrid ix, iy, iz = grid(igridpx, igridpy, igridpz, region) ixx, iyy, izz = np.meshgrid(ix, iy, iz) V_ang_i = my_V_ang_inter_func((ixx, iyy, izz)) #mlab.contour3d(V_ang_i,color = (1,1,1),opacity = 0.1) #obj = mlab.volume_slice(V_ang_i) #mlab.show() dis = np.sqrt(ixx**2 + iyy**2 + izz**2) dis2 = ixx**2 + iyy**2 + izz**2 theta = np.where(dis != 0., np.arccos(izz / dis), 0.) phi = np.where( iyy**2 + ixx**2 != 0, np.where(iyy >= 0, np.arccos(ixx / np.sqrt(ixx**2 + iyy**2)), np.pi + np.arccos(ixx / np.sqrt(ixx**2 + iyy**2))), 0.) #phi = np.where( iyy != 0. , phi, 0.) #phi = np.where(iyy > 0, phi,-phi) # region_t = np.where(dis < rofi[-1],1,0) sph_harm_mat = np.zeros( (LMAX, 2 * LMAX + 1, igridpx, igridpy, igridpz), dtype=np.complex64) for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): sph_harm_mat[l1][m1] = np.where(dis != 0., sph_harm(m1, l1, phi, theta), 0.) g_ln_mat = np.zeros((node, LMAX, igridpx, igridpy, igridpz), dtype=np.float64) for n1 in range(node): for l1 in range(LMAX): my_radial_g_inter_func = interpolate.interp1d( rofi, all_basis[l1][n1].g[:nr]) g_ln_mat[n1][l1] = my_radial_g_inter_func( np.sqrt(ixx**2 + iyy**2 + izz**2)) for n1 in range(node): for n2 in range(node): for l1 in range(LMAX): for l2 in range(LMAX): if all_basis[l1][n1].l != l1 or all_basis[l2][ n2].l != l2: print("error: L is differnt") sys.exit() # to avoid nan in region where it can not interpolate ie: dis > rofi g_V_g = np.where( dis < rofi[-1], g_ln_mat[n1][l1] * V_ang_i * g_ln_mat[n2][l2], 0.) for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): #print("n1 = {} n2 = {} l1 = {} l2 = {} m1 = {} m2 = {}".format(n1,n2,l1,l2,m1,m2)) umat[n1][n2][l1][l2][m1][m2] = np.sum( np.where( dis2 != 0., sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2, 0.)) * (2 * region[0] * 2 * region[1] * 2 * region[2]) / (igridpx * igridpy * igridpz) #print(umat[n1][n2][l1][l2][m1][m2]) count = 0 for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node): for n2 in range(node): fw_u.write(str(count)) fw_u.write("{:>15.8f}{:>15.8f}\n".format( umat[n1][n2][l1][l2][m1][m2].real, umat[n1][n2][l1][l2][m1][m2].imag)) count += 1 umat_av += umat fw_u.close() t2 = time.time() print("grid = ", ngrid, "time = ", t2 - t1) umat_av /= gridrange count = 0 fw_u_av = open("umat_grid_av" + str(gridstart) + "_" + str(gridend) + ".dat", mode="w") for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node): for n2 in range(node): fw_u_av.write(str(count)) fw_u_av.write("{:>15.8f}{:>15.8f}\n".format( umat_av[n1][n2][l1][l2][m1][m2].real, umat_av[n1][n2][l1][l2][m1][m2].imag)) count += 1 fw_u_av.close() ham_mat = np.zeros((nstates * nstates), dtype=np.float64) qmetric_mat = np.zeros((nstates * nstates), dtype=np.float64) for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): for n1 in range(node): for l2 in range(LMAX): for m2 in range(-l2, l2 + 1): for n2 in range(node): if l1 == l2 and m1 == m2: ham_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] += hs_L[l1][l2][n1][n2] qmetric_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] = qmat[l1][l2][n1][n2] ham_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] += umat_av[n1][n2][l1][l2][m1][m2].real lambda_mat = np.zeros(nstates * nstates, dtype=np.float64) alphalong = np.zeros(nstates) betalong = np.zeros(nstates) revec = np.zeros(nstates * nstates) for e_num in range(1, 2): E = e_num * 10 lambda_mat = np.zeros(nstates * nstates, dtype=np.float64) lambda_mat -= ham_mat """ for i in range(nstates): lambda_mat[i + i * nstates] += E """ count = 0 fw_lam = open("lambda.dat", mode="w") for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): for n1 in range(node): for l2 in range(LMAX): for m2 in range(-l2, l2 + 1): for n2 in range(node): if l1 == l2 and m1 == m2: lambda_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2] += Smat[l1][l2][n1][n2] * E fw_lam.write(str(count)) fw_lam.write("{:>15.8f}\n".format( lambda_mat[l1**2 * node * LMAX**2 * node + (l1 + m1) * node * LMAX**2 * node + n1 * LMAX**2 * node + l2**2 * node + (l2 + m2) * node + n2])) count += 1 info = solve_genev(nstates, lambda_mat, qmetric_mat, alphalong, betalong, revec) print("info = ", info) print("alphalong") print(alphalong) print("betalong") print(betalong) #print(revec) k = 0 jk = np.zeros(nstates, dtype=np.int32) for i in range(nstates): if betalong[i] != 0.: jk[k] = i k += 1 fw_revec = open("revec.dat", mode="w") print("revec") for j in range(nstates): fw_revec.write("{:>4}".format(j)) for i in range(LMAX**2): fw_revec.write("{:>13.8f}".format(revec[j + jk[i] * nstates])) print("{:>11.6f}".format(revec[j + jk[i] * nstates]), end="") print("") fw_revec.write("\n") print("")
#python implementation of the Hartree-Fock method import numpy as np import math from basis import Basis from integrals import Integrals from scf import SCF Basis = Basis() Integrals = Integrals() SCF = SCF() ################################## #init main variables #contains information user provided information about the system system = { #nuclear coordinates "R":[[0.0,0.0,-1.0], [0.0,0.0,1.0]], #atomic number "Z":[1,1], #number of electron "N":[2.0] } #basis set basis = Basis.buildBasis(system["Z"], system["R"]) print(basis)
import sys sys.path.append('../rt_erg_lib') ########################################### # basic function test import numpy as np import numpy.random as npr from basis import Basis from gym.spaces import Box # define the exploration space as gym.Box explr_space = Box(np.array([0.0, 0.0]), np.array([1.0, 1.0]), dtype=np.float32) # define the basis object basis = Basis(explr_space=explr_space, num_basis=5) # simulate/randomize a trajectory xt = [explr_space.sample() for _ in range(10)] # print indices for all basis functions print('indices for all basis functions: ') print(basis.k) # amount is square of num_basis # test basis function, the input is a pose print(basis.fk(xt[0])) # test derivative of basis function wrt a pose print(basis.dfk(xt[0])) # hk, even computed in the source code, is not # used in the end, so we temporarily ignore it ########################################### # compute trajectory to ck using basis function from utils import convert_traj2ck
def main(): # make environment pot_region = (2 / np.sqrt(3), 2 / np.sqrt(3), 2 / np.sqrt(3)) radius = np.sqrt(pot_region[0]**2 + pot_region[1]**2 + pot_region[2]**2) region = (radius, radius, radius) nr = 201 gridpx = 200 gridpy = 200 gridpz = 200 x, y, z = grid(gridpx, gridpy, gridpz, region) xx, yy, zz = np.meshgrid(x, y, z) #make mesh #linear mesh #r =np.linspace(0.0001,region,nr) #log mesh a = np.log(2) / (nr - 1) b = radius / (np.e**(a * (nr - 1)) - 1) rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)]) # make potential V = makepotential(xx, yy, zz, pot_region, pottype="cubic", potbottom=-1, potshow_f=False) # surface integral V_radial = surfaceintegral(x, y, z, rofi, V, method="lebedev_py", potshow_f=False) vofi = np.array(V_radial) # select method of surface integral # make basis node_open = 1 node_close = 2 LMAX = 4 all_basis = [] for lvalsh in range(LMAX): l_basis = [] # for open channel val = 1. slo = 0. for node in range(node_open): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) # for close channel val = 0. slo = -1. for node in range(node_close): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) all_basis.append(l_basis) with open("wavefunc.dat", mode="w") as fw_w: fw_w.write("#r, l, node, open or close = ") for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write(str(nyu_basis.l)) fw_w.write(str(nyu_basis.node)) if nyu_basis.open: fw_w.write("open") else: fw_w.write("close") fw_w.write(" ") fw_w.write("\n") for i in range(nr): fw_w.write("{:>13.8f}".format(rofi[i])) for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write("{:>13.8f}".format(nyu_basis.g[i])) fw_w.write("\n") hsmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) lmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) qmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) for l1 in range(LMAX): for l2 in range(LMAX): if l1 != l2: continue for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() hsmat[l1][l2][n1][n2] = integrate( all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr], rofi, nr) * all_basis[l1][n1].e lmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nhsmat") print(hsmat) print("\nlmat") print(lmat) print("\nqmat") print(qmat) #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial) V_ang = np.where( np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1], V - my_radial_interfunc(np.sqrt(xx * xx + yy * yy + zz * zz)), 0.) """ for i in range(gridpx): for j in range(gridpy): for k in range(gridpz): print(V_ang[i][j][k],end=" ") print("") print("\n") sys.exit() """ #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! """ with open ("V_ang.dat",mode = "w") as fw_a: for i in range(len(V_ang)): fw_a.write("{:>13.8f}".format(xx[50][i][50])) fw_a.write("{:>13.8f}\n".format(V_ang[i][50][50])) """ #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() fw_grid = open("umat_grid_all.dat", mode="w") for ngrid in range(20, 100): fw_grid_2 = open("umat_grid" + str(ngrid) + ".dat", mode="w") fw_grid.write(str(ngrid) + " ") t1 = time.time() umat = np.zeros((node_open + node_close, node_open + node_close, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) # umat_t = np.zeros((LMAX,LMAX,2 * LMAX + 1,2 * LMAX + 1,node_open + node_close,node_open + node_close), dtype = np.complex64) my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) igridpx = ngrid igridpy = ngrid igridpz = ngrid ix, iy, iz = grid(igridpx, igridpy, igridpz, region) ixx, iyy, izz = np.meshgrid(ix, iy, iz) V_ang_i = my_V_ang_inter_func((ixx, iyy, izz)) #mlab.points3d(V_ang_i,scale_factor=0.4) # mlab.contour3d(V_ang_i,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang_i) #mlab.show() dis = np.sqrt(ixx**2 + iyy**2 + izz**2) dis2 = ixx**2 + iyy**2 + izz**2 theta = np.where(dis != 0., np.arccos(izz / dis), 0.) phi = np.where( iyy**2 + ixx**2 != 0, np.where(iyy >= 0, np.arccos(ixx / np.sqrt(ixx**2 + iyy**2)), np.pi + np.arccos(ixx / np.sqrt(ixx**2 + iyy**2))), 0.) # region_t = np.where(dis < rofi[-1],1,0) sph_harm_mat = np.zeros( (LMAX, 2 * LMAX + 1, igridpx, igridpy, igridpz), dtype=np.complex64) for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): sph_harm_mat[l1][m1] = np.where(dis != 0., sph_harm(m1, l1, phi, theta), 0.) g_ln_mat = np.zeros( (node_open + node_close, LMAX, igridpx, igridpy, igridpz), dtype=np.float64) for n1 in range(node_open + node_close): for l1 in range(LMAX): my_radial_g_inter_func = interpolate.interp1d( rofi, all_basis[l1][n1].g[:nr]) g_ln_mat[n1][l1] = my_radial_g_inter_func( np.sqrt(ixx**2 + iyy**2 + izz**2)) for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): for l1 in range(LMAX): for l2 in range(LMAX): if all_basis[l1][n1].l != l1 or all_basis[l2][ n2].l != l2: print("error: L is differnt") sys.exit() # to avoid nan in region where it can not interpolate ie: dis > rofi g_V_g = np.where( dis < rofi[-1], g_ln_mat[n1][l1] * V_ang_i * g_ln_mat[n2][l2], 0.) for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): #print("n1 = {} n2 = {} l1 = {} l2 = {} m1 = {} m2 = {}".format(n1,n2,l1,l2,m1,m2)) umat[n1][n2][l1][l2][m1][m2] = np.sum( np.where( dis2 != 0., sph_harm_mat[l1][m1].conjugate() * g_V_g * sph_harm_mat[l2][m2] / dis2, 0.)) * (2 * region[0] * 2 * region[1] * 2 * region[2]) / (igridpx * igridpy * igridpz) fw_grid.write("{:>13.8f}".format( umat[n1][n2][l1][l2][m1][m2].real)) count = 0 for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): fw_grid_2.write(str(count)) fw_grid_2.write("{:>15.8f}{:>15.8f}\n".format( umat[n1][n2][l1][l2][m1][m2].real, umat[n1][n2][l1][l2][m1][m2].imag)) count += 1 t2 = time.time() fw_grid.write("\n") print("grid = ", ngrid, "time = ", t2 - t1) fw_grid.close()
g1 = AtomicOrbital(center=-0.3, alpha=5, pre_exponent=1) g1.normalize_square() g1.plot_function(-2, 2) print('integration g1^2 {:10.5f} {:10.5f}'.format( g1._full_integration_num_square(), g1.full_integration_square())) g2 = AtomicOrbital(center=0.4, alpha=10, pre_exponent=2) g2.normalize_square() g2.plot_function(-2, 2) print('integration g2^2 {:10.5f} {:10.5f}'.format( g2._full_integration_num_square(), g2.full_integration_square())) plt.show() # Generate orthogonal basis from basis functions basis = Basis(g1, g2) plt.title('MO basis eigenfunctions') print('Overlap_matrix') print(np.array(basis.get_overlap_matrix())) basis.plot_basis_function(-2, 2, 0, 0.001) basis.plot_basis_function(-2, 2, 1, 0.001) print('basis eigenfunction 1 integral', basis._get_integrate_test(0)) print('basis eigenfunction 2 integral', basis._get_integrate_test(1)) plt.show() # Create a arbitrary MO defined by the orthogonal basis phi = 2 # rad
def main(): # make environment pot_region = (2 / np.sqrt(3), 2 / np.sqrt(3), 2 / np.sqrt(3)) radius = np.sqrt(pot_region[0]**2 + pot_region[1]**2 + pot_region[2]**2) region = (radius, radius, radius) nr = 201 gridpx = 200 gridpy = 200 gridpz = 200 x, y, z = grid(gridpx, gridpy, gridpz, region) xx, yy, zz = np.meshgrid(x, y, z) #make mesh #linear mesh #r =np.linspace(0.0001,region,nr) #log mesh a = np.log(2) / (nr - 1) b = radius / (np.e**(a * (nr - 1)) - 1) rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)]) # make potential V = makepotential(xx, yy, zz, pot_region, pottype="cubic", potbottom=-1, potshow_f=False) # surface integral V_radial = surfaceintegral(x, y, z, rofi, V, method="lebedev_py", potshow_f=False) vofi = np.array(V_radial) # select method of surface integral # make basis node_open = 1 node_close = 2 LMAX = 10 all_basis = [] for lvalsh in range(LMAX): l_basis = [] # for open channel val = 1. slo = 0. for node in range(node_open): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) # for close channel val = 0. slo = -1. for node in range(node_close): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) all_basis.append(l_basis) with open("wavefunc.dat", mode="w") as fw_w: fw_w.write("#r, l, node, open or close = ") for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write(str(nyu_basis.l)) fw_w.write(str(nyu_basis.node)) if nyu_basis.open: fw_w.write("open") else: fw_w.write("close") fw_w.write(" ") fw_w.write("\n") for i in range(nr): fw_w.write("{:>13.8f}".format(rofi[i])) for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write("{:>13.8f}".format(nyu_basis.g[i])) fw_w.write("\n") hsmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) lmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) qmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) for l1 in range(LMAX): for l2 in range(LMAX): if l1 != l2: continue for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() hsmat[l1][l2][n1][n2] = integrate( all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr], rofi, nr) * all_basis[l1][n1].e lmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nhsmat") print(hsmat) print("\nlmat") print(lmat) print("\nqmat") print(qmat) #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial) #V_ang = np.where(np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1] , V - my_radial_interfunc(np.sqrt(xx * xx + yy * yy + zz * zz)),0. ) #my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) my_V_inter_func = RegularGridInterpolator((x, y, z), V) #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() #for V_L fw_umat_vl = open("umat_vl_all.dat", mode="w") for LMAX_k in range(10, 13): fw_umat_vl_2 = open("umat_vl_L" + str(LMAX_k) + ".dat", mode="w") t1 = time.time() umat = np.zeros((node_open + node_close, node_open + node_close, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) #LMAX_k = 3 fw_umat_vl.write(str(LMAX_k)) igridnr = 201 leb_r = np.linspace(0, radius, igridnr) lebedev_num = lebedev_num_list[-8] V_L = np.zeros((LMAX_k, 2 * LMAX_k + 1, igridnr), dtype=np.complex64) leb_x = np.zeros(lebedev_num) leb_y = np.zeros(lebedev_num) leb_z = np.zeros(lebedev_num) leb_w = np.zeros(lebedev_num) lebedev(lebedev_num, leb_x, leb_y, leb_z, leb_w) theta = np.arccos(leb_z) phi = np.where( leb_x**2 + leb_y**2 != 0., np.where(leb_y >= 0, np.arccos(leb_x / np.sqrt(leb_x**2 + leb_y**2)), np.pi + np.arccos(leb_x / np.sqrt(leb_x**2 + leb_y**2))), 0.) for i in range(igridnr): V_leb_r = my_V_inter_func( np.array([leb_x, leb_y, leb_z]).T * leb_r[i]) * leb_w for k in range(LMAX_k): for q in range(-k, k + 1): V_L[k][q][i] = 4 * np.pi * np.sum( V_leb_r * sph_harm(q, k, phi, theta).conjugate()) """ for k in range(LMAX_k): for q in range(-k,k+1): print("k = ",k,"q = ", q) plt.plot(leb_r,V_L[k][q].real,marker=".") plt.show() sys.exit() """ g_ln = np.zeros((node_open + node_close, LMAX, igridnr), dtype=np.float64) for n1 in range(node_open + node_close): for l1 in range(LMAX): my_radial_g_inter_func = interpolate.interp1d( rofi, all_basis[l1][n1].g[:nr]) g_ln[n1][l1] = my_radial_g_inter_func(leb_r) C_kq = np.zeros( (LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1, LMAX_k, 2 * LMAX_k + 1), dtype=np.float64) for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for k in range(1, LMAX_k): for q in range(-k, k + 1): C_kq[l1][l2][m1][m2][k][q] = (-1)**( -m1) * np.sqrt( (2 * l1 + 1) * (2 * l2 + 1)) * Wigner3j( l1, 0, k, 0, l2, 0).doit() * Wigner3j( l1, -m1, k, q, l2, m2).doit() #print(l1,l2,m1,m2,k,q,C_kq[l1][l2][m1][m2][k][q]) count = 0 for l1 in range(LMAX): for l2 in range(LMAX): for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): for k in range(1, LMAX_k): for q in range(-k, k + 1): umat[n1][n2][l1][l2][m1][m2] += simps( g_ln[n1][l1] * V_L[k][q] * g_ln[n2][l2], leb_r) * C_kq[l1][ l2][m1][m2][k][q] * np.sqrt( (2 * k + 1) / (4 * np.pi)) fw_umat_vl.write("{:>15.8f}".format( umat[n1][n2][l1][l2][m1][m2].real)) fw_umat_vl_2.write("{:>15.8f}".format(count)) fw_umat_vl_2.write("{:>15.8f}\n".format( umat[n1][n2][l1][l2][m1][m2].real)) count += 1 t2 = time.time() print("LMAX = ", LMAX_k, " time = ", t2 - t1) fw_umat_vl_2.close() fw_umat_vl.write("\n") fw_umat_vl.close()
class DErgControl(object): def __init__(self, agent_name, model, weights=None, t_horizon=10, num_basis=5, capacity=100000, batch_size=20): self._agent_name = agent_name self._model = model self._t_horizon = t_horizon self._replay_buffer = ReplayBuffer(capacity) self._batch_size = batch_size self._basis = Basis(self._model.explr_space, num_basis=num_basis) self._lamk = np.exp(-0.8*np.linalg.norm(self._basis.k, axis=1)) self._barr = Barrier(self._model.explr_space) self._targ_dist = TargetDist(basis=self._basis) self._u = [0.0*np.zeros(self._model.action_space.shape[0]) for _ in range(t_horizon)] # TODO: implement more weights if weights is None: weights = {'R' : np.eye(self._model.action_space.shape[0])} self._Rinv = np.linalg.inv(weights['R']) self._phik = None self._ck_mean = None self._ck_msg = Ck() self._ck_msg.name = self._agent_name self._ck_dict = {} self.pred_path = [] # set up the eos stuff last rospy.Subscriber('ck_link', Ck, self._ck_link_callback) self._ck_pub = rospy.Publisher('ck_link', Ck, queue_size=1) def _ck_link_callback(self, msg): if msg.name != self._agent_name: if self._ck_dict.has_key(msg.name): self._ck_dict[msg.name] = np.array(msg.ck) else: self._ck_dict.update({msg.name : np.array(msg.ck)}) def reset(self): self._u = [0.0*np.zeros(self._model.action_space.shape[0]) for _ in range(self._t_horizon)] self._replay_buffer.reset() def __call__(self, state): assert self._targ_dist.phik is not None, 'Forgot to set phik' if self._targ_dist.has_update==True: self._replay_buffer.reset() self._targ_dist.has_update = False self._u[:-1] = self._u[1:] self._u[-1] = np.zeros(self._model.action_space.shape[0]) x = self._model.reset(state.copy()) pred_traj = [] dfk = [] fdx = [] fdu = [] dbar = [] for t in range(self._t_horizon): # collect all the information that is needed pred_traj.append( x[self._model.explr_idx] ) dfk.append( self._basis.dfk(x[self._model.explr_idx]) ) dbar.append( self._barr.dx(x[self._model.explr_idx]) ) # step the model forwards x = self._model.step(self._u[t]) fdx.append(self._model.A) fdu.append(self._model.B) self.pred_path = deepcopy(pred_traj) # sample any past experiences if len(self._replay_buffer) > self._batch_size: past_states = self._replay_buffer.sample(self._batch_size) pred_traj = pred_traj + past_states else: past_states = self._replay_buffer.sample(len(self._replay_buffer)) pred_traj = pred_traj + past_states # calculate the cks for the trajectory # *** this is also in the utils file N = len(pred_traj) ck = np.sum([self._basis.fk(xt) for xt in pred_traj], axis=0) / N self._ck_msg.ck = ck.copy() self._ck_pub.publish(self._ck_msg) if len(self._ck_dict.keys()) > 1: self._ck_dict[self._agent_name] = ck cks = [] for key in self._ck_dict.keys(): cks.append(self._ck_dict[key]) ck = np.mean(cks, axis=0) # print('sharing and make sure first ck is 0 ', ck[0]) self._ck_mean = ck fourier_diff = self._lamk * (ck - self._targ_dist.phik) fourier_diff = fourier_diff.reshape(-1,1) # backwards pass rho = np.zeros(self._model.observation_space.shape[0]) for t in reversed(range(self._t_horizon)): edx = np.zeros(self._model.observation_space.shape[0]) edx[self._model.explr_idx] = np.sum(dfk[t] * fourier_diff, 0) bdx = np.zeros(self._model.observation_space.shape[0]) bdx[self._model.explr_idx] = dbar[t] rho = rho - self._model.dt * (-edx-bdx-np.dot(fdx[t].T, rho)) self._u[t] = -np.dot(np.dot(self._Rinv, fdu[t].T), rho) if (np.abs(self._u[t]) > 1.0).any(): self._u[t] /= np.linalg.norm(self._u[t]) self._replay_buffer.push(state[self._model.explr_idx].copy()) return self._u[0].copy()
#hartree fock master control file from basis import basis as Basis Basis = Basis() ############################################### #important functions go here ############################################### def ui(): #gets atom charges and coordinates from user atomicNumbers = [] coord = [] charges = [] option = 0 while (option != 2): print("Choose an option. \n") print("1. Add Atom") print("2. Exit") try: option = int(raw_input()) except: print("Invalid input! \n \n") continue if (option == 1): data = addAtom() atomicNumbers.append(data[0])
g1 = AtomicOrbital(center=-0.4, alpha=5, pre_exponent=1) g1.normalize_square() g1.plot_function(-2, 2) print('integration g1', g1._full_integration_num_square(), g1.full_integration_square()) g2 = AtomicOrbital(center=0.4, alpha=10, pre_exponent=2) g2.normalize_square() g2.plot_function(-2, 2) print('integration g2', g2._full_integration_num_square(), g2.full_integration_square()) plt.show() # Generate orthogonal basis from basis functions basis = Basis(g1, g2) plt.title('Basis functions') print(basis.get_eigenvalues()) print('Overlap_matrix') print(np.array(basis.get_overlap_matrix())) basis.plot_basis_function(-5, 5, 0, 0.001) basis.plot_basis_function(-5, 5, 1, 0.001) print('basis1', basis._get_integrate_test(0)) print('basis2', basis._get_integrate_test(1)) plt.show() # Create MO defined by the orthogonal basis
class RTErgodicControl(object): def __init__(self, model, target_dist, weights=None, horizon=100, num_basis=5, capacity=100000, batch_size=20): self.model = model self.target_dist = target_dist self.horizon = horizon self.replay_buffer = ReplayBuffer(capacity) self.batch_size = batch_size self.basis = Basis(self.model.explr_space, num_basis=num_basis) # self.lamk = 1.0/(np.linalg.norm(self.basis.k, axis=1) + 1)**(3.0/2.0) self.lamk = np.exp(-0.8 * np.linalg.norm(self.basis.k, axis=1)) self.barr = Barrier(self.model.explr_space) # initialize the control sequence # self.u_seq = [np.zeros(self.model.action_space.shape) # for _ in range(horizon)] self.u_seq = [ 0.0 * self.model.action_space.sample() for _ in range(horizon) ] if weights is None: weights = {'R': np.eye(self.model.action_space.shape[0])} self.Rinv = np.linalg.inv(weights['R']) self._phik = None self.ck = None def reset(self): self.u_seq = [ 0.0 * self.model.action_space.sample() for _ in range(self.horizon) ] self.replay_buffer.reset() @property def phik(self): return self._phik @phik.setter def phik(self, phik): assert len( phik ) == self.basis.tot_num_basis, 'phik does not have the same number as ck' self._phik = phik def __call__(self, state, ck_list=None, agent_num=None, seq=False, turtle_mode=True): assert self.phik is not None, 'Forgot to set phik, use set_target_phik method' self.u_seq[:-1] = self.u_seq[1:] self.u_seq[-1] = np.zeros(self.model.action_space.shape) x = self.model.reset(state) pred_traj = [] dfk = [] fdx = [] fdu = [] dbar = [] for t in range(self.horizon): # collect all the information that is needed pred_traj.append(x[self.model.explr_idx]) dfk.append(self.basis.dfk(x[self.model.explr_idx])) fdx.append(self.model.fdx(x, self.u_seq[t])) fdu.append(self.model.fdu(x)) dbar.append(self.barr.dx(x[self.model.explr_idx])) # step the model forwards x = self.model.step(self.u_seq[t] * 0.) # sample any past experiences # print('replay_buffer.shape: {}, batch_size.shape{}'.format(len(self.replay_buffer), self.batch_size)) if len(self.replay_buffer) > self.batch_size: past_states = self.replay_buffer.buffer[-self.batch_size:] pred_traj = pred_traj + past_states else: past_states = self.replay_buffer.buffer[0:] pred_traj = pred_traj + past_states # past_states = self.replay_buffer.sample(self.batch_size) # pred_traj = pred_traj + past_states # else: # past_states = self.replay_buffer.sample(len(self.replay_buffer)) # pred_traj = pred_traj + past_states # calculate the cks for the trajectory *** this is also in the utils file N = len(pred_traj) ck = np.sum([self.basis.fk(xt) for xt in pred_traj], axis=0) / N self.ck = ck.copy() if ck_list is not None: ck_list[agent_num] = ck ck = np.mean(ck_list, axis=0) fourier_diff = self.lamk * (ck - self.phik) fourier_diff = fourier_diff.reshape(-1, 1) # backwards pass rho = np.zeros(self.model.observation_space.shape) for t in reversed(range(self.horizon)): edx = np.zeros(self.model.observation_space.shape) edx[self.model.explr_idx] = np.sum(dfk[t] * fourier_diff, 0) bdx = np.zeros(self.model.observation_space.shape) bdx[self.model.explr_idx] = dbar[t] rho = rho - self.model.dt * (-edx - bdx - np.dot(fdx[t].T, rho)) self.u_seq[t] = -np.dot(np.dot(self.Rinv, fdu[t].T), rho) if (np.abs(self.u_seq[t]) > 1.0).any(): self.u_seq[t] /= np.linalg.norm(self.u_seq[t]) if turtle_mode is True: self.u_seq[t][0] = np.clip(self.u_seq[t][0], -0.2, 0.2) self.u_seq[t][1] = np.clip(self.u_seq[t][1], -2.8, 2.8) self.replay_buffer.push(state[self.model.explr_idx]) if seq is False: return self.u_seq[0].copy() else: return self.u_seq[0].copy(), self.u_seq.copy()
def main(): # make environment t1 = time.time() pot_region = (2 / np.sqrt(3), 2 / np.sqrt(3), 2 / np.sqrt(3)) radius = np.sqrt(pot_region[0]**2 + pot_region[1]**2 + pot_region[2]**2) region = (radius, radius, radius) nr = 201 gridpx = 131 gridpy = 131 gridpz = 131 x, y, z = grid(gridpx, gridpy, gridpz, region) xx, yy, zz = np.meshgrid(x, y, z) #make mesh #linear mesh #r =np.linspace(0.0001,region,nr) #log mesh a = np.log(2) / (nr - 1) b = radius / (np.e**(a * (nr - 1)) - 1) rofi = np.array([b * (np.e**(a * i) - 1) for i in range(nr)]) # make potential V = makepotential(xx, yy, zz, pot_region, pottype="cubic", potbottom=-1, potshow_f=False) # surface integral V_radial = surfaceintegral(x, y, z, rofi, V, method="lebedev_py", potshow_f=False) vofi = np.array(V_radial) # select method of surface integral # make basis node_open = 1 node_close = 2 LMAX = 4 all_basis = [] for lvalsh in range(LMAX): l_basis = [] # for open channel val = 1. slo = 0. for node in range(node_open): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) # for close channel val = 0. slo = -1. for node in range(node_close): basis = Basis(nr) emin = -10. emax = 100. basis.make_basis(a, b, emin, emax, lvalsh, node, nr, rofi, slo, vofi, val) l_basis.append(basis) all_basis.append(l_basis) with open("wavefunc.dat", mode="w") as fw_w: fw_w.write("#r, l, node, open or close = ") for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write(str(nyu_basis.l)) fw_w.write(str(nyu_basis.node)) if nyu_basis.open: fw_w.write("open") else: fw_w.write("close") fw_w.write(" ") fw_w.write("\n") for i in range(nr): fw_w.write("{:>13.8f}".format(rofi[i])) for l_basis in all_basis: for nyu_basis in l_basis: fw_w.write("{:>13.8f}".format(nyu_basis.g[i])) fw_w.write("\n") hsmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) lmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) qmat = np.zeros( (LMAX, LMAX, node_open + node_close, node_open + node_close), dtype=np.float64) for l1 in range(LMAX): for l2 in range(LMAX): if l1 != l2: continue for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() hsmat[l1][l2][n1][n2] = integrate( all_basis[l1][n1].g[:nr] * all_basis[l2][n2].g[:nr], rofi, nr) * all_basis[l1][n1].e lmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].slo qmat[l1][l2][n1][ n2] = all_basis[l1][n1].val * all_basis[l2][n2].val print("\nhsmat") print(hsmat) print("\nlmat") print(lmat) print("\nqmat") print(qmat) #make not spherical potential my_radial_interfunc = interpolate.interp1d(rofi, V_radial) V_ang = np.where( np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1], V - my_radial_interfunc(np.sqrt(xx * xx + yy * yy + zz * zz)), 0.) """ for i in range(gridpx): for j in range(gridpy): for k in range(gridpz): print(V_ang[i][j][k],end=" ") print("") print("\n") sys.exit() """ #WARING!!!!!!!!!!!!!!!!!!!!!! """ Fujikata rewrote ~/.local/lib/python3.6/site-packages/scipy/interpolate/interpolate.py line 690~702 To avoid exit with error "A value in x_new is below the interpolation range." """ #!!!!!!!!!!!!!!!!!!!!!!!!!!! """ with open ("V_ang.dat",mode = "w") as fw_a: for i in range(len(V_ang)): fw_a.write("{:>13.8f}".format(xx[50][i][50])) fw_a.write("{:>13.8f}\n".format(V_ang[i][50][50])) """ #mayavi.mlab.plot3d(xx,yy,V_ang) # mlab.contour3d(V_ang,color = (1,1,1),opacity = 0.1) # obj = mlab.volume_slice(V_ang) # mlab.show() umat = np.zeros((node_open + node_close, node_open + node_close, LMAX, LMAX, 2 * LMAX + 1, 2 * LMAX + 1), dtype=np.complex64) # umat_t = np.zeros((LMAX,LMAX,2 * LMAX + 1,2 * LMAX + 1,node_open + node_close,node_open + node_close), dtype = np.complex64) # my_V_ang_inter_func = RegularGridInterpolator((x, y, z), V_ang) dis = np.sqrt(xx**2 + yy**2 + zz**2) dis2 = xx**2 + yy**2 + zz**2 theta = np.where(dis != 0., np.arccos(zz / dis), 0.) phi = np.where(xx**2 + yy**2 != 0., np.arccos(xx / np.sqrt(xx**2 + yy**2)), 0.) # region_t = np.where(dis < rofi[-1],1,0) sph_harm_mat = np.zeros((LMAX, 2 * LMAX + 1, gridpx, gridpy, gridpz), dtype=np.complex64) for l1 in range(LMAX): for m1 in range(-l1, l1 + 1): sph_harm_mat[l1][m1] = np.where(dis != 0., sph_harm(m1, l1, theta, phi), 0.) g_ln_mat = np.zeros((node_open + node_close, LMAX, gridpx, gridpy, gridpz), dtype=np.float64) for n1 in range(node_open + node_close): for l1 in range(LMAX): my_radial_g_inter_func = interpolate.interp1d( rofi, all_basis[l1][n1].g[:nr]) g_ln_mat[n1][l1] = my_radial_g_inter_func( np.sqrt(xx**2 + yy**2 + zz**2)) for n1 in range(node_open + node_close): for n2 in range(node_open + node_close): for l1 in range(LMAX): for l2 in range(LMAX): if all_basis[l1][n1].l != l1 or all_basis[l2][n2].l != l2: print("error: L is differnt") sys.exit() # to avoid nan in region where it can not interpolate ie: dis > rofi g_V_g = np.where( dis < rofi[-1], g_ln_mat[n1][l1] * V_ang * g_ln_mat[n2][l2], 0.) for m1 in range(-l1, l1 + 1): for m2 in range(-l2, l2 + 1): print( "n1 = {} n2 = {} l1 = {} l2 = {} m1 = {} m2 = {}" .format(n1, n2, l1, l2, m1, m2)) umat[n1][n2][l1][l2][m1][m2] = np.sum( sph_harm_mat[l1][m1] * g_V_g * sph_harm_mat[l2][m2].conjugate() / dis2) * ( 2 * region[0] * 2 * region[1] * 2 * region[2]) / (gridpx * gridpy * gridpz) #umat[l1][l2][m1][m2][n1][n2] = simps(simps(simps(g_V_g * sph_harm_mat[l1][m1] * sph_harm_mat[l2][m2],x = z,even="first"),x = y,even="first"),x = x,even="first") #umat[l1][l2][m1][m2][n1][n2] = simps(simps(simps(g_V_g * sph_harm_mat[l1][m1] * sph_harm_mat[l2][m2],x = z),x = y),x = x) #umat[l1][l2][m1][m2][n1][n2] = cumtrapz(cumtrapz(cumtrapz(g_V_g * sph_harm_mat[l1][m1] * sph_harm_mat[l2][m2],x = z),x = y),x = x) #umat[l1][l2][m1][m2][n1][n2] = np.sum( np.where( dis < rofi[-1] ,sph_harm(m1,l1,theta,phi) * g1 * V_ang * sph_harm(m2,l2,theta,phi) * g2 ,0. )) / (gridpx * gridpy * gridpz) # umat_t[l1][l2][m1][m2][n1][n2] = np.sum( np.where( np.sqrt(xx * xx + yy * yy + zz * zz) < rofi[-1] ,sph_harm(m1,l1,np.arccos(zz / np.sqrt(xx **2 + yy **2 + zz **2)),np.arccos(xx / np.sqrt(xx **2 + yy **2))) * my_radial_g1_inter_func(np.sqrt(xx**2 + yy **2 + zz **2)) * my_V_ang_inter_func((xx,yy,zz)) * sph_harm(m2,l2,np.arccos(zz / np.sqrt(xx **2 + yy **2 + zz **2)),np.arccos(xx / np.sqrt(xx **2 + yy **2))) * my_radial_g2_inter_func(np.sqrt(xx **2 + yy **2 + zz **2)),0. )) # print(umat_t[l1][l2][m1][m2][n1][n2]) """ for xi in x: for yi in y: for zi in z: if np.sqrt(xi**2 + yi **2 + zi **2) < rofi[-1]: umat_t[l1][l2][m1][m2][n1][n2] += sph_harm(m1,l1,np.arccos(zi / np.sqrt(xi **2 + yi **2 + zi **2)),np.arccos(xi / np.sqrt(xi **2 + yi **2))) * my_radial_g1_inter_func(np.sqrt(xi**2 + yi **2 + zi **2)) * my_V_ang_inter_func((xi,yi,zi)) * sph_harm(m2,l2,np.arccos(zi / np.sqrt(xi **2 + yi **2 + zi **2)),np.arccos(xi / np.sqrt(xi **2 + yi **2))) * my_radial_g2_inter_func(np.sqrt(xi **2 + yi **2 + zi **2)) print(umat[l1][l2][m1][m2][n1][n2]) print(umat_t[l1][l2][m1][m2][n1][n2]) print(umat_t[l1][l2][m1][m2][n1][n2] - umat[l1][l2][m1][m2][n1][n2]) """ #umat[l1][l2][m1][m2][n1][n2] = tplquad( lambda x, y, z : sph_harm(m1,l1,np.arccos(z / np.sqrt(x **2 + y **2 + z **2)),np.arccos(x / np.sqrt(x **2 + y **2))).real * my_radial_g1_inter_func(np.sqrt(x**2 + y **2 + z **2)) * my_V_ang_inter_func((x,y,z)) * sph_harm(m2,l2,np.arccos(z / np.sqrt(x **2 + y **2 + z **2)),np.arccos(x / np.sqrt(x **2 + y **2))).real * my_radial_g2_inter_func(np.sqrt(x **2 + y **2 + z **2)) if np.sqrt(x **2 + y **2 + z **2) < rofi[-1] else 0 , -region, region , -region, region, -region, region) print(umat[n1][n2][l1][l2][m1][m2]) t2 = time.time() print("time = ", t2 - t1)