def get_power_in_mode(u0, rcore, ncore, nclad, mode, width, wl0): xa = np.linspace(-width, width, u0.shape[0]) ya = np.linspace(-width, width, u0.shape[1]) xg, yg = np.meshgrid(xa, ya) #xa = np.linspace(-width*3,width*3,u0.shape[0]*3) #ya = np.linspace(-width*3,width*3,u0.shape[1]*3) #xg,yg = np.meshgrid(xa,ya) s = u0.shape[0] if mode[0] == 0: lf = LPmodes.lpfield(xg, yg, mode[0], mode[1], rcore, wl0, ncore, nclad) field = normalize(lf) #[s:-s,s:-s] #field = normalize(LPmodes.lpfield(xg,yg,mode[0],mode[1],rcore,wl0,ncore,nclad)) #field = normalize(LP01gauss(xg,yg,rcore,wl0,ncore,nclad)) _power = np.power(overlap(u0, field), 2) return _power else: #field0 = normalize(LPmodes.lpfield(xg,yg,mode[0],mode[1],rcore,wl0,ncore,nclad,"cos")) #field1 = normalize(LPmodes.lpfield(xg,yg,mode[0],mode[1],rcore,wl0,ncore,nclad,"sin")) lf0 = LPmodes.lpfield(xg, yg, mode[0], mode[1], rcore, wl0, ncore, nclad, "cos") lf1 = LPmodes.lpfield(xg, yg, mode[0], mode[1], rcore, wl0, ncore, nclad, "sin") field0 = normalize(lf0) #[s:-s,s:-s] field1 = normalize(lf1) #[s:-s,s:-s] power0 = np.power(overlap(u0, field0), 2) power1 = np.power(overlap(u0, field1), 2) return power0 + power1
def randomize(self, width, height, player, max_speed=3, min_speed=2, auto_speed=True): max_speed += self.level min_speed += self.level self.appeared = False x = random.randint(-2 * width, 3 * width) y = random.randint(-2 * height, 3 * height) while -width < x < 2 * width and -height < y < 2 * height: x = random.randint(-width, 2 * width) y = random.randint(-height, 2 * height) self.set_x(x) self.set_y(y) self.angle = random.randint(0, 360) self.image = aliens[random.randint(0, 2)] self.set_v_x(player.get_x() - self.get_x() + random.random() * 200 - 100) self.set_v_y(player.get_y() - self.get_y() + random.random() * 200 - 100) self.speed = normalize( self.speed, random.random() * (max_speed - min_speed) + min_speed) self.speed_angle = random.random() * 2 - 1 return self
def LP01gauss(xg, yg, rcore, wl0, ncore, nclad): V = LPmodes.get_V(2 * np.pi / wl0, rcore, ncore, nclad) w = rcore * (0.65 + 1.619 / V**1.5 + 2.879 / V**6 - (0.016 + 1.561 * V**(-7))) rsq = xg * xg + yg * yg return normalize(np.exp(-rsq / w**2))
def coupling_vs_r_pupilplane_single(tele: AOtele.AOtele, pupilfields, rcore, ncore, nclad, wl0): k0 = 2 * np.pi / wl0 fieldshape = pupilfields[0].shape #need to generate the available modes V = LPmodes.get_V(k0, rcore, ncore, nclad) modes = LPmodes.get_modes(V) lpfields = [] for mode in modes: if mode[0] == 0: lpfields.append( normalize( LPmodes.lpfield(xg, yg, mode[0], mode[1], rcore, wl0, ncore, nclad))) else: lpfields.append( normalize( LPmodes.lpfield(xg, yg, mode[0], mode[1], rcore, wl0, ncore, nclad, "cos"))) lpfields.append( normalize( LPmodes.lpfield(xg, yg, mode[0], mode[1], rcore, wl0, ncore, nclad, "sin"))) lppupilfields = [] #then backpropagate for field in lpfields: wf = hc.Wavefront(hc.Field(field.flatten(), tele.focalgrid), wavelength=wl0 * 1.e-6) pupil_wf = tele.back_propagate(wf, True) lppupilfields.append(pupil_wf.electric_field.reshape(fieldshape)) lppupilfields = np.array(lppupilfields) pupilfields = np.array(pupilfields) #compute total overlap powers = np.sum(pupilfields * lppupilfields, axes=(1, 2)) return np.mean(powers), np.stddev(powers)
def main(src, outfile=None): dirpath, filepath = get_dirpath_and_filepath(src) open_file_or_stdout = FileOrPortOpener(outfile) source = filepath or dirpath for path in iterate_file_or_directory(source, glob_arg="*.json"): with open(path) as rf: nums = json.load(rf) result = [normalize(i) for i in nums] with open_file_or_stdout(path, "w") as wf: wf.write(json.dumps(result, ensure_ascii=False, indent=2)) sys.stderr.write(".")
def plot_modes(ncore, nclad, wl0): core_rs = [2.2] xa, ya = np.linspace(-50, 50, 400), np.linspace(-50, 50, 400) xg, yg = np.meshgrid(xa, ya) for r in core_rs: alpha = r / 10 field = LPmodes.lpfield(xg, yg, 0, 1, r, wl0, ncore, nclad) field = normalize(field) plt.plot(xa, np.abs(field[int(len(field) / 2)]), alpha=alpha, color='k') plt.show()
def run(phantom, algorithm, args): """Run reconstruction benchmarks for phantoms. Parameters ---------- phantom : string The name of the phantom to use. algorithm : string The name of the algorithm to test. args : argparser args Returns ------- Either rec or imgs rec : np.ndarray The reconstructed image. """ prj, ang, obj = generate(phantom, args) proj = np.zeros(shape=[prj.shape[1], prj.shape[0], prj.shape[2]], dtype=np.float) for i in range(0, prj.shape[1]): proj[i, :, :] = prj[:, i, :] # always add algorithm _kwargs = {"algorithm": algorithm} # assign number of cores _kwargs["ncore"] = args.ncores # don't assign "num_iter" if gridrec or fbp if algorithm not in ["fbp", "gridrec"]: _kwargs["num_iter"] = args.num_iter # use the accelerated version if algorithm in ["mlem", "sirt"]: _kwargs["accelerated"] = True print("kwargs: {}".format(_kwargs)) rec = tomopy.recon(prj, ang, **_kwargs) print("completed reconstruction...") rec = misc.normalize(rec) rec = misc.trim_border(rec, rec.shape[0], rec[0].shape[0] - obj[0].shape[0], rec[0].shape[1] - obj[0].shape[1]) misc.output_images(rec, algorithm, args.format)
def do_superblock(self, arg): 'superblock --create --event_block_height="28224" --payments="yLipDagwb1gM15RaUq3hpcaTxzDsFsSy9a=100"' 'superblock --create --event_date="2017/1/1" --payments="Addr1=amount,Addr2=amount,Addr3=amount"' parser = argparse.ArgumentParser(description='Create a dash proposal') # desired action parser.add_argument('-c', '--create', help="create", action='store_true') # meta data (create or amend) parser.add_argument('-p', '--payments', help='the payments desired in the superblock, serialized as a list. example: {"Addr1": amount,"Addr2": amount}') parser.add_argument('-b', '--event_block_height', help='block height to issue superblock') # process args = None try: args = parser.parse_args(parse(arg)) except: pass if not args: return ### ------ CREATE METHOD -------- #### if args.create: #--create --revision=1 --pubkey=XPubkey --username="******" if not args.payments: print "superblock creation requires a payment descriptions, use --payments" return if not args.event_block_height: print "superblock creation requires a event_block_height, use --event_block_height" return ### ---- CONVERT AND CHECK EPOCHS ----- payments = misc.normalize(args.payments).split(",") if len(payments) > 0: pass # COMPILE LIST OF ADDRESSES AND AMOUNTS list_addr = [] list_amount = [] for payment in payments: print payment addr,amount = payment.split("=") list_addr.append(addr) list_amount.append(amount) print list_amount print list_addr # CREATE NAME ACCORDING TO STARTING DATE (NON-UNIQUE IS NOT AN ATTACK) superblock_name = "sb" + str(random.randint(1000000, 9999999)) # DOES THIS ALREADY EXIST? if GovernanceObjectMananger.object_with_name_exists(superblock_name): print "governance object with that name already exists" return event_block_height = misc.normalize(args.event_block_height); print event_block_height fee_tx = CTransaction() newObj = GovernanceObject() newObj.create_new(parent, superblock_name, govtypes.trigger, govtypes.FIRST_REVISION, fee_tx) last_id = newObj.save() print last_id if last_id != None: # ADD OUR PROPOSAL AS A SUB-OBJECT WITHIN GOVERNANCE OBJECT c = Superblock() c.set_field("governance_object_id", last_id) c.set_field("type", govtypes.trigger) c.set_field("subtype", "superblock") c.set_field("superblock_name", superblock_name) c.set_field("event_block_height", event_block_height) c.set_field("payment_addresses", "|".join(list_addr)) c.set_field("payment_amounts", "|".join(list_amount)) # APPEND TO GOVERNANCE OBJECT newObj.add_subclass("trigger", c) newObj.save() # CREATE EVENT TO TALK TO DASHD / PREPARE / SUBMIT OBJECT event = Event() event.create_new(last_id) event.save() libmysql.db.commit() print "event queued successfully" else: print "error:", newObj.last_error() # abort mysql commit return ### ------- ELSE PRINT HELP --------------- ### parser.print_help()
def get_current_size(self): """""" if self.status == cons.STATUS_CORRECT: return self.normalized_total_size elif self.current_size: return misc.normalize(self.current_size)
def set_total_size(self, size): """""" self.total_size = size self.normalized_total_size = misc.normalize(size)
def get_speed(self): """""" if self.status == cons.STATUS_ACTIVE: return misc.normalize(self.current_speed, "%.1f%s/s") else: self.current_speed = 0
def do_superblock(self, arg): 'superblock --create --event_block_height="28224" --payments="yLipDagwb1gM15RaUq3hpcaTxzDsFsSy9a=100"' 'superblock --create --event_date="2017/1/1" --payments="Addr1=amount,Addr2=amount,Addr3=amount"' parser = argparse.ArgumentParser(description='Create a dash proposal') # desired action parser.add_argument('-c', '--create', help="create", action='store_true') # meta data (create or amend) parser.add_argument( '-p', '--payments', help= 'the payments desired in the superblock, serialized as a list. example: {"Addr1": amount,"Addr2": amount}' ) parser.add_argument('-b', '--event_block_height', help='block height to issue superblock') # process args = None try: args = parser.parse_args(parse(arg)) except: pass if not args: return ### ------ CREATE METHOD -------- #### if args.create: #--create --revision=1 --pubkey=XPubkey --username="******" if not args.payments: print "superblock creation requires a payment descriptions, use --payments" return if not args.event_block_height: print "superblock creation requires a event_block_height, use --event_block_height" return ### ---- CONVERT AND CHECK EPOCHS ----- payments = misc.normalize(args.payments).split(",") if len(payments) > 0: pass # COMPILE LIST OF ADDRESSES AND AMOUNTS list_addr = [] list_amount = [] for payment in payments: print payment addr, amount = payment.split("=") list_addr.append(addr) list_amount.append(amount) print list_amount print list_addr # CREATE NAME ACCORDING TO STARTING DATE (NON-UNIQUE IS NOT AN ATTACK) superblock_name = "sb" + str(random.randint(1000000, 9999999)) # DOES THIS ALREADY EXIST? if GovernanceObjectMananger.object_with_name_exists( superblock_name): print "governance object with that name already exists" return event_block_height = misc.normalize(args.event_block_height) print event_block_height fee_tx = CTransaction() newObj = GovernanceObject() newObj.create_new(parent, superblock_name, govtypes.trigger, govtypes.FIRST_REVISION, fee_tx) last_id = newObj.save() print last_id if last_id != None: # ADD OUR PROPOSAL AS A SUB-OBJECT WITHIN GOVERNANCE OBJECT c = Superblock() c.set_field("governance_object_id", last_id) c.set_field("type", govtypes.trigger) c.set_field("subtype", "superblock") c.set_field("superblock_name", superblock_name) c.set_field("event_block_height", event_block_height) c.set_field("payment_addresses", "|".join(list_addr)) c.set_field("payment_amounts", "|".join(list_amount)) # APPEND TO GOVERNANCE OBJECT newObj.add_subclass("trigger", c) newObj.save() # CREATE EVENT TO TALK TO DASHD / PREPARE / SUBMIT OBJECT event = Event() event.create_new(last_id) event.save() libmysql.db.commit() print "event queued successfully" else: print "error:", newObj.last_error() # abort mysql commit return ### ------- ELSE PRINT HELP --------------- ### parser.print_help()
def get_current_size(self): """""" if self.status == cons.STATUS_CORRECT: return self.normalized_total_size elif self.current_size: return misc.normalize(self.current_size)
def set_total_size(self, size): """""" self.total_size = size self.normalized_total_size = misc.normalize(size)
def get_speed(self): """""" if self.status == cons.STATUS_ACTIVE: return misc.normalize(self.current_speed, "%.1f%s/s") else: self.current_speed = 0
def prop2end(self, u, xyslice, zslice, u1_func=None, writeto=None, ucrit=5.e-3, remesh_every=20, dynamic_n0=True): mesh = self.mesh PML = mesh.PML za_keep = mesh.za[zslice] if type(za_keep) == np.ndarray: minz, maxz = za_keep[0], za_keep[-1] shape = (len(za_keep), *mesh.xg[xyslice].shape) else: raise Exception('uhh not implemented') self.field = np.zeros(shape, dtype=c128) xa_in = np.linspace(-mesh.xw / 2, mesh.xw / 2, u.shape[0]) ya_in = np.linspace(-mesh.yw / 2, mesh.yw / 2, u.shape[1]) dx0 = xa_in[1] - xa_in[0] dy0 = ya_in[1] - ya_in[0] print("normalizing input file") normalize(u, weight=dx0 * dy0) __z = 0 #pull xy mesh xy = mesh.xy dx, dy = xy.dx0, xy.dy0 #resample the field onto the smaller xy mesh (in the smaller mesh's computation zone!) u0 = xy.resample_complex(u, xa_in, ya_in, xy.xa[PML:-PML], xy.ya[PML:-PML]) #now we pad w/ zeros to extend it into the PML zone u0 = np.pad(u0, ((PML, PML), (PML, PML))) #initial mesh refinement print("initial remesh") xy.refine_base(u0, ucrit) #xy.plot_mesh(4) weights = xy.get_weights() #now resample the field onto the smaller *non-uniform* xy mesh u = xy.resample_complex(u, xa_in, ya_in, xy.xa[PML:-PML], xy.ya[PML:-PML]) u = np.pad(u, ((PML, PML), (PML, PML))) #do another norm to correct for the slight power change you get when resampling. I measure 0.1% change for psflo. should check again norm_nonu(u, weights) counter = 0 total_iters = self.mesh.zres print("propagating field...") z__ = 0 #step 0 setup self.update_grid_cor_facs('x') self.update_grid_cor_facs('y') # initial array allocation _trimatsx, rmatx, gx, _trimatsy, rmaty, gy, IORsq__, _IORsq_, __IORsq = self.allocate_mats( ) self.precomp_trimats('x') self.precomp_trimats('y') self.rmat_precomp('x') self.rmat_precomp('y') self._pmlcorrect(_trimatsx, 'x') self._pmlcorrect(_trimatsy, 'y') #get the current IOR dist self.set_IORsq(IORsq__, z__) print("initial shape: ", xy.shape) for i in range(total_iters): printProgressBar(i, total_iters - 1) u0 = xy.get_base_field(u) u0c = np.conj(u0) weights = xy.get_weights() ## Total power monitor ## self.totalpower[i] = overlap_nonu(u, u, weights) print(self.totalpower[i]) ## Other monitors ## if u1_func is not None: lp = norm_nonu(u1_func(xy.xg, xy.yg), weights) self.power[i] = power(overlap_nonu(u, lp, weights), 2) _z_ = z__ + mesh.half_dz __z = z__ + mesh.dz if minz <= __z <= maxz: ix0, ix1, ix2, ix3 = mesh.get_loc() mid = int(u0.shape[1] / 2) self.field[counter][ix0:ix1 + 1] = u0[:, mid] ## FIX ## counter += 1 #avoid remeshing on step 0 if (i + 1) % remesh_every == 0: #xy.plot_mesh(4) ## update the effective index if dynamic_n0: #update the effective index base = xy.get_base_field(IORsq__) self.n02 = xy.dx0 * xy.dy0 * np.real( np.sum(u0c * u0 * base)) / self.k02 oldxm, oldxM = xy.xm, xy.xM oldym, oldyM = xy.ym, xy.yM oldxw, oldyw = xy.xw, xy.yw #expand the grid if necessary new_xw = mesh.xwfunc(__z) new_yw = mesh.ywfunc(__z) new_xw, new_yw = xy.snapto(new_xw, new_yw) xy.reinit(new_xw, new_yw) #set grid back to base res with new dims if (xy.xw > oldxw or xy.yw > oldyw): #now we need to pad u,u0 with zeros to make sure it matches the new space xpad = int((xy.shape0[0] - u0.shape[0]) / 2) ypad = int((xy.shape0[1] - u0.shape[1]) / 2) u = np.pad(u, ((xpad, xpad), (ypad, ypad))) u0 = np.pad(u0, ((xpad, xpad), (ypad, ypad))) #pad coord arrays to do interpolation xy.xa_last = np.hstack( (np.linspace(xy.xm, oldxm - dx, xpad), xy.xa_last, np.linspace(oldxM + dx, xy.xM, xpad))) xy.ya_last = np.hstack( (np.linspace(xy.ym, oldym - dy, ypad), xy.ya_last, np.linspace(oldyM + dy, xy.yM, ypad))) #subdivide into nonuniform grid xy.refine_base(u0, ucrit) #interp the field to the new grid u = xy.resample_complex(u) #give the grid to the optical sys obj so it can compute IORs self.optical_system.set_sampling(xy) #compute nonuniform grid correction factors R_i self.update_grid_cor_facs('x') self.update_grid_cor_facs('y') # grid size has changed, so now we need to reallocate arrays for at least the next remesh_period iters _trimatsx, rmatx, gx, _trimatsy, rmaty, gy, IORsq__, _IORsq_, __IORsq = self.allocate_mats( ) #get the current IOR dist self.set_IORsq(IORsq__, z__) #precompute things that will be reused self.precomp_trimats('x') self.precomp_trimats('y') self.rmat_precomp('x') self.rmat_precomp('y') self._pmlcorrect(_trimatsx, 'x') self._pmlcorrect(_trimatsy, 'y') self.set_IORsq( _IORsq_, _z_, ) self.set_IORsq(__IORsq, __z) self.rmat(rmatx, u, IORsq__, 'x') self.rmat_pmlcorrect(rmatx, u, 'x') self._trimats(_trimatsx, _IORsq_, 'x') self._trimats(_trimatsy, __IORsq.T, 'y') tri_solve_vec(_trimatsx[0], _trimatsx[1], _trimatsx[2], rmatx, gx, u) self.rmat(rmaty, u.T, _IORsq_.T, 'y') self.rmat_pmlcorrect(rmaty, u.T, 'y') tri_solve_vec(_trimatsy[0], _trimatsy[1], _trimatsy[2], rmaty, gy, u.T) z__ = __z if (i + 2) % remesh_every != 0: IORsq__[:, :] = __IORsq print("final total power", self.totalpower[-1]) if writeto: np.save(writeto, self.field) return u