max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
getdata.py
teejaytanmay/image_object_localization_flipkart
0
6614251
# coding: utf-8 from PIL import Image import numpy as np import pickle import pandas as pd def Normalize(image,mean,std): for channel in range(3): image[:,:,channel]=(image[:,:,channel]-mean[channel])/std[channel] return image id_to_data={} id_to_size={} imgs = pd.read_csv("/media/teejay/TJ HDD2/data/training.csv") images = imgs.image_name for i in range(64): path=images[i] image=Image.open("/media/teejay/TJ HDD2/data/images/"+path).convert('RGB') id_to_size[i]=np.array(image,dtype=np.float32).shape[0:2] # image=image.resize((224,224)) image=np.array(image,dtype=np.float32) # image=image/255 # image=Normalize(image,[0.485,0.456,0.406],[0.229,0.224,0.225]) id_to_data[i]=image l=list(id_to_data.values()) m=list(id_to_size.values()) id_to_data=np.array(l) id_to_size=np.array(m) f=open("/media/teejay/TJ HDD2/data/id_to_data","wb+") pickle.dump(id_to_data,f) f=open("/media/teejay/TJ HDD2/data/id_to_size","wb+") pickle.dump(id_to_size,f) # id_to_box={} # with open("./data/images.txt") as f: # lines=f.read().splitlines() # for line in lines: # id,path=line.split(" ",1) # image=Image.open("./data/images/"+path).convert('RGB') # id_to_size[int(id)]=np.array(image,dtype=np.float32).shape[0:2] # image=image.resize((224,224)) # image=np.array(image,dtype=np.float32) # image=image/255 # image=Normalize(image,[0.485,0.456,0.406],[0.229,0.224,0.225]) # id_to_data[int(id)]=image # id_to_data=np.array(list(id_to_data.values())) # id_to_size=np.array(list(id_to_size.values())) # f=open("./id_to_data","wb+") # pickle.dump(id_to_data,f,protocol=4) # f=open("./id_to_size","wb+") # pickle.dump(id_to_size,f,protocol=4) id_to_box={} # print (id_to_size.shape[0]) # for i in range(id_to_size.shape[0]): imgs.x1 = imgs.x1/id_to_size[1][1] imgs.x2 = imgs.x2/id_to_size[0][0] imgs.y1 = imgs.y1/id_to_size[1][1] imgs.y2 = imgs.y2/id_to_size[0][0] for i in range(id_to_size.shape[0]): id_to_box[i] = np.array([imgs.x1[i],imgs.x2[i],imgs.y1[i],imgs.y2[i]]) # imgs.head(5) # with open("./data/bounding_boxes.txt") as f: # lines=f.read().splitlines() # for line in lines: # id,box=line.split(" ",1) # box=np.array([float(i) for i in box.split(" ")],dtype=np.float32) # box[0]=box[0]/id_to_size[int(id)-1][1]*224 # box[1]=box[1]/id_to_size[int(id)-1][0]*224 # box[2]=box[2]/id_to_size[int(id)-1][1]*224 # box[3]=box[3]/id_to_size[int(id)-1][0]*224 # id_to_box[int(id)]=box n=list(id_to_box.values()) id_to_box=np.array(n) f=open("/media/teejay/TJ HDD2/data/id_to_box","wb+") pickle.dump(id_to_box,f) # id_to_box=np.array(list(id_to_box.values())) # f=open("./id_to_box","wb+") # pickle.dump(id_to_box,f,protocol=4)
# coding: utf-8 from PIL import Image import numpy as np import pickle import pandas as pd def Normalize(image,mean,std): for channel in range(3): image[:,:,channel]=(image[:,:,channel]-mean[channel])/std[channel] return image id_to_data={} id_to_size={} imgs = pd.read_csv("/media/teejay/TJ HDD2/data/training.csv") images = imgs.image_name for i in range(64): path=images[i] image=Image.open("/media/teejay/TJ HDD2/data/images/"+path).convert('RGB') id_to_size[i]=np.array(image,dtype=np.float32).shape[0:2] # image=image.resize((224,224)) image=np.array(image,dtype=np.float32) # image=image/255 # image=Normalize(image,[0.485,0.456,0.406],[0.229,0.224,0.225]) id_to_data[i]=image l=list(id_to_data.values()) m=list(id_to_size.values()) id_to_data=np.array(l) id_to_size=np.array(m) f=open("/media/teejay/TJ HDD2/data/id_to_data","wb+") pickle.dump(id_to_data,f) f=open("/media/teejay/TJ HDD2/data/id_to_size","wb+") pickle.dump(id_to_size,f) # id_to_box={} # with open("./data/images.txt") as f: # lines=f.read().splitlines() # for line in lines: # id,path=line.split(" ",1) # image=Image.open("./data/images/"+path).convert('RGB') # id_to_size[int(id)]=np.array(image,dtype=np.float32).shape[0:2] # image=image.resize((224,224)) # image=np.array(image,dtype=np.float32) # image=image/255 # image=Normalize(image,[0.485,0.456,0.406],[0.229,0.224,0.225]) # id_to_data[int(id)]=image # id_to_data=np.array(list(id_to_data.values())) # id_to_size=np.array(list(id_to_size.values())) # f=open("./id_to_data","wb+") # pickle.dump(id_to_data,f,protocol=4) # f=open("./id_to_size","wb+") # pickle.dump(id_to_size,f,protocol=4) id_to_box={} # print (id_to_size.shape[0]) # for i in range(id_to_size.shape[0]): imgs.x1 = imgs.x1/id_to_size[1][1] imgs.x2 = imgs.x2/id_to_size[0][0] imgs.y1 = imgs.y1/id_to_size[1][1] imgs.y2 = imgs.y2/id_to_size[0][0] for i in range(id_to_size.shape[0]): id_to_box[i] = np.array([imgs.x1[i],imgs.x2[i],imgs.y1[i],imgs.y2[i]]) # imgs.head(5) # with open("./data/bounding_boxes.txt") as f: # lines=f.read().splitlines() # for line in lines: # id,box=line.split(" ",1) # box=np.array([float(i) for i in box.split(" ")],dtype=np.float32) # box[0]=box[0]/id_to_size[int(id)-1][1]*224 # box[1]=box[1]/id_to_size[int(id)-1][0]*224 # box[2]=box[2]/id_to_size[int(id)-1][1]*224 # box[3]=box[3]/id_to_size[int(id)-1][0]*224 # id_to_box[int(id)]=box n=list(id_to_box.values()) id_to_box=np.array(n) f=open("/media/teejay/TJ HDD2/data/id_to_box","wb+") pickle.dump(id_to_box,f) # id_to_box=np.array(list(id_to_box.values())) # f=open("./id_to_box","wb+") # pickle.dump(id_to_box,f,protocol=4)
en
0.313772
# coding: utf-8 # image=image.resize((224,224)) # image=image/255 # image=Normalize(image,[0.485,0.456,0.406],[0.229,0.224,0.225]) # id_to_box={} # with open("./data/images.txt") as f: # lines=f.read().splitlines() # for line in lines: # id,path=line.split(" ",1) # image=Image.open("./data/images/"+path).convert('RGB') # id_to_size[int(id)]=np.array(image,dtype=np.float32).shape[0:2] # image=image.resize((224,224)) # image=np.array(image,dtype=np.float32) # image=image/255 # image=Normalize(image,[0.485,0.456,0.406],[0.229,0.224,0.225]) # id_to_data[int(id)]=image # id_to_data=np.array(list(id_to_data.values())) # id_to_size=np.array(list(id_to_size.values())) # f=open("./id_to_data","wb+") # pickle.dump(id_to_data,f,protocol=4) # f=open("./id_to_size","wb+") # pickle.dump(id_to_size,f,protocol=4) # print (id_to_size.shape[0]) # for i in range(id_to_size.shape[0]): # imgs.head(5) # with open("./data/bounding_boxes.txt") as f: # lines=f.read().splitlines() # for line in lines: # id,box=line.split(" ",1) # box=np.array([float(i) for i in box.split(" ")],dtype=np.float32) # box[0]=box[0]/id_to_size[int(id)-1][1]*224 # box[1]=box[1]/id_to_size[int(id)-1][0]*224 # box[2]=box[2]/id_to_size[int(id)-1][1]*224 # box[3]=box[3]/id_to_size[int(id)-1][0]*224 # id_to_box[int(id)]=box # id_to_box=np.array(list(id_to_box.values())) # f=open("./id_to_box","wb+") # pickle.dump(id_to_box,f,protocol=4)
2.738078
3
make_word_list.py
schufo/lyrics-aligner
2
6614252
<filename>make_word_list.py """ Generates a .txt-file with all unique words in a dataset. This .txt/file can be used to translate words into phoneme sequences with the CMU pronunciation dictionary (http://www.speech.cs.cmu.edu/tools/lextool.html) """ import argparse import os import glob parser = argparse.ArgumentParser(description='Word list generation') parser.add_argument('lyrics', type=str, help='path to a directory with lyrics stored in .txt-files') parser.add_argument('--dataset-name', type=str, default='dataset1') args = parser.parse_args() unique_words = set() lyrics_files = glob.glob(os.path.join(args.lyrics, '*.txt')) assert len(lyrics_files) > 0, 'No .txt-files found in {}'.format(args.lyrics) # go through .txt-files and save unique words in the unique_words set for file in lyrics_files: with open(file) as word_file: lines = word_file.readlines() for line in lines: line = line.lower().replace('\n', '').replace('’', "'") clean_line = ''.join(c for c in line if c.isalnum() or c in ["'", ' ']) if clean_line == ' ' or clean_line == '': continue words = clean_line.split(' ') for word in words: unique_words.add(word) unique_words.remove('') # create .txt-file word_file_path = 'files/{}_word_list.txt'.format(args.dataset_name) assert not os.path.isfile(word_file_path), 'file {} exists already. Delete or choose different' \ ' file to avoid appending to existing file'.format(word_file_path) # write words in .txt-file words_file = open(word_file_path, 'a') for word in sorted(unique_words): words_file.write(word + '\n') words_file.close() # create empty .txt-file which will contain the output of the CMU pronuciation dictionary. empty_file_path = 'files/{}_word2phonemes.txt'.format(args.dataset_name) empty_file = open(empty_file_path, 'a') empty_file.write('') empty_file.close()
<filename>make_word_list.py """ Generates a .txt-file with all unique words in a dataset. This .txt/file can be used to translate words into phoneme sequences with the CMU pronunciation dictionary (http://www.speech.cs.cmu.edu/tools/lextool.html) """ import argparse import os import glob parser = argparse.ArgumentParser(description='Word list generation') parser.add_argument('lyrics', type=str, help='path to a directory with lyrics stored in .txt-files') parser.add_argument('--dataset-name', type=str, default='dataset1') args = parser.parse_args() unique_words = set() lyrics_files = glob.glob(os.path.join(args.lyrics, '*.txt')) assert len(lyrics_files) > 0, 'No .txt-files found in {}'.format(args.lyrics) # go through .txt-files and save unique words in the unique_words set for file in lyrics_files: with open(file) as word_file: lines = word_file.readlines() for line in lines: line = line.lower().replace('\n', '').replace('’', "'") clean_line = ''.join(c for c in line if c.isalnum() or c in ["'", ' ']) if clean_line == ' ' or clean_line == '': continue words = clean_line.split(' ') for word in words: unique_words.add(word) unique_words.remove('') # create .txt-file word_file_path = 'files/{}_word_list.txt'.format(args.dataset_name) assert not os.path.isfile(word_file_path), 'file {} exists already. Delete or choose different' \ ' file to avoid appending to existing file'.format(word_file_path) # write words in .txt-file words_file = open(word_file_path, 'a') for word in sorted(unique_words): words_file.write(word + '\n') words_file.close() # create empty .txt-file which will contain the output of the CMU pronuciation dictionary. empty_file_path = 'files/{}_word2phonemes.txt'.format(args.dataset_name) empty_file = open(empty_file_path, 'a') empty_file.write('') empty_file.close()
en
0.752932
Generates a .txt-file with all unique words in a dataset. This .txt/file can be used to translate words into phoneme sequences with the CMU pronunciation dictionary (http://www.speech.cs.cmu.edu/tools/lextool.html) # go through .txt-files and save unique words in the unique_words set # create .txt-file # write words in .txt-file # create empty .txt-file which will contain the output of the CMU pronuciation dictionary.
3.710906
4
Courses/Udacity/CS101/Lesson_2.5_How_To_Solve_Problems/21-Define_nextDay/supplied/studentMain.py
leparrav/Playground
1
6614253
# By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Compensate for leap days. # Assume that the birthday and current date are correct dates (and no time travel). # Simply put, if you were born 1 Jan 2012 and todays date is 2 Jan 2012 # you are 1 day old. # # Hint # A whole year is 365 days, 366 if a leap year. def nextDay(year, month, day): """ Returns the year, month, day of the next day. Simple version: assume every month has 30 days. """ # YOUR CODE HERE return
# By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Compensate for leap days. # Assume that the birthday and current date are correct dates (and no time travel). # Simply put, if you were born 1 Jan 2012 and todays date is 2 Jan 2012 # you are 1 day old. # # Hint # A whole year is 365 days, 366 if a leap year. def nextDay(year, month, day): """ Returns the year, month, day of the next day. Simple version: assume every month has 30 days. """ # YOUR CODE HERE return
en
0.938688
# By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Compensate for leap days. # Assume that the birthday and current date are correct dates (and no time travel). # Simply put, if you were born 1 Jan 2012 and todays date is 2 Jan 2012 # you are 1 day old. # # Hint # A whole year is 365 days, 366 if a leap year. Returns the year, month, day of the next day. Simple version: assume every month has 30 days. # YOUR CODE HERE
4.069884
4
pytorch_privacy/analysis/online_accountant.py
MJHutchinson/PytorchPrivacy
2
6614254
class OnlineAccountant(object): """ A class to perform accounting in an online manner to speed up experiments. requires an accountancy method to have an online method. """ def __init__(self, accountancy_update_method, ledger=None, accountancy_parameters=None): """ :param accountancy_update_method: A method to compute the desired accountancy in and online fashion. Should take as parameters some list of new privacy queries to update the privacy for, and some tracking variable specific to the method (E.g. log moments for the moment accountant). This method should fuction if the tracking variable are None. :param ledger: Some initial ledger. May be None :param accountancy_parameters: Some parameters to pass to the accountancy update method. E.g. the target epsilon or delta, maximum log moment... """ self._accountancy_update_method = accountancy_update_method self._accountancy_parameters = accountancy_parameters self._ledger = [] self._tracking_parameters = None self._position = 0 if ledger is None: ledger = [] self._privacy_bound = self.update_privacy(ledger) def update_privacy(self, incremented_ledger): """ Update the current privacy bound using new additions to the ledger. :param incremented_ledger: The new ledger. Assumes that the only differences from previously seen ledger is the new entries. This should be of the formatted ledger type. :return: The new privacy bound. """ self._ledger = incremented_ledger new_entries = self._ledger[self._position:] self._privacy_bound, self._tracking_parameters = self._accountancy_update_method( new_entries, self._tracking_parameters, **self._accountancy_parameters ) self._position = len(self._ledger) return self._privacy_bound @property def privacy_bound(self): return self._privacy_bound
class OnlineAccountant(object): """ A class to perform accounting in an online manner to speed up experiments. requires an accountancy method to have an online method. """ def __init__(self, accountancy_update_method, ledger=None, accountancy_parameters=None): """ :param accountancy_update_method: A method to compute the desired accountancy in and online fashion. Should take as parameters some list of new privacy queries to update the privacy for, and some tracking variable specific to the method (E.g. log moments for the moment accountant). This method should fuction if the tracking variable are None. :param ledger: Some initial ledger. May be None :param accountancy_parameters: Some parameters to pass to the accountancy update method. E.g. the target epsilon or delta, maximum log moment... """ self._accountancy_update_method = accountancy_update_method self._accountancy_parameters = accountancy_parameters self._ledger = [] self._tracking_parameters = None self._position = 0 if ledger is None: ledger = [] self._privacy_bound = self.update_privacy(ledger) def update_privacy(self, incremented_ledger): """ Update the current privacy bound using new additions to the ledger. :param incremented_ledger: The new ledger. Assumes that the only differences from previously seen ledger is the new entries. This should be of the formatted ledger type. :return: The new privacy bound. """ self._ledger = incremented_ledger new_entries = self._ledger[self._position:] self._privacy_bound, self._tracking_parameters = self._accountancy_update_method( new_entries, self._tracking_parameters, **self._accountancy_parameters ) self._position = len(self._ledger) return self._privacy_bound @property def privacy_bound(self): return self._privacy_bound
en
0.782924
A class to perform accounting in an online manner to speed up experiments. requires an accountancy method to have an online method. :param accountancy_update_method: A method to compute the desired accountancy in and online fashion. Should take as parameters some list of new privacy queries to update the privacy for, and some tracking variable specific to the method (E.g. log moments for the moment accountant). This method should fuction if the tracking variable are None. :param ledger: Some initial ledger. May be None :param accountancy_parameters: Some parameters to pass to the accountancy update method. E.g. the target epsilon or delta, maximum log moment... Update the current privacy bound using new additions to the ledger. :param incremented_ledger: The new ledger. Assumes that the only differences from previously seen ledger is the new entries. This should be of the formatted ledger type. :return: The new privacy bound.
3.669649
4
Motospeed-ck62/f5.py
godrix/motospeed-ck62-fix-key
0
6614255
keyboard.send_key("<f5>")
keyboard.send_key("<f5>")
none
1
1.167948
1
tests/test_alldistinct.py
Abhisheknishant/iteration_utilities
0
6614256
<gh_stars>0 # Licensed under Apache License Version 2.0 - see LICENSE import pytest from iteration_utilities import all_distinct import helper_funcs as _hf from helper_cls import T def test_alldistinct_empty1(): assert all_distinct([]) def test_alldistinct_normal1(): assert all_distinct([T(1), T(2), T(3)]) def test_alldistinct_normal2(): assert not all_distinct([T(1), T(1), T(1)]) def test_alldistinct_normal3(): # generator assert all_distinct((i for i in [T(1), T(2), T(3)])) def test_alldistinct_unhashable1(): assert all_distinct([{T('a'): T(1)}, {T('a'): T(2)}]) def test_alldistinct_unhashable2(): assert not all_distinct([{T('a'): T(1)}, {T('a'): T(1)}]) def test_alldistinct_failure1(): with pytest.raises(_hf.FailIter.EXC_TYP, match= _hf.FailIter.EXC_MSG): all_distinct(_hf.FailIter()) def test_alldistinct_failure2(): # Test that a failing iterator doesn't raise a SystemError with pytest.raises(_hf.FailNext.EXC_TYP, match=_hf.FailNext.EXC_MSG): all_distinct(_hf.FailNext()) def test_alldistinct_failure3(): # Failure when comparing the object to the objects in the list with pytest.raises(_hf.FailEqNoHash.EXC_TYP, match=_hf.FailEqNoHash.EXC_MSG): all_distinct([[T(1)], _hf.FailEqNoHash()]) def test_alldistinct_failure4(): # Failure (no TypeError) when trying to hash the value with pytest.raises(_hf.FailHash.EXC_TYP, match=_hf.FailHash.EXC_MSG): all_distinct([T(1), _hf.FailHash()]) @_hf.skip_on_pypy_because_cache_next_works_differently def test_alldistinct_failure5(): # Changing next method with pytest.raises(_hf.CacheNext.EXC_TYP, match=_hf.CacheNext.EXC_MSG): all_distinct(_hf.CacheNext(1))
# Licensed under Apache License Version 2.0 - see LICENSE import pytest from iteration_utilities import all_distinct import helper_funcs as _hf from helper_cls import T def test_alldistinct_empty1(): assert all_distinct([]) def test_alldistinct_normal1(): assert all_distinct([T(1), T(2), T(3)]) def test_alldistinct_normal2(): assert not all_distinct([T(1), T(1), T(1)]) def test_alldistinct_normal3(): # generator assert all_distinct((i for i in [T(1), T(2), T(3)])) def test_alldistinct_unhashable1(): assert all_distinct([{T('a'): T(1)}, {T('a'): T(2)}]) def test_alldistinct_unhashable2(): assert not all_distinct([{T('a'): T(1)}, {T('a'): T(1)}]) def test_alldistinct_failure1(): with pytest.raises(_hf.FailIter.EXC_TYP, match= _hf.FailIter.EXC_MSG): all_distinct(_hf.FailIter()) def test_alldistinct_failure2(): # Test that a failing iterator doesn't raise a SystemError with pytest.raises(_hf.FailNext.EXC_TYP, match=_hf.FailNext.EXC_MSG): all_distinct(_hf.FailNext()) def test_alldistinct_failure3(): # Failure when comparing the object to the objects in the list with pytest.raises(_hf.FailEqNoHash.EXC_TYP, match=_hf.FailEqNoHash.EXC_MSG): all_distinct([[T(1)], _hf.FailEqNoHash()]) def test_alldistinct_failure4(): # Failure (no TypeError) when trying to hash the value with pytest.raises(_hf.FailHash.EXC_TYP, match=_hf.FailHash.EXC_MSG): all_distinct([T(1), _hf.FailHash()]) @_hf.skip_on_pypy_because_cache_next_works_differently def test_alldistinct_failure5(): # Changing next method with pytest.raises(_hf.CacheNext.EXC_TYP, match=_hf.CacheNext.EXC_MSG): all_distinct(_hf.CacheNext(1))
en
0.799902
# Licensed under Apache License Version 2.0 - see LICENSE # generator # Test that a failing iterator doesn't raise a SystemError # Failure when comparing the object to the objects in the list # Failure (no TypeError) when trying to hash the value # Changing next method
2.304506
2
djskeletor/dashboard/urls.py
carthagecollege/django-djskeletor
0
6614257
# -*- coding: utf-8 -*- """URLs for all views.""" from django.urls import path from djskeletor.dashboard import views urlpatterns = [ path( 'search/', views.search, name='dashboard_search' ), path('', views.home, name='home'), ]
# -*- coding: utf-8 -*- """URLs for all views.""" from django.urls import path from djskeletor.dashboard import views urlpatterns = [ path( 'search/', views.search, name='dashboard_search' ), path('', views.home, name='home'), ]
en
0.836984
# -*- coding: utf-8 -*- URLs for all views.
1.639342
2
chapter-05/Exercise_5_6.py
yuetsin/CS-902
1
6614258
# Exercise 5.6 from Tkinter import * root = Tk() c = Canvas(root, width=550, height=400, bg='gray') c.pack() centralPoint = (300, 175) colors = ['yellow', 'red', 'blue', 'black', 'white'] i = 0 while i < 5: c.create_oval(275 - i * 20, 275 - i * 20, 200 + i * 20, 200 + i * 20, fill='', outline=colors[i], width=8) i += 1 root.mainloop()
# Exercise 5.6 from Tkinter import * root = Tk() c = Canvas(root, width=550, height=400, bg='gray') c.pack() centralPoint = (300, 175) colors = ['yellow', 'red', 'blue', 'black', 'white'] i = 0 while i < 5: c.create_oval(275 - i * 20, 275 - i * 20, 200 + i * 20, 200 + i * 20, fill='', outline=colors[i], width=8) i += 1 root.mainloop()
en
0.767826
# Exercise 5.6
3.505714
4
dobby/examples/passwordinput.py
gabrielcsapo/dobby
0
6614259
import dobby class Graze(dobby.App): def startup(self): main_container = dobby.Container() main_password = dobby.PasswordInput(placeholder="Password") main_container.add(main_password) main_container.constrain(main_password.TOP == main_container.TOP + 5) main_container.constrain(main_password.RIGHT == main_container.RIGHT - 5) main_container.constrain(main_password.LEFT == main_container.LEFT + 5) app.main_window.content = main_container if __name__ == '__main__': app = Graze('Graze', 'org.pybee.graze') app.main_loop()
import dobby class Graze(dobby.App): def startup(self): main_container = dobby.Container() main_password = dobby.PasswordInput(placeholder="Password") main_container.add(main_password) main_container.constrain(main_password.TOP == main_container.TOP + 5) main_container.constrain(main_password.RIGHT == main_container.RIGHT - 5) main_container.constrain(main_password.LEFT == main_container.LEFT + 5) app.main_window.content = main_container if __name__ == '__main__': app = Graze('Graze', 'org.pybee.graze') app.main_loop()
none
1
2.583961
3
gpugwas/viz.py
VibhuJawa/GPU-GWAS
4
6614260
#!/opt/conda/envs/rapids/bin/python """ Pre-reqs: --------- /opt/conda/envs/rapids/bin/pip install \ dash \ jupyter-dash \ dash_bootstrap_components \ dash_core_components \ dash_html_components """ import os import cudf import plotly.graph_objects as go import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html # from dash.dependencies import Input, Output, State, ALL # from plotly.offline import init_notebook_mode # init_notebook_mode(connected = True) EXT_STYLES = ['https://codepen.io/chriddyp/pen/bWLwgP.css', dbc.themes.BOOTSTRAP] class ManhattanPlot: def __init__(self, qq_spec, manhattan_spec, fig_path=None): self.app = dash.Dash( __name__, external_stylesheets=EXT_STYLES) self.qq_spec = qq_spec self.manhattan_spec = manhattan_spec self.fig_path = fig_path self.app.layout, self.manhattan_figure = self._construct() def start(self, host=None, port=5000): return self.app.run_server( debug=False, use_reloader=False, host=host, port=port) def _construct_qq(self): x_values = self.qq_spec['df'][self.qq_spec['x_axis']] y_values = self.qq_spec['df'][self.qq_spec['y_axis']] x_max = float(x_values.max()) y_max = float(y_values.max()) scatter_marker = go.Scattergl({ 'x': self.qq_spec['df'][self.qq_spec['x_axis']].to_array(), 'y': y_values.to_array(), 'mode': 'markers', 'marker': { 'size': 2, 'color': '#406278', }, }) scatter_line = go.Scattergl({ 'x': [0, x_max], 'y': [0, y_max], 'mode': 'lines', 'line': { 'width': 2, 'color': 'orange', }, }) scatter_fig = go.Figure( data = [scatter_marker, scatter_line], layout = { 'title': 'Q-Q Plot', 'showlegend': False, 'grid': { 'columns' : 1, }, }) return scatter_fig def _construct_manhatten(self): chroms = self.manhattan_spec['df'][self.manhattan_spec['group_by']].unique().to_array() start_position = -0.5 scatter_traces = [] for chrom in chroms: query = '%s == %s' % (self.manhattan_spec['group_by'], chrom) cdf = self.manhattan_spec['df'].query(query) x_array = cdf[self.manhattan_spec['x_axis']] + start_position scatter_trace = go.Scattergl({ 'x': x_array.to_array(), 'y': cdf[self.manhattan_spec['y_axis']].to_array(), 'name': 'Chromosome ' + str(chrom), 'mode': 'markers', 'marker': { 'size': 2, 'color': '#406278' if (start_position - 0.5) % 2 == 0 else '#e32636', }, }) scatter_traces.append(scatter_trace) start_position += 1 manhattan_fig = go.Figure( data = scatter_traces, layout = { 'title': 'GWAS Manhattan Plot', 'showlegend': False, 'grid': { 'columns' : 1, }, 'xaxis': { 'showgrid': False, 'gridwidth': 1, 'ticks': 'outside', 'zeroline': False, 'tickvals': [t for t in range(int(start_position + 0.5))], 'ticktext': [str(t) for t in chroms], }}) # plotly.offline.iplot({ "data": manhattan_fig, "layout": go.Layout(title="Sine wave")}) return manhattan_fig def _construct(self): manhattan_fig = self._construct_manhatten() # qq_plot_fig = self._construct_qq() if self.fig_path: manhattan_fig.write_html( os.path.join(self.fig_path, "manhattan.html")) #qq_plot_fig.write_html( # os.path.join(self.fig_path, "qq_plot.html")) layout = html.Div([ html.Div( children=[ dcc.Markdown( """ **GWAS** """), # html.Div([dcc.Graph(id='qq_plot_fig', figure=qq_plot_fig),]), html.Div([dcc.Graph(id='manhattan-figure', figure=manhattan_fig),]), ]), ]) return layout, manhattan_fig#, qq_plot_fig def main(): df = cudf.read_csv('./data/data.csv') qq_spec = {} qq_spec['df'] = df qq_spec['x_axis'] = 'P' qq_spec['y_axis'] = 'ZSCORE' manhattan_spec = {} manhattan_spec['df'] = df manhattan_spec['group_by'] = 'CHR' manhattan_spec['x_axis'] = 'P' manhattan_spec['y_axis'] = 'ZSCORE' fig_path = None plot = ManhattanPlot(qq_spec, manhattan_spec, fig_path) plot.start() if __name__=='__main__': main()
#!/opt/conda/envs/rapids/bin/python """ Pre-reqs: --------- /opt/conda/envs/rapids/bin/pip install \ dash \ jupyter-dash \ dash_bootstrap_components \ dash_core_components \ dash_html_components """ import os import cudf import plotly.graph_objects as go import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html # from dash.dependencies import Input, Output, State, ALL # from plotly.offline import init_notebook_mode # init_notebook_mode(connected = True) EXT_STYLES = ['https://codepen.io/chriddyp/pen/bWLwgP.css', dbc.themes.BOOTSTRAP] class ManhattanPlot: def __init__(self, qq_spec, manhattan_spec, fig_path=None): self.app = dash.Dash( __name__, external_stylesheets=EXT_STYLES) self.qq_spec = qq_spec self.manhattan_spec = manhattan_spec self.fig_path = fig_path self.app.layout, self.manhattan_figure = self._construct() def start(self, host=None, port=5000): return self.app.run_server( debug=False, use_reloader=False, host=host, port=port) def _construct_qq(self): x_values = self.qq_spec['df'][self.qq_spec['x_axis']] y_values = self.qq_spec['df'][self.qq_spec['y_axis']] x_max = float(x_values.max()) y_max = float(y_values.max()) scatter_marker = go.Scattergl({ 'x': self.qq_spec['df'][self.qq_spec['x_axis']].to_array(), 'y': y_values.to_array(), 'mode': 'markers', 'marker': { 'size': 2, 'color': '#406278', }, }) scatter_line = go.Scattergl({ 'x': [0, x_max], 'y': [0, y_max], 'mode': 'lines', 'line': { 'width': 2, 'color': 'orange', }, }) scatter_fig = go.Figure( data = [scatter_marker, scatter_line], layout = { 'title': 'Q-Q Plot', 'showlegend': False, 'grid': { 'columns' : 1, }, }) return scatter_fig def _construct_manhatten(self): chroms = self.manhattan_spec['df'][self.manhattan_spec['group_by']].unique().to_array() start_position = -0.5 scatter_traces = [] for chrom in chroms: query = '%s == %s' % (self.manhattan_spec['group_by'], chrom) cdf = self.manhattan_spec['df'].query(query) x_array = cdf[self.manhattan_spec['x_axis']] + start_position scatter_trace = go.Scattergl({ 'x': x_array.to_array(), 'y': cdf[self.manhattan_spec['y_axis']].to_array(), 'name': 'Chromosome ' + str(chrom), 'mode': 'markers', 'marker': { 'size': 2, 'color': '#406278' if (start_position - 0.5) % 2 == 0 else '#e32636', }, }) scatter_traces.append(scatter_trace) start_position += 1 manhattan_fig = go.Figure( data = scatter_traces, layout = { 'title': 'GWAS Manhattan Plot', 'showlegend': False, 'grid': { 'columns' : 1, }, 'xaxis': { 'showgrid': False, 'gridwidth': 1, 'ticks': 'outside', 'zeroline': False, 'tickvals': [t for t in range(int(start_position + 0.5))], 'ticktext': [str(t) for t in chroms], }}) # plotly.offline.iplot({ "data": manhattan_fig, "layout": go.Layout(title="Sine wave")}) return manhattan_fig def _construct(self): manhattan_fig = self._construct_manhatten() # qq_plot_fig = self._construct_qq() if self.fig_path: manhattan_fig.write_html( os.path.join(self.fig_path, "manhattan.html")) #qq_plot_fig.write_html( # os.path.join(self.fig_path, "qq_plot.html")) layout = html.Div([ html.Div( children=[ dcc.Markdown( """ **GWAS** """), # html.Div([dcc.Graph(id='qq_plot_fig', figure=qq_plot_fig),]), html.Div([dcc.Graph(id='manhattan-figure', figure=manhattan_fig),]), ]), ]) return layout, manhattan_fig#, qq_plot_fig def main(): df = cudf.read_csv('./data/data.csv') qq_spec = {} qq_spec['df'] = df qq_spec['x_axis'] = 'P' qq_spec['y_axis'] = 'ZSCORE' manhattan_spec = {} manhattan_spec['df'] = df manhattan_spec['group_by'] = 'CHR' manhattan_spec['x_axis'] = 'P' manhattan_spec['y_axis'] = 'ZSCORE' fig_path = None plot = ManhattanPlot(qq_spec, manhattan_spec, fig_path) plot.start() if __name__=='__main__': main()
en
0.462285
#!/opt/conda/envs/rapids/bin/python Pre-reqs: --------- /opt/conda/envs/rapids/bin/pip install \ dash \ jupyter-dash \ dash_bootstrap_components \ dash_core_components \ dash_html_components # from dash.dependencies import Input, Output, State, ALL # from plotly.offline import init_notebook_mode # init_notebook_mode(connected = True) # plotly.offline.iplot({ "data": manhattan_fig, "layout": go.Layout(title="Sine wave")}) # qq_plot_fig = self._construct_qq() #qq_plot_fig.write_html( # os.path.join(self.fig_path, "qq_plot.html")) **GWAS** # html.Div([dcc.Graph(id='qq_plot_fig', figure=qq_plot_fig),]), #, qq_plot_fig
2.313073
2
pyzmq/perf/perf.py
Surfndez/source-publish
0
6614261
#!/usr/bin/env python # coding: utf-8 # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. # # Some original test code Copyright (c) 2007-2010 iMatix Corporation, # Used under LGPLv3 import argparse from multiprocessing import Process import time try: now = time.monotonic except AttributeError: now = time.time import zmq def parse_args(argv=None): parser = argparse.ArgumentParser(description='Run a zmq performance test') parser.add_argument('-p', '--poll', action='store_true', help='use a zmq Poller instead of raw send/recv') parser.add_argument('-c', '--copy', action='store_true', help='copy messages instead of using zero-copy') parser.add_argument('-s', '--size', type=int, default=10240, help='size (in bytes) of the test message') parser.add_argument('-n', '--count', type=int, default=10240, help='number of test messages to send') parser.add_argument('--url', dest='url', type=str, default='tcp://127.0.0.1:5555', help='the zmq URL on which to run the test') parser.add_argument(dest='test', type=str, default='lat', choices=['lat', 'thr'], help='which test to run') return parser.parse_args(argv) def latency_echo(url, count, poll, copy): """echo messages on a REP socket Should be started before `latency` """ ctx = zmq.Context() s = ctx.socket(zmq.REP) if poll: p = zmq.Poller() p.register(s) s.bind(url) block = zmq.NOBLOCK if poll else 0 for i in range(count): if poll: res = p.poll() msg = s.recv(block, copy=copy) if poll: res = p.poll() s.send(msg, block, copy=copy) msg = s.recv() assert msg == b'done' s.close() ctx.term() def latency(url, count, size, poll, copy): """Perform a latency test""" ctx = zmq.Context() s = ctx.socket(zmq.REQ) s.setsockopt(zmq.LINGER, -1) s.connect(url) if poll: p = zmq.Poller() p.register(s) msg = b' ' * size block = zmq.NOBLOCK if poll else 0 time.sleep(1) start = now() for i in range (0, count): if poll: res = p.poll() assert(res[0][1] & zmq.POLLOUT) s.send(msg, block, copy=copy) if poll: res = p.poll() assert(res[0][1] & zmq.POLLIN) msg = s.recv(block, copy=copy) assert len(msg) == size elapsed = now() - start s.send(b'done') latency = 1e6 * elapsed / (count * 2.) print ("message size : %8i [B]" % (size, )) print ("roundtrip count: %8i [msgs]" % (count, )) print ("mean latency : %12.3f [µs]" % (latency, )) print ("test time : %12.3f [s]" % (elapsed, )) def pusher(url, count, size, poll, copy): """send a bunch of messages on a PUSH socket""" ctx = zmq.Context() s = ctx.socket(zmq.PUSH) # Add your socket options here. # For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. if poll: p = zmq.Poller() p.register(s) s.connect(url) msg = zmq.Message(b' ' * size) block = zmq.NOBLOCK if poll else 0 for i in range(count): if poll: res = p.poll() assert(res[0][1] & zmq.POLLOUT) s.send(msg, block, copy=copy) s.close() ctx.term() def throughput(url, count, size, poll, copy): """recv a bunch of messages on a PULL socket Should be started before `pusher` """ ctx = zmq.Context() s = ctx.socket(zmq.PULL) # Add your socket options here. # For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. if poll: p = zmq.Poller() p.register(s) s.bind(url) block = zmq.NOBLOCK if poll else 0 # Wait for the other side to connect. msg = s.recv() assert len (msg) == size start = now() for i in range (count-1): if poll: res = p.poll() msg = s.recv(block, copy=copy) elapsed = now() - start throughput = (float(count)) / float(elapsed) megabits = float(throughput * size * 8) / 1e6 print ("message size : %8i [B]" % (size, )) print ("message count : %8i [msgs]" % (count, )) print ("mean throughput: %8.0f [msg/s]" % (throughput, )) print ("mean throughput: %12.3f [Mb/s]" % (megabits, )) print ("test time : %12.3f [s]" % (elapsed, )) def main(): args = parse_args() tic = time.time() if args.test == 'lat': bg = Process(target=latency_echo, args=(args.url, args.count, args.poll, args.copy)) bg.start() latency(args.url, args.count, args.size, args.poll, args.copy) elif args.test == 'thr': bg = Process(target=throughput, args=(args.url, args.count, args.size, args.poll, args.copy)) bg.start() pusher(args.url, args.count, args.size, args.poll, args.copy) bg.join() toc = time.time() if (toc - tic) < 3: print ("For best results, tests should take at least a few seconds.") if __name__ == '__main__': main()
#!/usr/bin/env python # coding: utf-8 # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. # # Some original test code Copyright (c) 2007-2010 iMatix Corporation, # Used under LGPLv3 import argparse from multiprocessing import Process import time try: now = time.monotonic except AttributeError: now = time.time import zmq def parse_args(argv=None): parser = argparse.ArgumentParser(description='Run a zmq performance test') parser.add_argument('-p', '--poll', action='store_true', help='use a zmq Poller instead of raw send/recv') parser.add_argument('-c', '--copy', action='store_true', help='copy messages instead of using zero-copy') parser.add_argument('-s', '--size', type=int, default=10240, help='size (in bytes) of the test message') parser.add_argument('-n', '--count', type=int, default=10240, help='number of test messages to send') parser.add_argument('--url', dest='url', type=str, default='tcp://127.0.0.1:5555', help='the zmq URL on which to run the test') parser.add_argument(dest='test', type=str, default='lat', choices=['lat', 'thr'], help='which test to run') return parser.parse_args(argv) def latency_echo(url, count, poll, copy): """echo messages on a REP socket Should be started before `latency` """ ctx = zmq.Context() s = ctx.socket(zmq.REP) if poll: p = zmq.Poller() p.register(s) s.bind(url) block = zmq.NOBLOCK if poll else 0 for i in range(count): if poll: res = p.poll() msg = s.recv(block, copy=copy) if poll: res = p.poll() s.send(msg, block, copy=copy) msg = s.recv() assert msg == b'done' s.close() ctx.term() def latency(url, count, size, poll, copy): """Perform a latency test""" ctx = zmq.Context() s = ctx.socket(zmq.REQ) s.setsockopt(zmq.LINGER, -1) s.connect(url) if poll: p = zmq.Poller() p.register(s) msg = b' ' * size block = zmq.NOBLOCK if poll else 0 time.sleep(1) start = now() for i in range (0, count): if poll: res = p.poll() assert(res[0][1] & zmq.POLLOUT) s.send(msg, block, copy=copy) if poll: res = p.poll() assert(res[0][1] & zmq.POLLIN) msg = s.recv(block, copy=copy) assert len(msg) == size elapsed = now() - start s.send(b'done') latency = 1e6 * elapsed / (count * 2.) print ("message size : %8i [B]" % (size, )) print ("roundtrip count: %8i [msgs]" % (count, )) print ("mean latency : %12.3f [µs]" % (latency, )) print ("test time : %12.3f [s]" % (elapsed, )) def pusher(url, count, size, poll, copy): """send a bunch of messages on a PUSH socket""" ctx = zmq.Context() s = ctx.socket(zmq.PUSH) # Add your socket options here. # For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. if poll: p = zmq.Poller() p.register(s) s.connect(url) msg = zmq.Message(b' ' * size) block = zmq.NOBLOCK if poll else 0 for i in range(count): if poll: res = p.poll() assert(res[0][1] & zmq.POLLOUT) s.send(msg, block, copy=copy) s.close() ctx.term() def throughput(url, count, size, poll, copy): """recv a bunch of messages on a PULL socket Should be started before `pusher` """ ctx = zmq.Context() s = ctx.socket(zmq.PULL) # Add your socket options here. # For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. if poll: p = zmq.Poller() p.register(s) s.bind(url) block = zmq.NOBLOCK if poll else 0 # Wait for the other side to connect. msg = s.recv() assert len (msg) == size start = now() for i in range (count-1): if poll: res = p.poll() msg = s.recv(block, copy=copy) elapsed = now() - start throughput = (float(count)) / float(elapsed) megabits = float(throughput * size * 8) / 1e6 print ("message size : %8i [B]" % (size, )) print ("message count : %8i [msgs]" % (count, )) print ("mean throughput: %8.0f [msg/s]" % (throughput, )) print ("mean throughput: %12.3f [Mb/s]" % (megabits, )) print ("test time : %12.3f [s]" % (elapsed, )) def main(): args = parse_args() tic = time.time() if args.test == 'lat': bg = Process(target=latency_echo, args=(args.url, args.count, args.poll, args.copy)) bg.start() latency(args.url, args.count, args.size, args.poll, args.copy) elif args.test == 'thr': bg = Process(target=throughput, args=(args.url, args.count, args.size, args.poll, args.copy)) bg.start() pusher(args.url, args.count, args.size, args.poll, args.copy) bg.join() toc = time.time() if (toc - tic) < 3: print ("For best results, tests should take at least a few seconds.") if __name__ == '__main__': main()
en
0.690346
#!/usr/bin/env python # coding: utf-8 # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. # # Some original test code Copyright (c) 2007-2010 iMatix Corporation, # Used under LGPLv3 echo messages on a REP socket Should be started before `latency` Perform a latency test send a bunch of messages on a PUSH socket # Add your socket options here. # For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. recv a bunch of messages on a PULL socket Should be started before `pusher` # Add your socket options here. # For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. # Wait for the other side to connect.
2.556052
3
cms/tests/plugins.py
s-a-s-forks/django-cms
1
6614262
<reponame>s-a-s-forks/django-cms # -*- coding: utf-8 -*- from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered from cms.models import Page, Placeholder from cms.models.pluginmodel import CMSPlugin from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.plugins.file.models import File from cms.plugins.googlemap.models import GoogleMap from cms.plugins.inherit.models import InheritPagePlaceholder from cms.plugins.text.models import Text from cms.plugins.text.utils import (plugin_tags_to_id_list, plugin_tags_to_admin_html) from cms.test.testcases import (CMSTestCase, URL_CMS_PAGE, URL_CMS_PAGE_ADD, URL_CMS_PLUGIN_ADD, URL_CMS_PLUGIN_EDIT, URL_CMS_PAGE_CHANGE, URL_CMS_PLUGIN_REMOVE) from cms.test.util.context_managers import SettingsOverride from django.conf import settings from django.contrib.auth.models import User from django.core.files.uploadedfile import SimpleUploadedFile from django.core.urlresolvers import reverse from django.forms.widgets import Media from django.template import RequestContext from testapp.pluginapp.models import Article, Section from testapp.pluginapp.plugins.manytomany_rel.models import ArticlePluginModel import os class DumbFixturePlugin(CMSPluginBase): model = CMSPlugin name = "Dumb Test Plugin. It does nothing." render_template = "" admin_preview = False def render(self, context, instance, placeholder): return context class PluginsTestBaseCase(CMSTestCase): def setUp(self): self.super_user = User(username="test", is_staff = True, is_active = True, is_superuser = True) self.super_user.set_password("<PASSWORD>") self.super_user.save() self.slave = User(username="slave", is_staff=True, is_active=True, is_superuser=False) self.slave.set_password("<PASSWORD>") self.slave.save() self.login_user(self.super_user) self.FIRST_LANG = settings.LANGUAGES[0][0] self.SECOND_LANG = settings.LANGUAGES[1][0] # REFACTOR - the publish and appove methods exist in this file and in permmod.py - should they be in base? def publish_page(self, page, approve=False, user=None, published_check=True): if user: self.login_user(user) # publish / approve page by master response = self.client.post(URL_CMS_PAGE + "%d/change-status/" % page.pk, {1 :1}) self.assertEqual(response.status_code, 200) if not approve: return self.reload_page(page) # approve page = self.approve_page(page) if published_check: # must have public object now assert(page.publisher_public) # and public object must be published assert(page.publisher_public.published) return page def approve_page(self, page): response = self.client.get(URL_CMS_PAGE + "%d/approve/" % page.pk) self.assertRedirects(response, URL_CMS_PAGE) # reload page return self.reload_page(page) def get_request(self, *args, **kwargs): request = super(PluginsTestBaseCase, self).get_request(*args, **kwargs) request.placeholder_media = Media() return request class PluginsTestCase(PluginsTestBaseCase): def test_01_add_edit_plugin(self): """ Test that you can add a text plugin """ # add a new text plugin page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" response = self.client.get(edit_url) self.assertEquals(response.status_code, 200) data = { "body":"Hello World" } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) txt = Text.objects.all()[0] self.assertEquals("Hello World", txt.body) def test_02_copy_plugins(self): page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(len(settings.LANGUAGES) > 1, True) page = Page.objects.all()[0] placeholder = page.placeholders.get(slot="body") plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':placeholder.pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) text_plugin_pk = int(response.content) self.assertEquals(text_plugin_pk, CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" data = { "body":"Hello World" } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) txt = Text.objects.all()[0] self.assertEquals("Hello World", txt.body) # add an inline link #/admin/cms/page/2799/edit-plugin/17570/add-plugin/ #http://127.0.0.1/admin/cms/page/2799/edit-plugin/17570/edit-plugin/17574/?_popup=1 add_url = '%s%s/add-plugin/' % (URL_CMS_PLUGIN_EDIT, text_plugin_pk) data = { 'plugin_type': "LinkPlugin", "parent_id": txt.pk, "language": settings.LANGUAGES[0][0], } response = self.client.post(add_url, data) link_pk = response.content self.assertEqual(response.status_code, 200) # edit the inline link plugin edit_url = '%s%s/edit-plugin/%s/' % (URL_CMS_PLUGIN_EDIT, text_plugin_pk, link_pk) data = { 'name': "A Link", 'url': "http://www.divio.ch", } response = self.client.post(edit_url, data) self.assertEqual(response.status_code, 200) self.assertEqual(CMSPlugin.objects.get(pk=link_pk).parent.pk, txt.pk) #create 2nd language page page_data['language'] = settings.LANGUAGES[1][0] page_data['title'] += " %s" % settings.LANGUAGES[1][0] response = self.client.post(URL_CMS_PAGE_CHANGE % page.pk + "?language=%s" % settings.LANGUAGES[1][0], page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(CMSPlugin.objects.all().count(), 2) self.assertEquals(Page.objects.all().count(), 1) copy_data = { 'placeholder':page.placeholders.get(slot="body").pk, 'language':settings.LANGUAGES[1][0], 'copy_from':settings.LANGUAGES[0][0], } response = self.client.post(URL_CMS_PAGE + "copy-plugins/", copy_data) self.assertEquals(response.status_code, 200) self.assertEqual(response.content.count('<li '), 1) # assert copy success self.assertEquals(CMSPlugin.objects.filter(language=settings.LANGUAGES[0][0]).count(), 2) self.assertEquals(CMSPlugin.objects.filter(language=settings.LANGUAGES[1][0]).count(), 2) self.assertEquals(CMSPlugin.objects.all().count(), 4) # assert plugin tree for link in CMSPlugin.objects.filter(plugin_type="LinkPlugin"): self.assertNotEqual(link.parent, None) for text in Text.objects.all(): self.assertEquals(text.body, "Hello World") def test_03_remove_plugin_before_published(self): """ When removing a draft plugin we would expect the public copy of the plugin to also be removed """ # add a page page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) # delete the plugin plugin_data = { 'plugin_id': int(response.content) } remove_url = URL_CMS_PLUGIN_REMOVE response = self.client.post(remove_url, plugin_data) self.assertEquals(response.status_code, 200) # there should be no plugins self.assertEquals(0, CMSPlugin.objects.all().count()) def test_04_remove_plugin_after_published(self): # add a page page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) plugin_id = int(response.content) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) # publish page response = self.client.post(URL_CMS_PAGE + "%d/change-status/" % page.pk, {1 :1}) self.assertEqual(response.status_code, 200) # there should now be two plugins - 1 draft, 1 public self.assertEquals(CMSPlugin.objects.all().count(), 2) # delete the plugin plugin_data = { 'plugin_id': plugin_id } remove_url = URL_CMS_PLUGIN_REMOVE response = self.client.post(remove_url, plugin_data) self.assertEquals(response.status_code, 200) # there should be no plugins self.assertEquals(CMSPlugin.objects.all().count(), 0) def test_05_remove_plugin_not_associated_to_page(self): """ Test case for PlaceholderField """ page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) ph = Placeholder(slot="subplugin") ph.save() plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder': ph.pk, 'parent': int(response.content) } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) # no longer allowed for security reasons self.assertEqual(response.status_code, 404) def test_07_register_plugin_twice_should_raise(self): number_of_plugins_before = len(plugin_pool.get_all_plugins()) # The first time we register the plugin is should work plugin_pool.register_plugin(DumbFixturePlugin) # Let's add it a second time. We should catch and exception raised = False try: plugin_pool.register_plugin(DumbFixturePlugin) except PluginAlreadyRegistered: raised = True self.assertTrue(raised) # Let's also unregister the plugin now, and assert it's not in the # pool anymore plugin_pool.unregister_plugin(DumbFixturePlugin) # Let's make sure we have the same number of plugins as before: number_of_plugins_after = len(plugin_pool.get_all_plugins()) self.assertEqual(number_of_plugins_before, number_of_plugins_after) def test_08_unregister_non_existing_plugin_should_raise(self): number_of_plugins_before = len(plugin_pool.get_all_plugins()) raised = False try: # There should not be such a plugin registered if the others tests # don't leak plugins plugin_pool.unregister_plugin(DumbFixturePlugin) except PluginNotRegistered: raised = True self.assertTrue(raised) # Let's count, to make sure we didn't remove a plugin accidentally. number_of_plugins_after = len(plugin_pool.get_all_plugins()) self.assertEqual(number_of_plugins_before, number_of_plugins_after) def test_09_iheritplugin_media(self): """ Test case for InheritPagePlaceholder """ inheritfrompage = self.create_page(title='page to inherit from') body = inheritfrompage.placeholders.get(slot="body") plugin = GoogleMap( plugin_type='GoogleMapPlugin', placeholder=body, position=1, language=settings.LANGUAGE_CODE, lat=1, lng=1) plugin.insert_at(None, position='last-child', commit=True) page = self.create_page(title='inherit from page') inherited_body = page.placeholders.get(slot="body") inherit_plugin = InheritPagePlaceholder( plugin_type='InheritPagePlaceholderPlugin', placeholder=inherited_body, position=1, language=settings.LANGUAGE_CODE, from_page=inheritfrompage, from_language=settings.LANGUAGE_CODE) inherit_plugin.insert_at(None, position='last-child', commit=True) request = self.get_request() context = RequestContext(request, {}) inherit_plugin.render_plugin(context, inherited_body) self.assertEquals(unicode(request.placeholder_media).find('maps.google.com') != -1, True) def test_10_fileplugin_icon_uppercase(self): page = self.create_page(title='testpage') body = page.placeholders.get(slot="body") plugin = File( plugin_type='FilePlugin', placeholder=body, position=1, language=settings.LANGUAGE_CODE, ) plugin.file.save("UPPERCASE.JPG", SimpleUploadedFile("UPPERCASE.jpg", "content"), False) plugin.insert_at(None, position='last-child', commit=True) self.assertNotEquals(plugin.get_icon_url().find('jpg'), -1) response = self.client.get(plugin.get_icon_url(), follow=True) self.assertEqual(response.status_code, 200) # Nuke everything in the storage location directory (since removing just # our file would still leave a useless directory structure) # # By the way, plugin.file.storage.delete(plugin.file.name) does not work # since the delete method is a pass... See reversion.storage.delete() storage_location = plugin.file.storage.location # This is ".../media/" for root, dirs, files in os.walk(storage_location, topdown=False): # We need to walk() the directory tree since rmdir() does not allow # to remove non-empty directories... for name in files: # Start by killing all files we walked os.remove(os.path.join(root, name)) for name in dirs: # Now all directories we walked... os.rmdir(os.path.join(root, name)) def test_11_copy_textplugin(self): """ Test that copying of textplugins replaces references to copied plugins """ page = self.create_page() placeholder = page.placeholders.get(slot='body') plugin_base = CMSPlugin( plugin_type='TextPlugin', placeholder=placeholder, position=1, language=self.FIRST_LANG) plugin_base.insert_at(None, position='last-child', commit=False) plugin = Text(body='') plugin_base.set_base_attr(plugin) plugin.save() plugin_ref_1_base = CMSPlugin( plugin_type='TextPlugin', placeholder=placeholder, position=1, language=self.FIRST_LANG) plugin_ref_1_base.insert_at(plugin_base, position='last-child', commit=False) plugin_ref_1 = Text(body='') plugin_ref_1_base.set_base_attr(plugin_ref_1) plugin_ref_1.save() plugin_ref_2_base = CMSPlugin( plugin_type='TextPlugin', placeholder=placeholder, position=2, language=self.FIRST_LANG) plugin_ref_2_base.insert_at(plugin_base, position='last-child', commit=False) plugin_ref_2 = Text(body='') plugin_ref_2_base.set_base_attr(plugin_ref_2) plugin_ref_2.save() plugin.body = plugin_tags_to_admin_html(' {{ plugin_object %s }} {{ plugin_object %s }} ' % (str(plugin_ref_1.pk), str(plugin_ref_2.pk))) plugin.save() self.assertEquals(plugin.pk, 1) page_data = self.get_new_page_data() #create 2nd language page page_data.update({ 'language': self.SECOND_LANG, 'title': "%s %s" % (page.get_title(), self.SECOND_LANG), }) response = self.client.post(URL_CMS_PAGE_CHANGE % page.pk + "?language=%s" % self.SECOND_LANG, page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 3) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 0) self.assertEquals(CMSPlugin.objects.count(), 3) self.assertEquals(Page.objects.all().count(), 1) copy_data = { 'placeholder': placeholder.pk, 'language': self.SECOND_LANG, 'copy_from': self.FIRST_LANG, } response = self.client.post(URL_CMS_PAGE + "copy-plugins/", copy_data) self.assertEquals(response.status_code, 200) self.assertEqual(response.content.count('<li '), 3) # assert copy success self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 3) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 3) self.assertEquals(CMSPlugin.objects.count(), 6) new_plugin = Text.objects.get(pk=6) self.assertEquals(plugin_tags_to_id_list(new_plugin.body), [u'4', u'5']) class PluginManyToManyTestCase(PluginsTestBaseCase): def setUp(self): self.super_user = User(username="test", is_staff = True, is_active = True, is_superuser = True) self.super_user.set_password("<PASSWORD>") self.super_user.save() self.slave = User(username="slave", is_staff=True, is_active=True, is_superuser=False) self.slave.set_password("<PASSWORD>") self.slave.save() self.login_user(self.super_user) # create 3 sections self.sections = [] self.section_pks = [] for i in range(3): section = Section.objects.create(name="section %s" %i) self.sections.append(section) self.section_pks.append(section.pk) self.section_count = len(self.sections) # create 10 articles by section for section in self.sections: for j in range(10): Article.objects.create( title="article %s" % j, section=section ) self.FIRST_LANG = settings.LANGUAGES[0][0] self.SECOND_LANG = settings.LANGUAGES[1][0] def test_01_add_plugin_with_m2m(self): # add a new text plugin page_data = self.get_new_page_data() self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] placeholder = page.placeholders.get(slot="body") plugin_data = { 'plugin_type': "ArticlePlugin", 'language': self.FIRST_LANG, 'placeholder': placeholder.pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" response = self.client.get(edit_url) self.assertEquals(response.status_code, 200) data = { 'title': "Articles Plugin 1", "sections": self.section_pks } response = self.client.post(edit_url, data) self.assertEqual(response.status_code, 200) self.assertEqual(ArticlePluginModel.objects.count(), 1) plugin = ArticlePluginModel.objects.all()[0] self.assertEquals(self.section_count, plugin.sections.count()) def test_01_add_plugin_with_m2m_and_publisher(self): page_data = self.get_new_page_data() self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] placeholder = page.placeholders.get(slot="body") # add a plugin plugin_data = { 'plugin_type': "ArticlePlugin", 'language': self.FIRST_LANG, 'placeholder': placeholder.pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(1, CMSPlugin.objects.all().count()) articles_plugin_pk = int(response.content) self.assertEquals(articles_plugin_pk, CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" data = { 'title': "Articles Plugin 1", 'sections': self.section_pks } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) self.assertEquals(1, ArticlePluginModel.objects.count()) articles_plugin = ArticlePluginModel.objects.all()[0] self.assertEquals(u'Articles Plugin 1', articles_plugin.title) self.assertEquals(self.section_count, articles_plugin.sections.count()) # check publish box page = self.publish_page(page) # there should now be two plugins - 1 draft, 1 public self.assertEquals(2, ArticlePluginModel.objects.all().count()) db_counts = [plugin.sections.count() for plugin in ArticlePluginModel.objects.all()] expected = [self.section_count for i in range(len(db_counts))] self.assertEqual(expected, db_counts) def test_03_copy_plugin_with_m2m(self): page = self.create_page() placeholder = page.placeholders.get(slot='body') plugin = ArticlePluginModel( plugin_type='ArticlePlugin', placeholder=placeholder, position=1, language=self.FIRST_LANG) plugin.insert_at(None, position='last-child', commit=True) edit_url = URL_CMS_PLUGIN_EDIT + str(plugin.pk) + "/" data = { 'title': "Articles Plugin 1", "sections": self.section_pks } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) self.assertEqual(ArticlePluginModel.objects.count(), 1) self.assertEqual(ArticlePluginModel.objects.all()[0].sections.count(), self.section_count) page_data = self.get_new_page_data() #create 2nd language page page_data.update({ 'language': self.SECOND_LANG, 'title': "%s %s" % (page.get_title(), self.SECOND_LANG), }) response = self.client.post(URL_CMS_PAGE_CHANGE % page.pk + "?language=%s" % self.SECOND_LANG, page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 1) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 0) self.assertEquals(CMSPlugin.objects.count(), 1) self.assertEquals(Page.objects.all().count(), 1) copy_data = { 'placeholder': placeholder.pk, 'language': self.SECOND_LANG, 'copy_from': self.FIRST_LANG, } response = self.client.post(URL_CMS_PAGE + "copy-plugins/", copy_data) self.assertEquals(response.status_code, 200) self.assertEqual(response.content.count('<li '), 1) # assert copy success self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 1) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 1) self.assertEquals(CMSPlugin.objects.count(), 2) db_counts = [plugin.sections.count() for plugin in ArticlePluginModel.objects.all()] expected = [self.section_count for i in range(len(db_counts))] self.assertEqual(expected, db_counts)
# -*- coding: utf-8 -*- from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered from cms.models import Page, Placeholder from cms.models.pluginmodel import CMSPlugin from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.plugins.file.models import File from cms.plugins.googlemap.models import GoogleMap from cms.plugins.inherit.models import InheritPagePlaceholder from cms.plugins.text.models import Text from cms.plugins.text.utils import (plugin_tags_to_id_list, plugin_tags_to_admin_html) from cms.test.testcases import (CMSTestCase, URL_CMS_PAGE, URL_CMS_PAGE_ADD, URL_CMS_PLUGIN_ADD, URL_CMS_PLUGIN_EDIT, URL_CMS_PAGE_CHANGE, URL_CMS_PLUGIN_REMOVE) from cms.test.util.context_managers import SettingsOverride from django.conf import settings from django.contrib.auth.models import User from django.core.files.uploadedfile import SimpleUploadedFile from django.core.urlresolvers import reverse from django.forms.widgets import Media from django.template import RequestContext from testapp.pluginapp.models import Article, Section from testapp.pluginapp.plugins.manytomany_rel.models import ArticlePluginModel import os class DumbFixturePlugin(CMSPluginBase): model = CMSPlugin name = "Dumb Test Plugin. It does nothing." render_template = "" admin_preview = False def render(self, context, instance, placeholder): return context class PluginsTestBaseCase(CMSTestCase): def setUp(self): self.super_user = User(username="test", is_staff = True, is_active = True, is_superuser = True) self.super_user.set_password("<PASSWORD>") self.super_user.save() self.slave = User(username="slave", is_staff=True, is_active=True, is_superuser=False) self.slave.set_password("<PASSWORD>") self.slave.save() self.login_user(self.super_user) self.FIRST_LANG = settings.LANGUAGES[0][0] self.SECOND_LANG = settings.LANGUAGES[1][0] # REFACTOR - the publish and appove methods exist in this file and in permmod.py - should they be in base? def publish_page(self, page, approve=False, user=None, published_check=True): if user: self.login_user(user) # publish / approve page by master response = self.client.post(URL_CMS_PAGE + "%d/change-status/" % page.pk, {1 :1}) self.assertEqual(response.status_code, 200) if not approve: return self.reload_page(page) # approve page = self.approve_page(page) if published_check: # must have public object now assert(page.publisher_public) # and public object must be published assert(page.publisher_public.published) return page def approve_page(self, page): response = self.client.get(URL_CMS_PAGE + "%d/approve/" % page.pk) self.assertRedirects(response, URL_CMS_PAGE) # reload page return self.reload_page(page) def get_request(self, *args, **kwargs): request = super(PluginsTestBaseCase, self).get_request(*args, **kwargs) request.placeholder_media = Media() return request class PluginsTestCase(PluginsTestBaseCase): def test_01_add_edit_plugin(self): """ Test that you can add a text plugin """ # add a new text plugin page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" response = self.client.get(edit_url) self.assertEquals(response.status_code, 200) data = { "body":"Hello World" } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) txt = Text.objects.all()[0] self.assertEquals("Hello World", txt.body) def test_02_copy_plugins(self): page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(len(settings.LANGUAGES) > 1, True) page = Page.objects.all()[0] placeholder = page.placeholders.get(slot="body") plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':placeholder.pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) text_plugin_pk = int(response.content) self.assertEquals(text_plugin_pk, CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" data = { "body":"Hello World" } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) txt = Text.objects.all()[0] self.assertEquals("Hello World", txt.body) # add an inline link #/admin/cms/page/2799/edit-plugin/17570/add-plugin/ #http://127.0.0.1/admin/cms/page/2799/edit-plugin/17570/edit-plugin/17574/?_popup=1 add_url = '%s%s/add-plugin/' % (URL_CMS_PLUGIN_EDIT, text_plugin_pk) data = { 'plugin_type': "LinkPlugin", "parent_id": txt.pk, "language": settings.LANGUAGES[0][0], } response = self.client.post(add_url, data) link_pk = response.content self.assertEqual(response.status_code, 200) # edit the inline link plugin edit_url = '%s%s/edit-plugin/%s/' % (URL_CMS_PLUGIN_EDIT, text_plugin_pk, link_pk) data = { 'name': "A Link", 'url': "http://www.divio.ch", } response = self.client.post(edit_url, data) self.assertEqual(response.status_code, 200) self.assertEqual(CMSPlugin.objects.get(pk=link_pk).parent.pk, txt.pk) #create 2nd language page page_data['language'] = settings.LANGUAGES[1][0] page_data['title'] += " %s" % settings.LANGUAGES[1][0] response = self.client.post(URL_CMS_PAGE_CHANGE % page.pk + "?language=%s" % settings.LANGUAGES[1][0], page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(CMSPlugin.objects.all().count(), 2) self.assertEquals(Page.objects.all().count(), 1) copy_data = { 'placeholder':page.placeholders.get(slot="body").pk, 'language':settings.LANGUAGES[1][0], 'copy_from':settings.LANGUAGES[0][0], } response = self.client.post(URL_CMS_PAGE + "copy-plugins/", copy_data) self.assertEquals(response.status_code, 200) self.assertEqual(response.content.count('<li '), 1) # assert copy success self.assertEquals(CMSPlugin.objects.filter(language=settings.LANGUAGES[0][0]).count(), 2) self.assertEquals(CMSPlugin.objects.filter(language=settings.LANGUAGES[1][0]).count(), 2) self.assertEquals(CMSPlugin.objects.all().count(), 4) # assert plugin tree for link in CMSPlugin.objects.filter(plugin_type="LinkPlugin"): self.assertNotEqual(link.parent, None) for text in Text.objects.all(): self.assertEquals(text.body, "Hello World") def test_03_remove_plugin_before_published(self): """ When removing a draft plugin we would expect the public copy of the plugin to also be removed """ # add a page page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) # delete the plugin plugin_data = { 'plugin_id': int(response.content) } remove_url = URL_CMS_PLUGIN_REMOVE response = self.client.post(remove_url, plugin_data) self.assertEquals(response.status_code, 200) # there should be no plugins self.assertEquals(0, CMSPlugin.objects.all().count()) def test_04_remove_plugin_after_published(self): # add a page page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) plugin_id = int(response.content) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) # publish page response = self.client.post(URL_CMS_PAGE + "%d/change-status/" % page.pk, {1 :1}) self.assertEqual(response.status_code, 200) # there should now be two plugins - 1 draft, 1 public self.assertEquals(CMSPlugin.objects.all().count(), 2) # delete the plugin plugin_data = { 'plugin_id': plugin_id } remove_url = URL_CMS_PLUGIN_REMOVE response = self.client.post(remove_url, plugin_data) self.assertEquals(response.status_code, 200) # there should be no plugins self.assertEquals(CMSPlugin.objects.all().count(), 0) def test_05_remove_plugin_not_associated_to_page(self): """ Test case for PlaceholderField """ page_data = self.get_new_page_data() response = self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] # add a plugin plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder':page.placeholders.get(slot="body").pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(CMSPlugin.objects.all().count(), 1) ph = Placeholder(slot="subplugin") ph.save() plugin_data = { 'plugin_type':"TextPlugin", 'language':settings.LANGUAGES[0][0], 'placeholder': ph.pk, 'parent': int(response.content) } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) # no longer allowed for security reasons self.assertEqual(response.status_code, 404) def test_07_register_plugin_twice_should_raise(self): number_of_plugins_before = len(plugin_pool.get_all_plugins()) # The first time we register the plugin is should work plugin_pool.register_plugin(DumbFixturePlugin) # Let's add it a second time. We should catch and exception raised = False try: plugin_pool.register_plugin(DumbFixturePlugin) except PluginAlreadyRegistered: raised = True self.assertTrue(raised) # Let's also unregister the plugin now, and assert it's not in the # pool anymore plugin_pool.unregister_plugin(DumbFixturePlugin) # Let's make sure we have the same number of plugins as before: number_of_plugins_after = len(plugin_pool.get_all_plugins()) self.assertEqual(number_of_plugins_before, number_of_plugins_after) def test_08_unregister_non_existing_plugin_should_raise(self): number_of_plugins_before = len(plugin_pool.get_all_plugins()) raised = False try: # There should not be such a plugin registered if the others tests # don't leak plugins plugin_pool.unregister_plugin(DumbFixturePlugin) except PluginNotRegistered: raised = True self.assertTrue(raised) # Let's count, to make sure we didn't remove a plugin accidentally. number_of_plugins_after = len(plugin_pool.get_all_plugins()) self.assertEqual(number_of_plugins_before, number_of_plugins_after) def test_09_iheritplugin_media(self): """ Test case for InheritPagePlaceholder """ inheritfrompage = self.create_page(title='page to inherit from') body = inheritfrompage.placeholders.get(slot="body") plugin = GoogleMap( plugin_type='GoogleMapPlugin', placeholder=body, position=1, language=settings.LANGUAGE_CODE, lat=1, lng=1) plugin.insert_at(None, position='last-child', commit=True) page = self.create_page(title='inherit from page') inherited_body = page.placeholders.get(slot="body") inherit_plugin = InheritPagePlaceholder( plugin_type='InheritPagePlaceholderPlugin', placeholder=inherited_body, position=1, language=settings.LANGUAGE_CODE, from_page=inheritfrompage, from_language=settings.LANGUAGE_CODE) inherit_plugin.insert_at(None, position='last-child', commit=True) request = self.get_request() context = RequestContext(request, {}) inherit_plugin.render_plugin(context, inherited_body) self.assertEquals(unicode(request.placeholder_media).find('maps.google.com') != -1, True) def test_10_fileplugin_icon_uppercase(self): page = self.create_page(title='testpage') body = page.placeholders.get(slot="body") plugin = File( plugin_type='FilePlugin', placeholder=body, position=1, language=settings.LANGUAGE_CODE, ) plugin.file.save("UPPERCASE.JPG", SimpleUploadedFile("UPPERCASE.jpg", "content"), False) plugin.insert_at(None, position='last-child', commit=True) self.assertNotEquals(plugin.get_icon_url().find('jpg'), -1) response = self.client.get(plugin.get_icon_url(), follow=True) self.assertEqual(response.status_code, 200) # Nuke everything in the storage location directory (since removing just # our file would still leave a useless directory structure) # # By the way, plugin.file.storage.delete(plugin.file.name) does not work # since the delete method is a pass... See reversion.storage.delete() storage_location = plugin.file.storage.location # This is ".../media/" for root, dirs, files in os.walk(storage_location, topdown=False): # We need to walk() the directory tree since rmdir() does not allow # to remove non-empty directories... for name in files: # Start by killing all files we walked os.remove(os.path.join(root, name)) for name in dirs: # Now all directories we walked... os.rmdir(os.path.join(root, name)) def test_11_copy_textplugin(self): """ Test that copying of textplugins replaces references to copied plugins """ page = self.create_page() placeholder = page.placeholders.get(slot='body') plugin_base = CMSPlugin( plugin_type='TextPlugin', placeholder=placeholder, position=1, language=self.FIRST_LANG) plugin_base.insert_at(None, position='last-child', commit=False) plugin = Text(body='') plugin_base.set_base_attr(plugin) plugin.save() plugin_ref_1_base = CMSPlugin( plugin_type='TextPlugin', placeholder=placeholder, position=1, language=self.FIRST_LANG) plugin_ref_1_base.insert_at(plugin_base, position='last-child', commit=False) plugin_ref_1 = Text(body='') plugin_ref_1_base.set_base_attr(plugin_ref_1) plugin_ref_1.save() plugin_ref_2_base = CMSPlugin( plugin_type='TextPlugin', placeholder=placeholder, position=2, language=self.FIRST_LANG) plugin_ref_2_base.insert_at(plugin_base, position='last-child', commit=False) plugin_ref_2 = Text(body='') plugin_ref_2_base.set_base_attr(plugin_ref_2) plugin_ref_2.save() plugin.body = plugin_tags_to_admin_html(' {{ plugin_object %s }} {{ plugin_object %s }} ' % (str(plugin_ref_1.pk), str(plugin_ref_2.pk))) plugin.save() self.assertEquals(plugin.pk, 1) page_data = self.get_new_page_data() #create 2nd language page page_data.update({ 'language': self.SECOND_LANG, 'title': "%s %s" % (page.get_title(), self.SECOND_LANG), }) response = self.client.post(URL_CMS_PAGE_CHANGE % page.pk + "?language=%s" % self.SECOND_LANG, page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 3) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 0) self.assertEquals(CMSPlugin.objects.count(), 3) self.assertEquals(Page.objects.all().count(), 1) copy_data = { 'placeholder': placeholder.pk, 'language': self.SECOND_LANG, 'copy_from': self.FIRST_LANG, } response = self.client.post(URL_CMS_PAGE + "copy-plugins/", copy_data) self.assertEquals(response.status_code, 200) self.assertEqual(response.content.count('<li '), 3) # assert copy success self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 3) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 3) self.assertEquals(CMSPlugin.objects.count(), 6) new_plugin = Text.objects.get(pk=6) self.assertEquals(plugin_tags_to_id_list(new_plugin.body), [u'4', u'5']) class PluginManyToManyTestCase(PluginsTestBaseCase): def setUp(self): self.super_user = User(username="test", is_staff = True, is_active = True, is_superuser = True) self.super_user.set_password("<PASSWORD>") self.super_user.save() self.slave = User(username="slave", is_staff=True, is_active=True, is_superuser=False) self.slave.set_password("<PASSWORD>") self.slave.save() self.login_user(self.super_user) # create 3 sections self.sections = [] self.section_pks = [] for i in range(3): section = Section.objects.create(name="section %s" %i) self.sections.append(section) self.section_pks.append(section.pk) self.section_count = len(self.sections) # create 10 articles by section for section in self.sections: for j in range(10): Article.objects.create( title="article %s" % j, section=section ) self.FIRST_LANG = settings.LANGUAGES[0][0] self.SECOND_LANG = settings.LANGUAGES[1][0] def test_01_add_plugin_with_m2m(self): # add a new text plugin page_data = self.get_new_page_data() self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] placeholder = page.placeholders.get(slot="body") plugin_data = { 'plugin_type': "ArticlePlugin", 'language': self.FIRST_LANG, 'placeholder': placeholder.pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" response = self.client.get(edit_url) self.assertEquals(response.status_code, 200) data = { 'title': "Articles Plugin 1", "sections": self.section_pks } response = self.client.post(edit_url, data) self.assertEqual(response.status_code, 200) self.assertEqual(ArticlePluginModel.objects.count(), 1) plugin = ArticlePluginModel.objects.all()[0] self.assertEquals(self.section_count, plugin.sections.count()) def test_01_add_plugin_with_m2m_and_publisher(self): page_data = self.get_new_page_data() self.client.post(URL_CMS_PAGE_ADD, page_data) page = Page.objects.all()[0] placeholder = page.placeholders.get(slot="body") # add a plugin plugin_data = { 'plugin_type': "ArticlePlugin", 'language': self.FIRST_LANG, 'placeholder': placeholder.pk, } response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data) self.assertEquals(response.status_code, 200) self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk) # there should be only 1 plugin self.assertEquals(1, CMSPlugin.objects.all().count()) articles_plugin_pk = int(response.content) self.assertEquals(articles_plugin_pk, CMSPlugin.objects.all()[0].pk) # now edit the plugin edit_url = URL_CMS_PLUGIN_EDIT + response.content + "/" data = { 'title': "Articles Plugin 1", 'sections': self.section_pks } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) self.assertEquals(1, ArticlePluginModel.objects.count()) articles_plugin = ArticlePluginModel.objects.all()[0] self.assertEquals(u'Articles Plugin 1', articles_plugin.title) self.assertEquals(self.section_count, articles_plugin.sections.count()) # check publish box page = self.publish_page(page) # there should now be two plugins - 1 draft, 1 public self.assertEquals(2, ArticlePluginModel.objects.all().count()) db_counts = [plugin.sections.count() for plugin in ArticlePluginModel.objects.all()] expected = [self.section_count for i in range(len(db_counts))] self.assertEqual(expected, db_counts) def test_03_copy_plugin_with_m2m(self): page = self.create_page() placeholder = page.placeholders.get(slot='body') plugin = ArticlePluginModel( plugin_type='ArticlePlugin', placeholder=placeholder, position=1, language=self.FIRST_LANG) plugin.insert_at(None, position='last-child', commit=True) edit_url = URL_CMS_PLUGIN_EDIT + str(plugin.pk) + "/" data = { 'title': "Articles Plugin 1", "sections": self.section_pks } response = self.client.post(edit_url, data) self.assertEquals(response.status_code, 200) self.assertEqual(ArticlePluginModel.objects.count(), 1) self.assertEqual(ArticlePluginModel.objects.all()[0].sections.count(), self.section_count) page_data = self.get_new_page_data() #create 2nd language page page_data.update({ 'language': self.SECOND_LANG, 'title': "%s %s" % (page.get_title(), self.SECOND_LANG), }) response = self.client.post(URL_CMS_PAGE_CHANGE % page.pk + "?language=%s" % self.SECOND_LANG, page_data) self.assertRedirects(response, URL_CMS_PAGE) self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 1) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 0) self.assertEquals(CMSPlugin.objects.count(), 1) self.assertEquals(Page.objects.all().count(), 1) copy_data = { 'placeholder': placeholder.pk, 'language': self.SECOND_LANG, 'copy_from': self.FIRST_LANG, } response = self.client.post(URL_CMS_PAGE + "copy-plugins/", copy_data) self.assertEquals(response.status_code, 200) self.assertEqual(response.content.count('<li '), 1) # assert copy success self.assertEquals(CMSPlugin.objects.filter(language=self.FIRST_LANG).count(), 1) self.assertEquals(CMSPlugin.objects.filter(language=self.SECOND_LANG).count(), 1) self.assertEquals(CMSPlugin.objects.count(), 2) db_counts = [plugin.sections.count() for plugin in ArticlePluginModel.objects.all()] expected = [self.section_count for i in range(len(db_counts))] self.assertEqual(expected, db_counts)
en
0.848298
# -*- coding: utf-8 -*- # REFACTOR - the publish and appove methods exist in this file and in permmod.py - should they be in base? # publish / approve page by master # approve # must have public object now # and public object must be published # reload page Test that you can add a text plugin # add a new text plugin # now edit the plugin # now edit the plugin # add an inline link #/admin/cms/page/2799/edit-plugin/17570/add-plugin/ #http://127.0.0.1/admin/cms/page/2799/edit-plugin/17570/edit-plugin/17574/?_popup=1 # edit the inline link plugin #create 2nd language page # assert copy success # assert plugin tree When removing a draft plugin we would expect the public copy of the plugin to also be removed # add a page # add a plugin # there should be only 1 plugin # delete the plugin # there should be no plugins # add a page # add a plugin # there should be only 1 plugin # publish page # there should now be two plugins - 1 draft, 1 public # delete the plugin # there should be no plugins Test case for PlaceholderField # add a plugin # there should be only 1 plugin # no longer allowed for security reasons # The first time we register the plugin is should work # Let's add it a second time. We should catch and exception # Let's also unregister the plugin now, and assert it's not in the # pool anymore # Let's make sure we have the same number of plugins as before: # There should not be such a plugin registered if the others tests # don't leak plugins # Let's count, to make sure we didn't remove a plugin accidentally. Test case for InheritPagePlaceholder # Nuke everything in the storage location directory (since removing just # our file would still leave a useless directory structure) # # By the way, plugin.file.storage.delete(plugin.file.name) does not work # since the delete method is a pass... See reversion.storage.delete() # This is ".../media/" # We need to walk() the directory tree since rmdir() does not allow # to remove non-empty directories... # Start by killing all files we walked # Now all directories we walked... Test that copying of textplugins replaces references to copied plugins #create 2nd language page # assert copy success # create 3 sections # create 10 articles by section # add a new text plugin # now edit the plugin # add a plugin # there should be only 1 plugin # now edit the plugin # check publish box # there should now be two plugins - 1 draft, 1 public #create 2nd language page # assert copy success
1.801171
2
test_project/test_project/ext_db_sqlite3_settings.py
xiva-wgt/django-fias
108
6614263
from .settings import * DATABASES['fias'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_PATH, 'fias.sqlite'), }
from .settings import * DATABASES['fias'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_PATH, 'fias.sqlite'), }
none
1
1.222459
1
src/chains/migrations/0006_i18n.py
tough-dev-school/education-backend
62
6614264
<filename>src/chains/migrations/0006_i18n.py # Generated by Django 3.2.12 on 2022-03-19 11:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('products', '0019_CourseDisplayInLMS'), ('chains', '0005_MessageAdminSpeedup'), ] operations = [ migrations.AlterField( model_name='chain', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.course', verbose_name='Course'), ), migrations.AlterField( model_name='chain', name='name', field=models.CharField(max_length=256, verbose_name='Name'), ), migrations.AlterField( model_name='chain', name='sending_is_active', field=models.BooleanField(default=False, verbose_name='Sending is active'), ), migrations.AlterField( model_name='message', name='chain', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chains.chain', verbose_name='Chain'), ), migrations.AlterField( model_name='message', name='delay', field=models.BigIntegerField(default=0, help_text='86400 for day, 604800 for week', verbose_name='Delay (minutes)'), ), migrations.AlterField( model_name='message', name='name', field=models.CharField(max_length=256, verbose_name='Name'), ), migrations.AlterField( model_name='message', name='parent', field=models.ForeignKey(blank=True, help_text='Messages without parent will be sent upon start', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='children', to='chains.message', verbose_name='Parent'), ), migrations.AlterField( model_name='message', name='template_id', field=models.CharField(max_length=256, verbose_name='Template id'), ), ]
<filename>src/chains/migrations/0006_i18n.py # Generated by Django 3.2.12 on 2022-03-19 11:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('products', '0019_CourseDisplayInLMS'), ('chains', '0005_MessageAdminSpeedup'), ] operations = [ migrations.AlterField( model_name='chain', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.course', verbose_name='Course'), ), migrations.AlterField( model_name='chain', name='name', field=models.CharField(max_length=256, verbose_name='Name'), ), migrations.AlterField( model_name='chain', name='sending_is_active', field=models.BooleanField(default=False, verbose_name='Sending is active'), ), migrations.AlterField( model_name='message', name='chain', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chains.chain', verbose_name='Chain'), ), migrations.AlterField( model_name='message', name='delay', field=models.BigIntegerField(default=0, help_text='86400 for day, 604800 for week', verbose_name='Delay (minutes)'), ), migrations.AlterField( model_name='message', name='name', field=models.CharField(max_length=256, verbose_name='Name'), ), migrations.AlterField( model_name='message', name='parent', field=models.ForeignKey(blank=True, help_text='Messages without parent will be sent upon start', null=True, on_delete=django.db.models.deletion.PROTECT, related_name='children', to='chains.message', verbose_name='Parent'), ), migrations.AlterField( model_name='message', name='template_id', field=models.CharField(max_length=256, verbose_name='Template id'), ), ]
en
0.808352
# Generated by Django 3.2.12 on 2022-03-19 11:48
1.431325
1
GetStockData/getstockdata.py
scotthuang1989/FundAnalysis
0
6614265
from urllib.request import urlopen def GetStockData(stock_code,start,end,filename): #stock_code, end with .ss (shanghai) or .sz (shenzhen) url_template = "http://ichart.yahoo.com/table.csv?s={0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}&g=d" url_data = url_template.format(stock_code,start.month-1,start.day,start.year,end.month-1,end.day,end.year) print(url_data) url_response = urlopen(url_data) file_data = open(filename,'w') file_data.write(url_response.read().decode("utf-8")) file_data.close() return True; # except:
from urllib.request import urlopen def GetStockData(stock_code,start,end,filename): #stock_code, end with .ss (shanghai) or .sz (shenzhen) url_template = "http://ichart.yahoo.com/table.csv?s={0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}&g=d" url_data = url_template.format(stock_code,start.month-1,start.day,start.year,end.month-1,end.day,end.year) print(url_data) url_response = urlopen(url_data) file_data = open(filename,'w') file_data.write(url_response.read().decode("utf-8")) file_data.close() return True; # except:
en
0.759552
#stock_code, end with .ss (shanghai) or .sz (shenzhen) # except:
3.196837
3
apps/drug_target_interaction/graph_dta/src/model.py
agave233/PaddleHelix
454
6614266
<reponame>agave233/PaddleHelix # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ DTA model """ import paddle import paddle.nn as nn import pgl from pahelix.networks.compound_encoder import AtomEmbedding from pahelix.utils.protein_tools import ProteinTokenizer from pahelix.networks.gnn_block import MeanPool class CompoundGNNModel(nn.Layer): """ | CompoundGNNModel, implementation of the variant GNN models in paper ``GraphDTA: Predicting drug-target binding affinity with graph neural networks``. Public Functions: - ``forward``: forward to create the compound representation. """ def __init__(self, config): super(CompoundGNNModel, self).__init__() self.hidden_size = config['hidden_size'] self.embed_dim = config['embed_dim'] self.output_dim = config['output_dim'] self.dropout_rate = config['dropout_rate'] self.layer_num = config['layer_num'] self.gnn_type = config['gnn_type'] self.gat_nheads = config.get('gat_nheads', 10) self.activation = config.get('activation', 'relu') self.atomic_numeric_feat_dim = config.get( 'atomic_numeric_feat_dim', 28) self.atom_names = config['atom_names'] self.bond_names = config['bond_names'] self.atom_embedding = AtomEmbedding(self.atom_names, self.embed_dim) self.gnn_layers = nn.LayerList() if self.gnn_type == 'gcn': for layer_id in range(self.layer_num): self.gnn_layers.append(pgl.nn.GCNConv( self._get_in_size(layer_id), self.hidden_size, activation=self.activation)) self.graph_pool = pgl.nn.GraphPool(pool_type='max') self.fc = nn.Linear(self.hidden_size, self.output_dim) elif self.gnn_type == 'gat': for layer_id in range(self.layer_num): self.gnn_layers.append(pgl.nn.GATConv( self._get_in_size(layer_id, self.gat_nheads), self.hidden_size, activation=self.activation, num_heads=self.gat_nheads, feat_drop=self.dropout_rate, attn_drop=self.dropout_rate)) self.graph_pool = pgl.nn.GraphPool(pool_type='max') in_size = self.hidden_size * self.gat_nheads self.fc = nn.Linear(in_size, self.output_dim) elif self.gnn_type == 'gin': for layer_id in range(self.layer_num): self.gnn_layers.append(pgl.nn.GINConv( self._get_in_size(layer_id), self.hidden_size, activation=self.activation)) self.gnn_layers.append( nn.BatchNorm1D(self.hidden_size)) self.graph_pool = pgl.nn.GraphPool(pool_type='sum') self.fc = nn.Linear(self.hidden_size, self.output_dim) elif self.gnn_type == "gat_gcn": self.gnn_layers.append(pgl.nn.GATConv( self._get_in_size(0), self.hidden_size, activation=self.activation, num_heads=self.gat_nheads, feat_drop=0.0, attn_drop=0.0)) self.gnn_layers.append(pgl.nn.GCNConv( self.hidden_size * self.gat_nheads, self.hidden_size * self.gat_nheads, activation=self.activation)) self.graph_max_pool = pgl.nn.GraphPool(pool_type='max') self.graph_avg_pool = MeanPool() dim = self.hidden_size * self.gat_nheads * 2 self.fc1 = nn.Linear(dim, 1500) self.act1 = nn.ReLU() self.fc2 = nn.Linear(1500, self.output_dim) self.dropout = nn.Dropout(p=self.dropout_rate) def _get_in_size(self, layer_id, gat_heads=None): in_size = self.embed_dim + self.atomic_numeric_feat_dim gat_heads = 1 if gat_heads is None else gat_heads if layer_id > 0: in_size = self.hidden_size * gat_heads return in_size def _mol_encoder(self, graph): x = self.atom_embedding(graph.node_feat) x = paddle.squeeze(x, axis=1) x = paddle.concat([x, graph.node_feat['atom_numeric_feat']], axis=1) return x def forward(self, graph): """Forward function. Args: graph (pgl.Graph): a PGL Graph instance. """ feat = self._mol_encoder(graph) for i in range(len(self.gnn_layers)): if isinstance(self.gnn_layers[i], nn.BatchNorm1D): feat = self.gnn_layers[i](feat) else: feat = self.gnn_layers[i](graph, feat) if self.gnn_type == 'gat_gcn': x1 = self.graph_max_pool(graph, feat) x2 = self.graph_avg_pool(graph, feat) feat = paddle.concat([x1, x2], axis=1) feat = self.dropout(self.act1(self.fc1(feat))) feat = self.fc2(feat) else: feat = self.graph_pool(graph, feat) feat = self.dropout(self.fc(feat)) return feat class ProteinSequenceModel(nn.Layer): """ | ProteinSequenceModel, implementation of Conv1D model for protein representation. Public Functions: - ``forward``: forward to create protein sequence representation. """ def __init__(self, config): super(ProteinSequenceModel, self).__init__() self.config = config self.output_dim = config['output_dim'] self.embed_dim = config['embed_dim'] self.max_protein_len = config['max_protein_len'] self.vocab_size = len(ProteinTokenizer.vocab) self.num_filters = config.get('num_filters', 32) self.pool_type = config.get('pool_type', 'mean') self.initializer_range = config.get('initializer_range', 0.02) self.protein_embeddings =nn.Embedding( self.vocab_size, self.embed_dim, weight_attr=nn.initializer.TruncatedNormal( std=self.initializer_range)) self.conv1d = nn.Conv1D( self.embed_dim, self.num_filters, kernel_size=8, padding='SAME', data_format='NLC') if self.max_protein_len < 0: self.fc = nn.Linear(self.num_filters, self.output_dim) else: self.fc = nn.Linear(self.num_filters * self.max_protein_len, self.output_dim) def forward(self, token, mask): """Forward. Args: token (Tensor): a tensor that represents the amino acid sequence as IDs. mask (Tensor): a tensor that marks whether the position is a valid amino acid or a padding. """ token_emb = self.protein_embeddings(token) feat = self.conv1d(token_emb) if self.max_protein_len < 0: # average pooling feat = feat * paddle.unsqueeze(mask, 2) feat = paddle.sum(feat, axis=1) / paddle.sum(mask, 1, keepdim=True) else: feat = paddle.reshape(feat, [-1, self.max_protein_len * self.num_filters]) feat = self.fc(feat) return feat class DTAModel(nn.Layer): """ | DTAModel, implementation of the network architecture in GraphDTA. Public Functions: - ``forward``: forward. """ def __init__(self, config): super(DTAModel, self).__init__() self.dropout_rate = config['dropout_rate'] self.compound_model = CompoundGNNModel(config['compound']) self.protein_model = ProteinSequenceModel(config['protein']) self.fc1 = nn.Linear(self.compound_model.output_dim + self.protein_model.output_dim, 1024) self.fc2 = nn.Linear(1024, 256) self.fc3 = nn.Linear(256, 1) self.act = nn.ReLU() self.dropout = nn.Dropout(p=self.dropout_rate) def forward(self, graph, protein_token, protein_mask): """Forward function. Args: graph (pgl.Graph): a PGL Graph instance. protein_token (Tensor): a tensor that represents the amino acid sequence as IDs. protein_mask (Tensor): a tensor that marks whether the position is a valid amino acid or a padding. """ compound_repr = self.compound_model(graph) protein_repr = self.protein_model(protein_token, protein_mask) compound_protein = paddle.concat( [compound_repr, protein_repr], axis=1) h = self.dropout(self.act(self.fc1(compound_protein))) h = self.dropout(self.act(self.fc2(h))) pred = self.fc3(h) return pred class DTAModelCriterion(nn.Layer): """ | DTAModelCriterion, implementation of MSE loss for DTA model. Public Functions: - ``forward``: forward function. """ def __init__(self): super(DTAModelCriterion, self).__init__() def forward(self, pred, label): """Forward function. Args: pred (Tensor): affinity predictions, i.e. output from DTAModel. label (Tensor): affinity label. """ loss = nn.functional.square_error_cost(pred, label) loss = paddle.mean(loss) return loss
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ DTA model """ import paddle import paddle.nn as nn import pgl from pahelix.networks.compound_encoder import AtomEmbedding from pahelix.utils.protein_tools import ProteinTokenizer from pahelix.networks.gnn_block import MeanPool class CompoundGNNModel(nn.Layer): """ | CompoundGNNModel, implementation of the variant GNN models in paper ``GraphDTA: Predicting drug-target binding affinity with graph neural networks``. Public Functions: - ``forward``: forward to create the compound representation. """ def __init__(self, config): super(CompoundGNNModel, self).__init__() self.hidden_size = config['hidden_size'] self.embed_dim = config['embed_dim'] self.output_dim = config['output_dim'] self.dropout_rate = config['dropout_rate'] self.layer_num = config['layer_num'] self.gnn_type = config['gnn_type'] self.gat_nheads = config.get('gat_nheads', 10) self.activation = config.get('activation', 'relu') self.atomic_numeric_feat_dim = config.get( 'atomic_numeric_feat_dim', 28) self.atom_names = config['atom_names'] self.bond_names = config['bond_names'] self.atom_embedding = AtomEmbedding(self.atom_names, self.embed_dim) self.gnn_layers = nn.LayerList() if self.gnn_type == 'gcn': for layer_id in range(self.layer_num): self.gnn_layers.append(pgl.nn.GCNConv( self._get_in_size(layer_id), self.hidden_size, activation=self.activation)) self.graph_pool = pgl.nn.GraphPool(pool_type='max') self.fc = nn.Linear(self.hidden_size, self.output_dim) elif self.gnn_type == 'gat': for layer_id in range(self.layer_num): self.gnn_layers.append(pgl.nn.GATConv( self._get_in_size(layer_id, self.gat_nheads), self.hidden_size, activation=self.activation, num_heads=self.gat_nheads, feat_drop=self.dropout_rate, attn_drop=self.dropout_rate)) self.graph_pool = pgl.nn.GraphPool(pool_type='max') in_size = self.hidden_size * self.gat_nheads self.fc = nn.Linear(in_size, self.output_dim) elif self.gnn_type == 'gin': for layer_id in range(self.layer_num): self.gnn_layers.append(pgl.nn.GINConv( self._get_in_size(layer_id), self.hidden_size, activation=self.activation)) self.gnn_layers.append( nn.BatchNorm1D(self.hidden_size)) self.graph_pool = pgl.nn.GraphPool(pool_type='sum') self.fc = nn.Linear(self.hidden_size, self.output_dim) elif self.gnn_type == "gat_gcn": self.gnn_layers.append(pgl.nn.GATConv( self._get_in_size(0), self.hidden_size, activation=self.activation, num_heads=self.gat_nheads, feat_drop=0.0, attn_drop=0.0)) self.gnn_layers.append(pgl.nn.GCNConv( self.hidden_size * self.gat_nheads, self.hidden_size * self.gat_nheads, activation=self.activation)) self.graph_max_pool = pgl.nn.GraphPool(pool_type='max') self.graph_avg_pool = MeanPool() dim = self.hidden_size * self.gat_nheads * 2 self.fc1 = nn.Linear(dim, 1500) self.act1 = nn.ReLU() self.fc2 = nn.Linear(1500, self.output_dim) self.dropout = nn.Dropout(p=self.dropout_rate) def _get_in_size(self, layer_id, gat_heads=None): in_size = self.embed_dim + self.atomic_numeric_feat_dim gat_heads = 1 if gat_heads is None else gat_heads if layer_id > 0: in_size = self.hidden_size * gat_heads return in_size def _mol_encoder(self, graph): x = self.atom_embedding(graph.node_feat) x = paddle.squeeze(x, axis=1) x = paddle.concat([x, graph.node_feat['atom_numeric_feat']], axis=1) return x def forward(self, graph): """Forward function. Args: graph (pgl.Graph): a PGL Graph instance. """ feat = self._mol_encoder(graph) for i in range(len(self.gnn_layers)): if isinstance(self.gnn_layers[i], nn.BatchNorm1D): feat = self.gnn_layers[i](feat) else: feat = self.gnn_layers[i](graph, feat) if self.gnn_type == 'gat_gcn': x1 = self.graph_max_pool(graph, feat) x2 = self.graph_avg_pool(graph, feat) feat = paddle.concat([x1, x2], axis=1) feat = self.dropout(self.act1(self.fc1(feat))) feat = self.fc2(feat) else: feat = self.graph_pool(graph, feat) feat = self.dropout(self.fc(feat)) return feat class ProteinSequenceModel(nn.Layer): """ | ProteinSequenceModel, implementation of Conv1D model for protein representation. Public Functions: - ``forward``: forward to create protein sequence representation. """ def __init__(self, config): super(ProteinSequenceModel, self).__init__() self.config = config self.output_dim = config['output_dim'] self.embed_dim = config['embed_dim'] self.max_protein_len = config['max_protein_len'] self.vocab_size = len(ProteinTokenizer.vocab) self.num_filters = config.get('num_filters', 32) self.pool_type = config.get('pool_type', 'mean') self.initializer_range = config.get('initializer_range', 0.02) self.protein_embeddings =nn.Embedding( self.vocab_size, self.embed_dim, weight_attr=nn.initializer.TruncatedNormal( std=self.initializer_range)) self.conv1d = nn.Conv1D( self.embed_dim, self.num_filters, kernel_size=8, padding='SAME', data_format='NLC') if self.max_protein_len < 0: self.fc = nn.Linear(self.num_filters, self.output_dim) else: self.fc = nn.Linear(self.num_filters * self.max_protein_len, self.output_dim) def forward(self, token, mask): """Forward. Args: token (Tensor): a tensor that represents the amino acid sequence as IDs. mask (Tensor): a tensor that marks whether the position is a valid amino acid or a padding. """ token_emb = self.protein_embeddings(token) feat = self.conv1d(token_emb) if self.max_protein_len < 0: # average pooling feat = feat * paddle.unsqueeze(mask, 2) feat = paddle.sum(feat, axis=1) / paddle.sum(mask, 1, keepdim=True) else: feat = paddle.reshape(feat, [-1, self.max_protein_len * self.num_filters]) feat = self.fc(feat) return feat class DTAModel(nn.Layer): """ | DTAModel, implementation of the network architecture in GraphDTA. Public Functions: - ``forward``: forward. """ def __init__(self, config): super(DTAModel, self).__init__() self.dropout_rate = config['dropout_rate'] self.compound_model = CompoundGNNModel(config['compound']) self.protein_model = ProteinSequenceModel(config['protein']) self.fc1 = nn.Linear(self.compound_model.output_dim + self.protein_model.output_dim, 1024) self.fc2 = nn.Linear(1024, 256) self.fc3 = nn.Linear(256, 1) self.act = nn.ReLU() self.dropout = nn.Dropout(p=self.dropout_rate) def forward(self, graph, protein_token, protein_mask): """Forward function. Args: graph (pgl.Graph): a PGL Graph instance. protein_token (Tensor): a tensor that represents the amino acid sequence as IDs. protein_mask (Tensor): a tensor that marks whether the position is a valid amino acid or a padding. """ compound_repr = self.compound_model(graph) protein_repr = self.protein_model(protein_token, protein_mask) compound_protein = paddle.concat( [compound_repr, protein_repr], axis=1) h = self.dropout(self.act(self.fc1(compound_protein))) h = self.dropout(self.act(self.fc2(h))) pred = self.fc3(h) return pred class DTAModelCriterion(nn.Layer): """ | DTAModelCriterion, implementation of MSE loss for DTA model. Public Functions: - ``forward``: forward function. """ def __init__(self): super(DTAModelCriterion, self).__init__() def forward(self, pred, label): """Forward function. Args: pred (Tensor): affinity predictions, i.e. output from DTAModel. label (Tensor): affinity label. """ loss = nn.functional.square_error_cost(pred, label) loss = paddle.mean(loss) return loss
en
0.803854
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. DTA model | CompoundGNNModel, implementation of the variant GNN models in paper ``GraphDTA: Predicting drug-target binding affinity with graph neural networks``. Public Functions: - ``forward``: forward to create the compound representation. Forward function. Args: graph (pgl.Graph): a PGL Graph instance. | ProteinSequenceModel, implementation of Conv1D model for protein representation. Public Functions: - ``forward``: forward to create protein sequence representation. Forward. Args: token (Tensor): a tensor that represents the amino acid sequence as IDs. mask (Tensor): a tensor that marks whether the position is a valid amino acid or a padding. # average pooling | DTAModel, implementation of the network architecture in GraphDTA. Public Functions: - ``forward``: forward. Forward function. Args: graph (pgl.Graph): a PGL Graph instance. protein_token (Tensor): a tensor that represents the amino acid sequence as IDs. protein_mask (Tensor): a tensor that marks whether the position is a valid amino acid or a padding. | DTAModelCriterion, implementation of MSE loss for DTA model. Public Functions: - ``forward``: forward function. Forward function. Args: pred (Tensor): affinity predictions, i.e. output from DTAModel. label (Tensor): affinity label.
2.12956
2
App/softwares_env/softwares/maya_wizard/auto_hair.py
Wizard-collab/wizard
0
6614267
import sys if sys.platform == "win32": import ctypes ctypes.windll.kernel32.SetDllDirectoryA(None) import maya.standalone maya.standalone.initialize() from wizard.tools import log from wizard.asset import main as asset_core from wizard.vars import defaults from wizard.prefs.main import prefs from wizard.tools import utility as utils from wizard.project import wall import traceback import logging import copy import os import sys from softwares.maya_wizard.export_anim import export_anim from softwares.maya_wizard.export_fur import export_fur from wizard.asset.reference import references path_to_append = os.path.abspath('softwares/') sys.path.append(path_to_append) from softwares.maya_wizard import reference_asset from wizard.asset import checker import maya.cmds as cmds #cmds.loadPlugin( allPlugins=True ) logger = log.pipe_log(__name__) logger.info(path_to_append) class auto_hair(): def __init__(self, string_asset, file, nspace_list, frange, comment = None, set_done = 1, refresh_assets = 0): self.asset = asset_core.string_to_asset(string_asset) self.string_asset = string_asset self.file = file self.nspace_list = nspace_list self.frange = frange self.references_dic = prefs().asset(self.asset).software.references self.comment = comment self.set_done = set_done self.refresh_assets = refresh_assets def auto_hair(self): for nspace in self.nspace_list: self.export_anim(nspace) self.rig_asset = asset_core.string_to_asset(self.references_dic[nspace][defaults._asset_key_]) if self.get_grooming_asset(): if self.match_geos(): if self.create_new_scene(): if self.get_exported_asset(): self.add_anim_reference() self.add_grooming_reference() self.build_scene() self.blendshape_shapes() self.export_hair() if self.set_done: print('status:Done !') else: logger.warning("No {} publish found for this asset : {}-{}".format(defaults._hair_, self.rig_asset.category, self.rig_asset.name)) def build_scene(self): os.environ[defaults._asset_var_] = utils.asset_to_string(self.cfx_asset) cmds.file( f=True, new=True ) reference_asset.import_anim() reference_asset.import_hair() cmds.file( rename=self.cfx_scene ) cmds.file( save=True, type='mayaAscii', f=True ) def blendshape_shapes(self): cmds.namespace( set=self.animation_namespace ) obj_list = cmds.namespaceInfo( listNamespace=True ) logger.info(obj_list) anim_obj_list = [] for obj in obj_list: logger.info(obj) relatives_list = cmds.listRelatives(obj, shapes = 1) if relatives_list and relatives_list != [] and len(relatives_list) == 1: if cmds.objectType(relatives_list[0]) == 'mesh': anim_obj_list.append(obj) logger.info(anim_obj_list) for obj in anim_obj_list: groom_obj = obj.replace(self.animation_namespace, '{}:{}'.format(self.hair_nspace, self.groom_geo_namespace)) logger.info(obj) logger.info(groom_obj) try: self.blend(obj, groom_obj) except: logger.info("Can't blendshape {} and {}".format(obj, groom_obj)) cmds.file( save=True, type='mayaAscii', f=True ) def blend(self, base, target): cmds.namespace( set=':' ) cmds.select(cl=1) blendShapeName = '{}_blendShape'.format(base.split(':')[-1]) cmds.blendShape(base, target, origin='world', name=blendShapeName, tc=1 ) cmds.setAttr(blendShapeName+'.'+(base.split(':')[-1]), 1) def add_anim_reference(self): references(self.cfx_asset).remove_all_references() count = references(self.cfx_asset).add_reference(self.export_asset, 0,1) self.animation_namespace = references(self.cfx_asset).get_name_space(self.export_asset, count) def match_geos(self): match = None rig_references = prefs().asset(self.rig_asset).software.references rig_geo_asset = None for reference in rig_references.keys(): asset = asset_core.string_to_asset(rig_references[reference][defaults._asset_key_]) logger.info(asset.variant) logger.info(self.rig_asset.variant) if asset.stage == defaults._geo_ and asset.name == self.rig_asset.name: rig_geo_asset = asset break groom_references = prefs().asset(self.grooming_asset).software.references grooming_geo_asset = None for reference in groom_references.keys(): asset = asset_core.string_to_asset(groom_references[reference][defaults._asset_key_]) if asset.stage == defaults._geo_ and asset.name == self.grooming_asset.name: grooming_geo_asset = asset self.groom_geo_namespace = reference break if rig_geo_asset: if grooming_geo_asset: if rig_geo_asset.export_version == grooming_geo_asset.export_version: match = 1 else: logger.warning("The geo imported in rig and the geo imported in grooming doesn't matchs") else: logger.warning("No geo imported in the grooming scene") else: logger.warning("No geo imported in the rig scene") return match def get_grooming_asset(self): self.grooming_asset = copy.deepcopy(self.rig_asset) self.grooming_asset.stage = defaults._hair_ presence = None if checker.check_stage_existence(self.grooming_asset): self.grooming_asset.variant = self.rig_asset.variant if not checker.check_variant_existence(self.grooming_asset): self.grooming_asset.variant = prefs().asset(self.grooming_asset).stage.default_variant if checker.check_variant_existence(self.grooming_asset): self.grooming_asset.export_asset = prefs().asset(self.grooming_asset).export_root.default_export_asset if self.grooming_asset.export_asset: self.grooming_asset.export_version = prefs().asset(self.grooming_asset).export.last_version presence = 1 return presence def add_grooming_reference(self): count = references(self.cfx_asset).add_reference(self.grooming_asset, 0,1) self.hair_nspace = references(self.cfx_asset).get_name_space(self.grooming_asset, count) def export_anim(self, nspace): export_anim(self.string_asset, self.file, [nspace], self.frange, set_done = 0, refresh_assets = self.refresh_assets).export_anim() def export_hair(self): string_asset = utils.asset_to_string(self.cfx_asset) export_fur(string_asset, self.cfx_scene, [self.hair_nspace], self.frange, set_done = 0).export_fur() def create_new_scene(self): stage_exists = 0 variant_exists = 0 self.cfx_asset = copy.deepcopy(self.asset) self.cfx_asset.stage = defaults._cfx_ self.cfx_asset.variant = 'auto_hair' if not checker.check_stage_existence(self.cfx_asset): self.cfx_asset.variant = None self.cfx_asset.software = None self.cfx_asset.version = None self.cfx_asset.export_asset = None self.cfx_asset.export_version = None if self.cfx_asset.create(): stage_exists = 1 else: stage_exists = 1 self.cfx_asset.variant = 'auto_hair' if not checker.check_variant_existence(self.cfx_asset): logger.info('LOL') self.cfx_asset.software = None self.cfx_asset.version = None self.cfx_asset.export_asset = None self.cfx_asset.export_version = None if self.cfx_asset.create(): variant_exists = 1 else: variant_exists = 1 if variant_exists and stage_exists: prefs().asset(self.cfx_asset).stage.set_default_variant('auto_hair') self.cfx_asset.software = prefs().asset(self.cfx_asset).variant.default_software self.cfx_asset.version = prefs().asset(self.cfx_asset).software.get_new_version() prefs().asset(self.cfx_asset).software.new_version(self.cfx_asset.version) self.cfx_scene = self.cfx_asset.file return (variant_exists * stage_exists) def get_exported_asset(self): self.export_asset = copy.deepcopy(self.asset) self.export_asset.export_asset = prefs().asset(self.export_asset).export_root.default_export_asset self.export_asset.export_version = prefs().asset(self.export_asset).export.last_version file = prefs().asset(self.export_asset).export.full_file if os.path.isfile(file): return 1 else: return 0
import sys if sys.platform == "win32": import ctypes ctypes.windll.kernel32.SetDllDirectoryA(None) import maya.standalone maya.standalone.initialize() from wizard.tools import log from wizard.asset import main as asset_core from wizard.vars import defaults from wizard.prefs.main import prefs from wizard.tools import utility as utils from wizard.project import wall import traceback import logging import copy import os import sys from softwares.maya_wizard.export_anim import export_anim from softwares.maya_wizard.export_fur import export_fur from wizard.asset.reference import references path_to_append = os.path.abspath('softwares/') sys.path.append(path_to_append) from softwares.maya_wizard import reference_asset from wizard.asset import checker import maya.cmds as cmds #cmds.loadPlugin( allPlugins=True ) logger = log.pipe_log(__name__) logger.info(path_to_append) class auto_hair(): def __init__(self, string_asset, file, nspace_list, frange, comment = None, set_done = 1, refresh_assets = 0): self.asset = asset_core.string_to_asset(string_asset) self.string_asset = string_asset self.file = file self.nspace_list = nspace_list self.frange = frange self.references_dic = prefs().asset(self.asset).software.references self.comment = comment self.set_done = set_done self.refresh_assets = refresh_assets def auto_hair(self): for nspace in self.nspace_list: self.export_anim(nspace) self.rig_asset = asset_core.string_to_asset(self.references_dic[nspace][defaults._asset_key_]) if self.get_grooming_asset(): if self.match_geos(): if self.create_new_scene(): if self.get_exported_asset(): self.add_anim_reference() self.add_grooming_reference() self.build_scene() self.blendshape_shapes() self.export_hair() if self.set_done: print('status:Done !') else: logger.warning("No {} publish found for this asset : {}-{}".format(defaults._hair_, self.rig_asset.category, self.rig_asset.name)) def build_scene(self): os.environ[defaults._asset_var_] = utils.asset_to_string(self.cfx_asset) cmds.file( f=True, new=True ) reference_asset.import_anim() reference_asset.import_hair() cmds.file( rename=self.cfx_scene ) cmds.file( save=True, type='mayaAscii', f=True ) def blendshape_shapes(self): cmds.namespace( set=self.animation_namespace ) obj_list = cmds.namespaceInfo( listNamespace=True ) logger.info(obj_list) anim_obj_list = [] for obj in obj_list: logger.info(obj) relatives_list = cmds.listRelatives(obj, shapes = 1) if relatives_list and relatives_list != [] and len(relatives_list) == 1: if cmds.objectType(relatives_list[0]) == 'mesh': anim_obj_list.append(obj) logger.info(anim_obj_list) for obj in anim_obj_list: groom_obj = obj.replace(self.animation_namespace, '{}:{}'.format(self.hair_nspace, self.groom_geo_namespace)) logger.info(obj) logger.info(groom_obj) try: self.blend(obj, groom_obj) except: logger.info("Can't blendshape {} and {}".format(obj, groom_obj)) cmds.file( save=True, type='mayaAscii', f=True ) def blend(self, base, target): cmds.namespace( set=':' ) cmds.select(cl=1) blendShapeName = '{}_blendShape'.format(base.split(':')[-1]) cmds.blendShape(base, target, origin='world', name=blendShapeName, tc=1 ) cmds.setAttr(blendShapeName+'.'+(base.split(':')[-1]), 1) def add_anim_reference(self): references(self.cfx_asset).remove_all_references() count = references(self.cfx_asset).add_reference(self.export_asset, 0,1) self.animation_namespace = references(self.cfx_asset).get_name_space(self.export_asset, count) def match_geos(self): match = None rig_references = prefs().asset(self.rig_asset).software.references rig_geo_asset = None for reference in rig_references.keys(): asset = asset_core.string_to_asset(rig_references[reference][defaults._asset_key_]) logger.info(asset.variant) logger.info(self.rig_asset.variant) if asset.stage == defaults._geo_ and asset.name == self.rig_asset.name: rig_geo_asset = asset break groom_references = prefs().asset(self.grooming_asset).software.references grooming_geo_asset = None for reference in groom_references.keys(): asset = asset_core.string_to_asset(groom_references[reference][defaults._asset_key_]) if asset.stage == defaults._geo_ and asset.name == self.grooming_asset.name: grooming_geo_asset = asset self.groom_geo_namespace = reference break if rig_geo_asset: if grooming_geo_asset: if rig_geo_asset.export_version == grooming_geo_asset.export_version: match = 1 else: logger.warning("The geo imported in rig and the geo imported in grooming doesn't matchs") else: logger.warning("No geo imported in the grooming scene") else: logger.warning("No geo imported in the rig scene") return match def get_grooming_asset(self): self.grooming_asset = copy.deepcopy(self.rig_asset) self.grooming_asset.stage = defaults._hair_ presence = None if checker.check_stage_existence(self.grooming_asset): self.grooming_asset.variant = self.rig_asset.variant if not checker.check_variant_existence(self.grooming_asset): self.grooming_asset.variant = prefs().asset(self.grooming_asset).stage.default_variant if checker.check_variant_existence(self.grooming_asset): self.grooming_asset.export_asset = prefs().asset(self.grooming_asset).export_root.default_export_asset if self.grooming_asset.export_asset: self.grooming_asset.export_version = prefs().asset(self.grooming_asset).export.last_version presence = 1 return presence def add_grooming_reference(self): count = references(self.cfx_asset).add_reference(self.grooming_asset, 0,1) self.hair_nspace = references(self.cfx_asset).get_name_space(self.grooming_asset, count) def export_anim(self, nspace): export_anim(self.string_asset, self.file, [nspace], self.frange, set_done = 0, refresh_assets = self.refresh_assets).export_anim() def export_hair(self): string_asset = utils.asset_to_string(self.cfx_asset) export_fur(string_asset, self.cfx_scene, [self.hair_nspace], self.frange, set_done = 0).export_fur() def create_new_scene(self): stage_exists = 0 variant_exists = 0 self.cfx_asset = copy.deepcopy(self.asset) self.cfx_asset.stage = defaults._cfx_ self.cfx_asset.variant = 'auto_hair' if not checker.check_stage_existence(self.cfx_asset): self.cfx_asset.variant = None self.cfx_asset.software = None self.cfx_asset.version = None self.cfx_asset.export_asset = None self.cfx_asset.export_version = None if self.cfx_asset.create(): stage_exists = 1 else: stage_exists = 1 self.cfx_asset.variant = 'auto_hair' if not checker.check_variant_existence(self.cfx_asset): logger.info('LOL') self.cfx_asset.software = None self.cfx_asset.version = None self.cfx_asset.export_asset = None self.cfx_asset.export_version = None if self.cfx_asset.create(): variant_exists = 1 else: variant_exists = 1 if variant_exists and stage_exists: prefs().asset(self.cfx_asset).stage.set_default_variant('auto_hair') self.cfx_asset.software = prefs().asset(self.cfx_asset).variant.default_software self.cfx_asset.version = prefs().asset(self.cfx_asset).software.get_new_version() prefs().asset(self.cfx_asset).software.new_version(self.cfx_asset.version) self.cfx_scene = self.cfx_asset.file return (variant_exists * stage_exists) def get_exported_asset(self): self.export_asset = copy.deepcopy(self.asset) self.export_asset.export_asset = prefs().asset(self.export_asset).export_root.default_export_asset self.export_asset.export_version = prefs().asset(self.export_asset).export.last_version file = prefs().asset(self.export_asset).export.full_file if os.path.isfile(file): return 1 else: return 0
ru
0.135395
#cmds.loadPlugin( allPlugins=True )
1.870782
2
polls/application/dictionary.py
jphacks/B_2015
0
6614268
import requests from bs4 import BeautifulSoup def make_synonym_dict(word): #word = input() synonym_dict={word:[]} url = "https://thesaurus.weblio.jp/content/" + word #headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'} r = requests.get(url) html = r.text bs = BeautifulSoup(html, 'html.parser') try: synonyms_table = bs.find_all("td" ,class_="nwntsR") #synonyms_table = bs.find_all("div" ,class_="Nwnts") for synonyms in synonyms_table: synonyms = synonyms.find_all("li")#class_='crosslink') #meanings = bs.select_one("#main > div:nth-of-type(13) > div > div.Nwnts > table > tbody > tr:nth-of-type(2) > td.nwntsR > ul > li:nth-of-type(1) > a").text for synonym in synonyms: if synonym.find(class_='crosslink')!=None: synonym = synonym.find(class_='crosslink') synonym_dict[word] += synonym.contents #print(synonym_dict) return synonym_dict except AttributeError: meanings = "そのような言葉は見つからなかったよ...。ごめんね。" print(meanings) return {} synonym_dict={} synonym_dict = make_synonym_dict("ぬこ") synonym_dict
import requests from bs4 import BeautifulSoup def make_synonym_dict(word): #word = input() synonym_dict={word:[]} url = "https://thesaurus.weblio.jp/content/" + word #headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'} r = requests.get(url) html = r.text bs = BeautifulSoup(html, 'html.parser') try: synonyms_table = bs.find_all("td" ,class_="nwntsR") #synonyms_table = bs.find_all("div" ,class_="Nwnts") for synonyms in synonyms_table: synonyms = synonyms.find_all("li")#class_='crosslink') #meanings = bs.select_one("#main > div:nth-of-type(13) > div > div.Nwnts > table > tbody > tr:nth-of-type(2) > td.nwntsR > ul > li:nth-of-type(1) > a").text for synonym in synonyms: if synonym.find(class_='crosslink')!=None: synonym = synonym.find(class_='crosslink') synonym_dict[word] += synonym.contents #print(synonym_dict) return synonym_dict except AttributeError: meanings = "そのような言葉は見つからなかったよ...。ごめんね。" print(meanings) return {} synonym_dict={} synonym_dict = make_synonym_dict("ぬこ") synonym_dict
en
0.289113
#word = input() #headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'} #synonyms_table = bs.find_all("div" ,class_="Nwnts") #class_='crosslink') #meanings = bs.select_one("#main > div:nth-of-type(13) > div > div.Nwnts > table > tbody > tr:nth-of-type(2) > td.nwntsR > ul > li:nth-of-type(1) > a").text #print(synonym_dict)
3.10405
3
utils.py
davtoh/product-web-page
1
6614269
import re def get_referer_view(request, default=None): ''' Return the referer view of the current request Example: def some_view(request): ... referer_view = get_referer_view(request) return HttpResponseRedirect(referer_view, '/accounts/login/') ''' # https://djangosnippets.org/snippets/1474/ # if the user typed the url directly in the browser's address bar referer = request.META.get('HTTP_REFERER') if not referer: return default # remove the protocol and split the url at the slashes referer = re.sub('^https?:\/\/', '', referer).split('/') if referer[0] != request.META.get('SERVER_NAME'): return default # add the slash at the relative path's view and finished referer = u'/' + u'/'.join(referer[1:]) return referer
import re def get_referer_view(request, default=None): ''' Return the referer view of the current request Example: def some_view(request): ... referer_view = get_referer_view(request) return HttpResponseRedirect(referer_view, '/accounts/login/') ''' # https://djangosnippets.org/snippets/1474/ # if the user typed the url directly in the browser's address bar referer = request.META.get('HTTP_REFERER') if not referer: return default # remove the protocol and split the url at the slashes referer = re.sub('^https?:\/\/', '', referer).split('/') if referer[0] != request.META.get('SERVER_NAME'): return default # add the slash at the relative path's view and finished referer = u'/' + u'/'.join(referer[1:]) return referer
en
0.631761
Return the referer view of the current request Example: def some_view(request): ... referer_view = get_referer_view(request) return HttpResponseRedirect(referer_view, '/accounts/login/') # https://djangosnippets.org/snippets/1474/ # if the user typed the url directly in the browser's address bar # remove the protocol and split the url at the slashes # add the slash at the relative path's view and finished
2.79878
3
server/app/services/publish/views/__init__.py
goodfree/ActorCloud
173
6614270
<reponame>goodfree/ActorCloud<gh_stars>100-1000 from flask import Blueprint bp = Blueprint('publish', __name__) from . import devices # noqa: E402 from . import timers # noqa: E402 __all__ = [ 'bp', 'devices', 'timers' ]
from flask import Blueprint bp = Blueprint('publish', __name__) from . import devices # noqa: E402 from . import timers # noqa: E402 __all__ = [ 'bp', 'devices', 'timers' ]
uz
0.245811
# noqa: E402 # noqa: E402
1.336698
1
test/simplerw.py
rhjdvsgsgks/RPi.GPIO-Odroid
9
6614271
<reponame>rhjdvsgsgks/RPi.GPIO-Odroid<gh_stars>1-10 #Read state of GPIO output on GPIO input #Use jumper wire from pin 13 to pin 31 #XU4 without shifter-shield pin 13 to pin 19 import RPi.GPIO as GPIO import time LedPinW = 27 # pin13, bcm27 LedPinR = 6 # pin31, bcm6 def setup(): GPIO.setmode(GPIO.BCM) # Number GPIOs by BCM chip numbering scheme GPIO.setup(LedPinR, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set LedPinR mode input GPIO.setup(LedPinW, GPIO.OUT) # Set LedPinW mode to output GPIO.output(LedPinW, GPIO.HIGH) # Set LedPinW pin high def blink(): while True: GPIO.output(LedPinW, GPIO.HIGH) # LedPinW high time.sleep(2) pstate=GPIO.input(LedPinR) # Read LedPinR print("*****Pin state (LedPinW HIGH) ", pstate, "*****\n") time.sleep(2) GPIO.output(LedPinW, GPIO.LOW) # LedPinW low time.sleep(2) pstate=GPIO.input(LedPinR) # Read LedPinR print("*****Pin state (LedPinW LOW) ", pstate, "*****\n") time.sleep(2) def shutdown(): GPIO.output(LedPinW, GPIO.LOW) # LedPinW low GPIO.setup(LedPinW, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # LedPinW input GPIO.cleanup() if __name__ == '__main__': # Program start print('To read output correctly, jumper pin 13 (bcm27) to pin 31 (bcm6)') print('Press Ctrl-C to exit') setup() print("Hardware information: ", GPIO.RPI_INFO) try: blink() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, shut down cleanly shutdown()
#Read state of GPIO output on GPIO input #Use jumper wire from pin 13 to pin 31 #XU4 without shifter-shield pin 13 to pin 19 import RPi.GPIO as GPIO import time LedPinW = 27 # pin13, bcm27 LedPinR = 6 # pin31, bcm6 def setup(): GPIO.setmode(GPIO.BCM) # Number GPIOs by BCM chip numbering scheme GPIO.setup(LedPinR, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set LedPinR mode input GPIO.setup(LedPinW, GPIO.OUT) # Set LedPinW mode to output GPIO.output(LedPinW, GPIO.HIGH) # Set LedPinW pin high def blink(): while True: GPIO.output(LedPinW, GPIO.HIGH) # LedPinW high time.sleep(2) pstate=GPIO.input(LedPinR) # Read LedPinR print("*****Pin state (LedPinW HIGH) ", pstate, "*****\n") time.sleep(2) GPIO.output(LedPinW, GPIO.LOW) # LedPinW low time.sleep(2) pstate=GPIO.input(LedPinR) # Read LedPinR print("*****Pin state (LedPinW LOW) ", pstate, "*****\n") time.sleep(2) def shutdown(): GPIO.output(LedPinW, GPIO.LOW) # LedPinW low GPIO.setup(LedPinW, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # LedPinW input GPIO.cleanup() if __name__ == '__main__': # Program start print('To read output correctly, jumper pin 13 (bcm27) to pin 31 (bcm6)') print('Press Ctrl-C to exit') setup() print("Hardware information: ", GPIO.RPI_INFO) try: blink() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, shut down cleanly shutdown()
en
0.751535
#Read state of GPIO output on GPIO input #Use jumper wire from pin 13 to pin 31 #XU4 without shifter-shield pin 13 to pin 19 # pin13, bcm27 # pin31, bcm6 # Number GPIOs by BCM chip numbering scheme # Set LedPinR mode input # Set LedPinW mode to output # Set LedPinW pin high # LedPinW high # Read LedPinR # LedPinW low # Read LedPinR # LedPinW low # LedPinW input # Program start # When 'Ctrl+C' is pressed, shut down cleanly
3.350093
3
project/project_code/azure/TestCases/test_azuresqldb.py
cybertraining-dsc/fa19-516-147
0
6614272
<gh_stars>0 import requests import logging import json import jsonpath def test_get_database(): # url = 'http://0.0.0.0:8080/cloudmesh/v3/ui/#/Database%20Registry/cloudmesh.database.get' url = 'http://0.0.0.0:8080/cloudmesh/v3/database' response = requests.get(url) assert response.status_code == 200 print(response.content) ''' def test_create_new_database(): file = open('create_database.json','r') json_input =file.read() request_json = json.loads(json_input) # put request with JSON input dfata response = requests.put(url, request_json) #validate response code assert response.status_code ==200 print(response.header.get('Content-Length')) #parse response to Json format response_json = json.loads(response.text) #pick id uisng Json Path id = jsonpath.jsonpath(respone_json,'id') print(id[0]) ''' def test_get_schema(): url = 'http://0.0.0.0:8080/cloudmesh/v3/database/absdb/schema/all' response = requests.get(url) assert response.status_code == 200 print(response.content) def test_put_schema(): url = 'http://0.0.0.0:8080/cloudmesh/v3/database/testdb/schema/pycheck_sch' # file = open('create_database.json','r') # json_input =file.read() # request_json = json.loads(json_input) # put request with JSON input dfata response = requests.put(url) #validate response code assert response.status_code == 500 #print(response.header.get('Content-Length')) #parse response to Json format #response_json = json.loads(response.text) #pick id uisng Json Path #id = jsonpath.jsonpath(respone_json,'id') #print(id[0])
import requests import logging import json import jsonpath def test_get_database(): # url = 'http://0.0.0.0:8080/cloudmesh/v3/ui/#/Database%20Registry/cloudmesh.database.get' url = 'http://0.0.0.0:8080/cloudmesh/v3/database' response = requests.get(url) assert response.status_code == 200 print(response.content) ''' def test_create_new_database(): file = open('create_database.json','r') json_input =file.read() request_json = json.loads(json_input) # put request with JSON input dfata response = requests.put(url, request_json) #validate response code assert response.status_code ==200 print(response.header.get('Content-Length')) #parse response to Json format response_json = json.loads(response.text) #pick id uisng Json Path id = jsonpath.jsonpath(respone_json,'id') print(id[0]) ''' def test_get_schema(): url = 'http://0.0.0.0:8080/cloudmesh/v3/database/absdb/schema/all' response = requests.get(url) assert response.status_code == 200 print(response.content) def test_put_schema(): url = 'http://0.0.0.0:8080/cloudmesh/v3/database/testdb/schema/pycheck_sch' # file = open('create_database.json','r') # json_input =file.read() # request_json = json.loads(json_input) # put request with JSON input dfata response = requests.put(url) #validate response code assert response.status_code == 500 #print(response.header.get('Content-Length')) #parse response to Json format #response_json = json.loads(response.text) #pick id uisng Json Path #id = jsonpath.jsonpath(respone_json,'id') #print(id[0])
en
0.32606
# url = 'http://0.0.0.0:8080/cloudmesh/v3/ui/#/Database%20Registry/cloudmesh.database.get' def test_create_new_database(): file = open('create_database.json','r') json_input =file.read() request_json = json.loads(json_input) # put request with JSON input dfata response = requests.put(url, request_json) #validate response code assert response.status_code ==200 print(response.header.get('Content-Length')) #parse response to Json format response_json = json.loads(response.text) #pick id uisng Json Path id = jsonpath.jsonpath(respone_json,'id') print(id[0]) # file = open('create_database.json','r') # json_input =file.read() # request_json = json.loads(json_input) # put request with JSON input dfata #validate response code #print(response.header.get('Content-Length')) #parse response to Json format #response_json = json.loads(response.text) #pick id uisng Json Path #id = jsonpath.jsonpath(respone_json,'id') #print(id[0])
2.563223
3
packages/m5flowui/v1.4.0/generic/frozen/flowlib/units/_makey.py
TheVinhLuong102/micropy-stubs
18
6614273
<reponame>TheVinhLuong102/micropy-stubs import unit, i2c_bus MAKEY_I2C_ADDR = const(0x51) class Makey: def __init__(self, port): self.i2c = i2c_bus.get(port) self._available() self.sing_map = [261, 293, 329, 349, 392, 440, 494, 294] def _available(self): if self.i2c.is_ready(MAKEY_I2C_ADDR) or self.i2c.is_ready(MAKEY_I2C_ADDR): pass else: raise unit.Unit("Makey unit maybe not connect") def _updateValue(self): value = 0 data = self.i2c.readfrom(MAKEY_I2C_ADDR, 2) value = data[0]|(data[1] << 8) return value @property def valueAll(self): return self._updateValue() @property def value(self): value = self._updateValue() for i in range(16): if (value >> i) & 0x01: return i return -1 # def playPiano(self, beat): # key_value = self.get_value() # time.sleep_ms(1) # for i in range(8): # if (key_value >> i) & 0x01: # speaker.sing(self.sing_map[i], beat) # break def deinit(self): pass
import unit, i2c_bus MAKEY_I2C_ADDR = const(0x51) class Makey: def __init__(self, port): self.i2c = i2c_bus.get(port) self._available() self.sing_map = [261, 293, 329, 349, 392, 440, 494, 294] def _available(self): if self.i2c.is_ready(MAKEY_I2C_ADDR) or self.i2c.is_ready(MAKEY_I2C_ADDR): pass else: raise unit.Unit("Makey unit maybe not connect") def _updateValue(self): value = 0 data = self.i2c.readfrom(MAKEY_I2C_ADDR, 2) value = data[0]|(data[1] << 8) return value @property def valueAll(self): return self._updateValue() @property def value(self): value = self._updateValue() for i in range(16): if (value >> i) & 0x01: return i return -1 # def playPiano(self, beat): # key_value = self.get_value() # time.sleep_ms(1) # for i in range(8): # if (key_value >> i) & 0x01: # speaker.sing(self.sing_map[i], beat) # break def deinit(self): pass
en
0.185827
# def playPiano(self, beat): # key_value = self.get_value() # time.sleep_ms(1) # for i in range(8): # if (key_value >> i) & 0x01: # speaker.sing(self.sing_map[i], beat) # break
2.68408
3
modules/effects/__init__.py
bira37/puzzle-effect-filter
1
6614274
# __init__.py from .effects_handler import apply_v1 from .effects_handler import add_background from .effects_handler import apply_relief_and_shadow
# __init__.py from .effects_handler import apply_v1 from .effects_handler import add_background from .effects_handler import apply_relief_and_shadow
ar
0.447093
# __init__.py
1.023618
1
homeschool/reports/views.py
brandonmcclure/homeschool
0
6614275
<gh_stars>0 import datetime import io import zipfile from decimal import ROUND_HALF_UP, Decimal from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.views.generic import TemplateView from homeschool.courses.models import CourseResource from homeschool.schools.models import SchoolYear from homeschool.students.models import Coursework, Enrollment, Grade class ReportsIndexView(LoginRequiredMixin, TemplateView): template_name = "reports/index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["nav_link"] = "reports" user = self.request.user context["enrollments"] = ( Enrollment.objects.filter(grade_level__school_year__school__admin=user) .select_related("student", "grade_level", "grade_level__school_year") .order_by("-grade_level__school_year__start_date", "student") ) context["school_years"] = SchoolYear.objects.filter( school__admin=user ).order_by("-start_date") return context class BundleView(LoginRequiredMixin, TemplateView): template_name = "reports/bundle.html" def get_context_data(self, **kwargs): user = self.request.user context = super().get_context_data(**kwargs) context["school_year"] = get_object_or_404( SchoolYear, pk=self.kwargs["pk"], school__admin=user ) return context @login_required def create_bundle(request, pk): user = request.user get_object_or_404(SchoolYear, pk=pk, school__admin=user) zip_file_data = io.BytesIO() with zipfile.ZipFile(zip_file_data, "w") as zip_file: zip_file.writestr("file1.txt", b"hello world") zip_file.writestr("file2.txt", b"hello world") filename = "bundle.zip" return HttpResponse( zip_file_data.getbuffer(), headers={ "Content-Type": "application/zip", "Content-Disposition": f'attachment; filename="{filename}"', }, ) class AttendanceReportView(LoginRequiredMixin, TemplateView): template_name = "reports/attendance_report.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user enrollment = get_object_or_404( Enrollment.objects.select_related( "student", "grade_level", "grade_level__school_year" ), pk=self.kwargs["pk"], grade_level__school_year__school=user.school, ) context["grade_level"] = enrollment.grade_level context["school_year"] = enrollment.grade_level.school_year context["student"] = enrollment.student context["school_dates"] = self._build_school_dates(enrollment) context["total_days_attended"] = sum( 1 for school_date in context["school_dates"] if school_date["attended"] ) return context def _build_school_dates(self, enrollment): """Collect all the school dates in the year to the end or today.""" dates_with_work = set( Coursework.objects.filter( student=enrollment.student, course_task__course__grade_levels__in=[enrollment.grade_level], ).values_list("completed_date", flat=True) ) school_dates = [] school_year = enrollment.grade_level.school_year school_date = school_year.start_date end_date = min(school_year.end_date, self.request.user.get_local_today()) while school_date <= end_date: school_dates.append( { "date": school_date, "is_school_day": school_year.runs_on(school_date), "is_break": school_year.is_break( school_date, student=enrollment.student ), "attended": school_date in dates_with_work, } ) school_date += datetime.timedelta(days=1) return school_dates class ProgressReportView(LoginRequiredMixin, TemplateView): template_name = "reports/progress_report.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user enrollment = get_object_or_404( Enrollment.objects.select_related( "student", "grade_level", "grade_level__school_year" ), pk=self.kwargs["pk"], grade_level__school_year__school=user.school, ) context["grade_level"] = enrollment.grade_level context["school_year"] = enrollment.grade_level.school_year context["student"] = enrollment.student course_id = self.request.GET.get("course") if course_id: qs_filter = Q(graded_work__course_task__course__id=course_id) else: qs_filter = Q( graded_work__course_task__course__grade_levels__in=[ enrollment.grade_level ] ) grades = ( Grade.objects.filter(qs_filter, student=enrollment.student) # Include secondary ordering so tasks are ordered in the course. .order_by( "graded_work__course_task__course", "graded_work__course_task" ).select_related( "graded_work__course_task", "graded_work__course_task__course" ) ) self._mixin_coursework(grades, enrollment.student) context["courses"] = self._build_courses_info(grades) return context def _mixin_coursework(self, grades, student): """Mix in the coursework for the grades. Coursework is added to the grades to display the completed dates. It is possible for a user to add a grade without the student finishing the task so the coursework can be None. """ tasks = [grade.graded_work.course_task for grade in grades] coursework_by_task_id = { coursework.course_task_id: coursework for coursework in Coursework.objects.filter( student=student, course_task__in=tasks ) } for grade in grades: grade.coursework = coursework_by_task_id.get( grade.graded_work.course_task_id ) def _build_courses_info(self, grades): """Regroup the grades into an appropriate display structure for the template. Grades must be sorted by course. """ if not grades: return [] courses = [] course = None course_info = {} for grade in grades: next_course = grade.graded_work.course_task.course if course != next_course: # Don't compute average until a course is collected. # On the first iteration when course is None, nothing is collected yet. if course is not None: self._compute_course_average(course_info) course = next_course course_info = {"course": course, "grades": [grade]} courses.append(course_info) else: course_info["grades"].append(grade) # Compute average of last course to catch the edge case. self._compute_course_average(course_info) return courses def _compute_course_average(self, course_info): """Compute the average for the course based on collected grades.""" grades = course_info["grades"] average = sum(grade.score for grade in grades) / len(grades) # Sane rounding. course_info["course_average"] = int(Decimal(average).quantize(0, ROUND_HALF_UP)) class ResourceReportView(LoginRequiredMixin, TemplateView): template_name = "reports/resource_report.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user enrollment = get_object_or_404( Enrollment.objects.select_related( "student", "grade_level", "grade_level__school_year" ), pk=self.kwargs["pk"], grade_level__school_year__school=user.school, ) context["grade_level"] = enrollment.grade_level context["school_year"] = enrollment.grade_level.school_year context["student"] = enrollment.student context["resources"] = ( CourseResource.objects.filter( course__grade_levels__in=[enrollment.grade_level] ) .select_related("course") .order_by("course") ) return context
import datetime import io import zipfile from decimal import ROUND_HALF_UP, Decimal from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.views.generic import TemplateView from homeschool.courses.models import CourseResource from homeschool.schools.models import SchoolYear from homeschool.students.models import Coursework, Enrollment, Grade class ReportsIndexView(LoginRequiredMixin, TemplateView): template_name = "reports/index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["nav_link"] = "reports" user = self.request.user context["enrollments"] = ( Enrollment.objects.filter(grade_level__school_year__school__admin=user) .select_related("student", "grade_level", "grade_level__school_year") .order_by("-grade_level__school_year__start_date", "student") ) context["school_years"] = SchoolYear.objects.filter( school__admin=user ).order_by("-start_date") return context class BundleView(LoginRequiredMixin, TemplateView): template_name = "reports/bundle.html" def get_context_data(self, **kwargs): user = self.request.user context = super().get_context_data(**kwargs) context["school_year"] = get_object_or_404( SchoolYear, pk=self.kwargs["pk"], school__admin=user ) return context @login_required def create_bundle(request, pk): user = request.user get_object_or_404(SchoolYear, pk=pk, school__admin=user) zip_file_data = io.BytesIO() with zipfile.ZipFile(zip_file_data, "w") as zip_file: zip_file.writestr("file1.txt", b"hello world") zip_file.writestr("file2.txt", b"hello world") filename = "bundle.zip" return HttpResponse( zip_file_data.getbuffer(), headers={ "Content-Type": "application/zip", "Content-Disposition": f'attachment; filename="{filename}"', }, ) class AttendanceReportView(LoginRequiredMixin, TemplateView): template_name = "reports/attendance_report.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user enrollment = get_object_or_404( Enrollment.objects.select_related( "student", "grade_level", "grade_level__school_year" ), pk=self.kwargs["pk"], grade_level__school_year__school=user.school, ) context["grade_level"] = enrollment.grade_level context["school_year"] = enrollment.grade_level.school_year context["student"] = enrollment.student context["school_dates"] = self._build_school_dates(enrollment) context["total_days_attended"] = sum( 1 for school_date in context["school_dates"] if school_date["attended"] ) return context def _build_school_dates(self, enrollment): """Collect all the school dates in the year to the end or today.""" dates_with_work = set( Coursework.objects.filter( student=enrollment.student, course_task__course__grade_levels__in=[enrollment.grade_level], ).values_list("completed_date", flat=True) ) school_dates = [] school_year = enrollment.grade_level.school_year school_date = school_year.start_date end_date = min(school_year.end_date, self.request.user.get_local_today()) while school_date <= end_date: school_dates.append( { "date": school_date, "is_school_day": school_year.runs_on(school_date), "is_break": school_year.is_break( school_date, student=enrollment.student ), "attended": school_date in dates_with_work, } ) school_date += datetime.timedelta(days=1) return school_dates class ProgressReportView(LoginRequiredMixin, TemplateView): template_name = "reports/progress_report.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user enrollment = get_object_or_404( Enrollment.objects.select_related( "student", "grade_level", "grade_level__school_year" ), pk=self.kwargs["pk"], grade_level__school_year__school=user.school, ) context["grade_level"] = enrollment.grade_level context["school_year"] = enrollment.grade_level.school_year context["student"] = enrollment.student course_id = self.request.GET.get("course") if course_id: qs_filter = Q(graded_work__course_task__course__id=course_id) else: qs_filter = Q( graded_work__course_task__course__grade_levels__in=[ enrollment.grade_level ] ) grades = ( Grade.objects.filter(qs_filter, student=enrollment.student) # Include secondary ordering so tasks are ordered in the course. .order_by( "graded_work__course_task__course", "graded_work__course_task" ).select_related( "graded_work__course_task", "graded_work__course_task__course" ) ) self._mixin_coursework(grades, enrollment.student) context["courses"] = self._build_courses_info(grades) return context def _mixin_coursework(self, grades, student): """Mix in the coursework for the grades. Coursework is added to the grades to display the completed dates. It is possible for a user to add a grade without the student finishing the task so the coursework can be None. """ tasks = [grade.graded_work.course_task for grade in grades] coursework_by_task_id = { coursework.course_task_id: coursework for coursework in Coursework.objects.filter( student=student, course_task__in=tasks ) } for grade in grades: grade.coursework = coursework_by_task_id.get( grade.graded_work.course_task_id ) def _build_courses_info(self, grades): """Regroup the grades into an appropriate display structure for the template. Grades must be sorted by course. """ if not grades: return [] courses = [] course = None course_info = {} for grade in grades: next_course = grade.graded_work.course_task.course if course != next_course: # Don't compute average until a course is collected. # On the first iteration when course is None, nothing is collected yet. if course is not None: self._compute_course_average(course_info) course = next_course course_info = {"course": course, "grades": [grade]} courses.append(course_info) else: course_info["grades"].append(grade) # Compute average of last course to catch the edge case. self._compute_course_average(course_info) return courses def _compute_course_average(self, course_info): """Compute the average for the course based on collected grades.""" grades = course_info["grades"] average = sum(grade.score for grade in grades) / len(grades) # Sane rounding. course_info["course_average"] = int(Decimal(average).quantize(0, ROUND_HALF_UP)) class ResourceReportView(LoginRequiredMixin, TemplateView): template_name = "reports/resource_report.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user enrollment = get_object_or_404( Enrollment.objects.select_related( "student", "grade_level", "grade_level__school_year" ), pk=self.kwargs["pk"], grade_level__school_year__school=user.school, ) context["grade_level"] = enrollment.grade_level context["school_year"] = enrollment.grade_level.school_year context["student"] = enrollment.student context["resources"] = ( CourseResource.objects.filter( course__grade_levels__in=[enrollment.grade_level] ) .select_related("course") .order_by("course") ) return context
en
0.921535
Collect all the school dates in the year to the end or today. # Include secondary ordering so tasks are ordered in the course. Mix in the coursework for the grades. Coursework is added to the grades to display the completed dates. It is possible for a user to add a grade without the student finishing the task so the coursework can be None. Regroup the grades into an appropriate display structure for the template. Grades must be sorted by course. # Don't compute average until a course is collected. # On the first iteration when course is None, nothing is collected yet. # Compute average of last course to catch the edge case. Compute the average for the course based on collected grades. # Sane rounding.
1.949279
2
JYTools/MyRequests.py
meisanggou/Tools
0
6614276
<reponame>meisanggou/Tools #! /usr/bin/env python # coding: utf-8 import thread import requests from json import dumps as json_dumps __author__ = 'ZhouHeng' class RequestsManager(object): def __init__(self, conn_error_code=-1, http_error_code=1): self._req = requests.session() self.conn_error_code = conn_error_code self.http_error_code = http_error_code self.verify_http_code = True @property def auth(self): return self._req.auth @auth.setter def auth(self, v): self._req.auth = v @property def headers(self): return self._req.headers @headers.setter def headers(self, v): self._req.headers = v def options(self, url, **kwargs): return self._req.options(url, **kwargs) def head(self, url, **kwargs): return self._req.head(url, **kwargs) def get(self, url, **kwargs): return self.request("get", url, **kwargs) def post(self, url, data=None, json=None, **kwargs): return self.request("post", url, data=data, json=json, **kwargs) def put(self, url, data=None, **kwargs): return self.request("put", url, data=data, **kwargs) def delete(self, url, **kwargs): return self.request("delete", url, **kwargs) def close(self): self._req.close() def request(self, method, url, **kwargs): as_thread = kwargs.pop("as_thread", False) if as_thread is True: return thread.start_new_thread(self.request, (method, url), kwargs) if "allow_redirects" not in kwargs: kwargs["allow_redirects"] = True body = kwargs.pop("body", None) if body is not None: if method == "GET": kwargs["params"] = body elif method == "POST" or method == "GET" or method == "DELETE": kwargs["json"] = body try: resp = self._req.request(method, url, **kwargs) except requests.ConnectionError as ce: if hasattr(ce.message, "reason") is True: msg = ce.message.reason else: msg = ce.message raise JYRequestsException(self.conn_error_code, url, message=msg, **kwargs) if self.verify_http_code is True and resp.status_code != 200: raise JYRequestsException(self.http_error_code, url, http_code=resp.status_code, **kwargs) return resp class JYRequestsException(Exception): def __init__(self, error_type, url, **kwargs): self.error_type = error_type self.url = url if "http_code" in kwargs: self.http_code = kwargs["http_code"] else: self.http_code = 0 if "message" in kwargs: self.message = str(kwargs["message"]) else: self.message = "" self.json = None self.data = None if "json" in kwargs: self.json = kwargs["json"] if "data" in kwargs: self.data = kwargs["data"] def __str__(self): exp_msg = {"url": self.url, "error": self.message, "http_code": self.http_code} if self.data is not None: exp_msg["data"] = self.data if self.json is not None: exp_msg["json"] = self.json return json_dumps(exp_msg)
#! /usr/bin/env python # coding: utf-8 import thread import requests from json import dumps as json_dumps __author__ = 'ZhouHeng' class RequestsManager(object): def __init__(self, conn_error_code=-1, http_error_code=1): self._req = requests.session() self.conn_error_code = conn_error_code self.http_error_code = http_error_code self.verify_http_code = True @property def auth(self): return self._req.auth @auth.setter def auth(self, v): self._req.auth = v @property def headers(self): return self._req.headers @headers.setter def headers(self, v): self._req.headers = v def options(self, url, **kwargs): return self._req.options(url, **kwargs) def head(self, url, **kwargs): return self._req.head(url, **kwargs) def get(self, url, **kwargs): return self.request("get", url, **kwargs) def post(self, url, data=None, json=None, **kwargs): return self.request("post", url, data=data, json=json, **kwargs) def put(self, url, data=None, **kwargs): return self.request("put", url, data=data, **kwargs) def delete(self, url, **kwargs): return self.request("delete", url, **kwargs) def close(self): self._req.close() def request(self, method, url, **kwargs): as_thread = kwargs.pop("as_thread", False) if as_thread is True: return thread.start_new_thread(self.request, (method, url), kwargs) if "allow_redirects" not in kwargs: kwargs["allow_redirects"] = True body = kwargs.pop("body", None) if body is not None: if method == "GET": kwargs["params"] = body elif method == "POST" or method == "GET" or method == "DELETE": kwargs["json"] = body try: resp = self._req.request(method, url, **kwargs) except requests.ConnectionError as ce: if hasattr(ce.message, "reason") is True: msg = ce.message.reason else: msg = ce.message raise JYRequestsException(self.conn_error_code, url, message=msg, **kwargs) if self.verify_http_code is True and resp.status_code != 200: raise JYRequestsException(self.http_error_code, url, http_code=resp.status_code, **kwargs) return resp class JYRequestsException(Exception): def __init__(self, error_type, url, **kwargs): self.error_type = error_type self.url = url if "http_code" in kwargs: self.http_code = kwargs["http_code"] else: self.http_code = 0 if "message" in kwargs: self.message = str(kwargs["message"]) else: self.message = "" self.json = None self.data = None if "json" in kwargs: self.json = kwargs["json"] if "data" in kwargs: self.data = kwargs["data"] def __str__(self): exp_msg = {"url": self.url, "error": self.message, "http_code": self.http_code} if self.data is not None: exp_msg["data"] = self.data if self.json is not None: exp_msg["json"] = self.json return json_dumps(exp_msg)
en
0.321189
#! /usr/bin/env python # coding: utf-8
2.716016
3
setup.py
scalabli/neuraldig
0
6614277
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup setup( name="neuraldig", install_requires=[ "numpy==1.21.0", "scipy==1.5", "pandas==1.0", "scikit-learn==0.22", "joblib==0.15", "nibabel==3.0.0", "lxml", "quo", ], )
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup setup( name="neuraldig", install_requires=[ "numpy==1.21.0", "scipy==1.5", "pandas==1.0", "scikit-learn==0.22", "joblib==0.15", "nibabel==3.0.0", "lxml", "quo", ], )
en
0.308914
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
1.081448
1
projects/07/Parser.py
anArkitect/Nand2Tetris
0
6614278
<filename>projects/07/Parser.py import re import sys class Parser(object): C_ARITHMETIC = 0 C_PUSH = 1 C_POP = 2 C_LABAL = 3 C_GOTO = 4 C_IF = 5 C_FUNCTION = 6 C_RETURN = 7 C_CALL = 8 arithmetics = ['add', 'sub', 'neg', 'eq', 'gt', 'lt', 'and', 'or', 'not'] _cmd_type = -1 # store the cotent of .vm file _lines = [] def __init__(self, input_file): file_name = input_file if not file_name.endswith('.vm'): print('Only .vm files are supported') exit(1) with open(file_name, 'r') as new_file: self._lines = new_file.read().split('\n') #print(self._lines) def has_more_commands(self): return self._lines != [] def advance(self): if self.has_more_commands(): new_command = self._remove_comment(self._lines.pop(0)) if new_command == '': return '' else: tokens = new_command.split() if tokens[0] in self.arithmetics: self._cmd_type = self.C_ARITHMETIC return tokens elif tokens[0] == 'push': self._cmd_type = self.C_PUSH return tokens elif tokens[0] == 'pop': self._cmd_type = self.C_POP return tokens else: print("There is no more commands in .vm file, ERROR #1") exit(1) def get_command_type(self): return self._cmd_type def _remove_comment(self, line): _comment_pattern_1 = re.compile(r'/\*.*?\*/') _comment_pattern_2 = re.compile(r'//.*') _new_line = _comment_pattern_2.sub('', _comment_pattern_1.sub('', line)) return _new_line def output(self): while(self.has_more_commands): val = self.advance() if val != '': #print("command type: " + str(self.get_command_type())) print(val)
<filename>projects/07/Parser.py import re import sys class Parser(object): C_ARITHMETIC = 0 C_PUSH = 1 C_POP = 2 C_LABAL = 3 C_GOTO = 4 C_IF = 5 C_FUNCTION = 6 C_RETURN = 7 C_CALL = 8 arithmetics = ['add', 'sub', 'neg', 'eq', 'gt', 'lt', 'and', 'or', 'not'] _cmd_type = -1 # store the cotent of .vm file _lines = [] def __init__(self, input_file): file_name = input_file if not file_name.endswith('.vm'): print('Only .vm files are supported') exit(1) with open(file_name, 'r') as new_file: self._lines = new_file.read().split('\n') #print(self._lines) def has_more_commands(self): return self._lines != [] def advance(self): if self.has_more_commands(): new_command = self._remove_comment(self._lines.pop(0)) if new_command == '': return '' else: tokens = new_command.split() if tokens[0] in self.arithmetics: self._cmd_type = self.C_ARITHMETIC return tokens elif tokens[0] == 'push': self._cmd_type = self.C_PUSH return tokens elif tokens[0] == 'pop': self._cmd_type = self.C_POP return tokens else: print("There is no more commands in .vm file, ERROR #1") exit(1) def get_command_type(self): return self._cmd_type def _remove_comment(self, line): _comment_pattern_1 = re.compile(r'/\*.*?\*/') _comment_pattern_2 = re.compile(r'//.*') _new_line = _comment_pattern_2.sub('', _comment_pattern_1.sub('', line)) return _new_line def output(self): while(self.has_more_commands): val = self.advance() if val != '': #print("command type: " + str(self.get_command_type())) print(val)
en
0.266871
# store the cotent of .vm file #print(self._lines) #1") #print("command type: " + str(self.get_command_type()))
3.127014
3
lektor_markdown_mactutor.py
davidferguson/lektor-markdown-mactutor
2
6614279
<reponame>davidferguson/lektor-markdown-mactutor # -*- coding: utf-8 -*- from lektor.pluginsystem import Plugin import mistune import re import commands.m_link import commands.gl_link import commands.ac_link import commands.e_link import commands.translation import commands.reference import commands.ovl_text import commands.center_text import commands.sub_text import commands.sup_text import commands.color_text import commands.bgcolor_text import commands.math_inline import commands.text_inline # list of plugins here. to add new ones, import them and add them to this list plugins = [ commands.m_link, commands.gl_link, commands.ac_link, commands.e_link, commands.translation, commands.reference, commands.ovl_text, commands.center_text, commands.sub_text, commands.sup_text, commands.color_text, commands.bgcolor_text, commands.math_inline, commands.text_inline ] class MarkdownMactutorPlugin(Plugin): name = 'Markdown MacTutor' description = u'Lektor plugin that adds custom markdown syntax used for MacTutor.' def on_markdown_config(self, config, **extra): # create inline and block lexers inline_lexer = mistune.InlineLexer(mistune.Renderer()) block_lexer = mistune.BlockLexer() # does an lexer already exist? if so, use that if 'inline' in config.options: inline_lexer = config.options['inline'] if 'block' in config.options: block_lexer = config.options['inline'] # loop through all enabled plugins for plugin in plugins: # select the correct lexer lexer = inline_lexer if plugin.type == 'block': lexer = block_lexer # add the plugin in setattr(lexer.rules, plugin.name, plugin.regex) # if there is a position and renderer, add that in too if hasattr(plugin, 'position') and hasattr(plugin, 'render'): lexer.default_rules.insert(plugin.position, plugin.name) setattr(lexer, 'output_%s' % plugin.name, plugin.render) # set the config to use these custom lexers config.options['inline'] = inline_lexer config.options['block'] = block_lexer
# -*- coding: utf-8 -*- from lektor.pluginsystem import Plugin import mistune import re import commands.m_link import commands.gl_link import commands.ac_link import commands.e_link import commands.translation import commands.reference import commands.ovl_text import commands.center_text import commands.sub_text import commands.sup_text import commands.color_text import commands.bgcolor_text import commands.math_inline import commands.text_inline # list of plugins here. to add new ones, import them and add them to this list plugins = [ commands.m_link, commands.gl_link, commands.ac_link, commands.e_link, commands.translation, commands.reference, commands.ovl_text, commands.center_text, commands.sub_text, commands.sup_text, commands.color_text, commands.bgcolor_text, commands.math_inline, commands.text_inline ] class MarkdownMactutorPlugin(Plugin): name = 'Markdown MacTutor' description = u'Lektor plugin that adds custom markdown syntax used for MacTutor.' def on_markdown_config(self, config, **extra): # create inline and block lexers inline_lexer = mistune.InlineLexer(mistune.Renderer()) block_lexer = mistune.BlockLexer() # does an lexer already exist? if so, use that if 'inline' in config.options: inline_lexer = config.options['inline'] if 'block' in config.options: block_lexer = config.options['inline'] # loop through all enabled plugins for plugin in plugins: # select the correct lexer lexer = inline_lexer if plugin.type == 'block': lexer = block_lexer # add the plugin in setattr(lexer.rules, plugin.name, plugin.regex) # if there is a position and renderer, add that in too if hasattr(plugin, 'position') and hasattr(plugin, 'render'): lexer.default_rules.insert(plugin.position, plugin.name) setattr(lexer, 'output_%s' % plugin.name, plugin.render) # set the config to use these custom lexers config.options['inline'] = inline_lexer config.options['block'] = block_lexer
en
0.826251
# -*- coding: utf-8 -*- # list of plugins here. to add new ones, import them and add them to this list # create inline and block lexers # does an lexer already exist? if so, use that # loop through all enabled plugins # select the correct lexer # add the plugin in # if there is a position and renderer, add that in too # set the config to use these custom lexers
2.574155
3
Labeling/labeled-3.py
ChiNasa511/FGCB-REU
0
6614280
f = mh.gaussian_filter(f, 4) f = (f> f.mean()) imshow(f) show()
f = mh.gaussian_filter(f, 4) f = (f> f.mean()) imshow(f) show()
none
1
1.913413
2
cnn/parameters_init.py
EmanueleLM/CNN
1
6614281
# -*- coding: utf-8 -*- """ Created on Tue Nov 28 19:40:10 2018 @author: Emanuele Parameters' initializaton functions: provides both the functions and the dictionary to initialize the weights of a given layer. """ import numpy as np def uniform(weights, bias=None, args=None): if args is None: if bias is None: weights = np.random.uniform(.0, 1., size=weights.shape) return weights else: weights = np.random.uniform(.0, 1., size=weights.shape) bias = np.random.uniform(.0, 1., size=bias.shape) return weights, bias else: if bias is None: weights = np.random.uniform(args[0], args[1], size=weights.shape) return weights else: weights = np.random.uniform(args[0], args[1], size=weights.shape) bias = np.random.uniform(args[0], args[1], size=bias.shape) return weights, bias def random(weights, bias=None, args=None): if args is None: if bias is None: weights = np.random.rand(weights.shape[0], weights.shape[1]) return weights else: weights = np.random.rand(weights.shape[0], weights.shape[1]) bias = np.random.rand(bias.shape[0], bias.shape[1]) return weights, bias else: if bias is None: weights = np.random.rand(weights.shape[0], weights.shape[1]) return weights else: weights = np.random.rand(weights.shape[0], weights.shape[1]) bias = np.random.rand(bias.shape[0], bias.shape[1]) return weights, bias dict_parameters_init = { 'uniform': uniform, 'random': random }
# -*- coding: utf-8 -*- """ Created on Tue Nov 28 19:40:10 2018 @author: Emanuele Parameters' initializaton functions: provides both the functions and the dictionary to initialize the weights of a given layer. """ import numpy as np def uniform(weights, bias=None, args=None): if args is None: if bias is None: weights = np.random.uniform(.0, 1., size=weights.shape) return weights else: weights = np.random.uniform(.0, 1., size=weights.shape) bias = np.random.uniform(.0, 1., size=bias.shape) return weights, bias else: if bias is None: weights = np.random.uniform(args[0], args[1], size=weights.shape) return weights else: weights = np.random.uniform(args[0], args[1], size=weights.shape) bias = np.random.uniform(args[0], args[1], size=bias.shape) return weights, bias def random(weights, bias=None, args=None): if args is None: if bias is None: weights = np.random.rand(weights.shape[0], weights.shape[1]) return weights else: weights = np.random.rand(weights.shape[0], weights.shape[1]) bias = np.random.rand(bias.shape[0], bias.shape[1]) return weights, bias else: if bias is None: weights = np.random.rand(weights.shape[0], weights.shape[1]) return weights else: weights = np.random.rand(weights.shape[0], weights.shape[1]) bias = np.random.rand(bias.shape[0], bias.shape[1]) return weights, bias dict_parameters_init = { 'uniform': uniform, 'random': random }
en
0.768341
# -*- coding: utf-8 -*- Created on Tue Nov 28 19:40:10 2018 @author: Emanuele Parameters' initializaton functions: provides both the functions and the dictionary to initialize the weights of a given layer.
3.700682
4
build/lib/divis/pipelines.py
niu-lab/DIVIS
3
6614282
<filename>build/lib/divis/pipelines.py<gh_stars>1-10 import sys import os from divis.utils import dir_create from divis.flows import FLOWS_DICT from divis.macros import DEFAULT_MACROS_DICT from divis.macros import read_macros, write_macros from divis.steps import flow_run from multiprocessing import Process def somatic_pipeline(preview, input_macros_file, out_dir): # create out directory out_dir = os.path.abspath(out_dir) dir_create(out_dir) total_macros = read_macros(input_macros_file) # align normal_r1 = total_macros.get("NORMAL_R1") if not normal_r1: sys.stderr.write("can't find NORMAL_R1" + os.linesep) exit(1) normal_r2 = total_macros.get("NORMAL_R2") if not normal_r2: sys.stderr.write("can't find NORMAL_R2" + os.linesep) exit(1) tumor_r1 = total_macros.get("TUMOR_R1") if not tumor_r1: sys.stderr.write("can't find TUMOR_R1" + os.linesep) exit(1) tumor_r2 = total_macros.get("TUMOR_R2") if not tumor_r2: sys.stderr.write("can't find TUMOR_R2" + os.linesep) exit(1) sample_name = total_macros.get("SAMPLE_NAME") if not sample_name: sys.stderr.write("can't find SAMPLE_NAME" + os.linesep) exit(1) platform = total_macros.get("PLATFORM") if not platform: sys.stderr.write("can't find PLATFORM" + os.linesep) exit(1) normal_rg = '\'@RG\\tID:{sample_name}_N\\tSM:{sample_name}_N\\tLB:{sample_name}_N\\tPL:{platform}\''.format( sample_name=sample_name, platform=platform) tumor_rg = '\'@RG\\tID:{sample_name}_T\\tSM:{sample_name}_T\\tLB:{sample_name}_T\\tPL:{platform}\''.format( sample_name=sample_name, platform=platform) align_macros = read_macros(DEFAULT_MACROS_DICT.get("align")) for align_macro in align_macros: if align_macro in total_macros: align_macros[align_macro] = total_macros[align_macro] # normal align macro align_macros["R1"] = normal_r1 align_macros["R2"] = normal_r2 align_macros["RG"] = normal_rg align_macros["SAMPLE_NAME"] = "{}_normal".format(sample_name) normal_macros_file = os.path.join(out_dir, "normal.align.macros") write_macros(align_macros, normal_macros_file) # tumor align macros align_macros["R1"] = tumor_r1 align_macros["R2"] = tumor_r2 align_macros["RG"] = tumor_rg align_macros["SAMPLE_NAME"] = "{}_tumor".format(sample_name) tumor_macros_file = os.path.join(out_dir, "tumor.align.macros") write_macros(align_macros, tumor_macros_file) # normal align normal_align_dir = os.path.join(out_dir, "normal_align") print("------ normal align ------") normal_align_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("align"), normal_macros_file, normal_align_dir)) normal_align_thread.start() # tumor align tumor_align_dir = os.path.join(out_dir, "tumor_align") print("------ tumor align ------") tumor_align_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("align"), tumor_macros_file, tumor_align_dir)) tumor_align_thread.start() normal_align_thread.join() tumor_align_thread.join() # VSP variants calling # varscan somatic # print("------ varscan somatic ------") # varscan_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("varscan_somatic")) # for macro in varscan_somatic_macros: # if macro in total_macros: # varscan_somatic_macros[macro] = total_macros[macro] # # varscan_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # varscan_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # varscan_somatic_macros_file = os.path.join(out_dir, "varscan_somatic.macros") # write_macros(varscan_somatic_macros, varscan_somatic_macros_file) # varscan_somatic_dir = os.path.join(out_dir, "varscan_somatic") # varscan_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("varscan_somatic"), # varscan_somatic_macros_file, # varscan_somatic_dir)) # varscan_thread.start() # # # strelka somatic # print("------ strelka somatic ------") # strelka_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("strelka_somatic")) # for macro in strelka_somatic_macros: # if macro in total_macros: # strelka_somatic_macros[macro] = total_macros[macro] # # strelka_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # strelka_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # strelka_somatic_macros_file = os.path.join(out_dir, "strelka_somatic.macros") # write_macros(strelka_somatic_macros, strelka_somatic_macros_file) # strelka_somatic_dir = os.path.join(out_dir, "strelka_somatic") # strelka_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("strelka_somatic"), # strelka_somatic_macros_file, # strelka_somatic_dir)) # strelka_thread.start() # # # pindel somatic # print("------ pindel somatic ------") # pindel_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("pindel_somatic")) # for macro in pindel_somatic_macros: # if macro in total_macros: # pindel_somatic_macros[macro] = total_macros[macro] # # pindel_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # pindel_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # pindel_somatic_macros_file = os.path.join(out_dir, "pindel_somatic.macros") # write_macros(pindel_somatic_macros, pindel_somatic_macros_file) # pindel_somatic_dir = os.path.join(out_dir, "pindel_somatic") # pindel_thread = Process(target=flow_run, args=(preview, # FLOWS_DICT.get("pindel_somatic"), # pindel_somatic_macros_file, # pindel_somatic_dir)) # pindel_thread.start() # # varscan_thread.join() # strelka_thread.join() # pindel_thread.join() # # # annotation # print("------ oncotator annotation ------") # oncotator_macros = read_macros(DEFAULT_MACROS_DICT.get("oncotator")) # for macro in oncotator_macros: # if macro in total_macros: # oncotator_macros[macro] = total_macros[macro] # # vcfs = "{varscan_dir}/{sample_name}.indel.vcf " \ # "{varscan_dir}/{sample_name}.snp.vcf " \ # "{strelka_dir}/strelk_out/results/passed.somatic.indels.vcf " \ # "{strelka_dir}/strelk_out/results/passed.somatic.snvs.vcf " \ # "{pindel_dir}/{sample_name}.somatic.delete.vcf " \ # "{pindel_dir}/{sample_name}.somatic.insert.vcf ".format(varscan_dir=varscan_somatic_dir, # strelka_dir=strelka_somatic_dir, # pindel_dir=pindel_somatic_dir, # sample_name=sample_name) # oncotator_macros["VCFS"] = vcfs # oncotator_macros["NORMAL_BARCODE"] = "{}_normal".format(sample_name) # oncotator_macros["TUMOR_BARCODE"] = "{}_tumor".format(sample_name) # oncotator_macros_file = os.path.join(out_dir, "oncotator.macros") # write_macros(oncotator_macros, oncotator_macros_file) # oncotator_dir = os.path.join(out_dir, "oncotator") # oncotator_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("oncotator"), # oncotator_macros_file, # oncotator_dir)) # oncotator_thread.start() # oncotator_thread.join() pass def gatk4_haplotypecaller_germline_pipeline(preview, in_macro_file, out_dir): # create out directory out_dir = os.path.abspath(out_dir) dir_create(out_dir) total_macros = read_macros(in_macro_file) # quality control qc_macros = read_macros(DEFAULT_MACROS_DICT.get("qc")) for qc_macro in qc_macros: if qc_macro in total_macros: qc_macros[qc_macro] = total_macros[qc_macro] qc_macros_file = os.path.join(out_dir, "qc.macros") write_macros(qc_macros, qc_macros_file) qc_dir = os.path.join(out_dir, "qc") print("------ quality control ------") flow_run(preview, FLOWS_DICT.get("qc"), qc_macros_file, qc_dir) # alignment align_macros = read_macros(DEFAULT_MACROS_DICT.get("align")) for align_macro in align_macros: if align_macro in total_macros: align_macros[align_macro] = total_macros[align_macro] sample_name = total_macros.get("SAMPLE_NAME") platform = total_macros.get("PLATFORM") rg = '\'@RG\\tID:{sample_name}\\tSM:{sample_name}\\tLB:{sample_name}\\tPL:{platform}\''.format( sample_name=sample_name, platform=platform) align_macros["RG"] = rg align_macros_file = os.path.join(out_dir, "align.macros") write_macros(align_macros, align_macros_file) align_dir = os.path.join(out_dir, "align") print("------ align ------") flow_run(preview, FLOWS_DICT.get("align"), align_macros_file, align_dir) # variants calling bam_file = os.path.join(align_dir, "{}.bam".format(sample_name)) gatk4_haplotypecaller_macros = read_macros(DEFAULT_MACROS_DICT.get("gatk4_haplotypecaller_germline")) for gatk4_haplotypecaller_macro in gatk4_haplotypecaller_macros: if gatk4_haplotypecaller_macro in total_macros: gatk4_haplotypecaller_macros[gatk4_haplotypecaller_macro] = total_macros[gatk4_haplotypecaller_macro] gatk4_haplotypecaller_macros["BAM_FILE"] = bam_file gatk4_haplotypecaller_macros_file = os.path.join(out_dir, "gatk4_haplotypecaller_germline.macros") write_macros(gatk4_haplotypecaller_macros, gatk4_haplotypecaller_macros_file) gatk4_haplotypecaller_dir = os.path.join(out_dir, "gatk4_haplotypecaller") print("------ variants calling ------") flow_run(preview, FLOWS_DICT.get("gatk4_haplotypecaller_germline"), gatk4_haplotypecaller_macros_file, gatk4_haplotypecaller_dir) pass PIPELINE_FUNCS = { "wes_somatic": somatic_pipeline, "wgs_somatic": somatic_pipeline, "panel_germline": gatk4_haplotypecaller_germline_pipeline, } def pipeline_run(pipeline_name, preview, input_macros_file, out_dir): func = PIPELINE_FUNCS.get(pipeline_name) if not func: sys.stderr.write("can't find {} pipeline".format(pipeline_name) + os.linesep) func(preview, input_macros_file, out_dir)
<filename>build/lib/divis/pipelines.py<gh_stars>1-10 import sys import os from divis.utils import dir_create from divis.flows import FLOWS_DICT from divis.macros import DEFAULT_MACROS_DICT from divis.macros import read_macros, write_macros from divis.steps import flow_run from multiprocessing import Process def somatic_pipeline(preview, input_macros_file, out_dir): # create out directory out_dir = os.path.abspath(out_dir) dir_create(out_dir) total_macros = read_macros(input_macros_file) # align normal_r1 = total_macros.get("NORMAL_R1") if not normal_r1: sys.stderr.write("can't find NORMAL_R1" + os.linesep) exit(1) normal_r2 = total_macros.get("NORMAL_R2") if not normal_r2: sys.stderr.write("can't find NORMAL_R2" + os.linesep) exit(1) tumor_r1 = total_macros.get("TUMOR_R1") if not tumor_r1: sys.stderr.write("can't find TUMOR_R1" + os.linesep) exit(1) tumor_r2 = total_macros.get("TUMOR_R2") if not tumor_r2: sys.stderr.write("can't find TUMOR_R2" + os.linesep) exit(1) sample_name = total_macros.get("SAMPLE_NAME") if not sample_name: sys.stderr.write("can't find SAMPLE_NAME" + os.linesep) exit(1) platform = total_macros.get("PLATFORM") if not platform: sys.stderr.write("can't find PLATFORM" + os.linesep) exit(1) normal_rg = '\'@RG\\tID:{sample_name}_N\\tSM:{sample_name}_N\\tLB:{sample_name}_N\\tPL:{platform}\''.format( sample_name=sample_name, platform=platform) tumor_rg = '\'@RG\\tID:{sample_name}_T\\tSM:{sample_name}_T\\tLB:{sample_name}_T\\tPL:{platform}\''.format( sample_name=sample_name, platform=platform) align_macros = read_macros(DEFAULT_MACROS_DICT.get("align")) for align_macro in align_macros: if align_macro in total_macros: align_macros[align_macro] = total_macros[align_macro] # normal align macro align_macros["R1"] = normal_r1 align_macros["R2"] = normal_r2 align_macros["RG"] = normal_rg align_macros["SAMPLE_NAME"] = "{}_normal".format(sample_name) normal_macros_file = os.path.join(out_dir, "normal.align.macros") write_macros(align_macros, normal_macros_file) # tumor align macros align_macros["R1"] = tumor_r1 align_macros["R2"] = tumor_r2 align_macros["RG"] = tumor_rg align_macros["SAMPLE_NAME"] = "{}_tumor".format(sample_name) tumor_macros_file = os.path.join(out_dir, "tumor.align.macros") write_macros(align_macros, tumor_macros_file) # normal align normal_align_dir = os.path.join(out_dir, "normal_align") print("------ normal align ------") normal_align_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("align"), normal_macros_file, normal_align_dir)) normal_align_thread.start() # tumor align tumor_align_dir = os.path.join(out_dir, "tumor_align") print("------ tumor align ------") tumor_align_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("align"), tumor_macros_file, tumor_align_dir)) tumor_align_thread.start() normal_align_thread.join() tumor_align_thread.join() # VSP variants calling # varscan somatic # print("------ varscan somatic ------") # varscan_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("varscan_somatic")) # for macro in varscan_somatic_macros: # if macro in total_macros: # varscan_somatic_macros[macro] = total_macros[macro] # # varscan_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # varscan_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # varscan_somatic_macros_file = os.path.join(out_dir, "varscan_somatic.macros") # write_macros(varscan_somatic_macros, varscan_somatic_macros_file) # varscan_somatic_dir = os.path.join(out_dir, "varscan_somatic") # varscan_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("varscan_somatic"), # varscan_somatic_macros_file, # varscan_somatic_dir)) # varscan_thread.start() # # # strelka somatic # print("------ strelka somatic ------") # strelka_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("strelka_somatic")) # for macro in strelka_somatic_macros: # if macro in total_macros: # strelka_somatic_macros[macro] = total_macros[macro] # # strelka_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # strelka_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # strelka_somatic_macros_file = os.path.join(out_dir, "strelka_somatic.macros") # write_macros(strelka_somatic_macros, strelka_somatic_macros_file) # strelka_somatic_dir = os.path.join(out_dir, "strelka_somatic") # strelka_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("strelka_somatic"), # strelka_somatic_macros_file, # strelka_somatic_dir)) # strelka_thread.start() # # # pindel somatic # print("------ pindel somatic ------") # pindel_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("pindel_somatic")) # for macro in pindel_somatic_macros: # if macro in total_macros: # pindel_somatic_macros[macro] = total_macros[macro] # # pindel_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # pindel_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # pindel_somatic_macros_file = os.path.join(out_dir, "pindel_somatic.macros") # write_macros(pindel_somatic_macros, pindel_somatic_macros_file) # pindel_somatic_dir = os.path.join(out_dir, "pindel_somatic") # pindel_thread = Process(target=flow_run, args=(preview, # FLOWS_DICT.get("pindel_somatic"), # pindel_somatic_macros_file, # pindel_somatic_dir)) # pindel_thread.start() # # varscan_thread.join() # strelka_thread.join() # pindel_thread.join() # # # annotation # print("------ oncotator annotation ------") # oncotator_macros = read_macros(DEFAULT_MACROS_DICT.get("oncotator")) # for macro in oncotator_macros: # if macro in total_macros: # oncotator_macros[macro] = total_macros[macro] # # vcfs = "{varscan_dir}/{sample_name}.indel.vcf " \ # "{varscan_dir}/{sample_name}.snp.vcf " \ # "{strelka_dir}/strelk_out/results/passed.somatic.indels.vcf " \ # "{strelka_dir}/strelk_out/results/passed.somatic.snvs.vcf " \ # "{pindel_dir}/{sample_name}.somatic.delete.vcf " \ # "{pindel_dir}/{sample_name}.somatic.insert.vcf ".format(varscan_dir=varscan_somatic_dir, # strelka_dir=strelka_somatic_dir, # pindel_dir=pindel_somatic_dir, # sample_name=sample_name) # oncotator_macros["VCFS"] = vcfs # oncotator_macros["NORMAL_BARCODE"] = "{}_normal".format(sample_name) # oncotator_macros["TUMOR_BARCODE"] = "{}_tumor".format(sample_name) # oncotator_macros_file = os.path.join(out_dir, "oncotator.macros") # write_macros(oncotator_macros, oncotator_macros_file) # oncotator_dir = os.path.join(out_dir, "oncotator") # oncotator_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("oncotator"), # oncotator_macros_file, # oncotator_dir)) # oncotator_thread.start() # oncotator_thread.join() pass def gatk4_haplotypecaller_germline_pipeline(preview, in_macro_file, out_dir): # create out directory out_dir = os.path.abspath(out_dir) dir_create(out_dir) total_macros = read_macros(in_macro_file) # quality control qc_macros = read_macros(DEFAULT_MACROS_DICT.get("qc")) for qc_macro in qc_macros: if qc_macro in total_macros: qc_macros[qc_macro] = total_macros[qc_macro] qc_macros_file = os.path.join(out_dir, "qc.macros") write_macros(qc_macros, qc_macros_file) qc_dir = os.path.join(out_dir, "qc") print("------ quality control ------") flow_run(preview, FLOWS_DICT.get("qc"), qc_macros_file, qc_dir) # alignment align_macros = read_macros(DEFAULT_MACROS_DICT.get("align")) for align_macro in align_macros: if align_macro in total_macros: align_macros[align_macro] = total_macros[align_macro] sample_name = total_macros.get("SAMPLE_NAME") platform = total_macros.get("PLATFORM") rg = '\'@RG\\tID:{sample_name}\\tSM:{sample_name}\\tLB:{sample_name}\\tPL:{platform}\''.format( sample_name=sample_name, platform=platform) align_macros["RG"] = rg align_macros_file = os.path.join(out_dir, "align.macros") write_macros(align_macros, align_macros_file) align_dir = os.path.join(out_dir, "align") print("------ align ------") flow_run(preview, FLOWS_DICT.get("align"), align_macros_file, align_dir) # variants calling bam_file = os.path.join(align_dir, "{}.bam".format(sample_name)) gatk4_haplotypecaller_macros = read_macros(DEFAULT_MACROS_DICT.get("gatk4_haplotypecaller_germline")) for gatk4_haplotypecaller_macro in gatk4_haplotypecaller_macros: if gatk4_haplotypecaller_macro in total_macros: gatk4_haplotypecaller_macros[gatk4_haplotypecaller_macro] = total_macros[gatk4_haplotypecaller_macro] gatk4_haplotypecaller_macros["BAM_FILE"] = bam_file gatk4_haplotypecaller_macros_file = os.path.join(out_dir, "gatk4_haplotypecaller_germline.macros") write_macros(gatk4_haplotypecaller_macros, gatk4_haplotypecaller_macros_file) gatk4_haplotypecaller_dir = os.path.join(out_dir, "gatk4_haplotypecaller") print("------ variants calling ------") flow_run(preview, FLOWS_DICT.get("gatk4_haplotypecaller_germline"), gatk4_haplotypecaller_macros_file, gatk4_haplotypecaller_dir) pass PIPELINE_FUNCS = { "wes_somatic": somatic_pipeline, "wgs_somatic": somatic_pipeline, "panel_germline": gatk4_haplotypecaller_germline_pipeline, } def pipeline_run(pipeline_name, preview, input_macros_file, out_dir): func = PIPELINE_FUNCS.get(pipeline_name) if not func: sys.stderr.write("can't find {} pipeline".format(pipeline_name) + os.linesep) func(preview, input_macros_file, out_dir)
en
0.335403
# create out directory # align # normal align macro # tumor align macros # normal align # tumor align # VSP variants calling # varscan somatic # print("------ varscan somatic ------") # varscan_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("varscan_somatic")) # for macro in varscan_somatic_macros: # if macro in total_macros: # varscan_somatic_macros[macro] = total_macros[macro] # # varscan_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # varscan_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # varscan_somatic_macros_file = os.path.join(out_dir, "varscan_somatic.macros") # write_macros(varscan_somatic_macros, varscan_somatic_macros_file) # varscan_somatic_dir = os.path.join(out_dir, "varscan_somatic") # varscan_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("varscan_somatic"), # varscan_somatic_macros_file, # varscan_somatic_dir)) # varscan_thread.start() # # # strelka somatic # print("------ strelka somatic ------") # strelka_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("strelka_somatic")) # for macro in strelka_somatic_macros: # if macro in total_macros: # strelka_somatic_macros[macro] = total_macros[macro] # # strelka_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # strelka_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # strelka_somatic_macros_file = os.path.join(out_dir, "strelka_somatic.macros") # write_macros(strelka_somatic_macros, strelka_somatic_macros_file) # strelka_somatic_dir = os.path.join(out_dir, "strelka_somatic") # strelka_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("strelka_somatic"), # strelka_somatic_macros_file, # strelka_somatic_dir)) # strelka_thread.start() # # # pindel somatic # print("------ pindel somatic ------") # pindel_somatic_macros = read_macros(DEFAULT_MACROS_DICT.get("pindel_somatic")) # for macro in pindel_somatic_macros: # if macro in total_macros: # pindel_somatic_macros[macro] = total_macros[macro] # # pindel_somatic_macros["NORMAL_BAM"] = os.path.join(normal_align_dir, "{}_normal.bam".format(sample_name)) # pindel_somatic_macros["TUMOR_BAM"] = os.path.join(tumor_align_dir, "{}_tumor.bam".format(sample_name)) # pindel_somatic_macros_file = os.path.join(out_dir, "pindel_somatic.macros") # write_macros(pindel_somatic_macros, pindel_somatic_macros_file) # pindel_somatic_dir = os.path.join(out_dir, "pindel_somatic") # pindel_thread = Process(target=flow_run, args=(preview, # FLOWS_DICT.get("pindel_somatic"), # pindel_somatic_macros_file, # pindel_somatic_dir)) # pindel_thread.start() # # varscan_thread.join() # strelka_thread.join() # pindel_thread.join() # # # annotation # print("------ oncotator annotation ------") # oncotator_macros = read_macros(DEFAULT_MACROS_DICT.get("oncotator")) # for macro in oncotator_macros: # if macro in total_macros: # oncotator_macros[macro] = total_macros[macro] # # vcfs = "{varscan_dir}/{sample_name}.indel.vcf " \ # "{varscan_dir}/{sample_name}.snp.vcf " \ # "{strelka_dir}/strelk_out/results/passed.somatic.indels.vcf " \ # "{strelka_dir}/strelk_out/results/passed.somatic.snvs.vcf " \ # "{pindel_dir}/{sample_name}.somatic.delete.vcf " \ # "{pindel_dir}/{sample_name}.somatic.insert.vcf ".format(varscan_dir=varscan_somatic_dir, # strelka_dir=strelka_somatic_dir, # pindel_dir=pindel_somatic_dir, # sample_name=sample_name) # oncotator_macros["VCFS"] = vcfs # oncotator_macros["NORMAL_BARCODE"] = "{}_normal".format(sample_name) # oncotator_macros["TUMOR_BARCODE"] = "{}_tumor".format(sample_name) # oncotator_macros_file = os.path.join(out_dir, "oncotator.macros") # write_macros(oncotator_macros, oncotator_macros_file) # oncotator_dir = os.path.join(out_dir, "oncotator") # oncotator_thread = Process(target=flow_run, args=(preview, FLOWS_DICT.get("oncotator"), # oncotator_macros_file, # oncotator_dir)) # oncotator_thread.start() # oncotator_thread.join() # create out directory # quality control # alignment # variants calling
2.116731
2
ic_marathon_app/admin.py
sarifern/ciscorunning
0
6614283
from django.contrib import admin from .models import Workout, Profile from django.utils.html import format_html # Register your models here. class WorkoutAdmin(admin.ModelAdmin): list_display = ('uuid', 'belongs_to', 'distance', 'image_tag') list_filter = ['belongs_to'] def image_tag(self, obj): return format_html( '<img src="{}" width="600px" height="600px"/>'.format( obj.photo_evidence.url)) admin.site.register(Workout, WorkoutAdmin) class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'cec', 'user_goal', 'distance') list_filter = ['user', 'cec'] admin.site.register(Profile, ProfileAdmin)
from django.contrib import admin from .models import Workout, Profile from django.utils.html import format_html # Register your models here. class WorkoutAdmin(admin.ModelAdmin): list_display = ('uuid', 'belongs_to', 'distance', 'image_tag') list_filter = ['belongs_to'] def image_tag(self, obj): return format_html( '<img src="{}" width="600px" height="600px"/>'.format( obj.photo_evidence.url)) admin.site.register(Workout, WorkoutAdmin) class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'cec', 'user_goal', 'distance') list_filter = ['user', 'cec'] admin.site.register(Profile, ProfileAdmin)
en
0.968259
# Register your models here.
1.896459
2
isar/events/rulesservice.py
zardosht/isar
0
6614284
<reponame>zardosht/isar<gh_stars>0 import logging from threading import Thread from isar.events import events, eventmanager from isar.services.service import Service logger = logging.getLogger("isar.scene.rulesservice") class RulesService(Service): def __init__(self, service_name): super().__init__(service_name) self.actions_service = None self.__scenes_model = None self.current_scene = None self.register_for_all_events() def register_for_all_events(self): for event_class_name in events.event_types: eventmanager.register_listener(event_class_name, self) def set_scenes_model(self, scenes_model): self.__scenes_model = scenes_model def set_current_scene(self, current_scene): self.current_scene = current_scene def on_event(self, event): if self.current_scene is None: logger.error("self.scene is None. Return.") return for rule in self.current_scene.get_rules(): if rule.event == event: t = Thread(name="RuleServiceFireRuleThread", target=rule.fire) t.start()
import logging from threading import Thread from isar.events import events, eventmanager from isar.services.service import Service logger = logging.getLogger("isar.scene.rulesservice") class RulesService(Service): def __init__(self, service_name): super().__init__(service_name) self.actions_service = None self.__scenes_model = None self.current_scene = None self.register_for_all_events() def register_for_all_events(self): for event_class_name in events.event_types: eventmanager.register_listener(event_class_name, self) def set_scenes_model(self, scenes_model): self.__scenes_model = scenes_model def set_current_scene(self, current_scene): self.current_scene = current_scene def on_event(self, event): if self.current_scene is None: logger.error("self.scene is None. Return.") return for rule in self.current_scene.get_rules(): if rule.event == event: t = Thread(name="RuleServiceFireRuleThread", target=rule.fire) t.start()
none
1
2.457962
2
vgazer/install/custom_installer/sdl2_gpu.py
edomin/vgazer
2
6614285
import os from vgazer.command import RunCommand from vgazer.config.cmake import ConfigCmake from vgazer.exceptions import CommandError from vgazer.exceptions import InstallError from vgazer.platform import GetArFullPath from vgazer.platform import GetCc from vgazer.platform import GetInstallPrefix from vgazer.platform import GetSoPrefix from vgazer.platform import GetSoFilename from vgazer.store.temp import StoreTemp from vgazer.working_dir import WorkingDir def GetVersionFromSource(filename): with open(filename) as f: data = f.read() lines = data.splitlines() for line in lines: if "#define SDL_GPU_VERSION_MAJOR" in line: versionMajor = line.split(" ")[2] if "#define SDL_GPU_VERSION_MINOR" in line: versionMinor = line.split(" ")[2] if "#define SDL_GPU_VERSION_PATCH" in line: versionPatch = line.split(" ")[2] return "{major}.{minor}.{patch}".format(major=versionMajor, minor=versionMinor, patch=versionPatch) def Install(auth, software, platform, platformData, mirrors, verbose): configCmake = ConfigCmake(platformData) configCmake.GenerateCrossFile() installPrefix = GetInstallPrefix(platformData) ar = GetArFullPath(platformData["target"]) cc = GetCc(platformData["target"]) os = platformData["target"].GetOs() soPrefix = GetSoPrefix(platformData) soFilename = GetSoFilename(platformData["target"], "SDL2_gpu") storeTemp = StoreTemp() storeTemp.ResolveEmptySubdirectory(software) tempPath = storeTemp.GetSubdirectoryPath(software) try: with WorkingDir(tempPath): RunCommand( ["git", "clone", "https://github.com/grimfang4/sdl-gpu.git", "sdl2-gpu"], verbose) clonedDir = os.path.join(tempPath, "sdl2-gpu") with WorkingDir(clonedDir): RunCommand( ["sed", "-i", "-e", '/\t\t\tlink_libraries (${GLEW_LIBRARIES})/i \t\t\tadd_definitions("-DGLEW_STATIC")', "./CMakeLists.txt"], verbose) RunCommand(["mkdir", "build"], verbose) sdlGpuHeader = os.path.join(clonedDir, "include/SDL_gpu.h") version = GetVersionFromSource(sdlGpuHeader) if os == "linux": soLibname = "libSDL2_gpu.so" installedLibPrefix = installPrefix + "/SDL_gpu-" + version + "/lib" elif os == "windows": soLibname = "libSDL2_gpu.dll" installedLibPrefix = installPrefix + "/SDL_gpu-MINGW-" + version + "/lib" buildDir = os.path.join(clonedDir, "build") with WorkingDir(buildDir): RunCommand( [cc, "-c", "../src/externals/stb_image/stb_image.c", "-o", "../src/externals/stb_image/stb_image.o", "-O2", "-Wall", "-mmmx", "-msse", "-msse2", "-mfpmath=sse", "-fPIC", "-I" + installPrefix + "/include"], verbose) RunCommand( [ar, "rcs", "../src/externals/stb_image/libstbi.a", "../src/externals/stb_image/stb_image.o"], verbose) RunCommand( [cc, "-c", "../src/externals/stb_image_write/stb_image_write.c", "-o", "../src/externals/stb_image_write/stb_image_write.o", "-O2", "-Wall", "-mmmx", "-msse", "-msse2", "-mfpmath=sse", "-fPIC", "-I" + installPrefix + "/include"], verbose) RunCommand( [ar, "rcs", "../src/externals/stb_image_write/libstbi_write.a", "../src/externals/stb_image_write/stb_image_write.o"], verbose) RunCommand( [ "cmake", "..", "-G", "Unix Makefiles", "-DCMAKE_TOOLCHAIN_FILE=" + configCmake.GetCrossFileName(), "-DCMAKE_INSTALL_PREFIX=" + installPrefix, "-DSDL_gpu_INSTALL=ON", "-DSDL_gpu_BUILD_DEMOS=OFF", "-DSDL_gpu_USE_SYSTEM_GLEW=ON", "-DSTBI_INCLUDE_DIR=" + installPrefix + "/include", "-DSTBI_LIBRARY=" + buildDir + "/../src/externals/stb_image/libstbi.a", "-DSTBI_FOUND=TRUE", "-DSTBI_WRITE_INCLUDE_DIR=" + installPrefix + "/include", "-DSTBI_WRITE_LIBRARY=" + buildDir + "/../src/externals/stb_image_write/libstbi_write.a", "-DSTBI_WRITE_FOUND=TRUE", "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON", "-DCMAKE_AR=" + ar ], verbose) RunCommand(["make"], verbose) RunCommand(["make", "install"], verbose) RunCommand( ["mv", installedLibPrefix + "/" + soLibname, soPrefix + "/" + soFilename], verbose) RunCommand( ["mv", installedLibPrefix + "/libSDL2_gpu.a", installPrefix + "/lib/libSDL2_gpu.a"], verbose) RunCommand( ["rm", "-rf", installPrefix + "/SDL_gpu-" + version], verbose) except CommandError: print("VGAZER: Unable to install", software) raise InstallError(software + " not installed") print("VGAZER:", software, "installed")
import os from vgazer.command import RunCommand from vgazer.config.cmake import ConfigCmake from vgazer.exceptions import CommandError from vgazer.exceptions import InstallError from vgazer.platform import GetArFullPath from vgazer.platform import GetCc from vgazer.platform import GetInstallPrefix from vgazer.platform import GetSoPrefix from vgazer.platform import GetSoFilename from vgazer.store.temp import StoreTemp from vgazer.working_dir import WorkingDir def GetVersionFromSource(filename): with open(filename) as f: data = f.read() lines = data.splitlines() for line in lines: if "#define SDL_GPU_VERSION_MAJOR" in line: versionMajor = line.split(" ")[2] if "#define SDL_GPU_VERSION_MINOR" in line: versionMinor = line.split(" ")[2] if "#define SDL_GPU_VERSION_PATCH" in line: versionPatch = line.split(" ")[2] return "{major}.{minor}.{patch}".format(major=versionMajor, minor=versionMinor, patch=versionPatch) def Install(auth, software, platform, platformData, mirrors, verbose): configCmake = ConfigCmake(platformData) configCmake.GenerateCrossFile() installPrefix = GetInstallPrefix(platformData) ar = GetArFullPath(platformData["target"]) cc = GetCc(platformData["target"]) os = platformData["target"].GetOs() soPrefix = GetSoPrefix(platformData) soFilename = GetSoFilename(platformData["target"], "SDL2_gpu") storeTemp = StoreTemp() storeTemp.ResolveEmptySubdirectory(software) tempPath = storeTemp.GetSubdirectoryPath(software) try: with WorkingDir(tempPath): RunCommand( ["git", "clone", "https://github.com/grimfang4/sdl-gpu.git", "sdl2-gpu"], verbose) clonedDir = os.path.join(tempPath, "sdl2-gpu") with WorkingDir(clonedDir): RunCommand( ["sed", "-i", "-e", '/\t\t\tlink_libraries (${GLEW_LIBRARIES})/i \t\t\tadd_definitions("-DGLEW_STATIC")', "./CMakeLists.txt"], verbose) RunCommand(["mkdir", "build"], verbose) sdlGpuHeader = os.path.join(clonedDir, "include/SDL_gpu.h") version = GetVersionFromSource(sdlGpuHeader) if os == "linux": soLibname = "libSDL2_gpu.so" installedLibPrefix = installPrefix + "/SDL_gpu-" + version + "/lib" elif os == "windows": soLibname = "libSDL2_gpu.dll" installedLibPrefix = installPrefix + "/SDL_gpu-MINGW-" + version + "/lib" buildDir = os.path.join(clonedDir, "build") with WorkingDir(buildDir): RunCommand( [cc, "-c", "../src/externals/stb_image/stb_image.c", "-o", "../src/externals/stb_image/stb_image.o", "-O2", "-Wall", "-mmmx", "-msse", "-msse2", "-mfpmath=sse", "-fPIC", "-I" + installPrefix + "/include"], verbose) RunCommand( [ar, "rcs", "../src/externals/stb_image/libstbi.a", "../src/externals/stb_image/stb_image.o"], verbose) RunCommand( [cc, "-c", "../src/externals/stb_image_write/stb_image_write.c", "-o", "../src/externals/stb_image_write/stb_image_write.o", "-O2", "-Wall", "-mmmx", "-msse", "-msse2", "-mfpmath=sse", "-fPIC", "-I" + installPrefix + "/include"], verbose) RunCommand( [ar, "rcs", "../src/externals/stb_image_write/libstbi_write.a", "../src/externals/stb_image_write/stb_image_write.o"], verbose) RunCommand( [ "cmake", "..", "-G", "Unix Makefiles", "-DCMAKE_TOOLCHAIN_FILE=" + configCmake.GetCrossFileName(), "-DCMAKE_INSTALL_PREFIX=" + installPrefix, "-DSDL_gpu_INSTALL=ON", "-DSDL_gpu_BUILD_DEMOS=OFF", "-DSDL_gpu_USE_SYSTEM_GLEW=ON", "-DSTBI_INCLUDE_DIR=" + installPrefix + "/include", "-DSTBI_LIBRARY=" + buildDir + "/../src/externals/stb_image/libstbi.a", "-DSTBI_FOUND=TRUE", "-DSTBI_WRITE_INCLUDE_DIR=" + installPrefix + "/include", "-DSTBI_WRITE_LIBRARY=" + buildDir + "/../src/externals/stb_image_write/libstbi_write.a", "-DSTBI_WRITE_FOUND=TRUE", "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON", "-DCMAKE_AR=" + ar ], verbose) RunCommand(["make"], verbose) RunCommand(["make", "install"], verbose) RunCommand( ["mv", installedLibPrefix + "/" + soLibname, soPrefix + "/" + soFilename], verbose) RunCommand( ["mv", installedLibPrefix + "/libSDL2_gpu.a", installPrefix + "/lib/libSDL2_gpu.a"], verbose) RunCommand( ["rm", "-rf", installPrefix + "/SDL_gpu-" + version], verbose) except CommandError: print("VGAZER: Unable to install", software) raise InstallError(software + " not installed") print("VGAZER:", software, "installed")
none
1
2.067563
2
Course/syntax/example_4.py
zevgenia/Python_shultais
0
6614286
<gh_stars>0 d = 10 l = ("A", "B", "C") sl = {"en": "one", "ru": "один"} a = b = c = 10 a *= 5 print(a, b, c) # Каноническая форма x = "строка" # Приваивание кортежей a, b = 'a', 'b' print('a:', a) print('b:', b) #A, B = ('A', 'B') #print('A:', A) #print('B:', B) # Приваивание списков d, e = ["d", "e"] print('d:', d) print('e:', e) #d, e, f = ["d", "e"] #d, e, f = ["d", "e", "f", "g"] # f = ["a", "b", "c"] # Приваивание последовательностей s, t, r, o, k, a = "строка" a, b, c = ["строка", 45, {1: "one", 2: "two"}] print('a:', a) print('b:', b) print('c:', c) # Расширенное распаковывание последовательностей a, *b, c = "A", "B1", "B2", "B3", "C" print('a:', a) print('b:', b) print('c:', c) # Групповое присваивание одного значения a = b = c = 0 #c = 0 #b = c #a = b # Комбинированное присваивание a = 10 a += 20 #a = a + 20 print(a)
d = 10 l = ("A", "B", "C") sl = {"en": "one", "ru": "один"} a = b = c = 10 a *= 5 print(a, b, c) # Каноническая форма x = "строка" # Приваивание кортежей a, b = 'a', 'b' print('a:', a) print('b:', b) #A, B = ('A', 'B') #print('A:', A) #print('B:', B) # Приваивание списков d, e = ["d", "e"] print('d:', d) print('e:', e) #d, e, f = ["d", "e"] #d, e, f = ["d", "e", "f", "g"] # f = ["a", "b", "c"] # Приваивание последовательностей s, t, r, o, k, a = "строка" a, b, c = ["строка", 45, {1: "one", 2: "two"}] print('a:', a) print('b:', b) print('c:', c) # Расширенное распаковывание последовательностей a, *b, c = "A", "B1", "B2", "B3", "C" print('a:', a) print('b:', b) print('c:', c) # Групповое присваивание одного значения a = b = c = 0 #c = 0 #b = c #a = b # Комбинированное присваивание a = 10 a += 20 #a = a + 20 print(a)
ru
0.819429
# Каноническая форма # Приваивание кортежей #A, B = ('A', 'B') #print('A:', A) #print('B:', B) # Приваивание списков #d, e, f = ["d", "e"] #d, e, f = ["d", "e", "f", "g"] # f = ["a", "b", "c"] # Приваивание последовательностей # Расширенное распаковывание последовательностей # Групповое присваивание одного значения #c = 0 #b = c #a = b # Комбинированное присваивание #a = a + 20
3.880517
4
example/hello/__init__.py
mamaz/tdd-example
2
6614287
def test_hello_function_should_return_hello(): pass
def test_hello_function_should_return_hello(): pass
none
1
0.95068
1
pyronear/utils/__init__.py
JoaoFdC/PyroNear
0
6614288
<filename>pyronear/utils/__init__.py<gh_stars>0 from .collect_env import get_pretty_env_info del collect_env
<filename>pyronear/utils/__init__.py<gh_stars>0 from .collect_env import get_pretty_env_info del collect_env
none
1
1.043531
1
pycdt/corrections/kumagai_correction.py
hitarth64/pycdt
0
6614289
""" This module computes finite size supercell charge corrections for defects in anistropic systems using extended Freysoldt (or Kumagai) method developed by Kumagai and Oba. Kumagai method includes a) anisotropic PC energy b) potential alignment by atomic site averaging at Wigner Seitz cell edge If you use the corrections implemented in this module, cite a) Kumagai and Oba, Phys. Rev. B. 89, 195205 (2014) and b) Freysoldt, Neugebauer, and Van <NAME>, Phys. Status Solidi B. 248, 1067-1076 (2011) and in addition to the pycdt paper """ __author__ = '<NAME>, <NAME>' __email__ = '<EMAIL>, <EMAIL>' import math import logging import numpy as np from pymatgen.io.vasp.outputs import Locpot, Outcar from pymatgen.core.lattice import Lattice from pycdt.corrections.utils import * from pycdt.utils.units import hart_to_ev import warnings norm = np.linalg.norm warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def kumagai_init(structure, dieltens): angset = structure.lattice.get_cartesian_coords(1) dieltens = np.array(dieltens) if not len(dieltens.shape): dieltens = dieltens*np.identity(3) elif len(dieltens.shape) == 1: dieltens = np.diagflat(dieltens) logging.getLogger(__name__).debug('Lattice constants (in Angs): ' + str(cleanlat(angset))) [a1, a2, a3] = ang_to_bohr * angset # convert to bohr bohrset = [a1, a2, a3] vol = np.dot(a1, np.cross(a2, a3)) logging.getLogger(__name__).debug('Lattice constants (in Bohr): ' + str(cleanlat([a1, a2, a3]))) determ = np.linalg.det(dieltens) invdiel = np.linalg.inv(dieltens) logging.getLogger(__name__).debug('inv dielectric tensor: ' + str(invdiel)) return angset, bohrset, vol, determ, invdiel warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def real_sum(a1, a2, a3, r, q, dieltens, gamma, tolerance): invdiel = np.linalg.inv(dieltens) determ = np.linalg.det(dieltens) realpre = q / np.sqrt(determ) tolerance /= hart_to_ev #Real space sum by converging with respect to real space vectors #create list of real space vectors that satisfy |i*a1+j*a2+k*a3|<=N Nmaxlength = 40 #tolerance for stopping real space sum convergence N = 2 r_sums = [] while N < Nmaxlength: r_sum = 0.0 if norm(r): for i in range(-N, N+1): for j in range(-N, N+1): for k in range(-N, N+1): r_vec = i*a1 + j*a2 + k*a3 - r loc_res = np.dot(r_vec, np.dot(invdiel, r_vec)) nmr = math.erfc(gamma * np.sqrt(loc_res)) dmr = np.sqrt(determ * loc_res) r_sum += nmr / dmr else: for i in range(-N, N+1): for j in range(-N, N+1): for k in range(-N, N+1): if i == j == k == 0: continue else: r_vec = i*a1 + j*a2 + k*a3 loc_res = np.dot(r_vec, np.dot(invdiel, r_vec)) nmr = math.erfc(gamma * np.sqrt(loc_res)) dmr = np.sqrt(determ * loc_res) r_sum += nmr / dmr r_sums.append([N, realpre * r_sum]) if N == Nmaxlength-1: logging.getLogger(__name__).warning( 'Direct part could not converge with real space translation ' 'tolerance of {} for gamma {}'.format(Nmaxlength-1, gamma)) return elif len(r_sums) > 3: if abs(abs(r_sums[-1][1]) - abs(r_sums[-2][1])) < tolerance: r_sum = r_sums[-1][1] logging.debug("gamma is {}".format(gamma)) logging.getLogger(__name__).debug( "convergence for real summatin term occurs at step {} " "where real sum is {}".format(N, r_sum * hart_to_ev)) break N += 1 return r_sum warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def get_g_sum_at_r(g_sum, structure, dim, r): """ Args: g_sum: Reciprocal summation calculated from reciprocal_sum method structure: Bulk structure pymatgen object dim : ngxf dimension r: Position relative to defect (in cartesian coords) Returns: reciprocal summ value at g_sum[i_rx,j_ry,k_rz] """ fraccoord = structure.lattice.get_fractional_coords(r) i, j, k = getgridind(structure, dim, fraccoord) return g_sum[i, j, k] warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def anisotropic_madelung_potential(structure, dim, g_sum, r, dieltens, q, gamma, tolerance): """ Compute the anisotropic Madelung potential at r not equal to 0. For r=(0,0,0) use anisotropic_pc_energy function Args: structure: Bulk pymatgen structure type dim : ngxf dimension g_sum: Precomputed reciprocal sum for all r_vectors r: r vector (in cartesian coordinates) relative to defect position. Non zero r is expected dieltens: dielectric tensor q: Point charge (in units of e+) tolerance: Tolerance parameter for numerical convergence gamma (float): Convergence parameter silence (bool): Verbosity flag. If False, messages are printed. """ angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( structure, dieltens) recippartreal = q * get_g_sum_at_r(g_sum, structure, dim, r) directpart = real_sum(a1, a2, a3, r, q, dieltens, gamma, tolerance) #now add up total madelung potential part with two extra parts: #self interaction term selfint = q * np.pi / (vol * (gamma ** 2)) logging.getLogger(__name__).debug('self interaction piece is {}'.format( selfint * hart_to_ev)) pot = hart_to_ev * (directpart + recippartreal - selfint) return pot warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def anisotropic_pc_energy(structure, g_sum, dieltens, q, gamma, tolerance): """ Compute the anistropic periodic point charge interaction energy. Args: structure: Bulk pymatgen structure type g_sum : comes from KumagaiBulkInit class dieltens: dielectric tensor q: Point charge (in units of e+) gamma : convergence parameter optimized in KumagaiBulkInit class silence (bool): Verbosity flag. If False, messages are printed. """ angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( structure, dieltens) g_part = q*g_sum[0,0,0] r_part = real_sum(a1, a2, a3, [0,0,0], q, dieltens, gamma, tolerance) selfint = q*np.pi / (vol * (gamma**2)) #self interaction term #surface term (only for r not at origin) surfterm = 2*gamma*q / np.sqrt(np.pi*determ) logger = logging.getLogger(__name__) logger.debug('reciprocal part: {}'.format(g_part * hart_to_ev)) logger.debug('real part: {}'.format(r_part * hart_to_ev)) logger.debug('self interaction part: {}'.format(selfint * hart_to_ev)) logger.debug('surface term: {}'.format(surfterm * hart_to_ev)) pc_energy = -(q*0.5*hart_to_ev) * (r_part + g_part - selfint - surfterm) logging.debug('Final PC Energy term: {} eV'.format(pc_energy)) return pc_energy warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def getgridind(structure, dim, r, gridavg=0.0): """ Computes the index of a point, r, in the locpot grid Args: structure: Pymatgen structure object dim: dimension of FFT grid (NGXF dimension list in VASP) r: Relative co-ordinates with respect to abc lattice vectors gridavg: If you want to do atomic site averaging, set gridavg to the radius of the atom at r Returns: [i,j,k]: Indices as list TODO: Once final, remove the getgridind inside disttrans function """ abc = structure.lattice.abc grdind = [] if gridavg: radvals = [] #radius in terms of indices dxvals = [] for i in range(3): if r[i] < 0: while r[i] < 0: r[i] += 1 elif r[i] >= 1: while r[i] >= 1: r[i] -= 1 r[i] *= abc[i] num_pts = dim[i] x = [now_num / float(num_pts) * abc[i] for now_num in range(num_pts)] dx = x[1] - x[0] x_rprojection_delta_abs = np.absolute(x - r[i]) ind = np.argmin(x_rprojection_delta_abs) if x_rprojection_delta_abs[ind] > dx*1.1: #to avoid numerical errors logger = logging.getLogger(__name__) logger.error("Input position not within the locpot grid") logger.error("%d, %d, %f", i, ind, r) logger.error("%f", x_rprojection_delta_abs) raise ValueError("Input position is not within the locpot grid") grdind.append(ind) if gridavg: radvals.append(int(np.ceil(gridavg/dx))) dxvals.append(dx) if gridavg: grdindfull = [] for i in range(-radvals[0], radvals[0]+1): for j in range(-radvals[1], radvals[1]+1): for k in range(-radvals[2], radvals[2]+1): dtoc = [i*dxvals[0], j*dxvals[1], k*dxvals[2]] if norm(dtoc) < gridavg: ival = (i+grdind[0]) % dim[0] jval = (j+grdind[1]) % dim[1] kval = (k+grdind[2]) % dim[2] grdindfull.append((ival, jval, kval)) grdind = grdindfull return grdind warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def disttrans(struct, defstruct, defpos=None): """ To calculate distance from defect to each atom and finding NGX grid pts at each atom. Args: struct: Bulk structure object defstruct: Defect structure object defpos: (if known) defect position as a pymatgen Site object within bulk supercell """ #Find defect location in bulk and defect cells blksite, defsite = find_defect_pos(struct, defstruct, defpos=defpos) logger = logging.getLogger(__name__) if blksite is None and defsite is None: logger.error('Not able to determine defect site') return if blksite is None: logger.debug('Found defect to be Interstitial type at %s', repr(defsite)) elif defsite is None: logger.debug('Found defect to be Vacancy type at %s', repr(blksite)) else: logger.debug('Found defect to be antisite/subsitution type at %s ' \ ' in bulk, and %s in defect cell', repr(blksite), repr(defsite)) if blksite is None: blksite = defsite elif defsite is None: defsite = blksite def_ccoord = blksite[:] defcell_def_ccoord = defsite[:] if len(struct.sites) >= len(defstruct.sites): sitelist = struct.sites[:] else: #for interstitial list sitelist = defstruct.sites[:] #better image getter since pymatgen wasnt working well for this def returnclosestr(vec): from operator import itemgetter listvals = [] abclats = defstruct.lattice.matrix trylist = [-1, 0, 1] for i in trylist: for j in trylist: for k in trylist: transvec = i*abclats[0] + j*abclats[1] + k*abclats[2] rnew = vec - (defcell_def_ccoord + transvec) listvals.append([norm(rnew), rnew, transvec]) listvals.sort(key=itemgetter(0)) return listvals[0] #will return [dist,r to defect, and transvec for defect] grid_sites = {} # dictionary with indices keys in order of structure list for i in sitelist: if np.array_equal(i.coords, def_ccoord): logging.debug('Site {} is defect! Skipping '.format(i)) continue blksite, defsite = closestsites(struct, defstruct, i.coords) blkindex = blksite[-1] defindex = defsite[-1] dcart_coord = defsite[0].coords closeimage = returnclosestr(dcart_coord) cart_reldef = closeimage[1] defdist = closeimage[0] if abs(norm(cart_reldef) - defdist) > 0.1: logger.warning('Image locater issue encountered for site = %d', blkindex) logger.warning('In defect supercell') logger.warning('Distance should be %f', defdist) logger.warning('But, calculated distance is %f', norm(cart_reldef)) if blkindex in grid_sites: logger.warning('Index %d already exists in potinddict!', blkindex) logger.warning('Overwriting information.') grid_sites[blkindex] = { 'dist': defdist, 'cart': dcart_coord, 'cart_reldef': cart_reldef, 'siteobj': [i.coords, i.frac_coords, i.species_string], 'bulk_site_index': blkindex, 'def_site_index': defindex} return grid_sites warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def wigner_seitz_radius(structure): """ Calculate the Wigner Seitz radius for the given structure. Args: structure: pymatgen Structure object """ wz = structure.lattice.get_wigner_seitz_cell() dist = [] for facet in wz: midpt = np.mean(np.array(facet), axis=0) dist.append(norm(midpt)) wsrad = min(dist) return wsrad warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def read_ES_avg_fromlocpot(locpot): """ Reads Electrostatic potential at each atomic site from Locpot Pymatgen object """ structure = locpot.structure radii = {specie: 1.0 for specie in set(structure.species)} # TODO: The above radii could be smarter (related to ENAUG?) # but turns out you get a similar result to Outcar differences # when taking locpot avgd differences ES_data = {'sampling_radii': radii, 'ngxf_dims': locpot.dim} pot = [] for site in structure.sites: indexlist = getgridind(structure, locpot.dim, site.frac_coords, gridavg=radii[site.specie]) samplevals = [] for u,v,w in indexlist: samplevals.append(locpot.data["total"][u][v][w]) pot.append(np.mean(samplevals)) ES_data.update({'potential': pot}) return ES_data warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) class KumagaiBulkInit(object): """ Compute the anisotropic madelung potential array from the bulk locpot. This helps in evaluating the bulk supercell related part once to speed up the calculations. """ def __init__(self, structure, dim, epsilon, encut=520, tolerance=0.0001, optgamma=False): """ Args structure: Pymatgen structure object of bulk cell dim: Fine FFT grid dimensions as a list For vasp this is NGXF grid dimensions epsilon: Dielectric tensor encut (float): Energy cutoff for optimal gamma tolerance (float): Accuracy parameter optgamma: if you know optimized gamma, give its value. Otherwise it will be computed. """ self.structure = structure self.dim = dim self.epsilon = epsilon self.encut = encut self.tolerance = tolerance #self.silence = silence if not optgamma: self.gamma = self.find_optimal_gamma() else: self.gamma = optgamma self.g_sum = self.reciprocal_sum() logging.getLogger(__name__).info('optimized gamma: %f', self.gamma) def find_optimal_gamma(self): """ Find optimal gamma by evaluating the brute force reciprocal summation and seeing when the values are on the order of 1, This calculation is the anisotropic Madelung potential at r = (0,0,0). Note this only requires the STRUCTURE not the LOCPOT object. """ angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( self.structure, self.epsilon) optgam = None #do brute force recip summation def get_recippart(encut, gamma): recippart = 0.0 for rec in genrecip(a1, a2, a3, encut): Gdotdiel = np.dot(rec, np.dot(self.epsilon, rec)) summand = math.exp(-Gdotdiel / (4 * (gamma ** 2))) / Gdotdiel recippart += summand recippart *= 4*np.pi/vol return recippart, 0.0 def do_summation(gamma): # Do recip sum until it is bigger than 1eV # First do Recip space sum convergence with respect to encut for # this gamma encut = 20 #start with small encut for expediency recippartreal1, recippartimag1 = get_recippart(encut, gamma) encut += 10 recippartreal, recippartimag = get_recippart(encut, gamma) converge = [recippartreal1, recippartreal] logger = logging.getLogger(__name__) while abs(abs(converge[0]) - abs(converge[1])) * hart_to_ev > \ self.tolerance: encut += 10 recippartreal, recippartimag = get_recippart(encut, gamma) converge.reverse() converge[1] = recippartreal if encut > self.encut: msg = 'Optimal gamma not found at {} eV cutoff'.format( self.encut) logger.error(msg) raise ValueError(msg) if abs(recippartimag) * hart_to_ev > self.tolerance: logger.error("Imaginary part of reciprocal sum not converged.") logger.error("Imaginary sum value is {} (eV)".format( recippartimag * hart_to_ev)) return None, None logger.debug('Reciprocal sum converged to %f eV', recippartreal * hart_to_ev) logger.debug('Convergin encut = %d eV', encut) if (abs(converge[1]) * hart_to_ev < 1 and not optgam): logger.warning('Reciprocal summation value is less than 1 eV.') logger.warning('Might lead to errors') logger.warning('Change gamma.') return None, 'Try Again' return recippartreal, gamma logger = logging.getLogger(__name__) #start with gamma s.t. gamma*L=5 (this is optimal) #optimizing gamma for the reciprocal sum to improve convergence gamma = 5.0/(vol ** (1/3.0)) optimal_gamma_found = False while not optimal_gamma_found: recippartreal, optgamma = do_summation(gamma) if optgamma == gamma: logger.debug('optimized gamma found to be %f', optgamma) optimal_gamma_found = True elif 'Try Again' in optgamma: gamma *= 1.5 else: logger.error('Had problem in gamma optimization process.') return None if gamma > 50: logger.error('Could not optimize gamma before gamma = %d', 50) return None return optgamma def reciprocal_sum(self): """ Compute the reciprocal summation in the anisotropic Madelung potential. TODO: Get the input to fft cut by half by using rfft instead of fft """ logger = logging.getLogger(__name__) logger.debug('Reciprocal summation in Madeling potential') over_atob = 1.0 / ang_to_bohr atob3 = ang_to_bohr ** 3 latt = self.structure.lattice vol = latt.volume * atob3 # in Bohr^3 reci_latt = latt.reciprocal_lattice [b1, b2, b3] = reci_latt.get_cartesian_coords(1) b1 = np.array(b1) * over_atob # In 1/Bohr b2 = np.array(b2) * over_atob b3 = np.array(b3) * over_atob nx, ny, nz = self.dim logging.debug('nx: %d, ny: %d, nz: %d', nx, ny, nz) ind1 = np.arange(nx) for i in range(int(nx/2), nx): ind1[i] = i - nx ind2 = np.arange(ny) for i in range(int(ny/2), ny): ind2[i] = i - ny ind3 = np.arange(nz) for i in range(int(nz/2), nz): ind3[i] = i - nz g_array = np.zeros(self.dim, np.dtype('c16')) gamm2 = 4*(self.gamma**2) for i in ind1: for j in ind2: for k in ind3: g = i*b1 + j*b2 + k*b3 g_eps_g = np.dot(g, np.dot(self.epsilon, g)) if i == j == k == 0: continue else: g_array[i,j,k] = math.exp(-g_eps_g/gamm2) / g_eps_g r_array = np.fft.fftn(g_array) over_vol = 4*np.pi/vol # Multiply with q later r_array *= over_vol r_arr_real = np.real(r_array) r_arr_imag = np.imag(r_array) max_imag = r_arr_imag.max() logger.debug('Max imaginary part found to be %f', max_imag) return r_arr_real warnings.warn("Replacing PyCDT usage of Kumagai base classes and plotting with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) class KumagaiCorrection(object): """ Extended freysoldt correction developed by Kumagai and Oba. """ def __init__(self, dielectric_tensor, q, gamma, g_sum, bulk_structure, defect_structure, energy_cutoff=520, madetol=0.0001, lengths=None, **kw): """ Args: dielectric_tensor: Macroscopic dielectric tensor Include ionic also if defect is relaxed, othewise ion clamped. Can be a matrix array or scalar. q: Charge associated with the defect. Typically integer gamma: Convergence parameter. Obtained from KumagaiBulkPart g_sum: value that is dependent on the Bulk only. Obtained from KumagaiBulkPart bulk_structure: bulk Pymatgen structure object. Need to specify this if using Outcar method for atomic site avg. (If you specify outcar files for bulk_file_path but dont specify structure then code will break) (TO DO: resolve this dumb dependency by being smarter about where structure comes from?) defect_structure: defect structure. Needed if using Outcar method energy_cutoff: Energy for plane wave cutoff (in eV). If not given, Materials Project default 520 eV is used. madetol: Tolerance for convergence of energy terms in eV lengths: Lengths of axes, for speeding up plotting slightly keywords: 1) bulk_locpot: Bulk Locpot file path OR Bulk Locpot defect_locpot: Defect Locpot file path or defect Locpot 2) (Or) bulk_outcar: Bulk Outcar file path defect_outcar: Defect outcar file path 3) defect_position: Defect position as a pymatgen Site object in the bulk supercell structure NOTE: this is optional but recommended, if not provided then analysis is done to find the defect position; this analysis has been rigorously tested, but has broken in an example with severe long range relaxation (at which point you probably should not be including the defect in your analysis...) """ if isinstance(dielectric_tensor, int) or \ isinstance(dielectric_tensor, float): self.dieltens = np.identity(3) * dielectric_tensor else: self.dieltens = np.array(dielectric_tensor) if 'bulk_locpot' in kw: if isinstance(kw['bulk_locpot'], Locpot): self.locpot_blk = kw['bulk_locpot'] else: self.locpot_blk = Locpot.from_file(kw['bulk_locpot']) if isinstance(kw['defect_locpot'], Locpot): self.locpot_def = kw['defect_locpot'] else: self.locpot_def = Locpot.from_file(kw['defect_locpot']) self.dim = self.locpot_blk.dim self.outcar_blk = None self.outcar_def = None self.do_outcar_method = False if 'bulk_outcar' in kw: self.outcar_blk = Outcar(str(kw['bulk_outcar'])) self.outcar_def = Outcar(str(kw['defect_outcar'])) self.do_outcar_method = True self.locpot_blk = None self.locpot_def = None self.dim = self.outcar_blk.ngf if 'defect_position' in kw: self._defpos = kw['defect_position'] else: self._defpos = None self.madetol = madetol self.q = q self.encut = energy_cutoff self.structure = bulk_structure self.defstructure = defect_structure self.gamma = gamma self.g_sum = g_sum self.lengths=lengths def correction(self, title=None, partflag='All'): """ Computes the extended Freysoldt correction for anistropic systems developed by <NAME> and <NAME> (Ref: PRB 89, 195205 (2014) Args: title: If plot of potential averaging process is wanted set title partflag: Specifies the part of correction computed 'pc': periodic interaction of defect charges (point charge) only 'potalign': potential alignmnet correction only, 'All' (default): pc and potalign combined into one value, 'AllSplit' for correction in form [PC, potterm, full] """ logger = logging.getLogger(__name__) logger.info('This is Kumagai Correction.') if not self.q: if partflag == 'AllSplit': return [0., 0., 0.] else: return 0.0 if partflag != 'potalign': energy_pc = self.pc() if partflag != 'pc': potalign = self.potalign(title=title) #logger.info('Kumagai Correction details:') #if partflag != 'potalign': # logger.info('PCenergy (E_lat) = %f', round(energy_pc, 5)) #if partflag != 'pc': # logger.info('potential alignment (-q*delta V) = %f', # round(potalign, 5)) if partflag in ['All','AllSplit']: logger.info('Total Kumagai correction = %f', round(energy_pc+potalign, 5)) if partflag == 'pc': return round(energy_pc, 5) elif partflag == 'potalign': return round(potalign, 5) elif partflag == 'All': return round(energy_pc+potalign, 5) else: return map(lambda x: round(x, 5), [energy_pc, potalign, energy_pc+potalign]) def pc(self): energy_pc = anisotropic_pc_energy( self.structure, self.g_sum, self.dieltens, self.q, self.gamma, self.madetol) logger = logging.getLogger(__name__) logger.info('PC energy determined to be %f eV (%f Hartree)', energy_pc, energy_pc/hart_to_ev) return energy_pc def potalign(self, title=None, output_sr=False): """ Potential alignment for Kumagai method Args: title: Title for the plot. None will not generate the plot output_sr allows for output of the short range potential (Good for delocalization analysis) """ logger = logging.getLogger(__name__) logger.info('\nRunning potential alignment (atomic site averaging)') angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( self.structure, self.dieltens) potinddict = disttrans(self.structure, self.defstructure, defpos=self._defpos) minlat = min(norm(a1), norm(a2), norm(a3)) lat_perc_diffs = [100 * abs(norm(a1) - norm(lat)) / minlat for lat \ in [a2, a3]] lat_perc_diffs.append(100 * abs(norm(a2) - norm(a3)) / minlat) if not all(i < 45 for i in lat_perc_diffs): logger.warning('Detected that cell was not very cubic.') logger.warning('Sampling atoms outside wigner-seitz cell may '\ 'not be optimal') wsrad = wigner_seitz_radius(self.structure) logger.debug('wsrad %f', wsrad) for i in potinddict.keys(): logger.debug("Atom %d, distance: %f", i, potinddict[i]['dist']) if potinddict[i]['dist'] > wsrad: potinddict[i]['OutsideWS'] = True else: potinddict[i]['OutsideWS'] = False if not self.do_outcar_method: puredat = read_ES_avg_fromlocpot(self.locpot_blk) defdat = read_ES_avg_fromlocpot(self.locpot_def) else: puredat = {'potential': self.outcar_blk.electrostatic_potential} defdat = {'potential': self.outcar_def.electrostatic_potential} jup = 0 for i in potinddict.keys(): jup += 1 if (not title and not potinddict[i]['OutsideWS']): #dont need to calculate inside WS if not printing plot continue j = potinddict[i]['def_site_index'] #assuming zero defined k = potinddict[i]['bulk_site_index'] v_qb = defdat['potential'][j] - puredat['potential'][k] cart_reldef = potinddict[i]['cart_reldef'] v_pc = anisotropic_madelung_potential( self.structure, self.dim, self.g_sum, cart_reldef, self.dieltens, self.q, self.gamma, self.madetol) v_qb *= -1 #change charge sign convention potinddict[i]['Vpc'] = v_pc potinddict[i]['Vqb'] = v_qb logger.debug('Atom: %d, anisotropic madelung potential: %f', i, v_pc) logger.debug('Atom: %d, bulk/defect difference = %f', i, v_qb) if title: fullspecset = self.structure.species specset = list(set(fullspecset)) shade, forplot = {}, {} for i in specset: shade[i.symbol] = {'r': [], 'Vpc': [], 'Vqb': []} forplot[i.symbol] = {'r': [], 'Vpc': [], 'Vqb': [],'sites':[]} forcorrection = [] for i in potinddict.keys(): if (not title and not potinddict[i]['OutsideWS']): continue if potinddict[i]['OutsideWS']: forcorrection.append(potinddict[i]['Vqb']-potinddict[i]['Vpc']) if title: elt = fullspecset[i].symbol shade[elt]['r'].append(potinddict[i]['dist']) shade[elt]['Vpc'].append(potinddict[i]['Vpc']) shade[elt]['Vqb'].append(potinddict[i]['Vqb']) if title: elt = fullspecset[i].symbol forplot[elt]['r'].append(potinddict[i]['dist']) forplot[elt]['Vpc'].append(potinddict[i]['Vpc']) forplot[elt]['Vqb'].append(potinddict[i]['Vqb']) forplot[elt]['sites'].append(potinddict[i]['siteobj']) potalign = np.mean(forcorrection) if title: forplot['EXTRA'] = {'wsrad': wsrad, 'potalign': potalign} try: forplot['EXTRA']['lengths']=self.structure.lattice.abc except: forplot['EXTRA']['lengths']=self.lengths if title != 'written': KumagaiCorrection.plot(forplot, title=title) else: #TODO: use a more descriptive fname that describes the defect from monty.serialization import dumpfn from monty.json import MontyEncoder fname = 'KumagaiData.json' dumpfn(forplot, fname, cls=MontyEncoder) logger.info('potential alignment (site averaging): %f', np.mean(forcorrection)) logger.info('Potential correction energy: %f eV', -self.q * np.mean(forcorrection)) if output_sr: outpot = {'sampled': forcorrection, 'alldata':potinddict} return ((-self.q * np.mean(forcorrection)), outpot) #pot align energy correction (eV) else: return (-self.q * np.mean(forcorrection)) #pot align energy correction (eV) @classmethod def plot(cls, forplot, title): """ Plotting of locpot data TODO: Rename forplot to a more descriptive name """ import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties plt.figure() plt.clf() collis = ['b', 'g', 'c', 'm', 'y', 'w', 'k'] ylis = [] rlis = [] for i in range(len(forplot.keys())): inkey = list(forplot.keys())[i] if inkey == 'EXTRA': continue for k in forplot[inkey]['r']: rlis.append(k) for k in ['Vqb', 'Vpc']: for u in forplot[inkey][k]: ylis.append(u) plt.plot(forplot[inkey]['r'], forplot[inkey]['Vqb'], color=collis[i], marker='^', linestyle='None', label=str(inkey) + ': $V_{q/b}$') plt.plot(forplot[inkey]['r'], forplot[inkey]['Vpc'], color=collis[i], marker='o', linestyle='None', label=str(inkey) + ': $V_{pc}$') full = [] for i in forplot.keys(): if i == 'EXTRA': continue for k in range(len(forplot[i]['Vpc'])): full.append([ forplot[i]['r'][k], forplot[i]['Vqb'][k] - forplot[i]['Vpc'][k] ]) realfull = sorted(full, key=lambda x: x[0]) r, y = [], [] for i in realfull: r.append(i[0]) y.append(i[1]) wsrad = forplot['EXTRA']['wsrad'] potalign = forplot['EXTRA']['potalign'] plt.plot(r, y, color=collis[-1], marker='x', linestyle='None', label='$V_{q/b}$ - $V_{pc}$') plt.xlabel('Distance from defect ($\AA$)',fontsize=20) plt.ylabel('Potential (V)',fontsize=20) x = np.arange(wsrad, max(forplot['EXTRA']['lengths']), 0.01) plt.fill_between(x, min(ylis) - 1, max(ylis) + 1, facecolor='red', alpha=0.15, label='sampling region') plt.axhline(y=potalign, linewidth=0.5, color='red', label='pot. align. / q') fontP = FontProperties() fontP.set_size('small') plt.legend(bbox_to_anchor=(1.05, 0.5), prop=fontP) plt.axhline(y=0, linewidth=0.2, color='black') plt.ylim([min(ylis) - 0.5, max(ylis) + 0.5]) plt.xlim([0, max(rlis) + 3]) plt.title('%s atomic site potential plot' % title) plt.savefig('%s_kumagaisiteavgPlot.pdf' % title) @classmethod def plot_from_datfile(cls, name='KumagaiData.json', title='default'): """ Takes data file called 'name' and does plotting. Good for later plotting of locpot data after running run_correction() """ from monty.serialization import loadfn from monty.json import MontyDecoder forplot = loadfn(name, cls=MontyDecoder) cls.plot(forplot, title=title)
""" This module computes finite size supercell charge corrections for defects in anistropic systems using extended Freysoldt (or Kumagai) method developed by Kumagai and Oba. Kumagai method includes a) anisotropic PC energy b) potential alignment by atomic site averaging at Wigner Seitz cell edge If you use the corrections implemented in this module, cite a) Kumagai and Oba, Phys. Rev. B. 89, 195205 (2014) and b) Freysoldt, Neugebauer, and Van <NAME>, Phys. Status Solidi B. 248, 1067-1076 (2011) and in addition to the pycdt paper """ __author__ = '<NAME>, <NAME>' __email__ = '<EMAIL>, <EMAIL>' import math import logging import numpy as np from pymatgen.io.vasp.outputs import Locpot, Outcar from pymatgen.core.lattice import Lattice from pycdt.corrections.utils import * from pycdt.utils.units import hart_to_ev import warnings norm = np.linalg.norm warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def kumagai_init(structure, dieltens): angset = structure.lattice.get_cartesian_coords(1) dieltens = np.array(dieltens) if not len(dieltens.shape): dieltens = dieltens*np.identity(3) elif len(dieltens.shape) == 1: dieltens = np.diagflat(dieltens) logging.getLogger(__name__).debug('Lattice constants (in Angs): ' + str(cleanlat(angset))) [a1, a2, a3] = ang_to_bohr * angset # convert to bohr bohrset = [a1, a2, a3] vol = np.dot(a1, np.cross(a2, a3)) logging.getLogger(__name__).debug('Lattice constants (in Bohr): ' + str(cleanlat([a1, a2, a3]))) determ = np.linalg.det(dieltens) invdiel = np.linalg.inv(dieltens) logging.getLogger(__name__).debug('inv dielectric tensor: ' + str(invdiel)) return angset, bohrset, vol, determ, invdiel warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def real_sum(a1, a2, a3, r, q, dieltens, gamma, tolerance): invdiel = np.linalg.inv(dieltens) determ = np.linalg.det(dieltens) realpre = q / np.sqrt(determ) tolerance /= hart_to_ev #Real space sum by converging with respect to real space vectors #create list of real space vectors that satisfy |i*a1+j*a2+k*a3|<=N Nmaxlength = 40 #tolerance for stopping real space sum convergence N = 2 r_sums = [] while N < Nmaxlength: r_sum = 0.0 if norm(r): for i in range(-N, N+1): for j in range(-N, N+1): for k in range(-N, N+1): r_vec = i*a1 + j*a2 + k*a3 - r loc_res = np.dot(r_vec, np.dot(invdiel, r_vec)) nmr = math.erfc(gamma * np.sqrt(loc_res)) dmr = np.sqrt(determ * loc_res) r_sum += nmr / dmr else: for i in range(-N, N+1): for j in range(-N, N+1): for k in range(-N, N+1): if i == j == k == 0: continue else: r_vec = i*a1 + j*a2 + k*a3 loc_res = np.dot(r_vec, np.dot(invdiel, r_vec)) nmr = math.erfc(gamma * np.sqrt(loc_res)) dmr = np.sqrt(determ * loc_res) r_sum += nmr / dmr r_sums.append([N, realpre * r_sum]) if N == Nmaxlength-1: logging.getLogger(__name__).warning( 'Direct part could not converge with real space translation ' 'tolerance of {} for gamma {}'.format(Nmaxlength-1, gamma)) return elif len(r_sums) > 3: if abs(abs(r_sums[-1][1]) - abs(r_sums[-2][1])) < tolerance: r_sum = r_sums[-1][1] logging.debug("gamma is {}".format(gamma)) logging.getLogger(__name__).debug( "convergence for real summatin term occurs at step {} " "where real sum is {}".format(N, r_sum * hart_to_ev)) break N += 1 return r_sum warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def get_g_sum_at_r(g_sum, structure, dim, r): """ Args: g_sum: Reciprocal summation calculated from reciprocal_sum method structure: Bulk structure pymatgen object dim : ngxf dimension r: Position relative to defect (in cartesian coords) Returns: reciprocal summ value at g_sum[i_rx,j_ry,k_rz] """ fraccoord = structure.lattice.get_fractional_coords(r) i, j, k = getgridind(structure, dim, fraccoord) return g_sum[i, j, k] warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def anisotropic_madelung_potential(structure, dim, g_sum, r, dieltens, q, gamma, tolerance): """ Compute the anisotropic Madelung potential at r not equal to 0. For r=(0,0,0) use anisotropic_pc_energy function Args: structure: Bulk pymatgen structure type dim : ngxf dimension g_sum: Precomputed reciprocal sum for all r_vectors r: r vector (in cartesian coordinates) relative to defect position. Non zero r is expected dieltens: dielectric tensor q: Point charge (in units of e+) tolerance: Tolerance parameter for numerical convergence gamma (float): Convergence parameter silence (bool): Verbosity flag. If False, messages are printed. """ angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( structure, dieltens) recippartreal = q * get_g_sum_at_r(g_sum, structure, dim, r) directpart = real_sum(a1, a2, a3, r, q, dieltens, gamma, tolerance) #now add up total madelung potential part with two extra parts: #self interaction term selfint = q * np.pi / (vol * (gamma ** 2)) logging.getLogger(__name__).debug('self interaction piece is {}'.format( selfint * hart_to_ev)) pot = hart_to_ev * (directpart + recippartreal - selfint) return pot warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def anisotropic_pc_energy(structure, g_sum, dieltens, q, gamma, tolerance): """ Compute the anistropic periodic point charge interaction energy. Args: structure: Bulk pymatgen structure type g_sum : comes from KumagaiBulkInit class dieltens: dielectric tensor q: Point charge (in units of e+) gamma : convergence parameter optimized in KumagaiBulkInit class silence (bool): Verbosity flag. If False, messages are printed. """ angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( structure, dieltens) g_part = q*g_sum[0,0,0] r_part = real_sum(a1, a2, a3, [0,0,0], q, dieltens, gamma, tolerance) selfint = q*np.pi / (vol * (gamma**2)) #self interaction term #surface term (only for r not at origin) surfterm = 2*gamma*q / np.sqrt(np.pi*determ) logger = logging.getLogger(__name__) logger.debug('reciprocal part: {}'.format(g_part * hart_to_ev)) logger.debug('real part: {}'.format(r_part * hart_to_ev)) logger.debug('self interaction part: {}'.format(selfint * hart_to_ev)) logger.debug('surface term: {}'.format(surfterm * hart_to_ev)) pc_energy = -(q*0.5*hart_to_ev) * (r_part + g_part - selfint - surfterm) logging.debug('Final PC Energy term: {} eV'.format(pc_energy)) return pc_energy warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def getgridind(structure, dim, r, gridavg=0.0): """ Computes the index of a point, r, in the locpot grid Args: structure: Pymatgen structure object dim: dimension of FFT grid (NGXF dimension list in VASP) r: Relative co-ordinates with respect to abc lattice vectors gridavg: If you want to do atomic site averaging, set gridavg to the radius of the atom at r Returns: [i,j,k]: Indices as list TODO: Once final, remove the getgridind inside disttrans function """ abc = structure.lattice.abc grdind = [] if gridavg: radvals = [] #radius in terms of indices dxvals = [] for i in range(3): if r[i] < 0: while r[i] < 0: r[i] += 1 elif r[i] >= 1: while r[i] >= 1: r[i] -= 1 r[i] *= abc[i] num_pts = dim[i] x = [now_num / float(num_pts) * abc[i] for now_num in range(num_pts)] dx = x[1] - x[0] x_rprojection_delta_abs = np.absolute(x - r[i]) ind = np.argmin(x_rprojection_delta_abs) if x_rprojection_delta_abs[ind] > dx*1.1: #to avoid numerical errors logger = logging.getLogger(__name__) logger.error("Input position not within the locpot grid") logger.error("%d, %d, %f", i, ind, r) logger.error("%f", x_rprojection_delta_abs) raise ValueError("Input position is not within the locpot grid") grdind.append(ind) if gridavg: radvals.append(int(np.ceil(gridavg/dx))) dxvals.append(dx) if gridavg: grdindfull = [] for i in range(-radvals[0], radvals[0]+1): for j in range(-radvals[1], radvals[1]+1): for k in range(-radvals[2], radvals[2]+1): dtoc = [i*dxvals[0], j*dxvals[1], k*dxvals[2]] if norm(dtoc) < gridavg: ival = (i+grdind[0]) % dim[0] jval = (j+grdind[1]) % dim[1] kval = (k+grdind[2]) % dim[2] grdindfull.append((ival, jval, kval)) grdind = grdindfull return grdind warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def disttrans(struct, defstruct, defpos=None): """ To calculate distance from defect to each atom and finding NGX grid pts at each atom. Args: struct: Bulk structure object defstruct: Defect structure object defpos: (if known) defect position as a pymatgen Site object within bulk supercell """ #Find defect location in bulk and defect cells blksite, defsite = find_defect_pos(struct, defstruct, defpos=defpos) logger = logging.getLogger(__name__) if blksite is None and defsite is None: logger.error('Not able to determine defect site') return if blksite is None: logger.debug('Found defect to be Interstitial type at %s', repr(defsite)) elif defsite is None: logger.debug('Found defect to be Vacancy type at %s', repr(blksite)) else: logger.debug('Found defect to be antisite/subsitution type at %s ' \ ' in bulk, and %s in defect cell', repr(blksite), repr(defsite)) if blksite is None: blksite = defsite elif defsite is None: defsite = blksite def_ccoord = blksite[:] defcell_def_ccoord = defsite[:] if len(struct.sites) >= len(defstruct.sites): sitelist = struct.sites[:] else: #for interstitial list sitelist = defstruct.sites[:] #better image getter since pymatgen wasnt working well for this def returnclosestr(vec): from operator import itemgetter listvals = [] abclats = defstruct.lattice.matrix trylist = [-1, 0, 1] for i in trylist: for j in trylist: for k in trylist: transvec = i*abclats[0] + j*abclats[1] + k*abclats[2] rnew = vec - (defcell_def_ccoord + transvec) listvals.append([norm(rnew), rnew, transvec]) listvals.sort(key=itemgetter(0)) return listvals[0] #will return [dist,r to defect, and transvec for defect] grid_sites = {} # dictionary with indices keys in order of structure list for i in sitelist: if np.array_equal(i.coords, def_ccoord): logging.debug('Site {} is defect! Skipping '.format(i)) continue blksite, defsite = closestsites(struct, defstruct, i.coords) blkindex = blksite[-1] defindex = defsite[-1] dcart_coord = defsite[0].coords closeimage = returnclosestr(dcart_coord) cart_reldef = closeimage[1] defdist = closeimage[0] if abs(norm(cart_reldef) - defdist) > 0.1: logger.warning('Image locater issue encountered for site = %d', blkindex) logger.warning('In defect supercell') logger.warning('Distance should be %f', defdist) logger.warning('But, calculated distance is %f', norm(cart_reldef)) if blkindex in grid_sites: logger.warning('Index %d already exists in potinddict!', blkindex) logger.warning('Overwriting information.') grid_sites[blkindex] = { 'dist': defdist, 'cart': dcart_coord, 'cart_reldef': cart_reldef, 'siteobj': [i.coords, i.frac_coords, i.species_string], 'bulk_site_index': blkindex, 'def_site_index': defindex} return grid_sites warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def wigner_seitz_radius(structure): """ Calculate the Wigner Seitz radius for the given structure. Args: structure: pymatgen Structure object """ wz = structure.lattice.get_wigner_seitz_cell() dist = [] for facet in wz: midpt = np.mean(np.array(facet), axis=0) dist.append(norm(midpt)) wsrad = min(dist) return wsrad warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) def read_ES_avg_fromlocpot(locpot): """ Reads Electrostatic potential at each atomic site from Locpot Pymatgen object """ structure = locpot.structure radii = {specie: 1.0 for specie in set(structure.species)} # TODO: The above radii could be smarter (related to ENAUG?) # but turns out you get a similar result to Outcar differences # when taking locpot avgd differences ES_data = {'sampling_radii': radii, 'ngxf_dims': locpot.dim} pot = [] for site in structure.sites: indexlist = getgridind(structure, locpot.dim, site.frac_coords, gridavg=radii[site.specie]) samplevals = [] for u,v,w in indexlist: samplevals.append(locpot.data["total"][u][v][w]) pot.append(np.mean(samplevals)) ES_data.update({'potential': pot}) return ES_data warnings.warn("Replacing PyCDT usage of Kumagai base classes with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) class KumagaiBulkInit(object): """ Compute the anisotropic madelung potential array from the bulk locpot. This helps in evaluating the bulk supercell related part once to speed up the calculations. """ def __init__(self, structure, dim, epsilon, encut=520, tolerance=0.0001, optgamma=False): """ Args structure: Pymatgen structure object of bulk cell dim: Fine FFT grid dimensions as a list For vasp this is NGXF grid dimensions epsilon: Dielectric tensor encut (float): Energy cutoff for optimal gamma tolerance (float): Accuracy parameter optgamma: if you know optimized gamma, give its value. Otherwise it will be computed. """ self.structure = structure self.dim = dim self.epsilon = epsilon self.encut = encut self.tolerance = tolerance #self.silence = silence if not optgamma: self.gamma = self.find_optimal_gamma() else: self.gamma = optgamma self.g_sum = self.reciprocal_sum() logging.getLogger(__name__).info('optimized gamma: %f', self.gamma) def find_optimal_gamma(self): """ Find optimal gamma by evaluating the brute force reciprocal summation and seeing when the values are on the order of 1, This calculation is the anisotropic Madelung potential at r = (0,0,0). Note this only requires the STRUCTURE not the LOCPOT object. """ angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( self.structure, self.epsilon) optgam = None #do brute force recip summation def get_recippart(encut, gamma): recippart = 0.0 for rec in genrecip(a1, a2, a3, encut): Gdotdiel = np.dot(rec, np.dot(self.epsilon, rec)) summand = math.exp(-Gdotdiel / (4 * (gamma ** 2))) / Gdotdiel recippart += summand recippart *= 4*np.pi/vol return recippart, 0.0 def do_summation(gamma): # Do recip sum until it is bigger than 1eV # First do Recip space sum convergence with respect to encut for # this gamma encut = 20 #start with small encut for expediency recippartreal1, recippartimag1 = get_recippart(encut, gamma) encut += 10 recippartreal, recippartimag = get_recippart(encut, gamma) converge = [recippartreal1, recippartreal] logger = logging.getLogger(__name__) while abs(abs(converge[0]) - abs(converge[1])) * hart_to_ev > \ self.tolerance: encut += 10 recippartreal, recippartimag = get_recippart(encut, gamma) converge.reverse() converge[1] = recippartreal if encut > self.encut: msg = 'Optimal gamma not found at {} eV cutoff'.format( self.encut) logger.error(msg) raise ValueError(msg) if abs(recippartimag) * hart_to_ev > self.tolerance: logger.error("Imaginary part of reciprocal sum not converged.") logger.error("Imaginary sum value is {} (eV)".format( recippartimag * hart_to_ev)) return None, None logger.debug('Reciprocal sum converged to %f eV', recippartreal * hart_to_ev) logger.debug('Convergin encut = %d eV', encut) if (abs(converge[1]) * hart_to_ev < 1 and not optgam): logger.warning('Reciprocal summation value is less than 1 eV.') logger.warning('Might lead to errors') logger.warning('Change gamma.') return None, 'Try Again' return recippartreal, gamma logger = logging.getLogger(__name__) #start with gamma s.t. gamma*L=5 (this is optimal) #optimizing gamma for the reciprocal sum to improve convergence gamma = 5.0/(vol ** (1/3.0)) optimal_gamma_found = False while not optimal_gamma_found: recippartreal, optgamma = do_summation(gamma) if optgamma == gamma: logger.debug('optimized gamma found to be %f', optgamma) optimal_gamma_found = True elif 'Try Again' in optgamma: gamma *= 1.5 else: logger.error('Had problem in gamma optimization process.') return None if gamma > 50: logger.error('Could not optimize gamma before gamma = %d', 50) return None return optgamma def reciprocal_sum(self): """ Compute the reciprocal summation in the anisotropic Madelung potential. TODO: Get the input to fft cut by half by using rfft instead of fft """ logger = logging.getLogger(__name__) logger.debug('Reciprocal summation in Madeling potential') over_atob = 1.0 / ang_to_bohr atob3 = ang_to_bohr ** 3 latt = self.structure.lattice vol = latt.volume * atob3 # in Bohr^3 reci_latt = latt.reciprocal_lattice [b1, b2, b3] = reci_latt.get_cartesian_coords(1) b1 = np.array(b1) * over_atob # In 1/Bohr b2 = np.array(b2) * over_atob b3 = np.array(b3) * over_atob nx, ny, nz = self.dim logging.debug('nx: %d, ny: %d, nz: %d', nx, ny, nz) ind1 = np.arange(nx) for i in range(int(nx/2), nx): ind1[i] = i - nx ind2 = np.arange(ny) for i in range(int(ny/2), ny): ind2[i] = i - ny ind3 = np.arange(nz) for i in range(int(nz/2), nz): ind3[i] = i - nz g_array = np.zeros(self.dim, np.dtype('c16')) gamm2 = 4*(self.gamma**2) for i in ind1: for j in ind2: for k in ind3: g = i*b1 + j*b2 + k*b3 g_eps_g = np.dot(g, np.dot(self.epsilon, g)) if i == j == k == 0: continue else: g_array[i,j,k] = math.exp(-g_eps_g/gamm2) / g_eps_g r_array = np.fft.fftn(g_array) over_vol = 4*np.pi/vol # Multiply with q later r_array *= over_vol r_arr_real = np.real(r_array) r_arr_imag = np.imag(r_array) max_imag = r_arr_imag.max() logger.debug('Max imaginary part found to be %f', max_imag) return r_arr_real warnings.warn("Replacing PyCDT usage of Kumagai base classes and plotting with calls to " "corresponding objects in pymatgen.analysis.defects.corrections\n" "All core Kumagai code will be removed with Version 2.5 of PyCDT." " (note these functions all exist in pymatgen)", DeprecationWarning) class KumagaiCorrection(object): """ Extended freysoldt correction developed by Kumagai and Oba. """ def __init__(self, dielectric_tensor, q, gamma, g_sum, bulk_structure, defect_structure, energy_cutoff=520, madetol=0.0001, lengths=None, **kw): """ Args: dielectric_tensor: Macroscopic dielectric tensor Include ionic also if defect is relaxed, othewise ion clamped. Can be a matrix array or scalar. q: Charge associated with the defect. Typically integer gamma: Convergence parameter. Obtained from KumagaiBulkPart g_sum: value that is dependent on the Bulk only. Obtained from KumagaiBulkPart bulk_structure: bulk Pymatgen structure object. Need to specify this if using Outcar method for atomic site avg. (If you specify outcar files for bulk_file_path but dont specify structure then code will break) (TO DO: resolve this dumb dependency by being smarter about where structure comes from?) defect_structure: defect structure. Needed if using Outcar method energy_cutoff: Energy for plane wave cutoff (in eV). If not given, Materials Project default 520 eV is used. madetol: Tolerance for convergence of energy terms in eV lengths: Lengths of axes, for speeding up plotting slightly keywords: 1) bulk_locpot: Bulk Locpot file path OR Bulk Locpot defect_locpot: Defect Locpot file path or defect Locpot 2) (Or) bulk_outcar: Bulk Outcar file path defect_outcar: Defect outcar file path 3) defect_position: Defect position as a pymatgen Site object in the bulk supercell structure NOTE: this is optional but recommended, if not provided then analysis is done to find the defect position; this analysis has been rigorously tested, but has broken in an example with severe long range relaxation (at which point you probably should not be including the defect in your analysis...) """ if isinstance(dielectric_tensor, int) or \ isinstance(dielectric_tensor, float): self.dieltens = np.identity(3) * dielectric_tensor else: self.dieltens = np.array(dielectric_tensor) if 'bulk_locpot' in kw: if isinstance(kw['bulk_locpot'], Locpot): self.locpot_blk = kw['bulk_locpot'] else: self.locpot_blk = Locpot.from_file(kw['bulk_locpot']) if isinstance(kw['defect_locpot'], Locpot): self.locpot_def = kw['defect_locpot'] else: self.locpot_def = Locpot.from_file(kw['defect_locpot']) self.dim = self.locpot_blk.dim self.outcar_blk = None self.outcar_def = None self.do_outcar_method = False if 'bulk_outcar' in kw: self.outcar_blk = Outcar(str(kw['bulk_outcar'])) self.outcar_def = Outcar(str(kw['defect_outcar'])) self.do_outcar_method = True self.locpot_blk = None self.locpot_def = None self.dim = self.outcar_blk.ngf if 'defect_position' in kw: self._defpos = kw['defect_position'] else: self._defpos = None self.madetol = madetol self.q = q self.encut = energy_cutoff self.structure = bulk_structure self.defstructure = defect_structure self.gamma = gamma self.g_sum = g_sum self.lengths=lengths def correction(self, title=None, partflag='All'): """ Computes the extended Freysoldt correction for anistropic systems developed by <NAME> and <NAME> (Ref: PRB 89, 195205 (2014) Args: title: If plot of potential averaging process is wanted set title partflag: Specifies the part of correction computed 'pc': periodic interaction of defect charges (point charge) only 'potalign': potential alignmnet correction only, 'All' (default): pc and potalign combined into one value, 'AllSplit' for correction in form [PC, potterm, full] """ logger = logging.getLogger(__name__) logger.info('This is Kumagai Correction.') if not self.q: if partflag == 'AllSplit': return [0., 0., 0.] else: return 0.0 if partflag != 'potalign': energy_pc = self.pc() if partflag != 'pc': potalign = self.potalign(title=title) #logger.info('Kumagai Correction details:') #if partflag != 'potalign': # logger.info('PCenergy (E_lat) = %f', round(energy_pc, 5)) #if partflag != 'pc': # logger.info('potential alignment (-q*delta V) = %f', # round(potalign, 5)) if partflag in ['All','AllSplit']: logger.info('Total Kumagai correction = %f', round(energy_pc+potalign, 5)) if partflag == 'pc': return round(energy_pc, 5) elif partflag == 'potalign': return round(potalign, 5) elif partflag == 'All': return round(energy_pc+potalign, 5) else: return map(lambda x: round(x, 5), [energy_pc, potalign, energy_pc+potalign]) def pc(self): energy_pc = anisotropic_pc_energy( self.structure, self.g_sum, self.dieltens, self.q, self.gamma, self.madetol) logger = logging.getLogger(__name__) logger.info('PC energy determined to be %f eV (%f Hartree)', energy_pc, energy_pc/hart_to_ev) return energy_pc def potalign(self, title=None, output_sr=False): """ Potential alignment for Kumagai method Args: title: Title for the plot. None will not generate the plot output_sr allows for output of the short range potential (Good for delocalization analysis) """ logger = logging.getLogger(__name__) logger.info('\nRunning potential alignment (atomic site averaging)') angset, [a1, a2, a3], vol, determ, invdiel = kumagai_init( self.structure, self.dieltens) potinddict = disttrans(self.structure, self.defstructure, defpos=self._defpos) minlat = min(norm(a1), norm(a2), norm(a3)) lat_perc_diffs = [100 * abs(norm(a1) - norm(lat)) / minlat for lat \ in [a2, a3]] lat_perc_diffs.append(100 * abs(norm(a2) - norm(a3)) / minlat) if not all(i < 45 for i in lat_perc_diffs): logger.warning('Detected that cell was not very cubic.') logger.warning('Sampling atoms outside wigner-seitz cell may '\ 'not be optimal') wsrad = wigner_seitz_radius(self.structure) logger.debug('wsrad %f', wsrad) for i in potinddict.keys(): logger.debug("Atom %d, distance: %f", i, potinddict[i]['dist']) if potinddict[i]['dist'] > wsrad: potinddict[i]['OutsideWS'] = True else: potinddict[i]['OutsideWS'] = False if not self.do_outcar_method: puredat = read_ES_avg_fromlocpot(self.locpot_blk) defdat = read_ES_avg_fromlocpot(self.locpot_def) else: puredat = {'potential': self.outcar_blk.electrostatic_potential} defdat = {'potential': self.outcar_def.electrostatic_potential} jup = 0 for i in potinddict.keys(): jup += 1 if (not title and not potinddict[i]['OutsideWS']): #dont need to calculate inside WS if not printing plot continue j = potinddict[i]['def_site_index'] #assuming zero defined k = potinddict[i]['bulk_site_index'] v_qb = defdat['potential'][j] - puredat['potential'][k] cart_reldef = potinddict[i]['cart_reldef'] v_pc = anisotropic_madelung_potential( self.structure, self.dim, self.g_sum, cart_reldef, self.dieltens, self.q, self.gamma, self.madetol) v_qb *= -1 #change charge sign convention potinddict[i]['Vpc'] = v_pc potinddict[i]['Vqb'] = v_qb logger.debug('Atom: %d, anisotropic madelung potential: %f', i, v_pc) logger.debug('Atom: %d, bulk/defect difference = %f', i, v_qb) if title: fullspecset = self.structure.species specset = list(set(fullspecset)) shade, forplot = {}, {} for i in specset: shade[i.symbol] = {'r': [], 'Vpc': [], 'Vqb': []} forplot[i.symbol] = {'r': [], 'Vpc': [], 'Vqb': [],'sites':[]} forcorrection = [] for i in potinddict.keys(): if (not title and not potinddict[i]['OutsideWS']): continue if potinddict[i]['OutsideWS']: forcorrection.append(potinddict[i]['Vqb']-potinddict[i]['Vpc']) if title: elt = fullspecset[i].symbol shade[elt]['r'].append(potinddict[i]['dist']) shade[elt]['Vpc'].append(potinddict[i]['Vpc']) shade[elt]['Vqb'].append(potinddict[i]['Vqb']) if title: elt = fullspecset[i].symbol forplot[elt]['r'].append(potinddict[i]['dist']) forplot[elt]['Vpc'].append(potinddict[i]['Vpc']) forplot[elt]['Vqb'].append(potinddict[i]['Vqb']) forplot[elt]['sites'].append(potinddict[i]['siteobj']) potalign = np.mean(forcorrection) if title: forplot['EXTRA'] = {'wsrad': wsrad, 'potalign': potalign} try: forplot['EXTRA']['lengths']=self.structure.lattice.abc except: forplot['EXTRA']['lengths']=self.lengths if title != 'written': KumagaiCorrection.plot(forplot, title=title) else: #TODO: use a more descriptive fname that describes the defect from monty.serialization import dumpfn from monty.json import MontyEncoder fname = 'KumagaiData.json' dumpfn(forplot, fname, cls=MontyEncoder) logger.info('potential alignment (site averaging): %f', np.mean(forcorrection)) logger.info('Potential correction energy: %f eV', -self.q * np.mean(forcorrection)) if output_sr: outpot = {'sampled': forcorrection, 'alldata':potinddict} return ((-self.q * np.mean(forcorrection)), outpot) #pot align energy correction (eV) else: return (-self.q * np.mean(forcorrection)) #pot align energy correction (eV) @classmethod def plot(cls, forplot, title): """ Plotting of locpot data TODO: Rename forplot to a more descriptive name """ import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties plt.figure() plt.clf() collis = ['b', 'g', 'c', 'm', 'y', 'w', 'k'] ylis = [] rlis = [] for i in range(len(forplot.keys())): inkey = list(forplot.keys())[i] if inkey == 'EXTRA': continue for k in forplot[inkey]['r']: rlis.append(k) for k in ['Vqb', 'Vpc']: for u in forplot[inkey][k]: ylis.append(u) plt.plot(forplot[inkey]['r'], forplot[inkey]['Vqb'], color=collis[i], marker='^', linestyle='None', label=str(inkey) + ': $V_{q/b}$') plt.plot(forplot[inkey]['r'], forplot[inkey]['Vpc'], color=collis[i], marker='o', linestyle='None', label=str(inkey) + ': $V_{pc}$') full = [] for i in forplot.keys(): if i == 'EXTRA': continue for k in range(len(forplot[i]['Vpc'])): full.append([ forplot[i]['r'][k], forplot[i]['Vqb'][k] - forplot[i]['Vpc'][k] ]) realfull = sorted(full, key=lambda x: x[0]) r, y = [], [] for i in realfull: r.append(i[0]) y.append(i[1]) wsrad = forplot['EXTRA']['wsrad'] potalign = forplot['EXTRA']['potalign'] plt.plot(r, y, color=collis[-1], marker='x', linestyle='None', label='$V_{q/b}$ - $V_{pc}$') plt.xlabel('Distance from defect ($\AA$)',fontsize=20) plt.ylabel('Potential (V)',fontsize=20) x = np.arange(wsrad, max(forplot['EXTRA']['lengths']), 0.01) plt.fill_between(x, min(ylis) - 1, max(ylis) + 1, facecolor='red', alpha=0.15, label='sampling region') plt.axhline(y=potalign, linewidth=0.5, color='red', label='pot. align. / q') fontP = FontProperties() fontP.set_size('small') plt.legend(bbox_to_anchor=(1.05, 0.5), prop=fontP) plt.axhline(y=0, linewidth=0.2, color='black') plt.ylim([min(ylis) - 0.5, max(ylis) + 0.5]) plt.xlim([0, max(rlis) + 3]) plt.title('%s atomic site potential plot' % title) plt.savefig('%s_kumagaisiteavgPlot.pdf' % title) @classmethod def plot_from_datfile(cls, name='KumagaiData.json', title='default'): """ Takes data file called 'name' and does plotting. Good for later plotting of locpot data after running run_correction() """ from monty.serialization import loadfn from monty.json import MontyDecoder forplot = loadfn(name, cls=MontyDecoder) cls.plot(forplot, title=title)
en
0.739713
This module computes finite size supercell charge corrections for defects in anistropic systems using extended Freysoldt (or Kumagai) method developed by Kumagai and Oba. Kumagai method includes a) anisotropic PC energy b) potential alignment by atomic site averaging at Wigner Seitz cell edge If you use the corrections implemented in this module, cite a) Kumagai and Oba, Phys. Rev. B. 89, 195205 (2014) and b) Freysoldt, Neugebauer, and Van <NAME>, Phys. Status Solidi B. 248, 1067-1076 (2011) and in addition to the pycdt paper # convert to bohr #Real space sum by converging with respect to real space vectors #create list of real space vectors that satisfy |i*a1+j*a2+k*a3|<=N #tolerance for stopping real space sum convergence Args: g_sum: Reciprocal summation calculated from reciprocal_sum method structure: Bulk structure pymatgen object dim : ngxf dimension r: Position relative to defect (in cartesian coords) Returns: reciprocal summ value at g_sum[i_rx,j_ry,k_rz] Compute the anisotropic Madelung potential at r not equal to 0. For r=(0,0,0) use anisotropic_pc_energy function Args: structure: Bulk pymatgen structure type dim : ngxf dimension g_sum: Precomputed reciprocal sum for all r_vectors r: r vector (in cartesian coordinates) relative to defect position. Non zero r is expected dieltens: dielectric tensor q: Point charge (in units of e+) tolerance: Tolerance parameter for numerical convergence gamma (float): Convergence parameter silence (bool): Verbosity flag. If False, messages are printed. #now add up total madelung potential part with two extra parts: #self interaction term Compute the anistropic periodic point charge interaction energy. Args: structure: Bulk pymatgen structure type g_sum : comes from KumagaiBulkInit class dieltens: dielectric tensor q: Point charge (in units of e+) gamma : convergence parameter optimized in KumagaiBulkInit class silence (bool): Verbosity flag. If False, messages are printed. #self interaction term #surface term (only for r not at origin) Computes the index of a point, r, in the locpot grid Args: structure: Pymatgen structure object dim: dimension of FFT grid (NGXF dimension list in VASP) r: Relative co-ordinates with respect to abc lattice vectors gridavg: If you want to do atomic site averaging, set gridavg to the radius of the atom at r Returns: [i,j,k]: Indices as list TODO: Once final, remove the getgridind inside disttrans function #radius in terms of indices #to avoid numerical errors To calculate distance from defect to each atom and finding NGX grid pts at each atom. Args: struct: Bulk structure object defstruct: Defect structure object defpos: (if known) defect position as a pymatgen Site object within bulk supercell #Find defect location in bulk and defect cells #for interstitial list #better image getter since pymatgen wasnt working well for this #will return [dist,r to defect, and transvec for defect] # dictionary with indices keys in order of structure list Calculate the Wigner Seitz radius for the given structure. Args: structure: pymatgen Structure object Reads Electrostatic potential at each atomic site from Locpot Pymatgen object # TODO: The above radii could be smarter (related to ENAUG?) # but turns out you get a similar result to Outcar differences # when taking locpot avgd differences Compute the anisotropic madelung potential array from the bulk locpot. This helps in evaluating the bulk supercell related part once to speed up the calculations. Args structure: Pymatgen structure object of bulk cell dim: Fine FFT grid dimensions as a list For vasp this is NGXF grid dimensions epsilon: Dielectric tensor encut (float): Energy cutoff for optimal gamma tolerance (float): Accuracy parameter optgamma: if you know optimized gamma, give its value. Otherwise it will be computed. #self.silence = silence Find optimal gamma by evaluating the brute force reciprocal summation and seeing when the values are on the order of 1, This calculation is the anisotropic Madelung potential at r = (0,0,0). Note this only requires the STRUCTURE not the LOCPOT object. #do brute force recip summation # Do recip sum until it is bigger than 1eV # First do Recip space sum convergence with respect to encut for # this gamma #start with small encut for expediency #start with gamma s.t. gamma*L=5 (this is optimal) #optimizing gamma for the reciprocal sum to improve convergence Compute the reciprocal summation in the anisotropic Madelung potential. TODO: Get the input to fft cut by half by using rfft instead of fft # in Bohr^3 # In 1/Bohr # Multiply with q later Extended freysoldt correction developed by Kumagai and Oba. Args: dielectric_tensor: Macroscopic dielectric tensor Include ionic also if defect is relaxed, othewise ion clamped. Can be a matrix array or scalar. q: Charge associated with the defect. Typically integer gamma: Convergence parameter. Obtained from KumagaiBulkPart g_sum: value that is dependent on the Bulk only. Obtained from KumagaiBulkPart bulk_structure: bulk Pymatgen structure object. Need to specify this if using Outcar method for atomic site avg. (If you specify outcar files for bulk_file_path but dont specify structure then code will break) (TO DO: resolve this dumb dependency by being smarter about where structure comes from?) defect_structure: defect structure. Needed if using Outcar method energy_cutoff: Energy for plane wave cutoff (in eV). If not given, Materials Project default 520 eV is used. madetol: Tolerance for convergence of energy terms in eV lengths: Lengths of axes, for speeding up plotting slightly keywords: 1) bulk_locpot: Bulk Locpot file path OR Bulk Locpot defect_locpot: Defect Locpot file path or defect Locpot 2) (Or) bulk_outcar: Bulk Outcar file path defect_outcar: Defect outcar file path 3) defect_position: Defect position as a pymatgen Site object in the bulk supercell structure NOTE: this is optional but recommended, if not provided then analysis is done to find the defect position; this analysis has been rigorously tested, but has broken in an example with severe long range relaxation (at which point you probably should not be including the defect in your analysis...) Computes the extended Freysoldt correction for anistropic systems developed by <NAME> and <NAME> (Ref: PRB 89, 195205 (2014) Args: title: If plot of potential averaging process is wanted set title partflag: Specifies the part of correction computed 'pc': periodic interaction of defect charges (point charge) only 'potalign': potential alignmnet correction only, 'All' (default): pc and potalign combined into one value, 'AllSplit' for correction in form [PC, potterm, full] #logger.info('Kumagai Correction details:') #if partflag != 'potalign': # logger.info('PCenergy (E_lat) = %f', round(energy_pc, 5)) #if partflag != 'pc': # logger.info('potential alignment (-q*delta V) = %f', # round(potalign, 5)) Potential alignment for Kumagai method Args: title: Title for the plot. None will not generate the plot output_sr allows for output of the short range potential (Good for delocalization analysis) #dont need to calculate inside WS if not printing plot #assuming zero defined #change charge sign convention #TODO: use a more descriptive fname that describes the defect #pot align energy correction (eV) #pot align energy correction (eV) Plotting of locpot data TODO: Rename forplot to a more descriptive name Takes data file called 'name' and does plotting. Good for later plotting of locpot data after running run_correction()
2.33127
2
src/python/T0/StorageManager/StorageManagerAPI.py
silviodonato/T0
6
6614290
""" _StorageManagerAPI_ Contains all the code for interfacing with the StorageManager """ import logging import threading import time from WMCore.DAOFactory import DAOFactory knownStreamers = set() def injectNewData(dbInterfaceStorageManager, dbInterfaceHltConf, dbInterfaceSMNotify, streamerPNN, minRun = None, maxRun = None, injectRun = None): """ _injectNewData_ Replaces the old-style file notification injecton into the Tier0. Queries the StorageManager database for new data and injects it into the Tier0. These queries will find duplicates, ie. data that was already found and processed in a previous polling cycle. Code has to be robust against that. Needs to be passed the PNN on which streamer files are located """ logging.debug("injectNewData()") myThread = threading.currentThread() daoFactory = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = myThread.dbi) daoFactoryStorageManager = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceStorageManager) daoFactoryHltConf = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceHltConf) if dbInterfaceSMNotify: daoFactorySMNotify = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceSMNotify) insertFileStatusDAO = daoFactorySMNotify(classname = "SMNotification.InsertOfflineFileStatus") getNewDataDAO = daoFactoryStorageManager(classname = "StorageManager.GetNewData") getRunInfoDAO = daoFactoryHltConf(classname = "StorageManager.GetRunInfo") insertRunDAO = daoFactory(classname = "RunConfig.InsertRun") insertStreamDAO = daoFactory(classname = "RunConfig.InsertStream") insertCMSSWVersionDAO = daoFactory(classname = "RunConfig.InsertCMSSWVersion") insertStreamCMSSWVersionDAO = daoFactory(classname = "RunConfig.InsertStreamCMSSWVersion") insertLumiDAO = daoFactory(classname = "RunConfig.InsertLumiSection") insertStreamerDAO = daoFactory(classname = "RunConfig.InsertStreamer") newData = getNewDataDAO.execute(minRun = minRun, maxRun = maxRun, injectRun = injectRun, transaction = False) # remove already processed files newData[:] = [newFile for newFile in newData if newFile['p5_id'] not in knownStreamers] logging.debug("StoragemanagerAPI: found %d new files", len(newData)) newRuns = set() newRunStreams = {} for newFile in newData: run = newFile['run'] stream = newFile['stream'] newRuns.add(newFile['run']) if run not in newRunStreams: newRunStreams[run] = set() if stream not in newRunStreams[run]: newRunStreams[run].add(stream) logging.debug("StoragemanagerAPI: found %d new runs", len(newRuns)) cmsswVersions = set() streams = set() bindRunHltKey = [] bindRunStreamCMSSW = [] for run in sorted(list(newRuns)): (hltkey, cmssw) = getRunInfoDAO.execute(run = run, transaction = False) logging.debug("StorageManagerAPI: run = %d, hltkey = %s, cmssw = %s", run, hltkey, cmssw) if hltkey and cmssw: cmssw = '_'.join(cmssw.split('_')[0:4]) # only consider base release cmsswVersions.add(cmssw) bindRunHltKey.append( { 'RUN': run, 'HLTKEY': hltkey } ) for stream in newRunStreams[run]: streams.add(stream) bindRunStreamCMSSW.append( { 'RUN': run, 'STREAM': stream, 'VERSION': cmssw } ) else: # can't retrieve hltkey and cmssw for run, ignore any data for it newRuns.remove(run) if len(bindRunHltKey) > 0: insertRunDAO.execute(binds = bindRunHltKey, transaction = False) bindStream = [] for stream in streams: bindStream.append( { 'STREAM': stream } ) if len(bindStream) > 0: insertStreamDAO.execute(binds = bindStream, transaction = False) bindCMSSW = [] for cmssw in cmsswVersions: bindCMSSW.append( { 'VERSION': cmssw } ) if len(bindCMSSW) > 0: insertCMSSWVersionDAO.execute(binds = bindCMSSW, transaction = False) if len(bindRunStreamCMSSW) > 0: insertStreamCMSSWVersionDAO.execute(binds = bindRunStreamCMSSW, transaction = False) lumis = set() bindStreamer = [] bindInsertFileStatus = [] for newFile in newData: run = newFile['run'] if run not in newRuns: continue lumi = newFile['lumi'] lumis.add((run,lumi)) if newFile['filename'] == 'run289461_ls0020_streamExpressCosmics_StorageManager.dat': newFile['path'] = '/store/t0streamer/Data/ExpressCosmics/000/289/461' bindStreamer.append( { 'LFN': newFile['path'] + '/' + newFile['filename'], 'P5_ID': newFile['p5_id'], 'RUN': run, 'LUMI': lumi, 'STREAM': newFile['stream'], 'FILESIZE': newFile['filesize'], 'EVENTS': newFile['events'], 'TIME': int(time.time()) } ) if dbInterfaceSMNotify: bindInsertFileStatus.append( { 'P5_ID': newFile['p5_id'], 'FILENAME': newFile['filename'] } ) bindLumi = [] for lumi in lumis: bindLumi.append( { 'RUN': lumi[0], 'LUMI': lumi[1] } ) if len(bindLumi) > 0: insertLumiDAO.execute(binds = bindLumi, transaction = False) if len(bindStreamer) > 0: insertStreamerDAO.execute(streamerPNN, binds = bindStreamer, transaction = False) if len(bindInsertFileStatus) > 0: insertFileStatusDAO.execute(bindInsertFileStatus, transaction = False) for x in bindStreamer: knownStreamers.add(x['P5_ID']) return def markRepacked(dbInterfaceSMNotify): """ _markRepacked_ Find all finished streamers for closed all run/stream Update the StorageManager notification table Update the streamer status to finished (deleted = 1) """ if not dbInterfaceSMNotify: return logging.debug("updateFileStatus()") myThread = threading.currentThread() daoFactory = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = myThread.dbi) daoFactorySMNotify = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceSMNotify) getFinishedStreamersDAO = daoFactory(classname = "SMNotification.GetFinishedStreamers") updateFileStatusDAO = daoFactorySMNotify(classname = "SMNotification.UpdateOfflineFileStatus") markStreamersFinishedDAO = daoFactory(classname = "SMNotification.MarkStreamersFinished") finishedStreamers = getFinishedStreamersDAO.execute(transaction = False) streamers = [] bindUpdateFileStatus = [] for (streamer_id, p5_id) in finishedStreamers: streamers.append(streamer_id) bindUpdateFileStatus.append( { 'P5_ID': p5_id } ) if len(bindUpdateFileStatus) > 0: updateFileStatusDAO.execute(bindUpdateFileStatus, transaction = False) if len(streamers) > 0: markStreamersFinishedDAO.execute(streamers, transaction = False) return
""" _StorageManagerAPI_ Contains all the code for interfacing with the StorageManager """ import logging import threading import time from WMCore.DAOFactory import DAOFactory knownStreamers = set() def injectNewData(dbInterfaceStorageManager, dbInterfaceHltConf, dbInterfaceSMNotify, streamerPNN, minRun = None, maxRun = None, injectRun = None): """ _injectNewData_ Replaces the old-style file notification injecton into the Tier0. Queries the StorageManager database for new data and injects it into the Tier0. These queries will find duplicates, ie. data that was already found and processed in a previous polling cycle. Code has to be robust against that. Needs to be passed the PNN on which streamer files are located """ logging.debug("injectNewData()") myThread = threading.currentThread() daoFactory = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = myThread.dbi) daoFactoryStorageManager = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceStorageManager) daoFactoryHltConf = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceHltConf) if dbInterfaceSMNotify: daoFactorySMNotify = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceSMNotify) insertFileStatusDAO = daoFactorySMNotify(classname = "SMNotification.InsertOfflineFileStatus") getNewDataDAO = daoFactoryStorageManager(classname = "StorageManager.GetNewData") getRunInfoDAO = daoFactoryHltConf(classname = "StorageManager.GetRunInfo") insertRunDAO = daoFactory(classname = "RunConfig.InsertRun") insertStreamDAO = daoFactory(classname = "RunConfig.InsertStream") insertCMSSWVersionDAO = daoFactory(classname = "RunConfig.InsertCMSSWVersion") insertStreamCMSSWVersionDAO = daoFactory(classname = "RunConfig.InsertStreamCMSSWVersion") insertLumiDAO = daoFactory(classname = "RunConfig.InsertLumiSection") insertStreamerDAO = daoFactory(classname = "RunConfig.InsertStreamer") newData = getNewDataDAO.execute(minRun = minRun, maxRun = maxRun, injectRun = injectRun, transaction = False) # remove already processed files newData[:] = [newFile for newFile in newData if newFile['p5_id'] not in knownStreamers] logging.debug("StoragemanagerAPI: found %d new files", len(newData)) newRuns = set() newRunStreams = {} for newFile in newData: run = newFile['run'] stream = newFile['stream'] newRuns.add(newFile['run']) if run not in newRunStreams: newRunStreams[run] = set() if stream not in newRunStreams[run]: newRunStreams[run].add(stream) logging.debug("StoragemanagerAPI: found %d new runs", len(newRuns)) cmsswVersions = set() streams = set() bindRunHltKey = [] bindRunStreamCMSSW = [] for run in sorted(list(newRuns)): (hltkey, cmssw) = getRunInfoDAO.execute(run = run, transaction = False) logging.debug("StorageManagerAPI: run = %d, hltkey = %s, cmssw = %s", run, hltkey, cmssw) if hltkey and cmssw: cmssw = '_'.join(cmssw.split('_')[0:4]) # only consider base release cmsswVersions.add(cmssw) bindRunHltKey.append( { 'RUN': run, 'HLTKEY': hltkey } ) for stream in newRunStreams[run]: streams.add(stream) bindRunStreamCMSSW.append( { 'RUN': run, 'STREAM': stream, 'VERSION': cmssw } ) else: # can't retrieve hltkey and cmssw for run, ignore any data for it newRuns.remove(run) if len(bindRunHltKey) > 0: insertRunDAO.execute(binds = bindRunHltKey, transaction = False) bindStream = [] for stream in streams: bindStream.append( { 'STREAM': stream } ) if len(bindStream) > 0: insertStreamDAO.execute(binds = bindStream, transaction = False) bindCMSSW = [] for cmssw in cmsswVersions: bindCMSSW.append( { 'VERSION': cmssw } ) if len(bindCMSSW) > 0: insertCMSSWVersionDAO.execute(binds = bindCMSSW, transaction = False) if len(bindRunStreamCMSSW) > 0: insertStreamCMSSWVersionDAO.execute(binds = bindRunStreamCMSSW, transaction = False) lumis = set() bindStreamer = [] bindInsertFileStatus = [] for newFile in newData: run = newFile['run'] if run not in newRuns: continue lumi = newFile['lumi'] lumis.add((run,lumi)) if newFile['filename'] == 'run289461_ls0020_streamExpressCosmics_StorageManager.dat': newFile['path'] = '/store/t0streamer/Data/ExpressCosmics/000/289/461' bindStreamer.append( { 'LFN': newFile['path'] + '/' + newFile['filename'], 'P5_ID': newFile['p5_id'], 'RUN': run, 'LUMI': lumi, 'STREAM': newFile['stream'], 'FILESIZE': newFile['filesize'], 'EVENTS': newFile['events'], 'TIME': int(time.time()) } ) if dbInterfaceSMNotify: bindInsertFileStatus.append( { 'P5_ID': newFile['p5_id'], 'FILENAME': newFile['filename'] } ) bindLumi = [] for lumi in lumis: bindLumi.append( { 'RUN': lumi[0], 'LUMI': lumi[1] } ) if len(bindLumi) > 0: insertLumiDAO.execute(binds = bindLumi, transaction = False) if len(bindStreamer) > 0: insertStreamerDAO.execute(streamerPNN, binds = bindStreamer, transaction = False) if len(bindInsertFileStatus) > 0: insertFileStatusDAO.execute(bindInsertFileStatus, transaction = False) for x in bindStreamer: knownStreamers.add(x['P5_ID']) return def markRepacked(dbInterfaceSMNotify): """ _markRepacked_ Find all finished streamers for closed all run/stream Update the StorageManager notification table Update the streamer status to finished (deleted = 1) """ if not dbInterfaceSMNotify: return logging.debug("updateFileStatus()") myThread = threading.currentThread() daoFactory = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = myThread.dbi) daoFactorySMNotify = DAOFactory(package = "T0.WMBS", logger = logging, dbinterface = dbInterfaceSMNotify) getFinishedStreamersDAO = daoFactory(classname = "SMNotification.GetFinishedStreamers") updateFileStatusDAO = daoFactorySMNotify(classname = "SMNotification.UpdateOfflineFileStatus") markStreamersFinishedDAO = daoFactory(classname = "SMNotification.MarkStreamersFinished") finishedStreamers = getFinishedStreamersDAO.execute(transaction = False) streamers = [] bindUpdateFileStatus = [] for (streamer_id, p5_id) in finishedStreamers: streamers.append(streamer_id) bindUpdateFileStatus.append( { 'P5_ID': p5_id } ) if len(bindUpdateFileStatus) > 0: updateFileStatusDAO.execute(bindUpdateFileStatus, transaction = False) if len(streamers) > 0: markStreamersFinishedDAO.execute(streamers, transaction = False) return
en
0.919641
_StorageManagerAPI_ Contains all the code for interfacing with the StorageManager _injectNewData_ Replaces the old-style file notification injecton into the Tier0. Queries the StorageManager database for new data and injects it into the Tier0. These queries will find duplicates, ie. data that was already found and processed in a previous polling cycle. Code has to be robust against that. Needs to be passed the PNN on which streamer files are located # remove already processed files # only consider base release # can't retrieve hltkey and cmssw for run, ignore any data for it _markRepacked_ Find all finished streamers for closed all run/stream Update the StorageManager notification table Update the streamer status to finished (deleted = 1)
2.268322
2
machine_learning/over_sampling_by_replication.py
xwkuang5/code-fragments
0
6614291
""" This script tests the intuition behind the Synthetic Minority Over-sampling Technique (SMOTE). Bascially, the intution behind the technique is that simply over-sample the minority class by replicating will lead to overfitting. The authors argue that replicating minority samples will cause the decision boundary to become overly specific. Intuitively, if we do not have prior knowledge about the distribution of the input data, we should not mislead the learning algorithm to think that way, which arguably is what replication is doing. Therefore, the SMOTE algorithm can be thought of as a more conservative way of doing data replication: we do not have 100% confidence that the data will appear exactly the same as the sampled data. However, we believe that unseen data should be close to the sampled data and its neighbors. It is hard to replicate the results exactly without going into more details about creating an artificial datasets. However, the figure shown by this script should provide some evidence that the intution may be true to some extent. The second plot in the figure shows that the algorithm learns more decision boundaries for the second class due to over-sampling, which may (or may not) be a result of overfitting. Installed packages: Package Version ---------------- ------- cycler 0.10.0 imbalanced-learn 0.3.3 imblearn 0.0 kiwisolver 1.0.1 matplotlib 2.2.2 numpy 1.14.3 pip 10.0.1 pyparsing 2.2.0 python-dateutil 2.7.2 pytz 2018.4 scikit-learn 0.19.1 scipy 1.1.0 setuptools 39.1.0 six 1.11.0 wheel 0.31.0 """ import numpy as np import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import make_classification from imblearn.over_sampling import RandomOverSampler X, y = make_classification( n_samples=5000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2, weights=[0.95, 0.05], flip_y=0, class_sep=0.1, random_state=0) # over-sample the minority class ros = RandomOverSampler({1: 3000}, random_state=0) X_resampled, y_resampled = ros.fit_sample(X, y) # create mesh grid x_min = min(min(X[:, 0]), min(X_resampled[:, 0])) x_max = max(max(X[:, 0]), max(X_resampled[:, 0])) y_min = min(min(X[:, 1]), min(X_resampled[:, 1])) y_max = max(max(X[:, 1]), max(X_resampled[:, 1])) xx, yy = np.meshgrid( np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(2, 1, sharex='col', figsize=(10, 8)) """ Raw data """ clf = DecisionTreeClassifier(max_depth=4) clf.fit(X[:, :2], y) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[0].contourf(xx, yy, Z, alpha=0.4) axarr[0].scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor='k') axarr[0].set_title("Original data") """ Minority-class-over-sampled data """ clf_resampled = DecisionTreeClassifier(max_depth=4) clf_resampled.fit(X_resampled[:, :2], y_resampled) Z = clf_resampled.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[1].contourf(xx, yy, Z, alpha=0.4) axarr[1].scatter( X_resampled[:, 0], X_resampled[:, 1], c=y_resampled, s=20, edgecolor='k') axarr[1].set_title("Over-sampled data") plt.show()
""" This script tests the intuition behind the Synthetic Minority Over-sampling Technique (SMOTE). Bascially, the intution behind the technique is that simply over-sample the minority class by replicating will lead to overfitting. The authors argue that replicating minority samples will cause the decision boundary to become overly specific. Intuitively, if we do not have prior knowledge about the distribution of the input data, we should not mislead the learning algorithm to think that way, which arguably is what replication is doing. Therefore, the SMOTE algorithm can be thought of as a more conservative way of doing data replication: we do not have 100% confidence that the data will appear exactly the same as the sampled data. However, we believe that unseen data should be close to the sampled data and its neighbors. It is hard to replicate the results exactly without going into more details about creating an artificial datasets. However, the figure shown by this script should provide some evidence that the intution may be true to some extent. The second plot in the figure shows that the algorithm learns more decision boundaries for the second class due to over-sampling, which may (or may not) be a result of overfitting. Installed packages: Package Version ---------------- ------- cycler 0.10.0 imbalanced-learn 0.3.3 imblearn 0.0 kiwisolver 1.0.1 matplotlib 2.2.2 numpy 1.14.3 pip 10.0.1 pyparsing 2.2.0 python-dateutil 2.7.2 pytz 2018.4 scikit-learn 0.19.1 scipy 1.1.0 setuptools 39.1.0 six 1.11.0 wheel 0.31.0 """ import numpy as np import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import make_classification from imblearn.over_sampling import RandomOverSampler X, y = make_classification( n_samples=5000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2, weights=[0.95, 0.05], flip_y=0, class_sep=0.1, random_state=0) # over-sample the minority class ros = RandomOverSampler({1: 3000}, random_state=0) X_resampled, y_resampled = ros.fit_sample(X, y) # create mesh grid x_min = min(min(X[:, 0]), min(X_resampled[:, 0])) x_max = max(max(X[:, 0]), max(X_resampled[:, 0])) y_min = min(min(X[:, 1]), min(X_resampled[:, 1])) y_max = max(max(X[:, 1]), max(X_resampled[:, 1])) xx, yy = np.meshgrid( np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(2, 1, sharex='col', figsize=(10, 8)) """ Raw data """ clf = DecisionTreeClassifier(max_depth=4) clf.fit(X[:, :2], y) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[0].contourf(xx, yy, Z, alpha=0.4) axarr[0].scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor='k') axarr[0].set_title("Original data") """ Minority-class-over-sampled data """ clf_resampled = DecisionTreeClassifier(max_depth=4) clf_resampled.fit(X_resampled[:, :2], y_resampled) Z = clf_resampled.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[1].contourf(xx, yy, Z, alpha=0.4) axarr[1].scatter( X_resampled[:, 0], X_resampled[:, 1], c=y_resampled, s=20, edgecolor='k') axarr[1].set_title("Over-sampled data") plt.show()
en
0.904805
This script tests the intuition behind the Synthetic Minority Over-sampling Technique (SMOTE). Bascially, the intution behind the technique is that simply over-sample the minority class by replicating will lead to overfitting. The authors argue that replicating minority samples will cause the decision boundary to become overly specific. Intuitively, if we do not have prior knowledge about the distribution of the input data, we should not mislead the learning algorithm to think that way, which arguably is what replication is doing. Therefore, the SMOTE algorithm can be thought of as a more conservative way of doing data replication: we do not have 100% confidence that the data will appear exactly the same as the sampled data. However, we believe that unseen data should be close to the sampled data and its neighbors. It is hard to replicate the results exactly without going into more details about creating an artificial datasets. However, the figure shown by this script should provide some evidence that the intution may be true to some extent. The second plot in the figure shows that the algorithm learns more decision boundaries for the second class due to over-sampling, which may (or may not) be a result of overfitting. Installed packages: Package Version ---------------- ------- cycler 0.10.0 imbalanced-learn 0.3.3 imblearn 0.0 kiwisolver 1.0.1 matplotlib 2.2.2 numpy 1.14.3 pip 10.0.1 pyparsing 2.2.0 python-dateutil 2.7.2 pytz 2018.4 scikit-learn 0.19.1 scipy 1.1.0 setuptools 39.1.0 six 1.11.0 wheel 0.31.0 # over-sample the minority class # create mesh grid Raw data Minority-class-over-sampled data
3.228227
3
ACME/geometry/metric/quadrilateral/quadrilateral_shape_metric.py
mauriziokovacic/ACME
3
6614292
from .quadrilateral_metric import * class QuadrilateralShapeMetric(QuadrilateralMetric): def __init__(self): super(QuadrilateralShapeMetric, self).__init__( name='Quadrilateral Shape', dimension='1', acceptable_range=Range(min=0.3, max=1), normal_range=Range(min=0, max=1), full_range=Range(min=0, max=1), q_for_unit=1, ) def eval(self, P, T): L = torch.pow(torch.cat(self.edge_lengths(P, T), dim=1), 2) a = torch.cat(self.areas(P, T), dim=1) return 2*torch.min(torch.cat((a[:, 0] / (L[:, 0] + L[:, 3]), a[:, 1] / (L[:, 1] + L[:, 0]), a[:, 2] / (L[:, 2] + L[:, 1]), a[:, 3] / (L[:, 3] + L[:, 2]), ), dim=1), dim=1, keepdim=True)[0]
from .quadrilateral_metric import * class QuadrilateralShapeMetric(QuadrilateralMetric): def __init__(self): super(QuadrilateralShapeMetric, self).__init__( name='Quadrilateral Shape', dimension='1', acceptable_range=Range(min=0.3, max=1), normal_range=Range(min=0, max=1), full_range=Range(min=0, max=1), q_for_unit=1, ) def eval(self, P, T): L = torch.pow(torch.cat(self.edge_lengths(P, T), dim=1), 2) a = torch.cat(self.areas(P, T), dim=1) return 2*torch.min(torch.cat((a[:, 0] / (L[:, 0] + L[:, 3]), a[:, 1] / (L[:, 1] + L[:, 0]), a[:, 2] / (L[:, 2] + L[:, 1]), a[:, 3] / (L[:, 3] + L[:, 2]), ), dim=1), dim=1, keepdim=True)[0]
none
1
2.477068
2
vanderwijk.iivvoo.kar/default.py
iivvoo/kodiekar
1
6614293
import time import json import sys import xbmc import xbmcgui import xbmcaddon import xbmcplugin import xbmcvfs __addon_name__ = 'vanderwijk.iivvoo.kar' class Log(object): DEBUG = 0 INFO = 1 NOTICE = 2 WARNING = 3 ERROR = 4 SEVERE = 5 FATAL = 6 NONE = 7 def log(self, msg, level=NOTICE): xbmc.log(msg=msg, level=level) def debug(self, msg): self.log(msg, self.DEBUG) def info(self, msg): self.log(msg, self.INFO) def error(self, msg): self.log(msg, self.ERROR) DBURL = "http://pi.m3r.nl/db.sqlite" """ Download the database, store it locally, open it as file, use it to provide additional navigation and searching """ log = Log() # args contains the plugin id and an optional path / args. Urlparse it. log.info("KAR startup, args: {0}".format(" ".join(sys.argv))) import os, sys LIB_DIR = xbmc.translatePath( os.path.join( xbmcaddon.Addon(id=__addon_name__).getAddonInfo('path'), 'resources', 'lib' ) ) sys.path.append (LIB_DIR) DEBUG = xbmcaddon.Addon(id=__addon_name__).getSetting('debug') import easywebdav import requests import urlparse, urllib import sqlite3 class DB(object): def __init__(self, filename): log.info("Opening database {0}".format(filename)) self.filename = filename self._db = sqlite3.connect(self.filename) self._cursor = self._db.cursor() def execute(self, statement, *values): log.info("EXEC {0} {1}".format(statement, ",".join(values))) res = self._cursor.execute(statement, values) self._db.commit() return res class KVStore(DB): def __init__(self, filename): super(KVStore, self).__init__(filename) self.execute("""CREATE TABLE IF NOT EXISTS kvstore (key TEXT PRIMARY KEY, value BLOB)""") def put(self, key, value): self.execute("""INSERT OR REPLACE INTO kvstore (key, value) VALUES (?, ?)""", key, value) def get(self, key): res = self.execute("""SELECT key, value FROM kvstore WHERE key = ?""", key) if res is None: return None item = res.fetchone() if item is None: return None return item[1] class MediaDB(DB): def genres(self): """ fetch genres from the database """ def search(self, type, query="", genre=None, year=None): """ query media databases based on certain clauses """ if type == "movie": table = "movieinfo" else: table = "tvshowinfo" res = self.execute("""SELECT path, title FROM {0} WHERE lower(title) like ?""".format(table), '%{0}%'.format(query.strip().lower()) ) return res.fetchall() class RecentlyPlayed(object): LIMIT = 20 def __init__(self, kvstore): self.kvstore = kvstore def get(self): stored_raw = self.kvstore.get('recent') if stored_raw is None: return [] log.info("Stored recent found: {0}".format(stored_raw)) stored = json.loads(stored_raw) return stored def add(self, file): """ get folder, make it nice readable, add it to store """ current = self.get() or [] folder, file = file.rsplit('/', 1) newcurrent = [(folder, file)] for fol, fil in current[:self.LIMIT-1]: if fol != folder: newcurrent.append((fol, fil)) self.kvstore.put('recent', json.dumps(newcurrent)) class MediaFile(object): """ handle urls, translate it into components such as - filename - extension - parent folder - parent-parent folder .. etc Possible also provide de DAV interfacing, wrapping directories/ files directly in MediaFile (..Folder) object? """ class KarException(Exception): pass class SearchDialog(xbmcgui.WindowXMLDialog): """ Not used for now. Building dialogs for Kodi is a complicated, buggy and cumbersome task: - everything has to be specified: sizes, positions of all controls - background for the dialog - handling of events is primitive - .. and sometimes it simply wont work. You'll find that a certain setup cannot be made to work. as an alternative, a primitive folder-based navigation with Dialog.input is used in stead """ # http://kodi.wiki/view/WindowXML # http://kodi.wiki/view/HOW-TO:Add_a_new_window_or_dialog_via_skinning CONTROL_SEARCH_VIDEO = 26 CONTROL_SEARCH_SHOWS = 27 CONTROL_CANCEL = 28 CONTROL_GENRELIST = 12001 def onInit(self): self.s = xbmcgui.ControlList(0, 240, 1120, 160) self.s.setItemHeight(40) self.addControl(self.s) self.s.addItem("Hello World") self.s.addItem("Bye World") self.s.addItem("Kodi == crap") def onClick(self, control): log.info("onClick {0}".format(str(control))) if control == self.CONTROL_CANCEL: self.close() if control == self.CONTROL_SEARCH_VIDEO: self.close() if control == self.CONTROL_SEARCH_SHOWS: self.close() if control == self.CONTROL_GENRELIST: log.info("Genre selected {0}".format(str(self.s.getSelectedItem().getLabel()))) def xonAction(self, action): log.info("onAction {0} {1} {2}".format(action.getId(), action.getButtonCode(), action)) log.info(str(self.s.getSelectedItem().getLabel())) # ACTION_MOUSE_LEFT_CLICK if action.getId() == xbmcgui.ACTION_PREVIOUS_MENU: self.close() if action.getId() == xbmcgui.ACTION_PARENT_DIR: self.close() def onControl(self, control): log.info("onControl {0}".format(str(control))) class Kar(object): METADB_EXPIRE = 3600 def __init__(self, argv): try: self.args = dict(urlparse.parse_qsl(sys.argv[2].lstrip('?'))) except IndexError: self.args = {} self.plugin_url = argv[0] self.addon_handle = int(sys.argv[1]) self.addon = xbmcaddon.Addon() self.davhost = self.addon.getSetting('davhost') self.davport = int(self.addon.getSetting('davport')) log.info("Configured DAV URL " + self.davhost) log.info("Configured DAV port {0}".format(self.davport)) self.pluginid = self.addon.getAddonInfo('id') self.addonname = self.addon.getAddonInfo('name') self.dav = easywebdav.connect(self.davhost, port=self.davport) self.data_path = os.path.join(xbmc.translatePath("special://profile/addon_data/{0}".format(self.pluginid))) if not xbmcvfs.exists(self.data_path): xbmcvfs.mkdirs(self.data_path) self.store = KVStore(os.path.join(self.data_path, "kar_kvstore.sqlite")) self.recent = RecentlyPlayed(self.store) mediadb_path = self.clone_db() self.mediadb = MediaDB(mediadb_path) def clone_db(self): dbpath = os.path.join(self.data_path, "meta.db") st = xbmcvfs.Stat(dbpath) modified = st.st_mtime() log.info("AGE: {0}".format(modified - time.time())) if modified < time.time() - self.METADB_EXPIRE or st.st_size() < 1024 * 1024: r = requests.get(DBURL, stream=True) with open(dbpath, "wb") as metadb: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive chunks metadb.write(chunk) metadb.flush() log.info("Meta DB copied") return dbpath def debug(): """ invoke remote debugger """ import rpdb2 rpdb2.start_embedded_debugger('pw') def url(self, **kwargs): return self.plugin_url + "?" + urllib.urlencode(kwargs) # handle commands def run(self): if self.davhost == "example.org": dialog = xbmcgui.Dialog() dialog.ok("Please configure first", "Please configure the add-on first!", "You can do this through the context menu") return # need this? xbmcplugin.setContent(self.addon_handle, 'movies') command = self.args.get('command', 'main') log.info("COMMAND " + command + " - " + repr(self.args)) try: if hasattr(self, 'cmd_' + command): getattr(self, 'cmd_' + command)(self.args) else: self.cmd_main(self.args) except KarException as e: dialog = xbmcgui.Dialog() dialog.ok("Error occurred", str(e)) return def cmd_main(self, args): li = xbmcgui.ListItem('Browse Kar', iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="browse"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Search Kar', iconImage='icon_search.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="search"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Watchlist', iconImage='DefaultMusicPlaylists.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="watchlist"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Favorites', iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="favorites"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Recently Watched', iconImage='DefaultInProgressShows.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="recent"), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) def find_video_art(self, files, name): """ given a video 'foo.xxx', find video art 'foo.tbn' in files and return its url, or return default art """ artname = name.rsplit('.', 1)[0] + '.tbn' for f in files: filename = urlparse.urlparse(f.name.rsplit('/')[-1]).path if filename == artname: return f.name return 'DefaultVideo.png' def cmd_watchlist(self, args): pass def cmd_favorites(self, args): pass def cmd_search(self, args): # sd = SearchDialog("search-dialog.xml", self.addon.getAddonInfo('path'), 'default', '0') # sd.doModal() options = (dict(title="Shows by String", type="show", clause="str"), dict(title="Shows by Genre", type="show", clause="genre"), dict(title="Shows by year", type="show", clause="year"), dict(title="Movies by String", type="movie", clause="str"), dict(title="Movies by Genre", type="movie", clause="genre"), dict(title="Movies by year", type="movie", clause="year")) clause = args.get('clause') type = args.get('type') if type and clause: d = xbmcgui.Dialog() res = d.input("Enter search") log.info("You searched {0}".format(str(res))) matches = self.mediadb.search(type, res) # log.info("MATCH {0}".format(str(matches))) for match in matches: path = match[0] if path.startswith("/data/"): path = path[5:] ## XXX Reuse the browse art magic here li = xbmcgui.ListItem(match[1], iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="browse", path=path), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) else: for option in options: li = xbmcgui.ListItem(option['title'], iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="search", type=option['type'], clause=option['clause']), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) def cmd_browse(self, args): xbmcplugin.addSortMethod(self.addon_handle, xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE) xbmcplugin.addSortMethod(self.addon_handle, xbmcplugin.SORT_METHOD_FILE) path = args.get('path', '') log.info("Kar path " + path); try: files = self.dav.ls(path) except requests.ConnectionError as e: raise KarException(str(e)) # werkt niet # win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) # win.setProperty('title', 'Hello World') ## if there aren't too many seasons (S01, s01, season01, scan for a ## seasonXX.tbn file and use it as folder art for f in files: # [:5]: # XXX restrict, for now url = f.name # only use the last path part, no slashes name = urlparse.urlparse(url).path.rsplit('/')[-1] ext = name.rsplit('.')[-1] readable_name = urllib.unquote(name) if name.startswith("."): continue if not name: continue # skip / isfolder = False if f.contenttype == "httpd/unix-directory": isfolder = True command = "browse" fanart_path = path + '/' + name + '/' + 'fanart.jpg' folderart_path = path + '/' + name + '/' + 'folder.jpg' fanart_url = "http://{0}:{1}{2}".format(self.davhost, self.davport, fanart_path) folderart_url = "http://{0}:{1}{2}".format(self.davhost, self.davport, folderart_path) li = xbmcgui.ListItem(readable_name, iconImage='DefaultFolder.png') li.setInfo("video", {"title": readable_name}) ## This overrides the iconImage in ListItem. If it's not present, ## it means no iamge at all li.setArt({'thumb': folderart_url, 'fanart': fanart_url}) elif ext not in ('mp4', 'avi', 'mkv'): continue else: command = "play" li = xbmcgui.ListItem(readable_name, iconImage='DefaultVideo.png') li.setInfo("video", { "title": readable_name, "size": f.size}) # scan in the furrent 'files' for a .tbn equiv. If it's # there, use it as art art = self.find_video_art(files, name) # fanart could be series fanart in parent folder li.setArt({'thumb': art, 'fanart': art}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command=command, path=path + '/' + name), listitem=li, isFolder=isfolder) xbmcplugin.endOfDirectory(self.addon_handle) def cmd_play(self, args): # xbmcgui.Dialog().ok(self.addonname, "PLAY", args.get('path', '?'), "?") player = xbmc.Player() path = args.get('path', '') url = 'http://{0}:{1}{2}'.format(self.davhost, self.davport, urllib.quote(path)) log.info("PLAY " + url) name = urlparse.urlparse(url).path.rsplit('/')[-1] readable_name = urllib.unquote(name) li = xbmcgui.ListItem(readable_name, iconImage='DefaultVideo.png') li.setInfo("video", { "Title": readable_name }) self.recent.add(path) player.play(url, li) def cmd_recent(self, args): xbmcplugin.addSortMethod(self.addon_handle, xbmcplugin.SORT_METHOD_UNSORTED) recent = self.recent.get() for folder, file in recent: ## reuse stuff in browse! log.info("RECENT {0}".format(folder)) readable_folder = urllib.unquote(folder) readable_file = urllib.unquote(file) readable_folder = " - ".join(readable_folder.lstrip('/').split("/")) entry = "{0} -> {1}".format(readable_folder, readable_file) li = xbmcgui.ListItem(entry, iconImage='DefaultFolder.png') li.setInfo("video", {"title": entry}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="browse", path=folder), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) k = Kar(sys.argv) k.run()
import time import json import sys import xbmc import xbmcgui import xbmcaddon import xbmcplugin import xbmcvfs __addon_name__ = 'vanderwijk.iivvoo.kar' class Log(object): DEBUG = 0 INFO = 1 NOTICE = 2 WARNING = 3 ERROR = 4 SEVERE = 5 FATAL = 6 NONE = 7 def log(self, msg, level=NOTICE): xbmc.log(msg=msg, level=level) def debug(self, msg): self.log(msg, self.DEBUG) def info(self, msg): self.log(msg, self.INFO) def error(self, msg): self.log(msg, self.ERROR) DBURL = "http://pi.m3r.nl/db.sqlite" """ Download the database, store it locally, open it as file, use it to provide additional navigation and searching """ log = Log() # args contains the plugin id and an optional path / args. Urlparse it. log.info("KAR startup, args: {0}".format(" ".join(sys.argv))) import os, sys LIB_DIR = xbmc.translatePath( os.path.join( xbmcaddon.Addon(id=__addon_name__).getAddonInfo('path'), 'resources', 'lib' ) ) sys.path.append (LIB_DIR) DEBUG = xbmcaddon.Addon(id=__addon_name__).getSetting('debug') import easywebdav import requests import urlparse, urllib import sqlite3 class DB(object): def __init__(self, filename): log.info("Opening database {0}".format(filename)) self.filename = filename self._db = sqlite3.connect(self.filename) self._cursor = self._db.cursor() def execute(self, statement, *values): log.info("EXEC {0} {1}".format(statement, ",".join(values))) res = self._cursor.execute(statement, values) self._db.commit() return res class KVStore(DB): def __init__(self, filename): super(KVStore, self).__init__(filename) self.execute("""CREATE TABLE IF NOT EXISTS kvstore (key TEXT PRIMARY KEY, value BLOB)""") def put(self, key, value): self.execute("""INSERT OR REPLACE INTO kvstore (key, value) VALUES (?, ?)""", key, value) def get(self, key): res = self.execute("""SELECT key, value FROM kvstore WHERE key = ?""", key) if res is None: return None item = res.fetchone() if item is None: return None return item[1] class MediaDB(DB): def genres(self): """ fetch genres from the database """ def search(self, type, query="", genre=None, year=None): """ query media databases based on certain clauses """ if type == "movie": table = "movieinfo" else: table = "tvshowinfo" res = self.execute("""SELECT path, title FROM {0} WHERE lower(title) like ?""".format(table), '%{0}%'.format(query.strip().lower()) ) return res.fetchall() class RecentlyPlayed(object): LIMIT = 20 def __init__(self, kvstore): self.kvstore = kvstore def get(self): stored_raw = self.kvstore.get('recent') if stored_raw is None: return [] log.info("Stored recent found: {0}".format(stored_raw)) stored = json.loads(stored_raw) return stored def add(self, file): """ get folder, make it nice readable, add it to store """ current = self.get() or [] folder, file = file.rsplit('/', 1) newcurrent = [(folder, file)] for fol, fil in current[:self.LIMIT-1]: if fol != folder: newcurrent.append((fol, fil)) self.kvstore.put('recent', json.dumps(newcurrent)) class MediaFile(object): """ handle urls, translate it into components such as - filename - extension - parent folder - parent-parent folder .. etc Possible also provide de DAV interfacing, wrapping directories/ files directly in MediaFile (..Folder) object? """ class KarException(Exception): pass class SearchDialog(xbmcgui.WindowXMLDialog): """ Not used for now. Building dialogs for Kodi is a complicated, buggy and cumbersome task: - everything has to be specified: sizes, positions of all controls - background for the dialog - handling of events is primitive - .. and sometimes it simply wont work. You'll find that a certain setup cannot be made to work. as an alternative, a primitive folder-based navigation with Dialog.input is used in stead """ # http://kodi.wiki/view/WindowXML # http://kodi.wiki/view/HOW-TO:Add_a_new_window_or_dialog_via_skinning CONTROL_SEARCH_VIDEO = 26 CONTROL_SEARCH_SHOWS = 27 CONTROL_CANCEL = 28 CONTROL_GENRELIST = 12001 def onInit(self): self.s = xbmcgui.ControlList(0, 240, 1120, 160) self.s.setItemHeight(40) self.addControl(self.s) self.s.addItem("Hello World") self.s.addItem("Bye World") self.s.addItem("Kodi == crap") def onClick(self, control): log.info("onClick {0}".format(str(control))) if control == self.CONTROL_CANCEL: self.close() if control == self.CONTROL_SEARCH_VIDEO: self.close() if control == self.CONTROL_SEARCH_SHOWS: self.close() if control == self.CONTROL_GENRELIST: log.info("Genre selected {0}".format(str(self.s.getSelectedItem().getLabel()))) def xonAction(self, action): log.info("onAction {0} {1} {2}".format(action.getId(), action.getButtonCode(), action)) log.info(str(self.s.getSelectedItem().getLabel())) # ACTION_MOUSE_LEFT_CLICK if action.getId() == xbmcgui.ACTION_PREVIOUS_MENU: self.close() if action.getId() == xbmcgui.ACTION_PARENT_DIR: self.close() def onControl(self, control): log.info("onControl {0}".format(str(control))) class Kar(object): METADB_EXPIRE = 3600 def __init__(self, argv): try: self.args = dict(urlparse.parse_qsl(sys.argv[2].lstrip('?'))) except IndexError: self.args = {} self.plugin_url = argv[0] self.addon_handle = int(sys.argv[1]) self.addon = xbmcaddon.Addon() self.davhost = self.addon.getSetting('davhost') self.davport = int(self.addon.getSetting('davport')) log.info("Configured DAV URL " + self.davhost) log.info("Configured DAV port {0}".format(self.davport)) self.pluginid = self.addon.getAddonInfo('id') self.addonname = self.addon.getAddonInfo('name') self.dav = easywebdav.connect(self.davhost, port=self.davport) self.data_path = os.path.join(xbmc.translatePath("special://profile/addon_data/{0}".format(self.pluginid))) if not xbmcvfs.exists(self.data_path): xbmcvfs.mkdirs(self.data_path) self.store = KVStore(os.path.join(self.data_path, "kar_kvstore.sqlite")) self.recent = RecentlyPlayed(self.store) mediadb_path = self.clone_db() self.mediadb = MediaDB(mediadb_path) def clone_db(self): dbpath = os.path.join(self.data_path, "meta.db") st = xbmcvfs.Stat(dbpath) modified = st.st_mtime() log.info("AGE: {0}".format(modified - time.time())) if modified < time.time() - self.METADB_EXPIRE or st.st_size() < 1024 * 1024: r = requests.get(DBURL, stream=True) with open(dbpath, "wb") as metadb: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive chunks metadb.write(chunk) metadb.flush() log.info("Meta DB copied") return dbpath def debug(): """ invoke remote debugger """ import rpdb2 rpdb2.start_embedded_debugger('pw') def url(self, **kwargs): return self.plugin_url + "?" + urllib.urlencode(kwargs) # handle commands def run(self): if self.davhost == "example.org": dialog = xbmcgui.Dialog() dialog.ok("Please configure first", "Please configure the add-on first!", "You can do this through the context menu") return # need this? xbmcplugin.setContent(self.addon_handle, 'movies') command = self.args.get('command', 'main') log.info("COMMAND " + command + " - " + repr(self.args)) try: if hasattr(self, 'cmd_' + command): getattr(self, 'cmd_' + command)(self.args) else: self.cmd_main(self.args) except KarException as e: dialog = xbmcgui.Dialog() dialog.ok("Error occurred", str(e)) return def cmd_main(self, args): li = xbmcgui.ListItem('Browse Kar', iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="browse"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Search Kar', iconImage='icon_search.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="search"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Watchlist', iconImage='DefaultMusicPlaylists.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="watchlist"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Favorites', iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="favorites"), listitem=li, isFolder=True) li = xbmcgui.ListItem('Recently Watched', iconImage='DefaultInProgressShows.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="recent"), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) def find_video_art(self, files, name): """ given a video 'foo.xxx', find video art 'foo.tbn' in files and return its url, or return default art """ artname = name.rsplit('.', 1)[0] + '.tbn' for f in files: filename = urlparse.urlparse(f.name.rsplit('/')[-1]).path if filename == artname: return f.name return 'DefaultVideo.png' def cmd_watchlist(self, args): pass def cmd_favorites(self, args): pass def cmd_search(self, args): # sd = SearchDialog("search-dialog.xml", self.addon.getAddonInfo('path'), 'default', '0') # sd.doModal() options = (dict(title="Shows by String", type="show", clause="str"), dict(title="Shows by Genre", type="show", clause="genre"), dict(title="Shows by year", type="show", clause="year"), dict(title="Movies by String", type="movie", clause="str"), dict(title="Movies by Genre", type="movie", clause="genre"), dict(title="Movies by year", type="movie", clause="year")) clause = args.get('clause') type = args.get('type') if type and clause: d = xbmcgui.Dialog() res = d.input("Enter search") log.info("You searched {0}".format(str(res))) matches = self.mediadb.search(type, res) # log.info("MATCH {0}".format(str(matches))) for match in matches: path = match[0] if path.startswith("/data/"): path = path[5:] ## XXX Reuse the browse art magic here li = xbmcgui.ListItem(match[1], iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="browse", path=path), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) else: for option in options: li = xbmcgui.ListItem(option['title'], iconImage='DefaultVideo.png') xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="search", type=option['type'], clause=option['clause']), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) def cmd_browse(self, args): xbmcplugin.addSortMethod(self.addon_handle, xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE) xbmcplugin.addSortMethod(self.addon_handle, xbmcplugin.SORT_METHOD_FILE) path = args.get('path', '') log.info("Kar path " + path); try: files = self.dav.ls(path) except requests.ConnectionError as e: raise KarException(str(e)) # werkt niet # win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) # win.setProperty('title', 'Hello World') ## if there aren't too many seasons (S01, s01, season01, scan for a ## seasonXX.tbn file and use it as folder art for f in files: # [:5]: # XXX restrict, for now url = f.name # only use the last path part, no slashes name = urlparse.urlparse(url).path.rsplit('/')[-1] ext = name.rsplit('.')[-1] readable_name = urllib.unquote(name) if name.startswith("."): continue if not name: continue # skip / isfolder = False if f.contenttype == "httpd/unix-directory": isfolder = True command = "browse" fanart_path = path + '/' + name + '/' + 'fanart.jpg' folderart_path = path + '/' + name + '/' + 'folder.jpg' fanart_url = "http://{0}:{1}{2}".format(self.davhost, self.davport, fanart_path) folderart_url = "http://{0}:{1}{2}".format(self.davhost, self.davport, folderart_path) li = xbmcgui.ListItem(readable_name, iconImage='DefaultFolder.png') li.setInfo("video", {"title": readable_name}) ## This overrides the iconImage in ListItem. If it's not present, ## it means no iamge at all li.setArt({'thumb': folderart_url, 'fanart': fanart_url}) elif ext not in ('mp4', 'avi', 'mkv'): continue else: command = "play" li = xbmcgui.ListItem(readable_name, iconImage='DefaultVideo.png') li.setInfo("video", { "title": readable_name, "size": f.size}) # scan in the furrent 'files' for a .tbn equiv. If it's # there, use it as art art = self.find_video_art(files, name) # fanart could be series fanart in parent folder li.setArt({'thumb': art, 'fanart': art}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command=command, path=path + '/' + name), listitem=li, isFolder=isfolder) xbmcplugin.endOfDirectory(self.addon_handle) def cmd_play(self, args): # xbmcgui.Dialog().ok(self.addonname, "PLAY", args.get('path', '?'), "?") player = xbmc.Player() path = args.get('path', '') url = 'http://{0}:{1}{2}'.format(self.davhost, self.davport, urllib.quote(path)) log.info("PLAY " + url) name = urlparse.urlparse(url).path.rsplit('/')[-1] readable_name = urllib.unquote(name) li = xbmcgui.ListItem(readable_name, iconImage='DefaultVideo.png') li.setInfo("video", { "Title": readable_name }) self.recent.add(path) player.play(url, li) def cmd_recent(self, args): xbmcplugin.addSortMethod(self.addon_handle, xbmcplugin.SORT_METHOD_UNSORTED) recent = self.recent.get() for folder, file in recent: ## reuse stuff in browse! log.info("RECENT {0}".format(folder)) readable_folder = urllib.unquote(folder) readable_file = urllib.unquote(file) readable_folder = " - ".join(readable_folder.lstrip('/').split("/")) entry = "{0} -> {1}".format(readable_folder, readable_file) li = xbmcgui.ListItem(entry, iconImage='DefaultFolder.png') li.setInfo("video", {"title": entry}) xbmcplugin.addDirectoryItem(handle=self.addon_handle, url=self.url(command="browse", path=folder), listitem=li, isFolder=True) xbmcplugin.endOfDirectory(self.addon_handle) k = Kar(sys.argv) k.run()
en
0.729725
Download the database, store it locally, open it as file, use it to provide additional navigation and searching # args contains the plugin id and an optional path / args. Urlparse it. CREATE TABLE IF NOT EXISTS kvstore (key TEXT PRIMARY KEY, value BLOB) INSERT OR REPLACE INTO kvstore (key, value) VALUES (?, ?) SELECT key, value FROM kvstore WHERE key = ? fetch genres from the database query media databases based on certain clauses SELECT path, title FROM {0} WHERE lower(title) like ? get folder, make it nice readable, add it to store handle urls, translate it into components such as - filename - extension - parent folder - parent-parent folder .. etc Possible also provide de DAV interfacing, wrapping directories/ files directly in MediaFile (..Folder) object? Not used for now. Building dialogs for Kodi is a complicated, buggy and cumbersome task: - everything has to be specified: sizes, positions of all controls - background for the dialog - handling of events is primitive - .. and sometimes it simply wont work. You'll find that a certain setup cannot be made to work. as an alternative, a primitive folder-based navigation with Dialog.input is used in stead # http://kodi.wiki/view/WindowXML # http://kodi.wiki/view/HOW-TO:Add_a_new_window_or_dialog_via_skinning # ACTION_MOUSE_LEFT_CLICK # filter out keep-alive chunks invoke remote debugger # handle commands # need this? given a video 'foo.xxx', find video art 'foo.tbn' in files and return its url, or return default art # sd = SearchDialog("search-dialog.xml", self.addon.getAddonInfo('path'), 'default', '0') # sd.doModal() # log.info("MATCH {0}".format(str(matches))) ## XXX Reuse the browse art magic here # werkt niet # win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) # win.setProperty('title', 'Hello World') ## if there aren't too many seasons (S01, s01, season01, scan for a ## seasonXX.tbn file and use it as folder art # [:5]: # XXX restrict, for now # only use the last path part, no slashes # skip / ## This overrides the iconImage in ListItem. If it's not present, ## it means no iamge at all # scan in the furrent 'files' for a .tbn equiv. If it's # there, use it as art # fanart could be series fanart in parent folder # xbmcgui.Dialog().ok(self.addonname, "PLAY", args.get('path', '?'), "?") ## reuse stuff in browse!
2.323498
2
libtrack/elfmod/vstruct/defs/dns.py
columbia/libtrack
40
6614294
<gh_stars>10-100 import vstruct from vstruct.primitives import * DNS_FLAG_RESPONSE = 0x8000 DNS_FLAG_AUTHORITATIVE = 0x0400 DNS_TYPE_A = 1 DNS_TYPE_CNAME = 5 DNS_CLASS_IN = 1 class DnsNamePart(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.length = v_uint8() self.namepart = v_str() def pcb_length(self): size = self.length if size == 0xc0: size = 1 # FIXME offsets for name... self.vsGetField('namepart').vsSetLength(size) def isNameTerm(self): if self.length == 0: return True if self.length == 0xc0: return True return False class DnsName(vstruct.VArray): def __init__(self): vstruct.VStruct.__init__(self) def getFullName(self, dnspkt): r = [] for fname,fobj in self.vsGetFields(): if fobj.length == 0xc0: newn = DnsName() # FIXME redundant parsing... newn.vsParse(dnspkt, ord(fobj.namepart)) r.append( newn.getFullName(dnspkt) ) else: r.append(fobj.namepart) return '.'.join(r) def vsParse(self, bytes, offset=0): self.vsClearFields() while offset < len(bytes): np = DnsNamePart() offset = np.vsParse(bytes, offset=offset) self.vsAddElement(np) if np.isNameTerm(): break return offset class DnsQuery(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.qname = DnsName() self.qtype = v_uint16(bigend=True) self.qclass = v_uint16(bigend=True) class DnsQueryArray(vstruct.VArray): def __init__(self, reccnt): vstruct.VArray.__init__(self) for i in xrange(reccnt): self.vsAddElement( DnsQuery() ) class DnsAnswer(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.qname = DnsName() self.qtype = v_uint16(bigend=True) self.qclass = v_uint16(bigend=True) self.qttl = v_uint32(bigend=True) self.dlength = v_uint16(bigend=True) self.qdata = v_bytes() def pcb_dlength(self): size = self.dlength self.vsGetField('qdata').vsSetLength(size) class DnsAnswerArray(vstruct.VArray): def __init__(self, reccnt): vstruct.VArray.__init__(self) for i in xrange(reccnt): self.vsAddElement( DnsAnswer() ) class DnsPacket(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) #self.length = v_uint16(bigend=True) self.transid = v_uint16(bigend=True) self.flags = v_uint16(bigend=True) self.ques_cnt = v_uint16(bigend=True) self.answ_cnt = v_uint16(bigend=True) self.auth_cnt = v_uint16(bigend=True) self.addt_cnt = v_uint16(bigend=True) self.records = vstruct.VStruct() self.records.queries = DnsQueryArray(0) self.records.answers = DnsAnswerArray(0) self.records.authns = DnsAnswerArray(0) self.records.addtl = DnsAnswerArray(0) def pcb_ques_cnt(self): self.records.queries = DnsQueryArray( self.ques_cnt ) def pcb_answ_cnt(self): self.records.answers = DnsAnswerArray( self.answ_cnt ) def pcb_auth_cnt(self): self.records.authns = DnsAnswerArray( self.auth_cnt ) def pcb_addt_cnt(self): self.records.addtl = DnsAnswerArray( self.addt_cnt )
import vstruct from vstruct.primitives import * DNS_FLAG_RESPONSE = 0x8000 DNS_FLAG_AUTHORITATIVE = 0x0400 DNS_TYPE_A = 1 DNS_TYPE_CNAME = 5 DNS_CLASS_IN = 1 class DnsNamePart(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.length = v_uint8() self.namepart = v_str() def pcb_length(self): size = self.length if size == 0xc0: size = 1 # FIXME offsets for name... self.vsGetField('namepart').vsSetLength(size) def isNameTerm(self): if self.length == 0: return True if self.length == 0xc0: return True return False class DnsName(vstruct.VArray): def __init__(self): vstruct.VStruct.__init__(self) def getFullName(self, dnspkt): r = [] for fname,fobj in self.vsGetFields(): if fobj.length == 0xc0: newn = DnsName() # FIXME redundant parsing... newn.vsParse(dnspkt, ord(fobj.namepart)) r.append( newn.getFullName(dnspkt) ) else: r.append(fobj.namepart) return '.'.join(r) def vsParse(self, bytes, offset=0): self.vsClearFields() while offset < len(bytes): np = DnsNamePart() offset = np.vsParse(bytes, offset=offset) self.vsAddElement(np) if np.isNameTerm(): break return offset class DnsQuery(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.qname = DnsName() self.qtype = v_uint16(bigend=True) self.qclass = v_uint16(bigend=True) class DnsQueryArray(vstruct.VArray): def __init__(self, reccnt): vstruct.VArray.__init__(self) for i in xrange(reccnt): self.vsAddElement( DnsQuery() ) class DnsAnswer(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.qname = DnsName() self.qtype = v_uint16(bigend=True) self.qclass = v_uint16(bigend=True) self.qttl = v_uint32(bigend=True) self.dlength = v_uint16(bigend=True) self.qdata = v_bytes() def pcb_dlength(self): size = self.dlength self.vsGetField('qdata').vsSetLength(size) class DnsAnswerArray(vstruct.VArray): def __init__(self, reccnt): vstruct.VArray.__init__(self) for i in xrange(reccnt): self.vsAddElement( DnsAnswer() ) class DnsPacket(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) #self.length = v_uint16(bigend=True) self.transid = v_uint16(bigend=True) self.flags = v_uint16(bigend=True) self.ques_cnt = v_uint16(bigend=True) self.answ_cnt = v_uint16(bigend=True) self.auth_cnt = v_uint16(bigend=True) self.addt_cnt = v_uint16(bigend=True) self.records = vstruct.VStruct() self.records.queries = DnsQueryArray(0) self.records.answers = DnsAnswerArray(0) self.records.authns = DnsAnswerArray(0) self.records.addtl = DnsAnswerArray(0) def pcb_ques_cnt(self): self.records.queries = DnsQueryArray( self.ques_cnt ) def pcb_answ_cnt(self): self.records.answers = DnsAnswerArray( self.answ_cnt ) def pcb_auth_cnt(self): self.records.authns = DnsAnswerArray( self.auth_cnt ) def pcb_addt_cnt(self): self.records.addtl = DnsAnswerArray( self.addt_cnt )
en
0.496131
# FIXME offsets for name... # FIXME redundant parsing... #self.length = v_uint16(bigend=True)
2.232058
2
venv/Lib/site-packages/nipype/interfaces/semtools/brains/__init__.py
richung99/digitizePlots
585
6614295
<gh_stars>100-1000 # -*- coding: utf-8 -*- from .segmentation import SimilarityIndex, BRAINSTalairach, BRAINSTalairachMask from .utilities import ( HistogramMatchingFilter, GenerateEdgeMapImage, GeneratePurePlugMask, ) from .classify import BRAINSPosteriorToContinuousClass
# -*- coding: utf-8 -*- from .segmentation import SimilarityIndex, BRAINSTalairach, BRAINSTalairachMask from .utilities import ( HistogramMatchingFilter, GenerateEdgeMapImage, GeneratePurePlugMask, ) from .classify import BRAINSPosteriorToContinuousClass
en
0.769321
# -*- coding: utf-8 -*-
1.214938
1
Python3/216.combination-sum-iii.py
610yilingliu/leetcode
0
6614296
<gh_stars>0 # # @lc app=leetcode id=216 lang=python3 # # [216] Combination Sum III # # @lc code=start class Solution: def combinationSum3(self, k, n): if k == 0 or n == 0: return [] self.ans = [] self.k = k self.back(n, 0, []) return self.ans def back(self, rest, count, path): if rest == 0 and count == self.k: self.ans.append(path) if rest > (self.k - count) * 9: return if rest < self.k - count: return if rest < 0: return for i in range(1, 10): if not path or (path and i > path[-1]): self.back(rest - i, count + 1, path + [i]) if __name__ == '__main__': a = Solution() b = a.combinationSum3(3, 7) print(b) # @lc code=end
# # @lc app=leetcode id=216 lang=python3 # # [216] Combination Sum III # # @lc code=start class Solution: def combinationSum3(self, k, n): if k == 0 or n == 0: return [] self.ans = [] self.k = k self.back(n, 0, []) return self.ans def back(self, rest, count, path): if rest == 0 and count == self.k: self.ans.append(path) if rest > (self.k - count) * 9: return if rest < self.k - count: return if rest < 0: return for i in range(1, 10): if not path or (path and i > path[-1]): self.back(rest - i, count + 1, path + [i]) if __name__ == '__main__': a = Solution() b = a.combinationSum3(3, 7) print(b) # @lc code=end
en
0.361279
# # @lc app=leetcode id=216 lang=python3 # # [216] Combination Sum III # # @lc code=start # @lc code=end
3.201464
3
cudos-explorer-sync-to-node/checks.py
CudoVentures/cudos-infrastructure-monitoring
0
6614297
import datetime import settings import err import query import re node_stats = [] recorded_errors = {} def healthy(node_height: int) -> bool: global node_stats node_stats.append(node_height) if len(node_stats) == settings.SELF_CHECK_INTERVAL: try: average = abs((sum(node_stats) / len(node_stats)) - node_height) if average <= settings.MIN_AVERAGE: return False finally: node_stats = [] return True def check_sync() -> list: errors = [] global recorded_errors # NODE address = settings.NODE_API + settings.END_POINT_FOR_LAST_BLOCK node_msg = "" try: node_ip = re.search(r"\b([\d]{1,3}\.){3}[\d]{1,3}\b", address).group() instance = f'<{settings.GCLOUD_SEARCH + node_ip}|GCLOUD>' except AttributeError: instance = settings.NODE_API node_height, error = query.height(address) if not node_height: node_msg = f"{err.getting_height} node deployed @ {instance} @ {datetime.datetime.now()} {error}" if not healthy(node_height): node_msg = f"Node deployed @ {instance} might be stuck on block {node_height} @ {datetime.datetime.now()}" if not node_msg: # Checking height of the two explorers only if node is OK for i in range(1, 3): explorer_name = f"V{i} Explorer" explorer_msg = "" address = settings.EXPLORER_V1_HOST if i == 1 \ else settings.EXPLORER_V2_HOST explorer_height, error = query.height(address + settings.HEALTHCHECK_ENDPOINT) if not explorer_height: explorer_msg = f"{err.getting_height} {explorer_name} @ {datetime.datetime.now()} with error {error}" elif abs(explorer_height - node_height) >= settings.MAX_SYNC_TOLERANCE: explorer_msg = f"{explorer_name} {err.stuck_behind} {abs(explorer_height - node_height)} " \ f"blocks @ {datetime.datetime.now()}" if explorer_msg: errors.append(explorer_msg) recorded_errors[explorer_name] = explorer_msg else: errors.append(node_msg) recorded_errors[address] = node_msg return errors def msg_type(msg: str) -> dict: status_starting_message = { "username": "Sync info", "icon_emoji": ":large_green_circle:", "attachments": [ { "color": "#32D132", "fields": [ { "value": f"Monitoring started!\n" f" - Alive Status & Reminders:\n" f" every {settings.REMINDER} hours\n" f" - Allowed Block Delay:\n" f" {settings.MAX_SYNC_TOLERANCE} blocks per {settings.SCHEDULE_TIME} minutes\n" f" - Node Health Check:\n" f" minimum" f" {int(settings.MIN_AVERAGE) * int(settings.SELF_CHECK_INTERVAL)} blocks per" f" {int(settings.SELF_CHECK_INTERVAL) * int(settings.SCHEDULE_TIME)} minutes", "short": "false", } ] } ] } status_ok_message = { "username": "Sync info", "icon_emoji": ":large_green_circle:", "attachments": [ { "color": "#32D132", "fields": [ { "value": "All synced", "short": "false", } ] } ] } status_resume_message = { "username": "Sync info", "icon_emoji": ":large_green_circle:", "attachments": [ { "color": "#32D132", "fields": [ { "value": "Back ONLINE", "short": "false", } ] } ] } status_silent_message = { "username": "Sync info", "icon_emoji": ":large_orange_circle:", "attachments": [ { "color": "#D1C432", "fields": [ { "value": "Entering silent mode", "short": "false", } ] } ] } status_remind_message = { "username": "Sync reminder", "icon_emoji": ":exclamation:", "attachments": [ { "fields": [ { "value": "Unresolved error", "short": "true", } ] } ] } if msg == "Status - OK": return status_ok_message elif msg == "Status - RESUME": return status_resume_message elif msg == "Status - SILENT": return status_silent_message elif msg == "Status - REMIND": return status_remind_message elif msg == "Start monitoring": return status_starting_message return { "username": "Sync alert", "icon_emoji": ":red_circle:", "attachments": [ { "color": "#FF0000", "fields": [ { "value": msg, "short": "false", } ] } ] }
import datetime import settings import err import query import re node_stats = [] recorded_errors = {} def healthy(node_height: int) -> bool: global node_stats node_stats.append(node_height) if len(node_stats) == settings.SELF_CHECK_INTERVAL: try: average = abs((sum(node_stats) / len(node_stats)) - node_height) if average <= settings.MIN_AVERAGE: return False finally: node_stats = [] return True def check_sync() -> list: errors = [] global recorded_errors # NODE address = settings.NODE_API + settings.END_POINT_FOR_LAST_BLOCK node_msg = "" try: node_ip = re.search(r"\b([\d]{1,3}\.){3}[\d]{1,3}\b", address).group() instance = f'<{settings.GCLOUD_SEARCH + node_ip}|GCLOUD>' except AttributeError: instance = settings.NODE_API node_height, error = query.height(address) if not node_height: node_msg = f"{err.getting_height} node deployed @ {instance} @ {datetime.datetime.now()} {error}" if not healthy(node_height): node_msg = f"Node deployed @ {instance} might be stuck on block {node_height} @ {datetime.datetime.now()}" if not node_msg: # Checking height of the two explorers only if node is OK for i in range(1, 3): explorer_name = f"V{i} Explorer" explorer_msg = "" address = settings.EXPLORER_V1_HOST if i == 1 \ else settings.EXPLORER_V2_HOST explorer_height, error = query.height(address + settings.HEALTHCHECK_ENDPOINT) if not explorer_height: explorer_msg = f"{err.getting_height} {explorer_name} @ {datetime.datetime.now()} with error {error}" elif abs(explorer_height - node_height) >= settings.MAX_SYNC_TOLERANCE: explorer_msg = f"{explorer_name} {err.stuck_behind} {abs(explorer_height - node_height)} " \ f"blocks @ {datetime.datetime.now()}" if explorer_msg: errors.append(explorer_msg) recorded_errors[explorer_name] = explorer_msg else: errors.append(node_msg) recorded_errors[address] = node_msg return errors def msg_type(msg: str) -> dict: status_starting_message = { "username": "Sync info", "icon_emoji": ":large_green_circle:", "attachments": [ { "color": "#32D132", "fields": [ { "value": f"Monitoring started!\n" f" - Alive Status & Reminders:\n" f" every {settings.REMINDER} hours\n" f" - Allowed Block Delay:\n" f" {settings.MAX_SYNC_TOLERANCE} blocks per {settings.SCHEDULE_TIME} minutes\n" f" - Node Health Check:\n" f" minimum" f" {int(settings.MIN_AVERAGE) * int(settings.SELF_CHECK_INTERVAL)} blocks per" f" {int(settings.SELF_CHECK_INTERVAL) * int(settings.SCHEDULE_TIME)} minutes", "short": "false", } ] } ] } status_ok_message = { "username": "Sync info", "icon_emoji": ":large_green_circle:", "attachments": [ { "color": "#32D132", "fields": [ { "value": "All synced", "short": "false", } ] } ] } status_resume_message = { "username": "Sync info", "icon_emoji": ":large_green_circle:", "attachments": [ { "color": "#32D132", "fields": [ { "value": "Back ONLINE", "short": "false", } ] } ] } status_silent_message = { "username": "Sync info", "icon_emoji": ":large_orange_circle:", "attachments": [ { "color": "#D1C432", "fields": [ { "value": "Entering silent mode", "short": "false", } ] } ] } status_remind_message = { "username": "Sync reminder", "icon_emoji": ":exclamation:", "attachments": [ { "fields": [ { "value": "Unresolved error", "short": "true", } ] } ] } if msg == "Status - OK": return status_ok_message elif msg == "Status - RESUME": return status_resume_message elif msg == "Status - SILENT": return status_silent_message elif msg == "Status - REMIND": return status_remind_message elif msg == "Start monitoring": return status_starting_message return { "username": "Sync alert", "icon_emoji": ":red_circle:", "attachments": [ { "color": "#FF0000", "fields": [ { "value": msg, "short": "false", } ] } ] }
en
0.809825
# NODE # Checking height of the two explorers only if node is OK
2.528068
3
tests/databases/ensembl/utils.py
RNAcentral/rnacentral-import-pipeline
1
6614298
<filename>tests/databases/ensembl/utils.py """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest as ut from Bio import SeqIO from databases.ensembl import data from databases.ensembl.helpers import bio as helpers class Base(ut.TestCase): # pylint: disable=R0904 filename = None importer_class = None @classmethod def setUpClass(cls): cls.features = {} if not cls.filename: return for feature in cls.record.features: key = None if helpers.is_gene(feature): key = helpers.gene(feature) elif helpers.is_ncrna(feature): key = helpers.transcript(feature) or helpers.standard_name(feature) if not key: continue cls.features[key] = feature def setUp(self): self.importer = None if self.importer_class and self.filename: self.importer = self.importer_class("data/rfam/families.tsv") def data(self): with open(self.filename, "rb") as raw: for entry in self.importer.data(raw): yield entry def entries_for(self, feature_key): feature = self.features[feature_key] summary = self.summary_of(helpers.gene(feature)) entries = self.importer.rnacentral_entries(self.record, summary, feature) return list(entries) def entry_for(self, feature_key): entries = self.entries_for(feature_key) assert len(entries) == 1 return entries[0]
<filename>tests/databases/ensembl/utils.py """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest as ut from Bio import SeqIO from databases.ensembl import data from databases.ensembl.helpers import bio as helpers class Base(ut.TestCase): # pylint: disable=R0904 filename = None importer_class = None @classmethod def setUpClass(cls): cls.features = {} if not cls.filename: return for feature in cls.record.features: key = None if helpers.is_gene(feature): key = helpers.gene(feature) elif helpers.is_ncrna(feature): key = helpers.transcript(feature) or helpers.standard_name(feature) if not key: continue cls.features[key] = feature def setUp(self): self.importer = None if self.importer_class and self.filename: self.importer = self.importer_class("data/rfam/families.tsv") def data(self): with open(self.filename, "rb") as raw: for entry in self.importer.data(raw): yield entry def entries_for(self, feature_key): feature = self.features[feature_key] summary = self.summary_of(helpers.gene(feature)) entries = self.importer.rnacentral_entries(self.record, summary, feature) return list(entries) def entry_for(self, feature_key): entries = self.entries_for(feature_key) assert len(entries) == 1 return entries[0]
en
0.827854
Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # pylint: disable=R0904
2.041537
2
research/recommend/Fat-DeepFFM/eval.py
leelige/mindspore
77
6614299
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =========================================================================== """ eval model""" import argparse import os from src.config import ModelConfig from src.dataset import get_mindrecord_dataset from src.fat_deepffm import ModelBuilder from src.metrics import AUCMetric from mindspore import context, Model from mindspore.common import set_seed from mindspore.train.serialization import load_checkpoint, load_param_into_net parser = argparse.ArgumentParser(description='CTR Prediction') parser.add_argument('--dataset_path', type=str, default="/data/FM/mindrecord", help='Dataset path') parser.add_argument('--ckpt_path', type=str, default="/checkpoint/Fat-DeepFFM-24_5166.ckpt", help='Checkpoint path') parser.add_argument('--eval_file_name', type=str, default="./auc.log", help='Auc log file path. Default: "./auc.log"') parser.add_argument('--loss_file_name', type=str, default="./loss.log", help='Loss log file path. Default: "./loss.log"') parser.add_argument('--device_target', type=str, default="Ascend", choices=("Ascend", "GPU", "CPU"), help="device target, support Ascend, GPU and CPU.") parser.add_argument('--device_id', type=int, default=0, choices=(0, 1, 2, 3, 4, 5, 6, 7), help="device target, support Ascend, GPU and CPU.") args = parser.parse_args() rank_size = int(os.environ.get("RANK_SIZE", 1)) print("rank_size", rank_size) set_seed(1) if __name__ == '__main__': model_config = ModelConfig() device_id = int(os.getenv('DEVICE_ID', default=args.device_id)) context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target, device_id=device_id) print("Load dataset...") train_net, test_net = ModelBuilder(model_config).get_train_eval_net() auc_metric = AUCMetric() model = Model(train_net, eval_network=test_net, metrics={"AUC": auc_metric}) ds_test = get_mindrecord_dataset(args.dataset_path, train_mode=False) param_dict = load_checkpoint(args.ckpt_path) load_param_into_net(train_net, param_dict) print("Training started...") res = model.eval(ds_test, dataset_sink_mode=False) out_str = f'AUC: {list(res.values())[0]}' print(res) print(out_str)
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =========================================================================== """ eval model""" import argparse import os from src.config import ModelConfig from src.dataset import get_mindrecord_dataset from src.fat_deepffm import ModelBuilder from src.metrics import AUCMetric from mindspore import context, Model from mindspore.common import set_seed from mindspore.train.serialization import load_checkpoint, load_param_into_net parser = argparse.ArgumentParser(description='CTR Prediction') parser.add_argument('--dataset_path', type=str, default="/data/FM/mindrecord", help='Dataset path') parser.add_argument('--ckpt_path', type=str, default="/checkpoint/Fat-DeepFFM-24_5166.ckpt", help='Checkpoint path') parser.add_argument('--eval_file_name', type=str, default="./auc.log", help='Auc log file path. Default: "./auc.log"') parser.add_argument('--loss_file_name', type=str, default="./loss.log", help='Loss log file path. Default: "./loss.log"') parser.add_argument('--device_target', type=str, default="Ascend", choices=("Ascend", "GPU", "CPU"), help="device target, support Ascend, GPU and CPU.") parser.add_argument('--device_id', type=int, default=0, choices=(0, 1, 2, 3, 4, 5, 6, 7), help="device target, support Ascend, GPU and CPU.") args = parser.parse_args() rank_size = int(os.environ.get("RANK_SIZE", 1)) print("rank_size", rank_size) set_seed(1) if __name__ == '__main__': model_config = ModelConfig() device_id = int(os.getenv('DEVICE_ID', default=args.device_id)) context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target, device_id=device_id) print("Load dataset...") train_net, test_net = ModelBuilder(model_config).get_train_eval_net() auc_metric = AUCMetric() model = Model(train_net, eval_network=test_net, metrics={"AUC": auc_metric}) ds_test = get_mindrecord_dataset(args.dataset_path, train_mode=False) param_dict = load_checkpoint(args.ckpt_path) load_param_into_net(train_net, param_dict) print("Training started...") res = model.eval(ds_test, dataset_sink_mode=False) out_str = f'AUC: {list(res.values())[0]}' print(res) print(out_str)
en
0.807926
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =========================================================================== eval model
1.884698
2
src/anaplan_api/ResourceParserFile.py
pieter-pot/anaplan-api
0
6614300
<gh_stars>0 from .ResourceParserFactory import ResourceParserFactory from .AnaplanResourceFile import AnaplanResourceFile class ResourceParserFile(ResourceParserFactory): def get_parser(self, response: dict) -> AnaplanResourceFile: """Get a parser object for list of Anaplan files :param response: JSON list of files in an Anaplan model :type response: dict :return: Initialized object containing parsed list of files. :rtype: AnaplanResourceFile """ return AnaplanResourceFile(response)
from .ResourceParserFactory import ResourceParserFactory from .AnaplanResourceFile import AnaplanResourceFile class ResourceParserFile(ResourceParserFactory): def get_parser(self, response: dict) -> AnaplanResourceFile: """Get a parser object for list of Anaplan files :param response: JSON list of files in an Anaplan model :type response: dict :return: Initialized object containing parsed list of files. :rtype: AnaplanResourceFile """ return AnaplanResourceFile(response)
en
0.660024
Get a parser object for list of Anaplan files :param response: JSON list of files in an Anaplan model :type response: dict :return: Initialized object containing parsed list of files. :rtype: AnaplanResourceFile
2.668106
3
rotkehlchen/tests/test_no_missing_init.py
coblee/rotki
137
6614301
import os from typing import Set def find_directories_with_missing_init(path: str) -> Set[str]: package_dirs: Set[str] = set() py_directories: Set[str] = set() for root, dirs, files in os.walk(path): try: dirs.remove("__pycache__") except ValueError: pass for name in files: if name == "__init__.py": package_dirs.add(root) if name.endswith(".py"): py_directories.add(root) return py_directories - package_dirs def test_no_missing_init(): """Test that there is no directories missing an __init__.py file The reason for this is some linting tools like mypy and pylint don't check the directories that are missing the files. """ rotki_path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..")) print(f"\nScanning {rotki_path}") directories_with_missing_init = find_directories_with_missing_init(rotki_path) if directories_with_missing_init: print("The following directories are missing '__init__.py' files:") for directory in directories_with_missing_init: print(directory) assert not directories_with_missing_init, "some directories are missing __init__.py files"
import os from typing import Set def find_directories_with_missing_init(path: str) -> Set[str]: package_dirs: Set[str] = set() py_directories: Set[str] = set() for root, dirs, files in os.walk(path): try: dirs.remove("__pycache__") except ValueError: pass for name in files: if name == "__init__.py": package_dirs.add(root) if name.endswith(".py"): py_directories.add(root) return py_directories - package_dirs def test_no_missing_init(): """Test that there is no directories missing an __init__.py file The reason for this is some linting tools like mypy and pylint don't check the directories that are missing the files. """ rotki_path = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..")) print(f"\nScanning {rotki_path}") directories_with_missing_init = find_directories_with_missing_init(rotki_path) if directories_with_missing_init: print("The following directories are missing '__init__.py' files:") for directory in directories_with_missing_init: print(directory) assert not directories_with_missing_init, "some directories are missing __init__.py files"
en
0.930677
Test that there is no directories missing an __init__.py file The reason for this is some linting tools like mypy and pylint don't check the directories that are missing the files.
3.21206
3
tensorflow_lattice/python/premade.py
synergy-robotics-a-b/lattice
0
6614302
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """TF Lattice premade models implement typical monotonic model architectures. You can use TFL premade models to easily construct commonly used monotonic model architectures. To construct a TFL premade model, construct a model configuration from `tfl.configs` and pass it to the premade model constructor. Note that the inputs to the model should match the order in which they are defined in the feature configs. ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_lattice_model = tfl.premade.CalibratedLattice( model_config=model_config) calibrated_lattice_model.compile(...) calibrated_lattice_model.fit(...) ``` Supported models are defined in `tfl.configs`. Each model architecture can be used the same as any other `tf.keras.Model`. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from . import categorical_calibration_layer from . import configs from . import lattice_layer from . import linear_layer from . import pwl_calibration_layer from . import pwl_calibration_lib from absl import logging import enum import numpy as np import six import tensorflow as tf # Layer names used for layers in the premade models. INPUT_LAYER_NAME = 'tfl_input' CALIB_LAYER_NAME = 'tfl_calib' LATTICE_LAYER_NAME = 'tfl_lattice' LINEAR_LAYER_NAME = 'tfl_linear' OUTPUT_CALIB_LAYER_NAME = 'tfl_output_calib' # Prefix for passthrough (identity) nodes for shared calibration. # These nodes pass shared calibrated values to submodels in an ensemble. CALIB_PASSTHROUGH_NAME = 'tfl_calib_passthrough' # Prefix for defining feature calibrator regularizers. _INPUT_CALIB_REGULARIZER_PREFIX = 'calib_' # Prefix for defining output calibrator regularizers. _OUTPUT_CALIB_REGULARIZER_PREFIX = 'output_calib_' def _input_calibration_regularizers(model_config, feature_config): """Returns pwl layer regularizers defined in the model and feature configs.""" regularizer_configs = [] regularizer_configs.extend(feature_config.regularizer_configs or []) regularizer_configs.extend(model_config.regularizer_configs or []) return [(r.name.replace(_INPUT_CALIB_REGULARIZER_PREFIX, ''), r.l1, r.l2) for r in regularizer_configs if r.name.startswith(_INPUT_CALIB_REGULARIZER_PREFIX)] def _output_calibration_regularizers(model_config): """Returns output calibration regularizers defined in the model config.""" return [(r.name.replace(_OUTPUT_CALIB_REGULARIZER_PREFIX, ''), r.l1, r.l2) for r in model_config.regularizer_configs or [] if r.name.startswith(_OUTPUT_CALIB_REGULARIZER_PREFIX)] def _lattice_regularizers(model_config, feature_configs): """Returns lattice regularizers defined in the model and feature configs.""" # dict from regularizer name to pair of per feature l1 and l2 amounts. regularizers_dict = {} n_dims = len(feature_configs) for index, feature_config in enumerate(feature_configs): for regularizer_config in feature_config.regularizer_configs or []: if not ( regularizer_config.name.startswith(_INPUT_CALIB_REGULARIZER_PREFIX) or regularizer_config.name.startswith(_OUTPUT_CALIB_REGULARIZER_PREFIX)): if regularizer_config.name not in regularizers_dict: regularizers_dict[regularizer_config.name] = ([0.0] * n_dims, [0.0] * n_dims) regularizers_dict[ regularizer_config.name][0][index] += regularizer_config.l1 regularizers_dict[ regularizer_config.name][1][index] += regularizer_config.l2 regularizers = [(k,) + v for k, v in regularizers_dict.items()] for regularizer_config in model_config.regularizer_configs or []: if not ( regularizer_config.name.startswith(_INPUT_CALIB_REGULARIZER_PREFIX) or regularizer_config.name.startswith(_OUTPUT_CALIB_REGULARIZER_PREFIX)): regularizers.append((regularizer_config.name, regularizer_config.l1, regularizer_config.l2)) return regularizers class _LayerOutputRange(enum.Enum): """Enum to indicate the output range based on the input of the next layers.""" MODEL_OUTPUT = 1 INPUT_TO_LATTICE = 2 INPUT_TO_FINAL_CALIBRATION = 3 def _output_range(layer_output_range, model_config, feature_config=None): """Returns min/max/init_min/init_max for a given output range.""" if layer_output_range == _LayerOutputRange.INPUT_TO_LATTICE: if feature_config is None: raise ValueError('Expecting feature config for lattice inputs.') output_init_min = output_min = 0.0 output_init_max = output_max = feature_config.lattice_size - 1.0 elif layer_output_range == _LayerOutputRange.MODEL_OUTPUT: output_min = model_config.output_min output_max = model_config.output_max output_init_min = np.min(model_config.output_initialization) output_init_max = np.max(model_config.output_initialization) elif layer_output_range == _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION: output_init_min = output_min = 0.0 output_init_max = output_max = 1.0 else: raise ValueError('Unsupported layer output range.') return output_min, output_max, output_init_min, output_init_max def _input_layer(feature_configs, dtype): """Creates a calibration layer.""" input_layer = {} for feature_config in feature_configs: layer_name = '{}_{}'.format(INPUT_LAYER_NAME, feature_config.name) if feature_config.num_buckets: input_layer[feature_config.name] = tf.keras.Input( shape=(1,), dtype=tf.int32, name=layer_name) else: input_layer[feature_config.name] = tf.keras.Input( shape=(1,), dtype=dtype, name=layer_name) return input_layer def _calibration_layers(calibration_input_layer, feature_configs, model_config, layer_output_range, submodels, separate_calibrators, dtype): """Creates a calibration layer for `submodels` as list of list of features.""" # Create a list of (feature_name, calibration_output_idx) pairs for each # submodel. When using shared calibration, all submodels will have # calibration_output_idx = 0. submodels_input_features = [] calibration_last_index = collections.defaultdict(int) for submodel in submodels: submodel_input_features = [] submodels_input_features.append(submodel_input_features) for feature_name in submodel: submodel_input_features.append( (feature_name, calibration_last_index[feature_name])) if separate_calibrators: calibration_last_index[feature_name] += 1 calibration_output = {} for feature_config in feature_configs: feature_name = feature_config.name units = max(calibration_last_index[feature_name], 1) calibration_input = calibration_input_layer[feature_name] layer_name = '{}_{}'.format(CALIB_LAYER_NAME, feature_name) (output_min, output_max, output_init_min, output_init_max) = _output_range(layer_output_range, model_config, feature_config) if feature_config.num_buckets: kernel_initializer = tf.compat.v1.random_uniform_initializer( output_init_min, output_init_max) calibrated = ( categorical_calibration_layer.CategoricalCalibration( num_buckets=feature_config.num_buckets, units=units, output_min=output_min, output_max=output_max, kernel_initializer=kernel_initializer, monotonicities=feature_config.monotonicity if isinstance( feature_config.monotonicity, list) else None, default_input_value=feature_config.default_value, dtype=dtype, name=layer_name)(calibration_input)) else: kernel_regularizer = _input_calibration_regularizers( model_config, feature_config) monotonicity = feature_config.monotonicity if (pwl_calibration_lib.canonicalize_monotonicity(monotonicity) == 0 and feature_config.pwl_calibration_always_monotonic): monotonicity = 1 kernel_initializer = pwl_calibration_layer.UniformOutputInitializer( output_min=output_init_min, output_max=output_init_max, monotonicity=monotonicity) calibrated = ( pwl_calibration_layer.PWLCalibration( units=units, input_keypoints=feature_config.pwl_calibration_input_keypoints, output_min=output_min, output_max=output_max, clamp_min=feature_config.pwl_calibration_clamp_min, clamp_max=feature_config.pwl_calibration_clamp_max, missing_input_value=feature_config.default_value, impute_missing=(feature_config.default_value is not None), kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, monotonicity=monotonicity, convexity=feature_config.pwl_calibration_convexity, dtype=dtype, name=layer_name)(calibration_input)) if units == 1: calibration_output[feature_name] = [calibrated] else: calibration_output[feature_name] = tf.split(calibrated, units, axis=1) # Create passthrough nodes for each submodel input so that we can recover # the model structure for plotting and analysis. # {CALIB_PASSTHROUGH_NAME}_{feature_name}_ # {calibration_output_idx}_{submodel_idx}_{submodel_input_idx} submodels_inputs = [] for submodel_idx, submodel_input_features in enumerate( submodels_input_features): submodel_inputs = [] submodels_inputs.append(submodel_inputs) for (submodel_input_idx, (feature_name, calibration_output_idx)) in enumerate(submodel_input_features): passthrough_name = '{}_{}_{}_{}_{}'.format(CALIB_PASSTHROUGH_NAME, feature_name, calibration_output_idx, submodel_idx, submodel_input_idx) submodel_inputs.append( tf.identity( calibration_output[feature_name][calibration_output_idx], name=passthrough_name)) return submodels_inputs def _monotonicities_from_feature_configs(feature_configs): """Returns list of monotonicities defined in the given feature_configs.""" monotonicities = [] for feature_config in feature_configs: if not feature_config.monotonicity: monotonicities.append(0) elif (isinstance(feature_config.monotonicity, six.string_types) and feature_config.monotonicity.lower() == 'none'): monotonicities.append(0) else: monotonicities.append(1) return monotonicities def _dominance_constraints_from_feature_configs(feature_configs): """Returns list of dominance constraints in the given feature_configs.""" feature_names = [feature_config.name for feature_config in feature_configs] monotonic_dominances = [] for dominant_idx, dominant_feature_config in enumerate(feature_configs): for dominance_config in dominant_feature_config.dominates or []: if dominance_config.feature_name in feature_names: weak_idx = feature_names.index(dominance_config.feature_name) if dominance_config.dominance_type == 'monotonic': monotonic_dominances.append((dominant_idx, weak_idx)) else: raise ValueError('Unrecognized dominance type: {}'.format( dominance_config.dominance_type)) return monotonic_dominances def _linear_layer(linear_input, feature_configs, model_config, weighted_average, submodel_index, dtype): """Creates a linear layer initialized to be an average.""" layer_name = '{}_{}'.format(LINEAR_LAYER_NAME, submodel_index) linear_input = tf.keras.layers.Concatenate(axis=1)(linear_input) num_input_dims = len(feature_configs) kernel_initializer = tf.compat.v1.constant_initializer( [1.0 / num_input_dims] * num_input_dims) bias_initializer = tf.compat.v1.constant_initializer(0) if weighted_average: # Linear coefficients should be possitive and sum up to one. linear_monotonicities = [1] * num_input_dims normalization_order = 1 use_bias = False else: linear_monotonicities = _monotonicities_from_feature_configs( feature_configs) normalization_order = None use_bias = model_config.use_bias monotonic_dominances = _dominance_constraints_from_feature_configs( feature_configs) return linear_layer.Linear( num_input_dims=num_input_dims, monotonicities=linear_monotonicities, monotonic_dominances=monotonic_dominances, use_bias=use_bias, normalization_order=normalization_order, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, dtype=dtype, name=layer_name)( linear_input) def _lattice_layer(lattice_input, feature_configs, model_config, layer_output_range, submodel_index, is_inside_ensemble, dtype): """Creates a lattice layer.""" layer_name = '{}_{}'.format(LATTICE_LAYER_NAME, submodel_index) (output_min, output_max, output_init_min, output_init_max) = _output_range(layer_output_range, model_config) feature_names = [feature_config.name for feature_config in feature_configs] lattice_sizes = [ feature_config.lattice_size for feature_config in feature_configs ] lattice_monotonicities = _monotonicities_from_feature_configs(feature_configs) lattice_unimodalities = [ feature_config.unimodality for feature_config in feature_configs ] lattice_regularizers = _lattice_regularizers(model_config, feature_configs) # Construct trust constraints within this lattice. edgeworth_trusts = [] trapezoid_trusts = [] for conditional_idx, conditional_feature_config in enumerate(feature_configs): for trust_config in conditional_feature_config.reflects_trust_in or []: if trust_config.feature_name in feature_names: main_idx = feature_names.index(trust_config.feature_name) if trust_config.trust_type == 'edgeworth': edgeworth_trusts.append( (main_idx, conditional_idx, trust_config.direction)) elif trust_config.trust_type == 'trapezoid': trapezoid_trusts.append( (main_idx, conditional_idx, trust_config.direction)) else: raise ValueError('Unrecognized trust type: {}'.format( trust_config.trust_type)) elif is_inside_ensemble and trust_config.trust_type == 'trapezoid': logging.warning( 'A "main" feature (%s) for a trapezoid trust constraint is not ' 'present in a lattice that includes the "conditional" feature ' '(%s). In an ensemble model, this can result in constraint ' 'violations. Consider manually setting the ensemble structure if ' 'this constraint needs to be satisfied.', trust_config.feature_name, conditional_feature_config.name) monotonic_dominances = _dominance_constraints_from_feature_configs( feature_configs) kernel_initializer = lattice_layer.LinearInitializer( lattice_sizes=lattice_sizes, monotonicities=lattice_monotonicities, unimodalities=lattice_unimodalities, output_min=output_init_min, output_max=output_init_max) return lattice_layer.Lattice( lattice_sizes=lattice_sizes, monotonicities=lattice_monotonicities, unimodalities=lattice_unimodalities, edgeworth_trusts=edgeworth_trusts, trapezoid_trusts=trapezoid_trusts, monotonic_dominances=monotonic_dominances, output_min=output_min, output_max=output_max, clip_inputs=False, kernel_regularizer=lattice_regularizers, kernel_initializer=kernel_initializer, dtype=dtype, name=layer_name)( lattice_input) def _output_calibration_layer(output_calibration_input, model_config, dtype): """Creates a monotonic output calibration layer with inputs range [0, 1].""" # kernel format: bias followed by diffs between consecutive keypoint outputs. kernel_init_values = np.ediff1d( model_config.output_initialization, to_begin=model_config.output_initialization[0]) input_keypoints = np.linspace(0.0, 1.0, num=len(kernel_init_values)) kernel_initializer = tf.compat.v1.constant_initializer(kernel_init_values) kernel_regularizer = _output_calibration_regularizers(model_config) return pwl_calibration_layer.PWLCalibration( input_keypoints=input_keypoints, output_min=model_config.output_min, output_max=model_config.output_max, kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, monotonicity=1, dtype=dtype, name=OUTPUT_CALIB_LAYER_NAME)( output_calibration_input) # TODO: add support for serialization and object scoping or annoations. class CalibratedLatticeEnsemble(tf.keras.Model): """Premade model for Tensorflow calibrated lattice ensemble models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLatticeEnsembleConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeEnsembleConfig(...) calibrated_lattice_ensemble_model = tfl.premade.CalibratedLatticeEnsemble( model_config=model_config) calibrated_lattice_ensemble_model.compile(...) calibrated_lattice_ensemble_model.fit(...) ``` """ def __init__(self, model_config, dtype=tf.float32): """Initializes a `CalibratedLatticeEnsemble` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. """ # Check that proper config has been given. if not isinstance(model_config, configs.CalibratedLatticeEnsembleConfig): raise ValueError('Invalid config type: {}'.format(type(model_config))) # Get feature configs and construct model. input_layer = _input_layer( feature_configs=model_config.feature_configs, dtype=dtype) submodels_inputs = _calibration_layers( calibration_input_layer=input_layer, feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=_LayerOutputRange.INPUT_TO_LATTICE, submodels=model_config.lattices, separate_calibrators=model_config.separate_calibrators, dtype=dtype) lattice_outputs = [] for submodel_index, (lattice_feature_names, lattice_input) in enumerate( zip(model_config.lattices, submodels_inputs)): lattice_feature_configs = [ model_config.feature_config_by_name(feature_name) for feature_name in lattice_feature_names ] lattice_layer_output_range = ( _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION if model_config.output_calibration else _LayerOutputRange.MODEL_OUTPUT) lattice_outputs.append( _lattice_layer( lattice_input=lattice_input, feature_configs=lattice_feature_configs, model_config=model_config, layer_output_range=lattice_layer_output_range, submodel_index=submodel_index, is_inside_ensemble=True, dtype=dtype)) if len(lattice_outputs) > 1: averaged_lattice_output = tf.keras.layers.Average()(lattice_outputs) else: averaged_lattice_output = lattice_outputs[0] if model_config.output_calibration: model_output = _output_calibration_layer( output_calibration_input=averaged_lattice_output, model_config=model_config, dtype=dtype) else: model_output = averaged_lattice_output # Define inputs and initialize model. inputs = [ input_layer[feature_config.name] for feature_config in model_config.feature_configs ] super(CalibratedLatticeEnsemble, self).__init__( inputs=inputs, outputs=model_output) class CalibratedLattice(tf.keras.Model): """Premade model for Tensorflow calibrated lattice models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLatticeConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_lattice_model = tfl.premade.CalibratedLattice( model_config=model_config) calibrated_lattice_model.compile(...) calibrated_lattice_model.fit(...) ``` """ def __init__(self, model_config, dtype=tf.float32): """Initializes a `CalibratedLattice` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. """ # Check that proper config has been given. if not isinstance(model_config, configs.CalibratedLatticeConfig): raise ValueError('Invalid config type: {}'.format(type(model_config))) # Get feature configs and construct model. input_layer = _input_layer( feature_configs=model_config.feature_configs, dtype=dtype) submodels_inputs = _calibration_layers( calibration_input_layer=input_layer, feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=_LayerOutputRange.INPUT_TO_LATTICE, submodels=[[ feature_config.name for feature_config in model_config.feature_configs ]], separate_calibrators=False, dtype=dtype) lattice_layer_output_range = ( _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION if model_config.output_calibration else _LayerOutputRange.MODEL_OUTPUT) lattice_output = _lattice_layer( lattice_input=submodels_inputs[0], feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=lattice_layer_output_range, submodel_index=0, is_inside_ensemble=False, dtype=dtype) if model_config.output_calibration: model_output = _output_calibration_layer( output_calibration_input=lattice_output, model_config=model_config, dtype=dtype) else: model_output = lattice_output # Define inputs and initialize model. inputs = [ input_layer[feature_config.name] for feature_config in model_config.feature_configs ] super(CalibratedLattice, self).__init__(inputs=inputs, outputs=model_output) class CalibratedLinear(tf.keras.Model): """Premade model for Tensorflow calibrated linear models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLinearConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_linear_model = tfl.premade.CalibratedLinear( model_config=model_config) calibrated_linear_model.compile(...) calibrated_linear_model.fit(...) ``` """ def __init__(self, model_config, dtype=tf.float32): """Initializes a `CalibratedLinear` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. """ # Check that proper config has been given. if not isinstance(model_config, configs.CalibratedLinearConfig): raise ValueError('Invalid config type: {}'.format(type(model_config))) # Get feature configs and construct model. input_layer = _input_layer( feature_configs=model_config.feature_configs, dtype=dtype) calibration_layer_output_range = ( _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION if model_config.output_calibration else _LayerOutputRange.MODEL_OUTPUT) submodels_inputs = _calibration_layers( calibration_input_layer=input_layer, feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=calibration_layer_output_range, submodels=[[ feature_config.name for feature_config in model_config.feature_configs ]], separate_calibrators=False, dtype=dtype) weighted_average = ( model_config.output_min is not None or model_config.output_max is not None or model_config.output_calibration) linear_output = _linear_layer( linear_input=submodels_inputs[0], feature_configs=model_config.feature_configs, model_config=model_config, weighted_average=weighted_average, submodel_index=0, dtype=dtype) if model_config.output_calibration: model_output = _output_calibration_layer( output_calibration_input=linear_output, model_config=model_config, dtype=dtype) else: model_output = linear_output # Define inputs and initialize model. inputs = [ input_layer[feature_config.name] for feature_config in model_config.feature_configs ] super(CalibratedLinear, self).__init__(inputs=inputs, outputs=model_output)
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """TF Lattice premade models implement typical monotonic model architectures. You can use TFL premade models to easily construct commonly used monotonic model architectures. To construct a TFL premade model, construct a model configuration from `tfl.configs` and pass it to the premade model constructor. Note that the inputs to the model should match the order in which they are defined in the feature configs. ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_lattice_model = tfl.premade.CalibratedLattice( model_config=model_config) calibrated_lattice_model.compile(...) calibrated_lattice_model.fit(...) ``` Supported models are defined in `tfl.configs`. Each model architecture can be used the same as any other `tf.keras.Model`. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from . import categorical_calibration_layer from . import configs from . import lattice_layer from . import linear_layer from . import pwl_calibration_layer from . import pwl_calibration_lib from absl import logging import enum import numpy as np import six import tensorflow as tf # Layer names used for layers in the premade models. INPUT_LAYER_NAME = 'tfl_input' CALIB_LAYER_NAME = 'tfl_calib' LATTICE_LAYER_NAME = 'tfl_lattice' LINEAR_LAYER_NAME = 'tfl_linear' OUTPUT_CALIB_LAYER_NAME = 'tfl_output_calib' # Prefix for passthrough (identity) nodes for shared calibration. # These nodes pass shared calibrated values to submodels in an ensemble. CALIB_PASSTHROUGH_NAME = 'tfl_calib_passthrough' # Prefix for defining feature calibrator regularizers. _INPUT_CALIB_REGULARIZER_PREFIX = 'calib_' # Prefix for defining output calibrator regularizers. _OUTPUT_CALIB_REGULARIZER_PREFIX = 'output_calib_' def _input_calibration_regularizers(model_config, feature_config): """Returns pwl layer regularizers defined in the model and feature configs.""" regularizer_configs = [] regularizer_configs.extend(feature_config.regularizer_configs or []) regularizer_configs.extend(model_config.regularizer_configs or []) return [(r.name.replace(_INPUT_CALIB_REGULARIZER_PREFIX, ''), r.l1, r.l2) for r in regularizer_configs if r.name.startswith(_INPUT_CALIB_REGULARIZER_PREFIX)] def _output_calibration_regularizers(model_config): """Returns output calibration regularizers defined in the model config.""" return [(r.name.replace(_OUTPUT_CALIB_REGULARIZER_PREFIX, ''), r.l1, r.l2) for r in model_config.regularizer_configs or [] if r.name.startswith(_OUTPUT_CALIB_REGULARIZER_PREFIX)] def _lattice_regularizers(model_config, feature_configs): """Returns lattice regularizers defined in the model and feature configs.""" # dict from regularizer name to pair of per feature l1 and l2 amounts. regularizers_dict = {} n_dims = len(feature_configs) for index, feature_config in enumerate(feature_configs): for regularizer_config in feature_config.regularizer_configs or []: if not ( regularizer_config.name.startswith(_INPUT_CALIB_REGULARIZER_PREFIX) or regularizer_config.name.startswith(_OUTPUT_CALIB_REGULARIZER_PREFIX)): if regularizer_config.name not in regularizers_dict: regularizers_dict[regularizer_config.name] = ([0.0] * n_dims, [0.0] * n_dims) regularizers_dict[ regularizer_config.name][0][index] += regularizer_config.l1 regularizers_dict[ regularizer_config.name][1][index] += regularizer_config.l2 regularizers = [(k,) + v for k, v in regularizers_dict.items()] for regularizer_config in model_config.regularizer_configs or []: if not ( regularizer_config.name.startswith(_INPUT_CALIB_REGULARIZER_PREFIX) or regularizer_config.name.startswith(_OUTPUT_CALIB_REGULARIZER_PREFIX)): regularizers.append((regularizer_config.name, regularizer_config.l1, regularizer_config.l2)) return regularizers class _LayerOutputRange(enum.Enum): """Enum to indicate the output range based on the input of the next layers.""" MODEL_OUTPUT = 1 INPUT_TO_LATTICE = 2 INPUT_TO_FINAL_CALIBRATION = 3 def _output_range(layer_output_range, model_config, feature_config=None): """Returns min/max/init_min/init_max for a given output range.""" if layer_output_range == _LayerOutputRange.INPUT_TO_LATTICE: if feature_config is None: raise ValueError('Expecting feature config for lattice inputs.') output_init_min = output_min = 0.0 output_init_max = output_max = feature_config.lattice_size - 1.0 elif layer_output_range == _LayerOutputRange.MODEL_OUTPUT: output_min = model_config.output_min output_max = model_config.output_max output_init_min = np.min(model_config.output_initialization) output_init_max = np.max(model_config.output_initialization) elif layer_output_range == _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION: output_init_min = output_min = 0.0 output_init_max = output_max = 1.0 else: raise ValueError('Unsupported layer output range.') return output_min, output_max, output_init_min, output_init_max def _input_layer(feature_configs, dtype): """Creates a calibration layer.""" input_layer = {} for feature_config in feature_configs: layer_name = '{}_{}'.format(INPUT_LAYER_NAME, feature_config.name) if feature_config.num_buckets: input_layer[feature_config.name] = tf.keras.Input( shape=(1,), dtype=tf.int32, name=layer_name) else: input_layer[feature_config.name] = tf.keras.Input( shape=(1,), dtype=dtype, name=layer_name) return input_layer def _calibration_layers(calibration_input_layer, feature_configs, model_config, layer_output_range, submodels, separate_calibrators, dtype): """Creates a calibration layer for `submodels` as list of list of features.""" # Create a list of (feature_name, calibration_output_idx) pairs for each # submodel. When using shared calibration, all submodels will have # calibration_output_idx = 0. submodels_input_features = [] calibration_last_index = collections.defaultdict(int) for submodel in submodels: submodel_input_features = [] submodels_input_features.append(submodel_input_features) for feature_name in submodel: submodel_input_features.append( (feature_name, calibration_last_index[feature_name])) if separate_calibrators: calibration_last_index[feature_name] += 1 calibration_output = {} for feature_config in feature_configs: feature_name = feature_config.name units = max(calibration_last_index[feature_name], 1) calibration_input = calibration_input_layer[feature_name] layer_name = '{}_{}'.format(CALIB_LAYER_NAME, feature_name) (output_min, output_max, output_init_min, output_init_max) = _output_range(layer_output_range, model_config, feature_config) if feature_config.num_buckets: kernel_initializer = tf.compat.v1.random_uniform_initializer( output_init_min, output_init_max) calibrated = ( categorical_calibration_layer.CategoricalCalibration( num_buckets=feature_config.num_buckets, units=units, output_min=output_min, output_max=output_max, kernel_initializer=kernel_initializer, monotonicities=feature_config.monotonicity if isinstance( feature_config.monotonicity, list) else None, default_input_value=feature_config.default_value, dtype=dtype, name=layer_name)(calibration_input)) else: kernel_regularizer = _input_calibration_regularizers( model_config, feature_config) monotonicity = feature_config.monotonicity if (pwl_calibration_lib.canonicalize_monotonicity(monotonicity) == 0 and feature_config.pwl_calibration_always_monotonic): monotonicity = 1 kernel_initializer = pwl_calibration_layer.UniformOutputInitializer( output_min=output_init_min, output_max=output_init_max, monotonicity=monotonicity) calibrated = ( pwl_calibration_layer.PWLCalibration( units=units, input_keypoints=feature_config.pwl_calibration_input_keypoints, output_min=output_min, output_max=output_max, clamp_min=feature_config.pwl_calibration_clamp_min, clamp_max=feature_config.pwl_calibration_clamp_max, missing_input_value=feature_config.default_value, impute_missing=(feature_config.default_value is not None), kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, monotonicity=monotonicity, convexity=feature_config.pwl_calibration_convexity, dtype=dtype, name=layer_name)(calibration_input)) if units == 1: calibration_output[feature_name] = [calibrated] else: calibration_output[feature_name] = tf.split(calibrated, units, axis=1) # Create passthrough nodes for each submodel input so that we can recover # the model structure for plotting and analysis. # {CALIB_PASSTHROUGH_NAME}_{feature_name}_ # {calibration_output_idx}_{submodel_idx}_{submodel_input_idx} submodels_inputs = [] for submodel_idx, submodel_input_features in enumerate( submodels_input_features): submodel_inputs = [] submodels_inputs.append(submodel_inputs) for (submodel_input_idx, (feature_name, calibration_output_idx)) in enumerate(submodel_input_features): passthrough_name = '{}_{}_{}_{}_{}'.format(CALIB_PASSTHROUGH_NAME, feature_name, calibration_output_idx, submodel_idx, submodel_input_idx) submodel_inputs.append( tf.identity( calibration_output[feature_name][calibration_output_idx], name=passthrough_name)) return submodels_inputs def _monotonicities_from_feature_configs(feature_configs): """Returns list of monotonicities defined in the given feature_configs.""" monotonicities = [] for feature_config in feature_configs: if not feature_config.monotonicity: monotonicities.append(0) elif (isinstance(feature_config.monotonicity, six.string_types) and feature_config.monotonicity.lower() == 'none'): monotonicities.append(0) else: monotonicities.append(1) return monotonicities def _dominance_constraints_from_feature_configs(feature_configs): """Returns list of dominance constraints in the given feature_configs.""" feature_names = [feature_config.name for feature_config in feature_configs] monotonic_dominances = [] for dominant_idx, dominant_feature_config in enumerate(feature_configs): for dominance_config in dominant_feature_config.dominates or []: if dominance_config.feature_name in feature_names: weak_idx = feature_names.index(dominance_config.feature_name) if dominance_config.dominance_type == 'monotonic': monotonic_dominances.append((dominant_idx, weak_idx)) else: raise ValueError('Unrecognized dominance type: {}'.format( dominance_config.dominance_type)) return monotonic_dominances def _linear_layer(linear_input, feature_configs, model_config, weighted_average, submodel_index, dtype): """Creates a linear layer initialized to be an average.""" layer_name = '{}_{}'.format(LINEAR_LAYER_NAME, submodel_index) linear_input = tf.keras.layers.Concatenate(axis=1)(linear_input) num_input_dims = len(feature_configs) kernel_initializer = tf.compat.v1.constant_initializer( [1.0 / num_input_dims] * num_input_dims) bias_initializer = tf.compat.v1.constant_initializer(0) if weighted_average: # Linear coefficients should be possitive and sum up to one. linear_monotonicities = [1] * num_input_dims normalization_order = 1 use_bias = False else: linear_monotonicities = _monotonicities_from_feature_configs( feature_configs) normalization_order = None use_bias = model_config.use_bias monotonic_dominances = _dominance_constraints_from_feature_configs( feature_configs) return linear_layer.Linear( num_input_dims=num_input_dims, monotonicities=linear_monotonicities, monotonic_dominances=monotonic_dominances, use_bias=use_bias, normalization_order=normalization_order, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer, dtype=dtype, name=layer_name)( linear_input) def _lattice_layer(lattice_input, feature_configs, model_config, layer_output_range, submodel_index, is_inside_ensemble, dtype): """Creates a lattice layer.""" layer_name = '{}_{}'.format(LATTICE_LAYER_NAME, submodel_index) (output_min, output_max, output_init_min, output_init_max) = _output_range(layer_output_range, model_config) feature_names = [feature_config.name for feature_config in feature_configs] lattice_sizes = [ feature_config.lattice_size for feature_config in feature_configs ] lattice_monotonicities = _monotonicities_from_feature_configs(feature_configs) lattice_unimodalities = [ feature_config.unimodality for feature_config in feature_configs ] lattice_regularizers = _lattice_regularizers(model_config, feature_configs) # Construct trust constraints within this lattice. edgeworth_trusts = [] trapezoid_trusts = [] for conditional_idx, conditional_feature_config in enumerate(feature_configs): for trust_config in conditional_feature_config.reflects_trust_in or []: if trust_config.feature_name in feature_names: main_idx = feature_names.index(trust_config.feature_name) if trust_config.trust_type == 'edgeworth': edgeworth_trusts.append( (main_idx, conditional_idx, trust_config.direction)) elif trust_config.trust_type == 'trapezoid': trapezoid_trusts.append( (main_idx, conditional_idx, trust_config.direction)) else: raise ValueError('Unrecognized trust type: {}'.format( trust_config.trust_type)) elif is_inside_ensemble and trust_config.trust_type == 'trapezoid': logging.warning( 'A "main" feature (%s) for a trapezoid trust constraint is not ' 'present in a lattice that includes the "conditional" feature ' '(%s). In an ensemble model, this can result in constraint ' 'violations. Consider manually setting the ensemble structure if ' 'this constraint needs to be satisfied.', trust_config.feature_name, conditional_feature_config.name) monotonic_dominances = _dominance_constraints_from_feature_configs( feature_configs) kernel_initializer = lattice_layer.LinearInitializer( lattice_sizes=lattice_sizes, monotonicities=lattice_monotonicities, unimodalities=lattice_unimodalities, output_min=output_init_min, output_max=output_init_max) return lattice_layer.Lattice( lattice_sizes=lattice_sizes, monotonicities=lattice_monotonicities, unimodalities=lattice_unimodalities, edgeworth_trusts=edgeworth_trusts, trapezoid_trusts=trapezoid_trusts, monotonic_dominances=monotonic_dominances, output_min=output_min, output_max=output_max, clip_inputs=False, kernel_regularizer=lattice_regularizers, kernel_initializer=kernel_initializer, dtype=dtype, name=layer_name)( lattice_input) def _output_calibration_layer(output_calibration_input, model_config, dtype): """Creates a monotonic output calibration layer with inputs range [0, 1].""" # kernel format: bias followed by diffs between consecutive keypoint outputs. kernel_init_values = np.ediff1d( model_config.output_initialization, to_begin=model_config.output_initialization[0]) input_keypoints = np.linspace(0.0, 1.0, num=len(kernel_init_values)) kernel_initializer = tf.compat.v1.constant_initializer(kernel_init_values) kernel_regularizer = _output_calibration_regularizers(model_config) return pwl_calibration_layer.PWLCalibration( input_keypoints=input_keypoints, output_min=model_config.output_min, output_max=model_config.output_max, kernel_initializer=kernel_initializer, kernel_regularizer=kernel_regularizer, monotonicity=1, dtype=dtype, name=OUTPUT_CALIB_LAYER_NAME)( output_calibration_input) # TODO: add support for serialization and object scoping or annoations. class CalibratedLatticeEnsemble(tf.keras.Model): """Premade model for Tensorflow calibrated lattice ensemble models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLatticeEnsembleConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeEnsembleConfig(...) calibrated_lattice_ensemble_model = tfl.premade.CalibratedLatticeEnsemble( model_config=model_config) calibrated_lattice_ensemble_model.compile(...) calibrated_lattice_ensemble_model.fit(...) ``` """ def __init__(self, model_config, dtype=tf.float32): """Initializes a `CalibratedLatticeEnsemble` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. """ # Check that proper config has been given. if not isinstance(model_config, configs.CalibratedLatticeEnsembleConfig): raise ValueError('Invalid config type: {}'.format(type(model_config))) # Get feature configs and construct model. input_layer = _input_layer( feature_configs=model_config.feature_configs, dtype=dtype) submodels_inputs = _calibration_layers( calibration_input_layer=input_layer, feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=_LayerOutputRange.INPUT_TO_LATTICE, submodels=model_config.lattices, separate_calibrators=model_config.separate_calibrators, dtype=dtype) lattice_outputs = [] for submodel_index, (lattice_feature_names, lattice_input) in enumerate( zip(model_config.lattices, submodels_inputs)): lattice_feature_configs = [ model_config.feature_config_by_name(feature_name) for feature_name in lattice_feature_names ] lattice_layer_output_range = ( _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION if model_config.output_calibration else _LayerOutputRange.MODEL_OUTPUT) lattice_outputs.append( _lattice_layer( lattice_input=lattice_input, feature_configs=lattice_feature_configs, model_config=model_config, layer_output_range=lattice_layer_output_range, submodel_index=submodel_index, is_inside_ensemble=True, dtype=dtype)) if len(lattice_outputs) > 1: averaged_lattice_output = tf.keras.layers.Average()(lattice_outputs) else: averaged_lattice_output = lattice_outputs[0] if model_config.output_calibration: model_output = _output_calibration_layer( output_calibration_input=averaged_lattice_output, model_config=model_config, dtype=dtype) else: model_output = averaged_lattice_output # Define inputs and initialize model. inputs = [ input_layer[feature_config.name] for feature_config in model_config.feature_configs ] super(CalibratedLatticeEnsemble, self).__init__( inputs=inputs, outputs=model_output) class CalibratedLattice(tf.keras.Model): """Premade model for Tensorflow calibrated lattice models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLatticeConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_lattice_model = tfl.premade.CalibratedLattice( model_config=model_config) calibrated_lattice_model.compile(...) calibrated_lattice_model.fit(...) ``` """ def __init__(self, model_config, dtype=tf.float32): """Initializes a `CalibratedLattice` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. """ # Check that proper config has been given. if not isinstance(model_config, configs.CalibratedLatticeConfig): raise ValueError('Invalid config type: {}'.format(type(model_config))) # Get feature configs and construct model. input_layer = _input_layer( feature_configs=model_config.feature_configs, dtype=dtype) submodels_inputs = _calibration_layers( calibration_input_layer=input_layer, feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=_LayerOutputRange.INPUT_TO_LATTICE, submodels=[[ feature_config.name for feature_config in model_config.feature_configs ]], separate_calibrators=False, dtype=dtype) lattice_layer_output_range = ( _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION if model_config.output_calibration else _LayerOutputRange.MODEL_OUTPUT) lattice_output = _lattice_layer( lattice_input=submodels_inputs[0], feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=lattice_layer_output_range, submodel_index=0, is_inside_ensemble=False, dtype=dtype) if model_config.output_calibration: model_output = _output_calibration_layer( output_calibration_input=lattice_output, model_config=model_config, dtype=dtype) else: model_output = lattice_output # Define inputs and initialize model. inputs = [ input_layer[feature_config.name] for feature_config in model_config.feature_configs ] super(CalibratedLattice, self).__init__(inputs=inputs, outputs=model_output) class CalibratedLinear(tf.keras.Model): """Premade model for Tensorflow calibrated linear models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLinearConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_linear_model = tfl.premade.CalibratedLinear( model_config=model_config) calibrated_linear_model.compile(...) calibrated_linear_model.fit(...) ``` """ def __init__(self, model_config, dtype=tf.float32): """Initializes a `CalibratedLinear` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. """ # Check that proper config has been given. if not isinstance(model_config, configs.CalibratedLinearConfig): raise ValueError('Invalid config type: {}'.format(type(model_config))) # Get feature configs and construct model. input_layer = _input_layer( feature_configs=model_config.feature_configs, dtype=dtype) calibration_layer_output_range = ( _LayerOutputRange.INPUT_TO_FINAL_CALIBRATION if model_config.output_calibration else _LayerOutputRange.MODEL_OUTPUT) submodels_inputs = _calibration_layers( calibration_input_layer=input_layer, feature_configs=model_config.feature_configs, model_config=model_config, layer_output_range=calibration_layer_output_range, submodels=[[ feature_config.name for feature_config in model_config.feature_configs ]], separate_calibrators=False, dtype=dtype) weighted_average = ( model_config.output_min is not None or model_config.output_max is not None or model_config.output_calibration) linear_output = _linear_layer( linear_input=submodels_inputs[0], feature_configs=model_config.feature_configs, model_config=model_config, weighted_average=weighted_average, submodel_index=0, dtype=dtype) if model_config.output_calibration: model_output = _output_calibration_layer( output_calibration_input=linear_output, model_config=model_config, dtype=dtype) else: model_output = linear_output # Define inputs and initialize model. inputs = [ input_layer[feature_config.name] for feature_config in model_config.feature_configs ] super(CalibratedLinear, self).__init__(inputs=inputs, outputs=model_output)
en
0.699835
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. TF Lattice premade models implement typical monotonic model architectures. You can use TFL premade models to easily construct commonly used monotonic model architectures. To construct a TFL premade model, construct a model configuration from `tfl.configs` and pass it to the premade model constructor. Note that the inputs to the model should match the order in which they are defined in the feature configs. ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_lattice_model = tfl.premade.CalibratedLattice( model_config=model_config) calibrated_lattice_model.compile(...) calibrated_lattice_model.fit(...) ``` Supported models are defined in `tfl.configs`. Each model architecture can be used the same as any other `tf.keras.Model`. # Layer names used for layers in the premade models. # Prefix for passthrough (identity) nodes for shared calibration. # These nodes pass shared calibrated values to submodels in an ensemble. # Prefix for defining feature calibrator regularizers. # Prefix for defining output calibrator regularizers. Returns pwl layer regularizers defined in the model and feature configs. Returns output calibration regularizers defined in the model config. Returns lattice regularizers defined in the model and feature configs. # dict from regularizer name to pair of per feature l1 and l2 amounts. Enum to indicate the output range based on the input of the next layers. Returns min/max/init_min/init_max for a given output range. Creates a calibration layer. Creates a calibration layer for `submodels` as list of list of features. # Create a list of (feature_name, calibration_output_idx) pairs for each # submodel. When using shared calibration, all submodels will have # calibration_output_idx = 0. # Create passthrough nodes for each submodel input so that we can recover # the model structure for plotting and analysis. # {CALIB_PASSTHROUGH_NAME}_{feature_name}_ # {calibration_output_idx}_{submodel_idx}_{submodel_input_idx} Returns list of monotonicities defined in the given feature_configs. Returns list of dominance constraints in the given feature_configs. Creates a linear layer initialized to be an average. # Linear coefficients should be possitive and sum up to one. Creates a lattice layer. # Construct trust constraints within this lattice. Creates a monotonic output calibration layer with inputs range [0, 1]. # kernel format: bias followed by diffs between consecutive keypoint outputs. # TODO: add support for serialization and object scoping or annoations. Premade model for Tensorflow calibrated lattice ensemble models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLatticeEnsembleConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeEnsembleConfig(...) calibrated_lattice_ensemble_model = tfl.premade.CalibratedLatticeEnsemble( model_config=model_config) calibrated_lattice_ensemble_model.compile(...) calibrated_lattice_ensemble_model.fit(...) ``` Initializes a `CalibratedLatticeEnsemble` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. # Check that proper config has been given. # Get feature configs and construct model. # Define inputs and initialize model. Premade model for Tensorflow calibrated lattice models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLatticeConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_lattice_model = tfl.premade.CalibratedLattice( model_config=model_config) calibrated_lattice_model.compile(...) calibrated_lattice_model.fit(...) ``` Initializes a `CalibratedLattice` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. # Check that proper config has been given. # Get feature configs and construct model. # Define inputs and initialize model. Premade model for Tensorflow calibrated linear models. Creates a `tf.keras.Model` for the model architecture specified by the `model_config`, which should a `tfl.configs.CalibratedLinearConfig` Note that the inputs to the model should match the order in which they are defined in the feature configs. Example: ```python model_config = tfl.configs.CalibratedLatticeConfig(...) calibrated_linear_model = tfl.premade.CalibratedLinear( model_config=model_config) calibrated_linear_model.compile(...) calibrated_linear_model.fit(...) ``` Initializes a `CalibratedLinear` instance. Args: model_config: Model configuration object describing model architecutre. Should be one of the model configs in `tfl.configs`. dtype: dtype of layers used in the model. # Check that proper config has been given. # Get feature configs and construct model. # Define inputs and initialize model.
2.587067
3
images/serializers.py
mistakes-consortium/igng
1
6614303
<reponame>mistakes-consortium/igng import datetime from rest_framework.reverse import reverse from taggit_serializer.serializers import TagListSerializerField, TaggitSerializer from images.fields import Base64ImageField from images.models import Gallery, Image, EXIFEntry from rest_framework import serializers import pytz class GallerySerializer(serializers.ModelSerializer): uuid = serializers.CharField(read_only=True) class Meta: model = Gallery fields = ('uuid', 'user', 'updated', 'updated_u', 'rel_start', 'rel_end', 'title', 'private') updated_u = serializers.SerializerMethodField() def get_updated_u(self, obj): return (obj.updated - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() class EXIFSerializer(serializers.ModelSerializer): key = serializers.CharField(source="key.key") value = serializers.CharField(source="value.value") class Meta: model = EXIFEntry fields = ('key', 'value') class ImageSerializer(TaggitSerializer, serializers.ModelSerializer): full_url = serializers.SerializerMethodField() thumb_url = serializers.SerializerMethodField() tiny_thumb_url = serializers.SerializerMethodField() gallery = serializers.CharField(source="gallery.uuid") uploaded_u = serializers.SerializerMethodField() exif_data = EXIFSerializer(read_only=True, many=True) tags = TagListSerializerField(required=False) uuid = serializers.CharField(read_only=True) class Meta: model = Image fields = ('uuid', 'user', 'gallery', 'uploaded', 'uploaded_u', 'title', 'uuid', 'full_url', 'thumb_url', 'tiny_thumb_url', 'exif_data', 'tags') def get_full_url(self, obj): return obj.full_fixed.url def get_thumb_url(self, obj): return obj.thumb.url def get_tiny_thumb_url(self, obj): return obj.tiny_thumb.url def get_uploaded_u(self, obj): return (obj.uploaded - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() class ImageUploadSerializer(TaggitSerializer,serializers.ModelSerializer): uuid = serializers.CharField(read_only=True) original = serializers.FileField() tags = TagListSerializerField(required=False) class Meta: model = Image fields = ('user', 'gallery', 'title', 'original', 'tags', 'uuid') class PasteImageUploadSerializer(serializers.ModelSerializer): original = Base64ImageField(max_length=None, use_url=True,) gallery = serializers.SlugRelatedField(required=False, queryset=Gallery.objects.all(),slug_field="uuid") def get_fields(self, *args, **kwargs): fields = super(PasteImageUploadSerializer, self).get_fields(*args, **kwargs) if not 'request' in self.context or self.context['request'] == None: # Documentation Needs it fields['gallery'].queryset = Gallery.objects.none() else: fields['gallery'].queryset = Gallery.objects.filter(user=(self.context['request'].user)) return fields class Meta: model = Image fields = ('original', 'gallery') def validate_gallery(self, value): u = self.context['request'].user if u.galleries.filter(uuid=value.uuid).exists(): # print "YAY" return value elif value == None: # print "NULL" return value # print "BOO " raise serializers.ValidationError("Non-existent Gallery") class PasteReturnSerializer(serializers.ModelSerializer): tiny_thumb_url = serializers.SerializerMethodField() image_page = serializers.SerializerMethodField() class Meta: model = Image fields = ('tiny_thumb_url', 'image_page') # fields = ("original", ) def get_tiny_thumb_url(self, obj): # print dir(obj) return obj.tiny_thumb.url def get_image_page(self, obj): return reverse("upload_success", args=[obj.uuid])
import datetime from rest_framework.reverse import reverse from taggit_serializer.serializers import TagListSerializerField, TaggitSerializer from images.fields import Base64ImageField from images.models import Gallery, Image, EXIFEntry from rest_framework import serializers import pytz class GallerySerializer(serializers.ModelSerializer): uuid = serializers.CharField(read_only=True) class Meta: model = Gallery fields = ('uuid', 'user', 'updated', 'updated_u', 'rel_start', 'rel_end', 'title', 'private') updated_u = serializers.SerializerMethodField() def get_updated_u(self, obj): return (obj.updated - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() class EXIFSerializer(serializers.ModelSerializer): key = serializers.CharField(source="key.key") value = serializers.CharField(source="value.value") class Meta: model = EXIFEntry fields = ('key', 'value') class ImageSerializer(TaggitSerializer, serializers.ModelSerializer): full_url = serializers.SerializerMethodField() thumb_url = serializers.SerializerMethodField() tiny_thumb_url = serializers.SerializerMethodField() gallery = serializers.CharField(source="gallery.uuid") uploaded_u = serializers.SerializerMethodField() exif_data = EXIFSerializer(read_only=True, many=True) tags = TagListSerializerField(required=False) uuid = serializers.CharField(read_only=True) class Meta: model = Image fields = ('uuid', 'user', 'gallery', 'uploaded', 'uploaded_u', 'title', 'uuid', 'full_url', 'thumb_url', 'tiny_thumb_url', 'exif_data', 'tags') def get_full_url(self, obj): return obj.full_fixed.url def get_thumb_url(self, obj): return obj.thumb.url def get_tiny_thumb_url(self, obj): return obj.tiny_thumb.url def get_uploaded_u(self, obj): return (obj.uploaded - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() class ImageUploadSerializer(TaggitSerializer,serializers.ModelSerializer): uuid = serializers.CharField(read_only=True) original = serializers.FileField() tags = TagListSerializerField(required=False) class Meta: model = Image fields = ('user', 'gallery', 'title', 'original', 'tags', 'uuid') class PasteImageUploadSerializer(serializers.ModelSerializer): original = Base64ImageField(max_length=None, use_url=True,) gallery = serializers.SlugRelatedField(required=False, queryset=Gallery.objects.all(),slug_field="uuid") def get_fields(self, *args, **kwargs): fields = super(PasteImageUploadSerializer, self).get_fields(*args, **kwargs) if not 'request' in self.context or self.context['request'] == None: # Documentation Needs it fields['gallery'].queryset = Gallery.objects.none() else: fields['gallery'].queryset = Gallery.objects.filter(user=(self.context['request'].user)) return fields class Meta: model = Image fields = ('original', 'gallery') def validate_gallery(self, value): u = self.context['request'].user if u.galleries.filter(uuid=value.uuid).exists(): # print "YAY" return value elif value == None: # print "NULL" return value # print "BOO " raise serializers.ValidationError("Non-existent Gallery") class PasteReturnSerializer(serializers.ModelSerializer): tiny_thumb_url = serializers.SerializerMethodField() image_page = serializers.SerializerMethodField() class Meta: model = Image fields = ('tiny_thumb_url', 'image_page') # fields = ("original", ) def get_tiny_thumb_url(self, obj): # print dir(obj) return obj.tiny_thumb.url def get_image_page(self, obj): return reverse("upload_success", args=[obj.uuid])
en
0.615393
# Documentation Needs it # print "YAY" # print "NULL" # print "BOO " # fields = ("original", ) # print dir(obj)
2.23523
2
catalog/urls.py
choia/django-library-tutorial
0
6614304
<reponame>choia/django-library-tutorial from django.conf.urls import include, url from . import views # Application URL Mapper urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^authors/$', views.AuthorListView.as_view(), name='authors'), url(r'^authors/(?P<pk>\d+)$', views.AuthorDetailView.as_view(), name='author-detail'), url(r'^books/$', views.BookListView.as_view(), name='books'), url(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), ] # User Loaned Book URL Conf urlpatterns += [ url(r'^mybooks/$', views.LoanedBookUserListView.as_view(), name='borrowed-book'), url(r'^borrowed/$', views.AllBorrowedBookListView.as_view(), name='all-borrowed-book'), ] # Renew Book URL Conf urlpatterns += [ url(r'^book/(?P<pk>[-\w]+)/renew/$', views.renew_book, name='renew-book'), ] # Author Model URL Conf urlpatterns += [ url(r'^author/create/$', views.AuthorCreate.as_view(), name='author-create'), url(r'^author/(?P<pk>\d+)/update/$', views.AuthorUpdate.as_view(), name='author-update'), url(r'^author/(?P<pk>\d+)/delete/$', views.AuthorDelete.as_view(), name='author-delete'), ]
from django.conf.urls import include, url from . import views # Application URL Mapper urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^authors/$', views.AuthorListView.as_view(), name='authors'), url(r'^authors/(?P<pk>\d+)$', views.AuthorDetailView.as_view(), name='author-detail'), url(r'^books/$', views.BookListView.as_view(), name='books'), url(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), ] # User Loaned Book URL Conf urlpatterns += [ url(r'^mybooks/$', views.LoanedBookUserListView.as_view(), name='borrowed-book'), url(r'^borrowed/$', views.AllBorrowedBookListView.as_view(), name='all-borrowed-book'), ] # Renew Book URL Conf urlpatterns += [ url(r'^book/(?P<pk>[-\w]+)/renew/$', views.renew_book, name='renew-book'), ] # Author Model URL Conf urlpatterns += [ url(r'^author/create/$', views.AuthorCreate.as_view(), name='author-create'), url(r'^author/(?P<pk>\d+)/update/$', views.AuthorUpdate.as_view(), name='author-update'), url(r'^author/(?P<pk>\d+)/delete/$', views.AuthorDelete.as_view(), name='author-delete'), ]
en
0.410163
# Application URL Mapper # User Loaned Book URL Conf # Renew Book URL Conf # Author Model URL Conf
2.080863
2
improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibration.py
mspelman07/improver
0
6614305
<filename>improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibration.py # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown copyright. The Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Unit tests for the ApplyRainForestsCalibration class.""" import sys import numpy as np import pytest try: import treelite_runtime except ModuleNotFoundError: TREELITE_ENABLED = False else: TREELITE_ENABLED = True from improver.calibration.rainforest_calibration import ApplyRainForestsCalibration lightgbm = pytest.importorskip("lightgbm") class MockBooster: def __init__(self, model_file, **kwargs): self.model_class = "lightgbm-Booster" self.model_file = model_file def reset_parameter(self, params): self.threads = params.get("num_threads") return self class MockPredictor: def __init__(self, libpath, nthread, **kwargs): self.model_class = "treelite-Predictor" self.threads = nthread self.model_file = libpath @pytest.mark.parametrize("lightgbm_keys", (True, False)) @pytest.mark.parametrize("ordered_inputs", (True, False)) @pytest.mark.parametrize("treelite_model", (TREELITE_ENABLED, False)) @pytest.mark.parametrize("treelite_file", (True, False)) def test__init__( lightgbm_keys, ordered_inputs, treelite_model, treelite_file, monkeypatch, model_config, error_thresholds, ): """Test treelite models are loaded if model_config correctly defines them. If all thresholds contain treelite model AND the treelite module is available, treelite Predictor is returned, otherwise return lightgbm Boosters. Checks outputs are ordered when inputs can be unordered. If neither treelite nor lightgbm configs are complete, a ValueError is expected.""" if treelite_model: monkeypatch.setattr(treelite_runtime, "Predictor", MockPredictor) else: monkeypatch.setitem(sys.modules, "treelite_runtime", None) monkeypatch.setattr(lightgbm, "Booster", MockBooster) if not treelite_file: # Model type should default to lightgbm if there are any treelite models # missing across any thresholds model_config["0.0000"].pop("treelite_model", None) if not ordered_inputs: tmp_value = model_config.pop("0.0000", None) model_config["0.0000"] = tmp_value if not lightgbm_keys: for t, d in model_config.items(): d.pop("lightgbm_model") if treelite_model and treelite_file: expected_class = "treelite-Predictor" elif lightgbm_keys: expected_class = "lightgbm-Booster" else: with pytest.raises(ValueError, match="Path to lightgbm model missing"): ApplyRainForestsCalibration(model_config, threads=8) return result = ApplyRainForestsCalibration(model_config, threads=8) for model in result.tree_models: assert model.model_class == expected_class assert model.threads == 8 assert result.treelite_enabled is treelite_model assert np.all(result.error_thresholds == error_thresholds) for threshold, model in zip(result.error_thresholds, result.tree_models): assert f"{threshold:06.4f}" in model.model_file
<filename>improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibration.py # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown copyright. The Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Unit tests for the ApplyRainForestsCalibration class.""" import sys import numpy as np import pytest try: import treelite_runtime except ModuleNotFoundError: TREELITE_ENABLED = False else: TREELITE_ENABLED = True from improver.calibration.rainforest_calibration import ApplyRainForestsCalibration lightgbm = pytest.importorskip("lightgbm") class MockBooster: def __init__(self, model_file, **kwargs): self.model_class = "lightgbm-Booster" self.model_file = model_file def reset_parameter(self, params): self.threads = params.get("num_threads") return self class MockPredictor: def __init__(self, libpath, nthread, **kwargs): self.model_class = "treelite-Predictor" self.threads = nthread self.model_file = libpath @pytest.mark.parametrize("lightgbm_keys", (True, False)) @pytest.mark.parametrize("ordered_inputs", (True, False)) @pytest.mark.parametrize("treelite_model", (TREELITE_ENABLED, False)) @pytest.mark.parametrize("treelite_file", (True, False)) def test__init__( lightgbm_keys, ordered_inputs, treelite_model, treelite_file, monkeypatch, model_config, error_thresholds, ): """Test treelite models are loaded if model_config correctly defines them. If all thresholds contain treelite model AND the treelite module is available, treelite Predictor is returned, otherwise return lightgbm Boosters. Checks outputs are ordered when inputs can be unordered. If neither treelite nor lightgbm configs are complete, a ValueError is expected.""" if treelite_model: monkeypatch.setattr(treelite_runtime, "Predictor", MockPredictor) else: monkeypatch.setitem(sys.modules, "treelite_runtime", None) monkeypatch.setattr(lightgbm, "Booster", MockBooster) if not treelite_file: # Model type should default to lightgbm if there are any treelite models # missing across any thresholds model_config["0.0000"].pop("treelite_model", None) if not ordered_inputs: tmp_value = model_config.pop("0.0000", None) model_config["0.0000"] = tmp_value if not lightgbm_keys: for t, d in model_config.items(): d.pop("lightgbm_model") if treelite_model and treelite_file: expected_class = "treelite-Predictor" elif lightgbm_keys: expected_class = "lightgbm-Booster" else: with pytest.raises(ValueError, match="Path to lightgbm model missing"): ApplyRainForestsCalibration(model_config, threads=8) return result = ApplyRainForestsCalibration(model_config, threads=8) for model in result.tree_models: assert model.model_class == expected_class assert model.threads == 8 assert result.treelite_enabled is treelite_model assert np.all(result.error_thresholds == error_thresholds) for threshold, model in zip(result.error_thresholds, result.tree_models): assert f"{threshold:06.4f}" in model.model_file
en
0.709322
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown copyright. The Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. Unit tests for the ApplyRainForestsCalibration class. Test treelite models are loaded if model_config correctly defines them. If all thresholds contain treelite model AND the treelite module is available, treelite Predictor is returned, otherwise return lightgbm Boosters. Checks outputs are ordered when inputs can be unordered. If neither treelite nor lightgbm configs are complete, a ValueError is expected. # Model type should default to lightgbm if there are any treelite models # missing across any thresholds
1.408288
1
botx/clients/types/message_payload.py
ExpressApp/pybotx
13
6614306
<reponame>ExpressApp/pybotx<gh_stars>10-100 """Shape that is used for messages from bot.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from botx.models.constants import MAXIMUM_TEXT_LENGTH from botx.models.entities import Mention from botx.models.enums import Statuses from botx.models.messages.sending.options import ResultPayloadOptions from botx.models.typing import BubbleMarkup, KeyboardMarkup try: from typing import Literal # noqa: WPS433 except ImportError: from typing_extensions import Literal # type: ignore # noqa: WPS433, WPS440, F401 class ResultPayload(BaseModel): """Data that is sent when bot answers on command or send notification.""" #: status of operation. status: Literal[Statuses.ok] = Statuses.ok #: body for new message from bot. body: str = Field("", max_length=MAXIMUM_TEXT_LENGTH) #: message metadata. metadata: Dict[str, Any] = {} #: options for `notification` and `command_result` API entities. opts: ResultPayloadOptions = ResultPayloadOptions() #: keyboard that will be used for new message. keyboard: KeyboardMarkup = [] #: bubble elements that will be showed under new message. bubble: BubbleMarkup = [] #: mentions that BotX API will append before new message text. mentions: List[Mention] = [] class UpdatePayload(BaseModel): """Data that is sent when bot updates message.""" #: status of operation. status: Literal[Statuses.ok] = Statuses.ok #: new body in message. body: Optional[str] = Field(None, max_length=MAXIMUM_TEXT_LENGTH) #: message metadata. metadata: Optional[Dict[str, Any]] = None #: new keyboard that will be used for new message. keyboard: Optional[KeyboardMarkup] = None #: new bubble elements that will be showed under new message. bubble: Optional[BubbleMarkup] = None #: new mentions that BotX API will append before new message text. mentions: Optional[List[Mention]] = None class InternalBotNotificationPayload(BaseModel): """Data that is sent in internal bot notification.""" #: message data message: str #: extra information about notification sender sender: Optional[str]
"""Shape that is used for messages from bot.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Field from botx.models.constants import MAXIMUM_TEXT_LENGTH from botx.models.entities import Mention from botx.models.enums import Statuses from botx.models.messages.sending.options import ResultPayloadOptions from botx.models.typing import BubbleMarkup, KeyboardMarkup try: from typing import Literal # noqa: WPS433 except ImportError: from typing_extensions import Literal # type: ignore # noqa: WPS433, WPS440, F401 class ResultPayload(BaseModel): """Data that is sent when bot answers on command or send notification.""" #: status of operation. status: Literal[Statuses.ok] = Statuses.ok #: body for new message from bot. body: str = Field("", max_length=MAXIMUM_TEXT_LENGTH) #: message metadata. metadata: Dict[str, Any] = {} #: options for `notification` and `command_result` API entities. opts: ResultPayloadOptions = ResultPayloadOptions() #: keyboard that will be used for new message. keyboard: KeyboardMarkup = [] #: bubble elements that will be showed under new message. bubble: BubbleMarkup = [] #: mentions that BotX API will append before new message text. mentions: List[Mention] = [] class UpdatePayload(BaseModel): """Data that is sent when bot updates message.""" #: status of operation. status: Literal[Statuses.ok] = Statuses.ok #: new body in message. body: Optional[str] = Field(None, max_length=MAXIMUM_TEXT_LENGTH) #: message metadata. metadata: Optional[Dict[str, Any]] = None #: new keyboard that will be used for new message. keyboard: Optional[KeyboardMarkup] = None #: new bubble elements that will be showed under new message. bubble: Optional[BubbleMarkup] = None #: new mentions that BotX API will append before new message text. mentions: Optional[List[Mention]] = None class InternalBotNotificationPayload(BaseModel): """Data that is sent in internal bot notification.""" #: message data message: str #: extra information about notification sender sender: Optional[str]
en
0.732331
Shape that is used for messages from bot. # noqa: WPS433 # type: ignore # noqa: WPS433, WPS440, F401 Data that is sent when bot answers on command or send notification. #: status of operation. #: body for new message from bot. #: message metadata. #: options for `notification` and `command_result` API entities. #: keyboard that will be used for new message. #: bubble elements that will be showed under new message. #: mentions that BotX API will append before new message text. Data that is sent when bot updates message. #: status of operation. #: new body in message. #: message metadata. #: new keyboard that will be used for new message. #: new bubble elements that will be showed under new message. #: new mentions that BotX API will append before new message text. Data that is sent in internal bot notification. #: message data #: extra information about notification sender
2.777603
3
array.py
EdgarMoncloa/Algorithm_Genetic_Gecademica
0
6614307
<reponame>EdgarMoncloa/Algorithm_Genetic_Gecademica import random import time num_parameters = 4 num_populations = 5 num_classes = 100 num_subject_matters = 80 num_classrooms = 28 num_horaries = 5 num_teachers = 60 min_value = 1 pressure = 3 # individuos que se seleccionan para reporduccion mutation_probability = .50 def create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries): asigned_class = [] asigned_class.append(random.randint(min_value, num_subject_matters)) asigned_class.append(random.randint(min_value, num_classrooms)) asigned_class.append(random.randint(min_value, num_horaries)) asigned_class.append(random.randint(min_value, num_teachers)) return asigned_class def create_individual( num_teachers, num_classrooms, num_subject_matters, num_horaries): individual = [] for idx in range(0, num_classes): individual.append(create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries )) return individual def create_population(): return [create_individual( num_teachers, num_classrooms, num_subject_matters, num_horaries ) for i in range(0, num_populations)] def fitness_calculate(individual): fitness = 0 for idx_element, element in enumerate(individual): individual_compare = individual.copy() individual_compare.pop(idx_element) for compare_element in individual_compare: for idx in range(0, num_parameters): if element[idx] == compare_element[idx]: fitness -= 1 if fitness == 0 : print("-----------------------------------------------------FITNES 0") print(individual) quit() return fitness def selection_and_reproduction(population): population_punctuated = [ (fitness_calculate(element), element)for element in population] population_punctuated = [ element[1] for element in sorted(population_punctuated)] population = population_punctuated.copy() population_punctuated = population_punctuated[(len(population)-pressure):] # Mix for idx in range(len(population)-pressure): # Select one point to cut the individual cut_point = random.randint(1, num_classes) # Select two parents parents = random.sample(population_punctuated, 2) # Mix genetic material population[idx][:cut_point] = parents[0][:cut_point] population[idx][cut_point:] = parents[1][cut_point:] return population def mutation(population): for idx in range(len(population)-pressure): if random.random() <= mutation_probability: cut_point = random.randint(0, num_classes-1) new_class = create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries ) while(new_class == population[idx][cut_point]): new_class = create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries ) population[idx][cut_point]=new_class return population def print_data(population): print("VALORES") for element in population: print(element) print("FITNESS") for idx,element in enumerate(population): print("{} : {}".format(idx,fitness_calculate(element))) return start_time = time.time() # Create First population population = create_population() # Print # print('-----> PRIMERA POBLACION <-----') # print_data(population) # Algorithm for i in range(100000): # Selection and rerpoduction if i % 1000 == 0: print('----------{}-----------------'.format(i)) population = selection_and_reproduction(population) population = mutation(population) # Last population print('-----> ULTIMA POBLACION <-----') # print_data(population) # print('(---------{}--------------)'.format(time.time-start_time))
import random import time num_parameters = 4 num_populations = 5 num_classes = 100 num_subject_matters = 80 num_classrooms = 28 num_horaries = 5 num_teachers = 60 min_value = 1 pressure = 3 # individuos que se seleccionan para reporduccion mutation_probability = .50 def create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries): asigned_class = [] asigned_class.append(random.randint(min_value, num_subject_matters)) asigned_class.append(random.randint(min_value, num_classrooms)) asigned_class.append(random.randint(min_value, num_horaries)) asigned_class.append(random.randint(min_value, num_teachers)) return asigned_class def create_individual( num_teachers, num_classrooms, num_subject_matters, num_horaries): individual = [] for idx in range(0, num_classes): individual.append(create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries )) return individual def create_population(): return [create_individual( num_teachers, num_classrooms, num_subject_matters, num_horaries ) for i in range(0, num_populations)] def fitness_calculate(individual): fitness = 0 for idx_element, element in enumerate(individual): individual_compare = individual.copy() individual_compare.pop(idx_element) for compare_element in individual_compare: for idx in range(0, num_parameters): if element[idx] == compare_element[idx]: fitness -= 1 if fitness == 0 : print("-----------------------------------------------------FITNES 0") print(individual) quit() return fitness def selection_and_reproduction(population): population_punctuated = [ (fitness_calculate(element), element)for element in population] population_punctuated = [ element[1] for element in sorted(population_punctuated)] population = population_punctuated.copy() population_punctuated = population_punctuated[(len(population)-pressure):] # Mix for idx in range(len(population)-pressure): # Select one point to cut the individual cut_point = random.randint(1, num_classes) # Select two parents parents = random.sample(population_punctuated, 2) # Mix genetic material population[idx][:cut_point] = parents[0][:cut_point] population[idx][cut_point:] = parents[1][cut_point:] return population def mutation(population): for idx in range(len(population)-pressure): if random.random() <= mutation_probability: cut_point = random.randint(0, num_classes-1) new_class = create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries ) while(new_class == population[idx][cut_point]): new_class = create_class( num_teachers, num_classrooms, num_subject_matters, num_horaries ) population[idx][cut_point]=new_class return population def print_data(population): print("VALORES") for element in population: print(element) print("FITNESS") for idx,element in enumerate(population): print("{} : {}".format(idx,fitness_calculate(element))) return start_time = time.time() # Create First population population = create_population() # Print # print('-----> PRIMERA POBLACION <-----') # print_data(population) # Algorithm for i in range(100000): # Selection and rerpoduction if i % 1000 == 0: print('----------{}-----------------'.format(i)) population = selection_and_reproduction(population) population = mutation(population) # Last population print('-----> ULTIMA POBLACION <-----') # print_data(population) # print('(---------{}--------------)'.format(time.time-start_time))
en
0.382077
# individuos que se seleccionan para reporduccion # Mix # Select one point to cut the individual # Select two parents # Mix genetic material # Create First population # Print # print('-----> PRIMERA POBLACION <-----') # print_data(population) # Algorithm # Selection and rerpoduction # Last population # print_data(population) # print('(---------{}--------------)'.format(time.time-start_time))
3.20634
3
models/generator.py
martinoywa/creative-gan
2
6614308
<filename>models/generator.py import torch import torch.nn as nn from pathlib import Path # number of color channels in the input images. For color images this is 3 nc = 3 # length of latent vector z nz = 100 # Size of feature maps in generator ngf = 64 class Generator(nn.Module): def __init__(self): super(Generator, self).__init__() self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.ReLU(True), # state size. (ngf*8) x 4 x 4 nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.ReLU(True), # state size. (ngf*4) x 8 x 8 nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.ReLU(True), # state size. (ngf*2) x 16 x 16 nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), # state size. (ngf) x 32 x 32 nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False), nn.Tanh() # state size. (nc) x 64 x 64 ) def forward(self, input): return self.main(input) # weight initialization def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) # generator mode G = Generator() # apply the weights_init function to randomly initialize all weights # to mean=0, stdev=0.2. G.apply(weights_init) # loading the trained model checkpoint = Path('models/checkpoints/cars-0.0.6-Monday.pt') G.load_state_dict(torch.load(checkpoint, map_location='cpu')) def generate(latent_vector): # fake image with torch.no_grad(): fake = G(latent_vector)#.detach().cpu() return fake
<filename>models/generator.py import torch import torch.nn as nn from pathlib import Path # number of color channels in the input images. For color images this is 3 nc = 3 # length of latent vector z nz = 100 # Size of feature maps in generator ngf = 64 class Generator(nn.Module): def __init__(self): super(Generator, self).__init__() self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.ReLU(True), # state size. (ngf*8) x 4 x 4 nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.ReLU(True), # state size. (ngf*4) x 8 x 8 nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.ReLU(True), # state size. (ngf*2) x 16 x 16 nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), # state size. (ngf) x 32 x 32 nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False), nn.Tanh() # state size. (nc) x 64 x 64 ) def forward(self, input): return self.main(input) # weight initialization def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) # generator mode G = Generator() # apply the weights_init function to randomly initialize all weights # to mean=0, stdev=0.2. G.apply(weights_init) # loading the trained model checkpoint = Path('models/checkpoints/cars-0.0.6-Monday.pt') G.load_state_dict(torch.load(checkpoint, map_location='cpu')) def generate(latent_vector): # fake image with torch.no_grad(): fake = G(latent_vector)#.detach().cpu() return fake
en
0.674383
# number of color channels in the input images. For color images this is 3 # length of latent vector z # Size of feature maps in generator # input is Z, going into a convolution # state size. (ngf*8) x 4 x 4 # state size. (ngf*4) x 8 x 8 # state size. (ngf*2) x 16 x 16 # state size. (ngf) x 32 x 32 # state size. (nc) x 64 x 64 # weight initialization # generator mode # apply the weights_init function to randomly initialize all weights # to mean=0, stdev=0.2. # loading the trained model # fake image #.detach().cpu()
2.56986
3
cloudops_setup.py
wfclark/emrg
0
6614309
import urllib2 import datetime import time import psycopg2 from subprocess import call, Popen import os os.system('sudo apt-get update') os.system('sudo apt-get install apache2') os.system('sudo apt-get build-dep build-essential') os.system('sudo apt-get install lamp-server') os.system('sudo wget -qO- https://apt.boundlessgeo.com/gpg.key | apt-key add -') os.system('sudo echo "deb https://apt.boundlessgeo.com/suite/latest/ubuntu/ trusty main" > /etc/apt/sources.list.d/opengeo.list') os.system('sudo apt-get update') os.system('apt-cache search opengeo') os.system('sudo apt-get install opengeo') os.system("sudo sh -c "echo 'ProxyPassReverse /geoexplorer http://localhost:8080/geoexplorer' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /geoeditor http://localhost:8080/geoeditor' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPassReverse /geoeditor http://localhost:8080/geoeditor' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /geowebcache http://localhost:8080/geowebcache' >> /etc/apache2/sites-available/000-default.conf"") os.sytem("sudo sh -c "echo 'ProxyPassReverse /geowebcache http://localhost:8080/geowebcache' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /dashboard http://localhost:8080/dashboard' >> /etc/apache2/sites-available/000-default.conf"" os.system("sudo sh -c "echo 'ProxyPassReverse /dashboard http://localhost:8080/dashboard' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /recipes http://localhost:8080/recipes' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPassReverse /recipes http://localhost:8080/recipes' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /opengeo-docs http://localhost:8080/opengeo-docs' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPassReverse /opengeo-docs http://localhost:8080/opengeo-docs' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo ' ' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo '</VirtualHost>' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo chmod -R 755 /var/www") os.system("sudo service apache2 restart")
import urllib2 import datetime import time import psycopg2 from subprocess import call, Popen import os os.system('sudo apt-get update') os.system('sudo apt-get install apache2') os.system('sudo apt-get build-dep build-essential') os.system('sudo apt-get install lamp-server') os.system('sudo wget -qO- https://apt.boundlessgeo.com/gpg.key | apt-key add -') os.system('sudo echo "deb https://apt.boundlessgeo.com/suite/latest/ubuntu/ trusty main" > /etc/apt/sources.list.d/opengeo.list') os.system('sudo apt-get update') os.system('apt-cache search opengeo') os.system('sudo apt-get install opengeo') os.system("sudo sh -c "echo 'ProxyPassReverse /geoexplorer http://localhost:8080/geoexplorer' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /geoeditor http://localhost:8080/geoeditor' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPassReverse /geoeditor http://localhost:8080/geoeditor' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /geowebcache http://localhost:8080/geowebcache' >> /etc/apache2/sites-available/000-default.conf"") os.sytem("sudo sh -c "echo 'ProxyPassReverse /geowebcache http://localhost:8080/geowebcache' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /dashboard http://localhost:8080/dashboard' >> /etc/apache2/sites-available/000-default.conf"" os.system("sudo sh -c "echo 'ProxyPassReverse /dashboard http://localhost:8080/dashboard' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /recipes http://localhost:8080/recipes' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPassReverse /recipes http://localhost:8080/recipes' >>/etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPass /opengeo-docs http://localhost:8080/opengeo-docs' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo 'ProxyPassReverse /opengeo-docs http://localhost:8080/opengeo-docs' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo ' ' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo sh -c "echo '</VirtualHost>' >> /etc/apache2/sites-available/000-default.conf"") os.system("sudo chmod -R 755 /var/www") os.system("sudo service apache2 restart")
none
1
2.557209
3
mmflow/datasets/samplers/distributed_sampler.py
open-mmlab/mmflow
481
6614310
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Iterator, Optional, Sequence import torch import torch.distributed as dist from torch.utils.data import Dataset from torch.utils.data import DistributedSampler as _DistributedSampler from torch.utils.data import Sampler from mmflow.core.utils import sync_random_seed class DistributedSampler(_DistributedSampler): """DistributedSampler inheriting from `torch.utils.data.DistributedSampler`. This distributed sampler is compatible Pytorch==1.5, as there is no `seed` argument in Pytorch==1.5. Args: datasets (Dataset): the dataset will be loaded. num_replicas (int, optional): Number of processes participating in distributed training. By default, world_size is retrieved from the current distributed group. rank (int, optional): Rank of the current process within num_replicas. By default, rank is retrieved from the current distributed group. shuffle (bool): If True (default), sampler will shuffle the indices. seed (int): random seed used to shuffle the sampler if :attr:`shuffle=True`. This number should be identical across all processes in the distributed group. Default: ``0``. """ def __init__(self, dataset: Dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed=0) -> None: super().__init__( dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle) # In distributed sampling, different ranks should sample # non-overlapped data in the dataset. Therefore, this function # is used to make sure that each rank shuffles the data indices # in the same order based on the same seed. Then different # ranks could use different indices to select non-overlapped # data from the same data list. self.seed = sync_random_seed(seed) def __iter__(self) -> Iterator: """ Yields: Iterator: iterator of indices for rank. """ # deterministically shuffle based on epoch if self.shuffle: g = torch.Generator() # When :attr:`shuffle=True`, this ensures all replicas # use a different random ordering for each epoch. # Otherwise, the next iteration of this sampler will # yield the same ordering. g.manual_seed(self.epoch + self.seed) indices = torch.randperm(len(self.dataset), generator=g).tolist() else: indices = torch.arange(len(self.dataset)).tolist() # add extra samples to make it evenly divisible indices += indices[:(self.total_size - len(indices))] assert len(indices) == self.total_size # subsample indices = indices[self.rank:self.total_size:self.num_replicas] assert len(indices) == self.num_samples return iter(indices) class MixedBatchDistributedSampler(Sampler): """Distributed Sampler for mixed data batch. Args: datasets (list): List of datasets will be loaded. sample_ratio (list): List of the ratio of each dataset in a batch, e.g. datasets=[DatasetA, DatasetB], sample_ratio=[0.25, 0.75], sample_per_gpu=1, gpus=8, it means 2 gpus load DatasetA, and 6 gpus load DatasetB. The length of datasets must be equal to length of sample_ratio. num_replicas (int, optional): Number of processes participating in distributed training. By default, world_size is retrieved from the current distributed group. rank (int, optional): Rank of the current process within num_replicas. By default, rank is retrieved from the current distributed group. shuffle (bool): If True (default), sampler will shuffle the indices. seed (int): random seed used to shuffle the sampler if :attr:`shuffle=True`. This number should be identical across all processes in the distributed group. Default: ``0``. """ def __init__(self, datasets: Sequence[Dataset], sample_ratio: Sequence[float], num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0) -> None: # base class `Sampler` do nothing in `__init__` function # super().__init__() assert len(datasets) == len(sample_ratio) assert sum(sample_ratio) == 1. if num_replicas is None: if not dist.is_available(): raise RuntimeError( 'Requires distributed package to be available') num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError( 'Requires distributed package to be available') rank = dist.get_rank() if rank >= num_replicas or rank < 0: raise ValueError( f'Invalid rank {rank}, rank should be in the interval' f' [0, {num_replicas - 1}]') self.datasets = datasets self.num_replicas = num_replicas self.datasets_num_replicas = [ math.ceil(num_replicas * r) for r in sample_ratio ] self.cumulative_replicas = [] t = 0 for nr in self.datasets_num_replicas: t += nr self.cumulative_replicas.append(t) self.datasets_length = [len(d) for d in datasets] self.cumulative_datasets_length = [] t = 0 for dl in self.datasets_length: t += dl self.cumulative_datasets_length.append(t) # the smallest num_sample self.datasets_num_samples = [ math.ceil(length / ratio) for length, ratio in zip( self.datasets_length, self.datasets_num_replicas) ] self.num_samples = min(self.datasets_num_samples) # the dataset that decides the num_samples and total_size self.key_dataset = self.datasets_num_samples.index(self.num_samples) self.key_dataset_length = self.datasets_length[self.key_dataset] self.total_size = [ self.num_samples * nr for nr in self.datasets_num_replicas ] self.rank = rank self.epoch = 0 self.shuffle = shuffle # In distributed sampling, different ranks should sample # non-overlapped data in the dataset. Therefore, this function # is used to make sure that each rank shuffles the data indices # in the same order based on the same seed. Then different # ranks could use different indices to select non-overlapped # data from the same data list. self.seed = sync_random_seed(seed) def __iter__(self) -> Iterator: """ Yields: Iterator: iterator of indices for current rank. """ # datasets map different rank for dataset_idx, cumulative_replicas_ in enumerate( self.cumulative_replicas): if self.rank < cumulative_replicas_: break # deterministically shuffle each datasets based on epoch if self.shuffle: g = torch.Generator() # When :attr:`shuffle=True`, this ensures all replicas # use a different random ordering for each epoch. # Otherwise, the next iteration of this sampler will # yield the same ordering. g.manual_seed(self.epoch + self.seed) indices = torch.randperm( self.datasets_length[dataset_idx], generator=g).tolist() else: indices = torch.arange(self.datasets_length[dataset_idx]).tolist() if self.total_size[dataset_idx] > len(indices): # add extra samples for key_dataset to make it evenly divisible indices += indices[:(self.total_size[dataset_idx] - len(indices))] else: indices = indices[:self.total_size[dataset_idx]] assert len(indices) == self.total_size[dataset_idx] # subsample last_cumulative_replicas = 0 \ if dataset_idx == 0 else self.cumulative_replicas[dataset_idx - 1] indices = indices[( self.rank - last_cumulative_replicas ):self.total_size[dataset_idx]:self.datasets_num_replicas[dataset_idx]] assert len(indices) == self.num_samples # find the dataset for this rank last_cumulative_length = 0 \ if dataset_idx == 0 else \ self.cumulative_datasets_length[dataset_idx-1] indices = [idx + last_cumulative_length for idx in indices] return iter(indices) def __len__(self) -> int: """Get the combined dataset length.""" return self.num_samples def set_epoch(self, epoch: int) -> None: r""" Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas use a different random ordering for each epoch. Otherwise, the next iteration of this sampler will yield the same ordering. Arguments: epoch (int): Epoch number. """ self.epoch = epoch
# Copyright (c) OpenMMLab. All rights reserved. import math from typing import Iterator, Optional, Sequence import torch import torch.distributed as dist from torch.utils.data import Dataset from torch.utils.data import DistributedSampler as _DistributedSampler from torch.utils.data import Sampler from mmflow.core.utils import sync_random_seed class DistributedSampler(_DistributedSampler): """DistributedSampler inheriting from `torch.utils.data.DistributedSampler`. This distributed sampler is compatible Pytorch==1.5, as there is no `seed` argument in Pytorch==1.5. Args: datasets (Dataset): the dataset will be loaded. num_replicas (int, optional): Number of processes participating in distributed training. By default, world_size is retrieved from the current distributed group. rank (int, optional): Rank of the current process within num_replicas. By default, rank is retrieved from the current distributed group. shuffle (bool): If True (default), sampler will shuffle the indices. seed (int): random seed used to shuffle the sampler if :attr:`shuffle=True`. This number should be identical across all processes in the distributed group. Default: ``0``. """ def __init__(self, dataset: Dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed=0) -> None: super().__init__( dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle) # In distributed sampling, different ranks should sample # non-overlapped data in the dataset. Therefore, this function # is used to make sure that each rank shuffles the data indices # in the same order based on the same seed. Then different # ranks could use different indices to select non-overlapped # data from the same data list. self.seed = sync_random_seed(seed) def __iter__(self) -> Iterator: """ Yields: Iterator: iterator of indices for rank. """ # deterministically shuffle based on epoch if self.shuffle: g = torch.Generator() # When :attr:`shuffle=True`, this ensures all replicas # use a different random ordering for each epoch. # Otherwise, the next iteration of this sampler will # yield the same ordering. g.manual_seed(self.epoch + self.seed) indices = torch.randperm(len(self.dataset), generator=g).tolist() else: indices = torch.arange(len(self.dataset)).tolist() # add extra samples to make it evenly divisible indices += indices[:(self.total_size - len(indices))] assert len(indices) == self.total_size # subsample indices = indices[self.rank:self.total_size:self.num_replicas] assert len(indices) == self.num_samples return iter(indices) class MixedBatchDistributedSampler(Sampler): """Distributed Sampler for mixed data batch. Args: datasets (list): List of datasets will be loaded. sample_ratio (list): List of the ratio of each dataset in a batch, e.g. datasets=[DatasetA, DatasetB], sample_ratio=[0.25, 0.75], sample_per_gpu=1, gpus=8, it means 2 gpus load DatasetA, and 6 gpus load DatasetB. The length of datasets must be equal to length of sample_ratio. num_replicas (int, optional): Number of processes participating in distributed training. By default, world_size is retrieved from the current distributed group. rank (int, optional): Rank of the current process within num_replicas. By default, rank is retrieved from the current distributed group. shuffle (bool): If True (default), sampler will shuffle the indices. seed (int): random seed used to shuffle the sampler if :attr:`shuffle=True`. This number should be identical across all processes in the distributed group. Default: ``0``. """ def __init__(self, datasets: Sequence[Dataset], sample_ratio: Sequence[float], num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0) -> None: # base class `Sampler` do nothing in `__init__` function # super().__init__() assert len(datasets) == len(sample_ratio) assert sum(sample_ratio) == 1. if num_replicas is None: if not dist.is_available(): raise RuntimeError( 'Requires distributed package to be available') num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError( 'Requires distributed package to be available') rank = dist.get_rank() if rank >= num_replicas or rank < 0: raise ValueError( f'Invalid rank {rank}, rank should be in the interval' f' [0, {num_replicas - 1}]') self.datasets = datasets self.num_replicas = num_replicas self.datasets_num_replicas = [ math.ceil(num_replicas * r) for r in sample_ratio ] self.cumulative_replicas = [] t = 0 for nr in self.datasets_num_replicas: t += nr self.cumulative_replicas.append(t) self.datasets_length = [len(d) for d in datasets] self.cumulative_datasets_length = [] t = 0 for dl in self.datasets_length: t += dl self.cumulative_datasets_length.append(t) # the smallest num_sample self.datasets_num_samples = [ math.ceil(length / ratio) for length, ratio in zip( self.datasets_length, self.datasets_num_replicas) ] self.num_samples = min(self.datasets_num_samples) # the dataset that decides the num_samples and total_size self.key_dataset = self.datasets_num_samples.index(self.num_samples) self.key_dataset_length = self.datasets_length[self.key_dataset] self.total_size = [ self.num_samples * nr for nr in self.datasets_num_replicas ] self.rank = rank self.epoch = 0 self.shuffle = shuffle # In distributed sampling, different ranks should sample # non-overlapped data in the dataset. Therefore, this function # is used to make sure that each rank shuffles the data indices # in the same order based on the same seed. Then different # ranks could use different indices to select non-overlapped # data from the same data list. self.seed = sync_random_seed(seed) def __iter__(self) -> Iterator: """ Yields: Iterator: iterator of indices for current rank. """ # datasets map different rank for dataset_idx, cumulative_replicas_ in enumerate( self.cumulative_replicas): if self.rank < cumulative_replicas_: break # deterministically shuffle each datasets based on epoch if self.shuffle: g = torch.Generator() # When :attr:`shuffle=True`, this ensures all replicas # use a different random ordering for each epoch. # Otherwise, the next iteration of this sampler will # yield the same ordering. g.manual_seed(self.epoch + self.seed) indices = torch.randperm( self.datasets_length[dataset_idx], generator=g).tolist() else: indices = torch.arange(self.datasets_length[dataset_idx]).tolist() if self.total_size[dataset_idx] > len(indices): # add extra samples for key_dataset to make it evenly divisible indices += indices[:(self.total_size[dataset_idx] - len(indices))] else: indices = indices[:self.total_size[dataset_idx]] assert len(indices) == self.total_size[dataset_idx] # subsample last_cumulative_replicas = 0 \ if dataset_idx == 0 else self.cumulative_replicas[dataset_idx - 1] indices = indices[( self.rank - last_cumulative_replicas ):self.total_size[dataset_idx]:self.datasets_num_replicas[dataset_idx]] assert len(indices) == self.num_samples # find the dataset for this rank last_cumulative_length = 0 \ if dataset_idx == 0 else \ self.cumulative_datasets_length[dataset_idx-1] indices = [idx + last_cumulative_length for idx in indices] return iter(indices) def __len__(self) -> int: """Get the combined dataset length.""" return self.num_samples def set_epoch(self, epoch: int) -> None: r""" Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas use a different random ordering for each epoch. Otherwise, the next iteration of this sampler will yield the same ordering. Arguments: epoch (int): Epoch number. """ self.epoch = epoch
en
0.772394
# Copyright (c) OpenMMLab. All rights reserved. DistributedSampler inheriting from `torch.utils.data.DistributedSampler`. This distributed sampler is compatible Pytorch==1.5, as there is no `seed` argument in Pytorch==1.5. Args: datasets (Dataset): the dataset will be loaded. num_replicas (int, optional): Number of processes participating in distributed training. By default, world_size is retrieved from the current distributed group. rank (int, optional): Rank of the current process within num_replicas. By default, rank is retrieved from the current distributed group. shuffle (bool): If True (default), sampler will shuffle the indices. seed (int): random seed used to shuffle the sampler if :attr:`shuffle=True`. This number should be identical across all processes in the distributed group. Default: ``0``. # In distributed sampling, different ranks should sample # non-overlapped data in the dataset. Therefore, this function # is used to make sure that each rank shuffles the data indices # in the same order based on the same seed. Then different # ranks could use different indices to select non-overlapped # data from the same data list. Yields: Iterator: iterator of indices for rank. # deterministically shuffle based on epoch # When :attr:`shuffle=True`, this ensures all replicas # use a different random ordering for each epoch. # Otherwise, the next iteration of this sampler will # yield the same ordering. # add extra samples to make it evenly divisible # subsample Distributed Sampler for mixed data batch. Args: datasets (list): List of datasets will be loaded. sample_ratio (list): List of the ratio of each dataset in a batch, e.g. datasets=[DatasetA, DatasetB], sample_ratio=[0.25, 0.75], sample_per_gpu=1, gpus=8, it means 2 gpus load DatasetA, and 6 gpus load DatasetB. The length of datasets must be equal to length of sample_ratio. num_replicas (int, optional): Number of processes participating in distributed training. By default, world_size is retrieved from the current distributed group. rank (int, optional): Rank of the current process within num_replicas. By default, rank is retrieved from the current distributed group. shuffle (bool): If True (default), sampler will shuffle the indices. seed (int): random seed used to shuffle the sampler if :attr:`shuffle=True`. This number should be identical across all processes in the distributed group. Default: ``0``. # base class `Sampler` do nothing in `__init__` function # super().__init__() # the smallest num_sample # the dataset that decides the num_samples and total_size # In distributed sampling, different ranks should sample # non-overlapped data in the dataset. Therefore, this function # is used to make sure that each rank shuffles the data indices # in the same order based on the same seed. Then different # ranks could use different indices to select non-overlapped # data from the same data list. Yields: Iterator: iterator of indices for current rank. # datasets map different rank # deterministically shuffle each datasets based on epoch # When :attr:`shuffle=True`, this ensures all replicas # use a different random ordering for each epoch. # Otherwise, the next iteration of this sampler will # yield the same ordering. # add extra samples for key_dataset to make it evenly divisible # subsample # find the dataset for this rank Get the combined dataset length. Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas use a different random ordering for each epoch. Otherwise, the next iteration of this sampler will yield the same ordering. Arguments: epoch (int): Epoch number.
2.727302
3
frozen_lake/q_learning.py
elton-choi/rl-tutorial
0
6614311
<filename>frozen_lake/q_learning.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import gym from time import sleep import math class QLearning: def __init__(self, env, alpha=0.1, gamma=0.8, epsilon=0.1): self.env = env self.alpha = alpha self.gamma = gamma self.epsilon = epsilon self.n_state = env.observation_space.n self.n_action = env.action_space.n self.q_table = np.zeros((self.n_state, self.n_action)) self.S = np.arange(self.n_state) self.A = np.arange(self.n_action) self.str_a = ['LEFT', 'DOWN', 'RIGHT', 'UP'] def explore(self, s): # epsilon-greedy if np.random.rand() < self.epsilon: a = np.random.choice(self.A) else: # greedy: 1-e a = np.argmax(self.q_table[s]) # print('s=%d, a=%s\n' % (s, self.str_a[a])) return a def learn(self, s, a, r, s_): # print('\nbefore update') # self.print_q_table() # print('\ns=%d, a=%d, r=%.2f, s_=%d'%(s, a, r, s_)) self.q_table[s][a] = (1-self.alpha)*self.q_table[s][a] + self.alpha * ( r + self.gamma * np.max(self.q_table[s_]) - self.q_table[s][a] ) # print('\nafter q table') # self.print_q_table() # temp = input('Go next?') # print('----\n') def print_q_table(self): print('q_table') print('action = LEFT, DOWN, RIGHT, UP') for state in range(self.n_state): for action in range(self.n_action): if action == self.n_action - 1: print('%.1f ' % self.q_table[state][action], end='') else: print('%.1f, ' % self.q_table[state][action], end='') print('| ', end='') n_square = np.sqrt(self.n_state) if state % n_square == n_square-1: print('') def run_episode(self, render = False, key = False, wait = 0.0): obs = self.env.reset() total_reward = 0 step_idx = 0 while True: if render: self.env.render() if key: temp_key = input('') elif wait > 0.0: sleep(wait) a = self.explore(obs) next_obs, reward, done , _ = self.env.step(a) # print('obs = %d, a = %d, next_obs = %d\n'%(obs, a, next_obs)) # temp_key = input('') obs = next_obs # total_reward += (self.gamma ** step_idx * reward) total_reward += (reward) step_idx += 1 if done: break return (step_idx, reward, total_reward) if __name__ == '__main__': # env = gym.make("FrozenLake-v0") env = gym.make("FrozenLake8x8-v0") agent = QLearning(env, alpha=0.8, gamma=0.9, epsilon=0.2) # before learning step_idx, reward, total_reward = agent.run_episode(render=False) print('Run episode before learning') print('Total reward is %.3f\n\n' % total_reward) # q learning for i in range(10000): obs = env.reset() t=1 t_list = [] action_list = [] reward_list = [] obs_list = [] while True: # env.render() action = agent.explore(obs) # epsilon greedy next_obs, reward, done, info = env.step(action) obs_list.append(obs) action_list.append(action) if done: if reward == 0: reward = -1 reward_list.append(reward) agent.learn(obs, action, reward, next_obs) # q-learning t_list.append(t) if reward == 1: print("%dth Episode finished after %d timesteps with average reward %.3f" % (i+1, t, sum(reward_list)/t)) print("Observation list = {}".format(obs_list)) print("Action list = {}".format(action_list)) break else: if reward == 0: reward = -0.1 reward_list.append(reward) agent.learn(obs, action, reward, next_obs) # q-learning obs = next_obs t=t+1 agent.print_q_table() print("Shortest time step to reach a goal is %d"%min(t_list)) input('Next?') reward_list = [] step_list = [] n_episode = 1000 agent.epsilon = 0.0 for i in range(n_episode): (step_idx, reward, total_reward) = agent.run_episode(render=True) reward_list.append(total_reward) if reward == 1: step_list.append(step_idx) print("%dth episode finished at %d step with total reward %.3f" % (i, step_idx, total_reward)) input('Next?') print('\nRun episodes(%d) after learning' % n_episode) print('Total reward average is %.3f' % (sum(reward_list)/n_episode)) print('Shortest time step is %d' % min(step_list))
<filename>frozen_lake/q_learning.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import gym from time import sleep import math class QLearning: def __init__(self, env, alpha=0.1, gamma=0.8, epsilon=0.1): self.env = env self.alpha = alpha self.gamma = gamma self.epsilon = epsilon self.n_state = env.observation_space.n self.n_action = env.action_space.n self.q_table = np.zeros((self.n_state, self.n_action)) self.S = np.arange(self.n_state) self.A = np.arange(self.n_action) self.str_a = ['LEFT', 'DOWN', 'RIGHT', 'UP'] def explore(self, s): # epsilon-greedy if np.random.rand() < self.epsilon: a = np.random.choice(self.A) else: # greedy: 1-e a = np.argmax(self.q_table[s]) # print('s=%d, a=%s\n' % (s, self.str_a[a])) return a def learn(self, s, a, r, s_): # print('\nbefore update') # self.print_q_table() # print('\ns=%d, a=%d, r=%.2f, s_=%d'%(s, a, r, s_)) self.q_table[s][a] = (1-self.alpha)*self.q_table[s][a] + self.alpha * ( r + self.gamma * np.max(self.q_table[s_]) - self.q_table[s][a] ) # print('\nafter q table') # self.print_q_table() # temp = input('Go next?') # print('----\n') def print_q_table(self): print('q_table') print('action = LEFT, DOWN, RIGHT, UP') for state in range(self.n_state): for action in range(self.n_action): if action == self.n_action - 1: print('%.1f ' % self.q_table[state][action], end='') else: print('%.1f, ' % self.q_table[state][action], end='') print('| ', end='') n_square = np.sqrt(self.n_state) if state % n_square == n_square-1: print('') def run_episode(self, render = False, key = False, wait = 0.0): obs = self.env.reset() total_reward = 0 step_idx = 0 while True: if render: self.env.render() if key: temp_key = input('') elif wait > 0.0: sleep(wait) a = self.explore(obs) next_obs, reward, done , _ = self.env.step(a) # print('obs = %d, a = %d, next_obs = %d\n'%(obs, a, next_obs)) # temp_key = input('') obs = next_obs # total_reward += (self.gamma ** step_idx * reward) total_reward += (reward) step_idx += 1 if done: break return (step_idx, reward, total_reward) if __name__ == '__main__': # env = gym.make("FrozenLake-v0") env = gym.make("FrozenLake8x8-v0") agent = QLearning(env, alpha=0.8, gamma=0.9, epsilon=0.2) # before learning step_idx, reward, total_reward = agent.run_episode(render=False) print('Run episode before learning') print('Total reward is %.3f\n\n' % total_reward) # q learning for i in range(10000): obs = env.reset() t=1 t_list = [] action_list = [] reward_list = [] obs_list = [] while True: # env.render() action = agent.explore(obs) # epsilon greedy next_obs, reward, done, info = env.step(action) obs_list.append(obs) action_list.append(action) if done: if reward == 0: reward = -1 reward_list.append(reward) agent.learn(obs, action, reward, next_obs) # q-learning t_list.append(t) if reward == 1: print("%dth Episode finished after %d timesteps with average reward %.3f" % (i+1, t, sum(reward_list)/t)) print("Observation list = {}".format(obs_list)) print("Action list = {}".format(action_list)) break else: if reward == 0: reward = -0.1 reward_list.append(reward) agent.learn(obs, action, reward, next_obs) # q-learning obs = next_obs t=t+1 agent.print_q_table() print("Shortest time step to reach a goal is %d"%min(t_list)) input('Next?') reward_list = [] step_list = [] n_episode = 1000 agent.epsilon = 0.0 for i in range(n_episode): (step_idx, reward, total_reward) = agent.run_episode(render=True) reward_list.append(total_reward) if reward == 1: step_list.append(step_idx) print("%dth episode finished at %d step with total reward %.3f" % (i, step_idx, total_reward)) input('Next?') print('\nRun episodes(%d) after learning' % n_episode) print('Total reward average is %.3f' % (sum(reward_list)/n_episode)) print('Shortest time step is %d' % min(step_list))
en
0.329031
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # epsilon-greedy # greedy: 1-e # print('s=%d, a=%s\n' % (s, self.str_a[a])) # print('\nbefore update') # self.print_q_table() # print('\ns=%d, a=%d, r=%.2f, s_=%d'%(s, a, r, s_)) # print('\nafter q table') # self.print_q_table() # temp = input('Go next?') # print('----\n') # print('obs = %d, a = %d, next_obs = %d\n'%(obs, a, next_obs)) # temp_key = input('') # total_reward += (self.gamma ** step_idx * reward) # env = gym.make("FrozenLake-v0") # before learning # q learning # env.render() # epsilon greedy # q-learning # q-learning
3.180002
3
examples/plot_ITER_plasmas.py
fusion-energy/plasmaboundaries
4
6614312
<reponame>fusion-energy/plasmaboundaries<gh_stars>1-10 # plasma-boundaries # This script is an implementation of the method described in # “One size fits all” analytic solutions to the Grad–Shafranov equation # <NAME> and <NAME>, Physics of Plamas 17 032502 (2010) # https://doi.org/10.1063/1.3328818 import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np import plasmaboundaries # plasma parameters params = plasmaboundaries.ITER fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(10, 4.8)) for ax, config in zip( [ax1, ax2, ax3], ["non-null", "single-null", "double-null"]): # compute psi psi = plasmaboundaries.compute_psi(params, config=config) # plot the results xmin, xmax = 0.6, 1.35 ymin, ymax = -0.8, 0.7 x = np.arange(xmin, xmax, step=0.01) y = np.arange(ymin, ymax, step=0.01) X, Y = np.meshgrid(x, y) Z = psi(X, Y) # compute magnetic flux # add filled contours levels2 = np.unique(np.linspace(Z.min(), -Z.min(), num=100)) norm = mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=-Z.min()) CSF = ax.contourf( X, Y, Z, levels=levels2, cmap="coolwarm", norm=norm, vmax=-Z.min(), extend="max") # add contours levels = np.unique( np.append( np.linspace(Z.min(), 0, num=10), np.linspace(0, Z.max(), num=20))) CS = ax.contour( X, Y, Z, levels=levels[levels != 0], colors="black", linestyles="solid") separatrix = ax.contour( X, Y, Z, levels=[0], colors="black", linestyles="dashed") ax.clabel(separatrix, inline=True, fmt=r"$\Psi = $%.0f") ax.set_title('ITER ' + config) ax.set_xlabel('Radius $R/R_0$') ax.set_aspect("equal") ax1.set_ylabel('Height $Z/R_0$') plt.colorbar(CSF, label="Magnetic flux $\Psi$", format="%.3f") plt.show()
# plasma-boundaries # This script is an implementation of the method described in # “One size fits all” analytic solutions to the Grad–Shafranov equation # <NAME> and <NAME>, Physics of Plamas 17 032502 (2010) # https://doi.org/10.1063/1.3328818 import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np import plasmaboundaries # plasma parameters params = plasmaboundaries.ITER fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(10, 4.8)) for ax, config in zip( [ax1, ax2, ax3], ["non-null", "single-null", "double-null"]): # compute psi psi = plasmaboundaries.compute_psi(params, config=config) # plot the results xmin, xmax = 0.6, 1.35 ymin, ymax = -0.8, 0.7 x = np.arange(xmin, xmax, step=0.01) y = np.arange(ymin, ymax, step=0.01) X, Y = np.meshgrid(x, y) Z = psi(X, Y) # compute magnetic flux # add filled contours levels2 = np.unique(np.linspace(Z.min(), -Z.min(), num=100)) norm = mcolors.TwoSlopeNorm(vmin=Z.min(), vcenter=0., vmax=-Z.min()) CSF = ax.contourf( X, Y, Z, levels=levels2, cmap="coolwarm", norm=norm, vmax=-Z.min(), extend="max") # add contours levels = np.unique( np.append( np.linspace(Z.min(), 0, num=10), np.linspace(0, Z.max(), num=20))) CS = ax.contour( X, Y, Z, levels=levels[levels != 0], colors="black", linestyles="solid") separatrix = ax.contour( X, Y, Z, levels=[0], colors="black", linestyles="dashed") ax.clabel(separatrix, inline=True, fmt=r"$\Psi = $%.0f") ax.set_title('ITER ' + config) ax.set_xlabel('Radius $R/R_0$') ax.set_aspect("equal") ax1.set_ylabel('Height $Z/R_0$') plt.colorbar(CSF, label="Magnetic flux $\Psi$", format="%.3f") plt.show()
en
0.714658
# plasma-boundaries # This script is an implementation of the method described in # “One size fits all” analytic solutions to the Grad–Shafranov equation # <NAME> and <NAME>, Physics of Plamas 17 032502 (2010) # https://doi.org/10.1063/1.3328818 # plasma parameters # compute psi # plot the results # compute magnetic flux # add filled contours # add contours
2.298936
2
search_service/search/serializer_utils.py
digirati-co-uk/madoc-search-service
0
6614313
from django.core.validators import URLValidator from django.core.exceptions import ValidationError from django.utils.text import slugify import json from bs4 import BeautifulSoup from collections import defaultdict from ordered_set import OrderedSet from dateutil import parser import bleach import logging import itertools logger = logging.getLogger(__name__) pg_languages = [ "danish", "dutch", "english", "finnish", "french", "german", "hungarian", "italian", "norwegian", "portuguese", "romanian", "russian", "spanish", "swedish", "turkish", ] def resources_by_type(iiif, iiif_type=("Canvas",), master_resources=None): """ Iterate a Presentation API 3 manifest and produce a list of resources by type, e.g. Canvases or Annotations. """ if not master_resources: working_resources = [] else: working_resources = master_resources if (items := iiif.get("items", None)) is not None: if any([isinstance(item, list) for item in items]): resources = [c for c in itertools.chain.from_iterable(items) if c.get("type") is not None] else: resources = [c for c in items if c.get("type") is not None] filtered_resources = [r for r in resources if r.get("type") in iiif_type] if filtered_resources: working_resources += filtered_resources else: for f in resources: working_resources += resources_by_type( iiif=f, iiif_type=iiif_type, master_resources=filtered_resources ) return working_resources def iiif_to_presentationapiresourcemodel(data_dict): """ Somewhat hacky transformation of an incoming data object for the serializer into the correct format for the model """ lookup_dict = { "@id": {"model_key": "identifier", "default": None, "choices": None}, "identifier": {"model_key": "identifier", "default": None, "choices": None}, "@type": { "model_key": "type", "default": "Man", "choices": ( ("Col", "Collection"), ("Col", "sc:Collection"), ("Man", "Manifest"), ("Man", "sc:Manifest"), ("Seq", "Sequence"), ("Seq", "sc:Sequence"), ("Rng", "Range"), ("Rng", "sc:Range"), ("Cvs", "Canvas"), ("Cvs", "sc:Canvas"), ), }, "type": { "model_key": "type", "default": "Man", "choices": ( ("Col", "Collection"), ("Man", "Manifest"), ("Seq", "Sequence"), ("Rng", "Range"), ("Cvs", "Canvas"), ), }, "label": {"model_key": "label", "default": None, "choices": None}, "viewingDirection": { "model_key": "viewing_direction", "default": "l2", "choices": ( ("l2r", "left-to-right"), ("r2l", "right-to-left"), ("t2b", "top-to-bottom"), ("b2t", "bottom-to-top"), ), }, "viewingHint": { "model_key": "viewing_hint", "default": "paged", "choices": ( ("ind", "individuals"), ("pgd", "paged"), ("cnt", "continuous"), ("mpt", "multi-part"), ("npg", "non-paged"), ("top", "top"), ("fac", "facing-pages"), ), }, "description": {"model_key": "description", "default": None, "choices": None}, "attribution": {"model_key": "attribution", "default": None, "choices": None}, "license": {"model_key": "license", "default": None, "choices": None}, "metadata": {"model_key": "metadata", "default": None, "choices": None}, } return_dict = {} if data_dict.get("metadata"): if isinstance((data_dict["metadata"]), str): data_dict["metadata"] = json.load(data_dict["metadata"]) for k, v in data_dict.items(): lookup_result = lookup_dict.get(k) if lookup_result: if not lookup_result.get("choices"): return_dict[lookup_result["model_key"]] = v else: if v in [c[0] for c in lookup_result["choices"]]: return_dict[lookup_result["model_key"]] = v elif v in [c[1] for c in lookup_result["choices"]]: return_dict[lookup_result["model_key"]] = [ c[0] for c in lookup_result["choices"] if c[1] == v ][0] else: return_dict[lookup_result["model_key"]] = lookup_result.get("default") if return_dict.get("license"): val = URLValidator() try: val(return_dict["license"]) except ValidationError: del return_dict["license"] return return_dict def get_language_data(lang_code=None, langbase=None): if lang_code: if "-" in lang_code: lang_code = lang_code.split("-")[0] if len(lang_code) == 2: language_data = [x for x in langbase if x[1] == lang_code] if language_data: if language_data[0][-1].lower() in pg_languages: pg_lang = language_data[0][-1].lower() else: pg_lang = None return { "language_iso639_2": language_data[0][0], "language_iso639_1": language_data[0][1], "language_display": language_data[0][-1].lower(), "language_pg": pg_lang, } elif len(lang_code) == 3: language_data = [x for x in langbase if x[0] == lang_code] if language_data: if language_data[0][-1].lower() in pg_languages: pg_lang = language_data[0][-1].lower() else: pg_lang = None return { "language_iso639_2": language_data[0][0], "language_iso639_1": language_data[0][1], "language_display": language_data[0][-1].lower(), "language_pg": pg_lang, } return { "language_iso639_2": None, "language_iso639_1": None, "language_display": None, "language_pg": None, } def process_field( field_instance, key, default_language, lang_base, field_type="descriptive", field_indexable_type="text", ): val = None lang = default_language subtype = key field_data = [] if field_instance: if not field_instance.get("label"): # Problem here with multilanguage label field for val_lang, val in field_instance.items(): if val_lang in ["@none", "none"]: lang = default_language else: lang = val_lang if val: for v in val: v = str(v) if field_indexable_type == "text": field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable": BeautifulSoup(v, "html.parser").text, "original_content": {subtype: bleach.clean(v)}, **get_language_data(lang_code=lang, langbase=lang_base), } ) elif field_indexable_type == "date": """ This assumes a single navDate, but we translate this into a datetime range via adding two indexables. """ try: parsed_date = parser.parse(v) except ValueError: parsed_date = None if parsed_date: field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable_date_range_start": parsed_date, "indexable_date_range_end": parsed_date, "original_content": {subtype: bleach.clean(v)}, } ) else: indexable_values = [] label_values = field_instance.get("label", {}) if field_values:=field_instance.get("value"): for lang, vals in field_values.items(): if labels:= label_values.get(lang): subtype = labels[0] if lang in ["@none", "none"]: lang = default_language language_data = get_language_data(lang_code=lang, langbase=lang_base) for v in vals: if field_indexable_type == "text": field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable": BeautifulSoup(v, "html.parser").text, "original_content": {subtype: v}, **language_data, } ) elif field_indexable_type == "date": """ This assumes a single navDate, but we translate this into a datetime range via adding two indexables. """ try: parsed_date = parser.parse(v) except ValueError: parsed_date = None if parsed_date: field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable_date_range_start": parsed_date, "original_content": {subtype: v}, } ) field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable_date_range_end": parsed_date, "original_content": {subtype: v}, } ) return field_data return def flatten_iiif_descriptive(iiif, default_language=None, lang_base=None): """ Flatten the descriptive fields in a Presentation API into a list of dicts that can be passed to the Indexables model and serializers """ field_data = [] dict_fields = [ ("label", "descriptive", "text"), ("requiredStatement", "descriptive", "text"), ("summary", "descriptive", "text"), ("metadata", "metadata", "text"), ("navDate", "descriptive", "date"), ] for d in dict_fields: if iiif.get(d[0]): if isinstance(iiif[d[0]], dict): field_instances = [iiif[d[0]]] elif isinstance(iiif[d[0]], list): field_instances = iiif[d[0]] else: # This might be just a string, e.g. navDate # There is no language or label, so we just pass it through with the language set to None field_instances = [{"none": [iiif[d[0]]]}] if field_instances: for field_instance in field_instances: returned_data = process_field( field_instance=field_instance, lang_base=lang_base, default_language=default_language, key=d[0], field_type=d[1], field_indexable_type=d[2], ) if returned_data: field_data += returned_data if field_data: return field_data else: return def simplify_selector(selector): """ Simplify a selector from the OCR intermediate format or capture model format into a compact representation "selector": { "id": "0db4fdc1-73dd-4555-95da-7cbc746c980c", "state": { "height": "60", "width": "20", "x": "821", "y": "644" }, "type": "box-selector" }, Becomes (XYWH): 832,644,20,60 """ if selector: if selector.get("state"): if (selector_type := selector.get("type")) is not None: if selector_type == "box-selector": selector_list = [ selector["state"].get("x"), selector["state"].get("y"), selector["state"].get("width"), selector["state"].get("height"), ] if all([x is not None for x in selector_list]): try: return {selector_type: [int(x) for x in selector_list]} except ValueError: return return def simplify_ocr(ocr): """ Simplify ocr to just a single continuous page of text, with selectors. """ simplified = dict(text=[], selector=defaultdict(list)) if ocr.get("paragraph"): for paragraph in ocr["paragraph"]: if paragraph.get("properties"): if paragraph["properties"].get("lines"): for line in paragraph["properties"]["lines"]: if line.get("properties"): if line["properties"].get("text"): for text in line["properties"]["text"]: simplified["text"].append(text.get("value")) selector_obj = simplify_selector(text["selector"]) if selector_obj: for k, v in selector_obj.items(): simplified["selector"][k].append(v) simplified["indexable"] = " ".join([t for t in simplified["text"] if t]) simplified["original_content"] = simplified["indexable"] simplified["subtype"] = "intermediate" return [simplified] def simplify_label(s): return ".".join(OrderedSet(s.split("."))) def recurse_properties(properties, indexables=None, doc_subtype=None, target=None): if not indexables: indexables = [] if properties: if properties.get("properties"): # This is a nested model so recurse into that indexables += recurse_properties( properties=properties.get("properties"), doc_subtype=simplify_label( ".".join([doc_subtype, slugify(properties.get("type", ""))]) ), ) if properties.get("value"): # This is just the content of a list of values so index them d = { "subtype": simplify_label(doc_subtype), "indexable": properties.get("value"), "original_content": properties.get("value"), "content_id": properties["id"], "resource_id": target, } # Check for selector if properties.get("selector"): d["selector"] = { k: [v] for k, v in simplify_selector(properties.get("selector")).items() if simplify_selector(properties.get("selector")) is not None } indexables.append(d) else: # Iterate through the keys in the dictionary for property_key, property_value in properties.items(): # It's a list, so we should extract the indexables from each one if isinstance(property_value, list): for x in property_value: indexables += recurse_properties( properties=x, doc_subtype=simplify_label( ".".join([doc_subtype, slugify(property_key)]) ), ) # It's a dictionary if isinstance(property_value, dict): # To Do: Work out why this isn't working (some sort of simple nesting issue) # indexables += recurse_properties( # properties=property_value, # doc_subtype=simplify_label(".".join([doc_subtype, slugify(property_key)])), # ) if property_value.get("value"): d = { "subtype": simplify_label( ".".join([doc_subtype, slugify(property_value.get("label", ""))]) ), "indexable": property_value.get("value"), "original_content": property_value.get("value"), "content_id": property_value["id"], "resource_id": target, } if property_value.get("selector"): d["selector"] = { k: [v] for k, v in simplify_selector( property_value.get("selector") ).items() if simplify_selector(property_value.get("selector")) is not None } indexables.append(d) if property_value.get("properties"): indexables += recurse_properties( properties=property_value.get("properties"), doc_subtype=simplify_label( ".".join([doc_subtype, slugify(property_value.get("type", ""))]) ), ) return indexables def simplify_capturemodel(capturemodel): """ Function for parsing a capture model into indexables """ if (document := capturemodel.get("document")) is not None: indexables = [] doc_subtype = document.get("type") if (targets := capturemodel.get("target")) is not None: target = targets[-1].get("id") else: target = None if document.get("properties"): # This has regions of interest if (regions := document["properties"].get("region")) is not None: for region in regions: if region.get("value"): indexables.append( { "subtype": ".".join( [doc_subtype, slugify(region.get("label", ""))] ), "indexable": region.get("value"), "original_content": region.get("value"), "selector": { k: [v] for k, v in simplify_selector(region.get("selector")).items() }, "content_id": region["id"], "resource_id": target, } ) else: # This is some sort of entity type tagging task, or other non region of interest # so we are going to recurse into the nesting indexables += recurse_properties( properties=document.get("properties"), doc_subtype=doc_subtype, target=target ) return indexables return def calc_offsets(obj): """ The search "hit" should have a 'fullsnip' annotation which is a the entire text of the indexable resource, with <start_sel> and <end_sel> wrapping each highlighted word. Check if there's a selector on the indexable, and then if there's a box-selector use this to generate a list of xywh coordinates by retrieving the selector by its index from a list of lists """ if hasattr(obj, "fullsnip"): words = obj.fullsnip.split(" ") offsets = [] if words: for i, word in enumerate(words): if "<start_sel>" in word and "<end_sel>" in word: offsets.append(i) if offsets: if obj.selector: if (boxes := obj.selector.get("box-selector")) is not None: box_list = [] for x in offsets: try: box_list.append(boxes[x]) except (IndexError, ValueError): pass if box_list: return box_list # [boxes[x] for x in offsets if boxes[x]] else: return return class ActionBasedSerializerMixin(object): serializer_mapping = { "default": None, } def get_serializer_class(self): logger.info(self.action) if serializer_class := self.serializer_mapping.get(self.action): return serializer_class elif serializer_class := self.serializer_mapping.get("default"): return serializer_class else: return self.serializer_class class MethodBasedSerializerMixin(object): serializer_mapping = { "default": None, } def get_serializer_class(self): logger.info(self.request.method) if serializer_class := self.serializer_mapping.get(self.request.method.lower()): return serializer_class elif serializer_class := self.serializer_mapping.get("default"): return serializer_class else: return self.serializer_class
from django.core.validators import URLValidator from django.core.exceptions import ValidationError from django.utils.text import slugify import json from bs4 import BeautifulSoup from collections import defaultdict from ordered_set import OrderedSet from dateutil import parser import bleach import logging import itertools logger = logging.getLogger(__name__) pg_languages = [ "danish", "dutch", "english", "finnish", "french", "german", "hungarian", "italian", "norwegian", "portuguese", "romanian", "russian", "spanish", "swedish", "turkish", ] def resources_by_type(iiif, iiif_type=("Canvas",), master_resources=None): """ Iterate a Presentation API 3 manifest and produce a list of resources by type, e.g. Canvases or Annotations. """ if not master_resources: working_resources = [] else: working_resources = master_resources if (items := iiif.get("items", None)) is not None: if any([isinstance(item, list) for item in items]): resources = [c for c in itertools.chain.from_iterable(items) if c.get("type") is not None] else: resources = [c for c in items if c.get("type") is not None] filtered_resources = [r for r in resources if r.get("type") in iiif_type] if filtered_resources: working_resources += filtered_resources else: for f in resources: working_resources += resources_by_type( iiif=f, iiif_type=iiif_type, master_resources=filtered_resources ) return working_resources def iiif_to_presentationapiresourcemodel(data_dict): """ Somewhat hacky transformation of an incoming data object for the serializer into the correct format for the model """ lookup_dict = { "@id": {"model_key": "identifier", "default": None, "choices": None}, "identifier": {"model_key": "identifier", "default": None, "choices": None}, "@type": { "model_key": "type", "default": "Man", "choices": ( ("Col", "Collection"), ("Col", "sc:Collection"), ("Man", "Manifest"), ("Man", "sc:Manifest"), ("Seq", "Sequence"), ("Seq", "sc:Sequence"), ("Rng", "Range"), ("Rng", "sc:Range"), ("Cvs", "Canvas"), ("Cvs", "sc:Canvas"), ), }, "type": { "model_key": "type", "default": "Man", "choices": ( ("Col", "Collection"), ("Man", "Manifest"), ("Seq", "Sequence"), ("Rng", "Range"), ("Cvs", "Canvas"), ), }, "label": {"model_key": "label", "default": None, "choices": None}, "viewingDirection": { "model_key": "viewing_direction", "default": "l2", "choices": ( ("l2r", "left-to-right"), ("r2l", "right-to-left"), ("t2b", "top-to-bottom"), ("b2t", "bottom-to-top"), ), }, "viewingHint": { "model_key": "viewing_hint", "default": "paged", "choices": ( ("ind", "individuals"), ("pgd", "paged"), ("cnt", "continuous"), ("mpt", "multi-part"), ("npg", "non-paged"), ("top", "top"), ("fac", "facing-pages"), ), }, "description": {"model_key": "description", "default": None, "choices": None}, "attribution": {"model_key": "attribution", "default": None, "choices": None}, "license": {"model_key": "license", "default": None, "choices": None}, "metadata": {"model_key": "metadata", "default": None, "choices": None}, } return_dict = {} if data_dict.get("metadata"): if isinstance((data_dict["metadata"]), str): data_dict["metadata"] = json.load(data_dict["metadata"]) for k, v in data_dict.items(): lookup_result = lookup_dict.get(k) if lookup_result: if not lookup_result.get("choices"): return_dict[lookup_result["model_key"]] = v else: if v in [c[0] for c in lookup_result["choices"]]: return_dict[lookup_result["model_key"]] = v elif v in [c[1] for c in lookup_result["choices"]]: return_dict[lookup_result["model_key"]] = [ c[0] for c in lookup_result["choices"] if c[1] == v ][0] else: return_dict[lookup_result["model_key"]] = lookup_result.get("default") if return_dict.get("license"): val = URLValidator() try: val(return_dict["license"]) except ValidationError: del return_dict["license"] return return_dict def get_language_data(lang_code=None, langbase=None): if lang_code: if "-" in lang_code: lang_code = lang_code.split("-")[0] if len(lang_code) == 2: language_data = [x for x in langbase if x[1] == lang_code] if language_data: if language_data[0][-1].lower() in pg_languages: pg_lang = language_data[0][-1].lower() else: pg_lang = None return { "language_iso639_2": language_data[0][0], "language_iso639_1": language_data[0][1], "language_display": language_data[0][-1].lower(), "language_pg": pg_lang, } elif len(lang_code) == 3: language_data = [x for x in langbase if x[0] == lang_code] if language_data: if language_data[0][-1].lower() in pg_languages: pg_lang = language_data[0][-1].lower() else: pg_lang = None return { "language_iso639_2": language_data[0][0], "language_iso639_1": language_data[0][1], "language_display": language_data[0][-1].lower(), "language_pg": pg_lang, } return { "language_iso639_2": None, "language_iso639_1": None, "language_display": None, "language_pg": None, } def process_field( field_instance, key, default_language, lang_base, field_type="descriptive", field_indexable_type="text", ): val = None lang = default_language subtype = key field_data = [] if field_instance: if not field_instance.get("label"): # Problem here with multilanguage label field for val_lang, val in field_instance.items(): if val_lang in ["@none", "none"]: lang = default_language else: lang = val_lang if val: for v in val: v = str(v) if field_indexable_type == "text": field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable": BeautifulSoup(v, "html.parser").text, "original_content": {subtype: bleach.clean(v)}, **get_language_data(lang_code=lang, langbase=lang_base), } ) elif field_indexable_type == "date": """ This assumes a single navDate, but we translate this into a datetime range via adding two indexables. """ try: parsed_date = parser.parse(v) except ValueError: parsed_date = None if parsed_date: field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable_date_range_start": parsed_date, "indexable_date_range_end": parsed_date, "original_content": {subtype: bleach.clean(v)}, } ) else: indexable_values = [] label_values = field_instance.get("label", {}) if field_values:=field_instance.get("value"): for lang, vals in field_values.items(): if labels:= label_values.get(lang): subtype = labels[0] if lang in ["@none", "none"]: lang = default_language language_data = get_language_data(lang_code=lang, langbase=lang_base) for v in vals: if field_indexable_type == "text": field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable": BeautifulSoup(v, "html.parser").text, "original_content": {subtype: v}, **language_data, } ) elif field_indexable_type == "date": """ This assumes a single navDate, but we translate this into a datetime range via adding two indexables. """ try: parsed_date = parser.parse(v) except ValueError: parsed_date = None if parsed_date: field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable_date_range_start": parsed_date, "original_content": {subtype: v}, } ) field_data.append( { "type": field_type, "subtype": subtype.lower(), "indexable_date_range_end": parsed_date, "original_content": {subtype: v}, } ) return field_data return def flatten_iiif_descriptive(iiif, default_language=None, lang_base=None): """ Flatten the descriptive fields in a Presentation API into a list of dicts that can be passed to the Indexables model and serializers """ field_data = [] dict_fields = [ ("label", "descriptive", "text"), ("requiredStatement", "descriptive", "text"), ("summary", "descriptive", "text"), ("metadata", "metadata", "text"), ("navDate", "descriptive", "date"), ] for d in dict_fields: if iiif.get(d[0]): if isinstance(iiif[d[0]], dict): field_instances = [iiif[d[0]]] elif isinstance(iiif[d[0]], list): field_instances = iiif[d[0]] else: # This might be just a string, e.g. navDate # There is no language or label, so we just pass it through with the language set to None field_instances = [{"none": [iiif[d[0]]]}] if field_instances: for field_instance in field_instances: returned_data = process_field( field_instance=field_instance, lang_base=lang_base, default_language=default_language, key=d[0], field_type=d[1], field_indexable_type=d[2], ) if returned_data: field_data += returned_data if field_data: return field_data else: return def simplify_selector(selector): """ Simplify a selector from the OCR intermediate format or capture model format into a compact representation "selector": { "id": "0db4fdc1-73dd-4555-95da-7cbc746c980c", "state": { "height": "60", "width": "20", "x": "821", "y": "644" }, "type": "box-selector" }, Becomes (XYWH): 832,644,20,60 """ if selector: if selector.get("state"): if (selector_type := selector.get("type")) is not None: if selector_type == "box-selector": selector_list = [ selector["state"].get("x"), selector["state"].get("y"), selector["state"].get("width"), selector["state"].get("height"), ] if all([x is not None for x in selector_list]): try: return {selector_type: [int(x) for x in selector_list]} except ValueError: return return def simplify_ocr(ocr): """ Simplify ocr to just a single continuous page of text, with selectors. """ simplified = dict(text=[], selector=defaultdict(list)) if ocr.get("paragraph"): for paragraph in ocr["paragraph"]: if paragraph.get("properties"): if paragraph["properties"].get("lines"): for line in paragraph["properties"]["lines"]: if line.get("properties"): if line["properties"].get("text"): for text in line["properties"]["text"]: simplified["text"].append(text.get("value")) selector_obj = simplify_selector(text["selector"]) if selector_obj: for k, v in selector_obj.items(): simplified["selector"][k].append(v) simplified["indexable"] = " ".join([t for t in simplified["text"] if t]) simplified["original_content"] = simplified["indexable"] simplified["subtype"] = "intermediate" return [simplified] def simplify_label(s): return ".".join(OrderedSet(s.split("."))) def recurse_properties(properties, indexables=None, doc_subtype=None, target=None): if not indexables: indexables = [] if properties: if properties.get("properties"): # This is a nested model so recurse into that indexables += recurse_properties( properties=properties.get("properties"), doc_subtype=simplify_label( ".".join([doc_subtype, slugify(properties.get("type", ""))]) ), ) if properties.get("value"): # This is just the content of a list of values so index them d = { "subtype": simplify_label(doc_subtype), "indexable": properties.get("value"), "original_content": properties.get("value"), "content_id": properties["id"], "resource_id": target, } # Check for selector if properties.get("selector"): d["selector"] = { k: [v] for k, v in simplify_selector(properties.get("selector")).items() if simplify_selector(properties.get("selector")) is not None } indexables.append(d) else: # Iterate through the keys in the dictionary for property_key, property_value in properties.items(): # It's a list, so we should extract the indexables from each one if isinstance(property_value, list): for x in property_value: indexables += recurse_properties( properties=x, doc_subtype=simplify_label( ".".join([doc_subtype, slugify(property_key)]) ), ) # It's a dictionary if isinstance(property_value, dict): # To Do: Work out why this isn't working (some sort of simple nesting issue) # indexables += recurse_properties( # properties=property_value, # doc_subtype=simplify_label(".".join([doc_subtype, slugify(property_key)])), # ) if property_value.get("value"): d = { "subtype": simplify_label( ".".join([doc_subtype, slugify(property_value.get("label", ""))]) ), "indexable": property_value.get("value"), "original_content": property_value.get("value"), "content_id": property_value["id"], "resource_id": target, } if property_value.get("selector"): d["selector"] = { k: [v] for k, v in simplify_selector( property_value.get("selector") ).items() if simplify_selector(property_value.get("selector")) is not None } indexables.append(d) if property_value.get("properties"): indexables += recurse_properties( properties=property_value.get("properties"), doc_subtype=simplify_label( ".".join([doc_subtype, slugify(property_value.get("type", ""))]) ), ) return indexables def simplify_capturemodel(capturemodel): """ Function for parsing a capture model into indexables """ if (document := capturemodel.get("document")) is not None: indexables = [] doc_subtype = document.get("type") if (targets := capturemodel.get("target")) is not None: target = targets[-1].get("id") else: target = None if document.get("properties"): # This has regions of interest if (regions := document["properties"].get("region")) is not None: for region in regions: if region.get("value"): indexables.append( { "subtype": ".".join( [doc_subtype, slugify(region.get("label", ""))] ), "indexable": region.get("value"), "original_content": region.get("value"), "selector": { k: [v] for k, v in simplify_selector(region.get("selector")).items() }, "content_id": region["id"], "resource_id": target, } ) else: # This is some sort of entity type tagging task, or other non region of interest # so we are going to recurse into the nesting indexables += recurse_properties( properties=document.get("properties"), doc_subtype=doc_subtype, target=target ) return indexables return def calc_offsets(obj): """ The search "hit" should have a 'fullsnip' annotation which is a the entire text of the indexable resource, with <start_sel> and <end_sel> wrapping each highlighted word. Check if there's a selector on the indexable, and then if there's a box-selector use this to generate a list of xywh coordinates by retrieving the selector by its index from a list of lists """ if hasattr(obj, "fullsnip"): words = obj.fullsnip.split(" ") offsets = [] if words: for i, word in enumerate(words): if "<start_sel>" in word and "<end_sel>" in word: offsets.append(i) if offsets: if obj.selector: if (boxes := obj.selector.get("box-selector")) is not None: box_list = [] for x in offsets: try: box_list.append(boxes[x]) except (IndexError, ValueError): pass if box_list: return box_list # [boxes[x] for x in offsets if boxes[x]] else: return return class ActionBasedSerializerMixin(object): serializer_mapping = { "default": None, } def get_serializer_class(self): logger.info(self.action) if serializer_class := self.serializer_mapping.get(self.action): return serializer_class elif serializer_class := self.serializer_mapping.get("default"): return serializer_class else: return self.serializer_class class MethodBasedSerializerMixin(object): serializer_mapping = { "default": None, } def get_serializer_class(self): logger.info(self.request.method) if serializer_class := self.serializer_mapping.get(self.request.method.lower()): return serializer_class elif serializer_class := self.serializer_mapping.get("default"): return serializer_class else: return self.serializer_class
en
0.807046
Iterate a Presentation API 3 manifest and produce a list of resources by type, e.g. Canvases or Annotations. Somewhat hacky transformation of an incoming data object for the serializer into the correct format for the model # Problem here with multilanguage label field This assumes a single navDate, but we translate this into a datetime range via adding two indexables. This assumes a single navDate, but we translate this into a datetime range via adding two indexables. Flatten the descriptive fields in a Presentation API into a list of dicts that can be passed to the Indexables model and serializers # This might be just a string, e.g. navDate # There is no language or label, so we just pass it through with the language set to None Simplify a selector from the OCR intermediate format or capture model format into a compact representation "selector": { "id": "0db4fdc1-73dd-4555-95da-7cbc746c980c", "state": { "height": "60", "width": "20", "x": "821", "y": "644" }, "type": "box-selector" }, Becomes (XYWH): 832,644,20,60 Simplify ocr to just a single continuous page of text, with selectors. # This is a nested model so recurse into that # This is just the content of a list of values so index them # Check for selector # Iterate through the keys in the dictionary # It's a list, so we should extract the indexables from each one # It's a dictionary # To Do: Work out why this isn't working (some sort of simple nesting issue) # indexables += recurse_properties( # properties=property_value, # doc_subtype=simplify_label(".".join([doc_subtype, slugify(property_key)])), # ) Function for parsing a capture model into indexables # This has regions of interest # This is some sort of entity type tagging task, or other non region of interest # so we are going to recurse into the nesting The search "hit" should have a 'fullsnip' annotation which is a the entire text of the indexable resource, with <start_sel> and <end_sel> wrapping each highlighted word. Check if there's a selector on the indexable, and then if there's a box-selector use this to generate a list of xywh coordinates by retrieving the selector by its index from a list of lists # [boxes[x] for x in offsets if boxes[x]]
2.160444
2
groups/migrations/0004_auto_20200510_0509.py
3crabs/class-book
1
6614314
# Generated by Django 3.0.6 on 2020-05-09 22:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('groups', '0003_student'), ] operations = [ migrations.RenameField( model_name='group', old_name='subject', new_name='subjects', ), ]
# Generated by Django 3.0.6 on 2020-05-09 22:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('groups', '0003_student'), ] operations = [ migrations.RenameField( model_name='group', old_name='subject', new_name='subjects', ), ]
en
0.802708
# Generated by Django 3.0.6 on 2020-05-09 22:09
1.735571
2
gen_valset.py
likesum/deepFnF
8
6614315
#!/usr/bin/env python3 import os import numpy as np import tensorflow as tf from utils.dataset import Dataset outpath = 'data/valset' if not os.path.exists(outpath): os.makedirs(outpath) TLIST = 'data/train.txt' VLIST = 'data/val.txt' def gamma(img): return img**(1/2.2) BSZ = 1 IMSZ = 448 dataset = Dataset(TLIST, VLIST, bsz=BSZ, psz=IMSZ, onfly_val=True) example = dataset.batches[0] sess = tf.Session(config=tf.ConfigProto( allow_soft_placement=True)) sess.run(tf.global_variables_initializer()) dataset.init_handles(sess) dataset.swap_val(sess) c = 0 while True: try: data = sess.run(example) np.savez('%s/%d.npz' % (outpath, c), **data) c += 1 except tf.errors.OutOfRangeError: break
#!/usr/bin/env python3 import os import numpy as np import tensorflow as tf from utils.dataset import Dataset outpath = 'data/valset' if not os.path.exists(outpath): os.makedirs(outpath) TLIST = 'data/train.txt' VLIST = 'data/val.txt' def gamma(img): return img**(1/2.2) BSZ = 1 IMSZ = 448 dataset = Dataset(TLIST, VLIST, bsz=BSZ, psz=IMSZ, onfly_val=True) example = dataset.batches[0] sess = tf.Session(config=tf.ConfigProto( allow_soft_placement=True)) sess.run(tf.global_variables_initializer()) dataset.init_handles(sess) dataset.swap_val(sess) c = 0 while True: try: data = sess.run(example) np.savez('%s/%d.npz' % (outpath, c), **data) c += 1 except tf.errors.OutOfRangeError: break
fr
0.221828
#!/usr/bin/env python3
2.342383
2
tests/ci/commit_status_helper.py
zhongyuankai/ClickHouse
1
6614316
#!/usr/bin/env python3 import time from env_helper import GITHUB_REPOSITORY from ci_config import CI_CONFIG RETRY = 5 def override_status(status, check_name): if CI_CONFIG["tests_config"][check_name].get("force_tests", False): return "success" return status def get_commit(gh, commit_sha, retry_count=RETRY): for i in range(retry_count): try: repo = gh.get_repo(GITHUB_REPOSITORY) commit = repo.get_commit(commit_sha) return commit except Exception as ex: if i == retry_count - 1: raise ex time.sleep(i) # just suppress warning return None def post_commit_status(gh, sha, check_name, description, state, report_url): for i in range(RETRY): try: commit = get_commit(gh, sha, 1) commit.create_status( context=check_name, description=description, state=state, target_url=report_url, ) break except Exception as ex: if i == RETRY - 1: raise ex time.sleep(i)
#!/usr/bin/env python3 import time from env_helper import GITHUB_REPOSITORY from ci_config import CI_CONFIG RETRY = 5 def override_status(status, check_name): if CI_CONFIG["tests_config"][check_name].get("force_tests", False): return "success" return status def get_commit(gh, commit_sha, retry_count=RETRY): for i in range(retry_count): try: repo = gh.get_repo(GITHUB_REPOSITORY) commit = repo.get_commit(commit_sha) return commit except Exception as ex: if i == retry_count - 1: raise ex time.sleep(i) # just suppress warning return None def post_commit_status(gh, sha, check_name, description, state, report_url): for i in range(RETRY): try: commit = get_commit(gh, sha, 1) commit.create_status( context=check_name, description=description, state=state, target_url=report_url, ) break except Exception as ex: if i == RETRY - 1: raise ex time.sleep(i)
en
0.21501
#!/usr/bin/env python3 # just suppress warning
2.419401
2
packageopt/services/agents/implementations/daily_traded_volume_money_agent.py
nspostnov/for-article-optimal-position-liquidation
0
6614317
from ..abstract_base_classes.agent import Agent __all__ = ['DailyTradedVolumeMoneyAgent'] class DailyTradedVolumeMoneyAgent(Agent): def __init__(self, dailytradedvolumemoneyrepo, dailytradedvolumemoneysolver): self._dailytradedvolumemoneyrepo = dailytradedvolumemoneyrepo self._dailytradedvolumemoneysolver = dailytradedvolumemoneysolver def get(self, key): dailytradedvolumemoney = self._dailytradedvolumemoneyrepo.get(key) if dailytradedvolumemoney is None: dailytradedvolumemoney = self._dailytradedvolumemoneysolver.calculate(key) self._dailytradedvolumemoneyrepo.set(dailytradedvolumemoney) dailytradedvolumemoney = self._dailytradedvolumemoneyrepo.get(key) return dailytradedvolumemoney
from ..abstract_base_classes.agent import Agent __all__ = ['DailyTradedVolumeMoneyAgent'] class DailyTradedVolumeMoneyAgent(Agent): def __init__(self, dailytradedvolumemoneyrepo, dailytradedvolumemoneysolver): self._dailytradedvolumemoneyrepo = dailytradedvolumemoneyrepo self._dailytradedvolumemoneysolver = dailytradedvolumemoneysolver def get(self, key): dailytradedvolumemoney = self._dailytradedvolumemoneyrepo.get(key) if dailytradedvolumemoney is None: dailytradedvolumemoney = self._dailytradedvolumemoneysolver.calculate(key) self._dailytradedvolumemoneyrepo.set(dailytradedvolumemoney) dailytradedvolumemoney = self._dailytradedvolumemoneyrepo.get(key) return dailytradedvolumemoney
none
1
3.109981
3
Fig4_1Dtrack/unfamiliar_RNN1.25x/src_1comp_etalow/shared_setting.py
TatsuyaHaga/preplaymodel_codes
1
6614318
time_pitch=1.0 sim_len_sec=50.0 NE=300 Nsominh=100 Ndndinh=100 Ninput=500 Ndistractor=200
time_pitch=1.0 sim_len_sec=50.0 NE=300 Nsominh=100 Ndndinh=100 Ninput=500 Ndistractor=200
none
1
0.888564
1
dyndns_update.py
cptaffe/dyndns_update
0
6614319
#!/usr/bin/env python3 import requests, datetime from time import sleep urls = ['http://cpt.hopper.pw:LBbRhmu3gV@ipv4.www.hopper.pw/nic/update'] # basic auth to hopper.pw updates while True: for url in urls: try: r = requests.get(url, auth=('cpt.hopper.pw', 'LBbRhmu3gV')) print("response @", datetime.datetime.now(), ":", r.text) except requests.exceptions.RequestException as e: print(e, file=sys.stderr) # print to stderr sleep(300) # sleep for five minutes
#!/usr/bin/env python3 import requests, datetime from time import sleep urls = ['http://cpt.hopper.pw:LBbRhmu3gV@ipv4.www.hopper.pw/nic/update'] # basic auth to hopper.pw updates while True: for url in urls: try: r = requests.get(url, auth=('cpt.hopper.pw', 'LBbRhmu3gV')) print("response @", datetime.datetime.now(), ":", r.text) except requests.exceptions.RequestException as e: print(e, file=sys.stderr) # print to stderr sleep(300) # sleep for five minutes
en
0.489195
#!/usr/bin/env python3 # basic auth to hopper.pw updates # print to stderr # sleep for five minutes
2.574272
3
interview/leet/537_Complex_Number_Multiplication.py
eroicaleo/LearningPython
1
6614320
#!/usr/bin/env python # Example 1: # Input: "1+1i", "1+1i" # Output: "0+2i" # Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. # Example 2: # Input: "1+-1i", "1+-1i" # Output: "0+-2i" # Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. class Solution: def complexNumberMultiply(self, a: str, b: str) -> str: a_l, b_l = a.split('+'), b.split('+') ar, ai = int(a_l[0]), int(a_l[1][:-1]) br, bi = int(b_l[0]), int(b_l[1][:-1]) print(ar, ai, br, bi) return f'{ar*br-ai*bi}+{ar*bi+ai*br}i' a, b = "1+-1i", "1+-1i" a, b = "1+1i", "1+1i" sol = Solution() print(sol.complexNumberMultiply(a, b))
#!/usr/bin/env python # Example 1: # Input: "1+1i", "1+1i" # Output: "0+2i" # Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. # Example 2: # Input: "1+-1i", "1+-1i" # Output: "0+-2i" # Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. class Solution: def complexNumberMultiply(self, a: str, b: str) -> str: a_l, b_l = a.split('+'), b.split('+') ar, ai = int(a_l[0]), int(a_l[1][:-1]) br, bi = int(b_l[0]), int(b_l[1][:-1]) print(ar, ai, br, bi) return f'{ar*br-ai*bi}+{ar*bi+ai*br}i' a, b = "1+-1i", "1+-1i" a, b = "1+1i", "1+1i" sol = Solution() print(sol.complexNumberMultiply(a, b))
en
0.54551
#!/usr/bin/env python # Example 1: # Input: "1+1i", "1+1i" # Output: "0+2i" # Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. # Example 2: # Input: "1+-1i", "1+-1i" # Output: "0+-2i" # Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
4.040774
4
crumbs/information.py
alunduil/crumbs
10
6614321
# Copyright (C) 2015 by <NAME> <<EMAIL>> # # crumbs is freely distributable under the terms of an MIT-style license. # See COPYING or http://www.opensource.org/licenses/mit-license.php. NAME = 'crumbs' VERSION = '2.1.1' DESCRIPTION = 'Generalized all-in-one parameters module.' AUTHOR = '<NAME>' AUTHOR_EMAIL = '<EMAIL>' URL = 'https://github.com/alunduil/crumbs' LICENSE = 'MIT' COPYRIGHT = '2015'
# Copyright (C) 2015 by <NAME> <<EMAIL>> # # crumbs is freely distributable under the terms of an MIT-style license. # See COPYING or http://www.opensource.org/licenses/mit-license.php. NAME = 'crumbs' VERSION = '2.1.1' DESCRIPTION = 'Generalized all-in-one parameters module.' AUTHOR = '<NAME>' AUTHOR_EMAIL = '<EMAIL>' URL = 'https://github.com/alunduil/crumbs' LICENSE = 'MIT' COPYRIGHT = '2015'
en
0.682219
# Copyright (C) 2015 by <NAME> <<EMAIL>> # # crumbs is freely distributable under the terms of an MIT-style license. # See COPYING or http://www.opensource.org/licenses/mit-license.php.
0.837089
1
hw/DataStructure2019-PJ2/random-gen.py
Riteme/test
3
6614322
<reponame>Riteme/test #!/usr/bin/pypy from sys import * from random import * n, m, q, K, C = map(int, argv[1:]) print n, m # for v in xrange(2, n + 1): # u = randint(1, v - 1) # w = randint(1, C) # print u, v, w # m -= n - 1 for i in xrange(m): u = randint(1, n) v = randint(1, n) w = randint(1, C) print u, v, w print q for i in xrange(q): s = randint(1, n) t = randint(1, n) k = randint(0, K) idx = [randint(1, m) for j in xrange(k)] print s, t, k, ' '.join(map(str, idx))
#!/usr/bin/pypy from sys import * from random import * n, m, q, K, C = map(int, argv[1:]) print n, m # for v in xrange(2, n + 1): # u = randint(1, v - 1) # w = randint(1, C) # print u, v, w # m -= n - 1 for i in xrange(m): u = randint(1, n) v = randint(1, n) w = randint(1, C) print u, v, w print q for i in xrange(q): s = randint(1, n) t = randint(1, n) k = randint(0, K) idx = [randint(1, m) for j in xrange(k)] print s, t, k, ' '.join(map(str, idx))
en
0.385732
#!/usr/bin/pypy # for v in xrange(2, n + 1): # u = randint(1, v - 1) # w = randint(1, C) # print u, v, w # m -= n - 1
2.6617
3
bare_python/s19_07_import_mod_func_only.py
AndreiHondrari/python_exploration
3
6614323
#!python3 from ut import p p("from mod1 import something") _temp = __import__("mod1") something = _temp.something something()
#!python3 from ut import p p("from mod1 import something") _temp = __import__("mod1") something = _temp.something something()
none
1
1.741219
2
bbbs/diary/migrations/0003_alter_diary_meeting_date.py
dangerousmonk/bigBrothers-bigSisters-backend
0
6614324
# Generated by Django 3.2.5 on 2021-08-13 18:40 import bbbs.common.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('diary', '0002_auto_20210812_2011'), ] operations = [ migrations.AlterField( model_name='diary', name='meeting_date', field=models.DateField(validators=[bbbs.common.validators.year_validator], verbose_name='meeting date'), ), ]
# Generated by Django 3.2.5 on 2021-08-13 18:40 import bbbs.common.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('diary', '0002_auto_20210812_2011'), ] operations = [ migrations.AlterField( model_name='diary', name='meeting_date', field=models.DateField(validators=[bbbs.common.validators.year_validator], verbose_name='meeting date'), ), ]
en
0.846656
# Generated by Django 3.2.5 on 2021-08-13 18:40
1.563956
2
app/views/dashboard/questions/__init__.py
Wern-rm/raton.by
0
6614325
<reponame>Wern-rm/raton.by from app.views.dashboard.questions.index import questions from app.views.dashboard.questions.activation import question_activated from app.views.dashboard.questions.electron_activation import question_electron_activated from app.views.dashboard.questions.items_activation import question_items_activated
from app.views.dashboard.questions.index import questions from app.views.dashboard.questions.activation import question_activated from app.views.dashboard.questions.electron_activation import question_electron_activated from app.views.dashboard.questions.items_activation import question_items_activated
none
1
1.110897
1
challenge/slides/quarter-model/quarter-model.py
kjartan-at-tec/mr2023
0
6614326
<reponame>kjartan-at-tec/mr2023<filename>challenge/slides/quarter-model/quarter-model.py<gh_stars>0 import numpy as np from control import matlab as cm # Parameters From https://ctms.engin.umich.edu/CTMS/index.php?example=Suspension&section=SimulinkModeling M1 = 2500 # Sprung mass M1 = 0.2*M1 # Sprung mass M2 = 320 # Unsprung mass M2 = 0.2*M2 # Unsprung mass b1 = 350 # Damping coeff b1 = 8*b1 # Damping coeff b2 = 15020 # Damping coeff b2 = 0.5*b2 # Damping coeff K1 = 80000 # Spring stiffness K1 = 0.2*K1 # Spring stiffness K2 = 200000 # Tire stiffness Zr = 0.15 # Road input # State space model A = np.array([[0, 1, 0, 0], [-(b1*b2)/(M1*M2), 0, (b1/M1)*(b1/M1 + b1/M2 + b2/M2)-K1/M1, -b1/M1], [b2/M2, 0, -(b1/M1 + b1/M2 + b2/M2), 1], [K2/M2, 0, -(K1/M1 + K1/M2 + K2/M2), 0]]) B = np.array([[0, 0], [1/M1, b1*b2/(M1*M2)], [0, -b2/M2], [(1/M2+1/M1), -K2/M2]]) C = np.array([[1, 0, 0, 0],[0,0,1,0]]) D = np.array([[0,0],[0,0]]) ss_sys = cm.ss(A, B, C, D) # Input signal N = 240 tend = 6 tt = np.linspace(0, tend, N) uw = np.zeros((2,N)) uw[1,40:70] = Zr*np.sin(np.linspace(0,np.pi,30)) uw[1,120:150] = -Zr*np.sin(np.linspace(0,np.pi,30)) yout, T, xout = cm.lsim(ss_sys, uw.T, tt) kk = 10 # convert to dm for animation x1 = kk * xout[::2,0] x2 = x1 - kk*xout[::2,2] w = uw[1,::2] * 10 T.shape=(len(T),1) TT = T[::2] dta = np.transpose(np.vstack((np.ravel(TT), x1, x2, w))) np.savetxt('./quarter_model.dta', dta, delimiter=',', fmt='%8.4f')
import numpy as np from control import matlab as cm # Parameters From https://ctms.engin.umich.edu/CTMS/index.php?example=Suspension&section=SimulinkModeling M1 = 2500 # Sprung mass M1 = 0.2*M1 # Sprung mass M2 = 320 # Unsprung mass M2 = 0.2*M2 # Unsprung mass b1 = 350 # Damping coeff b1 = 8*b1 # Damping coeff b2 = 15020 # Damping coeff b2 = 0.5*b2 # Damping coeff K1 = 80000 # Spring stiffness K1 = 0.2*K1 # Spring stiffness K2 = 200000 # Tire stiffness Zr = 0.15 # Road input # State space model A = np.array([[0, 1, 0, 0], [-(b1*b2)/(M1*M2), 0, (b1/M1)*(b1/M1 + b1/M2 + b2/M2)-K1/M1, -b1/M1], [b2/M2, 0, -(b1/M1 + b1/M2 + b2/M2), 1], [K2/M2, 0, -(K1/M1 + K1/M2 + K2/M2), 0]]) B = np.array([[0, 0], [1/M1, b1*b2/(M1*M2)], [0, -b2/M2], [(1/M2+1/M1), -K2/M2]]) C = np.array([[1, 0, 0, 0],[0,0,1,0]]) D = np.array([[0,0],[0,0]]) ss_sys = cm.ss(A, B, C, D) # Input signal N = 240 tend = 6 tt = np.linspace(0, tend, N) uw = np.zeros((2,N)) uw[1,40:70] = Zr*np.sin(np.linspace(0,np.pi,30)) uw[1,120:150] = -Zr*np.sin(np.linspace(0,np.pi,30)) yout, T, xout = cm.lsim(ss_sys, uw.T, tt) kk = 10 # convert to dm for animation x1 = kk * xout[::2,0] x2 = x1 - kk*xout[::2,2] w = uw[1,::2] * 10 T.shape=(len(T),1) TT = T[::2] dta = np.transpose(np.vstack((np.ravel(TT), x1, x2, w))) np.savetxt('./quarter_model.dta', dta, delimiter=',', fmt='%8.4f')
en
0.604496
# Parameters From https://ctms.engin.umich.edu/CTMS/index.php?example=Suspension&section=SimulinkModeling # Sprung mass # Sprung mass # Unsprung mass # Unsprung mass # Damping coeff # Damping coeff # Damping coeff # Damping coeff # Spring stiffness # Spring stiffness # Tire stiffness # Road input # State space model # Input signal # convert to dm for animation
2.633816
3
globals.py
uuk0/mcpython-a-minecraft-clone-in-python
2
6614327
<reponame>uuk0/mcpython-a-minecraft-clone-in-python<gh_stars>1-10 window = None model = None player = None inventoryhandler = None local = "." mods = [] modnames = [] seed = None random = None statehandler = None State = None TileState = None NEXT_SPHERE_ID = 0
window = None model = None player = None inventoryhandler = None local = "." mods = [] modnames = [] seed = None random = None statehandler = None State = None TileState = None NEXT_SPHERE_ID = 0
none
1
1.304428
1
backend/Scripts/backend/api/models.py
makr11/FitCommit
1
6614328
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.validators import UnicodeUsernameValidator class Setup(models.Model): name = models.CharField(max_length=30, primary_key=True) value = models.CharField(max_length=100) class CustomUser(AbstractUser): username_validator = UnicodeUsernameValidator() IDUser = models.CharField(max_length=5, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) address = models.CharField(max_length=70, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) username = models.CharField( _('username'), max_length=150, unique=True, help_text=_( 'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, blank=True ) password = models.CharField(_('password'), max_length=128, blank=True) def __str__(self): return self.first_name + ' ' + self.last_name class Services(models.Model): service = models.CharField(max_length=50) def __str__(self): return self.service class Categories(models.Model): category = models.CharField(max_length=50) serviceID = models.ForeignKey( Services, related_name='categories', on_delete=models.CASCADE) def __str__(self): return self.category class Options(models.Model): arrivals = models.IntegerField() price = models.IntegerField() duration = models.IntegerField() categoryID = models.ForeignKey( Categories, related_name='options', on_delete=models.CASCADE) def __str__(self): return str(self.arrivals) class Records(models.Model): userObj = models.ForeignKey( CustomUser, related_name='user_records', on_delete=models.CASCADE, null=True) serviceObj = models.ForeignKey( Services, related_name='service_records', on_delete=models.CASCADE, null=True) categoryObj = models.ForeignKey( Categories, related_name='category_records', on_delete=models.CASCADE, null=True) optionObj = models.ForeignKey( Options, related_name='options_records', on_delete=models.CASCADE, null=True) arrivals_left = models.IntegerField() days_left = models.IntegerField(default=0) active = models.BooleanField(default=1, blank=True) price = models.IntegerField() discount = models.IntegerField() nett_price = models.IntegerField() paid = models.BooleanField(default=0) frozen = models.IntegerField(default=0) freeze_started = models.DateField(blank=True, null=True) freeze_ended = models.DateField(blank=True, null=True) started = models.DateField(auto_now_add=True) ends = models.DateField() def is_active(self): if self.arrivals_left == 0: self.active = 0 self.save() else: self.active = 1 self.save() def get_days_left(self): now = timezone.now().date() if self.ends > now: days_left = self.ends - now self.days_left = days_left.days self.save() else: self.days_left = 0 self.active = False self.save() def is_frozen(self): now = timezone.now().date() if self.freeze_ended != None and self.freeze_ended < now: self.freeze_started = None self.freeze_ended = None self.save() @property def user(self): return self.userObj.first_name + ' ' + self.userObj.last_name class Arrivals(models.Model): userObj = models.ForeignKey( CustomUser, related_name='user_arrivals', on_delete=models.CASCADE, null=True) recordObj = models.ForeignKey( Records, related_name='record_arrivals', on_delete=models.CASCADE, null=True) arrival = models.DateTimeField()
from django.db import models from django.contrib.auth.models import AbstractUser from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.validators import UnicodeUsernameValidator class Setup(models.Model): name = models.CharField(max_length=30, primary_key=True) value = models.CharField(max_length=100) class CustomUser(AbstractUser): username_validator = UnicodeUsernameValidator() IDUser = models.CharField(max_length=5, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) address = models.CharField(max_length=70, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) username = models.CharField( _('username'), max_length=150, unique=True, help_text=_( 'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, blank=True ) password = models.CharField(_('password'), max_length=128, blank=True) def __str__(self): return self.first_name + ' ' + self.last_name class Services(models.Model): service = models.CharField(max_length=50) def __str__(self): return self.service class Categories(models.Model): category = models.CharField(max_length=50) serviceID = models.ForeignKey( Services, related_name='categories', on_delete=models.CASCADE) def __str__(self): return self.category class Options(models.Model): arrivals = models.IntegerField() price = models.IntegerField() duration = models.IntegerField() categoryID = models.ForeignKey( Categories, related_name='options', on_delete=models.CASCADE) def __str__(self): return str(self.arrivals) class Records(models.Model): userObj = models.ForeignKey( CustomUser, related_name='user_records', on_delete=models.CASCADE, null=True) serviceObj = models.ForeignKey( Services, related_name='service_records', on_delete=models.CASCADE, null=True) categoryObj = models.ForeignKey( Categories, related_name='category_records', on_delete=models.CASCADE, null=True) optionObj = models.ForeignKey( Options, related_name='options_records', on_delete=models.CASCADE, null=True) arrivals_left = models.IntegerField() days_left = models.IntegerField(default=0) active = models.BooleanField(default=1, blank=True) price = models.IntegerField() discount = models.IntegerField() nett_price = models.IntegerField() paid = models.BooleanField(default=0) frozen = models.IntegerField(default=0) freeze_started = models.DateField(blank=True, null=True) freeze_ended = models.DateField(blank=True, null=True) started = models.DateField(auto_now_add=True) ends = models.DateField() def is_active(self): if self.arrivals_left == 0: self.active = 0 self.save() else: self.active = 1 self.save() def get_days_left(self): now = timezone.now().date() if self.ends > now: days_left = self.ends - now self.days_left = days_left.days self.save() else: self.days_left = 0 self.active = False self.save() def is_frozen(self): now = timezone.now().date() if self.freeze_ended != None and self.freeze_ended < now: self.freeze_started = None self.freeze_ended = None self.save() @property def user(self): return self.userObj.first_name + ' ' + self.userObj.last_name class Arrivals(models.Model): userObj = models.ForeignKey( CustomUser, related_name='user_arrivals', on_delete=models.CASCADE, null=True) recordObj = models.ForeignKey( Records, related_name='record_arrivals', on_delete=models.CASCADE, null=True) arrival = models.DateTimeField()
none
1
2.431582
2
node_listener/demo/demo_weather.py
bkosciow/sensor_listener
0
6614329
from pprint import pprint from node_listener.worker.openweather_worker import OpenweatherWorker from node_listener.service.config import Config config = Config('../../config.ini') apikey = config["openweather"]["apikey"] cities = {3103402: "Bielsko-Biała"} w = OpenweatherWorker(cities, apikey, config["general"]["user_agent"]) pprint(w.execute())
from pprint import pprint from node_listener.worker.openweather_worker import OpenweatherWorker from node_listener.service.config import Config config = Config('../../config.ini') apikey = config["openweather"]["apikey"] cities = {3103402: "Bielsko-Biała"} w = OpenweatherWorker(cities, apikey, config["general"]["user_agent"]) pprint(w.execute())
none
1
1.900738
2
major_event_log/migrations/0002_auto_20180911_1613.py
unt-libraries/django-major-event-log
0
6614330
<reponame>unt-libraries/django-major-event-log # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('major_event_log', '0001_initial'), ] operations = [ migrations.AlterField( model_name='event', name='contact_name', field=models.CharField(help_text=b'Appears as the Reporting Agent', max_length=100), ), migrations.AlterField( model_name='event', name='outcome', field=models.CharField(max_length=80, choices=[(b'http://purl.org/NET/UNTL/vocabularies/eventOutcomes/#success', b'Success'), (b'http://purl.org/NET/UNTL/vocabularies/eventOutcomes/#failure', b'Failure')]), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('major_event_log', '0001_initial'), ] operations = [ migrations.AlterField( model_name='event', name='contact_name', field=models.CharField(help_text=b'Appears as the Reporting Agent', max_length=100), ), migrations.AlterField( model_name='event', name='outcome', field=models.CharField(max_length=80, choices=[(b'http://purl.org/NET/UNTL/vocabularies/eventOutcomes/#success', b'Success'), (b'http://purl.org/NET/UNTL/vocabularies/eventOutcomes/#failure', b'Failure')]), ), ]
en
0.375
# -*- coding: utf-8 -*- #success', b'Success'), (b'http://purl.org/NET/UNTL/vocabularies/eventOutcomes/#failure', b'Failure')]),
1.683153
2
videos/factories.py
mitodl/ocw-studio
2
6614331
"""videos factories""" import factory from django.conf import settings from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from videos.constants import ALL_DESTINATIONS, VideoStatus from videos.models import Video, VideoFile, VideoJob from websites.factories import WebsiteFactory class VideoFactory(DjangoModelFactory): """ Factory for Video model""" source_key = factory.Sequence( lambda n: f"{settings.DRIVE_S3_UPLOAD_PREFIX}/{n}/file_{n}" ) website = factory.SubFactory(WebsiteFactory) status = FuzzyChoice(VideoStatus.ALL_STATUSES) class Meta: model = Video class VideoFileFactory(DjangoModelFactory): """Factory for VideoFile model""" video = factory.SubFactory(VideoFactory) s3_key = factory.Sequence( lambda n: f"{settings.VIDEO_S3_TRANSCODE_PREFIX}/{n}/file_{n}" ) destination = FuzzyChoice(ALL_DESTINATIONS) destination_id = factory.Faker("domain_word") class Meta: model = VideoFile class VideoJobFactory(DjangoModelFactory): """Factory for VideoJob model""" video = factory.SubFactory(VideoFactory) job_id = factory.Faker("md5") status = FuzzyChoice("ERROR") class Meta: model = VideoJob
"""videos factories""" import factory from django.conf import settings from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from videos.constants import ALL_DESTINATIONS, VideoStatus from videos.models import Video, VideoFile, VideoJob from websites.factories import WebsiteFactory class VideoFactory(DjangoModelFactory): """ Factory for Video model""" source_key = factory.Sequence( lambda n: f"{settings.DRIVE_S3_UPLOAD_PREFIX}/{n}/file_{n}" ) website = factory.SubFactory(WebsiteFactory) status = FuzzyChoice(VideoStatus.ALL_STATUSES) class Meta: model = Video class VideoFileFactory(DjangoModelFactory): """Factory for VideoFile model""" video = factory.SubFactory(VideoFactory) s3_key = factory.Sequence( lambda n: f"{settings.VIDEO_S3_TRANSCODE_PREFIX}/{n}/file_{n}" ) destination = FuzzyChoice(ALL_DESTINATIONS) destination_id = factory.Faker("domain_word") class Meta: model = VideoFile class VideoJobFactory(DjangoModelFactory): """Factory for VideoJob model""" video = factory.SubFactory(VideoFactory) job_id = factory.Faker("md5") status = FuzzyChoice("ERROR") class Meta: model = VideoJob
en
0.768992
videos factories Factory for Video model Factory for VideoFile model Factory for VideoJob model
2.265178
2
projectdiffview/gui.py
jdpatt/project-diff-view
0
6614332
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'gui.ui' ## ## Created by: Qt User Interface Compiler version 5.15.0 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import ( QCoreApplication, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, Qt, QTime, QUrl, ) from PySide2.QtGui import ( QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QIcon, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, ) from PySide2.QtWidgets import ( QAbstractItemView, QAction, QHBoxLayout, QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSizePolicy, QSpacerItem, QStatusBar, QTreeView, QVBoxLayout, QWidget, ) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(1200, 600) MainWindow.setDocumentMode(True) self.actionPreferences = QAction(MainWindow) self.actionPreferences.setObjectName("actionPreferences") self.actionExit = QAction(MainWindow) self.actionExit.setObjectName("actionExit") self.actionNew_Project = QAction(MainWindow) self.actionNew_Project.setObjectName("actionNew_Project") self.actionSave = QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.actionOpen_Project = QAction(MainWindow) self.actionOpen_Project.setObjectName("actionOpen_Project") self.actionDocumentation = QAction(MainWindow) self.actionDocumentation.setObjectName("actionDocumentation") self.actionAbout = QAction(MainWindow) self.actionAbout.setObjectName("actionAbout") self.actionConsole_Visibility = QAction(MainWindow) self.actionConsole_Visibility.setObjectName("actionConsole_Visibility") self.actionConsole_Visibility.setCheckable(True) self.actionConsole_Visibility.setChecked(True) self.actionSave_As = QAction(MainWindow) self.actionSave_As.setObjectName("actionSave_As") self.actionSettings = QAction(MainWindow) self.actionSettings.setObjectName("actionSettings") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout_3 = QVBoxLayout(self.centralwidget) self.verticalLayout_3.setObjectName("verticalLayout_3") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label = QLabel(self.centralwidget) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.directory_path = QLineEdit(self.centralwidget) self.directory_path.setObjectName("directory_path") self.horizontalLayout.addWidget(self.directory_path) self.browse = QPushButton(self.centralwidget) self.browse.setObjectName("browse") self.horizontalLayout.addWidget(self.browse) self.verticalLayout_3.addLayout(self.horizontalLayout) self.horizontalLayout_5 = QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.verticalLayout = QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.template_tree = QTreeView(self.centralwidget) self.template_tree.setObjectName("template_tree") self.template_tree.setEditTriggers(QAbstractItemView.NoEditTriggers) self.template_tree.setUniformRowHeights(True) self.template_tree.setSortingEnabled(True) self.template_tree.header().setMinimumSectionSize(20) self.template_tree.header().setDefaultSectionSize(150) self.template_tree.header().setStretchLastSection(False) self.verticalLayout.addWidget(self.template_tree) self.horizontalLayout_3 = QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label_2 = QLabel(self.centralwidget) self.label_2.setObjectName("label_2") self.horizontalLayout_3.addWidget(self.label_2) self.template_version = QLineEdit(self.centralwidget) self.template_version.setObjectName("template_version") self.template_version.setReadOnly(True) self.horizontalLayout_3.addWidget(self.template_version) self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(self.horizontalSpacer_2) self.verticalLayout.addLayout(self.horizontalLayout_3) self.horizontalLayout_5.addLayout(self.verticalLayout) self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.working_tree = QTreeView(self.centralwidget) self.working_tree.setObjectName("working_tree") self.working_tree.setEditTriggers(QAbstractItemView.NoEditTriggers) self.working_tree.setUniformRowHeights(True) self.working_tree.setSortingEnabled(True) self.working_tree.header().setMinimumSectionSize(20) self.working_tree.header().setDefaultSectionSize(150) self.working_tree.header().setStretchLastSection(False) self.verticalLayout_2.addWidget(self.working_tree) self.horizontalLayout_2 = QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label_3 = QLabel(self.centralwidget) self.label_3.setObjectName("label_3") self.horizontalLayout_2.addWidget(self.label_3) self.directory_version = QLineEdit(self.centralwidget) self.directory_version.setObjectName("directory_version") self.directory_version.setReadOnly(True) self.horizontalLayout_2.addWidget(self.directory_version) self.horizontalSpacer_3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(self.horizontalSpacer_3) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.horizontalLayout_5.addLayout(self.verticalLayout_2) self.verticalLayout_3.addLayout(self.horizontalLayout_5) self.horizontalLayout_4 = QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_4.addItem(self.horizontalSpacer) self.cleanup_working = QPushButton(self.centralwidget) self.cleanup_working.setObjectName("cleanup_working") self.cleanup_working.setFlat(False) self.horizontalLayout_4.addWidget(self.cleanup_working) self.copy_template = QPushButton(self.centralwidget) self.copy_template.setObjectName("copy_template") self.horizontalLayout_4.addWidget(self.copy_template) self.add_selected = QPushButton(self.centralwidget) self.add_selected.setObjectName("add_selected") self.horizontalLayout_4.addWidget(self.add_selected) self.verticalLayout_3.addLayout(self.horizontalLayout_4) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setObjectName("menubar") self.menubar.setGeometry(QRect(0, 0, 1200, 22)) self.menubar.setDefaultUp(False) self.menuFile = QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuHelp = QMenu(self.menubar) self.menuHelp.setObjectName("menuHelp") MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.menuFile.addAction(self.actionSettings) self.menuFile.addAction(self.actionExit) self.menuHelp.addAction(self.actionDocumentation) self.menuHelp.addAction(self.actionAbout) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle( QCoreApplication.translate("MainWindow", "projectdiffview", None) ) self.actionPreferences.setText( QCoreApplication.translate("MainWindow", "Preferences", None) ) # if QT_CONFIG(shortcut) self.actionPreferences.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+,", None) ) # endif // QT_CONFIG(shortcut) self.actionExit.setText(QCoreApplication.translate("MainWindow", "Exit", None)) # if QT_CONFIG(shortcut) self.actionExit.setShortcut(QCoreApplication.translate("MainWindow", "Ctrl+Q", None)) # endif // QT_CONFIG(shortcut) self.actionNew_Project.setText( QCoreApplication.translate("MainWindow", "New Project", None) ) # if QT_CONFIG(shortcut) self.actionNew_Project.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+N", None) ) # endif // QT_CONFIG(shortcut) self.actionSave.setText(QCoreApplication.translate("MainWindow", "Save", None)) # if QT_CONFIG(shortcut) self.actionSave.setShortcut(QCoreApplication.translate("MainWindow", "Ctrl+S", None)) # endif // QT_CONFIG(shortcut) self.actionOpen_Project.setText(QCoreApplication.translate("MainWindow", "Open", None)) # if QT_CONFIG(shortcut) self.actionOpen_Project.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+O", None) ) # endif // QT_CONFIG(shortcut) self.actionDocumentation.setText( QCoreApplication.translate("MainWindow", "Documentation", None) ) self.actionAbout.setText(QCoreApplication.translate("MainWindow", "About", None)) self.actionConsole_Visibility.setText( QCoreApplication.translate("MainWindow", "Console Visibility", None) ) # if QT_CONFIG(shortcut) self.actionConsole_Visibility.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+`", None) ) # endif // QT_CONFIG(shortcut) self.actionSave_As.setText(QCoreApplication.translate("MainWindow", "Save As", None)) # if QT_CONFIG(shortcut) self.actionSave_As.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+Shift+S", None) ) # endif // QT_CONFIG(shortcut) self.actionSettings.setText(QCoreApplication.translate("MainWindow", "Settings", None)) self.label.setText(QCoreApplication.translate("MainWindow", "Project Directory", None)) self.browse.setText(QCoreApplication.translate("MainWindow", "Browse", None)) self.label_2.setText(QCoreApplication.translate("MainWindow", "Template Version:", None)) self.label_3.setText(QCoreApplication.translate("MainWindow", "Folder Version:", None)) self.cleanup_working.setText( QCoreApplication.translate("MainWindow", "Cleanup Folder", None) ) self.copy_template.setText( QCoreApplication.translate("MainWindow", "Add All to Folder", None) ) self.add_selected.setText( QCoreApplication.translate("MainWindow", "Add Selected to Folder", None) ) self.menuFile.setTitle(QCoreApplication.translate("MainWindow", "&File", None)) self.menuHelp.setTitle(QCoreApplication.translate("MainWindow", "&Help", None)) # retranslateUi
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'gui.ui' ## ## Created by: Qt User Interface Compiler version 5.15.0 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import ( QCoreApplication, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, Qt, QTime, QUrl, ) from PySide2.QtGui import ( QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QIcon, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, ) from PySide2.QtWidgets import ( QAbstractItemView, QAction, QHBoxLayout, QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSizePolicy, QSpacerItem, QStatusBar, QTreeView, QVBoxLayout, QWidget, ) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName("MainWindow") MainWindow.resize(1200, 600) MainWindow.setDocumentMode(True) self.actionPreferences = QAction(MainWindow) self.actionPreferences.setObjectName("actionPreferences") self.actionExit = QAction(MainWindow) self.actionExit.setObjectName("actionExit") self.actionNew_Project = QAction(MainWindow) self.actionNew_Project.setObjectName("actionNew_Project") self.actionSave = QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.actionOpen_Project = QAction(MainWindow) self.actionOpen_Project.setObjectName("actionOpen_Project") self.actionDocumentation = QAction(MainWindow) self.actionDocumentation.setObjectName("actionDocumentation") self.actionAbout = QAction(MainWindow) self.actionAbout.setObjectName("actionAbout") self.actionConsole_Visibility = QAction(MainWindow) self.actionConsole_Visibility.setObjectName("actionConsole_Visibility") self.actionConsole_Visibility.setCheckable(True) self.actionConsole_Visibility.setChecked(True) self.actionSave_As = QAction(MainWindow) self.actionSave_As.setObjectName("actionSave_As") self.actionSettings = QAction(MainWindow) self.actionSettings.setObjectName("actionSettings") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout_3 = QVBoxLayout(self.centralwidget) self.verticalLayout_3.setObjectName("verticalLayout_3") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label = QLabel(self.centralwidget) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.directory_path = QLineEdit(self.centralwidget) self.directory_path.setObjectName("directory_path") self.horizontalLayout.addWidget(self.directory_path) self.browse = QPushButton(self.centralwidget) self.browse.setObjectName("browse") self.horizontalLayout.addWidget(self.browse) self.verticalLayout_3.addLayout(self.horizontalLayout) self.horizontalLayout_5 = QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.verticalLayout = QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.template_tree = QTreeView(self.centralwidget) self.template_tree.setObjectName("template_tree") self.template_tree.setEditTriggers(QAbstractItemView.NoEditTriggers) self.template_tree.setUniformRowHeights(True) self.template_tree.setSortingEnabled(True) self.template_tree.header().setMinimumSectionSize(20) self.template_tree.header().setDefaultSectionSize(150) self.template_tree.header().setStretchLastSection(False) self.verticalLayout.addWidget(self.template_tree) self.horizontalLayout_3 = QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.label_2 = QLabel(self.centralwidget) self.label_2.setObjectName("label_2") self.horizontalLayout_3.addWidget(self.label_2) self.template_version = QLineEdit(self.centralwidget) self.template_version.setObjectName("template_version") self.template_version.setReadOnly(True) self.horizontalLayout_3.addWidget(self.template_version) self.horizontalSpacer_2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_3.addItem(self.horizontalSpacer_2) self.verticalLayout.addLayout(self.horizontalLayout_3) self.horizontalLayout_5.addLayout(self.verticalLayout) self.verticalLayout_2 = QVBoxLayout() self.verticalLayout_2.setObjectName("verticalLayout_2") self.working_tree = QTreeView(self.centralwidget) self.working_tree.setObjectName("working_tree") self.working_tree.setEditTriggers(QAbstractItemView.NoEditTriggers) self.working_tree.setUniformRowHeights(True) self.working_tree.setSortingEnabled(True) self.working_tree.header().setMinimumSectionSize(20) self.working_tree.header().setDefaultSectionSize(150) self.working_tree.header().setStretchLastSection(False) self.verticalLayout_2.addWidget(self.working_tree) self.horizontalLayout_2 = QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label_3 = QLabel(self.centralwidget) self.label_3.setObjectName("label_3") self.horizontalLayout_2.addWidget(self.label_3) self.directory_version = QLineEdit(self.centralwidget) self.directory_version.setObjectName("directory_version") self.directory_version.setReadOnly(True) self.horizontalLayout_2.addWidget(self.directory_version) self.horizontalSpacer_3 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_2.addItem(self.horizontalSpacer_3) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.horizontalLayout_5.addLayout(self.verticalLayout_2) self.verticalLayout_3.addLayout(self.horizontalLayout_5) self.horizontalLayout_4 = QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout_4.addItem(self.horizontalSpacer) self.cleanup_working = QPushButton(self.centralwidget) self.cleanup_working.setObjectName("cleanup_working") self.cleanup_working.setFlat(False) self.horizontalLayout_4.addWidget(self.cleanup_working) self.copy_template = QPushButton(self.centralwidget) self.copy_template.setObjectName("copy_template") self.horizontalLayout_4.addWidget(self.copy_template) self.add_selected = QPushButton(self.centralwidget) self.add_selected.setObjectName("add_selected") self.horizontalLayout_4.addWidget(self.add_selected) self.verticalLayout_3.addLayout(self.horizontalLayout_4) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QMenuBar(MainWindow) self.menubar.setObjectName("menubar") self.menubar.setGeometry(QRect(0, 0, 1200, 22)) self.menubar.setDefaultUp(False) self.menuFile = QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuHelp = QMenu(self.menubar) self.menuHelp.setObjectName("menuHelp") MainWindow.setMenuBar(self.menubar) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.menuFile.addAction(self.actionSettings) self.menuFile.addAction(self.actionExit) self.menuHelp.addAction(self.actionDocumentation) self.menuHelp.addAction(self.actionAbout) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) # setupUi def retranslateUi(self, MainWindow): MainWindow.setWindowTitle( QCoreApplication.translate("MainWindow", "projectdiffview", None) ) self.actionPreferences.setText( QCoreApplication.translate("MainWindow", "Preferences", None) ) # if QT_CONFIG(shortcut) self.actionPreferences.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+,", None) ) # endif // QT_CONFIG(shortcut) self.actionExit.setText(QCoreApplication.translate("MainWindow", "Exit", None)) # if QT_CONFIG(shortcut) self.actionExit.setShortcut(QCoreApplication.translate("MainWindow", "Ctrl+Q", None)) # endif // QT_CONFIG(shortcut) self.actionNew_Project.setText( QCoreApplication.translate("MainWindow", "New Project", None) ) # if QT_CONFIG(shortcut) self.actionNew_Project.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+N", None) ) # endif // QT_CONFIG(shortcut) self.actionSave.setText(QCoreApplication.translate("MainWindow", "Save", None)) # if QT_CONFIG(shortcut) self.actionSave.setShortcut(QCoreApplication.translate("MainWindow", "Ctrl+S", None)) # endif // QT_CONFIG(shortcut) self.actionOpen_Project.setText(QCoreApplication.translate("MainWindow", "Open", None)) # if QT_CONFIG(shortcut) self.actionOpen_Project.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+O", None) ) # endif // QT_CONFIG(shortcut) self.actionDocumentation.setText( QCoreApplication.translate("MainWindow", "Documentation", None) ) self.actionAbout.setText(QCoreApplication.translate("MainWindow", "About", None)) self.actionConsole_Visibility.setText( QCoreApplication.translate("MainWindow", "Console Visibility", None) ) # if QT_CONFIG(shortcut) self.actionConsole_Visibility.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+`", None) ) # endif // QT_CONFIG(shortcut) self.actionSave_As.setText(QCoreApplication.translate("MainWindow", "Save As", None)) # if QT_CONFIG(shortcut) self.actionSave_As.setShortcut( QCoreApplication.translate("MainWindow", "Ctrl+Shift+S", None) ) # endif // QT_CONFIG(shortcut) self.actionSettings.setText(QCoreApplication.translate("MainWindow", "Settings", None)) self.label.setText(QCoreApplication.translate("MainWindow", "Project Directory", None)) self.browse.setText(QCoreApplication.translate("MainWindow", "Browse", None)) self.label_2.setText(QCoreApplication.translate("MainWindow", "Template Version:", None)) self.label_3.setText(QCoreApplication.translate("MainWindow", "Folder Version:", None)) self.cleanup_working.setText( QCoreApplication.translate("MainWindow", "Cleanup Folder", None) ) self.copy_template.setText( QCoreApplication.translate("MainWindow", "Add All to Folder", None) ) self.add_selected.setText( QCoreApplication.translate("MainWindow", "Add Selected to Folder", None) ) self.menuFile.setTitle(QCoreApplication.translate("MainWindow", "&File", None)) self.menuHelp.setTitle(QCoreApplication.translate("MainWindow", "&Help", None)) # retranslateUi
de
0.122805
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'gui.ui' ## ## Created by: Qt User Interface Compiler version 5.15.0 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ # setupUi # if QT_CONFIG(shortcut) # endif // QT_CONFIG(shortcut) # if QT_CONFIG(shortcut) # endif // QT_CONFIG(shortcut) # if QT_CONFIG(shortcut) # endif // QT_CONFIG(shortcut) # if QT_CONFIG(shortcut) # endif // QT_CONFIG(shortcut) # if QT_CONFIG(shortcut) # endif // QT_CONFIG(shortcut) # if QT_CONFIG(shortcut) # endif // QT_CONFIG(shortcut) # if QT_CONFIG(shortcut) # endif // QT_CONFIG(shortcut) # retranslateUi
1.468272
1
src/nn/exmple1.py
del680202/MachineLearning-memo
4
6614333
#!/usr/bin/env python # encoding: utf-8 from neuralnetwork import * # [(inputs, outputs)] dataset = [ ((0.3, 0.5), (0, 1))] nn = NeuralNetwork() hidden_layer = NeuronLayer(input_num=2, neuron_num=2, init_weights=[0.5, 0.3, 0.25, 0.6], bias=0.6) output_layer = NeuronLayer(input_num=2, neuron_num=2, init_weights=[0.1, 0.25, 0.2, 0.7], bias=0.5) nn.add_layer(hidden_layer) nn.add_layer(output_layer) nn.dump() tracking = [] for i in range(2000): nn.train(dataset) tracking.append(nn.calculate_total_error(dataset)) #for (i, e) in enumerate(tracking): # print "%sth square total error: %s" % (i+1, e) print "NeuralNetwork 2-2-2, Except output:[0, 1], Real output:%s" % nn.get_output([0.3, 0.5]) nn2 = NeuralNetwork() nn2.add_layer(NeuronLayer(input_num=2, neuron_num=5)) nn2.add_layer(NeuronLayer(input_num=5, neuron_num=5)) nn2.add_layer(NeuronLayer(input_num=5, neuron_num=2)) for i in range(2000): nn2.train(dataset) print "NeuralNetwork 2-5-5-2, Except output:[0, 1], Real output:%s" % nn2.get_output([0.3, 0.5]) # When model is too complex, it need more iterations to train #nn3 = NeuralNetwork() #nn3.add_layer(NeuronLayer(input_num=2, neuron_num=30)) #nn3.add_layer(NeuronLayer(input_num=30, neuron_num=2)) #for i in range(200000): # nn3.train(dataset) #print "NeuralNetwork 2-30-2, Except output:[0, 1], Real output:%s" % nn3.get_output([0.3, 0.5])
#!/usr/bin/env python # encoding: utf-8 from neuralnetwork import * # [(inputs, outputs)] dataset = [ ((0.3, 0.5), (0, 1))] nn = NeuralNetwork() hidden_layer = NeuronLayer(input_num=2, neuron_num=2, init_weights=[0.5, 0.3, 0.25, 0.6], bias=0.6) output_layer = NeuronLayer(input_num=2, neuron_num=2, init_weights=[0.1, 0.25, 0.2, 0.7], bias=0.5) nn.add_layer(hidden_layer) nn.add_layer(output_layer) nn.dump() tracking = [] for i in range(2000): nn.train(dataset) tracking.append(nn.calculate_total_error(dataset)) #for (i, e) in enumerate(tracking): # print "%sth square total error: %s" % (i+1, e) print "NeuralNetwork 2-2-2, Except output:[0, 1], Real output:%s" % nn.get_output([0.3, 0.5]) nn2 = NeuralNetwork() nn2.add_layer(NeuronLayer(input_num=2, neuron_num=5)) nn2.add_layer(NeuronLayer(input_num=5, neuron_num=5)) nn2.add_layer(NeuronLayer(input_num=5, neuron_num=2)) for i in range(2000): nn2.train(dataset) print "NeuralNetwork 2-5-5-2, Except output:[0, 1], Real output:%s" % nn2.get_output([0.3, 0.5]) # When model is too complex, it need more iterations to train #nn3 = NeuralNetwork() #nn3.add_layer(NeuronLayer(input_num=2, neuron_num=30)) #nn3.add_layer(NeuronLayer(input_num=30, neuron_num=2)) #for i in range(200000): # nn3.train(dataset) #print "NeuralNetwork 2-30-2, Except output:[0, 1], Real output:%s" % nn3.get_output([0.3, 0.5])
en
0.389699
#!/usr/bin/env python # encoding: utf-8 # [(inputs, outputs)] #for (i, e) in enumerate(tracking): # print "%sth square total error: %s" % (i+1, e) # When model is too complex, it need more iterations to train #nn3 = NeuralNetwork() #nn3.add_layer(NeuronLayer(input_num=2, neuron_num=30)) #nn3.add_layer(NeuronLayer(input_num=30, neuron_num=2)) #for i in range(200000): # nn3.train(dataset) #print "NeuralNetwork 2-30-2, Except output:[0, 1], Real output:%s" % nn3.get_output([0.3, 0.5])
3.426452
3
tests/test_one_line_logger.py
balosh-daniel/tuul
0
6614334
<filename>tests/test_one_line_logger.py #!/usr/bin/env python """Tests for `tuul` package.""" import logging import unittest from unittest.mock import patch import tuul class TestOneLineLogger(unittest.TestCase): def test_print_only_one_line(self): with self.assertLogs(level="DEBUG") as cm: logger = tuul.one_line_logger.get_logger() logger.debug("d1\nd2\n") logger.info("i1\ni2\n") logger.error("e1\ne2\n") try: 1 / 0 except ZeroDivisionError: logger.exception("x1\nx2\n") self.assertEqual(len(cm.output), 4, cm.output) self.assertEqual(len(cm.output[0].splitlines()), 1, cm.output[0]) self.assertEqual(len(cm.output[1].splitlines()), 1, cm.output[0]) self.assertEqual(len(cm.output[2].splitlines()), 1, cm.output[0]) def test_control_logging_level(self): with self.assertLogs(level="ERROR") as cm: logger = tuul.one_line_logger.get_logger(logging_level=logging.ERROR) logger.debug("d1\nd2\n") logger.info("i1\ni2\n") logger.error("e1\ne2\n") try: 1 / 0 except ZeroDivisionError: logger.exception("x1\nx2\n") self.assertEqual(len(cm.output), 2, cm.output) def test_set_aws_logger_level(self): for name in ["boto", "urllib3", "s3transfer", "boto3", "botocore", "nose"]: with self.assertLogs(level="DEBUG") as cm: logger = tuul.one_line_logger.get_logger() logger.debug("print me") l1 = logging.getLogger(name) l1.debug("I should not be printed") l1.info("I should not be printed") l1.critical("I should be printed") self.assertEqual(2, len(cm.output), cm.output) for name in ["boto", "urllib3", "s3transfer", "boto3", "botocore", "nose"]: with self.assertLogs(level="DEBUG") as cm: logger = tuul.one_line_logger.get_logger(aws_logging_level=logging.INFO) logger.debug("print me") l1 = logging.getLogger(name) l1.debug("I should not be printed") l1.info("I should be printed") l1.critical("I should be printed") self.assertEqual(3, len(cm.output), cm.output) @staticmethod def foo_raises(record): raise RuntimeError("boom") @patch.object( tuul.one_line_logger.OneLineFormatter, "_handle_non_exists_aws_request_id", foo_raises, ) def test_error_raised_in_formatter(self): with self.assertLogs(level="INFO") as cm: logger = tuul.one_line_logger.get_logger(logging_level=logging.DEBUG) logger.info("i1\ni2\n") self.assertEqual(len(cm.output), 1, cm.output) self.assertTrue("MONITOR_THIS " in cm.output[0], cm.output[0])
<filename>tests/test_one_line_logger.py #!/usr/bin/env python """Tests for `tuul` package.""" import logging import unittest from unittest.mock import patch import tuul class TestOneLineLogger(unittest.TestCase): def test_print_only_one_line(self): with self.assertLogs(level="DEBUG") as cm: logger = tuul.one_line_logger.get_logger() logger.debug("d1\nd2\n") logger.info("i1\ni2\n") logger.error("e1\ne2\n") try: 1 / 0 except ZeroDivisionError: logger.exception("x1\nx2\n") self.assertEqual(len(cm.output), 4, cm.output) self.assertEqual(len(cm.output[0].splitlines()), 1, cm.output[0]) self.assertEqual(len(cm.output[1].splitlines()), 1, cm.output[0]) self.assertEqual(len(cm.output[2].splitlines()), 1, cm.output[0]) def test_control_logging_level(self): with self.assertLogs(level="ERROR") as cm: logger = tuul.one_line_logger.get_logger(logging_level=logging.ERROR) logger.debug("d1\nd2\n") logger.info("i1\ni2\n") logger.error("e1\ne2\n") try: 1 / 0 except ZeroDivisionError: logger.exception("x1\nx2\n") self.assertEqual(len(cm.output), 2, cm.output) def test_set_aws_logger_level(self): for name in ["boto", "urllib3", "s3transfer", "boto3", "botocore", "nose"]: with self.assertLogs(level="DEBUG") as cm: logger = tuul.one_line_logger.get_logger() logger.debug("print me") l1 = logging.getLogger(name) l1.debug("I should not be printed") l1.info("I should not be printed") l1.critical("I should be printed") self.assertEqual(2, len(cm.output), cm.output) for name in ["boto", "urllib3", "s3transfer", "boto3", "botocore", "nose"]: with self.assertLogs(level="DEBUG") as cm: logger = tuul.one_line_logger.get_logger(aws_logging_level=logging.INFO) logger.debug("print me") l1 = logging.getLogger(name) l1.debug("I should not be printed") l1.info("I should be printed") l1.critical("I should be printed") self.assertEqual(3, len(cm.output), cm.output) @staticmethod def foo_raises(record): raise RuntimeError("boom") @patch.object( tuul.one_line_logger.OneLineFormatter, "_handle_non_exists_aws_request_id", foo_raises, ) def test_error_raised_in_formatter(self): with self.assertLogs(level="INFO") as cm: logger = tuul.one_line_logger.get_logger(logging_level=logging.DEBUG) logger.info("i1\ni2\n") self.assertEqual(len(cm.output), 1, cm.output) self.assertTrue("MONITOR_THIS " in cm.output[0], cm.output[0])
en
0.288768
#!/usr/bin/env python Tests for `tuul` package.
2.878037
3
crownstone_core/packets/debug/PowerSamplesPacket.py
crownstone/crownstone-lib-python-core
0
6614335
<filename>crownstone_core/packets/debug/PowerSamplesPacket.py from crownstone_core.protocol.BluenetTypes import PowerSamplesType from crownstone_core.util.BufferReader import BufferReader class PowerSamplesPacket: def __init__(self, data): self.samplesType = PowerSamplesType.UNSPECIFIED self.index = 0 # uint8 self.count = 0 # uint16 self.timestamp = 0 # uint32 self.delayUs = 0 # uint16 self.sampleIntervalUs = 0 # uint16 self.reserved = 0 # 2 bytes self.offset = 0 # int16 self.multiplier = 0.0 # float self.samples = [] # int16 list self.load(data) def load(self, data): """ Parses data buffer to set member variables. data : list of bytes Raises exception when parsing fails. """ streamBuf = BufferReader(data) samplesTypeVal = streamBuf.getUInt8() self.samplesType = PowerSamplesType(samplesTypeVal) # Throws exception of value is not in enum self.index = streamBuf.getUInt8() self.count = streamBuf.getUInt16() self.timestamp = streamBuf.getUInt32() self.delayUs = streamBuf.getUInt16() self.sampleIntervalUs = streamBuf.getUInt16() streamBuf.skip(2) self.offset = streamBuf.getInt16() self.multiplier = streamBuf.getFloat() self.samples = [] for i in range(0, self.count): self.samples.append(streamBuf.getInt16()) def toString(self): msg = "PowerSamplesPacket(" msg += "type=" + str(self.samplesType) msg += " count=" + str(self.count) msg += " timestamp=" + str(self.timestamp) msg += " delayUs=" + str(self.delayUs) msg += " sampleIntervalUs=" + str(self.sampleIntervalUs) msg += " offset=" + str(self.offset) msg += " multiplier=" + str(self.multiplier) msg += " samples=" + str(self.samples) msg += ")" return msg def __str__(self): return self.toString()
<filename>crownstone_core/packets/debug/PowerSamplesPacket.py from crownstone_core.protocol.BluenetTypes import PowerSamplesType from crownstone_core.util.BufferReader import BufferReader class PowerSamplesPacket: def __init__(self, data): self.samplesType = PowerSamplesType.UNSPECIFIED self.index = 0 # uint8 self.count = 0 # uint16 self.timestamp = 0 # uint32 self.delayUs = 0 # uint16 self.sampleIntervalUs = 0 # uint16 self.reserved = 0 # 2 bytes self.offset = 0 # int16 self.multiplier = 0.0 # float self.samples = [] # int16 list self.load(data) def load(self, data): """ Parses data buffer to set member variables. data : list of bytes Raises exception when parsing fails. """ streamBuf = BufferReader(data) samplesTypeVal = streamBuf.getUInt8() self.samplesType = PowerSamplesType(samplesTypeVal) # Throws exception of value is not in enum self.index = streamBuf.getUInt8() self.count = streamBuf.getUInt16() self.timestamp = streamBuf.getUInt32() self.delayUs = streamBuf.getUInt16() self.sampleIntervalUs = streamBuf.getUInt16() streamBuf.skip(2) self.offset = streamBuf.getInt16() self.multiplier = streamBuf.getFloat() self.samples = [] for i in range(0, self.count): self.samples.append(streamBuf.getInt16()) def toString(self): msg = "PowerSamplesPacket(" msg += "type=" + str(self.samplesType) msg += " count=" + str(self.count) msg += " timestamp=" + str(self.timestamp) msg += " delayUs=" + str(self.delayUs) msg += " sampleIntervalUs=" + str(self.sampleIntervalUs) msg += " offset=" + str(self.offset) msg += " multiplier=" + str(self.multiplier) msg += " samples=" + str(self.samples) msg += ")" return msg def __str__(self): return self.toString()
en
0.742306
# uint8 # uint16 # uint32 # uint16 # uint16 # 2 bytes # int16 # float # int16 list Parses data buffer to set member variables. data : list of bytes Raises exception when parsing fails. # Throws exception of value is not in enum
2.244307
2
Towers/main.py
avivgood/Reinforcement-learning-starters-template
0
6614336
<reponame>avivgood/Reinforcement-learning-starters-template import asyncio from Enums.gameLevel import GameLevel from eventNotifier import _game_tick, _game_turn from map import Map async def main(): map_ = Map(GameLevel.EASY.value) async def driver(): await asyncio.gather(_game_tick(), _game_turn(), main()) if __name__ == '__main__': asyncio.run(driver())
import asyncio from Enums.gameLevel import GameLevel from eventNotifier import _game_tick, _game_turn from map import Map async def main(): map_ = Map(GameLevel.EASY.value) async def driver(): await asyncio.gather(_game_tick(), _game_turn(), main()) if __name__ == '__main__': asyncio.run(driver())
none
1
2.60501
3
HIV/params.py
jonathanhhb/bindery_demo
0
6614337
<reponame>jonathanhhb/bindery_demo exp_name="HIV Rakai Simpler CoC" nSims = 1 base_year=1960.5
exp_name="HIV Rakai Simpler CoC" nSims = 1 base_year=1960.5
none
1
0.892477
1
semparse/attention.py
lukovnikov/semparse
0
6614338
import torch import qelos as q import numpy as np import math # region normal attention class AttComp(torch.nn.Module): """ computes attention scores """ def forward(self, qry, ctx, ctx_mask=None): raise NotImplemented() class SummComp(torch.nn.Module): def forward(self, values, alphas): raise NotImplemented() class Attention(torch.nn.Module): """ Computes phrase attention. For use with encoders and decoders from rnn.py """ def __init__(self, attcomp:AttComp=None, summcomp:SummComp=None, score_norm=torch.nn.Softmax(-1)): """ :param attcomp: used to compute attention scores :param summcomp: used to compute summary """ super(Attention, self).__init__() # self.prevatts = None # holds previous attention vectors # self.prevatt_ptr = None # for every example, contains a list with pointers to indexes of prevatts self.attcomp = attcomp if attcomp is not None else DotAttComp() self.summcomp = summcomp if summcomp is not None else SumSummComp() self.score_norm = score_norm def forward(self, qry, ctx, ctx_mask=None, values=None): """ :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :return: """ scores = self.attcomp(qry, ctx, ctx_mask=ctx_mask) scores = scores + (torch.log(ctx_mask.float()) if ctx_mask is not None else 0) alphas = self.score_norm(scores) values = ctx if values is None else values summary = self.summcomp(values, alphas) return alphas, summary, scores class DotAttComp(AttComp): def forward(self, qry, ctx, ctx_mask=None): """ :param qry: (batsize, dim) or (batsize, zeqlen, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: :return: """ if qry.dim() == 2: ret = torch.einsum("bd,bsd->bs", [qry, ctx]) elif qry.dim() == 3: ret = torch.einsum("bzd,bsd->bzs", [qry, ctx]) else: raise q.SumTingWongException("qry has unsupported dimension: {}".format(qry.dim())) return ret class FwdAttComp(AttComp): def __init__(self, qrydim=None, ctxdim=None, encdim=None, numlayers=1, dropout=0, **kw): super(FwdAttComp, self).__init__(**kw) layers = [torch.nn.Linear(qrydim + ctxdim, encdim)] \ + [torch.nn.Linear(encdim, encdim) for _ in range(numlayers - 1)] acts = [torch.nn.Tanh() for _ in range(len(layers))] layers = [a for b in zip(layers, acts) for a in b] layers.append(torch.nn.Dropout(dropout)) layers.append(torch.nn.Linear(encdim, 1)) self.mlp = torch.nn.Sequential(*layers) def forward(self, qry, ctx, ctx_mask=None): """ :param qry: (batsize, qrydim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :return: """ inp = torch.cat([ctx, qry.unsqueeze(1).repeat(1, ctx.size(1), 1)], 2) out = self.mlp(inp) ret = out.squeeze(-1) return ret class SumSummComp(SummComp): def forward(self, values, alphas): summary = values * alphas.unsqueeze(2) summary = summary.sum(1) return summary class BasicAttention(Attention): def __init__(self, **kw): attcomp = DotAttComp() summcomp = SumSummComp() super(BasicAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, **kw) class FwdAttention(Attention): def __init__(self, qrydim, ctxdim, encdim, dropout=0., **kw): attcomp = FwdAttComp(qrydim=qrydim, ctxdim=ctxdim, encdim=encdim, dropout=dropout) summcomp = SumSummComp() super(FwdAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, **kw) # endregion # region Relative Attention class VecComp(torch.nn.Module): """ maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention """ def __init__(self, ctxdim, vecdim, **kw): super(VecComp, self).__init__(**kw) self.ctxdim, self.vecdim = ctxdim, vecdim def forward(self, ctx): """ :param ctx: (batsize, seqlen, ctxdim) :return: (batsize, seqlen, seqlen, vecdim) """ raise NotImplemented() class FwdVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(FwdVecComp, self).__init__(ctxdim, vecdim, **kw) self.lin1 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin2 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.nonlin = torch.nn.Tanh() def forward(self, ctx): out1 = self.lin1(ctx) out2 = self.lin2(ctx) # (batsize, seqlen, vecdim) out = self.nonlin(out1.unsqueeze(1) + out2.unsqueeze(2)) return out class ComboFwdVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(ComboFwdVecComp, self).__init__(ctxdim, vecdim, **kw) self.lin1 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin2 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_mul = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_diff = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.nonlin = torch.nn.Tanh() def forward(self, ctx): out1 = self.lin1(ctx) out2 = self.lin2(ctx) # (batsize, seqlen, vecdim) mul = ctx.unsqueeze(1) * ctx.unsqueeze(2) # (batsize, seqlen, seqlen, vecdim) diff = ctx.unsqueeze(1) - ctx.unsqueeze(2) outmul = self.lin_mul(mul) outdiff = self.lin_diff(diff) out = self.nonlin(out1.unsqueeze(1) + out2.unsqueeze(2) + outmul + outdiff) return out class BilinVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(BilinVecComp, self).__init__(ctxdim, vecdim, **kw) self.W = torch.nn.Parameter(torch.Tensor(ctxdim, ctxdim, vecdim)) self.bias = torch.nn.Parameter(torch.Tensor(vecdim)) if bias else None self.nonlin = torch.nn.Tanh() self.reset_parameters() def reset_parameters(self): bound = 1 / math.sqrt(self.weight.size(1)) torch.init.uniform_(self.weight, -bound, bound) if self.bias is not None: torch.init.uniform_(self.bias, -bound, bound) def forward(self, ctx): out = torch.einsum("bsi,bzj,ijk->bszk", ctx, ctx, self.W) if self.bias is not None: out = out + self.bias out = self.nonlin(out) return out class BilinAndFwdComboVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(BilinAndFwdComboVecComp, self).__init__(ctxdim, vecdim, **kw) self.W = torch.nn.Parameter(torch.Tensor(ctxdim, ctxdim, vecdim)) self.bias = torch.nn.Parameter(torch.Tensor(vecdim)) if bias else None self.lin1 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin2 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_mul = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_diff = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.nonlin = torch.nn.Tanh() self.reset_parameters() def reset_parameters(self): bound = 1 / math.sqrt(self.weight.size(1)) torch.init.uniform_(self.weight, -bound, bound) if self.bias is not None: torch.init.uniform_(self.bias, -bound, bound) def forward(self, ctx): out = torch.einsum("bsi,bzj,ijk->bszk", ctx, ctx, self.W) if self.bias is not None: out = out + self.bias out1 = self.lin1(ctx) out2 = self.lin2(ctx) # (batsize, seqlen, vecdim) mul = ctx.unsqueeze(1) * ctx.unsqueeze(2) # (batsize, seqlen, seqlen, vecdim) diff = ctx.unsqueeze(1) - ctx.unsqueeze(2) outmul = self.lin_mul(mul) outdiff = self.lin_diff(diff) out = self.nonlin(out + out1.unsqueeze(1) + out2.unsqueeze(2) + outmul + outdiff) return out class RelAttention(torch.nn.Module): def __init__(self, veccomp:VecComp=None, attcomp:AttComp=DotAttComp(), summcomp:SummComp=SumSummComp(), temperature=1., threshold=1e-6, **kw): super(RelAttention, self).__init__(**kw) self.threshold, self.temperature = threshold, temperature self.veccomp = veccomp # maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention self.attcomp, self.summcomp = attcomp, summcomp self.scorenorm = torch.nn.Softmax(-1) self.prevatts = None # (batsize, seqlen) self.relvecs = None # (batsize, seqlen, seqlen, vecdim) self.prevatts_history = [] # will become decseqlen-sized list of prevatts (batsize, seqlen) self.feed_prevatts_acc = None # decseqlen-sized list of prevatts (batsize, seqlen) self.t = 0 self._bad_prevatts = False def batch_reset(self): self.prevatts = None self.relvecs = None self.prevatts_history = [] self.feed_prevatts_acc = None self.t = 0 def forward(self, qry, ctx, ctx_mask=None, values=None): """ :param qry: (batsize, qdim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen) :return: """ # initialize prevatts if None: init assigns all prob to first element --> first element of ctx must be a start token if self.prevatts is None: self.prevatts = torch.zeros_like(ctx[:, :, 0]) self.prevatts[:, 0] = 1. # create and store relation vectors self.relvecs = self.veccomp(ctx) # get non-negligible part of relvecs # TODO: do sparse for more efficiency # relvecs_idxs = torch.nonzero(self.prevatts > self.threshold) # do attcomp with qry over relvecs flatrelvecs = self.relvecs.view(self.relvecs.size(0), self.relvecs.size(1) * self.relvecs.size(2), self.relvecs.size(3)) # (batsize, seqlen*seqlen, vecdim) flatrelatt_scores = self.attcomp(qry, flatrelvecs) # (batsize, seqlen * seqlen) relatt_scores = flatrelatt_scores.view(self.relvecs.size(0), self.relvecs.size(1), self.relvecs.size(2)) # (batsize, seqlen, seqlen) # apply ctx_mask before summary relatt_scores = relatt_scores + (torch.log(ctx_mask.float().unsqueeze(1)) if ctx_mask is not None else 0) relatt_alphas = self.scorenorm(relatt_scores) # (batsize, seqlen, seqlen) alphas = torch.einsum("bsz,bs->bz", relatt_alphas, self.prevatts) self.prevatts = alphas if self._bad_prevatts is True: self.prevatts = torch.zeros_like(ctx[:, :, 0]) self.prevatts[:, 2] = 1. # saving history and using feed: self.prevatts_history.append(self.prevatts) if self.feed_prevatts_acc is not None: self.prevatts = self.feed_prevatts_acc[self.t] values = ctx if values is None else values summary = self.summcomp(values, alphas) self.t += 1 return alphas, summary, relatt_scores class BasicRelAttention(RelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = FwdVecComp(ctxdim, vecdim, bias=bias) super(BasicRelAttention, self).__init__(veccomp, **kw) class ComboRelAttention(RelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = ComboFwdVecComp(ctxdim, vecdim, bias=bias) super(ComboRelAttention, self).__init__(veccomp, **kw) class AbsRelAttention(torch.nn.Module): """ Attention mechanism consisting of first absolute attention, followed by a relative attention step --> doesn't need prevatts """ def __init__(self, prevattcomp:AttComp=DotAttComp(), veccomp:VecComp=None, attcomp:AttComp=DotAttComp(), summcomp:SummComp=SumSummComp(), temperature=1., threshold=1e-6, **kw): super(AbsRelAttention, self).__init__(**kw) self.threshold, self.temperature = threshold, temperature self.prevattcomp = prevattcomp self.veccomp = veccomp # maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention self.attcomp, self.summcomp = attcomp, summcomp self.scorenorm = torch.nn.Softmax(-1) self.relvecs = None # (batsize, seqlen, seqlen, vecdim) self.t = 0 def batch_reset(self): self.relvecs = None self.t = 0 def forward(self, qry, ctx, ctx_mask=None, values=None): """ :param qry: (batsize, qdim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen) :return: """ if self.relvecs is None: # create and store relation vectors self.relvecs = self.veccomp(ctx) prevatts = self.prevattcomp(qry, ctx, ctx_mask=ctx_mask) prevatts += (torch.log(ctx_mask.float()) if ctx_mask is not None else 0) prevatts = self.scorenorm(prevatts) # get non-negligible part of relvecs # TODO: do sparse for more efficiency # relvecs_idxs = torch.nonzero(self.prevatts > self.threshold) # do attcomp with qry over relvecs flatrelvecs = self.relvecs.view(self.relvecs.size(0), self.relvecs.size(1) * self.relvecs.size(2), self.relvecs.size(3)) # (batsize, seqlen*seqlen, vecdim) flatrelatt_scores = self.attcomp(qry, flatrelvecs) # (batsize, seqlen * seqlen) relatt_scores = flatrelatt_scores.view(self.relvecs.size(0), self.relvecs.size(1), self.relvecs.size(2)) # (batsize, seqlen, seqlen) # apply ctx_mask before summary relatt_scores = relatt_scores + (torch.log(ctx_mask.float().unsqueeze(1)) if ctx_mask is not None else 0) relatt_alphas = self.scorenorm(relatt_scores) # (batsize, seqlen, seqlen) alphas = torch.einsum("bsz,bs->bz", relatt_alphas, prevatts) values = ctx if values is None else values summary = self.summcomp(values, alphas) self.t += 1 return alphas, summary, relatt_scores class BasicAbsRelAttention(AbsRelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = FwdVecComp(ctxdim, vecdim, bias=bias) super(BasicAbsRelAttention, self).__init__(veccomp=veccomp, **kw) class ComboAbsRelAttention(AbsRelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = ComboFwdVecComp(ctxdim, vecdim, bias=bias) super(ComboAbsRelAttention, self).__init__(veccomp=veccomp, **kw) def test_rel_attention(lr=0.): qry = torch.randn(2, 5) ctx = torch.randn(2, 3, 6) ctx_mask = torch.tensor([ [1,1,0], [1,1,1] ]) m = ComboRelAttention(6, 5) y = m(qry, ctx, ctx_mask=ctx_mask) print(y) # endregion # region Phrase Attention # function with a custom backward for getting gradients to both parent and children in PhraseAttention # forward is an elementwise min # backward: - alphas always gets whole gradient # - parent_alphas is increased when gradient > 0 else nothing # (so parent's attention can only be increased here if the child needs to attend more to certain places) # (if we equally tried to decrease parent's attentions here too, then would have conflicting signals from its children's attentions, which may not overlap) # (decrease comes from overlap penalty and gradient on parent attention itself) class ParentOverlapFunction(torch.autograd.Function): @staticmethod def forward(ctx, parent_alphas, alphas): ctx.save_for_backward(parent_alphas, alphas) ret = torch.min(parent_alphas, alphas) return ret @staticmethod def backward(ctx, grad_output): gradzeros = torch.zeros_like(grad_output) parent_grads = torch.max(gradzeros, grad_output) return parent_grads, grad_output def parent_overlap_f_parent_first(parent_alphas, alphas): alphas = 1 - alphas _z = torch.min(torch.tensor(1.0), parent_alphas / alphas) z = parent_alphas - alphas * _z.detach() return z parent_overlap_f = ParentOverlapFunction.apply # parent_overlap_f = parent_overlap_f_parent_first def test_custom_f(lr=0): x = torch.rand(5) x.requires_grad = True y = torch.rand(5) y.requires_grad = True z = parent_overlap_f(x, y) l = z #z.sum() l.backward(gradient=torch.tensor([-1,1,-1,1,1]).float()) print(x) print(y) print(z) print(x.grad) print(y.grad) class PhraseAttention(Attention): # for depth-first decoding """ Assumes masking by termination of tree structure assuming single root (which is also start token) """ def __init__(self, attcomp:AttComp=None, summcomp:SummComp=None, hard=False, **kw): score_norm = torch.nn.Sigmoid() super(PhraseAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, score_norm=score_norm) self.hard = hard self.prevatts_probs = None # (batsize, declen_so_far, enclen) if self.hard is True: self.prevatts_samples = None self.prevatts_mask = None self.prevatt_ptr = None # for every example, keeps a list of pointers to positions in prevatts # structure: batsize x stackdepth x numsiblings # For every example, the stack contains groups of siblings. # Could have had just batsize x stackdepth, but need to remember siblings for sibling overlap penalty (see prevatt_siblings) self.prevatt_siblings = None # for every example, keeps a list of sets of pointers to groups of siblings # structure: batsize x num_sibling_groups x num_siblings_in_group # Mainly populated during forward (with a finalization step for top-level siblings in get_sibling_overlap). # Consumed in get_sibling_overlap. def batch_reset(self): self.prevatts_probs, self.prevatt_ptr = None, None self.prevatt_siblings = None if self.hard is True: self.prevatts_samples = None self.prevatts_mask = None def get_sibling_overlap(self): # called after all forwards are done """ Gets overlap in siblings based on current state of prevatts and prevatt_ptr. Must be called after a batch and before batch reset. """ # finalize prevattr_ptr for i, prevattr_ptr_e in enumerate(self.prevatt_ptr): if len(prevattr_ptr_e) != 2: # must contain only the zero-group and top-level group pass # raise q.SumTingWongException() while len(prevattr_ptr_e) > 0: ptr_group = prevattr_ptr_e.pop() if len(ptr_group) > 1: pass # self.prevatt_siblings[i].append(ptr_group) # don't add overlap of top-level siblings (we assume single top child, everything else is mask) # generate ids by which to gather from prevatts ids = torch.zeros(self.prevatts_probs.size(0), self.prevatts_probs.size(1), self.prevatts_probs.size(1), dtype=torch.long, device=self.prevatts_probs.device) maxnumsiblingses, maxnumsiblings = 0, 0 for eid, siblingses in enumerate(self.prevatt_siblings): # list of lists of ids in prevatts maxnumsiblingses = max(maxnumsiblingses, len(siblingses)) for sgid, siblings in enumerate(siblingses): # list of ids in prevatts maxnumsiblings = max(maxnumsiblings, len(siblings)) for sid, sibling in enumerate(siblings): ids[eid, sgid, sid] = sibling ids = ids[:, :maxnumsiblingses, :maxnumsiblings] prevatts = self.prevatts_probs idsmask= ((ids != 0).sum(2, keepdim=True) > 1).float() # gather from prevatts _ids = ids.contiguous().view(ids.size(0), -1).unsqueeze(-1).repeat(1, 1, prevatts.size(2)) prevatts_gathered = torch.gather(prevatts, 1, _ids) prevatts_gathered = prevatts_gathered.view(prevatts.size(0), ids.size(1), ids.size(2), prevatts.size(2)) # compute overlaps overlaps = prevatts_gathered.prod(2) overlaps = overlaps * idsmask overlaps = overlaps.sum(2).sum(1) # overlaps = overlaps.mean(0) return overlaps def get_logprob_of_sampled_alphas(self): if self.hard is False: raise q.SumTingWongException("Use this only for RL on hard attention (must be in hard mode).") probs = self.prevatts_probs * self.prevatts_samples + (1 - self.prevatts_probs) * (1 - self.prevatts_samples) logprobs = torch.log(probs) logprobs = logprobs * self.prevatts_mask # mask the logprobs average_within_timestep = True if average_within_timestep: totals = self.prevatts_mask.sum(2) + 1e-6 logprobs = logprobs.sum(2) / totals else: logprobs = logprobs.mean(2) return logprobs[:, 2:] # (batsize, seqlen) -- decoder mask should be applied on this later def get_entropies_of_alpha_dists(self): probs = self.prevatts_probs dists = torch.distributions.Bernoulli(probs=probs) entropies = dists.entropy() entropies = entropies * self.prevatts_mask average_within_timestep = True if average_within_timestep: totals = self.prevatts_mask.sum(2) + 1e-12 entropies = entropies.sum(2) / totals else: entropies = entropies.mean(2) return entropies[:, 2:] # (batsize, seqlen) -- decoder mask should be applied on this later def forward(self, qry, ctx, ctx_mask=None, values=None, prev_pushpop=None): """ :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :param prev_pushpop: (batsize,) - whether PREVIOUS token was a push or pop (or do-nothing) token: -N ==> pop (N=how many to pop), 0 ==> nothing, +N ==> push (N doesn't matter, always pushes one) ! push/pop happens AFTER the element :return: """ # compute attention for token that we will produce next # compute attention scores scores = self.attcomp(qry, ctx, ctx_mask=ctx_mask) # apply ctx mask to attention scores scores = scores + (torch.log(ctx_mask.float()) if ctx_mask is not None else 0) # normalize attention scores alphas_probs = self.score_norm(scores) # sigmoid probs if self.hard: alphas_dist = torch.distributions.Bernoulli(probs=alphas_probs) alphas_samples = alphas_dist.sample() # constrain alphas to parent's alphas: if self.prevatts_probs is None: # there is no history # initialize prevatts (history) self.prevatts_probs = torch.ones_like(alphas_probs).unsqueeze(1).repeat(1, 2, 1) # means everything is attended to if ctx_mask is not None: self.prevatts_probs = self.prevatts_probs * ctx_mask.float().unsqueeze(1) if self.hard is True: self.prevatts_samples = self.prevatts_probs.clone().detach() #torch.ones_like(alphas_probs).unsqueeze(1).repeat(1, 2, 1) self.prevatts_mask = torch.zeros_like(alphas_probs).unsqueeze(1).repeat(1, 2, 1) # --> we assume the previous (first ever) attention, used to compute initial (current input) token attended over whole sequence # initialize prevatt_ptr self.prevatt_ptr = [[[0], []] for _ in range(len(prev_pushpop))] # initialize prevatt_siblings self.prevatt_siblings = [[] for _ in range(len(prev_pushpop))] # update pointers to prevatt k = self.prevatts_probs.size(1) - 1 # index of the last produced attention alphas (that were used for prev token) for i in range(len(prev_pushpop)): self.prevatt_ptr[i][-1].append(k) # make last token a sibling of the children of the same parent before it (if any) if prev_pushpop[i].cpu().item() > 0: # PUSH: previous token requires children --> make stack deeper by one level self.prevatt_ptr[i].append([]) elif prev_pushpop[i].cpu().item() < 0: # POP: previous token was last in its row of siblings (and possibly terminates upwards levels too) pp = prev_pushpop[i].cpu().item() while pp < 0 and len(self.prevatt_ptr[i]) > 2: siblings = self.prevatt_ptr[i].pop(-1) # pop the list from stack if len(siblings) > 1: # if longer than 1, add to the list of siblings self.prevatt_siblings[i].append(siblings) pp += 1 else: pass # constrain alphas to parent's alphas parent_ptr = [prevatt_ptr_e[-2][-1] for prevatt_ptr_e in self.prevatt_ptr] parent_ptr = torch.tensor(parent_ptr).long().to(self.prevatts_probs.device) if self.hard is True: # no backprop through alphas # parent_alphas_probs = self.prevatts_probs.gather(1, parent_ptr.unsqueeze(-1).unsqueeze(-1) # .repeat(1, 1, self.prevatts_probs.size(-1))).squeeze(1) parent_alphas_samples = self.prevatts_samples.gather(1, parent_ptr.unsqueeze(-1).unsqueeze(-1) .repeat(1, 1, self.prevatts_samples.size(-1))).squeeze(1) alphas_samples = torch.min(parent_alphas_samples, alphas_samples) # save parent-masked samples self.prevatts_samples = torch.cat([self.prevatts_samples, alphas_samples.unsqueeze(1)], 1) self.prevatts_mask = torch.cat([self.prevatts_mask, parent_alphas_samples.unsqueeze(1)], 1) alphas = alphas_samples else: # need to backprop differently parent_alphas_probs = self.prevatts_probs.gather(1, parent_ptr.unsqueeze(-1).unsqueeze(-1) .repeat(1, 1, self.prevatts_probs.size(-1))).squeeze(1) alphas_probs = parent_overlap_f(parent_alphas_probs, alphas_probs) alphas = alphas_probs # append current alpha probs to prevatts accumulator self.prevatts_probs = torch.cat([self.prevatts_probs, alphas_probs.unsqueeze(1)], 1) # compute summary values = ctx if values is None else values summary = self.summcomp(values, alphas) return alphas, summary, scores class PhraseAttentionTeacher(Attention): # for depth-first decoding """ Normal attention. Stores probs for the batch for use to supervise real phrase attention. """ """ Assumes masking by termination of tree structure assuming single root (which is also start token) """ def __init__(self, attcomp:AttComp=None, hard=True, **kw): score_norm = torch.nn.Softmax(-1) summcomp = SumSummComp() super(PhraseAttentionTeacher, self).__init__(attcomp=attcomp, summcomp=summcomp, score_norm=score_norm) self.prevatts_probs = None # (batsize, declen_so_far, enclen) self.prevatt_ptr = None # for every example, keeps a list of pointers to positions in prevatts self.prevatts_masks = None # structure: batsize x stackdepth x numsiblings # For every example, the stack contains groups of siblings. # Could have had just batsize x stackdepth, but need to remember siblings for sibling overlap penalty (see prevatt_siblings) self.record = False self.hard = hard def batch_reset(self): self.prevatts_probs, self.prevatt_ptr = None, None self.prevatts_masks = None def get_phraseatt_supervision(self, hard=True): """ Propagates attentions in self.prevatts_probs from children to parents according to self.prevatt_ptr, this way converting softmax attentions generated here to a supervision signal usable for sigmoid attention. If hard, does argmax before propagating, else propagates probs. """ return self.prevatts_probs, self.prevatts_masks def forward(self, qry, ctx, ctx_mask=None, values=None, prev_pushpop=None): """ :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :param prev_pushpop: (batsize,) - whether PREVIOUS token was a push or pop (or do-nothing) token: -N ==> pop (N=how many to pop), 0 ==> nothing, +N ==> push (N doesn't matter, always pushes one) ! push/pop happens AFTER the element :return: """ alphas_probs, summary, scores = super(PhraseAttentionTeacher, self).forward(qry, ctx, ctx_mask=ctx_mask, values=values) if self.record is True: if self.prevatts_probs is None: # there is no history # initialize prevatts (history) self.prevatts_probs = torch.zeros_like(alphas_probs).unsqueeze(1) # initialize prevatt masks self.prevatts_masks = torch.ones_like(alphas_probs).unsqueeze(1) if ctx_mask is not None: self.prevatts_masks = self.prevatts_masks * ctx_mask.unsqueeze(1).float() # initialize prevatt_ptr self.prevatt_ptr = [[[]] for _ in range(len(prev_pushpop))] # update pointers to prevatt k = self.prevatts_probs.size(1) - 1 # index of the last produced attention alphas (that were used for prev token) for i in range(len(prev_pushpop)): # iterate over all examples self.prevatt_ptr[i][-1].append(k) # make last token a sibling of the children of the same parent before it (if any) if prev_pushpop[i].cpu().item() > 0: # PUSH: previous token requires children --> make stack deeper by one level self.prevatt_ptr[i].append([]) elif prev_pushpop[i].cpu().item() < 0: # POP: previous token was last in its row of siblings (and possibly terminates upwards levels too) pp = prev_pushpop[i].cpu().item() while pp < 0 and len(self.prevatt_ptr[i]) > 1: siblings = self.prevatt_ptr[i].pop(-1) # pop the list from stack # add each of the sibling's attention probs to their parent and populate children's masks parent = self.prevatt_ptr[i][-1][-1] for sibling in siblings: sibling_alphas = self.prevatts_probs[i, sibling] self.prevatts_probs[i, parent] += sibling_alphas self.prevatts_probs[i, parent].clamp_(0., 1.) parent_alphas = self.prevatts_probs[i, parent] for sibling in siblings: self.prevatts_masks[i, sibling] = parent_alphas pp += 1 else: pass # append current alpha probs to prevatts accumulator if self.hard: # _alphas_probs = torch.zeros_like(alphas_probs)\ # .scatter_(1, torch.argmax(alphas_probs, 1, True), 1.) alphas_dist = torch.distributions.OneHotCategorical(probs=alphas_probs) _alphas_probs = alphas_dist.sample() else: _alphas_probs = alphas_probs self.prevatts_probs = torch.cat([self.prevatts_probs, _alphas_probs.unsqueeze(1)], 1) self.prevatts_masks = torch.cat([self.prevatts_masks, torch.zeros_like(_alphas_probs.unsqueeze(1))], 1) # will be filled once siblings have been done return alphas_probs, summary, scores def test_phrase_attention(lr=0): # simulate operation of attention ctx = torch.randn(2, 5, 4) qrys = torch.randn(2, 6, 4) ctx_mask = torch.tensor([[1,1,1,1,1],[1,1,1,0,0]]) pushpop = torch.tensor([[1,0,1,0,-1,-1], [1,1,1,1,-4,0]]) # pushpop = list(zip(*pushpop)) m = PhraseAttention(hard=True) for i in range(qrys.size(1)): alphas, summary, scores = m(qrys[:, i], ctx, ctx_mask=ctx_mask, prev_pushpop=pushpop[:, i]) overlap = m.get_sibling_overlap() pass def test_phrase_attention_teacher(lr=0): # simulate operation of attention ctx = torch.randn(2, 5, 4) qrys = torch.randn(2, 6, 4) ctx_mask = torch.tensor([[1,1,1,1,1],[1,1,1,0,0]]) pushpop = torch.tensor([[1,0,1,0,-1,-1], [1,1,1,1,-4,0]]) # pushpop = list(zip(*pushpop)) m = PhraseAttentionTeacher(hard=True) m.record = True for i in range(qrys.size(1)): alphas, summary, scores = m(qrys[:, i], ctx, ctx_mask=ctx_mask, prev_pushpop=pushpop[:, i]) print(m.prevatts_probs[0]) print(m.prevatts_masks[0]) print(m.prevatts_probs[1]) print(m.prevatts_masks[1]) overlap = m.get_phraseatt_supervision(hard=True) pass # endregion # region components for phrase attention class LSTMAttComp(AttComp): def __init__(self, qrydim=None, ctxdim=None, encdim=None, dropout=0., numlayers=1, bidir=False, **kw): super(LSTMAttComp, self).__init__(**kw) encdims = [encdim] * numlayers self.layers = q.LSTMEncoder(qrydim+ctxdim, *encdims, bidir=bidir, dropout_in=dropout) self.lin = torch.nn.Linear(encdim, 1) def forward(self, qry, ctx, ctx_mask=None): """ :param qry: (batsize, qrydim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :return: """ inp = torch.cat([ctx, qry.unsqueeze(1).repeat(1, ctx.size(1), 1)], 2) out = self.layers(inp, mask=ctx_mask) ret = self.lin(out).squeeze(-1) # (batsize, seqlen) return ret class LSTMSummComp(SummComp): def __init__(self, valdim=None, encdim=None, dropout=0., numlayers=1, **kw): super(LSTMSummComp, self).__init__(**kw) encdims = [encdim] * numlayers self.layers = q.LSTMCellEncoder(valdim, *encdims, bidir=False, dropout_in=dropout) def forward(self, values, alphas): _, out = self.layers(values, gate=alphas, ret_states=True) out = out[:, 0] skip = values * alphas.unsqueeze(-1) skip = skip.sum(1) out = out + skip return out class PooledLSTMSummComp(SummComp): """ Uses a bidirectional lstm encoder with skip connections to encode according to given mask, not updating the state if gate is zero. If valdim != encdim * 2, uses a linear projection on the values. After encoding, does max and mean pooling across time, weighted by the provided attention weights. Best use only with hard attention alphas. """ def __init__(self, valdim=None, encdim=None, dropout=0., numlayers=1, **kw): super(PooledLSTMSummComp, self).__init__(**kw) encdims = [encdim] * numlayers self.layers = q.LSTMCellEncoder(valdim, *encdims, bidir=True, dropout_in=dropout) self.skip_adapt = torch.nn.Linear(valdim, encdim*2) if valdim != encdim * 2 else lambda x: x def forward(self, values, alphas): """ :param values: (batsize, seqlen, valdim) :param alphas: (batsize, seqlen) :return: (batsize, seqlen, encdim*2*2) """ topouts, out = self.layers(values, gate=alphas, ret_states=True) skip_vals = self.skip_adapt(values) rnnouts = topouts + skip_vals rnnouts = rnnouts * alphas.unsqueeze(2) meanpool = rnnouts.sum(1) / (alphas.unsqueeze(2).sum(1) + 1e-6) maxpool = rnnouts#.clone() maxpool.masked_fill_((1 - alphas).byte().unsqueeze(2), -np.infty) maxpool = maxpool.max(1)[0] maxpool = q.inf2zero(maxpool) out = torch.cat([meanpool, maxpool], 1) # (batsize, encdim * 2 * 2) return out # # out = out[:, 0] # # skip = values * alphas.unsqueeze(-1) # skip = skip.sum(1) # # out = out + skip # return out def test_pooled_lstm_summ_comp(lr=0.): vals = torch.randn(2, 5, 8) vals.requires_grad = True alphas = (torch.rand(2, 5) > 0.8).float() print(alphas) m = PooledLSTMSummComp(valdim=8, encdim=4) out = m(vals, alphas) print(out.size()) l = out.sum() l.backward() print(vals.grad) class LSTMPhraseAttention(PhraseAttention): def __init__(self, qrydim=None, ctxdim=None, valdim=None, encdim=None, dropout=0., numlayers=1, hard=False, **kw): ctxdim = qrydim if ctxdim is None else ctxdim valdim = ctxdim if valdim is None else valdim encdim = ctxdim if encdim is None else encdim attcomp = FwdAttComp(qrydim=qrydim, ctxdim=ctxdim, encdim=encdim, dropout=dropout, numlayers=numlayers) summcomp = LSTMSummComp(valdim=valdim, encdim=encdim, dropout=dropout, numlayers=numlayers) super(LSTMPhraseAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, hard=hard, **kw) class PooledLSTMPhraseAttention(PhraseAttention): def __init__(self, qrydim=None, ctxdim=None, valdim=None, encdim=None, dropout=0., numlayers=1, hard=False, **kw): ctxdim = qrydim if ctxdim is None else ctxdim valdim = ctxdim if valdim is None else valdim encdim = ctxdim if encdim is None else encdim attcomp = FwdAttComp(qrydim=qrydim, ctxdim=ctxdim, encdim=encdim, dropout=dropout, numlayers=numlayers) summcomp = PooledLSTMSummComp(valdim=valdim, encdim=encdim, dropout=dropout, numlayers=numlayers) super(PooledLSTMPhraseAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, hard=hard, **kw) class PhraseAttentionDecoderCell(torch.nn.Module): # Luong-style decoder cell """ Need to subclass this, implementing get_pushpop_from for specific vocabulary. Or specify mapping id2pushpop during construction. """ def __init__(self, emb=None, core=None, att:PhraseAttention=None, merge:q.rnn.DecCellMerge=q.rnn.ConcatDecCellMerge(), out=None, feed_att=False, return_alphas=False, return_scores=False, return_other=False, dropout=0, id2pushpop=None, **kw): """ Based on LuongCell, only change: support for prev_pushpop arg in forward --> passed to attention :param emb: :param core: :param att: :param merge: :param out: if None, out_vec (after merge) is returned :param feed_att: :param h_hat_0: :param id2pushpop: torch tensor mapping token ids to pushpop values :param kw: """ super(PhraseAttentionDecoderCell, self).__init__(**kw) self.emb, self.core, self.att, self.merge, self.out = emb, core, att, merge, out self.feed_att = feed_att self._outvec_tm1 = None self.outvec_t0 = None self.return_alphas = return_alphas self.return_scores = return_scores self.return_other = return_other self._id2pushpop = id2pushpop # THIS LINE IS ADDED self.dropout = torch.nn.Dropout(dropout) def batch_reset(self): self.outvec_t0 = None self._outvec_tm1 = None def forward(self, x_t, ctx=None, ctx_mask=None, **kw): assert (ctx is not None) embs = self.emb(x_t) if q.issequence(embs) and len(embs) == 2: embs, mask = embs if self.feed_att: if self._outvec_tm1 is None: assert (self.outvec_t0 is not None) #"h_hat_0 must be set when feed_att=True" self._outvec_tm1 = self.outvec_t0 core_inp = torch.cat([embs, self._outvec_tm1], 1) else: core_inp = embs prev_pushpop = self.get_pushpop_from(x_t) # THIS LINE IS ADDED core_out = self.core(core_inp) alphas, summaries, scores = self.att(core_out, ctx, ctx_mask=ctx_mask, values=ctx, prev_pushpop=prev_pushpop) # THIS LINE IS CHANGED out_vec = self.merge(core_out, summaries, core_inp) out_vec = self.dropout(out_vec) self._outvec_tm1 = out_vec # store outvec ret = tuple() if self.out is None: ret += (out_vec,) else: _out_vec = self.out(out_vec) ret += (_out_vec,) if self.return_alphas: ret += (alphas,) if self.return_scores: ret += (scores,) if self.return_other: ret += (embs, core_out, summaries) return ret[0] if len(ret) == 1 else ret def get_pushpop_from(self, x_t): # (batsize,) ids # THIS METHOD IS ADDED """ Get pushpop from x_t: based on x_t, decides whether to push (>0), do nothing (0) or pop (<0) previous attentions """ if self._id2pushpop is not None: return self._id2pushpop[x_t] else: raise NotImplemented() def test_lstm_phrase_attention(lr=0): m = LSTMPhraseAttention(4) ctx = torch.randn(2, 5, 4) qrys = torch.randn(2, 6, 4) ctx_mask = torch.tensor([[1,1,1,1,1],[1,1,1,0,0]]) pushpop = [[1,0,1,0,-1,-1], # output of last step will be "masked" [1,1,1,1,-4,0]] # output of last two steps will be "masked" pushpop = torch.tensor(pushpop) # pushpop = list(zip(*pushpop)) for i in range(qrys.size(1)): alphas, summary, scores = m(qrys[:, i], ctx, ctx_mask=ctx_mask, prev_pushpop=pushpop[:, i]) overlap = m.get_sibling_overlap() pass # endregion if __name__ == '__main__': # q.argprun(test_custom_f) # q.argprun(test_phrase_attention) # q.argprun(test_phrase_attention_teacher) # q.argprun(test_lstm_phrase_attention) # q.argprun(test_pooled_lstm_summ_comp) q.argprun(test_rel_attention)
import torch import qelos as q import numpy as np import math # region normal attention class AttComp(torch.nn.Module): """ computes attention scores """ def forward(self, qry, ctx, ctx_mask=None): raise NotImplemented() class SummComp(torch.nn.Module): def forward(self, values, alphas): raise NotImplemented() class Attention(torch.nn.Module): """ Computes phrase attention. For use with encoders and decoders from rnn.py """ def __init__(self, attcomp:AttComp=None, summcomp:SummComp=None, score_norm=torch.nn.Softmax(-1)): """ :param attcomp: used to compute attention scores :param summcomp: used to compute summary """ super(Attention, self).__init__() # self.prevatts = None # holds previous attention vectors # self.prevatt_ptr = None # for every example, contains a list with pointers to indexes of prevatts self.attcomp = attcomp if attcomp is not None else DotAttComp() self.summcomp = summcomp if summcomp is not None else SumSummComp() self.score_norm = score_norm def forward(self, qry, ctx, ctx_mask=None, values=None): """ :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :return: """ scores = self.attcomp(qry, ctx, ctx_mask=ctx_mask) scores = scores + (torch.log(ctx_mask.float()) if ctx_mask is not None else 0) alphas = self.score_norm(scores) values = ctx if values is None else values summary = self.summcomp(values, alphas) return alphas, summary, scores class DotAttComp(AttComp): def forward(self, qry, ctx, ctx_mask=None): """ :param qry: (batsize, dim) or (batsize, zeqlen, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: :return: """ if qry.dim() == 2: ret = torch.einsum("bd,bsd->bs", [qry, ctx]) elif qry.dim() == 3: ret = torch.einsum("bzd,bsd->bzs", [qry, ctx]) else: raise q.SumTingWongException("qry has unsupported dimension: {}".format(qry.dim())) return ret class FwdAttComp(AttComp): def __init__(self, qrydim=None, ctxdim=None, encdim=None, numlayers=1, dropout=0, **kw): super(FwdAttComp, self).__init__(**kw) layers = [torch.nn.Linear(qrydim + ctxdim, encdim)] \ + [torch.nn.Linear(encdim, encdim) for _ in range(numlayers - 1)] acts = [torch.nn.Tanh() for _ in range(len(layers))] layers = [a for b in zip(layers, acts) for a in b] layers.append(torch.nn.Dropout(dropout)) layers.append(torch.nn.Linear(encdim, 1)) self.mlp = torch.nn.Sequential(*layers) def forward(self, qry, ctx, ctx_mask=None): """ :param qry: (batsize, qrydim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :return: """ inp = torch.cat([ctx, qry.unsqueeze(1).repeat(1, ctx.size(1), 1)], 2) out = self.mlp(inp) ret = out.squeeze(-1) return ret class SumSummComp(SummComp): def forward(self, values, alphas): summary = values * alphas.unsqueeze(2) summary = summary.sum(1) return summary class BasicAttention(Attention): def __init__(self, **kw): attcomp = DotAttComp() summcomp = SumSummComp() super(BasicAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, **kw) class FwdAttention(Attention): def __init__(self, qrydim, ctxdim, encdim, dropout=0., **kw): attcomp = FwdAttComp(qrydim=qrydim, ctxdim=ctxdim, encdim=encdim, dropout=dropout) summcomp = SumSummComp() super(FwdAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, **kw) # endregion # region Relative Attention class VecComp(torch.nn.Module): """ maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention """ def __init__(self, ctxdim, vecdim, **kw): super(VecComp, self).__init__(**kw) self.ctxdim, self.vecdim = ctxdim, vecdim def forward(self, ctx): """ :param ctx: (batsize, seqlen, ctxdim) :return: (batsize, seqlen, seqlen, vecdim) """ raise NotImplemented() class FwdVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(FwdVecComp, self).__init__(ctxdim, vecdim, **kw) self.lin1 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin2 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.nonlin = torch.nn.Tanh() def forward(self, ctx): out1 = self.lin1(ctx) out2 = self.lin2(ctx) # (batsize, seqlen, vecdim) out = self.nonlin(out1.unsqueeze(1) + out2.unsqueeze(2)) return out class ComboFwdVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(ComboFwdVecComp, self).__init__(ctxdim, vecdim, **kw) self.lin1 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin2 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_mul = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_diff = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.nonlin = torch.nn.Tanh() def forward(self, ctx): out1 = self.lin1(ctx) out2 = self.lin2(ctx) # (batsize, seqlen, vecdim) mul = ctx.unsqueeze(1) * ctx.unsqueeze(2) # (batsize, seqlen, seqlen, vecdim) diff = ctx.unsqueeze(1) - ctx.unsqueeze(2) outmul = self.lin_mul(mul) outdiff = self.lin_diff(diff) out = self.nonlin(out1.unsqueeze(1) + out2.unsqueeze(2) + outmul + outdiff) return out class BilinVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(BilinVecComp, self).__init__(ctxdim, vecdim, **kw) self.W = torch.nn.Parameter(torch.Tensor(ctxdim, ctxdim, vecdim)) self.bias = torch.nn.Parameter(torch.Tensor(vecdim)) if bias else None self.nonlin = torch.nn.Tanh() self.reset_parameters() def reset_parameters(self): bound = 1 / math.sqrt(self.weight.size(1)) torch.init.uniform_(self.weight, -bound, bound) if self.bias is not None: torch.init.uniform_(self.bias, -bound, bound) def forward(self, ctx): out = torch.einsum("bsi,bzj,ijk->bszk", ctx, ctx, self.W) if self.bias is not None: out = out + self.bias out = self.nonlin(out) return out class BilinAndFwdComboVecComp(VecComp): def __init__(self, ctxdim, vecdim, bias=True, **kw): super(BilinAndFwdComboVecComp, self).__init__(ctxdim, vecdim, **kw) self.W = torch.nn.Parameter(torch.Tensor(ctxdim, ctxdim, vecdim)) self.bias = torch.nn.Parameter(torch.Tensor(vecdim)) if bias else None self.lin1 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin2 = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_mul = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.lin_diff = torch.nn.Linear(ctxdim, vecdim, bias=bias) self.nonlin = torch.nn.Tanh() self.reset_parameters() def reset_parameters(self): bound = 1 / math.sqrt(self.weight.size(1)) torch.init.uniform_(self.weight, -bound, bound) if self.bias is not None: torch.init.uniform_(self.bias, -bound, bound) def forward(self, ctx): out = torch.einsum("bsi,bzj,ijk->bszk", ctx, ctx, self.W) if self.bias is not None: out = out + self.bias out1 = self.lin1(ctx) out2 = self.lin2(ctx) # (batsize, seqlen, vecdim) mul = ctx.unsqueeze(1) * ctx.unsqueeze(2) # (batsize, seqlen, seqlen, vecdim) diff = ctx.unsqueeze(1) - ctx.unsqueeze(2) outmul = self.lin_mul(mul) outdiff = self.lin_diff(diff) out = self.nonlin(out + out1.unsqueeze(1) + out2.unsqueeze(2) + outmul + outdiff) return out class RelAttention(torch.nn.Module): def __init__(self, veccomp:VecComp=None, attcomp:AttComp=DotAttComp(), summcomp:SummComp=SumSummComp(), temperature=1., threshold=1e-6, **kw): super(RelAttention, self).__init__(**kw) self.threshold, self.temperature = threshold, temperature self.veccomp = veccomp # maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention self.attcomp, self.summcomp = attcomp, summcomp self.scorenorm = torch.nn.Softmax(-1) self.prevatts = None # (batsize, seqlen) self.relvecs = None # (batsize, seqlen, seqlen, vecdim) self.prevatts_history = [] # will become decseqlen-sized list of prevatts (batsize, seqlen) self.feed_prevatts_acc = None # decseqlen-sized list of prevatts (batsize, seqlen) self.t = 0 self._bad_prevatts = False def batch_reset(self): self.prevatts = None self.relvecs = None self.prevatts_history = [] self.feed_prevatts_acc = None self.t = 0 def forward(self, qry, ctx, ctx_mask=None, values=None): """ :param qry: (batsize, qdim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen) :return: """ # initialize prevatts if None: init assigns all prob to first element --> first element of ctx must be a start token if self.prevatts is None: self.prevatts = torch.zeros_like(ctx[:, :, 0]) self.prevatts[:, 0] = 1. # create and store relation vectors self.relvecs = self.veccomp(ctx) # get non-negligible part of relvecs # TODO: do sparse for more efficiency # relvecs_idxs = torch.nonzero(self.prevatts > self.threshold) # do attcomp with qry over relvecs flatrelvecs = self.relvecs.view(self.relvecs.size(0), self.relvecs.size(1) * self.relvecs.size(2), self.relvecs.size(3)) # (batsize, seqlen*seqlen, vecdim) flatrelatt_scores = self.attcomp(qry, flatrelvecs) # (batsize, seqlen * seqlen) relatt_scores = flatrelatt_scores.view(self.relvecs.size(0), self.relvecs.size(1), self.relvecs.size(2)) # (batsize, seqlen, seqlen) # apply ctx_mask before summary relatt_scores = relatt_scores + (torch.log(ctx_mask.float().unsqueeze(1)) if ctx_mask is not None else 0) relatt_alphas = self.scorenorm(relatt_scores) # (batsize, seqlen, seqlen) alphas = torch.einsum("bsz,bs->bz", relatt_alphas, self.prevatts) self.prevatts = alphas if self._bad_prevatts is True: self.prevatts = torch.zeros_like(ctx[:, :, 0]) self.prevatts[:, 2] = 1. # saving history and using feed: self.prevatts_history.append(self.prevatts) if self.feed_prevatts_acc is not None: self.prevatts = self.feed_prevatts_acc[self.t] values = ctx if values is None else values summary = self.summcomp(values, alphas) self.t += 1 return alphas, summary, relatt_scores class BasicRelAttention(RelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = FwdVecComp(ctxdim, vecdim, bias=bias) super(BasicRelAttention, self).__init__(veccomp, **kw) class ComboRelAttention(RelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = ComboFwdVecComp(ctxdim, vecdim, bias=bias) super(ComboRelAttention, self).__init__(veccomp, **kw) class AbsRelAttention(torch.nn.Module): """ Attention mechanism consisting of first absolute attention, followed by a relative attention step --> doesn't need prevatts """ def __init__(self, prevattcomp:AttComp=DotAttComp(), veccomp:VecComp=None, attcomp:AttComp=DotAttComp(), summcomp:SummComp=SumSummComp(), temperature=1., threshold=1e-6, **kw): super(AbsRelAttention, self).__init__(**kw) self.threshold, self.temperature = threshold, temperature self.prevattcomp = prevattcomp self.veccomp = veccomp # maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention self.attcomp, self.summcomp = attcomp, summcomp self.scorenorm = torch.nn.Softmax(-1) self.relvecs = None # (batsize, seqlen, seqlen, vecdim) self.t = 0 def batch_reset(self): self.relvecs = None self.t = 0 def forward(self, qry, ctx, ctx_mask=None, values=None): """ :param qry: (batsize, qdim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen) :return: """ if self.relvecs is None: # create and store relation vectors self.relvecs = self.veccomp(ctx) prevatts = self.prevattcomp(qry, ctx, ctx_mask=ctx_mask) prevatts += (torch.log(ctx_mask.float()) if ctx_mask is not None else 0) prevatts = self.scorenorm(prevatts) # get non-negligible part of relvecs # TODO: do sparse for more efficiency # relvecs_idxs = torch.nonzero(self.prevatts > self.threshold) # do attcomp with qry over relvecs flatrelvecs = self.relvecs.view(self.relvecs.size(0), self.relvecs.size(1) * self.relvecs.size(2), self.relvecs.size(3)) # (batsize, seqlen*seqlen, vecdim) flatrelatt_scores = self.attcomp(qry, flatrelvecs) # (batsize, seqlen * seqlen) relatt_scores = flatrelatt_scores.view(self.relvecs.size(0), self.relvecs.size(1), self.relvecs.size(2)) # (batsize, seqlen, seqlen) # apply ctx_mask before summary relatt_scores = relatt_scores + (torch.log(ctx_mask.float().unsqueeze(1)) if ctx_mask is not None else 0) relatt_alphas = self.scorenorm(relatt_scores) # (batsize, seqlen, seqlen) alphas = torch.einsum("bsz,bs->bz", relatt_alphas, prevatts) values = ctx if values is None else values summary = self.summcomp(values, alphas) self.t += 1 return alphas, summary, relatt_scores class BasicAbsRelAttention(AbsRelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = FwdVecComp(ctxdim, vecdim, bias=bias) super(BasicAbsRelAttention, self).__init__(veccomp=veccomp, **kw) class ComboAbsRelAttention(AbsRelAttention): def __init__(self, ctxdim, vecdim, bias=True, **kw): veccomp = ComboFwdVecComp(ctxdim, vecdim, bias=bias) super(ComboAbsRelAttention, self).__init__(veccomp=veccomp, **kw) def test_rel_attention(lr=0.): qry = torch.randn(2, 5) ctx = torch.randn(2, 3, 6) ctx_mask = torch.tensor([ [1,1,0], [1,1,1] ]) m = ComboRelAttention(6, 5) y = m(qry, ctx, ctx_mask=ctx_mask) print(y) # endregion # region Phrase Attention # function with a custom backward for getting gradients to both parent and children in PhraseAttention # forward is an elementwise min # backward: - alphas always gets whole gradient # - parent_alphas is increased when gradient > 0 else nothing # (so parent's attention can only be increased here if the child needs to attend more to certain places) # (if we equally tried to decrease parent's attentions here too, then would have conflicting signals from its children's attentions, which may not overlap) # (decrease comes from overlap penalty and gradient on parent attention itself) class ParentOverlapFunction(torch.autograd.Function): @staticmethod def forward(ctx, parent_alphas, alphas): ctx.save_for_backward(parent_alphas, alphas) ret = torch.min(parent_alphas, alphas) return ret @staticmethod def backward(ctx, grad_output): gradzeros = torch.zeros_like(grad_output) parent_grads = torch.max(gradzeros, grad_output) return parent_grads, grad_output def parent_overlap_f_parent_first(parent_alphas, alphas): alphas = 1 - alphas _z = torch.min(torch.tensor(1.0), parent_alphas / alphas) z = parent_alphas - alphas * _z.detach() return z parent_overlap_f = ParentOverlapFunction.apply # parent_overlap_f = parent_overlap_f_parent_first def test_custom_f(lr=0): x = torch.rand(5) x.requires_grad = True y = torch.rand(5) y.requires_grad = True z = parent_overlap_f(x, y) l = z #z.sum() l.backward(gradient=torch.tensor([-1,1,-1,1,1]).float()) print(x) print(y) print(z) print(x.grad) print(y.grad) class PhraseAttention(Attention): # for depth-first decoding """ Assumes masking by termination of tree structure assuming single root (which is also start token) """ def __init__(self, attcomp:AttComp=None, summcomp:SummComp=None, hard=False, **kw): score_norm = torch.nn.Sigmoid() super(PhraseAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, score_norm=score_norm) self.hard = hard self.prevatts_probs = None # (batsize, declen_so_far, enclen) if self.hard is True: self.prevatts_samples = None self.prevatts_mask = None self.prevatt_ptr = None # for every example, keeps a list of pointers to positions in prevatts # structure: batsize x stackdepth x numsiblings # For every example, the stack contains groups of siblings. # Could have had just batsize x stackdepth, but need to remember siblings for sibling overlap penalty (see prevatt_siblings) self.prevatt_siblings = None # for every example, keeps a list of sets of pointers to groups of siblings # structure: batsize x num_sibling_groups x num_siblings_in_group # Mainly populated during forward (with a finalization step for top-level siblings in get_sibling_overlap). # Consumed in get_sibling_overlap. def batch_reset(self): self.prevatts_probs, self.prevatt_ptr = None, None self.prevatt_siblings = None if self.hard is True: self.prevatts_samples = None self.prevatts_mask = None def get_sibling_overlap(self): # called after all forwards are done """ Gets overlap in siblings based on current state of prevatts and prevatt_ptr. Must be called after a batch and before batch reset. """ # finalize prevattr_ptr for i, prevattr_ptr_e in enumerate(self.prevatt_ptr): if len(prevattr_ptr_e) != 2: # must contain only the zero-group and top-level group pass # raise q.SumTingWongException() while len(prevattr_ptr_e) > 0: ptr_group = prevattr_ptr_e.pop() if len(ptr_group) > 1: pass # self.prevatt_siblings[i].append(ptr_group) # don't add overlap of top-level siblings (we assume single top child, everything else is mask) # generate ids by which to gather from prevatts ids = torch.zeros(self.prevatts_probs.size(0), self.prevatts_probs.size(1), self.prevatts_probs.size(1), dtype=torch.long, device=self.prevatts_probs.device) maxnumsiblingses, maxnumsiblings = 0, 0 for eid, siblingses in enumerate(self.prevatt_siblings): # list of lists of ids in prevatts maxnumsiblingses = max(maxnumsiblingses, len(siblingses)) for sgid, siblings in enumerate(siblingses): # list of ids in prevatts maxnumsiblings = max(maxnumsiblings, len(siblings)) for sid, sibling in enumerate(siblings): ids[eid, sgid, sid] = sibling ids = ids[:, :maxnumsiblingses, :maxnumsiblings] prevatts = self.prevatts_probs idsmask= ((ids != 0).sum(2, keepdim=True) > 1).float() # gather from prevatts _ids = ids.contiguous().view(ids.size(0), -1).unsqueeze(-1).repeat(1, 1, prevatts.size(2)) prevatts_gathered = torch.gather(prevatts, 1, _ids) prevatts_gathered = prevatts_gathered.view(prevatts.size(0), ids.size(1), ids.size(2), prevatts.size(2)) # compute overlaps overlaps = prevatts_gathered.prod(2) overlaps = overlaps * idsmask overlaps = overlaps.sum(2).sum(1) # overlaps = overlaps.mean(0) return overlaps def get_logprob_of_sampled_alphas(self): if self.hard is False: raise q.SumTingWongException("Use this only for RL on hard attention (must be in hard mode).") probs = self.prevatts_probs * self.prevatts_samples + (1 - self.prevatts_probs) * (1 - self.prevatts_samples) logprobs = torch.log(probs) logprobs = logprobs * self.prevatts_mask # mask the logprobs average_within_timestep = True if average_within_timestep: totals = self.prevatts_mask.sum(2) + 1e-6 logprobs = logprobs.sum(2) / totals else: logprobs = logprobs.mean(2) return logprobs[:, 2:] # (batsize, seqlen) -- decoder mask should be applied on this later def get_entropies_of_alpha_dists(self): probs = self.prevatts_probs dists = torch.distributions.Bernoulli(probs=probs) entropies = dists.entropy() entropies = entropies * self.prevatts_mask average_within_timestep = True if average_within_timestep: totals = self.prevatts_mask.sum(2) + 1e-12 entropies = entropies.sum(2) / totals else: entropies = entropies.mean(2) return entropies[:, 2:] # (batsize, seqlen) -- decoder mask should be applied on this later def forward(self, qry, ctx, ctx_mask=None, values=None, prev_pushpop=None): """ :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :param prev_pushpop: (batsize,) - whether PREVIOUS token was a push or pop (or do-nothing) token: -N ==> pop (N=how many to pop), 0 ==> nothing, +N ==> push (N doesn't matter, always pushes one) ! push/pop happens AFTER the element :return: """ # compute attention for token that we will produce next # compute attention scores scores = self.attcomp(qry, ctx, ctx_mask=ctx_mask) # apply ctx mask to attention scores scores = scores + (torch.log(ctx_mask.float()) if ctx_mask is not None else 0) # normalize attention scores alphas_probs = self.score_norm(scores) # sigmoid probs if self.hard: alphas_dist = torch.distributions.Bernoulli(probs=alphas_probs) alphas_samples = alphas_dist.sample() # constrain alphas to parent's alphas: if self.prevatts_probs is None: # there is no history # initialize prevatts (history) self.prevatts_probs = torch.ones_like(alphas_probs).unsqueeze(1).repeat(1, 2, 1) # means everything is attended to if ctx_mask is not None: self.prevatts_probs = self.prevatts_probs * ctx_mask.float().unsqueeze(1) if self.hard is True: self.prevatts_samples = self.prevatts_probs.clone().detach() #torch.ones_like(alphas_probs).unsqueeze(1).repeat(1, 2, 1) self.prevatts_mask = torch.zeros_like(alphas_probs).unsqueeze(1).repeat(1, 2, 1) # --> we assume the previous (first ever) attention, used to compute initial (current input) token attended over whole sequence # initialize prevatt_ptr self.prevatt_ptr = [[[0], []] for _ in range(len(prev_pushpop))] # initialize prevatt_siblings self.prevatt_siblings = [[] for _ in range(len(prev_pushpop))] # update pointers to prevatt k = self.prevatts_probs.size(1) - 1 # index of the last produced attention alphas (that were used for prev token) for i in range(len(prev_pushpop)): self.prevatt_ptr[i][-1].append(k) # make last token a sibling of the children of the same parent before it (if any) if prev_pushpop[i].cpu().item() > 0: # PUSH: previous token requires children --> make stack deeper by one level self.prevatt_ptr[i].append([]) elif prev_pushpop[i].cpu().item() < 0: # POP: previous token was last in its row of siblings (and possibly terminates upwards levels too) pp = prev_pushpop[i].cpu().item() while pp < 0 and len(self.prevatt_ptr[i]) > 2: siblings = self.prevatt_ptr[i].pop(-1) # pop the list from stack if len(siblings) > 1: # if longer than 1, add to the list of siblings self.prevatt_siblings[i].append(siblings) pp += 1 else: pass # constrain alphas to parent's alphas parent_ptr = [prevatt_ptr_e[-2][-1] for prevatt_ptr_e in self.prevatt_ptr] parent_ptr = torch.tensor(parent_ptr).long().to(self.prevatts_probs.device) if self.hard is True: # no backprop through alphas # parent_alphas_probs = self.prevatts_probs.gather(1, parent_ptr.unsqueeze(-1).unsqueeze(-1) # .repeat(1, 1, self.prevatts_probs.size(-1))).squeeze(1) parent_alphas_samples = self.prevatts_samples.gather(1, parent_ptr.unsqueeze(-1).unsqueeze(-1) .repeat(1, 1, self.prevatts_samples.size(-1))).squeeze(1) alphas_samples = torch.min(parent_alphas_samples, alphas_samples) # save parent-masked samples self.prevatts_samples = torch.cat([self.prevatts_samples, alphas_samples.unsqueeze(1)], 1) self.prevatts_mask = torch.cat([self.prevatts_mask, parent_alphas_samples.unsqueeze(1)], 1) alphas = alphas_samples else: # need to backprop differently parent_alphas_probs = self.prevatts_probs.gather(1, parent_ptr.unsqueeze(-1).unsqueeze(-1) .repeat(1, 1, self.prevatts_probs.size(-1))).squeeze(1) alphas_probs = parent_overlap_f(parent_alphas_probs, alphas_probs) alphas = alphas_probs # append current alpha probs to prevatts accumulator self.prevatts_probs = torch.cat([self.prevatts_probs, alphas_probs.unsqueeze(1)], 1) # compute summary values = ctx if values is None else values summary = self.summcomp(values, alphas) return alphas, summary, scores class PhraseAttentionTeacher(Attention): # for depth-first decoding """ Normal attention. Stores probs for the batch for use to supervise real phrase attention. """ """ Assumes masking by termination of tree structure assuming single root (which is also start token) """ def __init__(self, attcomp:AttComp=None, hard=True, **kw): score_norm = torch.nn.Softmax(-1) summcomp = SumSummComp() super(PhraseAttentionTeacher, self).__init__(attcomp=attcomp, summcomp=summcomp, score_norm=score_norm) self.prevatts_probs = None # (batsize, declen_so_far, enclen) self.prevatt_ptr = None # for every example, keeps a list of pointers to positions in prevatts self.prevatts_masks = None # structure: batsize x stackdepth x numsiblings # For every example, the stack contains groups of siblings. # Could have had just batsize x stackdepth, but need to remember siblings for sibling overlap penalty (see prevatt_siblings) self.record = False self.hard = hard def batch_reset(self): self.prevatts_probs, self.prevatt_ptr = None, None self.prevatts_masks = None def get_phraseatt_supervision(self, hard=True): """ Propagates attentions in self.prevatts_probs from children to parents according to self.prevatt_ptr, this way converting softmax attentions generated here to a supervision signal usable for sigmoid attention. If hard, does argmax before propagating, else propagates probs. """ return self.prevatts_probs, self.prevatts_masks def forward(self, qry, ctx, ctx_mask=None, values=None, prev_pushpop=None): """ :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :param prev_pushpop: (batsize,) - whether PREVIOUS token was a push or pop (or do-nothing) token: -N ==> pop (N=how many to pop), 0 ==> nothing, +N ==> push (N doesn't matter, always pushes one) ! push/pop happens AFTER the element :return: """ alphas_probs, summary, scores = super(PhraseAttentionTeacher, self).forward(qry, ctx, ctx_mask=ctx_mask, values=values) if self.record is True: if self.prevatts_probs is None: # there is no history # initialize prevatts (history) self.prevatts_probs = torch.zeros_like(alphas_probs).unsqueeze(1) # initialize prevatt masks self.prevatts_masks = torch.ones_like(alphas_probs).unsqueeze(1) if ctx_mask is not None: self.prevatts_masks = self.prevatts_masks * ctx_mask.unsqueeze(1).float() # initialize prevatt_ptr self.prevatt_ptr = [[[]] for _ in range(len(prev_pushpop))] # update pointers to prevatt k = self.prevatts_probs.size(1) - 1 # index of the last produced attention alphas (that were used for prev token) for i in range(len(prev_pushpop)): # iterate over all examples self.prevatt_ptr[i][-1].append(k) # make last token a sibling of the children of the same parent before it (if any) if prev_pushpop[i].cpu().item() > 0: # PUSH: previous token requires children --> make stack deeper by one level self.prevatt_ptr[i].append([]) elif prev_pushpop[i].cpu().item() < 0: # POP: previous token was last in its row of siblings (and possibly terminates upwards levels too) pp = prev_pushpop[i].cpu().item() while pp < 0 and len(self.prevatt_ptr[i]) > 1: siblings = self.prevatt_ptr[i].pop(-1) # pop the list from stack # add each of the sibling's attention probs to their parent and populate children's masks parent = self.prevatt_ptr[i][-1][-1] for sibling in siblings: sibling_alphas = self.prevatts_probs[i, sibling] self.prevatts_probs[i, parent] += sibling_alphas self.prevatts_probs[i, parent].clamp_(0., 1.) parent_alphas = self.prevatts_probs[i, parent] for sibling in siblings: self.prevatts_masks[i, sibling] = parent_alphas pp += 1 else: pass # append current alpha probs to prevatts accumulator if self.hard: # _alphas_probs = torch.zeros_like(alphas_probs)\ # .scatter_(1, torch.argmax(alphas_probs, 1, True), 1.) alphas_dist = torch.distributions.OneHotCategorical(probs=alphas_probs) _alphas_probs = alphas_dist.sample() else: _alphas_probs = alphas_probs self.prevatts_probs = torch.cat([self.prevatts_probs, _alphas_probs.unsqueeze(1)], 1) self.prevatts_masks = torch.cat([self.prevatts_masks, torch.zeros_like(_alphas_probs.unsqueeze(1))], 1) # will be filled once siblings have been done return alphas_probs, summary, scores def test_phrase_attention(lr=0): # simulate operation of attention ctx = torch.randn(2, 5, 4) qrys = torch.randn(2, 6, 4) ctx_mask = torch.tensor([[1,1,1,1,1],[1,1,1,0,0]]) pushpop = torch.tensor([[1,0,1,0,-1,-1], [1,1,1,1,-4,0]]) # pushpop = list(zip(*pushpop)) m = PhraseAttention(hard=True) for i in range(qrys.size(1)): alphas, summary, scores = m(qrys[:, i], ctx, ctx_mask=ctx_mask, prev_pushpop=pushpop[:, i]) overlap = m.get_sibling_overlap() pass def test_phrase_attention_teacher(lr=0): # simulate operation of attention ctx = torch.randn(2, 5, 4) qrys = torch.randn(2, 6, 4) ctx_mask = torch.tensor([[1,1,1,1,1],[1,1,1,0,0]]) pushpop = torch.tensor([[1,0,1,0,-1,-1], [1,1,1,1,-4,0]]) # pushpop = list(zip(*pushpop)) m = PhraseAttentionTeacher(hard=True) m.record = True for i in range(qrys.size(1)): alphas, summary, scores = m(qrys[:, i], ctx, ctx_mask=ctx_mask, prev_pushpop=pushpop[:, i]) print(m.prevatts_probs[0]) print(m.prevatts_masks[0]) print(m.prevatts_probs[1]) print(m.prevatts_masks[1]) overlap = m.get_phraseatt_supervision(hard=True) pass # endregion # region components for phrase attention class LSTMAttComp(AttComp): def __init__(self, qrydim=None, ctxdim=None, encdim=None, dropout=0., numlayers=1, bidir=False, **kw): super(LSTMAttComp, self).__init__(**kw) encdims = [encdim] * numlayers self.layers = q.LSTMEncoder(qrydim+ctxdim, *encdims, bidir=bidir, dropout_in=dropout) self.lin = torch.nn.Linear(encdim, 1) def forward(self, qry, ctx, ctx_mask=None): """ :param qry: (batsize, qrydim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :return: """ inp = torch.cat([ctx, qry.unsqueeze(1).repeat(1, ctx.size(1), 1)], 2) out = self.layers(inp, mask=ctx_mask) ret = self.lin(out).squeeze(-1) # (batsize, seqlen) return ret class LSTMSummComp(SummComp): def __init__(self, valdim=None, encdim=None, dropout=0., numlayers=1, **kw): super(LSTMSummComp, self).__init__(**kw) encdims = [encdim] * numlayers self.layers = q.LSTMCellEncoder(valdim, *encdims, bidir=False, dropout_in=dropout) def forward(self, values, alphas): _, out = self.layers(values, gate=alphas, ret_states=True) out = out[:, 0] skip = values * alphas.unsqueeze(-1) skip = skip.sum(1) out = out + skip return out class PooledLSTMSummComp(SummComp): """ Uses a bidirectional lstm encoder with skip connections to encode according to given mask, not updating the state if gate is zero. If valdim != encdim * 2, uses a linear projection on the values. After encoding, does max and mean pooling across time, weighted by the provided attention weights. Best use only with hard attention alphas. """ def __init__(self, valdim=None, encdim=None, dropout=0., numlayers=1, **kw): super(PooledLSTMSummComp, self).__init__(**kw) encdims = [encdim] * numlayers self.layers = q.LSTMCellEncoder(valdim, *encdims, bidir=True, dropout_in=dropout) self.skip_adapt = torch.nn.Linear(valdim, encdim*2) if valdim != encdim * 2 else lambda x: x def forward(self, values, alphas): """ :param values: (batsize, seqlen, valdim) :param alphas: (batsize, seqlen) :return: (batsize, seqlen, encdim*2*2) """ topouts, out = self.layers(values, gate=alphas, ret_states=True) skip_vals = self.skip_adapt(values) rnnouts = topouts + skip_vals rnnouts = rnnouts * alphas.unsqueeze(2) meanpool = rnnouts.sum(1) / (alphas.unsqueeze(2).sum(1) + 1e-6) maxpool = rnnouts#.clone() maxpool.masked_fill_((1 - alphas).byte().unsqueeze(2), -np.infty) maxpool = maxpool.max(1)[0] maxpool = q.inf2zero(maxpool) out = torch.cat([meanpool, maxpool], 1) # (batsize, encdim * 2 * 2) return out # # out = out[:, 0] # # skip = values * alphas.unsqueeze(-1) # skip = skip.sum(1) # # out = out + skip # return out def test_pooled_lstm_summ_comp(lr=0.): vals = torch.randn(2, 5, 8) vals.requires_grad = True alphas = (torch.rand(2, 5) > 0.8).float() print(alphas) m = PooledLSTMSummComp(valdim=8, encdim=4) out = m(vals, alphas) print(out.size()) l = out.sum() l.backward() print(vals.grad) class LSTMPhraseAttention(PhraseAttention): def __init__(self, qrydim=None, ctxdim=None, valdim=None, encdim=None, dropout=0., numlayers=1, hard=False, **kw): ctxdim = qrydim if ctxdim is None else ctxdim valdim = ctxdim if valdim is None else valdim encdim = ctxdim if encdim is None else encdim attcomp = FwdAttComp(qrydim=qrydim, ctxdim=ctxdim, encdim=encdim, dropout=dropout, numlayers=numlayers) summcomp = LSTMSummComp(valdim=valdim, encdim=encdim, dropout=dropout, numlayers=numlayers) super(LSTMPhraseAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, hard=hard, **kw) class PooledLSTMPhraseAttention(PhraseAttention): def __init__(self, qrydim=None, ctxdim=None, valdim=None, encdim=None, dropout=0., numlayers=1, hard=False, **kw): ctxdim = qrydim if ctxdim is None else ctxdim valdim = ctxdim if valdim is None else valdim encdim = ctxdim if encdim is None else encdim attcomp = FwdAttComp(qrydim=qrydim, ctxdim=ctxdim, encdim=encdim, dropout=dropout, numlayers=numlayers) summcomp = PooledLSTMSummComp(valdim=valdim, encdim=encdim, dropout=dropout, numlayers=numlayers) super(PooledLSTMPhraseAttention, self).__init__(attcomp=attcomp, summcomp=summcomp, hard=hard, **kw) class PhraseAttentionDecoderCell(torch.nn.Module): # Luong-style decoder cell """ Need to subclass this, implementing get_pushpop_from for specific vocabulary. Or specify mapping id2pushpop during construction. """ def __init__(self, emb=None, core=None, att:PhraseAttention=None, merge:q.rnn.DecCellMerge=q.rnn.ConcatDecCellMerge(), out=None, feed_att=False, return_alphas=False, return_scores=False, return_other=False, dropout=0, id2pushpop=None, **kw): """ Based on LuongCell, only change: support for prev_pushpop arg in forward --> passed to attention :param emb: :param core: :param att: :param merge: :param out: if None, out_vec (after merge) is returned :param feed_att: :param h_hat_0: :param id2pushpop: torch tensor mapping token ids to pushpop values :param kw: """ super(PhraseAttentionDecoderCell, self).__init__(**kw) self.emb, self.core, self.att, self.merge, self.out = emb, core, att, merge, out self.feed_att = feed_att self._outvec_tm1 = None self.outvec_t0 = None self.return_alphas = return_alphas self.return_scores = return_scores self.return_other = return_other self._id2pushpop = id2pushpop # THIS LINE IS ADDED self.dropout = torch.nn.Dropout(dropout) def batch_reset(self): self.outvec_t0 = None self._outvec_tm1 = None def forward(self, x_t, ctx=None, ctx_mask=None, **kw): assert (ctx is not None) embs = self.emb(x_t) if q.issequence(embs) and len(embs) == 2: embs, mask = embs if self.feed_att: if self._outvec_tm1 is None: assert (self.outvec_t0 is not None) #"h_hat_0 must be set when feed_att=True" self._outvec_tm1 = self.outvec_t0 core_inp = torch.cat([embs, self._outvec_tm1], 1) else: core_inp = embs prev_pushpop = self.get_pushpop_from(x_t) # THIS LINE IS ADDED core_out = self.core(core_inp) alphas, summaries, scores = self.att(core_out, ctx, ctx_mask=ctx_mask, values=ctx, prev_pushpop=prev_pushpop) # THIS LINE IS CHANGED out_vec = self.merge(core_out, summaries, core_inp) out_vec = self.dropout(out_vec) self._outvec_tm1 = out_vec # store outvec ret = tuple() if self.out is None: ret += (out_vec,) else: _out_vec = self.out(out_vec) ret += (_out_vec,) if self.return_alphas: ret += (alphas,) if self.return_scores: ret += (scores,) if self.return_other: ret += (embs, core_out, summaries) return ret[0] if len(ret) == 1 else ret def get_pushpop_from(self, x_t): # (batsize,) ids # THIS METHOD IS ADDED """ Get pushpop from x_t: based on x_t, decides whether to push (>0), do nothing (0) or pop (<0) previous attentions """ if self._id2pushpop is not None: return self._id2pushpop[x_t] else: raise NotImplemented() def test_lstm_phrase_attention(lr=0): m = LSTMPhraseAttention(4) ctx = torch.randn(2, 5, 4) qrys = torch.randn(2, 6, 4) ctx_mask = torch.tensor([[1,1,1,1,1],[1,1,1,0,0]]) pushpop = [[1,0,1,0,-1,-1], # output of last step will be "masked" [1,1,1,1,-4,0]] # output of last two steps will be "masked" pushpop = torch.tensor(pushpop) # pushpop = list(zip(*pushpop)) for i in range(qrys.size(1)): alphas, summary, scores = m(qrys[:, i], ctx, ctx_mask=ctx_mask, prev_pushpop=pushpop[:, i]) overlap = m.get_sibling_overlap() pass # endregion if __name__ == '__main__': # q.argprun(test_custom_f) # q.argprun(test_phrase_attention) # q.argprun(test_phrase_attention_teacher) # q.argprun(test_lstm_phrase_attention) # q.argprun(test_pooled_lstm_summ_comp) q.argprun(test_rel_attention)
en
0.730075
# region normal attention computes attention scores Computes phrase attention. For use with encoders and decoders from rnn.py :param attcomp: used to compute attention scores :param summcomp: used to compute summary # self.prevatts = None # holds previous attention vectors # self.prevatt_ptr = None # for every example, contains a list with pointers to indexes of prevatts :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :return: :param qry: (batsize, dim) or (batsize, zeqlen, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: :return: :param qry: (batsize, qrydim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :return: # endregion # region Relative Attention maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention :param ctx: (batsize, seqlen, ctxdim) :return: (batsize, seqlen, seqlen, vecdim) # (batsize, seqlen, vecdim) # (batsize, seqlen, vecdim) # (batsize, seqlen, seqlen, vecdim) # (batsize, seqlen, vecdim) # (batsize, seqlen, seqlen, vecdim) # maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention # (batsize, seqlen) # (batsize, seqlen, seqlen, vecdim) # will become decseqlen-sized list of prevatts (batsize, seqlen) # decseqlen-sized list of prevatts (batsize, seqlen) :param qry: (batsize, qdim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen) :return: # initialize prevatts if None: init assigns all prob to first element --> first element of ctx must be a start token # create and store relation vectors # get non-negligible part of relvecs # TODO: do sparse for more efficiency # relvecs_idxs = torch.nonzero(self.prevatts > self.threshold) # do attcomp with qry over relvecs # (batsize, seqlen*seqlen, vecdim) # (batsize, seqlen * seqlen) # (batsize, seqlen, seqlen) # apply ctx_mask before summary # (batsize, seqlen, seqlen) # saving history and using feed: Attention mechanism consisting of first absolute attention, followed by a relative attention step --> doesn't need prevatts # maps ctx~(batsize, seqlen, ctxdim) to relvecs~(batsize, seqlen, seqlen, vecdim) ~~ self-attention # (batsize, seqlen, seqlen, vecdim) :param qry: (batsize, qdim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen) :return: # create and store relation vectors # get non-negligible part of relvecs # TODO: do sparse for more efficiency # relvecs_idxs = torch.nonzero(self.prevatts > self.threshold) # do attcomp with qry over relvecs # (batsize, seqlen*seqlen, vecdim) # (batsize, seqlen * seqlen) # (batsize, seqlen, seqlen) # apply ctx_mask before summary # (batsize, seqlen, seqlen) # endregion # region Phrase Attention # function with a custom backward for getting gradients to both parent and children in PhraseAttention # forward is an elementwise min # backward: - alphas always gets whole gradient # - parent_alphas is increased when gradient > 0 else nothing # (so parent's attention can only be increased here if the child needs to attend more to certain places) # (if we equally tried to decrease parent's attentions here too, then would have conflicting signals from its children's attentions, which may not overlap) # (decrease comes from overlap penalty and gradient on parent attention itself) # parent_overlap_f = parent_overlap_f_parent_first #z.sum() # for depth-first decoding Assumes masking by termination of tree structure assuming single root (which is also start token) # (batsize, declen_so_far, enclen) # for every example, keeps a list of pointers to positions in prevatts # structure: batsize x stackdepth x numsiblings # For every example, the stack contains groups of siblings. # Could have had just batsize x stackdepth, but need to remember siblings for sibling overlap penalty (see prevatt_siblings) # for every example, keeps a list of sets of pointers to groups of siblings # structure: batsize x num_sibling_groups x num_siblings_in_group # Mainly populated during forward (with a finalization step for top-level siblings in get_sibling_overlap). # Consumed in get_sibling_overlap. # called after all forwards are done Gets overlap in siblings based on current state of prevatts and prevatt_ptr. Must be called after a batch and before batch reset. # finalize prevattr_ptr # must contain only the zero-group and top-level group # raise q.SumTingWongException() # self.prevatt_siblings[i].append(ptr_group) # don't add overlap of top-level siblings (we assume single top child, everything else is mask) # generate ids by which to gather from prevatts # list of lists of ids in prevatts # list of ids in prevatts # gather from prevatts # compute overlaps # overlaps = overlaps.mean(0) # mask the logprobs # (batsize, seqlen) -- decoder mask should be applied on this later # (batsize, seqlen) -- decoder mask should be applied on this later :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :param prev_pushpop: (batsize,) - whether PREVIOUS token was a push or pop (or do-nothing) token: -N ==> pop (N=how many to pop), 0 ==> nothing, +N ==> push (N doesn't matter, always pushes one) ! push/pop happens AFTER the element :return: # compute attention for token that we will produce next # compute attention scores # apply ctx mask to attention scores # normalize attention scores # sigmoid probs # constrain alphas to parent's alphas: # there is no history # initialize prevatts (history) # means everything is attended to #torch.ones_like(alphas_probs).unsqueeze(1).repeat(1, 2, 1) # --> we assume the previous (first ever) attention, used to compute initial (current input) token attended over whole sequence # initialize prevatt_ptr # initialize prevatt_siblings # update pointers to prevatt # index of the last produced attention alphas (that were used for prev token) # make last token a sibling of the children of the same parent before it (if any) # PUSH: previous token requires children --> make stack deeper by one level # POP: previous token was last in its row of siblings (and possibly terminates upwards levels too) # pop the list from stack # if longer than 1, add to the list of siblings # constrain alphas to parent's alphas # no backprop through alphas # parent_alphas_probs = self.prevatts_probs.gather(1, parent_ptr.unsqueeze(-1).unsqueeze(-1) # .repeat(1, 1, self.prevatts_probs.size(-1))).squeeze(1) # save parent-masked samples # need to backprop differently # append current alpha probs to prevatts accumulator # compute summary # for depth-first decoding Normal attention. Stores probs for the batch for use to supervise real phrase attention. Assumes masking by termination of tree structure assuming single root (which is also start token) # (batsize, declen_so_far, enclen) # for every example, keeps a list of pointers to positions in prevatts # structure: batsize x stackdepth x numsiblings # For every example, the stack contains groups of siblings. # Could have had just batsize x stackdepth, but need to remember siblings for sibling overlap penalty (see prevatt_siblings) Propagates attentions in self.prevatts_probs from children to parents according to self.prevatt_ptr, this way converting softmax attentions generated here to a supervision signal usable for sigmoid attention. If hard, does argmax before propagating, else propagates probs. :param qry: (batsize, dim) :param ctx: (batsize, seqlen, dim) :param ctx_mask: (batsize, seqlen) :param values: (batsize, seqlen, dim) :param prev_pushpop: (batsize,) - whether PREVIOUS token was a push or pop (or do-nothing) token: -N ==> pop (N=how many to pop), 0 ==> nothing, +N ==> push (N doesn't matter, always pushes one) ! push/pop happens AFTER the element :return: # there is no history # initialize prevatts (history) # initialize prevatt masks # initialize prevatt_ptr # update pointers to prevatt # index of the last produced attention alphas (that were used for prev token) # iterate over all examples # make last token a sibling of the children of the same parent before it (if any) # PUSH: previous token requires children --> make stack deeper by one level # POP: previous token was last in its row of siblings (and possibly terminates upwards levels too) # pop the list from stack # add each of the sibling's attention probs to their parent and populate children's masks # append current alpha probs to prevatts accumulator # _alphas_probs = torch.zeros_like(alphas_probs)\ # .scatter_(1, torch.argmax(alphas_probs, 1, True), 1.) # will be filled once siblings have been done # simulate operation of attention # pushpop = list(zip(*pushpop)) # simulate operation of attention # pushpop = list(zip(*pushpop)) # endregion # region components for phrase attention :param qry: (batsize, qrydim) :param ctx: (batsize, seqlen, ctxdim) :param ctx_mask: (batsize, seqlen) :return: # (batsize, seqlen) Uses a bidirectional lstm encoder with skip connections to encode according to given mask, not updating the state if gate is zero. If valdim != encdim * 2, uses a linear projection on the values. After encoding, does max and mean pooling across time, weighted by the provided attention weights. Best use only with hard attention alphas. :param values: (batsize, seqlen, valdim) :param alphas: (batsize, seqlen) :return: (batsize, seqlen, encdim*2*2) #.clone() # (batsize, encdim * 2 * 2) # # out = out[:, 0] # # skip = values * alphas.unsqueeze(-1) # skip = skip.sum(1) # # out = out + skip # return out # Luong-style decoder cell Need to subclass this, implementing get_pushpop_from for specific vocabulary. Or specify mapping id2pushpop during construction. Based on LuongCell, only change: support for prev_pushpop arg in forward --> passed to attention :param emb: :param core: :param att: :param merge: :param out: if None, out_vec (after merge) is returned :param feed_att: :param h_hat_0: :param id2pushpop: torch tensor mapping token ids to pushpop values :param kw: # THIS LINE IS ADDED #"h_hat_0 must be set when feed_att=True" # THIS LINE IS ADDED # THIS LINE IS CHANGED # store outvec # (batsize,) ids # THIS METHOD IS ADDED Get pushpop from x_t: based on x_t, decides whether to push (>0), do nothing (0) or pop (<0) previous attentions # output of last step will be "masked" # output of last two steps will be "masked" # pushpop = list(zip(*pushpop)) # endregion # q.argprun(test_custom_f) # q.argprun(test_phrase_attention) # q.argprun(test_phrase_attention_teacher) # q.argprun(test_lstm_phrase_attention) # q.argprun(test_pooled_lstm_summ_comp)
2.883658
3
lib/config.py
lee-kode/hapaas
0
6614339
<filename>lib/config.py import ConfigParser import os CONFIG_FILE = '/etc/hapaas/config.ini' def get_config(): cfg_file = os.getenv('HAPAAS_CONFIG', CONFIG_FILE) cfg = ConfigParser.RawConfigParser(allow_no_value=True) cfg.read(cfg_file) return cfg
<filename>lib/config.py import ConfigParser import os CONFIG_FILE = '/etc/hapaas/config.ini' def get_config(): cfg_file = os.getenv('HAPAAS_CONFIG', CONFIG_FILE) cfg = ConfigParser.RawConfigParser(allow_no_value=True) cfg.read(cfg_file) return cfg
none
1
2.222972
2
organize/filters/lastmodified.py
ytzhangFTD/organize
1
6614340
<gh_stars>1-10 from datetime import datetime, timedelta from typing import Union from fs.base import FS from schema import Optional, Or from .filter import Filter, FilterResult from .utils import age_condition_applies class LastModified(Filter): """Matches files by last modified date Args: years (int): specify number of years months (int): specify number of months weeks (float): specify number of weeks days (float): specify number of days hours (float): specify number of hours minutes (float): specify number of minutes seconds (float): specify number of seconds mode (str): either 'older' or 'newer'. 'older' matches files / folders last modified before the given time, 'newer' matches files / folders last modified within the given time. (default = 'older') Returns: {lastmodified}: The datetime the files / folders was lastmodified. """ name = "lastmodified" schema_support_instance_without_args = True arg_schema = { Optional("mode"): Or("older", "newer"), Optional("years"): int, Optional("months"): int, Optional("weeks"): int, Optional("days"): int, Optional("hours"): int, Optional("minutes"): int, Optional("seconds"): int, } def __init__( self, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, mode="older", ): self.age = timedelta( weeks=52 * years + 4 * months + weeks, # quick and a bit dirty days=days, hours=hours, minutes=minutes, seconds=seconds, ) self.mode = mode.strip().lower() if self.mode not in ("older", "newer"): raise ValueError("Unknown option for 'mode': must be 'older' or 'newer'.") def matches_lastmodified_time(self, lastmodified: Union[None, datetime]): match = True if self.age.total_seconds(): if not lastmodified: match = False else: match = age_condition_applies( dt=lastmodified, age=self.age, mode=self.mode, reference=datetime.now(), ) return match def pipeline(self, args: dict) -> FilterResult: fs = args["fs"] # type: FS fs_path = args["fs_path"] modified = fs.getmodified(fs_path) if modified: modified = modified.astimezone() match = self.matches_lastmodified_time(modified) return FilterResult( matches=match, updates={self.get_name(): modified}, ) def __str__(self): return "[LastModified] All files / folders last modified %s than %s" % ( self._mode, self.timedelta, )
from datetime import datetime, timedelta from typing import Union from fs.base import FS from schema import Optional, Or from .filter import Filter, FilterResult from .utils import age_condition_applies class LastModified(Filter): """Matches files by last modified date Args: years (int): specify number of years months (int): specify number of months weeks (float): specify number of weeks days (float): specify number of days hours (float): specify number of hours minutes (float): specify number of minutes seconds (float): specify number of seconds mode (str): either 'older' or 'newer'. 'older' matches files / folders last modified before the given time, 'newer' matches files / folders last modified within the given time. (default = 'older') Returns: {lastmodified}: The datetime the files / folders was lastmodified. """ name = "lastmodified" schema_support_instance_without_args = True arg_schema = { Optional("mode"): Or("older", "newer"), Optional("years"): int, Optional("months"): int, Optional("weeks"): int, Optional("days"): int, Optional("hours"): int, Optional("minutes"): int, Optional("seconds"): int, } def __init__( self, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, mode="older", ): self.age = timedelta( weeks=52 * years + 4 * months + weeks, # quick and a bit dirty days=days, hours=hours, minutes=minutes, seconds=seconds, ) self.mode = mode.strip().lower() if self.mode not in ("older", "newer"): raise ValueError("Unknown option for 'mode': must be 'older' or 'newer'.") def matches_lastmodified_time(self, lastmodified: Union[None, datetime]): match = True if self.age.total_seconds(): if not lastmodified: match = False else: match = age_condition_applies( dt=lastmodified, age=self.age, mode=self.mode, reference=datetime.now(), ) return match def pipeline(self, args: dict) -> FilterResult: fs = args["fs"] # type: FS fs_path = args["fs_path"] modified = fs.getmodified(fs_path) if modified: modified = modified.astimezone() match = self.matches_lastmodified_time(modified) return FilterResult( matches=match, updates={self.get_name(): modified}, ) def __str__(self): return "[LastModified] All files / folders last modified %s than %s" % ( self._mode, self.timedelta, )
en
0.386335
Matches files by last modified date Args: years (int): specify number of years months (int): specify number of months weeks (float): specify number of weeks days (float): specify number of days hours (float): specify number of hours minutes (float): specify number of minutes seconds (float): specify number of seconds mode (str): either 'older' or 'newer'. 'older' matches files / folders last modified before the given time, 'newer' matches files / folders last modified within the given time. (default = 'older') Returns: {lastmodified}: The datetime the files / folders was lastmodified. # quick and a bit dirty # type: FS
2.982057
3
IPP/desempacotamento.py
juarezhenriquelisboa/Python
1
6614341
def imprime_maior(mensagem, *numeros): maior = None for e in numeros: if maior == None or maior < e: maior = e print(mensagem, maior) imprime_maior("Maior:", 5,4,3,1) imprime_maior("Max:", *[1, 7, 9])
def imprime_maior(mensagem, *numeros): maior = None for e in numeros: if maior == None or maior < e: maior = e print(mensagem, maior) imprime_maior("Maior:", 5,4,3,1) imprime_maior("Max:", *[1, 7, 9])
none
1
3.571095
4
fish-wf/scripts/fish_sphere_boxplot.py
jfear/larval_gonad
1
6614342
<reponame>jfear/larval_gonad import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from matplotlib.collections import LineCollection import matplotlib.pyplot as plt from scipy.stats import ttest_rel from larval_gonad import plotting def main(): plt.style.use(["1c", "science_base"]) width = plt.rcParams["figure.figsize"][0] plt.rcParams["figure.figsize"] = (width, width) sphere = pd.read_csv(snakemake.input[0]) ax = sns.boxplot( "chrom", "um3", data=sphere.melt(var_name="chrom", value_name="um3"), palette=snakemake.params.colors, notch=True ) # Clean up plot ax.set(ylabel=r"$\Psi$", xlabel="") sns.despine(ax=ax) # Test that not significant pval = np.round(ttest_rel(sphere["X"], sphere["2L"])[1], 3) if pval <= 0.05: # Extend axis and add NS. _max = sphere.max().max() + 0.05 ax.set_ylim(None, _max) ax.text(0.5, 0.99, f"p = {pval}", transform=ax.transAxes, va="top", ha="center") l = plt.Line2D([0.3, 0.7], [0.94, 0.94], transform=ax.transAxes, color="k", lw=0.8, ls="-") ax.add_line(l) plt.savefig(snakemake.output[0]) if __name__ == "__main__": if os.getenv("SNAKE_DEBUG", False): from larval_gonad.debug import snakemake_debug snakemake = snakemake_debug( workdir="fish-wf", input="../data/external/miriam/oligopaint_sphere.csv", params=dict(colors=["red", "grey"]), ) main()
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from matplotlib.collections import LineCollection import matplotlib.pyplot as plt from scipy.stats import ttest_rel from larval_gonad import plotting def main(): plt.style.use(["1c", "science_base"]) width = plt.rcParams["figure.figsize"][0] plt.rcParams["figure.figsize"] = (width, width) sphere = pd.read_csv(snakemake.input[0]) ax = sns.boxplot( "chrom", "um3", data=sphere.melt(var_name="chrom", value_name="um3"), palette=snakemake.params.colors, notch=True ) # Clean up plot ax.set(ylabel=r"$\Psi$", xlabel="") sns.despine(ax=ax) # Test that not significant pval = np.round(ttest_rel(sphere["X"], sphere["2L"])[1], 3) if pval <= 0.05: # Extend axis and add NS. _max = sphere.max().max() + 0.05 ax.set_ylim(None, _max) ax.text(0.5, 0.99, f"p = {pval}", transform=ax.transAxes, va="top", ha="center") l = plt.Line2D([0.3, 0.7], [0.94, 0.94], transform=ax.transAxes, color="k", lw=0.8, ls="-") ax.add_line(l) plt.savefig(snakemake.output[0]) if __name__ == "__main__": if os.getenv("SNAKE_DEBUG", False): from larval_gonad.debug import snakemake_debug snakemake = snakemake_debug( workdir="fish-wf", input="../data/external/miriam/oligopaint_sphere.csv", params=dict(colors=["red", "grey"]), ) main()
en
0.792041
# Clean up plot # Test that not significant # Extend axis and add NS.
2.481744
2
01_Language/05_Python/study/lesson_02/10.类型转换.py
cliff363825/TwentyFour
3
6614343
<gh_stars>1-10 # 类型转换四个函数 int() float() str() bool() # int() 可以用来将其他的对象转换为整型 # 规则: # 布尔值:True -> 1 False -> 0 # 浮点数:直接取整,省略小数点后的内容 # 字符串:合法的整数字符串,直接转换为对应的数字 # 如果不是一个合法的整数字符串,则报错 ValueError: invalid literal for int() with base 10: '11.5' # 对于其他不可转换为整型的对象,直接抛出异常 ValueError # float() 和 int()基本一致,不同的是它会将对象转换为浮点数 # str() 可以将对象转换为字符串 # True -> 'True' # False -> 'False' # 123 -> '123' # 。。。 # bool() 可以将对象转换为布尔值,任何对象都可以转换为布尔值 # 规则:对于所有表示空性的对象都会转换为False,其余的转换为True # 哪些表示的空性:0 、 None 、 '' 。。。 a = True # 调用int()来将a转换为整型 # int()函数不会对原来的变量产生影响,他是对象转换为指定的类型并将其作为返回值返回 # 如果希望修改原来的变量,则需要对变量进行重新赋值 a = int(a) a = False a = int(a) a = '123' a = int(a) a = 11.6 a = int(a) a = '11.5' # a = int(a) a = None # a = int(a) a = 1 a = float(a) a = False a = float(a) a = 123 a = str(a) a = None a = bool(a) print('a =', a) print('a的类型是', type(a)) # b = 456 # print('hello'+str(b))
# 类型转换四个函数 int() float() str() bool() # int() 可以用来将其他的对象转换为整型 # 规则: # 布尔值:True -> 1 False -> 0 # 浮点数:直接取整,省略小数点后的内容 # 字符串:合法的整数字符串,直接转换为对应的数字 # 如果不是一个合法的整数字符串,则报错 ValueError: invalid literal for int() with base 10: '11.5' # 对于其他不可转换为整型的对象,直接抛出异常 ValueError # float() 和 int()基本一致,不同的是它会将对象转换为浮点数 # str() 可以将对象转换为字符串 # True -> 'True' # False -> 'False' # 123 -> '123' # 。。。 # bool() 可以将对象转换为布尔值,任何对象都可以转换为布尔值 # 规则:对于所有表示空性的对象都会转换为False,其余的转换为True # 哪些表示的空性:0 、 None 、 '' 。。。 a = True # 调用int()来将a转换为整型 # int()函数不会对原来的变量产生影响,他是对象转换为指定的类型并将其作为返回值返回 # 如果希望修改原来的变量,则需要对变量进行重新赋值 a = int(a) a = False a = int(a) a = '123' a = int(a) a = 11.6 a = int(a) a = '11.5' # a = int(a) a = None # a = int(a) a = 1 a = float(a) a = False a = float(a) a = 123 a = str(a) a = None a = bool(a) print('a =', a) print('a的类型是', type(a)) # b = 456 # print('hello'+str(b))
zh
0.948916
# 类型转换四个函数 int() float() str() bool() # int() 可以用来将其他的对象转换为整型 # 规则: # 布尔值:True -> 1 False -> 0 # 浮点数:直接取整,省略小数点后的内容 # 字符串:合法的整数字符串,直接转换为对应的数字 # 如果不是一个合法的整数字符串,则报错 ValueError: invalid literal for int() with base 10: '11.5' # 对于其他不可转换为整型的对象,直接抛出异常 ValueError # float() 和 int()基本一致,不同的是它会将对象转换为浮点数 # str() 可以将对象转换为字符串 # True -> 'True' # False -> 'False' # 123 -> '123' # 。。。 # bool() 可以将对象转换为布尔值,任何对象都可以转换为布尔值 # 规则:对于所有表示空性的对象都会转换为False,其余的转换为True # 哪些表示的空性:0 、 None 、 '' 。。。 # 调用int()来将a转换为整型 # int()函数不会对原来的变量产生影响,他是对象转换为指定的类型并将其作为返回值返回 # 如果希望修改原来的变量,则需要对变量进行重新赋值 # a = int(a) # a = int(a) # b = 456 # print('hello'+str(b))
4.383765
4
DB.py
YashSingh2006/DATA-VISUALISATION
0
6614344
import pandas as pd import plotly.express as ps df = pd.read_csv("Copy+of+data+-+data.csv") fig = ps.scatter(df,x = "date", y = "cases", color = "country") fig.show()
import pandas as pd import plotly.express as ps df = pd.read_csv("Copy+of+data+-+data.csv") fig = ps.scatter(df,x = "date", y = "cases", color = "country") fig.show()
none
1
3.338706
3
deploy/deploy.py
chud0/is_workday
0
6614345
<reponame>chud0/is_workday import logging from pathlib import Path import paramiko from plumbum import local from plumbum.machines.paramiko_machine import ParamikoMachine BASE_DIR = Path(__file__).parent.parent logging.basicConfig(format='%(levelname)-8s %(asctime)s %(message)s', level=logging.INFO) logger = logging.getLogger('deploy') if __name__ == '__main__': host = local.env['DEPLOY_HOST'] user = local.env['DEPLOY_USER'] remote_dir = local.env['DEPLOY_DIR'] deploy_key = local.env['DEPLOY_KEY'] deploy_key_file = BASE_DIR / 'tmp' deploy_key_file.write_text('\n'.join(deploy_key.split('|'))) try: with ParamikoMachine( host, user=user, keyfile=str(deploy_key_file), load_system_host_keys=False, missing_host_policy=paramiko.AutoAddPolicy(), ) as rem: rem.upload(BASE_DIR / 'deploy' / 'docker-compose.yml', f'{remote_dir}/docker-compose.yml') logger.info('Copy %s', 'docker-compose.yml') rem.upload(BASE_DIR / 'deploy' / 'nginx.conf', f'{remote_dir}/nginx.conf') logger.info('Copy %s', 'nginx.conf') docker_compose = rem['docker-compose'] docker_compose['down', '--rmi', 'all']() logger.info('docker-compose stop') docker_compose['up', '-d']() logger.info('docker-compose up') finally: deploy_key_file.unlink()
import logging from pathlib import Path import paramiko from plumbum import local from plumbum.machines.paramiko_machine import ParamikoMachine BASE_DIR = Path(__file__).parent.parent logging.basicConfig(format='%(levelname)-8s %(asctime)s %(message)s', level=logging.INFO) logger = logging.getLogger('deploy') if __name__ == '__main__': host = local.env['DEPLOY_HOST'] user = local.env['DEPLOY_USER'] remote_dir = local.env['DEPLOY_DIR'] deploy_key = local.env['DEPLOY_KEY'] deploy_key_file = BASE_DIR / 'tmp' deploy_key_file.write_text('\n'.join(deploy_key.split('|'))) try: with ParamikoMachine( host, user=user, keyfile=str(deploy_key_file), load_system_host_keys=False, missing_host_policy=paramiko.AutoAddPolicy(), ) as rem: rem.upload(BASE_DIR / 'deploy' / 'docker-compose.yml', f'{remote_dir}/docker-compose.yml') logger.info('Copy %s', 'docker-compose.yml') rem.upload(BASE_DIR / 'deploy' / 'nginx.conf', f'{remote_dir}/nginx.conf') logger.info('Copy %s', 'nginx.conf') docker_compose = rem['docker-compose'] docker_compose['down', '--rmi', 'all']() logger.info('docker-compose stop') docker_compose['up', '-d']() logger.info('docker-compose up') finally: deploy_key_file.unlink()
none
1
2.096409
2
app/blueprints/gallery/routes.py
reynoldsjs/Final-Project
0
6614346
import os from . import bp as gallery from flask import render_template, url_for @gallery.route('/gallery') def gallery(): # return render_template('gallery.html') # def photos(): # basedir = os.path.abspath(os.path.dirname(__file__)) pics = os.listdir('app/static/gallery') return render_template("gallery.html", pics=pics)
import os from . import bp as gallery from flask import render_template, url_for @gallery.route('/gallery') def gallery(): # return render_template('gallery.html') # def photos(): # basedir = os.path.abspath(os.path.dirname(__file__)) pics = os.listdir('app/static/gallery') return render_template("gallery.html", pics=pics)
en
0.20987
# return render_template('gallery.html') # def photos(): # basedir = os.path.abspath(os.path.dirname(__file__))
2.230018
2
examples/demo1.py
rid-dim/pySafe
9
6614347
# Demo 1 # Demonstrates some basic functionality of the library and serves as a reminder of what needs to be cleaned up # This file will be done when there is no weird variables or boilerplate import safenet import time # try it with and without the logger enabled. # check config.py for default settings. check log_util.setup_logger() for kw arguments # if you want to intercept the messages, you can inject your own handlers. safenet.setup_logger() with open('creds.txt') as f: # For simplicity, my credentials are in a simple file called creds.txt. creds=f.readlines()[0].strip().split() usrnm,psw = creds[0],creds[1] # Logging in is easy! myAuth=safenet.Authenticator() #myAuth.login(usrnm,psw,myAuth.pointer, o_cb=myAuth.login_cb) # works, as it goes through user data myAuth.login(usrnm,psw,None, o_cb=myAuth.login_cb) # Necessary to avoid issues with threading .. safenet.log.info('sleeping until login cb') while myAuth.handle is None: time.sleep(0.1) #myAuth.auth_account_info(myAuth.handle, myAuth.pointer, o_cb=myAuth.info_cb) # this way uses userdata myAuth.account_info() # Necessary to avoid issues with threading .. safenet.log.info('sleeping until info cb') while myAuth._info is None: time.sleep(0.1) myAuth.auth_registered_apps(myAuth.handle, myAuth.pointer, o_cb=myAuth.registered_apps_cb) safenet.log.info('sleeping until apps cb') while myAuth._apps is None: time.sleep(0.1) #myApp=safenet.App() #I = safenet.ImmutableData() #I.idata_new_self_encryptor()
# Demo 1 # Demonstrates some basic functionality of the library and serves as a reminder of what needs to be cleaned up # This file will be done when there is no weird variables or boilerplate import safenet import time # try it with and without the logger enabled. # check config.py for default settings. check log_util.setup_logger() for kw arguments # if you want to intercept the messages, you can inject your own handlers. safenet.setup_logger() with open('creds.txt') as f: # For simplicity, my credentials are in a simple file called creds.txt. creds=f.readlines()[0].strip().split() usrnm,psw = creds[0],creds[1] # Logging in is easy! myAuth=safenet.Authenticator() #myAuth.login(usrnm,psw,myAuth.pointer, o_cb=myAuth.login_cb) # works, as it goes through user data myAuth.login(usrnm,psw,None, o_cb=myAuth.login_cb) # Necessary to avoid issues with threading .. safenet.log.info('sleeping until login cb') while myAuth.handle is None: time.sleep(0.1) #myAuth.auth_account_info(myAuth.handle, myAuth.pointer, o_cb=myAuth.info_cb) # this way uses userdata myAuth.account_info() # Necessary to avoid issues with threading .. safenet.log.info('sleeping until info cb') while myAuth._info is None: time.sleep(0.1) myAuth.auth_registered_apps(myAuth.handle, myAuth.pointer, o_cb=myAuth.registered_apps_cb) safenet.log.info('sleeping until apps cb') while myAuth._apps is None: time.sleep(0.1) #myApp=safenet.App() #I = safenet.ImmutableData() #I.idata_new_self_encryptor()
en
0.812471
# Demo 1 # Demonstrates some basic functionality of the library and serves as a reminder of what needs to be cleaned up # This file will be done when there is no weird variables or boilerplate # try it with and without the logger enabled. # check config.py for default settings. check log_util.setup_logger() for kw arguments # if you want to intercept the messages, you can inject your own handlers. # For simplicity, my credentials are in a simple file called creds.txt. # Logging in is easy! #myAuth.login(usrnm,psw,myAuth.pointer, o_cb=myAuth.login_cb) # works, as it goes through user data # Necessary to avoid issues with threading .. #myAuth.auth_account_info(myAuth.handle, myAuth.pointer, o_cb=myAuth.info_cb) # this way uses userdata # Necessary to avoid issues with threading .. #myApp=safenet.App() #I = safenet.ImmutableData() #I.idata_new_self_encryptor()
2.165715
2
localgraphclustering/capacity_releasing_diffusion.py
vishalbelsare/LocalGraphClustering
106
6614348
from typing import * import numpy as np from .cpp import * from .GraphLocal import GraphLocal def capacity_releasing_diffusion(G,ref_nodes, U: int = 3, h: int = 10, w: int = 2, iterations: int = 20): """ Description ----------- Algorithm Capacity Releasing Diffusion for local graph clustering. This algorithm uses a flow based method to push excess flow out of nodes. The algorithm is in worst-case faster and stays more local than classical spectral diffusion processes. For more details please refere to: <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. Capacity Releasing Diffusion for Speed and Locality. ICML 2017. arXiv link: https://arxiv.org/abs/1706.05826 Parameters (mandatory) ---------------------- G: GraphLocal ref_nodes: Sequence[int] A sequence of reference nodes, i.e., nodes of interest around which we are looking for a target cluster. Parameters (optional) -------------------- U: integer default == 3 The maximum flow that can be send out of a node for the push/relabel algorithm. h: integer defaul == 10 The maximum flow that an edge can handle. w: integer default == 2 Multiplicative factor for increasing the capacity of the nodes at each iteration. iterations: integer default = 20 Maximum number of iterations of Capacity Releasing Diffusion Algorithm. Returns ------- It returns in a list of length 2 with the following: output 0: list Stores indices of the best clusters found by the last called rounding procedure. output 1: float Stores the value of the best conductance found by the last called rounding procedure. Printing statements (warnings) ------------------------------ Too much excess: Means that push/relabel cannot push the excess flow out of the nodes. This might indicate that a cluster has been found. In this case the best cluster in terms of conductance is returned. Too much flow: Means that the algorithm has touched about a third of the whole given graph. The algorithm is terminated in this case and the best cluster in terms of conductance is returned. """ n = G.adjacency_matrix.shape[0] actual_xids = capacity_releasing_diffusion_cpp(n,G.ai,G.aj,np.float64(G.adjacency_matrix.data), U,h,w,iterations,ref_nodes) return [actual_xids, G.compute_conductance(actual_xids)]
from typing import * import numpy as np from .cpp import * from .GraphLocal import GraphLocal def capacity_releasing_diffusion(G,ref_nodes, U: int = 3, h: int = 10, w: int = 2, iterations: int = 20): """ Description ----------- Algorithm Capacity Releasing Diffusion for local graph clustering. This algorithm uses a flow based method to push excess flow out of nodes. The algorithm is in worst-case faster and stays more local than classical spectral diffusion processes. For more details please refere to: <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. Capacity Releasing Diffusion for Speed and Locality. ICML 2017. arXiv link: https://arxiv.org/abs/1706.05826 Parameters (mandatory) ---------------------- G: GraphLocal ref_nodes: Sequence[int] A sequence of reference nodes, i.e., nodes of interest around which we are looking for a target cluster. Parameters (optional) -------------------- U: integer default == 3 The maximum flow that can be send out of a node for the push/relabel algorithm. h: integer defaul == 10 The maximum flow that an edge can handle. w: integer default == 2 Multiplicative factor for increasing the capacity of the nodes at each iteration. iterations: integer default = 20 Maximum number of iterations of Capacity Releasing Diffusion Algorithm. Returns ------- It returns in a list of length 2 with the following: output 0: list Stores indices of the best clusters found by the last called rounding procedure. output 1: float Stores the value of the best conductance found by the last called rounding procedure. Printing statements (warnings) ------------------------------ Too much excess: Means that push/relabel cannot push the excess flow out of the nodes. This might indicate that a cluster has been found. In this case the best cluster in terms of conductance is returned. Too much flow: Means that the algorithm has touched about a third of the whole given graph. The algorithm is terminated in this case and the best cluster in terms of conductance is returned. """ n = G.adjacency_matrix.shape[0] actual_xids = capacity_releasing_diffusion_cpp(n,G.ai,G.aj,np.float64(G.adjacency_matrix.data), U,h,w,iterations,ref_nodes) return [actual_xids, G.compute_conductance(actual_xids)]
en
0.847586
Description ----------- Algorithm Capacity Releasing Diffusion for local graph clustering. This algorithm uses a flow based method to push excess flow out of nodes. The algorithm is in worst-case faster and stays more local than classical spectral diffusion processes. For more details please refere to: <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. Capacity Releasing Diffusion for Speed and Locality. ICML 2017. arXiv link: https://arxiv.org/abs/1706.05826 Parameters (mandatory) ---------------------- G: GraphLocal ref_nodes: Sequence[int] A sequence of reference nodes, i.e., nodes of interest around which we are looking for a target cluster. Parameters (optional) -------------------- U: integer default == 3 The maximum flow that can be send out of a node for the push/relabel algorithm. h: integer defaul == 10 The maximum flow that an edge can handle. w: integer default == 2 Multiplicative factor for increasing the capacity of the nodes at each iteration. iterations: integer default = 20 Maximum number of iterations of Capacity Releasing Diffusion Algorithm. Returns ------- It returns in a list of length 2 with the following: output 0: list Stores indices of the best clusters found by the last called rounding procedure. output 1: float Stores the value of the best conductance found by the last called rounding procedure. Printing statements (warnings) ------------------------------ Too much excess: Means that push/relabel cannot push the excess flow out of the nodes. This might indicate that a cluster has been found. In this case the best cluster in terms of conductance is returned. Too much flow: Means that the algorithm has touched about a third of the whole given graph. The algorithm is terminated in this case and the best cluster in terms of conductance is returned.
3.232136
3
src/kafka_core/kafka_util.py
bkatwal/distributed-kafka-consumer-python
2
6614349
<gh_stars>1-10 from kafka import KafkaConsumer TWO_MINUTES = 2 def is_end_offset_none(end_offsets: dict, start_offsets: dict) -> bool: """ Utility function to check if the partition that has start offset has end offset too. :param end_offsets: topic partition and end offsets :param start_offsets:topic partition and start offsets :return: True/False """ if len(end_offsets) == 0: return True for tp, offset in end_offsets.items(): if offset is None and start_offsets[tp] is not None: return True return False def is_all_end_offset_found(end_offsets: dict, start_offsets: dict) -> bool: """ Utility function to check if the partition that has start offset has end offset too. :param end_offsets: topic partition and end offsets :param start_offsets:topic partition and start offsets :return: True/False """ if len(end_offsets) == 0: return False for tp, offset in end_offsets.items(): if offset is None and start_offsets[tp] is not None: return False return True def get_start_end_offsets(start_timestamp: int, end_timestamp: int, topic_partitions: set, consumer: KafkaConsumer): """ Get start and end offset for all the partitions based on the given start and end timestamp :param start_timestamp: start timestamp in epoch time millis :param end_timestamp: end timestamp in epoch time millis :param topic_partitions: topic partition set :param consumer: kafka consumer :return: tuple of start offsets and end offsets for each partition """ tp_start_timestamps: dict = {} for tp in topic_partitions: tp_start_timestamps[tp] = start_timestamp start_offsets = consumer.offsets_for_times(tp_start_timestamps) end_offsets = {} # go back 2 minute and keep checking if there are end offsets in partition tp_end_timestamps: dict = {} while not is_all_end_offset_found(start_offsets=start_offsets, end_offsets=end_offsets): for tp in topic_partitions: # seek previous offset from a partition only if the offset is not found if len(end_offsets) == 0 or (end_offsets[tp] is None and start_offsets[tp] is not None): tp_end_timestamps[tp] = end_timestamp end_offsets = consumer.offsets_for_times(tp_end_timestamps) end_timestamp = end_timestamp - (TWO_MINUTES * 60 * 1000) return start_offsets, end_offsets
from kafka import KafkaConsumer TWO_MINUTES = 2 def is_end_offset_none(end_offsets: dict, start_offsets: dict) -> bool: """ Utility function to check if the partition that has start offset has end offset too. :param end_offsets: topic partition and end offsets :param start_offsets:topic partition and start offsets :return: True/False """ if len(end_offsets) == 0: return True for tp, offset in end_offsets.items(): if offset is None and start_offsets[tp] is not None: return True return False def is_all_end_offset_found(end_offsets: dict, start_offsets: dict) -> bool: """ Utility function to check if the partition that has start offset has end offset too. :param end_offsets: topic partition and end offsets :param start_offsets:topic partition and start offsets :return: True/False """ if len(end_offsets) == 0: return False for tp, offset in end_offsets.items(): if offset is None and start_offsets[tp] is not None: return False return True def get_start_end_offsets(start_timestamp: int, end_timestamp: int, topic_partitions: set, consumer: KafkaConsumer): """ Get start and end offset for all the partitions based on the given start and end timestamp :param start_timestamp: start timestamp in epoch time millis :param end_timestamp: end timestamp in epoch time millis :param topic_partitions: topic partition set :param consumer: kafka consumer :return: tuple of start offsets and end offsets for each partition """ tp_start_timestamps: dict = {} for tp in topic_partitions: tp_start_timestamps[tp] = start_timestamp start_offsets = consumer.offsets_for_times(tp_start_timestamps) end_offsets = {} # go back 2 minute and keep checking if there are end offsets in partition tp_end_timestamps: dict = {} while not is_all_end_offset_found(start_offsets=start_offsets, end_offsets=end_offsets): for tp in topic_partitions: # seek previous offset from a partition only if the offset is not found if len(end_offsets) == 0 or (end_offsets[tp] is None and start_offsets[tp] is not None): tp_end_timestamps[tp] = end_timestamp end_offsets = consumer.offsets_for_times(tp_end_timestamps) end_timestamp = end_timestamp - (TWO_MINUTES * 60 * 1000) return start_offsets, end_offsets
en
0.826563
Utility function to check if the partition that has start offset has end offset too. :param end_offsets: topic partition and end offsets :param start_offsets:topic partition and start offsets :return: True/False Utility function to check if the partition that has start offset has end offset too. :param end_offsets: topic partition and end offsets :param start_offsets:topic partition and start offsets :return: True/False Get start and end offset for all the partitions based on the given start and end timestamp :param start_timestamp: start timestamp in epoch time millis :param end_timestamp: end timestamp in epoch time millis :param topic_partitions: topic partition set :param consumer: kafka consumer :return: tuple of start offsets and end offsets for each partition # go back 2 minute and keep checking if there are end offsets in partition # seek previous offset from a partition only if the offset is not found
3.158036
3
bugal/base/models/shift_types.py
aquitania99/bugal-app
0
6614350
# Django from django.db import models class ShiftType(models.Model): """Shift Types model. List of Shift types, used by users and clients. """ name = models.CharField('shift type', max_length=100) def __str__(self): return self.name
# Django from django.db import models class ShiftType(models.Model): """Shift Types model. List of Shift types, used by users and clients. """ name = models.CharField('shift type', max_length=100) def __str__(self): return self.name
en
0.863859
# Django Shift Types model. List of Shift types, used by users and clients.
2.429767
2