repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
StagPython/StagPy | stagpy/field.py | plot_iso | def plot_iso(axis, step, var):
"""Plot isocontours of scalar field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the isocontours should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the scalar field name.
"""
xmesh, ymesh, fld = get_meshes_fld(step, var)
if conf.field.shift:
fld = np.roll(fld, conf.field.shift, axis=0)
axis.contour(xmesh, ymesh, fld, linewidths=1) | python | def plot_iso(axis, step, var):
"""Plot isocontours of scalar field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the isocontours should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the scalar field name.
"""
xmesh, ymesh, fld = get_meshes_fld(step, var)
if conf.field.shift:
fld = np.roll(fld, conf.field.shift, axis=0)
axis.contour(xmesh, ymesh, fld, linewidths=1) | [
"def",
"plot_iso",
"(",
"axis",
",",
"step",
",",
"var",
")",
":",
"xmesh",
",",
"ymesh",
",",
"fld",
"=",
"get_meshes_fld",
"(",
"step",
",",
"var",
")",
"if",
"conf",
".",
"field",
".",
"shift",
":",
"fld",
"=",
"np",
".",
"roll",
"(",
"fld",
... | Plot isocontours of scalar field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the isocontours should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the scalar field name. | [
"Plot",
"isocontours",
"of",
"scalar",
"field",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/field.py#L199-L213 | train | 42,200 |
StagPython/StagPy | stagpy/field.py | plot_vec | def plot_vec(axis, step, var):
"""Plot vector field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the vector field should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the vector field name.
"""
xmesh, ymesh, vec1, vec2 = get_meshes_vec(step, var)
dipz = step.geom.nztot // 10
if conf.field.shift:
vec1 = np.roll(vec1, conf.field.shift, axis=0)
vec2 = np.roll(vec2, conf.field.shift, axis=0)
if step.geom.spherical or conf.plot.ratio is None:
dipx = dipz
else:
dipx = step.geom.nytot if step.geom.twod_yz else step.geom.nxtot
dipx = int(dipx // 10 * conf.plot.ratio) + 1
axis.quiver(xmesh[::dipx, ::dipz], ymesh[::dipx, ::dipz],
vec1[::dipx, ::dipz], vec2[::dipx, ::dipz],
linewidths=1) | python | def plot_vec(axis, step, var):
"""Plot vector field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the vector field should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the vector field name.
"""
xmesh, ymesh, vec1, vec2 = get_meshes_vec(step, var)
dipz = step.geom.nztot // 10
if conf.field.shift:
vec1 = np.roll(vec1, conf.field.shift, axis=0)
vec2 = np.roll(vec2, conf.field.shift, axis=0)
if step.geom.spherical or conf.plot.ratio is None:
dipx = dipz
else:
dipx = step.geom.nytot if step.geom.twod_yz else step.geom.nxtot
dipx = int(dipx // 10 * conf.plot.ratio) + 1
axis.quiver(xmesh[::dipx, ::dipz], ymesh[::dipx, ::dipz],
vec1[::dipx, ::dipz], vec2[::dipx, ::dipz],
linewidths=1) | [
"def",
"plot_vec",
"(",
"axis",
",",
"step",
",",
"var",
")",
":",
"xmesh",
",",
"ymesh",
",",
"vec1",
",",
"vec2",
"=",
"get_meshes_vec",
"(",
"step",
",",
"var",
")",
"dipz",
"=",
"step",
".",
"geom",
".",
"nztot",
"//",
"10",
"if",
"conf",
"."... | Plot vector field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the vector field should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the vector field name. | [
"Plot",
"vector",
"field",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/field.py#L216-L239 | train | 42,201 |
StagPython/StagPy | stagpy/field.py | cmd | def cmd():
"""Implementation of field subcommand.
Other Parameters:
conf.field
conf.core
"""
sdat = StagyyData(conf.core.path)
sovs = set_of_vars(conf.field.plot)
minmax = {}
if conf.plot.cminmax:
conf.plot.vmin = None
conf.plot.vmax = None
for step in sdat.walk.filter(snap=True):
for var, _ in sovs:
if var in step.fields:
if var in phyvars.FIELD:
dim = phyvars.FIELD[var].dim
else:
dim = phyvars.FIELD_EXTRA[var].dim
field, _ = sdat.scale(step.fields[var], dim)
if var in minmax:
minmax[var] = (min(minmax[var][0], np.nanmin(field)),
max(minmax[var][1], np.nanmax(field)))
else:
minmax[var] = np.nanmin(field), np.nanmax(field)
for step in sdat.walk.filter(snap=True):
for var in sovs:
if var[0] not in step.fields:
print("'{}' field on snap {} not found".format(var[0],
step.isnap))
continue
opts = {}
if var[0] in minmax:
opts = dict(vmin=minmax[var[0]][0], vmax=minmax[var[0]][1])
fig, axis, _, _ = plot_scalar(step, var[0], **opts)
if valid_field_var(var[1]):
plot_iso(axis, step, var[1])
elif var[1]:
plot_vec(axis, step, var[1])
oname = '{}_{}'.format(*var) if var[1] else var[0]
misc.saveplot(fig, oname, step.isnap) | python | def cmd():
"""Implementation of field subcommand.
Other Parameters:
conf.field
conf.core
"""
sdat = StagyyData(conf.core.path)
sovs = set_of_vars(conf.field.plot)
minmax = {}
if conf.plot.cminmax:
conf.plot.vmin = None
conf.plot.vmax = None
for step in sdat.walk.filter(snap=True):
for var, _ in sovs:
if var in step.fields:
if var in phyvars.FIELD:
dim = phyvars.FIELD[var].dim
else:
dim = phyvars.FIELD_EXTRA[var].dim
field, _ = sdat.scale(step.fields[var], dim)
if var in minmax:
minmax[var] = (min(minmax[var][0], np.nanmin(field)),
max(minmax[var][1], np.nanmax(field)))
else:
minmax[var] = np.nanmin(field), np.nanmax(field)
for step in sdat.walk.filter(snap=True):
for var in sovs:
if var[0] not in step.fields:
print("'{}' field on snap {} not found".format(var[0],
step.isnap))
continue
opts = {}
if var[0] in minmax:
opts = dict(vmin=minmax[var[0]][0], vmax=minmax[var[0]][1])
fig, axis, _, _ = plot_scalar(step, var[0], **opts)
if valid_field_var(var[1]):
plot_iso(axis, step, var[1])
elif var[1]:
plot_vec(axis, step, var[1])
oname = '{}_{}'.format(*var) if var[1] else var[0]
misc.saveplot(fig, oname, step.isnap) | [
"def",
"cmd",
"(",
")",
":",
"sdat",
"=",
"StagyyData",
"(",
"conf",
".",
"core",
".",
"path",
")",
"sovs",
"=",
"set_of_vars",
"(",
"conf",
".",
"field",
".",
"plot",
")",
"minmax",
"=",
"{",
"}",
"if",
"conf",
".",
"plot",
".",
"cminmax",
":",
... | Implementation of field subcommand.
Other Parameters:
conf.field
conf.core | [
"Implementation",
"of",
"field",
"subcommand",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/field.py#L242-L283 | train | 42,202 |
StagPython/StagPy | stagpy/args.py | _sub | def _sub(cmd, *sections):
"""Build Subcmd instance."""
cmd_func = cmd if isfunction(cmd) else cmd.cmd
return Subcmd(baredoc(cmd), *sections, func=cmd_func) | python | def _sub(cmd, *sections):
"""Build Subcmd instance."""
cmd_func = cmd if isfunction(cmd) else cmd.cmd
return Subcmd(baredoc(cmd), *sections, func=cmd_func) | [
"def",
"_sub",
"(",
"cmd",
",",
"*",
"sections",
")",
":",
"cmd_func",
"=",
"cmd",
"if",
"isfunction",
"(",
"cmd",
")",
"else",
"cmd",
".",
"cmd",
"return",
"Subcmd",
"(",
"baredoc",
"(",
"cmd",
")",
",",
"*",
"sections",
",",
"func",
"=",
"cmd_fun... | Build Subcmd instance. | [
"Build",
"Subcmd",
"instance",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/args.py#L15-L18 | train | 42,203 |
StagPython/StagPy | stagpy/args.py | _steps_to_slices | def _steps_to_slices():
"""parse timesteps and snapshots arguments and return slices"""
if not (conf.core.timesteps or conf.core.snapshots):
# default to the last snap
conf.core.timesteps = None
conf.core.snapshots = slice(-1, None, None)
return
elif conf.core.snapshots:
# snapshots take precedence over timesteps
# if both are defined
conf.core.timesteps = None
steps = conf.core.snapshots
else:
conf.core.snapshots = None
steps = conf.core.timesteps
steps = steps.split(':')
steps[0] = int(steps[0]) if steps[0] else None
if len(steps) == 1:
steps.append(steps[0] + 1)
steps[1] = int(steps[1]) if steps[1] else None
if len(steps) != 3:
steps = steps[0:2] + [1]
steps[2] = int(steps[2]) if steps[2] else None
steps = slice(*steps)
if conf.core.snapshots is not None:
conf.core.snapshots = steps
else:
conf.core.timesteps = steps | python | def _steps_to_slices():
"""parse timesteps and snapshots arguments and return slices"""
if not (conf.core.timesteps or conf.core.snapshots):
# default to the last snap
conf.core.timesteps = None
conf.core.snapshots = slice(-1, None, None)
return
elif conf.core.snapshots:
# snapshots take precedence over timesteps
# if both are defined
conf.core.timesteps = None
steps = conf.core.snapshots
else:
conf.core.snapshots = None
steps = conf.core.timesteps
steps = steps.split(':')
steps[0] = int(steps[0]) if steps[0] else None
if len(steps) == 1:
steps.append(steps[0] + 1)
steps[1] = int(steps[1]) if steps[1] else None
if len(steps) != 3:
steps = steps[0:2] + [1]
steps[2] = int(steps[2]) if steps[2] else None
steps = slice(*steps)
if conf.core.snapshots is not None:
conf.core.snapshots = steps
else:
conf.core.timesteps = steps | [
"def",
"_steps_to_slices",
"(",
")",
":",
"if",
"not",
"(",
"conf",
".",
"core",
".",
"timesteps",
"or",
"conf",
".",
"core",
".",
"snapshots",
")",
":",
"# default to the last snap",
"conf",
".",
"core",
".",
"timesteps",
"=",
"None",
"conf",
".",
"core... | parse timesteps and snapshots arguments and return slices | [
"parse",
"timesteps",
"and",
"snapshots",
"arguments",
"and",
"return",
"slices"
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/args.py#L35-L62 | train | 42,204 |
StagPython/StagPy | stagpy/args.py | parse_args | def parse_args(arglist=None):
"""Parse cmd line arguments.
Update :attr:`stagpy.conf` accordingly.
Args:
arglist (list of str): the list of cmd line arguments. If set to
None, the arguments are taken from :attr:`sys.argv`.
Returns:
function: the function implementing the sub command to be executed.
"""
climan = CLIManager(conf, **SUB_CMDS)
create_complete_files(climan, CONFIG_DIR, 'stagpy', 'stagpy-git',
zsh_sourceable=True)
cmd_args, all_subs = climan.parse_args(arglist)
sub_cmd = cmd_args.loam_sub_name
if sub_cmd is None:
return cmd_args.func
if sub_cmd != 'config':
commands.report_parsing_problems(PARSING_OUT)
if conf.common.set:
set_conf_str(conf, conf.common.set)
if conf.common.config:
commands.config_pp(all_subs)
load_mplstyle()
try:
_steps_to_slices()
except AttributeError:
pass
return cmd_args.func | python | def parse_args(arglist=None):
"""Parse cmd line arguments.
Update :attr:`stagpy.conf` accordingly.
Args:
arglist (list of str): the list of cmd line arguments. If set to
None, the arguments are taken from :attr:`sys.argv`.
Returns:
function: the function implementing the sub command to be executed.
"""
climan = CLIManager(conf, **SUB_CMDS)
create_complete_files(climan, CONFIG_DIR, 'stagpy', 'stagpy-git',
zsh_sourceable=True)
cmd_args, all_subs = climan.parse_args(arglist)
sub_cmd = cmd_args.loam_sub_name
if sub_cmd is None:
return cmd_args.func
if sub_cmd != 'config':
commands.report_parsing_problems(PARSING_OUT)
if conf.common.set:
set_conf_str(conf, conf.common.set)
if conf.common.config:
commands.config_pp(all_subs)
load_mplstyle()
try:
_steps_to_slices()
except AttributeError:
pass
return cmd_args.func | [
"def",
"parse_args",
"(",
"arglist",
"=",
"None",
")",
":",
"climan",
"=",
"CLIManager",
"(",
"conf",
",",
"*",
"*",
"SUB_CMDS",
")",
"create_complete_files",
"(",
"climan",
",",
"CONFIG_DIR",
",",
"'stagpy'",
",",
"'stagpy-git'",
",",
"zsh_sourceable",
"=",... | Parse cmd line arguments.
Update :attr:`stagpy.conf` accordingly.
Args:
arglist (list of str): the list of cmd line arguments. If set to
None, the arguments are taken from :attr:`sys.argv`.
Returns:
function: the function implementing the sub command to be executed. | [
"Parse",
"cmd",
"line",
"arguments",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/args.py#L65-L103 | train | 42,205 |
StagPython/StagPy | stagpy/plates.py | plot_plate_limits | def plot_plate_limits(axis, ridges, trenches, ymin, ymax):
"""plot lines designating ridges and trenches"""
for trench in trenches:
axis.axvline(
x=trench, ymin=ymin, ymax=ymax,
color='red', ls='dashed', alpha=0.4)
for ridge in ridges:
axis.axvline(
x=ridge, ymin=ymin, ymax=ymax,
color='green', ls='dashed', alpha=0.4)
axis.set_xlim(0, 2 * np.pi)
axis.set_ylim(ymin, ymax) | python | def plot_plate_limits(axis, ridges, trenches, ymin, ymax):
"""plot lines designating ridges and trenches"""
for trench in trenches:
axis.axvline(
x=trench, ymin=ymin, ymax=ymax,
color='red', ls='dashed', alpha=0.4)
for ridge in ridges:
axis.axvline(
x=ridge, ymin=ymin, ymax=ymax,
color='green', ls='dashed', alpha=0.4)
axis.set_xlim(0, 2 * np.pi)
axis.set_ylim(ymin, ymax) | [
"def",
"plot_plate_limits",
"(",
"axis",
",",
"ridges",
",",
"trenches",
",",
"ymin",
",",
"ymax",
")",
":",
"for",
"trench",
"in",
"trenches",
":",
"axis",
".",
"axvline",
"(",
"x",
"=",
"trench",
",",
"ymin",
"=",
"ymin",
",",
"ymax",
"=",
"ymax",
... | plot lines designating ridges and trenches | [
"plot",
"lines",
"designating",
"ridges",
"and",
"trenches"
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/plates.py#L168-L179 | train | 42,206 |
StagPython/StagPy | stagpy/plates.py | plot_plate_limits_field | def plot_plate_limits_field(axis, rcmb, ridges, trenches):
"""plot arrows designating ridges and trenches in 2D field plots"""
for trench in trenches:
xxd = (rcmb + 1.02) * np.cos(trench) # arrow begin
yyd = (rcmb + 1.02) * np.sin(trench) # arrow begin
xxt = (rcmb + 1.35) * np.cos(trench) # arrow end
yyt = (rcmb + 1.35) * np.sin(trench) # arrow end
axis.annotate('', xy=(xxd, yyd), xytext=(xxt, yyt),
arrowprops=dict(facecolor='red', shrink=0.05))
for ridge in ridges:
xxd = (rcmb + 1.02) * np.cos(ridge)
yyd = (rcmb + 1.02) * np.sin(ridge)
xxt = (rcmb + 1.35) * np.cos(ridge)
yyt = (rcmb + 1.35) * np.sin(ridge)
axis.annotate('', xy=(xxd, yyd), xytext=(xxt, yyt),
arrowprops=dict(facecolor='green', shrink=0.05)) | python | def plot_plate_limits_field(axis, rcmb, ridges, trenches):
"""plot arrows designating ridges and trenches in 2D field plots"""
for trench in trenches:
xxd = (rcmb + 1.02) * np.cos(trench) # arrow begin
yyd = (rcmb + 1.02) * np.sin(trench) # arrow begin
xxt = (rcmb + 1.35) * np.cos(trench) # arrow end
yyt = (rcmb + 1.35) * np.sin(trench) # arrow end
axis.annotate('', xy=(xxd, yyd), xytext=(xxt, yyt),
arrowprops=dict(facecolor='red', shrink=0.05))
for ridge in ridges:
xxd = (rcmb + 1.02) * np.cos(ridge)
yyd = (rcmb + 1.02) * np.sin(ridge)
xxt = (rcmb + 1.35) * np.cos(ridge)
yyt = (rcmb + 1.35) * np.sin(ridge)
axis.annotate('', xy=(xxd, yyd), xytext=(xxt, yyt),
arrowprops=dict(facecolor='green', shrink=0.05)) | [
"def",
"plot_plate_limits_field",
"(",
"axis",
",",
"rcmb",
",",
"ridges",
",",
"trenches",
")",
":",
"for",
"trench",
"in",
"trenches",
":",
"xxd",
"=",
"(",
"rcmb",
"+",
"1.02",
")",
"*",
"np",
".",
"cos",
"(",
"trench",
")",
"# arrow begin",
"yyd",
... | plot arrows designating ridges and trenches in 2D field plots | [
"plot",
"arrows",
"designating",
"ridges",
"and",
"trenches",
"in",
"2D",
"field",
"plots"
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/plates.py#L182-L197 | train | 42,207 |
StagPython/StagPy | stagpy/plates.py | io_surface | def io_surface(timestep, time, fid, fld):
"""Output for surface files"""
fid.write("{} {}".format(timestep, time))
fid.writelines(["%10.2e" % item for item in fld[:]])
fid.writelines(["\n"]) | python | def io_surface(timestep, time, fid, fld):
"""Output for surface files"""
fid.write("{} {}".format(timestep, time))
fid.writelines(["%10.2e" % item for item in fld[:]])
fid.writelines(["\n"]) | [
"def",
"io_surface",
"(",
"timestep",
",",
"time",
",",
"fid",
",",
"fld",
")",
":",
"fid",
".",
"write",
"(",
"\"{} {}\"",
".",
"format",
"(",
"timestep",
",",
"time",
")",
")",
"fid",
".",
"writelines",
"(",
"[",
"\"%10.2e\"",
"%",
"item",
"for",
... | Output for surface files | [
"Output",
"for",
"surface",
"files"
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/plates.py#L478-L482 | train | 42,208 |
StagPython/StagPy | stagpy/plates.py | set_of_vars | def set_of_vars(arg_plot):
"""Build set of needed variables.
Args:
arg_plot (str): string with variable names separated with ``,``.
Returns:
set of str: set of variables.
"""
return set(var for var in arg_plot.split(',') if var in phyvars.PLATES) | python | def set_of_vars(arg_plot):
"""Build set of needed variables.
Args:
arg_plot (str): string with variable names separated with ``,``.
Returns:
set of str: set of variables.
"""
return set(var for var in arg_plot.split(',') if var in phyvars.PLATES) | [
"def",
"set_of_vars",
"(",
"arg_plot",
")",
":",
"return",
"set",
"(",
"var",
"for",
"var",
"in",
"arg_plot",
".",
"split",
"(",
"','",
")",
"if",
"var",
"in",
"phyvars",
".",
"PLATES",
")"
] | Build set of needed variables.
Args:
arg_plot (str): string with variable names separated with ``,``.
Returns:
set of str: set of variables. | [
"Build",
"set",
"of",
"needed",
"variables",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/plates.py#L577-L585 | train | 42,209 |
StagPython/StagPy | stagpy/__init__.py | _check_config | def _check_config():
"""Create config files as necessary."""
config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
verfile = config.CONFIG_DIR / '.version'
uptodate = verfile.is_file() and verfile.read_text() == __version__
if not uptodate:
verfile.write_text(__version__)
if not (uptodate and config.CONFIG_FILE.is_file()):
conf.create_config_(update=True)
for stfile in ('stagpy-paper.mplstyle',
'stagpy-slides.mplstyle'):
stfile_conf = config.CONFIG_DIR / stfile
if not (uptodate and stfile_conf.is_file()):
stfile_local = pathlib.Path(__file__).parent / stfile
shutil.copy(str(stfile_local), str(stfile_conf)) | python | def _check_config():
"""Create config files as necessary."""
config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
verfile = config.CONFIG_DIR / '.version'
uptodate = verfile.is_file() and verfile.read_text() == __version__
if not uptodate:
verfile.write_text(__version__)
if not (uptodate and config.CONFIG_FILE.is_file()):
conf.create_config_(update=True)
for stfile in ('stagpy-paper.mplstyle',
'stagpy-slides.mplstyle'):
stfile_conf = config.CONFIG_DIR / stfile
if not (uptodate and stfile_conf.is_file()):
stfile_local = pathlib.Path(__file__).parent / stfile
shutil.copy(str(stfile_local), str(stfile_conf)) | [
"def",
"_check_config",
"(",
")",
":",
"config",
".",
"CONFIG_DIR",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"verfile",
"=",
"config",
".",
"CONFIG_DIR",
"/",
"'.version'",
"uptodate",
"=",
"verfile",
".",
"is_file",
... | Create config files as necessary. | [
"Create",
"config",
"files",
"as",
"necessary",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/__init__.py#L48-L62 | train | 42,210 |
StagPython/StagPy | stagpy/__init__.py | load_mplstyle | def load_mplstyle():
"""Try to load conf.plot.mplstyle matplotlib style."""
plt = importlib.import_module('matplotlib.pyplot')
if conf.plot.mplstyle:
for style in conf.plot.mplstyle.split():
stfile = config.CONFIG_DIR / (style + '.mplstyle')
if stfile.is_file():
style = str(stfile)
try:
plt.style.use(style)
except OSError:
print('Cannot import style {}.'.format(style),
file=sys.stderr)
conf.plot.mplstyle = ''
if conf.plot.xkcd:
plt.xkcd() | python | def load_mplstyle():
"""Try to load conf.plot.mplstyle matplotlib style."""
plt = importlib.import_module('matplotlib.pyplot')
if conf.plot.mplstyle:
for style in conf.plot.mplstyle.split():
stfile = config.CONFIG_DIR / (style + '.mplstyle')
if stfile.is_file():
style = str(stfile)
try:
plt.style.use(style)
except OSError:
print('Cannot import style {}.'.format(style),
file=sys.stderr)
conf.plot.mplstyle = ''
if conf.plot.xkcd:
plt.xkcd() | [
"def",
"load_mplstyle",
"(",
")",
":",
"plt",
"=",
"importlib",
".",
"import_module",
"(",
"'matplotlib.pyplot'",
")",
"if",
"conf",
".",
"plot",
".",
"mplstyle",
":",
"for",
"style",
"in",
"conf",
".",
"plot",
".",
"mplstyle",
".",
"split",
"(",
")",
... | Try to load conf.plot.mplstyle matplotlib style. | [
"Try",
"to",
"load",
"conf",
".",
"plot",
".",
"mplstyle",
"matplotlib",
"style",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/__init__.py#L65-L80 | train | 42,211 |
StagPython/StagPy | stagpy/processing.py | dtime | def dtime(sdat, tstart=None, tend=None):
"""Time increment dt.
Compute dt as a function of time.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: dt and time arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
time = tseries['t'].values
return time[1:] - time[:-1], time[:-1] | python | def dtime(sdat, tstart=None, tend=None):
"""Time increment dt.
Compute dt as a function of time.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: dt and time arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
time = tseries['t'].values
return time[1:] - time[:-1], time[:-1] | [
"def",
"dtime",
"(",
"sdat",
",",
"tstart",
"=",
"None",
",",
"tend",
"=",
"None",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"time",
"=",
"tseries",
"[",
"'t'",
"]",
".",
"values",
"return",
"time",
... | Time increment dt.
Compute dt as a function of time.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: dt and time arrays. | [
"Time",
"increment",
"dt",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L18-L34 | train | 42,212 |
StagPython/StagPy | stagpy/processing.py | dt_dt | def dt_dt(sdat, tstart=None, tend=None):
"""Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: derivative of temperature and time
arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
time = tseries['t'].values
temp = tseries['Tmean'].values
dtdt = (temp[1:] - temp[:-1]) / (time[1:] - time[:-1])
return dtdt, time[:-1] | python | def dt_dt(sdat, tstart=None, tend=None):
"""Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: derivative of temperature and time
arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
time = tseries['t'].values
temp = tseries['Tmean'].values
dtdt = (temp[1:] - temp[:-1]) / (time[1:] - time[:-1])
return dtdt, time[:-1] | [
"def",
"dt_dt",
"(",
"sdat",
",",
"tstart",
"=",
"None",
",",
"tend",
"=",
"None",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"time",
"=",
"tseries",
"[",
"'t'",
"]",
".",
"values",
"temp",
"=",
"tser... | Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: derivative of temperature and time
arrays. | [
"Derivative",
"of",
"temperature",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L37-L56 | train | 42,213 |
StagPython/StagPy | stagpy/processing.py | ebalance | def ebalance(sdat, tstart=None, tend=None):
"""Energy balance.
Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit
Euler scheme. This should be zero if energy is conserved.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: energy balance and time arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
rbot, rtop = misc.get_rbounds(sdat.steps.last)
if rbot != 0: # spherical
coefsurf = (rtop / rbot)**2
volume = rbot * ((rtop / rbot)**3 - 1) / 3
else:
coefsurf = 1.
volume = 1.
dtdt, time = dt_dt(sdat, tstart, tend)
ftop = tseries['ftop'].values * coefsurf
fbot = tseries['fbot'].values
radio = tseries['H_int'].values
ebal = ftop[1:] - fbot[1:] + volume * (dtdt - radio[1:])
return ebal, time | python | def ebalance(sdat, tstart=None, tend=None):
"""Energy balance.
Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit
Euler scheme. This should be zero if energy is conserved.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: energy balance and time arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
rbot, rtop = misc.get_rbounds(sdat.steps.last)
if rbot != 0: # spherical
coefsurf = (rtop / rbot)**2
volume = rbot * ((rtop / rbot)**3 - 1) / 3
else:
coefsurf = 1.
volume = 1.
dtdt, time = dt_dt(sdat, tstart, tend)
ftop = tseries['ftop'].values * coefsurf
fbot = tseries['fbot'].values
radio = tseries['H_int'].values
ebal = ftop[1:] - fbot[1:] + volume * (dtdt - radio[1:])
return ebal, time | [
"def",
"ebalance",
"(",
"sdat",
",",
"tstart",
"=",
"None",
",",
"tend",
"=",
"None",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"sdat",
".",
... | Energy balance.
Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit
Euler scheme. This should be zero if energy is conserved.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: energy balance and time arrays. | [
"Energy",
"balance",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L59-L87 | train | 42,214 |
StagPython/StagPy | stagpy/processing.py | mobility | def mobility(sdat, tstart=None, tend=None):
"""Plates mobility.
Compute the ratio vsurf / vrms.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: mobility and time arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
steps = sdat.steps[tseries.index[0]:tseries.index[-1]]
time = []
mob = []
for step in steps.filter(rprof=True):
time.append(step.timeinfo['t'])
mob.append(step.rprof.iloc[-1].loc['vrms'] / step.timeinfo['vrms'])
return np.array(mob), np.array(time) | python | def mobility(sdat, tstart=None, tend=None):
"""Plates mobility.
Compute the ratio vsurf / vrms.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: mobility and time arrays.
"""
tseries = sdat.tseries_between(tstart, tend)
steps = sdat.steps[tseries.index[0]:tseries.index[-1]]
time = []
mob = []
for step in steps.filter(rprof=True):
time.append(step.timeinfo['t'])
mob.append(step.rprof.iloc[-1].loc['vrms'] / step.timeinfo['vrms'])
return np.array(mob), np.array(time) | [
"def",
"mobility",
"(",
"sdat",
",",
"tstart",
"=",
"None",
",",
"tend",
"=",
"None",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"steps",
"=",
"sdat",
".",
"steps",
"[",
"tseries",
".",
"index",
"[",
... | Plates mobility.
Compute the ratio vsurf / vrms.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to None.
tend (float): time at which the computation should end. Use the
end of the time series data if set to None.
Returns:
tuple of :class:`numpy.array`: mobility and time arrays. | [
"Plates",
"mobility",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L90-L111 | train | 42,215 |
StagPython/StagPy | stagpy/processing.py | r_edges | def r_edges(step):
"""Cell border.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the position of the bottom and top walls
of the cells. The two elements of the tuple are identical.
"""
rbot, rtop = misc.get_rbounds(step)
centers = step.rprof.loc[:, 'r'].values + rbot
# assume walls are mid-way between T-nodes
# could be T-nodes at center between walls
edges = (centers[:-1] + centers[1:]) / 2
edges = np.insert(edges, 0, rbot)
edges = np.append(edges, rtop)
return edges, edges | python | def r_edges(step):
"""Cell border.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the position of the bottom and top walls
of the cells. The two elements of the tuple are identical.
"""
rbot, rtop = misc.get_rbounds(step)
centers = step.rprof.loc[:, 'r'].values + rbot
# assume walls are mid-way between T-nodes
# could be T-nodes at center between walls
edges = (centers[:-1] + centers[1:]) / 2
edges = np.insert(edges, 0, rbot)
edges = np.append(edges, rtop)
return edges, edges | [
"def",
"r_edges",
"(",
"step",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"centers",
"=",
"step",
".",
"rprof",
".",
"loc",
"[",
":",
",",
"'r'",
"]",
".",
"values",
"+",
"rbot",
"# assume walls are mid-way betwee... | Cell border.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the position of the bottom and top walls
of the cells. The two elements of the tuple are identical. | [
"Cell",
"border",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L114-L131 | train | 42,216 |
StagPython/StagPy | stagpy/processing.py | _scale_prof | def _scale_prof(step, rprof, rad=None):
"""Scale profile to take sphericity into account"""
rbot, rtop = misc.get_rbounds(step)
if rbot == 0: # not spherical
return rprof
if rad is None:
rad = step.rprof['r'].values + rbot
return rprof * (2 * rad / (rtop + rbot))**2 | python | def _scale_prof(step, rprof, rad=None):
"""Scale profile to take sphericity into account"""
rbot, rtop = misc.get_rbounds(step)
if rbot == 0: # not spherical
return rprof
if rad is None:
rad = step.rprof['r'].values + rbot
return rprof * (2 * rad / (rtop + rbot))**2 | [
"def",
"_scale_prof",
"(",
"step",
",",
"rprof",
",",
"rad",
"=",
"None",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"if",
"rbot",
"==",
"0",
":",
"# not spherical",
"return",
"rprof",
"if",
"rad",
"is",
"None",... | Scale profile to take sphericity into account | [
"Scale",
"profile",
"to",
"take",
"sphericity",
"into",
"account"
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L148-L155 | train | 42,217 |
StagPython/StagPy | stagpy/processing.py | diffs_prof | def diffs_prof(step):
"""Scaled diffusion.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at which it is evaluated.
"""
diff, rad = diff_prof(step)
return _scale_prof(step, diff, rad), rad | python | def diffs_prof(step):
"""Scaled diffusion.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at which it is evaluated.
"""
diff, rad = diff_prof(step)
return _scale_prof(step, diff, rad), rad | [
"def",
"diffs_prof",
"(",
"step",
")",
":",
"diff",
",",
"rad",
"=",
"diff_prof",
"(",
"step",
")",
"return",
"_scale_prof",
"(",
"step",
",",
"diff",
",",
"rad",
")",
",",
"rad"
] | Scaled diffusion.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at which it is evaluated. | [
"Scaled",
"diffusion",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L180-L193 | train | 42,218 |
StagPython/StagPy | stagpy/processing.py | energy_prof | def energy_prof(step):
"""Energy flux.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the energy flux and the radial position
at which it is evaluated.
"""
diff, rad = diffs_prof(step)
adv, _ = advts_prof(step)
return (diff + np.append(adv, 0)), rad | python | def energy_prof(step):
"""Energy flux.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the energy flux and the radial position
at which it is evaluated.
"""
diff, rad = diffs_prof(step)
adv, _ = advts_prof(step)
return (diff + np.append(adv, 0)), rad | [
"def",
"energy_prof",
"(",
"step",
")",
":",
"diff",
",",
"rad",
"=",
"diffs_prof",
"(",
"step",
")",
"adv",
",",
"_",
"=",
"advts_prof",
"(",
"step",
")",
"return",
"(",
"diff",
"+",
"np",
".",
"append",
"(",
"adv",
",",
"0",
")",
")",
",",
"r... | Energy flux.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the energy flux and the radial position
at which it is evaluated. | [
"Energy",
"flux",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L241-L255 | train | 42,219 |
StagPython/StagPy | stagpy/processing.py | advth | def advth(step):
"""Theoretical advection.
This compute the theoretical profile of total advection as function of
radius.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array` and None: the theoretical advection.
The second element of the tuple is None.
"""
rbot, rtop = misc.get_rbounds(step)
rmean = 0.5 * (rbot + rtop)
rad = step.rprof['r'].values + rbot
radio = step.timeinfo['H_int']
if rbot != 0: # spherical
th_adv = -(rtop**3 - rad**3) / rmean**2 / 3
else:
th_adv = rad - rtop
th_adv *= radio
th_adv += step.timeinfo['Nutop']
return th_adv, None | python | def advth(step):
"""Theoretical advection.
This compute the theoretical profile of total advection as function of
radius.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array` and None: the theoretical advection.
The second element of the tuple is None.
"""
rbot, rtop = misc.get_rbounds(step)
rmean = 0.5 * (rbot + rtop)
rad = step.rprof['r'].values + rbot
radio = step.timeinfo['H_int']
if rbot != 0: # spherical
th_adv = -(rtop**3 - rad**3) / rmean**2 / 3
else:
th_adv = rad - rtop
th_adv *= radio
th_adv += step.timeinfo['Nutop']
return th_adv, None | [
"def",
"advth",
"(",
"step",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"rmean",
"=",
"0.5",
"*",
"(",
"rbot",
"+",
"rtop",
")",
"rad",
"=",
"step",
".",
"rprof",
"[",
"'r'",
"]",
".",
"values",
"+",
"rbot... | Theoretical advection.
This compute the theoretical profile of total advection as function of
radius.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array` and None: the theoretical advection.
The second element of the tuple is None. | [
"Theoretical",
"advection",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L258-L281 | train | 42,220 |
StagPython/StagPy | stagpy/processing.py | init_c_overturn | def init_c_overturn(step):
"""Initial concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated.
"""
rbot, rtop = misc.get_rbounds(step)
xieut = step.sdat.par['tracersin']['fe_eut']
k_fe = step.sdat.par['tracersin']['k_fe']
xi0l = step.sdat.par['tracersin']['fe_cont']
xi0s = k_fe * xi0l
xired = xi0l / xieut
rsup = (rtop**3 - xired**(1 / (1 - k_fe)) *
(rtop**3 - rbot**3))**(1 / 3)
def initprof(rpos):
"""Theoretical initial profile."""
if rpos < rsup:
return xi0s * ((rtop**3 - rbot**3) /
(rtop**3 - rpos**3))**(1 - k_fe)
return xieut
rad = np.linspace(rbot, rtop, 500)
initprof = np.vectorize(initprof)
return initprof(rad), rad | python | def init_c_overturn(step):
"""Initial concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated.
"""
rbot, rtop = misc.get_rbounds(step)
xieut = step.sdat.par['tracersin']['fe_eut']
k_fe = step.sdat.par['tracersin']['k_fe']
xi0l = step.sdat.par['tracersin']['fe_cont']
xi0s = k_fe * xi0l
xired = xi0l / xieut
rsup = (rtop**3 - xired**(1 / (1 - k_fe)) *
(rtop**3 - rbot**3))**(1 / 3)
def initprof(rpos):
"""Theoretical initial profile."""
if rpos < rsup:
return xi0s * ((rtop**3 - rbot**3) /
(rtop**3 - rpos**3))**(1 - k_fe)
return xieut
rad = np.linspace(rbot, rtop, 500)
initprof = np.vectorize(initprof)
return initprof(rad), rad | [
"def",
"init_c_overturn",
"(",
"step",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"xieut",
"=",
"step",
".",
"sdat",
".",
"par",
"[",
"'tracersin'",
"]",
"[",
"'fe_eut'",
"]",
"k_fe",
"=",
"step",
".",
"sdat",
... | Initial concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated. | [
"Initial",
"concentration",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L284-L315 | train | 42,221 |
StagPython/StagPy | stagpy/processing.py | c_overturned | def c_overturned(step):
"""Theoretical overturned concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed and then a purely radial
overturn happens.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated.
"""
rbot, rtop = misc.get_rbounds(step)
cinit, rad = init_c_overturn(step)
radf = (rtop**3 + rbot**3 - rad**3)**(1 / 3)
return cinit, radf | python | def c_overturned(step):
"""Theoretical overturned concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed and then a purely radial
overturn happens.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated.
"""
rbot, rtop = misc.get_rbounds(step)
cinit, rad = init_c_overturn(step)
radf = (rtop**3 + rbot**3 - rad**3)**(1 / 3)
return cinit, radf | [
"def",
"c_overturned",
"(",
"step",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"cinit",
",",
"rad",
"=",
"init_c_overturn",
"(",
"step",
")",
"radf",
"=",
"(",
"rtop",
"**",
"3",
"+",
"rbot",
"**",
"3",
"-",
... | Theoretical overturned concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed and then a purely radial
overturn happens.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the composition and the radial position
at which it is evaluated. | [
"Theoretical",
"overturned",
"concentration",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L318-L335 | train | 42,222 |
StagPython/StagPy | stagpy/stagyydata.py | _Steps.last | def last(self):
"""Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1])
"""
if self._last is UNDETERMINED:
# not necessarily the last one...
self._last = self.sdat.tseries.index[-1]
return self[self._last] | python | def last(self):
"""Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1])
"""
if self._last is UNDETERMINED:
# not necessarily the last one...
self._last = self.sdat.tseries.index[-1]
return self[self._last] | [
"def",
"last",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last",
"is",
"UNDETERMINED",
":",
"# not necessarily the last one...",
"self",
".",
"_last",
"=",
"self",
".",
"sdat",
".",
"tseries",
".",
"index",
"[",
"-",
"1",
"]",
"return",
"self",
"[",
"... | Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1]) | [
"Last",
"time",
"step",
"available",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L160-L170 | train | 42,223 |
StagPython/StagPy | stagpy/stagyydata.py | _StepsView.filter | def filter(self, **filters):
"""Update filters with provided arguments.
Note that filters are only resolved when the view is iterated, and
hence they do not compose. Each call to filter merely updates the
relevant filters. For example, with this code::
view = sdat.steps[500:].filter(rprof=True, fields=['T'])
view.filter(fields=[])
the produced ``view``, when iterated, will generate the steps after the
500-th that have radial profiles. The ``fields`` filter set in the
first line is emptied in the second line.
Args:
snap (bool): the step must be a snapshot to pass.
rprof (bool): the step must have rprof data to pass.
fields (list): list of fields that must be present to pass.
func (function): arbitrary function taking a
:class:`~stagpy._step.Step` as argument and returning a True
value if the step should pass the filter.
Returns:
self.
"""
for flt, val in self._flt.items():
self._flt[flt] = filters.pop(flt, val)
if filters:
raise error.UnknownFiltersError(filters.keys())
return self | python | def filter(self, **filters):
"""Update filters with provided arguments.
Note that filters are only resolved when the view is iterated, and
hence they do not compose. Each call to filter merely updates the
relevant filters. For example, with this code::
view = sdat.steps[500:].filter(rprof=True, fields=['T'])
view.filter(fields=[])
the produced ``view``, when iterated, will generate the steps after the
500-th that have radial profiles. The ``fields`` filter set in the
first line is emptied in the second line.
Args:
snap (bool): the step must be a snapshot to pass.
rprof (bool): the step must have rprof data to pass.
fields (list): list of fields that must be present to pass.
func (function): arbitrary function taking a
:class:`~stagpy._step.Step` as argument and returning a True
value if the step should pass the filter.
Returns:
self.
"""
for flt, val in self._flt.items():
self._flt[flt] = filters.pop(flt, val)
if filters:
raise error.UnknownFiltersError(filters.keys())
return self | [
"def",
"filter",
"(",
"self",
",",
"*",
"*",
"filters",
")",
":",
"for",
"flt",
",",
"val",
"in",
"self",
".",
"_flt",
".",
"items",
"(",
")",
":",
"self",
".",
"_flt",
"[",
"flt",
"]",
"=",
"filters",
".",
"pop",
"(",
"flt",
",",
"val",
")",... | Update filters with provided arguments.
Note that filters are only resolved when the view is iterated, and
hence they do not compose. Each call to filter merely updates the
relevant filters. For example, with this code::
view = sdat.steps[500:].filter(rprof=True, fields=['T'])
view.filter(fields=[])
the produced ``view``, when iterated, will generate the steps after the
500-th that have radial profiles. The ``fields`` filter set in the
first line is emptied in the second line.
Args:
snap (bool): the step must be a snapshot to pass.
rprof (bool): the step must have rprof data to pass.
fields (list): list of fields that must be present to pass.
func (function): arbitrary function taking a
:class:`~stagpy._step.Step` as argument and returning a True
value if the step should pass the filter.
Returns:
self. | [
"Update",
"filters",
"with",
"provided",
"arguments",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L323-L352 | train | 42,224 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.hdf5 | def hdf5(self):
"""Path of output hdf5 folder if relevant, None otherwise."""
if self._rundir['hdf5'] is UNDETERMINED:
h5_folder = self.path / self.par['ioin']['hdf5_output_folder']
if (h5_folder / 'Data.xmf').is_file():
self._rundir['hdf5'] = h5_folder
else:
self._rundir['hdf5'] = None
return self._rundir['hdf5'] | python | def hdf5(self):
"""Path of output hdf5 folder if relevant, None otherwise."""
if self._rundir['hdf5'] is UNDETERMINED:
h5_folder = self.path / self.par['ioin']['hdf5_output_folder']
if (h5_folder / 'Data.xmf').is_file():
self._rundir['hdf5'] = h5_folder
else:
self._rundir['hdf5'] = None
return self._rundir['hdf5'] | [
"def",
"hdf5",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rundir",
"[",
"'hdf5'",
"]",
"is",
"UNDETERMINED",
":",
"h5_folder",
"=",
"self",
".",
"path",
"/",
"self",
".",
"par",
"[",
"'ioin'",
"]",
"[",
"'hdf5_output_folder'",
"]",
"if",
"(",
"h5_fo... | Path of output hdf5 folder if relevant, None otherwise. | [
"Path",
"of",
"output",
"hdf5",
"folder",
"if",
"relevant",
"None",
"otherwise",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L431-L439 | train | 42,225 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.tseries | def tseries(self):
"""Time series data.
This is a :class:`pandas.DataFrame` with istep as index and variable
names as columns.
"""
if self._stagdat['tseries'] is UNDETERMINED:
timefile = self.filename('TimeSeries.h5')
self._stagdat['tseries'] = stagyyparsers.time_series_h5(
timefile, list(phyvars.TIME.keys()))
if self._stagdat['tseries'] is not None:
return self._stagdat['tseries']
timefile = self.filename('time.dat')
if self.hdf5 and not timefile.is_file():
# check legacy folder as well
timefile = self.filename('time.dat', force_legacy=True)
self._stagdat['tseries'] = stagyyparsers.time_series(
timefile, list(phyvars.TIME.keys()))
return self._stagdat['tseries'] | python | def tseries(self):
"""Time series data.
This is a :class:`pandas.DataFrame` with istep as index and variable
names as columns.
"""
if self._stagdat['tseries'] is UNDETERMINED:
timefile = self.filename('TimeSeries.h5')
self._stagdat['tseries'] = stagyyparsers.time_series_h5(
timefile, list(phyvars.TIME.keys()))
if self._stagdat['tseries'] is not None:
return self._stagdat['tseries']
timefile = self.filename('time.dat')
if self.hdf5 and not timefile.is_file():
# check legacy folder as well
timefile = self.filename('time.dat', force_legacy=True)
self._stagdat['tseries'] = stagyyparsers.time_series(
timefile, list(phyvars.TIME.keys()))
return self._stagdat['tseries'] | [
"def",
"tseries",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stagdat",
"[",
"'tseries'",
"]",
"is",
"UNDETERMINED",
":",
"timefile",
"=",
"self",
".",
"filename",
"(",
"'TimeSeries.h5'",
")",
"self",
".",
"_stagdat",
"[",
"'tseries'",
"]",
"=",
"stagyyp... | Time series data.
This is a :class:`pandas.DataFrame` with istep as index and variable
names as columns. | [
"Time",
"series",
"data",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L451-L469 | train | 42,226 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.files | def files(self):
"""Set of found binary files output by StagYY."""
if self._rundir['ls'] is UNDETERMINED:
out_stem = pathlib.Path(self.par['ioin']['output_file_stem'] + '_')
out_dir = self.path / out_stem.parent
if out_dir.is_dir():
self._rundir['ls'] = set(out_dir.iterdir())
else:
self._rundir['ls'] = set()
return self._rundir['ls'] | python | def files(self):
"""Set of found binary files output by StagYY."""
if self._rundir['ls'] is UNDETERMINED:
out_stem = pathlib.Path(self.par['ioin']['output_file_stem'] + '_')
out_dir = self.path / out_stem.parent
if out_dir.is_dir():
self._rundir['ls'] = set(out_dir.iterdir())
else:
self._rundir['ls'] = set()
return self._rundir['ls'] | [
"def",
"files",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rundir",
"[",
"'ls'",
"]",
"is",
"UNDETERMINED",
":",
"out_stem",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"par",
"[",
"'ioin'",
"]",
"[",
"'output_file_stem'",
"]",
"+",
"'_'",
")",
... | Set of found binary files output by StagYY. | [
"Set",
"of",
"found",
"binary",
"files",
"output",
"by",
"StagYY",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L505-L514 | train | 42,227 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.walk | def walk(self):
"""Return view on configured steps slice.
Other Parameters:
conf.core.snapshots: the slice of snapshots.
conf.core.timesteps: the slice of timesteps.
"""
if conf.core.snapshots is not None:
return self.snaps[conf.core.snapshots]
elif conf.core.timesteps is not None:
return self.steps[conf.core.timesteps]
return self.snaps[-1:] | python | def walk(self):
"""Return view on configured steps slice.
Other Parameters:
conf.core.snapshots: the slice of snapshots.
conf.core.timesteps: the slice of timesteps.
"""
if conf.core.snapshots is not None:
return self.snaps[conf.core.snapshots]
elif conf.core.timesteps is not None:
return self.steps[conf.core.timesteps]
return self.snaps[-1:] | [
"def",
"walk",
"(",
"self",
")",
":",
"if",
"conf",
".",
"core",
".",
"snapshots",
"is",
"not",
"None",
":",
"return",
"self",
".",
"snaps",
"[",
"conf",
".",
"core",
".",
"snapshots",
"]",
"elif",
"conf",
".",
"core",
".",
"timesteps",
"is",
"not"... | Return view on configured steps slice.
Other Parameters:
conf.core.snapshots: the slice of snapshots.
conf.core.timesteps: the slice of timesteps. | [
"Return",
"view",
"on",
"configured",
"steps",
"slice",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L517-L528 | train | 42,228 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.scale | def scale(self, data, unit):
"""Scales quantity to obtain dimensionful quantity.
Args:
data (numpy.array): the quantity that should be scaled.
dim (str): the dimension of data as defined in phyvars.
Return:
(float, str): scaling factor and unit string.
Other Parameters:
conf.scaling.dimensional: if set to False (default), the factor is
always 1.
"""
if self.par['switches']['dimensional_units'] or \
not conf.scaling.dimensional or \
unit == '1':
return data, ''
scaling = phyvars.SCALES[unit](self.scales)
factor = conf.scaling.factors.get(unit, ' ')
if conf.scaling.time_in_y and unit == 's':
scaling /= conf.scaling.yearins
unit = 'yr'
elif conf.scaling.vel_in_cmpy and unit == 'm/s':
scaling *= 100 * conf.scaling.yearins
unit = 'cm/y'
if factor in phyvars.PREFIXES:
scaling *= 10**(-3 * (phyvars.PREFIXES.index(factor) + 1))
unit = factor + unit
return data * scaling, unit | python | def scale(self, data, unit):
"""Scales quantity to obtain dimensionful quantity.
Args:
data (numpy.array): the quantity that should be scaled.
dim (str): the dimension of data as defined in phyvars.
Return:
(float, str): scaling factor and unit string.
Other Parameters:
conf.scaling.dimensional: if set to False (default), the factor is
always 1.
"""
if self.par['switches']['dimensional_units'] or \
not conf.scaling.dimensional or \
unit == '1':
return data, ''
scaling = phyvars.SCALES[unit](self.scales)
factor = conf.scaling.factors.get(unit, ' ')
if conf.scaling.time_in_y and unit == 's':
scaling /= conf.scaling.yearins
unit = 'yr'
elif conf.scaling.vel_in_cmpy and unit == 'm/s':
scaling *= 100 * conf.scaling.yearins
unit = 'cm/y'
if factor in phyvars.PREFIXES:
scaling *= 10**(-3 * (phyvars.PREFIXES.index(factor) + 1))
unit = factor + unit
return data * scaling, unit | [
"def",
"scale",
"(",
"self",
",",
"data",
",",
"unit",
")",
":",
"if",
"self",
".",
"par",
"[",
"'switches'",
"]",
"[",
"'dimensional_units'",
"]",
"or",
"not",
"conf",
".",
"scaling",
".",
"dimensional",
"or",
"unit",
"==",
"'1'",
":",
"return",
"da... | Scales quantity to obtain dimensionful quantity.
Args:
data (numpy.array): the quantity that should be scaled.
dim (str): the dimension of data as defined in phyvars.
Return:
(float, str): scaling factor and unit string.
Other Parameters:
conf.scaling.dimensional: if set to False (default), the factor is
always 1. | [
"Scales",
"quantity",
"to",
"obtain",
"dimensionful",
"quantity",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L530-L557 | train | 42,229 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.tseries_between | def tseries_between(self, tstart=None, tend=None):
"""Return time series data between requested times.
Args:
tstart (float): starting time. Set to None to start at the
beginning of available data.
tend (float): ending time. Set to None to stop at the end of
available data.
Returns:
:class:`pandas.DataFrame`: slice of :attr:`tseries`.
"""
if self.tseries is None:
return None
ndat = self.tseries.shape[0]
if tstart is None:
istart = 0
else:
igm = 0
igp = ndat - 1
while igp - igm > 1:
istart = igm + (igp - igm) // 2
if self.tseries.iloc[istart]['t'] >= tstart:
igp = istart
else:
igm = istart
istart = igp
if tend is None:
iend = None
else:
igm = 0
igp = ndat - 1
while igp - igm > 1:
iend = igm + (igp - igm) // 2
if self.tseries.iloc[iend]['t'] > tend:
igp = iend
else:
igm = iend
iend = igm + 1
return self.tseries.iloc[istart:iend] | python | def tseries_between(self, tstart=None, tend=None):
"""Return time series data between requested times.
Args:
tstart (float): starting time. Set to None to start at the
beginning of available data.
tend (float): ending time. Set to None to stop at the end of
available data.
Returns:
:class:`pandas.DataFrame`: slice of :attr:`tseries`.
"""
if self.tseries is None:
return None
ndat = self.tseries.shape[0]
if tstart is None:
istart = 0
else:
igm = 0
igp = ndat - 1
while igp - igm > 1:
istart = igm + (igp - igm) // 2
if self.tseries.iloc[istart]['t'] >= tstart:
igp = istart
else:
igm = istart
istart = igp
if tend is None:
iend = None
else:
igm = 0
igp = ndat - 1
while igp - igm > 1:
iend = igm + (igp - igm) // 2
if self.tseries.iloc[iend]['t'] > tend:
igp = iend
else:
igm = iend
iend = igm + 1
return self.tseries.iloc[istart:iend] | [
"def",
"tseries_between",
"(",
"self",
",",
"tstart",
"=",
"None",
",",
"tend",
"=",
"None",
")",
":",
"if",
"self",
".",
"tseries",
"is",
"None",
":",
"return",
"None",
"ndat",
"=",
"self",
".",
"tseries",
".",
"shape",
"[",
"0",
"]",
"if",
"tstar... | Return time series data between requested times.
Args:
tstart (float): starting time. Set to None to start at the
beginning of available data.
tend (float): ending time. Set to None to stop at the end of
available data.
Returns:
:class:`pandas.DataFrame`: slice of :attr:`tseries`. | [
"Return",
"time",
"series",
"data",
"between",
"requested",
"times",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L559-L601 | train | 42,230 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.filename | def filename(self, fname, timestep=None, suffix='', force_legacy=False):
"""Return name of StagYY output file.
Args:
fname (str): name stem.
timestep (int): snapshot number, set to None if this is not
relevant.
suffix (str): optional suffix of file name.
force_legacy (bool): force returning the legacy output path.
Returns:
:class:`pathlib.Path`: the path of the output file constructed
with the provided segments.
"""
if timestep is not None:
fname += '{:05d}'.format(timestep)
fname += suffix
if not force_legacy and self.hdf5:
fpath = self.hdf5 / fname
else:
fpath = self.par['ioin']['output_file_stem'] + '_' + fname
fpath = self.path / fpath
return fpath | python | def filename(self, fname, timestep=None, suffix='', force_legacy=False):
"""Return name of StagYY output file.
Args:
fname (str): name stem.
timestep (int): snapshot number, set to None if this is not
relevant.
suffix (str): optional suffix of file name.
force_legacy (bool): force returning the legacy output path.
Returns:
:class:`pathlib.Path`: the path of the output file constructed
with the provided segments.
"""
if timestep is not None:
fname += '{:05d}'.format(timestep)
fname += suffix
if not force_legacy and self.hdf5:
fpath = self.hdf5 / fname
else:
fpath = self.par['ioin']['output_file_stem'] + '_' + fname
fpath = self.path / fpath
return fpath | [
"def",
"filename",
"(",
"self",
",",
"fname",
",",
"timestep",
"=",
"None",
",",
"suffix",
"=",
"''",
",",
"force_legacy",
"=",
"False",
")",
":",
"if",
"timestep",
"is",
"not",
"None",
":",
"fname",
"+=",
"'{:05d}'",
".",
"format",
"(",
"timestep",
... | Return name of StagYY output file.
Args:
fname (str): name stem.
timestep (int): snapshot number, set to None if this is not
relevant.
suffix (str): optional suffix of file name.
force_legacy (bool): force returning the legacy output path.
Returns:
:class:`pathlib.Path`: the path of the output file constructed
with the provided segments. | [
"Return",
"name",
"of",
"StagYY",
"output",
"file",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L603-L624 | train | 42,231 |
StagPython/StagPy | stagpy/stagyydata.py | StagyyData.binfiles_set | def binfiles_set(self, isnap):
"""Set of existing binary files at a given snap.
Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number.
"""
possible_files = set(self.filename(fstem, isnap, force_legacy=True)
for fstem in phyvars.FIELD_FILES)
return possible_files & self.files | python | def binfiles_set(self, isnap):
"""Set of existing binary files at a given snap.
Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number.
"""
possible_files = set(self.filename(fstem, isnap, force_legacy=True)
for fstem in phyvars.FIELD_FILES)
return possible_files & self.files | [
"def",
"binfiles_set",
"(",
"self",
",",
"isnap",
")",
":",
"possible_files",
"=",
"set",
"(",
"self",
".",
"filename",
"(",
"fstem",
",",
"isnap",
",",
"force_legacy",
"=",
"True",
")",
"for",
"fstem",
"in",
"phyvars",
".",
"FIELD_FILES",
")",
"return",... | Set of existing binary files at a given snap.
Args:
isnap (int): snapshot index.
Returns:
set of pathlib.Path: the set of output files available for this
snapshot number. | [
"Set",
"of",
"existing",
"binary",
"files",
"at",
"a",
"given",
"snap",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyydata.py#L626-L637 | train | 42,232 |
StagPython/StagPy | stagpy/stagyyparsers.py | _tidy_names | def _tidy_names(names, nnames, extra_names=None):
"""Truncate or extend names so that its len is nnames.
The list is modified, this function returns nothing.
Args:
names (list): list of names.
nnames (int): desired number of names.
extra_names (list of str): list of names to be used to extend the list
if needed. If this list isn't provided, a range is used instead.
"""
if len(names) < nnames and extra_names is not None:
names.extend(extra_names)
names.extend(range(nnames - len(names)))
del names[nnames:] | python | def _tidy_names(names, nnames, extra_names=None):
"""Truncate or extend names so that its len is nnames.
The list is modified, this function returns nothing.
Args:
names (list): list of names.
nnames (int): desired number of names.
extra_names (list of str): list of names to be used to extend the list
if needed. If this list isn't provided, a range is used instead.
"""
if len(names) < nnames and extra_names is not None:
names.extend(extra_names)
names.extend(range(nnames - len(names)))
del names[nnames:] | [
"def",
"_tidy_names",
"(",
"names",
",",
"nnames",
",",
"extra_names",
"=",
"None",
")",
":",
"if",
"len",
"(",
"names",
")",
"<",
"nnames",
"and",
"extra_names",
"is",
"not",
"None",
":",
"names",
".",
"extend",
"(",
"extra_names",
")",
"names",
".",
... | Truncate or extend names so that its len is nnames.
The list is modified, this function returns nothing.
Args:
names (list): list of names.
nnames (int): desired number of names.
extra_names (list of str): list of names to be used to extend the list
if needed. If this list isn't provided, a range is used instead. | [
"Truncate",
"or",
"extend",
"names",
"so",
"that",
"its",
"len",
"is",
"nnames",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L21-L35 | train | 42,233 |
StagPython/StagPy | stagpy/stagyyparsers.py | time_series | def time_series(timefile, colnames):
"""Read temporal series text file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional numeric column names from 0 to N-1 will be attributed to the N
extra columns present in :data:`timefile`.
Args:
timefile (:class:`pathlib.Path`): path of the time.dat file.
colnames (list of names): names of the variables expected in
:data:`timefile` (may be modified).
Returns:
:class:`pandas.DataFrame`:
Time series, with the variables in columns and the time steps in
rows.
"""
if not timefile.is_file():
return None
data = pd.read_csv(timefile, delim_whitespace=True, dtype=str,
header=None, skiprows=1, index_col=0,
engine='c', memory_map=True,
error_bad_lines=False, warn_bad_lines=False)
data = data.apply(pd.to_numeric, raw=True, errors='coerce')
# detect useless lines produced when run is restarted
rows_to_del = []
irow = len(data) - 1
while irow > 0:
iprev = irow - 1
while iprev >= 0 and data.index[irow] <= data.index[iprev]:
rows_to_del.append(iprev)
iprev -= 1
irow = iprev
if rows_to_del:
rows_to_keep = set(range(len(data))) - set(rows_to_del)
data = data.take(list(rows_to_keep), convert=False)
ncols = data.shape[1]
_tidy_names(colnames, ncols)
data.columns = colnames
return data | python | def time_series(timefile, colnames):
"""Read temporal series text file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional numeric column names from 0 to N-1 will be attributed to the N
extra columns present in :data:`timefile`.
Args:
timefile (:class:`pathlib.Path`): path of the time.dat file.
colnames (list of names): names of the variables expected in
:data:`timefile` (may be modified).
Returns:
:class:`pandas.DataFrame`:
Time series, with the variables in columns and the time steps in
rows.
"""
if not timefile.is_file():
return None
data = pd.read_csv(timefile, delim_whitespace=True, dtype=str,
header=None, skiprows=1, index_col=0,
engine='c', memory_map=True,
error_bad_lines=False, warn_bad_lines=False)
data = data.apply(pd.to_numeric, raw=True, errors='coerce')
# detect useless lines produced when run is restarted
rows_to_del = []
irow = len(data) - 1
while irow > 0:
iprev = irow - 1
while iprev >= 0 and data.index[irow] <= data.index[iprev]:
rows_to_del.append(iprev)
iprev -= 1
irow = iprev
if rows_to_del:
rows_to_keep = set(range(len(data))) - set(rows_to_del)
data = data.take(list(rows_to_keep), convert=False)
ncols = data.shape[1]
_tidy_names(colnames, ncols)
data.columns = colnames
return data | [
"def",
"time_series",
"(",
"timefile",
",",
"colnames",
")",
":",
"if",
"not",
"timefile",
".",
"is_file",
"(",
")",
":",
"return",
"None",
"data",
"=",
"pd",
".",
"read_csv",
"(",
"timefile",
",",
"delim_whitespace",
"=",
"True",
",",
"dtype",
"=",
"s... | Read temporal series text file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional numeric column names from 0 to N-1 will be attributed to the N
extra columns present in :data:`timefile`.
Args:
timefile (:class:`pathlib.Path`): path of the time.dat file.
colnames (list of names): names of the variables expected in
:data:`timefile` (may be modified).
Returns:
:class:`pandas.DataFrame`:
Time series, with the variables in columns and the time steps in
rows. | [
"Read",
"temporal",
"series",
"text",
"file",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L38-L80 | train | 42,234 |
StagPython/StagPy | stagpy/stagyyparsers.py | time_series_h5 | def time_series_h5(timefile, colnames):
"""Read temporal series HDF5 file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional column names will be deduced from the content of the file.
Args:
timefile (:class:`pathlib.Path`): path of the TimeSeries.h5 file.
colnames (list of names): names of the variables expected in
:data:`timefile` (may be modified).
Returns:
:class:`pandas.DataFrame`:
Time series, with the variables in columns and the time steps in
rows.
"""
if not timefile.is_file():
return None
with h5py.File(timefile, 'r') as h5f:
dset = h5f['tseries']
_, ncols = dset.shape
ncols -= 1 # first is istep
h5names = map(bytes.decode, h5f['names'][len(colnames) + 1:])
_tidy_names(colnames, ncols, h5names)
data = dset[()]
return pd.DataFrame(data[:, 1:],
index=np.int_(data[:, 0]), columns=colnames) | python | def time_series_h5(timefile, colnames):
"""Read temporal series HDF5 file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional column names will be deduced from the content of the file.
Args:
timefile (:class:`pathlib.Path`): path of the TimeSeries.h5 file.
colnames (list of names): names of the variables expected in
:data:`timefile` (may be modified).
Returns:
:class:`pandas.DataFrame`:
Time series, with the variables in columns and the time steps in
rows.
"""
if not timefile.is_file():
return None
with h5py.File(timefile, 'r') as h5f:
dset = h5f['tseries']
_, ncols = dset.shape
ncols -= 1 # first is istep
h5names = map(bytes.decode, h5f['names'][len(colnames) + 1:])
_tidy_names(colnames, ncols, h5names)
data = dset[()]
return pd.DataFrame(data[:, 1:],
index=np.int_(data[:, 0]), columns=colnames) | [
"def",
"time_series_h5",
"(",
"timefile",
",",
"colnames",
")",
":",
"if",
"not",
"timefile",
".",
"is_file",
"(",
")",
":",
"return",
"None",
"with",
"h5py",
".",
"File",
"(",
"timefile",
",",
"'r'",
")",
"as",
"h5f",
":",
"dset",
"=",
"h5f",
"[",
... | Read temporal series HDF5 file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional column names will be deduced from the content of the file.
Args:
timefile (:class:`pathlib.Path`): path of the TimeSeries.h5 file.
colnames (list of names): names of the variables expected in
:data:`timefile` (may be modified).
Returns:
:class:`pandas.DataFrame`:
Time series, with the variables in columns and the time steps in
rows. | [
"Read",
"temporal",
"series",
"HDF5",
"file",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L83-L109 | train | 42,235 |
StagPython/StagPy | stagpy/stagyyparsers.py | _extract_rsnap_isteps | def _extract_rsnap_isteps(rproffile):
"""Extract istep and compute list of rows to delete"""
step_regex = re.compile(r'^\*+step:\s*(\d+) ; time =\s*(\S+)')
isteps = [] # list of (istep, time, nz)
rows_to_del = set()
line = ' '
with rproffile.open() as stream:
while line[0] != '*':
line = stream.readline()
match = step_regex.match(line)
istep = int(match.group(1))
time = float(match.group(2))
nlines = 0
iline = 0
for line in stream:
if line[0] == '*':
isteps.append((istep, time, nlines))
match = step_regex.match(line)
istep = int(match.group(1))
time = float(match.group(2))
nlines = 0
# remove useless lines produced when run is restarted
nrows_to_del = 0
while isteps and istep <= isteps[-1][0]:
nrows_to_del += isteps.pop()[-1]
rows_to_del = rows_to_del.union(
range(iline - nrows_to_del, iline))
else:
nlines += 1
iline += 1
isteps.append((istep, time, nlines))
return isteps, rows_to_del | python | def _extract_rsnap_isteps(rproffile):
"""Extract istep and compute list of rows to delete"""
step_regex = re.compile(r'^\*+step:\s*(\d+) ; time =\s*(\S+)')
isteps = [] # list of (istep, time, nz)
rows_to_del = set()
line = ' '
with rproffile.open() as stream:
while line[0] != '*':
line = stream.readline()
match = step_regex.match(line)
istep = int(match.group(1))
time = float(match.group(2))
nlines = 0
iline = 0
for line in stream:
if line[0] == '*':
isteps.append((istep, time, nlines))
match = step_regex.match(line)
istep = int(match.group(1))
time = float(match.group(2))
nlines = 0
# remove useless lines produced when run is restarted
nrows_to_del = 0
while isteps and istep <= isteps[-1][0]:
nrows_to_del += isteps.pop()[-1]
rows_to_del = rows_to_del.union(
range(iline - nrows_to_del, iline))
else:
nlines += 1
iline += 1
isteps.append((istep, time, nlines))
return isteps, rows_to_del | [
"def",
"_extract_rsnap_isteps",
"(",
"rproffile",
")",
":",
"step_regex",
"=",
"re",
".",
"compile",
"(",
"r'^\\*+step:\\s*(\\d+) ; time =\\s*(\\S+)'",
")",
"isteps",
"=",
"[",
"]",
"# list of (istep, time, nz)",
"rows_to_del",
"=",
"set",
"(",
")",
"line",
"=",
"... | Extract istep and compute list of rows to delete | [
"Extract",
"istep",
"and",
"compute",
"list",
"of",
"rows",
"to",
"delete"
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L112-L143 | train | 42,236 |
StagPython/StagPy | stagpy/stagyyparsers.py | _readbin | def _readbin(fid, fmt='i', nwords=1, file64=False, unpack=True):
"""Read n words of 4 or 8 bytes with fmt format.
fmt: 'i' or 'f' or 'b' (integer or float or bytes)
4 or 8 bytes: depends on header
Return an array of elements if more than one element.
Default: read 1 word formatted as an integer.
"""
if fmt in 'if':
fmt += '8' if file64 else '4'
elts = np.fromfile(fid, fmt, nwords)
if unpack and len(elts) == 1:
elts = elts[0]
return elts | python | def _readbin(fid, fmt='i', nwords=1, file64=False, unpack=True):
"""Read n words of 4 or 8 bytes with fmt format.
fmt: 'i' or 'f' or 'b' (integer or float or bytes)
4 or 8 bytes: depends on header
Return an array of elements if more than one element.
Default: read 1 word formatted as an integer.
"""
if fmt in 'if':
fmt += '8' if file64 else '4'
elts = np.fromfile(fid, fmt, nwords)
if unpack and len(elts) == 1:
elts = elts[0]
return elts | [
"def",
"_readbin",
"(",
"fid",
",",
"fmt",
"=",
"'i'",
",",
"nwords",
"=",
"1",
",",
"file64",
"=",
"False",
",",
"unpack",
"=",
"True",
")",
":",
"if",
"fmt",
"in",
"'if'",
":",
"fmt",
"+=",
"'8'",
"if",
"file64",
"else",
"'4'",
"elts",
"=",
"... | Read n words of 4 or 8 bytes with fmt format.
fmt: 'i' or 'f' or 'b' (integer or float or bytes)
4 or 8 bytes: depends on header
Return an array of elements if more than one element.
Default: read 1 word formatted as an integer. | [
"Read",
"n",
"words",
"of",
"4",
"or",
"8",
"bytes",
"with",
"fmt",
"format",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L241-L256 | train | 42,237 |
StagPython/StagPy | stagpy/stagyyparsers.py | tracers | def tracers(tracersfile):
"""Extract tracers data.
Args:
tracersfile (:class:`pathlib.Path`): path of the binary tracers file.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block.
"""
if not tracersfile.is_file():
return None
tra = {}
with tracersfile.open('rb') as fid:
readbin = partial(_readbin, fid)
magic = readbin()
if magic > 8000: # 64 bits
magic -= 8000
readbin()
readbin = partial(readbin, file64=True)
if magic < 100:
raise ParsingError(tracersfile,
'magic > 100 expected to get tracervar info')
nblk = magic % 100
readbin('f', 2) # aspect ratio
readbin() # istep
readbin('f') # time
ninfo = readbin()
ntra = readbin(nwords=nblk, unpack=False)
readbin('f') # tracer ideal mass
curv = readbin()
if curv:
readbin('f') # r_cmb
infos = [] # list of info names
for _ in range(ninfo):
infos.append(b''.join(readbin('b', 16)).strip().decode())
tra[infos[-1]] = []
if magic > 200:
ntrace_elt = readbin()
if ntrace_elt > 0:
readbin('f', ntrace_elt) # outgassed
for ntrab in ntra: # blocks
data = readbin('f', ntrab * ninfo)
for idx, info in enumerate(infos):
tra[info].append(data[idx::ninfo])
return tra | python | def tracers(tracersfile):
"""Extract tracers data.
Args:
tracersfile (:class:`pathlib.Path`): path of the binary tracers file.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block.
"""
if not tracersfile.is_file():
return None
tra = {}
with tracersfile.open('rb') as fid:
readbin = partial(_readbin, fid)
magic = readbin()
if magic > 8000: # 64 bits
magic -= 8000
readbin()
readbin = partial(readbin, file64=True)
if magic < 100:
raise ParsingError(tracersfile,
'magic > 100 expected to get tracervar info')
nblk = magic % 100
readbin('f', 2) # aspect ratio
readbin() # istep
readbin('f') # time
ninfo = readbin()
ntra = readbin(nwords=nblk, unpack=False)
readbin('f') # tracer ideal mass
curv = readbin()
if curv:
readbin('f') # r_cmb
infos = [] # list of info names
for _ in range(ninfo):
infos.append(b''.join(readbin('b', 16)).strip().decode())
tra[infos[-1]] = []
if magic > 200:
ntrace_elt = readbin()
if ntrace_elt > 0:
readbin('f', ntrace_elt) # outgassed
for ntrab in ntra: # blocks
data = readbin('f', ntrab * ninfo)
for idx, info in enumerate(infos):
tra[info].append(data[idx::ninfo])
return tra | [
"def",
"tracers",
"(",
"tracersfile",
")",
":",
"if",
"not",
"tracersfile",
".",
"is_file",
"(",
")",
":",
"return",
"None",
"tra",
"=",
"{",
"}",
"with",
"tracersfile",
".",
"open",
"(",
"'rb'",
")",
"as",
"fid",
":",
"readbin",
"=",
"partial",
"(",... | Extract tracers data.
Args:
tracersfile (:class:`pathlib.Path`): path of the binary tracers file.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block. | [
"Extract",
"tracers",
"data",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L389-L434 | train | 42,238 |
StagPython/StagPy | stagpy/stagyyparsers.py | _read_group_h5 | def _read_group_h5(filename, groupname):
"""Return group content.
Args:
filename (:class:`pathlib.Path`): path of hdf5 file.
groupname (str): name of group to read.
Returns:
:class:`numpy.array`: content of group.
"""
with h5py.File(filename, 'r') as h5f:
data = h5f[groupname][()]
return data | python | def _read_group_h5(filename, groupname):
"""Return group content.
Args:
filename (:class:`pathlib.Path`): path of hdf5 file.
groupname (str): name of group to read.
Returns:
:class:`numpy.array`: content of group.
"""
with h5py.File(filename, 'r') as h5f:
data = h5f[groupname][()]
return data | [
"def",
"_read_group_h5",
"(",
"filename",
",",
"groupname",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'r'",
")",
"as",
"h5f",
":",
"data",
"=",
"h5f",
"[",
"groupname",
"]",
"[",
"(",
")",
"]",
"return",
"data"
] | Return group content.
Args:
filename (:class:`pathlib.Path`): path of hdf5 file.
groupname (str): name of group to read.
Returns:
:class:`numpy.array`: content of group. | [
"Return",
"group",
"content",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L437-L448 | train | 42,239 |
StagPython/StagPy | stagpy/stagyyparsers.py | _make_3d | def _make_3d(field, twod):
"""Add a dimension to field if necessary.
Args:
field (numpy.array): the field that need to be 3d.
twod (str): 'XZ', 'YZ' or None depending on what is relevant.
Returns:
numpy.array: reshaped field.
"""
shp = list(field.shape)
if twod and 'X' in twod:
shp.insert(1, 1)
elif twod:
shp.insert(0, 1)
return field.reshape(shp) | python | def _make_3d(field, twod):
"""Add a dimension to field if necessary.
Args:
field (numpy.array): the field that need to be 3d.
twod (str): 'XZ', 'YZ' or None depending on what is relevant.
Returns:
numpy.array: reshaped field.
"""
shp = list(field.shape)
if twod and 'X' in twod:
shp.insert(1, 1)
elif twod:
shp.insert(0, 1)
return field.reshape(shp) | [
"def",
"_make_3d",
"(",
"field",
",",
"twod",
")",
":",
"shp",
"=",
"list",
"(",
"field",
".",
"shape",
")",
"if",
"twod",
"and",
"'X'",
"in",
"twod",
":",
"shp",
".",
"insert",
"(",
"1",
",",
"1",
")",
"elif",
"twod",
":",
"shp",
".",
"insert"... | Add a dimension to field if necessary.
Args:
field (numpy.array): the field that need to be 3d.
twod (str): 'XZ', 'YZ' or None depending on what is relevant.
Returns:
numpy.array: reshaped field. | [
"Add",
"a",
"dimension",
"to",
"field",
"if",
"necessary",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L451-L465 | train | 42,240 |
StagPython/StagPy | stagpy/stagyyparsers.py | _ncores | def _ncores(meshes, twod):
"""Compute number of nodes in each direction."""
nnpb = len(meshes) # number of nodes per block
nns = [1, 1, 1] # number of nodes in x, y, z directions
if twod is None or 'X' in twod:
while (nnpb > 1 and
meshes[nns[0]]['X'][0, 0, 0] ==
meshes[nns[0] - 1]['X'][-1, 0, 0]):
nns[0] += 1
nnpb -= 1
cpu = lambda icy: icy * nns[0]
if twod is None or 'Y' in twod:
while (nnpb > 1 and
meshes[cpu(nns[1])]['Y'][0, 0, 0] ==
meshes[cpu(nns[1] - 1)]['Y'][0, -1, 0]):
nns[1] += 1
nnpb -= nns[0]
cpu = lambda icz: icz * nns[0] * nns[1]
while (nnpb > 1 and
meshes[cpu(nns[2])]['Z'][0, 0, 0] ==
meshes[cpu(nns[2] - 1)]['Z'][0, 0, -1]):
nns[2] += 1
nnpb -= nns[0] * nns[1]
return np.array(nns) | python | def _ncores(meshes, twod):
"""Compute number of nodes in each direction."""
nnpb = len(meshes) # number of nodes per block
nns = [1, 1, 1] # number of nodes in x, y, z directions
if twod is None or 'X' in twod:
while (nnpb > 1 and
meshes[nns[0]]['X'][0, 0, 0] ==
meshes[nns[0] - 1]['X'][-1, 0, 0]):
nns[0] += 1
nnpb -= 1
cpu = lambda icy: icy * nns[0]
if twod is None or 'Y' in twod:
while (nnpb > 1 and
meshes[cpu(nns[1])]['Y'][0, 0, 0] ==
meshes[cpu(nns[1] - 1)]['Y'][0, -1, 0]):
nns[1] += 1
nnpb -= nns[0]
cpu = lambda icz: icz * nns[0] * nns[1]
while (nnpb > 1 and
meshes[cpu(nns[2])]['Z'][0, 0, 0] ==
meshes[cpu(nns[2] - 1)]['Z'][0, 0, -1]):
nns[2] += 1
nnpb -= nns[0] * nns[1]
return np.array(nns) | [
"def",
"_ncores",
"(",
"meshes",
",",
"twod",
")",
":",
"nnpb",
"=",
"len",
"(",
"meshes",
")",
"# number of nodes per block",
"nns",
"=",
"[",
"1",
",",
"1",
",",
"1",
"]",
"# number of nodes in x, y, z directions",
"if",
"twod",
"is",
"None",
"or",
"'X'"... | Compute number of nodes in each direction. | [
"Compute",
"number",
"of",
"nodes",
"in",
"each",
"direction",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L468-L491 | train | 42,241 |
StagPython/StagPy | stagpy/stagyyparsers.py | _conglomerate_meshes | def _conglomerate_meshes(meshin, header):
"""Conglomerate meshes from several cores into one."""
meshout = {}
npc = header['nts'] // header['ncs']
shp = [val + 1 if val != 1 else 1 for val in header['nts']]
x_p = int(shp[0] != 1)
y_p = int(shp[1] != 1)
for coord in meshin[0]:
meshout[coord] = np.zeros(shp)
for icore in range(np.prod(header['ncs'])):
ifs = [icore // np.prod(header['ncs'][:i]) % header['ncs'][i] * npc[i]
for i in range(3)]
for coord, mesh in meshin[icore].items():
meshout[coord][ifs[0]:ifs[0] + npc[0] + x_p,
ifs[1]:ifs[1] + npc[1] + y_p,
ifs[2]:ifs[2] + npc[2] + 1] = mesh
return meshout | python | def _conglomerate_meshes(meshin, header):
"""Conglomerate meshes from several cores into one."""
meshout = {}
npc = header['nts'] // header['ncs']
shp = [val + 1 if val != 1 else 1 for val in header['nts']]
x_p = int(shp[0] != 1)
y_p = int(shp[1] != 1)
for coord in meshin[0]:
meshout[coord] = np.zeros(shp)
for icore in range(np.prod(header['ncs'])):
ifs = [icore // np.prod(header['ncs'][:i]) % header['ncs'][i] * npc[i]
for i in range(3)]
for coord, mesh in meshin[icore].items():
meshout[coord][ifs[0]:ifs[0] + npc[0] + x_p,
ifs[1]:ifs[1] + npc[1] + y_p,
ifs[2]:ifs[2] + npc[2] + 1] = mesh
return meshout | [
"def",
"_conglomerate_meshes",
"(",
"meshin",
",",
"header",
")",
":",
"meshout",
"=",
"{",
"}",
"npc",
"=",
"header",
"[",
"'nts'",
"]",
"//",
"header",
"[",
"'ncs'",
"]",
"shp",
"=",
"[",
"val",
"+",
"1",
"if",
"val",
"!=",
"1",
"else",
"1",
"f... | Conglomerate meshes from several cores into one. | [
"Conglomerate",
"meshes",
"from",
"several",
"cores",
"into",
"one",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L494-L510 | train | 42,242 |
StagPython/StagPy | stagpy/stagyyparsers.py | _get_field | def _get_field(xdmf_file, data_item):
"""Extract field from data item."""
shp = _get_dim(data_item)
h5file, group = data_item.text.strip().split(':/', 1)
icore = int(group.split('_')[-2]) - 1
fld = _read_group_h5(xdmf_file.parent / h5file, group).reshape(shp)
return icore, fld | python | def _get_field(xdmf_file, data_item):
"""Extract field from data item."""
shp = _get_dim(data_item)
h5file, group = data_item.text.strip().split(':/', 1)
icore = int(group.split('_')[-2]) - 1
fld = _read_group_h5(xdmf_file.parent / h5file, group).reshape(shp)
return icore, fld | [
"def",
"_get_field",
"(",
"xdmf_file",
",",
"data_item",
")",
":",
"shp",
"=",
"_get_dim",
"(",
"data_item",
")",
"h5file",
",",
"group",
"=",
"data_item",
".",
"text",
".",
"strip",
"(",
")",
".",
"split",
"(",
"':/'",
",",
"1",
")",
"icore",
"=",
... | Extract field from data item. | [
"Extract",
"field",
"from",
"data",
"item",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L576-L582 | train | 42,243 |
StagPython/StagPy | stagpy/stagyyparsers.py | _maybe_get | def _maybe_get(elt, item, info, conversion=None):
"""Extract and convert info if item is present."""
maybe_item = elt.find(item)
if maybe_item is not None:
maybe_item = maybe_item.get(info)
if conversion is not None:
maybe_item = conversion(maybe_item)
return maybe_item | python | def _maybe_get(elt, item, info, conversion=None):
"""Extract and convert info if item is present."""
maybe_item = elt.find(item)
if maybe_item is not None:
maybe_item = maybe_item.get(info)
if conversion is not None:
maybe_item = conversion(maybe_item)
return maybe_item | [
"def",
"_maybe_get",
"(",
"elt",
",",
"item",
",",
"info",
",",
"conversion",
"=",
"None",
")",
":",
"maybe_item",
"=",
"elt",
".",
"find",
"(",
"item",
")",
"if",
"maybe_item",
"is",
"not",
"None",
":",
"maybe_item",
"=",
"maybe_item",
".",
"get",
"... | Extract and convert info if item is present. | [
"Extract",
"and",
"convert",
"info",
"if",
"item",
"is",
"present",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L585-L592 | train | 42,244 |
StagPython/StagPy | stagpy/stagyyparsers.py | read_geom_h5 | def read_geom_h5(xdmf_file, snapshot):
"""Extract geometry information from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
snapshot (int): snapshot number.
Returns:
(dict, root): geometry information and root of xdmf document.
"""
header = {}
xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
if snapshot is None:
return None, xdmf_root
# Domain, Temporal Collection, Snapshot
# should check that this is indeed the required snapshot
elt_snap = xdmf_root[0][0][snapshot]
header['ti_ad'] = float(elt_snap.find('Time').get('Value'))
header['mo_lambda'] = _maybe_get(elt_snap, 'mo_lambda', 'Value', float)
header['mo_thick_sol'] = _maybe_get(elt_snap, 'mo_thick_sol', 'Value',
float)
header['ntb'] = 1
coord_h5 = [] # all the coordinate files
coord_shape = [] # shape of meshes
twod = None
for elt_subdomain in elt_snap.findall('Grid'):
if elt_subdomain.get('Name').startswith('meshYang'):
header['ntb'] = 2
break # iterate only through meshYin
elt_geom = elt_subdomain.find('Geometry')
if elt_geom.get('Type') == 'X_Y' and twod is None:
twod = ''
for data_item in elt_geom.findall('DataItem'):
coord = data_item.text.strip()[-1]
if coord in 'XYZ':
twod += coord
data_item = elt_geom.find('DataItem')
coord_shape.append(_get_dim(data_item))
coord_h5.append(
xdmf_file.parent / data_item.text.strip().split(':/', 1)[0])
_read_coord_h5(coord_h5, coord_shape, header, twod)
return header, xdmf_root | python | def read_geom_h5(xdmf_file, snapshot):
"""Extract geometry information from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
snapshot (int): snapshot number.
Returns:
(dict, root): geometry information and root of xdmf document.
"""
header = {}
xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
if snapshot is None:
return None, xdmf_root
# Domain, Temporal Collection, Snapshot
# should check that this is indeed the required snapshot
elt_snap = xdmf_root[0][0][snapshot]
header['ti_ad'] = float(elt_snap.find('Time').get('Value'))
header['mo_lambda'] = _maybe_get(elt_snap, 'mo_lambda', 'Value', float)
header['mo_thick_sol'] = _maybe_get(elt_snap, 'mo_thick_sol', 'Value',
float)
header['ntb'] = 1
coord_h5 = [] # all the coordinate files
coord_shape = [] # shape of meshes
twod = None
for elt_subdomain in elt_snap.findall('Grid'):
if elt_subdomain.get('Name').startswith('meshYang'):
header['ntb'] = 2
break # iterate only through meshYin
elt_geom = elt_subdomain.find('Geometry')
if elt_geom.get('Type') == 'X_Y' and twod is None:
twod = ''
for data_item in elt_geom.findall('DataItem'):
coord = data_item.text.strip()[-1]
if coord in 'XYZ':
twod += coord
data_item = elt_geom.find('DataItem')
coord_shape.append(_get_dim(data_item))
coord_h5.append(
xdmf_file.parent / data_item.text.strip().split(':/', 1)[0])
_read_coord_h5(coord_h5, coord_shape, header, twod)
return header, xdmf_root | [
"def",
"read_geom_h5",
"(",
"xdmf_file",
",",
"snapshot",
")",
":",
"header",
"=",
"{",
"}",
"xdmf_root",
"=",
"xmlET",
".",
"parse",
"(",
"str",
"(",
"xdmf_file",
")",
")",
".",
"getroot",
"(",
")",
"if",
"snapshot",
"is",
"None",
":",
"return",
"No... | Extract geometry information from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
snapshot (int): snapshot number.
Returns:
(dict, root): geometry information and root of xdmf document. | [
"Extract",
"geometry",
"information",
"from",
"hdf5",
"files",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L595-L636 | train | 42,245 |
StagPython/StagPy | stagpy/stagyyparsers.py | _to_spherical | def _to_spherical(flds, header):
"""Convert vector field to spherical."""
cth = np.cos(header['t_mesh'][:, :, :-1])
sth = np.sin(header['t_mesh'][:, :, :-1])
cph = np.cos(header['p_mesh'][:, :, :-1])
sph = np.sin(header['p_mesh'][:, :, :-1])
fout = np.copy(flds)
fout[0] = cth * cph * flds[0] + cth * sph * flds[1] - sth * flds[2]
fout[1] = sph * flds[0] - cph * flds[1] # need to take the opposite here
fout[2] = sth * cph * flds[0] + sth * sph * flds[1] + cth * flds[2]
return fout | python | def _to_spherical(flds, header):
"""Convert vector field to spherical."""
cth = np.cos(header['t_mesh'][:, :, :-1])
sth = np.sin(header['t_mesh'][:, :, :-1])
cph = np.cos(header['p_mesh'][:, :, :-1])
sph = np.sin(header['p_mesh'][:, :, :-1])
fout = np.copy(flds)
fout[0] = cth * cph * flds[0] + cth * sph * flds[1] - sth * flds[2]
fout[1] = sph * flds[0] - cph * flds[1] # need to take the opposite here
fout[2] = sth * cph * flds[0] + sth * sph * flds[1] + cth * flds[2]
return fout | [
"def",
"_to_spherical",
"(",
"flds",
",",
"header",
")",
":",
"cth",
"=",
"np",
".",
"cos",
"(",
"header",
"[",
"'t_mesh'",
"]",
"[",
":",
",",
":",
",",
":",
"-",
"1",
"]",
")",
"sth",
"=",
"np",
".",
"sin",
"(",
"header",
"[",
"'t_mesh'",
"... | Convert vector field to spherical. | [
"Convert",
"vector",
"field",
"to",
"spherical",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L639-L649 | train | 42,246 |
StagPython/StagPy | stagpy/stagyyparsers.py | _flds_shape | def _flds_shape(fieldname, header):
"""Compute shape of flds variable."""
shp = list(header['nts'])
shp.append(header['ntb'])
# probably a better way to handle this
if fieldname == 'Velocity':
shp.insert(0, 3)
# extra points
header['xp'] = int(header['nts'][0] != 1)
shp[1] += header['xp']
header['yp'] = int(header['nts'][1] != 1)
shp[2] += header['yp']
header['zp'] = 1
header['xyp'] = 1
else:
shp.insert(0, 1)
header['xp'] = 0
header['yp'] = 0
header['zp'] = 0
header['xyp'] = 0
return shp | python | def _flds_shape(fieldname, header):
"""Compute shape of flds variable."""
shp = list(header['nts'])
shp.append(header['ntb'])
# probably a better way to handle this
if fieldname == 'Velocity':
shp.insert(0, 3)
# extra points
header['xp'] = int(header['nts'][0] != 1)
shp[1] += header['xp']
header['yp'] = int(header['nts'][1] != 1)
shp[2] += header['yp']
header['zp'] = 1
header['xyp'] = 1
else:
shp.insert(0, 1)
header['xp'] = 0
header['yp'] = 0
header['zp'] = 0
header['xyp'] = 0
return shp | [
"def",
"_flds_shape",
"(",
"fieldname",
",",
"header",
")",
":",
"shp",
"=",
"list",
"(",
"header",
"[",
"'nts'",
"]",
")",
"shp",
".",
"append",
"(",
"header",
"[",
"'ntb'",
"]",
")",
"# probably a better way to handle this",
"if",
"fieldname",
"==",
"'Ve... | Compute shape of flds variable. | [
"Compute",
"shape",
"of",
"flds",
"variable",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L652-L672 | train | 42,247 |
StagPython/StagPy | stagpy/stagyyparsers.py | _post_read_flds | def _post_read_flds(flds, header):
"""Process flds to handle sphericity."""
if flds.shape[0] >= 3 and header['rcmb'] > 0:
# spherical vector
header['p_mesh'] = np.roll(
np.arctan2(header['y_mesh'], header['x_mesh']), -1, 1)
for ibk in range(header['ntb']):
flds[..., ibk] = _to_spherical(flds[..., ibk], header)
header['p_mesh'] = np.roll(
np.arctan2(header['y_mesh'], -header['x_mesh']) + np.pi, -1, 1)
return flds | python | def _post_read_flds(flds, header):
"""Process flds to handle sphericity."""
if flds.shape[0] >= 3 and header['rcmb'] > 0:
# spherical vector
header['p_mesh'] = np.roll(
np.arctan2(header['y_mesh'], header['x_mesh']), -1, 1)
for ibk in range(header['ntb']):
flds[..., ibk] = _to_spherical(flds[..., ibk], header)
header['p_mesh'] = np.roll(
np.arctan2(header['y_mesh'], -header['x_mesh']) + np.pi, -1, 1)
return flds | [
"def",
"_post_read_flds",
"(",
"flds",
",",
"header",
")",
":",
"if",
"flds",
".",
"shape",
"[",
"0",
"]",
">=",
"3",
"and",
"header",
"[",
"'rcmb'",
"]",
">",
"0",
":",
"# spherical vector",
"header",
"[",
"'p_mesh'",
"]",
"=",
"np",
".",
"roll",
... | Process flds to handle sphericity. | [
"Process",
"flds",
"to",
"handle",
"sphericity",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L675-L685 | train | 42,248 |
StagPython/StagPy | stagpy/stagyyparsers.py | read_field_h5 | def read_field_h5(xdmf_file, fieldname, snapshot, header=None):
"""Extract field data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
fieldname (str): name of field to extract.
snapshot (int): snapshot number.
header (dict): geometry information.
Returns:
(dict, numpy.array): geometry information and field data. None
is returned if data is unavailable.
"""
if header is None:
header, xdmf_root = read_geom_h5(xdmf_file, snapshot)
else:
xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
npc = header['nts'] // header['ncs'] # number of grid point per node
flds = np.zeros(_flds_shape(fieldname, header))
data_found = False
for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):
ibk = int(elt_subdomain.get('Name').startswith('meshYang'))
for data_attr in elt_subdomain.findall('Attribute'):
if data_attr.get('Name') != fieldname:
continue
icore, fld = _get_field(xdmf_file, data_attr.find('DataItem'))
# for some reason, the field is transposed
fld = fld.T
shp = fld.shape
if shp[-1] == 1 and header['nts'][0] == 1: # YZ
fld = fld.reshape((shp[0], 1, shp[1], shp[2]))
if header['rcmb'] < 0:
fld = fld[(2, 0, 1), ...]
elif shp[-1] == 1: # XZ
fld = fld.reshape((shp[0], shp[1], 1, shp[2]))
if header['rcmb'] < 0:
fld = fld[(0, 2, 1), ...]
elif header['nts'][1] == 1: # cart XZ
fld = fld.reshape((1, shp[0], 1, shp[1]))
ifs = [icore // np.prod(header['ncs'][:i]) % header['ncs'][i] *
npc[i] for i in range(3)]
if header['zp']: # remove top row
fld = fld[:, :, :, :-1]
flds[:,
ifs[0]:ifs[0] + npc[0] + header['xp'],
ifs[1]:ifs[1] + npc[1] + header['yp'],
ifs[2]:ifs[2] + npc[2],
ibk] = fld
data_found = True
flds = _post_read_flds(flds, header)
return (header, flds) if data_found else None | python | def read_field_h5(xdmf_file, fieldname, snapshot, header=None):
"""Extract field data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
fieldname (str): name of field to extract.
snapshot (int): snapshot number.
header (dict): geometry information.
Returns:
(dict, numpy.array): geometry information and field data. None
is returned if data is unavailable.
"""
if header is None:
header, xdmf_root = read_geom_h5(xdmf_file, snapshot)
else:
xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
npc = header['nts'] // header['ncs'] # number of grid point per node
flds = np.zeros(_flds_shape(fieldname, header))
data_found = False
for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):
ibk = int(elt_subdomain.get('Name').startswith('meshYang'))
for data_attr in elt_subdomain.findall('Attribute'):
if data_attr.get('Name') != fieldname:
continue
icore, fld = _get_field(xdmf_file, data_attr.find('DataItem'))
# for some reason, the field is transposed
fld = fld.T
shp = fld.shape
if shp[-1] == 1 and header['nts'][0] == 1: # YZ
fld = fld.reshape((shp[0], 1, shp[1], shp[2]))
if header['rcmb'] < 0:
fld = fld[(2, 0, 1), ...]
elif shp[-1] == 1: # XZ
fld = fld.reshape((shp[0], shp[1], 1, shp[2]))
if header['rcmb'] < 0:
fld = fld[(0, 2, 1), ...]
elif header['nts'][1] == 1: # cart XZ
fld = fld.reshape((1, shp[0], 1, shp[1]))
ifs = [icore // np.prod(header['ncs'][:i]) % header['ncs'][i] *
npc[i] for i in range(3)]
if header['zp']: # remove top row
fld = fld[:, :, :, :-1]
flds[:,
ifs[0]:ifs[0] + npc[0] + header['xp'],
ifs[1]:ifs[1] + npc[1] + header['yp'],
ifs[2]:ifs[2] + npc[2],
ibk] = fld
data_found = True
flds = _post_read_flds(flds, header)
return (header, flds) if data_found else None | [
"def",
"read_field_h5",
"(",
"xdmf_file",
",",
"fieldname",
",",
"snapshot",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
",",
"xdmf_root",
"=",
"read_geom_h5",
"(",
"xdmf_file",
",",
"snapshot",
")",
"else",
":",
"x... | Extract field data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
fieldname (str): name of field to extract.
snapshot (int): snapshot number.
header (dict): geometry information.
Returns:
(dict, numpy.array): geometry information and field data. None
is returned if data is unavailable. | [
"Extract",
"field",
"data",
"from",
"hdf5",
"files",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L688-L741 | train | 42,249 |
StagPython/StagPy | stagpy/stagyyparsers.py | read_tracers_h5 | def read_tracers_h5(xdmf_file, infoname, snapshot, position):
"""Extract tracers data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
infoname (str): name of information to extract.
snapshot (int): snapshot number.
position (bool): whether to extract position of tracers.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block.
"""
xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
tra = {}
tra[infoname] = [{}, {}] # two blocks, ordered by cores
if position:
for axis in 'xyz':
tra[axis] = [{}, {}]
for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):
ibk = int(elt_subdomain.get('Name').startswith('meshYang'))
if position:
for data_attr in elt_subdomain.findall('Geometry'):
for data_item, axis in zip(data_attr.findall('DataItem'),
'xyz'):
icore, data = _get_field(xdmf_file, data_item)
tra[axis][ibk][icore] = data
for data_attr in elt_subdomain.findall('Attribute'):
if data_attr.get('Name') != infoname:
continue
icore, data = _get_field(xdmf_file, data_attr.find('DataItem'))
tra[infoname][ibk][icore] = data
for info in tra:
tra[info] = [trab for trab in tra[info] if trab] # remove empty blocks
for iblk, trab in enumerate(tra[info]):
tra[info][iblk] = np.concatenate([trab[icore]
for icore in range(len(trab))])
return tra | python | def read_tracers_h5(xdmf_file, infoname, snapshot, position):
"""Extract tracers data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
infoname (str): name of information to extract.
snapshot (int): snapshot number.
position (bool): whether to extract position of tracers.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block.
"""
xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
tra = {}
tra[infoname] = [{}, {}] # two blocks, ordered by cores
if position:
for axis in 'xyz':
tra[axis] = [{}, {}]
for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):
ibk = int(elt_subdomain.get('Name').startswith('meshYang'))
if position:
for data_attr in elt_subdomain.findall('Geometry'):
for data_item, axis in zip(data_attr.findall('DataItem'),
'xyz'):
icore, data = _get_field(xdmf_file, data_item)
tra[axis][ibk][icore] = data
for data_attr in elt_subdomain.findall('Attribute'):
if data_attr.get('Name') != infoname:
continue
icore, data = _get_field(xdmf_file, data_attr.find('DataItem'))
tra[infoname][ibk][icore] = data
for info in tra:
tra[info] = [trab for trab in tra[info] if trab] # remove empty blocks
for iblk, trab in enumerate(tra[info]):
tra[info][iblk] = np.concatenate([trab[icore]
for icore in range(len(trab))])
return tra | [
"def",
"read_tracers_h5",
"(",
"xdmf_file",
",",
"infoname",
",",
"snapshot",
",",
"position",
")",
":",
"xdmf_root",
"=",
"xmlET",
".",
"parse",
"(",
"str",
"(",
"xdmf_file",
")",
")",
".",
"getroot",
"(",
")",
"tra",
"=",
"{",
"}",
"tra",
"[",
"inf... | Extract tracers data from hdf5 files.
Args:
xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
infoname (str): name of information to extract.
snapshot (int): snapshot number.
position (bool): whether to extract position of tracers.
Returns:
dict of list of numpy.array:
Tracers data organized by attribute and block. | [
"Extract",
"tracers",
"data",
"from",
"hdf5",
"files",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/stagyyparsers.py#L744-L780 | train | 42,250 |
StagPython/StagPy | stagpy/_step.py | _Geometry._init_shape | def _init_shape(self):
"""Determine shape of geometry"""
shape = self._par['geometry']['shape'].lower()
aspect = self._header['aspect']
if self.rcmb is not None and self.rcmb >= 0:
# curvilinear
self._shape['cyl'] = self.twod_xz and (shape == 'cylindrical' or
aspect[0] >= np.pi)
self._shape['sph'] = not self._shape['cyl']
elif self.rcmb is None:
self._header['rcmb'] = self._par['geometry']['r_cmb']
if self.rcmb >= 0:
if self.twod_xz and shape == 'cylindrical':
self._shape['cyl'] = True
elif shape == 'spherical':
self._shape['sph'] = True
self._shape['axi'] = self.cartesian and self.twod_xz and \
shape == 'axisymmetric' | python | def _init_shape(self):
"""Determine shape of geometry"""
shape = self._par['geometry']['shape'].lower()
aspect = self._header['aspect']
if self.rcmb is not None and self.rcmb >= 0:
# curvilinear
self._shape['cyl'] = self.twod_xz and (shape == 'cylindrical' or
aspect[0] >= np.pi)
self._shape['sph'] = not self._shape['cyl']
elif self.rcmb is None:
self._header['rcmb'] = self._par['geometry']['r_cmb']
if self.rcmb >= 0:
if self.twod_xz and shape == 'cylindrical':
self._shape['cyl'] = True
elif shape == 'spherical':
self._shape['sph'] = True
self._shape['axi'] = self.cartesian and self.twod_xz and \
shape == 'axisymmetric' | [
"def",
"_init_shape",
"(",
"self",
")",
":",
"shape",
"=",
"self",
".",
"_par",
"[",
"'geometry'",
"]",
"[",
"'shape'",
"]",
".",
"lower",
"(",
")",
"aspect",
"=",
"self",
".",
"_header",
"[",
"'aspect'",
"]",
"if",
"self",
".",
"rcmb",
"is",
"not"... | Determine shape of geometry | [
"Determine",
"shape",
"of",
"geometry"
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/_step.py#L103-L120 | train | 42,251 |
StagPython/StagPy | stagpy/_step.py | _Fields._get_raw_data | def _get_raw_data(self, name):
"""Find file holding data and return its content."""
# try legacy first, then hdf5
filestem = ''
for filestem, list_fvar in self._files.items():
if name in list_fvar:
break
fieldfile = self.step.sdat.filename(filestem, self.step.isnap,
force_legacy=True)
if not fieldfile.is_file():
fieldfile = self.step.sdat.filename(filestem, self.step.isnap)
parsed_data = None
if fieldfile.is_file():
parsed_data = stagyyparsers.fields(fieldfile)
elif self.step.sdat.hdf5 and self._filesh5:
for filestem, list_fvar in self._filesh5.items():
if name in list_fvar:
break
parsed_data = stagyyparsers.read_field_h5(
self.step.sdat.hdf5 / 'Data.xmf', filestem, self.step.isnap)
return list_fvar, parsed_data | python | def _get_raw_data(self, name):
"""Find file holding data and return its content."""
# try legacy first, then hdf5
filestem = ''
for filestem, list_fvar in self._files.items():
if name in list_fvar:
break
fieldfile = self.step.sdat.filename(filestem, self.step.isnap,
force_legacy=True)
if not fieldfile.is_file():
fieldfile = self.step.sdat.filename(filestem, self.step.isnap)
parsed_data = None
if fieldfile.is_file():
parsed_data = stagyyparsers.fields(fieldfile)
elif self.step.sdat.hdf5 and self._filesh5:
for filestem, list_fvar in self._filesh5.items():
if name in list_fvar:
break
parsed_data = stagyyparsers.read_field_h5(
self.step.sdat.hdf5 / 'Data.xmf', filestem, self.step.isnap)
return list_fvar, parsed_data | [
"def",
"_get_raw_data",
"(",
"self",
",",
"name",
")",
":",
"# try legacy first, then hdf5",
"filestem",
"=",
"''",
"for",
"filestem",
",",
"list_fvar",
"in",
"self",
".",
"_files",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"list_fvar",
":",
"break"... | Find file holding data and return its content. | [
"Find",
"file",
"holding",
"data",
"and",
"return",
"its",
"content",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/_step.py#L241-L261 | train | 42,252 |
StagPython/StagPy | stagpy/_step.py | _Fields.geom | def geom(self):
"""Geometry information.
:class:`_Geometry` instance holding geometry information. It is
issued from binary files holding field information. It is set to
None if not available for this time step.
"""
if self._header is UNDETERMINED:
binfiles = self.step.sdat.binfiles_set(self.step.isnap)
if binfiles:
self._header = stagyyparsers.fields(binfiles.pop(),
only_header=True)
elif self.step.sdat.hdf5:
xmf = self.step.sdat.hdf5 / 'Data.xmf'
self._header, _ = stagyyparsers.read_geom_h5(xmf,
self.step.isnap)
else:
self._header = None
if self._geom is UNDETERMINED:
if self._header is None:
self._geom = None
else:
self._geom = _Geometry(self._header, self.step.sdat.par)
return self._geom | python | def geom(self):
"""Geometry information.
:class:`_Geometry` instance holding geometry information. It is
issued from binary files holding field information. It is set to
None if not available for this time step.
"""
if self._header is UNDETERMINED:
binfiles = self.step.sdat.binfiles_set(self.step.isnap)
if binfiles:
self._header = stagyyparsers.fields(binfiles.pop(),
only_header=True)
elif self.step.sdat.hdf5:
xmf = self.step.sdat.hdf5 / 'Data.xmf'
self._header, _ = stagyyparsers.read_geom_h5(xmf,
self.step.isnap)
else:
self._header = None
if self._geom is UNDETERMINED:
if self._header is None:
self._geom = None
else:
self._geom = _Geometry(self._header, self.step.sdat.par)
return self._geom | [
"def",
"geom",
"(",
"self",
")",
":",
"if",
"self",
".",
"_header",
"is",
"UNDETERMINED",
":",
"binfiles",
"=",
"self",
".",
"step",
".",
"sdat",
".",
"binfiles_set",
"(",
"self",
".",
"step",
".",
"isnap",
")",
"if",
"binfiles",
":",
"self",
".",
... | Geometry information.
:class:`_Geometry` instance holding geometry information. It is
issued from binary files holding field information. It is set to
None if not available for this time step. | [
"Geometry",
"information",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/_step.py#L276-L299 | train | 42,253 |
StagPython/StagPy | stagpy/_step.py | Step.timeinfo | def timeinfo(self):
"""Time series data of the time step.
Set to None if no time series data is available for this time step.
"""
if self.istep not in self.sdat.tseries.index:
return None
return self.sdat.tseries.loc[self.istep] | python | def timeinfo(self):
"""Time series data of the time step.
Set to None if no time series data is available for this time step.
"""
if self.istep not in self.sdat.tseries.index:
return None
return self.sdat.tseries.loc[self.istep] | [
"def",
"timeinfo",
"(",
"self",
")",
":",
"if",
"self",
".",
"istep",
"not",
"in",
"self",
".",
"sdat",
".",
"tseries",
".",
"index",
":",
"return",
"None",
"return",
"self",
".",
"sdat",
".",
"tseries",
".",
"loc",
"[",
"self",
".",
"istep",
"]"
] | Time series data of the time step.
Set to None if no time series data is available for this time step. | [
"Time",
"series",
"data",
"of",
"the",
"time",
"step",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/_step.py#L403-L410 | train | 42,254 |
StagPython/StagPy | stagpy/_step.py | Step.rprof | def rprof(self):
"""Radial profiles data of the time step.
Set to None if no radial profiles data is available for this time step.
"""
if self.istep not in self.sdat.rprof.index.levels[0]:
return None
return self.sdat.rprof.loc[self.istep] | python | def rprof(self):
"""Radial profiles data of the time step.
Set to None if no radial profiles data is available for this time step.
"""
if self.istep not in self.sdat.rprof.index.levels[0]:
return None
return self.sdat.rprof.loc[self.istep] | [
"def",
"rprof",
"(",
"self",
")",
":",
"if",
"self",
".",
"istep",
"not",
"in",
"self",
".",
"sdat",
".",
"rprof",
".",
"index",
".",
"levels",
"[",
"0",
"]",
":",
"return",
"None",
"return",
"self",
".",
"sdat",
".",
"rprof",
".",
"loc",
"[",
... | Radial profiles data of the time step.
Set to None if no radial profiles data is available for this time step. | [
"Radial",
"profiles",
"data",
"of",
"the",
"time",
"step",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/_step.py#L413-L420 | train | 42,255 |
StagPython/StagPy | stagpy/_step.py | Step.isnap | def isnap(self):
"""Snapshot index corresponding to time step.
It is set to None if no snapshot exists for the time step.
"""
if self._isnap is UNDETERMINED:
istep = None
isnap = -1
# could be more efficient if do 0 and -1 then bisection
# (but loose intermediate <- would probably use too much
# memory for what it's worth if search algo is efficient)
while (istep is None or istep < self.istep) and isnap < 99999:
isnap += 1
istep = self.sdat.snaps[isnap].istep
self.sdat.snaps.bind(isnap, istep)
# all intermediate istep could have their ._isnap to None
if istep != self.istep:
self._isnap = None
return self._isnap | python | def isnap(self):
"""Snapshot index corresponding to time step.
It is set to None if no snapshot exists for the time step.
"""
if self._isnap is UNDETERMINED:
istep = None
isnap = -1
# could be more efficient if do 0 and -1 then bisection
# (but loose intermediate <- would probably use too much
# memory for what it's worth if search algo is efficient)
while (istep is None or istep < self.istep) and isnap < 99999:
isnap += 1
istep = self.sdat.snaps[isnap].istep
self.sdat.snaps.bind(isnap, istep)
# all intermediate istep could have their ._isnap to None
if istep != self.istep:
self._isnap = None
return self._isnap | [
"def",
"isnap",
"(",
"self",
")",
":",
"if",
"self",
".",
"_isnap",
"is",
"UNDETERMINED",
":",
"istep",
"=",
"None",
"isnap",
"=",
"-",
"1",
"# could be more efficient if do 0 and -1 then bisection",
"# (but loose intermediate <- would probably use too much",
"# memory fo... | Snapshot index corresponding to time step.
It is set to None if no snapshot exists for the time step. | [
"Snapshot",
"index",
"corresponding",
"to",
"time",
"step",
"."
] | 18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4 | https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/_step.py#L423-L441 | train | 42,256 |
data61/clkhash | clkhash/schema.py | from_json_dict | def from_json_dict(dct, validate=True):
# type: (Dict[str, Any], bool) -> Schema
""" Create a Schema for v1 or v2 according to dct
:param dct: This dictionary must have a `'features'`
key specifying the columns of the dataset. It must have
a `'version'` key containing the master schema version
that this schema conforms to. It must have a `'hash'`
key with all the globals.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
:return: the Schema
"""
if validate:
# This raises iff the schema is invalid.
validate_schema_dict(dct)
version = dct['version']
if version == 1:
dct = convert_v1_to_v2(dct)
if validate:
validate_schema_dict(dct)
elif version != 2:
msg = ('Schema version {} is not supported. '
'Consider updating clkhash.').format(version)
raise SchemaError(msg)
clk_config = dct['clkConfig']
l = clk_config['l']
xor_folds = clk_config.get('xor_folds', 0)
kdf = clk_config['kdf']
kdf_type = kdf['type']
kdf_hash = kdf.get('hash', 'SHA256')
kdf_info_string = kdf.get('info')
kdf_info = (base64.b64decode(kdf_info_string)
if kdf_info_string is not None
else None)
kdf_salt_string = kdf.get('salt')
kdf_salt = (base64.b64decode(kdf_salt_string)
if kdf_salt_string is not None
else None)
kdf_key_size = kdf.get('keySize', DEFAULT_KDF_KEY_SIZE)
fields = list(map(spec_from_json_dict, dct['features']))
return Schema(fields, l, xor_folds,
kdf_type, kdf_hash, kdf_info, kdf_salt, kdf_key_size) | python | def from_json_dict(dct, validate=True):
# type: (Dict[str, Any], bool) -> Schema
""" Create a Schema for v1 or v2 according to dct
:param dct: This dictionary must have a `'features'`
key specifying the columns of the dataset. It must have
a `'version'` key containing the master schema version
that this schema conforms to. It must have a `'hash'`
key with all the globals.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
:return: the Schema
"""
if validate:
# This raises iff the schema is invalid.
validate_schema_dict(dct)
version = dct['version']
if version == 1:
dct = convert_v1_to_v2(dct)
if validate:
validate_schema_dict(dct)
elif version != 2:
msg = ('Schema version {} is not supported. '
'Consider updating clkhash.').format(version)
raise SchemaError(msg)
clk_config = dct['clkConfig']
l = clk_config['l']
xor_folds = clk_config.get('xor_folds', 0)
kdf = clk_config['kdf']
kdf_type = kdf['type']
kdf_hash = kdf.get('hash', 'SHA256')
kdf_info_string = kdf.get('info')
kdf_info = (base64.b64decode(kdf_info_string)
if kdf_info_string is not None
else None)
kdf_salt_string = kdf.get('salt')
kdf_salt = (base64.b64decode(kdf_salt_string)
if kdf_salt_string is not None
else None)
kdf_key_size = kdf.get('keySize', DEFAULT_KDF_KEY_SIZE)
fields = list(map(spec_from_json_dict, dct['features']))
return Schema(fields, l, xor_folds,
kdf_type, kdf_hash, kdf_info, kdf_salt, kdf_key_size) | [
"def",
"from_json_dict",
"(",
"dct",
",",
"validate",
"=",
"True",
")",
":",
"# type: (Dict[str, Any], bool) -> Schema",
"if",
"validate",
":",
"# This raises iff the schema is invalid.",
"validate_schema_dict",
"(",
"dct",
")",
"version",
"=",
"dct",
"[",
"'version'",
... | Create a Schema for v1 or v2 according to dct
:param dct: This dictionary must have a `'features'`
key specifying the columns of the dataset. It must have
a `'version'` key containing the master schema version
that this schema conforms to. It must have a `'hash'`
key with all the globals.
:param validate: (default True) Raise an exception if the
schema does not conform to the master schema.
:return: the Schema | [
"Create",
"a",
"Schema",
"for",
"v1",
"or",
"v2",
"according",
"to",
"dct"
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/schema.py#L132-L178 | train | 42,257 |
data61/clkhash | clkhash/schema.py | _get_master_schema | def _get_master_schema(version):
# type: (Hashable) -> bytes
""" Loads the master schema of given version as bytes.
:param version: The version of the master schema whose path we
wish to retrieve.
:raises SchemaError: When the schema version is unknown. This
usually means that either (a) clkhash is out of date, or (b)
the schema version listed is incorrect.
:return: Bytes of the schema.
"""
try:
file_name = MASTER_SCHEMA_FILE_NAMES[version]
except (TypeError, KeyError) as e:
msg = ('Schema version {} is not supported. '
'Consider updating clkhash.').format(version)
raise_from(SchemaError(msg), e)
try:
schema_bytes = pkgutil.get_data('clkhash', 'schemas/{}'.format(file_name))
except IOError as e: # In Python 3 we can be more specific with
# FileNotFoundError, but that doesn't exist in
# Python 2.
msg = ('The master schema could not be found. The schema cannot be '
'validated. Please file a bug report.')
raise_from(MasterSchemaError(msg), e)
if schema_bytes is None:
msg = ('The master schema could not be loaded. The schema cannot be '
'validated. Please file a bug report.')
raise MasterSchemaError(msg)
return schema_bytes | python | def _get_master_schema(version):
# type: (Hashable) -> bytes
""" Loads the master schema of given version as bytes.
:param version: The version of the master schema whose path we
wish to retrieve.
:raises SchemaError: When the schema version is unknown. This
usually means that either (a) clkhash is out of date, or (b)
the schema version listed is incorrect.
:return: Bytes of the schema.
"""
try:
file_name = MASTER_SCHEMA_FILE_NAMES[version]
except (TypeError, KeyError) as e:
msg = ('Schema version {} is not supported. '
'Consider updating clkhash.').format(version)
raise_from(SchemaError(msg), e)
try:
schema_bytes = pkgutil.get_data('clkhash', 'schemas/{}'.format(file_name))
except IOError as e: # In Python 3 we can be more specific with
# FileNotFoundError, but that doesn't exist in
# Python 2.
msg = ('The master schema could not be found. The schema cannot be '
'validated. Please file a bug report.')
raise_from(MasterSchemaError(msg), e)
if schema_bytes is None:
msg = ('The master schema could not be loaded. The schema cannot be '
'validated. Please file a bug report.')
raise MasterSchemaError(msg)
return schema_bytes | [
"def",
"_get_master_schema",
"(",
"version",
")",
":",
"# type: (Hashable) -> bytes",
"try",
":",
"file_name",
"=",
"MASTER_SCHEMA_FILE_NAMES",
"[",
"version",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
")",
"as",
"e",
":",
"msg",
"=",
"(",
"'Schema versi... | Loads the master schema of given version as bytes.
:param version: The version of the master schema whose path we
wish to retrieve.
:raises SchemaError: When the schema version is unknown. This
usually means that either (a) clkhash is out of date, or (b)
the schema version listed is incorrect.
:return: Bytes of the schema. | [
"Loads",
"the",
"master",
"schema",
"of",
"given",
"version",
"as",
"bytes",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/schema.py#L201-L233 | train | 42,258 |
data61/clkhash | clkhash/schema.py | validate_schema_dict | def validate_schema_dict(schema):
# type: (Dict[str, Any]) -> None
""" Validate the schema.
This raises iff either the schema or the master schema are
invalid. If it's successful, it returns nothing.
:param schema: The schema to validate, as parsed by `json`.
:raises SchemaError: When the schema is invalid.
:raises MasterSchemaError: When the master schema is invalid.
"""
if not isinstance(schema, dict):
msg = ('The top level of the schema file is a {}, whereas a dict is '
'expected.'.format(type(schema).__name__))
raise SchemaError(msg)
if 'version' in schema:
version = schema['version']
else:
raise SchemaError('A format version is expected in the schema.')
master_schema_bytes = _get_master_schema(version)
try:
master_schema = json.loads(master_schema_bytes.decode('utf-8'))
except ValueError as e: # In Python 3 we can be more specific with
# json.decoder.JSONDecodeError, but that
# doesn't exist in Python 2.
msg = ('The master schema is not a valid JSON file. The schema cannot '
'be validated. Please file a bug report.')
raise_from(MasterSchemaError(msg), e)
try:
jsonschema.validate(schema, master_schema)
except jsonschema.exceptions.ValidationError as e:
raise_from(SchemaError('The schema is not valid.'), e)
except jsonschema.exceptions.SchemaError as e:
msg = ('The master schema is not valid. The schema cannot be '
'validated. Please file a bug report.')
raise_from(MasterSchemaError(msg), e) | python | def validate_schema_dict(schema):
# type: (Dict[str, Any]) -> None
""" Validate the schema.
This raises iff either the schema or the master schema are
invalid. If it's successful, it returns nothing.
:param schema: The schema to validate, as parsed by `json`.
:raises SchemaError: When the schema is invalid.
:raises MasterSchemaError: When the master schema is invalid.
"""
if not isinstance(schema, dict):
msg = ('The top level of the schema file is a {}, whereas a dict is '
'expected.'.format(type(schema).__name__))
raise SchemaError(msg)
if 'version' in schema:
version = schema['version']
else:
raise SchemaError('A format version is expected in the schema.')
master_schema_bytes = _get_master_schema(version)
try:
master_schema = json.loads(master_schema_bytes.decode('utf-8'))
except ValueError as e: # In Python 3 we can be more specific with
# json.decoder.JSONDecodeError, but that
# doesn't exist in Python 2.
msg = ('The master schema is not a valid JSON file. The schema cannot '
'be validated. Please file a bug report.')
raise_from(MasterSchemaError(msg), e)
try:
jsonschema.validate(schema, master_schema)
except jsonschema.exceptions.ValidationError as e:
raise_from(SchemaError('The schema is not valid.'), e)
except jsonschema.exceptions.SchemaError as e:
msg = ('The master schema is not valid. The schema cannot be '
'validated. Please file a bug report.')
raise_from(MasterSchemaError(msg), e) | [
"def",
"validate_schema_dict",
"(",
"schema",
")",
":",
"# type: (Dict[str, Any]) -> None",
"if",
"not",
"isinstance",
"(",
"schema",
",",
"dict",
")",
":",
"msg",
"=",
"(",
"'The top level of the schema file is a {}, whereas a dict is '",
"'expected.'",
".",
"format",
... | Validate the schema.
This raises iff either the schema or the master schema are
invalid. If it's successful, it returns nothing.
:param schema: The schema to validate, as parsed by `json`.
:raises SchemaError: When the schema is invalid.
:raises MasterSchemaError: When the master schema is invalid. | [
"Validate",
"the",
"schema",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/schema.py#L236-L274 | train | 42,259 |
data61/clkhash | clkhash/benchmark.py | compute_hash_speed | def compute_hash_speed(num, quiet=False):
# type: (int, bool) -> float
""" Hash time.
"""
namelist = NameList(num)
os_fd, tmpfile_name = tempfile.mkstemp(text=True)
schema = NameList.SCHEMA
header_row = ','.join([f.identifier for f in schema.fields])
with open(tmpfile_name, 'wt') as f:
f.write(header_row)
f.write('\n')
for person in namelist.names:
print(','.join([str(field) for field in person]), file=f)
with open(tmpfile_name, 'rt') as f:
start = timer()
generate_clk_from_csv(f, ('key1', 'key2'), schema, progress_bar=not quiet)
end = timer()
os.close(os_fd)
os.remove(tmpfile_name)
elapsed_time = end - start
if not quiet:
print("{:6d} hashes in {:.6f} seconds. {:.2f} KH/s".format(num, elapsed_time, num / (1000 * elapsed_time)))
return num / elapsed_time | python | def compute_hash_speed(num, quiet=False):
# type: (int, bool) -> float
""" Hash time.
"""
namelist = NameList(num)
os_fd, tmpfile_name = tempfile.mkstemp(text=True)
schema = NameList.SCHEMA
header_row = ','.join([f.identifier for f in schema.fields])
with open(tmpfile_name, 'wt') as f:
f.write(header_row)
f.write('\n')
for person in namelist.names:
print(','.join([str(field) for field in person]), file=f)
with open(tmpfile_name, 'rt') as f:
start = timer()
generate_clk_from_csv(f, ('key1', 'key2'), schema, progress_bar=not quiet)
end = timer()
os.close(os_fd)
os.remove(tmpfile_name)
elapsed_time = end - start
if not quiet:
print("{:6d} hashes in {:.6f} seconds. {:.2f} KH/s".format(num, elapsed_time, num / (1000 * elapsed_time)))
return num / elapsed_time | [
"def",
"compute_hash_speed",
"(",
"num",
",",
"quiet",
"=",
"False",
")",
":",
"# type: (int, bool) -> float",
"namelist",
"=",
"NameList",
"(",
"num",
")",
"os_fd",
",",
"tmpfile_name",
"=",
"tempfile",
".",
"mkstemp",
"(",
"text",
"=",
"True",
")",
"schema... | Hash time. | [
"Hash",
"time",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/benchmark.py#L12-L40 | train | 42,260 |
data61/clkhash | clkhash/cli.py | hash | def hash(pii_csv, keys, schema, clk_json, quiet, no_header, check_header, validate):
"""Process data to create CLKs
Given a file containing CSV data as PII_CSV, and a JSON
document defining the expected schema, verify the schema, then
hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV
file should contain a header row - however this row is not used
by this tool.
It is important that the keys are only known by the two data providers. Two words should be provided. For example:
$clkutil hash pii.csv horse staple pii-schema.json clk.json
Use "-" for CLK_JSON to write JSON to stdout.
"""
schema_object = clkhash.schema.from_json_file(schema_file=schema)
header = True
if not check_header:
header = 'ignore'
if no_header:
header = False
try:
clk_data = clk.generate_clk_from_csv(
pii_csv, keys, schema_object,
validate=validate,
header=header,
progress_bar=not quiet)
except (validate_data.EntryError, validate_data.FormatError) as e:
msg, = e.args
log(msg)
log('Hashing failed.')
else:
json.dump({'clks': clk_data}, clk_json)
if hasattr(clk_json, 'name'):
log("CLK data written to {}".format(clk_json.name)) | python | def hash(pii_csv, keys, schema, clk_json, quiet, no_header, check_header, validate):
"""Process data to create CLKs
Given a file containing CSV data as PII_CSV, and a JSON
document defining the expected schema, verify the schema, then
hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV
file should contain a header row - however this row is not used
by this tool.
It is important that the keys are only known by the two data providers. Two words should be provided. For example:
$clkutil hash pii.csv horse staple pii-schema.json clk.json
Use "-" for CLK_JSON to write JSON to stdout.
"""
schema_object = clkhash.schema.from_json_file(schema_file=schema)
header = True
if not check_header:
header = 'ignore'
if no_header:
header = False
try:
clk_data = clk.generate_clk_from_csv(
pii_csv, keys, schema_object,
validate=validate,
header=header,
progress_bar=not quiet)
except (validate_data.EntryError, validate_data.FormatError) as e:
msg, = e.args
log(msg)
log('Hashing failed.')
else:
json.dump({'clks': clk_data}, clk_json)
if hasattr(clk_json, 'name'):
log("CLK data written to {}".format(clk_json.name)) | [
"def",
"hash",
"(",
"pii_csv",
",",
"keys",
",",
"schema",
",",
"clk_json",
",",
"quiet",
",",
"no_header",
",",
"check_header",
",",
"validate",
")",
":",
"schema_object",
"=",
"clkhash",
".",
"schema",
".",
"from_json_file",
"(",
"schema_file",
"=",
"sch... | Process data to create CLKs
Given a file containing CSV data as PII_CSV, and a JSON
document defining the expected schema, verify the schema, then
hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV
file should contain a header row - however this row is not used
by this tool.
It is important that the keys are only known by the two data providers. Two words should be provided. For example:
$clkutil hash pii.csv horse staple pii-schema.json clk.json
Use "-" for CLK_JSON to write JSON to stdout. | [
"Process",
"data",
"to",
"create",
"CLKs"
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L56-L92 | train | 42,261 |
data61/clkhash | clkhash/cli.py | status | def status(server, output, verbose):
"""Connect to an entity matching server and check the service status.
Use "-" to output status to stdout.
"""
if verbose:
log("Connecting to Entity Matching Server: {}".format(server))
service_status = server_get_status(server)
if verbose:
log("Status: {}".format(service_status['status']))
print(json.dumps(service_status), file=output) | python | def status(server, output, verbose):
"""Connect to an entity matching server and check the service status.
Use "-" to output status to stdout.
"""
if verbose:
log("Connecting to Entity Matching Server: {}".format(server))
service_status = server_get_status(server)
if verbose:
log("Status: {}".format(service_status['status']))
print(json.dumps(service_status), file=output) | [
"def",
"status",
"(",
"server",
",",
"output",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"log",
"(",
"\"Connecting to Entity Matching Server: {}\"",
".",
"format",
"(",
"server",
")",
")",
"service_status",
"=",
"server_get_status",
"(",
"server",
")",
"... | Connect to an entity matching server and check the service status.
Use "-" to output status to stdout. | [
"Connect",
"to",
"an",
"entity",
"matching",
"server",
"and",
"check",
"the",
"service",
"status",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L99-L110 | train | 42,262 |
data61/clkhash | clkhash/cli.py | create_project | def create_project(type, schema, server, name, output, verbose):
"""Create a new project on an entity matching server.
See entity matching service documentation for details on mapping type and schema
Returns authentication details for the created project.
"""
if verbose:
log("Entity Matching Server: {}".format(server))
if schema is not None:
schema_json = json.load(schema)
# Validate the schema
clkhash.schema.validate_schema_dict(schema_json)
else:
raise ValueError("Schema must be provided when creating new linkage project")
name = name if name is not None else ''
# Creating new project
try:
project_creation_reply = project_create(server, schema_json, type, name)
except ServiceError as e:
log("Unexpected response - {}".format(e.status_code))
log(e.text)
raise SystemExit
else:
log("Project created")
json.dump(project_creation_reply, output) | python | def create_project(type, schema, server, name, output, verbose):
"""Create a new project on an entity matching server.
See entity matching service documentation for details on mapping type and schema
Returns authentication details for the created project.
"""
if verbose:
log("Entity Matching Server: {}".format(server))
if schema is not None:
schema_json = json.load(schema)
# Validate the schema
clkhash.schema.validate_schema_dict(schema_json)
else:
raise ValueError("Schema must be provided when creating new linkage project")
name = name if name is not None else ''
# Creating new project
try:
project_creation_reply = project_create(server, schema_json, type, name)
except ServiceError as e:
log("Unexpected response - {}".format(e.status_code))
log(e.text)
raise SystemExit
else:
log("Project created")
json.dump(project_creation_reply, output) | [
"def",
"create_project",
"(",
"type",
",",
"schema",
",",
"server",
",",
"name",
",",
"output",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"log",
"(",
"\"Entity Matching Server: {}\"",
".",
"format",
"(",
"server",
")",
")",
"if",
"schema",
"is",
"n... | Create a new project on an entity matching server.
See entity matching service documentation for details on mapping type and schema
Returns authentication details for the created project. | [
"Create",
"a",
"new",
"project",
"on",
"an",
"entity",
"matching",
"server",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L143-L171 | train | 42,263 |
data61/clkhash | clkhash/cli.py | create | def create(server, name, project, apikey, output, threshold, verbose):
"""Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run.
"""
if verbose:
log("Entity Matching Server: {}".format(server))
if threshold is None:
raise ValueError("Please provide a threshold")
# Create a new run
try:
response = run_create(server, project, apikey, threshold, name)
except ServiceError as e:
log("Unexpected response with status {}".format(e.status_code))
log(e.text)
else:
json.dump(response, output) | python | def create(server, name, project, apikey, output, threshold, verbose):
"""Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run.
"""
if verbose:
log("Entity Matching Server: {}".format(server))
if threshold is None:
raise ValueError("Please provide a threshold")
# Create a new run
try:
response = run_create(server, project, apikey, threshold, name)
except ServiceError as e:
log("Unexpected response with status {}".format(e.status_code))
log(e.text)
else:
json.dump(response, output) | [
"def",
"create",
"(",
"server",
",",
"name",
",",
"project",
",",
"apikey",
",",
"output",
",",
"threshold",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"log",
"(",
"\"Entity Matching Server: {}\"",
".",
"format",
"(",
"server",
")",
")",
"if",
"thre... | Create a new run on an entity matching server.
See entity matching service documentation for details on threshold.
Returns details for the created run. | [
"Create",
"a",
"new",
"run",
"on",
"an",
"entity",
"matching",
"server",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L182-L202 | train | 42,264 |
data61/clkhash | clkhash/cli.py | upload | def upload(clk_json, project, apikey, server, output, verbose):
"""Upload CLK data to entity matching server.
Given a json file containing hashed clk data as CLK_JSON, upload to
the entity resolution service.
Use "-" to read from stdin.
"""
if verbose:
log("Uploading CLK data from {}".format(clk_json.name))
log("To Entity Matching Server: {}".format(server))
log("Project ID: {}".format(project))
log("Uploading CLK data to the server")
response = project_upload_clks(server, project, apikey, clk_json)
if verbose:
log(response)
json.dump(response, output) | python | def upload(clk_json, project, apikey, server, output, verbose):
"""Upload CLK data to entity matching server.
Given a json file containing hashed clk data as CLK_JSON, upload to
the entity resolution service.
Use "-" to read from stdin.
"""
if verbose:
log("Uploading CLK data from {}".format(clk_json.name))
log("To Entity Matching Server: {}".format(server))
log("Project ID: {}".format(project))
log("Uploading CLK data to the server")
response = project_upload_clks(server, project, apikey, clk_json)
if verbose:
log(response)
json.dump(response, output) | [
"def",
"upload",
"(",
"clk_json",
",",
"project",
",",
"apikey",
",",
"server",
",",
"output",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"log",
"(",
"\"Uploading CLK data from {}\"",
".",
"format",
"(",
"clk_json",
".",
"name",
")",
")",
"log",
"("... | Upload CLK data to entity matching server.
Given a json file containing hashed clk data as CLK_JSON, upload to
the entity resolution service.
Use "-" to read from stdin. | [
"Upload",
"CLK",
"data",
"to",
"entity",
"matching",
"server",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L212-L231 | train | 42,265 |
data61/clkhash | clkhash/cli.py | results | def results(project, apikey, run, watch, server, output):
"""
Check to see if results are available for a particular mapping
and if so download.
Authentication is carried out using the --apikey option which
must be provided. Depending on the server operating mode this
may return a mask, a linkage table, or a permutation. Consult
the entity service documentation for details.
"""
status = run_get_status(server, project, run, apikey)
log(format_run_status(status))
if watch:
for status in watch_run_status(server, project, run, apikey, 24*60*60):
log(format_run_status(status))
if status['state'] == 'completed':
log("Downloading result")
response = run_get_result_text(server, project, run, apikey)
log("Received result")
print(response, file=output)
elif status['state'] == 'error':
log("There was an error")
error_result = run_get_result_text(server, project, run, apikey)
print(error_result, file=output)
else:
log("No result yet") | python | def results(project, apikey, run, watch, server, output):
"""
Check to see if results are available for a particular mapping
and if so download.
Authentication is carried out using the --apikey option which
must be provided. Depending on the server operating mode this
may return a mask, a linkage table, or a permutation. Consult
the entity service documentation for details.
"""
status = run_get_status(server, project, run, apikey)
log(format_run_status(status))
if watch:
for status in watch_run_status(server, project, run, apikey, 24*60*60):
log(format_run_status(status))
if status['state'] == 'completed':
log("Downloading result")
response = run_get_result_text(server, project, run, apikey)
log("Received result")
print(response, file=output)
elif status['state'] == 'error':
log("There was an error")
error_result = run_get_result_text(server, project, run, apikey)
print(error_result, file=output)
else:
log("No result yet") | [
"def",
"results",
"(",
"project",
",",
"apikey",
",",
"run",
",",
"watch",
",",
"server",
",",
"output",
")",
":",
"status",
"=",
"run_get_status",
"(",
"server",
",",
"project",
",",
"run",
",",
"apikey",
")",
"log",
"(",
"format_run_status",
"(",
"st... | Check to see if results are available for a particular mapping
and if so download.
Authentication is carried out using the --apikey option which
must be provided. Depending on the server operating mode this
may return a mask, a linkage table, or a permutation. Consult
the entity service documentation for details. | [
"Check",
"to",
"see",
"if",
"results",
"are",
"available",
"for",
"a",
"particular",
"mapping",
"and",
"if",
"so",
"download",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L241-L268 | train | 42,266 |
data61/clkhash | clkhash/cli.py | generate | def generate(size, output, schema):
"""Generate fake PII data for testing"""
pii_data = randomnames.NameList(size)
if schema is not None:
raise NotImplementedError
randomnames.save_csv(
pii_data.names,
[f.identifier for f in pii_data.SCHEMA.fields],
output) | python | def generate(size, output, schema):
"""Generate fake PII data for testing"""
pii_data = randomnames.NameList(size)
if schema is not None:
raise NotImplementedError
randomnames.save_csv(
pii_data.names,
[f.identifier for f in pii_data.SCHEMA.fields],
output) | [
"def",
"generate",
"(",
"size",
",",
"output",
",",
"schema",
")",
":",
"pii_data",
"=",
"randomnames",
".",
"NameList",
"(",
"size",
")",
"if",
"schema",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"randomnames",
".",
"save_csv",
"(",
"pii_d... | Generate fake PII data for testing | [
"Generate",
"fake",
"PII",
"data",
"for",
"testing"
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L288-L298 | train | 42,267 |
data61/clkhash | clkhash/cli.py | generate_default_schema | def generate_default_schema(output):
"""Get default schema for fake PII"""
original_path = os.path.join(os.path.dirname(__file__),
'data',
'randomnames-schema.json')
shutil.copyfile(original_path, output) | python | def generate_default_schema(output):
"""Get default schema for fake PII"""
original_path = os.path.join(os.path.dirname(__file__),
'data',
'randomnames-schema.json')
shutil.copyfile(original_path, output) | [
"def",
"generate_default_schema",
"(",
"output",
")",
":",
"original_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'data'",
",",
"'randomnames-schema.json'",
")",
"shutil",
".",
"copyfile",
... | Get default schema for fake PII | [
"Get",
"default",
"schema",
"for",
"fake",
"PII"
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L306-L311 | train | 42,268 |
IndicoDataSolutions/IndicoIo-python | indicoio/docx/docx_extraction.py | docx_extraction | def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> from indicoio import docx_extraction
>>> results = docx_extraction(docx_file)
:param docx: The docx to be analyzed.
:type docx: str or list of strs
:rtype: dict or list of dicts
"""
docx = docx_preprocess(docx, batch=batch)
url_params = {"batch": batch, "api_key": api_key, "version": version}
results = api_handler(docx, cloud=cloud, api="docxextraction", url_params=url_params, **kwargs)
return results | python | def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> from indicoio import docx_extraction
>>> results = docx_extraction(docx_file)
:param docx: The docx to be analyzed.
:type docx: str or list of strs
:rtype: dict or list of dicts
"""
docx = docx_preprocess(docx, batch=batch)
url_params = {"batch": batch, "api_key": api_key, "version": version}
results = api_handler(docx, cloud=cloud, api="docxextraction", url_params=url_params, **kwargs)
return results | [
"def",
"docx_extraction",
"(",
"docx",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"docx",
"=",
"docx_preprocess",
"(",
"docx",
",",
"batch",
"=",... | Given a .docx file, returns the raw text associated with the given .docx file.
The .docx file may be provided as base64 encoded data or as a filepath.
Example usage:
.. code-block:: python
>>> from indicoio import docx_extraction
>>> results = docx_extraction(docx_file)
:param docx: The docx to be analyzed.
:type docx: str or list of strs
:rtype: dict or list of dicts | [
"Given",
"a",
".",
"docx",
"file",
"returns",
"the",
"raw",
"text",
"associated",
"with",
"the",
"given",
".",
"docx",
"file",
".",
"The",
".",
"docx",
"file",
"may",
"be",
"provided",
"as",
"base64",
"encoded",
"data",
"or",
"as",
"a",
"filepath",
"."... | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/docx/docx_extraction.py#L6-L25 | train | 42,269 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/docx.py | docx_preprocess | def docx_preprocess(docx, batch=False):
"""
Load docx files from local filepath if not already b64 encoded
"""
if batch:
return [docx_preprocess(doc, batch=False) for doc in docx]
if os.path.isfile(docx):
# a filepath is provided, read and encode
return b64encode(open(docx, 'rb').read())
else:
# assume doc is already b64 encoded
return docx | python | def docx_preprocess(docx, batch=False):
"""
Load docx files from local filepath if not already b64 encoded
"""
if batch:
return [docx_preprocess(doc, batch=False) for doc in docx]
if os.path.isfile(docx):
# a filepath is provided, read and encode
return b64encode(open(docx, 'rb').read())
else:
# assume doc is already b64 encoded
return docx | [
"def",
"docx_preprocess",
"(",
"docx",
",",
"batch",
"=",
"False",
")",
":",
"if",
"batch",
":",
"return",
"[",
"docx_preprocess",
"(",
"doc",
",",
"batch",
"=",
"False",
")",
"for",
"doc",
"in",
"docx",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
... | Load docx files from local filepath if not already b64 encoded | [
"Load",
"docx",
"files",
"from",
"local",
"filepath",
"if",
"not",
"already",
"b64",
"encoded"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/docx.py#L5-L17 | train | 42,270 |
ambv/flake8-pyi | pyi.py | PyiAwareFlakesChecker.LAMBDA | def LAMBDA(self, node):
"""This is likely very brittle, currently works for pyflakes 1.3.0.
Deferring annotation handling depends on the fact that during calls
to LAMBDA visiting the function's body is already deferred and the
only eager calls to `handleNode` are for annotations.
"""
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode
super().LAMBDA(node)
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode | python | def LAMBDA(self, node):
"""This is likely very brittle, currently works for pyflakes 1.3.0.
Deferring annotation handling depends on the fact that during calls
to LAMBDA visiting the function's body is already deferred and the
only eager calls to `handleNode` are for annotations.
"""
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode
super().LAMBDA(node)
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode | [
"def",
"LAMBDA",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"handleNode",
",",
"self",
".",
"deferHandleNode",
"=",
"self",
".",
"deferHandleNode",
",",
"self",
".",
"handleNode",
"super",
"(",
")",
".",
"LAMBDA",
"(",
"node",
")",
"self",
".",
... | This is likely very brittle, currently works for pyflakes 1.3.0.
Deferring annotation handling depends on the fact that during calls
to LAMBDA visiting the function's body is already deferred and the
only eager calls to `handleNode` are for annotations. | [
"This",
"is",
"likely",
"very",
"brittle",
"currently",
"works",
"for",
"pyflakes",
"1",
".",
"3",
".",
"0",
"."
] | 19e8028b44b6305dff1bfb9a51a23a029c546993 | https://github.com/ambv/flake8-pyi/blob/19e8028b44b6305dff1bfb9a51a23a029c546993/pyi.py#L68-L77 | train | 42,271 |
data61/clkhash | clkhash/bloomfilter.py | double_hash_encode_ngrams | def double_hash_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
):
# type: (...) -> bitarray
""" Computes the double hash encoding of the ngrams with the given keys.
Using the method from:
Schnell, R., Bachteler, T., & Reiher, J. (2011).
A Novel Error-Tolerant Anonymous Linking Code.
http://grlc.german-microsimulation.de/wp-content/uploads/2017/05/downloadwp-grlc-2011-02.pdf
:param ngrams: list of n-grams to be encoded
:param keys: hmac secret keys for md5 and sha1 as bytes
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to
the encoding of the ngrams
"""
key_sha1, key_md5 = keys
bf = bitarray(l)
bf.setall(False)
for m, k in zip(ngrams, ks):
sha1hm = int(
hmac.new(key_sha1, m.encode(encoding=encoding), sha1).hexdigest(),
16) % l
md5hm = int(
hmac.new(key_md5, m.encode(encoding=encoding), md5).hexdigest(),
16) % l
for i in range(k):
gi = (sha1hm + i * md5hm) % l
bf[gi] = 1
return bf | python | def double_hash_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
):
# type: (...) -> bitarray
""" Computes the double hash encoding of the ngrams with the given keys.
Using the method from:
Schnell, R., Bachteler, T., & Reiher, J. (2011).
A Novel Error-Tolerant Anonymous Linking Code.
http://grlc.german-microsimulation.de/wp-content/uploads/2017/05/downloadwp-grlc-2011-02.pdf
:param ngrams: list of n-grams to be encoded
:param keys: hmac secret keys for md5 and sha1 as bytes
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to
the encoding of the ngrams
"""
key_sha1, key_md5 = keys
bf = bitarray(l)
bf.setall(False)
for m, k in zip(ngrams, ks):
sha1hm = int(
hmac.new(key_sha1, m.encode(encoding=encoding), sha1).hexdigest(),
16) % l
md5hm = int(
hmac.new(key_md5, m.encode(encoding=encoding), md5).hexdigest(),
16) % l
for i in range(k):
gi = (sha1hm + i * md5hm) % l
bf[gi] = 1
return bf | [
"def",
"double_hash_encode_ngrams",
"(",
"ngrams",
",",
"# type: Iterable[str]",
"keys",
",",
"# type: Sequence[bytes]",
"ks",
",",
"# type: Sequence[int]",
"l",
",",
"# type: int",
"encoding",
"# type: str",
")",
":",
"# type: (...) -> bitarray",
"key_sha1",
",",
"key_md... | Computes the double hash encoding of the ngrams with the given keys.
Using the method from:
Schnell, R., Bachteler, T., & Reiher, J. (2011).
A Novel Error-Tolerant Anonymous Linking Code.
http://grlc.german-microsimulation.de/wp-content/uploads/2017/05/downloadwp-grlc-2011-02.pdf
:param ngrams: list of n-grams to be encoded
:param keys: hmac secret keys for md5 and sha1 as bytes
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to
the encoding of the ngrams | [
"Computes",
"the",
"double",
"hash",
"encoding",
"of",
"the",
"ngrams",
"with",
"the",
"given",
"keys",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/bloomfilter.py#L29-L66 | train | 42,272 |
data61/clkhash | clkhash/bloomfilter.py | double_hash_encode_ngrams_non_singular | def double_hash_encode_ngrams_non_singular(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
):
# type: (...) -> bitarray.bitarray
""" computes the double hash encoding of the n-grams with the given keys.
The original construction of [Schnell2011]_ displays an abnormality for
certain inputs:
An n-gram can be encoded into just one bit irrespective of the number
of k.
Their construction goes as follows: the :math:`k` different indices
:math:`g_i` of the Bloom filter for an n-gram
:math:`x` are defined as:
.. math:: g_{i}(x) = (h_1(x) + i h_2(x)) \\mod l
with :math:`0 \\leq i < k` and :math:`l` is the length of the Bloom
filter. If the value of the hash of :math:`x` of
the second hash function is a multiple of :math:`l`, then
.. math:: h_2(x) = 0 \\mod l
and thus
.. math:: g_i(x) = h_1(x) \\mod l,
irrespective of the value :math:`i`. A discussion of this potential flaw
can be found
`here <https://github.com/data61/clkhash/issues/33>`_.
:param ngrams: list of n-grams to be encoded
:param keys: tuple with (key_sha1, key_md5).
That is, (hmac secret keys for sha1 as bytes, hmac secret keys for
md5 as bytes)
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to the
encoding of the ngrams
"""
key_sha1, key_md5 = keys
bf = bitarray(l)
bf.setall(False)
for m, k in zip(ngrams, ks):
m_bytes = m.encode(encoding=encoding)
sha1hm_bytes = hmac.new(key_sha1, m_bytes, sha1).digest()
md5hm_bytes = hmac.new(key_md5, m_bytes, md5).digest()
sha1hm = int_from_bytes(sha1hm_bytes, 'big') % l
md5hm = int_from_bytes(md5hm_bytes, 'big') % l
i = 0
while md5hm == 0:
md5hm_bytes = hmac.new(
key_md5, m_bytes + chr(i).encode(), md5).digest()
md5hm = int_from_bytes(md5hm_bytes, 'big') % l
i += 1
for i in range(k):
gi = (sha1hm + i * md5hm) % l
bf[gi] = True
return bf | python | def double_hash_encode_ngrams_non_singular(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
):
# type: (...) -> bitarray.bitarray
""" computes the double hash encoding of the n-grams with the given keys.
The original construction of [Schnell2011]_ displays an abnormality for
certain inputs:
An n-gram can be encoded into just one bit irrespective of the number
of k.
Their construction goes as follows: the :math:`k` different indices
:math:`g_i` of the Bloom filter for an n-gram
:math:`x` are defined as:
.. math:: g_{i}(x) = (h_1(x) + i h_2(x)) \\mod l
with :math:`0 \\leq i < k` and :math:`l` is the length of the Bloom
filter. If the value of the hash of :math:`x` of
the second hash function is a multiple of :math:`l`, then
.. math:: h_2(x) = 0 \\mod l
and thus
.. math:: g_i(x) = h_1(x) \\mod l,
irrespective of the value :math:`i`. A discussion of this potential flaw
can be found
`here <https://github.com/data61/clkhash/issues/33>`_.
:param ngrams: list of n-grams to be encoded
:param keys: tuple with (key_sha1, key_md5).
That is, (hmac secret keys for sha1 as bytes, hmac secret keys for
md5 as bytes)
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to the
encoding of the ngrams
"""
key_sha1, key_md5 = keys
bf = bitarray(l)
bf.setall(False)
for m, k in zip(ngrams, ks):
m_bytes = m.encode(encoding=encoding)
sha1hm_bytes = hmac.new(key_sha1, m_bytes, sha1).digest()
md5hm_bytes = hmac.new(key_md5, m_bytes, md5).digest()
sha1hm = int_from_bytes(sha1hm_bytes, 'big') % l
md5hm = int_from_bytes(md5hm_bytes, 'big') % l
i = 0
while md5hm == 0:
md5hm_bytes = hmac.new(
key_md5, m_bytes + chr(i).encode(), md5).digest()
md5hm = int_from_bytes(md5hm_bytes, 'big') % l
i += 1
for i in range(k):
gi = (sha1hm + i * md5hm) % l
bf[gi] = True
return bf | [
"def",
"double_hash_encode_ngrams_non_singular",
"(",
"ngrams",
",",
"# type: Iterable[str]",
"keys",
",",
"# type: Sequence[bytes]",
"ks",
",",
"# type: Sequence[int]",
"l",
",",
"# type: int",
"encoding",
"# type: str",
")",
":",
"# type: (...) -> bitarray.bitarray",
"key_s... | computes the double hash encoding of the n-grams with the given keys.
The original construction of [Schnell2011]_ displays an abnormality for
certain inputs:
An n-gram can be encoded into just one bit irrespective of the number
of k.
Their construction goes as follows: the :math:`k` different indices
:math:`g_i` of the Bloom filter for an n-gram
:math:`x` are defined as:
.. math:: g_{i}(x) = (h_1(x) + i h_2(x)) \\mod l
with :math:`0 \\leq i < k` and :math:`l` is the length of the Bloom
filter. If the value of the hash of :math:`x` of
the second hash function is a multiple of :math:`l`, then
.. math:: h_2(x) = 0 \\mod l
and thus
.. math:: g_i(x) = h_1(x) \\mod l,
irrespective of the value :math:`i`. A discussion of this potential flaw
can be found
`here <https://github.com/data61/clkhash/issues/33>`_.
:param ngrams: list of n-grams to be encoded
:param keys: tuple with (key_sha1, key_md5).
That is, (hmac secret keys for sha1 as bytes, hmac secret keys for
md5 as bytes)
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to the
encoding of the ngrams | [
"computes",
"the",
"double",
"hash",
"encoding",
"of",
"the",
"n",
"-",
"grams",
"with",
"the",
"given",
"keys",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/bloomfilter.py#L69-L137 | train | 42,273 |
data61/clkhash | clkhash/bloomfilter.py | blake_encode_ngrams | def blake_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
):
# type: (...) -> bitarray.bitarray
""" Computes the encoding of the ngrams using the BLAKE2 hash function.
We deliberately do not use the double hashing scheme as proposed in [
Schnell2011]_, because this
would introduce an exploitable structure into the Bloom filter. For more
details on the
weakness, see [Kroll2015]_.
In short, the double hashing scheme only allows for :math:`l^2`
different encodings for any possible n-gram,
whereas the use of :math:`k` different independent hash functions gives
you :math:`\\sum_{j=1}^{k}{\\binom{l}{j}}`
combinations.
**Our construction**
It is advantageous to construct Bloom filters using a family of hash
functions with the property of
`k-independence <https://en.wikipedia.org/wiki/K-independent_hashing>`_
to compute the indices for an entry.
This approach minimises the change of collisions.
An informal definition of *k-independence* of a family of hash functions
is, that if selecting a function at random
from the family, it guarantees that the hash codes of any designated k
keys are independent random variables.
Our construction utilises the fact that the output bits of a
cryptographic hash function are uniformly distributed,
independent, binary random variables (well, at least as close to as
possible. See [Kaminsky2011]_ for an analysis).
Thus, slicing the output of a cryptographic hash function into k
different slices gives you k independent random
variables.
We chose Blake2 as the cryptographic hash function mainly for two reasons:
* it is fast.
* in keyed hashing mode, Blake2 provides MACs with just one hash
function call instead of the two calls in the HMAC construction used
in the double hashing scheme.
.. warning::
Please be aware that, although this construction makes the attack of
[Kroll2015]_ infeasible, it is most likely
not enough to ensure security. Or in their own words:
| However, we think that using independent hash functions alone
will not be sufficient to ensure security,
since in this case other approaches (maybe related to or at least
inspired through work from the
area of Frequent Itemset Mining) are promising to detect at least
the most frequent atoms automatically.
:param ngrams: list of n-grams to be encoded
:param keys: secret key for blake2 as bytes
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray (has to be a power of 2)
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to the
encoding of the ngrams
"""
key, = keys # Unpack.
log_l = int(math.log(l, 2))
if not 2 ** log_l == l:
raise ValueError(
'parameter "l" has to be a power of two for the BLAKE2 encoding, '
'but was: {}'.format(
l))
bf = bitarray(l)
bf.setall(False)
for m, k in zip(ngrams, ks):
random_shorts = [] # type: List[int]
num_macs = (k + 31) // 32
for i in range(num_macs):
hash_bytes = blake2b(m.encode(encoding=encoding), key=key,
salt=str(i).encode()).digest()
random_shorts.extend(struct.unpack('32H',
hash_bytes)) # interpret
# hash bytes as 32 unsigned shorts.
for i in range(k):
idx = random_shorts[i] % l
bf[idx] = 1
return bf | python | def blake_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
):
# type: (...) -> bitarray.bitarray
""" Computes the encoding of the ngrams using the BLAKE2 hash function.
We deliberately do not use the double hashing scheme as proposed in [
Schnell2011]_, because this
would introduce an exploitable structure into the Bloom filter. For more
details on the
weakness, see [Kroll2015]_.
In short, the double hashing scheme only allows for :math:`l^2`
different encodings for any possible n-gram,
whereas the use of :math:`k` different independent hash functions gives
you :math:`\\sum_{j=1}^{k}{\\binom{l}{j}}`
combinations.
**Our construction**
It is advantageous to construct Bloom filters using a family of hash
functions with the property of
`k-independence <https://en.wikipedia.org/wiki/K-independent_hashing>`_
to compute the indices for an entry.
This approach minimises the change of collisions.
An informal definition of *k-independence* of a family of hash functions
is, that if selecting a function at random
from the family, it guarantees that the hash codes of any designated k
keys are independent random variables.
Our construction utilises the fact that the output bits of a
cryptographic hash function are uniformly distributed,
independent, binary random variables (well, at least as close to as
possible. See [Kaminsky2011]_ for an analysis).
Thus, slicing the output of a cryptographic hash function into k
different slices gives you k independent random
variables.
We chose Blake2 as the cryptographic hash function mainly for two reasons:
* it is fast.
* in keyed hashing mode, Blake2 provides MACs with just one hash
function call instead of the two calls in the HMAC construction used
in the double hashing scheme.
.. warning::
Please be aware that, although this construction makes the attack of
[Kroll2015]_ infeasible, it is most likely
not enough to ensure security. Or in their own words:
| However, we think that using independent hash functions alone
will not be sufficient to ensure security,
since in this case other approaches (maybe related to or at least
inspired through work from the
area of Frequent Itemset Mining) are promising to detect at least
the most frequent atoms automatically.
:param ngrams: list of n-grams to be encoded
:param keys: secret key for blake2 as bytes
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray (has to be a power of 2)
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to the
encoding of the ngrams
"""
key, = keys # Unpack.
log_l = int(math.log(l, 2))
if not 2 ** log_l == l:
raise ValueError(
'parameter "l" has to be a power of two for the BLAKE2 encoding, '
'but was: {}'.format(
l))
bf = bitarray(l)
bf.setall(False)
for m, k in zip(ngrams, ks):
random_shorts = [] # type: List[int]
num_macs = (k + 31) // 32
for i in range(num_macs):
hash_bytes = blake2b(m.encode(encoding=encoding), key=key,
salt=str(i).encode()).digest()
random_shorts.extend(struct.unpack('32H',
hash_bytes)) # interpret
# hash bytes as 32 unsigned shorts.
for i in range(k):
idx = random_shorts[i] % l
bf[idx] = 1
return bf | [
"def",
"blake_encode_ngrams",
"(",
"ngrams",
",",
"# type: Iterable[str]",
"keys",
",",
"# type: Sequence[bytes]",
"ks",
",",
"# type: Sequence[int]",
"l",
",",
"# type: int",
"encoding",
"# type: str",
")",
":",
"# type: (...) -> bitarray.bitarray",
"key",
",",
"=",
"k... | Computes the encoding of the ngrams using the BLAKE2 hash function.
We deliberately do not use the double hashing scheme as proposed in [
Schnell2011]_, because this
would introduce an exploitable structure into the Bloom filter. For more
details on the
weakness, see [Kroll2015]_.
In short, the double hashing scheme only allows for :math:`l^2`
different encodings for any possible n-gram,
whereas the use of :math:`k` different independent hash functions gives
you :math:`\\sum_{j=1}^{k}{\\binom{l}{j}}`
combinations.
**Our construction**
It is advantageous to construct Bloom filters using a family of hash
functions with the property of
`k-independence <https://en.wikipedia.org/wiki/K-independent_hashing>`_
to compute the indices for an entry.
This approach minimises the change of collisions.
An informal definition of *k-independence* of a family of hash functions
is, that if selecting a function at random
from the family, it guarantees that the hash codes of any designated k
keys are independent random variables.
Our construction utilises the fact that the output bits of a
cryptographic hash function are uniformly distributed,
independent, binary random variables (well, at least as close to as
possible. See [Kaminsky2011]_ for an analysis).
Thus, slicing the output of a cryptographic hash function into k
different slices gives you k independent random
variables.
We chose Blake2 as the cryptographic hash function mainly for two reasons:
* it is fast.
* in keyed hashing mode, Blake2 provides MACs with just one hash
function call instead of the two calls in the HMAC construction used
in the double hashing scheme.
.. warning::
Please be aware that, although this construction makes the attack of
[Kroll2015]_ infeasible, it is most likely
not enough to ensure security. Or in their own words:
| However, we think that using independent hash functions alone
will not be sufficient to ensure security,
since in this case other approaches (maybe related to or at least
inspired through work from the
area of Frequent Itemset Mining) are promising to detect at least
the most frequent atoms automatically.
:param ngrams: list of n-grams to be encoded
:param keys: secret key for blake2 as bytes
:param ks: ks[i] is k value to use for ngram[i]
:param l: length of the output bitarray (has to be a power of 2)
:param encoding: the encoding to use when turning the ngrams to bytes
:return: bitarray of length l with the bits set which correspond to the
encoding of the ngrams | [
"Computes",
"the",
"encoding",
"of",
"the",
"ngrams",
"using",
"the",
"BLAKE2",
"hash",
"function",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/bloomfilter.py#L140-L235 | train | 42,274 |
data61/clkhash | clkhash/bloomfilter.py | fold_xor | def fold_xor(bloomfilter, # type: bitarray
folds # type: int
):
# type: (...) -> bitarray
""" Performs XOR folding on a Bloom filter.
If the length of the original Bloom filter is n and we perform
r folds, then the length of the resulting filter is n / 2 ** r.
:param bloomfilter: Bloom filter to fold
:param folds: number of folds
:return: folded bloom filter
"""
if len(bloomfilter) % 2 ** folds != 0:
msg = ('The length of the bloom filter is {length}. It is not '
'divisible by 2 ** {folds}, so it cannot be folded {folds} '
'times.'
.format(length=len(bloomfilter), folds=folds))
raise ValueError(msg)
for _ in range(folds):
bf1 = bloomfilter[:len(bloomfilter) // 2]
bf2 = bloomfilter[len(bloomfilter) // 2:]
bloomfilter = bf1 ^ bf2
return bloomfilter | python | def fold_xor(bloomfilter, # type: bitarray
folds # type: int
):
# type: (...) -> bitarray
""" Performs XOR folding on a Bloom filter.
If the length of the original Bloom filter is n and we perform
r folds, then the length of the resulting filter is n / 2 ** r.
:param bloomfilter: Bloom filter to fold
:param folds: number of folds
:return: folded bloom filter
"""
if len(bloomfilter) % 2 ** folds != 0:
msg = ('The length of the bloom filter is {length}. It is not '
'divisible by 2 ** {folds}, so it cannot be folded {folds} '
'times.'
.format(length=len(bloomfilter), folds=folds))
raise ValueError(msg)
for _ in range(folds):
bf1 = bloomfilter[:len(bloomfilter) // 2]
bf2 = bloomfilter[len(bloomfilter) // 2:]
bloomfilter = bf1 ^ bf2
return bloomfilter | [
"def",
"fold_xor",
"(",
"bloomfilter",
",",
"# type: bitarray",
"folds",
"# type: int",
")",
":",
"# type: (...) -> bitarray",
"if",
"len",
"(",
"bloomfilter",
")",
"%",
"2",
"**",
"folds",
"!=",
"0",
":",
"msg",
"=",
"(",
"'The length of the bloom filter is {leng... | Performs XOR folding on a Bloom filter.
If the length of the original Bloom filter is n and we perform
r folds, then the length of the resulting filter is n / 2 ** r.
:param bloomfilter: Bloom filter to fold
:param folds: number of folds
:return: folded bloom filter | [
"Performs",
"XOR",
"folding",
"on",
"a",
"Bloom",
"filter",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/bloomfilter.py#L258-L286 | train | 42,275 |
data61/clkhash | clkhash/bloomfilter.py | crypto_bloom_filter | def crypto_bloom_filter(record, # type: Sequence[Text]
tokenizers, # type: List[Callable[[Text, Optional[Text]], Iterable[Text]]]
schema, # type: Schema
keys # type: Sequence[Sequence[bytes]]
):
# type: (...) -> Tuple[bitarray, Text, int]
""" Computes the composite Bloom filter encoding of a record.
Using the method from
http://www.record-linkage.de/-download=wp-grlc-2011-02.pdf
:param record: plaintext record tuple. E.g. (index, name, dob, gender)
:param tokenizers: A list of tokenizers. A tokenizer is a function that
returns tokens from a string.
:param schema: Schema
:param keys: Keys for the hash functions as a tuple of lists of bytes.
:return: 3-tuple:
- bloom filter for record as a bitarray
- first element of record (usually an index)
- number of bits set in the bloomfilter
"""
hash_l = schema.l * 2 ** schema.xor_folds
bloomfilter = bitarray(hash_l)
bloomfilter.setall(False)
for (entry, tokenize, field, key) \
in zip(record, tokenizers, schema.fields, keys):
fhp = field.hashing_properties
if fhp:
ngrams = list(tokenize(field.format_value(entry)))
hash_function = hashing_function_from_properties(fhp)
bloomfilter |= hash_function(ngrams, key,
fhp.ks(len(ngrams)),
hash_l, fhp.encoding)
c1 = bloomfilter.count()
bloomfilter = fold_xor(bloomfilter, schema.xor_folds)
c2 = bloomfilter.count()
return bloomfilter, record[0], bloomfilter.count() | python | def crypto_bloom_filter(record, # type: Sequence[Text]
tokenizers, # type: List[Callable[[Text, Optional[Text]], Iterable[Text]]]
schema, # type: Schema
keys # type: Sequence[Sequence[bytes]]
):
# type: (...) -> Tuple[bitarray, Text, int]
""" Computes the composite Bloom filter encoding of a record.
Using the method from
http://www.record-linkage.de/-download=wp-grlc-2011-02.pdf
:param record: plaintext record tuple. E.g. (index, name, dob, gender)
:param tokenizers: A list of tokenizers. A tokenizer is a function that
returns tokens from a string.
:param schema: Schema
:param keys: Keys for the hash functions as a tuple of lists of bytes.
:return: 3-tuple:
- bloom filter for record as a bitarray
- first element of record (usually an index)
- number of bits set in the bloomfilter
"""
hash_l = schema.l * 2 ** schema.xor_folds
bloomfilter = bitarray(hash_l)
bloomfilter.setall(False)
for (entry, tokenize, field, key) \
in zip(record, tokenizers, schema.fields, keys):
fhp = field.hashing_properties
if fhp:
ngrams = list(tokenize(field.format_value(entry)))
hash_function = hashing_function_from_properties(fhp)
bloomfilter |= hash_function(ngrams, key,
fhp.ks(len(ngrams)),
hash_l, fhp.encoding)
c1 = bloomfilter.count()
bloomfilter = fold_xor(bloomfilter, schema.xor_folds)
c2 = bloomfilter.count()
return bloomfilter, record[0], bloomfilter.count() | [
"def",
"crypto_bloom_filter",
"(",
"record",
",",
"# type: Sequence[Text]",
"tokenizers",
",",
"# type: List[Callable[[Text, Optional[Text]], Iterable[Text]]]",
"schema",
",",
"# type: Schema",
"keys",
"# type: Sequence[Sequence[bytes]]",
")",
":",
"# type: (...) -> Tuple[bitarray, T... | Computes the composite Bloom filter encoding of a record.
Using the method from
http://www.record-linkage.de/-download=wp-grlc-2011-02.pdf
:param record: plaintext record tuple. E.g. (index, name, dob, gender)
:param tokenizers: A list of tokenizers. A tokenizer is a function that
returns tokens from a string.
:param schema: Schema
:param keys: Keys for the hash functions as a tuple of lists of bytes.
:return: 3-tuple:
- bloom filter for record as a bitarray
- first element of record (usually an index)
- number of bits set in the bloomfilter | [
"Computes",
"the",
"composite",
"Bloom",
"filter",
"encoding",
"of",
"a",
"record",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/bloomfilter.py#L289-L329 | train | 42,276 |
data61/clkhash | clkhash/backports.py | re_compile_full | def re_compile_full(pattern, flags=0):
# type: (AnyStr, int) -> Pattern
""" Create compiled regular expression such that it matches the
entire string. Calling re.match on the output of this function
is equivalent to calling re.fullmatch on its input.
This is needed to support Python 2. (On Python 3, we would just
call re.fullmatch.)
Kudos: https://stackoverflow.com/a/30212799
:param pattern: The pattern to compile.
:param flags: Regular expression flags. Refer to Python
documentation.
:returns: A compiled regular expression.
"""
# Don't worry, this short-circuits.
assert type(pattern) is str or type(pattern) is unicode # type: ignore
return re.compile(r'(?:{})\Z'.format(pattern), flags=flags) | python | def re_compile_full(pattern, flags=0):
# type: (AnyStr, int) -> Pattern
""" Create compiled regular expression such that it matches the
entire string. Calling re.match on the output of this function
is equivalent to calling re.fullmatch on its input.
This is needed to support Python 2. (On Python 3, we would just
call re.fullmatch.)
Kudos: https://stackoverflow.com/a/30212799
:param pattern: The pattern to compile.
:param flags: Regular expression flags. Refer to Python
documentation.
:returns: A compiled regular expression.
"""
# Don't worry, this short-circuits.
assert type(pattern) is str or type(pattern) is unicode # type: ignore
return re.compile(r'(?:{})\Z'.format(pattern), flags=flags) | [
"def",
"re_compile_full",
"(",
"pattern",
",",
"flags",
"=",
"0",
")",
":",
"# type: (AnyStr, int) -> Pattern",
"# Don't worry, this short-circuits.",
"assert",
"type",
"(",
"pattern",
")",
"is",
"str",
"or",
"type",
"(",
"pattern",
")",
"is",
"unicode",
"# type: ... | Create compiled regular expression such that it matches the
entire string. Calling re.match on the output of this function
is equivalent to calling re.fullmatch on its input.
This is needed to support Python 2. (On Python 3, we would just
call re.fullmatch.)
Kudos: https://stackoverflow.com/a/30212799
:param pattern: The pattern to compile.
:param flags: Regular expression flags. Refer to Python
documentation.
:returns: A compiled regular expression. | [
"Create",
"compiled",
"regular",
"expression",
"such",
"that",
"it",
"matches",
"the",
"entire",
"string",
".",
"Calling",
"re",
".",
"match",
"on",
"the",
"output",
"of",
"this",
"function",
"is",
"equivalent",
"to",
"calling",
"re",
".",
"fullmatch",
"on",... | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/backports.py#L53-L72 | train | 42,277 |
data61/clkhash | clkhash/backports.py | _p2_unicode_reader | def _p2_unicode_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
""" Encode Unicode as UTF-8 and parse as CSV.
This is needed since Python 2's `csv` doesn't do Unicode.
Kudos: https://docs.python.org/2/library/csv.html#examples
:param unicode_csv_data: The Unicode stream to parse.
:param dialect: The CSV dialect to use.
:param kwargs: Any other parameters to pass to csv.reader.
:returns: An iterator
"""
# Encode temporarily as UTF-8:
utf8_csv_data = _utf_8_encoder(unicode_csv_data)
# Now we can parse!
csv_reader = csv.reader(utf8_csv_data, dialect=dialect, **kwargs)
# Decode UTF-8 back to Unicode, cell by cell:
return ([unicode(cell, 'utf-8') for cell in row] for row in csv_reader) | python | def _p2_unicode_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
""" Encode Unicode as UTF-8 and parse as CSV.
This is needed since Python 2's `csv` doesn't do Unicode.
Kudos: https://docs.python.org/2/library/csv.html#examples
:param unicode_csv_data: The Unicode stream to parse.
:param dialect: The CSV dialect to use.
:param kwargs: Any other parameters to pass to csv.reader.
:returns: An iterator
"""
# Encode temporarily as UTF-8:
utf8_csv_data = _utf_8_encoder(unicode_csv_data)
# Now we can parse!
csv_reader = csv.reader(utf8_csv_data, dialect=dialect, **kwargs)
# Decode UTF-8 back to Unicode, cell by cell:
return ([unicode(cell, 'utf-8') for cell in row] for row in csv_reader) | [
"def",
"_p2_unicode_reader",
"(",
"unicode_csv_data",
",",
"dialect",
"=",
"csv",
".",
"excel",
",",
"*",
"*",
"kwargs",
")",
":",
"# Encode temporarily as UTF-8:",
"utf8_csv_data",
"=",
"_utf_8_encoder",
"(",
"unicode_csv_data",
")",
"# Now we can parse!",
"csv_reade... | Encode Unicode as UTF-8 and parse as CSV.
This is needed since Python 2's `csv` doesn't do Unicode.
Kudos: https://docs.python.org/2/library/csv.html#examples
:param unicode_csv_data: The Unicode stream to parse.
:param dialect: The CSV dialect to use.
:param kwargs: Any other parameters to pass to csv.reader.
:returns: An iterator | [
"Encode",
"Unicode",
"as",
"UTF",
"-",
"8",
"and",
"parse",
"as",
"CSV",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/backports.py#L79-L99 | train | 42,278 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/preprocessing.py | get_list_dimensions | def get_list_dimensions(_list):
"""
Takes a nested list and returns the size of each dimension followed
by the element type in the list
"""
if isinstance(_list, list) or isinstance(_list, tuple):
return [len(_list)] + get_list_dimensions(_list[0])
return [] | python | def get_list_dimensions(_list):
"""
Takes a nested list and returns the size of each dimension followed
by the element type in the list
"""
if isinstance(_list, list) or isinstance(_list, tuple):
return [len(_list)] + get_list_dimensions(_list[0])
return [] | [
"def",
"get_list_dimensions",
"(",
"_list",
")",
":",
"if",
"isinstance",
"(",
"_list",
",",
"list",
")",
"or",
"isinstance",
"(",
"_list",
",",
"tuple",
")",
":",
"return",
"[",
"len",
"(",
"_list",
")",
"]",
"+",
"get_list_dimensions",
"(",
"_list",
... | Takes a nested list and returns the size of each dimension followed
by the element type in the list | [
"Takes",
"a",
"nested",
"list",
"and",
"returns",
"the",
"size",
"of",
"each",
"dimension",
"followed",
"by",
"the",
"element",
"type",
"in",
"the",
"list"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/preprocessing.py#L99-L106 | train | 42,279 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/preprocessing.py | get_element_type | def get_element_type(_list, dimens):
"""
Given the dimensions of a nested list and the list, returns the type of the
elements in the inner list.
"""
elem = _list
for _ in range(len(dimens)):
elem = elem[0]
return type(elem) | python | def get_element_type(_list, dimens):
"""
Given the dimensions of a nested list and the list, returns the type of the
elements in the inner list.
"""
elem = _list
for _ in range(len(dimens)):
elem = elem[0]
return type(elem) | [
"def",
"get_element_type",
"(",
"_list",
",",
"dimens",
")",
":",
"elem",
"=",
"_list",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"dimens",
")",
")",
":",
"elem",
"=",
"elem",
"[",
"0",
"]",
"return",
"type",
"(",
"elem",
")"
] | Given the dimensions of a nested list and the list, returns the type of the
elements in the inner list. | [
"Given",
"the",
"dimensions",
"of",
"a",
"nested",
"list",
"and",
"the",
"list",
"returns",
"the",
"type",
"of",
"the",
"elements",
"in",
"the",
"inner",
"list",
"."
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/preprocessing.py#L109-L117 | train | 42,280 |
IndicoDataSolutions/IndicoIo-python | indicoio/image/image_recognition.py | image_recognition | def image_recognition(image, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given an input image, returns a dictionary of image classifications with associated scores
* Input can be either grayscale or rgb color and should either be a numpy array or nested list format.
* Input data should be either uint8 0-255 range values or floating point between 0 and 1.
* Large images (i.e. 1024x768+) are much bigger than needed, minaxis resizing will be done internally to 144 if needed.
* For ideal performance, images should be square aspect ratio but non-square aspect ratios are supported as well.
Example usage:
.. code-block:: python
>>> from indicoio import image_recognition
>>> features = image_recognition(<filename>)
:param image: The image to be analyzed.
:type image: str
:rtype: dict containing classifications
"""
image = data_preprocess(image, batch=batch, size=144, min_axis=True)
url_params = {"batch": batch, "api_key": api_key, "version": version}
return api_handler(image, cloud=cloud, api="imagerecognition", url_params=url_params, **kwargs) | python | def image_recognition(image, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given an input image, returns a dictionary of image classifications with associated scores
* Input can be either grayscale or rgb color and should either be a numpy array or nested list format.
* Input data should be either uint8 0-255 range values or floating point between 0 and 1.
* Large images (i.e. 1024x768+) are much bigger than needed, minaxis resizing will be done internally to 144 if needed.
* For ideal performance, images should be square aspect ratio but non-square aspect ratios are supported as well.
Example usage:
.. code-block:: python
>>> from indicoio import image_recognition
>>> features = image_recognition(<filename>)
:param image: The image to be analyzed.
:type image: str
:rtype: dict containing classifications
"""
image = data_preprocess(image, batch=batch, size=144, min_axis=True)
url_params = {"batch": batch, "api_key": api_key, "version": version}
return api_handler(image, cloud=cloud, api="imagerecognition", url_params=url_params, **kwargs) | [
"def",
"image_recognition",
"(",
"image",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"image",
"=",
"data_preprocess",
"(",
"image",
",",
"batch",
... | Given an input image, returns a dictionary of image classifications with associated scores
* Input can be either grayscale or rgb color and should either be a numpy array or nested list format.
* Input data should be either uint8 0-255 range values or floating point between 0 and 1.
* Large images (i.e. 1024x768+) are much bigger than needed, minaxis resizing will be done internally to 144 if needed.
* For ideal performance, images should be square aspect ratio but non-square aspect ratios are supported as well.
Example usage:
.. code-block:: python
>>> from indicoio import image_recognition
>>> features = image_recognition(<filename>)
:param image: The image to be analyzed.
:type image: str
:rtype: dict containing classifications | [
"Given",
"an",
"input",
"image",
"returns",
"a",
"dictionary",
"of",
"image",
"classifications",
"with",
"associated",
"scores"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/image/image_recognition.py#L7-L29 | train | 42,281 |
data61/clkhash | clkhash/field_formats.py | spec_from_json_dict | def spec_from_json_dict(
json_dict # type: Dict[str, Any]
):
# type: (...) -> FieldSpec
""" Turns a dictionary into the appropriate object.
:param dict json_dict: A dictionary with properties.
:returns: An initialised instance of the appropriate FieldSpec
subclass.
"""
if 'ignored' in json_dict:
return Ignore(json_dict['identifier'])
type_str = json_dict['format']['type']
spec_type = cast(FieldSpec, FIELD_TYPE_MAP[type_str])
return spec_type.from_json_dict(json_dict) | python | def spec_from_json_dict(
json_dict # type: Dict[str, Any]
):
# type: (...) -> FieldSpec
""" Turns a dictionary into the appropriate object.
:param dict json_dict: A dictionary with properties.
:returns: An initialised instance of the appropriate FieldSpec
subclass.
"""
if 'ignored' in json_dict:
return Ignore(json_dict['identifier'])
type_str = json_dict['format']['type']
spec_type = cast(FieldSpec, FIELD_TYPE_MAP[type_str])
return spec_type.from_json_dict(json_dict) | [
"def",
"spec_from_json_dict",
"(",
"json_dict",
"# type: Dict[str, Any]",
")",
":",
"# type: (...) -> FieldSpec",
"if",
"'ignored'",
"in",
"json_dict",
":",
"return",
"Ignore",
"(",
"json_dict",
"[",
"'identifier'",
"]",
")",
"type_str",
"=",
"json_dict",
"[",
"'for... | Turns a dictionary into the appropriate object.
:param dict json_dict: A dictionary with properties.
:returns: An initialised instance of the appropriate FieldSpec
subclass. | [
"Turns",
"a",
"dictionary",
"into",
"the",
"appropriate",
"object",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/field_formats.py#L842-L856 | train | 42,282 |
data61/clkhash | clkhash/field_formats.py | FieldHashingProperties.replace_missing_value | def replace_missing_value(self, str_in):
# type: (Text) -> Text
""" returns 'str_in' if it is not equals to the 'sentinel' as
defined in the missingValue section of
the schema. Else it will return the 'replaceWith' value.
:param str_in:
:return: str_in or the missingValue replacement value
"""
if self.missing_value is None:
return str_in
elif self.missing_value.sentinel == str_in:
return self.missing_value.replace_with
else:
return str_in | python | def replace_missing_value(self, str_in):
# type: (Text) -> Text
""" returns 'str_in' if it is not equals to the 'sentinel' as
defined in the missingValue section of
the schema. Else it will return the 'replaceWith' value.
:param str_in:
:return: str_in or the missingValue replacement value
"""
if self.missing_value is None:
return str_in
elif self.missing_value.sentinel == str_in:
return self.missing_value.replace_with
else:
return str_in | [
"def",
"replace_missing_value",
"(",
"self",
",",
"str_in",
")",
":",
"# type: (Text) -> Text",
"if",
"self",
".",
"missing_value",
"is",
"None",
":",
"return",
"str_in",
"elif",
"self",
".",
"missing_value",
".",
"sentinel",
"==",
"str_in",
":",
"return",
"se... | returns 'str_in' if it is not equals to the 'sentinel' as
defined in the missingValue section of
the schema. Else it will return the 'replaceWith' value.
:param str_in:
:return: str_in or the missingValue replacement value | [
"returns",
"str_in",
"if",
"it",
"is",
"not",
"equals",
"to",
"the",
"sentinel",
"as",
"defined",
"in",
"the",
"missingValue",
"section",
"of",
"the",
"schema",
".",
"Else",
"it",
"will",
"return",
"the",
"replaceWith",
"value",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/field_formats.py#L140-L154 | train | 42,283 |
data61/clkhash | clkhash/field_formats.py | StringSpec.from_json_dict | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> StringSpec
""" Make a StringSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'encoding'` key associated with a Python-conformant
encoding. It must also contain a `'hashing'` key, whose
contents are passed to :class:`FieldHashingProperties`.
Permitted keys also include `'pattern'`, `'case'`,
`'minLength'`, and `'maxLength'`.
:raises InvalidSchemaError: When a regular expression is
provided but is not a valid pattern.
"""
# noinspection PyCompatibility
result = cast(StringSpec, # Go away, Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
if 'encoding' in format_ and result.hashing_properties:
result.hashing_properties.encoding = format_['encoding']
if 'pattern' in format_:
pattern = format_['pattern']
try:
result.regex = re_compile_full(pattern)
except (SyntaxError, re.error) as e:
msg = "Invalid regular expression '{}.'".format(pattern)
e_new = InvalidSchemaError(msg)
raise_from(e_new, e)
result.regex_based = True
else:
result.case = format_.get('case', StringSpec._DEFAULT_CASE)
result.min_length = format_.get('minLength')
result.max_length = format_.get('maxLength')
result.regex_based = False
return result | python | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> StringSpec
""" Make a StringSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'encoding'` key associated with a Python-conformant
encoding. It must also contain a `'hashing'` key, whose
contents are passed to :class:`FieldHashingProperties`.
Permitted keys also include `'pattern'`, `'case'`,
`'minLength'`, and `'maxLength'`.
:raises InvalidSchemaError: When a regular expression is
provided but is not a valid pattern.
"""
# noinspection PyCompatibility
result = cast(StringSpec, # Go away, Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
if 'encoding' in format_ and result.hashing_properties:
result.hashing_properties.encoding = format_['encoding']
if 'pattern' in format_:
pattern = format_['pattern']
try:
result.regex = re_compile_full(pattern)
except (SyntaxError, re.error) as e:
msg = "Invalid regular expression '{}.'".format(pattern)
e_new = InvalidSchemaError(msg)
raise_from(e_new, e)
result.regex_based = True
else:
result.case = format_.get('case', StringSpec._DEFAULT_CASE)
result.min_length = format_.get('minLength')
result.max_length = format_.get('maxLength')
result.regex_based = False
return result | [
"def",
"from_json_dict",
"(",
"cls",
",",
"json_dict",
"# type: Dict[str, Any]",
")",
":",
"# type: (...) -> StringSpec",
"# noinspection PyCompatibility",
"result",
"=",
"cast",
"(",
"StringSpec",
",",
"# Go away, Mypy.",
"super",
"(",
")",
".",
"from_json_dict",
"(",
... | Make a StringSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'encoding'` key associated with a Python-conformant
encoding. It must also contain a `'hashing'` key, whose
contents are passed to :class:`FieldHashingProperties`.
Permitted keys also include `'pattern'`, `'case'`,
`'minLength'`, and `'maxLength'`.
:raises InvalidSchemaError: When a regular expression is
provided but is not a valid pattern. | [
"Make",
"a",
"StringSpec",
"object",
"from",
"a",
"dictionary",
"containing",
"its",
"properties",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/field_formats.py#L413-L453 | train | 42,284 |
data61/clkhash | clkhash/field_formats.py | IntegerSpec.from_json_dict | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> IntegerSpec
""" Make a IntegerSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary may contain
`'minimum'` and `'maximum'` keys. In addition, it must
contain a `'hashing'` key, whose contents are passed to
:class:`FieldHashingProperties`.
:param dict json_dict: The properties dictionary.
"""
# noinspection PyCompatibility
result = cast(IntegerSpec, # For Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
result.minimum = format_.get('minimum')
result.maximum = format_.get('maximum')
return result | python | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> IntegerSpec
""" Make a IntegerSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary may contain
`'minimum'` and `'maximum'` keys. In addition, it must
contain a `'hashing'` key, whose contents are passed to
:class:`FieldHashingProperties`.
:param dict json_dict: The properties dictionary.
"""
# noinspection PyCompatibility
result = cast(IntegerSpec, # For Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
result.minimum = format_.get('minimum')
result.maximum = format_.get('maximum')
return result | [
"def",
"from_json_dict",
"(",
"cls",
",",
"json_dict",
"# type: Dict[str, Any]",
")",
":",
"# type: (...) -> IntegerSpec",
"# noinspection PyCompatibility",
"result",
"=",
"cast",
"(",
"IntegerSpec",
",",
"# For Mypy.",
"super",
"(",
")",
".",
"from_json_dict",
"(",
"... | Make a IntegerSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary may contain
`'minimum'` and `'maximum'` keys. In addition, it must
contain a `'hashing'` key, whose contents are passed to
:class:`FieldHashingProperties`.
:param dict json_dict: The properties dictionary. | [
"Make",
"a",
"IntegerSpec",
"object",
"from",
"a",
"dictionary",
"containing",
"its",
"properties",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/field_formats.py#L553-L575 | train | 42,285 |
data61/clkhash | clkhash/field_formats.py | DateSpec.from_json_dict | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> DateSpec
""" Make a DateSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain a
`'format'` key. In addition, it must contain a
`'hashing'` key, whose contents are passed to
:class:`FieldHashingProperties`.
:param json_dict: The properties dictionary.
"""
# noinspection PyCompatibility
result = cast(DateSpec, # For Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
result.format = format_['format']
return result | python | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> DateSpec
""" Make a DateSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain a
`'format'` key. In addition, it must contain a
`'hashing'` key, whose contents are passed to
:class:`FieldHashingProperties`.
:param json_dict: The properties dictionary.
"""
# noinspection PyCompatibility
result = cast(DateSpec, # For Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
result.format = format_['format']
return result | [
"def",
"from_json_dict",
"(",
"cls",
",",
"json_dict",
"# type: Dict[str, Any]",
")",
":",
"# type: (...) -> DateSpec",
"# noinspection PyCompatibility",
"result",
"=",
"cast",
"(",
"DateSpec",
",",
"# For Mypy.",
"super",
"(",
")",
".",
"from_json_dict",
"(",
"json_d... | Make a DateSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain a
`'format'` key. In addition, it must contain a
`'hashing'` key, whose contents are passed to
:class:`FieldHashingProperties`.
:param json_dict: The properties dictionary. | [
"Make",
"a",
"DateSpec",
"object",
"from",
"a",
"dictionary",
"containing",
"its",
"properties",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/field_formats.py#L676-L697 | train | 42,286 |
data61/clkhash | clkhash/field_formats.py | EnumSpec.from_json_dict | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> EnumSpec
""" Make a EnumSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'enum'` key specifying the permitted values. In
addition, it must contain a `'hashing'` key, whose
contents are passed to :class:`FieldHashingProperties`.
"""
# noinspection PyCompatibility
result = cast(EnumSpec, # Appease the gods of Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
result.values = set(format_['values'])
return result | python | def from_json_dict(cls,
json_dict # type: Dict[str, Any]
):
# type: (...) -> EnumSpec
""" Make a EnumSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'enum'` key specifying the permitted values. In
addition, it must contain a `'hashing'` key, whose
contents are passed to :class:`FieldHashingProperties`.
"""
# noinspection PyCompatibility
result = cast(EnumSpec, # Appease the gods of Mypy.
super().from_json_dict(json_dict))
format_ = json_dict['format']
result.values = set(format_['values'])
return result | [
"def",
"from_json_dict",
"(",
"cls",
",",
"json_dict",
"# type: Dict[str, Any]",
")",
":",
"# type: (...) -> EnumSpec",
"# noinspection PyCompatibility",
"result",
"=",
"cast",
"(",
"EnumSpec",
",",
"# Appease the gods of Mypy.",
"super",
"(",
")",
".",
"from_json_dict",
... | Make a EnumSpec object from a dictionary containing its
properties.
:param dict json_dict: This dictionary must contain an
`'enum'` key specifying the permitted values. In
addition, it must contain a `'hashing'` key, whose
contents are passed to :class:`FieldHashingProperties`. | [
"Make",
"a",
"EnumSpec",
"object",
"from",
"a",
"dictionary",
"containing",
"its",
"properties",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/field_formats.py#L770-L789 | train | 42,287 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/api.py | standardize_input_data | def standardize_input_data(data):
"""
Ensure utf-8 encoded strings are passed to the indico API
"""
if type(data) == bytes:
data = data.decode('utf-8')
if type(data) == list:
data = [
el.decode('utf-8') if type(data) == bytes else el
for el in data
]
return data | python | def standardize_input_data(data):
"""
Ensure utf-8 encoded strings are passed to the indico API
"""
if type(data) == bytes:
data = data.decode('utf-8')
if type(data) == list:
data = [
el.decode('utf-8') if type(data) == bytes else el
for el in data
]
return data | [
"def",
"standardize_input_data",
"(",
"data",
")",
":",
"if",
"type",
"(",
"data",
")",
"==",
"bytes",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"type",
"(",
"data",
")",
"==",
"list",
":",
"data",
"=",
"[",
"el",
".",
"... | Ensure utf-8 encoded strings are passed to the indico API | [
"Ensure",
"utf",
"-",
"8",
"encoded",
"strings",
"are",
"passed",
"to",
"the",
"indico",
"API"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/api.py#L49-L60 | train | 42,288 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/api.py | api_handler | def api_handler(input_data, cloud, api, url_params=None, batch_size=None, **kwargs):
"""
Sends finalized request data to ML server and receives response.
If a batch_size is specified, breaks down a request into smaller
component requests and aggregates the results.
"""
url_params = url_params or {}
input_data = standardize_input_data(input_data)
cloud = cloud or config.cloud
host = "%s.indico.domains" % cloud if cloud else config.host
# LOCAL DEPLOYMENTS
if not (host.endswith('indico.domains') or host.endswith('indico.io')):
url_protocol = "http"
else:
url_protocol = config.url_protocol
headers = dict(JSON_HEADERS)
headers["X-ApiKey"] = url_params.get("api_key") or config.api_key
url = create_url(url_protocol, host, api, dict(kwargs, **url_params))
return collect_api_results(input_data, url, headers, api, batch_size, kwargs) | python | def api_handler(input_data, cloud, api, url_params=None, batch_size=None, **kwargs):
"""
Sends finalized request data to ML server and receives response.
If a batch_size is specified, breaks down a request into smaller
component requests and aggregates the results.
"""
url_params = url_params or {}
input_data = standardize_input_data(input_data)
cloud = cloud or config.cloud
host = "%s.indico.domains" % cloud if cloud else config.host
# LOCAL DEPLOYMENTS
if not (host.endswith('indico.domains') or host.endswith('indico.io')):
url_protocol = "http"
else:
url_protocol = config.url_protocol
headers = dict(JSON_HEADERS)
headers["X-ApiKey"] = url_params.get("api_key") or config.api_key
url = create_url(url_protocol, host, api, dict(kwargs, **url_params))
return collect_api_results(input_data, url, headers, api, batch_size, kwargs) | [
"def",
"api_handler",
"(",
"input_data",
",",
"cloud",
",",
"api",
",",
"url_params",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url_params",
"=",
"url_params",
"or",
"{",
"}",
"input_data",
"=",
"standardize_input_dat... | Sends finalized request data to ML server and receives response.
If a batch_size is specified, breaks down a request into smaller
component requests and aggregates the results. | [
"Sends",
"finalized",
"request",
"data",
"to",
"ML",
"server",
"and",
"receives",
"response",
".",
"If",
"a",
"batch_size",
"is",
"specified",
"breaks",
"down",
"a",
"request",
"into",
"smaller",
"component",
"requests",
"and",
"aggregates",
"the",
"results",
... | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/api.py#L63-L84 | train | 42,289 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/api.py | collect_api_results | def collect_api_results(input_data, url, headers, api, batch_size, kwargs):
"""
Optionally split up a single request into a series of requests
to ensure timely HTTP responses.
Could eventually speed up the time required to receive a response by
sending batches to the indico API concurrently
"""
if batch_size:
results = []
for batch in batched(input_data, size=batch_size):
try:
result = send_request(batch, api, url, headers, kwargs)
if isinstance(result, list):
results.extend(result)
else:
results.append(result)
except IndicoError as e:
# Log results so far to file
timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
filename = "indico-{api}-{timestamp}.json".format(
api=api,
timestamp=timestamp
)
if sys.version_info > (3, 0):
json.dump(results, open(filename, mode='w', encoding='utf-8'), cls=NumpyEncoder)
else:
json.dump(results, open(filename, mode='w'), cls=NumpyEncoder)
raise BatchProcessingError(
"The following error occurred while processing your data: `{err}` "
"Partial results have been saved to {filename}".format(
err=e,
filename=os.path.abspath(filename)
)
)
return results
else:
return send_request(input_data, api, url, headers, kwargs) | python | def collect_api_results(input_data, url, headers, api, batch_size, kwargs):
"""
Optionally split up a single request into a series of requests
to ensure timely HTTP responses.
Could eventually speed up the time required to receive a response by
sending batches to the indico API concurrently
"""
if batch_size:
results = []
for batch in batched(input_data, size=batch_size):
try:
result = send_request(batch, api, url, headers, kwargs)
if isinstance(result, list):
results.extend(result)
else:
results.append(result)
except IndicoError as e:
# Log results so far to file
timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
filename = "indico-{api}-{timestamp}.json".format(
api=api,
timestamp=timestamp
)
if sys.version_info > (3, 0):
json.dump(results, open(filename, mode='w', encoding='utf-8'), cls=NumpyEncoder)
else:
json.dump(results, open(filename, mode='w'), cls=NumpyEncoder)
raise BatchProcessingError(
"The following error occurred while processing your data: `{err}` "
"Partial results have been saved to {filename}".format(
err=e,
filename=os.path.abspath(filename)
)
)
return results
else:
return send_request(input_data, api, url, headers, kwargs) | [
"def",
"collect_api_results",
"(",
"input_data",
",",
"url",
",",
"headers",
",",
"api",
",",
"batch_size",
",",
"kwargs",
")",
":",
"if",
"batch_size",
":",
"results",
"=",
"[",
"]",
"for",
"batch",
"in",
"batched",
"(",
"input_data",
",",
"size",
"=",
... | Optionally split up a single request into a series of requests
to ensure timely HTTP responses.
Could eventually speed up the time required to receive a response by
sending batches to the indico API concurrently | [
"Optionally",
"split",
"up",
"a",
"single",
"request",
"into",
"a",
"series",
"of",
"requests",
"to",
"ensure",
"timely",
"HTTP",
"responses",
"."
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/api.py#L87-L124 | train | 42,290 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/api.py | send_request | def send_request(input_data, api, url, headers, kwargs):
"""
Use the requests library to send of an HTTP call to the indico servers
"""
data = {}
if input_data != None:
data['data'] = input_data
# request that the API respond with a msgpack encoded result
serializer = kwargs.pop("serializer", config.serializer)
data['serializer'] = serializer
data.update(**kwargs)
json_data = json.dumps(data)
response = requests.post(url, data=json_data, headers=headers)
warning = response.headers.get('x-warning')
if warning:
warnings.warn(warning)
cloud = urlparse(url).hostname
if response.status_code == 503 and not cloud.endswith('.indico.io'):
raise APIDoesNotExist("Private cloud '%s' does not include api '%s'" % (cloud, api))
try:
if serializer == 'msgpack':
json_results = msgpack.unpackb(response.content)
else:
json_results = response.json()
except (msgpack.exceptions.UnpackException, msgpack.exceptions.ExtraData):
try:
json_results = response.json()
except:
json_results = {"error": response.text}
if config.PY3:
json_results = convert(json_results)
results = json_results.get('results', False)
if results is False:
error = json_results.get('error')
raise convert_to_py_error(error)
return results | python | def send_request(input_data, api, url, headers, kwargs):
"""
Use the requests library to send of an HTTP call to the indico servers
"""
data = {}
if input_data != None:
data['data'] = input_data
# request that the API respond with a msgpack encoded result
serializer = kwargs.pop("serializer", config.serializer)
data['serializer'] = serializer
data.update(**kwargs)
json_data = json.dumps(data)
response = requests.post(url, data=json_data, headers=headers)
warning = response.headers.get('x-warning')
if warning:
warnings.warn(warning)
cloud = urlparse(url).hostname
if response.status_code == 503 and not cloud.endswith('.indico.io'):
raise APIDoesNotExist("Private cloud '%s' does not include api '%s'" % (cloud, api))
try:
if serializer == 'msgpack':
json_results = msgpack.unpackb(response.content)
else:
json_results = response.json()
except (msgpack.exceptions.UnpackException, msgpack.exceptions.ExtraData):
try:
json_results = response.json()
except:
json_results = {"error": response.text}
if config.PY3:
json_results = convert(json_results)
results = json_results.get('results', False)
if results is False:
error = json_results.get('error')
raise convert_to_py_error(error)
return results | [
"def",
"send_request",
"(",
"input_data",
",",
"api",
",",
"url",
",",
"headers",
",",
"kwargs",
")",
":",
"data",
"=",
"{",
"}",
"if",
"input_data",
"!=",
"None",
":",
"data",
"[",
"'data'",
"]",
"=",
"input_data",
"# request that the API respond with a msg... | Use the requests library to send of an HTTP call to the indico servers | [
"Use",
"the",
"requests",
"library",
"to",
"send",
"of",
"an",
"HTTP",
"call",
"to",
"the",
"indico",
"servers"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/api.py#L127-L172 | train | 42,291 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/api.py | create_url | def create_url(url_protocol, host, api, url_params):
"""
Generate the proper url for sending off data for analysis
"""
is_batch = url_params.pop("batch", None)
apis = url_params.pop("apis", None)
version = url_params.pop("version", None) or url_params.pop("v", None)
method = url_params.pop('method', None)
host_url_seg = url_protocol + "://%s" % host
api_url_seg = "/%s" % api
batch_url_seg = "/batch" if is_batch else ""
method_url_seg = "/%s" % method if method else ""
params = {}
if apis:
params["apis"] = ",".join(apis)
if version:
params["version"] = version
url = host_url_seg + api_url_seg + batch_url_seg + method_url_seg
if params:
url += "?" + urlencode(params)
return url | python | def create_url(url_protocol, host, api, url_params):
"""
Generate the proper url for sending off data for analysis
"""
is_batch = url_params.pop("batch", None)
apis = url_params.pop("apis", None)
version = url_params.pop("version", None) or url_params.pop("v", None)
method = url_params.pop('method', None)
host_url_seg = url_protocol + "://%s" % host
api_url_seg = "/%s" % api
batch_url_seg = "/batch" if is_batch else ""
method_url_seg = "/%s" % method if method else ""
params = {}
if apis:
params["apis"] = ",".join(apis)
if version:
params["version"] = version
url = host_url_seg + api_url_seg + batch_url_seg + method_url_seg
if params:
url += "?" + urlencode(params)
return url | [
"def",
"create_url",
"(",
"url_protocol",
",",
"host",
",",
"api",
",",
"url_params",
")",
":",
"is_batch",
"=",
"url_params",
".",
"pop",
"(",
"\"batch\"",
",",
"None",
")",
"apis",
"=",
"url_params",
".",
"pop",
"(",
"\"apis\"",
",",
"None",
")",
"ve... | Generate the proper url for sending off data for analysis | [
"Generate",
"the",
"proper",
"url",
"for",
"sending",
"off",
"data",
"for",
"analysis"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/api.py#L175-L199 | train | 42,292 |
IndicoDataSolutions/IndicoIo-python | indicoio/text/keywords.py | keywords | def keywords(text, cloud=None, batch=False, api_key=None, version=2, batch_size=None, **kwargs):
"""
Given input text, returns series of keywords and associated scores
Example usage:
.. code-block:: python
>>> import indicoio
>>> import numpy as np
>>> text = 'Monday: Delightful with mostly sunny skies. Highs in the low 70s.'
>>> keywords = indicoio.keywords(text, top_n=3)
>>> print "The keywords are: "+str(keywords.keys())
u'The keywords are ['delightful', 'highs', 'skies']
:param text: The text to be analyzed.
:type text: str or unicode
:rtype: Dictionary of feature score pairs
"""
if kwargs.get("language", "english") != "english":
version = 1
url_params = {"batch": batch, "api_key": api_key, "version": version}
return api_handler(text, cloud=cloud, api="keywords", url_params=url_params, batch_size=batch_size, **kwargs) | python | def keywords(text, cloud=None, batch=False, api_key=None, version=2, batch_size=None, **kwargs):
"""
Given input text, returns series of keywords and associated scores
Example usage:
.. code-block:: python
>>> import indicoio
>>> import numpy as np
>>> text = 'Monday: Delightful with mostly sunny skies. Highs in the low 70s.'
>>> keywords = indicoio.keywords(text, top_n=3)
>>> print "The keywords are: "+str(keywords.keys())
u'The keywords are ['delightful', 'highs', 'skies']
:param text: The text to be analyzed.
:type text: str or unicode
:rtype: Dictionary of feature score pairs
"""
if kwargs.get("language", "english") != "english":
version = 1
url_params = {"batch": batch, "api_key": api_key, "version": version}
return api_handler(text, cloud=cloud, api="keywords", url_params=url_params, batch_size=batch_size, **kwargs) | [
"def",
"keywords",
"(",
"text",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"2",
",",
"batch_size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"\"l... | Given input text, returns series of keywords and associated scores
Example usage:
.. code-block:: python
>>> import indicoio
>>> import numpy as np
>>> text = 'Monday: Delightful with mostly sunny skies. Highs in the low 70s.'
>>> keywords = indicoio.keywords(text, top_n=3)
>>> print "The keywords are: "+str(keywords.keys())
u'The keywords are ['delightful', 'highs', 'skies']
:param text: The text to be analyzed.
:type text: str or unicode
:rtype: Dictionary of feature score pairs | [
"Given",
"input",
"text",
"returns",
"series",
"of",
"keywords",
"and",
"associated",
"scores"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/text/keywords.py#L6-L28 | train | 42,293 |
IndicoDataSolutions/IndicoIo-python | indicoio/text/personas.py | personas | def personas(text, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given input text, returns the authors likelihood of being 16 different personality
types in a dict.
Example usage:
.. code-block:: python
>>> text = "I love going out with my friends"
>>> entities = indicoio.personas(text)
{'architect': 0.2191890478134155, 'logician': 0.0158474326133728,
'commander': 0.07654544115066528 ...}
:param text: The text to be analyzed.
:type text: str or unicode
:rtype: The authors 'Extraversion', 'Conscientiousness',
'Openness', and 'Agreeableness' score (a float between 0 and 1) in a dictionary.
"""
url_params = {"batch": batch, "api_key": api_key, "version": version}
kwargs['persona'] = True
return api_handler(text, cloud=cloud, api="personality", url_params=url_params, **kwargs) | python | def personas(text, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given input text, returns the authors likelihood of being 16 different personality
types in a dict.
Example usage:
.. code-block:: python
>>> text = "I love going out with my friends"
>>> entities = indicoio.personas(text)
{'architect': 0.2191890478134155, 'logician': 0.0158474326133728,
'commander': 0.07654544115066528 ...}
:param text: The text to be analyzed.
:type text: str or unicode
:rtype: The authors 'Extraversion', 'Conscientiousness',
'Openness', and 'Agreeableness' score (a float between 0 and 1) in a dictionary.
"""
url_params = {"batch": batch, "api_key": api_key, "version": version}
kwargs['persona'] = True
return api_handler(text, cloud=cloud, api="personality", url_params=url_params, **kwargs) | [
"def",
"personas",
"(",
"text",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url_params",
"=",
"{",
"\"batch\"",
":",
"batch",
",",
"\"api_key\"",... | Given input text, returns the authors likelihood of being 16 different personality
types in a dict.
Example usage:
.. code-block:: python
>>> text = "I love going out with my friends"
>>> entities = indicoio.personas(text)
{'architect': 0.2191890478134155, 'logician': 0.0158474326133728,
'commander': 0.07654544115066528 ...}
:param text: The text to be analyzed.
:type text: str or unicode
:rtype: The authors 'Extraversion', 'Conscientiousness',
'Openness', and 'Agreeableness' score (a float between 0 and 1) in a dictionary. | [
"Given",
"input",
"text",
"returns",
"the",
"authors",
"likelihood",
"of",
"being",
"16",
"different",
"personality",
"types",
"in",
"a",
"dict",
"."
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/text/personas.py#L6-L27 | train | 42,294 |
IndicoDataSolutions/IndicoIo-python | indicoio/pdf/pdf_extraction.py | pdf_extraction | def pdf_extraction(pdf, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a pdf, returns the text and metadata associated with the given pdf.
PDFs may be provided as base64 encoded data or as a filepath.
Base64 image data and formatted table is optionally returned by setting
`images=True` or `tables=True`.
Example usage:
.. code-block:: python
>>> from indicoio import pdf_extraction
>>> results = pdf_extraction(pdf_file)
>>> results.keys()
['text', 'metadata']
:param pdf: The pdf to be analyzed.
:type pdf: str or list of strs
:rtype: dict or list of dicts
"""
pdf = pdf_preprocess(pdf, batch=batch)
url_params = {"batch": batch, "api_key": api_key, "version": version}
results = api_handler(pdf, cloud=cloud, api="pdfextraction", url_params=url_params, **kwargs)
if batch:
for result in results:
result["images"] = postprocess_images(result.get("images", []))
else:
results['images'] = postprocess_images(results.get("images", []))
return results | python | def pdf_extraction(pdf, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given a pdf, returns the text and metadata associated with the given pdf.
PDFs may be provided as base64 encoded data or as a filepath.
Base64 image data and formatted table is optionally returned by setting
`images=True` or `tables=True`.
Example usage:
.. code-block:: python
>>> from indicoio import pdf_extraction
>>> results = pdf_extraction(pdf_file)
>>> results.keys()
['text', 'metadata']
:param pdf: The pdf to be analyzed.
:type pdf: str or list of strs
:rtype: dict or list of dicts
"""
pdf = pdf_preprocess(pdf, batch=batch)
url_params = {"batch": batch, "api_key": api_key, "version": version}
results = api_handler(pdf, cloud=cloud, api="pdfextraction", url_params=url_params, **kwargs)
if batch:
for result in results:
result["images"] = postprocess_images(result.get("images", []))
else:
results['images'] = postprocess_images(results.get("images", []))
return results | [
"def",
"pdf_extraction",
"(",
"pdf",
",",
"cloud",
"=",
"None",
",",
"batch",
"=",
"False",
",",
"api_key",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pdf",
"=",
"pdf_preprocess",
"(",
"pdf",
",",
"batch",
"=",
"b... | Given a pdf, returns the text and metadata associated with the given pdf.
PDFs may be provided as base64 encoded data or as a filepath.
Base64 image data and formatted table is optionally returned by setting
`images=True` or `tables=True`.
Example usage:
.. code-block:: python
>>> from indicoio import pdf_extraction
>>> results = pdf_extraction(pdf_file)
>>> results.keys()
['text', 'metadata']
:param pdf: The pdf to be analyzed.
:type pdf: str or list of strs
:rtype: dict or list of dicts | [
"Given",
"a",
"pdf",
"returns",
"the",
"text",
"and",
"metadata",
"associated",
"with",
"the",
"given",
"pdf",
".",
"PDFs",
"may",
"be",
"provided",
"as",
"base64",
"encoded",
"data",
"or",
"as",
"a",
"filepath",
".",
"Base64",
"image",
"data",
"and",
"f... | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/pdf/pdf_extraction.py#L6-L35 | train | 42,295 |
data61/clkhash | clkhash/tokenizer.py | get_tokenizer | def get_tokenizer(fhp # type: Optional[field_formats.FieldHashingProperties]
):
# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]
""" Get tokeniser function from the hash settings.
This function takes a FieldHashingProperties object. It returns a
function that takes a string and tokenises based on those properties.
"""
def dummy(word, ignore=None):
# type: (Text, Optional[Text]) -> Iterable[Text]
"""
Null tokenizer returns empty Iterable.
FieldSpec Ignore has hashing_properties = None
and get_tokenizer has to return something for this case,
even though it's never called. An alternative would be to
use an Optional[Callable]].
:param word: not used
:param ignore: not used
:return: empty Iterable
"""
return ('' for i in range(0))
if not fhp:
return dummy
n = fhp.ngram
if n < 0:
raise ValueError('`n` in `n`-gram must be non-negative.')
positional = fhp.positional
def tok(word, ignore=None):
# type: (Text, Optional[Text]) -> Iterable[Text]
""" Produce `n`-grams of `word`.
:param word: The string to tokenize.
:param ignore: The substring whose occurrences we remove from
`word` before tokenization.
:return: Tuple of n-gram strings.
"""
if ignore is not None:
word = word.replace(ignore, '')
if n > 1:
word = ' {} '.format(word)
if positional:
# These are 1-indexed.
return ('{} {}'.format(i + 1, word[i:i + n])
for i in range(len(word) - n + 1))
else:
return (word[i:i + n] for i in range(len(word) - n + 1))
return tok | python | def get_tokenizer(fhp # type: Optional[field_formats.FieldHashingProperties]
):
# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]
""" Get tokeniser function from the hash settings.
This function takes a FieldHashingProperties object. It returns a
function that takes a string and tokenises based on those properties.
"""
def dummy(word, ignore=None):
# type: (Text, Optional[Text]) -> Iterable[Text]
"""
Null tokenizer returns empty Iterable.
FieldSpec Ignore has hashing_properties = None
and get_tokenizer has to return something for this case,
even though it's never called. An alternative would be to
use an Optional[Callable]].
:param word: not used
:param ignore: not used
:return: empty Iterable
"""
return ('' for i in range(0))
if not fhp:
return dummy
n = fhp.ngram
if n < 0:
raise ValueError('`n` in `n`-gram must be non-negative.')
positional = fhp.positional
def tok(word, ignore=None):
# type: (Text, Optional[Text]) -> Iterable[Text]
""" Produce `n`-grams of `word`.
:param word: The string to tokenize.
:param ignore: The substring whose occurrences we remove from
`word` before tokenization.
:return: Tuple of n-gram strings.
"""
if ignore is not None:
word = word.replace(ignore, '')
if n > 1:
word = ' {} '.format(word)
if positional:
# These are 1-indexed.
return ('{} {}'.format(i + 1, word[i:i + n])
for i in range(len(word) - n + 1))
else:
return (word[i:i + n] for i in range(len(word) - n + 1))
return tok | [
"def",
"get_tokenizer",
"(",
"fhp",
"# type: Optional[field_formats.FieldHashingProperties]",
")",
":",
"# type: (...) -> Callable[[Text, Optional[Text]], Iterable[Text]]",
"def",
"dummy",
"(",
"word",
",",
"ignore",
"=",
"None",
")",
":",
"# type: (Text, Optional[Text]) -> Itera... | Get tokeniser function from the hash settings.
This function takes a FieldHashingProperties object. It returns a
function that takes a string and tokenises based on those properties. | [
"Get",
"tokeniser",
"function",
"from",
"the",
"hash",
"settings",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/tokenizer.py#L15-L69 | train | 42,296 |
IndicoDataSolutions/IndicoIo-python | indicoio/utils/pdf.py | pdf_preprocess | def pdf_preprocess(pdf, batch=False):
"""
Load pdfs from local filepath if not already b64 encoded
"""
if batch:
return [pdf_preprocess(doc, batch=False) for doc in pdf]
if os.path.isfile(pdf):
# a filepath is provided, read and encode
return b64encode(open(pdf, 'rb').read())
else:
# assume pdf is already b64 encoded
return pdf | python | def pdf_preprocess(pdf, batch=False):
"""
Load pdfs from local filepath if not already b64 encoded
"""
if batch:
return [pdf_preprocess(doc, batch=False) for doc in pdf]
if os.path.isfile(pdf):
# a filepath is provided, read and encode
return b64encode(open(pdf, 'rb').read())
else:
# assume pdf is already b64 encoded
return pdf | [
"def",
"pdf_preprocess",
"(",
"pdf",
",",
"batch",
"=",
"False",
")",
":",
"if",
"batch",
":",
"return",
"[",
"pdf_preprocess",
"(",
"doc",
",",
"batch",
"=",
"False",
")",
"for",
"doc",
"in",
"pdf",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
"("... | Load pdfs from local filepath if not already b64 encoded | [
"Load",
"pdfs",
"from",
"local",
"filepath",
"if",
"not",
"already",
"b64",
"encoded"
] | 6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa | https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/pdf.py#L16-L28 | train | 42,297 |
data61/clkhash | clkhash/stats.py | OnlineMeanVariance.update | def update(self,
x # type: Sequence[Union[int, float]]
):
# type: (...) -> None
"""
updates the statistics with the given list of numbers
It uses an online algorithm which uses compensated summation to reduce numerical errors.
See https://angelacorasaniti.wordpress.com/2015/05/06/hw2-mean-and-variance-of-data-stream/ for details.
:param x: list of numbers
:return: nothing
"""
if any(math.isnan(float(i)) or math.isinf(float(i)) for i in x):
raise ValueError('input contains non-finite numbers like "nan" or "+/- inf"')
t = sum(x)
m = float(len(x))
norm_t = t / m
S = sum((xi - norm_t) ** 2 for xi in x)
if self.n == 0:
self.S = self.S + S
else:
self.S = self.S + S + self.n / (m * (m + self.n)) * (m / self.n * self.t - t) ** 2
self.t = self.t + t
self.n = self.n + len(x) | python | def update(self,
x # type: Sequence[Union[int, float]]
):
# type: (...) -> None
"""
updates the statistics with the given list of numbers
It uses an online algorithm which uses compensated summation to reduce numerical errors.
See https://angelacorasaniti.wordpress.com/2015/05/06/hw2-mean-and-variance-of-data-stream/ for details.
:param x: list of numbers
:return: nothing
"""
if any(math.isnan(float(i)) or math.isinf(float(i)) for i in x):
raise ValueError('input contains non-finite numbers like "nan" or "+/- inf"')
t = sum(x)
m = float(len(x))
norm_t = t / m
S = sum((xi - norm_t) ** 2 for xi in x)
if self.n == 0:
self.S = self.S + S
else:
self.S = self.S + S + self.n / (m * (m + self.n)) * (m / self.n * self.t - t) ** 2
self.t = self.t + t
self.n = self.n + len(x) | [
"def",
"update",
"(",
"self",
",",
"x",
"# type: Sequence[Union[int, float]]",
")",
":",
"# type: (...) -> None",
"if",
"any",
"(",
"math",
".",
"isnan",
"(",
"float",
"(",
"i",
")",
")",
"or",
"math",
".",
"isinf",
"(",
"float",
"(",
"i",
")",
")",
"f... | updates the statistics with the given list of numbers
It uses an online algorithm which uses compensated summation to reduce numerical errors.
See https://angelacorasaniti.wordpress.com/2015/05/06/hw2-mean-and-variance-of-data-stream/ for details.
:param x: list of numbers
:return: nothing | [
"updates",
"the",
"statistics",
"with",
"the",
"given",
"list",
"of",
"numbers"
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/stats.py#L13-L37 | train | 42,298 |
data61/clkhash | clkhash/clk.py | generate_clk_from_csv | def generate_clk_from_csv(input_f, # type: TextIO
keys, # type: Tuple[AnyStr, AnyStr]
schema, # type: Schema
validate=True, # type: bool
header=True, # type: Union[bool, AnyStr]
progress_bar=True # type: bool
):
# type: (...) -> List[str]
""" Generate Bloom filters from CSV file, then serialise them.
This function also computes and outputs the Hamming weight
(a.k.a popcount -- the number of bits set to high) of the
generated Bloom filters.
:param input_f: A file-like object of csv data to hash.
:param keys: A tuple of two lists of secret keys.
:param schema: Schema specifying the record formats and
hashing settings.
:param validate: Set to `False` to disable validation of
data against the schema. Note that this will silence
warnings whose aim is to keep the hashes consistent between
data sources; this may affect linkage accuracy.
:param header: Set to `False` if the CSV file does not have
a header. Set to `'ignore'` if the CSV file does have a
header but it should not be checked against the schema.
:param bool progress_bar: Set to `False` to disable the progress
bar.
:return: A list of serialized Bloom filters and a list of
corresponding popcounts.
"""
if header not in {False, True, 'ignore'}:
raise ValueError("header must be False, True or 'ignore' but is {}."
.format(header))
log.info("Hashing data")
# Read from CSV file
reader = unicode_reader(input_f)
if header:
column_names = next(reader)
if header != 'ignore':
validate_header(schema.fields, column_names)
start_time = time.time()
# Read the lines in CSV file and add it to PII
pii_data = []
for line in reader:
pii_data.append(tuple(element.strip() for element in line))
validate_row_lengths(schema.fields, pii_data)
if progress_bar:
stats = OnlineMeanVariance()
with tqdm(desc="generating CLKs", total=len(pii_data), unit='clk', unit_scale=True,
postfix={'mean': stats.mean(), 'std': stats.std()}) as pbar:
def callback(tics, clk_stats):
stats.update(clk_stats)
pbar.set_postfix(mean=stats.mean(), std=stats.std(), refresh=False)
pbar.update(tics)
results = generate_clks(pii_data,
schema,
keys,
validate=validate,
callback=callback)
else:
results = generate_clks(pii_data,
schema,
keys,
validate=validate)
log.info("Hashing took {:.2f} seconds".format(time.time() - start_time))
return results | python | def generate_clk_from_csv(input_f, # type: TextIO
keys, # type: Tuple[AnyStr, AnyStr]
schema, # type: Schema
validate=True, # type: bool
header=True, # type: Union[bool, AnyStr]
progress_bar=True # type: bool
):
# type: (...) -> List[str]
""" Generate Bloom filters from CSV file, then serialise them.
This function also computes and outputs the Hamming weight
(a.k.a popcount -- the number of bits set to high) of the
generated Bloom filters.
:param input_f: A file-like object of csv data to hash.
:param keys: A tuple of two lists of secret keys.
:param schema: Schema specifying the record formats and
hashing settings.
:param validate: Set to `False` to disable validation of
data against the schema. Note that this will silence
warnings whose aim is to keep the hashes consistent between
data sources; this may affect linkage accuracy.
:param header: Set to `False` if the CSV file does not have
a header. Set to `'ignore'` if the CSV file does have a
header but it should not be checked against the schema.
:param bool progress_bar: Set to `False` to disable the progress
bar.
:return: A list of serialized Bloom filters and a list of
corresponding popcounts.
"""
if header not in {False, True, 'ignore'}:
raise ValueError("header must be False, True or 'ignore' but is {}."
.format(header))
log.info("Hashing data")
# Read from CSV file
reader = unicode_reader(input_f)
if header:
column_names = next(reader)
if header != 'ignore':
validate_header(schema.fields, column_names)
start_time = time.time()
# Read the lines in CSV file and add it to PII
pii_data = []
for line in reader:
pii_data.append(tuple(element.strip() for element in line))
validate_row_lengths(schema.fields, pii_data)
if progress_bar:
stats = OnlineMeanVariance()
with tqdm(desc="generating CLKs", total=len(pii_data), unit='clk', unit_scale=True,
postfix={'mean': stats.mean(), 'std': stats.std()}) as pbar:
def callback(tics, clk_stats):
stats.update(clk_stats)
pbar.set_postfix(mean=stats.mean(), std=stats.std(), refresh=False)
pbar.update(tics)
results = generate_clks(pii_data,
schema,
keys,
validate=validate,
callback=callback)
else:
results = generate_clks(pii_data,
schema,
keys,
validate=validate)
log.info("Hashing took {:.2f} seconds".format(time.time() - start_time))
return results | [
"def",
"generate_clk_from_csv",
"(",
"input_f",
",",
"# type: TextIO",
"keys",
",",
"# type: Tuple[AnyStr, AnyStr]",
"schema",
",",
"# type: Schema",
"validate",
"=",
"True",
",",
"# type: bool",
"header",
"=",
"True",
",",
"# type: Union[bool, AnyStr]",
"progress_bar",
... | Generate Bloom filters from CSV file, then serialise them.
This function also computes and outputs the Hamming weight
(a.k.a popcount -- the number of bits set to high) of the
generated Bloom filters.
:param input_f: A file-like object of csv data to hash.
:param keys: A tuple of two lists of secret keys.
:param schema: Schema specifying the record formats and
hashing settings.
:param validate: Set to `False` to disable validation of
data against the schema. Note that this will silence
warnings whose aim is to keep the hashes consistent between
data sources; this may affect linkage accuracy.
:param header: Set to `False` if the CSV file does not have
a header. Set to `'ignore'` if the CSV file does have a
header but it should not be checked against the schema.
:param bool progress_bar: Set to `False` to disable the progress
bar.
:return: A list of serialized Bloom filters and a list of
corresponding popcounts. | [
"Generate",
"Bloom",
"filters",
"from",
"CSV",
"file",
"then",
"serialise",
"them",
"."
] | ec6398d6708a063de83f7c3d6286587bff8e7121 | https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/clk.py#L51-L125 | train | 42,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.