body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def _write_metrics(metrics_mngr, tb_mngr, metrics, round_num):
'Atomic metrics writer which inlines logic from MetricsHook class.'
if (not isinstance(metrics, dict)):
raise TypeError('metrics should be type `dict`.')
if (not isinstance(round_num, int)):
raise TypeError('round_num should be t... | 1,945,417,938,138,571,300 | Atomic metrics writer which inlines logic from MetricsHook class. | utils/training_loop.py | _write_metrics | houcharlie/federated | python | def _write_metrics(metrics_mngr, tb_mngr, metrics, round_num):
if (not isinstance(metrics, dict)):
raise TypeError('metrics should be type `dict`.')
if (not isinstance(round_num, int)):
raise TypeError('round_num should be type `int`.')
logging.info('Metrics at round {:d}:\n{!s}'.format... |
def _check_iterative_process_compatibility(iterative_process):
'Checks the compatibility of an iterative process with the training loop.'
error_message = 'The iterative_process argument must be of type`tff.templates.IterativeProcess`, and must have an attribute `get_model_weights`, which must be a `tff.Computat... | -6,501,721,324,460,617,000 | Checks the compatibility of an iterative process with the training loop. | utils/training_loop.py | _check_iterative_process_compatibility | houcharlie/federated | python | def _check_iterative_process_compatibility(iterative_process):
error_message = 'The iterative_process argument must be of type`tff.templates.IterativeProcess`, and must have an attribute `get_model_weights`, which must be a `tff.Computation`. This computation must accept as input the state of `iterative_proces... |
def run(iterative_process: tff.templates.IterativeProcess, client_datasets_fn: Callable[([int], List[tf.data.Dataset])], validation_fn: Callable[([Any, int], Dict[(str, float)])], total_rounds: int, experiment_name: str, test_fn: Optional[Callable[([Any], Dict[(str, float)])]]=None, root_output_dir: Optional[str]='/tmp... | -629,683,971,590,818,000 | Runs federated training for a given `tff.templates.IterativeProcess`.
We assume that the iterative process has the following functional type
signatures:
* `initialize`: `( -> S@SERVER)` where `S` represents the server state.
* `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`
represen... | utils/training_loop.py | run | houcharlie/federated | python | def run(iterative_process: tff.templates.IterativeProcess, client_datasets_fn: Callable[([int], List[tf.data.Dataset])], validation_fn: Callable[([Any, int], Dict[(str, float)])], total_rounds: int, experiment_name: str, test_fn: Optional[Callable[([Any], Dict[(str, float)])]]=None, root_output_dir: Optional[str]='/tmp... |
def setup_inp(inp):
'Convert list of strings into list of lists, with glves/goblins replaced by tuples'
grid = []
for (rowI, row) in enumerate(inp.split('\n')):
grid.append([x for x in row])
for (colI, col) in enumerate(row):
if (col in ['G', 'E']):
char_tup = (co... | -1,784,923,850,771,478,300 | Convert list of strings into list of lists, with glves/goblins replaced by tuples | 2018/15/helpme.py | setup_inp | mark-inderhees/aoc | python | def setup_inp(inp):
grid = []
for (rowI, row) in enumerate(inp.split('\n')):
grid.append([x for x in row])
for (colI, col) in enumerate(row):
if (col in ['G', 'E']):
char_tup = (col, 200, False)
grid[rowI][colI] = char_tup
return grid |
def move_character(inp, from_row, from_col, to_row, to_col, char):
'Move character on grid, and increment the i value so we can tell we already moved it'
inp[from_row][from_col] = '.'
inp[to_row][to_col] = (char[0], char[1], True)
return inp | -2,405,267,525,196,605,400 | Move character on grid, and increment the i value so we can tell we already moved it | 2018/15/helpme.py | move_character | mark-inderhees/aoc | python | def move_character(inp, from_row, from_col, to_row, to_col, char):
inp[from_row][from_col] = '.'
inp[to_row][to_col] = (char[0], char[1], True)
return inp |
def attack(inp, row, col, enemy, damage=3):
'\n Attack weakest adjacent enemy, if one is there\n If multiple weakest enemies, attack in reading order\n Return the modified board, and a boolean indicating whether anyone died\n '
if (not adjacent_enemy(inp, row, col, enemy)):
return (inp, Fals... | -7,804,793,766,275,739,000 | Attack weakest adjacent enemy, if one is there
If multiple weakest enemies, attack in reading order
Return the modified board, and a boolean indicating whether anyone died | 2018/15/helpme.py | attack | mark-inderhees/aoc | python | def attack(inp, row, col, enemy, damage=3):
'\n Attack weakest adjacent enemy, if one is there\n If multiple weakest enemies, attack in reading order\n Return the modified board, and a boolean indicating whether anyone died\n '
if (not adjacent_enemy(inp, row, col, enemy)):
return (inp, Fals... |
def adjacent_enemy(inp, rowI, colI, enemy):
'Check for enemy in adjacent square'
if any(((x[0] == enemy) for x in [inp[(rowI + 1)][colI], inp[(rowI - 1)][colI], inp[rowI][(colI + 1)], inp[rowI][(colI - 1)]])):
return True
return False | 3,321,948,015,826,023,400 | Check for enemy in adjacent square | 2018/15/helpme.py | adjacent_enemy | mark-inderhees/aoc | python | def adjacent_enemy(inp, rowI, colI, enemy):
if any(((x[0] == enemy) for x in [inp[(rowI + 1)][colI], inp[(rowI - 1)][colI], inp[rowI][(colI + 1)], inp[rowI][(colI - 1)]])):
return True
return False |
def get_best_move(best_moves):
'\n Takes a list of tuples of\n (first_move, number_of_moves, tile_coordinates), which might look like -\n ((12, 22), 8, (17, 25))\n ((12, 22), 8, (18, 24))\n ((12, 22), 8, (19, 21))\n ((13, 21), 6, (19, 21))\n ((13, 23), 6, (17, 25))\n ((13, 23), 6, (18, 24))\... | -3,099,320,645,593,120,300 | Takes a list of tuples of
(first_move, number_of_moves, tile_coordinates), which might look like -
((12, 22), 8, (17, 25))
((12, 22), 8, (18, 24))
((12, 22), 8, (19, 21))
((13, 21), 6, (19, 21))
((13, 23), 6, (17, 25))
((13, 23), 6, (18, 24))
((14, 22), 6, (17, 25))
((14, 22), 6, (18, 24))
((14, 22), 6, (19, 21))
And f... | 2018/15/helpme.py | get_best_move | mark-inderhees/aoc | python | def get_best_move(best_moves):
'\n Takes a list of tuples of\n (first_move, number_of_moves, tile_coordinates), which might look like -\n ((12, 22), 8, (17, 25))\n ((12, 22), 8, (18, 24))\n ((12, 22), 8, (19, 21))\n ((13, 21), 6, (19, 21))\n ((13, 23), 6, (17, 25))\n ((13, 23), 6, (18, 24))\... |
def bfs_move(inp, rowI, colI, hero, enemy):
'\n Perform a breadth first search for each adjacent tile\n Although not the most efficient, the approach is still fast and makes it\n easy to sort in such a way that satisfies all the conditions\n '
if adjacent_enemy(inp, rowI, colI, enemy):
retur... | 7,900,044,209,021,287,000 | Perform a breadth first search for each adjacent tile
Although not the most efficient, the approach is still fast and makes it
easy to sort in such a way that satisfies all the conditions | 2018/15/helpme.py | bfs_move | mark-inderhees/aoc | python | def bfs_move(inp, rowI, colI, hero, enemy):
'\n Perform a breadth first search for each adjacent tile\n Although not the most efficient, the approach is still fast and makes it\n easy to sort in such a way that satisfies all the conditions\n '
if adjacent_enemy(inp, rowI, colI, enemy):
retur... |
def reset_moved_bools(inp):
"Reset the third value in our character tuples, which tracks whether they've moved in a round"
for (rowI, row) in enumerate(inp):
for (colI, col) in enumerate(row):
if (col[0] in ['G', 'E']):
char_tup = (col[0], col[1], False)
inp[r... | -8,201,011,777,282,888,000 | Reset the third value in our character tuples, which tracks whether they've moved in a round | 2018/15/helpme.py | reset_moved_bools | mark-inderhees/aoc | python | def reset_moved_bools(inp):
for (rowI, row) in enumerate(inp):
for (colI, col) in enumerate(row):
if (col[0] in ['G', 'E']):
char_tup = (col[0], col[1], False)
inp[rowI][colI] = char_tup
return inp |
def equal_devision(length, div_num):
'\n # 概要\n length を div_num で分割する。\n 端数が出た場合は誤差拡散法を使って上手い具合に分散させる。\n '
base = (length / div_num)
ret_array = [base for x in range(div_num)]
diff = 0
for idx in range(div_num):
diff += math.modf(ret_array[idx])[0]
if (diff >= 1.0):
... | -5,392,802,471,796,530,000 | # 概要
length を div_num で分割する。
端数が出た場合は誤差拡散法を使って上手い具合に分散させる。 | ty_lib/test_pattern_generator2.py | equal_devision | colour-science/sample_code | python | def equal_devision(length, div_num):
'\n # 概要\n length を div_num で分割する。\n 端数が出た場合は誤差拡散法を使って上手い具合に分散させる。\n '
base = (length / div_num)
ret_array = [base for x in range(div_num)]
diff = 0
for idx in range(div_num):
diff += math.modf(ret_array[idx])[0]
if (diff >= 1.0):
... |
def do_matrix(img, mtx):
'\n img に対して mtx を適用する。\n '
base_shape = img.shape
(r, g, b) = (img[(..., 0)], img[(..., 1)], img[(..., 2)])
ro = (((r * mtx[0][0]) + (g * mtx[0][1])) + (b * mtx[0][2]))
go = (((r * mtx[1][0]) + (g * mtx[1][1])) + (b * mtx[1][2]))
bo = (((r * mtx[2][0]) + (g * mtx[... | -4,858,280,892,068,223,000 | img に対して mtx を適用する。 | ty_lib/test_pattern_generator2.py | do_matrix | colour-science/sample_code | python | def do_matrix(img, mtx):
'\n \n '
base_shape = img.shape
(r, g, b) = (img[(..., 0)], img[(..., 1)], img[(..., 2)])
ro = (((r * mtx[0][0]) + (g * mtx[0][1])) + (b * mtx[0][2]))
go = (((r * mtx[1][0]) + (g * mtx[1][1])) + (b * mtx[1][2]))
bo = (((r * mtx[2][0]) + (g * mtx[2][1])) + (b * mtx[... |
def _get_cmfs_xy():
'\n xy色度図のプロットのための馬蹄形の外枠のxy値を求める。\n\n Returns\n -------\n array_like\n xy coordinate for chromaticity diagram\n\n '
cmf = CMFS.get(CMFS_NAME)
d65_white = D65_WHITE
cmf_xy = XYZ_to_xy(cmf.values, d65_white)
return cmf_xy | 1,856,355,623,035,113,500 | xy色度図のプロットのための馬蹄形の外枠のxy値を求める。
Returns
-------
array_like
xy coordinate for chromaticity diagram | ty_lib/test_pattern_generator2.py | _get_cmfs_xy | colour-science/sample_code | python | def _get_cmfs_xy():
'\n xy色度図のプロットのための馬蹄形の外枠のxy値を求める。\n\n Returns\n -------\n array_like\n xy coordinate for chromaticity diagram\n\n '
cmf = CMFS.get(CMFS_NAME)
d65_white = D65_WHITE
cmf_xy = XYZ_to_xy(cmf.values, d65_white)
return cmf_xy |
def get_primaries(name='ITU-R BT.2020'):
'\n prmary color の座標を求める\n\n\n Parameters\n ----------\n name : str\n a name of the color space.\n\n Returns\n -------\n array_like\n prmaries. [[rx, ry], [gx, gy], [bx, by], [rx, ry]]\n\n '
primaries = RGB_COLOURSPACES[name].primari... | -1,104,957,472,951,224,800 | prmary color の座標を求める
Parameters
----------
name : str
a name of the color space.
Returns
-------
array_like
prmaries. [[rx, ry], [gx, gy], [bx, by], [rx, ry]] | ty_lib/test_pattern_generator2.py | get_primaries | colour-science/sample_code | python | def get_primaries(name='ITU-R BT.2020'):
'\n prmary color の座標を求める\n\n\n Parameters\n ----------\n name : str\n a name of the color space.\n\n Returns\n -------\n array_like\n prmaries. [[rx, ry], [gx, gy], [bx, by], [rx, ry]]\n\n '
primaries = RGB_COLOURSPACES[name].primari... |
def xy_to_rgb(xy, name='ITU-R BT.2020', normalize='maximum', specific=None):
"\n xy値からRGB値を算出する。\n いい感じに正規化もしておく。\n\n Parameters\n ----------\n xy : array_like\n xy value.\n name : string\n color space name.\n normalize : string\n normalize method. You can select 'maximum',... | -2,746,982,639,432,358,000 | xy値からRGB値を算出する。
いい感じに正規化もしておく。
Parameters
----------
xy : array_like
xy value.
name : string
color space name.
normalize : string
normalize method. You can select 'maximum', 'specific' or None.
Returns
-------
array_like
rgb value. the value is normalized. | ty_lib/test_pattern_generator2.py | xy_to_rgb | colour-science/sample_code | python | def xy_to_rgb(xy, name='ITU-R BT.2020', normalize='maximum', specific=None):
"\n xy値からRGB値を算出する。\n いい感じに正規化もしておく。\n\n Parameters\n ----------\n xy : array_like\n xy value.\n name : string\n color space name.\n normalize : string\n normalize method. You can select 'maximum',... |
def get_white_point(name):
'\n white point を求める。CIE1931ベース。\n '
if (name != 'DCI-P3'):
illuminant = RGB_COLOURSPACES[name].illuminant
white_point = ILLUMINANTS[CMFS_NAME][illuminant]
else:
white_point = ILLUMINANTS[CMFS_NAME]['D65']
return white_point | 8,828,608,032,943,556,000 | white point を求める。CIE1931ベース。 | ty_lib/test_pattern_generator2.py | get_white_point | colour-science/sample_code | python | def get_white_point(name):
'\n \n '
if (name != 'DCI-P3'):
illuminant = RGB_COLOURSPACES[name].illuminant
white_point = ILLUMINANTS[CMFS_NAME][illuminant]
else:
white_point = ILLUMINANTS[CMFS_NAME]['D65']
return white_point |
def get_secondaries(name='ITU-R BT.2020'):
'\n secondary color の座標を求める\n\n Parameters\n ----------\n name : str\n a name of the color space.\n\n Returns\n -------\n array_like\n secondaries. the order is magenta, yellow, cyan.\n\n '
secondary_rgb = np.array([[1.0, 0.0, 1.0]... | 5,985,841,218,541,587,000 | secondary color の座標を求める
Parameters
----------
name : str
a name of the color space.
Returns
-------
array_like
secondaries. the order is magenta, yellow, cyan. | ty_lib/test_pattern_generator2.py | get_secondaries | colour-science/sample_code | python | def get_secondaries(name='ITU-R BT.2020'):
'\n secondary color の座標を求める\n\n Parameters\n ----------\n name : str\n a name of the color space.\n\n Returns\n -------\n array_like\n secondaries. the order is magenta, yellow, cyan.\n\n '
secondary_rgb = np.array([[1.0, 0.0, 1.0]... |
def get_chromaticity_image(samples=1024, antialiasing=True, bg_color=0.9, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0):
'\n xy色度図の馬蹄形の画像を生成する\n\n Returns\n -------\n ndarray\n rgb image.\n '
'\n 色域設定。sRGBだと狭くて少し変だったのでBT.2020に設定。\n 若干色が薄くなるのが難点。暇があれば改良したい。\n '
color_space = models.A... | 9,152,031,279,301,552,000 | xy色度図の馬蹄形の画像を生成する
Returns
-------
ndarray
rgb image. | ty_lib/test_pattern_generator2.py | get_chromaticity_image | colour-science/sample_code | python | def get_chromaticity_image(samples=1024, antialiasing=True, bg_color=0.9, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0):
'\n xy色度図の馬蹄形の画像を生成する\n\n Returns\n -------\n ndarray\n rgb image.\n '
'\n 色域設定。sRGBだと狭くて少し変だったのでBT.2020に設定。\n 若干色が薄くなるのが難点。暇があれば改良したい。\n '
color_space = models.A... |
def get_csf_color_image(width=640, height=480, lv1=np.uint16(((np.array([1.0, 1.0, 1.0]) * 1023) * 64)), lv2=np.uint16(((np.array([1.0, 1.0, 1.0]) * 512) * 64)), stripe_num=18):
'\n 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。\n 入力信号レベルは16bitに限定する。\n\n Parameters\n ----------\n width : numeric.\n width of... | -7,187,334,406,667,908,000 | 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。
入力信号レベルは16bitに限定する。
Parameters
----------
width : numeric.
width of the pattern image.
height : numeric.
height of the pattern image.
lv1 : numeric
video level 1. this value must be 10bit.
lv2 : numeric
video level 2. this value must be 10bit.
stripe_num : numeric
n... | ty_lib/test_pattern_generator2.py | get_csf_color_image | colour-science/sample_code | python | def get_csf_color_image(width=640, height=480, lv1=np.uint16(((np.array([1.0, 1.0, 1.0]) * 1023) * 64)), lv2=np.uint16(((np.array([1.0, 1.0, 1.0]) * 512) * 64)), stripe_num=18):
'\n 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。\n 入力信号レベルは16bitに限定する。\n\n Parameters\n ----------\n width : numeric.\n width of... |
def plot_xyY_color_space(name='ITU-R BT.2020', samples=1024, antialiasing=True):
'\n SONY の HDR説明資料にあるような xyY の図を作る。\n\n Parameters\n ----------\n name : str\n name of the target color space.\n\n Returns\n -------\n None\n\n '
(primary_xy, _) = get_primaries(name=name)
triangu... | 2,697,745,789,533,632,000 | SONY の HDR説明資料にあるような xyY の図を作る。
Parameters
----------
name : str
name of the target color space.
Returns
-------
None | ty_lib/test_pattern_generator2.py | plot_xyY_color_space | colour-science/sample_code | python | def plot_xyY_color_space(name='ITU-R BT.2020', samples=1024, antialiasing=True):
'\n SONY の HDR説明資料にあるような xyY の図を作る。\n\n Parameters\n ----------\n name : str\n name of the target color space.\n\n Returns\n -------\n None\n\n '
(primary_xy, _) = get_primaries(name=name)
triangu... |
def get_3d_grid_cube_format(grid_num=4):
'\n # 概要\n (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), ...\n みたいな配列を返す。\n CUBE形式の3DLUTを作成する時に便利。\n '
base = np.linspace(0, 1, grid_num)
ones_x = np.ones((grid_num, grid_num, 1))
ones_y = np.ones((grid_num, 1, grid_num))
ones_z = np.o... | 2,705,412,234,827,614,700 | # 概要
(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), ...
みたいな配列を返す。
CUBE形式の3DLUTを作成する時に便利。 | ty_lib/test_pattern_generator2.py | get_3d_grid_cube_format | colour-science/sample_code | python | def get_3d_grid_cube_format(grid_num=4):
'\n # 概要\n (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), ...\n みたいな配列を返す。\n CUBE形式の3DLUTを作成する時に便利。\n '
base = np.linspace(0, 1, grid_num)
ones_x = np.ones((grid_num, grid_num, 1))
ones_y = np.ones((grid_num, 1, grid_num))
ones_z = np.o... |
def gen_step_gradation(width=1024, height=128, step_num=17, bit_depth=10, color=(1.0, 1.0, 1.0), direction='h', debug=False):
"\n # 概要\n 階段状に変化するグラデーションパターンを作る。\n なお、引数の調整により正確に1階調ずつ変化するパターンも作成可能。\n\n # 注意事項\n 正確に1階調ずつ変化するグラデーションを作る場合は\n ```step_num = (2 ** bit_depth) + 1```\n となるようにパラメータを指定するこ... | -6,042,160,212,514,663,000 | # 概要
階段状に変化するグラデーションパターンを作る。
なお、引数の調整により正確に1階調ずつ変化するパターンも作成可能。
# 注意事項
正確に1階調ずつ変化するグラデーションを作る場合は
```step_num = (2 ** bit_depth) + 1```
となるようにパラメータを指定すること。具体例は以下のExample参照。
# Example
```
grad_8 = gen_step_gradation(width=grad_width, height=grad_height,
step_num=257, bit_depth=8,
... | ty_lib/test_pattern_generator2.py | gen_step_gradation | colour-science/sample_code | python | def gen_step_gradation(width=1024, height=128, step_num=17, bit_depth=10, color=(1.0, 1.0, 1.0), direction='h', debug=False):
"\n # 概要\n 階段状に変化するグラデーションパターンを作る。\n なお、引数の調整により正確に1階調ずつ変化するパターンも作成可能。\n\n # 注意事項\n 正確に1階調ずつ変化するグラデーションを作る場合は\n ```step_num = (2 ** bit_depth) + 1```\n となるようにパラメータを指定するこ... |
def merge(img_a, img_b, pos=(0, 0)):
'\n img_a に img_b をマージする。\n img_a にデータを上書きする。\n\n pos = (horizontal_st, vertical_st)\n '
b_width = img_b.shape[1]
b_height = img_b.shape[0]
img_a[pos[1]:(b_height + pos[1]), pos[0]:(b_width + pos[0])] = img_b | 2,923,293,055,995,527,000 | img_a に img_b をマージする。
img_a にデータを上書きする。
pos = (horizontal_st, vertical_st) | ty_lib/test_pattern_generator2.py | merge | colour-science/sample_code | python | def merge(img_a, img_b, pos=(0, 0)):
'\n img_a に img_b をマージする。\n img_a にデータを上書きする。\n\n pos = (horizontal_st, vertical_st)\n '
b_width = img_b.shape[1]
b_height = img_b.shape[0]
img_a[pos[1]:(b_height + pos[1]), pos[0]:(b_width + pos[0])] = img_b |
def merge_with_alpha(bg_img, fg_img, tf_str=tf.SRGB, pos=(0, 0)):
'\n 合成する。\n\n Parameters\n ----------\n bg_img : array_like(float, 3-channel)\n image data.\n fg_img : array_like(float, 4-channel)\n image data\n tf : strings\n transfer function\n pos : list(int)\n (... | -8,414,558,190,074,198,000 | 合成する。
Parameters
----------
bg_img : array_like(float, 3-channel)
image data.
fg_img : array_like(float, 4-channel)
image data
tf : strings
transfer function
pos : list(int)
(pos_h, pos_v) | ty_lib/test_pattern_generator2.py | merge_with_alpha | colour-science/sample_code | python | def merge_with_alpha(bg_img, fg_img, tf_str=tf.SRGB, pos=(0, 0)):
'\n 合成する。\n\n Parameters\n ----------\n bg_img : array_like(float, 3-channel)\n image data.\n fg_img : array_like(float, 4-channel)\n image data\n tf : strings\n transfer function\n pos : list(int)\n (... |
def dot_pattern(dot_size=4, repeat=4, color=np.array([1.0, 1.0, 1.0])):
'\n dot pattern 作る。\n\n Parameters\n ----------\n dot_size : integer\n dot size.\n repeat : integer\n The number of high-low pairs.\n color : array_like\n color value.\n\n Returns\n -------\n arra... | -1,414,203,125,807,372,500 | dot pattern 作る。
Parameters
----------
dot_size : integer
dot size.
repeat : integer
The number of high-low pairs.
color : array_like
color value.
Returns
-------
array_like
dot pattern image. | ty_lib/test_pattern_generator2.py | dot_pattern | colour-science/sample_code | python | def dot_pattern(dot_size=4, repeat=4, color=np.array([1.0, 1.0, 1.0])):
'\n dot pattern 作る。\n\n Parameters\n ----------\n dot_size : integer\n dot size.\n repeat : integer\n The number of high-low pairs.\n color : array_like\n color value.\n\n Returns\n -------\n arra... |
def complex_dot_pattern(kind_num=3, whole_repeat=2, fg_color=np.array([1.0, 1.0, 1.0]), bg_color=np.array([0.15, 0.15, 0.15])):
'\n dot pattern 作る。\n\n Parameters\n ----------\n kind_num : integer\n 作成するドットサイズの種類。\n 例えば、kind_num=3 ならば、1dot, 2dot, 4dot のパターンを作成。\n whole_repeat : integer\... | 7,652,356,003,343,272,000 | dot pattern 作る。
Parameters
----------
kind_num : integer
作成するドットサイズの種類。
例えば、kind_num=3 ならば、1dot, 2dot, 4dot のパターンを作成。
whole_repeat : integer
異なる複数種類のドットパターンの組数。
例えば、kind_num=3, whole_repeat=2 ならば、
1dot, 2dot, 4dot のパターンを水平・垂直に2組作る。
fg_color : array_like
foreground color value.
bg_color : array_... | ty_lib/test_pattern_generator2.py | complex_dot_pattern | colour-science/sample_code | python | def complex_dot_pattern(kind_num=3, whole_repeat=2, fg_color=np.array([1.0, 1.0, 1.0]), bg_color=np.array([0.15, 0.15, 0.15])):
'\n dot pattern 作る。\n\n Parameters\n ----------\n kind_num : integer\n 作成するドットサイズの種類。\n 例えば、kind_num=3 ならば、1dot, 2dot, 4dot のパターンを作成。\n whole_repeat : integer\... |
def make_csf_color_image(width=640, height=640, lv1=np.array([940, 940, 940], dtype=np.uint16), lv2=np.array([1023, 1023, 1023], dtype=np.uint16), stripe_num=6):
'\n 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。\n 入力信号レベルは10bitに限定する。\n\n Parameters\n ----------\n width : numeric.\n width of the pattern ima... | 6,239,938,353,410,582,000 | 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。
入力信号レベルは10bitに限定する。
Parameters
----------
width : numeric.
width of the pattern image.
height : numeric.
height of the pattern image.
lv1 : array_like
video level 1. this value must be 10bit.
lv2 : array_like
video level 2. this value must be 10bit.
stripe_num : numeric... | ty_lib/test_pattern_generator2.py | make_csf_color_image | colour-science/sample_code | python | def make_csf_color_image(width=640, height=640, lv1=np.array([940, 940, 940], dtype=np.uint16), lv2=np.array([1023, 1023, 1023], dtype=np.uint16), stripe_num=6):
'\n 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。\n 入力信号レベルは10bitに限定する。\n\n Parameters\n ----------\n width : numeric.\n width of the pattern ima... |
def make_tile_pattern(width=480, height=960, h_tile_num=4, v_tile_num=4, low_level=(940, 940, 940), high_level=(1023, 1023, 1023)):
'\n タイル状の縞々パターンを作る\n '
width_array = equal_devision(width, h_tile_num)
height_array = equal_devision(height, v_tile_num)
high_level = np.array(high_level, dtype=np.ui... | -1,309,246,484,004,092,000 | タイル状の縞々パターンを作る | ty_lib/test_pattern_generator2.py | make_tile_pattern | colour-science/sample_code | python | def make_tile_pattern(width=480, height=960, h_tile_num=4, v_tile_num=4, low_level=(940, 940, 940), high_level=(1023, 1023, 1023)):
'\n \n '
width_array = equal_devision(width, h_tile_num)
height_array = equal_devision(height, v_tile_num)
high_level = np.array(high_level, dtype=np.uint16)
low_... |
def make_ycbcr_checker(height=480, v_tile_num=4):
'\n YCbCr係数誤りを確認するテストパターンを作る。\n 正直かなり汚い組み方です。雑に作ったパターンを悪魔合体させています。\n\n Parameters\n ----------\n height : numeric.\n height of the pattern image.\n v_tile_num : numeric\n number of the tile in the vertical direction.\n\n Note\n ... | -2,052,380,776,987,882,000 | YCbCr係数誤りを確認するテストパターンを作る。
正直かなり汚い組み方です。雑に作ったパターンを悪魔合体させています。
Parameters
----------
height : numeric.
height of the pattern image.
v_tile_num : numeric
number of the tile in the vertical direction.
Note
----
横長のパターンになる。以下の式が成立する。
```
h_tile_num = v_tile_num * 2
width = height * 2
```
Returns
-------
array_li... | ty_lib/test_pattern_generator2.py | make_ycbcr_checker | colour-science/sample_code | python | def make_ycbcr_checker(height=480, v_tile_num=4):
'\n YCbCr係数誤りを確認するテストパターンを作る。\n 正直かなり汚い組み方です。雑に作ったパターンを悪魔合体させています。\n\n Parameters\n ----------\n height : numeric.\n height of the pattern image.\n v_tile_num : numeric\n number of the tile in the vertical direction.\n\n Note\n ... |
def plot_color_checker_image(rgb, rgb2=None, size=(1920, 1080), block_size=(1 / 4.5), padding=0.01):
"\n ColorCheckerをプロットする\n\n Parameters\n ----------\n rgb : array_like\n RGB value of the ColorChecker.\n RGB's shape must be (24, 3).\n rgb2 : array_like\n It's a optional parame... | 6,027,125,347,553,437,000 | ColorCheckerをプロットする
Parameters
----------
rgb : array_like
RGB value of the ColorChecker.
RGB's shape must be (24, 3).
rgb2 : array_like
It's a optional parameter.
If You want to draw two different ColorCheckers,
set the RGB value to this variable.
size : tuple
canvas size.
block_size : float
... | ty_lib/test_pattern_generator2.py | plot_color_checker_image | colour-science/sample_code | python | def plot_color_checker_image(rgb, rgb2=None, size=(1920, 1080), block_size=(1 / 4.5), padding=0.01):
"\n ColorCheckerをプロットする\n\n Parameters\n ----------\n rgb : array_like\n RGB value of the ColorChecker.\n RGB's shape must be (24, 3).\n rgb2 : array_like\n It's a optional parame... |
def get_log10_x_scale(sample_num=8, ref_val=1.0, min_exposure=(- 1), max_exposure=6):
'\n Log10スケールのx軸データを作る。\n\n Examples\n --------\n >>> get_log2_x_scale(\n ... sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6)\n array([ 1.0000e-01 1.0000e+00 1.0000e+01 1.0000e+02\n ... | -7,178,071,663,818,056,000 | Log10スケールのx軸データを作る。
Examples
--------
>>> get_log2_x_scale(
... sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6)
array([ 1.0000e-01 1.0000e+00 1.0000e+01 1.0000e+02
1.0000e+03 1.0000e+04 1.0000e+05 1.0000e+06]) | ty_lib/test_pattern_generator2.py | get_log10_x_scale | colour-science/sample_code | python | def get_log10_x_scale(sample_num=8, ref_val=1.0, min_exposure=(- 1), max_exposure=6):
'\n Log10スケールのx軸データを作る。\n\n Examples\n --------\n >>> get_log2_x_scale(\n ... sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6)\n array([ 1.0000e-01 1.0000e+00 1.0000e+01 1.0000e+02\n ... |
def get_log2_x_scale(sample_num=32, ref_val=1.0, min_exposure=(- 6.5), max_exposure=6.5):
'\n Log2スケールのx軸データを作る。\n\n Examples\n --------\n >>> get_log2_x_scale(sample_num=10, min_exposure=-4.0, max_exposure=4.0)\n array([[ 0.0625 0.11573434 0.214311 0.39685026 0.73486725\n ... | -5,210,454,686,189,132,000 | Log2スケールのx軸データを作る。
Examples
--------
>>> get_log2_x_scale(sample_num=10, min_exposure=-4.0, max_exposure=4.0)
array([[ 0.0625 0.11573434 0.214311 0.39685026 0.73486725
1.36079 2.5198421 4.66611616 8.64047791 16. ]]) | ty_lib/test_pattern_generator2.py | get_log2_x_scale | colour-science/sample_code | python | def get_log2_x_scale(sample_num=32, ref_val=1.0, min_exposure=(- 6.5), max_exposure=6.5):
'\n Log2スケールのx軸データを作る。\n\n Examples\n --------\n >>> get_log2_x_scale(sample_num=10, min_exposure=-4.0, max_exposure=4.0)\n array([[ 0.0625 0.11573434 0.214311 0.39685026 0.73486725\n ... |
def shaper_func_linear_to_log2(x, mid_gray=0.18, min_exposure=(- 6.5), max_exposure=6.5):
'\n ACESutil.Lin_to_Log2_param.ctl を参考に作成。\n https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Lin_to_Log2_param.ctl\n\n Parameters\n ----------\n x : array_like\n linear dat... | -4,971,467,536,164,493,000 | ACESutil.Lin_to_Log2_param.ctl を参考に作成。
https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Lin_to_Log2_param.ctl
Parameters
----------
x : array_like
linear data.
mid_gray : float
18% gray value on linear scale.
min_exposure : float
minimum value on log scale.
max_exposure : flo... | ty_lib/test_pattern_generator2.py | shaper_func_linear_to_log2 | colour-science/sample_code | python | def shaper_func_linear_to_log2(x, mid_gray=0.18, min_exposure=(- 6.5), max_exposure=6.5):
'\n ACESutil.Lin_to_Log2_param.ctl を参考に作成。\n https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Lin_to_Log2_param.ctl\n\n Parameters\n ----------\n x : array_like\n linear dat... |
def shaper_func_log2_to_linear(x, mid_gray=0.18, min_exposure=(- 6.5), max_exposure=6.5):
'\n ACESutil.Log2_to_Lin_param.ctl を参考に作成。\n https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Log2_to_Lin_param.ctl\n\n Log2空間の補足は shaper_func_linear_to_log2() の説明を参照\n\n Examples\n ... | 5,381,534,480,915,387,000 | ACESutil.Log2_to_Lin_param.ctl を参考に作成。
https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Log2_to_Lin_param.ctl
Log2空間の補足は shaper_func_linear_to_log2() の説明を参照
Examples
--------
>>> x = np.array([0.0, 1.0])
>>> shaper_func_log2_to_linear(
... x, mid_gray=0.18, min_exposure=-6.5, max_ex... | ty_lib/test_pattern_generator2.py | shaper_func_log2_to_linear | colour-science/sample_code | python | def shaper_func_log2_to_linear(x, mid_gray=0.18, min_exposure=(- 6.5), max_exposure=6.5):
'\n ACESutil.Log2_to_Lin_param.ctl を参考に作成。\n https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Log2_to_Lin_param.ctl\n\n Log2空間の補足は shaper_func_linear_to_log2() の説明を参照\n\n Examples\n ... |
def draw_straight_line(img, pt1, pt2, color, thickness):
'\n 直線を引く。OpenCV だと 8bit しか対応してないっぽいので自作。\n\n Parameters\n ----------\n img : array_like\n image data.\n pt1 : list(pos_h, pos_v)\n start point.\n pt2 : list(pos_h, pos_v)\n end point.\n color : array_like\n co... | -1,859,524,669,991,116,500 | 直線を引く。OpenCV だと 8bit しか対応してないっぽいので自作。
Parameters
----------
img : array_like
image data.
pt1 : list(pos_h, pos_v)
start point.
pt2 : list(pos_h, pos_v)
end point.
color : array_like
color
thickness : int
thickness.
Returns
-------
array_like
image data with line.
Notes
-----
thickness のパラメータは... | ty_lib/test_pattern_generator2.py | draw_straight_line | colour-science/sample_code | python | def draw_straight_line(img, pt1, pt2, color, thickness):
'\n 直線を引く。OpenCV だと 8bit しか対応してないっぽいので自作。\n\n Parameters\n ----------\n img : array_like\n image data.\n pt1 : list(pos_h, pos_v)\n start point.\n pt2 : list(pos_h, pos_v)\n end point.\n color : array_like\n co... |
def draw_outline(img, fg_color, outline_width):
'\n img に対して外枠線を引く\n\n Parameters\n ----------\n img : array_like\n image data.\n fg_color : array_like\n color\n outline_width : int\n thickness.\n\n Returns\n -------\n array_like\n image data with line.\n\n ... | 6,796,354,785,387,014,000 | img に対して外枠線を引く
Parameters
----------
img : array_like
image data.
fg_color : array_like
color
outline_width : int
thickness.
Returns
-------
array_like
image data with line.
Examples
--------
>>> img = np.zeros((1080, 1920, 3))
>>> color = (940, 940, 940)
>>> thickness = 2
>>> draw_outline(img, color... | ty_lib/test_pattern_generator2.py | draw_outline | colour-science/sample_code | python | def draw_outline(img, fg_color, outline_width):
'\n img に対して外枠線を引く\n\n Parameters\n ----------\n img : array_like\n image data.\n fg_color : array_like\n color\n outline_width : int\n thickness.\n\n Returns\n -------\n array_like\n image data with line.\n\n ... |
def convert_luminance_to_color_value(luminance, transfer_function):
'\n 輝度[cd/m2] から code value の RGB値に変換する。\n luminance の単位は [cd/m2]。無彩色である。\n\n Examples\n --------\n >>> convert_luminance_to_color_value(100, tf.GAMMA24)\n >>> [ 1.0 1.0 1.0 ]\n >>> convert_luminance_to_color_value(100, tf.ST... | -9,198,726,890,243,419,000 | 輝度[cd/m2] から code value の RGB値に変換する。
luminance の単位は [cd/m2]。無彩色である。
Examples
--------
>>> convert_luminance_to_color_value(100, tf.GAMMA24)
>>> [ 1.0 1.0 1.0 ]
>>> convert_luminance_to_color_value(100, tf.ST2084)
>>> [ 0.50807842 0.50807842 0.50807842 ] | ty_lib/test_pattern_generator2.py | convert_luminance_to_color_value | colour-science/sample_code | python | def convert_luminance_to_color_value(luminance, transfer_function):
'\n 輝度[cd/m2] から code value の RGB値に変換する。\n luminance の単位は [cd/m2]。無彩色である。\n\n Examples\n --------\n >>> convert_luminance_to_color_value(100, tf.GAMMA24)\n >>> [ 1.0 1.0 1.0 ]\n >>> convert_luminance_to_color_value(100, tf.ST... |
def convert_luminance_to_code_value(luminance, transfer_function):
'\n 輝度[cd/m2] から code value に変換する。\n luminance の単位は [cd/m2]\n '
return tf.oetf_from_luminance(luminance, transfer_function) | 5,017,816,043,957,604,000 | 輝度[cd/m2] から code value に変換する。
luminance の単位は [cd/m2] | ty_lib/test_pattern_generator2.py | convert_luminance_to_code_value | colour-science/sample_code | python | def convert_luminance_to_code_value(luminance, transfer_function):
'\n 輝度[cd/m2] から code value に変換する。\n luminance の単位は [cd/m2]\n '
return tf.oetf_from_luminance(luminance, transfer_function) |
def calc_rad_patch_idx2(outmost_num=5, current_num=3):
'\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png\n\n 得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で\n 得られる変換テーブルを使った変換が必要。\n 本関... | -7,178,791,033,226,871,000 | 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で
得られる変換テーブルを使った変換が必要。
本関数はまさにその変換を行う。 | ty_lib/test_pattern_generator2.py | calc_rad_patch_idx2 | colour-science/sample_code | python | def calc_rad_patch_idx2(outmost_num=5, current_num=3):
'\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png\n\n 得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で\n 得られる変換テーブルを使った変換が必要。\n 本関... |
def _calc_rgb_from_same_lstar_radial_data(lstar, temp_chroma, current_num, color_space):
'\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png\n\n 得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で... | 5,056,633,246,826,132,000 | 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で
得られる変換テーブルを使った変換が必要。 | ty_lib/test_pattern_generator2.py | _calc_rgb_from_same_lstar_radial_data | colour-science/sample_code | python | def _calc_rgb_from_same_lstar_radial_data(lstar, temp_chroma, current_num, color_space):
'\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png\n\n 得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で... |
def calc_same_lstar_radial_color_patch_data(lstar=58, chroma=32.5, outmost_num=9, color_space=BT709_COLOURSPACE, transfer_function=tf.GAMMA24):
'\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.p... | -4,732,374,722,857,101,000 | 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの
RGB値のリストを得る。
https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png
得られた RGB値のリストは最初のデータが画像左上の緑データ、
最後のデータが画像右下の紫データとなるよう既に**並べ替え**が行われている。
よってパッチをプロットする場合はRGB値リストの先頭から順にデータを取り出し、
右下に向かって並べていけば良い。 | ty_lib/test_pattern_generator2.py | calc_same_lstar_radial_color_patch_data | colour-science/sample_code | python | def calc_same_lstar_radial_color_patch_data(lstar=58, chroma=32.5, outmost_num=9, color_space=BT709_COLOURSPACE, transfer_function=tf.GAMMA24):
'\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.p... |
def get_accelerated_x_1x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n\n Examples\n --------\n >>> x0 = np.linspace(0, 1, 8)\n ... | -6,556,408,200,352,419,000 | 単調増加ではなく、加速度が 0→1→0 となるような x を作る
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
Examples
--------
>>> x0 = np.linspace(0, 1, 8)
>>> x1 = get_accelerated_x_1x(8)
>>> print(x0)
>>> [ 0. 0.142 0.285 0.428 0.571 0.714 0.857 1. ]
>>> print... | ty_lib/test_pattern_generator2.py | get_accelerated_x_1x | colour-science/sample_code | python | def get_accelerated_x_1x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n\n Examples\n --------\n >>> x0 = np.linspace(0, 1, 8)\n ... |
def get_accelerated_x_2x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の2倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n\n Examples\n -------... | 8,900,704,438,845,922,000 | 単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の2倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list
Examples
--------
>>> x0 = np.linspace(0, 1, 8)
>>> x2 = get_accelerated_x_2x(8)
>>> print(x0)
>>> [ 0. 0.142 0.285 0.428 ... | ty_lib/test_pattern_generator2.py | get_accelerated_x_2x | colour-science/sample_code | python | def get_accelerated_x_2x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の2倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n\n Examples\n -------... |
def get_accelerated_x_4x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の4倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n '
rad = np.linspace... | 1,836,093,452,671,727,900 | 単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の4倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list | ty_lib/test_pattern_generator2.py | get_accelerated_x_4x | colour-science/sample_code | python | def get_accelerated_x_4x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の4倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n '
rad = np.linspace... |
def get_accelerated_x_8x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の4倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n '
rad = np.linspace... | 4,805,954,959,950,164,000 | 単調増加ではなく、加速度が 0→1→0 となるような x を作る。
加速度が `get_accelerated_x_1x` の4倍!!
Parameters
----------
sample_num : int
the number of the sample.
Returns
-------
array_like
accelerated value list | ty_lib/test_pattern_generator2.py | get_accelerated_x_8x | colour-science/sample_code | python | def get_accelerated_x_8x(sample_num=64):
'\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の4倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n '
rad = np.linspace... |
def generate_color_checker_rgb_value(color_space=BT709_COLOURSPACE, target_white=D65_WHITE):
'\n Generate the 24 RGB values of the color checker.\n\n Parameters\n ----------\n color_space : color space\n color space object in `colour` module.\n\n target_white : array_like\n the xy value... | 6,887,916,821,628,261,000 | Generate the 24 RGB values of the color checker.
Parameters
----------
color_space : color space
color space object in `colour` module.
target_white : array_like
the xy values of the white point of target color space.
Returns
-------
array_like
24 RGB values. This is linear. OETF is not applied.
Example... | ty_lib/test_pattern_generator2.py | generate_color_checker_rgb_value | colour-science/sample_code | python | def generate_color_checker_rgb_value(color_space=BT709_COLOURSPACE, target_white=D65_WHITE):
'\n Generate the 24 RGB values of the color checker.\n\n Parameters\n ----------\n color_space : color space\n color space object in `colour` module.\n\n target_white : array_like\n the xy value... |
def make_color_checker_image(rgb, width=1920, padding_rate=0.01):
'\n 6x4 の カラーチェッカーの画像を作る。\n Height は Width から自動計算される。padding_rate で少し値が変わる。\n '
h_patch_num = 6
v_patch_num = 4
each_padding = int(((width * padding_rate) + 0.5))
h_padding_total = (each_padding * (h_patch_num + 1))
h_pat... | 2,040,358,170,524,852,500 | 6x4 の カラーチェッカーの画像を作る。
Height は Width から自動計算される。padding_rate で少し値が変わる。 | ty_lib/test_pattern_generator2.py | make_color_checker_image | colour-science/sample_code | python | def make_color_checker_image(rgb, width=1920, padding_rate=0.01):
'\n 6x4 の カラーチェッカーの画像を作る。\n Height は Width から自動計算される。padding_rate で少し値が変わる。\n '
h_patch_num = 6
v_patch_num = 4
each_padding = int(((width * padding_rate) + 0.5))
h_padding_total = (each_padding * (h_patch_num + 1))
h_pat... |
def calc_st_pos_for_centering(bg_size, fg_size):
'\n Calculate start postion for centering.\n\n Parameters\n ----------\n bg_size : touple(int)\n (width, height) of the background image.\n\n fg_size : touple(int)\n (width, height) of the foreground image.\n\n Returns\n -------\n ... | -4,828,180,079,277,697,000 | Calculate start postion for centering.
Parameters
----------
bg_size : touple(int)
(width, height) of the background image.
fg_size : touple(int)
(width, height) of the foreground image.
Returns
-------
touple (int)
(st_pos_h, st_pos_v)
Examples
--------
>>> calc_st_pos_for_centering(bg_size=(1920, 1080... | ty_lib/test_pattern_generator2.py | calc_st_pos_for_centering | colour-science/sample_code | python | def calc_st_pos_for_centering(bg_size, fg_size):
'\n Calculate start postion for centering.\n\n Parameters\n ----------\n bg_size : touple(int)\n (width, height) of the background image.\n\n fg_size : touple(int)\n (width, height) of the foreground image.\n\n Returns\n -------\n ... |
def get_size_from_image(img):
'\n `calc_st_pos_for_centering()` の引数計算が面倒だったので関数化。\n '
return (img.shape[1], img.shape[0]) | 2,285,655,585,279,918,300 | `calc_st_pos_for_centering()` の引数計算が面倒だったので関数化。 | ty_lib/test_pattern_generator2.py | get_size_from_image | colour-science/sample_code | python | def get_size_from_image(img):
'\n \n '
return (img.shape[1], img.shape[0]) |
def _Args(parser, deprecate_maintenance_policy=False, container_mount_enabled=False):
'Add flags shared by all release tracks.'
parser.display_info.AddFormat(instances_flags.DEFAULT_LIST_FORMAT)
metadata_utils.AddMetadataArgs(parser)
instances_flags.AddDiskArgs(parser, True, container_mount_enabled=cont... | -7,180,734,195,565,543,000 | Add flags shared by all release tracks. | lib/surface/compute/instances/create_with_container.py | _Args | bshaffer/google-cloud-sdk | python | def _Args(parser, deprecate_maintenance_policy=False, container_mount_enabled=False):
parser.display_info.AddFormat(instances_flags.DEFAULT_LIST_FORMAT)
metadata_utils.AddMetadataArgs(parser)
instances_flags.AddDiskArgs(parser, True, container_mount_enabled=container_mount_enabled)
instances_flags.... |
@staticmethod
def Args(parser):
'Register parser args.'
_Args(parser)
instances_flags.AddNetworkTierArgs(parser, instance=True)
instances_flags.AddMinCpuPlatformArgs(parser, base.ReleaseTrack.GA) | 469,272,078,714,869,000 | Register parser args. | lib/surface/compute/instances/create_with_container.py | Args | bshaffer/google-cloud-sdk | python | @staticmethod
def Args(parser):
_Args(parser)
instances_flags.AddNetworkTierArgs(parser, instance=True)
instances_flags.AddMinCpuPlatformArgs(parser, base.ReleaseTrack.GA) |
@staticmethod
def Args(parser):
'Register parser args.'
_Args(parser, container_mount_enabled=True)
instances_flags.AddNetworkTierArgs(parser, instance=True)
instances_flags.AddContainerMountDiskFlag(parser)
instances_flags.AddLocalSsdArgsWithSize(parser)
instances_flags.AddMinCpuPlatformArgs(pa... | -3,262,381,641,413,971,000 | Register parser args. | lib/surface/compute/instances/create_with_container.py | Args | bshaffer/google-cloud-sdk | python | @staticmethod
def Args(parser):
_Args(parser, container_mount_enabled=True)
instances_flags.AddNetworkTierArgs(parser, instance=True)
instances_flags.AddContainerMountDiskFlag(parser)
instances_flags.AddLocalSsdArgsWithSize(parser)
instances_flags.AddMinCpuPlatformArgs(parser, base.ReleaseTrack... |
def deprecated_arg_names(arg_mapping: Mapping[(str, str)]):
'\n Decorator which marks a functions keyword arguments as deprecated. It will\n result in a warning being emitted when the deprecated keyword argument is\n used, and the function being called with the new argument.\n\n Parameters\n --------... | 7,597,204,064,448,840,000 | Decorator which marks a functions keyword arguments as deprecated. It will
result in a warning being emitted when the deprecated keyword argument is
used, and the function being called with the new argument.
Parameters
----------
arg_mapping
Mapping from deprecated argument name to current argument name. | scanpy/_utils.py | deprecated_arg_names | VolkerBergen/scanpy | python | def deprecated_arg_names(arg_mapping: Mapping[(str, str)]):
'\n Decorator which marks a functions keyword arguments as deprecated. It will\n result in a warning being emitted when the deprecated keyword argument is\n used, and the function being called with the new argument.\n\n Parameters\n --------... |
def _doc_params(**kwds):
' Docstrings should start with "" in the first line for proper formatting.\n '
def dec(obj):
obj.__orig_doc__ = obj.__doc__
obj.__doc__ = dedent(obj.__doc__).format_map(kwds)
return obj
return dec | 4,215,397,845,106,700,000 | Docstrings should start with "" in the first line for proper formatting. | scanpy/_utils.py | _doc_params | VolkerBergen/scanpy | python | def _doc_params(**kwds):
' \n '
def dec(obj):
obj.__orig_doc__ = obj.__doc__
obj.__doc__ = dedent(obj.__doc__).format_map(kwds)
return obj
return dec |
def _check_array_function_arguments(**kwargs):
'Checks for invalid arguments when an array is passed.\n\n Helper for functions that work on either AnnData objects or array-likes.\n '
invalid_args = [k for (k, v) in kwargs.items() if (v is not None)]
if (len(invalid_args) > 0):
raise TypeError(... | 5,586,756,840,675,026,000 | Checks for invalid arguments when an array is passed.
Helper for functions that work on either AnnData objects or array-likes. | scanpy/_utils.py | _check_array_function_arguments | VolkerBergen/scanpy | python | def _check_array_function_arguments(**kwargs):
'Checks for invalid arguments when an array is passed.\n\n Helper for functions that work on either AnnData objects or array-likes.\n '
invalid_args = [k for (k, v) in kwargs.items() if (v is not None)]
if (len(invalid_args) > 0):
raise TypeError(... |
def _check_use_raw(adata: AnnData, use_raw: Union[(None, bool)]) -> bool:
'\n Normalize checking `use_raw`.\n\n My intentention here is to also provide a single place to throw a deprecation warning from in future.\n '
if (use_raw is not None):
return use_raw
elif (adata.raw is not None):
... | -2,252,908,537,909,248,500 | Normalize checking `use_raw`.
My intentention here is to also provide a single place to throw a deprecation warning from in future. | scanpy/_utils.py | _check_use_raw | VolkerBergen/scanpy | python | def _check_use_raw(adata: AnnData, use_raw: Union[(None, bool)]) -> bool:
'\n Normalize checking `use_raw`.\n\n My intentention here is to also provide a single place to throw a deprecation warning from in future.\n '
if (use_raw is not None):
return use_raw
elif (adata.raw is not None):
... |
def get_igraph_from_adjacency(adjacency, directed=None):
'Get igraph graph from adjacency matrix.'
import igraph as ig
(sources, targets) = adjacency.nonzero()
weights = adjacency[(sources, targets)]
if isinstance(weights, np.matrix):
weights = weights.A1
g = ig.Graph(directed=directed)
... | -752,489,011,673,892,500 | Get igraph graph from adjacency matrix. | scanpy/_utils.py | get_igraph_from_adjacency | VolkerBergen/scanpy | python | def get_igraph_from_adjacency(adjacency, directed=None):
import igraph as ig
(sources, targets) = adjacency.nonzero()
weights = adjacency[(sources, targets)]
if isinstance(weights, np.matrix):
weights = weights.A1
g = ig.Graph(directed=directed)
g.add_vertices(adjacency.shape[0])
... |
def compute_association_matrix_of_groups(adata: AnnData, prediction: str, reference: str, normalization: Literal[('prediction', 'reference')]='prediction', threshold: float=0.01, max_n_names: Optional[int]=2):
'Compute overlaps between groups.\n\n See ``identify_groups`` for identifying the groups.\n\n Parame... | -2,052,598,117,330,322,400 | Compute overlaps between groups.
See ``identify_groups`` for identifying the groups.
Parameters
----------
adata
prediction
Field name of adata.obs.
reference
Field name of adata.obs.
normalization
Whether to normalize with respect to the predicted groups or the
reference groups.
threshold
Do not ... | scanpy/_utils.py | compute_association_matrix_of_groups | VolkerBergen/scanpy | python | def compute_association_matrix_of_groups(adata: AnnData, prediction: str, reference: str, normalization: Literal[('prediction', 'reference')]='prediction', threshold: float=0.01, max_n_names: Optional[int]=2):
'Compute overlaps between groups.\n\n See ``identify_groups`` for identifying the groups.\n\n Parame... |
def identify_groups(ref_labels, pred_labels, return_overlaps=False):
'Which predicted label explains which reference label?\n\n A predicted label explains the reference label which maximizes the minimum\n of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.\n\n Compare this with ``compute_associati... | 8,182,894,112,265,649,000 | Which predicted label explains which reference label?
A predicted label explains the reference label which maximizes the minimum
of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.
Compare this with ``compute_association_matrix_of_groups``.
Returns
-------
A dictionary of length ``len(np.unique(ref_labels))... | scanpy/_utils.py | identify_groups | VolkerBergen/scanpy | python | def identify_groups(ref_labels, pred_labels, return_overlaps=False):
'Which predicted label explains which reference label?\n\n A predicted label explains the reference label which maximizes the minimum\n of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.\n\n Compare this with ``compute_associati... |
def sanitize_anndata(adata):
'Transform string annotations to categoricals.'
adata._sanitize() | 4,622,148,062,683,588,000 | Transform string annotations to categoricals. | scanpy/_utils.py | sanitize_anndata | VolkerBergen/scanpy | python | def sanitize_anndata(adata):
adata._sanitize() |
def moving_average(a: np.ndarray, n: int):
'Moving average over one-dimensional array.\n\n Parameters\n ----------\n a\n One-dimensional array.\n n\n Number of entries to average over. n=2 means averaging over the currrent\n the previous entry.\n\n Returns\n -------\n An ar... | -7,559,639,221,853,936,000 | Moving average over one-dimensional array.
Parameters
----------
a
One-dimensional array.
n
Number of entries to average over. n=2 means averaging over the currrent
the previous entry.
Returns
-------
An array view storing the moving average. | scanpy/_utils.py | moving_average | VolkerBergen/scanpy | python | def moving_average(a: np.ndarray, n: int):
'Moving average over one-dimensional array.\n\n Parameters\n ----------\n a\n One-dimensional array.\n n\n Number of entries to average over. n=2 means averaging over the currrent\n the previous entry.\n\n Returns\n -------\n An ar... |
def update_params(old_params: Mapping[(str, Any)], new_params: Mapping[(str, Any)], check=False) -> Dict[(str, Any)]:
' Update old_params with new_params.\n\n If check==False, this merely adds and overwrites the content of old_params.\n\n If check==True, this only allows updating of parameters that are alr... | -392,503,575,934,761,200 | Update old_params with new_params.
If check==False, this merely adds and overwrites the content of old_params.
If check==True, this only allows updating of parameters that are already
present in old_params.
Parameters
----------
old_params
new_params
check
Returns
-------
updated_params | scanpy/_utils.py | update_params | VolkerBergen/scanpy | python | def update_params(old_params: Mapping[(str, Any)], new_params: Mapping[(str, Any)], check=False) -> Dict[(str, Any)]:
' Update old_params with new_params.\n\n If check==False, this merely adds and overwrites the content of old_params.\n\n If check==True, this only allows updating of parameters that are alr... |
def check_nonnegative_integers(X: Union[(np.ndarray, sparse.spmatrix)]):
'Checks values of X to ensure it is count data'
from numbers import Integral
data = (X if isinstance(X, np.ndarray) else X.data)
if np.signbit(data).any():
return False
elif issubclass(data.dtype.type, Integral):
... | 2,527,016,762,427,564,000 | Checks values of X to ensure it is count data | scanpy/_utils.py | check_nonnegative_integers | VolkerBergen/scanpy | python | def check_nonnegative_integers(X: Union[(np.ndarray, sparse.spmatrix)]):
from numbers import Integral
data = (X if isinstance(X, np.ndarray) else X.data)
if np.signbit(data).any():
return False
elif issubclass(data.dtype.type, Integral):
return True
elif np.any((~ np.equal(np.mo... |
def select_groups(adata, groups_order_subset='all', key='groups'):
'Get subset of groups in adata.obs[key].'
groups_order = adata.obs[key].cat.categories
if ((key + '_masks') in adata.uns):
groups_masks = adata.uns[(key + '_masks')]
else:
groups_masks = np.zeros((len(adata.obs[key].cat.c... | -3,030,545,903,539,323,000 | Get subset of groups in adata.obs[key]. | scanpy/_utils.py | select_groups | VolkerBergen/scanpy | python | def select_groups(adata, groups_order_subset='all', key='groups'):
groups_order = adata.obs[key].cat.categories
if ((key + '_masks') in adata.uns):
groups_masks = adata.uns[(key + '_masks')]
else:
groups_masks = np.zeros((len(adata.obs[key].cat.categories), adata.obs[key].values.size), ... |
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
'Get full tracebacks when warning is raised by setting\n\n warnings.showwarning = warn_with_traceback\n\n See also\n --------\n http://stackoverflow.com/questions/22373927/get-traceback-of-warnings\n '
import trac... | 3,395,872,396,392,298,500 | Get full tracebacks when warning is raised by setting
warnings.showwarning = warn_with_traceback
See also
--------
http://stackoverflow.com/questions/22373927/get-traceback-of-warnings | scanpy/_utils.py | warn_with_traceback | VolkerBergen/scanpy | python | def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
'Get full tracebacks when warning is raised by setting\n\n warnings.showwarning = warn_with_traceback\n\n See also\n --------\n http://stackoverflow.com/questions/22373927/get-traceback-of-warnings\n '
import trac... |
def subsample(X: np.ndarray, subsample: int=1, seed: int=0) -> Tuple[(np.ndarray, np.ndarray)]:
' Subsample a fraction of 1/subsample samples from the rows of X.\n\n Parameters\n ----------\n X\n Data array.\n subsample\n 1/subsample is the fraction of data sampled, n = X.shape[0]/subsa... | 7,856,776,734,611,695,000 | Subsample a fraction of 1/subsample samples from the rows of X.
Parameters
----------
X
Data array.
subsample
1/subsample is the fraction of data sampled, n = X.shape[0]/subsample.
seed
Seed for sampling.
Returns
-------
Xsampled
Subsampled X.
rows
Indices of rows that are stored in Xsampled. | scanpy/_utils.py | subsample | VolkerBergen/scanpy | python | def subsample(X: np.ndarray, subsample: int=1, seed: int=0) -> Tuple[(np.ndarray, np.ndarray)]:
' Subsample a fraction of 1/subsample samples from the rows of X.\n\n Parameters\n ----------\n X\n Data array.\n subsample\n 1/subsample is the fraction of data sampled, n = X.shape[0]/subsa... |
def subsample_n(X: np.ndarray, n: int=0, seed: int=0) -> Tuple[(np.ndarray, np.ndarray)]:
'Subsample n samples from rows of array.\n\n Parameters\n ----------\n X\n Data array.\n n\n Sample size.\n seed\n Seed for sampling.\n\n Returns\n -------\n Xsampled\n Subsa... | -170,607,391,929,341,630 | Subsample n samples from rows of array.
Parameters
----------
X
Data array.
n
Sample size.
seed
Seed for sampling.
Returns
-------
Xsampled
Subsampled X.
rows
Indices of rows that are stored in Xsampled. | scanpy/_utils.py | subsample_n | VolkerBergen/scanpy | python | def subsample_n(X: np.ndarray, n: int=0, seed: int=0) -> Tuple[(np.ndarray, np.ndarray)]:
'Subsample n samples from rows of array.\n\n Parameters\n ----------\n X\n Data array.\n n\n Sample size.\n seed\n Seed for sampling.\n\n Returns\n -------\n Xsampled\n Subsa... |
def check_presence_download(filename: Path, backup_url):
'Check if file is present otherwise download.'
if (not filename.is_file()):
from .readwrite import _download
_download(backup_url, filename) | 5,616,465,864,957,180,000 | Check if file is present otherwise download. | scanpy/_utils.py | check_presence_download | VolkerBergen/scanpy | python | def check_presence_download(filename: Path, backup_url):
if (not filename.is_file()):
from .readwrite import _download
_download(backup_url, filename) |
def lazy_import(full_name):
'Imports a module in a way that it’s only executed on member access'
try:
return sys.modules[full_name]
except KeyError:
spec = importlib.util.find_spec(full_name)
module = importlib.util.module_from_spec(spec)
loader = importlib.util.LazyLoader(sp... | 5,384,361,978,549,375,000 | Imports a module in a way that it’s only executed on member access | scanpy/_utils.py | lazy_import | VolkerBergen/scanpy | python | def lazy_import(full_name):
try:
return sys.modules[full_name]
except KeyError:
spec = importlib.util.find_spec(full_name)
module = importlib.util.module_from_spec(spec)
loader = importlib.util.LazyLoader(spec.loader)
loader.exec_module(module)
return module |
def _choose_graph(adata, obsp, neighbors_key):
'Choose connectivities from neighbbors or another obsp column'
if ((obsp is not None) and (neighbors_key is not None)):
raise ValueError("You can't specify both obsp, neighbors_key. Please select only one.")
if (obsp is not None):
return adata.o... | -3,498,210,811,662,967,300 | Choose connectivities from neighbbors or another obsp column | scanpy/_utils.py | _choose_graph | VolkerBergen/scanpy | python | def _choose_graph(adata, obsp, neighbors_key):
if ((obsp is not None) and (neighbors_key is not None)):
raise ValueError("You can't specify both obsp, neighbors_key. Please select only one.")
if (obsp is not None):
return adata.obsp[obsp]
else:
neighbors = NeighborsView(adata, n... |
def user_display_name(user):
'\n Returns the preferred display name for the given user object: the result of\n user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.\n '
try:
full_name = user.get_full_name().strip()
if full_name:
return full_nam... | 1,981,022,365,203,509,000 | Returns the preferred display name for the given user object: the result of
user.get_full_name() if implemented and non-empty, or user.get_username() otherwise. | wagtail_review/text.py | user_display_name | icanbwell/wagtail-review | python | def user_display_name(user):
'\n Returns the preferred display name for the given user object: the result of\n user.get_full_name() if implemented and non-empty, or user.get_username() otherwise.\n '
try:
full_name = user.get_full_name().strip()
if full_name:
return full_nam... |
def testDataProtectionOfficer(self):
'Test DataProtectionOfficer'
pass | -2,687,668,233,648,560,600 | Test DataProtectionOfficer | test/test_data_protection_officer.py | testDataProtectionOfficer | My-Data-My-Consent/python-sdk | python | def testDataProtectionOfficer(self):
pass |
def select_server(server_type, config):
'Select a server type using different possible strings.\n\n Right now this just returns `OptimizationServer`, but this\n function could be useful when there are multiple choices of\n server.\n\n Args:\n server_type (str): indicates server choice.\n c... | 2,689,991,968,026,703,000 | Select a server type using different possible strings.
Right now this just returns `OptimizationServer`, but this
function could be useful when there are multiple choices of
server.
Args:
server_type (str): indicates server choice.
config (dict): config parsed from YAML, passed so that
parameters can ... | core/server.py | select_server | simra/msrflute | python | def select_server(server_type, config):
'Select a server type using different possible strings.\n\n Right now this just returns `OptimizationServer`, but this\n function could be useful when there are multiple choices of\n server.\n\n Args:\n server_type (str): indicates server choice.\n c... |
def __init__(self, num_clients, model, optimizer, ss_scheduler, data_path, model_path, train_dataloader, val_dataloader, test_dataloader, config, config_server):
"Implement Server's orchestration and aggregation.\n\n This is the main Server class, that actually implements orchestration\n and aggregati... | -5,509,703,606,496,693,000 | Implement Server's orchestration and aggregation.
This is the main Server class, that actually implements orchestration
and aggregation, inheriting from `federated.Server`, which deals with
communication only.
The `train` method is central in FLUTE, as it defines good part of what
happens during training.
Args:
... | core/server.py | __init__ | simra/msrflute | python | def __init__(self, num_clients, model, optimizer, ss_scheduler, data_path, model_path, train_dataloader, val_dataloader, test_dataloader, config, config_server):
"Implement Server's orchestration and aggregation.\n\n This is the main Server class, that actually implements orchestration\n and aggregati... |
def load_saved_status(self):
'Load checkpoint from disk'
if os.path.exists(self.last_model_path):
print_rank('Resuming from checkpoint model {}'.format(self.last_model_path))
self.worker_trainer.load(self.last_model_path, update_lr_scheduler=True, update_ss_scheduler=True)
if (self.serve... | -5,987,352,651,717,467,000 | Load checkpoint from disk | core/server.py | load_saved_status | simra/msrflute | python | def load_saved_status(self):
if os.path.exists(self.last_model_path):
print_rank('Resuming from checkpoint model {}'.format(self.last_model_path))
self.worker_trainer.load(self.last_model_path, update_lr_scheduler=True, update_ss_scheduler=True)
if (self.server_trainer is not None):
... |
def run(self):
'Trigger training.\n\n This is a simple wrapper to the `train` method.\n '
print_rank('server started')
self.train()
print_rank('server terminated') | 5,204,790,440,284,381,000 | Trigger training.
This is a simple wrapper to the `train` method. | core/server.py | run | simra/msrflute | python | def run(self):
'Trigger training.\n\n This is a simple wrapper to the `train` method.\n '
print_rank('server started')
self.train()
print_rank('server terminated') |
def train(self):
'Main method for training.'
self.run_stats = {'secsPerClientRound': [], 'secsPerClient': [], 'secsPerClientTraining': [], 'secsPerClientSetup': [], 'secsPerClientFull': [], 'secsPerRoundHousekeeping': [], 'secsPerRoundTotal': [], 'mpiCosts': []}
run.log('Max iterations', self.max_iteration)... | 1,279,950,367,566,187,500 | Main method for training. | core/server.py | train | simra/msrflute | python | def train(self):
self.run_stats = {'secsPerClientRound': [], 'secsPerClient': [], 'secsPerClientTraining': [], 'secsPerClientSetup': [], 'secsPerClientFull': [], 'secsPerRoundHousekeeping': [], 'secsPerRoundTotal': [], 'mpiCosts': []}
run.log('Max iterations', self.max_iteration)
try:
(self.wor... |
def backup_models(self, i):
'Save the current best models.\n\n Save CER model, the best loss model and the best WER model. This occurs\n at a specified period.\n\n Args:\n i: no. of iterations.\n '
self.worker_trainer.save(model_path=self.model_path, token='latest', config... | 363,412,540,844,676,350 | Save the current best models.
Save CER model, the best loss model and the best WER model. This occurs
at a specified period.
Args:
i: no. of iterations. | core/server.py | backup_models | simra/msrflute | python | def backup_models(self, i):
'Save the current best models.\n\n Save CER model, the best loss model and the best WER model. This occurs\n at a specified period.\n\n Args:\n i: no. of iterations.\n '
self.worker_trainer.save(model_path=self.model_path, token='latest', config... |
def fall_back_to_prev_best_status(self):
'Go back to the past best status and switch to the recent best model.'
if self.fall_back_to_best_model:
print_rank('falling back to model {}'.format(self.best_model_path))
tmp_lr = get_lr(self.worker_trainer.optimizer)
self.worker_trainer.load(sel... | -3,130,464,585,995,101,700 | Go back to the past best status and switch to the recent best model. | core/server.py | fall_back_to_prev_best_status | simra/msrflute | python | def fall_back_to_prev_best_status(self):
if self.fall_back_to_best_model:
print_rank('falling back to model {}'.format(self.best_model_path))
tmp_lr = get_lr(self.worker_trainer.optimizer)
self.worker_trainer.load(self.best_model_path, update_lr_scheduler=False, update_ss_scheduler=Fals... |
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
'\n Get HTTP signature authentication for a request.\n '
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(headers=['(request-target)', 'user-agent', 'host', 'date'], algorithm='rsa-sha256', ke... | 6,171,740,104,618,513,000 | Get HTTP signature authentication for a request. | federation/protocols/activitypub/signing.py | get_http_authentication | jaywink/federation | python | def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth:
'\n \n '
key = private_key.exportKey()
return HTTPSignatureHeaderAuth(headers=['(request-target)', 'user-agent', 'host', 'date'], algorithm='rsa-sha256', key=key, key_id=private_key_id) |
def verify_request_signature(request: RequestType, public_key: Union[(str, bytes)]):
'\n Verify HTTP signature in request against a public key.\n '
key = encode_if_text(public_key)
date_header = request.headers.get('Date')
if (not date_header):
raise ValueError('Rquest Date header is missi... | 3,867,310,073,539,097,000 | Verify HTTP signature in request against a public key. | federation/protocols/activitypub/signing.py | verify_request_signature | jaywink/federation | python | def verify_request_signature(request: RequestType, public_key: Union[(str, bytes)]):
'\n \n '
key = encode_if_text(public_key)
date_header = request.headers.get('Date')
if (not date_header):
raise ValueError('Rquest Date header is missing')
ts = parse_http_date(date_header)
dt = da... |
def __init__(self, selection):
'\n Create a new :py:class:`Selection` from the given ``selection`` string.\n '
ptr = self.ffi.chfl_selection(selection.encode('utf8'))
super(Selection, self).__init__(ptr, is_const=False) | 8,582,937,328,836,864,000 | Create a new :py:class:`Selection` from the given ``selection`` string. | chemfiles/selection.py | __init__ | Luthaf/Chemharp-python | python | def __init__(self, selection):
'\n \n '
ptr = self.ffi.chfl_selection(selection.encode('utf8'))
super(Selection, self).__init__(ptr, is_const=False) |
@property
def size(self):
"\n Get the size of this :py:class:`Selection`.\n\n The size of a selection is the number of atoms we are selecting\n together. This value is 1 for the 'atom' context, 2 for the 'pair' and\n 'bond' context, 3 for the 'three' and 'angles' contextes and 4 for the\... | -4,548,979,829,295,121,000 | Get the size of this :py:class:`Selection`.
The size of a selection is the number of atoms we are selecting
together. This value is 1 for the 'atom' context, 2 for the 'pair' and
'bond' context, 3 for the 'three' and 'angles' contextes and 4 for the
'four' and 'dihedral' contextes. | chemfiles/selection.py | size | Luthaf/Chemharp-python | python | @property
def size(self):
"\n Get the size of this :py:class:`Selection`.\n\n The size of a selection is the number of atoms we are selecting\n together. This value is 1 for the 'atom' context, 2 for the 'pair' and\n 'bond' context, 3 for the 'three' and 'angles' contextes and 4 for the\... |
@property
def string(self):
'\n Get the selection string used to create this :py:class:`Selection`.\n '
return _call_with_growing_buffer((lambda buffer, size: self.ffi.chfl_selection_string(self.ptr, buffer, size)), initial=128) | -8,501,303,544,896,859,000 | Get the selection string used to create this :py:class:`Selection`. | chemfiles/selection.py | string | Luthaf/Chemharp-python | python | @property
def string(self):
'\n \n '
return _call_with_growing_buffer((lambda buffer, size: self.ffi.chfl_selection_string(self.ptr, buffer, size)), initial=128) |
def evaluate(self, frame):
'\n Evaluate a :py:class:`Selection` for a given :py:class:`Frame`, and\n return a list of matching atoms, either as a list of index or a list\n of tuples of indexes.\n '
matching = c_uint64()
self.ffi.chfl_selection_evaluate(self.mut_ptr, frame.ptr, ma... | 2,673,721,999,087,359,000 | Evaluate a :py:class:`Selection` for a given :py:class:`Frame`, and
return a list of matching atoms, either as a list of index or a list
of tuples of indexes. | chemfiles/selection.py | evaluate | Luthaf/Chemharp-python | python | def evaluate(self, frame):
'\n Evaluate a :py:class:`Selection` for a given :py:class:`Frame`, and\n return a list of matching atoms, either as a list of index or a list\n of tuples of indexes.\n '
matching = c_uint64()
self.ffi.chfl_selection_evaluate(self.mut_ptr, frame.ptr, ma... |
def _find_neighbor_and_lambda(neighbor_indices, neighbor_distances, core_distances, min_samples):
'\n Find the nearest mutual reachability neighbor of a point, and compute\n the associated lambda value for the point, given the mutual reachability\n distance to a nearest neighbor.\n\n Parameters\n --... | -6,260,141,226,484,943,000 | Find the nearest mutual reachability neighbor of a point, and compute
the associated lambda value for the point, given the mutual reachability
distance to a nearest neighbor.
Parameters
----------
neighbor_indices : array (2 * min_samples, )
An array of raw distance based nearest neighbor indices.
neighbor_dista... | hdbscan/prediction.py | _find_neighbor_and_lambda | CKrawczyk/hdbscan | python | def _find_neighbor_and_lambda(neighbor_indices, neighbor_distances, core_distances, min_samples):
'\n Find the nearest mutual reachability neighbor of a point, and compute\n the associated lambda value for the point, given the mutual reachability\n distance to a nearest neighbor.\n\n Parameters\n --... |
def _extend_condensed_tree(tree, neighbor_indices, neighbor_distances, core_distances, min_samples):
'\n Create a new condensed tree with an additional point added, allowing for\n computations as if this point had been part of the original tree. Note\n that this makes as little change to the tree as possib... | 2,089,607,605,473,284,400 | Create a new condensed tree with an additional point added, allowing for
computations as if this point had been part of the original tree. Note
that this makes as little change to the tree as possible, with no
re-optimizing/re-condensing so that the selected clusters remain
effectively unchanged.
Parameters
----------... | hdbscan/prediction.py | _extend_condensed_tree | CKrawczyk/hdbscan | python | def _extend_condensed_tree(tree, neighbor_indices, neighbor_distances, core_distances, min_samples):
'\n Create a new condensed tree with an additional point added, allowing for\n computations as if this point had been part of the original tree. Note\n that this makes as little change to the tree as possib... |
def _find_cluster_and_probability(tree, cluster_tree, neighbor_indices, neighbor_distances, core_distances, cluster_map, max_lambdas, min_samples):
'\n Return the cluster label (of the original clustering) and membership\n probability of a new data point.\n\n Parameters\n ----------\n tree : Condense... | -6,342,860,168,396,817,000 | Return the cluster label (of the original clustering) and membership
probability of a new data point.
Parameters
----------
tree : CondensedTree
The condensed tree associated with the clustering.
cluster_tree : structured_array
The raw form of the condensed tree with only cluster information (no
data on i... | hdbscan/prediction.py | _find_cluster_and_probability | CKrawczyk/hdbscan | python | def _find_cluster_and_probability(tree, cluster_tree, neighbor_indices, neighbor_distances, core_distances, cluster_map, max_lambdas, min_samples):
'\n Return the cluster label (of the original clustering) and membership\n probability of a new data point.\n\n Parameters\n ----------\n tree : Condense... |
def approximate_predict(clusterer, points_to_predict):
"Predict the cluster label of new points. The returned labels\n will be those of the original clustering found by ``clusterer``,\n and therefore are not (necessarily) the cluster labels that would\n be found by clustering the original data combined wit... | -9,133,352,897,079,680,000 | Predict the cluster label of new points. The returned labels
will be those of the original clustering found by ``clusterer``,
and therefore are not (necessarily) the cluster labels that would
be found by clustering the original data combined with
``points_to_predict``, hence the 'approximate' label.
If you simply wish... | hdbscan/prediction.py | approximate_predict | CKrawczyk/hdbscan | python | def approximate_predict(clusterer, points_to_predict):
"Predict the cluster label of new points. The returned labels\n will be those of the original clustering found by ``clusterer``,\n and therefore are not (necessarily) the cluster labels that would\n be found by clustering the original data combined wit... |
def membership_vector(clusterer, points_to_predict):
'Predict soft cluster membership. The result produces a vector\n for each point in ``points_to_predict`` that gives a probability that\n the given point is a member of a cluster for each of the selected clusters\n of the ``clusterer``.\n\n Parameters\... | 1,341,451,579,952,617,700 | Predict soft cluster membership. The result produces a vector
for each point in ``points_to_predict`` that gives a probability that
the given point is a member of a cluster for each of the selected clusters
of the ``clusterer``.
Parameters
----------
clusterer : HDBSCAN
A clustering object that has been fit to the... | hdbscan/prediction.py | membership_vector | CKrawczyk/hdbscan | python | def membership_vector(clusterer, points_to_predict):
'Predict soft cluster membership. The result produces a vector\n for each point in ``points_to_predict`` that gives a probability that\n the given point is a member of a cluster for each of the selected clusters\n of the ``clusterer``.\n\n Parameters\... |
def all_points_membership_vectors(clusterer):
"Predict soft cluster membership vectors for all points in the\n original dataset the clusterer was trained on. This function is more\n efficient by making use of the fact that all points are already in the\n condensed tree, and processing in bulk.\n\n Param... | 8,111,365,759,064,287,000 | Predict soft cluster membership vectors for all points in the
original dataset the clusterer was trained on. This function is more
efficient by making use of the fact that all points are already in the
condensed tree, and processing in bulk.
Parameters
----------
clusterer : HDBSCAN
A clustering object that has b... | hdbscan/prediction.py | all_points_membership_vectors | CKrawczyk/hdbscan | python | def all_points_membership_vectors(clusterer):
"Predict soft cluster membership vectors for all points in the\n original dataset the clusterer was trained on. This function is more\n efficient by making use of the fact that all points are already in the\n condensed tree, and processing in bulk.\n\n Param... |
def index(request):
'\n View for the static index page\n '
return render(request, 'public/home.html', _get_context('Home')) | 5,071,290,183,332,569,000 | View for the static index page | sigmapiweb/apps/PubSite/views.py | index | Jacobvs/sigmapi-web | python | def index(request):
'\n \n '
return render(request, 'public/home.html', _get_context('Home')) |
def about(request):
'\n View for the static chapter history page.\n '
return render(request, 'public/about.html', _get_context('About')) | 3,343,995,519,148,531,000 | View for the static chapter history page. | sigmapiweb/apps/PubSite/views.py | about | Jacobvs/sigmapi-web | python | def about(request):
'\n \n '
return render(request, 'public/about.html', _get_context('About')) |
def activities(request):
'\n View for the static chapter service page.\n '
return render(request, 'public/activities.html', _get_context('Service & Activities')) | 5,797,297,894,108,019,000 | View for the static chapter service page. | sigmapiweb/apps/PubSite/views.py | activities | Jacobvs/sigmapi-web | python | def activities(request):
'\n \n '
return render(request, 'public/activities.html', _get_context('Service & Activities')) |
def rush(request):
'\n View for the static chapter service page.\n '
return render(request, 'public/rush.html', _get_context('Rush')) | 2,282,172,684,523,212,000 | View for the static chapter service page. | sigmapiweb/apps/PubSite/views.py | rush | Jacobvs/sigmapi-web | python | def rush(request):
'\n \n '
return render(request, 'public/rush.html', _get_context('Rush')) |
def campaign(request):
'\n View for the campaign service page.\n '
class NoRebuildAuthSession(requests.Session):
def rebuild_auth(self, prepared_request, response):
'\n No code here means requests will always preserve the Authorization\n header when redirected.\... | 8,055,564,660,194,777,000 | View for the campaign service page. | sigmapiweb/apps/PubSite/views.py | campaign | Jacobvs/sigmapi-web | python | def campaign(request):
'\n \n '
class NoRebuildAuthSession(requests.Session):
def rebuild_auth(self, prepared_request, response):
'\n No code here means requests will always preserve the Authorization\n header when redirected.\n Be careful not to leak... |
def permission_denied(request):
'\n View for 403 (Permission Denied) error.\n '
return render(request, 'common/403.html', _get_context('Permission Denied')) | -3,855,063,181,969,753,600 | View for 403 (Permission Denied) error. | sigmapiweb/apps/PubSite/views.py | permission_denied | Jacobvs/sigmapi-web | python | def permission_denied(request):
'\n \n '
return render(request, 'common/403.html', _get_context('Permission Denied')) |
def rebuild_auth(self, prepared_request, response):
'\n No code here means requests will always preserve the Authorization\n header when redirected.\n Be careful not to leak your credentials to untrusted hosts!\n ' | -5,803,225,964,835,695,000 | No code here means requests will always preserve the Authorization
header when redirected.
Be careful not to leak your credentials to untrusted hosts! | sigmapiweb/apps/PubSite/views.py | rebuild_auth | Jacobvs/sigmapi-web | python | def rebuild_auth(self, prepared_request, response):
'\n No code here means requests will always preserve the Authorization\n header when redirected.\n Be careful not to leak your credentials to untrusted hosts!\n ' |
def normalize(self, text: str) -> str:
'Normalize text.\n \n Args:\n text (str): text to be normalized\n '
for (normalize_fn, repl) in self._normalize:
text = normalize_fn(text, repl)
return text | 6,344,072,354,142,538,000 | Normalize text.
Args:
text (str): text to be normalized | prenlp/data/normalizer.py | normalize | awesome-archive/prenlp | python | def normalize(self, text: str) -> str:
'Normalize text.\n \n Args:\n text (str): text to be normalized\n '
for (normalize_fn, repl) in self._normalize:
text = normalize_fn(text, repl)
return text |
def _init_normalize(self) -> None:
"Initialize normalize function.\n If 'repl' is None, normalization is not applied to the pattern corresponding to 'repl'.\n "
if (self.url_repl is not None):
self._normalize.append((self._url_normalize, self.url_repl))
if (self.tag_repl is not None):
... | 9,143,328,064,171,123,000 | Initialize normalize function.
If 'repl' is None, normalization is not applied to the pattern corresponding to 'repl'. | prenlp/data/normalizer.py | _init_normalize | awesome-archive/prenlp | python | def _init_normalize(self) -> None:
"Initialize normalize function.\n If 'repl' is None, normalization is not applied to the pattern corresponding to 'repl'.\n "
if (self.url_repl is not None):
self._normalize.append((self._url_normalize, self.url_repl))
if (self.tag_repl is not None):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.