def process(pth): print(f'\nProcessing {pth}') save_pth = pth / 'intra_reg_stacks' try: save_pth.mkdir() except FileExistsError: ex('Save File for reg stacks already exists. Delete and re-run.') #Intravolume registration of the fixed volume print('Doing intravolume registration.') files = sorted(list(pth.glob('*.tif')), key=sort_key) #files = list(pth.glob('*.tif')) loop_starts = time.time() for file in files: start_time = time.time() print(f'Processing: {file}') fixed = io.imread(str(file)) fixed = flat.fix(fixed[:, :, :512], divisor=4) save_name = save_pth / f'intra_reg_{file.name}' io.imsave(arr=fixed.astype('float32'), fname=str(save_name)) end_time = time.time() print(f'{file} was processed in {(end_time - start_time):.2f}s. \ \n{((end_time - loop_starts)/60):.2f} minutes have elapsed.')
def main(): source = askdirectory() if source == '': ex("\n\nExited: No file path selected\n\n") #sorting(Path(os.path.abspath(source))) process(Path(source)) print('\n\n\n\t\t\t\t---------\n\t\t\t\tCompleted\n\t\t\t\t---------')
def process(pth): print(f'\nProcessing {pth}') save_pth = pth / 'reg_stacks' #tmat_pth = pth / 'transformation_matrices' try: save_pth.mkdir() #tmat_pth.mkdir() except FileExistsError: ex('Save File for reg stacks or tmats already exists. Delete and re-run.' ) #tell pystack reg that we will use a translational transformation #there shouldn't be intra-volume rotation or shear (there might be for rod blink) sr = StackReg(StackReg.TRANSLATION) #register to the first slice and output the transfomation matrix without transforming #iterate through the files in the stacks folder files = pth.glob('*.tif') loop_starts = time.time() for i, file in enumerate(files): #start_time = time.time() print(f'Processing: {file}') #Intravolume registration of the fixed volume #load first stack and do a 3d gaussian blur with a sigma=1 #str needed for imread, otherwise only one frame is loaded fixed = io.imread(str(file)) #had gauss(), testing t_mats = sr.register_stack(gauss(fixed), reference='first', n_frames=1) #remove the x shift from all the matrices - horizontal movement isn't relevant here, #the volume should be acquired quickly enough that this isn't a problem. t_mats[:, 0, -1] = 0 fixed = sr.transform_stack(fixed, tmats=t_mats) #Using previous to see if I could get rid of wigge. Didn't seem to work. #t_mats = sr.register_stack(gauss(fixed), reference='previous') #t_mats[:,1,-1] = 0 #fixed = sr.transform_stack(fixed, tmats=t_mats) #save the register fixed volume in the parent directory for reference save_name = save_pth / f'reg_{file.name}' #io.imsave(arr=img_as_uint(fixed), fname=str(save_name)) io.imsave(arr=img_as_float32(fixed), fname=str(save_name)) #get fixed out of memory - may not be worth the time? print(f'Intravolume registration complete. File saved at {save_name}') #end_time = time.time() #print(f'{file} was processed in {(end_time - start_time):.2f}s. \ #\n{((end_time - loop_starts)/60):.2f} minutes have elapsed.') #de;ete emumerate #if i==4: #ex('auto break') end_time = time.time() print(f'Run took {(end_time-loop_starts)/60:.2f} minutes')
def main(): source = askdirectory() if source == '': ex("\n\nExited: No file path selected\n\n") #sorting(Path(os.path.abspath(source))) src = Path(source) stack = im_open(src) avg_stack = timeseries(stack) save_pth = src / 'timeseries' save_pth.mkdir() io.imsave(arr=img_as_float32(avg_stack), fname=str(save_pth / 'timeseries.tif')) print('\n\n\n\t\t\t\t---------\n\t\t\t\tCompleted\n\t\t\t\t---------')
def dependency_check(): # pylint: disable=import-outside-toplevel # fmt: off try: import oead del oead except ImportError: from platform import system if system() == "Windows": native_msg( "The latest (2019) Visual C++ redistributable is required to run BCML. " "Please download it from the following link and try again:\n" "https://aka.ms/vs/16/release/vc_redist.x64.exe", "Dependency Error") from sys import exit as ex ex(1)
def im_open(pth): """Imports a folder containing a stack of images using scikit image collections""" try: #Double check to make sure pth is a directory. assert pth.is_dir() #Get list of tif files in pth and sort based on 'stem' which is the index of the B-scan (i.e. y position) #files = sorted(pth.glob('*.tif'), key=sort_key) #load the collection raw_stack = io.imread_collection(str(pth / '*.tif')) #turn them into a stack that can be manipulated as a multdimensional array. stack = io.collection.concatenate_images(raw_stack) return stack except AssertionError: #if the assert fails the program stops. This is a bit heavy handed... ex("A non-directory object was given to the __open__ function")
def main (): if len (argv) < 4: print 'Use: memeorystar.py <value> <type> <pid>' ex (-1) op = OptionParser ('memorystar.py <value> <type> <pid>') op.add_option ('-G', '--graph', default=False, action='store_true', dest='graph', help='if you want to use GTK interface use this option') (op, args) = op.parse_args () if op.graph: window = gt.MainWindow () window.main () else: dbg = ProcessDebugger (argv [-1]) if argv [-2] == 'boolean': print dbg.search_boolean_value (argv [-3]) elif argv [-2] == 'integer': print dbg.search_integer_value (argv [-3]) else: print dbg.search_addr_by_value (argv [-3])
def prepareData(dataFolderPath, storagePlace, fileList, numTest,\ test='test.scp', train='train.scp'): totlFiles = len(fileList) if numTest > totlFiles - 1: print 'No enough data' sys.ex(1) mark = [0 for _ in xrange(totlFiles)] testFiles = [] trainFiles = [] testFilePointer = open(os.path.join(storagePlace, 'test.scp'), "w") trainFilePointer = open(os.path.join(storagePlace, 'train.scp'), "w") cnt = 0 while cnt < numTest: while True: index = random.randint(0, totlFiles-1) if mark[index] == 0: line = fileList[index].split('|')[1] testFiles.append( line ) if cnt < numTest - 1: testFilePointer.write( line + '\n' ) else: testFilePointer.write(line) mark[index] = 1 break cnt += 1 firstFlag = False for i in xrange(totlFiles): if mark[i] == 0: line = fileList[i].split('|')[1] trainFiles.append( line ) if firstFlag is False: trainFilePointer.write( line ) firstFlag = True else: trainFilePointer.write( '\n' + line ) testFilePointer.close() trainFilePointer.close()
print repr(a + b), repr(a - b) print type(a + b), type(a - b) print a | b, abs(c) print type(a | b), type(abs(c)) print pi * c, c * pi print type(pi * c), type(c * pi) #print repr(c[1]), repr(c[:-1]), a[::2], repr(c[1:2]) #print type(c[1]), type(c[:-1]), type(a[::2]), type(c[1:2]), type(a<<1) print a == b, (a << 1) == (a >> 3), a << 1, a != b, a != a print a ^ b, b ^ a print "Iterator test:", tuple('<' + str(e) + '>' for e in a) from sys import exc_info as ex try: a + 1 except: print 'Caught:', ex()[1:2] try: a - 1 except: print 'Caught:', ex()[1:2] try: a + c except: print 'Caught:', ex()[1:2] try: a - c except: print 'Caught:', ex()[1:2] try: a * b except:
def process(pth): print(f'\nProcessing {pth}') save_pth = pth / 'vol_reg_stacks' tmat_pth = pth / 'vol_transformation_matrices' try: save_pth.mkdir() tmat_pth.mkdir() except FileExistsError: ex('Save File for reg stacks or tmats already exists. Delete and re-run.') #Intravolume registration of the fixed volume print('Doing intravolume registration.') #load first stack and do a 3d gaussian blur with a sigma=1 #str needed for imread, otherwise only one frame is loaded fixed = io.imread(str(pth/'stack0.tif')) #had gauss(), testing #tell pystack reg that we will use a translational transformation #there shouldn't be intra-volume rotation or shear (there might be for rod blink) sr = StackReg(StackReg.TRANSLATION) #register to the first slice and output the transfomation matrix without transforming t_mats = sr.register_stack(gauss(fixed), reference='first', n_frames=1) #remove the x shift from all the matrices - horizontal movement isn't relevant here, #the volume should be acquired quickly enough that this isn't a problem. t_mats[:,0,-1] = 0 fixed = sr.transform_stack(fixed, tmats=t_mats) #save the register fixed volume in the parent directory for reference save_name = pth.parent / 'fixed.tif' #io.imsave(arr=img_as_uint(fixed), fname=str(save_name)) io.imsave(arr=fixed.astype('float32'), fname=str(save_name)) #get fixed out of memory - may not be worth the time? del fixed print(f'Intravolume registration complete. File saved at {save_name}') #Volume registration #switch to tmat folder because i dont know how to set the output folder to save #the transformation mats. elastix.Execute() automatically saves #TransformParameters.0.txt in the current directory os.chdir(tmat_pth) #reload fixed image with sitk so it is in the right format fixed = sitk.ReadImage(str(save_name)) #set up for multivolume registration parameterMap = sitk.GetDefaultParameterMap('affine') elastixImageFilter = sitk.ElastixImageFilter() elastixImageFilter.SetFixedImage(fixed) elastixImageFilter.SetParameterMap(parameterMap) #test 11-8-2019 parameterMap['Image Sampler'] = ['Full'] #parameterMap['Metric'] = ['AdvancedMeanSquares'] parameterMap['Optimiser'] = ['FullSearch'] #iterate through the files in the stacks folder files = sorted(list(pth.glob('*.tif')), key=sort_key) loop_starts = time.time() for i,file in enumerate(files): #i=0 #use first stack #register to previous stack if i > 1: fixed = sitk.ReadImage(str(save_name)) elastixImageFilter.SetFixedImage(fixed) start_time = time.time() print(f'Processing: {file}') #load the volume #Do affine registration so that volume can shear to do the intravolume registration #this code is equivalent to the lines below, but allows the export of the #transformation matrices #moving = sitk.ReadImage(file) #reg_volume = sitk.Elastix(fixed, moving, "affine") elastixImageFilter.SetMovingImage(sitk.ReadImage(str(file))) elastixImageFilter.Execute() reg_volume = elastixImageFilter.GetResultImage() #can get the transform parameters, but have no idea how to save them #maybe just through normal python file manipulation? #transformParameterMap = elastixImageFilter.GetTransformParameterMap() #save volume save_name = save_pth / f'reg_{file.name}' sitk.WriteImage(reg_volume, str(save_name)) #transformation was saved on execute, now rename. #tmat_name = tmat_pth / f'tmat_{file.name}' os.rename('TransformParameters.0.txt', f'tmat_{file.stem}.txt') end_time = time.time() print(f'{file} was processed in {(end_time - start_time):.2f}s. \ \n{((end_time - loop_starts)/60):.2f} minutes have elapsed.')
#url = str(top_link[0]) # Can replace the previous few lines with: url = str([x.url for x in top][0]) # We'll only need the image's unique URL (i.e. after the last '/') # I'm going to use re.split('/', url) to get the file_name. file_name = split('/', url)[-1] # If there's no '.jpg', '.jpeg', or '.png' at the end of url, it's either an # album (which I don't want to deal with right now), a link to a website # (which I probably won't ever deal with), or a .gif, so we'll ignore it. if (file_name[-4:] not in ['.jpg', '.png'] and \ file_name[-4:] not in ['.jpeg']) or \ file_name == '' or '/' in file_name: ex(-1) """ Should fix this part to make it grab the next link, if possible. That is, until it runs out of links to grab [(num_subs)*(links_per_sub)]""" # Otherwise, the link should work, so we just download it to the wallpaper # folder and set the desktop background to it. # Make an opener to connect to the webpage to save the file file_saver = urllib2.build_opener() # Go to the page to get the image file_page = file_saver.open(url) # Read the picture into (binary) memory pic = file_page.read()
score_file = open(score_file_path, "w") score_file.truncate() score_file.close() ############################# # LOCATING GAME WINDOW ETC: # ############################# #pos = agu.locateOnScreen("Images/active.png") #if pos == None: pos = agu.locateOnScreen("Images/unactive.png") if pos == None: pos = agu.locateOnScreen("Images/gameover.png") if pos == None: pos = agu.locateOnScreen("Images/closetoedge.png") if pos == None: ex("Can't find Tetris window, try moving window away from edge. Aborting.") agu.moveTo(pos[0] - 30, pos[1] + 5) agu.click() pos = agu.locateOnScreen("Images/active.png") game_region = (pos[0] - 118, pos[1] + 55, 340, 318) initial_state = functions.Get_current_state(game_region) # img = agu.screenshot(region=game_region) # plt.imshow(np.array(img)) # plt.show() # ex("saddf") ############################# # Hyperparameters and shit: # ############################# actions = ["nothing", "up", "down", "left", "right", "space"]
assert args.accesstoken is not None, 'Could not read cached token.' # build image ID (name_tag) if args.imgID is not used if args.imgID is None: # if name and tag pair is given, join with an underscore if args.name is not None and args.tag is not None: args.imgID = args.name + '_' + args.tag # if only name is given, find most recent tag elif args.name is not None: args.imgID = args.name + '_' + singularitypy.get_newest_img_tag( args.name, args.accesstoken) # if nothing given, exit with error else: ex('One of three options must be provided: an image ID, a container name, or a container name and tag pair.' ) # build header and url header = {'Authorization': 'Bearer ' + args.accesstoken} filename = args.imgID + '.img.bz2' url = 'https://agave.iplantc.org/singularity/v2/quay.io/biocontainers/' + filename # get compressed file resp = get(url, headers=header, stream=True) assert resp.status_code == 200, 'Unable to download ' + args.imgID + '. HTTP status code ' + str( resp.status_code) # write file with open(filename, 'wb') as f: for chunk in resp: f.write(chunk)
def Prop(): print("\033[1;31 [+]Enter 1 To see in what directory u are : \n") print("\033[1;31 [+]Enter 2 For Installing django : \n") print("\033[1;31 [+]Enter 3 To see what django version \n") print("\033[1;31 [+]Enter 4 For starting a new project : \n") print("\033[1;31 [+]Enter 5 For starting a new application : \n") print("\033[1;31 [+]Enter 6 To apply migrates : \n") print("\033[1;31 [+]Enter 7 To Makemigration To an app : \n") print("\033[1;31 [+]Enter 8 To Make a super user : \n") print("\033[1;31 [+]Enter 9 To run the Server : \n") print("\033[1;31 [+]Enter 10 To exit the script : \n") choose = int(input("\033[1;34m] [+]Shoose One : ")) if choose == 1 : pwwd() sl(6) Prop() if choose == 2 : install_dj() sl(6) Prop() if choose == 3 : django_ver() sl(6) Prop() if choose == 4 : projet_nom = str(input("Choose a name for Your Project : ")) start_project(projet_nom) sl(6) Prop() if choose == 5 : print("please make sure to exit the script an to copy it into the prject file , then use it again to create apps and to run the server") print("Make sure to migrate after creating to application ...") app_nom = str(input("choose Your Application Name : ")) start_application(app_nom) sl(6) Prop() if choose == 7 : application_name = input("Please Enter The name of The application : ") mkmig(application_name) sl(6) Prop() if choose == 6 : apply_migrates() sl(6) Prop() if choose == 8 : super_user() sl(6) Prop() if choose == 9: run_server() sl(6) Prop() if choose == 10 : ex(0)
d=300 nc=1 nd=1 winner="Noone" firsttime=True pa=0 pb=0 run=False play=True while True: for e in pygame.event.get(): if e.type==QUIT: ex() if e.type==KEYDOWN : if e.key == K_x: ex() if e.key == K_f: FullScreen = not FullScreen if FullScreen: screen=pygame.display.set_mode((800,600), 0, 32) else: screen=pygame.display.set_mode((800,600), 0, 32) if e.key == K_DOWN: nq=1 ns=1 elif e.key == K_UP: if q>=60:
V(0., h2+i2-j2-k2, 2.*(ij+hk), 2.*(ik-hj)), \ V(0., 2.*(ij-hk), h2-i2+j2-k2, 2.*(jk+hi)), \ V(0., 2.*(ik+hj), 2.*(jk-hi), h2-i2-j2+k2)) if __name__=='__main__': print "===Beginning module point.py test suite===" print "origin=",origin a=P(1,2,3); b=P((2,3,4)); c=P([3,4,5]); d=P(V(4,5,6)) print tuple(repr(e) for e in (a,b,c,d)) a=P(1,1,2,3); b=P((1,2,3,4)); c=P([1,3,4,5]); d=P(V(1,4,5,6)) print tuple(repr(e) for e in (a,b,c,d)) b=P(1,(2,3,4)); c=P(2.0,[3,4,5]); d=P(0.0,V(4,5,6)) print tuple(repr(e) for e in (b,c,d)) from sys import exc_info as ex try: a=P(1,2,3,4,5) except: print 'Caught:',ex()[1:2] try: a=P(1) except: print 'Caught:',ex()[1:2] print "===__init__ tests complete===" print repr(a) print repr(-a),repr(a+(a-b)),abs(a) print repr(a-b),repr(a-(a-b)) print repr((a-b)-a),repr((a-b)+a) print a==a, a==b, a!=b, a!=a print a.p,a.infinite,a^b print repr(~c),repr(~d),c.p,d.p print c.infinite,d.infinite,c^d print "===class 'P' tests complete===" q=Q(1,2,3); i=Q(1,0,0) print q,i,'\n',q*i,i*q print i(q.d),q*q,q.d|q.d,'\n',q(i.d)
def log_critical(msg): t = datetime.now().strftime('%H:%M:%S') print '{head} {t} --> {msg}'.format(t=t, msg=msg, head=colored('CRITICAL:', 'red')) ex(-2)