repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
DMSC-Instrument-Data/lewis | src/lewis/examples/example_motor/__init__.py | SimulatedExampleMotor.stop | def stop(self):
"""Stops the motor and returns the new target and position, which are equal"""
self._target = self.position
self.log.info('Stopping movement after user request.')
return self.target, self.position | python | def stop(self):
"""Stops the motor and returns the new target and position, which are equal"""
self._target = self.position
self.log.info('Stopping movement after user request.')
return self.target, self.position | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_target",
"=",
"self",
".",
"position",
"self",
".",
"log",
".",
"info",
"(",
"'Stopping movement after user request.'",
")",
"return",
"self",
".",
"target",
",",
"self",
".",
"position"
] | Stops the motor and returns the new target and position, which are equal | [
"Stops",
"the",
"motor",
"and",
"returns",
"the",
"new",
"target",
"and",
"position",
"which",
"are",
"equal"
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/examples/example_motor/__init__.py#L75-L82 |
DMSC-Instrument-Data/lewis | src/lewis/examples/example_motor/__init__.py | ExampleMotorStreamInterface.set_target | def set_target(self, new_target):
"""
Sets the new target in mm, the movement starts immediately. If the value is outside
the interval [0, 250] or the motor is already moving, an error is returned, otherwise
the new target is returned."""
try:
self.device.target = new... | python | def set_target(self, new_target):
"""
Sets the new target in mm, the movement starts immediately. If the value is outside
the interval [0, 250] or the motor is already moving, an error is returned, otherwise
the new target is returned."""
try:
self.device.target = new... | [
"def",
"set_target",
"(",
"self",
",",
"new_target",
")",
":",
"try",
":",
"self",
".",
"device",
".",
"target",
"=",
"new_target",
"return",
"'T={}'",
".",
"format",
"(",
"new_target",
")",
"except",
"RuntimeError",
":",
"return",
"'err: not idle'",
"except... | Sets the new target in mm, the movement starts immediately. If the value is outside
the interval [0, 250] or the motor is already moving, an error is returned, otherwise
the new target is returned. | [
"Sets",
"the",
"new",
"target",
"in",
"mm",
"the",
"movement",
"starts",
"immediately",
".",
"If",
"the",
"value",
"is",
"outside",
"the",
"interval",
"[",
"0",
"250",
"]",
"or",
"the",
"motor",
"is",
"already",
"moving",
"an",
"error",
"is",
"returned",... | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/examples/example_motor/__init__.py#L124-L135 |
DMSC-Instrument-Data/lewis | src/lewis/scripts/run.py | run_simulation | def run_simulation(argument_list=None): # noqa: C901
"""
This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list:... | python | def run_simulation(argument_list=None): # noqa: C901
"""
This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list:... | [
"def",
"run_simulation",
"(",
"argument_list",
"=",
"None",
")",
":",
"# noqa: C901",
"try",
":",
"arguments",
"=",
"parser",
".",
"parse_args",
"(",
"argument_list",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"arguments",
".",
"version",
"... | This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list: Argument list to pass to the argument parser declared in this mod... | [
"This",
"is",
"effectively",
"the",
"main",
"function",
"of",
"a",
"typical",
"simulation",
"run",
".",
"Arguments",
"passed",
"in",
"are",
"parsed",
"and",
"used",
"to",
"construct",
"and",
"run",
"the",
"simulation",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/scripts/run.py#L172-L253 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | Func.map_arguments | def map_arguments(self, arguments):
"""
Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments.
"""
... | python | def map_arguments(self, arguments):
"""
Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments.
"""
... | [
"def",
"map_arguments",
"(",
"self",
",",
"arguments",
")",
":",
"if",
"self",
".",
"argument_mappings",
"is",
"None",
":",
"return",
"arguments",
"return",
"[",
"f",
"(",
"a",
")",
"for",
"f",
",",
"a",
"in",
"zip",
"(",
"self",
".",
"argument_mapping... | Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments. | [
"Returns",
"the",
"mapped",
"function",
"arguments",
".",
"If",
"no",
"mapping",
"functions",
"are",
"defined",
"the",
"arguments",
"are",
"returned",
"as",
"they",
"were",
"supplied",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L368-L379 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | Func.map_return_value | def map_return_value(self, return_value):
"""
Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_... | python | def map_return_value(self, return_value):
"""
Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_... | [
"def",
"map_return_value",
"(",
"self",
",",
"return_value",
")",
":",
"if",
"callable",
"(",
"self",
".",
"return_mapping",
")",
":",
"return",
"self",
".",
"return_mapping",
"(",
"return_value",
")",
"if",
"self",
".",
"return_mapping",
"is",
"not",
"None"... | Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_value: Value to map.
:return: Mapped return value. | [
"Returns",
"the",
"mapped",
"return_value",
"of",
"a",
"processed",
"request",
".",
"If",
"no",
"return_mapping",
"has",
"been",
"defined",
"the",
"value",
"is",
"returned",
"as",
"is",
".",
"If",
"return_mapping",
"is",
"a",
"static",
"value",
"that",
"valu... | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L381-L396 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | StreamAdapter.start_server | def start_server(self):
"""
Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals.
... | python | def start_server(self):
"""
Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals.
... | [
"def",
"start_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"if",
"self",
".",
"_options",
".",
"telnet_mode",
":",
"self",
".",
"interface",
".",
"in_terminator",
"=",
"'\\r\\n'",
"self",
".",
"interface",
".",
"out_te... | Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals. | [
"Starts",
"the",
"TCP",
"stream",
"server",
"binding",
"to",
"the",
"configured",
"host",
"and",
"port",
".",
"Host",
"and",
"port",
"are",
"configured",
"via",
"the",
"command",
"line",
"arguments",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L632-L647 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | StreamAdapter.handle | def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) | python | def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) | [
"def",
"handle",
"(",
"self",
",",
"cycle_delay",
"=",
"0.1",
")",
":",
"asyncore",
".",
"loop",
"(",
"cycle_delay",
",",
"count",
"=",
"1",
")",
"self",
".",
"_server",
".",
"process",
"(",
"int",
"(",
"cycle_delay",
"*",
"1000",
")",
")"
] | Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S | [
"Spend",
"approximately",
"cycle_delay",
"seconds",
"to",
"process",
"requests",
"to",
"the",
"server",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L658-L665 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | StreamInterface._bind_device | def _bind_device(self):
"""
This method implements ``_bind_device`` from :class:`~lewis.core.devices.InterfaceBase`.
It binds Cmd and Var definitions to implementations in Interface and Device.
"""
patterns = set()
self.bound_commands = []
for cmd in self.comman... | python | def _bind_device(self):
"""
This method implements ``_bind_device`` from :class:`~lewis.core.devices.InterfaceBase`.
It binds Cmd and Var definitions to implementations in Interface and Device.
"""
patterns = set()
self.bound_commands = []
for cmd in self.comman... | [
"def",
"_bind_device",
"(",
"self",
")",
":",
"patterns",
"=",
"set",
"(",
")",
"self",
".",
"bound_commands",
"=",
"[",
"]",
"for",
"cmd",
"in",
"self",
".",
"commands",
":",
"bound",
"=",
"cmd",
".",
"bind",
"(",
"self",
")",
"or",
"cmd",
".",
... | This method implements ``_bind_device`` from :class:`~lewis.core.devices.InterfaceBase`.
It binds Cmd and Var definitions to implementations in Interface and Device. | [
"This",
"method",
"implements",
"_bind_device",
"from",
":",
"class",
":",
"~lewis",
".",
"core",
".",
"devices",
".",
"InterfaceBase",
".",
"It",
"binds",
"Cmd",
"and",
"Var",
"definitions",
"to",
"implementations",
"in",
"Interface",
"and",
"Device",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L734-L760 |
DMSC-Instrument-Data/lewis | src/lewis/devices/__init__.py | StateMachineDevice._override_data | def _override_data(self, overrides):
"""
This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides.
"""
if overrides is not None:
for name, val in overrides.items():
self.log... | python | def _override_data(self, overrides):
"""
This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides.
"""
if overrides is not None:
for name, val in overrides.items():
self.log... | [
"def",
"_override_data",
"(",
"self",
",",
"overrides",
")",
":",
"if",
"overrides",
"is",
"not",
"None",
":",
"for",
"name",
",",
"val",
"in",
"overrides",
".",
"items",
"(",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Trying to override initial ... | This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides. | [
"This",
"method",
"overrides",
"data",
"members",
"of",
"the",
"class",
"but",
"does",
"not",
"allow",
"for",
"adding",
"new",
"members",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/__init__.py#L177-L191 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusDataBank.get | def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside va... | python | def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside va... | [
"def",
"get",
"(",
"self",
",",
"addr",
",",
"count",
")",
":",
"addr",
"-=",
"self",
".",
"_start_addr",
"data",
"=",
"self",
".",
"_data",
"[",
"addr",
":",
"addr",
"+",
"count",
"]",
"if",
"len",
"(",
"data",
")",
"!=",
"count",
":",
"addr",
... | Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range | [
"Read",
"list",
"of",
"count",
"values",
"at",
"addr",
"memory",
"location",
"in",
"DataBank",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L64-L79 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusDataBank.set | def set(self, addr, values):
"""
Write list ``values`` to ``addr`` memory location in DataBank.
:param addr: Address to write to
:param values: list of values to write
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_a... | python | def set(self, addr, values):
"""
Write list ``values`` to ``addr`` memory location in DataBank.
:param addr: Address to write to
:param values: list of values to write
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_a... | [
"def",
"set",
"(",
"self",
",",
"addr",
",",
"values",
")",
":",
"addr",
"-=",
"self",
".",
"_start_addr",
"end",
"=",
"addr",
"+",
"len",
"(",
"values",
")",
"if",
"not",
"0",
"<=",
"addr",
"<=",
"end",
"<=",
"len",
"(",
"self",
".",
"_data",
... | Write list ``values`` to ``addr`` memory location in DataBank.
:param addr: Address to write to
:param values: list of values to write
:except IndexError: Raised if address range falls outside valid range | [
"Write",
"list",
"values",
"to",
"addr",
"memory",
"location",
"in",
"DataBank",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L81-L95 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.from_bytearray | def from_bytearray(self, stream):
"""
Constructs this frame from input data stream, consuming as many bytes as necessary from
the beginning of the stream.
If stream does not contain enough data to construct a complete modbus frame, an EOFError
is raised and no data is consumed.
... | python | def from_bytearray(self, stream):
"""
Constructs this frame from input data stream, consuming as many bytes as necessary from
the beginning of the stream.
If stream does not contain enough data to construct a complete modbus frame, an EOFError
is raised and no data is consumed.
... | [
"def",
"from_bytearray",
"(",
"self",
",",
"stream",
")",
":",
"fmt",
"=",
"'>HHHBB'",
"size_header",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"if",
"len",
"(",
"stream",
")",
"<",
"size_header",
":",
"raise",
"EOFError",
"(",
"self",
".",
"tra... | Constructs this frame from input data stream, consuming as many bytes as necessary from
the beginning of the stream.
If stream does not contain enough data to construct a complete modbus frame, an EOFError
is raised and no data is consumed.
:param stream: bytearray to consume data from... | [
"Constructs",
"this",
"frame",
"from",
"input",
"data",
"stream",
"consuming",
"as",
"many",
"bytes",
"as",
"necessary",
"from",
"the",
"beginning",
"of",
"the",
"stream",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L171-L200 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.to_bytearray | def to_bytearray(self):
"""
Convert this frame into its bytearray representation.
:return: bytearray representation of this frame.
"""
header = bytearray(struct.pack(
'>HHHBB',
self.transaction_id,
self.protocol_id,
self.length,
... | python | def to_bytearray(self):
"""
Convert this frame into its bytearray representation.
:return: bytearray representation of this frame.
"""
header = bytearray(struct.pack(
'>HHHBB',
self.transaction_id,
self.protocol_id,
self.length,
... | [
"def",
"to_bytearray",
"(",
"self",
")",
":",
"header",
"=",
"bytearray",
"(",
"struct",
".",
"pack",
"(",
"'>HHHBB'",
",",
"self",
".",
"transaction_id",
",",
"self",
".",
"protocol_id",
",",
"self",
".",
"length",
",",
"self",
".",
"unit_id",
",",
"s... | Convert this frame into its bytearray representation.
:return: bytearray representation of this frame. | [
"Convert",
"this",
"frame",
"into",
"its",
"bytearray",
"representation",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L202-L216 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.is_valid | def is_valid(self):
"""
Check integrity and validity of this frame.
:return: bool True if this frame is structurally valid.
"""
conditions = [
self.protocol_id == 0, # Modbus always uses protocol 0
2 <= self.length <= 260, # Absolute length limits
... | python | def is_valid(self):
"""
Check integrity and validity of this frame.
:return: bool True if this frame is structurally valid.
"""
conditions = [
self.protocol_id == 0, # Modbus always uses protocol 0
2 <= self.length <= 260, # Absolute length limits
... | [
"def",
"is_valid",
"(",
"self",
")",
":",
"conditions",
"=",
"[",
"self",
".",
"protocol_id",
"==",
"0",
",",
"# Modbus always uses protocol 0",
"2",
"<=",
"self",
".",
"length",
"<=",
"260",
",",
"# Absolute length limits",
"len",
"(",
"self",
".",
"data",
... | Check integrity and validity of this frame.
:return: bool True if this frame is structurally valid. | [
"Check",
"integrity",
"and",
"validity",
"of",
"this",
"frame",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L218-L229 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.create_exception | def create_exception(self, code):
"""
Create an exception frame based on this frame.
:param code: Modbus exception code to use for this exception
:return: ModbusTCPFrame instance that represents an exception
"""
frame = deepcopy(self)
frame.length = 3
fra... | python | def create_exception(self, code):
"""
Create an exception frame based on this frame.
:param code: Modbus exception code to use for this exception
:return: ModbusTCPFrame instance that represents an exception
"""
frame = deepcopy(self)
frame.length = 3
fra... | [
"def",
"create_exception",
"(",
"self",
",",
"code",
")",
":",
"frame",
"=",
"deepcopy",
"(",
"self",
")",
"frame",
".",
"length",
"=",
"3",
"frame",
".",
"fcode",
"+=",
"0x80",
"frame",
".",
"data",
"=",
"bytearray",
"(",
"chr",
"(",
"code",
")",
... | Create an exception frame based on this frame.
:param code: Modbus exception code to use for this exception
:return: ModbusTCPFrame instance that represents an exception | [
"Create",
"an",
"exception",
"frame",
"based",
"on",
"this",
"frame",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L231-L242 |
DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.create_response | def create_response(self, data=None):
"""
Create a response frame based on this frame.
:param data: Data section of response as bytearray. If None, request data section is kept.
:return: ModbusTCPFrame instance that represents a response
"""
frame = deepcopy(self)
... | python | def create_response(self, data=None):
"""
Create a response frame based on this frame.
:param data: Data section of response as bytearray. If None, request data section is kept.
:return: ModbusTCPFrame instance that represents a response
"""
frame = deepcopy(self)
... | [
"def",
"create_response",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"frame",
"=",
"deepcopy",
"(",
"self",
")",
"if",
"data",
"is",
"not",
"None",
":",
"frame",
".",
"data",
"=",
"data",
"frame",
".",
"length",
"=",
"2",
"+",
"len",
"(",
"... | Create a response frame based on this frame.
:param data: Data section of response as bytearray. If None, request data section is kept.
:return: ModbusTCPFrame instance that represents a response | [
"Create",
"a",
"response",
"frame",
"based",
"on",
"this",
"frame",
"."
] | train | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L244-L255 |
simpleai-team/simpleai | simpleai/search/local.py | _all_expander | def _all_expander(fringe, iteration, viewer):
'''
Expander that expands all nodes on the fringe.
'''
expanded_neighbors = [node.expand(local_search=True)
for node in fringe]
if viewer:
viewer.event('expanded', list(fringe), expanded_neighbors)
list(map(fringe.... | python | def _all_expander(fringe, iteration, viewer):
'''
Expander that expands all nodes on the fringe.
'''
expanded_neighbors = [node.expand(local_search=True)
for node in fringe]
if viewer:
viewer.event('expanded', list(fringe), expanded_neighbors)
list(map(fringe.... | [
"def",
"_all_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"expanded_neighbors",
"=",
"[",
"node",
".",
"expand",
"(",
"local_search",
"=",
"True",
")",
"for",
"node",
"in",
"fringe",
"]",
"if",
"viewer",
":",
"viewer",
".",
"event... | Expander that expands all nodes on the fringe. | [
"Expander",
"that",
"expands",
"all",
"nodes",
"on",
"the",
"fringe",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L8-L18 |
simpleai-team/simpleai | simpleai/search/local.py | beam | def beam(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Req... | python | def beam(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Req... | [
"def",
"beam",
"(",
"problem",
",",
"beam_size",
"=",
"100",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_all_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fri... | Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
an... | [
"Beam",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L21-L38 |
simpleai-team/simpleai | simpleai/search/local.py | _first_expander | def _first_expander(fringe, iteration, viewer):
'''
Expander that expands only the first node on the fringe.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
fringe.extend(neighbors) | python | def _first_expander(fringe, iteration, viewer):
'''
Expander that expands only the first node on the fringe.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
fringe.extend(neighbors) | [
"def",
"_first_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"current",
"=",
"fringe",
"[",
"0",
"]",
"neighbors",
"=",
"current",
".",
"expand",
"(",
"local_search",
"=",
"True",
")",
"if",
"viewer",
":",
"viewer",
".",
"event",
... | Expander that expands only the first node on the fringe. | [
"Expander",
"that",
"expands",
"only",
"the",
"first",
"node",
"on",
"the",
"fringe",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L41-L51 |
simpleai-team/simpleai | simpleai/search/local.py | beam_best_first | def beam_best_first(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search best first.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than th... | python | def beam_best_first(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search best first.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than th... | [
"def",
"beam_best_first",
"(",
"problem",
",",
"beam_size",
"=",
"100",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_first_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
... | Beam search best first.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchPr... | [
"Beam",
"search",
"best",
"first",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L55-L72 |
simpleai-team/simpleai | simpleai/search/local.py | hill_climbing | def hill_climbing(problem, iterations_limit=0, viewer=None):
'''
Hill climbing search.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, Search... | python | def hill_climbing(problem, iterations_limit=0, viewer=None):
'''
Hill climbing search.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, Search... | [
"def",
"hill_climbing",
"(",
"problem",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_first_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"1",
... | Hill climbing search.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | [
"Hill",
"climbing",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L75-L90 |
simpleai-team/simpleai | simpleai/search/local.py | _random_best_expander | def _random_best_expander(fringe, iteration, viewer):
'''
Expander that expands one randomly chosen nodes on the fringe that
is better than the current (first) node.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [... | python | def _random_best_expander(fringe, iteration, viewer):
'''
Expander that expands one randomly chosen nodes on the fringe that
is better than the current (first) node.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [... | [
"def",
"_random_best_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"current",
"=",
"fringe",
"[",
"0",
"]",
"neighbors",
"=",
"current",
".",
"expand",
"(",
"local_search",
"=",
"True",
")",
"if",
"viewer",
":",
"viewer",
".",
"eve... | Expander that expands one randomly chosen nodes on the fringe that
is better than the current (first) node. | [
"Expander",
"that",
"expands",
"one",
"randomly",
"chosen",
"nodes",
"on",
"the",
"fringe",
"that",
"is",
"better",
"than",
"the",
"current",
"(",
"first",
")",
"node",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L93-L109 |
simpleai-team/simpleai | simpleai/search/local.py | hill_climbing_stochastic | def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None):
'''
Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.... | python | def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None):
'''
Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.... | [
"def",
"hill_climbing_stochastic",
"(",
"problem",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_random_best_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",... | Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | [
"Stochastic",
"hill",
"climbing",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L112-L127 |
simpleai-team/simpleai | simpleai/search/local.py | hill_climbing_random_restarts | def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=0, viewer=None):
'''
Hill climbing with random restarts.
restarts_limit specifies the number of times hill_climbing will be runned.
If iterations_limit is specified, each hill_climbing will end after that
number of iteratio... | python | def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=0, viewer=None):
'''
Hill climbing with random restarts.
restarts_limit specifies the number of times hill_climbing will be runned.
If iterations_limit is specified, each hill_climbing will end after that
number of iteratio... | [
"def",
"hill_climbing_random_restarts",
"(",
"problem",
",",
"restarts_limit",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"restarts",
"=",
"0",
"best",
"=",
"None",
"while",
"restarts",
"<",
"restarts_limit",
":",
"new",
"=",
"_... | Hill climbing with random restarts.
restarts_limit specifies the number of times hill_climbing will be runned.
If iterations_limit is specified, each hill_climbing will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: Sear... | [
"Hill",
"climbing",
"with",
"random",
"restarts",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L130-L161 |
simpleai-team/simpleai | simpleai/search/local.py | _exp_schedule | def _exp_schedule(iteration, k=20, lam=0.005, limit=100):
'''
Possible scheduler for simulated_annealing, based on the aima example.
'''
return k * math.exp(-lam * iteration) | python | def _exp_schedule(iteration, k=20, lam=0.005, limit=100):
'''
Possible scheduler for simulated_annealing, based on the aima example.
'''
return k * math.exp(-lam * iteration) | [
"def",
"_exp_schedule",
"(",
"iteration",
",",
"k",
"=",
"20",
",",
"lam",
"=",
"0.005",
",",
"limit",
"=",
"100",
")",
":",
"return",
"k",
"*",
"math",
".",
"exp",
"(",
"-",
"lam",
"*",
"iteration",
")"
] | Possible scheduler for simulated_annealing, based on the aima example. | [
"Possible",
"scheduler",
"for",
"simulated_annealing",
"based",
"on",
"the",
"aima",
"example",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L165-L169 |
simpleai-team/simpleai | simpleai/search/local.py | _create_simulated_annealing_expander | def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
'''
def _expander(fringe, iteration, viewer):
T = schedule(iteration)
current = frin... | python | def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
'''
def _expander(fringe, iteration, viewer):
T = schedule(iteration)
current = frin... | [
"def",
"_create_simulated_annealing_expander",
"(",
"schedule",
")",
":",
"def",
"_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"T",
"=",
"schedule",
"(",
"iteration",
")",
"current",
"=",
"fringe",
"[",
"0",
"]",
"neighbors",
"=",
... | Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time. | [
"Creates",
"an",
"expander",
"that",
"has",
"a",
"random",
"chance",
"to",
"choose",
"a",
"node",
"that",
"is",
"worse",
"than",
"the",
"current",
"(",
"first",
")",
"node",
"but",
"that",
"chance",
"decreases",
"with",
"time",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L172-L195 |
simpleai-team/simpleai | simpleai/search/local.py | simulated_annealing | def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=0, viewer=None):
'''
Simulated annealing.
schedule is the scheduling function that decides the chance to choose worst
nodes depending on the time.
If iterations_limit is specified, the algorithm will end after that
number... | python | def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=0, viewer=None):
'''
Simulated annealing.
schedule is the scheduling function that decides the chance to choose worst
nodes depending on the time.
If iterations_limit is specified, the algorithm will end after that
number... | [
"def",
"simulated_annealing",
"(",
"problem",
",",
"schedule",
"=",
"_exp_schedule",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_create_simulated_annealing_expander",
"(",
"schedule",
"... | Simulated annealing.
schedule is the scheduling function that decides the chance to choose worst
nodes depending on the time.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
... | [
"Simulated",
"annealing",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L198-L215 |
simpleai-team/simpleai | simpleai/search/local.py | _create_genetic_expander | def _create_genetic_expander(problem, mutation_chance):
'''
Creates an expander that expands the bests nodes of the population,
crossing over them.
'''
def _expander(fringe, iteration, viewer):
fitness = [x.value for x in fringe]
sampler = InverseTransformSampler(fitness, fringe)
... | python | def _create_genetic_expander(problem, mutation_chance):
'''
Creates an expander that expands the bests nodes of the population,
crossing over them.
'''
def _expander(fringe, iteration, viewer):
fitness = [x.value for x in fringe]
sampler = InverseTransformSampler(fitness, fringe)
... | [
"def",
"_create_genetic_expander",
"(",
"problem",
",",
"mutation_chance",
")",
":",
"def",
"_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"fitness",
"=",
"[",
"x",
".",
"value",
"for",
"x",
"in",
"fringe",
"]",
"sampler",
"=",
"I... | Creates an expander that expands the bests nodes of the population,
crossing over them. | [
"Creates",
"an",
"expander",
"that",
"expands",
"the",
"bests",
"nodes",
"of",
"the",
"population",
"crossing",
"over",
"them",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L218-L256 |
simpleai-team/simpleai | simpleai/search/local.py | genetic | def genetic(problem, population_size=100, mutation_chance=0.1,
iterations_limit=0, viewer=None):
'''
Genetic search.
population_size specifies the size of the population (ORLY).
mutation_chance specifies the probability of a mutation on a child,
varying from 0 to 1.
If iterations_li... | python | def genetic(problem, population_size=100, mutation_chance=0.1,
iterations_limit=0, viewer=None):
'''
Genetic search.
population_size specifies the size of the population (ORLY).
mutation_chance specifies the probability of a mutation on a child,
varying from 0 to 1.
If iterations_li... | [
"def",
"genetic",
"(",
"problem",
",",
"population_size",
"=",
"100",
",",
"mutation_chance",
"=",
"0.1",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_create_genetic_expander",
"(",
... | Genetic search.
population_size specifies the size of the population (ORLY).
mutation_chance specifies the probability of a mutation on a child,
varying from 0 to 1.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find ... | [
"Genetic",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L259-L279 |
simpleai-team/simpleai | simpleai/search/local.py | _local_search | def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,
random_initial_states=False, stop_when_no_better=True,
viewer=None):
'''
Basic algorithm for all local search algorithms.
'''
if viewer:
viewer.event('started')
fringe = Bounde... | python | def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,
random_initial_states=False, stop_when_no_better=True,
viewer=None):
'''
Basic algorithm for all local search algorithms.
'''
if viewer:
viewer.event('started')
fringe = Bounde... | [
"def",
"_local_search",
"(",
"problem",
",",
"fringe_expander",
",",
"iterations_limit",
"=",
"0",
",",
"fringe_size",
"=",
"1",
",",
"random_initial_states",
"=",
"False",
",",
"stop_when_no_better",
"=",
"True",
",",
"viewer",
"=",
"None",
")",
":",
"if",
... | Basic algorithm for all local search algorithms. | [
"Basic",
"algorithm",
"for",
"all",
"local",
"search",
"algorithms",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L282-L325 |
simpleai-team/simpleai | samples/search/eight_puzzle.py | find_location | def find_location(rows, element_to_find):
'''Find the location of a piece in the puzzle.
Returns a tuple: row, column'''
for ir, row in enumerate(rows):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic | python | def find_location(rows, element_to_find):
'''Find the location of a piece in the puzzle.
Returns a tuple: row, column'''
for ir, row in enumerate(rows):
for ic, element in enumerate(row):
if element == element_to_find:
return ir, ic | [
"def",
"find_location",
"(",
"rows",
",",
"element_to_find",
")",
":",
"for",
"ir",
",",
"row",
"in",
"enumerate",
"(",
"rows",
")",
":",
"for",
"ic",
",",
"element",
"in",
"enumerate",
"(",
"row",
")",
":",
"if",
"element",
"==",
"element_to_find",
":... | Find the location of a piece in the puzzle.
Returns a tuple: row, column | [
"Find",
"the",
"location",
"of",
"a",
"piece",
"in",
"the",
"puzzle",
".",
"Returns",
"a",
"tuple",
":",
"row",
"column"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/eight_puzzle.py#L46-L52 |
simpleai-team/simpleai | samples/search/eight_puzzle.py | EigthPuzzleProblem.actions | def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actio... | python | def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actio... | [
"def",
"actions",
"(",
"self",
",",
"state",
")",
":",
"rows",
"=",
"string_to_list",
"(",
"state",
")",
"row_e",
",",
"col_e",
"=",
"find_location",
"(",
"rows",
",",
"'e'",
")",
"actions",
"=",
"[",
"]",
"if",
"row_e",
">",
"0",
":",
"actions",
"... | Returns a list of the pieces we can move to the empty space. | [
"Returns",
"a",
"list",
"of",
"the",
"pieces",
"we",
"can",
"move",
"to",
"the",
"empty",
"space",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/eight_puzzle.py#L64-L79 |
simpleai-team/simpleai | samples/search/eight_puzzle.py | EigthPuzzleProblem.result | def result(self, state, action):
'''Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move)
'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
row_n, col_n = find_location(rows, actio... | python | def result(self, state, action):
'''Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move)
'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
row_n, col_n = find_location(rows, actio... | [
"def",
"result",
"(",
"self",
",",
"state",
",",
"action",
")",
":",
"rows",
"=",
"string_to_list",
"(",
"state",
")",
"row_e",
",",
"col_e",
"=",
"find_location",
"(",
"rows",
",",
"'e'",
")",
"row_n",
",",
"col_n",
"=",
"find_location",
"(",
"rows",
... | Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move) | [
"Return",
"the",
"resulting",
"state",
"after",
"moving",
"a",
"piece",
"to",
"the",
"empty",
"space",
".",
"(",
"the",
"action",
"parameter",
"contains",
"the",
"piece",
"to",
"move",
")"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/eight_puzzle.py#L81-L91 |
simpleai-team/simpleai | samples/search/eight_puzzle.py | EigthPuzzleProblem.heuristic | def heuristic(self, state):
'''Returns an *estimation* of the distance from a state to the goal.
We are using the manhattan distance.
'''
rows = string_to_list(state)
distance = 0
for number in '12345678e':
row_n, col_n = find_location(rows, number)
... | python | def heuristic(self, state):
'''Returns an *estimation* of the distance from a state to the goal.
We are using the manhattan distance.
'''
rows = string_to_list(state)
distance = 0
for number in '12345678e':
row_n, col_n = find_location(rows, number)
... | [
"def",
"heuristic",
"(",
"self",
",",
"state",
")",
":",
"rows",
"=",
"string_to_list",
"(",
"state",
")",
"distance",
"=",
"0",
"for",
"number",
"in",
"'12345678e'",
":",
"row_n",
",",
"col_n",
"=",
"find_location",
"(",
"rows",
",",
"number",
")",
"r... | Returns an *estimation* of the distance from a state to the goal.
We are using the manhattan distance. | [
"Returns",
"an",
"*",
"estimation",
"*",
"of",
"the",
"distance",
"from",
"a",
"state",
"to",
"the",
"goal",
".",
"We",
"are",
"using",
"the",
"manhattan",
"distance",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/eight_puzzle.py#L103-L117 |
simpleai-team/simpleai | simpleai/machine_learning/models.py | is_attribute | def is_attribute(method, name=None):
"""
Decorator for methods that are attributes.
"""
if name is None:
name = method.__name__
method.is_attribute = True
method.name = name
return method | python | def is_attribute(method, name=None):
"""
Decorator for methods that are attributes.
"""
if name is None:
name = method.__name__
method.is_attribute = True
method.name = name
return method | [
"def",
"is_attribute",
"(",
"method",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"method",
".",
"__name__",
"method",
".",
"is_attribute",
"=",
"True",
"method",
".",
"name",
"=",
"name",
"return",
"method"
] | Decorator for methods that are attributes. | [
"Decorator",
"for",
"methods",
"that",
"are",
"attributes",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/models.py#L230-L238 |
simpleai-team/simpleai | simpleai/machine_learning/models.py | Classifier.load | def load(cls, filepath):
"""
Loads a pickled version of the classifier saved in `filepath`
"""
with open(filepath, "rb") as filehandler:
classifier = pickle.load(filehandler)
if not isinstance(classifier, Classifier):
raise ValueError("Pickled object is n... | python | def load(cls, filepath):
"""
Loads a pickled version of the classifier saved in `filepath`
"""
with open(filepath, "rb") as filehandler:
classifier = pickle.load(filehandler)
if not isinstance(classifier, Classifier):
raise ValueError("Pickled object is n... | [
"def",
"load",
"(",
"cls",
",",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"filehandler",
":",
"classifier",
"=",
"pickle",
".",
"load",
"(",
"filehandler",
")",
"if",
"not",
"isinstance",
"(",
"classifier",
",",
"... | Loads a pickled version of the classifier saved in `filepath` | [
"Loads",
"a",
"pickled",
"version",
"of",
"the",
"classifier",
"saved",
"in",
"filepath"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/models.py#L76-L86 |
simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | tree_to_str | def tree_to_str(root):
"""
Returns a string representation of a decision tree with
root node `root`.
"""
xs = []
for value, node, depth in iter_tree(root):
template = "{indent}"
if node is not root:
template += "case={value}\t"
if node.attribute is None:
... | python | def tree_to_str(root):
"""
Returns a string representation of a decision tree with
root node `root`.
"""
xs = []
for value, node, depth in iter_tree(root):
template = "{indent}"
if node is not root:
template += "case={value}\t"
if node.attribute is None:
... | [
"def",
"tree_to_str",
"(",
"root",
")",
":",
"xs",
"=",
"[",
"]",
"for",
"value",
",",
"node",
",",
"depth",
"in",
"iter_tree",
"(",
"root",
")",
":",
"template",
"=",
"\"{indent}\"",
"if",
"node",
"is",
"not",
"root",
":",
"template",
"+=",
"\"case=... | Returns a string representation of a decision tree with
root node `root`. | [
"Returns",
"a",
"string",
"representation",
"of",
"a",
"decision",
"tree",
"with",
"root",
"node",
"root",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L216-L238 |
simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | DecisionTreeLearner.learn | def learn(self, examples, attributes, parent_examples):
"""
A decision tree learner that *strictly* follows the pseudocode given in
AIMA. In 3rd edition, see Figure 18.5, page 702.
"""
if not examples:
return self.plurality_value(parent_examples)
elif len(set(... | python | def learn(self, examples, attributes, parent_examples):
"""
A decision tree learner that *strictly* follows the pseudocode given in
AIMA. In 3rd edition, see Figure 18.5, page 702.
"""
if not examples:
return self.plurality_value(parent_examples)
elif len(set(... | [
"def",
"learn",
"(",
"self",
",",
"examples",
",",
"attributes",
",",
"parent_examples",
")",
":",
"if",
"not",
"examples",
":",
"return",
"self",
".",
"plurality_value",
"(",
"parent_examples",
")",
"elif",
"len",
"(",
"set",
"(",
"map",
"(",
"self",
".... | A decision tree learner that *strictly* follows the pseudocode given in
AIMA. In 3rd edition, see Figure 18.5, page 702. | [
"A",
"decision",
"tree",
"learner",
"that",
"*",
"strictly",
"*",
"follows",
"the",
"pseudocode",
"given",
"in",
"AIMA",
".",
"In",
"3rd",
"edition",
"see",
"Figure",
"18",
".",
"5",
"page",
"702",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L42-L59 |
simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | DecisionTreeLearner.importance | def importance(self, attribute, examples):
"""
AIMA implies that importance should be information gain.
Since AIMA only defines it for binary features this implementation
was based on the wikipedia article:
http://en.wikipedia.org/wiki/Information_gain_in_decision_trees
"... | python | def importance(self, attribute, examples):
"""
AIMA implies that importance should be information gain.
Since AIMA only defines it for binary features this implementation
was based on the wikipedia article:
http://en.wikipedia.org/wiki/Information_gain_in_decision_trees
"... | [
"def",
"importance",
"(",
"self",
",",
"attribute",
",",
"examples",
")",
":",
"gain_counter",
"=",
"OnlineInformationGain",
"(",
"attribute",
",",
"self",
".",
"target",
")",
"for",
"example",
"in",
"examples",
":",
"gain_counter",
".",
"add",
"(",
"example... | AIMA implies that importance should be information gain.
Since AIMA only defines it for binary features this implementation
was based on the wikipedia article:
http://en.wikipedia.org/wiki/Information_gain_in_decision_trees | [
"AIMA",
"implies",
"that",
"importance",
"should",
"be",
"information",
"gain",
".",
"Since",
"AIMA",
"only",
"defines",
"it",
"for",
"binary",
"features",
"this",
"implementation",
"was",
"based",
"on",
"the",
"wikipedia",
"article",
":",
"http",
":",
"//",
... | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L72-L82 |
simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | KNearestNeighbors.save | def save(self, filepath):
"""
Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator.
"""
if not filepath or not isinstance(filepath, str):
rai... | python | def save(self, filepath):
"""
Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator.
"""
if not filepath or not isinstance(filepath, str):
rai... | [
"def",
"save",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"not",
"filepath",
"or",
"not",
"isinstance",
"(",
"filepath",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid filepath\"",
")",
"with",
"open",
"(",
"filepath",
",",
"\"wb\"",
")"... | Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator. | [
"Saves",
"the",
"classifier",
"to",
"filepath",
".",
"Because",
"this",
"classifier",
"needs",
"to",
"save",
"the",
"dataset",
"it",
"must",
"be",
"something",
"that",
"can",
"be",
"pickled",
"and",
"not",
"something",
"like",
"an",
"iterator",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L180-L192 |
simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | DecisionTreeNode.take_branch | def take_branch(self, example):
"""
Returns a `DecisionTreeNode` instance that can better classify
`example` based on the selectors value.
If there are no more branches (ie, this node is a leaf) or the
attribute gives a value for an unexistent branch then this method
retu... | python | def take_branch(self, example):
"""
Returns a `DecisionTreeNode` instance that can better classify
`example` based on the selectors value.
If there are no more branches (ie, this node is a leaf) or the
attribute gives a value for an unexistent branch then this method
retu... | [
"def",
"take_branch",
"(",
"self",
",",
"example",
")",
":",
"if",
"self",
".",
"attribute",
"is",
"None",
":",
"return",
"None",
"value",
"=",
"self",
".",
"attribute",
"(",
"example",
")",
"return",
"self",
".",
"branches",
".",
"get",
"(",
"value",
... | Returns a `DecisionTreeNode` instance that can better classify
`example` based on the selectors value.
If there are no more branches (ie, this node is a leaf) or the
attribute gives a value for an unexistent branch then this method
returns None. | [
"Returns",
"a",
"DecisionTreeNode",
"instance",
"that",
"can",
"better",
"classify",
"example",
"based",
"on",
"the",
"selectors",
"value",
".",
"If",
"there",
"are",
"no",
"more",
"branches",
"(",
"ie",
"this",
"node",
"is",
"a",
"leaf",
")",
"or",
"the",... | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L252-L263 |
simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | DecisionTreeLearner_Queued._max_gain_split | def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
win... | python | def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
win... | [
"def",
"_max_gain_split",
"(",
"self",
",",
"examples",
")",
":",
"gains",
"=",
"self",
".",
"_new_set_of_gain_counters",
"(",
")",
"for",
"example",
"in",
"examples",
":",
"for",
"gain",
"in",
"gains",
":",
"gain",
".",
"add",
"(",
"example",
")",
"winn... | Returns an OnlineInformationGain of the attribute with
max gain based on `examples`. | [
"Returns",
"an",
"OnlineInformationGain",
"of",
"the",
"attribute",
"with",
"max",
"gain",
"based",
"on",
"examples",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L322-L334 |
simpleai-team/simpleai | simpleai/search/csp.py | backtrack | def backtrack(problem, variable_heuristic='', value_heuristic='', inference=True):
'''
Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristi... | python | def backtrack(problem, variable_heuristic='', value_heuristic='', inference=True):
'''
Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristi... | [
"def",
"backtrack",
"(",
"problem",
",",
"variable_heuristic",
"=",
"''",
",",
"value_heuristic",
"=",
"''",
",",
"inference",
"=",
"True",
")",
":",
"assignment",
"=",
"{",
"}",
"domains",
"=",
"deepcopy",
"(",
"problem",
".",
"domains",
")",
"if",
"var... | Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristic for value choosing, can be
LEAST_CONSTRAINING_VALUE or blank for simple ordered choosing. | [
"Backtracking",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L12-L41 |
simpleai-team/simpleai | simpleai/search/csp.py | _most_constrained_variable_chooser | def _most_constrained_variable_chooser(problem, variables, domains):
'''
Choose the variable that has less available values.
'''
# the variable with fewer values available
return sorted(variables, key=lambda v: len(domains[v]))[0] | python | def _most_constrained_variable_chooser(problem, variables, domains):
'''
Choose the variable that has less available values.
'''
# the variable with fewer values available
return sorted(variables, key=lambda v: len(domains[v]))[0] | [
"def",
"_most_constrained_variable_chooser",
"(",
"problem",
",",
"variables",
",",
"domains",
")",
":",
"# the variable with fewer values available",
"return",
"sorted",
"(",
"variables",
",",
"key",
"=",
"lambda",
"v",
":",
"len",
"(",
"domains",
"[",
"v",
"]",
... | Choose the variable that has less available values. | [
"Choose",
"the",
"variable",
"that",
"has",
"less",
"available",
"values",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L51-L56 |
simpleai-team/simpleai | simpleai/search/csp.py | _highest_degree_variable_chooser | def _highest_degree_variable_chooser(problem, variables, domains):
'''
Choose the variable that is involved on more constraints.
'''
# the variable involved in more constraints
return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0] | python | def _highest_degree_variable_chooser(problem, variables, domains):
'''
Choose the variable that is involved on more constraints.
'''
# the variable involved in more constraints
return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0] | [
"def",
"_highest_degree_variable_chooser",
"(",
"problem",
",",
"variables",
",",
"domains",
")",
":",
"# the variable involved in more constraints",
"return",
"sorted",
"(",
"variables",
",",
"key",
"=",
"lambda",
"v",
":",
"problem",
".",
"var_degrees",
"[",
"v",
... | Choose the variable that is involved on more constraints. | [
"Choose",
"the",
"variable",
"that",
"is",
"involved",
"on",
"more",
"constraints",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L59-L64 |
simpleai-team/simpleai | simpleai/search/csp.py | _count_conflicts | def _count_conflicts(problem, assignment, variable=None, value=None):
'''
Count the number of violated constraints on a given assignment.
'''
return len(_find_conflicts(problem, assignment, variable, value)) | python | def _count_conflicts(problem, assignment, variable=None, value=None):
'''
Count the number of violated constraints on a given assignment.
'''
return len(_find_conflicts(problem, assignment, variable, value)) | [
"def",
"_count_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"return",
"len",
"(",
"_find_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
",",
"value",
")",
")"
] | Count the number of violated constraints on a given assignment. | [
"Count",
"the",
"number",
"of",
"violated",
"constraints",
"on",
"a",
"given",
"assignment",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L67-L71 |
simpleai-team/simpleai | simpleai/search/csp.py | _find_conflicts | def _find_conflicts(problem, assignment, variable=None, value=None):
'''
Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking.
'''
if variable is not None and value is not None:
assignment = ... | python | def _find_conflicts(problem, assignment, variable=None, value=None):
'''
Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking.
'''
if variable is not None and value is not None:
assignment = ... | [
"def",
"_find_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"if",
"variable",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"assignment",
"=",
"deepcopy",
"(",
"assignme... | Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking. | [
"Find",
"violated",
"constraints",
"on",
"a",
"given",
"assignment",
"with",
"the",
"possibility",
"of",
"specifying",
"a",
"new",
"variable",
"and",
"value",
"to",
"add",
"to",
"the",
"assignment",
"before",
"checking",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L80-L97 |
simpleai-team/simpleai | simpleai/search/csp.py | _least_constraining_values_sorter | def _least_constraining_values_sorter(problem, assignment, variable, domains):
'''
Sort values based on how many conflicts they generate if assigned.
'''
# the value that generates less conflicts
def update_assignment(value):
new_assignment = deepcopy(assignment)
new_assignment[varia... | python | def _least_constraining_values_sorter(problem, assignment, variable, domains):
'''
Sort values based on how many conflicts they generate if assigned.
'''
# the value that generates less conflicts
def update_assignment(value):
new_assignment = deepcopy(assignment)
new_assignment[varia... | [
"def",
"_least_constraining_values_sorter",
"(",
"problem",
",",
"assignment",
",",
"variable",
",",
"domains",
")",
":",
"# the value that generates less conflicts",
"def",
"update_assignment",
"(",
"value",
")",
":",
"new_assignment",
"=",
"deepcopy",
"(",
"assignment... | Sort values based on how many conflicts they generate if assigned. | [
"Sort",
"values",
"based",
"on",
"how",
"many",
"conflicts",
"they",
"generate",
"if",
"assigned",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L107-L120 |
simpleai-team/simpleai | simpleai/search/csp.py | _backtracking | def _backtracking(problem, assignment, domains, variable_chooser, values_sorter, inference=True):
'''
Internal recursive backtracking algorithm.
'''
from simpleai.search.arc import arc_consistency_3
if len(assignment) == len(problem.variables):
return assignment
pending = [v for v in pr... | python | def _backtracking(problem, assignment, domains, variable_chooser, values_sorter, inference=True):
'''
Internal recursive backtracking algorithm.
'''
from simpleai.search.arc import arc_consistency_3
if len(assignment) == len(problem.variables):
return assignment
pending = [v for v in pr... | [
"def",
"_backtracking",
"(",
"problem",
",",
"assignment",
",",
"domains",
",",
"variable_chooser",
",",
"values_sorter",
",",
"inference",
"=",
"True",
")",
":",
"from",
"simpleai",
".",
"search",
".",
"arc",
"import",
"arc_consistency_3",
"if",
"len",
"(",
... | Internal recursive backtracking algorithm. | [
"Internal",
"recursive",
"backtracking",
"algorithm",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L123-L155 |
simpleai-team/simpleai | simpleai/search/csp.py | _min_conflicts_value | def _min_conflicts_value(problem, assignment, variable):
'''
Return the value generate the less number of conflicts.
In case of tie, a random value is selected among this values subset.
'''
return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x)) | python | def _min_conflicts_value(problem, assignment, variable):
'''
Return the value generate the less number of conflicts.
In case of tie, a random value is selected among this values subset.
'''
return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x)) | [
"def",
"_min_conflicts_value",
"(",
"problem",
",",
"assignment",
",",
"variable",
")",
":",
"return",
"argmin",
"(",
"problem",
".",
"domains",
"[",
"variable",
"]",
",",
"lambda",
"x",
":",
"_count_conflicts",
"(",
"problem",
",",
"assignment",
",",
"varia... | Return the value generate the less number of conflicts.
In case of tie, a random value is selected among this values subset. | [
"Return",
"the",
"value",
"generate",
"the",
"less",
"number",
"of",
"conflicts",
".",
"In",
"case",
"of",
"tie",
"a",
"random",
"value",
"is",
"selected",
"among",
"this",
"values",
"subset",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L158-L163 |
simpleai-team/simpleai | simpleai/search/csp.py | min_conflicts | def min_conflicts(problem, initial_assignment=None, iterations_limit=0):
"""
Min conflicts search.
initial_assignment the initial assignment, or None to generate a random
one.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until ... | python | def min_conflicts(problem, initial_assignment=None, iterations_limit=0):
"""
Min conflicts search.
initial_assignment the initial assignment, or None to generate a random
one.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until ... | [
"def",
"min_conflicts",
"(",
"problem",
",",
"initial_assignment",
"=",
"None",
",",
"iterations_limit",
"=",
"0",
")",
":",
"assignment",
"=",
"{",
"}",
"if",
"initial_assignment",
":",
"assignment",
".",
"update",
"(",
"initial_assignment",
")",
"else",
":",... | Min conflicts search.
initial_assignment the initial assignment, or None to generate a random
one.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until if finds an assignment
that doesn't generate conflicts (a solution). | [
"Min",
"conflicts",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L166-L204 |
simpleai-team/simpleai | simpleai/search/csp.py | convert_to_binary | def convert_to_binary(variables, domains, constraints):
"""
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem.
"""
def wdiff(vars_):
def diff(variables, values):
hidden, other = variables
if hidd... | python | def convert_to_binary(variables, domains, constraints):
"""
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem.
"""
def wdiff(vars_):
def diff(variables, values):
hidden, other = variables
if hidd... | [
"def",
"convert_to_binary",
"(",
"variables",
",",
"domains",
",",
"constraints",
")",
":",
"def",
"wdiff",
"(",
"vars_",
")",
":",
"def",
"diff",
"(",
"variables",
",",
"values",
")",
":",
"hidden",
",",
"other",
"=",
"variables",
"if",
"hidden",
".",
... | Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem. | [
"Returns",
"new",
"constraint",
"list",
"all",
"binary",
"using",
"hidden",
"variables",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L207-L242 |
simpleai-team/simpleai | simpleai/machine_learning/reinforcement_learning.py | boltzmann_exploration | def boltzmann_exploration(actions, utilities, temperature, action_counter):
'''returns an action with a probability depending on utilities and temperature'''
utilities = [utilities[x] for x in actions]
temperature = max(temperature, 0.01)
_max = max(utilities)
_min = min(utilities)
if _max == _m... | python | def boltzmann_exploration(actions, utilities, temperature, action_counter):
'''returns an action with a probability depending on utilities and temperature'''
utilities = [utilities[x] for x in actions]
temperature = max(temperature, 0.01)
_max = max(utilities)
_min = min(utilities)
if _max == _m... | [
"def",
"boltzmann_exploration",
"(",
"actions",
",",
"utilities",
",",
"temperature",
",",
"action_counter",
")",
":",
"utilities",
"=",
"[",
"utilities",
"[",
"x",
"]",
"for",
"x",
"in",
"actions",
"]",
"temperature",
"=",
"max",
"(",
"temperature",
",",
... | returns an action with a probability depending on utilities and temperature | [
"returns",
"an",
"action",
"with",
"a",
"probability",
"depending",
"on",
"utilities",
"and",
"temperature"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/reinforcement_learning.py#L28-L45 |
simpleai-team/simpleai | simpleai/machine_learning/reinforcement_learning.py | make_exponential_temperature | def make_exponential_temperature(initial_temperature, alpha):
'''returns a function like initial / exp(n * alpha)'''
def _function(n):
try:
return initial_temperature / math.exp(n * alpha)
except OverflowError:
return 0.01
return _function | python | def make_exponential_temperature(initial_temperature, alpha):
'''returns a function like initial / exp(n * alpha)'''
def _function(n):
try:
return initial_temperature / math.exp(n * alpha)
except OverflowError:
return 0.01
return _function | [
"def",
"make_exponential_temperature",
"(",
"initial_temperature",
",",
"alpha",
")",
":",
"def",
"_function",
"(",
"n",
")",
":",
"try",
":",
"return",
"initial_temperature",
"/",
"math",
".",
"exp",
"(",
"n",
"*",
"alpha",
")",
"except",
"OverflowError",
"... | returns a function like initial / exp(n * alpha) | [
"returns",
"a",
"function",
"like",
"initial",
"/",
"exp",
"(",
"n",
"*",
"alpha",
")"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/reinforcement_learning.py#L48-L55 |
simpleai-team/simpleai | samples/search/sudoku.py | mkconstraints | def mkconstraints():
"""
Make constraint list for binary constraint problem.
"""
constraints = []
for j in range(1, 10):
vars = ["%s%d" % (i, j) for i in uppercase[:9]]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for i in uppercase[:9]:
vars ... | python | def mkconstraints():
"""
Make constraint list for binary constraint problem.
"""
constraints = []
for j in range(1, 10):
vars = ["%s%d" % (i, j) for i in uppercase[:9]]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for i in uppercase[:9]:
vars ... | [
"def",
"mkconstraints",
"(",
")",
":",
"constraints",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"vars",
"=",
"[",
"\"%s%d\"",
"%",
"(",
"i",
",",
"j",
")",
"for",
"i",
"in",
"uppercase",
"[",
":",
"9",
"]",
"]",... | Make constraint list for binary constraint problem. | [
"Make",
"constraint",
"list",
"for",
"binary",
"constraint",
"problem",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/sudoku.py#L57-L77 |
simpleai-team/simpleai | simpleai/machine_learning/evaluation.py | precision | def precision(classifier, testset):
"""
Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set.
"""
hit = 0
total = 0
for e... | python | def precision(classifier, testset):
"""
Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set.
"""
hit = 0
total = 0
for e... | [
"def",
"precision",
"(",
"classifier",
",",
"testset",
")",
":",
"hit",
"=",
"0",
"total",
"=",
"0",
"for",
"example",
"in",
"testset",
":",
"if",
"classifier",
".",
"classify",
"(",
"example",
")",
"[",
"0",
"]",
"==",
"classifier",
".",
"target",
"... | Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set. | [
"Runs",
"the",
"classifier",
"for",
"each",
"example",
"in",
"testset",
"and",
"verifies",
"that",
"the",
"classification",
"is",
"correct",
"using",
"the",
"target",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/evaluation.py#L12-L30 |
simpleai-team/simpleai | simpleai/machine_learning/evaluation.py | kfold | def kfold(dataset, problem, method, k=10):
"""
Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio.
"""
if k <=... | python | def kfold(dataset, problem, method, k=10):
"""
Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio.
"""
if k <=... | [
"def",
"kfold",
"(",
"dataset",
",",
"problem",
",",
"method",
",",
"k",
"=",
"10",
")",
":",
"if",
"k",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"\"k argument must be at least 2\"",
")",
"dataset",
"=",
"list",
"(",
"dataset",
")",
"random",
".",
"... | Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio. | [
"Does",
"a",
"k",
"-",
"fold",
"on",
"dataset",
"with",
"method",
".",
"This",
"is",
"it",
"randomly",
"creates",
"k",
"-",
"partitions",
"of",
"the",
"dataset",
"and",
"k",
"-",
"times",
"trains",
"the",
"method",
"with",
"k",
"-",
"1",
"parts",
"an... | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/evaluation.py#L33-L59 |
simpleai-team/simpleai | samples/machine_learning/tic_tac_toe.py | TicTacToeProblem.actions | def actions(self, state):
'actions are index where we can make a move'
actions = []
for index, char in enumerate(state):
if char == '_':
actions.append(index)
return actions | python | def actions(self, state):
'actions are index where we can make a move'
actions = []
for index, char in enumerate(state):
if char == '_':
actions.append(index)
return actions | [
"def",
"actions",
"(",
"self",
",",
"state",
")",
":",
"actions",
"=",
"[",
"]",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"state",
")",
":",
"if",
"char",
"==",
"'_'",
":",
"actions",
".",
"append",
"(",
"index",
")",
"return",
"actions... | actions are index where we can make a move | [
"actions",
"are",
"index",
"where",
"we",
"can",
"make",
"a",
"move"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/machine_learning/tic_tac_toe.py#L14-L20 |
simpleai-team/simpleai | samples/search/missioners.py | MissionersProblem.actions | def actions(self, s):
'''Possible actions from a state.'''
# we try to generate every possible state and then filter those
# states that are valid
return [a for a in self._actions if self._is_valid(self.result(s, a))] | python | def actions(self, s):
'''Possible actions from a state.'''
# we try to generate every possible state and then filter those
# states that are valid
return [a for a in self._actions if self._is_valid(self.result(s, a))] | [
"def",
"actions",
"(",
"self",
",",
"s",
")",
":",
"# we try to generate every possible state and then filter those",
"# states that are valid",
"return",
"[",
"a",
"for",
"a",
"in",
"self",
".",
"_actions",
"if",
"self",
".",
"_is_valid",
"(",
"self",
".",
"resul... | Possible actions from a state. | [
"Possible",
"actions",
"from",
"a",
"state",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/missioners.py#L21-L25 |
simpleai-team/simpleai | samples/search/missioners.py | MissionersProblem._is_valid | def _is_valid(self, s):
'''Check if a state is valid.'''
# valid states: no more cannibals than missioners on each side,
# and numbers between 0 and 3
return ((s[0] >= s[1] or s[0] == 0)) and \
((3 - s[0]) >= (3 - s[1]) or s[0] == 3) and \
(0 <= s[0] <= 3)... | python | def _is_valid(self, s):
'''Check if a state is valid.'''
# valid states: no more cannibals than missioners on each side,
# and numbers between 0 and 3
return ((s[0] >= s[1] or s[0] == 0)) and \
((3 - s[0]) >= (3 - s[1]) or s[0] == 3) and \
(0 <= s[0] <= 3)... | [
"def",
"_is_valid",
"(",
"self",
",",
"s",
")",
":",
"# valid states: no more cannibals than missioners on each side,",
"# and numbers between 0 and 3",
"return",
"(",
"(",
"s",
"[",
"0",
"]",
">=",
"s",
"[",
"1",
"]",
"or",
"s",
"[",
"0",
"]",
"==",
"0",
")... | Check if a state is valid. | [
"Check",
"if",
"a",
"state",
"is",
"valid",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/missioners.py#L27-L34 |
simpleai-team/simpleai | samples/search/missioners.py | MissionersProblem.result | def result(self, s, a):
'''Result of applying an action to a state.'''
# result: boat on opposite side, and numbers of missioners and
# cannibals updated according to the move
if s[2] == 0:
return (s[0] - a[1][0], s[1] - a[1][1], 1)
else:
return (s[0] + a[... | python | def result(self, s, a):
'''Result of applying an action to a state.'''
# result: boat on opposite side, and numbers of missioners and
# cannibals updated according to the move
if s[2] == 0:
return (s[0] - a[1][0], s[1] - a[1][1], 1)
else:
return (s[0] + a[... | [
"def",
"result",
"(",
"self",
",",
"s",
",",
"a",
")",
":",
"# result: boat on opposite side, and numbers of missioners and",
"# cannibals updated according to the move",
"if",
"s",
"[",
"2",
"]",
"==",
"0",
":",
"return",
"(",
"s",
"[",
"0",
"]",
"-",
"a",
"[... | Result of applying an action to a state. | [
"Result",
"of",
"applying",
"an",
"action",
"to",
"a",
"state",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/missioners.py#L36-L43 |
simpleai-team/simpleai | simpleai/search/arc.py | revise | def revise(domains, arc, constraints):
"""
Given the arc X, Y (variables), removes the values from X's domain that
do not meet the constraint between X and Y.
That is, given x1 in X's domain, x1 will be removed from the domain, if
there is no value y in Y's domain that makes constraint(X,Y) True, f... | python | def revise(domains, arc, constraints):
"""
Given the arc X, Y (variables), removes the values from X's domain that
do not meet the constraint between X and Y.
That is, given x1 in X's domain, x1 will be removed from the domain, if
there is no value y in Y's domain that makes constraint(X,Y) True, f... | [
"def",
"revise",
"(",
"domains",
",",
"arc",
",",
"constraints",
")",
":",
"x",
",",
"y",
"=",
"arc",
"related_constraints",
"=",
"[",
"(",
"neighbors",
",",
"constraint",
")",
"for",
"neighbors",
",",
"constraint",
"in",
"constraints",
"if",
"set",
"(",... | Given the arc X, Y (variables), removes the values from X's domain that
do not meet the constraint between X and Y.
That is, given x1 in X's domain, x1 will be removed from the domain, if
there is no value y in Y's domain that makes constraint(X,Y) True, for
those constraints affecting X and Y. | [
"Given",
"the",
"arc",
"X",
"Y",
"(",
"variables",
")",
"removes",
"the",
"values",
"from",
"X",
"s",
"domain",
"that",
"do",
"not",
"meet",
"the",
"constraint",
"between",
"X",
"and",
"Y",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/arc.py#L13-L39 |
simpleai-team/simpleai | simpleai/search/arc.py | all_arcs | def all_arcs(constraints):
"""
For each constraint ((X, Y), const) adds:
((X, Y), const)
((Y, X), const)
"""
arcs = set()
for neighbors, constraint in constraints:
if len(neighbors) == 2:
x, y = neighbors
list(map(arcs.add, ((x, y), (y, x))))
ret... | python | def all_arcs(constraints):
"""
For each constraint ((X, Y), const) adds:
((X, Y), const)
((Y, X), const)
"""
arcs = set()
for neighbors, constraint in constraints:
if len(neighbors) == 2:
x, y = neighbors
list(map(arcs.add, ((x, y), (y, x))))
ret... | [
"def",
"all_arcs",
"(",
"constraints",
")",
":",
"arcs",
"=",
"set",
"(",
")",
"for",
"neighbors",
",",
"constraint",
"in",
"constraints",
":",
"if",
"len",
"(",
"neighbors",
")",
"==",
"2",
":",
"x",
",",
"y",
"=",
"neighbors",
"list",
"(",
"map",
... | For each constraint ((X, Y), const) adds:
((X, Y), const)
((Y, X), const) | [
"For",
"each",
"constraint",
"((",
"X",
"Y",
")",
"const",
")",
"adds",
":",
"((",
"X",
"Y",
")",
"const",
")",
"((",
"Y",
"X",
")",
"const",
")"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/arc.py#L42-L55 |
simpleai-team/simpleai | simpleai/search/arc.py | arc_consistency_3 | def arc_consistency_3(domains, constraints):
"""
Makes a CSP problem arc consistent.
Ignores any constraint that is not binary.
"""
arcs = list(all_arcs(constraints))
pending_arcs = set(arcs)
while pending_arcs:
x, y = pending_arcs.pop()
if revise(domains, (x, y), constrain... | python | def arc_consistency_3(domains, constraints):
"""
Makes a CSP problem arc consistent.
Ignores any constraint that is not binary.
"""
arcs = list(all_arcs(constraints))
pending_arcs = set(arcs)
while pending_arcs:
x, y = pending_arcs.pop()
if revise(domains, (x, y), constrain... | [
"def",
"arc_consistency_3",
"(",
"domains",
",",
"constraints",
")",
":",
"arcs",
"=",
"list",
"(",
"all_arcs",
"(",
"constraints",
")",
")",
"pending_arcs",
"=",
"set",
"(",
"arcs",
")",
"while",
"pending_arcs",
":",
"x",
",",
"y",
"=",
"pending_arcs",
... | Makes a CSP problem arc consistent.
Ignores any constraint that is not binary. | [
"Makes",
"a",
"CSP",
"problem",
"arc",
"consistent",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/arc.py#L58-L74 |
simpleai-team/simpleai | simpleai/search/models.py | SearchNode.expand | def expand(self, local_search=False):
'''Create successors.'''
new_nodes = []
for action in self.problem.actions(self.state):
new_state = self.problem.result(self.state, action)
cost = self.problem.cost(self.state,
action,
... | python | def expand(self, local_search=False):
'''Create successors.'''
new_nodes = []
for action in self.problem.actions(self.state):
new_state = self.problem.result(self.state, action)
cost = self.problem.cost(self.state,
action,
... | [
"def",
"expand",
"(",
"self",
",",
"local_search",
"=",
"False",
")",
":",
"new_nodes",
"=",
"[",
"]",
"for",
"action",
"in",
"self",
".",
"problem",
".",
"actions",
"(",
"self",
".",
"state",
")",
":",
"new_state",
"=",
"self",
".",
"problem",
".",
... | Create successors. | [
"Create",
"successors",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/models.py#L102-L117 |
simpleai-team/simpleai | simpleai/search/models.py | SearchNode.path | def path(self):
'''Path (list of nodes and actions) from root to this node.'''
node = self
path = []
while node:
path.append((node.action, node.state))
node = node.parent
return list(reversed(path)) | python | def path(self):
'''Path (list of nodes and actions) from root to this node.'''
node = self
path = []
while node:
path.append((node.action, node.state))
node = node.parent
return list(reversed(path)) | [
"def",
"path",
"(",
"self",
")",
":",
"node",
"=",
"self",
"path",
"=",
"[",
"]",
"while",
"node",
":",
"path",
".",
"append",
"(",
"(",
"node",
".",
"action",
",",
"node",
".",
"state",
")",
")",
"node",
"=",
"node",
".",
"parent",
"return",
"... | Path (list of nodes and actions) from root to this node. | [
"Path",
"(",
"list",
"of",
"nodes",
"and",
"actions",
")",
"from",
"root",
"to",
"this",
"node",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/models.py#L119-L126 |
simpleai-team/simpleai | simpleai/environments.py | Environment.step | def step(self, viewer=None):
"This method evolves one step in time"
if not self.is_completed(self.state):
for agent in self.agents:
action = agent.program(self.percept(agent, self.state))
next_state = self.do_action(self.state, action, agent)
i... | python | def step(self, viewer=None):
"This method evolves one step in time"
if not self.is_completed(self.state):
for agent in self.agents:
action = agent.program(self.percept(agent, self.state))
next_state = self.do_action(self.state, action, agent)
i... | [
"def",
"step",
"(",
"self",
",",
"viewer",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_completed",
"(",
"self",
".",
"state",
")",
":",
"for",
"agent",
"in",
"self",
".",
"agents",
":",
"action",
"=",
"agent",
".",
"program",
"(",
"self",
... | This method evolves one step in time | [
"This",
"method",
"evolves",
"one",
"step",
"in",
"time"
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/environments.py#L18-L28 |
simpleai-team/simpleai | simpleai/search/traditional.py | breadth_first | def breadth_first(problem, graph_search=False, viewer=None):
'''
Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
FifoList(),
... | python | def breadth_first(problem, graph_search=False, viewer=None):
'''
Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
FifoList(),
... | [
"def",
"breadth_first",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"FifoList",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"viewer",
"=",
"viewer",
")"
] | Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Breadth",
"first",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L8-L19 |
simpleai-team/simpleai | simpleai/search/traditional.py | depth_first | def depth_first(problem, graph_search=False, viewer=None):
'''
Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
LifoList(),
... | python | def depth_first(problem, graph_search=False, viewer=None):
'''
Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
LifoList(),
... | [
"def",
"depth_first",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"LifoList",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"viewer",
"=",
"viewer",
")"
] | Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Depth",
"first",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L22-L33 |
simpleai-team/simpleai | simpleai/search/traditional.py | limited_depth_first | def limited_depth_first(problem, depth_limit, graph_search=False, viewer=None):
'''
Limited depth first search.
Depth_limit is the maximum depth allowed, being depth 0 the initial state.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.resul... | python | def limited_depth_first(problem, depth_limit, graph_search=False, viewer=None):
'''
Limited depth first search.
Depth_limit is the maximum depth allowed, being depth 0 the initial state.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.resul... | [
"def",
"limited_depth_first",
"(",
"problem",
",",
"depth_limit",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"LifoList",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"depth_l... | Limited depth first search.
Depth_limit is the maximum depth allowed, being depth 0 the initial state.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Limited",
"depth",
"first",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L36-L49 |
simpleai-team/simpleai | simpleai/search/traditional.py | iterative_limited_depth_first | def iterative_limited_depth_first(problem, graph_search=False, viewer=None):
'''
Iterative limited depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
solution = None
limit ... | python | def iterative_limited_depth_first(problem, graph_search=False, viewer=None):
'''
Iterative limited depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
solution = None
limit ... | [
"def",
"iterative_limited_depth_first",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"solution",
"=",
"None",
"limit",
"=",
"0",
"while",
"not",
"solution",
":",
"solution",
"=",
"limited_depth_first",
"(",
"problem"... | Iterative limited depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Iterative",
"limited",
"depth",
"first",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L52-L73 |
simpleai-team/simpleai | simpleai/search/traditional.py | uniform_cost | def uniform_cost(problem, graph_search=False, viewer=None):
'''
Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost.
'''
return _search(problem,
... | python | def uniform_cost(problem, graph_search=False, viewer=None):
'''
Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost.
'''
return _search(problem,
... | [
"def",
"uniform_cost",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"BoundedPriorityQueue",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"node_factory",
"=",
"S... | Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost. | [
"Uniform",
"cost",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L76-L89 |
simpleai-team/simpleai | simpleai/search/traditional.py | greedy | def greedy(problem, graph_search=False, viewer=None):
'''
Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
... | python | def greedy(problem, graph_search=False, viewer=None):
'''
Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
... | [
"def",
"greedy",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"BoundedPriorityQueue",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"node_factory",
"=",
"SearchN... | Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. | [
"Greedy",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L92-L105 |
simpleai-team/simpleai | simpleai/search/traditional.py | astar | def astar(problem, graph_search=False, viewer=None):
'''
A* search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
... | python | def astar(problem, graph_search=False, viewer=None):
'''
A* search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
... | [
"def",
"astar",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"BoundedPriorityQueue",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"node_factory",
"=",
"SearchNo... | A* search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. | [
"A",
"*",
"search",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L108-L121 |
simpleai-team/simpleai | simpleai/search/traditional.py | _search | def _search(problem, fringe, graph_search=False, depth_limit=None,
node_factory=SearchNode, graph_replace_when_better=False,
viewer=None):
'''
Basic search algorithm, base of all the other search algorithms.
'''
if viewer:
viewer.event('started')
memory = set()
i... | python | def _search(problem, fringe, graph_search=False, depth_limit=None,
node_factory=SearchNode, graph_replace_when_better=False,
viewer=None):
'''
Basic search algorithm, base of all the other search algorithms.
'''
if viewer:
viewer.event('started')
memory = set()
i... | [
"def",
"_search",
"(",
"problem",
",",
"fringe",
",",
"graph_search",
"=",
"False",
",",
"depth_limit",
"=",
"None",
",",
"node_factory",
"=",
"SearchNode",
",",
"graph_replace_when_better",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"if",
"viewer",... | Basic search algorithm, base of all the other search algorithms. | [
"Basic",
"search",
"algorithm",
"base",
"of",
"all",
"the",
"other",
"search",
"algorithms",
"."
] | train | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L124-L173 |
andosa/treeinterpreter | treeinterpreter/treeinterpreter.py | _get_tree_paths | def _get_tree_paths(tree, node_id, depth=0):
"""
Returns all paths through the tree as list of node_ids
"""
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
if... | python | def _get_tree_paths(tree, node_id, depth=0):
"""
Returns all paths through the tree as list of node_ids
"""
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
if... | [
"def",
"_get_tree_paths",
"(",
"tree",
",",
"node_id",
",",
"depth",
"=",
"0",
")",
":",
"if",
"node_id",
"==",
"_tree",
".",
"TREE_LEAF",
":",
"raise",
"ValueError",
"(",
"\"Invalid node_id %s\"",
"%",
"_tree",
".",
"TREE_LEAF",
")",
"left_child",
"=",
"t... | Returns all paths through the tree as list of node_ids | [
"Returns",
"all",
"paths",
"through",
"the",
"tree",
"as",
"list",
"of",
"node_ids"
] | train | https://github.com/andosa/treeinterpreter/blob/c4294ad6ad74ea574ca41aa81b6f7f1545da0186/treeinterpreter/treeinterpreter.py#L12-L33 |
andosa/treeinterpreter | treeinterpreter/treeinterpreter.py | _predict_tree | def _predict_tree(model, X, joint_contribution=False):
"""
For a given DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, or ExtraTreeClassifier,
returns a triple of [prediction, bias and feature_contributions], such
that prediction ≈ bias + feature_contributions.
"""
leaves ... | python | def _predict_tree(model, X, joint_contribution=False):
"""
For a given DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, or ExtraTreeClassifier,
returns a triple of [prediction, bias and feature_contributions], such
that prediction ≈ bias + feature_contributions.
"""
leaves ... | [
"def",
"_predict_tree",
"(",
"model",
",",
"X",
",",
"joint_contribution",
"=",
"False",
")",
":",
"leaves",
"=",
"model",
".",
"apply",
"(",
"X",
")",
"paths",
"=",
"_get_tree_paths",
"(",
"model",
".",
"tree_",
",",
"0",
")",
"for",
"path",
"in",
"... | For a given DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, or ExtraTreeClassifier,
returns a triple of [prediction, bias and feature_contributions], such
that prediction ≈ bias + feature_contributions. | [
"For",
"a",
"given",
"DecisionTreeRegressor",
"DecisionTreeClassifier",
"ExtraTreeRegressor",
"or",
"ExtraTreeClassifier",
"returns",
"a",
"triple",
"of",
"[",
"prediction",
"bias",
"and",
"feature_contributions",
"]",
"such",
"that",
"prediction",
"≈",
"bias",
"+",
"... | train | https://github.com/andosa/treeinterpreter/blob/c4294ad6ad74ea574ca41aa81b6f7f1545da0186/treeinterpreter/treeinterpreter.py#L36-L114 |
andosa/treeinterpreter | treeinterpreter/treeinterpreter.py | _predict_forest | def _predict_forest(model, X, joint_contribution=False):
"""
For a given RandomForestRegressor, RandomForestClassifier,
ExtraTreesRegressor, or ExtraTreesClassifier returns a triple of
[prediction, bias and feature_contributions], such that prediction ≈ bias +
feature_contributions.
"""
bias... | python | def _predict_forest(model, X, joint_contribution=False):
"""
For a given RandomForestRegressor, RandomForestClassifier,
ExtraTreesRegressor, or ExtraTreesClassifier returns a triple of
[prediction, bias and feature_contributions], such that prediction ≈ bias +
feature_contributions.
"""
bias... | [
"def",
"_predict_forest",
"(",
"model",
",",
"X",
",",
"joint_contribution",
"=",
"False",
")",
":",
"biases",
"=",
"[",
"]",
"contributions",
"=",
"[",
"]",
"predictions",
"=",
"[",
"]",
"if",
"joint_contribution",
":",
"for",
"tree",
"in",
"model",
"."... | For a given RandomForestRegressor, RandomForestClassifier,
ExtraTreesRegressor, or ExtraTreesClassifier returns a triple of
[prediction, bias and feature_contributions], such that prediction ≈ bias +
feature_contributions. | [
"For",
"a",
"given",
"RandomForestRegressor",
"RandomForestClassifier",
"ExtraTreesRegressor",
"or",
"ExtraTreesClassifier",
"returns",
"a",
"triple",
"of",
"[",
"prediction",
"bias",
"and",
"feature_contributions",
"]",
"such",
"that",
"prediction",
"≈",
"bias",
"+",
... | train | https://github.com/andosa/treeinterpreter/blob/c4294ad6ad74ea574ca41aa81b6f7f1545da0186/treeinterpreter/treeinterpreter.py#L117-L167 |
andosa/treeinterpreter | treeinterpreter/treeinterpreter.py | predict | def predict(model, X, joint_contribution=False):
""" Returns a triple (prediction, bias, feature_contributions), such
that prediction ≈ bias + feature_contributions.
Parameters
----------
model : DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, ExtraTreeClassifier,
... | python | def predict(model, X, joint_contribution=False):
""" Returns a triple (prediction, bias, feature_contributions), such
that prediction ≈ bias + feature_contributions.
Parameters
----------
model : DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, ExtraTreeClassifier,
... | [
"def",
"predict",
"(",
"model",
",",
"X",
",",
"joint_contribution",
"=",
"False",
")",
":",
"# Only single out response variable supported,",
"if",
"model",
".",
"n_outputs_",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Multilabel classification trees not supported\"... | Returns a triple (prediction, bias, feature_contributions), such
that prediction ≈ bias + feature_contributions.
Parameters
----------
model : DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, ExtraTreeClassifier,
RandomForestRegressor, RandomForestClassifier,
Ex... | [
"Returns",
"a",
"triple",
"(",
"prediction",
"bias",
"feature_contributions",
")",
"such",
"that",
"prediction",
"≈",
"bias",
"+",
"feature_contributions",
".",
"Parameters",
"----------",
"model",
":",
"DecisionTreeRegressor",
"DecisionTreeClassifier",
"ExtraTreeRegresso... | train | https://github.com/andosa/treeinterpreter/blob/c4294ad6ad74ea574ca41aa81b6f7f1545da0186/treeinterpreter/treeinterpreter.py#L170-L215 |
csurfer/rake-nltk | rake_nltk/rake.py | Rake.extract_keywords_from_text | def extract_keywords_from_text(self, text):
"""Method to extract keywords from the text provided.
:param text: Text to extract keywords from, provided as a string.
"""
sentences = nltk.tokenize.sent_tokenize(text)
self.extract_keywords_from_sentences(sentences) | python | def extract_keywords_from_text(self, text):
"""Method to extract keywords from the text provided.
:param text: Text to extract keywords from, provided as a string.
"""
sentences = nltk.tokenize.sent_tokenize(text)
self.extract_keywords_from_sentences(sentences) | [
"def",
"extract_keywords_from_text",
"(",
"self",
",",
"text",
")",
":",
"sentences",
"=",
"nltk",
".",
"tokenize",
".",
"sent_tokenize",
"(",
"text",
")",
"self",
".",
"extract_keywords_from_sentences",
"(",
"sentences",
")"
] | Method to extract keywords from the text provided.
:param text: Text to extract keywords from, provided as a string. | [
"Method",
"to",
"extract",
"keywords",
"from",
"the",
"text",
"provided",
"."
] | train | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L76-L82 |
csurfer/rake-nltk | rake_nltk/rake.py | Rake.extract_keywords_from_sentences | def extract_keywords_from_sentences(self, sentences):
"""Method to extract keywords from the list of sentences provided.
:param sentences: Text to extraxt keywords from, provided as a list
of strings, where each string is a sentence.
"""
phrase_list = self._gen... | python | def extract_keywords_from_sentences(self, sentences):
"""Method to extract keywords from the list of sentences provided.
:param sentences: Text to extraxt keywords from, provided as a list
of strings, where each string is a sentence.
"""
phrase_list = self._gen... | [
"def",
"extract_keywords_from_sentences",
"(",
"self",
",",
"sentences",
")",
":",
"phrase_list",
"=",
"self",
".",
"_generate_phrases",
"(",
"sentences",
")",
"self",
".",
"_build_frequency_dist",
"(",
"phrase_list",
")",
"self",
".",
"_build_word_co_occurance_graph"... | Method to extract keywords from the list of sentences provided.
:param sentences: Text to extraxt keywords from, provided as a list
of strings, where each string is a sentence. | [
"Method",
"to",
"extract",
"keywords",
"from",
"the",
"list",
"of",
"sentences",
"provided",
"."
] | train | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L84-L93 |
csurfer/rake-nltk | rake_nltk/rake.py | Rake._build_word_co_occurance_graph | def _build_word_co_occurance_graph(self, phrase_list):
"""Builds the co-occurance graph of words in the given body of text to
compute degree of each word.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender p... | python | def _build_word_co_occurance_graph(self, phrase_list):
"""Builds the co-occurance graph of words in the given body of text to
compute degree of each word.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender p... | [
"def",
"_build_word_co_occurance_graph",
"(",
"self",
",",
"phrase_list",
")",
":",
"co_occurance_graph",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
")",
"for",
"phrase",
"in",
"phrase_list",
":",
"# For each phrase in the... | Builds the co-occurance graph of words in the given body of text to
compute degree of each word.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender phrase. | [
"Builds",
"the",
"co",
"-",
"occurance",
"graph",
"of",
"words",
"in",
"the",
"given",
"body",
"of",
"text",
"to",
"compute",
"degree",
"of",
"each",
"word",
"."
] | train | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L135-L153 |
csurfer/rake-nltk | rake_nltk/rake.py | Rake._build_ranklist | def _build_ranklist(self, phrase_list):
"""Method to rank each contender phrase using the formula
phrase_score = sum of scores of words in the phrase.
word_score = d(w)/f(w) where d is degree and f is frequency.
:param phrase_list: List of List of strings where each sublist... | python | def _build_ranklist(self, phrase_list):
"""Method to rank each contender phrase using the formula
phrase_score = sum of scores of words in the phrase.
word_score = d(w)/f(w) where d is degree and f is frequency.
:param phrase_list: List of List of strings where each sublist... | [
"def",
"_build_ranklist",
"(",
"self",
",",
"phrase_list",
")",
":",
"self",
".",
"rank_list",
"=",
"[",
"]",
"for",
"phrase",
"in",
"phrase_list",
":",
"rank",
"=",
"0.0",
"for",
"word",
"in",
"phrase",
":",
"if",
"self",
".",
"metric",
"==",
"Metric"... | Method to rank each contender phrase using the formula
phrase_score = sum of scores of words in the phrase.
word_score = d(w)/f(w) where d is degree and f is frequency.
:param phrase_list: List of List of strings where each sublist is a
collection of wor... | [
"Method",
"to",
"rank",
"each",
"contender",
"phrase",
"using",
"the",
"formula"
] | train | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L155-L176 |
csurfer/rake-nltk | rake_nltk/rake.py | Rake._generate_phrases | def _generate_phrases(self, sentences):
"""Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tu... | python | def _generate_phrases(self, sentences):
"""Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tu... | [
"def",
"_generate_phrases",
"(",
"self",
",",
"sentences",
")",
":",
"phrase_list",
"=",
"set",
"(",
")",
"# Create contender phrases from sentences.",
"for",
"sentence",
"in",
"sentences",
":",
"word_list",
"=",
"[",
"word",
".",
"lower",
"(",
")",
"for",
"wo... | Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tuple is a collection
of words formi... | [
"Method",
"to",
"generate",
"contender",
"phrases",
"given",
"the",
"sentences",
"of",
"the",
"text",
"document",
"."
] | train | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L178-L192 |
csurfer/rake-nltk | rake_nltk/rake.py | Rake._get_phrase_list_from_words | def _get_phrase_list_from_words(self, word_list):
"""Method to create contender phrases from the list of words that form
a sentence by dropping stopwords and punctuations and grouping the left
words into phrases. Only phrases in the given length range (both limits
inclusive) would be con... | python | def _get_phrase_list_from_words(self, word_list):
"""Method to create contender phrases from the list of words that form
a sentence by dropping stopwords and punctuations and grouping the left
words into phrases. Only phrases in the given length range (both limits
inclusive) would be con... | [
"def",
"_get_phrase_list_from_words",
"(",
"self",
",",
"word_list",
")",
":",
"groups",
"=",
"groupby",
"(",
"word_list",
",",
"lambda",
"x",
":",
"x",
"not",
"in",
"self",
".",
"to_ignore",
")",
"phrases",
"=",
"[",
"tuple",
"(",
"group",
"[",
"1",
"... | Method to create contender phrases from the list of words that form
a sentence by dropping stopwords and punctuations and grouping the left
words into phrases. Only phrases in the given length range (both limits
inclusive) would be considered to build co-occurrence matrix. Ex:
Sentence:... | [
"Method",
"to",
"create",
"contender",
"phrases",
"from",
"the",
"list",
"of",
"words",
"that",
"form",
"a",
"sentence",
"by",
"dropping",
"stopwords",
"and",
"punctuations",
"and",
"grouping",
"the",
"left",
"words",
"into",
"phrases",
".",
"Only",
"phrases",... | train | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L194-L222 |
HazyResearch/pdftotree | pdftotree/utils/pdf/grid.py | _retain_centroids | def _retain_centroids(numbers, thres):
"""Only keep one number for each cluster within thres of each other"""
numbers.sort()
prev = -1
ret = []
for n in numbers:
if prev < 0 or n - prev > thres:
ret.append(n)
prev = n
return ret | python | def _retain_centroids(numbers, thres):
"""Only keep one number for each cluster within thres of each other"""
numbers.sort()
prev = -1
ret = []
for n in numbers:
if prev < 0 or n - prev > thres:
ret.append(n)
prev = n
return ret | [
"def",
"_retain_centroids",
"(",
"numbers",
",",
"thres",
")",
":",
"numbers",
".",
"sort",
"(",
")",
"prev",
"=",
"-",
"1",
"ret",
"=",
"[",
"]",
"for",
"n",
"in",
"numbers",
":",
"if",
"prev",
"<",
"0",
"or",
"n",
"-",
"prev",
">",
"thres",
"... | Only keep one number for each cluster within thres of each other | [
"Only",
"keep",
"one",
"number",
"for",
"each",
"cluster",
"within",
"thres",
"of",
"each",
"other"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/grid.py#L178-L187 |
HazyResearch/pdftotree | pdftotree/utils/pdf/grid.py | _split_vlines_hlines | def _split_vlines_hlines(lines):
"""Separates lines into horizontal and vertical ones"""
vlines, hlines = [], []
for line in lines:
(vlines if line.x1 - line.x0 < 0.1 else hlines).append(line)
return vlines, hlines | python | def _split_vlines_hlines(lines):
"""Separates lines into horizontal and vertical ones"""
vlines, hlines = [], []
for line in lines:
(vlines if line.x1 - line.x0 < 0.1 else hlines).append(line)
return vlines, hlines | [
"def",
"_split_vlines_hlines",
"(",
"lines",
")",
":",
"vlines",
",",
"hlines",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"(",
"vlines",
"if",
"line",
".",
"x1",
"-",
"line",
".",
"x0",
"<",
"0.1",
"else",
"hlines",
")",
".... | Separates lines into horizontal and vertical ones | [
"Separates",
"lines",
"into",
"horizontal",
"and",
"vertical",
"ones"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/grid.py#L190-L195 |
HazyResearch/pdftotree | pdftotree/utils/pdf/grid.py | _npiter | def _npiter(arr):
"""Wrapper for iterating numpy array"""
for a in np.nditer(arr, flags=["refs_ok"]):
c = a.item()
if c is not None:
yield c | python | def _npiter(arr):
"""Wrapper for iterating numpy array"""
for a in np.nditer(arr, flags=["refs_ok"]):
c = a.item()
if c is not None:
yield c | [
"def",
"_npiter",
"(",
"arr",
")",
":",
"for",
"a",
"in",
"np",
".",
"nditer",
"(",
"arr",
",",
"flags",
"=",
"[",
"\"refs_ok\"",
"]",
")",
":",
"c",
"=",
"a",
".",
"item",
"(",
")",
"if",
"c",
"is",
"not",
"None",
":",
"yield",
"c"
] | Wrapper for iterating numpy array | [
"Wrapper",
"for",
"iterating",
"numpy",
"array"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/grid.py#L198-L203 |
HazyResearch/pdftotree | pdftotree/utils/pdf/grid.py | Grid.get_normalized_grid | def get_normalized_grid(self):
"""
Analyzes subcell structure
"""
log = logging.getLogger(__name__)
# Resolve multirow mentions, TODO: validate against all PDFs
# subcol_count = 0
mega_rows = []
for row_id, row in enumerate(self._grid):
# maps... | python | def get_normalized_grid(self):
"""
Analyzes subcell structure
"""
log = logging.getLogger(__name__)
# Resolve multirow mentions, TODO: validate against all PDFs
# subcol_count = 0
mega_rows = []
for row_id, row in enumerate(self._grid):
# maps... | [
"def",
"get_normalized_grid",
"(",
"self",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Resolve multirow mentions, TODO: validate against all PDFs",
"# subcol_count = 0",
"mega_rows",
"=",
"[",
"]",
"for",
"row_id",
",",
"row",
"in",
... | Analyzes subcell structure | [
"Analyzes",
"subcell",
"structure"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/grid.py#L118-L144 |
HazyResearch/pdftotree | pdftotree/utils/pdf/grid.py | Grid._mark_grid_bounds | def _mark_grid_bounds(self, plane, region_bbox):
"""
Assume all lines define a complete grid over the region_bbox.
Detect which lines are missing so that we can recover merged
cells.
"""
# Grid boundaries
vbars = np.zeros([self.num_rows, self.num_cols + 1], dtype=... | python | def _mark_grid_bounds(self, plane, region_bbox):
"""
Assume all lines define a complete grid over the region_bbox.
Detect which lines are missing so that we can recover merged
cells.
"""
# Grid boundaries
vbars = np.zeros([self.num_rows, self.num_cols + 1], dtype=... | [
"def",
"_mark_grid_bounds",
"(",
"self",
",",
"plane",
",",
"region_bbox",
")",
":",
"# Grid boundaries",
"vbars",
"=",
"np",
".",
"zeros",
"(",
"[",
"self",
".",
"num_rows",
",",
"self",
".",
"num_cols",
"+",
"1",
"]",
",",
"dtype",
"=",
"np",
".",
... | Assume all lines define a complete grid over the region_bbox.
Detect which lines are missing so that we can recover merged
cells. | [
"Assume",
"all",
"lines",
"define",
"a",
"complete",
"grid",
"over",
"the",
"region_bbox",
".",
"Detect",
"which",
"lines",
"are",
"missing",
"so",
"that",
"we",
"can",
"recover",
"merged",
"cells",
"."
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/grid.py#L146-L170 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | vectorize | def vectorize(e, tolerance=0.1):
"""
vectorizes the pdf object's bounding box
min_width is the width under which we consider it a line
instead of a big rectangle
"""
tolerance = max(tolerance, e.linewidth)
is_high = e.height > tolerance
is_wide = e.width > tolerance
# if skewed towar... | python | def vectorize(e, tolerance=0.1):
"""
vectorizes the pdf object's bounding box
min_width is the width under which we consider it a line
instead of a big rectangle
"""
tolerance = max(tolerance, e.linewidth)
is_high = e.height > tolerance
is_wide = e.width > tolerance
# if skewed towar... | [
"def",
"vectorize",
"(",
"e",
",",
"tolerance",
"=",
"0.1",
")",
":",
"tolerance",
"=",
"max",
"(",
"tolerance",
",",
"e",
".",
"linewidth",
")",
"is_high",
"=",
"e",
".",
"height",
">",
"tolerance",
"is_wide",
"=",
"e",
".",
"width",
">",
"tolerance... | vectorizes the pdf object's bounding box
min_width is the width under which we consider it a line
instead of a big rectangle | [
"vectorizes",
"the",
"pdf",
"object",
"s",
"bounding",
"box",
"min_width",
"is",
"the",
"width",
"under",
"which",
"we",
"consider",
"it",
"a",
"line",
"instead",
"of",
"a",
"big",
"rectangle"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L36-L49 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | aligned | def aligned(e1, e2):
"""
alignment is determined by two boxes having one exactly the same
attribute, which could mean parallel, perpendicularly forming a
corner etc.
"""
return (
any(close(c1, c2) for c1, c2 in zip(e1.bbox, e2.bbox))
or x_center_aligned(e1, e2)
or y_cente... | python | def aligned(e1, e2):
"""
alignment is determined by two boxes having one exactly the same
attribute, which could mean parallel, perpendicularly forming a
corner etc.
"""
return (
any(close(c1, c2) for c1, c2 in zip(e1.bbox, e2.bbox))
or x_center_aligned(e1, e2)
or y_cente... | [
"def",
"aligned",
"(",
"e1",
",",
"e2",
")",
":",
"return",
"(",
"any",
"(",
"close",
"(",
"c1",
",",
"c2",
")",
"for",
"c1",
",",
"c2",
"in",
"zip",
"(",
"e1",
".",
"bbox",
",",
"e2",
".",
"bbox",
")",
")",
"or",
"x_center_aligned",
"(",
"e1... | alignment is determined by two boxes having one exactly the same
attribute, which could mean parallel, perpendicularly forming a
corner etc. | [
"alignment",
"is",
"determined",
"by",
"two",
"boxes",
"having",
"one",
"exactly",
"the",
"same",
"attribute",
"which",
"could",
"mean",
"parallel",
"perpendicularly",
"forming",
"a",
"corner",
"etc",
"."
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L52-L62 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | bound_bboxes | def bound_bboxes(bboxes):
"""
Finds the minimal bbox that contains all given bboxes
"""
group_x0 = min(map(lambda l: l[x0], bboxes))
group_y0 = min(map(lambda l: l[y0], bboxes))
group_x1 = max(map(lambda l: l[x1], bboxes))
group_y1 = max(map(lambda l: l[y1], bboxes))
return (group_x0, gr... | python | def bound_bboxes(bboxes):
"""
Finds the minimal bbox that contains all given bboxes
"""
group_x0 = min(map(lambda l: l[x0], bboxes))
group_y0 = min(map(lambda l: l[y0], bboxes))
group_x1 = max(map(lambda l: l[x1], bboxes))
group_y1 = max(map(lambda l: l[y1], bboxes))
return (group_x0, gr... | [
"def",
"bound_bboxes",
"(",
"bboxes",
")",
":",
"group_x0",
"=",
"min",
"(",
"map",
"(",
"lambda",
"l",
":",
"l",
"[",
"x0",
"]",
",",
"bboxes",
")",
")",
"group_y0",
"=",
"min",
"(",
"map",
"(",
"lambda",
"l",
":",
"l",
"[",
"y0",
"]",
",",
... | Finds the minimal bbox that contains all given bboxes | [
"Finds",
"the",
"minimal",
"bbox",
"that",
"contains",
"all",
"given",
"bboxes"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L106-L114 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | bound_elems | def bound_elems(elems):
"""
Finds the minimal bbox that contains all given elems
"""
group_x0 = min(map(lambda l: l.x0, elems))
group_y0 = min(map(lambda l: l.y0, elems))
group_x1 = max(map(lambda l: l.x1, elems))
group_y1 = max(map(lambda l: l.y1, elems))
return (group_x0, group_y0, gro... | python | def bound_elems(elems):
"""
Finds the minimal bbox that contains all given elems
"""
group_x0 = min(map(lambda l: l.x0, elems))
group_y0 = min(map(lambda l: l.y0, elems))
group_x1 = max(map(lambda l: l.x1, elems))
group_y1 = max(map(lambda l: l.y1, elems))
return (group_x0, group_y0, gro... | [
"def",
"bound_elems",
"(",
"elems",
")",
":",
"group_x0",
"=",
"min",
"(",
"map",
"(",
"lambda",
"l",
":",
"l",
".",
"x0",
",",
"elems",
")",
")",
"group_y0",
"=",
"min",
"(",
"map",
"(",
"lambda",
"l",
":",
"l",
".",
"y0",
",",
"elems",
")",
... | Finds the minimal bbox that contains all given elems | [
"Finds",
"the",
"minimal",
"bbox",
"that",
"contains",
"all",
"given",
"elems"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L117-L125 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | intersect | def intersect(a, b):
"""
Check if two rectangles intersect
"""
if a[x0] == a[x1] or a[y0] == a[y1]:
return False
if b[x0] == b[x1] or b[y0] == b[y1]:
return False
return a[x0] <= b[x1] and b[x0] <= a[x1] and a[y0] <= b[y1] and b[y0] <= a[y1] | python | def intersect(a, b):
"""
Check if two rectangles intersect
"""
if a[x0] == a[x1] or a[y0] == a[y1]:
return False
if b[x0] == b[x1] or b[y0] == b[y1]:
return False
return a[x0] <= b[x1] and b[x0] <= a[x1] and a[y0] <= b[y1] and b[y0] <= a[y1] | [
"def",
"intersect",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"[",
"x0",
"]",
"==",
"a",
"[",
"x1",
"]",
"or",
"a",
"[",
"y0",
"]",
"==",
"a",
"[",
"y1",
"]",
":",
"return",
"False",
"if",
"b",
"[",
"x0",
"]",
"==",
"b",
"[",
"x1",
"]",
... | Check if two rectangles intersect | [
"Check",
"if",
"two",
"rectangles",
"intersect"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L128-L136 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | reading_order | def reading_order(e1, e2):
"""
A comparator to sort bboxes from top to bottom, left to right
"""
b1 = e1.bbox
b2 = e2.bbox
if round(b1[y0]) == round(b2[y0]) or round(b1[y1]) == round(b2[y1]):
return float_cmp(b1[x0], b2[x0])
return float_cmp(b1[y0], b2[y0]) | python | def reading_order(e1, e2):
"""
A comparator to sort bboxes from top to bottom, left to right
"""
b1 = e1.bbox
b2 = e2.bbox
if round(b1[y0]) == round(b2[y0]) or round(b1[y1]) == round(b2[y1]):
return float_cmp(b1[x0], b2[x0])
return float_cmp(b1[y0], b2[y0]) | [
"def",
"reading_order",
"(",
"e1",
",",
"e2",
")",
":",
"b1",
"=",
"e1",
".",
"bbox",
"b2",
"=",
"e2",
".",
"bbox",
"if",
"round",
"(",
"b1",
"[",
"y0",
"]",
")",
"==",
"round",
"(",
"b2",
"[",
"y0",
"]",
")",
"or",
"round",
"(",
"b1",
"[",... | A comparator to sort bboxes from top to bottom, left to right | [
"A",
"comparator",
"to",
"sort",
"bboxes",
"from",
"top",
"to",
"bottom",
"left",
"to",
"right"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L155-L163 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | xy_reading_order | def xy_reading_order(e1, e2):
"""
A comparator to sort bboxes from left to right, top to bottom
"""
b1 = e1.bbox
b2 = e2.bbox
if round(b1[x0]) == round(b2[x0]):
return float_cmp(b1[y0], b2[y0])
return float_cmp(b1[x0], b2[x0]) | python | def xy_reading_order(e1, e2):
"""
A comparator to sort bboxes from left to right, top to bottom
"""
b1 = e1.bbox
b2 = e2.bbox
if round(b1[x0]) == round(b2[x0]):
return float_cmp(b1[y0], b2[y0])
return float_cmp(b1[x0], b2[x0]) | [
"def",
"xy_reading_order",
"(",
"e1",
",",
"e2",
")",
":",
"b1",
"=",
"e1",
".",
"bbox",
"b2",
"=",
"e2",
".",
"bbox",
"if",
"round",
"(",
"b1",
"[",
"x0",
"]",
")",
"==",
"round",
"(",
"b2",
"[",
"x0",
"]",
")",
":",
"return",
"float_cmp",
"... | A comparator to sort bboxes from left to right, top to bottom | [
"A",
"comparator",
"to",
"sort",
"bboxes",
"from",
"left",
"to",
"right",
"top",
"to",
"bottom"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L166-L174 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | column_order | def column_order(b1, b2):
"""
A comparator that sorts bboxes first by "columns", where a column is made
up of all bboxes that overlap, then by vertical position in each column.
b1 = [b1.type, b1.top, b1.left, b1.bottom, b1.right]
b2 = [b2.type, b2.top, b2.left, b2.bottom, b2.right]
"""
(top... | python | def column_order(b1, b2):
"""
A comparator that sorts bboxes first by "columns", where a column is made
up of all bboxes that overlap, then by vertical position in each column.
b1 = [b1.type, b1.top, b1.left, b1.bottom, b1.right]
b2 = [b2.type, b2.top, b2.left, b2.bottom, b2.right]
"""
(top... | [
"def",
"column_order",
"(",
"b1",
",",
"b2",
")",
":",
"(",
"top",
",",
"left",
",",
"bottom",
")",
"=",
"(",
"1",
",",
"2",
",",
"3",
")",
"# TODO(senwu): Reimplement the functionality of this comparator to",
"# detect the number of columns, and sort those in reading... | A comparator that sorts bboxes first by "columns", where a column is made
up of all bboxes that overlap, then by vertical position in each column.
b1 = [b1.type, b1.top, b1.left, b1.bottom, b1.right]
b2 = [b2.type, b2.top, b2.left, b2.bottom, b2.right] | [
"A",
"comparator",
"that",
"sorts",
"bboxes",
"first",
"by",
"columns",
"where",
"a",
"column",
"is",
"made",
"up",
"of",
"all",
"bboxes",
"that",
"overlap",
"then",
"by",
"vertical",
"position",
"in",
"each",
"column",
"."
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L177-L193 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | merge_intervals | def merge_intervals(elems, overlap_thres=2.0):
"""
Project in x axis
Sort by start
Go through segments and keep max x1
Return a list of non-overlapping intervals
"""
overlap_thres = max(0.0, overlap_thres)
ordered = sorted(elems, key=lambda e: e.x0)
intervals = []
cur = [-overl... | python | def merge_intervals(elems, overlap_thres=2.0):
"""
Project in x axis
Sort by start
Go through segments and keep max x1
Return a list of non-overlapping intervals
"""
overlap_thres = max(0.0, overlap_thres)
ordered = sorted(elems, key=lambda e: e.x0)
intervals = []
cur = [-overl... | [
"def",
"merge_intervals",
"(",
"elems",
",",
"overlap_thres",
"=",
"2.0",
")",
":",
"overlap_thres",
"=",
"max",
"(",
"0.0",
",",
"overlap_thres",
")",
"ordered",
"=",
"sorted",
"(",
"elems",
",",
"key",
"=",
"lambda",
"e",
":",
"e",
".",
"x0",
")",
... | Project in x axis
Sort by start
Go through segments and keep max x1
Return a list of non-overlapping intervals | [
"Project",
"in",
"x",
"axis",
"Sort",
"by",
"start",
"Go",
"through",
"segments",
"and",
"keep",
"max",
"x1"
] | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L212-L235 |
HazyResearch/pdftotree | pdftotree/visual/visual_utils.py | predict_heatmap | def predict_heatmap(pdf_path, page_num, model, img_dim=448, img_dir="tmp/img"):
"""
Return an image corresponding to the page of the pdf
documents saved at pdf_path. If the image is not found in img_dir this
function creates it and saves it in img_dir.
:param pdf_path: path to the pdf document.
... | python | def predict_heatmap(pdf_path, page_num, model, img_dim=448, img_dir="tmp/img"):
"""
Return an image corresponding to the page of the pdf
documents saved at pdf_path. If the image is not found in img_dir this
function creates it and saves it in img_dir.
:param pdf_path: path to the pdf document.
... | [
"def",
"predict_heatmap",
"(",
"pdf_path",
",",
"page_num",
",",
"model",
",",
"img_dim",
"=",
"448",
",",
"img_dir",
"=",
"\"tmp/img\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"img_dir",
")",
":",
"print",
"(",
"\"\\nCreating image... | Return an image corresponding to the page of the pdf
documents saved at pdf_path. If the image is not found in img_dir this
function creates it and saves it in img_dir.
:param pdf_path: path to the pdf document.
:param page_num: page number to create image from in the pdf file.
:return: | [
"Return",
"an",
"image",
"corresponding",
"to",
"the",
"page",
"of",
"the",
"pdf",
"documents",
"saved",
"at",
"pdf_path",
".",
"If",
"the",
"image",
"is",
"not",
"found",
"in",
"img_dir",
"this",
"function",
"creates",
"it",
"and",
"saves",
"it",
"in",
... | train | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/visual/visual_utils.py#L11-L41 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.